From e7d3625b73c85f98d5582860dd4f180dccc51e3f Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 24 Jul 2025 19:09:55 +0530 Subject: [PATCH 01/44] fix: case when reranker returns invalid scores array --- core/context/providers/DocsContextProvider.ts | 10 +++++++--- core/llm/llms/Voyage.ts | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 0f87a3f61..5c8e0af1b 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -43,9 +43,13 @@ class DocsContextProvider extends BaseContextProvider { try { const scores = await reranker.rerank(fullInput, chunksCopy); - chunksCopy.sort( - (a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)], - ); + if (Array.isArray(scores)) { + // reranker model has returned a valid array + chunksCopy.sort( + (a, b) => + scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)], + ); + } chunksCopy = chunksCopy.splice( 0, diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index fe08d8b1d..94c344a56 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,7 +1,21 @@ -import { Chunk, LLMOptions } from "../../index.js"; +import { z } from "zod"; +import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; +/**used to check a valid response from voyage is received + * reference: https://docs.voyageai.com/reference/reranker-api + */ +const VoyageRerankSuccessResponseSchema = z.object({ + data: z.array( + z.object({ + index: z.number(), + relevance_score: z.number(), + document: z.string(), + }), + ), +}); + class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { @@ -36,6 +50,9 @@ class Voyage extends OpenAI { const data = (await resp.json()) as { data: Array<{ index: number; relevance_score: number }>; }; + + VoyageRerankSuccessResponseSchema.parse(data); + const results = data.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } From 2473a3993f0e2cac1740061146e3d0246668bf74 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 25 Jul 2025 19:11:55 +0530 Subject: [PATCH 02/44] handle mcp authenticated token - spin up a local server to handle redirects - create an MCPOauth class to handle oauths --- core/config/yaml/loadYaml.ts | 1 + core/context/mcp/MCPConnection.ts | 21 +++- core/context/mcp/MCPManagerSingleton.ts | 10 +- core/context/mcp/MCPOauth.ts | 119 ++++++++++++++++++ .../vscode/src/extension/VsCodeExtension.ts | 6 + 5 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 core/context/mcp/MCPOauth.ts diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 4f1a1632f..e7e6bb0c3 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -440,6 +440,7 @@ async function configYamlToContinueConfig(options: { timeout: server.connectionTimeout, })), false, + { ide }, ); return { config: continueConfig, errors: localErrors }; diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 3d39a0c7c..71d1d1e62 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -7,6 +7,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { + IDE, MCPConnectionStatus, MCPOptions, MCPPrompt, @@ -16,6 +17,7 @@ import { MCPTool, } from "../.."; import { getEnvPathFromUserShell } from "../../util/shellPath"; +import { performAuth } from "./MCPOauth"; const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds @@ -30,6 +32,10 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +export type MCPExtras = { + ide: IDE; +}; + class MCPConnection { public client: Client; public abortController: AbortController; @@ -46,7 +52,10 @@ class MCPConnection { stderr: "", }; - constructor(public options: MCPOptions) { + constructor( + public options: MCPOptions, + public extras?: MCPExtras, + ) { // Don't construct transport in constructor to avoid blocking this.transport = {} as Transport; // Will be set in connectClient @@ -106,6 +115,16 @@ class MCPConnection { this.abortController.abort(); this.abortController = new AbortController(); + if (this.options.transport.type === "sse") { + // currently support oauth for sse transports only + console.log("debug1 extras", this.extras); + performAuth(this.options.transport.url, this.extras?.ide!).then( + (result) => { + console.log("debug1 result", result); + }, + ); + } + this.connectionPromise = Promise.race([ // If aborted by a refresh or other, cancel and don't do anything new Promise((resolve) => { diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 7eafa1564..515fdecc7 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -6,7 +6,7 @@ import { StdioOptions, TransportOptions, } from "../.."; -import MCPConnection from "./MCPConnection"; +import MCPConnection, { MCPExtras } from "./MCPConnection"; export class MCPManagerSingleton { private static instance: MCPManagerSingleton; @@ -48,7 +48,11 @@ export class MCPManagerSingleton { this.connections.delete(id); } - setConnections(servers: MCPOptions[], forceRefresh: boolean) { + setConnections( + servers: MCPOptions[], + forceRefresh: boolean, + extras?: MCPExtras, + ) { let refresh = false; // Remove any connections that are no longer in config @@ -75,7 +79,7 @@ export class MCPManagerSingleton { servers.forEach((server) => { if (!this.connections.has(server.id)) { refresh = true; - this.connections.set(server.id, new MCPConnection(server)); + this.connections.set(server.id, new MCPConnection(server, extras)); } else { const conn = this.connections.get(server.id); if (conn) { diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts new file mode 100644 index 000000000..1a961feb2 --- /dev/null +++ b/core/context/mcp/MCPOauth.ts @@ -0,0 +1,119 @@ +import { + OAuthClientProvider, + auth, +} from "@modelcontextprotocol/sdk/client/auth.js"; +import { + OAuthClientInformationFull, + OAuthTokens, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { IDE } from "../.."; + +import http from "http"; +import url from "url"; + +const PORT = 3000; + +const server = http.createServer((req, res) => { + // TODO: instead of sending bad requests for each case, try catch handle the bad request at the end of the function + if (!req.url) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end("Bad Request"); + return; + } + const parsedUrl = url.parse(req.url, true); + + if (parsedUrl.pathname === "/") { + const query = new URLSearchParams( + parsedUrl.query as Record, + ).toString(); + if (!query) { + console.error("no query params found!"); + } + const redirectUrl = `vscode://continue.Continue${query ? "?" + query : ""}`; + + res.writeHead(302, { + Location: redirectUrl, + }); + res.end(); + } else { + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("Not Found"); + } +}); + +server.listen(PORT, () => { + console.log(`Server running at http://localhost:${PORT}/`); +}); + +class MCPConnectionOauthProvider implements OAuthClientProvider { + constructor( + public oauthServerUrl: string, + private ide: IDE, + ) {} + + get redirectUrl() { + return "http://localhost:3000"; // TODO: this has to be a hub url or should we spin up a server? + } + + get clientMetadata() { + return { + redirect_uris: [this.redirectUrl], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_name: "Continue Dev, Inc", // get this from package.json? + client_uri: "https://continue.dev", // get this from package.json? + }; + } + + saveClientInformation(clientInformation: OAuthClientInformationFull) {} + + async clientInformation() { + return undefined; + } + + async tokens() { + return undefined; + } + + saveTokens(tokens: OAuthTokens) {} + + codeVerifier(): string | Promise { + return ""; + } + + saveCodeVerifier(codeVerifier: string) {} + + clear() {} + + async redirectToAuthorization(authorizationUrl: URL) { + console.log("debug1 redirecting to url", authorizationUrl); + // TODO here the url needs to be sent to the extension + this.ide.openUrl(authorizationUrl.toString()); + } +} + +export async function performAuth(mcpServerUrl: string, ide: IDE) { + const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + await auth(authProvider, { serverUrl: mcpServerUrl }); + + // full uri is of the format "https://localhost:3000/?code=712020%253Abed80c83-1041-49e0-99b5-5d4f9f8aa538%3ACSlICEGG3rzCQhla%3AHA0oJYDjijnNE8nCoADpZsSp8jr7cCSZ" + // const input = await ide.showInput({ + // prompt: "Paste the auth code here", + // }); + // const result = await auth(authProvider, { + // serverUrl: mcpServerUrl, + // authorizationCode: input, + // }); + // if (result === "AUTHORIZED") { + // void ide.showToast( + // "info", + // `Authenticated with ${new URL(mcpServerUrl).hostname} MCP server`, + // ); + // } else { + // void ide.showToast( + // "error", + // `Failed to authenticate with ${new URL(mcpServerUrl).hostname} MCP server`, + // ); + // } +} diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index f0137bd0c..fe624179a 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -72,6 +72,12 @@ export class VsCodeExtension { constructor(context: vscode.ExtensionContext) { // Register auth provider this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler); + + // TODO: this should practically only start listening when user has started an mcp oauth flow. how to do this? + this.uriHandler.event((uri) => { + console.log("debug1 uri was", uri); + }); + void this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); From 35a58c0c9d5933d044208f397ff24936f3c9ab4b Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 28 Jul 2025 12:26:03 +0530 Subject: [PATCH 03/44] handle authentication callback - add storage to store tokens - in mcp connection, add headers --- core/context/mcp/MCPConnection.ts | 18 +- core/context/mcp/MCPOauth.ts | 180 +++++++++++++----- core/core.ts | 5 + core/protocol/core.ts | 6 + core/protocol/passThrough.ts | 1 + core/protocol/webview.ts | 5 + core/util/GlobalContext.ts | 13 ++ .../vscode/src/extension/VsCodeExtension.ts | 13 +- 8 files changed, 187 insertions(+), 54 deletions(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 71d1d1e62..71412d476 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -17,7 +17,7 @@ import { MCPTool, } from "../.."; import { getEnvPathFromUserShell } from "../../util/shellPath"; -import { performAuth } from "./MCPOauth"; +import { getOauthToken } from "./MCPOauth"; const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds @@ -118,11 +118,19 @@ class MCPConnection { if (this.options.transport.type === "sse") { // currently support oauth for sse transports only console.log("debug1 extras", this.extras); - performAuth(this.options.transport.url, this.extras?.ide!).then( - (result) => { - console.log("debug1 result", result); - }, + if (!this.options.transport.requestOptions) { + this.options.transport.requestOptions = { + headers: {}, + }; + } + const accessToken = await getOauthToken( + this.options.transport.url, + this.extras?.ide!, ); + this.options.transport.requestOptions.headers = { + ...this.options.transport.requestOptions.headers, + Authorization: `Bearer ${accessToken}`, + }; } this.connectionPromise = Promise.race([ diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 1a961feb2..6e1544533 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -4,55 +4,77 @@ import { } from "@modelcontextprotocol/sdk/client/auth.js"; import { OAuthClientInformationFull, + OAuthClientInformationSchema, OAuthTokens, + OAuthTokensSchema, } from "@modelcontextprotocol/sdk/shared/auth.js"; import { IDE } from "../.."; import http from "http"; import url from "url"; +import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; +import { IMessenger } from "../../protocol/messenger"; +import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; + +export type MCPOauthState = "login" | "authenticating" | "disconnect"; const PORT = 3000; const server = http.createServer((req, res) => { - // TODO: instead of sending bad requests for each case, try catch handle the bad request at the end of the function - if (!req.url) { - res.writeHead(400, { "Content-Type": "text/plain" }); - res.end("Bad Request"); - return; - } - const parsedUrl = url.parse(req.url, true); + try { + if (!req.url) { + throw new Error("no url found"); + } + const parsedUrl = url.parse(req.url, true); + if (parsedUrl.pathname !== "/") { + throw new Error("path is not index"); + } - if (parsedUrl.pathname === "/") { const query = new URLSearchParams( parsedUrl.query as Record, ).toString(); if (!query) { - console.error("no query params found!"); + throw new Error("no query params found"); } - const redirectUrl = `vscode://continue.Continue${query ? "?" + query : ""}`; + + const redirectUrl = `vscode://continue.Continue?${query}`; res.writeHead(302, { Location: redirectUrl, }); res.end(); - } else { - res.writeHead(404, { "Content-Type": "text/plain" }); - res.end("Not Found"); + } catch (error) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end(`Unexpected redirect error: ${(error as Error).message}`); } }); +// TODO: start the server only when mcp oauth process starts and kill when done server.listen(PORT, () => { - console.log(`Server running at http://localhost:${PORT}/`); + console.log( + `Server running for MCP Oauth process at http://localhost:${PORT}/`, + ); }); +type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string]; +type MCPOauthStorageKey = keyof MCPOauthStorage; + class MCPConnectionOauthProvider implements OAuthClientProvider { + private globalContext: GlobalContext; + constructor( public oauthServerUrl: string, private ide: IDE, - ) {} + ) { + this.globalContext = new GlobalContext(); + console.log( + "debug1 mcp oauth storage", + this.globalContext.get("mcpOauthStorage"), + ); + } get redirectUrl() { - return "http://localhost:3000"; // TODO: this has to be a hub url or should we spin up a server? + return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server? } get clientMetadata() { @@ -66,25 +88,76 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { }; } - saveClientInformation(clientInformation: OAuthClientInformationFull) {} + private _getOauthStorage(key: K) { + return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[ + key + ]; + } + + private _updateOauthStorage( + key: K, + value: MCPOauthStorage[K], + ) { + const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {}; + const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {}; + + this.globalContext.update("mcpOauthStorage", { + ...existingStorage, + [this.oauthServerUrl]: { + ...existingServerStorage, + [key]: value, + }, + }); + } + + private _clearOauthStorage() { + const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {}; + delete existingStorage[this.oauthServerUrl]; + this.globalContext.update("mcpOauthStorage", existingStorage); + } + + saveClientInformation(clientInformation: OAuthClientInformationFull) { + this._updateOauthStorage("clientInformation", clientInformation); + } async clientInformation() { - return undefined; + const existingClientInformation = + this._getOauthStorage("clientInformation"); + if (!existingClientInformation) { + return undefined; + } + return await OAuthClientInformationSchema.parseAsync( + existingClientInformation, + ); } async tokens() { - return undefined; + const existingTokens = this._getOauthStorage("tokens"); + if (!existingTokens) { + return undefined; + } + return await OAuthTokensSchema.parseAsync(existingTokens); } - saveTokens(tokens: OAuthTokens) {} + saveTokens(tokens: OAuthTokens) { + this._updateOauthStorage("tokens", tokens); + } codeVerifier(): string | Promise { - return ""; + const existingCodeVerifier = this._getOauthStorage("codeVerifier"); + if (!existingCodeVerifier) { + return ""; + } + return existingCodeVerifier; } - saveCodeVerifier(codeVerifier: string) {} + saveCodeVerifier(codeVerifier: string) { + this._updateOauthStorage("codeVerifier", codeVerifier); + } - clear() {} + clear() { + this._clearOauthStorage(); + } async redirectToAuthorization(authorizationUrl: URL) { console.log("debug1 redirecting to url", authorizationUrl); @@ -93,27 +166,46 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { } } +// TODO: first fetch can fail - need to refresh from gui +export async function getOauthToken(mcpServerUrl: string, ide: IDE) { + const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + const tokens = await authProvider.tokens(); + return tokens?.access_token; +} + +// TODO: this needs to be called from an authenticate button in gui export async function performAuth(mcpServerUrl: string, ide: IDE) { const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - await auth(authProvider, { serverUrl: mcpServerUrl }); - - // full uri is of the format "https://localhost:3000/?code=712020%253Abed80c83-1041-49e0-99b5-5d4f9f8aa538%3ACSlICEGG3rzCQhla%3AHA0oJYDjijnNE8nCoADpZsSp8jr7cCSZ" - // const input = await ide.showInput({ - // prompt: "Paste the auth code here", - // }); - // const result = await auth(authProvider, { - // serverUrl: mcpServerUrl, - // authorizationCode: input, - // }); - // if (result === "AUTHORIZED") { - // void ide.showToast( - // "info", - // `Authenticated with ${new URL(mcpServerUrl).hostname} MCP server`, - // ); - // } else { - // void ide.showToast( - // "error", - // `Failed to authenticate with ${new URL(mcpServerUrl).hostname} MCP server`, - // ); - // } + const result = await auth(authProvider, { + serverUrl: mcpServerUrl, + }); + console.log("debug1 first result", result); +} + +export async function handleMCPOauthCode( + authorizationCode: string, + ide: IDE, + messenger: IMessenger, +) { + // const { serverUrl, authState } = await messenger.request( + // "getMCPOauthState", // remove this if not needed including the protocols - we can store the state in current file itself (also easier to kill the server) + // undefined, + // ); + const serverUrl = "https://mcp.asana.com/sse"; + if (!authorizationCode) { + ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); + } + + console.log("debug1 authenticating ", { + serverUrl, + authorizationCode, + }); + const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); + console.log("debug1 starting auth"); + const result = await auth(authProvider, { + serverUrl, + authorizationCode, + }); + + console.log("debug1 after auth result", result); } diff --git a/core/core.ts b/core/core.ts index d8275b8ff..74702f80c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,6 +61,7 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; +import { handleMCPOauthCode } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -433,6 +434,10 @@ export class Core { description: prompt.description, }; }); + on("mcp/sendOauthCode", async (msg) => { + await handleMCPOauthCode(msg.data.code, this.ide, this.messenger); + }); + // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 743556d15..5f1aa7ad9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -142,6 +142,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { description: string | undefined; }, ]; + "mcp/sendOauthCode": [ + { + code: string; + }, + void, + ]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 6e25e5f54..482ec37f6 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -92,4 +92,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "didCloseFiles", "toolCallPartialOutput", "freeTrialExceeded", + "getMCPOauthState", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 1a8d40313..cc963982f 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,5 +1,6 @@ import { ConfigResult } from "@continuedev/config-yaml"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; +import { MCPOauthState } from "../context/mcp/MCPOauth.js"; import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js"; import type { BrowserSerializedContinueConfig, @@ -44,4 +45,8 @@ export type ToWebviewFromIdeOrCoreProtocol = { sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; freeTrialExceeded: [undefined, void]; + getMCPOauthState: [ + undefined, + { serverUrl: string; authState: MCPOauthState }, + ]; }; diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 6885edde2..ddf9f6f44 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -9,6 +9,10 @@ import { SharedConfigSchema, } from "../config/sharedConfig"; +import { + OAuthClientInformationFull, + OAuthTokens, +} from "@modelcontextprotocol/sdk/shared/auth.js"; import { getGlobalContextFilePath } from "./paths"; export type GlobalContextModelSelections = Partial< @@ -39,6 +43,15 @@ export type GlobalContextType = { isSupportedLanceDbCpuTargetForLinux: boolean; sharedConfig: SharedConfigSchema; failedDocs: SiteIndexingConfig[]; + + mcpOauthStorage: Record< + string, + { + clientInformation?: OAuthClientInformationFull; + tokens?: OAuthTokens; + codeVerifier?: string; + } + >; }; /** diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index fe624179a..463b2ba42 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -73,11 +73,6 @@ export class VsCodeExtension { // Register auth provider this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler); - // TODO: this should practically only start listening when user has started an mcp oauth flow. how to do this? - this.uriHandler.event((uri) => { - console.log("debug1 uri was", uri); - }); - void this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); @@ -445,6 +440,14 @@ export class VsCodeExtension { void this.core.invoke("config/ideSettingsUpdate", settings); } }); + + // TODO: this should practically only start listening when user has started an mcp oauth flow. how to do this? + this.uriHandler.event((uri) => { + console.log("debug1 uri->", uri); + this.core.invoke("mcp/sendOauthCode", { + code: new URLSearchParams(uri.query).get("code") ?? "", + }); + }); } static continueVirtualDocumentScheme = EXTENSION_NAME; From a062f26559ff289bea3b20f1e9bda66734d88dd4 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 28 Jul 2025 21:51:47 +0530 Subject: [PATCH 04/44] add authenticate button in gui - added a startAuthentication protocol --- core/context/mcp/MCPConnection.ts | 1 - core/context/mcp/MCPOauth.ts | 14 ++---- core/core.ts | 17 ++++++- core/protocol/core.ts | 2 + core/protocol/passThrough.ts | 1 + .../Lump/sections/mcp/MCPSection.tsx | 46 +++++++++++++++++-- 6 files changed, 65 insertions(+), 16 deletions(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 71412d476..7b1d0b615 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -117,7 +117,6 @@ class MCPConnection { if (this.options.transport.type === "sse") { // currently support oauth for sse transports only - console.log("debug1 extras", this.extras); if (!this.options.transport.requestOptions) { this.options.transport.requestOptions = { headers: {}, diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 6e1544533..043117251 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -8,7 +8,7 @@ import { OAuthTokens, OAuthTokensSchema, } from "@modelcontextprotocol/sdk/shared/auth.js"; -import { IDE } from "../.."; +import { IDE, MCPServerStatus, SSEOptions } from "../.."; import http from "http"; import url from "url"; @@ -173,13 +173,12 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { return tokens?.access_token; } -// TODO: this needs to be called from an authenticate button in gui -export async function performAuth(mcpServerUrl: string, ide: IDE) { +export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { + const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - const result = await auth(authProvider, { + return await auth(authProvider, { serverUrl: mcpServerUrl, }); - console.log("debug1 first result", result); } export async function handleMCPOauthCode( @@ -201,11 +200,8 @@ export async function handleMCPOauthCode( authorizationCode, }); const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - console.log("debug1 starting auth"); - const result = await auth(authProvider, { + return await auth(authProvider, { serverUrl, authorizationCode, }); - - console.log("debug1 after auth result", result); } diff --git a/core/core.ts b/core/core.ts index 74702f80c..c72503af0 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,7 +61,7 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; -import { handleMCPOauthCode } from "./context/mcp/MCPOauth"; +import { handleMCPOauthCode, performAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -434,8 +434,21 @@ export class Core { description: prompt.description, }; }); + on("mcp/startAuthentication", async (msg) => { + const status = await performAuth(msg.data, this.ide); + if (status === "AUTHORIZED") { + await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + } + }); on("mcp/sendOauthCode", async (msg) => { - await handleMCPOauthCode(msg.data.code, this.ide, this.messenger); + const status = await handleMCPOauthCode( + msg.data.code, + this.ide, + this.messenger, + ); + if (status === "AUTHORIZED") { + // await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + } }); // Context providers diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 5f1aa7ad9..517dd34fd 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -26,6 +26,7 @@ import { FileSymbolMap, IdeSettings, LLMFullCompletionOptions, + MCPServerStatus, MessageOption, ModelDescription, PromptLog, @@ -142,6 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { description: string | undefined; }, ]; + "mcp/startAuthentication": [MCPServerStatus, void]; "mcp/sendOauthCode": [ { code: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 482ec37f6..96858f29d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -28,6 +28,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/updateSelectedModel", "mcp/reloadServer", "mcp/getPrompt", + "mcp/startAuthentication", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 76fb338e9..73b890fd2 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -1,13 +1,16 @@ import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml"; import { + ArrowLeftCircleIcon, ArrowPathIcon, CircleStackIcon, CommandLineIcon, + GlobeAltIcon, InformationCircleIcon, + UserCircleIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -17,6 +20,10 @@ import { ToolTip } from "../../../../gui/Tooltip"; import EditBlockButton from "../../EditBlockButton"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; +function has401Error(errors: string[]) { + return !!errors.find((error) => error.includes("401")); +} + interface MCPServerStatusProps { server: MCPServerStatus; serverFromYaml?: NonNullable[number]; @@ -30,7 +37,17 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const resourcesTooltipId = `${server.id}-resources`; const errorsTooltipId = `${server.id}-errors`; - async function onRefresh() { + const [mcpAuthStatus, setMcpAuthStatus] = useState< + "unauthenticated" | "authenticated" | "authenticating" + >("unauthenticated"); + + const onAuthenticate = async () => { + setMcpAuthStatus("authenticating"); // TODO: move this updateConfig later with "authenticated" and "authenticating" status + await ideMessenger.request("mcp/startAuthentication", server); + setMcpAuthStatus("authenticated"); + }; + + const onRefresh = async () => { // optimistic config update dispatch( updateConfig({ @@ -48,7 +65,13 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { ideMessenger.post("mcp/reloadServer", { id: server.id, }); - } + }; + + // useEffect(() => { + // if (hasConnectionResetError(server.errors)) { + // onRefresh(); + // } + // }, [server.errors]); return (
- {/* Refresh button */}
+ {has401Error(server.errors) && ( + <> +
+ {mcpAuthStatus === "authenticating" ? ( + + ) : mcpAuthStatus === "authenticated" ? ( + + ) : ( + + )} +
+ + )} Date: Mon, 28 Jul 2025 22:33:43 +0530 Subject: [PATCH 05/44] remove getmcpauthstate --- core/protocol/passThrough.ts | 1 - core/protocol/webview.ts | 5 ----- 2 files changed, 6 deletions(-) diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 96858f29d..1f79d9867 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -93,5 +93,4 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "didCloseFiles", "toolCallPartialOutput", "freeTrialExceeded", - "getMCPOauthState", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index cc963982f..1a8d40313 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,6 +1,5 @@ import { ConfigResult } from "@continuedev/config-yaml"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; -import { MCPOauthState } from "../context/mcp/MCPOauth.js"; import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js"; import type { BrowserSerializedContinueConfig, @@ -45,8 +44,4 @@ export type ToWebviewFromIdeOrCoreProtocol = { sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; freeTrialExceeded: [undefined, void]; - getMCPOauthState: [ - undefined, - { serverUrl: string; authState: MCPOauthState }, - ]; }; From ab66938a661b4604afef8e25833c02acc933eb44 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 28 Jul 2025 22:42:47 +0530 Subject: [PATCH 06/44] added mcp remove authentication - add protectedresource key to mcp server status - shift mcp server auth status handling to core --- core/context/mcp/MCPConnection.ts | 32 ++++++++++--- core/context/mcp/MCPOauth.ts | 24 +++++----- core/core.ts | 16 ++++--- core/index.d.ts | 1 + core/protocol/core.ts | 3 ++ core/protocol/passThrough.ts | 1 + core/tools/mcpToolName.vitest.ts | 1 + .../Lump/sections/mcp/MCPSection.tsx | 48 ++++++++++++------- 8 files changed, 84 insertions(+), 42 deletions(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 7b1d0b615..c5a975473 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -1,7 +1,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { + SSEClientTransport, + SseError, +} from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; @@ -32,6 +35,14 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +function is401Error(error: unknown) { + return ( + (error instanceof SseError && error.code === 401) || + (error instanceof Error && error.message.includes("401")) || + (error instanceof Error && error.message.includes("Unauthorized")) + ); +} + export type MCPExtras = { ide: IDE; }; @@ -40,6 +51,7 @@ class MCPConnection { public client: Client; public abortController: AbortController; public status: MCPConnectionStatus = "not-connected"; + public isProtectedResource = false; public errors: string[] = []; public prompts: MCPPrompt[] = []; public tools: MCPTool[] = []; @@ -87,6 +99,7 @@ class MCPConnection { resourceTemplates: this.resourceTemplates, tools: this.tools, status: this.status, + isProtectedResource: this.isProtectedResource, }; } @@ -115,8 +128,8 @@ class MCPConnection { this.abortController.abort(); this.abortController = new AbortController(); + // currently support oauth for sse transports only if (this.options.transport.type === "sse") { - // currently support oauth for sse transports only if (!this.options.transport.requestOptions) { this.options.transport.requestOptions = { headers: {}, @@ -126,10 +139,13 @@ class MCPConnection { this.options.transport.url, this.extras?.ide!, ); - this.options.transport.requestOptions.headers = { - ...this.options.transport.requestOptions.headers, - Authorization: `Bearer ${accessToken}`, - }; + if (accessToken) { + this.isProtectedResource = true; + this.options.transport.requestOptions.headers = { + ...this.options.transport.requestOptions.headers, + Authorization: `Bearer ${accessToken}`, + }; + } } this.connectionPromise = Promise.race([ @@ -270,6 +286,10 @@ class MCPConnection { } } + if (is401Error(error)) { + this.isProtectedResource = true; + } + // Include stdio output if available for stdio transport if ( this.options.transport.type === "stdio" && diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 043117251..f76b62fba 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -12,11 +12,9 @@ import { IDE, MCPServerStatus, SSEOptions } from "../.."; import http from "http"; import url from "url"; -import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; -import { IMessenger } from "../../protocol/messenger"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; -export type MCPOauthState = "login" | "authenticating" | "disconnect"; +let currentMCPAuthServerUrl = ""; const PORT = 3000; @@ -157,6 +155,10 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { clear() { this._clearOauthStorage(); + console.log( + "debug1 after clearing mcp oauth storage", + this.globalContext.get("mcpOauthStorage"), + ); } async redirectToAuthorization(authorizationUrl: URL) { @@ -181,15 +183,7 @@ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { }); } -export async function handleMCPOauthCode( - authorizationCode: string, - ide: IDE, - messenger: IMessenger, -) { - // const { serverUrl, authState } = await messenger.request( - // "getMCPOauthState", // remove this if not needed including the protocols - we can store the state in current file itself (also easier to kill the server) - // undefined, - // ); +export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { const serverUrl = "https://mcp.asana.com/sse"; if (!authorizationCode) { ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); @@ -205,3 +199,9 @@ export async function handleMCPOauthCode( authorizationCode, }); } + +export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { + const mcpServerUrl = (mcpServer.transport as SSEOptions).url; + const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + authProvider.clear(); +} diff --git a/core/core.ts b/core/core.ts index c72503af0..cb846c7ad 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,7 +61,11 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; -import { handleMCPOauthCode, performAuth } from "./context/mcp/MCPOauth"; +import { + handleMCPOauthCode, + performAuth, + removeMCPAuth, +} from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -441,15 +445,15 @@ export class Core { } }); on("mcp/sendOauthCode", async (msg) => { - const status = await handleMCPOauthCode( - msg.data.code, - this.ide, - this.messenger, - ); + const status = await handleMCPOauthCode(msg.data.code, this.ide); if (status === "AUTHORIZED") { // await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); + on("mcp/removeAuthentication", async (msg) => { + removeMCPAuth(msg.data, this.ide); + await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + }); // Context providers on("context/addDocs", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 13e231b87..90b978a63 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1310,6 +1310,7 @@ export interface MCPTool { export interface MCPServerStatus extends MCPOptions { status: MCPConnectionStatus; errors: string[]; + isProtectedResource: boolean; prompts: MCPPrompt[]; tools: MCPTool[]; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 517dd34fd..daacaa4f1 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -126,6 +126,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "mcp/reloadServer": [ { id: string; @@ -150,6 +151,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + "mcp/removeAuthentication": [MCPServerStatus, void]; + "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1f79d9867..4575a2b53 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -29,6 +29,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "mcp/reloadServer", "mcp/getPrompt", "mcp/startAuthentication", + "mcp/removeAuthentication", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts index 8c20f630a..ff60d5200 100644 --- a/core/tools/mcpToolName.vitest.ts +++ b/core/tools/mcpToolName.vitest.ts @@ -15,6 +15,7 @@ const createMcpServer = (name: string): MCPServerStatus => ({ type: "sse", url: "", }, + isProtectedResource: false, }); const createMCPTool = (name: string): MCPTool => ({ diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 73b890fd2..ede04c013 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -1,22 +1,22 @@ import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml"; import { - ArrowLeftCircleIcon, ArrowPathIcon, CircleStackIcon, CommandLineIcon, - GlobeAltIcon, InformationCircleIcon, - UserCircleIcon, + ShieldCheckIcon, + ShieldExclamationIcon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo, useState } from "react"; +import { useContext, useMemo } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; import { updateConfig } from "../../../../../redux/slices/configSlice"; import { fontSize } from "../../../../../util"; import { ToolTip } from "../../../../gui/Tooltip"; +import { Button } from "../../../../ui"; import EditBlockButton from "../../EditBlockButton"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; @@ -36,15 +36,14 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const promptsTooltipId = `${server.id}-prompts`; const resourcesTooltipId = `${server.id}-resources`; const errorsTooltipId = `${server.id}-errors`; - - const [mcpAuthStatus, setMcpAuthStatus] = useState< - "unauthenticated" | "authenticated" | "authenticating" - >("unauthenticated"); + const mcpAuthTooltipId = `${server.id}-auth`; const onAuthenticate = async () => { - setMcpAuthStatus("authenticating"); // TODO: move this updateConfig later with "authenticated" and "authenticating" status await ideMessenger.request("mcp/startAuthentication", server); - setMcpAuthStatus("authenticated"); + }; + + const onRemoveAuth = async () => { + await ideMessenger.request("mcp/removeAuthentication", server); }; const onRefresh = async () => { @@ -154,20 +153,33 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {has401Error(server.errors) && ( + {server.isProtectedResource && ( <>
- {mcpAuthStatus === "authenticating" ? ( - - ) : mcpAuthStatus === "authenticated" ? ( - - ) : ( - + {server.status === "error" ? ( + + ) : server.status === "connecting" ? null : ( + )}
+ +
+ +
+
)} Date: Mon, 28 Jul 2025 23:03:01 +0530 Subject: [PATCH 07/44] handle mcp oauth callback --- core/context/mcp/MCPOauth.ts | 31 ++++++++++++++----- core/core.ts | 11 +++++-- .../Lump/sections/mcp/MCPSection.tsx | 14 ++++----- 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index f76b62fba..34e79368d 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -14,7 +14,8 @@ import http from "http"; import url from "url"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; -let currentMCPAuthServerUrl = ""; +/**in memory storage variable for the server that is currently being authenticated */ +let authenticatingMCPServer: MCPServerStatus | null = null; const PORT = 3000; @@ -162,29 +163,40 @@ class MCPConnectionOauthProvider implements OAuthClientProvider { } async redirectToAuthorization(authorizationUrl: URL) { - console.log("debug1 redirecting to url", authorizationUrl); - // TODO here the url needs to be sent to the extension this.ide.openUrl(authorizationUrl.toString()); } } -// TODO: first fetch can fail - need to refresh from gui export async function getOauthToken(mcpServerUrl: string, ide: IDE) { const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); const tokens = await authProvider.tokens(); return tokens?.access_token; } +/** + * checks if the authentication is already done for the current server + * if not, starts the authentication process by opening a webpage url + */ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - return await auth(authProvider, { + const authStatus = await auth(authProvider, { serverUrl: mcpServerUrl, }); + if (authStatus === "REDIRECT") { + authenticatingMCPServer = mcpServer; + } + return authStatus; } +/** + * handle the authentication code received from the oauth redirect + */ export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { - const serverUrl = "https://mcp.asana.com/sse"; + const serverUrl = (authenticatingMCPServer?.transport as SSEOptions).url; + if (!serverUrl) { + ide.showToast("error", "No MCP server url found for authentication"); + } if (!authorizationCode) { ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); } @@ -194,10 +206,15 @@ export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { authorizationCode, }); const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - return await auth(authProvider, { + const authStatus = await auth(authProvider, { serverUrl, authorizationCode, }); + + const prevAuthenticatingMCPServer = authenticatingMCPServer!; + authenticatingMCPServer = null; + + return { authStatus, authenticatingMCPServer: prevAuthenticatingMCPServer }; } export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { diff --git a/core/core.ts b/core/core.ts index cb846c7ad..41663acca 100644 --- a/core/core.ts +++ b/core/core.ts @@ -445,9 +445,14 @@ export class Core { } }); on("mcp/sendOauthCode", async (msg) => { - const status = await handleMCPOauthCode(msg.data.code, this.ide); - if (status === "AUTHORIZED") { - // await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + const { authStatus, authenticatingMCPServer } = await handleMCPOauthCode( + msg.data.code, + this.ide, + ); + if (authStatus === "AUTHORIZED") { + await MCPManagerSingleton.getInstance().refreshConnection( + authenticatingMCPServer.id, + ); } }); on("mcp/removeAuthentication", async (msg) => { diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index ede04c013..4363df837 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -9,7 +9,7 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo } from "react"; +import { useContext, useMemo, useState } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -30,6 +30,8 @@ interface MCPServerStatusProps { } function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const ideMessenger = useContext(IdeMessengerContext); + // TODO: refactor this to mcp state - also easier to remove the in memory storage + const [isMcpAuthenticating, setIsMcpAuthenticating] = useState(false); const config = useAppSelector((store) => store.config.config); const dispatch = useAppDispatch(); const toolsTooltipId = `${server.id}-tools`; @@ -39,7 +41,9 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const mcpAuthTooltipId = `${server.id}-auth`; const onAuthenticate = async () => { + setIsMcpAuthenticating(true); await ideMessenger.request("mcp/startAuthentication", server); + setIsMcpAuthenticating(false); }; const onRemoveAuth = async () => { @@ -66,12 +70,6 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { }); }; - // useEffect(() => { - // if (hasConnectionResetError(server.errors)) { - // onRefresh(); - // } - // }, [server.errors]); - return (
- {server.isProtectedResource && ( + {server.isProtectedResource && !isMcpAuthenticating && ( <>
Date: Mon, 28 Jul 2025 23:21:45 +0530 Subject: [PATCH 08/44] store mcp authenticating server as connection status --- core/context/mcp/MCPOauth.ts | 30 ++++++----------- core/core.ts | 11 +++++-- core/index.d.ts | 1 + .../Lump/sections/mcp/MCPSection.tsx | 33 ++++++++++--------- 4 files changed, 36 insertions(+), 39 deletions(-) diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 34e79368d..58f55b34c 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -14,9 +14,6 @@ import http from "http"; import url from "url"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; -/**in memory storage variable for the server that is currently being authenticated */ -let authenticatingMCPServer: MCPServerStatus | null = null; - const PORT = 3000; const server = http.createServer((req, res) => { @@ -180,41 +177,34 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); - const authStatus = await auth(authProvider, { + return await auth(authProvider, { serverUrl: mcpServerUrl, }); - if (authStatus === "REDIRECT") { - authenticatingMCPServer = mcpServer; - } - return authStatus; } /** * handle the authentication code received from the oauth redirect */ -export async function handleMCPOauthCode(authorizationCode: string, ide: IDE) { - const serverUrl = (authenticatingMCPServer?.transport as SSEOptions).url; +export async function handleMCPOauthCode( + authorizationCode: string, + ide: IDE, + authenticatingServer: MCPServerStatus | undefined, +) { + const serverUrl = (authenticatingServer?.transport as SSEOptions).url; if (!serverUrl) { ide.showToast("error", "No MCP server url found for authentication"); + return; } if (!authorizationCode) { ide.showToast("error", `No MCP authorization code found for ${serverUrl}`); + return; } - console.log("debug1 authenticating ", { - serverUrl, - authorizationCode, - }); const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - const authStatus = await auth(authProvider, { + return await auth(authProvider, { serverUrl, authorizationCode, }); - - const prevAuthenticatingMCPServer = authenticatingMCPServer!; - authenticatingMCPServer = null; - - return { authStatus, authenticatingMCPServer: prevAuthenticatingMCPServer }; } export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { diff --git a/core/core.ts b/core/core.ts index 41663acca..bac3744c6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -439,19 +439,24 @@ export class Core { }; }); on("mcp/startAuthentication", async (msg) => { + await new Promise((resolve) => setTimeout(resolve, 5000)); const status = await performAuth(msg.data, this.ide); if (status === "AUTHORIZED") { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); on("mcp/sendOauthCode", async (msg) => { - const { authStatus, authenticatingMCPServer } = await handleMCPOauthCode( + const authenticatingServer = MCPManagerSingleton.getInstance() + .getStatuses() + .find((s) => s.status === "authenticating"); + const authStatus = await handleMCPOauthCode( msg.data.code, this.ide, + authenticatingServer, ); - if (authStatus === "AUTHORIZED") { + if (authStatus === "AUTHORIZED" && authenticatingServer) { await MCPManagerSingleton.getInstance().refreshConnection( - authenticatingMCPServer.id, + authenticatingServer.id, ); } }); diff --git a/core/index.d.ts b/core/index.d.ts index 90b978a63..f71b200bb 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1262,6 +1262,7 @@ export interface MCPOptions { } export type MCPConnectionStatus = + | "authenticating" | "connecting" | "connected" | "error" diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 4363df837..51e3368da 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -9,7 +9,7 @@ import { WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; -import { useContext, useMemo, useState } from "react"; +import { useContext, useMemo } from "react"; import { useAuth } from "../../../../../context/Auth"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; @@ -30,8 +30,6 @@ interface MCPServerStatusProps { } function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const ideMessenger = useContext(IdeMessengerContext); - // TODO: refactor this to mcp state - also easier to remove the in memory storage - const [isMcpAuthenticating, setIsMcpAuthenticating] = useState(false); const config = useAppSelector((store) => store.config.config); const dispatch = useAppDispatch(); const toolsTooltipId = `${server.id}-tools`; @@ -40,17 +38,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { const errorsTooltipId = `${server.id}-errors`; const mcpAuthTooltipId = `${server.id}-auth`; - const onAuthenticate = async () => { - setIsMcpAuthenticating(true); - await ideMessenger.request("mcp/startAuthentication", server); - setIsMcpAuthenticating(false); - }; - - const onRemoveAuth = async () => { - await ideMessenger.request("mcp/removeAuthentication", server); - }; - - const onRefresh = async () => { + const updateMCPServerStatus = (status: MCPServerStatus["status"]) => { // optimistic config update dispatch( updateConfig({ @@ -59,12 +47,25 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { s.id === server.id ? { ...s, - status: "connecting", + status, } : s, ), }), ); + }; + + const onAuthenticate = async () => { + updateMCPServerStatus("authenticating"); + await ideMessenger.request("mcp/startAuthentication", server); + }; + + const onRemoveAuth = async () => { + await ideMessenger.request("mcp/removeAuthentication", server); + }; + + const onRefresh = async () => { + updateMCPServerStatus("connecting"); ideMessenger.post("mcp/reloadServer", { id: server.id, }); @@ -151,7 +152,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {server.isProtectedResource && !isMcpAuthenticating && ( + {server.isProtectedResource && server.status !== "authenticating" && ( <>
Date: Tue, 29 Jul 2025 11:53:28 +0530 Subject: [PATCH 09/44] fix find authenticating server --- core/context/mcp/MCPManagerSingleton.ts | 4 ++++ core/core.ts | 1 + 2 files changed, 5 insertions(+) diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 515fdecc7..4a704f427 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -166,6 +166,10 @@ export class MCPManagerSingleton { })); } + setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) { + this.connections.get(server.id)!.status = status; + } + async getPrompt( serverName: string, promptName: string, diff --git a/core/core.ts b/core/core.ts index bac3744c6..abe73b2be 100644 --- a/core/core.ts +++ b/core/core.ts @@ -440,6 +440,7 @@ export class Core { }); on("mcp/startAuthentication", async (msg) => { await new Promise((resolve) => setTimeout(resolve, 5000)); + MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating"); const status = await performAuth(msg.data, this.ide); if (status === "AUTHORIZED") { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); From 64702333a768c15fe2fb86a0d17154fbd59e69ed Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 29 Jul 2025 12:24:27 +0530 Subject: [PATCH 10/44] remove vscode redirect after authentication --- core/context/mcp/MCPOauth.ts | 56 ++++++++++++++++++++++++------------ core/core.ts | 37 +++++++++++------------- 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/core/context/mcp/MCPOauth.ts b/core/context/mcp/MCPOauth.ts index 58f55b34c..b746286bb 100644 --- a/core/context/mcp/MCPOauth.ts +++ b/core/context/mcp/MCPOauth.ts @@ -14,6 +14,11 @@ import http from "http"; import url from "url"; import { GlobalContext, GlobalContextType } from "../../util/GlobalContext"; +let authenticatingMCPContext = null as { + authenticatingServer: MCPServerStatus; + ide: IDE; +} | null; + const PORT = 3000; const server = http.createServer((req, res) => { @@ -21,24 +26,25 @@ const server = http.createServer((req, res) => { if (!req.url) { throw new Error("no url found"); } - const parsedUrl = url.parse(req.url, true); - if (parsedUrl.pathname !== "/") { - throw new Error("path is not index"); - } - const query = new URLSearchParams( - parsedUrl.query as Record, - ).toString(); - if (!query) { + const parsedUrl = url.parse(req.url, true); + if (!parsedUrl.query["code"]) { throw new Error("no query params found"); } - const redirectUrl = `vscode://continue.Continue?${query}`; + handleMCPOauthCode(parsedUrl.query["code"] as string); - res.writeHead(302, { - Location: redirectUrl, + const html = ` + + +Authentication Complete +Authentication Complete. You can close this page now. +`; + + res.writeHead(200, { + "Content-Type": "text/html", }); - res.end(); + res.end(html); } catch (error) { res.writeHead(400, { "Content-Type": "text/plain" }); res.end(`Unexpected redirect error: ${(error as Error).message}`); @@ -177,6 +183,10 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) { export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { const mcpServerUrl = (mcpServer.transport as SSEOptions).url; const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide); + authenticatingMCPContext = { + authenticatingServer: mcpServer, + ide, + }; return await auth(authProvider, { serverUrl: mcpServerUrl, }); @@ -185,12 +195,13 @@ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) { /** * handle the authentication code received from the oauth redirect */ -export async function handleMCPOauthCode( - authorizationCode: string, - ide: IDE, - authenticatingServer: MCPServerStatus | undefined, -) { - const serverUrl = (authenticatingServer?.transport as SSEOptions).url; +export async function handleMCPOauthCode(authorizationCode: string) { + if (!authenticatingMCPContext) { + return; + } + const { ide, authenticatingServer } = authenticatingMCPContext; + const serverUrl = (authenticatingServer.transport as SSEOptions).url; + if (!serverUrl) { ide.showToast("error", "No MCP server url found for authentication"); return; @@ -201,10 +212,17 @@ export async function handleMCPOauthCode( } const authProvider = new MCPConnectionOauthProvider(serverUrl, ide); - return await auth(authProvider, { + const authStatus = await auth(authProvider, { serverUrl, authorizationCode, }); + if (authStatus === "AUTHORIZED") { + const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports + await MCPManagerSingleton.getInstance().refreshConnection( + authenticatingServer.id, + ); + } + authenticatingMCPContext = null; } export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) { diff --git a/core/core.ts b/core/core.ts index abe73b2be..c1c36c37c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -61,11 +61,7 @@ import { } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; -import { - handleMCPOauthCode, - performAuth, - removeMCPAuth, -} from "./context/mcp/MCPOauth"; +import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; @@ -446,21 +442,22 @@ export class Core { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); - on("mcp/sendOauthCode", async (msg) => { - const authenticatingServer = MCPManagerSingleton.getInstance() - .getStatuses() - .find((s) => s.status === "authenticating"); - const authStatus = await handleMCPOauthCode( - msg.data.code, - this.ide, - authenticatingServer, - ); - if (authStatus === "AUTHORIZED" && authenticatingServer) { - await MCPManagerSingleton.getInstance().refreshConnection( - authenticatingServer.id, - ); - } - }); + // TODO: remove this protocol altogher along with vscode counterpart + // on("mcp/sendOauthCode", async (msg) => { + // const authenticatingServer = MCPManagerSingleton.getInstance() + // .getStatuses() + // .find((s) => s.status === "authenticating"); + // const authStatus = await handleMCPOauthCode( + // msg.data.code, + // this.ide, + // authenticatingServer, + // ); + // if (authStatus === "AUTHORIZED" && authenticatingServer) { + // await MCPManagerSingleton.getInstance().refreshConnection( + // authenticatingServer.id, + // ); + // } + // }); on("mcp/removeAuthentication", async (msg) => { removeMCPAuth(msg.data, this.ide); await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); From 2bc7f158640be5ba9fb0f46eff48af4af4af631d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 29 Jul 2025 12:25:56 +0530 Subject: [PATCH 11/44] remove mcp/sendOauthCode protocol --- core/core.ts | 16 ---------------- core/protocol/core.ts | 6 ------ .../vscode/src/extension/VsCodeExtension.ts | 8 -------- 3 files changed, 30 deletions(-) diff --git a/core/core.ts b/core/core.ts index c1c36c37c..4e406fa3f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -442,22 +442,6 @@ export class Core { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); } }); - // TODO: remove this protocol altogher along with vscode counterpart - // on("mcp/sendOauthCode", async (msg) => { - // const authenticatingServer = MCPManagerSingleton.getInstance() - // .getStatuses() - // .find((s) => s.status === "authenticating"); - // const authStatus = await handleMCPOauthCode( - // msg.data.code, - // this.ide, - // authenticatingServer, - // ); - // if (authStatus === "AUTHORIZED" && authenticatingServer) { - // await MCPManagerSingleton.getInstance().refreshConnection( - // authenticatingServer.id, - // ); - // } - // }); on("mcp/removeAuthentication", async (msg) => { removeMCPAuth(msg.data, this.ide); await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index daacaa4f1..086ba2104 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -145,12 +145,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ]; "mcp/startAuthentication": [MCPServerStatus, void]; - "mcp/sendOauthCode": [ - { - code: string; - }, - void, - ]; "mcp/removeAuthentication": [MCPServerStatus, void]; "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 463b2ba42..32154e19a 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -440,14 +440,6 @@ export class VsCodeExtension { void this.core.invoke("config/ideSettingsUpdate", settings); } }); - - // TODO: this should practically only start listening when user has started an mcp oauth flow. how to do this? - this.uriHandler.event((uri) => { - console.log("debug1 uri->", uri); - this.core.invoke("mcp/sendOauthCode", { - code: new URLSearchParams(uri.query).get("code") ?? "", - }); - }); } static continueVirtualDocumentScheme = EXTENSION_NAME; From c401c2cda4eb79a0ec689a1391417aa5269f4c15 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 29 Jul 2025 12:46:20 +0530 Subject: [PATCH 12/44] put a spinner to show authentication progress --- core/index.d.ts | 2 +- .../Lump/sections/mcp/MCPSection.tsx | 23 ++++++++++++------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index f71b200bb..f9e85f72d 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1262,10 +1262,10 @@ export interface MCPOptions { } export type MCPConnectionStatus = - | "authenticating" | "connecting" | "connected" | "error" + | "authenticating" | "not-connected"; export type MCPPromptArgs = { diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index 51e3368da..d771aad4a 100644 --- a/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -3,6 +3,7 @@ import { ArrowPathIcon, CircleStackIcon, CommandLineIcon, + GlobeAltIcon, InformationCircleIcon, ShieldCheckIcon, ShieldExclamationIcon, @@ -20,10 +21,6 @@ import { Button } from "../../../../ui"; import EditBlockButton from "../../EditBlockButton"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; -function has401Error(errors: string[]) { - return !!errors.find((error) => error.includes("401")); -} - interface MCPServerStatusProps { server: MCPServerStatus; serverFromYaml?: NonNullable[number]; @@ -61,6 +58,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { }; const onRemoveAuth = async () => { + updateMCPServerStatus("authenticating"); await ideMessenger.request("mcp/removeAuthentication", server); }; @@ -76,7 +74,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { style={{ fontSize: fontSize(-2), }} - className="flex flex-row items-center justify-between gap-3" + className={`flex flex-row items-center justify-between gap-3 ${server.status === "authenticating" ? "my-0.5" : ""}`} >
{/* Name and Status */} @@ -152,7 +150,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
- {server.isProtectedResource && server.status !== "authenticating" && ( + {server.isProtectedResource && ( <>
{server.status === "error" ? ( - ) : server.status === "connecting" ? null : ( + ) : server.status === "authenticating" ? ( + + ) : ( )}
- + + {server.status !== "authenticating" && ( + + {server.status === "error" ? "Authenticate" : "Logout"} + + )} )} Date: Fri, 8 Aug 2025 10:52:59 +0530 Subject: [PATCH 20/44] remove schema parser --- core/llm/llms/Voyage.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 94c344a56..6a3a3dd1f 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,21 +1,6 @@ -import { z } from "zod"; - import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; -/**used to check a valid response from voyage is received - * reference: https://docs.voyageai.com/reference/reranker-api - */ -const VoyageRerankSuccessResponseSchema = z.object({ - data: z.array( - z.object({ - index: z.number(), - relevance_score: z.number(), - document: z.string(), - }), - ), -}); - class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { @@ -51,8 +36,6 @@ class Voyage extends OpenAI { data: Array<{ index: number; relevance_score: number }>; }; - VoyageRerankSuccessResponseSchema.parse(data); - const results = data.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } From 5b9feccc69efa8631258c499b461f9ed7a25df09 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 8 Aug 2025 12:42:08 +0530 Subject: [PATCH 21/44] fix: abort controller before clearing --- core/indexing/CodebaseIndexer.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 6e1dab530..b28ece8da 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -735,6 +735,7 @@ export class CodebaseIndexer { }); } if (this.indexingCancellationController === localController) { + this.indexingCancellationController.abort(); // abort before clearing to prevent race condition (multiple starts) this.indexingCancellationController = undefined; } } From 4ea64921775d5c86e7220f01c6dbace44b0d0a01 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 11 Aug 2025 08:23:08 +0530 Subject: [PATCH 22/44] Revert "remove schema parser" This reverts commit 4dea1af5e907b3092b300514ba846d35677f49ba. --- core/llm/llms/Voyage.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 6a3a3dd1f..94c344a56 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,6 +1,21 @@ +import { z } from "zod"; + import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; +/**used to check a valid response from voyage is received + * reference: https://docs.voyageai.com/reference/reranker-api + */ +const VoyageRerankSuccessResponseSchema = z.object({ + data: z.array( + z.object({ + index: z.number(), + relevance_score: z.number(), + document: z.string(), + }), + ), +}); + class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { @@ -36,6 +51,8 @@ class Voyage extends OpenAI { data: Array<{ index: number; relevance_score: number }>; }; + VoyageRerankSuccessResponseSchema.parse(data); + const results = data.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } From 4e181804f69eeac186a07b319732b03db28aa8ae Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 12 Aug 2025 00:47:34 +0530 Subject: [PATCH 23/44] use safe parsed schema --- core/llm/llms/Voyage.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 94c344a56..9ba43554e 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -51,9 +51,9 @@ class Voyage extends OpenAI { data: Array<{ index: number; relevance_score: number }>; }; - VoyageRerankSuccessResponseSchema.parse(data); + const parsedData = VoyageRerankSuccessResponseSchema.parse(data); - const results = data.data.sort((a, b) => a.index - b.index); + const results = parsedData.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } } From d1f06da04e9e62120ec93f6663611d6c644e4194 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:44:11 -0700 Subject: [PATCH 24/44] refactor: rename model 1 to instinct --- core/llm/autodetect.ts | 2 +- core/llm/autodetect.vitest.ts | 12 ++++---- core/llm/constants.ts | 2 +- core/nextEdit/constants.ts | 27 ++++++++++++----- .../templating/NextEditPromptEngine.vitest.ts | 30 +++++++++---------- .../templating/{model1.ts => instinct.ts} | 22 +++++++------- .../{model1.vitest.ts => instinct.vitest.ts} | 2 +- core/nextEdit/templating/utils.ts | 8 ++--- core/nextEdit/templating/utils.vitest.ts | 12 ++++---- core/nextEdit/types.ts | 2 +- 10 files changed, 67 insertions(+), 52 deletions(-) rename core/nextEdit/templating/{model1.ts => instinct.ts} (84%) rename core/nextEdit/templating/{model1.vitest.ts => instinct.vitest.ts} (99%) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index b2943e316..f167d02f9 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -178,7 +178,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( // update core/nextEdit/templating/NextEditPromptEngine.ts as well. const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, - NEXT_EDIT_MODELS.MODEL_1, + NEXT_EDIT_MODELS.INSTINCT, ]; function modelSupportsNextEdit( diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts index 01d48aacc..4e250f1ad 100644 --- a/core/llm/autodetect.vitest.ts +++ b/core/llm/autodetect.vitest.ts @@ -245,8 +245,10 @@ describe("modelSupportsNextEdit", () => { ).toBe(true); }); - it("should return true for model-1", () => { - expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true); + it("should return true for instinct", () => { + expect(modelSupportsNextEdit(undefined, "instinct", undefined)).toBe( + true, + ); }); it("should return true when model contains supported model name as substring", () => { @@ -269,9 +271,9 @@ describe("modelSupportsNextEdit", () => { ).toBe(true); }); - it("should return true when title contains model-1", () => { + it("should return true when title contains instinct", () => { expect( - modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"), + modelSupportsNextEdit(undefined, "some-model", "instinct deployment"), ).toBe(true); }); @@ -317,7 +319,7 @@ describe("modelSupportsNextEdit", () => { it("should handle case sensitivity correctly", () => { expect( - modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"), + modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"), ).toBe(true); }); diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 5b93048e9..704931af5 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -21,7 +21,7 @@ export enum LLMConfigurationStatuses { export enum NEXT_EDIT_MODELS { MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", - MODEL_1 = "model-1", + INSTINCT = "instinct", } export { diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 21e249b96..27a743dcc 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -1,14 +1,27 @@ +import { NEXT_EDIT_MODELS } from "../llm/constants"; + export const IS_NEXT_EDIT_ACTIVE = false; export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0; export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; +export const MODEL_WINDOW_SIZES: Record< + NEXT_EDIT_MODELS, + { topMargin: number; bottomMargin: number } +> = { + "mercury-coder-nextedit": { + topMargin: 0, + bottomMargin: 5, + }, // mercury coder nextedit uses full file diff, so this should be unnecessary + instinct: { topMargin: 1, bottomMargin: 5 }, +}; + // Model 1-specific tokens. -export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; -export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; -export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; -export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>"; -export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>"; -export const MODEL_1_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. +export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; +export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; +export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; +export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>"; +export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>"; +export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. You have access to the following information to help you make informed suggestions: @@ -31,7 +44,7 @@ Your task is to predict and complete the changes the developer would have made n - Provide only the revised code within the tags. Do not include the tags in your output. - Ensure that you do not output duplicate code that exists outside of these tags. - Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`; -export const MODEL_1_USER_PROMPT_PREFIX = +export const INSTINCT_USER_PROMPT_PREFIX = "Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code."; // Mercury Coder Next Edit-specific tokens. diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 23ae1d7cb..3df88e9f3 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -5,6 +5,8 @@ import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { + INSTINCT_USER_CURSOR_IS_HERE_TOKEN, + INSTINCT_USER_PROMPT_PREFIX, MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, MERCURY_CURSOR, @@ -12,8 +14,6 @@ import { MERCURY_EDIT_DIFF_HISTORY_OPEN, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, - MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { renderDefaultSystemPrompt, @@ -24,7 +24,7 @@ import { describe("NextEditPromptEngine", () => { describe("renderPrompt", () => { let mercuryHelper: HelperVars; - let model1Helper: HelperVars; + let instinctHelper: HelperVars; let testHelper: HelperVars; let unsupportedHelper: HelperVars; let ctx: any; @@ -36,8 +36,8 @@ describe("NextEditPromptEngine", () => { pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, } as HelperVars; - model1Helper = { - modelName: "continuedev/model-1" as NEXT_EDIT_MODELS, + instinctHelper = { + modelName: "continuedev/instinct" as NEXT_EDIT_MODELS, fileContents: "function test() {\n const a = 1;\n return a;\n}", pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, @@ -81,35 +81,35 @@ describe("NextEditPromptEngine", () => { expect(result.userExcerpts).toContain(MERCURY_CURSOR); }); - it("should render model-1 prompt correctly", async () => { - // Create proper model-1 context structure matching NextEditProvider.ts - const model1Ctx = { + it("should render instinct prompt correctly", async () => { + // Create proper instinct context structure matching NextEditProvider.ts + const instinctCtx = { contextSnippets: "+++++ /path/to/context.ts\nconst contextVar = 'test';", - currentFileContent: model1Helper.fileContents, + currentFileContent: instinctHelper.fileContents, windowStart: 0, // Math.max(0, helper.pos.line - 25) windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) - adjustedEditableStart: 0, // Math.max(0, helper.pos.line - 1) within window - adjustedEditableEnd: 2, // Math.min(helper.pos.line + 5) within window + editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window + editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window editDiffHistory: "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", // unified diff currentFilePath: "/path/to/file.ts", languageShorthand: "ts", }; - const result = await renderPrompt(model1Helper, model1Ctx); + const result = await renderPrompt(instinctHelper, instinctCtx); console.log(result); expect(result).toHaveProperty("prompt"); expect(result.prompt.role).toBe("user"); - expect(result.prompt.content).toContain(MODEL_1_USER_PROMPT_PREFIX); + expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX); expect(result.prompt.content).toContain("### Context:"); expect(result.prompt.content).toContain("### User Edits:"); expect(result.prompt.content).toContain("### User Excerpts:"); expect(result.prompt.content).toContain("```ts"); - expect(result.userEdits).toBe(model1Ctx.editDiffHistory); - expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); + expect(result.userEdits).toBe(instinctCtx.editDiffHistory); + expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); }); it("should throw error for unsupported model name", async () => { diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/instinct.ts similarity index 84% rename from core/nextEdit/templating/model1.ts rename to core/nextEdit/templating/instinct.ts index 821d46d3b..b7e14f165 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/instinct.ts @@ -1,10 +1,10 @@ import { Position } from "../.."; import { - MODEL_1_CONTEXT_FILE_TOKEN, - MODEL_1_EDITABLE_REGION_END_TOKEN, - MODEL_1_EDITABLE_REGION_START_TOKEN, - MODEL_1_SNIPPET_TOKEN, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + INSTINCT_CONTEXT_FILE_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, + INSTINCT_SNIPPET_TOKEN, + INSTINCT_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { insertCursorToken } from "./utils"; @@ -20,13 +20,13 @@ export function contextSnippetsBlock(contextSnippets: string) { const matches = line.match(headerRegex); if (matches) { const filename = matches[2]; - acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`); + acc.push(`${INSTINCT_CONTEXT_FILE_TOKEN}: ${filename}`); } else { if ( acc.length > 0 && - acc[acc.length - 1].startsWith(MODEL_1_CONTEXT_FILE_TOKEN) // if header was added just before + acc[acc.length - 1].startsWith(INSTINCT_CONTEXT_FILE_TOKEN) // if header was added just before ) { - acc.push(`${MODEL_1_SNIPPET_TOKEN}`); + acc.push(`${INSTINCT_SNIPPET_TOKEN}`); } acc.push(line); } @@ -49,17 +49,17 @@ export function currentFileContentBlock( const insertedCursorLines = insertCursorToken( currentFileContentLines, cursorPosition, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + INSTINCT_USER_CURSOR_IS_HERE_TOKEN, ); const instrumentedLines = [ ...insertedCursorLines.slice(windowStart, editableRegionStartLine), - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, ...insertedCursorLines.slice( editableRegionStartLine, editableRegionEndLine + 1, ), - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, ...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1), ]; diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/instinct.vitest.ts similarity index 99% rename from core/nextEdit/templating/model1.vitest.ts rename to core/nextEdit/templating/instinct.vitest.ts index b1020f040..aa15c2fcd 100644 --- a/core/nextEdit/templating/model1.vitest.ts +++ b/core/nextEdit/templating/instinct.vitest.ts @@ -4,7 +4,7 @@ import { contextSnippetsBlock, currentFileContentBlock, editHistoryBlock, -} from "./model1"; +} from "./instinct"; describe("contextSnippetsBlock", () => { test("should format empty context snippets", () => { diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts index 586fd1795..89d0f6791 100644 --- a/core/nextEdit/templating/utils.ts +++ b/core/nextEdit/templating/utils.ts @@ -1,7 +1,7 @@ import { Position } from "../.."; import { - MODEL_1_EDITABLE_REGION_END_TOKEN, - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "../constants"; @@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange( const instrumentedLines = [ ...lines.slice(0, editableRegionStart), - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, ...lines.slice(editableRegionStart, editableRegionEnd + 1), - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, ...lines.slice(editableRegionEnd + 1), ]; diff --git a/core/nextEdit/templating/utils.vitest.ts b/core/nextEdit/templating/utils.vitest.ts index f60a26d7d..92bd98c3d 100644 --- a/core/nextEdit/templating/utils.vitest.ts +++ b/core/nextEdit/templating/utils.vitest.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import { Position } from "../.."; import { - MODEL_1_EDITABLE_REGION_END_TOKEN, - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "../constants"; @@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => { const expected = [ ...lines.slice(0, expectedStart), - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, ...lines.slice(expectedStart, expectedEnd + 1), - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, ...lines.slice(expectedEnd + 1), ]; @@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => { const expected = [ "line 0", - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, "line 1", "line 2", "line 3", - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, "line 4", ]; diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 4c50e0291..d30d803e0 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -90,7 +90,7 @@ export interface NextEditTemplate { export interface TemplateVars {} -export interface Model1TemplateVars extends TemplateVars { +export interface InstinctTemplateVars extends TemplateVars { contextSnippets: string; currentFileContent: string; editDiffHistory: string; // could be a singe large unified diff From ffa1d64a554ab470f38be75e14da303e7786155c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:44:51 -0700 Subject: [PATCH 25/44] fix: accepting next edit does not count as typing --- extensions/vscode/src/extension/VsCodeExtension.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 3861edcb7..4b1d8e6ee 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -113,7 +113,8 @@ export class VsCodeExtension { Date.now() - state.lastDocumentChangeTime; if ( state.isTypingSession && - timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY + timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY && + !NextEditWindowManager.getInstance().hasAccepted() ) { console.log("VsCodeExtension: typing in progress, preserving chain"); return true; From 10d4d4cda0c252a36bac96178593d13b1ea6f2d6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:45:27 -0700 Subject: [PATCH 26/44] fix: editedCodeWithTokens uses the processed context block --- .../templating/NextEditPromptEngine.ts | 54 ++++++++++--------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 326ac4d84..98e23e45b 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -4,35 +4,33 @@ import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { + INSTINCT_USER_PROMPT_PREFIX, MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, - MERCURY_CURSOR, MERCURY_EDIT_DIFF_HISTORY_CLOSE, MERCURY_EDIT_DIFF_HISTORY_OPEN, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, - MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { + InstinctTemplateVars, MercuryTemplateVars, - Model1TemplateVars, NextEditTemplate, PromptMetadata, SystemPrompt, TemplateVars, UserPrompt, } from "../types"; +import { + contextSnippetsBlock, + currentFileContentBlock as instinctCurrentFileContentBlock, + editHistoryBlock as instinctEditHistoryBlock, +} from "./instinct"; import { currentFileContentBlock, editHistoryBlock, recentlyViewedCodeSnippetsBlock, } from "./mercuryCoderNextEdit"; -import { - contextSnippetsBlock, - currentFileContentBlock as model1CurrentFileContentBlock, - editHistoryBlock as model1EditHistoryBlock, -} from "./model1"; import { insertCursorToken, insertEditableRegionTokensWithStaticRange, @@ -44,8 +42,8 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, - "model-1": { - template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, + instinct: { + template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -95,11 +93,11 @@ export async function renderPrompt( case "mercury-coder-nextedit": { userEdits = ctx.editDiffHistory; - editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - MERCURY_CURSOR, - ); + // editedCodeWithTokens = insertTokens( + // helper.fileContents.split("\n"), + // helper.pos, + // MERCURY_CURSOR, + // ); const mercuryCtx: MercuryTemplateVars = { recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( @@ -117,20 +115,22 @@ export async function renderPrompt( tv = mercuryCtx; + editedCodeWithTokens = mercuryCtx.currentFileContent; + break; } - case "model-1": { + case "instinct": { userEdits = ctx.editDiffHistory; - editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, - ); + // editedCodeWithTokens = insertTokens( + // helper.fileContents.split("\n"), + // helper.pos, + // INSTINCT_USER_CURSOR_IS_HERE_TOKEN, + // ); - const model1Ctx: Model1TemplateVars = { + const instinctCtx: InstinctTemplateVars = { contextSnippets: contextSnippetsBlock(ctx.contextSnippets), - currentFileContent: model1CurrentFileContentBlock( + currentFileContent: instinctCurrentFileContentBlock( ctx.currentFileContent, ctx.windowStart, ctx.windowEnd, @@ -138,12 +138,14 @@ export async function renderPrompt( ctx.editableRegionEndLine, helper.pos, ), - editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory), + editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory), currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, }; - tv = model1Ctx; + tv = instinctCtx; + + editedCodeWithTokens = instinctCtx.currentFileContent; break; } From 3b878986c587faaa4f4c75358030d9592b73599e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:45:57 -0700 Subject: [PATCH 27/44] feat: sliding jump starts at the cursor line and expands outwards --- .../NextEditEditableRegionCalculator.ts | 101 +++++++++++++----- 1 file changed, 72 insertions(+), 29 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 7ced3b435..ad6a1afa2 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,11 +1,9 @@ import Parser from "web-tree-sitter"; import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; import { getAst } from "../autocomplete/util/ast"; +import { NEXT_EDIT_MODELS } from "../llm/constants"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; -import { - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, -} from "./constants"; +import { MODEL_WINDOW_SIZES } from "./constants"; export enum EditableRegionStrategy { Naive = "naive", @@ -60,16 +58,16 @@ function naiveJump(ctx: any): RangeInFile[] | null { // Sliding splits the file using into sliding window. function slidingJump(ctx: any): RangeInFile[] | null { - const { fileLines, filepath } = ctx; - if (!fileLines || !filepath) { - console.warn("Missing required context for naive jump"); + const { fileLines, filepath, modelName, currentCursorPos } = ctx; + if (!fileLines || !filepath || !modelName || !currentCursorPos) { + console.warn("Missing required context for sliding jump"); return null; } - const windowSize = - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN + - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN + - 1; // 1 for current line; + const topMargin = MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].topMargin; + const bottomMargin = + MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].bottomMargin; + const windowSize = topMargin + bottomMargin + 1; // 1 for current line if (fileLines.length <= windowSize) { return [ @@ -86,29 +84,74 @@ function slidingJump(ctx: any): RangeInFile[] | null { ]; } - const slidingStep = Math.max(1, Math.floor(windowSize / 2)); const ranges: RangeInFile[] = []; + const cursorLine = currentCursorPos.line; - for ( - let startLine = 0; - startLine < fileLines.length; - startLine += slidingStep - ) { - const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1); + // Create the first window centered around the cursor position + const firstWindowStart = Math.max(0, cursorLine - topMargin); + const firstWindowEnd = Math.min( + fileLines.length - 1, + cursorLine + bottomMargin, + ); - ranges.push({ - filepath, - range: { - start: { line: startLine, character: 0 }, - end: { - line: endLine, - character: fileLines[endLine].length, - }, + ranges.push({ + filepath, + range: { + start: { line: firstWindowStart, character: 0 }, + end: { + line: firstWindowEnd, + character: fileLines[firstWindowEnd].length, }, - }); + }, + }); - if (endLine >= fileLines.length - 1) { - break; + // Alternating pattern: down once, up once, repeat + const slidingStep = Math.max(1, Math.floor(windowSize / 2)); + let currentStartDown = firstWindowEnd + 1; + let currentStartUp = firstWindowStart - slidingStep; + while (currentStartDown < fileLines.length || currentStartUp >= 0) { + // Go down once + if (currentStartDown < fileLines.length) { + const windowStart = currentStartDown; + const windowEnd = Math.min( + windowStart + windowSize - 1, + fileLines.length - 1, + ); + + ranges.push({ + filepath, + range: { + start: { line: windowStart, character: 0 }, + end: { + line: windowEnd, + character: fileLines[windowEnd].length, + }, + }, + }); + + currentStartDown += slidingStep; + } + + // Go up once + if (currentStartUp >= 0) { + const windowStart = Math.max(0, currentStartUp); + const windowEnd = Math.min( + windowStart + windowSize - 1, + fileLines.length - 1, + ); + + ranges.push({ + filepath, + range: { + start: { line: windowStart, character: 0 }, + end: { + line: windowEnd, + character: fileLines[windowEnd].length, + }, + }, + }); + + currentStartUp -= slidingStep; } } From c34b1d82b161402b84581552b2cddf57219d8230 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 18:19:35 -0700 Subject: [PATCH 28/44] feat: diffContext is now an array --- core/nextEdit/NextEditProvider.ts | 50 ++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 67f7d1cf0..bd396cf7c 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -35,11 +35,10 @@ import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { + INSTINCT_SYSTEM_PROMPT, MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, - MODEL_1_SYSTEM_PROMPT, - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + MODEL_WINDOW_SIZES, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { @@ -83,7 +82,7 @@ export class NextEditProvider { private loggingService: NextEditLoggingService; private contextRetrievalService: ContextRetrievalService; private endpointType: "default" | "fineTuned"; - private diffContext: string = ""; + private diffContext: string[] = []; private autocompleteContext: string = ""; private promptMetadata: PromptMetadata | null = null; private currentEditChainId: string | null = null; @@ -136,7 +135,10 @@ export class NextEditProvider { } public addDiffToContext(diff: string): void { - this.diffContext = diff; + this.diffContext.push(diff); + if (this.diffContext.length > 5) { + this.diffContext.shift(); + } } public addAutocompleteContext(ctx: string): void { @@ -390,16 +392,20 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); + const modelName = helper.modelName.includes("mercury-coder-nextedit") + ? "mercury-coder-nextedit" + : "instinct"; + const { editableRegionStartLine, editableRegionEndLine } = opts?.usingFullFileDiff ? this._calculateOptimalEditableRegion(helper, "tokenizer") : { editableRegionStartLine: Math.max( - helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin, 0, ), editableRegionEndLine: Math.min( - helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin, helper.fileLines.length - 1, ), }; @@ -558,7 +564,7 @@ export class NextEditProvider { editDiffHistory: this.diffContext, currentFilePath: helper.filepath, }; - } else if (modelName.includes("model-1")) { + } else if (modelName.includes("instinct")) { // Calculate the window around the cursor position (25 lines above and below). const windowStart = Math.max(0, helper.pos.line - 25); const windowEnd = Math.min( @@ -567,10 +573,13 @@ export class NextEditProvider { ); // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). - const actualEditableStart = Math.max(0, helper.pos.line - 1); + const actualEditableStart = Math.max( + 0, + helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, + ); const actualEditableEnd = Math.min( helper.fileLines.length - 1, - helper.pos.line + 5, + helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, ); // Ensure editable region boundaries are within the window. @@ -581,8 +590,8 @@ export class NextEditProvider { currentFileContent: helper.fileContents, windowStart, windowEnd, - adjustedEditableStart, - adjustedEditableEnd, + editableRegionStartLine: adjustedEditableStart, + editableRegionEndLine: adjustedEditableEnd, editDiffHistory: this.diffContext, currentFilePath: helper.filepath, languageShorthand: helper.lang.name, @@ -598,7 +607,7 @@ export class NextEditProvider { role: "system", content: modelName.includes("mercury-coder-nextedit") ? MERCURY_SYSTEM_PROMPT - : MODEL_1_SYSTEM_PROMPT, + : INSTINCT_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; @@ -666,6 +675,8 @@ export class NextEditProvider { if (!llm) return undefined; const msg: ChatMessage = await llm.chat(prompts, token); + console.log("message"); + console.log(msg.content); if (typeof msg.content !== "string") { return undefined; @@ -677,16 +688,17 @@ export class NextEditProvider { ? replaceEscapedCharacters( msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1], ).replace(/\n$/, "") - : ""; + : replaceEscapedCharacters(msg.content); if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { return await this._handlePartialFileDiff( + // we could use fillFileDiff helper, + editableRegionStartLine, + editableRegionEndLine, startTime, llm, nextCompletion, - editableRegionStartLine, - editableRegionEndLine, ); } else { return await this._handleFullFileDiff( @@ -702,11 +714,11 @@ export class NextEditProvider { private async _handlePartialFileDiff( helper: HelperVars, + editableRegionStartLine: number, + editableRegionEndLine: number, startTime: number, llm: ILLM, nextCompletion: string, - editableRegionStartLine: number, - editableRegionEndLine: number, ): Promise { const oldEditRangeSlice = helper.fileContents .split("\n") @@ -1016,6 +1028,7 @@ export class NextEditProvider { try { const previousOutcome = this.getPreviousCompletion(); if (!previousOutcome) { + console.log("previousOutcome is undefined"); return undefined; } @@ -1026,6 +1039,7 @@ export class NextEditProvider { ctx, ); if (!input) { + console.log("input is undefined"); return undefined; } From 72399ca5ccad459c32d800a732f4ba3ead6a0217 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 18:20:05 -0700 Subject: [PATCH 29/44] feat: use a list of diffContexts instead of a single one --- core/nextEdit/templating/instinct.ts | 80 ++++++++++--------- core/nextEdit/templating/instinct.vitest.ts | 52 ++++++++++-- .../templating/mercuryCoderNextEdit.ts | 7 +- .../templating/mercuryCoderNextEdit.vitest.ts | 4 +- 4 files changed, 95 insertions(+), 48 deletions(-) diff --git a/core/nextEdit/templating/instinct.ts b/core/nextEdit/templating/instinct.ts index b7e14f165..b2140d1da 100644 --- a/core/nextEdit/templating/instinct.ts +++ b/core/nextEdit/templating/instinct.ts @@ -67,56 +67,62 @@ export function currentFileContentBlock( } export function editHistoryBlock( - editDiffHistories: string, // unified diffs with Index headers + editDiffHistories: string[], // array of unified diffs with Index headers ) { - if (!editDiffHistories.trim()) { + if (!editDiffHistories.length) { return ""; } const blocks: string[] = []; - // Split on Index: lines to get the unified diff. - const diffSections = editDiffHistories - .split(/^Index: /m) - .filter((section) => section.trim()); + for (const editDiffHistory of editDiffHistories) { + if (!editDiffHistory.trim()) { + continue; + } - for (const section of diffSections) { - const lines = section.split("\n"); + // Split on Index: lines to get the unified diff. + const diffSections = editDiffHistory + .split(/^Index: /m) + .filter((section) => section.trim()); - // Extract filename from the first line (after "Index: " was split off). - const filename = lines[0]; + for (const section of diffSections) { + const lines = section.split("\n"); - // Find the start of the actual diff content (skip ---, +++, and === lines). - const diffLines = lines - .filter( + // Extract filename from the first line (after "Index: " was split off). + const filename = lines[0]; + + // Find the start of the actual diff content (skip ---, +++, and === lines). + const diffLines = lines + .filter( + (line) => + !line.startsWith("---") && + !line.startsWith("+++") && + !line.startsWith("===") && + line.trim() !== "", // remove empty lines from header section + ) + .slice(1); // remove the filename line + + // Only include lines that are actual diff content (@@, +, -, or context lines). + const actualDiffContent = diffLines.filter( (line) => - !line.startsWith("---") && - !line.startsWith("+++") && - !line.startsWith("===") && - line.trim() !== "", // remove empty lines from header section - ) - .slice(1); // remove the filename line + line.startsWith("@@") || + line.startsWith("+") || + line.startsWith("-") || + line.startsWith(" "), // context lines + ); - // Only include lines that are actual diff content (@@, +, -, or context lines). - const actualDiffContent = diffLines.filter( - (line) => - line.startsWith("@@") || - line.startsWith("+") || - line.startsWith("-") || - line.startsWith(" "), // context lines - ); + if (actualDiffContent.length === 0) continue; - if (actualDiffContent.length === 0) continue; + const diffBlock = [ + `User edited file "${filename}"`, + "", + "```diff", + actualDiffContent.join("\n"), + "```", + ].join("\n"); - const diffBlock = [ - `User edited file "${filename}"`, - "", - "```diff", - actualDiffContent.join("\n"), - "```", - ].join("\n"); - - blocks.push(diffBlock); + blocks.push(diffBlock); + } } return blocks.join("\n"); diff --git a/core/nextEdit/templating/instinct.vitest.ts b/core/nextEdit/templating/instinct.vitest.ts index aa15c2fcd..b7972dc5d 100644 --- a/core/nextEdit/templating/instinct.vitest.ts +++ b/core/nextEdit/templating/instinct.vitest.ts @@ -291,7 +291,7 @@ line 3`; describe("editHistoryBlock", () => { test("should format empty edit history", () => { - const result = editHistoryBlock(""); + const result = editHistoryBlock([]); expect(result).toBe(""); }); @@ -306,7 +306,7 @@ describe("editHistoryBlock", () => { + console.log("new"); }`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "test.js" \`\`\`diff @@ -337,7 +337,45 @@ Index: file2.js -let x = "old"; +let x = "new";`; - const result = editHistoryBlock(unifiedDiff); + const result = editHistoryBlock([unifiedDiff]); + const expected = `User edited file "file1.js" + +\`\`\`diff +@@ -1 +1 @@ +-const old = 1; ++const new = 1; +\`\`\` +User edited file "file2.js" + +\`\`\`diff +@@ -1 +1 @@ +-let x = "old"; ++let x = "new"; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should format multiple diff history entries", () => { + // Multiple diffs should be concatenated into a single string + const unifiedDiffs = [ + `Index: file1.js +=================================================================== +--- a/file1.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1 +1 @@ +-const old = 1; ++const new = 1;`, + `Index: file2.js +=================================================================== +--- a/file2.js 2023-01-01 10:02:00.000000000 +0000 ++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 +@@ -1 +1 @@ +-let x = "old"; ++let x = "new";`, + ]; + + const result = editHistoryBlock(unifiedDiffs); const expected = `User edited file "file1.js" \`\`\`diff @@ -366,7 +404,7 @@ User edited file "file2.js" -export const Button = () => ; +export const Button = () => ;`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "src/components/Button/Button.tsx" \`\`\`diff @@ -388,7 +426,7 @@ User edited file "file2.js" + return "hello world"; +}`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "newfile.js" \`\`\`diff @@ -411,7 +449,7 @@ User edited file "file2.js" - return "goodbye"; -}`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "deletedfile.js" \`\`\`diff @@ -431,7 +469,7 @@ User edited file "file2.js" -old text +new text`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "simple.txt" \`\`\`diff diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts index 1d7950e96..80c465fc1 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -50,12 +50,15 @@ export function currentFileContentBlock( } export function editHistoryBlock( - editDiffHistory: string, // could be a singe large unified diff + editDiffHistory: string[], // could be a singe large unified diff ) { // diffHistory is made from createDiff. // This uses createPatch from npm diff library, which includes an index line and a separator. // We get rid of these first two lines. - return editDiffHistory.split("\n").slice(2).join("\n"); + return editDiffHistory + .map((diff) => diff.split("\n").slice(2).join("\n")) + .join("\n"); + // return editDiffHistory.split("\n").slice(2).join("\n"); } function mercuryNextEditTemplateBuilder( diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts index 6a1c35c74..24c1520e7 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts @@ -108,12 +108,12 @@ describe("mercuryCoderNextEdit", () => { it("should return the edit diff history unchanged", () => { const diffHistory = "diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@"; - const result = editHistoryBlock(diffHistory); + const result = editHistoryBlock([diffHistory]); expect(result).toBe("@@ -1,3 +1,4 @@"); }); it("should handle empty diff history", () => { - const result = editHistoryBlock(""); + const result = editHistoryBlock([]); expect(result).toBe(""); }); }); From f249c23f8ada580243e73b03862eaa59458bcf0e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 19:19:30 -0700 Subject: [PATCH 30/44] fix: skip redundant calculation --- core/nextEdit/NextEditProvider.ts | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index bd396cf7c..7cc7e8df6 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -572,19 +572,22 @@ export class NextEditProvider { helper.pos.line + 25, ); - // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). - const actualEditableStart = Math.max( - 0, - helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, - ); - const actualEditableEnd = Math.min( - helper.fileLines.length - 1, - helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, - ); + // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). + // const actualEditableStart = Math.max( + // 0, + // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, + // ); + // const actualEditableEnd = Math.min( + // helper.fileLines.length - 1, + // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, + // ); // Ensure editable region boundaries are within the window. - const adjustedEditableStart = Math.max(windowStart, actualEditableStart); - const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd); + const adjustedEditableStart = Math.max( + windowStart, + editableRegionStartLine, + ); + const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine); ctx = { contextSnippets: this.autocompleteContext, currentFileContent: helper.fileContents, From cec4f0f4a3ed5fa35f09586dd3f4e932c27b4044 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 12 Aug 2025 13:05:42 +0530 Subject: [PATCH 31/44] abort controller should not be undefined --- core/indexing/CodebaseIndexer.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b28ece8da..54e84bf17 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -56,7 +56,7 @@ export class CodebaseIndexer { // and only need to `await` it for tests. public initPromise: Promise; private config!: ContinueConfig; - private indexingCancellationController: AbortController | undefined; + private indexingCancellationController: AbortController; private codebaseIndexingState: IndexingProgressUpdate; private readonly pauseToken: PauseToken; @@ -97,6 +97,9 @@ export class CodebaseIndexer { this.pauseToken = new PauseToken(initialPaused); this.initPromise = this.init(configHandler); + + this.indexingCancellationController = new AbortController(); + this.indexingCancellationController.abort(); // initialize and abort so that a new one can be created } // Initialization - load config and attach config listener @@ -693,7 +696,7 @@ export class CodebaseIndexer { } public async refreshCodebaseIndex(paths: string[]) { - if (this.indexingCancellationController) { + if (!this.indexingCancellationController.signal.aborted) { this.indexingCancellationController.abort(); } const localController = new AbortController(); @@ -735,17 +738,13 @@ export class CodebaseIndexer { }); } if (this.indexingCancellationController === localController) { - this.indexingCancellationController.abort(); // abort before clearing to prevent race condition (multiple starts) - this.indexingCancellationController = undefined; + this.indexingCancellationController.abort(); } } public async refreshCodebaseIndexFiles(files: string[]) { // Can be cancelled by codebase index but not vice versa - if ( - this.indexingCancellationController && - !this.indexingCancellationController.signal.aborted - ) { + if (!this.indexingCancellationController.signal.aborted) { return; } const localController = new AbortController(); @@ -771,7 +770,7 @@ export class CodebaseIndexer { }); } if (this.indexingCancellationController === localController) { - this.indexingCancellationController = undefined; + this.indexingCancellationController.abort(); } } From 51c365c990904097a0c6e0a500cb789778795c0f Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 12 Aug 2025 15:56:52 +0530 Subject: [PATCH 32/44] style: prevent text selection when double clicking tool policy --- .../mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx index 97da69b99..09b64f2ed 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx @@ -118,7 +118,7 @@ function ToolPolicyItem(props: ToolDropdownItemProps) {
Date: Tue, 12 Aug 2025 15:37:08 +0000 Subject: [PATCH 33/44] chore(deps): bump actions/checkout from 4 to 5 Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/auto-release.yml | 4 ++-- .github/workflows/compliance.yaml | 4 ++-- .github/workflows/docs.yml | 2 +- .github/workflows/jetbrains-release.yaml | 12 +++++----- .github/workflows/label-merged-prs.yml | 2 +- .github/workflows/main-build.yaml | 2 +- .github/workflows/main.yaml | 8 +++---- .github/workflows/pr-build-upload-vsix.yaml | 2 +- .github/workflows/pr-checks.yaml | 22 +++++++++---------- .github/workflows/preview.yaml | 6 ++--- .github/workflows/reusable-release.yml | 2 +- .github/workflows/similar-issues.yml | 2 +- .../submit-github-dependency-graph.yml | 2 +- .github/workflows/vscode-version-bump.yml | 2 +- 14 files changed, 36 insertions(+), 36 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 031ed1fbe..2e047b5d0 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -16,7 +16,7 @@ jobs: contents: write # Needed for creating releases steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Get version from package.json id: get_version @@ -45,7 +45,7 @@ jobs: contents: write # Needed for creating releases steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 3b69c00cb..6ab98b27e 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -101,7 +101,7 @@ jobs: contents: read steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js uses: actions/setup-node@v4 @@ -134,7 +134,7 @@ jobs: if: ${{ !github.event.pull_request.draft }} steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Check required files run: | diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b83567fca..589a8e2ed 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js uses: actions/setup-node@v4 diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 72bd84235..a0aa2d3f0 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -56,7 +56,7 @@ jobs: # steps: # # 0. Setup git # - name: Checkout - # uses: actions/checkout@v4 + # uses: actions/checkout@v5 # - name: Set up Git # run: | @@ -102,7 +102,7 @@ jobs: steps: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: ${{ github.event.release.tag_name }} @@ -362,7 +362,7 @@ jobs: steps: # 1. Check-out repository - name: Check-out repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 # 2. Install npm dependencies - name: Use Node.js from .nvmrc @@ -429,7 +429,7 @@ jobs: steps: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Set up Java environment for the next steps - name: Setup Java @@ -482,7 +482,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Set up Java environment for the next steps - name: Setup Java @@ -513,7 +513,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Set up Java environment for the next steps - name: Setup Java diff --git a/.github/workflows/label-merged-prs.yml b/.github/workflows/label-merged-prs.yml index c3c034117..d6f83eba8 100644 --- a/.github/workflows/label-merged-prs.yml +++ b/.github/workflows/label-merged-prs.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Check if author is in tier list id: check-author diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml index 75e4104ab..a04afb945 100644 --- a/.github/workflows/main-build.yaml +++ b/.github/workflows/main-build.yaml @@ -18,7 +18,7 @@ jobs: matrix: platform: [Linux, macOS] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 2 # Get the last 2 commits to find the merge commit diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 0a5845f6d..cf276f360 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -66,7 +66,7 @@ jobs: arch: arm64 npm_config_arch: arm64 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 @@ -92,7 +92,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # This ensures all tags are fetched @@ -112,7 +112,7 @@ jobs: - build steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | @@ -145,7 +145,7 @@ jobs: steps: # 0. Setup git - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | diff --git a/.github/workflows/pr-build-upload-vsix.yaml b/.github/workflows/pr-build-upload-vsix.yaml index 6a8250a83..926855b7c 100644 --- a/.github/workflows/pr-build-upload-vsix.yaml +++ b/.github/workflows/pr-build-upload-vsix.yaml @@ -24,7 +24,7 @@ jobs: runner: macos-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 63afde345..6aa1429a8 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -14,7 +14,7 @@ jobs: prettier-check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -35,7 +35,7 @@ jobs: core-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -71,7 +71,7 @@ jobs: gui-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -101,7 +101,7 @@ jobs: binary-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -123,7 +123,7 @@ jobs: vscode-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -156,7 +156,7 @@ jobs: outputs: packages: ${{ steps.get-packages.outputs.packages }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Get package list id: get-packages run: | @@ -171,7 +171,7 @@ jobs: matrix: package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages @@ -197,7 +197,7 @@ jobs: outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -257,7 +257,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 @@ -289,7 +289,7 @@ jobs: test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} command: ["e2e:ci:run", "e2e:ci:run-yaml"] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Run VS Code E2E test uses: ./.github/actions/run-vscode-e2e-test with: @@ -303,7 +303,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Run JetBrains tests uses: ./.github/actions/run-jetbrains-tests with: diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 84e5399eb..b68a65efd 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -66,7 +66,7 @@ jobs: arch: arm64 npm_config_arch: arm64 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 @@ -96,7 +96,7 @@ jobs: - build steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | @@ -131,7 +131,7 @@ jobs: steps: # 0. Setup git - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index 80d135e29..7cab0df2a 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -47,7 +47,7 @@ jobs: working-directory: ${{ inputs.package-path }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 13ebcf269..343982af8 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout deja-view - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: repository: 'bdougie/deja-view' # Option 1: Pin to specific commit (most secure) diff --git a/.github/workflows/submit-github-dependency-graph.yml b/.github/workflows/submit-github-dependency-graph.yml index 50987cc2c..83611f4b7 100644 --- a/.github/workflows/submit-github-dependency-graph.yml +++ b/.github/workflows/submit-github-dependency-graph.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Java uses: actions/setup-java@v4 with: diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index a7aaee3d5..961fa50ba 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # Fetch all history and tags From d5860296fbea16c09f1c7b24eb48eebc9cf2280d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 13:41:44 -0700 Subject: [PATCH 34/44] feat: add debugging log method to peek first three --- core/nextEdit/NextEditPrefetchQueue.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 5cbb7ddc8..5123a841d 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -59,6 +59,11 @@ export class PrefetchQueue { !this.abortController.signal.aborted ) { const location = this.dequeueUnprocessed(); + console.log("processing:"); + console.log( + location?.range.start.line + " to " + location?.range.end.line, + ); + if (!location) break; try { @@ -70,12 +75,20 @@ export class PrefetchQueue { this.usingFullFileDiff, ); - if (!outcome) continue; + if (!outcome) { + console.log("outcome is undefined"); + continue; + } this.enqueueProcessed({ location, outcome, }); + + console.log( + "the length of processed queue after processing is:", + this.processedQueue.length, + ); } catch (error) { if (!this.abortController.signal.aborted) { // Handle error @@ -115,6 +128,16 @@ export class PrefetchQueue { return this.processedQueue[0]; } + peekThreeProcessed(): void { + const count = Math.min(3, this.processedQueue.length); + const firstThree = this.processedQueue.slice(0, count); + firstThree.forEach((item, index) => { + console.log( + `Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`, + ); + }); + } + setPreetchLimit(limit: number): void { this.prefetchLimit = limit; } From e119ae1b6a61c8a060f849b37accae491b24092c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 13:43:01 -0700 Subject: [PATCH 35/44] feat: peek for better logs --- .../vscode/src/autocomplete/completionProvider.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b81111e81..db420924c 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -261,18 +261,15 @@ export class ContinueCompletionProvider let outcome: AutocompleteOutcome | NextEditOutcome | undefined; - // console.log( - // "chain exists?", - // this.nextEditProvider.chainExists(), - // ", length:", - // this.nextEditProvider.getChainLength(), - // ", next regions queue:", - // this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(), - // ); + // TODO: We can probably decide here if we want to do the jumping logic. + // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager. + // It would simplify the logic quite substantially. // Determine why this method was triggered. const isJumping = this.jumpManager.isJumpInProgress(); const chainExists = this.nextEditProvider.chainExists(); + console.log("isJumping:", isJumping, "/ chainExists:", chainExists); + this.prefetchQueue.peekThreeProcessed(); if (isJumping && chainExists) { // Case 2: Jumping (chain exists, jump was taken) @@ -340,7 +337,6 @@ export class ContinueCompletionProvider if (isJumpSuggested) { // Store completion to be rendered after a jump. - // TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location. this.jumpManager.setCompletionAfterJump({ completionId: completionId, outcome, From db14da1cbe0f0fab2c7e2628ef1ef14ea24c0d25 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 13:54:35 -0700 Subject: [PATCH 36/44] fix: update test using the latest editDiffHistory --- .../nextEdit/templating/NextEditPromptEngine.vitest.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 3df88e9f3..0b90ecda3 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -54,7 +54,7 @@ describe("NextEditPromptEngine", () => { { filepath: "/path/to/file1.ts", content: "const b = 2;" }, ], currentFileContent: "function test() {\n const a = 1;\n return a;\n}", - editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@", + editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], editableRegionStartLine: 0, editableRegionEndLine: 3, userEdits: "Added constant a", @@ -91,8 +91,9 @@ describe("NextEditPromptEngine", () => { windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window - editDiffHistory: - "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", // unified diff + editDiffHistory: [ + "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", + ], // unified diff currentFilePath: "/path/to/file.ts", languageShorthand: "ts", }; @@ -106,7 +107,6 @@ describe("NextEditPromptEngine", () => { expect(result.prompt.content).toContain("### Context:"); expect(result.prompt.content).toContain("### User Edits:"); expect(result.prompt.content).toContain("### User Excerpts:"); - expect(result.prompt.content).toContain("```ts"); expect(result.userEdits).toBe(instinctCtx.editDiffHistory); expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); @@ -223,7 +223,7 @@ describe("NextEditPromptEngine", () => { { filepath: "/path/to/file1.ts", content: "const b = 2;" }, ], currentFileContent: "function test() {\n const a = 1;\n return a;\n}", - editDiffHistory: "diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@", + editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], editableRegionStartLine: 0, editableRegionEndLine: 3, userEdits: "Added constant a", From 308f685a6ed69811f5465e6d6804b46060e6b6c6 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 12 Aug 2025 17:58:41 -0700 Subject: [PATCH 37/44] docs: clarify apiVersion usage in Azure YAML configuration (#7109) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: clarify apiVersion usage in Azure YAML configuration - Add info box explaining apiVersion migration from JSON to YAML - Document env section parameters in YAML reference - Add Azure example showing proper apiVersion usage under env - Include link to complete YAML schema Fixes #7098 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude * docs: add apiVersion to Azure YAML examples - Add apiVersion parameter to chat model example - Add apiVersion parameter to embeddings model example - Shows proper placement under env section 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude * remove docs --------- Co-authored-by: Claude --- .../customize/model-providers/top-level/azure.mdx | 15 +++++++-------- docs/reference.mdx | 4 ++-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/docs/customize/model-providers/top-level/azure.mdx b/docs/customize/model-providers/top-level/azure.mdx index c91404df9..722a2fd97 100644 --- a/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/customize/model-providers/top-level/azure.mdx @@ -5,12 +5,6 @@ slug: ../azure Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com). - - -For details on OpenAI model setup, see [Azure OpenAI Service configuration](#azure-openai-service-configuration). - - - ## Chat model We recommend configuring **GPT-4o** as your chat model. @@ -27,6 +21,7 @@ We recommend configuring **GPT-4o** as your chat model. env: deployment: apiType: azure-foundry # Or "azure-openai" if using OpenAI models + apiVersion: 2023-07-01-preview # Azure API version ``` @@ -48,10 +43,13 @@ 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. -**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint. + **Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint + required for autocomplete functionality. To use Codestral for autocomplete, + deploy it through **Azure Machine Learning Studio** instead, which provides + the necessary `/v1/fim/completions` endpoint. If you use Azure Machine Learning Studio to deploy Codestral: @@ -100,6 +98,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. env: deployment: apiType: azure + apiVersion: 2023-07-01-preview ``` diff --git a/docs/reference.mdx b/docs/reference.mdx index c96bd7d96..06393cc2d 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -175,11 +175,11 @@ The `models` section defines the language models used in your configuration. Mod - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. Supported capabilities include: + - `tool_use`: Enables function/tool calling support (required for Agent mode) - `image_input`: Enables image upload and processing support - + Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly. - `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. From 3606665992bbb9ac1a2fa6eb1d7976f5bad407e6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 18:25:01 -0700 Subject: [PATCH 38/44] feat: add more next edit endpoints to protocol (#7110) * feat: add endpoint handlers in core * feat: export interface * feat: update protocol to support more next edit endpoints * feat: add new next edit endpoints to passthrough * feat: support new next edit endpoints to jetbrains --- core/core.ts | 69 ++++++++++++++++++- core/nextEdit/NextEditPrefetchQueue.ts | 2 +- core/protocol/core.ts | 39 ++++++++++- core/protocol/passThrough.ts | 8 +++ .../constants/MessageTypes.kt | 8 +++ 5 files changed, 121 insertions(+), 5 deletions(-) diff --git a/core/core.ts b/core/core.ts index aa558736c..d52a51e05 100644 --- a/core/core.ts +++ b/core/core.ts @@ -76,6 +76,7 @@ import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; import { getUriPathBasename } from "./util/uri"; +import { PrefetchQueue } from "./nextEdit/NextEditPrefetchQueue"; const hasRulesFiles = (uris: string[]): boolean => { for (const uri of uris) { @@ -578,18 +579,80 @@ export class Core { // Next Edit on("nextEdit/predict", async (msg) => { const outcome = await this.nextEditProvider.provideInlineCompletionItems( - msg.data, + msg.data.input, undefined, - { withChain: false, usingFullFileDiff: true }, + { + withChain: msg.data.options?.withChain ?? false, + usingFullFileDiff: msg.data.options?.usingFullFileDiff ?? true, + }, ); - return outcome ? [outcome.completion, outcome.originalEditableRange] : []; + return outcome; + // ? [outcome.completion, outcome.originalEditableRange] }); on("nextEdit/accept", async (msg) => { + console.log("nextEdit/accept"); this.nextEditProvider.accept(msg.data.completionId); }); on("nextEdit/reject", async (msg) => { + console.log("nextEdit/reject"); this.nextEditProvider.reject(msg.data.completionId); }); + on("nextEdit/startChain", async (msg) => { + console.log("nextEdit/startChain"); + NextEditProvider.getInstance().startChain(); + return; + }); + + on("nextEdit/deleteChain", async (msg) => { + console.log("nextEdit/deleteChain"); + await NextEditProvider.getInstance().deleteChain(); + return; + }); + + on("nextEdit/isChainAlive", async (msg) => { + console.log("nextEdit/isChainAlive"); + return NextEditProvider.getInstance().chainExists(); + }); + + on("nextEdit/queue/getProcessedCount", async (msg) => { + console.log("nextEdit/queue/getProcessedCount"); + const queue = PrefetchQueue.getInstance(); + console.log(queue.processedCount); + return queue.processedCount; + }); + + on("nextEdit/queue/dequeueProcessed", async (msg) => { + console.log("nextEdit/queue/dequeueProcessed"); + const queue = PrefetchQueue.getInstance(); + return queue.dequeueProcessed() || null; + }); + + on("nextEdit/queue/processOne", async (msg) => { + console.log("nextEdit/queue/processOne"); + const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data; + const queue = PrefetchQueue.getInstance(); + + await queue.process({ + ...ctx, + recentlyVisitedRanges, + recentlyEditedRanges, + }); + return; + }); + + on("nextEdit/queue/clear", async (msg) => { + console.log("nextEdit/queue/clear"); + const queue = PrefetchQueue.getInstance(); + queue.clear(); + return; + }); + + on("nextEdit/queue/abort", async (msg) => { + console.log("nextEdit/queue/abort"); + const queue = PrefetchQueue.getInstance(); + queue.abort(); + return; + }); on("streamDiffLines", async (msg) => { const { config } = await this.configHandler.loadConfig(); diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 5123a841d..8e158d0fa 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -2,7 +2,7 @@ import { RangeInFile } from ".."; import { NextEditProvider } from "./NextEditProvider"; import { NextEditOutcome } from "./types"; -interface ProcessedItem { +export interface ProcessedItem { location: RangeInFile; outcome: NextEditOutcome; // Result from the model } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 258feaaa9..ced0fb546 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -48,6 +48,8 @@ import { ControlPlaneSessionInfo, } from "../control-plane/AuthTypes"; import { FreeTrialStatus } from "../control-plane/client"; +import { NextEditOutcome } from "../nextEdit/types"; +import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; export enum OnboardingModes { API_KEY = "API Key", @@ -153,9 +155,44 @@ export type ToCoreFromIdeOrWebviewProtocol = { "context/indexDocs": [{ reIndex: boolean }, void]; "autocomplete/cancel": [undefined, void]; "autocomplete/accept": [{ completionId: string }, void]; - "nextEdit/predict": [AutocompleteInput, string[]]; + "nextEdit/predict": [ + { + input: AutocompleteInput; + options?: { + withChain?: boolean; + usingFullFileDiff?: boolean; + }; + }, + NextEditOutcome | undefined, + ]; "nextEdit/reject": [{ completionId: string }, void]; "nextEdit/accept": [{ completionId: string }, void]; + "nextEdit/startChain": [undefined, void]; + "nextEdit/deleteChain": [undefined, void]; + "nextEdit/isChainAlive": [undefined, boolean]; + "nextEdit/queue/getProcessedCount": [undefined, number]; + "nextEdit/queue/dequeueProcessed": [undefined, ProcessedItem | null]; + "nextEdit/queue/processOne": [ + { + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + void, + ]; + "nextEdit/queue/clear": [undefined, void]; + "nextEdit/queue/abort": [undefined, void]; "llm/complete": [ { prompt: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 967e0262e..7461e366e 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -40,6 +40,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "nextEdit/predict", "nextEdit/reject", "nextEdit/accept", + "nextEdit/startChain", + "nextEdit/deleteChain", + "nextEdit/isChainAlive", + "nextEdit/queue/getProcessedCount", + "nextEdit/queue/dequeueProcessed", + "nextEdit/queue/processOne", + "nextEdit/queue/clear", + "nextEdit/queue/abort", "tts/kill", "llm/complete", "llm/streamChat", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 1945bf546..e8eb4332f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -105,6 +105,14 @@ class MessageTypes { "nextEdit/predict", "nextEdit/reject", "nextEdit/accept", + "nextEdit/startChain", + "nextEdit/deleteChain", + "nextEdit/isChainAlive", + "nextEdit/queue/getProcessedCount", + "nextEdit/queue/dequeueProcessed", + "nextEdit/queue/processOne", + "nextEdit/queue/clear", + "nextEdit/queue/abort", "tts/kill", "llm/complete", "llm/streamChat", From c7fdfe497995cda7c43631a369d3d9eb62575c6c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 12 Aug 2025 20:22:43 -0700 Subject: [PATCH 39/44] feat: tool call status icon for search and replace UI (#7112) --- .../StepContainerPreToolbar/index.tsx | 30 ++++++++++ .../StyledMarkdownPreview/index.tsx | 3 + gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 5 ++ .../FunctionSpecificToolCallDiv.tsx | 3 + .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 2 +- .../pages/gui/ToolCallDiv/ToolCallDisplay.tsx | 57 +++++++++---------- gui/src/pages/gui/ToolCallDiv/index.tsx | 14 +++-- 7 files changed, 76 insertions(+), 38 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 4679c232c..e97c13061 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -1,10 +1,13 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; +import { renderContextItems } from "core/util/messageContent"; import { useContext, useEffect, useMemo, useState } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { getStatusIcon } from "../../../pages/gui/ToolCallDiv/utils"; import { useAppSelector } from "../../../redux/hooks"; +import { selectToolCallById } from "../../../redux/selectors/selectToolCalls"; import { selectApplyStateByStreamId, selectApplyStateByToolCallId, @@ -21,6 +24,7 @@ import { InsertButton } from "./InsertButton"; import { RunInTerminalButton } from "./RunInTerminalButton"; export interface StepContainerPreToolbarProps { + showToolCallStatusIcon?: boolean; codeBlockContent: string; language: string | null; relativeFilepath?: string; @@ -37,6 +41,7 @@ export interface StepContainerPreToolbarProps { } export function StepContainerPreToolbar({ + showToolCallStatusIcon, codeBlockContent, language, relativeFilepath, @@ -81,6 +86,30 @@ export function StepContainerPreToolbar({ selectApplyStateByToolCallId(state, forceToolCallId), ); + const toolCallState = useAppSelector((state) => + forceToolCallId ? selectToolCallById(state, forceToolCallId) : undefined, + ); + + const toolCallStatusIcon = + showToolCallStatusIcon && + (toolCallState?.status === "canceled" || + toolCallState?.status === "errored" || + toolCallState?.status === "done") ? ( +
{ + if (toolCallState.output) { + ideMessenger.post("showVirtualFile", { + name: "Edit output", + content: renderContextItems(toolCallState.output), + }); + } + }} + > + {getStatusIcon(toolCallState.status)} +
+ ) : null; + /** * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. * However, if no `relativeFilepath` is defined, then this will @@ -269,6 +298,7 @@ export function StepContainerPreToolbar({ style={{ fontSize: `${getFontSize() - 2}px` }} >
+ {toolCallStatusIcon} setIsExpanded(!isExpanded)} diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index 5b1249cd8..0ccab5df1 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -123,6 +123,7 @@ const StyledMarkdown = styled.div<{ `; interface StyledMarkdownPreviewProps { + showToolCallStatusIcon?: boolean; source?: string; className?: string; isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks @@ -300,6 +301,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( return ( +
-
-
-
-
-
- {icon} -
- {tool?.faviconUrl && ( - - )} - -
-
- {!!toolCallState.output && ( - - )} - {!!args.length ? ( - - ) : null} +
+
+
+
+
+ {icon}
+ {tool?.faviconUrl && ( + + )} + +
+
+ {!!toolCallState.output && ( + + )} + {!!args.length ? ( + + ) : null}
- {argsExpanded && !!args.length && ( - - )}
-
{children}
+ {argsExpanded && !!args.length && ( + + )}
- +
{children}
+
); } diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index ca99d8fdd..12556998e 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -56,10 +56,12 @@ export function ToolCallDiv({ // But we'd need a nicer place to put the truncate button and the X icon when tool call fails if (functionName === BuiltInToolNames.SearchAndReplaceInFile) { return ( - +
+ +
); } @@ -80,7 +82,7 @@ export function ToolCallDiv({ if (shouldShowGroupedUI) { return ( -
+
( -
+
{renderToolCall(toolCallState)}
)); From 76d2c4035a6e4841e62c3dc3e4be21adae766a8d Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 12 Aug 2025 21:09:01 -0700 Subject: [PATCH 40/44] Update similar-issues.yml --- .github/workflows/similar-issues.yml | 80 ++++++++++++++-------------- 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 343982af8..9873a0585 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -7,6 +7,8 @@ on: jobs: analyze: + # Disabling for now due to bugs + if: false runs-on: ubuntu-latest permissions: issues: write @@ -16,28 +18,28 @@ jobs: - name: Checkout deja-view uses: actions/checkout@v5 with: - repository: 'bdougie/deja-view' + repository: "bdougie/deja-view" # Option 1: Pin to specific commit (most secure) - ref: '45e7696' # Pin to specific commit for stability - + ref: "45e7696" # Pin to specific commit for stability + # Option 2: Use a tag (recommended after creating releases) # ref: 'v1.0.0' - + # Option 3: Use main branch (least secure, gets latest changes) # ref: 'main' - + path: deja-view - name: Setup Python uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: "3.11" - name: Install dependencies run: | cd deja-view pip install -r requirements.txt - + - name: Index repository if needed env: CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} @@ -46,10 +48,10 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | cd deja-view - + # Index the repository (this will update existing index) python cli.py index "${{ github.repository }}" --max-issues 200 || true - + - name: Search for similar issues id: search env: @@ -59,7 +61,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | cd deja-view - + # Determine if this is an issue or PR if [ "${{ github.event_name }}" = "pull_request" ]; then ISSUE_URL="https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}" @@ -70,26 +72,26 @@ jobs: THRESHOLD="0.7" TOP_K="5" fi - + # Create a Python script to search and format as JSON cat << 'PYTHON_SCRIPT' > search_similar.py import sys import json import os from github_similarity_service import SimilarityService - + issue_url = sys.argv[1] threshold = float(sys.argv[2]) top_k = int(sys.argv[3]) - + # Parse issue number from URL issue_number = int(issue_url.split('/')[-1]) repo_parts = issue_url.split('/') owner = repo_parts[3] repo = repo_parts[4] - + service = SimilarityService() - + # Find similar issues similar = service.find_similar_issues( owner=owner, @@ -98,26 +100,26 @@ jobs: top_k=top_k, min_similarity=threshold ) - + # Format as JSON print(json.dumps(similar)) PYTHON_SCRIPT - + # Search for similar issues SIMILAR_ISSUES=$(python search_similar.py "$ISSUE_URL" "$THRESHOLD" "$TOP_K") - + # Save to output echo "similar_issues<> $GITHUB_OUTPUT echo "$SIMILAR_ISSUES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - + # Check if any similar issues found if [ "$(echo "$SIMILAR_ISSUES" | jq '. | length')" -gt 0 ]; then echo "has_similar=true" >> $GITHUB_OUTPUT else echo "has_similar=false" >> $GITHUB_OUTPUT fi - + - name: Check if issue should be a discussion id: discussion_check if: github.event_name == 'issues' @@ -128,19 +130,19 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | cd deja-view - + # Create a Python script to analyze the issue cat << 'PYTHON_SCRIPT' > check_discussion.py import os import json import re from github_similarity_service import SimilarityService - + # Get issue details from environment issue_title = os.environ.get('ISSUE_TITLE', '') issue_body = os.environ.get('ISSUE_BODY', '') issue_labels = json.loads(os.environ.get('ISSUE_LABELS', '[]')) - + # Mock Issue object for analysis class MockIssue: def __init__(self): @@ -152,41 +154,41 @@ jobs: self.created_at = '' self.updated_at = '' self.url = '' - + service = SimilarityService() issue = MockIssue() - + score, reasons = service._calculate_discussion_score(issue) - + result = { 'score': score, 'reasons': reasons, 'should_be_discussion': score >= 0.5, 'confidence': 'high' if score >= 0.7 else 'medium' if score >= 0.5 else 'low' } - + print(json.dumps(result)) PYTHON_SCRIPT - + # Run the analysis DISCUSSION_ANALYSIS=$(ISSUE_TITLE="${{ github.event.issue.title }}" \ ISSUE_BODY='${{ github.event.issue.body }}' \ ISSUE_LABELS='${{ toJson(github.event.issue.labels.*.name) }}' \ ISSUE_NUMBER="${{ github.event.issue.number }}" \ python check_discussion.py) - + echo "analysis<> $GITHUB_OUTPUT echo "$DISCUSSION_ANALYSIS" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - + # Extract whether it should be a discussion SHOULD_BE_DISCUSSION=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.should_be_discussion') echo "should_be_discussion=$SHOULD_BE_DISCUSSION" >> $GITHUB_OUTPUT - + # Extract confidence level CONFIDENCE=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.confidence') echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT - + - name: Comment with analysis uses: actions/github-script@v7 with: @@ -195,7 +197,7 @@ jobs: const hasSimilar = '${{ steps.search.outputs.has_similar }}' === 'true'; const isPR = '${{ github.event_name }}' === 'pull_request'; const shouldBeDiscussion = !isPR && '${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true'; - + // Add similar issues section if found if (hasSimilar) { const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`); @@ -243,7 +245,7 @@ jobs: comment += '\n'; } } - + // Add discussion suggestion if applicable if (shouldBeDiscussion) { const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`); @@ -280,7 +282,7 @@ jobs: comment += '_Consider converting this to a discussion if it\'s not a bug report or actionable task._\n'; } - + // Only comment if we have something to say if (comment) { comment += '\n---\n'; @@ -302,14 +304,14 @@ jobs: }); } } - + - name: Add labels if: github.event_name == 'issues' uses: actions/github-script@v7 with: script: | const labels = []; - + // Check for duplicate if ('${{ steps.search.outputs.has_similar }}' === 'true') { const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`); @@ -319,7 +321,7 @@ jobs: labels.push('potential-duplicate'); } } - + // Check for discussion suggestion if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') { const confidence = '${{ steps.discussion_check.outputs.confidence }}'; @@ -330,7 +332,7 @@ jobs: labels.push('discussion'); } } - + // Add labels if any if (labels.length > 0) { await github.rest.issues.addLabels({ From d2645f9e5f50d1f0f68a12c90b554adcb63d74b3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Aug 2025 17:05:02 +0000 Subject: [PATCH 41/44] chore(deps): bump actions/checkout from 4 to 5 Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/continue-review.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 95a9c48ea..3ca4ffab4 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -33,7 +33,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # Fetch full history for better context From 29f9e8588da51544d731c0d96a2f507a92f6e7d2 Mon Sep 17 00:00:00 2001 From: Ty Dunn Date: Wed, 13 Aug 2025 11:04:48 -0700 Subject: [PATCH 42/44] update front page of docs --- docs/home.mdx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/home.mdx b/docs/home.mdx index 7e2dcc7cb..d5d4416d6 100644 --- a/docs/home.mdx +++ b/docs/home.mdx @@ -2,9 +2,16 @@ title: "Introduction" --- -**Continue enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)** +**Continue enables developers to ship faster with Continuous AI.** -- [Chat](/features/chat/quick-start) to understand and iterate on code in the sidebar -- [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type -- [Edit](/features/edit/quick-start) to modify code without leaving your current file +**You can use Continue to build and run custom agents across your IDE, terminal, and CI.** + +1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions: - [Agent](/features/agent/quick-start) to make more substantial changes to your codebase +- [Chat](/features/chat/quick-start) to understand and iterate on code in the sidebar +- [Edit](/features/edit/quick-start) to modify code without leaving your current file +- [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type + +2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback. + +3. Discover the models, rules, and MCP tools you need to create a custom AI coding agent on [Continue Hub](https://hub.continue.dev/) From 6226f175835e49ee2f17a5ebf83d427e31d68eac Mon Sep 17 00:00:00 2001 From: Ty Dunn Date: Wed, 13 Aug 2025 11:07:50 -0700 Subject: [PATCH 43/44] remove period --- docs/home.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/home.mdx b/docs/home.mdx index d5d4416d6..d9f81befd 100644 --- a/docs/home.mdx +++ b/docs/home.mdx @@ -12,6 +12,6 @@ title: "Introduction" - [Edit](/features/edit/quick-start) to modify code without leaving your current file - [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type -2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback. +2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback 3. Discover the models, rules, and MCP tools you need to create a custom AI coding agent on [Continue Hub](https://hub.continue.dev/) From 0f15e036f0539f325bdd6b976826f5ba5e76d9a1 Mon Sep 17 00:00:00 2001 From: Ty Dunn Date: Wed, 13 Aug 2025 11:20:35 -0700 Subject: [PATCH 44/44] better agent / chat distinction --- docs/home.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/home.mdx b/docs/home.mdx index d9f81befd..a24548999 100644 --- a/docs/home.mdx +++ b/docs/home.mdx @@ -7,9 +7,9 @@ title: "Introduction" **You can use Continue to build and run custom agents across your IDE, terminal, and CI.** 1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions: -- [Agent](/features/agent/quick-start) to make more substantial changes to your codebase -- [Chat](/features/chat/quick-start) to understand and iterate on code in the sidebar -- [Edit](/features/edit/quick-start) to modify code without leaving your current file +- [Agent](/features/agent/quick-start) to work on development tasks together with AI +- [Chat](/features/chat/quick-start) to ask general questions and clarify code sections +- [Edit](/features/edit/quick-start) to modify code section without leaving your current file - [Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type 2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback