continue-custom/core/indexing/CodebaseIndexer.ts
Nate Sesti f72b00d38d
Dev (#1678)
* Fix an issue where CMD+K does not clear the terminal when the terminal has focus (#1671)

On MacOS, ⌘+K is bound, by default, to Terminal:Clear. Without this
change ⌘+K does not clear the terminal but instead iniates a chord
sequence and waits for the next stroke of the chord.

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* Change treeSitter to cache the Language objects it loads from wasm (#1672)

Without this change, for a repository with 600 typescript files, the
indexer would fail to finish correctly and there would be many of the
following errors in the webview console log:

'Unable to load language for file ${path} RuntimeError: table index is out of bounds'

The following bash will create a repo that reproduces the problem:

current_path="."

for ((i=1; i<=20; i++)); do
    new_folder="folder-$i"
    mkdir -p "$current_path/$new_folder"
    current_path="$current_path/$new_folder"

    for ((a=1; a<=30; a++)); do
      head -c 10000 /dev/urandom | base64 > "$current_path/file-$a.ts"
    done
done

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* acknowledge sourcemap flag in esbuild.js

* don't run jetbrains-release.yaml on vscode releases

* further testing for walkDir

* chore: add telemetry to commands (#1673)

* test: Add basic unit test to baseLLM (#1668)

* update version

* test: Add basic unit test to baseLLM

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: inimaz <imaz@ai-verse.com>

* feat: add Quick Actions CodeLens feature (#1674)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

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

* ✨ use and cache imports for autocomplete

* fix tsc

* add voyage rerank-1

* import Handlebars

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* 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

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

* small UI tweaks

* media query

* feat: add best experience onboarding

* small fixes

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

* feat: add free trial card to onboarding

* add import

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

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* manually implement stop tokens for hf inference api

* chore: onboarding metrics (#1626)

* fix: pageview tracking

* feat: add onboarding telemetry

* create single `onboardingStatus` type

* improved var naming

* remove console logs

* fix windows performance issue

* rename vscodeExtension.ts

* migration of onboarding variables

* "stash" instead of "delete" in indexing progress

* fix preview.yaml

* also fix main.yaml

* Update troubleshooting.md (#1637)

* feat: add quick actions

* Update index.d.ts

* quick actions mvp

* update docs

* subscribe to vscode change settings

* Update commands.ts

* cleanup

* Update quick-actions.md

* Update VerticalPerLineCodeLensProvider.ts

* resolve feedback

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>

* chore: add `isCommandEvent` to command telemetry (#1675)

* chore: add `isCommandEvent` to command telemetry

* Update commands.ts

* Nate/better retrieval (#1677)

* deduplicatearray tests

* break out separate retrieval pipelines

* IConfigHandler

* tests for codebase indexer

* better .continueignore for continue

* indexing fixes

* ignore .gitignore and .continueignore when indexing

* retrieval pipeline improvements

* fix formatting err in out .continueignore

* add necessary filter to lance_db_cache

* update package.json version

---------

Co-authored-by: Rob Leidle <rleidle@gmail.com>
Co-authored-by: Rob Leidle <rleidle@tesla.com>
Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com>
Co-authored-by: inimaz <imaz@ai-verse.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
2024-07-05 23:20:28 -07:00

204 lines
6 KiB
TypeScript

import { IConfigHandler } from "../config/IConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
export class PauseToken {
constructor(private _paused: boolean) {}
set paused(value: boolean) {
this._paused = value;
}
get paused(): boolean {
return this._paused;
}
}
export class CodebaseIndexer {
constructor(
private readonly configHandler: IConfigHandler,
private readonly ide: IDE,
private readonly pauseToken: PauseToken,
private readonly continueServerClient: IContinueServerClient,
) {}
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const indexes = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
),
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
];
return indexes;
}
async *refresh(
workspaceDirs: string[],
abortSignal: AbortSignal,
): AsyncGenerator<IndexingProgressUpdate> {
let progress = 0;
if (workspaceDirs.length === 0) {
yield {
progress,
desc: "Nothing to index",
status: "disabled",
};
return;
}
const config = await this.configHandler.loadConfig();
if (config.disableIndexing) {
yield {
progress,
desc: "Indexing is disabled in config.json",
status: "disabled",
};
return;
} else {
yield {
progress,
desc: "Starting indexing",
status: "loading",
};
}
const indexesToBuild = await this.getIndexesToBuild();
let completedDirs = 0;
const totalRelativeExpectedTime = indexesToBuild.reduce(
(sum, index) => sum + index.relativeExpectedTime,
0,
);
// Wait until Git Extension has loaded to report progress
// so we don't appear stuck at 0% while waiting
await this.ide.getRepoName(workspaceDirs[0]);
yield {
progress,
desc: "Starting indexing...",
status: "loading",
};
for (const directory of workspaceDirs) {
const files = await walkDir(directory, this.ide);
const stats = await this.ide.getLastModified(files);
const branch = await this.ide.getBranch(directory);
const repoName = await this.ide.getRepoName(directory);
let completedRelativeExpectedTime = 0;
for (const codebaseIndex of indexesToBuild) {
// TODO: IndexTag type should use repoName rather than directory
const tag: IndexTag = {
directory,
branch,
artifactId: codebaseIndex.artifactId,
};
const [results, markComplete] = await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
try {
for await (let {
progress: indexProgress,
desc,
} of codebaseIndex.update(tag, results, markComplete, repoName)) {
// Handle pausing in this loop because it's the only one really taking time
if (abortSignal.aborted) {
yield {
progress: 1,
desc: "Indexing cancelled",
status: "disabled",
};
return;
}
if (this.pauseToken.paused) {
yield {
progress,
desc: "Paused",
status: "paused",
};
while (this.pauseToken.paused) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
progress =
(completedDirs +
(completedRelativeExpectedTime +
Math.min(1.0, indexProgress) *
codebaseIndex.relativeExpectedTime) /
totalRelativeExpectedTime) /
workspaceDirs.length;
yield {
progress,
desc,
status: "indexing",
};
}
completedRelativeExpectedTime += codebaseIndex.relativeExpectedTime;
yield {
progress:
(completedDirs +
completedRelativeExpectedTime / totalRelativeExpectedTime) /
workspaceDirs.length,
desc: "Completed indexing " + codebaseIndex.artifactId,
status: "indexing",
};
} catch (e: any) {
let errMsg = `${e}`;
const errorRegex =
/Invalid argument error: Values length (\d+) is less than the length \((\d+)\) multiplied by the value size \(\d+\)/;
const match = e.message.match(errorRegex);
if (match) {
const [_, valuesLength, expectedLength] = match;
errMsg = `Generated embedding had length ${valuesLength} but was expected to be ${expectedLength}. This may be solved by deleting ~/.continue/index and refreshing the window to re-index.`;
}
yield {
progress: 0,
desc: errMsg,
status: "failed",
};
console.warn(
`Error updating the ${codebaseIndex.artifactId} index: ${e}`,
);
return;
}
}
completedDirs++;
progress = completedDirs / workspaceDirs.length;
yield {
progress,
desc: "Indexing Complete",
status: "done",
};
}
}
}