Merge branch 'continuedev:main' into main

This commit is contained in:
Anoyi 2024-11-21 10:51:55 +08:00 • committed by GitHub
commit ee88b595c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
114 changed files with 2639 additions and 884 deletions

6
.gitignore vendored
View file

@ -142,7 +142,7 @@ codeql
.tiktoken_cache
# IntelliJ Plugin
# IntelliJ Plugin
**/**/.gradle
**/**/.qodana
**/**/build
@ -168,4 +168,6 @@ extensions/intellij/.idea/**
**/.idea/shelf/
extensions/intellij/bin
extensions/.continue-debug/
extensions/.continue-debug/
*.vsix

1
.husky/pre-commit Normal file
View file

@ -0,0 +1 @@
npx prettier --write .

View file

@ -1,4 +1,17 @@
binary/bin
binary/build
binary/out
binary/tmp
core/.continue-test
docs/.docusaurus
extensions/.continue-debug
extensions/vscode/continue_rc_schema.json
extensions/vscode/.vscode-test
extensions/vscode/bin
extensions/vscode/build
extensions/vscode/out
gui/dist
**/.continueignore
CHANGELOG.md
**/continue_tutorial.py
**/node_modules

View file

@ -29,6 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get();
const ERRORS_TO_IGNORE = [
// From Ollama
"unexpected server status",
"operation was aborted"
];
export type GetLspDefinitionsFunction = (
@ -176,17 +177,18 @@ export class CompletionProvider {
// or they might separately track recently edited ranges)
const extraSnippets = await this._getExtraSnippets(helper);
let snippets = await aggregateSnippets(
helper,
extraSnippets,
this.contextRetrievalService,
);
const [snippets, diff, workspaceDirs] = await Promise.all([
aggregateSnippets(helper, extraSnippets, this.contextRetrievalService),
this.ide.getDiff(true),
this.ide.getWorkspaceDirs(),
]);
const { prompt, prefix, suffix, completionOptions } = renderPrompt(
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
snippets,
await this.ide.getWorkspaceDirs(),
diff,
workspaceDirs,
helper,
);
});
// Completion
let completion: string | undefined = "";

View file

@ -1,10 +1,7 @@
import { Position, Range } from "../index.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import {
fillPromptWithSnippets,
rankAndOrderSnippets,
removeRangeFromSnippets,
type AutocompleteSnippet,
} from "./context/ranking/index.js";
import { HelperVars } from "./util/HelperVars.js";
@ -21,29 +18,6 @@ function filterSnippetsAlreadyInCaretWindow(
);
}
function getRangeOfPrefixAndSuffixWithBuffer(
prefix: string,
suffix: string,
caretPos: Position,
): Range {
// Remove prefix range from snippets
const prefixLines = prefix.split("\n").length;
const suffixLines = suffix.split("\n").length;
const buffer = 8;
const prefixSuffixRangeWithBuffer = {
start: {
line: caretPos.line - prefixLines - buffer,
character: 0,
},
end: {
line: caretPos.line + suffixLines + buffer,
character: 0,
},
};
return prefixSuffixRangeWithBuffer;
}
export async function aggregateSnippets(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
@ -61,24 +35,7 @@ export async function aggregateSnippets(
const scoredSnippets = rankAndOrderSnippets(snippets, helper);
// This might be redundant with filterSnippetsAlreadyInCaretWindow
let finalSnippets = removeRangeFromSnippets(
scoredSnippets,
helper.filepath.split("://").slice(-1)[0],
getRangeOfPrefixAndSuffixWithBuffer(
helper.prunedPrefix,
helper.prunedSuffix,
helper.pos,
),
);
// Filter snippets below similarity threshold
finalSnippets = finalSnippets.filter(
(snippet) =>
snippet.score >= helper.options.recentlyEditedSimilarityThreshold,
);
finalSnippets = fillPromptWithSnippets(
const finalSnippets = fillPromptWithSnippets(
scoredSnippets,
helper.maxSnippetTokens,
helper.modelName,

View file

@ -153,24 +153,6 @@ export function fillPromptWithSnippets(
return keptSnippets;
}
function rangeIntersectionByLines(a: Range, b: Range): Range | null {
const startLine = Math.max(a.start.line, b.start.line);
const endLine = Math.min(a.end.line, b.end.line);
if (startLine >= endLine) {
return null;
}
return {
start: {
line: startLine,
character: 0,
},
end: {
line: endLine,
character: 0,
},
};
}
/**
* Remove one range from another range, which may lead to returning two disjoint ranges
*/
@ -225,31 +207,3 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
}
return [orig];
}
export function removeRangeFromSnippets(
snippets: Required<AutocompleteSnippet>[],
filepath: string,
range: Range,
): Required<AutocompleteSnippet>[] {
const finalSnippets: Required<AutocompleteSnippet>[] = [];
for (const snippet of snippets) {
if (snippet.filepath !== filepath) {
finalSnippets.push(snippet);
continue;
}
const intersection = rangeIntersectionByLines(range, snippet.range);
if (!intersection) {
finalSnippets.push(snippet);
} else {
finalSnippets.push(
...rangeDifferenceByLines(snippet.range, intersection).map((range) => ({
...snippet,
range,
})),
);
}
}
return finalSnippets;
}

View file

@ -25,10 +25,10 @@ export class CompletionStreamer {
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
prefix,
() =>
(abortSignal: AbortSignal) =>
llm.supportsFim()
? llm.streamFim(prefix, suffix, completionOptions)
: llm.streamComplete(prompt, {
? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
: llm.streamComplete(prompt, abortSignal, {
...completionOptions,
raw: true,
}),

View file

@ -4,7 +4,7 @@ import { GeneratorReuseManager } from "./GeneratorReuseManager";
function createMockGenerator(
data: string[],
delay: number = 0,
): () => AsyncGenerator<string> {
): (abortSignal: AbortSignal) => AsyncGenerator<string> {
const mockGenerator = async function* () {
for (const chunk of data) {
yield chunk;

View file

@ -8,12 +8,13 @@ export class GeneratorReuseManager {
constructor(private readonly onError: (err: any) => void) {}
private _createListenableGenerator(
abortController: AbortController,
gen: AsyncGenerator<string>,
prefix: string,
) {
this.currentGenerator?.cancel();
const listenableGen = new ListenableGenerator(gen, this.onError);
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
this.pendingGeneratorPrefix = prefix;
@ -35,13 +36,14 @@ export class GeneratorReuseManager {
async *getGenerator(
prefix: string,
newGenerator: () => AsyncGenerator<string>,
newGenerator: (abortSignal: AbortSignal) => AsyncGenerator<string>,
multiline: boolean,
): AsyncGenerator<string> {
// If we can't reuse, then create a new generator
if (!this.shouldReuseExistingGenerator(prefix)) {
// Create a wrapper over the current generator to fix the prompt
this._createListenableGenerator(newGenerator(), prefix);
const abortController = new AbortController();
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
}
// Already typed characters are those that are new in the prefix from the old generator

View file

@ -3,16 +3,20 @@ export class ListenableGenerator<T> {
private _buffer: T[] = [];
private _listeners: Set<(value: T) => void> = new Set();
private _isEnded = false;
private _abortController: AbortController
constructor(
source: AsyncGenerator<T>,
private readonly onError: (e: any) => void,
abortController: AbortController
) {
this._source = source;
this._abortController = abortController;
this._start();
}
public cancel() {
this._abortController.abort();
this._isEnded = true;
}

View file

@ -1,5 +1,7 @@
import path from "node:path";
import ignore from "ignore";
import { IDE } from "../..";
import { getBasename } from "../../util";
import { getConfigJsonPath } from "../../util/paths";
@ -31,7 +33,7 @@ async function isDisabledForFile(
}
// @ts-ignore
const pattern = ignore.default().add(options.disableInFiles);
const pattern = ignore.default().add(disableInFiles);
if (pattern.ignores(filepath)) {
return true;
}

View file

@ -11,6 +11,7 @@ import {
getTemplateForModel,
} from "./AutocompleteTemplate";
import { getStopTokens } from "./getStopTokens";
import { countTokens } from "../../llm/countTokens";
export function formatExternalSnippet(
filepath: string,
@ -33,25 +34,17 @@ function getContextComments(
snippets: AutocompleteSnippet[],
lang: AutocompleteLanguageInfo,
filepath: string,
prefix: string,
suffix: string,
) {
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
return `${formattedSnippets}\n\n`;
}
const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`;
const isEmptyFile = prefix.trim().length === 0 && suffix.trim().length === 0;
if (isEmptyFile) {
// Include the file name as a comment
prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n`;
}
const formattedSnippets =
snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n") + fileNameSnippet;
return "";
return formattedSnippets;
}
function getTemplate(helper: HelperVars): AutocompleteTemplate {
@ -85,11 +78,29 @@ function renderStringTemplate(
});
}
export function renderPrompt(
snippets: AutocompleteSnippet[],
workspaceDirs: string[],
helper: HelperVars,
): {
const formatDiff = (helper: HelperVars, diff?: string) => {
if (!diff) return "";
const tokenCount = countTokens(diff, helper.modelName);
if (tokenCount > helper.maxDiffTokens) {
return "";
}
return `${diff}\n\n`;
};
export function renderPrompt({
snippets,
workspaceDirs,
helper,
diff,
}: {
snippets: AutocompleteSnippet[];
workspaceDirs: string[];
helper: HelperVars;
diff?: string;
}): {
prompt: string;
prefix: string;
suffix: string;
@ -119,10 +130,10 @@ export function renderPrompt(
snippets,
helper.lang,
helper.filepath,
prefix,
suffix,
);
prefix = `${contextComments}${prefix}`;
const formattedDiff = formatDiff(helper, diff);
prefix = `${formattedDiff}${contextComments}${prefix}`;
}
const prompt =

View file

@ -39,7 +39,9 @@ export class HelperVars {
private async init() {
// Don't do anything if already initialized
if (this._fileContents !== undefined) {return;}
if (this._fileContents !== undefined) {
return;
}
this._fileContents =
this.input.manuallyPassFileContents ??
@ -115,6 +117,11 @@ export class HelperVars {
get maxSnippetTokens() {
return this.options.maxPromptTokens * this.options.maxSnippetPercentage;
}
get maxDiffTokens() {
return this.options.maxPromptTokens * this.options.maxDiffPercentage;
}
get prunedCaretWindow() {
return this.prunedPrefix + this.prunedSuffix;
}

View file

@ -58,7 +58,7 @@ export function slashFromCustomCommand(
}
}
for await (const chunk of llm.streamChat(messages)) {
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -24,7 +24,9 @@ const GenerateTerminalCommand: SlashCommand = {
"${input}"
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`);
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
new AbortController().signal
);
const lines = streamLines(gen);
let cmd = "";

View file

@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = {
const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
])) {
], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -30,7 +30,7 @@ const DraftIssueCommand: SlashCommand = {
return;
}
let title = await llm.complete(
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal,
{ maxTokens: 20 },
);
@ -43,7 +43,7 @@ const DraftIssueCommand: SlashCommand = {
{ role: "user", content: PROMPT(input, title) },
];
for await (const chunk of llm.streamChat(messages)) {
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
body += chunk.content;
yield stripImages(chunk.content);
}

View file

@ -478,7 +478,7 @@ const EditSlashCommand: SlashCommand = {
messages = rendered;
}
const completion = llm.streamComplete(rendered as string, {
const completion = llm.streamComplete(rendered as string, new AbortController().signal, {
maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096),
raw: true,
});
@ -494,7 +494,7 @@ const EditSlashCommand: SlashCommand = {
);
} else {
async function* gen() {
for await (const chunk of llm.streamChat(messages, {
for await (const chunk of llm.streamChat(messages, new AbortController().signal,{
temperature: 0.5, // TODO
maxTokens: Math.min(
maxTokens,
@ -609,7 +609,7 @@ ${lines.join("\n")}
Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`;
for await (const update of llm.streamComplete(prompt)) {
for await (const update of llm.streamComplete(prompt, new AbortController().signal)) {
yield update;
}
}

View file

@ -39,7 +39,7 @@ const MultiFileEditSlashCommand: SlashCommand = {
const content = createPrompt(filesToEditStr, additionalContextStr, input);
for await (const chunk of llm.streamChat([{ role: "user", content }])) {
for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -47,7 +47,7 @@ const OnboardSlashCommand: SlashCommand = {
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
])) {
], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},
@ -134,7 +134,7 @@ function createOnboardingPrompt(context: string): string {
Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
Here is an example of a valid response:
## Important folders
### /folder1

View file

@ -45,7 +45,7 @@ const ReviewMessageCommand: SlashCommand = {
for await (const chunk of llm.streamChat([
{ role: "user", content: content },
])) {
], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -125,7 +125,7 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}

View file

@ -836,7 +836,7 @@ declare global {
slidingWindowPrefixPercentage: number;
slidingWindowSize: number;
maxSnippetPercentage: number;
recentlyEditedSimilarityThreshold: number;
maxDiffPercentage: number;
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;

View file

@ -9,7 +9,6 @@ import {
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { Telemetry } from "../../util/posthog";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
@ -88,38 +87,10 @@ class DocsContextProvider extends BaseContextProvider {
return [];
}
const isJetBrainsAndPreIndexedDocsProvider =
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
void extras.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const preIndexedDoc = preIndexedDocs[query];
if (!!preIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
const embeddingsProvider = await docsService.getEmbeddingsProvider(
!!preIndexedDoc,
);
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
let chunks = await docsService.retrieveChunks(
await docsService.isInitialized;
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
vector,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
);
@ -175,7 +146,7 @@ class DocsContextProvider extends BaseContextProvider {
return [];
}
const docs = (await docsService.list()) ?? [];
const docs = (await docsService.listMetadata()) ?? [];
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
const submenuItemsMap = new Map<string, ContextSubmenuItem>();

View file

@ -21,11 +21,12 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
const issueId = query;
const { Octokit } = await import("@octokit/rest");
const domain = this.options?.domain ?? "github.com";
const octokit = new Octokit({
auth: this.options?.githubToken,
baseUrl: `https://${domain}/api/v3`,
baseUrl: this.options?.domain
? `https://${this.options.domain}/api/v3`
: undefined,
request: {
fetch: extras.fetch,
},

View file

@ -6,7 +6,7 @@ const RERANK_PROMPT = (
documentId: string,
document: string,
) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
Query: Where is the FastAPI server?
Snippet:
\`\`\`/Users/andrew/Desktop/server/main.py
@ -17,7 +17,7 @@ const RERANK_PROMPT = (
return {{"Hello": "World"}}
\`\`\`
Relevant: Yes
Query: Where in the documentation does it talk about the UI?
Snippet:
\`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs
@ -32,13 +32,13 @@ const RERANK_PROMPT = (
}}
\`\`\`
Relevant: No
Query: ${query}
Snippet:
\`\`\`${documentId}
${document}
\`\`\`
Relevant:
Relevant:
`;
export class LLMReranker implements Reranker {
@ -49,6 +49,7 @@ export class LLMReranker implements Reranker {
async scoreChunk(chunk: Chunk, query: string): Promise<number> {
const completion = await this.llm.complete(
RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content),
new AbortController().signal,
{
maxTokens: 1,
model:

View file

@ -61,7 +61,7 @@ This is the question that you should select relevant files for: "${input}"`;
const response = await llm.chat([
{ role: "user", content: prompt },
{ role: "assistant", content: "<reasoning>" },
]);
], new AbortController().signal);
const content = stripImages(response.content);
console.debug("Repo map retrieval response: ", content);

View file

@ -30,6 +30,7 @@ import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
@ -42,7 +43,7 @@ export class Core {
codebaseIndexerPromise: Promise<CodebaseIndexer>;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
indexingState: IndexingProgressUpdate;
codebaseIndexingState: IndexingProgressUpdate;
controlPlaneClient: ControlPlaneClient;
private docsService: DocsService;
private globalContext = new GlobalContext();
@ -88,7 +89,11 @@ export class Core {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
this.indexingState = { status: "loading", desc: "loading", progress: 0 };
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
@ -148,6 +153,7 @@ export class Core {
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
this.indexingPauseToken.paused = true;
if (ideSettings.pauseCodebaseIndexOnStart) {
void this.messenger.request("indexProgress", {
progress: 1,
@ -272,34 +278,15 @@ export class Core {
// Context providers
on("context/addDocs", async (msg) => {
let hasFailed = false;
for await (const result of this.docsService.indexAndAdd(msg.data)) {
if (result.status === "failed") {
hasFailed = true;
break;
}
}
if (hasFailed) {
void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
void this.ide.showToast(
"info",
`Successfully indexed ${msg.data.startUrl}`,
);
this.messenger.send("refreshSubmenuItems", undefined);
}
void this.docsService.indexAndAdd(msg.data);
});
on("context/removeDocs", async (msg) => {
await this.docsService.delete(msg.data.startUrl);
this.messenger.send("refreshSubmenuItems", undefined);
});
on("context/indexDocs", async (msg) => {
await this.docsService.indexAllDocs(msg.data.reIndex);
this.messenger.send("refreshSubmenuItems", undefined);
await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex);
});
on("context/loadSubmenuItems", async (msg) => {
@ -365,6 +352,11 @@ export class Core {
}
});
on("context/getSymbolsForFiles", async (msg) => {
const { uris } = msg.data;
return await getSymbolsForManyFiles(uris, this.ide);
});
on("config/getSerializedProfileInfo", async (msg) => {
return {
config: await this.configHandler.getSerializedConfig(),
@ -387,6 +379,7 @@ export class Core {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
@ -428,6 +421,7 @@ export class Core {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
@ -460,6 +454,7 @@ export class Core {
const model = await this.configHandler.llmFromTitle(msg.data.title);
const completion = await model.complete(
msg.data.prompt,
new AbortController().signal,
msg.data.completionOptions,
);
return completion;
@ -540,33 +535,39 @@ export class Core {
}
}, 100);
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
}
if (content) {
yield { content };
try {
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
break;
}
if (content) {
yield { content };
}
}
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
}
clearInterval(checkActiveInterval);
yield { done: true, content: "" };
}
on("command/run", (msg) =>
@ -678,6 +679,8 @@ export class Core {
const rows = await DevDataSqliteDb.getTokensPerModel();
return rows;
});
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
@ -693,17 +696,41 @@ export class Core {
}
});
on("index/setPaused", (msg) => {
new GlobalContext().update("indexingPaused", msg.data);
this.globalContext.update("indexingPaused", msg.data);
this.indexingPauseToken.paused = msg.data;
});
on("index/indexingProgressBarInitialized", async (msg) => {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.indexingState.status !== "loading") {
void this.messenger.request("indexProgress", this.indexingState);
if (this.codebaseIndexingState.status !== "loading") {
void this.messenger.request(
"indexProgress",
this.codebaseIndexingState,
);
}
});
// Docs, etc. indexing
on("indexing/reindex", async (msg) => {
if (msg.data.type === "docs") {
void this.docsService.reindexDoc(msg.data.id);
}
});
on("indexing/abort", async (msg) => {
if (msg.data.type === "docs") {
this.docsService.abort(msg.data.id);
}
});
on("indexing/setPaused", async (msg) => {
if (msg.data.type === "docs") {
this.docsService.setPaused(msg.data.id, msg.data.paused);
}
});
on("indexing/initStatuses", async (msg) => {
return this.docsService.initStatuses();
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
@ -760,7 +787,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -794,7 +821,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -803,4 +830,6 @@ export class Core {
this.messenger.send("refreshSubmenuItems", undefined);
}
// private
}

View file

@ -86,7 +86,7 @@ export async function* getReplacementWithLlm(
const completion = await llm.streamChat([
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
]);
], new AbortController().signal);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);

View file

@ -23,7 +23,7 @@ export async function* streamLazyApply(
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(promptMessages);
const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal);
// Do find and replace over the lazy edit response
async function* replacementFunction(

View file

@ -96,8 +96,8 @@ export async function* streamDiffLines(
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt, { raw: true, prediction })
: llm.streamChat(prompt, {
? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction })
: llm.streamChat(prompt, new AbortController().signal, {
prediction,
});

47
core/index.d.ts vendored
View file

@ -1,3 +1,4 @@
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
@ -45,6 +46,30 @@ export interface IndexingProgressUpdate {
debugInfo?: string;
}
// This is more or less a V2 of IndexingProgressUpdate
export interface IndexingStatus {
id: string;
type: "docs";
progress: number;
description: string;
status:
| "indexing"
| "complete"
| "paused"
| "failed"
| "aborted"
| "deleted"
| "pending";
embeddingsProviderId: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
icon?: string;
url?: string;
}
export type IndexingStatusMap = Map<string, IndexingStatus>;
export type PromptTemplateFunction = (
history: ChatMessage[],
otherData: Record<string, string>,
@ -78,26 +103,34 @@ export interface ILLM extends LLMOptions {
region?: string;
projectId?: string;
complete(prompt: string, options?: LLMFullCompletionOptions): Promise<string>;
complete(
prompt: string,
signal: AbortSignal,
options?: LLMFullCompletionOptions
): Promise<string>;
streamComplete(
prompt: string,
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): AsyncGenerator<string, PromptLog>;
streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): AsyncGenerator<string, PromptLog>;
streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): AsyncGenerator<ChatMessage, PromptLog>;
chat(
messages: ChatMessage[],
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): Promise<ChatMessage>;
@ -303,13 +336,19 @@ export interface InputModifiers {
noContext: boolean;
}
export interface SymbolWithRange extends RangeInFile {
name: string;
type: Parser.SyntaxNode["type"];
}
export type FileSymbolMap = Record<string, SymbolWithRange[]>;
export interface PromptLog {
modelTitle: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;
}
export interface ChatHistoryItem {
message: ChatMessage;
editorState?: any;
@ -388,11 +427,13 @@ export interface CustomLLMWithOptionals {
options: LLMOptions;
streamCompletion?: (
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
streamChat?: (
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
@ -937,7 +978,7 @@ export interface TabAutocompleteOptions {
slidingWindowPrefixPercentage: number;
slidingWindowSize: number;
maxSnippetPercentage: number;
recentlyEditedSimilarityThreshold: number;
maxDiffPercentage: number;
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;

View file

@ -95,6 +95,6 @@ export default DocsCrawler;
export {
CheerioCrawler,
ChromiumCrawler,
ChromiumInstaller as ChromiumInstaller,
ChromiumInstaller,
GitHubCrawler,
};

View file

@ -66,23 +66,20 @@ describe.skip("DocsService Integration Tests", () => {
});
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(mockSiteConfig);
let latestConfig = await getReloadedConfig();
// Sqlite check
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// config.json check
expect(latestConfig.docs).toContainEqual(mockSiteConfig);
// Lance DB check
const embeddingsProvider = await docsService.getEmbeddingsProvider();
const [mockVector] = await embeddingsProvider.embed(["test"]);
let retrievedChunks = await docsService.retrieveChunks(
let retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
mockVector,
5,
);
@ -91,7 +88,7 @@ describe.skip("DocsService Integration Tests", () => {
await docsService.delete(mockSiteConfig.startUrl);
// Sqlite check
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
// config.json check
latestConfig = await getReloadedConfig();
@ -100,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => {
);
// LanceDB check
retrievedChunks = await docsService.retrieveChunks(
retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
mockVector,
5,
);
expect(retrievedChunks.length).toBe(0);
@ -133,17 +130,15 @@ describe.skip("DocsService Integration Tests", () => {
test("Handles pulling down and adding pre-indexed docs", async () => {
const preIndexedDoc = Object.values(preIndexedDocs)[0];
const generator = docsService.indexAndAdd(preIndexedDoc);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(preIndexedDoc);
});
test("Config synchronization with SQLite", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(mockSiteConfig);
await getReloadedConfig();
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
editConfigJson((config) => {
const { docs, ...restConfig } = config;
@ -164,6 +159,6 @@ describe.skip("DocsService Integration Tests", () => {
await new Promise((resolve) => setTimeout(resolve, 100));
}
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
});
});

File diff suppressed because it is too large Load diff

View file

@ -330,6 +330,12 @@ const preIndexedDocs: Record<
startUrl: "https://llama-stack.readthedocs.io/",
rootUrl: "https://llama-stack.readthedocs.io/",
},
"https://go.dev/doc": {
title: "Go",
startUrl: "https://go.dev/doc",
rootUrl: "https://go.dev",
faviconUrl: "https://go.dev/favicon.ico",
},
};
export default preIndexedDocs;

View file

@ -372,10 +372,11 @@ export abstract class BaseLLM implements ILLM {
`HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
);
} else {
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);
if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);
}
if (
e.code === "ECONNREFUSED" &&
e.message.includes("http://127.0.0.1:11434")
@ -424,6 +425,7 @@ export abstract class BaseLLM implements ILLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string, PromptLog> {
throw new Error("Not implemented");
@ -432,6 +434,7 @@ export abstract class BaseLLM implements ILLM {
async *streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
const { completionOptions, log } = this._parseCompletionOptions(options);
@ -452,6 +455,7 @@ export abstract class BaseLLM implements ILLM {
for await (const chunk of this._streamFim(
prefix,
suffix,
signal,
completionOptions,
)) {
completion += chunk;
@ -477,6 +481,7 @@ export abstract class BaseLLM implements ILLM {
async *streamComplete(
_prompt: string,
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
@ -506,6 +511,7 @@ export abstract class BaseLLM implements ILLM {
try {
for await (const chunk of this._streamComplete(
prompt,
signal,
completionOptions,
)) {
completion += chunk;
@ -527,7 +533,7 @@ export abstract class BaseLLM implements ILLM {
};
}
async complete(_prompt: string, options: LLMFullCompletionOptions = {}) {
async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -551,7 +557,7 @@ export abstract class BaseLLM implements ILLM {
}
}
const completion = await this._complete(prompt, completionOptions);
const completion = await this._complete(prompt, signal, completionOptions);
this._logTokensGenerated(completionOptions.model, prompt, completion);
@ -562,9 +568,9 @@ export abstract class BaseLLM implements ILLM {
return completion;
}
async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) {
async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
let completion = "";
for await (const chunk of this.streamChat(messages, options)) {
for await (const chunk of this.streamChat(messages, signal, options)) {
completion += chunk.content;
}
return { role: "assistant" as ChatMessageRole, content: completion };
@ -572,6 +578,7 @@ export abstract class BaseLLM implements ILLM {
async *streamChat(
_messages: ChatMessage[],
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
const { completionOptions, log, raw } =
@ -597,6 +604,7 @@ export abstract class BaseLLM implements ILLM {
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
signal,
completionOptions,
)) {
completion += chunk;
@ -605,6 +613,7 @@ export abstract class BaseLLM implements ILLM {
} else {
for await (const chunk of this._streamChat(
messages,
signal,
completionOptions,
)) {
completion += chunk.content;
@ -633,6 +642,7 @@ export abstract class BaseLLM implements ILLM {
// biome-ignore lint/correctness/useYield: Purposefully not implemented
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
throw new Error("Not implemented");
@ -640,6 +650,7 @@ export abstract class BaseLLM implements ILLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (!this.templateMessages) {
@ -650,15 +661,16 @@ export abstract class BaseLLM implements ILLM {
for await (const chunk of this._streamComplete(
this.templateMessages(messages),
signal,
options,
)) {
yield { role: "assistant", content: chunk };
}
}
protected async _complete(prompt: string, options: CompletionOptions) {
protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) {
let completion = "";
for await (const chunk of this._streamComplete(prompt, options)) {
for await (const chunk of this._streamComplete(prompt, signal, options)) {
completion += chunk;
}
return completion;

View file

@ -37,7 +37,9 @@ class Anthropic extends BaseLLM {
public convertMessages(msgs: ChatMessage[]): any[] {
// should be public for use within VertexAI
const filteredmessages = msgs.filter((m) => m.role !== "system");
const filteredmessages = msgs.filter(
(m) => m.role !== "system" && !!m.content,
);
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)
@ -95,16 +97,18 @@ class Anthropic extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage =
@ -137,6 +141,7 @@ class Anthropic extends BaseLLM {
]
: systemMessage,
}),
signal
});
if (options.stream === false) {
@ -146,7 +151,9 @@ class Anthropic extends BaseLLM {
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") {console.log(value);}
if (value.type == "message_start") {
console.log(value);
}
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}

View file

@ -98,6 +98,7 @@ class Asksage extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions
): Promise<string> {
if (typeof prompt !== "string" || prompt.trim() === "") {
@ -126,14 +127,16 @@ class Asksage extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions
): AsyncGenerator<string> {
const completion = await this._complete(prompt, options);
const completion = await this._complete(prompt, signal, options);
yield completion;
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(options, messages);
@ -142,6 +145,7 @@ class Asksage extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(args),
signal
});
if (!response.ok) {

View file

@ -5,6 +5,10 @@ import OpenAI from "./OpenAI.js";
class Azure extends OpenAI {
static providerName: ModelProvider = "azure";
protected supportsPrediction(model: string): boolean {
return false;
}
static defaultOptions: Partial<LLMOptions> = {
apiVersion: "2024-02-15-preview",
apiType: "azure",

View file

@ -14,6 +14,11 @@ import {
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
/**
* Bedrock class implements AWS Bedrock LLM integration.
* It handles streaming completions and chat messages using AWS Bedrock runtime.
* Supports both text and image inputs through Claude 3 models.
*/
class Bedrock extends BaseLLM {
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
@ -37,16 +42,18 @@ class Bedrock extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
@ -84,7 +91,7 @@ class Bedrock extends BaseLLM {
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);
const response = await client.send(command, { abortSignal: signal});
if (response.stream) {
for await (const chunk of response.stream) {
@ -120,7 +127,9 @@ class Bedrock extends BaseLLM {
// TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback.
// For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes),
// providing meaningful error messages to improve the user experience.
stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4),
stopSequences: options.stop
?.filter((stop) => stop.trim() !== "")
.slice(0, 4),
},
};
}
@ -162,7 +171,7 @@ class Bedrock extends BaseLLM {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true
ignoreCache: true,
})();
} catch (e) {
console.warn(

View file

@ -37,6 +37,7 @@ class BedrockImport extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
@ -51,7 +52,7 @@ class BedrockImport extends BaseLLM {
const input = this._generateInvokeModelCommandInput(prompt, options);
const command = new InvokeModelWithResponseStreamCommand(input);
const response = await client.send(command);
const response = await client.send(command, {abortSignal: signal});
if (response.body) {
for await (const item of response.body) {

View file

@ -16,6 +16,7 @@ export default class Cloudflare extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage, any, unknown> {
const headers = {
@ -35,6 +36,7 @@ export default class Cloudflare extends BaseLLM {
model: this.model,
...this._convertArgs(options),
}),
signal
});
for await (const value of streamSse(resp)) {
@ -46,10 +48,12 @@ export default class Cloudflare extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield stripImages(chunk.content);

View file

@ -46,16 +46,18 @@ class Cohere extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const headers = {
@ -73,6 +75,7 @@ class Cohere extends BaseLLM {
chat_history: this._convertMessages(messages),
preamble: this.systemMessage,
}),
signal
});
if (options.stream === false) {

View file

@ -13,12 +13,14 @@ class CustomLLMClass extends BaseLLM {
private customStreamCompletion?: (
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
private customStreamChat?: (
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
@ -31,18 +33,20 @@ class CustomLLMClass extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (this.customStreamChat) {
for await (const content of this.customStreamChat(
messages,
signal,
options,
(...args) => this.fetch(...args),
)) {
yield { role: "assistant", content };
}
} else {
for await (const update of super._streamChat(messages, options)) {
for await (const update of super._streamChat(messages, signal, options)) {
yield update;
}
}
@ -50,11 +54,13 @@ class CustomLLMClass extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (this.customStreamCompletion) {
for await (const content of this.customStreamCompletion(
prompt,
signal,
options,
(...args) => this.fetch(...args),
)) {
@ -63,6 +69,7 @@ class CustomLLMClass extends BaseLLM {
} else if (this.customStreamChat) {
for await (const content of this.customStreamChat(
[{ role: "user", content: prompt }],
signal,
options,
(...args) => this.fetch(...args),
)) {

View file

@ -23,6 +23,7 @@ class Deepseek extends OpenAI {
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("beta/completions", this.apiBase);
@ -45,6 +46,7 @@ class Deepseek extends OpenAI {
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].text;

View file

@ -121,16 +121,18 @@ class Flowise extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const message: ChatMessage = { role: "user", content: prompt };
for await (const chunk of this._streamChat([message], options)) {
for await (const chunk of this._streamChat([message], signal, options)) {
yield stripImages(chunk.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const requestBody = this._getRequestBody(messages, options);
@ -139,6 +141,7 @@ class Flowise extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal
}).then((res) => res.json());
while (await socketInfo.hasNextToken()) {

View file

@ -60,6 +60,7 @@ class FreeTrial extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(this.collectArgs(options));
@ -73,6 +74,7 @@ class FreeTrial extends BaseLLM {
prompt,
...args,
}),
signal
});
let completion = "";
@ -103,6 +105,7 @@ class FreeTrial extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(this.collectArgs(options));
@ -120,6 +123,7 @@ class FreeTrial extends BaseLLM {
messages: messages.map(this._convertMessage),
...args,
}),
signal
});
let completion = "";
@ -140,6 +144,7 @@ class FreeTrial extends BaseLLM {
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(this.collectArgs(options));
@ -153,6 +158,7 @@ class FreeTrial extends BaseLLM {
suffix,
...args,
}),
signal
});
let completion = "";

View file

@ -46,10 +46,12 @@ class Gemini extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
signal,
options,
)) {
yield stripImages(message.content);
@ -72,6 +74,7 @@ class Gemini extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
// Ensure this.apiBase is used if available, otherwise use default
@ -89,6 +92,7 @@ class Gemini extends BaseLLM {
if (options.model.includes("gemini")) {
for await (const message of this.streamChatGemini(
convertedMsgs,
signal,
options,
)) {
yield message;
@ -96,6 +100,7 @@ class Gemini extends BaseLLM {
} else {
for await (const message of this.streamChatBison(
convertedMsgs,
signal,
options,
)) {
yield message;
@ -118,6 +123,7 @@ class Gemini extends BaseLLM {
private async *streamChatGemini(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
@ -159,6 +165,7 @@ class Gemini extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
});
let buffer = "";
@ -211,6 +218,7 @@ class Gemini extends BaseLLM {
}
private async *streamChatBison(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const msgList = [];
@ -226,6 +234,7 @@ class Gemini extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
});
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };

View file

@ -16,6 +16,7 @@ class HuggingFaceInferenceAPI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (!this.apiBase) {
@ -36,6 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM {
stream: true,
parameters: this._convertArgs(options),
}),
signal
});
async function* stream() {

View file

@ -48,6 +48,7 @@ class HuggingFaceTGI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(options, prompt);
@ -60,6 +61,7 @@ class HuggingFaceTGI extends BaseLLM {
"Content-Type": "application/json",
},
body: JSON.stringify({ inputs: prompt, parameters: args }),
signal
},
);

View file

@ -26,6 +26,7 @@ class LlamaCpp extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const headers = {
@ -42,6 +43,7 @@ class LlamaCpp extends BaseLLM {
stream: true,
...this._convertArgs(options, prompt),
}),
signal
});
for await (const value of streamSse(resp)) {

View file

@ -7,6 +7,7 @@ class Mock extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
yield this.completion;
@ -14,6 +15,7 @@ class Mock extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
for (const char of this.completion) {

View file

@ -23,6 +23,7 @@ class Moonshot extends OpenAI {
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("v1/chat/completions", this.apiBase);
@ -49,6 +50,7 @@ class Moonshot extends OpenAI {
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].delta.content;

View file

@ -30,7 +30,7 @@ interface ModelFileParams {
min_p?: number;
// deprecated?
num_thread?: number;
use_mmap?: boolean;
use_mmap?: boolean;
num_gqa?: number;
num_gpu?: number;
}
@ -77,7 +77,6 @@ class Ollama extends BaseLLM {
if (options.model === "AUTODETECT") {
return;
}
this.fetch(this.getEndpoint("api/show"), {
method: "POST",
headers: {
@ -262,6 +261,7 @@ class Ollama extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
@ -271,6 +271,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getGenerateOptions(options, prompt)),
signal
});
let buffer = "";
@ -301,6 +302,7 @@ class Ollama extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(this.getEndpoint("api/chat"), {
@ -310,6 +312,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getChatOptions(options, messages)),
signal
});
let buffer = "";
@ -348,8 +351,10 @@ class Ollama extends BaseLLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
@ -357,6 +362,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
signal
});
let buffer = "";

View file

@ -95,11 +95,8 @@ class OpenAI extends BaseLLM {
);
}
private supportsPrediction(model: string): boolean {
return [
"gpt-4o-mini",
"gpt-4o"
].includes(model);
protected supportsPrediction(model: string): boolean {
return ["gpt-4o-mini", "gpt-4o"].includes(model);
}
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) {
@ -120,9 +117,9 @@ class OpenAI extends BaseLLM {
: url.host === "api.deepseek.com"
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
@ -143,10 +140,12 @@ class OpenAI extends BaseLLM {
}
if (options.prediction && this.supportsPrediction(options.model)) {
if (finalOptions.presence_penalty) { // prediction doesn't support > 0
if (finalOptions.presence_penalty) {
// prediction doesn't support > 0
finalOptions.presence_penalty = undefined;
}
if (finalOptions.frequency_penalty) { // prediction doesn't support > 0
if (finalOptions.frequency_penalty) {
// prediction doesn't support > 0
finalOptions.frequency_penalty = undefined;
}
finalOptions.max_completion_tokens = undefined;
@ -167,11 +166,13 @@ class OpenAI extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): Promise<string> {
let completion = "";
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
completion += chunk.content;
@ -200,10 +201,12 @@ class OpenAI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield stripImages(chunk.content);
@ -212,6 +215,7 @@ class OpenAI extends BaseLLM {
protected async *_legacystreamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args: any = this._convertArgs(options, []);
@ -225,6 +229,7 @@ class OpenAI extends BaseLLM {
...args,
stream: true,
}),
signal
});
for await (const value of streamSse(response)) {
@ -236,6 +241,7 @@ class OpenAI extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (
@ -247,6 +253,7 @@ class OpenAI extends BaseLLM {
) {
for await (const content of this._legacystreamComplete(
stripImages(messages[messages.length - 1]?.content || ""),
signal,
options,
)) {
yield {
@ -267,6 +274,7 @@ class OpenAI extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(body),
signal
});
// Handle non-streaming response
@ -286,6 +294,7 @@ class OpenAI extends BaseLLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = this.apiBase?.includes("completions") ? new URL(this.apiBase) : new URL("fim/completions", this.apiBase);
@ -309,6 +318,7 @@ class OpenAI extends BaseLLM {
"x-api-key": this.apiKey ?? "",
Authorization: `Bearer ${this.apiKey}`,
},
signal
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].delta.content;

View file

@ -41,11 +41,13 @@ class Replicate extends BaseLLM {
private _convertArgs(
options: CompletionOptions,
prompt: string,
): [`${string}/${string}:${string}`, { input: any }] {
signal: AbortSignal
): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] {
return [
Replicate.MODEL_IDS[options.model] || (options.model as any),
{
input: { prompt, message: prompt },
signal
},
];
}
@ -57,9 +59,10 @@ class Replicate extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): Promise<string> {
const [model, args] = this._convertArgs(options, prompt);
const [model, args] = this._convertArgs(options, prompt, signal);
const response = await this._replicate.run(model, args);
return (response as any)[0];
@ -67,9 +70,10 @@ class Replicate extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const [model, args] = this._convertArgs(options, prompt);
const [model, args] = this._convertArgs(options, prompt, signal);
for await (const event of this._replicate.stream(model, args)) {
if (event.event === "output") {
yield event.data;

View file

@ -32,6 +32,7 @@ class SageMaker extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
@ -45,7 +46,7 @@ class SageMaker extends BaseLLM {
});
const toolkit = new CompletionAPIToolkit(this);
const command = toolkit.generateCommand([], prompt, options);
const response = await client.send(command);
const response = await client.send(command, { abortSignal: signal });
if (response.Body) {
let buffer = "";
for await (const rawValue of response.Body) {
@ -82,6 +83,7 @@ class SageMaker extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
@ -96,7 +98,7 @@ class SageMaker extends BaseLLM {
const toolkit = new MessageAPIToolkit(this);
const command = toolkit.generateCommand(messages, "", options);
const response = await client.send(command);
const response = await client.send(command, { abortSignal: signal });
if (response.Body) {
let buffer = "";
for await (const rawValue of response.Body) {

View file

@ -41,9 +41,10 @@ class Together extends OpenAI {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._legacystreamComplete(prompt, options)) {
for await (const chunk of this._legacystreamComplete(prompt,signal, options)) {
yield chunk;
}
}

View file

@ -49,7 +49,7 @@ class VertexAI extends BaseLLM {
"unknown";
this.anthropicInstance = new Anthropic(_options);
this.geminiInstance = new Gemini(_options);
}
async fetch(url: RequestInfo | URL, init?: RequestInit) {
@ -307,6 +307,7 @@ class VertexAI extends BaseLLM {
protected async *StreamFimMistral(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const apiBase = this.apiBase!;
@ -329,6 +330,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
});
for await (const chunk of streamSse(response)) {
@ -342,6 +344,7 @@ class VertexAI extends BaseLLM {
protected async *streamFimGecko(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase);
@ -363,6 +366,7 @@ class VertexAI extends BaseLLM {
}
}),
signal
});
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
@ -373,6 +377,7 @@ class VertexAI extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const isV1API = this.apiBase.includes("/v1/");
@ -396,10 +401,12 @@ class VertexAI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
signal,
options,
)) {
yield stripImages(message.content);
@ -409,15 +416,16 @@ class VertexAI extends BaseLLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (this.model === "code-gecko") {
yield* this.streamFimGecko(prefix, suffix, options);
yield* this.streamFimGecko(prefix, suffix, signal, options);
} else if (this.model.includes("codestral")) {
yield* this.StreamFimMistral(prefix, suffix, options);
yield* this.StreamFimMistral(prefix, suffix, signal, options);
} else {
throw new Error(`Unsupported model: ${this.model}`);
}

View file

@ -140,11 +140,13 @@ class WatsonX extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): Promise<string> {
let completion = "";
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
completion += chunk.content;
@ -155,10 +157,12 @@ class WatsonX extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield stripImages(chunk.content);
@ -167,6 +171,7 @@ class WatsonX extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
var now = new Date().getTime() / 1000;
@ -219,6 +224,7 @@ class WatsonX extends BaseLLM {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal
});
if (!response.ok || response.body === null) {

View file

@ -90,7 +90,7 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -7,7 +7,9 @@ import type {
ContextItemWithId,
ContextSubmenuItem,
DiffLine,
FileSymbolMap,
IdeSettings,
IndexingStatusMap,
LLMFullCompletionOptions,
MessageContent,
ModelDescription,
@ -76,6 +78,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
"context/addDocs": [SiteIndexingConfig, void];
@ -142,6 +145,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ model: string; promptTokens: number; generatedTokens: number }[],
];
"tts/kill": [undefined, void];
// Codebase indexing
"index/setPaused": [boolean, void];
"index/forceReIndex": [
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
@ -155,6 +160,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
// Docs etc. Indexing. TODO move codebase to this
"indexing/reindex": [{ type: string; id: string }, void];
"indexing/abort": [{ type: string; id: string }, void];
"indexing/setPaused": [{ type: string; id: string; paused: boolean }, void];
"indexing/initStatuses": [undefined, void];
addAutocompleteModel: [{ model: ModelDescription }, void];
"profiles/switch": [{ id: string }, undefined];

View file

@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/deleteModel",
"config/reload",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
@ -39,10 +40,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/forceReIndexFiles",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/initStatuses",
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
//
"completeOnboarding",
"addAutocompleteModel",
"config/listProfiles",
@ -55,7 +63,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",

View file

@ -1,12 +1,17 @@
import { ConfigValidationError } from "../config/validation.js";
import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js";
import type {
ContextItemWithId,
IndexingProgressUpdate,
IndexingStatus,
} from "../index.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [undefined, void];
configError: [ConfigValidationError[] | undefined, void];
getDefaultModelTitle: [undefined, string];
indexProgress: [IndexingProgressUpdate, void];
indexProgress: [IndexingProgressUpdate, void]; // Codebase
"indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc.
refreshSubmenuItems: [undefined, void];
isContinueInputFocused: [undefined, boolean];
addContextItem: [

View file

@ -52,6 +52,7 @@ export class ChatDescriber {
content: ChatDescriber.prompt + message,
},
],
new AbortController().signal,
completionOptions,
);

View file

@ -11,8 +11,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
multilineCompletions: "auto",
slidingWindowPrefixPercentage: 0.75,
slidingWindowSize: 500,
maxSnippetPercentage: 0.6,
recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold.
maxSnippetPercentage: 0.5,
maxDiffPercentage: 0.5,
useCache: true,
onlyMyCode: true,
useOtherFiles: true,

View file

@ -2,6 +2,7 @@ import fs from "node:fs";
import * as path from "node:path";
import Parser, { Language } from "web-tree-sitter";
import { FileSymbolMap, IDE, SymbolWithRange } from "..";
export enum LanguageName {
CPP = "cpp",
@ -205,3 +206,93 @@ async function loadLanguageForFileExt(
);
return await Parser.Language.load(wasmPath);
}
// See https://tree-sitter.github.io/tree-sitter/using-parsers
const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [
"class_declaration",
"class_definition",
"function_item", // function name = first "identifier" child
"function_definition",
"method_declaration", // method name = first "identifier" child
"method_definition",
"generator_function_declaration",
// property_identifier
// field_declaration
// "arrow_function",
];
export async function getSymbolsForFile(
filepath: string,
contents: string,
): Promise<SymbolWithRange[] | undefined> {
const parser = await getParserForFile(filepath);
if (!parser) {
return;
}
const tree = parser.parse(contents);
// console.log(`file: ${filepath}`);
// Function to recursively find all named nodes (classes and functions)
const symbols: SymbolWithRange[] = [];
function findNamedNodesRecursive(node: Parser.SyntaxNode) {
// console.log(`node: ${node.type}, ${node.text}`);
if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) {
// console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`);
// node.children.forEach((child) => {
// console.log(`child: ${child.type}, ${child.text}`);
// });
// Empirically, the actual name is the last identifier in the node
// Especially with languages where return type is declared before the name
// TODO use findLast in newer version of node target
let identifier: Parser.SyntaxNode | undefined = undefined;
for (let i = node.children.length - 1; i >= 0; i--) {
if (
node.children[i].type === "identifier" ||
node.children[i].type === "property_identifier"
) {
identifier = node.children[i];
break;
}
}
if (identifier?.text) {
symbols.push({
filepath,
type: node.type,
name: identifier.text,
range: {
start: {
character: node.startPosition.column,
line: node.startPosition.row,
},
end: {
character: node.endPosition.column + 1,
line: node.endPosition.row + 1,
},
},
});
}
}
node.children.forEach(findNamedNodesRecursive);
}
findNamedNodesRecursive(tree.rootNode);
return symbols;
}
export async function getSymbolsForManyFiles(
uris: string[],
ide: IDE,
): Promise<FileSymbolMap> {
const filesAndSymbols = await Promise.all(
uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => {
const contents = await ide.readFile(uri);
const symbols = await getSymbolsForFile(uri, contents);
return [uri, symbols ?? []];
}),
);
return Object.fromEntries(filesAndSymbols);
}

View file

@ -291,7 +291,7 @@ Reference the conversation in a Jira issue.
"name": "jira",
"params": {
"domain": "company.atlassian.net",
"token ": "ATATT..."
"token": "ATATT..."
}
}
]

View file

@ -27,7 +27,6 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
}
```
## Autocomplete model
We recommend configuring **Codestral** or **code-gecko** as your autocomplete model.
@ -43,6 +42,7 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo
}
}
```
## Embeddings model
We recommend configuring **text-embedding-004** as your embeddings model.

View file

@ -1,5 +1,5 @@
---
title: Reference
title: config.json Reference
description: Reference for the Continue _config.json_ configuration file
keywords: [config, config_schema.json, json]
---

View file

@ -7,7 +7,7 @@ sidebar_position: 5
## 内置的斜杠命令
Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。
Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。
## 定制斜杠命令

View file

@ -5,7 +5,7 @@ keywords: [定制]
sidebar_position: 5
---
Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡:
Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡:
```json title="config.json"
"tabAutocompleteOptions": {

View file

@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
:::info
这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。
这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。
:::
## 最好的总体体验

View file

@ -44,7 +44,7 @@ ollama run starcoder2:3b
}
```
如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。
如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。
## 配置选项

View file

@ -0,0 +1,52 @@
---
title: NVIDIA
---
:::info
[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key.
:::
## Chat model
We recommend configuring **Nemotron-4-340B-Instruct** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Nemotron-4-340B-Instruct",
"provider": "nvidia",
"model": "nvidia-nemotron-4-340b-instruct",
"apiKey": "[API_KEY]"
}
]
}
```
## Autocomplete model
NVIDIA currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "nvidia",
"model": "nvidia/nv-embedqa-mistral-7b-v2",
"apiKey": "[API_KEY]"
}
}
```
## Reranking model
NVIDIA currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.

View file

@ -0,0 +1,65 @@
---
title: Vertex AI
slug: ../vertexai
---
:::info
You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).
:::
## Chat model
We recommend configuring **Claude 3.5 Sonnet** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "vertexai",
"model": "claude-3-5-sonnet-20240620",
"projectId": "[PROJECT_ID]",
"region": "us-east5"
}
]
}
```
## Autocomplete model
We recommend configuring **Codestral** or **code-gecko** as your autocomplete model.
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Codestral (Vertex AI)",
"provider": "vertexai",
"model": "codestral",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
}
```
## Embeddings model
We recommend configuring **text-embedding-004** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "vertexai",
"model": "text-embedding-004",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
}
```
## Reranking model
<!-- Vertex AI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers. -->

View file

@ -0,0 +1,53 @@
---
title: xAI
slug: ../xai
---
:::info
You can get an API key from the [xAI console](https://console.x.ai/)
:::
## Chat model
We recommend configuring **grok-beta** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Grok Beta",
"provider": "xAI",
"model": "grok-beta",
"apiKey": "[API_KEY]"
}
]
}
```
## Autocomplete model
xAI currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
xAI currently does not offer any embeddings models.
[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers.
## Reranking model
xAI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Legacy Completions
To force usage of `chat/completions` instead of `completions` endpoint you can set
```json
"useLegacyCompletionsEndpoint": false
```

View file

@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config
## 开始
要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。
要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。
当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。
## 每个工作区的配置
如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。
如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。
## 可编程的配置

View file

@ -5,6 +5,6 @@ description: 如何设置一个编辑模型
keywords: [编辑, cmd l, 模型]
---
默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。
默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。
你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。
你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。

View file

@ -0,0 +1,446 @@
---
title: Reference
description: Reference for the Continue _config.json_ configuration file
keywords: [config, config_schema.json, json]
---
Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json).
**All properties at all levels are optional unless explicitly marked required**
### `models`
Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md).
Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json.
**Properties:**
- `title` (**required**): The title to assign to your model, shown in dropdowns, etc.
- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions.
- `model` (**required**): The name of the model, used for prompt template auto-detection.
- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere.
- `apiBase`: The base URL of the LLM API.
- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048).
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions.
- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt).
- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override.
- `systemMessage`: A system message that will precede responses from the LLM.
- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override.
- `apiType`: Specifies the type of API (`openai` or `azure`).
- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`).
- `engine`: Engine for Azure OpenAI requests.
- `capabilities`: Override auto-detected capabilities:
- `uploadImage`: Boolean indicating if the model supports image uploads.
_(AWS Only)_
- `profile`: AWS security profile for authorization.
- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider).
- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`).
Example:
```json title="config.json"
{
"models": [
{
"title": "Ollama",
"provider": "ollama",
"model": "AUTODETECT"
},
{
"model": "gpt-4o",
"contextLength": 128000,
"title": "GPT-4o",
"provider": "openai",
"apiKey": "YOUR_API_KEY"
}
]
}
```
### `tabAutocompleteModel`
Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model.
Example
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "My Starcoder",
"provider": "ollama",
"model": "starcoder2:3b"
}
}
```
### `tabAutocompleteOptions`
Specifies options for tab autocompletion behavior.
**Properties:**
- `disable`: If `true`, disables tab autocomplete (default: `false`).
- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt.
- `useFileSuffix`: If `true`, includes file suffix in the prompt.
- `maxPromptTokens`: Maximum number of tokens for the prompt.
- `debounceDelay`: Delay (in ms) before triggering autocomplete.
- `maxSuffixPercentage`: Maximum percentage of prompt for suffix.
- `prefixPercentage`: Percentage of input for prefix.
- `template`: Template string for autocomplete, using Mustache templating.
- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`).
- `useCache`: If `true`, caches completions.
- `onlyMyCode`: If `true`, only includes code within the repository.
- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`).
- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled.
Example
```json title="config.json"
{
"tabAutocompleteOptions": {
"debounceDelay": 500,
"maxPromptTokens": 1500,
"disableInFiles": ["*.md"]
}
}
```
### `embeddingsProvider`
Embeddings model settings - the model used for @Codebase and @docs.
**Properties:**
- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc
- `model`: Model name for embeddings.
- `apiKey`: API key for the provider.
- `apiBase`: Base URL for API requests.
- `requestOptions`: Additional HTTP request settings specific to the embeddings provider.
- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens.
- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk.
(AWS ONLY)
- `region`: Specifies the region hosting the model.
- `profile`: AWS security profile.
Example:
```json title="config.json"
{
"embeddingsProvider": {
"provider": "openai",
"model": "text-embedding-ada-002",
"apiKey": "<API_KEY>",
"maxChunkSize": 256,
"maxBatchSize": 5
}
}
```
### `completionOptions`
Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_.
**Properties:**
- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`).
- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs.
- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass.
- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability.
- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output.
- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition.
- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0).
- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions.
- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`).
- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`.
- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes).
- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
Example
```json title="config.json"
{
"completionOptions": {
"stream": false,
"temperature": 0.5
}
}
```
### `requestOptions`
Default HTTP request options that apply to all models and context providers, unless overridden at the model level.
**Properties:**
- `timeout`: Timeout for each request to the LLM (default: 7200 seconds).
- `verifySsl`: Whether to verify SSL certificates for requests.
- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths)
- `proxy`: Proxy URL to use for HTTP requests.
- `headers`: Custom headers for HTTP requests.
- `extraBodyProperties`: Additional properties to merge with the HTTP request body.
- `noProxy`: List of hostnames that should bypass the specified proxy.
- `clientCertificate`: Client certificate for HTTP requests.
- `cert`: Path to the client certificate file.
- `key`: Path to the client certificate key file.
- `passphrase`: Optional passphrase for the client certificate key file.
Example
```json title="config.json"
{
"requestOptions": {
"headers": {
"X-Auth-Token": "xxx"
}
}
}
```
### `reranker`
Configuration for the reranker model used in response ranking.
**Properties:**
- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`
- `params`:
- `model`: Model name
- `apiKey`: Api key
Example
```json title="config.json"
{
"reranker": {
"name": "voyage",
"params": {
"model": "rerank-2",
"apiKey": "<VOYAGE_API_KEY>"
}
}
}
```
### `docs`
List of documentation sites to index.
**Properties:**
- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
- `maxDepth`: Maximum depth for crawling. Default `3`
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
Example
```json title="config.json"
"docs": [
{
"title": "Continue",
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
}
]
```
### `analytics`
Configuration for analytics tracking.
**Properties:**
- `provider`: Analytics provider (`"posthog"` or `"logstash"`).
- `url`: URL for analytics data.
- `clientKey`: Client key for analytics.
### `slashCommands`
Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined.
**Properties:**
- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review".
- `description`: Brief description of the command.
- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options.
- `params`: Additional parameters to configure command behavior (command-specific - see code for command)
Example:
```json title="config.json"
{
"slashCommands": [
{
"name": "commit",
"description": "Generate a commit message"
},
{
"name": "share",
"description": "Export this session as markdown"
},
{
"name": "cmd",
"description": "Generate a shell command"
}
]
}
```
### `customCommands`
User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions.
**Properties:**
- `name`: The name of the custom command.
- `prompt`: Text prompt for the command.
- `description`: Brief description explaining the command's function.
Example:
```json title="config.json"
{
"customCommands": [
{
"name": "test",
"prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
"description": "Write unit tests for highlighted code"
}
]
}
```
### `contextProviders`
List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`.
**Properties:**
- `name`: Name of the context provider, e.g. `docs` or `web`
- `params`: A context-provider-specific record of params to configure the context behavior
Example
```json title="config.json"
{
"contextProviders": [
{
"name": "code",
"params": {}
},
{
"name": "docs",
"params": {}
},
{
"name": "diff",
"params": {}
},
{
"name": "open",
"params": {}
}
]
}
```
### `disableSessionTitles`
Prevents generating summary titles for each chat session when set to `true`.
### `ui`
Customizable UI settings to control interface appearance and behavior.
**Properties:**
- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`.
- `fontSize`: Specifies font size for UI elements.
- `displayRawMarkdown`: If `true`, shows raw markdown in responses.
- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window.
Example:
```json title="config.json"
{
"ui": {
"codeBlockToolbarPosition": "bottom",
"fontSize": 14,
"displayRawMarkdown": false
}
}
```
### `allowAnonymousTelemetry`
When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`.
### `userToken`
An optional token that identifies the user, primarily for authenticated services.
### `systemMessage`
Defines a system message that appears before every response from the language model, providing guidance or context.
### `disableIndexing`
Prevents indexing of the codebase, useful primarily for debugging purposes.
### `experimental`
Several experimental config parameters are available, as described below:
`experimental`:
- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.=
- `modelRoles`:
- `inlineEdit`: Model title for inline edits.
- `applyCodeBlock`: Model title for applying code blocks.
- `repoMapFileSelection`: Model title for repo map selections.
- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`.
- `promptPath`: Change the path to custom prompt files from the default ".prompts"
- `quickActions`: Array of custom quick actions
- `title` (**required**): Display title for the quick action.
- `prompt` (**required**): Prompt for quick action.
- `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`.
- `contextMenuPrompts`:
- `comment`: Prompt for commenting code.
- `docstring`: Prompt for adding docstrings.
- `fix`: Prompt for fixing code.
- `optimize`: Prompt for optimizing code.
- `fixGrammar`: Prompt for fixing grammar or spelling.
- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`..
Example
```json title="config.json"
{
"experimental": {
"modelRoles": {
"inlineEdit": "Edit Model"
},
"promptPath": "custom/.prompts",
"quickActions": [
{
"title": "Tags",
"prompt": "Return a list of any function and class names from the included code block",
"sendToChat": true
}
],
"contextMenuPrompts": {
"fixGrammar": "Fix grammar in the above but allow for typos."
},
"readResponseTTS": false,
"useChromiumForDocsCrawling": true
}
}
```

View file

@ -771,6 +771,9 @@
"starcoder-1b",
"starcoder-3b",
"starcoder2-3b",
"mistral-tiny",
"mistral-small",
"mistral-medium",
"qwen2.5-coder:1.5b",
"qwen2.5-coder:3b",
"qwen2.5-coder:7b",
@ -2353,7 +2356,7 @@
"type": "integer",
"description": "The maximum depth to crawl the documentation site"
},
"favicon": {
"faviconUrl": {
"type": "string",
"description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL"
}

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.231",
"version": "0.9.232",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -21,7 +21,6 @@ import {
uriFromFilePath,
} from "./vscode";
import type { FileEdit, RangeInFile, Thread } from "core";
const util = require("node:util");
@ -181,7 +180,8 @@ export class VsCodeIdeUtils {
vscode.workspace
.openTextDocument(
vscode.Uri.parse(
`${VsCodeExtension.continueVirtualDocumentScheme
`${
VsCodeExtension.continueVirtualDocumentScheme
}:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`,
),
)
@ -305,8 +305,8 @@ export class VsCodeIdeUtils {
return `${lines
.slice(range.start.line, range.end.line)
.join("\n")}\n${lines[
range.end.line < lines.length - 1 ? range.end.line : lines.length - 1
].slice(0, range.end.character)}`;
range.end.line < lines.length - 1 ? range.end.line : lines.length - 1
].slice(0, range.end.character)}`;
}
async getTerminalContents(commands = -1): Promise<string> {
@ -572,7 +572,6 @@ export class VsCodeIdeUtils {
async getDiff(includeUnstaged: boolean): Promise<string> {
let diffs: string[] = [];
let repos = [];
for (const dir of this.getWorkspaceDirectories()) {
const repo = await this.getRepo(vscode.Uri.file(dir));
@ -580,20 +579,16 @@ export class VsCodeIdeUtils {
continue;
}
repos.push(repo.state.HEAD?.name);
const staged = await repo.diff(true);
diffs.push(`${staged}`);
diffs.push(staged);
if (includeUnstaged) {
const unstaged = await repo.diff(false);
diffs.push(`\n${unstaged}`);
diffs.push(unstaged);
}
}
const fullDiff = diffs.join("\n\n");
if (fullDiff.trim() === "") {
console.log(`Diff empty for repos: ${repos}`);
}
return fullDiff;
}

View file

@ -1,11 +1,12 @@
import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline";
import { SessionInfo } from "core";
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Input } from "..";
import useHistory from "../../hooks/useHistory";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { RootState } from "../../redux/store";
function lastPartOfPath(path: string): string {
const sep = path.includes("/") ? "/" : "\\";
@ -29,6 +30,9 @@ export function HistoryTableRow({
const [sessionTitleEditValue, setSessionTitleEditValue] = useState(
session.title,
);
const currentSessionId = useSelector(
(state: RootState) => state.state.sessionId,
);
const { saveSession, deleteSession, loadSession, getSession, updateSession } =
useHistory(dispatch);
@ -59,8 +63,11 @@ export function HistoryTableRow({
className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3"
onClick={async () => {
// Save current session
await saveSession();
await loadSession(session.sessionId);
if (session.sessionId !== currentSessionId) {
await saveSession();
await loadSession(session.sessionId);
}
navigate("/");
}}
>

View file

@ -93,6 +93,7 @@ export default function StepContainer(props: StepContainerProps) {
<StyledMarkdownPreview
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
itemIndex={props.index}
/>
)}
</ContentDiv>

View file

@ -1,11 +1,20 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
import {
CheckCircleIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "@heroicons/react/24/outline";
import { SiteIndexingConfig } from "core";
import { usePostHog } from "posthog-js/react";
import { useContext, useLayoutEffect, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { Button, HelperText, Input, lightGray } from "..";
import { useDispatch, useSelector } from "react-redux";
import { Button, HelperText, Input, lightGray, SecondaryButton } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { RootState } from "../../redux/store";
import IndexingStatusViewer from "../indexing/IndexingStatus";
function AddDocsDialog() {
const posthog = usePostHog();
@ -18,7 +27,12 @@ function AddDocsDialog() {
const [faviconUrl, setFaviconUrl] = useState("");
const [isOpen, setIsOpen] = useState(false);
const [submittedConfig, setSubmittedConfig] = useState<SiteIndexingConfig>();
const ideMessenger = useContext(IdeMessengerContext);
const indexingStatuses = useSelector(
(store: RootState) => store.state.indexing.statuses,
);
const isFormValid = startUrl && title;
@ -41,15 +55,66 @@ function AddDocsDialog() {
ideMessenger.post("context/addDocs", siteIndexingConfig);
setSubmittedConfig(siteIndexingConfig);
setTitle("");
setStartUrl("");
setFaviconUrl("");
dispatch(setShowDialog(false));
posthog.capture("add_docs_gui", { url: startUrl });
}
if (submittedConfig) {
const status = indexingStatuses[submittedConfig.startUrl];
return (
<div className="flex flex-col p-4">
<div className="flex flex-row items-center gap-2">
<CheckCircleIcon className="h-8 w-8" />
<h1>{`Docs added`}</h1>
</div>
<div className="flex flex-col gap-1 text-stone-500">
<p className="m-0 p-0">Title: {submittedConfig.title}</p>
<p className="m-0 p-0">Start URL: {submittedConfig.startUrl}</p>
{submittedConfig.rootUrl && (
<p className="m-0 p-0">Root URL: {submittedConfig.rootUrl}</p>
)}
{submittedConfig.maxDepth && (
<p className="m-0 p-0">Max depth: {submittedConfig.maxDepth}</p>
)}
{submittedConfig.faviconUrl && (
<p className="m-0 p-0">Favicon URL: {submittedConfig.faviconUrl}</p>
)}
</div>
{!!status && (
<div className="mt-4 flex flex-col divide-x-0 divide-y-2 divide-solid divide-zinc-700">
<p className="m-0 mb-5 p-0 leading-snug">{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}</p>
<div className="pt-1">
<IndexingStatusViewer status={status} />
</div>
</div>
)}
<div className="mt-4 flex flex-row items-center justify-end gap-4">
<SecondaryButton
className=""
onClick={() => {
setSubmittedConfig(undefined);
}}
>
Add another
</SecondaryButton>
<Button
className=""
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
}}
>
Done
</Button>
</div>
</div>
);
}
return (
<div className="p-4">
<div className="mb-8">

View file

@ -34,7 +34,6 @@ const DialogContainer = styled.div`
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 75%;
`;
const Dialog = styled.div`
@ -72,6 +71,7 @@ const TextDialog = (props: TextDialogProps) => {
return (
<ScreenCover onClick={props.onClose} hidden={!props.showDialog}>
<DialogContainer
className="xs:w-[85%] w-[92%] sm:w-[75%]"
onClick={(e) => {
e.stopPropagation();
}}

View file

@ -154,7 +154,6 @@ export const Button = styled.button`
export const SecondaryButton = styled.button`
padding: 10px 12px;
margin: 8px 0;
height: 2.5rem;
border-radius: ${defaultBorderRadius};
border: 1px solid ${vscForeground};

View file

@ -0,0 +1,113 @@
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import { IndexingStatus } from "core";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline";
import { setIndexingChatPeekHidden } from "../../redux/slices/stateSlice";
interface MergedIndexingState {
displayName: string;
type: IndexingStatus["type"];
titles: IndexingStatus["title"][];
progressPercentage: number;
}
const mergeProgress = (states: IndexingStatus[]): number => {
const progress =
states.reduce((acc, state) => acc + state.progress, 0) / states.length;
return Math.min(100, Math.max(0, progress * 100));
};
export interface ChatIndexingPeekProps {
state: MergedIndexingState;
}
function ChatIndexingPeek({ state }: ChatIndexingPeekProps) {
const navigate = useNavigate();
const dispatch = useDispatch();
const hiddenPeeks = useSelector(
(store: RootState) => store.state.indexing.hiddenChatPeekTypes,
);
if (hiddenPeeks[state.type]) return null;
return (
<div
className="flex flex-row items-center border-0 border-t border-solid border-t-zinc-700 px-3 py-0.5"
onClick={() => {
navigate("/more");
}}
>
<div className="group flex flex-1 cursor-pointer flex-row items-center gap-2">
<div className={`flex flex-row items-center gap-2`}>
<p className="m-0 p-0 text-stone-500 group-hover:underline">
{state.displayName}
</p>
{/* <p className="no-underline lines lines-1 m-0 max-w-20 p-0 text-xs text-stone-500">
{state.titles.join(", ")}
</p> */}
</div>
<div className="my-2 h-1.5 flex-1 rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg bg-stone-500 transition-all duration-200 ease-in-out`}
style={{
width: `${state.progressPercentage}%`,
}}
/>
</div>
<div className="xs:flex hidden flex-row items-center gap-1 text-stone-500">
<span className="text-xs no-underline">
{state.progressPercentage.toFixed(0)}%
</span>
<ArrowPathIcon
className={`animate-spin-slow inline-block h-4 w-4 text-stone-500`}
></ArrowPathIcon>
</div>
</div>
<EyeSlashIcon
className="ml-2 h-4 w-4 cursor-pointer text-stone-500 hover:opacity-80"
onClick={(e) => {
dispatch(
setIndexingChatPeekHidden({ type: state.type, hidden: true }),
);
e.stopPropagation();
}}
/>
</div>
);
}
function ChatIndexingPeeks() {
const indexingStatuses = useSelector(
(store: RootState) => store.state.indexing.statuses,
);
const mergedIndexingStates: MergedIndexingState[] = useMemo(() => {
const mergedStates: MergedIndexingState[] = [];
const docsStates = Object.values(indexingStatuses).filter(
(status) => status.type === "docs" && status.status === "indexing",
);
if (docsStates.length > 0) {
mergedStates.push({
displayName: "Docs indexing",
type: "docs",
titles: docsStates.map((state) => state.title),
progressPercentage: mergeProgress(docsStates),
});
}
return mergedStates;
}, [indexingStatuses]);
if (!mergedIndexingStates.length) return null;
return (
<div className="flex flex-col gap-1">
{mergedIndexingStates.map((state) => {
return <ChatIndexingPeek state={state} />;
})}
</div>
);
}
export default ChatIndexingPeeks;

View file

@ -0,0 +1,147 @@
import { IndexingStatus } from "core";
import { PropsWithChildren, useContext, useMemo } from "react";
import { useDispatch } from "react-redux";
import { usePostHog } from "posthog-js/react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import {
ArrowPathIcon,
ArrowRightStartOnRectangleIcon,
ArrowTopRightOnSquareIcon,
CheckCircleIcon,
PauseCircleIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { updateIndexingStatus } from "../../redux/slices/stateSlice";
interface IndexingStatusViewerProps {
status: IndexingStatus;
}
const STATUS_TO_ICON: Record<IndexingStatus["status"], any> = {
indexing: ArrowPathIcon,
paused: PauseCircleIcon,
complete: CheckCircleIcon,
aborted: null,
deleted: null,
pending: null,
failed: XMarkIcon, // Since we show an erorr message below
};
function IndexingStatusViewer({ status }: IndexingStatusViewerProps) {
const ideMessenger = useContext(IdeMessengerContext);
const posthog = usePostHog();
const dispatch = useDispatch();
const reIndex = () =>
ideMessenger.post("indexing/reindex", {
type: status.type,
id: status.id,
});
const abort = () => {
ideMessenger.post("indexing/abort", {
type: status.type,
id: status.id,
});
// Optimistic abort status
dispatch(
updateIndexingStatus({ ...status, status: "aborted", progress: 0 }),
);
};
const progressPercentage = useMemo(() => {
return Math.min(100, Math.max(0, status.progress * 100));
}, [status.progress]);
const Icon = STATUS_TO_ICON[status.status];
return (
<div className="mt-2 flex w-full flex-col">
{/* {`${status.type} - ${status.id} - ${status.status} - ${status.progress} - ${status.description} - ${status.icon}`} */}
<div
className={`flex flex-row items-center justify-between gap-2 text-sm`}
>
<div
className={`flex flex-row items-center gap-2 ${status.url ? "cursor-pointer hover:underline" : ""}`}
onClick={() => {
if (status.url) {
ideMessenger.post("openUrl", status.url);
}
}}
>
{status.icon ? (
<img src={status.icon} alt="doc icon" className="h-4 w-4" />
) : null}
<p className="lines lines-1 m-0 p-0 text-left">
{status.title ?? status.id}
</p>
{!!status.url && (
<ArrowTopRightOnSquareIcon className="mb-0.5 h-3 w-3 text-stone-500" />
)}
</div>
{status.status === "pending" ? (
<div className="text-xs text-stone-500">Pending...</div>
) : (
<div className="flex flex-row items-center gap-1 text-stone-500">
<span className="text-xs">{progressPercentage.toFixed(0)}%</span>
{Icon ? (
<Icon
className={`inline-block h-4 w-4 text-stone-500 ${
status.status === "indexing" ? "animate-spin-slow" : ""
}`}
></Icon>
) : null}
</div>
)}
</div>
<div className="my-2 h-1.5 w-full rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg transition-all duration-200 ease-in-out ${
status.status === "failed" ? "bg-red-600" : "bg-stone-500"
}`}
style={{
width: `${progressPercentage}%`,
}}
/>
</div>
<div className="flex flex-row items-center justify-between gap-4">
<span
className={`cursor-pointer whitespace-nowrap text-xs text-stone-500 underline`}
onClick={
{
complete: reIndex,
indexing: abort,
failed: reIndex,
aborted: reIndex,
paused: () => {},
deleted: () => {},
pending: () => {},
}[status.status]
}
>
{
{
complete: "Click to re-index",
indexing: "Cancel indexing",
failed: "Click to retry",
aborted: "Click to index",
paused: "",
deleted: "",
pending: "",
}[status.status]
}
</span>
{/* {status.status === "indexing" && ( */}
<span className="lines lines-1 text-right text-xs text-stone-500">
{status.description}
</span>
{/* )} */}
</div>
</div>
);
}
export default IndexingStatusViewer;

View file

@ -0,0 +1,56 @@
import { useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import IndexingStatusViewer from "./IndexingStatus";
import { Button, SecondaryButton } from "..";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import AddDocsDialog from "../dialogs/AddDocsDialog";
function IndexingStatuses() {
const indexingStatuses = useSelector(
(store: RootState) => store.state.indexing.statuses,
);
const docsStatuses = useMemo(() => {
const docs = Object.values(indexingStatuses).filter(
(status) => status.type === "docs" && status.status !== "deleted",
);
return docs;
}, [indexingStatuses]);
const dispatch = useDispatch();
return (
<div className="flex flex-col gap-1">
<div className="flex flex-row items-center justify-between">
<h3 className="mb-1 mt-0 text-xl">@docs indexes</h3>
{/* <div className="border-1 rounded-full border">
<ChevronUpIcon className="h-8 w-8" />
</div> */}
{/* TODO add some way to hide, scroll, etc. */}
</div>
<span className="text-xs text-stone-500">
Manage your documentation sources
</span>
{/* <div className="flex max-h-[170px] flex-col gap-1 overflow-x-hidden overflow-y-scroll pr-2"> */}
{docsStatuses.length ? (
docsStatuses.map((status) => {
return <IndexingStatusViewer key={status.id} status={status} />;
})
) : (
<SecondaryButton
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));
}}
>
Add Docs
</SecondaryButton>
)}
</div>
// </div>
);
}
export default IndexingStatuses;

View file

@ -0,0 +1,16 @@
import {
ArrowPathIcon,
CheckCircleIcon,
PauseCircleIcon,
} from "@heroicons/react/24/outline";
import { IndexingStatus } from "core";
export const STATUS_TO_ICON: Record<IndexingStatus["status"], any> = {
indexing: ArrowPathIcon,
paused: PauseCircleIcon,
complete: CheckCircleIcon,
aborted: null,
deleted: null,
pending: null,
failed: null, // XMarkIcon, // Since we show an error message below
};

View file

@ -2,8 +2,6 @@ import { NodeViewWrapper } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { vscBadgeBackground } from "..";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
export const CodeBlockComponent = (props: any) => {
const { node, deleteNode, selected, editor, updateAttributes } = props;
@ -13,7 +11,7 @@ export const CodeBlockComponent = (props: any) => {
// store.state.history[store.state.history.length - 1].contextItems,
// );
// const isFirstContextItem = item.id === contextItems[0]?.id;
const isFirstContextItem = false;
const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now
return (
<NodeViewWrapper className="code-block-with-content" as="p">

View file

@ -9,10 +9,12 @@ import SafeImg from "../SafeImg";
import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils";
import { getIconFromDropdownItem } from "./MentionList";
import { getBasename } from "core/util";
import { RootState } from "../../redux/store";
import { useSelector } from "react-redux";
interface ContextItemsPeekProps {
contextItems?: ContextItemWithId[];
isGatheringContext: boolean;
isCurrentContextPeek: boolean;
}
interface ContextItemsPeekItemProps {
@ -118,7 +120,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
function ContextItemsPeek({
contextItems,
isGatheringContext,
isCurrentContextPeek,
}: ContextItemsPeekProps) {
const [open, setOpen] = useState(false);
@ -126,7 +128,16 @@ function ContextItemsPeek({
(ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name),
);
if ((!ctxItems || ctxItems.length === 0) && !isGatheringContext) {
const isGatheringContext = useSelector(
(store: RootState) => store.state.context.isGathering,
);
const gatheringMessage = useSelector(
(store: RootState) => store.state.context.gatheringMessage,
);
const indicateIsGathering = isCurrentContextPeek && isGatheringContext;
if ((!ctxItems || ctxItems.length === 0) && !indicateIsGathering) {
return null;
}
@ -151,7 +162,7 @@ function ContextItemsPeek({
<span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
{isGatheringContext ? (
<>
Gathering context
{gatheringMessage}
<AnimatedEllipsis />
</>
) : (

View file

@ -1,6 +1,5 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
@ -69,12 +68,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const availableContextProviders = useSelector(
(store: RootState) => store.state.config.contextProviders,
);
const isGatheringContextStore = useSelector(
(store: RootState) => store.state.isGatheringContext,
);
const [isGatheringContext, setIsGatheringContext] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
useWebviewListener(
"newSessionWithPrompt",
@ -92,22 +85,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
[props.isMainInput],
);
useEffect(() => {
if (isGatheringContextStore && !isGatheringContext) {
// 500ms delay when going from false -> true to prevent flashing loading indicator
timeoutRef.current = setTimeout(() => setIsGatheringContext(true), 500);
} else {
// Update immediately otherwise (i.e. true -> false)
setIsGatheringContext(isGatheringContextStore);
}
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [isGatheringContextStore]);
return (
<div className={`mb-1 ${props.hidden ? "hidden" : ""}`}>
<div className={`relative flex px-2`}>
@ -135,7 +112,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
</div>
<ContextItemsPeek
contextItems={props.contextItems}
isGatheringContext={isGatheringContext && props.isLastUserInput}
isCurrentContextPeek={props.isLastUserInput}
/>
</div>
);

View file

@ -9,6 +9,8 @@ import {
} from "core";
import { stripImages } from "core/llm/images";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { Dispatch } from "@reduxjs/toolkit";
import { setIsGatheringContext } from "../../redux/slices/stateSlice";
interface MentionAttrs {
label: string;
@ -29,6 +31,7 @@ async function resolveEditorContent(
modifiers: InputModifiers,
ideMessenger: IIdeMessenger,
defaultContextProviders: DefaultContextProvider[],
dispatch: Dispatch,
): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> {
let parts: MessagePart[] = [];
let contextItemAttrs: MentionAttrs[] = [];
@ -38,8 +41,7 @@ async function resolveEditorContent(
if (p.type === "paragraph") {
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
// Only take the first slash command
// Only take the first slash command\
if (foundSlashCommand && typeof slashCommand === "undefined") {
slashCommand = foundSlashCommand;
}
@ -103,6 +105,17 @@ async function resolveEditorContent(
}
}
const shouldGatherContext = modifiers.useCodebase || slashCommand;
if (shouldGatherContext) {
dispatch(
setIsGatheringContext({
isGathering: true,
gatheringMessage: "Gathering context",
}),
);
}
let contextItemsText = "";
let contextItems: ContextItemWithId[] = [];
for (const item of contextItemAttrs) {
@ -172,6 +185,15 @@ async function resolveEditorContent(
}
}
if (shouldGatherContext) {
dispatch(
setIsGatheringContext({
isGathering: false,
gatheringMessage: "Gathering context",
}),
);
}
return [contextItems, selectedCode, parts];
}

View file

@ -124,7 +124,6 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description.split(" ")[0],
)} ${props.item.description}\n${content}\n${fence}`}
contextItems={[props.item]}
/>
</div>

View file

@ -20,15 +20,15 @@ function FilenameLink({ rif }: FilenameLinkProps) {
}
return (
<div
className="mb-0.5 inline-flex cursor-pointer items-center gap-0.5 rounded-md py-0.5 pl-0 pr-1 align-middle hover:bg-stone-800"
<span
className="mx-[0.1em] mb-[0.15em] inline-flex cursor-pointer items-center gap-0.5 rounded-md pr-[0.2em] align-middle hover:ring-1"
onClick={onClick}
>
<FileIcon filename={rif.filepath} height="20px" width="20px" />
<span className="align-middle underline decoration-gray-600 underline-offset-2">
<span className="align-middle underline underline-offset-2">
{getBasename(rif.filepath)}
</span>
</div>
</span>
);
}

View file

@ -1,4 +1,4 @@
import { memo, useEffect } from "react";
import { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { useRemark } from "react-remark";
import rehypeHighlight, { Options } from "rehype-highlight";
import rehypeKatex from "rehype-katex";
@ -20,7 +20,10 @@ import StepContainerPreToolbar from "./StepContainerPreToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
import { ContextItemWithId } from "core";
import { RootState } from "../../redux/store";
import { ContextItemWithId, SymbolWithRange } from "core";
import SymbolLink from "./SymbolLink";
import { useSelector } from "react-redux";
const StyledMarkdown = styled.div<{
fontSize?: number;
@ -93,7 +96,7 @@ interface StyledMarkdownPreviewProps {
className?: string;
isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
scrollLocked?: boolean;
contextItems?: ContextItemWithId[];
itemIndex?: number;
}
const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
@ -117,12 +120,10 @@ function getCodeChildrenContent(children: any) {
} else if (
Array.isArray(children) &&
children.length > 0 &&
typeof children[0] === "string" &&
children[0] !== ""
typeof children[0] === "string"
) {
return children[0];
}
return undefined;
}
@ -154,6 +155,28 @@ function processCodeBlocks(tree: any) {
const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
props: StyledMarkdownPreviewProps,
) {
const contextItems = useSelector(
(state: RootState) =>
state.state.history[props.itemIndex - 1]?.contextItems,
);
const symbols = useSelector((state: RootState) => state.state.symbols);
// The refs are a workaround because rehype options are stored on initiation
// So they won't use the most up-to-date state values
// So in this case we just put them in refs
const symbolsRef = useRef<SymbolWithRange[]>([]);
const contextItemsRef = useRef<ContextItemWithId[]>([]);
useEffect(() => {
contextItemsRef.current = contextItems || [];
}, [contextItems]);
useEffect(() => {
// Note, before I was only looking for symbols that matched
// Context item files on current history item
// but in practice global symbols for session makes way more sense
symbolsRef.current = Object.values(symbols).flat();
}, [symbols]);
const [reactContent, setMarkdownSource] = useRemark({
remarkPlugins: [remarkMath, () => processCodeBlocks],
rehypePlugins: [
@ -236,16 +259,30 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
code: ({ node, ...codeProps }) => {
const content = getCodeChildrenContent(codeProps.children);
if (props.contextItems) {
const ctxItem = props.contextItems.find((ctxItem) =>
if (content && contextItemsRef.current) {
const ctxItem = contextItemsRef.current.find((ctxItem) =>
ctxItem.uri?.value.includes(content),
);
if (ctxItem) {
const rif = ctxItemToRifWithContents(ctxItem);
return <FilenameLink rif={rif} />;
}
}
const exactSymbol = symbolsRef.current.find(
(s) => s.name === content,
);
if (exactSymbol) {
return <SymbolLink content={content} symbol={exactSymbol} />;
}
// PARTIAL - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract`
const partialSymbol = symbolsRef.current.find((s) =>
content.startsWith(s.name),
);
if (partialSymbol) {
return <SymbolLink content={content} symbol={partialSymbol} />;
}
}
return <code {...codeProps}>{codeProps.children}</code>;
},
},

Some files were not shown because too many files have changed in this diff Show more