continue-custom/core/indexing/refreshIndex.ts
Nate Sesti 04c08c7159
dev (#1542)
* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
2024-06-28 16:21:36 -07:00

387 lines
10 KiB
TypeScript

import crypto from "node:crypto";
import * as fs from "node:fs";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import { IndexTag, IndexingProgressUpdate } from "../index.js";
import { getIndexSqlitePath } from "../util/paths.js";
import {
CodebaseIndex,
IndexResultType,
LastModifiedMap,
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
export type DatabaseConnection = Database<sqlite3.Database>;
export function tagToString(tag: IndexTag): string {
return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
}
export class SqliteDb {
static db: DatabaseConnection | null = null;
private static async createTables(db: DatabaseConnection) {
await db.exec(
`CREATE TABLE IF NOT EXISTS tag_catalog (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dir STRING NOT NULL,
branch STRING NOT NULL,
artifactId STRING NOT NULL,
path STRING NOT NULL,
cacheKey STRING NOT NULL,
lastUpdated INTEGER NOT NULL
)`,
);
await db.exec(
`CREATE TABLE IF NOT EXISTS global_cache (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cacheKey STRING NOT NULL,
dir STRING NOT NULL,
branch STRING NOT NULL,
artifactId STRING NOT NULL
)`,
);
}
private static indexSqlitePath = getIndexSqlitePath();
static async get() {
if (SqliteDb.db && fs.existsSync(SqliteDb.indexSqlitePath)) {
return SqliteDb.db;
}
SqliteDb.indexSqlitePath = getIndexSqlitePath();
SqliteDb.db = await open({
filename: SqliteDb.indexSqlitePath,
driver: sqlite3.Database,
});
await SqliteDb.createTables(SqliteDb.db);
return SqliteDb.db;
}
}
async function getSavedItemsForTag(
tag: IndexTag,
): Promise<{ path: string; cacheKey: string; lastUpdated: number }[]> {
const db = await SqliteDb.get();
const stmt = await db.prepare(
`SELECT path, cacheKey, lastUpdated FROM tag_catalog
WHERE dir = ? AND branch = ? AND artifactId = ?`,
tag.directory,
tag.branch,
tag.artifactId,
);
const rows = await stmt.all();
return rows;
}
interface PathAndOptionalCacheKey {
path: string;
cacheKey?: string;
}
enum AddRemoveResultType {
Add = "add",
Remove = "remove",
UpdateNewVersion = "updateNewVersion",
UpdateOldVersion = "updateOldVersion",
}
async function getAddRemoveForTag(
tag: IndexTag,
currentFiles: LastModifiedMap,
readFile: (path: string) => Promise<string>,
): Promise<[PathAndCacheKey[], PathAndCacheKey[], MarkCompleteCallback]> {
const newLastUpdatedTimestamp = Date.now();
const saved = await getSavedItemsForTag(tag);
const add: PathAndCacheKey[] = [];
const updateNewVersion: PathAndCacheKey[] = [];
const updateOldVersion: PathAndCacheKey[] = [];
const remove: PathAndCacheKey[] = [];
for (const item of saved) {
const { lastUpdated, ...pathAndCacheKey } = item;
if (currentFiles[item.path] === undefined) {
// Was indexed, but no longer exists. Remove
remove.push(pathAndCacheKey);
} else {
// Exists in old and new, so determine whether it was updated
if (lastUpdated < currentFiles[item.path]) {
// Change was made after last update
updateNewVersion.push({
path: pathAndCacheKey.path,
cacheKey: calculateHash(await readFile(pathAndCacheKey.path)),
});
updateOldVersion.push(pathAndCacheKey);
} else {
// Already updated, do nothing
}
// Remove so we can check leftovers afterward
delete currentFiles[item.path];
}
}
// Any leftover in current files need to be added
add.push(
...(await Promise.all(
Object.keys(currentFiles).map(async (path) => {
const fileContents = await readFile(path);
return { path, cacheKey: calculateHash(fileContents) };
}),
)),
);
// Create the markComplete callback function
const db = await SqliteDb.get();
const itemToAction: {
[key: string]: [PathAndCacheKey, AddRemoveResultType];
} = {};
async function markComplete(items: PathAndCacheKey[], _: IndexResultType) {
const actions = items.map(
(item) =>
itemToAction[
JSON.stringify({ path: item.path, cacheKey: item.cacheKey })
],
);
for (const [{ path, cacheKey }, resultType] of actions) {
switch (resultType) {
case AddRemoveResultType.Add:
await db.run(
"INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
path,
cacheKey,
newLastUpdatedTimestamp,
tag.directory,
tag.branch,
tag.artifactId,
);
break;
case AddRemoveResultType.Remove:
await db.run(
`DELETE FROM tag_catalog WHERE
cacheKey = ? AND
path = ? AND
dir = ? AND
branch = ? AND
artifactId = ?
`,
cacheKey,
path,
tag.directory,
tag.branch,
tag.artifactId,
);
break;
case AddRemoveResultType.UpdateNewVersion:
await db.run(
`UPDATE tag_catalog SET
cacheKey = ?,
lastUpdated = ?
WHERE
path = ? AND
dir = ? AND
branch = ? AND
artifactId = ?
`,
cacheKey,
newLastUpdatedTimestamp,
path,
tag.directory,
tag.branch,
tag.artifactId,
);
break;
case AddRemoveResultType.UpdateOldVersion:
break;
}
}
}
for (const item of updateNewVersion) {
itemToAction[JSON.stringify(item)] = [
item,
AddRemoveResultType.UpdateNewVersion,
];
}
for (const item of add) {
itemToAction[JSON.stringify(item)] = [item, AddRemoveResultType.Add];
}
for (const item of updateOldVersion) {
itemToAction[JSON.stringify(item)] = [
item,
AddRemoveResultType.UpdateOldVersion,
];
}
for (const item of remove) {
itemToAction[JSON.stringify(item)] = [item, AddRemoveResultType.Remove];
}
return [
[...add, ...updateNewVersion],
[...remove, ...updateOldVersion],
markComplete,
];
}
/**
* Check the global cache for items with this cacheKey for the given artifactId.
* Return all of the tags that it exists under, which could be an empty array
*/
async function getTagsFromGlobalCache(
cacheKey: string,
artifactId: string,
): Promise<IndexTag[]> {
const db = await SqliteDb.get();
const stmt = await db.prepare(
"SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?",
);
const rows = await stmt.all(cacheKey, artifactId);
return rows;
}
function calculateHash(fileContents: string): string {
const hash = crypto.createHash("sha256");
hash.update(fileContents);
return hash.digest("hex");
}
export async function getComputeDeleteAddRemove(
tag: IndexTag,
currentFiles: LastModifiedMap,
readFile: (path: string) => Promise<string>,
repoName: string | undefined,
): Promise<[RefreshIndexResults, MarkCompleteCallback]> {
const [add, remove, markComplete] = await getAddRemoveForTag(
tag,
currentFiles,
readFile,
);
const compute: PathAndCacheKey[] = [];
const del: PathAndCacheKey[] = [];
const addTag: PathAndCacheKey[] = [];
const removeTag: PathAndCacheKey[] = [];
for (const { path, cacheKey } of add) {
const existingTags = await getTagsFromGlobalCache(cacheKey, tag.artifactId);
if (existingTags.length > 0) {
addTag.push({ path, cacheKey });
} else {
compute.push({ path, cacheKey });
}
}
for (const { path, cacheKey } of remove) {
const existingTags = await getTagsFromGlobalCache(cacheKey, tag.artifactId);
if (existingTags.length > 1) {
removeTag.push({ path, cacheKey });
} else {
if (existingTags.length === 0) {
// console.warn("Existing tags should not be empty when trying to remove");
}
del.push({ path, cacheKey });
}
}
const results = {
compute,
del,
addTag,
removeTag,
};
const globalCacheIndex = await GlobalCacheCodeBaseIndex.create();
return [
results,
async (items, resultType) => {
// Update tag catalog
markComplete(items, resultType);
// Update the global cache
const results: any = {
compute: [],
del: [],
addTag: [],
removeTag: [],
};
results[resultType] = items;
for await (const _ of globalCacheIndex.update(
tag,
results,
() => {},
repoName,
)) {
}
},
];
}
export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
private db: DatabaseConnection;
constructor(db: DatabaseConnection) {
this.db = db;
}
artifactId = "globalCache";
static async create(): Promise<GlobalCacheCodeBaseIndex> {
return new GlobalCacheCodeBaseIndex(await SqliteDb.get());
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
_: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const add = [...results.compute, ...results.addTag];
const remove = [...results.del, ...results.removeTag];
await Promise.all([
...add.map(({ cacheKey }) => {
return this.computeOrAddTag(cacheKey, tag);
}),
...remove.map(({ cacheKey }) => {
return this.deleteOrRemoveTag(cacheKey, tag);
}),
]);
yield { progress: 1, desc: "Done updating global cache", status: "done" };
}
private async computeOrAddTag(
cacheKey: string,
tag: IndexTag,
): Promise<void> {
await this.db.run(
"INSERT INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
cacheKey,
tag.directory,
tag.branch,
tag.artifactId,
);
}
private async deleteOrRemoveTag(
cacheKey: string,
tag: IndexTag,
): Promise<void> {
await this.db.run(
"DELETE FROM global_cache WHERE cacheKey = ? AND dir = ? AND branch = ? AND artifactId = ?",
cacheKey,
tag.directory,
tag.branch,
tag.artifactId,
);
}
}