Merge branch 'main' into nate/tool-use

This commit is contained in:
Test 2024-11-21 21:36:36 -08:00
commit cf25bb210f
128 changed files with 4283 additions and 1724 deletions

View file

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

View file

@ -1,5 +1,4 @@
import { IDE } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import { IDE, RangeInFileWithContents } from "../..";
import { PrecalculatedLruCache } from "../../util/LruCache";
import {
getFullLanguageName,

View file

@ -1,7 +1,6 @@
import { RangeInFileWithContents } from "../../../commands/util.js";
import { Range } from "../../../index.js";
import { countTokens } from "../../../llm/countTokens.js";
import { HelperVars } from "../../util/HelperVars.js";
import { Range, RangeInFileWithContents } from "../../../";
import { countTokens } from "../../../llm/countTokens";
import { HelperVars } from "../../util/HelperVars";
export type AutocompleteSnippet = RangeInFileWithContents & {
score?: number;

View file

@ -1,6 +1,6 @@
import { RangeInFileWithContents } from "../../../commands/util.js";
import { RangeInFileWithContents } from "../../../";
import { AutocompleteSnippet, jaccardSimilarity } from "./index.js";
import { AutocompleteSnippet, jaccardSimilarity } from "./";
function* slidingWindow(
content: string,

View file

@ -83,6 +83,7 @@ export const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",
"<START EDITING HERE>",
"{{FILL_HERE}}"
];
export const ENGLISH_START_PHRASES = [

View file

@ -83,6 +83,24 @@ export function postprocessCompletion({
}
}
if (llm.model.includes("granite")) {
// Granite tends to repeat the start of the line in the completion output
let prefixEnd = prefix.split("\n").pop();
if (prefixEnd) {
if (completion.startsWith(prefixEnd)) {
completion = completion.slice(prefixEnd.length);
} else {
const trimmedPrefix = prefixEnd.trim();
const lastWord = trimmedPrefix.split(/\s+/).pop();
if (lastWord && completion.startsWith(lastWord)) {
completion = completion.slice(lastWord.length);
} else if (completion.startsWith(trimmedPrefix)) {
completion = completion.slice(trimmedPrefix.length);
}
}
}
}
// // If completion starts with multiple whitespaces, but the cursor is at the end of the line
// // then it should probably be on a new line
// if (
@ -99,7 +117,6 @@ export function postprocessCompletion({
prefix.endsWith(" ") &&
completion.startsWith(" ")
) {
const test = prefix.split("\n").pop()?.trim() !== "";
completion = completion.slice(1);
}

View file

@ -376,7 +376,8 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
if (
lowerCaseModel.includes("gpt") ||
lowerCaseModel.includes("davinci-002") ||
lowerCaseModel.includes("claude")
lowerCaseModel.includes("claude") ||
lowerCaseModel.includes("granite3")
) {
return holeFillerTemplate;
}

View file

@ -13,21 +13,24 @@ import {
import { getStopTokens } from "./getStopTokens";
import { countTokens } from "../../llm/countTokens";
const addCommentMarks = (text: string, language: AutocompleteLanguageInfo) => {
const comment = language.singleLineComment;
const lines = [
...text
.trim()
.split("\n")
.map((line) => `${comment} ${line}`),
];
return lines.join("\n");
};
export function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo,
) {
const comment = language.singleLineComment;
const lines = [
`${comment} Path: ${getBasename(filepath)}`,
...snippet
.trim()
.split("\n")
.map((line) => `${comment} ${line}`),
comment,
];
return lines.join("\n");
const filePathString = `Path: ${getBasename(filepath)}\n`;
return addCommentMarks(`${filePathString}${snippet}`, language);
}
function getContextComments(
@ -35,14 +38,21 @@ function getContextComments(
lang: AutocompleteLanguageInfo,
filepath: string,
) {
if (snippets.length === 0) {
return "";
}
const headerSnipper = `\n\n${lang.singleLineComment} Related code:\n`;
const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`;
const formattedSnippets =
headerSnipper +
snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n") + fileNameSnippet;
.join("\n") +
fileNameSnippet;
return formattedSnippets;
}
@ -90,16 +100,51 @@ const formatDiff = (helper: HelperVars, diff?: string) => {
return `${diff}\n\n`;
};
const MAX_CLIPBOARD_AGE = 5 * 60 * 1000;
const formatClipboardContent = (
helper: HelperVars,
{ text, copiedAt }: { text: string; copiedAt: string },
) => {
const currDate = new Date();
const isTooOld =
currDate.getTime() - new Date(copiedAt).getTime() > MAX_CLIPBOARD_AGE;
if (isTooOld) {
return "";
}
const tokenCount = countTokens(text, helper.modelName);
const isTooLong = tokenCount > helper.maxClipboardTokens;
if (isTooLong) {
return "";
}
return (
addCommentMarks(
`Recently copied by user:${text.includes("\n") ? "\n" : ""} ${text}`,
helper.lang,
) + "\n"
);
};
export function renderPrompt({
snippets,
workspaceDirs,
helper,
diff,
clipboardContent,
}: {
snippets: AutocompleteSnippet[];
workspaceDirs: string[];
helper: HelperVars;
diff?: string;
clipboardContent: {
text: string;
copiedAt: string;
};
}): {
prompt: string;
prefix: string;
@ -132,8 +177,11 @@ export function renderPrompt({
helper.filepath,
);
const formattedDiff = formatDiff(helper, diff);
const formattedClipboard = formatClipboardContent(helper, clipboardContent);
prefix = `${formattedDiff}${contextComments}${prefix}`;
prefix = [formattedClipboard, formattedDiff, contextComments, prefix].join(
"",
);
}
const prompt =

View file

@ -122,6 +122,10 @@ export class HelperVars {
return this.options.maxPromptTokens * this.options.maxDiffPercentage;
}
get maxClipboardTokens() {
return this.options.maxPromptTokens * this.options.maxClipboardPercentage;
}
get prunedCaretWindow() {
return this.prunedPrefix + this.prunedSuffix;
}

View file

@ -1,7 +1,7 @@
import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../../commands/util.js";
import { getParserForFile } from "../../util/treeSitter.js";
import { RangeInFileWithContents } from "../../";
import { getParserForFile } from "../../util/treeSitter";
export type AstPath = Parser.SyntaxNode[];

View file

@ -1,5 +1,10 @@
import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import {
Position,
Range,
RangeInFile,
RangeInFileWithContents,
TabAutocompleteOptions,
} from "../..";
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;

View file

@ -2,7 +2,6 @@ import GenerateTerminalCommand from "./cmd";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import HttpSlashCommand from "./http";
import MultiFileEditSlashCommand from "./multifileEdit";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
@ -15,5 +14,4 @@ export default [
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
MultiFileEditSlashCommand,
];

View file

@ -1,110 +0,0 @@
import { SlashCommand } from "../..";
import { renderChatMessage } from "../../util/messageContent";
const MultiFileEditSlashCommand: SlashCommand = {
name: "multifile-edit",
description: "Edit multiple files in the codebase at once",
run: async function* ({ llm, contextItems, selectedCode, input, ide }) {
// TODO: This is causing GUI builds to fail, so we're disabling it for now
// const selectedCodeStr = (
// await Promise.all(
// selectedCode.map(async (item) => {
// // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]`
// const [filepath, rangeStr] = item.filepath.split(" ");
// const { getFullyQualifiedPath } = await import(
// "../../../extensions/vscode/src/util/util"
// );
// const fullPath = getFullyQualifiedPath(ide as any, filepath); // any = VsCodeIde here, but importing it breaks tests
// if (!fullPath) {
// return "";
// }
// const codeStr = await ide.readRangeInFile(fullPath, item.range);
// // Include the filepath so the model can map it correctly with codeblock outputs
// return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``;
// }),
// )
// ).join("\n");
const fileContextItemsStr = contextItems
.filter((item) => item.uri?.type === "file")
.map((item) => item.content)
.join("\n");
const filesToEditStr = fileContextItemsStr + "\n"; // + selectedCodeStr;
const additionalContextStr = contextItems
.filter((item) => item.uri?.type !== "file")
.map((item) => `${item.description}: ${item.content}`)
.join("\n");
const content = createPrompt(filesToEditStr, additionalContextStr, input);
for await (const chunk of llm.streamChat(
[{ role: "user", content }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};
function createPrompt(
filesToEditStr: string,
additionalContextStr: string,
input: string,
): string {
return `
You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines:
1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!"
2. When providing instructions, if a user needs to interact with a CLI, walk them through each step
2. Perform file edits in a logical, sequential ordering
3. For each file edit, provide a brief explanation of the changes
4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
a. When creating new files, also inlcude the filname in the language specifier of the code block.
6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits
Remember to be concise and focus on the code changes and their impact.
Here's an example of how your response should be structured:
<example>
I'll make the following changes to implement feature X:
1. First, I'll modify file1.js to add a new function:
\`\`\`javascript /path/to/file1.js
// Entire content of file1.js or changes to be made
\`\`\`
2. Next, let's create a new test file:
\`\`\`javascript /path/to/file1.test.js
# Entire content of file2.py or changes to be made
\`\`\`
Summary:
- [Sequential overview of the most important 3-5 edits]
</example>
Now, let's make the changes based on the engineer's request:
<input>
${input}
</input>
Here are the files to base your edits on:
<files>
${filesToEditStr}
</files>
And here is any additional context the engineer has provided:
<context>
${additionalContextStr}
</context>
Please provide the multi-file edit details based on the engineer's request.
`;
}
export default MultiFileEditSlashCommand;

View file

@ -1,13 +1,4 @@
import { ContextItemWithId } from "../";
export interface RangeInFileWithContents {
filepath: string;
range: {
start: { line: number; character: number };
end: { line: number; character: number };
};
contents: string;
}
import { ContextItemWithId, RangeInFileWithContents } from "../";
export function ctxItemToRifWithContents(
item: ContextItemWithId,

View file

@ -12,6 +12,7 @@ import {
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath } from "../util/paths.js";
import { ConfigResult } from "./load.js";
import {
@ -84,6 +85,18 @@ export class ConfigHandler {
return this.profiles.filter((p) => p.profileId !== this.selectedProfileId);
}
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
await this.ide.openFile(getConfigJsonPath());
} else {
await this.ide.openUrl(
"https://app.continue.dev/",
// `https://app.continue.dev/workspaces/${openProfileId}/chat`,
);
}
}
private async fetchControlPlaneProfiles() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient

View file

@ -837,6 +837,7 @@ declare global {
slidingWindowSize: number;
maxSnippetPercentage: number;
maxDiffPercentage: number;
maxClipboardPercentage: 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

@ -28,8 +28,13 @@ import { DevDataSqliteDb } from "./util/devdataSqlite";
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import {
editConfigJson,
getConfigJsonPath,
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 ".";
@ -43,7 +48,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();
@ -89,7 +94,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", {
@ -149,6 +158,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,
@ -259,6 +269,10 @@ export class Core {
await this.configHandler.reloadConfig();
});
on("config/openProfile", async (msg) => {
await this.configHandler.openConfigProfile(msg.data.profileId);
});
on("config/reload", (msg) => {
void this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();
@ -273,34 +287,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) => {
@ -366,6 +361,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(),
@ -565,33 +565,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) =>
@ -703,6 +709,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;
@ -718,17 +726,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();
@ -809,7 +841,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -843,7 +875,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -852,4 +884,6 @@ export class Core {
this.messenger.send("refreshSubmenuItems", undefined);
}
// private
}

67
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>,
@ -352,13 +377,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;
@ -519,6 +550,7 @@ export interface IDE {
getIdeInfo(): Promise<IdeInfo>;
getIdeSettings(): Promise<IdeSettings>;
getDiff(includeUnstaged: boolean): Promise<string>;
getClipboardContent(): Promise<{ text: string; copiedAt: string }>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
@ -536,6 +568,7 @@ export interface IDE {
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
openFile(path: string): Promise<void>;
openUrl(url: string): Promise<void>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;
@ -1008,6 +1041,7 @@ export interface TabAutocompleteOptions {
slidingWindowSize: number;
maxSnippetPercentage: number;
maxDiffPercentage: number;
maxClipboardPercentage: number;
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;
@ -1041,6 +1075,37 @@ interface ModelRoles {
repoMapFileSelection?: string;
}
export type EditStatus =
| "not-started"
| "streaming"
| "accepting"
| "accepting:full-diff"
| "done";
export type ApplyStateStatus =
| "streaming" // Changes are being applied to the file
| "done" // All changes have been applied, awaiting user to accept/reject
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
export interface ApplyState {
streamId: string;
status?: ApplyStateStatus;
numDiffs?: number;
filepath?: string;
fileContent?: string;
}
export interface RangeInFileWithContents {
filepath: string;
range: {
start: { line: number; character: number };
end: { line: number; character: number };
};
contents: string;
}
export type CodeToEdit = RangeInFileWithContents | FileWithContents;
/**
* Represents the configuration for a quick action in the Code Lens.
* Quick actions are custom commands that can be added to function and class declarations.

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

@ -470,7 +470,7 @@ export abstract class BaseLLM implements ILLM {
);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
await this.writeLog(`Completion:\n${completion}\n\n`);
}
return {
@ -522,7 +522,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
await this.writeLog(`Completion:\n${completion}\n\n`);
}
}
@ -567,7 +567,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
await this.writeLog(`Completion:\n${completion}\n\n`);
}
return completion;
@ -637,7 +637,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
await this.writeLog(`Completion:\n${completion}\n\n`);
}
return {

View file

@ -105,7 +105,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)

View file

@ -14,6 +14,11 @@ import {
import { renderChatMessage } from "../../util/messageContent.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> = {

485
core/package-lock.json generated
View file

@ -24,7 +24,7 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.11.0",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
@ -1230,6 +1230,241 @@
}
}
},
"node_modules/@azure/abort-controller": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz",
"integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-auth": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.9.0.tgz",
"integrity": "sha512-FPwHpZywuyasDSLMqJ6fhbOK3TqUdviZNF8OqRGA4W5Ewib2lEEZ+pBsYcBa88B2NGO/SEnYPGhyBqNlE8ilSw==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-util": "^1.11.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-client": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/@azure/core-client/-/core-client-1.9.2.tgz",
"integrity": "sha512-kRdry/rav3fUKHl/aDLd/pDLcB+4pOFwPPTVEExuMyaI5r+JBbMWqRbCY1pn5BniDaU3lRxO9eaQ1AmSMehl/w==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.4.0",
"@azure/core-rest-pipeline": "^1.9.1",
"@azure/core-tracing": "^1.0.0",
"@azure/core-util": "^1.6.1",
"@azure/logger": "^1.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-http-compat": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-http-compat/-/core-http-compat-2.1.2.tgz",
"integrity": "sha512-5MnV1yqzZwgNLLjlizsU3QqOeQChkIXw781Fwh1xdAqJR5AA32IUaq6xv1BICJvfbHoa+JYcaij2HFkhLbNTJQ==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-client": "^1.3.0",
"@azure/core-rest-pipeline": "^1.3.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-lro": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/@azure/core-lro/-/core-lro-2.7.2.tgz",
"integrity": "sha512-0YIpccoX8m/k00O7mDDMdJpbr6mf1yWo2dfmxt5A8XVZVVMz2SSKaEbMCeJRvgQ0IaSlqhjT47p4hVIRRy90xw==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-util": "^1.2.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-paging": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/@azure/core-paging/-/core-paging-1.6.2.tgz",
"integrity": "sha512-YKWi9YuCU04B55h25cnOYZHxXYtEvQEbKST5vqRga7hWY9ydd3FZHdeQF8pyh+acWZvppw13M/LMGx0LABUVMA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-rest-pipeline": {
"version": "1.18.0",
"resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.18.0.tgz",
"integrity": "sha512-QSoGUp4Eq/gohEFNJaUOwTN7BCc2nHTjjbm75JT0aD7W65PWM1H/tItz0GsABn22uaKyGxiMhWQLt2r+FGU89Q==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.8.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.11.0",
"@azure/logger": "^1.0.0",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-tracing": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz",
"integrity": "sha512-UKTiEJPkWcESPYJz3X5uKRYyOcJD+4nYph+KpfdPRnQJVrZfk0KJgdnaAWKfhsBBtAf/D58Az4AvCJEmWgIBAg==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-util": {
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.11.0.tgz",
"integrity": "sha512-DxOSLua+NdpWoSqULhjDyAZTXFdP/LKkqtYuxxz1SCN289zk3OG8UOpnCQAz/tygyACBtWp/BoO72ptK7msY8g==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/identity": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/@azure/identity/-/identity-4.5.0.tgz",
"integrity": "sha512-EknvVmtBuSIic47xkOqyNabAme0RYTw52BTMz8eBgU1ysTyMrD1uOoM+JdS0J/4Yfp98IBT3osqq3BfwSaNaGQ==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.9.0",
"@azure/core-client": "^1.9.2",
"@azure/core-rest-pipeline": "^1.17.0",
"@azure/core-tracing": "^1.0.0",
"@azure/core-util": "^1.11.0",
"@azure/logger": "^1.0.0",
"@azure/msal-browser": "^3.26.1",
"@azure/msal-node": "^2.15.0",
"events": "^3.0.0",
"jws": "^4.0.0",
"open": "^8.0.0",
"stoppable": "^1.1.0",
"tslib": "^2.2.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/keyvault-common": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@azure/keyvault-common/-/keyvault-common-2.0.0.tgz",
"integrity": "sha512-wRLVaroQtOqfg60cxkzUkGKrKMsCP6uYXAOomOIysSMyt1/YM0eUn9LqieAWM8DLcU4+07Fio2YGpPeqUbpP9w==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.3.0",
"@azure/core-client": "^1.5.0",
"@azure/core-rest-pipeline": "^1.8.0",
"@azure/core-tracing": "^1.0.0",
"@azure/core-util": "^1.10.0",
"@azure/logger": "^1.1.4",
"tslib": "^2.2.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/keyvault-keys": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/@azure/keyvault-keys/-/keyvault-keys-4.9.0.tgz",
"integrity": "sha512-ZBP07+K4Pj3kS4TF4XdkqFcspWwBHry3vJSOFM5k5ZABvf7JfiMonvaFk2nBF6xjlEbMpz5PE1g45iTMme0raQ==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.3.0",
"@azure/core-client": "^1.5.0",
"@azure/core-http-compat": "^2.0.1",
"@azure/core-lro": "^2.2.0",
"@azure/core-paging": "^1.1.1",
"@azure/core-rest-pipeline": "^1.8.1",
"@azure/core-tracing": "^1.0.0",
"@azure/core-util": "^1.0.0",
"@azure/keyvault-common": "^2.0.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/logger": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.4.tgz",
"integrity": "sha512-4IXXzcCdLdlXuCG+8UKEwLA1T1NHqUfanhXYHiQTn+6sfWCZXduqbtXDGceg3Ce5QxTGo7EqmbV6Bi+aqKuClQ==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/msal-browser": {
"version": "3.27.0",
"resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-3.27.0.tgz",
"integrity": "sha512-+b4ZKSD8+vslCtVRVetkegEhOFMLP3rxDWJY212ct+2r6jVg6OSQKc1Qz3kCoXo0FgwaXkb+76TMZfpHp8QtgA==",
"dependencies": {
"@azure/msal-common": "14.16.0"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/@azure/msal-common": {
"version": "14.16.0",
"resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-14.16.0.tgz",
"integrity": "sha512-1KOZj9IpcDSwpNiQNjt0jDYZpQvNZay7QAEi/5DLubay40iGYtLzya/jbjRPLyOTZhEKyL1MzPuw2HqBCjceYA==",
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/@azure/msal-node": {
"version": "2.16.2",
"resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-2.16.2.tgz",
"integrity": "sha512-An7l1hEr0w1HMMh1LU+rtDtqL7/jw74ORlc9Wnh06v7TU/xpG39/Zdr1ZJu3QpjUfKJ+E0/OXMW8DRSWTlh7qQ==",
"dependencies": {
"@azure/msal-common": "14.16.0",
"jsonwebtoken": "^9.0.0",
"uuid": "^8.3.0"
},
"engines": {
"node": ">=16"
}
},
"node_modules/@azure/msal-node/node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/@babel/code-frame": {
"version": "7.24.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz",
@ -3856,6 +4091,11 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@js-joda/core": {
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/@js-joda/core/-/core-5.6.3.tgz",
"integrity": "sha512-T1rRxzdqkEXcou0ZprN1q9yDRlvzCPLqmlNt5IIsGBzoEVgLCCYrKEwc84+TvsXuAc95VAZwtWD2zVsKPY4bcA=="
},
"node_modules/@lancedb/vectordb-darwin-arm64": {
"version": "0.4.20",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.20.tgz",
@ -4815,6 +5055,11 @@
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="
},
"node_modules/@tediousjs/connection-string": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/@tediousjs/connection-string/-/connection-string-0.5.0.tgz",
"integrity": "sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ=="
},
"node_modules/@tootallnate/once": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz",
@ -5086,6 +5331,20 @@
"node": ">=12"
}
},
"node_modules/@types/readable-stream": {
"version": "4.0.18",
"resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.18.tgz",
"integrity": "sha512-21jK/1j+Wg+7jVw1xnSwy/2Q1VgVjWuFssbYGTREPUBeZ+rqVFl2udq0IkxzPC0ZhOzVceUbyIACFZKLqKEBlA==",
"dependencies": {
"@types/node": "*",
"safe-buffer": "~5.1.1"
}
},
"node_modules/@types/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/@types/request": {
"version": "2.48.12",
"resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.12.tgz",
@ -6274,7 +6533,6 @@
"url": "https://feross.org/support"
}
],
"optional": true,
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
@ -6966,10 +7224,11 @@
}
},
"node_modules/dbinfoz": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.11.0.tgz",
"integrity": "sha512-l7REBd9pwTBI6PWSk/dx+zCpSE2tiJdSKfApeoOajnSgyMJgkwGfhpPO2mV76MLQeKPaSm0mMKxmoqd38SaHmw==",
"version": "0.14.0",
"resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.14.0.tgz",
"integrity": "sha512-8NLjmj3gEyxbMu1ZwPEby77QvoEkk5NrHKSwX4oSKeaREherwuSx1y08cXmxBEjrSmvByUX9axoKscuilSXfmg==",
"dependencies": {
"mssql": "^11.0.1",
"mysql2": "^3.9.1",
"pg": "^8.11.3",
"sqlite3": "^5.1.7"
@ -7062,6 +7321,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/define-lazy-prop": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz",
"integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==",
"engines": {
"node": ">=8"
}
},
"node_modules/define-properties": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
@ -9374,6 +9641,20 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-docker": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz",
"integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==",
"bin": {
"is-docker": "cli.js"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-electron": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/is-electron/-/is-electron-2.2.2.tgz",
@ -9578,6 +9859,17 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-wsl": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
"dependencies": {
"is-docker": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/isarray": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
@ -10560,6 +10852,11 @@
"jinjajs": "cli.js"
}
},
"node_modules/js-md4": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/js-md4/-/js-md4-0.3.2.tgz",
"integrity": "sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA=="
},
"node_modules/js-tiktoken": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.12.tgz",
@ -10724,6 +11021,46 @@
"node": ">= 10.0.0"
}
},
"node_modules/jsonwebtoken": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
"integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==",
"dependencies": {
"jws": "^3.2.2",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^7.5.4"
},
"engines": {
"node": ">=12",
"npm": ">=6"
}
},
"node_modules/jsonwebtoken/node_modules/jwa": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
"integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
"dependencies": {
"buffer-equal-constant-time": "1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jsonwebtoken/node_modules/jws": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
"integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
"dependencies": {
"jwa": "^1.4.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jsprim": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
@ -10889,6 +11226,36 @@
"integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==",
"dev": true
},
"node_modules/lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="
},
"node_modules/lodash.isboolean": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="
},
"node_modules/lodash.isinteger": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="
},
"node_modules/lodash.isnumber": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="
},
"node_modules/lodash.isplainobject": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="
},
"node_modules/lodash.isstring": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="
},
"node_modules/lodash.memoize": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz",
@ -10900,6 +11267,11 @@
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="
},
"node_modules/lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="
},
"node_modules/long": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
@ -11289,6 +11661,33 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/mssql": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/mssql/-/mssql-11.0.1.tgz",
"integrity": "sha512-KlGNsugoT90enKlR8/G36H0kTxPthDhmtNUCwEHvgRza5Cjpjoj+P2X6eMpFUDN7pFrJZsKadL4x990G8RBE1w==",
"dependencies": {
"@tediousjs/connection-string": "^0.5.0",
"commander": "^11.0.0",
"debug": "^4.3.3",
"rfdc": "^1.3.0",
"tarn": "^3.0.2",
"tedious": "^18.2.1"
},
"bin": {
"mssql": "bin/mssql"
},
"engines": {
"node": ">=18"
}
},
"node_modules/mssql/node_modules/commander": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz",
"integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==",
"engines": {
"node": ">=16"
}
},
"node_modules/myers-diff": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/myers-diff/-/myers-diff-2.1.0.tgz",
@ -11341,6 +11740,11 @@
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz",
"integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg=="
},
"node_modules/native-duplexpair": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/native-duplexpair/-/native-duplexpair-1.0.0.tgz",
"integrity": "sha512-E7QQoM+3jvNtlmyfqRZ0/U75VFgCls+fSkbml2MpgWkWyz3ox8Y58gNhfuziuQYGNNQAbFZJQck55LHCnCK6CA=="
},
"node_modules/natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@ -11799,6 +12203,22 @@
"resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz",
"integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA=="
},
"node_modules/open": {
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz",
"integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==",
"dependencies": {
"define-lazy-prop": "^2.0.0",
"is-docker": "^2.1.1",
"is-wsl": "^2.2.0"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/openai": {
"version": "4.47.1",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.47.1.tgz",
@ -12519,7 +12939,6 @@
"version": "0.11.10",
"resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
"integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
"optional": true,
"engines": {
"node": ">= 0.6.0"
}
@ -12881,7 +13300,6 @@
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz",
"integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==",
"optional": true,
"dependencies": {
"abort-controller": "^3.0.0",
"buffer": "^6.0.3",
@ -13154,6 +13572,11 @@
"node": ">=0.10.0"
}
},
"node_modules/rfdc": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
"integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA=="
},
"node_modules/rimraf": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
@ -13717,6 +14140,15 @@
"node": ">=8"
}
},
"node_modules/stoppable": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz",
"integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==",
"engines": {
"node": ">=4",
"npm": ">=6"
}
},
"node_modules/stream-read-all": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/stream-read-all/-/stream-read-all-3.0.1.tgz",
@ -14089,6 +14521,45 @@
"node": ">=18"
}
},
"node_modules/tarn": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/tarn/-/tarn-3.0.2.tgz",
"integrity": "sha512-51LAVKUSZSVfI05vjPESNc5vwqqZpbXCsU+/+wxlOrUjk2SnFTt97v9ZgQrD4YmxYW1Px6w2KjaDitCfkvgxMQ==",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/tedious": {
"version": "18.6.1",
"resolved": "https://registry.npmjs.org/tedious/-/tedious-18.6.1.tgz",
"integrity": "sha512-9AvErXXQTd6l7TDd5EmM+nxbOGyhnmdbp/8c3pw+tjaiSXW9usME90ET/CRG1LN1Y9tPMtz/p83z4Q97B4DDpw==",
"dependencies": {
"@azure/core-auth": "^1.7.2",
"@azure/identity": "^4.2.1",
"@azure/keyvault-keys": "^4.4.0",
"@js-joda/core": "^5.6.1",
"@types/node": ">=18",
"bl": "^6.0.11",
"iconv-lite": "^0.6.3",
"js-md4": "^0.3.2",
"native-duplexpair": "^1.0.0",
"sprintf-js": "^1.1.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/tedious/node_modules/bl": {
"version": "6.0.16",
"resolved": "https://registry.npmjs.org/bl/-/bl-6.0.16.tgz",
"integrity": "sha512-V/kz+z2Mx5/6qDfRCilmrukUXcXuCoXKg3/3hDvzKKoSUx8CJKudfIoT29XZc3UE9xBvxs5qictiHdprwtteEg==",
"dependencies": {
"@types/readable-stream": "^4.0.0",
"buffer": "^6.0.3",
"inherits": "^2.0.4",
"readable-stream": "^4.2.0"
}
},
"node_modules/test-exclude": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz",

View file

@ -55,7 +55,7 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.11.0",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",

View file

@ -8,7 +8,9 @@ import type {
ContextItemWithId,
ContextSubmenuItem,
DiffLine,
FileSymbolMap,
IdeSettings,
IndexingStatusMap,
LLMFullCompletionOptions,
ModelDescription,
ModelRoles,
@ -68,6 +70,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, BrowserSerializedContinueConfig];
"config/listProfiles": [undefined, ProfileDescription[]];
"config/openProfile": [{ profileId: string | undefined }, void];
"context/getContextItems": [
{
name: string;
@ -77,6 +80,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
"context/addDocs": [SiteIndexingConfig, void];
@ -143,6 +147,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 },
@ -156,6 +162,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

@ -28,6 +28,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
showVirtualFile: [{ name: string; content: string }, void];
getContinueDir: [undefined, string];
openFile: [{ path: string }, void];
openUrl: [string, void];
runCommand: [{ command: string }, void];
getSearchResults: [{ query: string }, string];
subprocess: [{ command: string; cwd?: string }, [string, string]];
@ -49,11 +50,17 @@ export type ToIdeFromWebviewOrCoreProtocol = {
];
getProblems: [{ filepath: string }, Problem[]];
getOpenFiles: [undefined, string[]];
getCurrentFile: [undefined, undefined | {
isUntitled: boolean;
path: string;
contents: string;
}];
getCurrentFile: [
undefined,
(
| undefined
| {
isUntitled: boolean;
path: string;
contents: string;
}
),
];
getPinnedFiles: [undefined, string[]];
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
readRangeInFile: [{ filepath: string; range: Range }, string];

View file

@ -1,8 +1,14 @@
import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
import { ToIdeFromWebviewOrCoreProtocol } from "./ide";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import type { RangeInFileWithContents } from "../commands/util.js";
import type { ContextSubmenuItem, MessageContent } from "../index.js";
import type {
ApplyState,
CodeToEdit,
ContextSubmenuItem,
EditStatus,
MessageContent,
RangeInFileWithContents,
} from "../";
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
onLoad: [
@ -30,7 +36,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
@ -54,30 +59,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
"edit/escape": [undefined, void];
};
export interface EditModeArgs {
highlightedCode: RangeInFileWithContents;
}
export type EditStatus =
| "not-started"
| "streaming"
| "accepting"
| "accepting:full-diff"
| "done";
export type ApplyStateStatus =
| "streaming" // Changes are being applied to the file
| "done" // All changes have been applied, awaiting user to accept/reject
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
export interface ApplyState {
streamId: string;
status?: ApplyStateStatus;
numDiffs?: number;
filepath?: string;
fileContent?: string;
}
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
@ -98,10 +79,10 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
},
void,
];
addCodeToEdit: [CodeToEdit, void];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
openSettings: [undefined, void];
/**
* @deprecated Use navigateTo with a path instead.
*/
@ -118,7 +99,8 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
openOnboardingCard: [undefined, void];
applyCodeFromChat: [undefined, void];
updateApplyState: [ApplyState, void];
startEditMode: [EditModeArgs, void];
setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void];
exitEditMode: [undefined, void];
focusEdit: [undefined, void];
focusEditWithoutClear: [undefined, void];
};

View file

@ -21,7 +21,10 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/reload",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
@ -39,13 +42,19 @@ 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",
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
@ -56,11 +65,14 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
"setTTSActive",
"getWebviewHistoryLength",
"signInToControlPlane",
"openDialogMessage",
];

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: [
@ -18,4 +23,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
];
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
signInToControlPlane: [undefined, void];
openDialogMessage: ["account", void];
};

View file

@ -129,6 +129,10 @@ class FileSystemIde implements IDE {
return Promise.resolve("");
}
getClipboardContent(): Promise<{ text: string; copiedAt: string }> {
return Promise.resolve({ text: "", copiedAt: new Date().toISOString() });
}
getTerminalContents(): Promise<string> {
return Promise.resolve("");
}
@ -187,6 +191,10 @@ class FileSystemIde implements IDE {
return Promise.resolve();
}
openUrl(url: string): Promise<void> {
return Promise.resolve();
}
runCommand(command: string): Promise<void> {
return Promise.resolve();
}

View file

@ -28,7 +28,7 @@ export class MessageIde implements IDE {
messageType: T,
callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1],
) => void,
) { }
) {}
pathSep(): Promise<string> {
return this.request("pathSep", undefined);
@ -113,6 +113,13 @@ export class MessageIde implements IDE {
return await this.request("getDiff", { includeUnstaged });
}
async getClipboardContent(): Promise<{ text: string; copiedAt: string }> {
return {
text: "",
copiedAt: new Date().toISOString(),
};
}
async getTerminalContents() {
return await this.request("getTerminalContents", undefined);
}
@ -156,6 +163,10 @@ export class MessageIde implements IDE {
await this.request("openFile", { path });
}
async openUrl(url: string): Promise<void> {
await this.request("openUrl", url);
}
async runCommand(command: string): Promise<void> {
await this.request("runCommand", { command });
}

View file

@ -13,6 +13,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
slidingWindowSize: 500,
maxSnippetPercentage: 0.5,
maxDiffPercentage: 0.5,
maxClipboardPercentage: 0.5, // yes the percentages do not add up
useCache: true,
onlyMyCode: true,
useOtherFiles: true,

View file

@ -1,7 +1,7 @@
import * as fs from "fs";
import * as os from "os";
import { pathToFileURL } from "url";
import * as path from "path";
import * as JSONC from "comment-json";
import dotenv from "dotenv";
@ -41,6 +41,9 @@ export function getGlobalContinueIgnorePath(): string {
return continueIgnorePath;
}
/*
Deprecated, replace with getContinueGlobalUri where possible
*/
export function getContinueGlobalPath(): string {
// This is ~/.continue on mac/linux
const continuePath = CONTINUE_GLOBAL_DIR;
@ -50,6 +53,10 @@ export function getContinueGlobalPath(): string {
return continuePath;
}
export function getContinueGlobalUri(): string {
return pathToFileURL(CONTINUE_GLOBAL_DIR).href;
}
export function getSessionsFolderPath(): string {
const sessionsPath = path.join(getContinueGlobalPath(), "sessions");
if (!fs.existsSync(sessionsPath)) {
@ -94,6 +101,10 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
return p;
}
export function getConfigJsonUri(): string {
return getContinueGlobalUri() + "/config.json";
}
export function getConfigTsPath(): string {
const p = path.join(getContinueGlobalPath(), "config.ts");
if (!fs.existsSync(p)) {

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

@ -19,19 +19,19 @@ You can include the currently open file as context by pressing <kbd>cmd/ctrl</kb
## Specific file
You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#files) and selecting the file.
You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#file) and selecting the file.
## Specific folder
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folders) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
## Entire codebase
You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase-retrieval). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
## Documentation site
You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#documentation) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md).
You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#docs) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md).
## Terminal contents

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

@ -31,7 +31,10 @@ const config = {
// to replace "en" with "zh-Hans".
i18n: {
defaultLocale: "en",
locales: ["en", "zh-CN"],
locales: [
"en",
// "zh-CN"
],
},
themes: [],

View file

@ -19,19 +19,19 @@ sidebar_position: 3
## 指定文件
你可以通过输入 [`@Files`](../customize/context-providers.md#files) 并选择文件,包含当前工作区中的指定文件作为上下文。
你可以通过输入 [`@Files`](../customize/context-providers.md#file) 并选择文件,包含当前工作区中的指定文件作为上下文。
## 指定目录
你可以通过输入 [`@Folder`](../customize/context-providers.md#folders) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。
你可以通过输入 [`@Folder`](../customize/context-providers.md#folder) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。
## 整个代码库
你可以通过输入 [`@Codebase`](../customize/context-providers.md#codebase-retrieval) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。
你可以通过输入 [`@Codebase`](../customize/context-providers.md#codebase) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。
## 文档网址
你可以通过输入 [`@Docs`](../customize/context-providers.md#documentation) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。
你可以通过输入 [`@Docs`](../customize/context-providers.md#docs) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。
## 终端内容

View file

@ -9,7 +9,7 @@ sidebar_position: 4
模型的响应会直接流式地返回到侧边栏。每个响应中的代码片段将放在它自己的代码块中,每个代码块会给你一些按钮,“应用到当前文件”, “插入到光标处” 或 “复制” 。当你在会话的结尾按下 `cmd/ctrl + L` (VS Code) 或 `cmd/ctrl + J` (JetBrains) ,所有上下文会被清除,一个新的会话将会开始,让你可以开始一个新的任务。
如果你想查看聊天中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](troubleshooting.md#llm-prompt-logs) 。
如果你想查看聊天中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](../troubleshooting.md#llm-提示词日志) 。
You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md).

View file

@ -11,6 +11,6 @@ sidebar_position: 1
## 推荐的自动补全模型
如果你有使用任何模型的能力,我们推荐通过 [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) 使用 `Codestral` 。
如果你有使用任何模型的能力,我们推荐通过 [Mistral](../model-providers/top-level/mistral.md#自动补全模型) 使用 `Codestral` 。
如果你想要在本地运行模型,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#autocomplete-model) 使用 `Starcoder2-3B` 。
如果你想要在本地运行模型,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#自动补全模型) 使用 `Starcoder2-3B` 。

View file

@ -13,7 +13,7 @@ sidebar_position: 3
如果你有使用任何模型的能力,我们推荐 `voyage-code-2` ,它独立列在下面,和其他的嵌入模型选项一起。
如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#embeddings-model) 使用 `nomic-embed-text` 。
如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#嵌入模型) 使用 `nomic-embed-text` 。
### Voyage AI
@ -31,7 +31,7 @@ sidebar_position: 3
### Ollama
查看 [这个](../model-providers/top-level/ollama.md#embeddings-model) 获取如何使用 Ollama 来嵌入的指令。
查看 [这个](../model-providers/top-level/ollama.md#嵌入模型) 获取如何使用 Ollama 来嵌入的指令。
### Transformers.js (当前只有 VS Code)
@ -60,12 +60,12 @@ sidebar_position: 3
### OpenAI
查看 [这里](../model-providers/top-level/openai.md#embeddings-model) 获取如何使用 OpenAI 嵌入的指令。
查看 [这里](../model-providers/top-level/openai.md#嵌入模型) 获取如何使用 OpenAI 嵌入的指令。
### Cohere
查看 [这里](../model-providers/more/cohere.md#embeddings-model) 获取如何使用 Cohere 嵌入的指令。
查看 [这里](../model-providers/more/cohere.md#嵌入模型) 获取如何使用 Cohere 嵌入的指令。
### Gemini
查看 [这里](../model-providers/top-level/gemini.md#embeddings-model) 获取如何使用 Gemini 嵌入的指令。
查看 [这里](../model-providers/top-level/gemini.md#嵌入模型) 获取如何使用 Gemini 嵌入的指令。

View file

@ -20,4 +20,4 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config
`config.json` 可以处理大多数需要的配置,所以我们推荐在可能的情况下使用它。不过,如果你需要可编程的配置 Continue ,你可以使用 `config.ts` ,它位于 `~/.continue/config.ts` (MacOS / Linux) 或 `%USERPROFILE%\.continue\config.ts` (Windows) 。
例如,如何使用 `config.ts` ,查看 [编写定制斜杠命令](./tutorials/build-your-own-slash-command.md#custom-slash-commands) 或者 [编写定制上下文提供者](./tutorials/build-your-own-context-provider.md) 。
例如,如何使用 `config.ts` ,查看 [编写定制斜杠命令](./tutorials/build-your-own-slash-command.md#自定义斜杠命令) 或者 [编写定制上下文提供者](./tutorials/build-your-own-context-provider.md) 。

View file

@ -11,4 +11,4 @@ keywords: [编辑, cmd l, 工作]
如果你接受 diff ,我们移除之前的高亮行,如果你拒绝 diff ,我们移除建议的变更。
如果你想查看在编辑中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](troubleshooting.md#check-the-logs) 。
如果你想查看在编辑中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](../troubleshooting.md#检查日志) 。

View file

@ -13,45 +13,45 @@ import Admonition from "@theme/Admonition";
<Tabs>
<TabItem value="chat" label="聊天">
[聊天](../chat/how-to-use-it.md#how-to-use-it) 让你方便向 LLM 寻求帮助,而不需要离开 IDE
[聊天](../chat/how-to-use-it.md#如何使用它) 让你方便向 LLM 寻求帮助,而不需要离开 IDE
![chat](/img/chat.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于 [聊天](../chat/how-to-use-it.md#how-to-use-it)
了解更多关于 [聊天](../chat/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>
<TabItem value="autocomplete" label="自动补全">
[自动补全](../autocomplete/how-to-use-it.md#how-to-use-it) 随着你的输入提供行内代码建议
[自动补全](../autocomplete/how-to-use-it.md#如何使用它) 随着你的输入提供行内代码建议
![autocomplete](/img/autocomplete.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#how-to-use-it)
了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>
<TabItem value="edit" label="编辑">
[编辑](../edit/how-to-use-it.md#how-to-use-it) 是一种编辑代码的方便的方式,不需要离开你的当前文件
[编辑](../edit/how-to-use-it.md#如何使用它) 是一种编辑代码的方便的方式,不需要离开你的当前文件
![edit](/img/edit.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于 [编辑](../edit/how-to-use-it.md#how-to-use-it)
了解更多关于 [编辑](../edit/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>
<TabItem value="s" label="Actions">
[Actions](../actions/how-to-use-it.md#how-to-use-it) 是常用情况的快捷方式
[Actions](../actions/how-to-use-it.md#如何使用它) 是常用情况的快捷方式
![actions](/img/actions.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#how-to-use-it)
了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>

View file

@ -6,11 +6,11 @@ keywords: [重新加载, 删除, 手动, 日志, 服务器, 控制台]
Continue VS Code 扩展现在是 beta , JetBrains 扩展现在是 Alpha 。如果你有问题,请跟随下面的步骤。
1. [检查日志](#check-the-logs)
2. [尝试最新的预览版](#download-the-latest-pre-release)
3. [下载较老的版本](#download-an-older-version)
4. [解析快件键问题](#keyboard-shortcuts-not-resolving)
5. [检查常见问题的 FAQ](#faqs)
1. [检查日志](#检查日志)
2. [尝试最新的预览版](#下载最新的预览版)
3. [下载较老的版本](#下载一个较老的版本)
4. [解析快件键问题](#快捷键无法解析)
5. [检查常见问题的 FAQ](#常见问题)
## 检查日志
@ -128,4 +128,4 @@ Continue 可以在 [code-server](https://coder.com/) 中使用,但是如果你
## 仍然有问题?
你还可以 [在这里](https://discord.gg/vapESyrFmJ) 加入我们的 Discord 社区,获得更多的支持和讨论。另外,你可以 [在这里](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=) 创建一个 GitHub issue ,提供你的问题的详情,我们将能更快的帮助你。
你还可以 [在这里](https://discord.gg/vapESyrFmJ) 加入我们的 Discord 社区,获得更多的支持和讨论。另外,你可以 [在这里](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=) 创建一个 GitHub issue ,提供你的问题的详情,我们将能更快的帮助你。

View file

@ -129,6 +129,13 @@ class AutocompleteService(private val project: Project) {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength))
}
// Determine the index of a newline character within the text following the cursor.
val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
// If a newline character is found and the current line is not empty, truncate the text at that point.
if (newlineIndex > 0) {
textAfterCursor = textAfterCursor.substring(0, newlineIndex)
}
val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor)
if (indexOfTextAfterCursorInCompletion > 0) {
return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1)

View file

@ -192,9 +192,6 @@ class ContinueBrowser(val project: Project, url: String) {
}
"reloadWindow" -> {}
"openConfigJson" -> {
ide?.setFileOpen(getConfigJsonPath())
}
"readRangeInFile" -> {
val data = data.asJsonObject

View file

@ -2356,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.232",
"version": "0.9.233",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -205,12 +205,6 @@
"title": "Debug Terminal",
"group": "Continue"
},
{
"command": "continue.edit",
"category": "Continue",
"title": "Edit code with natural language",
"group": "Continue"
},
{
"command": "continue.exitEditMode",
"category": "Continue",
@ -225,9 +219,10 @@
"group": "Continue"
},
{
"command": "continue.openConfigJson",
"command": "continue.openConfig",
"category": "Continue",
"title": "Open config.json",
"title": "Open Continue Config",
"icon": "$(gear)",
"group": "Continue"
},
{
@ -256,12 +251,25 @@
"icon": "$(history)",
"group": "Continue"
},
{
"command": "continue.viewLogs",
"category": "Continue",
"title": "View History",
"group": "Continue"
},
{
"command": "continue.navigateTo",
"category": "Continue",
"title": "Navigate to a path",
"group": "Continue"
},
{
"command": "continue.openMorePage",
"category": "Continue",
"title": "More",
"icon": "$(ellipsis)",
"group": "Continue"
},
{
"command": "continue.writeCommentsForCode",
"category": "Continue",
@ -321,6 +329,20 @@
"category": "Continue",
"title": "Focus Continue Chat",
"group": "Continue"
},
{
"command": "continue.signInToControlPlane",
"title": "Sign In",
"category": "Continue",
"group": "Continue",
"icon": "$(account)"
},
{
"command": "continue.openAccountDialog",
"title": "Account",
"category": "Continue",
"group": "Continue",
"icon": "$(account)"
}
],
"keybindings": [
@ -375,10 +397,16 @@
"key": "alt+ctrl+n"
},
{
"command": "continue.edit",
"command": "continue.focusEdit",
"title": "Edit code with natural language",
"mac": "cmd+i",
"key": "ctrl+i"
},
{
"command": "continue.focusEditWithoutClear",
"mac": "cmd+shift+i",
"key": "ctrl+shift+i"
},
{
"command": "continue.exitEditMode",
"mac": "escape",
@ -498,6 +526,26 @@
"command": "continue.toggleFullScreen",
"group": "navigation@3",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.openConfig",
"group": "navigation@4",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.signInToControlPlane",
"group": "navigation@5",
"when": "(view == continue.continueGUIView) && config.continue.enableContinueForTeams && !continue.isSignedInToControlPlane"
},
{
"command": "continue.openAccountDialog",
"group": "navigation@5",
"when": "(view == continue.continueGUIView) && config.continue.enableContinueForTeams && continue.isSignedInToControlPlane"
},
{
"command": "continue.openMorePage",
"group": "navigation@6",
"when": "view == continue.continueGUIView"
}
],
"editor/title": [

View file

@ -168,7 +168,15 @@ export class ContinueGUIWebviewViewProvider
const currentTheme = getTheme();
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("workbench.colorTheme")) {
if (
e.affectsConfiguration("workbench.colorTheme") ||
e.affectsConfiguration("window.autoDetectColorScheme") ||
e.affectsConfiguration("window.autoDetectHighContrast") ||
e.affectsConfiguration("workbench.preferredDarkColorTheme") ||
e.affectsConfiguration("workbench.preferredLightColorTheme") ||
e.affectsConfiguration("workbench.preferredHighContrastColorTheme") ||
e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
) {
// Send new theme to GUI to update embedded Monaco themes
this.webviewProtocol?.request("setTheme", { theme: getTheme() });
}
@ -188,7 +196,7 @@ export class ContinueGUIWebviewViewProvider
</head>
<body>
<div id="root"></div>
${
inDevelopmentMode
? `<script type="module">

View file

@ -36,6 +36,7 @@ import type {
RangeInFile,
Thread,
} from "core";
import { text } from "stream/consumers";
class VsCodeIde implements IDE {
ideUtils: VsCodeIdeUtils;
@ -43,6 +44,7 @@ class VsCodeIde implements IDE {
constructor(
private readonly diffManager: DiffManager,
private readonly vscodeWebviewProtocolPromise: Promise<VsCodeWebviewProtocol>,
private readonly context: vscode.ExtensionContext,
) {
this.ideUtils = new VsCodeIdeUtils();
}
@ -314,6 +316,13 @@ class VsCodeIde implements IDE {
return await this.ideUtils.getDiff(includeUnstaged);
}
async getClipboardContent() {
return this.context.workspaceState.get("continue.copyBuffer", {
text: "",
copiedAt: new Date("1900-01-01").toISOString(),
});
}
async getTerminalContents(): Promise<string> {
return await this.ideUtils.getTerminalContents(1);
}
@ -476,6 +485,11 @@ class VsCodeIde implements IDE {
return "";
}
}
async openUrl(url: string): Promise<void> {
await vscode.env.openExternal(vscode.Uri.parse(url));
}
async showDiff(
filepath: string,
newContents: string,

View file

@ -2,7 +2,6 @@ import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"
import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo";
import { AutocompleteSnippet } from "core/autocomplete/context/ranking";
import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast";
import { RangeInFileWithContents } from "core/commands/util";
import {
FUNCTION_BLOCK_NODE_TYPES,
FUNCTION_DECLARATION_NODE_TYPEs,
@ -10,7 +9,7 @@ import {
import { intersection } from "core/util/ranges";
import * as vscode from "vscode";
import type { IDE, Range, RangeInFile } from "core";
import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core";
import type Parser from "web-tree-sitter";
type GotoProviderName =
@ -134,7 +133,9 @@ async function crawlTypes(
// Parse AST
const ast = await getAst(rif.filepath, contents);
if (!ast) {return results;}
if (!ast) {
return results;
}
const astLineCount = ast.rootNode.text.split("\n").length;
// Find type identifiers
@ -343,10 +344,14 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async (
): Promise<AutocompleteSnippet[]> => {
try {
const ast = await getAst(filepath, contents);
if (!ast) {return [];}
if (!ast) {
return [];
}
const treePath = await getTreePathAtCursor(ast, cursorIndex);
if (!treePath) {return [];}
if (!treePath) {
return [];
}
const results: RangeInFileWithContents[] = [];
for (const node of treePath.reverse()) {

View file

@ -1,6 +1,6 @@
import { RangeInFileWithContents } from "core";
import { getSymbolsForSnippet } from "core/autocomplete/context/ranking";
import { RecentlyEditedRange } from "core/autocomplete/util/types";
import { RangeInFileWithContents } from "core/commands/util";
import * as vscode from "vscode";
type VsCodeRecentlyEditedRange = {

View file

@ -3,9 +3,8 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { ContextMenuConfig } from "core";
import { ContextMenuConfig, RangeInFileWithContents } from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { RangeInFileWithContents } from "core/commands/util";
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
import { ContinueServerClient } from "core/continueServer/stubs/client";
@ -138,7 +137,6 @@ async function addHighlightedCodeToContext(
async function addEntireFileToContext(
filepath: vscode.Uri,
edit: boolean,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
@ -149,7 +147,6 @@ async function addEntireFileToContext(
if (type === vscode.FileType.File) {
addEntireFileToContext(
vscode.Uri.joinPath(filepath, filename),
edit,
webviewProtocol,
);
}
@ -203,8 +200,60 @@ function hideGUI() {
}
}
async function processDiff(
action: "accept" | "reject",
sidebar: ContinueGUIWebviewViewProvider,
diffManager: DiffManager,
ide: VsCodeIde,
verticalDiffManager: VerticalDiffManager,
newFilepath?: string | vscode.Uri,
streamId?: string,
) {
captureCommandTelemetry(`${action}Diff`);
let fullPath = newFilepath;
if (fullPath instanceof vscode.Uri) {
fullPath = fullPath.fsPath;
} else if (fullPath) {
fullPath = getFullyQualifiedPath(ide, fullPath);
} else {
console.warn(`Unable to resolve filepath: ${newFilepath}`);
}
if (!fullPath) return;
await ide.openFile(fullPath);
// Clear vertical diffs depending on action
verticalDiffManager.clearForFilepath(fullPath, action === "accept");
// Accept or reject the diff
if (action === "accept") {
await diffManager.acceptDiff(fullPath);
} else {
await diffManager.rejectDiff(fullPath);
}
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId) {
const fileContent = await ide.readFile(fullPath);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: fullPath,
streamId,
status: "closed",
numDiffs: 0,
});
}
}
// Copy everything over from extension.ts
const commandsMap: (
const getCommandsMap: (
ide: VsCodeIde,
extensionContext: vscode.ExtensionContext,
sidebar: ContinueGUIWebviewViewProvider,
@ -269,77 +318,34 @@ const commandsMap: (
range,
);
}
return {
"continue.acceptDiff": async (
newFilepath?: string | vscode.Uri,
streamId?: string,
) => {
captureCommandTelemetry("acceptDiff");
) =>
processDiff(
"accept",
sidebar,
diffManager,
ide,
verticalDiffManager,
newFilepath,
streamId,
),
let fullPath = newFilepath;
if (fullPath instanceof vscode.Uri) {
fullPath = fullPath.fsPath;
} else if (fullPath) {
fullPath = getFullyQualifiedPath(ide, fullPath);
} else {
console.warn(`Unable to resolve filepath: ${newFilepath}`);
}
verticalDiffManager.clearForFilepath(fullPath, true);
await diffManager.acceptDiff(fullPath);
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId && fullPath) {
const fileContent = await ide.readFile(fullPath);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: fullPath,
streamId: streamId,
status: "closed",
numDiffs: 0,
});
}
},
"continue.rejectDiff": async (
newFilepath?: string | vscode.Uri,
streamId?: string,
) => {
captureCommandTelemetry("rejectDiff");
let fullPath = newFilepath;
if (fullPath instanceof vscode.Uri) {
fullPath = fullPath.fsPath;
} else if (fullPath) {
fullPath = getFullyQualifiedPath(ide, fullPath);
} else {
console.warn(`Unable to resolve filepath: ${newFilepath}`);
}
verticalDiffManager.clearForFilepath(fullPath, false);
await diffManager.rejectDiff(fullPath);
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId && fullPath) {
const fileContent = await ide.readFile(fullPath);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: fullPath,
streamId: streamId,
status: "closed",
numDiffs: 0,
});
}
},
) =>
processDiff(
"reject",
sidebar,
diffManager,
ide,
verticalDiffManager,
newFilepath,
streamId,
),
"continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => {
captureCommandTelemetry("acceptVerticalDiffBlock");
verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index);
@ -455,42 +461,96 @@ const commandsMap: (
void addHighlightedCodeToContext(sidebar.webviewProtocol);
}
},
"continue.edit": async () => {
captureCommandTelemetry("edit");
"continue.focusEdit": async () => {
captureCommandTelemetry("focusEdit");
focusGUI();
sidebar.webviewProtocol?.request("focusEdit", undefined);
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const existingDiff = await verticalDiffManager.getHandlerForFile(
const existingDiff = verticalDiffManager.getHandlerForFile(
editor.document.fileName,
);
if (!existingDiff) {
// If there's a diff currently being applied, then we just toggle focus back to the input
editDecorationManager.setDecoration(
editor,
new vscode.Range(editor.selection.start, editor.selection.end),
);
const highlightedCode = getCurrentlyHighlightedCode(true)!;
await sidebar.webviewProtocol?.request("startEditMode", {
highlightedCode,
});
// If there's a diff currently being applied, then we just toggle focus back to the input
if (existingDiff) {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
return;
}
editDecorationManager.setDecoration(
editor,
new vscode.Range(editor.selection.start, editor.selection.end),
);
const rangeInFileWithContents = getCurrentlyHighlightedCode(true);
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addCodeToEdit",
rangeInFileWithContents,
);
// Un-select the current selection
editor.selection = new vscode.Selection(
editor.selection.anchor,
editor.selection.anchor,
);
setTimeout(() => {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
}, 30);
} else {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
}
setTimeout(() => {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
}, 30);
},
"continue.focusEditWithoutClear": async () => {
captureCommandTelemetry("focusEditWithoutClear");
focusGUI();
sidebar.webviewProtocol?.request("focusEditWithoutClear", undefined);
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const document = editor.document;
const existingDiff = verticalDiffManager.getHandlerForFile(
document.fileName,
);
// If there's a diff currently being applied, then we just toggle focus back to the input
if (existingDiff) {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
return;
}
const rangeInFileWithContents = getCurrentlyHighlightedCode(false);
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addCodeToEdit",
rangeInFileWithContents,
);
} else {
const filepath = document.uri.fsPath;
const contents = document.getText();
sidebar.webviewProtocol?.request("addCodeToEdit", {
filepath,
contents,
});
}
setTimeout(() => {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
}, 30);
},
"continue.exitEditMode": async () => {
captureCommandTelemetry("exitEditMode");
@ -580,10 +640,6 @@ const commandsMap: (
vscode.commands.executeCommand("continue.continueGUIView.focus");
sidebar.webviewProtocol?.request("addModel", undefined);
},
"continue.openSettingsUI": () => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
sidebar.webviewProtocol?.request("openSettings", undefined);
},
"continue.sendMainUserInput": (text: string) => {
sidebar.webviewProtocol?.request("userInput", {
input: text,
@ -683,8 +739,10 @@ const commandsMap: (
vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow");
},
"continue.openConfigJson": () => {
ide.openFile(getConfigJsonPath());
"continue.openConfig": () => {
core.invoke("config/openProfile", {
profileId: undefined,
});
},
"continue.selectFilesAsContext": async (
firstUri: vscode.Uri,
@ -705,12 +763,11 @@ const commandsMap: (
for await (const filepath of walkDirAsync(uri.fsPath, ide)) {
addEntireFileToContext(
uriFromFilePath(filepath),
false,
sidebar.webviewProtocol,
);
}
} else {
addEntireFileToContext(uri, false, sidebar.webviewProtocol);
addEntireFileToContext(uri, sidebar.webviewProtocol);
}
}
},
@ -857,7 +914,7 @@ const commandsMap: (
vscode.commands.executeCommand("continue.toggleFullScreen");
} else if (selectedOption === "$(question) Open help center") {
focusGUI();
vscode.commands.executeCommand("continue.navigateTo", "/more");
vscode.commands.executeCommand("continue.navigateTo", "/more", true);
}
quickPick.dispose();
});
@ -877,13 +934,51 @@ const commandsMap: (
client.sendFeedback(feedback, lastLines);
}
},
"continue.navigateTo": (path: string) => {
sidebar.webviewProtocol?.request("navigateTo", { path });
"continue.openMorePage": () => {
vscode.commands.executeCommand("continue.navigateTo", "/more", true);
},
"continue.navigateTo": (path: string, toggle: boolean) => {
sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
focusGUI();
},
"continue.signInToControlPlane": () => {
sidebar.webviewProtocol?.request("signInToControlPlane", undefined);
},
"continue.openAccountDialog": () => {
sidebar.webviewProtocol?.request("openDialogMessage", "account");
},
};
};
const registerCopyBufferSpy = (context: vscode.ExtensionContext) => {
const typeDisposable = vscode.commands.registerCommand(
"editor.action.clipboardCopyAction",
async (arg) => doCopy(typeDisposable),
);
async function doCopy(typeDisposable: any) {
typeDisposable.dispose(); // must dispose to avoid endless loops
await vscode.commands.executeCommand("editor.action.clipboardCopyAction");
const clipboardText = await vscode.env.clipboard.readText();
await context.workspaceState.update("continue.copyBuffer", {
text: clipboardText,
copiedAt: new Date().toISOString(),
});
// re-register to continue intercepting copy commands
typeDisposable = vscode.commands.registerCommand(
"editor.action.clipboardCopyAction",
async () => doCopy(typeDisposable),
);
context.subscriptions.push(typeDisposable);
}
context.subscriptions.push(typeDisposable);
};
export function registerAllCommands(
context: vscode.ExtensionContext,
ide: VsCodeIde,
@ -898,8 +993,10 @@ export function registerAllCommands(
core: Core,
editDecorationManager: EditDecorationManager,
) {
registerCopyBufferSpy(context);
for (const [command, callback] of Object.entries(
commandsMap(
getCommandsMap(
ide,
extensionContext,
sidebar,

View file

@ -1,4 +1,3 @@
import { ApplyState } from "core/protocol/ideWebview";
import * as vscode from "vscode";
import {
@ -10,7 +9,7 @@ import {
} from "./decorations";
import type { VerticalDiffCodeLens } from "./manager";
import type { DiffLine } from "core";
import type { ApplyState, DiffLine } from "core";
export interface VerticalDiffHandlerOptions {
input?: string;

View file

@ -73,7 +73,11 @@ export class VsCodeExtension {
},
);
this.diffManager = new DiffManager(context);
this.ide = new VsCodeIde(this.diffManager, this.webviewProtocolPromise);
this.ide = new VsCodeIde(
this.diffManager,
this.webviewProtocolPromise,
context,
);
this.extensionContext = context;
this.windowId = uuidv4();
@ -317,9 +321,13 @@ export class VsCodeExtension {
// When GitHub sign-in status changes, reload config
vscode.authentication.onDidChangeSessions(async (e) => {
if (e.provider.id === "github") {
this.configHandler.reloadConfig();
} else if (e.provider.id === controlPlaneEnv.AUTH_TYPE) {
if (e.provider.id === controlPlaneEnv.AUTH_TYPE) {
vscode.commands.executeCommand(
"setContext",
"continue.isSignedInToControlPlane",
true,
);
const sessionInfo = await getControlPlaneSessionInfo(true);
this.webviewProtocolPromise.then(async (webviewProtocol) => {
void webviewProtocol.request("didChangeControlPlaneSessionInfo", {
@ -329,7 +337,19 @@ export class VsCodeExtension {
// To make sure continue-proxy models and anything else requiring it get updated access token
this.configHandler.reloadConfig();
});
void this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo });
void this.core.invoke("didChangeControlPlaneSessionInfo", {
sessionInfo,
});
} else {
vscode.commands.executeCommand(
"setContext",
"continue.isSignedInToControlPlane",
false,
);
if (e.provider.id === "github") {
this.configHandler.reloadConfig();
}
}
});

View file

@ -18,7 +18,6 @@ import {
} from "core/protocol/passThrough";
import { getBasename } from "core/util";
import { InProcessMessenger, Message } from "core/util/messenger";
import { getConfigJsonPath } from "core/util/paths";
import * as vscode from "vscode";
import { stripImages } from "core/util/messageContent";
@ -108,10 +107,6 @@ export class VsCodeMessenger {
);
});
this.onWebview("openConfigJson", (msg) => {
this.ide.openFile(getConfigJsonPath());
});
this.onWebview("readRangeInFile", async (msg) => {
return await vscode.workspace
.openTextDocument(msg.data.filepath)
@ -255,7 +250,9 @@ export class VsCodeMessenger {
llm,
fastLlm,
);
const verticalDiffManager = await this.verticalDiffManagerPromise;
if (instant) {
await verticalDiffManager.streamDiffLines(
diffLines,

View file

@ -35,7 +35,7 @@ export class ConfigPyCodeLensProvider implements vscode.CodeLensProvider {
codeLenses.push(
new vscode.CodeLens(range, {
title: "✏️ Edit in UI",
command: "continue.openSettingsUI",
command: "continue.openConfigUI", // command likely doesn't exist anymore, check
}),
);
}

View file

@ -132,7 +132,9 @@ export function registerAllCodeLensProviders(
context.subscriptions.push(verticalPerLineCodeLensProvider);
context.subscriptions.push(suggestionsCodeLensDisposable);
context.subscriptions.push(diffsCodeLensDisposable);
context.subscriptions.push(configPyCodeLensDisposable);
// was opening config UI from config.json. Not currently applicable.
// context.subscriptions.push(configPyCodeLensDisposable);
return { verticalDiffCodeLens };
}

View file

@ -36,9 +36,55 @@ function parseThemeString(themeString: string | undefined): any {
export function getTheme() {
let currentTheme = undefined;
const colorTheme =
vscode.workspace.getConfiguration("workbench").get<string>("colorTheme") ||
"Default Dark Modern";
// Get color theme from settings
// use user settings if available
// otherwise use default
let colorTheme: string | undefined = undefined;
// Get color theme from settings
const workbenchConfig = vscode.workspace.getConfiguration();
const autoDetectColorScheme = workbenchConfig.get<boolean>(
"window.autoDetectColorScheme",
);
const autoDetectHighContrast = workbenchConfig.get<boolean>(
"window.autoDetectHighContrast",
);
const activeColorTheme = vscode.window.activeColorTheme.kind;
if (autoDetectHighContrast || autoDetectColorScheme) {
switch (activeColorTheme) {
case vscode.ColorThemeKind.Dark:
colorTheme = workbenchConfig.get<string>(
"workbench.preferredDarkColorTheme",
);
break;
case vscode.ColorThemeKind.Light:
colorTheme = workbenchConfig.get<string>(
"workbench.preferredLightColorTheme",
);
break;
case vscode.ColorThemeKind.HighContrast:
colorTheme = workbenchConfig.get<string>(
"workbench.preferredHighContrastColorTheme",
);
break;
case vscode.ColorThemeKind.HighContrastLight:
colorTheme = workbenchConfig.get<string>(
"workbench.preferredHighContrastLightColorTheme",
);
break;
default:
console.log("unknown color theme kind", activeColorTheme);
colorTheme = workbenchConfig.get<string>("workbench.colorTheme");
break;
}
}
if (!colorTheme) {
colorTheme =
workbenchConfig.get<string>("workbench.colorTheme") ??
"Default Dark Modern";
}
try {
// Pass color theme to webview for syntax highlighting
@ -85,7 +131,8 @@ export function getTheme() {
converted.base = (
["vs", "hc-black"].includes(converted.base)
? converted.base
: colorTheme.includes("Light")
: activeColorTheme === vscode.ColorThemeKind.Light ||
activeColorTheme === vscode.ColorThemeKind.HighContrastLight
? "vs"
: "vs-dark"
) as any;

6
gui/package-lock.json generated
View file

@ -56,6 +56,7 @@
"socket.io-client": "^4.7.2",
"styled-components": "^5.3.6",
"table": "^6.8.1",
"tailwind-scrollbar-hide": "^1.1.7",
"tippy.js": "^6.3.7",
"unist-util-visit": "^5.0.0",
"uuid": "^9.0.1",
@ -8984,6 +8985,11 @@
"node": ">=10.0.0"
}
},
"node_modules/tailwind-scrollbar-hide": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/tailwind-scrollbar-hide/-/tailwind-scrollbar-hide-1.1.7.tgz",
"integrity": "sha512-X324n9OtpTmOMqEgDUEA/RgLrNfBF/jwJdctaPZDzB3mppxJk7TLIDmOreEDm1Bq4R9LSPu4Epf8VSdovNU+iA=="
},
"node_modules/tailwindcss": {
"version": "3.4.12",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz",

View file

@ -8,7 +8,7 @@ import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders";
import { useVscTheme } from "./hooks/useVscTheme";
import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel";
import ConfigErrorPage from "./pages/config-error";
import Edit from "./pages/edit";
import Edit from "./pages/Edit";
import ErrorPage from "./pages/error";
import Chat from "./pages/gui";
import History from "./pages/history";

View file

@ -0,0 +1,155 @@
import { Listbox, Transition } from "@headlessui/react";
import { ChevronUpDownIcon } from "@heroicons/react/24/outline";
import { Fragment, useContext } from "react";
import styled from "styled-components";
import {
Button,
SecondaryButton,
vscInputBackground,
vscInputBorder,
vscListActiveBackground,
vscListActiveForeground,
} from ".";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAuth } from "../context/Auth";
import { setSelectedProfileId } from "../redux/slices/stateSlice";
import { useDispatch } from "react-redux";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import { NewSessionButton } from "./mainInput/NewSessionButton";
const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>`
background-color: ${({ selected }) =>
selected ? vscListActiveBackground : vscInputBackground};
cursor: pointer;
padding: 6px 8px;
&:hover {
background-color: ${vscListActiveBackground};
color: ${vscListActiveForeground};
}
`;
function AccountDialog() {
const ideMessenger = useContext(IdeMessengerContext);
const {
session,
logout,
login,
profiles,
selectedProfile,
controlServerBetaEnabled,
} = useAuth();
// These shouldn't usually show but just to be safe
if (!session?.account?.id) {
return (
<div className="p-4">
<h1>Account</h1>
<p>Not signed in</p>
<Button onClick={login}>Login</Button>
</div>
);
}
if (!controlServerBetaEnabled) {
return (
<div className="p-4">
<h1>Account</h1>
<p>
Continue for teams is not enabled. You can enable it in your IDE
settings
</p>
<p>Using local config.</p>
<Button>Close</Button>
</div>
);
}
const dispatch = useDispatch();
const changeProfileId = (id: string) => {
ideMessenger.post("didChangeSelectedProfile", { id });
dispatch(setSelectedProfileId(id));
};
return (
<div className="p-4">
<h1>Account</h1>
<p className="">Select a workspace</p>
<Listbox value={"local"} onChange={changeProfileId}>
{({ open }) => (
<div className="relative">
<Listbox.Button
className="bg-vsc-background hover:bg-vsc-input-background text-vsc-foreground xs:w-[170px] relative m-0 flex w-[130px] cursor-pointer items-center justify-between rounded-md px-3 py-2 text-left sm:w-[220px]"
style={{
borderTop: `1px solid ${vscInputBorder}`,
borderLeft: `1px solid ${vscInputBorder}`,
borderRight: `1px solid ${vscInputBorder}`,
borderBottom: `1px solid ${vscInputBorder}`,
}}
>
<span className="lines lines-1">{selectedProfile?.title}</span>
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon className="h-5 w-5" aria-hidden="true" />
</div>
</Listbox.Button>
<Transition
as={Fragment}
show={open}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Listbox.Options className="bg-vsc-background max-h-80vh xs:w-[170px] absolute w-[130px] overflow-y-scroll rounded-sm p-0 sm:w-[220px]">
{profiles.map((option, idx) => (
<StyledListboxOption
key={idx}
selected={selectedProfile.id === option.id}
value={option.id}
className="w-full"
>
<div className="lines lines-1 relative flex h-5 items-center justify-between gap-3 pr-2">
{option.title}
</div>
</StyledListboxOption>
))}
{profiles.length === 0 ? (
<div className="px-4 py-2">
<i>No workspaces found</i>
</div>
) : null}
</Listbox.Options>
</Transition>
</div>
)}
</Listbox>
<p className="mt-6">
{session.account.label === ""
? "Signed in"
: `Signed in as ${session.account.label}`}
</p>
<NewSessionButton className="border border-solid" onClick={logout}>
Sign out
</NewSessionButton>
<div className="mt-3 flex flex-row">
<Button
className="basis-1/4"
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
}}
>
Done
</Button>
</div>
</div>
);
}
export default AccountDialog;

View file

@ -10,7 +10,11 @@ function AddModelButtonSubtext() {
This will update your{" "}
<span
className="cursor-pointer underline"
onClick={() => ideMessenger.post("openConfigJson", undefined)}
onClick={() =>
ideMessenger.post("config/openProfile", {
profileId: "local",
})
}
>
config file
</span>

View file

@ -1,15 +1,12 @@
import DOMPurify from "dompurify";
import { themeIcons } from "seti-file-icons";
const FileIcon = ({
filename,
height,
width,
}: {
export interface FileIconProps {
filename: string;
height: string;
width: string;
}) => {
}
export default function FileIcon({ filename, height, width }: FileIconProps) {
const filenameParts = filename.includes(" (")
? filename.split(" ")
: [filename, ""];
@ -39,6 +36,4 @@ const FileIcon = ({
style={{ width: width, height: height, fill: color, flexShrink: 0 }}
/>
);
};
export default FileIcon;
}

View file

@ -1,92 +1,22 @@
import {
Cog6ToothIcon,
EllipsisHorizontalCircleIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import { RootState } from "../redux/store";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip";
import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar";
import ProfileSwitcher from "./ProfileSwitcher";
function Footer() {
const navigate = useNavigate();
const { pathname } = useLocation();
const defaultModel = useSelector(defaultModelSelector);
const ideMessenger = useContext(IdeMessengerContext);
const selectedProfileId = useSelector(
(store: RootState) => store.state.selectedProfileId,
);
const configError = useSelector(
(store: RootState) => store.state.configError,
);
function onClickMore() {
navigate(pathname === ROUTES.MORE ? "/" : ROUTES.MORE);
if (defaultModel?.provider === "free-trial") {
return (
<footer className="flex flex-col border-0 border-t border-solid border-t-zinc-700 px-2 py-2">
<FreeTrialProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={FREE_TRIAL_LIMIT_REQUESTS}
/>
</footer>
);
}
function onClickError() {
navigate(pathname === ROUTES.CONFIG_ERROR ? "/" : ROUTES.CONFIG_ERROR);
}
function onClickSettings() {
if (selectedProfileId === "local") {
ideMessenger.post("openConfigJson", undefined);
} else {
ideMessenger.post(
"openUrl",
`http://app.continue.dev/workspaces/${selectedProfileId}/chat`,
);
}
}
return (
<footer className="flex h-7 items-center justify-between overflow-hidden border-0 border-t border-solid border-t-zinc-700 p-2">
<div className="flex max-w-[40vw] gap-2">
<ProfileSwitcher />
{defaultModel?.provider === "free-trial" && (
<FreeTrialProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={FREE_TRIAL_LIMIT_REQUESTS}
/>
)}
</div>
<div className="flex gap-1">
{configError && (
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="Config error"
onClick={onClickError}
>
<ExclamationTriangleIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
)}
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="More"
onClick={onClickMore}
>
<EllipsisHorizontalCircleIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
onClick={onClickSettings}
text="Configure Continue"
>
<Cog6ToothIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
</div>
</footer>
);
return null;
}
export default Footer;

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

@ -129,18 +129,26 @@ export function History() {
return (
<Fragment key={index}>
{index === 0 && date > yesterday && (
<tr className={HEADER_CLASS}>Today</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>Today</td>
</tr>
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
<tr className={HEADER_CLASS}>This Week</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>This Week</td>
</tr>
)}
{date < lastWeek && date > lastMonth && prevDate > lastWeek && (
<tr className={HEADER_CLASS}>This Month</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>This Month</td>
</tr>
)}
{date < lastMonth && prevDate > lastMonth && (
<tr className={HEADER_CLASS}>Older</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>Older</td>
</tr>
)}
<HistoryTableRow

View file

@ -10,9 +10,11 @@ import { useConfigError } from "../redux/hooks";
import {
setEditDone,
setEditStatus,
startEditMode,
addCodeToEdit,
focusEdit,
clearCodeToEdit,
} from "../redux/slices/editModeState";
import { setShowDialog } from "../redux/slices/uiStateSlice";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import {
updateApplyState,
updateCurCheckpoint,
@ -25,6 +27,8 @@ import TextDialog from "./dialogs";
import Footer from "./Footer";
import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard";
import PostHogPageView from "./PosthogPageView";
import AccountDialog from "./AccountDialog";
import { AuthProvider } from "../context/Auth";
const LayoutTopDiv = styled(CustomScrollbarDiv)`
height: 100%;
@ -50,22 +54,6 @@ const GridDiv = styled.div`
overflow-x: visible;
`;
const ModelDropdownPortalDiv = styled.div`
background-color: ${vscInputBackground};
position: relative;
margin-left: 8px;
z-index: 200;
font-size: ${getFontSize()};
`;
const ProfileDropdownPortalDiv = styled.div`
background-color: ${vscInputBackground};
position: relative;
margin-left: 8px;
z-index: 200;
font-size: ${getFontSize() - 2};
`;
const Layout = () => {
const navigate = useNavigate();
const location = useLocation();
@ -109,6 +97,17 @@ const Layout = () => {
};
}, [timeline]);
useWebviewListener(
"openDialogMessage",
async (message) => {
if (message === "account") {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AccountDialog />));
}
},
[],
);
useWebviewListener(
"addModel",
async () => {
@ -117,10 +116,6 @@ const Layout = () => {
[navigate],
);
useWebviewListener("openSettings", async () => {
ideMessenger.post("openConfigJson", undefined);
});
useWebviewListener(
"viewHistory",
async () => {
@ -190,14 +185,32 @@ const Layout = () => {
);
useWebviewListener(
"startEditMode",
async (args) => {
dispatch(startEditMode(args));
"focusEdit",
async () => {
dispatch(focusEdit());
dispatch(clearCodeToEdit());
navigate("/edit");
},
[navigate],
);
useWebviewListener(
"focusEditWithoutClear",
async () => {
dispatch(focusEdit());
navigate("/edit");
},
[navigate],
);
useWebviewListener(
"addCodeToEdit",
async (payload) => {
dispatch(addCodeToEdit(payload));
},
[navigate],
);
useWebviewListener("setEditStatus", async ({ status, fileAfterEdit }) => {
dispatch(setEditStatus({ status, fileAfterEdit }));
});
@ -217,56 +230,55 @@ const Layout = () => {
}, [location]);
return (
<LastSessionProvider>
<LayoutTopDiv>
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
<AuthProvider>
<LastSessionProvider>
<LayoutTopDiv>
<div
style={{
scrollbarGutter: "stable both-edges",
minHeight: "100%",
display: "grid",
gridTemplateRows: "1fr auto",
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
>
<TextDialog
showDialog={showDialog}
onEnter={() => {
dispatch(setShowDialog(false));
}}
onClose={() => {
dispatch(setShowDialog(false));
}}
message={dialogMessage}
/>
<GridDiv className="">
<PostHogPageView />
<Outlet />
{hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && (
<div
className="z-50 cursor-pointer bg-red-600 p-4 text-center text-white"
role="alert"
onClick={() => navigate(ROUTES.CONFIG_ERROR)}
>
<strong className="font-bold">Error!</strong>{" "}
<span className="block sm:inline">
Could not load config.json
</span>
<div className="mt-2 underline">Learn More</div>
</div>
)}
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
<GridDiv className="">
<PostHogPageView />
<Outlet />
{hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && (
<div
className="z-50 cursor-pointer bg-red-600 p-4 text-center text-white"
role="alert"
onClick={() => navigate(ROUTES.CONFIG_ERROR)}
>
<strong className="font-bold">Error!</strong>{" "}
<span className="block sm:inline">
Could not load config.json
</span>
<div className="mt-2 underline">Learn More</div>
</div>
)}
<ModelDropdownPortalDiv id="model-select-top-div"></ModelDropdownPortalDiv>
<ProfileDropdownPortalDiv id="profile-select-top-div"></ProfileDropdownPortalDiv>
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
</LayoutTopDiv>
</LastSessionProvider>
</LayoutTopDiv>
</LastSessionProvider>
</AuthProvider>
);
};

View file

@ -18,8 +18,8 @@ import {
vscListActiveBackground,
vscListActiveForeground,
} from ".";
import { useAuth } from "../context/Auth";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAuth } from "../hooks/useAuth";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice";
import { RootState } from "../redux/store";

View file

@ -1,17 +1,22 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core/protocol/ideWebview";
import { ApplyState } from "core";
export interface AcceptRejectAllButtonsProps {
pendingApplyStates: ApplyState[];
onAcceptOrReject?: () => void;
}
export default function AcceptRejectAllButtons({
pendingApplyStates,
onAcceptOrReject,
}: AcceptRejectAllButtonsProps) {
const ideMessenger = useContext(IdeMessengerContext);
// To handle the case of a single-range edit
const hasSinglePendingApplyStates = pendingApplyStates.length === 1;
async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") {
for (const { filepath, streamId } of pendingApplyStates) {
ideMessenger.post(status, {
@ -19,8 +24,11 @@ export default function AcceptRejectAllButtons({
streamId,
});
}
}
if (onAcceptOrReject) {
onAcceptOrReject();
}
}
return (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button
@ -28,18 +36,30 @@ export default function AcceptRejectAllButtons({
onClick={() => handleAcceptOrReject("rejectDiff")}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-600" />
<span className="sm:hidden">Reject</span>
<span className="max-sm:hidden md:hidden">Reject all</span>
<span className="max-md:hidden">Reject all changes</span>
{hasSinglePendingApplyStates ? (
<span>Reject</span>
) : (
<>
<span className="sm:hidden">Reject</span>
<span className="max-sm:hidden md:hidden">Reject all</span>
<span className="max-md:hidden">Reject all changes</span>
</>
)}
</button>
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("acceptDiff")}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-600" />
<span className="sm:hidden">Accept</span>
<span className="max-sm:hidden md:hidden">Accept all</span>
<span className="max-md:hidden">Accept all changes</span>
{hasSinglePendingApplyStates ? (
<span>Accept</span>
) : (
<>
<span className="sm:hidden">Accept</span>
<span className="max-sm:hidden md:hidden">Accept all</span>
<span className="max-md:hidden">Accept all changes</span>
</>
)}
</button>
</div>
);

View file

@ -8,18 +8,17 @@ import UndoAndRedoButtons from "./UndoAndRedoButtons";
import { renderChatMessage } from "core/util/messageContent";
import { CopyIconButton } from "../gui/CopyIconButton";
export interface MultifileEditActionsProps {
export interface EditActionsProps {
index: number;
item: ChatHistoryItem;
}
export default function MultifileEditActions({
index,
item,
}: MultifileEditActionsProps) {
const curCheckpointIndex = useSelector(
(store: RootState) => store.state.curCheckpointIndex,
);
export default function EditActions({ index, item }: EditActionsProps) {
// const curCheckpointIndex = useSelector(
// (store: RootState) => store.state.curCheckpointIndex,
// );
const active = useSelector((state: RootState) => state.state.active);
const applyStates = useSelector(
(state: RootState) => state.state.applyStates,
@ -33,23 +32,32 @@ export default function MultifileEditActions({
(state) => state.status === "closed",
);
const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex;
// const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex;
const hasPendingApplies = pendingApplyStates.length > 0;
if (active) return;
return (
<div
className={`mx-2 mb-2 mt-2 flex h-7 items-center justify-between pb-0 text-xs text-gray-400`}
>
<div className="flex-1" />
{isCurCheckpoint && (
{/* {isCurCheckpoint && (
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons pendingApplyStates={pendingApplyStates} />
)}
{hasClosedAllStreams && <UndoAndRedoButtons />}
</div>
)}
)} */}
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons pendingApplyStates={pendingApplyStates} />
)}
{/* {hasClosedAllStreams && <UndoAndRedoButtons />} */}
</div>
<div className="flex flex-1 justify-end">
<CopyIconButton

View file

@ -6,7 +6,7 @@ import { RootState } from "../../redux/store";
import { CopyIconButton } from "../gui/CopyIconButton";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import FeedbackButtons from "./FeedbackButtons";
import MultifileEditActions from "./MultifileEditActions";
import EditActions from "./EditActions";
export interface ResponseActionsProps {
isTruncated: boolean;
@ -23,15 +23,15 @@ export default function ResponseActions({
isTruncated,
onDelete,
}: ResponseActionsProps) {
const isInMultifileEdit = useSelector(
(store: RootState) => store.state.isMultifileEdit,
const isInEditMode = useSelector(
(store: RootState) => store.editModeState.isInEditMode,
);
// Only render delete button if there is more than one message
const shouldRenderDelete = index !== 1;
if (isInMultifileEdit) {
return <MultifileEditActions index={index} item={item} />;
if (isInEditMode) {
return <EditActions index={index} item={item} />;
}
return (

View file

@ -1,5 +1,5 @@
import { ChatHistoryItem } from "core";
import { renderChatMessage } from "core/util/messageContent";
import { renderChatMessage, stripImages } from "core/util/messageContent";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
@ -32,13 +32,13 @@ export default function StepContainer(props: StepContainerProps) {
const curCheckpointIndex = useSelector(
(store: RootState) => store.state.curCheckpointIndex,
);
const isMultifileEdit = useSelector(
(store: RootState) => store.state.isMultifileEdit,
const isInEditMode = useSelector(
(store: RootState) => store.editModeState.isInEditMode,
);
const uiConfig = useUIConfig();
const shouldHideActions = active && props.isLast;
const isStepAheadOfCurCheckpoint =
isMultifileEdit && Math.floor(props.index / 2) > curCheckpointIndex;
// const isStepAheadOfCurCheckpoint =
// isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex;
useEffect(() => {
if (!active) {
@ -77,7 +77,7 @@ export default function StepContainer(props: StepContainerProps) {
return (
<div
className={isStepAheadOfCurCheckpoint ? "opacity-25" : "relative"}
// className={isStepAheadOfCurCheckpoint ? "opacity-25" : "relative"}
style={{
minHeight: props.isLast ? "50vh" : 0,
}}
@ -93,7 +93,8 @@ export default function StepContainer(props: StepContainerProps) {
) : (
<StyledMarkdownPreview
isRenderingInStepContainer
source={renderChatMessage(props.item.message)}
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

@ -43,9 +43,9 @@ function ConfirmationDialog(props: ConfirmationDialogProps) {
<SecondaryButton
style={{ color: lightGray }}
onClick={() => {
props.onCancel?.();
dispatch(setShowDialog(false));
dispatch(setDialogMessage(undefined));
props.onCancel?.();
}}
>
Cancel

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

@ -1,12 +1,11 @@
import { Tooltip } from "react-tooltip";
import { vscInputBackground, vscBadgeBackground, vscForeground } from "..";
import { vscInputBackground, vscForeground } from "..";
import { getFontSize } from "../../util";
import ReactDOM from "react-dom";
const TooltipStyles = {
fontSize: `${getFontSize() - 2}px`,
backgroundColor: vscInputBackground,
boxShadow: `0px 0px 2px 1px ${vscBadgeBackground}`,
color: vscForeground,
padding: "4px 8px",
zIndex: 1000,

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

@ -37,7 +37,7 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
return (
<>
<div
className="flex cursor-default items-center gap-1"
className="flex flex-1 cursor-default select-none items-center justify-center gap-1"
data-tooltip-id="usage_progress_bar"
>
<ExclamationCircleIcon width="18px" height="18px" color="red" />
@ -54,21 +54,14 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
return (
<>
<div
className="flex cursor-pointer flex-col text-[10px] text-gray-400"
className="flex flex-1 cursor-pointer flex-row items-center gap-2 text-[10px] text-gray-400 sm:gap-3"
data-tooltip-id="usage_progress_bar"
onClick={onClick}
>
<div className="xs:flex mb-0 hidden justify-between">
<span>
Free trial <span className="hidden sm:inline">requests</span>
</span>
<span>
{completed} / {total}
</span>
</div>
<div className="my-1.5 flex h-1.5 w-[40vw] rounded-md border border-solid border-gray-400">
<span>
Free trial <span className="hidden sm:inline">requests</span>
</span>
<div className="flex h-1.5 flex-1 rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg transition-all duration-200 ease-in-out ${
completed / total > 0.75 ? "bg-amber-500" : "bg-stone-500"
@ -78,6 +71,9 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
}}
/>
</div>
<span>
{completed} / {total}
</span>
</div>
<ToolTip id="usage_progress_bar" place="top">
{`Click to use your own API key or local LLM (required after ${FREE_TRIAL_LIMIT_REQUESTS} inputs)`}

View file

@ -0,0 +1,198 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
export type MentionOptions = {
HTMLAttributes: Record<string, any>;
renderHTML: (props: {
options: MentionOptions;
node: ProseMirrorNode;
}) => DOMOutputSpec;
suggestion: Omit<SuggestionOptions, "editor">;
};
export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit");
export const AddCodeToEdit = Node.create<MentionOptions>({
name: "add-code-to-edit",
addOptions() {
return {
HTMLAttributes: {},
renderHTML({ options, node }) {
return [
"span",
this.HTMLAttributes,
`${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`,
];
},
suggestion: {
char: "#",
pluginKey: AddCodeToEditPluginKey,
allow: ({ state, range }) => {
const $from = state.doc.resolve(range.from);
const type = state.schema.nodes[this.name];
const allow = !!$from.parent.type.contentMatch.matchType(type);
// Check if there's a space after the "#"
const textFrom = range.from;
const textTo = state.selection.$to.pos;
const text = state.doc.textBetween(textFrom, textTo);
const hasSpace = text.includes(" ");
return allow && !hasSpace;
},
},
};
},
group: "inline",
inline: true,
selectable: false,
atom: true,
addAttributes() {
return {
id: {
default: null,
parseHTML: (element) => element.getAttribute("data-id"),
renderHTML: (attributes) => {
if (!attributes.id) {
return {};
}
return {
"data-id": attributes.id,
};
},
},
label: {
default: null,
parseHTML: (element) => element.getAttribute("data-label"),
renderHTML: (attributes) => {
if (!attributes.label) {
return {};
}
return {
"data-label": attributes.label,
};
},
},
renderInlineAs: {
default: null,
parseHTML: (element) => element.getAttribute("data-renderInlineAs"),
renderHTML: (attributes) => {
if (!attributes.renderInlineAs) {
return {};
}
return {
"data-renderInlineAs": attributes.renderInlineAs,
};
},
},
query: {
default: null,
parseHTML: (element) => element.getAttribute("data-query"),
renderHTML: (attributes) => {
if (!attributes.query) {
return {};
}
return {
"data-query": attributes.query,
};
},
},
itemType: {
default: null,
parseHTML: (element) => element.getAttribute("data-itemType"),
renderHTML: (attributes) => {
if (!attributes.itemType) {
return {};
}
return {
"data-itemType": attributes.itemType,
};
},
},
};
},
parseHTML() {
return [
{
tag: `span[data-type="${this.name}"]`,
},
];
},
renderHTML({ node, HTMLAttributes }) {
const html = this.options.renderHTML({
options: this.options,
node,
});
if (typeof html === "string") {
return [
"span",
mergeAttributes(
{ "data-type": this.name },
this.options.HTMLAttributes,
HTMLAttributes,
),
html,
];
}
return html;
},
addKeyboardShortcuts() {
return {
Backspace: () =>
this.editor.commands.command(({ tr, state }) => {
let isMention = false;
const { selection } = state;
const { empty, anchor } = selection;
if (!empty) {
return false;
}
state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => {
if (node.type.name === this.name) {
isMention = true;
tr.insertText(
this.options.suggestion.char || "",
pos,
pos + node.nodeSize,
);
return false;
}
});
return isMention;
}),
};
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
];
},
});

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,10 +11,10 @@ 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">
<NodeViewWrapper className="code-block-with-content" as="div">
<CodeSnippetPreview
borderColor={
isFirstContextItem

View file

@ -9,10 +9,12 @@ import { IdeMessengerContext } from "../../context/IdeMessenger";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import { getIconFromDropdownItem } from "./MentionList";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
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;
}
@ -156,7 +167,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={`${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

@ -65,6 +65,9 @@ import {
} from "./handleMetaKeyIssues";
import { ComboBoxItem } from "./types";
import useIsOSREnabled from "../../hooks/useIsOSREnabled";
import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice";
import { AddCodeToEdit } from "./AddCodeToEditExtension";
import { addCodeToEdit } from "../../redux/slices/editModeState";
const InputBoxDiv = styled.div<{ border?: string }>`
resize: none;
@ -158,7 +161,6 @@ interface TipTapEditorProps {
toolbarOptions?: ToolbarOptions;
border?: string;
placeholder?: string;
header?: React.ReactNode;
historyKey: string;
}
@ -171,6 +173,7 @@ function TipTapEditor(props: TipTapEditorProps) {
const historyLength = useSelector(
(store: RootState) => store.state.history.length,
);
const useActiveFile = useSelector(selectUseActiveFile);
const { saveSession, loadSession } = useHistory(dispatch);
@ -184,6 +187,14 @@ function TipTapEditor(props: TipTapEditorProps) {
const isOSREnabled = useIsOSREnabled();
const isInEditMode = useSelector(
(state: RootState) => state.editModeState.isInEditMode,
);
const shouldAddFileForEditing = useSelector(
(state: RootState) => state.uiState.shouldAddFileForEditing,
);
const enterSubmenu = async (editor: Editor, providerId: string) => {
const contents = editor.getText();
const indexOfAt = contents.lastIndexOf("@");
@ -467,6 +478,49 @@ function TipTapEditor(props: TipTapEditorProps) {
},
})
: undefined,
isInEditMode
? AddCodeToEdit.configure({
HTMLAttributes: {
class: "add-code-to-edit",
},
suggestion: {
...getContextProviderDropdownOptions(
availableContextProvidersRef,
getSubmenuContextItemsRef,
enterSubmenu,
onClose,
onOpen,
inSubmenuRef,
ideMessenger,
),
command: async ({ editor, range, props }) => {
editor.chain().focus().insertContentAt(range, "").run();
const filepath = props.id;
const contents = await ideMessenger.ide.readFile(filepath);
dispatch(
addCodeToEdit({
filepath,
contents,
}),
);
},
items: async ({ query }) => {
// Only display files in the dropdown
const results = getSubmenuContextItemsRef.current(
"file",
query,
);
return results.map((result) => ({
...result,
label: result.title,
type: "file",
query: result.id,
icon: result.icon,
}));
},
},
})
: undefined,
props.availableSlashCommands.length
? SlashCommand.configure({
HTMLAttributes: {
@ -768,6 +822,13 @@ function TipTapEditor(props: TipTapEditorProps) {
const [activeKey, setActiveKey] = useState<string | null>(null);
useEffect(() => {
if (shouldAddFileForEditing && props.isMainInput) {
insertCharacterWithWhitespace("#");
dispatch(setShouldAddFileForEditing(false));
}
}, [shouldAddFileForEditing]);
const insertCharacterWithWhitespace = useCallback(
(char: string) => {
const text = editor.getText();
@ -829,8 +890,6 @@ function TipTapEditor(props: TipTapEditorProps) {
event.preventDefault();
}}
>
<div>{props.header}</div>
<PaddingDiv>
<EditorContent
spellCheck={false}

View file

@ -9,6 +9,8 @@ import {
} from "core";
import { stripImages } from "core/util/messageContent";
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

@ -44,6 +44,7 @@ interface CodeSnippetPreviewProps {
item: ContextItemWithId;
onDelete?: () => void;
borderColor?: string;
hideHeader?: boolean;
}
const MAX_PREVIEW_HEIGHT = 300;
@ -74,47 +75,49 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
borderColor={props.borderColor}
className="find-widget-skip"
>
<PreviewMarkdownHeader
className="flex cursor-pointer justify-between"
onClick={() => {
if (props.item.id.providerTitle === "file") {
ideMessenger.post("showFile", {
filepath: props.item.description,
});
} else if (props.item.id.providerTitle === "code") {
const lines = props.item.name
.split("(")[1]
.split(")")[0]
.split("-");
ideMessenger.ide.showLines(
props.item.description.split(" ")[0],
parseInt(lines[0]) - 1,
parseInt(lines[1]) - 1,
);
} else {
ideMessenger.post("showVirtualFile", {
content,
name: props.item.name,
});
}
}}
>
<div className="flex items-center gap-1">
<FileIcon height="16px" width="16px" filename={props.item.name} />
{props.item.name}
</div>
<div className="flex items-center gap-1">
<HeaderButtonWithToolTip
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete?.();
}}
>
<XMarkIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
</div>
</PreviewMarkdownHeader>
{!props.hideHeader && (
<PreviewMarkdownHeader
className="flex cursor-pointer justify-between"
onClick={() => {
if (props.item.id.providerTitle === "file") {
ideMessenger.post("showFile", {
filepath: props.item.description,
});
} else if (props.item.id.providerTitle === "code") {
const lines = props.item.name
.split("(")[1]
.split(")")[0]
.split("-");
ideMessenger.ide.showLines(
props.item.description.split(" ")[0],
parseInt(lines[0]) - 1,
parseInt(lines[1]) - 1,
);
} else {
ideMessenger.post("showVirtualFile", {
content,
name: props.item.name,
});
}
}}
>
<div className="flex items-center gap-1">
<FileIcon height="16px" width="16px" filename={props.item.name} />
{props.item.name}
</div>
<div className="flex items-center gap-1">
<HeaderButtonWithToolTip
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete?.();
}}
>
<XMarkIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
</div>
</PreviewMarkdownHeader>
)}
<div
contentEditable={false}
className={`m-0 ${collapsed ? "max-h-[33vh] overflow-hidden" : "overflow-auto"}`}
@ -124,7 +127,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-baseline underline underline-offset-2 mb-0.5">
{getBasename(rif.filepath)}
</span>
</div>
</span>
);
}

View file

@ -1,10 +1,10 @@
import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline";
import Spinner from "./Spinner";
import { lightGray, vscForeground } from "../..";
import { ApplyState } from "core/protocol/ideWebview";
import { useState } from "react";
import { getMetaKeyLabel } from "../../../util";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
import { ApplyState } from "core";
interface ApplyActionsProps {
applyState?: ApplyState;

View file

@ -70,11 +70,11 @@ export default function StepContainerPreToolbar(
const ideMessenger = useContext(IdeMessengerContext);
const streamIdRef = useRef<string>(uuidv4());
const wasGeneratingRef = useRef(props.isGeneratingCodeBlock);
const isMultifileEdit = useSelector(
(state: RootState) => state.state.isMultifileEdit,
const isInEditMode = useSelector(
(state: RootState) => state.editModeState.isInEditMode,
);
const [isExpanded, setIsExpanded] = useState(
props.expanded ?? (isMultifileEdit ? false : true),
props.expanded ?? (isInEditMode ? false : true),
);
const active = useSelector((state: RootState) => state.state.active);
const [codeBlockContent, setCodeBlockContent] = useState("");
@ -139,7 +139,7 @@ export default function StepContainerPreToolbar(
useEffect(() => {
const hasCompletedGenerating =
wasGeneratingRef.current && !isGeneratingCodeBlock;
const shouldAutoApply = hasCompletedGenerating && isMultifileEdit;
const shouldAutoApply = hasCompletedGenerating && isInEditMode;
if (shouldAutoApply) {
onClickApply();
@ -178,7 +178,7 @@ export default function StepContainerPreToolbar(
<div className="flex min-w-0 max-w-[45%] items-center">
<ChevronDownIcon
onClick={onClickExpand}
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 hover:bg-gray-800 hover:brightness-125 ${
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 transition-colors hover:bg-white/10 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>

View file

@ -1,6 +1,4 @@
import { ContextItemWithId } from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { memo, useEffect } from "react";
import { memo, useEffect, useRef } from "react";
import { useRemark } from "react-remark";
import rehypeHighlight, { Options } from "rehype-highlight";
import rehypeKatex from "rehype-katex";
@ -21,6 +19,11 @@ import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
import StepContainerPreToolbar from "./StepContainerPreToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
import { RootState } from "../../redux/store";
import { ContextItemWithId, SymbolWithRange } from "core";
import SymbolLink from "./SymbolLink";
import { useSelector } from "react-redux";
import { ctxItemToRifWithContents } from "core/commands/util";
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;
}
@ -140,8 +141,8 @@ function processCodeBlocks(tree: any) {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node;
node.data.hProperties.codeBlockContent = node.value;
node.data.hProperties["data-isgeneratingcodeblock"] = lastCodeNode === node;
node.data.hProperties["data-codeblockcontent"] = node.value;
if (node.meta) {
let meta = node.meta.split(" ");
@ -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: [
@ -189,13 +212,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
);
},
pre: ({ node, ...preProps }) => {
const {
className,
filepath,
isGeneratingCodeBlock,
codeBlockContent,
range,
} = preProps?.children?.[0]?.props;
const preChildProps = preProps?.children?.[0]?.props;
const { className, filepath, range } = preProps?.children?.[0]?.props;
const codeBlockContent = preChildProps["data-codeblockcontent"];
const isGeneratingCodeBlock =
preChildProps["data-isgeneratingcodeblock"];
if (!props.isRenderingInStepContainer) {
return <SyntaxHighlightedPre {...preProps} />;
@ -236,16 +258,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>;
},
},

View file

@ -0,0 +1,33 @@
import { SymbolWithRange } from "core";
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
interface SymbolLinkProps {
symbol: SymbolWithRange;
content: string;
}
function SymbolLink({ symbol, content }: SymbolLinkProps) {
const ideMessenger = useContext(IdeMessengerContext);
function onClick() {
ideMessenger.post("showLines", {
filepath: symbol.filepath,
startLine: symbol.range.start.line,
endLine: symbol.range.end.line,
});
}
return (
<span
className="mx-[0.1em] mb-[0.15em] inline-flex cursor-pointer flex-row items-center gap-[0.2rem] rounded-md align-middle hover:ring-1"
onClick={onClick}
>
<code className="align-middle underline underline-offset-2">
{content}
</code>
</span>
);
}
export default SymbolLink;

View file

@ -16,6 +16,7 @@ import {
vscInputBackground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import AddModelForm from "../../forms/AddModelForm";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
import { setDefaultModel } from "../../redux/slices/stateSlice";
import {
@ -29,7 +30,6 @@ import {
isMetaEquivalentKeyPressed,
} from "../../util";
import ConfirmationDialog from "../dialogs/ConfirmationDialog";
import AddModelForm from "../../forms/AddModelForm";
interface ModelOptionProps {
option: Option;
@ -169,7 +169,9 @@ function ModelOption({
e.stopPropagation();
e.preventDefault();
ideMessenger.post("openConfigJson", undefined);
ideMessenger.post("config/openProfile", {
profileId: "local",
});
}
function handleOptionClick(e) {

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