Merge branch 'main' into dallin/autodetect-label

This commit is contained in:
Nate 2025-03-07 23:02:06 -08:00
commit f44094a615
40 changed files with 675 additions and 298 deletions

View file

@ -275,7 +275,7 @@ jobs:
cd core
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }}
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@ -409,6 +409,14 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
# We don't want to cache the Continue extension, so it is deleted at the end of the job
- uses: actions/cache@v4
id: test-extensions-cache
with:
path: extensions/vscode/e2e/.test-extensions
# package.json used as the key because that's where the download script is defined
key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }}
- name: Download build artifact
uses: actions/download-artifact@v4
with:
@ -436,7 +444,7 @@ jobs:
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts
echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
if: ${{ github.event.pull_request.head.repo.fork == false }}
if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}
- name: Set up Xvfb
run: |
@ -446,10 +454,15 @@ jobs:
- name: Run e2e tests
run: |
cd extensions/vscode
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
env:
DISPLAY: :99
- name: Delete continue from test extensions
run: |
cd extensions/vscode
rm -rf e2e/.test-extensions/continue*
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4

View file

@ -0,0 +1,25 @@
name: "Label / close stale issues"
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!"
stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue."
days-before-stale: 90
days-before-close: 10
days-before-pr-stale: -1
days-before-pr-close: -1
operations-per-run: 1000
stale-issue-label: "stale"
stale-pr-label: "stale"
exempt-issue-labels: "needs-triage,no-stale,high,highest"
exempt-pr-labels: "no-stale"

View file

@ -2,8 +2,7 @@ import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = {
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const ig = ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(getGlobalContinueIgArray());
const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
const entries = await ide.listDir(dir);
const ignoreUri = joinPathsToUri(dir, ".gitignore");

View file

@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
});
}
private async getRemoteBranchName(
private async getRemoteBranchInfo(
extras: ContextProviderExtras,
): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = /:(?<project>.*).git/.exec(remoteUrl);
let urlMatches: RegExpExecArray | null;
if (/https?.*/.test(remoteUrl)) {
const pathname = new URL(remoteUrl).pathname;
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
} else {
// ssh
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
}
const project = urlMatches?.groups?.project ?? null;
const project = urlMatches?.groups?.projectPath ?? null;
return {
branch: remoteBranch,
@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const { branch, project } = await this.getRemoteBranchName(extras);
const { branch, project } = await this.getRemoteBranchInfo(extras);
const api = await this.getApi();

View file

@ -1,7 +1,4 @@
import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import ignore from "ignore";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
@ -26,7 +23,6 @@ import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { getAllSuggestedDocs } from "./indexing/docs/suggestions";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -53,6 +49,7 @@ import {
type IndexingProgressUpdate,
} from ".";
import { shouldIgnore } from "./indexing/shouldIgnore";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -829,6 +826,10 @@ export class Core {
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
return; // TODO silent in case of commands?
}
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
@ -886,30 +887,51 @@ export class Core {
uri.endsWith(".gitignore")
) {
// Reindex the workspaces
this.invoke("index/forceReIndex", undefined);
this.invoke("index/forceReIndex", {
shouldClearIndexes: true,
});
} else {
// Reindex the file
await this.refreshCodebaseIndexFiles([uri]);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
// Reindex the file
const ignore = await shouldIgnore(uri, this.ide);
if (!ignore) {
await this.refreshCodebaseIndexFiles([uri]);
}
}
}
}
}
});
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
const refreshIfNotIgnored = async (uris: string[]) => {
const toRefresh: string[] = [];
for (const uri of uris) {
const ignore = await shouldIgnore(uri, ide);
if (!ignore) {
toRefresh.push(uri);
}
}
if (toRefresh.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
await this.refreshCodebaseIndexFiles(toRefresh);
}
}
};
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
void refreshIfNotIgnored(data.uris);
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
void refreshIfNotIgnored(data.uris);
}
});
on("files/opened", async ({ data }) => {
@ -950,15 +972,21 @@ export class Core {
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
on("didChangeSelectedProfile", async (msg) => {
await this.configHandler.setSelectedProfile(msg.data.id);
await this.configHandler.reloadConfig();
});
on("didChangeSelectedOrg", (msg) => {
void this.configHandler.setSelectedOrgId(msg.data.id);
void this.configHandler.reloadConfig();
void this.configHandler.loadAssistantsForSelectedOrg();
on("didChangeSelectedOrg", async (msg) => {
await this.configHandler.setSelectedOrgId(msg.data.id);
await this.configHandler.loadAssistantsForSelectedOrg();
if (msg.data.profileId) {
this.invoke("didChangeSelectedProfile", {
id: msg.data.profileId,
});
} else {
await this.configHandler.reloadConfig();
}
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
@ -975,19 +1003,15 @@ export class Core {
});
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
const ignoreInstance = ignore().add(defaultIgnoreFile);
let rootDirectory = await this.ide.getWorkspaceDirs();
const relativeFilePath = path.relative(rootDirectory[0], filepath);
try {
if (!ignoreInstance.ignores(relativeFilePath)) {
const ignore = shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
} catch (e) {
if (e instanceof RangeError) {
// do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json`
} else {
console.debug("unhandled ignores error", relativeFilePath, e);
}
console.error(
`didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
);
}
});

2
core/index.d.ts vendored
View file

@ -543,7 +543,7 @@ export interface CustomLLMWithOptionals {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => Promise<string[]>;

View file

@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
export const defaultIgnoreFileAndDir = ignore()
.add(defaultIgnoreFile)
.add(defaultIgnoreDir);
export function gitIgArrayFromFile(file: string) {
return file
.split(/\r?\n/) // Split on new line

View file

@ -0,0 +1,167 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
TEST_DIR,
addToTestDir,
setUpTestDir,
tearDownTestDir,
} from "../test/testDir";
import { shouldIgnore } from "./shouldIgnore";
// Test for the shouldIgnore function
describe("shouldIgnore", () => {
beforeEach(() => {
setUpTestDir();
});
afterEach(() => {
tearDownTestDir();
});
test("should return true if a file is ignored by .gitignore", async () => {
addToTestDir([
["ignored-file.txt", "content"],
[".gitignore", "ignored-file.txt"],
]);
const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should return true if a folder is ignored by .continueignore", async () => {
addToTestDir([
["ignored-folder/file.txt", "content"],
[".continueignore", "ignored-folder/"],
]);
const result = await shouldIgnore(
TEST_DIR + "/ignored-folder/file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(true);
});
test("should return false if a file is not ignored", async () => {
addToTestDir([["kept-file.txt", "contents"]]);
const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(false);
});
test("should return true if a file is ignored by .gitignore with spaces in file name", async () => {
addToTestDir([
["ignored file.txt", "content"],
[".gitignore", "ignored file.txt"],
]);
const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should return true if a .continueignore override ignores file", async () => {
addToTestDir([
["override-file.txt", "content"],
[".gitignore", "override-file.txt"],
[".continueignore", "!override-file.txt"],
]);
const result = await shouldIgnore(
TEST_DIR + "/override-file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(false);
});
test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => {
addToTestDir([
["level1/level2/level3/ignored-file.txt", "content"],
["level1/.gitignore", "level2/"],
["level1/level2/.continueignore", "level3/"],
]);
const result = await shouldIgnore(
TEST_DIR + "/level1/level2/level3/ignored-file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(true);
});
test("should return false if a file with spaces is not ignored", async () => {
addToTestDir([["kept file.txt", "contents"]]);
const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(false);
});
test("should handle multiple levels of directories with some files ignored", async () => {
addToTestDir([
["nested/dir1/.gitignore", "ignored.txt"],
["nested/dir1/ignored.txt", "content"],
["nested/dir2/kept.txt", "content"],
]);
const ignoredResult = await shouldIgnore(
TEST_DIR + "/nested/dir1/ignored.txt",
testIde,
[TEST_DIR],
);
expect(ignoredResult).toBe(true);
const keptResult = await shouldIgnore(
TEST_DIR + "/nested/dir2/kept.txt",
testIde,
[TEST_DIR],
);
expect(keptResult).toBe(false);
});
test("should respect default file and folder ignores top level", async () => {
addToTestDir([
[".env", "contents"],
["go.sum", "contents"],
".idea/",
[".idea/test.xml", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should respect default file and folder ignores at nested level", async () => {
addToTestDir([
"nested/.idea/test.xml",
["nested/.env", "contents"],
["nested/go.sum", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
});

View file

@ -0,0 +1,73 @@
import ignore from "ignore";
import type { FileType, IDE } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
import { getIgnoreContext } from "./walkDir";
/*
Process:
1. Check global/default ignores
2. Walk UP tree from file, checking ignores at each level
TODO there might be issues with symlinks here
*/
export async function shouldIgnore(
fileUri: string,
ide: IDE,
rootDirCandidates?: string[],
): Promise<boolean> {
const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs());
const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris);
if (!rootDir) {
return true;
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
let currentDir = uri;
let directParent = true;
let fileType = 1 as FileType.File as FileType;
while (currentDir !== rootDir) {
// Go to parent dir of file
const splitUri = currentDir.split("/");
splitUri.pop();
currentDir = splitUri.join("/");
// Get all files in the dir
const dirEntries = await ide.listDir(currentDir);
// Check if the file is a symbolic link, ignore if so
if (directParent) {
directParent = false;
const baseName = getUriPathBasename(fileUri);
const entry = dirEntries.find(([name, _]) => name === baseName);
if (entry) {
fileType = entry[1];
if (fileType === (64 as FileType.SymbolicLink)) {
return true;
}
}
}
const ignoreContext = await getIgnoreContext(
currentDir,
dirEntries,
ide,
defaultAndGlobalIgnores,
);
let relativePath = uri.substring(currentDir.length + 1);
if (fileType === (2 as FileType.Directory)) {
relativePath += "/";
}
if (ignoreContext.ignores(relativePath)) {
return true;
}
}
return false;
}

View file

@ -1,14 +1,14 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import fs from "fs";
import path from "path";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
describe("walkDir functions", () => {
beforeEach(async () => {
@ -19,6 +19,27 @@ describe("walkDir functions", () => {
tearDownTestDir();
});
// describe.only("test speed", () => {
// it("should walk a simple directory structure", async () => {
// addToTestDir([
// "src/",
// ["src/file1.ts", "content1"],
// ["src/file2.ts", "content2"],
// "src/nested/",
// ["src/nested/file3.ts", "content3"],
// ]);
// const dir = await testIde.getWorkspaceDirs();
// const start = Date.now();
// for (let i = 0; i < 10000; i++) {
// await walkDir(dir[0], testIde);
// }
// const passed = Date.now() - start;
// console.log(`Test took ${passed} ms`);
// });
// });
describe("walkDir", () => {
it("should walk a simple directory structure", async () => {
addToTestDir([
@ -313,6 +334,9 @@ describe("walkDir functions", () => {
["node_modules/package/index.js", "content"],
["dist/bundle.js", "content"],
["coverage/lcov.env", "content"],
["nested/node_modules/package/index.js", "content"],
["nested/dist/bundle.js", "content"],
["nested/coverage/lcov.env", "content"],
]);
const files = await walkDir(
@ -327,6 +351,9 @@ describe("walkDir functions", () => {
expect(files).not.toContain(".git/config");
expect(files).not.toContain("node_modules/package/index.js");
expect(files).not.toContain("coverage/lcov.info");
expect(files).not.toContain("nested/node_modules/package/index.js");
expect(files).not.toContain("nested/dist/bundle.js");
expect(files).not.toContain("nested/coverage/lcov.env");
});
it("should handle directory-specific ignore patterns correctly", async () => {

View file

@ -2,27 +2,23 @@ import ignore, { Ignore } from "ignore";
import type { FileType, IDE } from "..";
import { joinPathsToUri } from "../util/uri";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
defaultIgnoreFileAndDir,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore";
import { joinPathsToUri } from "../util/uri";
export interface WalkerOptions {
ignoreFiles?: string[];
onlyDirs?: boolean;
returnRelativeUrisPaths?: boolean;
additionalIgnoreRules?: string[];
}
type Entry = [string, FileType];
// helper struct used for the DFS walk
type WalkableEntry = {
name: string;
relativeUriPath: string;
uri: string;
type: FileType;
@ -41,143 +37,110 @@ type IgnoreContext = {
};
class DFSWalker {
private readonly ignoreFileNames: Set<string>;
constructor(
private readonly uri: string,
private readonly ide: IDE,
private readonly options: WalkerOptions,
) {
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
}
) {}
// walk is a depth-first search implementation
public async *walk(): AsyncGenerator<string> {
const root = this.newRootWalkContext();
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignoreContexts = await this.getIgnoreToApplyInDir(
cur,
walkableEntries,
);
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignoreContexts)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignoreContexts: ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
} else {
// Note that shouldInclude handles skipping files if options.onlyDirs is true
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
}
}
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
private newRootWalkContext(): WalkContext {
const globalIgnoreFile = getGlobalContinueIgArray();
return {
const rootContext: WalkContext = {
walkableEntry: {
name: "",
relativeUriPath: "",
uri: this.uri,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreContexts: [
ignoreContexts: [],
};
const stack = [rootContext];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
// Only directories will be added to the stack
const entries = await this.ide.listDir(cur.walkableEntry.uri);
const newIgnore = await getIgnoreContext(
cur.walkableEntry.uri,
entries,
this.ide,
defaultAndGlobalIgnores,
);
const ignoreContexts = [
...cur.ignoreContexts,
{
ignore: ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(globalIgnoreFile),
dirname: "",
ignore: newIgnore,
dirname: cur.walkableEntry.relativeUriPath,
},
],
};
}
];
private async listDirForWalking(
walkableEntry: WalkableEntry,
): Promise<WalkableEntry[]> {
const entries = await this.ide.listDir(walkableEntry.uri);
return entries.map((e) => ({
relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`,
uri: joinPathsToUri(walkableEntry.uri, e[0]),
type: e[1],
entry: e,
}));
}
for (const entry of entries) {
if (this.entryIsSymlink(entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
continue;
}
const walkableEntry = {
name: entry[0],
relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`,
uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]),
type: entry[1],
entry: entry,
};
private async getIgnoreToApplyInDir(
curDir: WalkContext,
entriesInDir: WalkableEntry[],
): Promise<IgnoreContext[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir);
if (ignoreFilesInDir.length === 0) {
return curDir.ignoreContexts;
}
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
const newIgnoreContext = {
ignore: ignore().add(patterns),
dirname: curDir.walkableEntry.relativeUriPath,
};
return [...curDir.ignoreContexts, newIgnoreContext];
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
continue;
}
}
let shouldInclude = true;
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength =
ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
shouldInclude = false;
}
}
if (!shouldInclude) {
continue;
}
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
const ignoreEntries = entries.filter((w) =>
this.entryIsIgnoreFile(w.entry),
);
const promises = ignoreEntries.map(async (w) => {
return await this.ide.readFile(w.uri);
});
return Promise.all(promises);
}
private shouldInclude(
walkableEntry: WalkableEntry,
ignoreContexts: IgnoreContext[],
) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
return false;
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(walkableEntry.entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
return false;
if (this.entryIsDirectory(entry)) {
stack.push({
walkableEntry,
ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
} else {
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
}
}
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
return false;
}
}
return true;
}
private entryIsDirectory(entry: Entry) {
@ -187,21 +150,9 @@ class DFSWalker {
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
private entryIsIgnoreFile(e: Entry): boolean {
if (
e[1] === (2 as FileType.Directory) ||
e[1] === (64 as FileType.SymbolicLink)
) {
return false;
}
return this.ignoreFileNames.has(e[0]);
}
}
const defaultOptions: WalkerOptions = {
ignoreFiles: [".gitignore", ".continueignore"],
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
onlyDirs: false,
returnRelativeUrisPaths: false,
};
@ -238,3 +189,49 @@ export async function walkDirs(
);
return results.flat();
}
export async function getIgnoreContext(
currentDir: string,
currentDirEntries: Entry[],
ide: IDE,
defaultAndGlobalIgnores: Ignore,
) {
const dirFiles = currentDirEntries
.filter(([_, entryType]) => entryType === (1 as FileType.File))
.map(([name, _]) => name);
// Find ignore files and get ignore arrays from their contexts
// These are done separately so that .continueignore can override .gitignore
const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore");
const continueIgnoreFile = dirFiles.find(
(name) => name === ".continueignore",
);
const getGitIgnorePatterns = async () => {
if (gitIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.gitignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const getContinueIgnorePatterns = async () => {
if (continueIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.continueignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const ignoreArrays = await Promise.all([
getGitIgnorePatterns(),
getContinueIgnorePatterns(),
]);
// Note precedence here!
const ignoreContext = ignore()
.add(ignoreArrays[0]) // gitignore
.add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed
.add(ignoreArrays[1]); // local .continueignore
return ignoreContext;
}

View file

@ -763,6 +763,7 @@ export abstract class BaseLLM implements ILLM {
}
let completion = "";
let citations: null | string[] = null
try {
if (this.templateMessages) {
@ -790,6 +791,8 @@ export abstract class BaseLLM implements ILLM {
completion = renderChatMessage(msg);
} else {
// Stream true
console.log("Streaming");
const stream = this.openaiAdapter.chatCompletionStream(
{
...body,
@ -802,6 +805,9 @@ export abstract class BaseLLM implements ILLM {
if (result) {
yield result;
}
if (!citations && (chunk as any).citations && Array.isArray((chunk as any).citations)) {
citations = (chunk as any).citations;
}
}
}
} else {
@ -824,6 +830,10 @@ export abstract class BaseLLM implements ILLM {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
if (citations) {
await this.writeLog(`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`);
}
}
return {

View file

@ -205,10 +205,11 @@ describe("LLM", () => {
});
testLLM(
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }),
{ skip: false, timeout: 20000 },
{ skip: false, timeout: 60000 },
);
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), {
skip: false,
timeout: 60000,
});
testLLM(
new Gemini({

View file

@ -1,4 +1,5 @@
import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
class CustomLLMClass extends BaseLLM {
@ -18,7 +19,7 @@ class CustomLLMClass extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
constructor(custom: CustomLLM) {
super(custom.options || { model: "custom" });
@ -38,7 +39,11 @@ class CustomLLMClass extends BaseLLM {
options,
(...args) => this.fetch(...args),
)) {
yield { role: "assistant", content };
if (typeof content === "string") {
yield { role: "assistant", content };
} else {
yield content;
}
}
} else {
for await (const update of super._streamChat(messages, signal, options)) {
@ -68,7 +73,11 @@ class CustomLLMClass extends BaseLLM {
options,
(...args) => this.fetch(...args),
)) {
yield content;
if (typeof content === "string") {
yield content;
} else {
yield renderChatMessage(content);
}
}
} else {
throw new Error(

View file

@ -57,9 +57,18 @@ export const PROVIDER_TOOL_SUPPORT: Record<
},
// https://ollama.com/search?c=tools
ollama: (model) => {
let modelName = "";
// Extract the model name after the last slash to support other registries
if(model.includes("/")) {
let parts = model.split('/');
modelName = parts[parts.length - 1];
} else {
modelName = model;
}
if (
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
(part) => model.toLowerCase().includes(part),
(part) => modelName.toLowerCase().includes(part),
)
) {
return false;
@ -79,10 +88,11 @@ export const PROVIDER_TOOL_SUPPORT: Record<
"nemotron",
"llama3-groq",
"granite3",
"granite-3",
"aya-expanse",
"firefunction-v2",
"mistral",
].some((part) => model.toLowerCase().startsWith(part))
].some((part) => modelName.toLowerCase().includes(part))
) {
return true;
}

View file

@ -6163,9 +6163,10 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",

View file

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

View file

@ -5,7 +5,10 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
didChangeSelectedProfile: [{ id: string | null }, void];
didChangeSelectedOrg: [{ id: string | null }, void];
didChangeSelectedOrg: [
{ id: string | null; profileId?: string | null },
void,
];
};
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
didChangeAvailableProfiles: [

View file

@ -1,7 +1,7 @@
import fs from "fs";
import os from "os";
import path from "path";
import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri";
import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri";
// Want this outside of the git repository so we can change branches in tests
export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir");
@ -26,7 +26,7 @@ export function tearDownTestDir() {
"index/index.ts" creates an empty index/index.ts
["index/index.ts", "hello"] creates index/index.ts with contents "hello"
*/
export function addToTestDir(pathsOrUris: (string | string[])[]) {
export function addToTestDir(pathsOrUris: (string | [string, string])[]) {
// Allow tests to use URIs or local paths
const paths = pathsOrUris.map((val) => {
if (Array.isArray(val)) {

View file

@ -368,7 +368,7 @@ export function readAllGlobalPromptFiles(
if (stats.isDirectory()) {
const nestedPromptFiles = readAllGlobalPromptFiles(filepath);
promptFiles.push(...nestedPromptFiles);
} else {
} else if (file.endsWith(".prompt")) {
const content = fs.readFileSync(filepath, "utf8");
promptFiles.push({ path: filepath, content });
}

View file

@ -116,19 +116,23 @@ export function getLastNUriRelativePathParts(
}
export function joinPathsToUri(uri: string, ...pathSegments: string[]) {
const components = URI.parse(uri);
let baseUri = uri;
if (baseUri.at(-1) !== "/") {
baseUri += "/";
}
const segments = pathSegments.map((segment) => pathToUriPathSegment(segment));
components.path = `${components.path}/${segments.join("/")}`;
return URI.serialize(components);
return URI.resolve(baseUri, segments.join("/"));
}
export function joinEncodedUriPathSegmentToUri(
uri: string,
pathSegment: string,
) {
const components = URI.parse(uri);
components.path = `${components.path}/${pathSegment}`;
return URI.serialize(components);
let baseUri = uri;
if (baseUri.at(-1) !== "/") {
baseUri += "/";
}
return URI.resolve(baseUri, pathSegment);
}
export function getShortestUniqueRelativeUriPaths(

View file

@ -18,7 +18,7 @@ To open your configuration file, you can click the "gear" icon in the bottom rig
When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist.
See the full reference for `config.yaml` [here](../../reference.md).
See the full reference for `config.yaml` [here](../../yaml-reference.md).
## Deprecated configuration methods

View file

@ -14,7 +14,7 @@ You can read more about how development data is generated as a byproduct of LLM-
You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories.
For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&block=data).
For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data).
See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data)

View file

@ -64,7 +64,7 @@ Pre-indexed docs are only available in VS Code because the VS Code extension shi
### Hub `docs` Blocks
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&block=docs).
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
### Through the `@Docs` Context Provider
@ -137,7 +137,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
context:
- provider: docs
params:
nRetrieve: 25 # The number of docs to retreive from the embeddings query
nRetrieve: 25 # The number of docs to retrieve from the embeddings query
nFinal: 5 # The number of docs chunks to return IF reranking
useReranking: true # use reranking if a reranker is configured (defaults to true)
```
@ -149,7 +149,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo
{
"name": "docs",
"params": {
"nRetrieve": 25, // The number of docs to retreive from the embeddings query
"nRetrieve": 25, // The number of docs to retrieve from the embeddings query
"nFinal": 5, // The number of docs chunks to return IF reranking
"useReranking": true // use reranking if a reranker is configured (defaults to true)
}

View file

@ -4,7 +4,7 @@ title: Prompt files
Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts.
On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&block=rules).
On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules).
Prompt files can also be stored within your project's root directory as `.prompt` files. See below.

View file

@ -9,7 +9,7 @@ Rules are used to provide instructions to **chat** models. They are inserted int
## Hub `rules` blocks
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&block=rules) in the Hub.
Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
## `.continuerules`

View file

@ -51,7 +51,7 @@ We recommend configuring **GPT-4o** as your chat model.
## Autocomplete model
We recommend configuring **Codestral** as your autocomplete model.
We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral:
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
@ -60,6 +60,8 @@ We recommend configuring **Codestral** as your autocomplete model.
- name: Codestral
provider: mistral
model: codestral-latest
apiBase: https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1
apiKey: <YOUR_AZURE_API_KEY>
roles:
- autocomplete
```
@ -70,7 +72,9 @@ We recommend configuring **Codestral** as your autocomplete model.
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral-latest"
"model": "codestral-latest",
"apiBase": "https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1",
"apiKey": "<YOUR_AZURE_API_KEY>"
}
}
```

View file

@ -30,7 +30,7 @@ Currently custom tools can be configured using the [Model Context Protocol](http
MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp).
To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&block=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md):
To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md):
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">

View file

@ -41,7 +41,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c
1. Open the "Output" panel (right next to the terminal)
2. In the dropdown, select "Continue - LLM Prompts/Completions"
3. View the exact prompts that were sent to the LLM and the completions recieved
3. View the exact prompts that were sent to the LLM and the completions received
### JetBrains

View file

@ -12,7 +12,7 @@ See also
- [Intro to YAML](https://yaml.org/)
- [JSON Continue Config Reference](/json-reference)
- [YAML Continue Config Reference](/reference)
- [YAML Continue Config Reference](/yaml-reference)
## Create YAML file
@ -37,9 +37,9 @@ Add all model configurations in `config.json`, including models in `models`, `ta
- `inlineEdit` -> e.g. `roles: [chat, edit]`
- `applyCodeBlock` -> e.g. `roles: [chat, apply]`
Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/reference#requestoptions)
Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions)
Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions)
Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions)
<!-- TODO - ollama autodetect supported? -->

View file

@ -111,7 +111,10 @@ class OpenedConnection(private val connection: URLConnection?) :
) {
try {
if (connection != null) {
val url = connection.url.toString()
val fullUrl = connection.url.toString()
// Extract only the resource path after the JAR prefix to prevent incorrect mime type matching
// (e.g., if a user's home folder contains "js" in the path)
val url = fullUrl.substringAfterLast("jar!/", fullUrl)
when {
url.contains("css") -> cefResponse.mimeType = "text/css"
url.contains("js") -> cefResponse.mimeType = "text/javascript"

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.4",
"version": "1.1.5",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -52,6 +52,7 @@
"llama"
],
"activationEvents": [
"onUri",
"onStartupFinished",
"onView:continueGUIView"
],
@ -594,7 +595,7 @@
"e2e:compile": "tsc -p ./tsconfig.e2e.json",
"e2e:build": "npm --prefix ../../gui run build && npm run package",
"e2e:create-storage": "mkdir -p ./e2e/storage",
"e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage",
"e2e:get-chromedriver": "CODE_VERSION=\"1.95.0\" extest get-chromedriver --storage ./e2e/storage",
"e2e:get-vscode": "CODE_VERSION=\"1.95.0\" extest get-vscode --storage ./e2e/storage",
"e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'",
"e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh",

View file

@ -47,7 +47,7 @@ export class RecentlyEditedTracker {
editedRange: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
): Promise<void> {
if (editedRange.uri.scheme === "output") {
if (editedRange.uri.scheme !== "file") {
return;
}
@ -83,7 +83,6 @@ export class RecentlyEditedTracker {
RecentlyEditedTracker.maxRecentlyEditedRanges,
);
}
}
private insertDocument(uri: vscode.Uri): void {

View file

@ -230,7 +230,7 @@ export class VerticalDiffManager {
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
console.warn("Issue occurred while creating new vertical diff handler");
return;
}
@ -353,7 +353,7 @@ export class VerticalDiffManager {
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
console.warn("Issue occurred while creating new vertical diff handler");
return undefined;
}

View file

@ -28,6 +28,7 @@ import { registerAllPromptFilesCompletionProviders } from "../lang-server/prompt
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
import { UriEventHandler } from "../stubs/uriHandler";
import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
@ -55,10 +56,11 @@ export class VsCodeExtension {
private battery: Battery;
private workOsAuthProvider: WorkOsAuthProvider;
private fileSearch: FileSearch;
private uriHandler = new UriEventHandler();
constructor(context: vscode.ExtensionContext) {
// Register auth provider
this.workOsAuthProvider = new WorkOsAuthProvider(context);
this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler);
this.workOsAuthProvider.refreshSessions();
context.subscriptions.push(this.workOsAuthProvider);
@ -193,6 +195,41 @@ export class VsCodeExtension {
),
);
// Handle uri events
this.uriHandler.event((uri) => {
const queryParams = new URLSearchParams(uri.query);
let profileId = queryParams.get("profile_id");
let orgId = queryParams.get("org_id");
if (orgId) {
if (orgId === "null") {
orgId = null;
}
// In case org id is passed with profile id
// Make sure org is updated before profile is set
if (profileId) {
if (profileId === "null") {
profileId = null;
}
this.core.invoke("didChangeSelectedOrg", {
id: orgId,
profileId,
});
} else {
this.core.invoke("didChangeSelectedOrg", {
id: orgId,
});
}
} else if (profileId) {
if (profileId === "null") {
profileId = null;
}
this.core.invoke("didChangeSelectedProfile", {
id: profileId,
});
}
});
// Battery
this.battery = new Battery();
context.subscriptions.push(this.battery);

View file

@ -15,13 +15,13 @@ import {
ExtensionContext,
ProgressLocation,
Uri,
UriHandler,
window,
workspace,
} from "vscode";
import { PromiseAdapter, promiseFromEvent } from "./promiseUtils";
import { SecretStorage } from "./SecretStorage";
import { UriEventHandler } from "./uriHandler";
const AUTH_NAME = "Continue";
@ -35,11 +35,6 @@ const controlPlaneEnv = getControlPlaneEnvSync(
const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`;
class UriEventHandler extends EventEmitter<Uri> implements UriHandler {
public handleUri(uri: Uri) {
this.fire(uri);
}
}
// Function to generate a random string of specified length
function generateRandomString(length: number): string {
const possibleCharacters =
@ -83,13 +78,15 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable {
string,
{ promise: Promise<string>; cancel: EventEmitter<void> }
>();
private _uriHandler = new UriEventHandler();
private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes
private secretStorage: SecretStorage;
constructor(private readonly context: ExtensionContext) {
constructor(
private readonly context: ExtensionContext,
private readonly _uriHandler: UriEventHandler,
) {
this._disposable = Disposable.from(
authentication.registerAuthenticationProvider(
controlPlaneEnv.AUTH_TYPE,

View file

@ -0,0 +1,10 @@
import * as vscode from "vscode";
export class UriEventHandler
extends vscode.EventEmitter<vscode.Uri>
implements vscode.UriHandler
{
public handleUri(uri: vscode.Uri) {
this.fire(uri);
}
}

View file

@ -155,10 +155,6 @@ export function TabBar() {
);
const tabs = useSelector((state: RootState) => state.tabs.tabs);
useEffect(() => {
console.log("session", currentSession);
}, [currentSession.id]);
// Simple UUID generator for our needs
const generateId = useCallback(() => {
return Date.now().toString(36) + Math.random().toString(36).substring(2);

View file

@ -8,9 +8,8 @@
// TODO support github-specific markdown as well, edge case
*/
export const patchNestedMarkdown = (source: string): string => {
if (!source.match(/```(md|markdown)/)) return source; // For performance
if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
// const start = Date.now();
let nestCount = 0;
const lines = source.split("\n");
@ -28,9 +27,17 @@ export const patchNestedMarkdown = (source: string): string => {
}
} else {
// Enter the markdown block, start tracking nesting
if (line.startsWith("```md") || line.startsWith("```markdown")) {
nestCount = 1;
lines[i] = lines[i].replace(/```(md|markdown)/, "~~~"); // Replace backticks with tildes
if (line.startsWith("```")) {
const header = line.replaceAll("`", "");
const file = header.split(" ")[0];
if (file) {
const ext = file.split(".").at(-1);
if (ext === "md" || ext === "markdown") {
nestCount = 1;
lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
}
}
}
}
}
@ -38,53 +45,3 @@ export const patchNestedMarkdown = (source: string): string => {
// console.log(`patched in ${Date.now() - start}ms`);
return out;
};
// This version tries to detect if a codeblock without a language specified is a starter codeblock
// It tries again if didn't come back to root nesting, without checking for that ^
// I didn't use for performance and also because the root nest check doesn't make sense mid-generation
// export const patchNestedMarkdown = (source: string): string => {
// const start = Date.now();
// let attempts = 0;
// while (attempts <= 2) {
// let nestCount = 0;
// const lines = source.split("\n");
// const trimmedLines = lines.map((l) => l.trim());
// for (let i = 0; i < trimmedLines.length; i++) {
// const line = trimmedLines[i];
// if (nestCount) {
// if (line.match(/^`+$/)) {
// if (attempts === 0 && i !== lines.length && lines[i + 1] !== "") {
// nestCount++;
// continue;
// }
// if (nestCount === 1) lines[i] = "~~~";
// nestCount--;
// } else if (line.startsWith("```")) {
// // Going into a nested codeblock
// nestCount++;
// }
// } else {
// // Enter the markdown block, start tracking nesting
// if (line.startsWith("```md") || line.startsWith("```markdown")) {
// nestCount = 1;
// lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes
// }
// }
// }
// if (nestCount === 0) {
// console.log(
// `patch successful in ${Date.now() - start} ms with ${attempts} attempts`,
// );
// return lines.join("\n");
// }
// attempts++;
// }
// console.log(
// `patch failed in ${Date.now() - start} ms with ${attempts} attempts`,
// );
// return source;
// };

View file

@ -40,8 +40,10 @@ export class AzureOpenAIApi implements BaseLlmApi {
if (PROXY) {
const url = new URL(PROXY);
proxyOptions = {
host: url.hostname,
port: Number(url.port),
host: (url.protocol ? url.protocol + "//" : "") + url.hostname,
port: Number(url.port || 80),
username: url.username,
password: url.password,
};
}