Merge branch 'commandblock2-debug-context-provider' into preview

This commit is contained in:
Nate Sesti 2024-03-17 14:40:28 -07:00
commit 1e41ed6ca3
17 changed files with 462 additions and 79 deletions

View file

@ -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<ContextItem[]> {
// 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<ContextSubmenuItem[]> {
const threads = await args.ide.getAvailableThreads();
return threads.map((thread) => ({
id: `${thread.id}`,
title: thread.name,
description: `${thread.id}`,
}));
}
}
export default LocalsProvider;

View file

@ -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,

36
core/index.d.ts vendored
View file

@ -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<string, LLMReturnValue>;
streamChat(
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
options?: LLMFullCompletionOptions
): AsyncGenerator<ChatMessage, LLMReturnValue>;
chat(
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
options?: LLMFullCompletionOptions
): Promise<ChatMessage>;
countTokens(text: string): number;
@ -123,10 +123,10 @@ export interface CustomContextProvider {
type?: ContextProviderType;
getContextItems(
query: string,
extras: ContextProviderExtras,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs,
args: LoadSubmenuItemsArgs
) => Promise<ContextSubmenuItem[]>;
}
@ -141,7 +141,7 @@ export interface IContextProvider {
getContextItems(
query: string,
extras: ContextProviderExtras,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
@ -287,15 +287,15 @@ export interface CustomLLMWithOptionals {
streamCompletion?: (
prompt: string,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
) => AsyncGenerator<string>;
streamChat?: (
messages: ChatMessage[],
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
) => AsyncGenerator<string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
) => Promise<string[]>;
}
@ -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<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
getDebugLocals(threadIndex: number): Promise<string>;
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]>;
getAvailableThreads(): Promise<Thread[]>;
listWorkspaceContents(directory?: string): Promise<string[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
@ -355,12 +366,12 @@ export interface IDE {
showLines(
filepath: string,
startLine: number,
endLine: number,
endLine: number
): Promise<void>;
showDiff(
filepath: string,
newContents: string,
stepIndex: number,
stepIndex: number
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
@ -415,6 +426,7 @@ type ContextProviderName =
| "diff"
| "github"
| "terminal"
| "locals"
| "open"
| "google"
| "search"

View file

@ -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<string> {
return Promise.resolve("");
}
async getDebugLocals(threadIndex: number): Promise<string> {
return Promise.resolve("");
}
async getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]> {
return Promise.resolve([]);
}
async getAvailableThreads(): Promise<Thread[]> {
return Promise.resolve([]);
}
showLines(
filepath: string,
startLine: number,
endLine: number,
endLine: number
): Promise<void> {
return Promise.resolve();
}
@ -105,7 +117,7 @@ class FileSystemIde implements IDE {
showDiff(
filepath: string,
newContents: string,
stepIndex: number,
stepIndex: number
): Promise<void> {
return Promise.resolve();
}

View file

@ -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<any>,
private readonly request: (messageType: string, data: any) => Promise<any>
) {}
getDebugLocals(threadIndex: number): Promise<string> {
return this.request("getDebugLocals", { threadIndex });
}
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]> {
return this.request("getTopLevelCallStackSources", {
threadIndex,
stackDepth,
});
}
getAvailableThreads(): Promise<Thread[]> {
return this.request("getAvailableThreads", undefined);
}
getTags(artifactId: string): Promise<IndexTag[]> {
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<void> {
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<void> {
await this.request("showDiff", { filepath, newContents, stepIndex });
}

View file

@ -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];

View file

@ -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.

View file

@ -1043,6 +1043,7 @@
"enum": [
"diff",
"terminal",
"locals",
"open",
"google",
"search",

View file

@ -1043,6 +1043,7 @@
"enum": [
"diff",
"terminal",
"locals",
"open",
"google",
"search",

View file

@ -1043,6 +1043,7 @@
"enum": [
"diff",
"terminal",
"locals",
"open",
"google",
"search",

View file

@ -1159,6 +1159,7 @@
"enum": [
"diff",
"terminal",
"locals",
"open",
"google",
"search",

View file

@ -0,0 +1,71 @@
import * as vscode from "vscode";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { VsCodeIde } from "../ideProtocol";
export const threadStopped: Map<number, boolean> = 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;
}
}
},
};
},
});
}

View file

@ -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<boolean>("continue.indexingPaused") === true,
context.globalState.get<boolean>("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
)
);
}

View file

@ -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<string> {
return await this.ideUtils.getDebugLocals(threadIndex);
}
async getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]> {
return await this.ideUtils.getTopLevelCallStackSources(
threadIndex,
stackDepth
);
}
async getAvailableThreads(): Promise<Thread[]> {
return await this.ideUtils.getAvailableThreads();
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
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<void> {
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<void> {
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<void> {
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 = "";

View file

@ -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<vscode.Location[]> {
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<vscode.DocumentSymbol[]> {
return await vscode.commands.executeCommand(
"vscode.executeDocumentSymbolProvider",
uriFromFilePath(filepath),
uriFromFilePath(filepath)
);
}
async references(
filepath: string,
position: vscode.Position,
position: vscode.Position
): Promise<vscode.Location[]> {
return await vscode.commands.executeCommand(
"vscode.executeReferenceProvider",
uriFromFilePath(filepath),
position,
position
);
}
async foldingRanges(filepath: string): Promise<vscode.FoldingRange[]> {
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<string[]> {
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<string> {
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<Thread[]> {
const session = vscode.debug.activeDebugSession;
if (!session) return [];
const threadsResponse = await this._getThreads(session);
return threadsResponse.threads;
}
async getDebugLocals(threadIndex: number = 0): Promise<string> {
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<string[]> {
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<string> {
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<any | undefined> {
// Use the native git extension to get the branch name
const extension = vscode.extensions.getExtension("vscode.git");

View file

@ -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();
});

View file

@ -42,7 +42,28 @@ function useSubmenuContextProviders() {
}
useWebviewListener("refreshSubmenuItems", async (data) => {
setLoaded(true);
setLoaded(false);
});
useWebviewListener("updateSubmenuItems", async (data) => {
const minisearch = new MiniSearch<ContextSubmenuItem>({
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) {