diff --git a/core/context/providers/LocalsProvider.ts b/core/context/providers/LocalsProvider.ts new file mode 100644 index 000000000..9b5ea5dbc --- /dev/null +++ b/core/context/providers/LocalsProvider.ts @@ -0,0 +1,62 @@ +import { BaseContextProvider } from ".."; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../.."; + +class LocalsProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "locals", + displayTitle: "Locals", + description: "Reference the contents of the local variables", + type: "submenu", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras + ): Promise { + // Assuming that the query is a number + const localVariables = await extras.ide.getDebugLocals(Number(query)); + const threadIndex = Number(query); + const thread = (await extras.ide.getAvailableThreads()).find( + (thread) => thread.id == threadIndex + ); + const callStacksSources = await extras.ide.getTopLevelCallStackSources( + threadIndex, + this.options?.stackDepth || 3 + ); + const callStackContents = callStacksSources.reduce( + (acc, source, index) => + acc + `\n\ncall stack ${index}\n` + "```\n" + source + "\n```", + "" + ); + return [ + { + description: "The value, name and possibly type of the local variables", + content: + `This is a paused thread: ${thread?.name}\n` + + `Current local variable contents: \n${localVariables}.\n` + + `Current top level call stacks: ${callStackContents}`, + name: "Locals", + }, + ]; + } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs + ): Promise { + const threads = await args.ide.getAvailableThreads(); + + return threads.map((thread) => ({ + id: `${thread.id}`, + title: thread.name, + description: `${thread.id}`, + })); + } +} + +export default LocalsProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 978c8e94c..db2fd290f 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -16,6 +16,7 @@ import PostgresContextProvider from "./PostgresContextProvider"; import ProblemsContextProvider from "./ProblemsContextProvider"; import SearchContextProvider from "./SearchContextProvider"; import TerminalContextProvider from "./TerminalContextProvider"; +import LocalsProvider from "./LocalsProvider"; import URLContextProvider from "./URLContextProvider"; const Providers: (typeof BaseContextProvider)[] = [ @@ -24,6 +25,7 @@ const Providers: (typeof BaseContextProvider)[] = [ GitHubIssuesContextProvider, GoogleContextProvider, TerminalContextProvider, + LocalsProvider, URLContextProvider, OpenFilesContextProvider, HttpContextProvider, diff --git a/core/index.d.ts b/core/index.d.ts index abb337154..ed0336014 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -16,7 +16,7 @@ declare global { postIntellijMessage?: ( messageType: string, data: any, - messageIde: string, + messageIde: string ) => void; } } @@ -73,17 +73,17 @@ export interface ILLM extends LLMOptions { streamComplete( prompt: string, - options?: LLMFullCompletionOptions, + options?: LLMFullCompletionOptions ): AsyncGenerator; streamChat( messages: ChatMessage[], - options?: LLMFullCompletionOptions, + options?: LLMFullCompletionOptions ): AsyncGenerator; chat( messages: ChatMessage[], - options?: LLMFullCompletionOptions, + options?: LLMFullCompletionOptions ): Promise; countTokens(text: string): number; @@ -123,10 +123,10 @@ export interface CustomContextProvider { type?: ContextProviderType; getContextItems( query: string, - extras: ContextProviderExtras, + extras: ContextProviderExtras ): Promise; loadSubmenuItems?: ( - args: LoadSubmenuItemsArgs, + args: LoadSubmenuItemsArgs ) => Promise; } @@ -141,7 +141,7 @@ export interface IContextProvider { getContextItems( query: string, - extras: ContextProviderExtras, + extras: ContextProviderExtras ): Promise; loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; @@ -287,15 +287,15 @@ export interface CustomLLMWithOptionals { streamCompletion?: ( prompt: string, options: CompletionOptions, - fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise ) => AsyncGenerator; streamChat?: ( messages: ChatMessage[], options: CompletionOptions, - fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise ) => AsyncGenerator; listModels?: ( - fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise ) => Promise; } @@ -320,6 +320,11 @@ export class Problem { message: string; } +export class Thread { + name: string; + id: number; +} + export type IdeType = "vscode" | "jetbrains"; export interface IdeInfo { ideType: IdeType; @@ -340,6 +345,12 @@ export interface IDE { isTelemetryEnabled(): Promise; getUniqueId(): Promise; getTerminalContents(): Promise; + getDebugLocals(threadIndex: number): Promise; + getTopLevelCallStackSources( + threadIndex: number, + stackDepth: number + ): Promise; + getAvailableThreads(): Promise; listWorkspaceContents(directory?: string): Promise; listFolders(): Promise; getWorkspaceDirs(): Promise; @@ -355,12 +366,12 @@ export interface IDE { showLines( filepath: string, startLine: number, - endLine: number, + endLine: number ): Promise; showDiff( filepath: string, newContents: string, - stepIndex: number, + stepIndex: number ): Promise; getOpenFiles(): Promise; getPinnedFiles(): Promise; @@ -415,6 +426,7 @@ type ContextProviderName = | "diff" | "github" | "terminal" + | "locals" | "open" | "google" | "search" diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index f93aa8f80..3753c35d9 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,5 +1,5 @@ import * as fs from "fs"; -import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range } from ".."; +import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from ".."; import { getContinueGlobalPath } from "./paths"; @@ -37,10 +37,22 @@ class FileSystemIde implements IDE { getTerminalContents(): Promise { return Promise.resolve(""); } + async getDebugLocals(threadIndex: number): Promise { + return Promise.resolve(""); + } + async getTopLevelCallStackSources( + threadIndex: number, + stackDepth: number + ): Promise { + return Promise.resolve([]); + } + async getAvailableThreads(): Promise { + return Promise.resolve([]); + } showLines( filepath: string, startLine: number, - endLine: number, + endLine: number ): Promise { return Promise.resolve(); } @@ -105,7 +117,7 @@ class FileSystemIde implements IDE { showDiff( filepath: string, newContents: string, - stepIndex: number, + stepIndex: number ): Promise { return Promise.resolve(); } diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 6677f0508..cfcaded5a 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -1,9 +1,24 @@ -import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range } from ".."; +import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from ".."; export class MessageIde implements IDE { constructor( - private readonly request: (messageType: string, data: any) => Promise, + private readonly request: (messageType: string, data: any) => Promise ) {} + getDebugLocals(threadIndex: number): Promise { + return this.request("getDebugLocals", { threadIndex }); + } + getTopLevelCallStackSources( + threadIndex: number, + stackDepth: number + ): Promise { + return this.request("getTopLevelCallStackSources", { + threadIndex, + stackDepth, + }); + } + getAvailableThreads(): Promise { + return this.request("getAvailableThreads", undefined); + } getTags(artifactId: string): Promise { return this.request("getTags", artifactId); } @@ -48,7 +63,7 @@ export class MessageIde implements IDE { async showLines( filepath: string, startLine: number, - endLine: number, + endLine: number ): Promise { return await this.request("showLines", { filepath, startLine, endLine }); } @@ -93,7 +108,7 @@ export class MessageIde implements IDE { async showDiff( filepath: string, newContents: string, - stepIndex: number, + stepIndex: number ): Promise { await this.request("showDiff", { filepath, newContents, stepIndex }); } diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts index 220ed8be6..e2c36d337 100644 --- a/core/web/webviewProtocol.ts +++ b/core/web/webviewProtocol.ts @@ -1,10 +1,12 @@ import { ContextItemWithId, + ContextSubmenuItem, ContinueRcJson, DiffLine, IndexTag, Problem, Range, + Thread, } from ".."; import { RangeInFileWithContents } from "../commands/util"; @@ -25,7 +27,7 @@ export type IdeProtocol = { readFile: [{ filepath: string }, string]; showDiff: [ { filepath: string; newContents: string; stepIndex: number }, - void, + void ]; diffLine: [ { @@ -34,7 +36,7 @@ export type IdeProtocol = { startLine: number; endLine: number; }, - void, + void ]; getProblems: [{ filepath: string }, Problem[]]; getBranch: [{ dir: string }, string]; @@ -45,6 +47,12 @@ export type IdeProtocol = { getDiff: [undefined, string]; getWorkspaceConfigs: [undefined, ContinueRcJson[]]; getTerminalContents: [undefined, string]; + getDebugLocals: [{ threadIndex: Number }, string]; + getTopLevelCallStackSources: [ + { threadIndex: number; stackDepth: number }, + string[] + ]; + getAvailableThreads: [undefined, Thread[]]; isTelemetryEnabled: [undefined, boolean]; getUniqueId: [undefined, string]; getTags: [string, IndexTag[]]; @@ -60,7 +68,7 @@ export type WebviewProtocol = Protocol & workspacePaths: string[]; vscMachineId: string; vscMediaUrl: string; - }, + } ]; errorPopup: [{ message: string }, void]; @@ -86,7 +94,11 @@ export type ReverseWebviewProtocol = { historyIndex: number; item: ContextItemWithId; }, - void, + void + ]; + updateSubmenuItems: [ + { provider: string; submenuItems: ContextSubmenuItem[] }, + void ]; getDefaultModelTitle: [undefined, string]; newSessionWithPrompt: [{ prompt: string }, void]; diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 3328f2fbb..f8cb25db6 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -230,6 +230,19 @@ Type `@database` to reference table schemas you can use the drop-down or start t } ``` +### Debugger: Local Variables + +Type `@locals` to reference the contents of the local variables with top n level (defaulting to 3) of call stack for that thread. A dropdown will appear, allowing you to select a specific thread to see the local variables in that thread. + +```json +{ + "name": "locals", + "params": { + "stackDepth": 3 + } +} +``` + ### Requesting Context Providers Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new ContextProvider. diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 14fa444e1..e7080caf0 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1043,6 +1043,7 @@ "enum": [ "diff", "terminal", + "locals", "open", "google", "search", diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 14fa444e1..e7080caf0 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1043,6 +1043,7 @@ "enum": [ "diff", "terminal", + "locals", "open", "google", "search", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 14fa444e1..e7080caf0 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1043,6 +1043,7 @@ "enum": [ "diff", "terminal", + "locals", "open", "google", "search", diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index e21a1c0fb..44acd2362 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1159,6 +1159,7 @@ "enum": [ "diff", "terminal", + "locals", "open", "google", "search", diff --git a/extensions/vscode/src/debug/debug.ts b/extensions/vscode/src/debug/debug.ts new file mode 100644 index 000000000..15c374846 --- /dev/null +++ b/extensions/vscode/src/debug/debug.ts @@ -0,0 +1,71 @@ +import * as vscode from "vscode"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { VsCodeIde } from "../ideProtocol"; + +export const threadStopped: Map = new Map(); +// Arrays has better perf but you probably won't have thousands of threads in a single debug session + +export function registerDebugTracker( + webviewProtocol: VsCodeWebviewProtocol, + ide: VsCodeIde +) { + vscode.debug.registerDebugAdapterTrackerFactory("*", { + createDebugAdapterTracker(_session: vscode.DebugSession) { + const updateThreads = async () => { + webviewProtocol?.request("updateSubmenuItems", { + provider: "locals", + submenuItems: (await ide.getAvailableThreads()).map((thread) => ({ + id: `${thread.id}`, + title: thread.name, + description: `${thread.id}`, + })), + }); + }; + + return { + async onWillStopSession() { + threadStopped.clear(); + updateThreads(); + }, + async onDidSendMessage(message: any) { + if (message.type == "event") { + switch (message.event) { + case "continued": + case "stopped": + if (typeof message.body.threadId !== "undefined") + threadStopped.set( + Number(message.body.threadId), + message.event == "stopped" + ); + + if (message.body.allThreadsStopped) + threadStopped.forEach((_, key) => + threadStopped.set(key, true) + ); + + if (message.body.allThreadsContinued) + threadStopped.forEach((_, key) => + threadStopped.set(key, false) + ); + + updateThreads(); + break; + + case "thread": + if (message.body.reason == "exited") + threadStopped.delete(Number(message.body.threadId)); + else if (message.body.reason == "started") + threadStopped.set(Number(message.body.threadId), false); + // somehow the threadId does not respect the specification in my vscodium (debugging C++) + // expecting a number but got a string instead + break; + + default: + break; + } + } + }, + }; + }, + }); +} diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index 36f8cafc4..9c57b884e 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -14,6 +14,7 @@ import { registerAllCodeLensProviders } from "../lang-server/codeLens"; import { setupRemoteConfigSync } from "../stubs/activation"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { registerDebugTracker } from "../debug/debug"; export class VsCodeExtension { private configHandler: ConfigHandler; @@ -47,26 +48,26 @@ export class VsCodeExtension { // Config Handler with output channel const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion", + "Continue - LLM Prompt/Completion" ); this.configHandler = new ConfigHandler( this.ide, Promise.resolve(ideSettings), async (log: string) => { outputChannel.appendLine( - "==========================================================================", + "==========================================================================" ); outputChannel.appendLine( - "==========================================================================", + "==========================================================================" ); outputChannel.append(log); }, - () => this.webviewProtocol?.request("configUpdate", undefined), + () => this.webviewProtocol?.request("configUpdate", undefined) ); this.configHandler.reloadConfig(); this.verticalDiffManager = new VerticalPerLineDiffManager( - this.configHandler, + this.configHandler ); this.extensionContext = context; this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); @@ -76,7 +77,7 @@ export class VsCodeExtension { this.ide, this.windowId, this.extensionContext, - this.verticalDiffManager, + this.verticalDiffManager ); setupRemoteConfigSync( @@ -90,14 +91,14 @@ export class VsCodeExtension { this.sidebar, { webviewOptions: { retainContextWhenHidden: true }, - }, - ), + } + ) ); this.webviewProtocol = this.sidebar.webviewProtocol; // Indexing + pause token const indexingPauseToken = new PauseToken( - context.globalState.get("continue.indexingPaused") === true, + context.globalState.get("continue.indexingPaused") === true ); this.webviewProtocol.on("index/setPaused", (msg) => { context.globalState.update("continue.indexingPaused", msg.data); @@ -108,14 +109,14 @@ export class VsCodeExtension { this.indexer = new CodebaseIndexer( this.configHandler, this.ide, - indexingPauseToken, + indexingPauseToken ); // CodeLens registerAllCodeLensProviders( context, this.diffManager, - this.verticalDiffManager.editorToVerticalDiffCodeLens, + this.verticalDiffManager.editorToVerticalDiffCodeLens ); // Tab autocomplete @@ -130,9 +131,9 @@ export class VsCodeExtension { new ContinueCompletionProvider( this.configHandler, this.ide, - this.tabAutocompleteModel, - ), - ), + this.tabAutocompleteModel + ) + ) ); // Commands @@ -143,9 +144,11 @@ export class VsCodeExtension { this.sidebar, this.configHandler, this.diffManager, - this.verticalDiffManager, + this.verticalDiffManager ); + registerDebugTracker(this.webviewProtocol, this.ide); + // Indexing this.ide.getWorkspaceDirs().then((dirs) => this.refreshCodebaseIndex(dirs)); @@ -192,7 +195,7 @@ export class VsCodeExtension { } }); } - }), + }) ); // Register a content provider for the readonly virtual documents @@ -210,8 +213,8 @@ export class VsCodeExtension { context.subscriptions.push( vscode.workspace.registerTextDocumentContentProvider( VsCodeExtension.continueVirtualDocumentScheme, - documentContentProvider, - ), + documentContentProvider + ) ); } diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index ea8edcc1d..a20e53022 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -1,6 +1,6 @@ import * as child_process from "child_process"; import { exec } from "child_process"; -import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range } from "core"; +import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from "core"; import { getContinueGlobalPath } from "core/util/paths"; import * as path from "path"; import * as vscode from "vscode"; @@ -47,8 +47,8 @@ class VsCodeIde implements IDE { filepath, new vscode.Range( new vscode.Position(range.start.line, range.start.character), - new vscode.Position(range.end.line, range.end.character), - ), + new vscode.Position(range.end.line, range.end.character) + ) ); } @@ -60,7 +60,7 @@ class VsCodeIde implements IDE { files.map(async (file) => { let stat = await vscode.workspace.fs.stat(uriFromFilePath(file)); pathToLastModified[file] = stat.mtime; - }), + }) ); return pathToLastModified; @@ -89,6 +89,23 @@ class VsCodeIde implements IDE { return await this.ideUtils.getTerminalContents(1); } + async getDebugLocals(threadIndex: number): Promise { + return await this.ideUtils.getDebugLocals(threadIndex); + } + + async getTopLevelCallStackSources( + threadIndex: number, + stackDepth: number + ): Promise { + return await this.ideUtils.getTopLevelCallStackSources( + threadIndex, + stackDepth + ); + } + async getAvailableThreads(): Promise { + return await this.ideUtils.getAvailableThreads(); + } + async listWorkspaceContents(directory?: string): Promise { if (directory) { return await this.ideUtils.getDirectoryContents(directory, true); @@ -96,7 +113,7 @@ class VsCodeIde implements IDE { const contents = await Promise.all( this.ideUtils .getWorkspaceDirectories() - .map((dir) => this.ideUtils.getDirectoryContents(dir, true)), + .map((dir) => this.ideUtils.getDirectoryContents(dir, true)) ); return contents.flat(); } @@ -111,7 +128,7 @@ class VsCodeIde implements IDE { for (const [filename, type] of files) { if (type === vscode.FileType.File && filename === ".continuerc.json") { const contents = await this.ideUtils.readFile( - vscode.Uri.joinPath(workspaceDir, filename).fsPath, + vscode.Uri.joinPath(workspaceDir, filename).fsPath ); configs.push(JSON.parse(contents)); } @@ -129,7 +146,7 @@ class VsCodeIde implements IDE { directory, [], false, - undefined, + undefined )) { allDirs.push(dir); } @@ -149,7 +166,7 @@ class VsCodeIde implements IDE { async writeFile(path: string, contents: string): Promise { await vscode.workspace.fs.writeFile( vscode.Uri.file(path), - Buffer.from(contents), + Buffer.from(contents) ); } @@ -164,11 +181,11 @@ class VsCodeIde implements IDE { async showLines( filepath: string, startLine: number, - endLine: number, + endLine: number ): Promise { const range = new vscode.Range( new vscode.Position(startLine, 0), - new vscode.Position(endLine, 0), + new vscode.Position(endLine, 0) ); openEditorAndRevealRange(filepath, range).then(() => { // TODO: Highlight lines @@ -202,7 +219,7 @@ class VsCodeIde implements IDE { async showDiff( filepath: string, newContents: string, - stepIndex: number, + stepIndex: number ): Promise { await this.diffManager.writeDiff(filepath, newContents, stepIndex); } @@ -227,10 +244,10 @@ class VsCodeIde implements IDE { "@vscode", "ripgrep", "bin", - "rg", + "rg" ), ["-i", "-C", "2", `"${query}"`, "."], - { cwd: dir }, + { cwd: dir } ); let output = ""; diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index cf47c7e19..3004e9b4c 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -1,4 +1,4 @@ -import { FileEdit, RangeInFile } from "core"; +import { FileEdit, RangeInFile, Thread } from "core"; import path from "path"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/vscodeExtension"; @@ -15,6 +15,8 @@ import { openEditorAndRevealRange, uriFromFilePath, } from "./vscode"; +import { threadStopped } from "../debug/debug"; + const util = require("util"); const asyncExec = util.promisify(require("child_process").exec); @@ -23,12 +25,12 @@ export class VsCodeIdeUtils { async gotoDefinition( filepath: string, - position: vscode.Position, + position: vscode.Position ): Promise { const locations: vscode.Location[] = await vscode.commands.executeCommand( "vscode.executeDefinitionProvider", uriFromFilePath(filepath), - position, + position ); return locations; } @@ -36,25 +38,25 @@ export class VsCodeIdeUtils { async documentSymbol(filepath: string): Promise { return await vscode.commands.executeCommand( "vscode.executeDocumentSymbolProvider", - uriFromFilePath(filepath), + uriFromFilePath(filepath) ); } async references( filepath: string, - position: vscode.Position, + position: vscode.Position ): Promise { return await vscode.commands.executeCommand( "vscode.executeReferenceProvider", uriFromFilePath(filepath), - position, + position ); } async foldingRanges(filepath: string): Promise { return await vscode.commands.executeCommand( "vscode.executeFoldingRangeProvider", - uriFromFilePath(filepath), + uriFromFilePath(filepath) ); } @@ -78,12 +80,12 @@ export class VsCodeIdeUtils { rangeInFile.range.start.line, rangeInFile.range.start.character, rangeInFile.range.end.line, - rangeInFile.range.end.character, + rangeInFile.range.end.character ); const editor = await openEditorAndRevealRange( rangeInFile.filepath, range, - vscode.ViewColumn.One, + vscode.ViewColumn.One ); if (editor) { const decorationType = vscode.window.createTextEditorDecorationType({ @@ -98,7 +100,7 @@ export class VsCodeIdeUtils { cursorDisposable.dispose(); editor.setDecorations(decorationType, []); } - }, + } ); setTimeout(() => { @@ -121,9 +123,9 @@ export class VsCodeIdeUtils { edit.range.start.line, edit.range.start.character, edit.range.end.line, - edit.range.end.character, + edit.range.end.character ), - edit.replacement, + edit.replacement ); } @@ -132,7 +134,7 @@ export class VsCodeIdeUtils { const panel = vscode.window.createWebviewPanel( "continue.continueGUIView", "Continue", - vscode.ViewColumn.One, + vscode.ViewColumn.One ); // panel.webview.html = this.sidebar.getSidebarContent( // extensionContext, @@ -163,8 +165,8 @@ export class VsCodeIdeUtils { vscode.Uri.parse( `${ VsCodeExtension.continueVirtualDocumentScheme - }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`, - ), + }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}` + ) ) .then((doc) => { vscode.window.showTextDocument(doc, { preview: false }); @@ -246,7 +248,7 @@ export class VsCodeIdeUtils { async getDirectoryContents( directory: string, - recursive: boolean, + recursive: boolean ): Promise { if (!recursive) { return ( @@ -271,7 +273,7 @@ export class VsCodeIdeUtils { gitRoot ?? directory, [], true, - gitRoot === directory ? undefined : onlyThisDirectory, + gitRoot === directory ? undefined : onlyThisDirectory )) { allFiles.push(file); } @@ -322,16 +324,18 @@ export class VsCodeIdeUtils { async readRangeInFile( filepath: string, - range: vscode.Range, + range: vscode.Range ): Promise { const contents = new TextDecoder().decode( - await vscode.workspace.fs.readFile(vscode.Uri.file(filepath)), + await vscode.workspace.fs.readFile(vscode.Uri.file(filepath)) ); const lines = contents.split("\n"); return ( lines.slice(range.start.line, range.end.line).join("\n") + "\n" + - lines[range.end.line].slice(0, range.end.character) + lines[ + range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 + ].slice(0, range.end.character) ); } @@ -339,20 +343,20 @@ export class VsCodeIdeUtils { const tempCopyBuffer = await vscode.env.clipboard.readText(); if (commands < 0) { await vscode.commands.executeCommand( - "workbench.action.terminal.selectAll", + "workbench.action.terminal.selectAll" ); } else { for (let i = 0; i < commands; i++) { await vscode.commands.executeCommand( - "workbench.action.terminal.selectToPreviousCommand", + "workbench.action.terminal.selectToPreviousCommand" ); } } await vscode.commands.executeCommand( - "workbench.action.terminal.copySelection", + "workbench.action.terminal.copySelection" ); await vscode.commands.executeCommand( - "workbench.action.terminal.clearSelection", + "workbench.action.terminal.clearSelection" ); const terminalContents = await vscode.env.clipboard.readText(); await vscode.env.clipboard.writeText(tempCopyBuffer); @@ -364,6 +368,129 @@ export class VsCodeIdeUtils { return terminalContents; } + private async _getThreads(session: vscode.DebugSession) { + const threadsResponse = await session.customRequest("threads"); + const threads = threadsResponse.threads.filter((thread: any) => + threadStopped.get(thread.id) + ); + threads.sort((a: any, b: any) => a.id - b.id); + threadsResponse.threads = threads; + + return threadsResponse; + } + + async getAvailableThreads(): Promise { + const session = vscode.debug.activeDebugSession; + if (!session) return []; + + const threadsResponse = await this._getThreads(session); + return threadsResponse.threads; + } + + async getDebugLocals(threadIndex: number = 0): Promise { + const session = vscode.debug.activeDebugSession; + + if (!session) { + vscode.window.showWarningMessage( + "No active debug session found, therefore no debug context will be provided for the llm." + ); + return ""; + } + + const variablesResponse = await session + .customRequest("stackTrace", { + threadId: threadIndex, + startFrame: 0, + }) + .then((traceResponse) => + session.customRequest("scopes", { + frameId: traceResponse.stackFrames[0].id, + }) + ) + .then((scopesResponse) => + session.customRequest("variables", { + variablesReference: scopesResponse.scopes[0].variablesReference, + }) + ); + + const variableContext = variablesResponse.variables + .filter((variable: any) => variable.type !== "global") + .reduce( + (acc: any, variable: any) => + `${acc}\nname: ${variable.name}, type: ${variable.type}, ` + + `value: ${variable.value}`, + "" + ); + + return variableContext; + } + + async getTopLevelCallStackSources( + threadIndex: number, + stackDepth: number = 3 + ): Promise { + const session = vscode.debug.activeDebugSession; + if (!session) return []; + + const sourcesPromises = await session + .customRequest("stackTrace", { + threadId: threadIndex, + startFrame: 0, + }) + .then((traceResponse) => + traceResponse.stackFrames + .slice(0, stackDepth) + .map(async (stackFrame: any) => { + const scopeResponse = await session.customRequest("scopes", { + frameId: stackFrame.id, + }); + + const scope = scopeResponse.scopes[0]; + + return await this.retrieveSource(scope.source ? scope : stackFrame); + }) + ); + + return Promise.all(sourcesPromises); + } + + private async retrieveSource(sourceContainer: any): Promise { + if (!sourceContainer.source) return ""; + + const sourceRef = sourceContainer.source.sourceReference; + if (sourceRef && sourceRef > 0) { + // according to the spec, source might be ony available in a debug session + // not yet able to test this branch + const sourceResponse = + await vscode.debug.activeDebugSession?.customRequest("source", { + source: sourceContainer.source, + sourceReference: sourceRef, + }); + return sourceResponse.content; + } else if (sourceContainer.line && sourceContainer.endLine) { + return await this.readRangeInFile( + sourceContainer.source.path, + new vscode.Range( + sourceContainer.line - 1, // The line number from scope response starts from 1 + sourceContainer.column, + sourceContainer.endLine - 1, + sourceContainer.endColumn + ) + ); + } else if (sourceContainer.line) + // fall back to 5 line of context + return await this.readRangeInFile( + sourceContainer.source.path, + new vscode.Range( + sourceContainer.line - 3, + 0, + sourceContainer.line + 2, + 0 + ) + ); + else return "unavailable"; + } + private async _getRepo(forDirectory: vscode.Uri): Promise { // Use the native git extension to get the branch name const extension = vscode.extensions.getExtension("vscode.git"); diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index b50e4b99f..41697bccd 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -161,6 +161,18 @@ export class VsCodeWebviewProtocol { this.on("getTerminalContents", async (msg) => { return await ide.getTerminalContents(); }); + this.on("getDebugLocals", async (msg) => { + return await ide.getDebugLocals(Number(msg.data.threadIndex)); + }); + this.on("getAvailableThreads", async (msg) => { + return await ide.getAvailableThreads(); + }); + this.on("getTopLevelCallStackSources", async (msg) => { + return await ide.getTopLevelCallStackSources( + msg.data.threadIndex, + msg.data.stackDepth + ); + }); this.on("listWorkspaceContents", async (msg) => { return await ide.listWorkspaceContents(); }); diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index c992b4632..b0097f3ce 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -42,7 +42,28 @@ function useSubmenuContextProviders() { } useWebviewListener("refreshSubmenuItems", async (data) => { - setLoaded(true); + setLoaded(false); + }); + + useWebviewListener("updateSubmenuItems", async (data) => { + const minisearch = new MiniSearch({ + fields: ["title", "description"], + storeFields: ["id", "title", "description"], + }); + + minisearch.addAll(data.submenuItems); + + setMinisearches((prev) => ({ ...prev, [data.provider]: minisearch })); + + if (data.provider === "file") { + const openFiles = await getOpenFileItems(); + setFallbackResults((prev) => ({ ...prev, file: openFiles })); + } else { + setFallbackResults((prev) => ({ + ...prev, + [data.provider]: data.submenuItems.slice(0, 6), + })); + } }); function addItem(providerTitle: string, item: ContextSubmenuItem) {