From ff5e7092dddd36ad746d1b5b524a0c9d5c47d0f2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 20 Jul 2025 10:14:14 +0200 Subject: [PATCH 01/20] feat: onlyUseSystemMessageTools experimental setting --- core/config/sharedConfig.ts | 6 ++++++ core/config/types.ts | 1 - core/index.d.ts | 1 + gui/src/pages/config/UserSettingsForm.tsx | 12 ++++++++++++ gui/src/pages/gui/StreamError.tsx | 2 -- 5 files changed, 19 insertions(+), 3 deletions(-) diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index c720f4272..8412c71b7 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -21,6 +21,7 @@ export const sharedConfigSchema = z useCurrentFileAsContext: z.boolean(), optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), + onlyUseSystemMessageTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), // `ui` in `ContinueConfig` @@ -184,6 +185,11 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.optInNextEditFeature = sharedConfig.optInNextEditFeature; } + if (sharedConfig.onlyUseSystemMessageTools !== undefined) { + configCopy.experimental.onlyUseSystemMessageTools = + sharedConfig.onlyUseSystemMessageTools; + } + if (sharedConfig.codebaseToolCallingOnly !== undefined) { configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; diff --git a/core/config/types.ts b/core/config/types.ts index 406f40ddd..0c2a7cd70 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -1122,7 +1122,6 @@ declare global { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - useTools?: boolean; modelContextProtocolServers?: MCPOptions[]; } diff --git a/core/index.d.ts b/core/index.d.ts index c2bc7487b..980048ef4 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1443,6 +1443,7 @@ export interface ExperimentalConfig { defaultContext?: DefaultContextProvider[]; promptPath?: string; enableExperimentalTools?: boolean; + onlyUseSystemMessageTools?: boolean; /** * Quick actions are a way to add custom commands to the Code Lens of diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 9eea8003b..eb4d30d1f 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -88,6 +88,8 @@ export function UserSettingsForm() { config.experimental?.useCurrentFileAsContext ?? false; const enableExperimentalTools = config.experimental?.enableExperimentalTools ?? false; + const onlyUseSystemMessageTools = + config.experimental?.onlyUseSystemMessageTools ?? false; const optInNextEditFeature = config.experimental?.optInNextEditFeature ?? false; const codebaseToolCallingOnly = @@ -419,6 +421,16 @@ export function UserSettingsForm() { text="Enable experimental tools" /> + + handleUpdate({ + onlyUseSystemMessageTools: !onlyUseSystemMessageTools, + }) + } + text="Only use system message tools" + /> + diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 58fcaf97b..a49e5f795 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -246,8 +246,6 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); } - console.log({ message }); - return (
{/* Concise error title */} From dde117e471299c34bab98b4e1c1ab06ee3e6034d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 20 Jul 2025 10:22:43 +0200 Subject: [PATCH 02/20] feat: warning for models not great with tools --- core/llm/autodetect.ts | 20 +---- core/llm/toolSupport.ts | 29 +++++++ gui/src/components/ModeSelect/ModeSelect.tsx | 87 +++++++++++-------- .../StepContainer/ResponseActions.tsx | 4 +- gui/src/components/mainInput/InputToolbar.tsx | 6 +- gui/src/redux/thunks/streamNormalInput.ts | 4 +- 6 files changed, 86 insertions(+), 64 deletions(-) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index a220b5dbd..92693456d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,9 +1,4 @@ -import { - ChatMessage, - ModelCapability, - ModelDescription, - TemplateType, -} from "../index.js"; +import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; import { anthropicTemplateMessages, @@ -41,7 +36,6 @@ import { xWinCoderEditPrompt, zephyrEditPrompt, } from "./templates/edit.js"; -import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js"; const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", @@ -107,17 +101,6 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "granite-vision", ]; -function modelSupportsTools(modelDescription: ModelDescription) { - if (modelDescription.capabilities?.tools !== undefined) { - return modelDescription.capabilities.tools; - } - const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; - if (!providerSupport) { - return false; - } - return providerSupport(modelDescription.model) ?? false; -} - function modelSupportsImages( provider: string, model: string, @@ -400,5 +383,4 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools, }; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ccaf906ce..f1eb14ad4 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -1,4 +1,5 @@ import { parseProxyModelName } from "@continuedev/config-yaml"; +import { ModelDescription } from ".."; export const PROVIDER_TOOL_SUPPORT: Record boolean> = { @@ -287,3 +288,31 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, }; + +export function isRecommendedAgentModel(modelName: string): boolean { + // AND behavior + const recs: RegExp[][] = [ + [/o[134]/], + [/deepseek/, /r1|reasoner/], + [/gemini/, /2\.5/, /pro/], + [/gpt/, /4/], + [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], + [/claude/, /opus/, /-4/], + ]; + for (const combo of recs) { + if (combo.every((regex) => modelName.toLowerCase().match(regex))) { + return true; + } + } + return false; +} +export function modelSupportsNativeTools(modelDescription: ModelDescription) { + if (modelDescription.capabilities?.tools !== undefined) { + return modelDescription.capabilities.tools; + } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; + if (!providerSupport) { + return false; + } + return providerSupport(modelDescription.model) ?? false; +} diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index b7bc81c2e..caffe9181 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -1,10 +1,12 @@ import { CheckIcon, ChevronDownIcon, + ExclamationCircleIcon, InformationCircleIcon, } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { isRecommendedAgentModel } from "core/llm/toolSupport"; +import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; @@ -19,24 +21,17 @@ export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); - const agentModeSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + const showAgentModeWarning = useMemo(() => { + if (!selectedModel || isRecommendedAgentModel(selectedModel.model)) { + return false; // no need to show warning if no model is selected + } + return true; }, [selectedModel]); const { mainEditor } = useMainEditor(); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); }, []); - // Switch to chat mode if agent mode is selected but not supported - useEffect(() => { - if (!selectedModel) { - return; - } - if (mode !== "chat" && !agentModeSupported) { - dispatch(setMode("chat")); - } - }, [mode, agentModeSupported, dispatch, selectedModel]); - const cycleMode = useCallback(() => { if (mode === "chat") { dispatch(setMode("plan")); @@ -76,6 +71,37 @@ export function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [cycleMode]); + const agentWarning = ( + <> + + + {`${capitalize(mode)} might not work well with this model.`} + {/* can't seem to make link in tooltip clickable. globalCloseEvents or closeEvents? */} + {/* { + ideMessenger.post( + "openUrl", + "https://docs.continue.dev/agent/model-setup", + ); + }} + className="text-link cursor-pointer" + > + See docs + */} + + + ); + return (
@@ -117,11 +143,7 @@ export function ModeSelect() {
{mode === "chat" && } - +
Plan @@ -138,19 +160,13 @@ export function ModeSelect() { Read-only/MCP tools available
- {agentModeSupported ? ( - - ) : ( - (Not supported) - )} + {showAgentModeWarning && agentWarning} +
- + +
Agent @@ -167,13 +183,10 @@ export function ModeSelect() { All tools available
- {agentModeSupported ? ( - - ) : ( - (Not supported) - )} + {showAgentModeWarning && agentWarning} +
diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 068432792..0dc09a438 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -5,7 +5,7 @@ import { TrashIcon, } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { renderChatMessage } from "core/util/messageContent"; import { useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -41,7 +41,7 @@ export default function ResponseActions({ ); const isPruned = useAppSelector((state) => state.session.isPruned); const ruleGenerationSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + return selectedModel && modelSupportsNativeTools(selectedModel); }, [selectedModel]); const percent = Math.round((contextPercentage ?? 0) * 100); diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 9be9f25d9..f97c7d101 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -4,7 +4,7 @@ import { PhotoIcon, } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; -import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsImages } from "core/llm/autodetect"; import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -57,8 +57,6 @@ function InputToolbar(props: InputToolbarProps) { const isEnterDisabled = props.disabled || (isInEdit && codeToEdit.length === 0); - const toolsSupported = defaultModel && modelSupportsTools(defaultModel); - const supportsImages = defaultModel && modelSupportsImages( @@ -174,7 +172,7 @@ function InputToolbar(props: InputToolbarProps) { {!isInEdit && } {!props.toolbarOptions?.hideUseCodebase && !isInEdit && ( - {showAgentModeWarning && agentWarning} - + {isAgentSupported ? ( + <> + {!isGoodAtAgentMode && notGreatAtAgent} + + + ) : ( + notSupported + )} @@ -183,10 +201,16 @@ export function ModeSelect() { All tools available
- {showAgentModeWarning && agentWarning} - + {isAgentSupported ? ( + <> + {!isGoodAtAgentMode && notGreatAtAgent} + + + ) : ( + notSupported + )}
From 74dd75a15920d775f0b8cf7605deb72447a0e48a Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 23 Jul 2025 22:29:18 -0700 Subject: [PATCH 14/20] fix edit tool by adjusting prompt to say "diffs" instead of "diff" --- .../definitions/searchAndReplaceInFile.ts | 2 +- .../complexToolCall.vitest.ts | 304 ++++++++++++++++++ gui/src/util/clientTools/searchReplaceImpl.ts | 45 ++- 3 files changed, 346 insertions(+), 5 deletions(-) create mode 100644 core/tools/systemMessageTools/complexToolCall.vitest.ts diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index aa12e7c72..96dac65da 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -104,7 +104,7 @@ ${SEARCH_AND_REPLACE_RULES} [ ["filepath", "path/to/file.ts"], [ - "diff", + "diffs", `[ "------- SEARCH [exact content to find] diff --git a/core/tools/systemMessageTools/complexToolCall.vitest.ts b/core/tools/systemMessageTools/complexToolCall.vitest.ts new file mode 100644 index 000000000..954427ee2 --- /dev/null +++ b/core/tools/systemMessageTools/complexToolCall.vitest.ts @@ -0,0 +1,304 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { AssistantChatMessage, ChatMessage, PromptLog } from "../.."; +import { interceptSystemToolCalls } from "./interceptSystemToolCalls"; + +describe("interceptSystemToolCalls - Complex Tool Call Test", () => { + let abortController: AbortController; + + beforeEach(() => { + abortController = new AbortController(); + }); + + const createAsyncGenerator = async function* ( + messages: ChatMessage[][], + ): AsyncGenerator { + for (const messageGroup of messages) { + yield messageGroup; + } + return undefined; + }; + + function isAssistantMessageWithToolCalls( + message: ChatMessage, + ): message is AssistantChatMessage { + return ( + message.role === "assistant" && + "toolCalls" in message && + message.toolCalls !== undefined && + message.toolCalls.length > 0 + ); + } + + async function collectAllResults( + generator: AsyncGenerator, + ): Promise { + const results: ChatMessage[][] = []; + while (true) { + const result = await generator.next(); + if (result.done) break; + if (result.value) results.push(result.value); + } + return results; + } + + it("handles complex multi-line tool arguments with nested content and special characters", async () => { + // This test case is based on the example.txt which has complex nested content + // that includes JSON arrays, code blocks, escape characters, and the word "assistant" + const complexDiffContent = `I'll add an exp method to the Calculator class in test.js. This method will raise the current result to the power of a given number. + +\`\`\`tool +TOOL_NAME: search_and_replace_in_file +BEGIN_ARG: filepath +test.js +END_ARG +BEGIN_ARG: diff +[ +"------- SEARCH + /** + * Divide the current result by a number + * @param {number} number - The number to divide by + * @ +assistant +returns {Calculator} - Returns this instance for method chaining + * @throws {Error} - Throws error if attempting to divide by zero + */ + divide(number) { + if (number === 0) { + throw new Error(\"Cannot divide by zero\"); + } + this.result /= number; + return this; + } + +======= + /** + * Divide the current result by a number + * @param {number} number - The number to +assistant + divide by + * @returns {Calculator} - Returns this instance for method chaining + * @throws {Error} - Throws error if attempting to divide by zero + */ + divide(number) { + if (number === 0) { + throw new Error(\"Cannot divide by zero\"); + } + this.result /= number; + return this; + } + + /** + * Raise the current result to the power of a number + * +assistant + @param {number} number - The exponent to raise to + * @returns {Calculator} - Returns this instance for method chaining + */ + exp(number) { + this.result = Math.pow(this.result, number); + return this; + } + ++++++++ REPLACE" +] +END_ARG +\`\`\``; + + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: + "I'll add an exp method to the Calculator class in test.js.\n\n", + }, + ], + [{ role: "assistant", content: "```tool\n" }], + [ + { + role: "assistant", + content: "TOOL_NAME: search_and_replace_in_file\n", + }, + ], + [{ role: "assistant", content: "BEGIN_ARG: filepath\n" }], + [{ role: "assistant", content: "test.js\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "BEGIN_ARG: diffs\n" }], + [{ role: "assistant", content: complexDiffContent }], + [{ role: "assistant", content: "\nEND_ARG\n" }], + [{ role: "assistant", content: "```" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + const allResults = await collectAllResults(generator); + + // Should have processed intro text + expect(allResults[0]).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "I'll add an exp method to the Calculator class in test.js.", + }, + ], + }, + ]); + + // Should have detected and parsed the tool call + const toolCallResults = allResults.filter( + (r): r is AssistantChatMessage[] => + r && r[0] && isAssistantMessageWithToolCalls(r[0]), + ); + + expect(toolCallResults.length).toBeGreaterThan(0); + + // Tool name should be correct + const toolNameResult = toolCallResults.find( + (r) => + r[0].toolCalls?.[0]?.function?.name === "search_and_replace_in_file", + ); + expect(toolNameResult).toBeTruthy(); + + // Reconstruct the full arguments from all deltas + let fullArgs = ""; + for (const toolResult of toolCallResults) { + fullArgs += toolResult[0].toolCalls?.[0]?.function?.arguments || ""; + } + + console.log("Full args reconstructed:", fullArgs); + + // Should be valid JSON + expect(() => JSON.parse(fullArgs)).not.toThrow(); + + const parsed = JSON.parse(fullArgs); + expect(parsed.filepath).toBe("test.js"); + expect(parsed.diffs).toBeTruthy(); + + // The diffs should contain the complex content including special markers + const diffContent1 = + typeof parsed.diffs === "string" + ? parsed.diffs + : JSON.stringify(parsed.diffs); + expect(diffContent1).toContain("SEARCH"); + expect(diffContent1).toContain("REPLACE"); + expect(diffContent1).toContain("Cannot divide by zero"); + expect(diffContent1).toContain("assistant"); // Word should be preserved in content + }); + + it("handles arguments with embedded JSON and special escape sequences", async () => { + // Test with JSON array containing embedded quotes and backslashes + const jsonArrayContent = `["first item", "second \\"quoted\\" item", "third\\nitem"]`; + + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: json_array\n" }], + [{ role: "assistant", content: jsonArrayContent }], + [{ role: "assistant", content: "\nEND_ARG\n" }], + [{ role: "assistant", content: "```" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + const allResults = await collectAllResults(generator); + + // Should have parsed the tool call + const toolCallResults = allResults.filter( + (r): r is AssistantChatMessage[] => + r && r[0] && isAssistantMessageWithToolCalls(r[0]), + ); + + expect(toolCallResults.length).toBeGreaterThan(0); + + // Reconstruct the full arguments + let fullArgs = ""; + for (const toolResult of toolCallResults) { + fullArgs += toolResult[0].toolCalls?.[0]?.function?.arguments || ""; + } + + // Should be valid JSON + expect(() => JSON.parse(fullArgs)).not.toThrow(); + + const parsed = JSON.parse(fullArgs); + expect(parsed.json_array).toBeTruthy(); + + // The parsed array should be correct + const arrayValue = + typeof parsed.json_array === "string" + ? JSON.parse(parsed.json_array) + : parsed.json_array; + + expect(Array.isArray(arrayValue)).toBe(true); + expect(arrayValue).toHaveLength(3); + expect(arrayValue[0]).toBe("first item"); + expect(arrayValue[1]).toBe('second "quoted" item'); + expect(arrayValue[2]).toBe("third\nitem"); + }); + + it("simulates the exact user scenario that causes parsing issues", async () => { + // This simulates the exact scenario from example.txt that was causing issues + const userProblemDiff = `[ +"------- SEARCH + /** + * Divide the current result by a number + * @param {number} number - The number to divide by + * @returns {Calculator} - Returns this instance for method chaining + * @throws {Error} - Throws error if attempting to divide by zero + */ + divide(number) { + if (number === 0) { + throw new Error(\"Cannot divide by zero\"); + } + this.result /= number; + return this; + } +======= + /** + * Divide the current result by a number + * @param {number} number - The number to divide by + * @returns {Calculator} - Returns this instance for method chaining + * @throws {Error} - Throws error if attempting to divide by zero + */ + divide(number) { + if (number === 0) { + throw new Error(\"Cannot divide by zero\"); + } + this.result /= number; + return this; + } + + /** + * Raise the current result to the power of a number + * @param {number} number - The exponent to raise to + * @returns {Calculator} - Returns this instance for method chaining + */ + exp(number) { + this.result = Math.pow(this.result, number); + return this; + } ++++++++ REPLACE" +]`; + + // Test that the JSON string can be properly parsed and used + let parsed; + expect(() => { + parsed = JSON.parse(userProblemDiff); + }).not.toThrow(); + + expect(Array.isArray(parsed)).toBe(true); + expect(parsed!.length).toBe(1); + + const diffContent = parsed![0]; + expect(diffContent).toContain("------- SEARCH"); + expect(diffContent).toContain("======="); + expect(diffContent).toContain("+++++++ REPLACE"); + expect(diffContent).toContain("Cannot divide by zero"); + }); +}); diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts index 1fcf649e5..bdd04a5e7 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.ts @@ -10,13 +10,45 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( toolCallId, extras, ) => { - const { filepath, diffs } = args; + const { filepath } = args; + let { diffs } = args; + + // Handle legacy parameter name and system message tools edge cases + if (!diffs && (args as any).diff) { + diffs = (args as any).diff; + } + + if (!diffs) { + throw new Error("Missing required parameter: diffs (or diff)"); + } const state = extras.getState(); const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; const streamId = uuid(); + // Handle the case where system message tools provide diffs as a JSON string + // instead of an actual array (due to JSON parsing/stringifying in system message tools) + let processedDiffs: string[]; + if (typeof diffs === "string") { + try { + const parsed = JSON.parse(diffs); + if (Array.isArray(parsed)) { + processedDiffs = parsed; + } else { + processedDiffs = [diffs]; + } + } catch (e) { + processedDiffs = [diffs]; + } + } else if (Array.isArray(diffs)) { + processedDiffs = diffs; + } else { + throw new Error( + "diffs parameter must be an array of strings or a JSON string representing an array", + ); + } + // Resolve the file path const resolvedFilepath = await resolveRelativePathInDir( filepath, @@ -28,11 +60,16 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( // Parse all search/replace blocks from all diff strings const allBlocks = []; - for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) { - const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]); + for (let diffIndex = 0; diffIndex < processedDiffs.length; diffIndex++) { + const blocks = parseAllSearchReplaceBlocks(processedDiffs[diffIndex]); if (blocks.length === 0) { throw new Error( - `No complete search/replace blocks found in diff ${diffIndex + 1}`, + `No complete search/replace blocks found in diff ${diffIndex + 1}. Each diff must contain at least one complete SEARCH/REPLACE block with the format: +------- SEARCH +[content to find] +======= +[replacement content] ++++++++ REPLACE`, ); } allBlocks.push(...blocks); From 96780f5abf6437daccfb6d92bcfa1131ee912196 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 23 Jul 2025 23:03:57 -0700 Subject: [PATCH 15/20] remove comments --- manual-testing-sandbox/test.js | 37 +--------------------------------- 1 file changed, 1 insertion(+), 36 deletions(-) diff --git a/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js index 0e60af4e0..44c55402e 100644 --- a/manual-testing-sandbox/test.js +++ b/manual-testing-sandbox/test.js @@ -1,50 +1,23 @@ -/** - * Calculator class for performing basic arithmetic operations - * Uses method chaining to allow consecutive operations - */ class Calculator { - /** - * Initialize calculator with result set to 0 - */ constructor() { this.result = 0; } - /** - * Add a number to the current result - * @param {number} number - The number to add - * @returns {Calculator} - Returns this instance for method chaining - */ add(number) { this.result += number; return this; } - /** - * Subtract a number from the current result - * @param {number} number - The number to subtract - * @returns {Calculator} - Returns this instance for method chaining - */ subtract(number) { + this.result -= number; return this; } - /** - * Multiply the current result by a number - * @param {number} number - The number to multiply by - * @returns {Calculator} - Returns this instance for method chaining - */ multiply(number) { this.result *= number; return this; } - /** - * Divide the current result by a number - * @param {number} number - The number to divide by - * @returns {Calculator} - Returns this instance for method chaining - * @throws {Error} - Throws error if attempting to divide by zero - */ divide(number) { if (number === 0) { throw new Error("Cannot divide by zero"); @@ -53,18 +26,10 @@ class Calculator { return this; } - /** - * Get the current result value - * @returns {number} - The current result - */ getResult() { return this.result; } - /** - * Reset the result to 0 - * @returns {Calculator} - Returns this instance for method chaining - */ reset() { this.result = 0; return this; From 85ba04a4c7d8b4db19ffda4a5a6e66678bf534ea Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 23 Jul 2025 23:27:34 -0700 Subject: [PATCH 16/20] improve error message for failed read file tool --- core/tools/implementations/readFile.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index a026d0f47..ae8964445 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -10,7 +10,9 @@ export const readFileImpl: ToolImpl = async (args, extras) => { const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); if (!firstUriMatch) { - throw new Error(`Could not find file ${filepath}`); + throw new Error( + `File "${filepath}" does not exist. You might want to check the path and try again.`, + ); } const content = await extras.ide.readFile(firstUriMatch); From ec9d3157bb3d4413db982fd84eb3bb3d85301eab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 24 Jul 2025 19:06:42 +0700 Subject: [PATCH 17/20] fix: system message tools array args for search and replace tool --- .../definitions/searchAndReplaceInFile.ts | 2 +- .../systemMessageTools/parseSystemToolCall.ts | 21 ++++++++++- .../parseSystemToolCall.vitest.ts | 32 ++++++++++++++++ manual-testing-sandbox/test.js | 37 ------------------- 4 files changed, 53 insertions(+), 39 deletions(-) diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index aa12e7c72..96dac65da 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -104,7 +104,7 @@ ${SEARCH_AND_REPLACE_RULES} [ ["filepath", "path/to/file.ts"], [ - "diff", + "diffs", `[ "------- SEARCH [exact content to find] diff --git a/core/tools/systemMessageTools/parseSystemToolCall.ts b/core/tools/systemMessageTools/parseSystemToolCall.ts index 74dc6f470..0300654d9 100644 --- a/core/tools/systemMessageTools/parseSystemToolCall.ts +++ b/core/tools/systemMessageTools/parseSystemToolCall.ts @@ -87,12 +87,31 @@ export function handleToolCallBuffer( if (isNewLine) { const isEndArgTag = line.match(/end_?arg/i); if (isEndArgTag) { - const trimmedValue = state.currentArgLines.join("").trim(); + let trimmedValue = state.currentArgLines.join("").trim(); state.currentArgLines.length = 0; state.processedArgNames.add(state.currentArgName); state.currentArgName = undefined; try { + if ( + trimmedValue.startsWith("[") || + trimmedValue.startsWith("{") + ) { + trimmedValue = trimmedValue.replace( + /"((?:\\[\s\S]|[^"\\])*?)"/g, + (match) => { + const content = match.slice(1, -1); + // Replace unescaped newlines + return ( + '"' + + content + .replace(/([^\\])\n/g, "$1\\n") + .replace(/^\n/g, "\\n") + + '"' + ); + }, + ); + } const parsed = JSON.parse(trimmedValue); const stringifiedArg = JSON.stringify(parsed); return createDelta("", stringifiedArg, state.toolCallId); diff --git a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts b/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts index 436e3fa6e..2aeac2ce8 100644 --- a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts +++ b/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts @@ -266,4 +266,36 @@ describe("handleToolCallBuffer", () => { }); expect(state.done).toBe(true); }); + + it("handles JSON array args", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = [ + "[\n", + '"------- SEARCH\n', + " subtract(number) {\n", + " return this;\n", + " }\n", + "=======\n", + " subtract(number) {\n", + " this -= number\n", + " return this;\n", + " }\n", + '+++++++ REPLACE"\n', + "]\n", + ]; + + handleToolCallBuffer("END_ARG", state); + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: + '["------- SEARCH\\n subtract(number) {\\n return this;\\n }\\n=======\\n subtract(number) {\\n this -= number\\n return this;\\n }\\n+++++++ REPLACE"]', + }, + id: expect.any(String), + }); + }); }); diff --git a/manual-testing-sandbox/test.js b/manual-testing-sandbox/test.js index 0e60af4e0..d2920d6af 100644 --- a/manual-testing-sandbox/test.js +++ b/manual-testing-sandbox/test.js @@ -1,50 +1,21 @@ -/** - * Calculator class for performing basic arithmetic operations - * Uses method chaining to allow consecutive operations - */ class Calculator { - /** - * Initialize calculator with result set to 0 - */ constructor() { this.result = 0; } - /** - * Add a number to the current result - * @param {number} number - The number to add - * @returns {Calculator} - Returns this instance for method chaining - */ add(number) { this.result += number; return this; } - - /** - * Subtract a number from the current result - * @param {number} number - The number to subtract - * @returns {Calculator} - Returns this instance for method chaining - */ subtract(number) { return this; } - /** - * Multiply the current result by a number - * @param {number} number - The number to multiply by - * @returns {Calculator} - Returns this instance for method chaining - */ multiply(number) { this.result *= number; return this; } - /** - * Divide the current result by a number - * @param {number} number - The number to divide by - * @returns {Calculator} - Returns this instance for method chaining - * @throws {Error} - Throws error if attempting to divide by zero - */ divide(number) { if (number === 0) { throw new Error("Cannot divide by zero"); @@ -53,18 +24,10 @@ class Calculator { return this; } - /** - * Get the current result value - * @returns {number} - The current result - */ getResult() { return this.result; } - /** - * Reset the result to 0 - * @returns {Calculator} - Returns this instance for method chaining - */ reset() { this.result = 0; return this; From 3adf4b62a7019936f578cdcd1d72015827858b24 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 24 Jul 2025 19:12:21 +0700 Subject: [PATCH 18/20] chore: revert duplicate fix logic for search and replace array args --- .../complexToolCall.vitest.ts | 304 ------------------ gui/src/util/clientTools/searchReplaceImpl.ts | 45 +-- 2 files changed, 4 insertions(+), 345 deletions(-) delete mode 100644 core/tools/systemMessageTools/complexToolCall.vitest.ts diff --git a/core/tools/systemMessageTools/complexToolCall.vitest.ts b/core/tools/systemMessageTools/complexToolCall.vitest.ts deleted file mode 100644 index 954427ee2..000000000 --- a/core/tools/systemMessageTools/complexToolCall.vitest.ts +++ /dev/null @@ -1,304 +0,0 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { AssistantChatMessage, ChatMessage, PromptLog } from "../.."; -import { interceptSystemToolCalls } from "./interceptSystemToolCalls"; - -describe("interceptSystemToolCalls - Complex Tool Call Test", () => { - let abortController: AbortController; - - beforeEach(() => { - abortController = new AbortController(); - }); - - const createAsyncGenerator = async function* ( - messages: ChatMessage[][], - ): AsyncGenerator { - for (const messageGroup of messages) { - yield messageGroup; - } - return undefined; - }; - - function isAssistantMessageWithToolCalls( - message: ChatMessage, - ): message is AssistantChatMessage { - return ( - message.role === "assistant" && - "toolCalls" in message && - message.toolCalls !== undefined && - message.toolCalls.length > 0 - ); - } - - async function collectAllResults( - generator: AsyncGenerator, - ): Promise { - const results: ChatMessage[][] = []; - while (true) { - const result = await generator.next(); - if (result.done) break; - if (result.value) results.push(result.value); - } - return results; - } - - it("handles complex multi-line tool arguments with nested content and special characters", async () => { - // This test case is based on the example.txt which has complex nested content - // that includes JSON arrays, code blocks, escape characters, and the word "assistant" - const complexDiffContent = `I'll add an exp method to the Calculator class in test.js. This method will raise the current result to the power of a given number. - -\`\`\`tool -TOOL_NAME: search_and_replace_in_file -BEGIN_ARG: filepath -test.js -END_ARG -BEGIN_ARG: diff -[ -"------- SEARCH - /** - * Divide the current result by a number - * @param {number} number - The number to divide by - * @ -assistant -returns {Calculator} - Returns this instance for method chaining - * @throws {Error} - Throws error if attempting to divide by zero - */ - divide(number) { - if (number === 0) { - throw new Error(\"Cannot divide by zero\"); - } - this.result /= number; - return this; - } - -======= - /** - * Divide the current result by a number - * @param {number} number - The number to -assistant - divide by - * @returns {Calculator} - Returns this instance for method chaining - * @throws {Error} - Throws error if attempting to divide by zero - */ - divide(number) { - if (number === 0) { - throw new Error(\"Cannot divide by zero\"); - } - this.result /= number; - return this; - } - - /** - * Raise the current result to the power of a number - * -assistant - @param {number} number - The exponent to raise to - * @returns {Calculator} - Returns this instance for method chaining - */ - exp(number) { - this.result = Math.pow(this.result, number); - return this; - } - -+++++++ REPLACE" -] -END_ARG -\`\`\``; - - const messages: ChatMessage[][] = [ - [ - { - role: "assistant", - content: - "I'll add an exp method to the Calculator class in test.js.\n\n", - }, - ], - [{ role: "assistant", content: "```tool\n" }], - [ - { - role: "assistant", - content: "TOOL_NAME: search_and_replace_in_file\n", - }, - ], - [{ role: "assistant", content: "BEGIN_ARG: filepath\n" }], - [{ role: "assistant", content: "test.js\n" }], - [{ role: "assistant", content: "END_ARG\n" }], - [{ role: "assistant", content: "BEGIN_ARG: diffs\n" }], - [{ role: "assistant", content: complexDiffContent }], - [{ role: "assistant", content: "\nEND_ARG\n" }], - [{ role: "assistant", content: "```" }], - ]; - - const generator = interceptSystemToolCalls( - createAsyncGenerator(messages), - abortController, - ); - - const allResults = await collectAllResults(generator); - - // Should have processed intro text - expect(allResults[0]).toEqual([ - { - role: "assistant", - content: [ - { - type: "text", - text: "I'll add an exp method to the Calculator class in test.js.", - }, - ], - }, - ]); - - // Should have detected and parsed the tool call - const toolCallResults = allResults.filter( - (r): r is AssistantChatMessage[] => - r && r[0] && isAssistantMessageWithToolCalls(r[0]), - ); - - expect(toolCallResults.length).toBeGreaterThan(0); - - // Tool name should be correct - const toolNameResult = toolCallResults.find( - (r) => - r[0].toolCalls?.[0]?.function?.name === "search_and_replace_in_file", - ); - expect(toolNameResult).toBeTruthy(); - - // Reconstruct the full arguments from all deltas - let fullArgs = ""; - for (const toolResult of toolCallResults) { - fullArgs += toolResult[0].toolCalls?.[0]?.function?.arguments || ""; - } - - console.log("Full args reconstructed:", fullArgs); - - // Should be valid JSON - expect(() => JSON.parse(fullArgs)).not.toThrow(); - - const parsed = JSON.parse(fullArgs); - expect(parsed.filepath).toBe("test.js"); - expect(parsed.diffs).toBeTruthy(); - - // The diffs should contain the complex content including special markers - const diffContent1 = - typeof parsed.diffs === "string" - ? parsed.diffs - : JSON.stringify(parsed.diffs); - expect(diffContent1).toContain("SEARCH"); - expect(diffContent1).toContain("REPLACE"); - expect(diffContent1).toContain("Cannot divide by zero"); - expect(diffContent1).toContain("assistant"); // Word should be preserved in content - }); - - it("handles arguments with embedded JSON and special escape sequences", async () => { - // Test with JSON array containing embedded quotes and backslashes - const jsonArrayContent = `["first item", "second \\"quoted\\" item", "third\\nitem"]`; - - const messages: ChatMessage[][] = [ - [{ role: "assistant", content: "```tool\n" }], - [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], - [{ role: "assistant", content: "BEGIN_ARG: json_array\n" }], - [{ role: "assistant", content: jsonArrayContent }], - [{ role: "assistant", content: "\nEND_ARG\n" }], - [{ role: "assistant", content: "```" }], - ]; - - const generator = interceptSystemToolCalls( - createAsyncGenerator(messages), - abortController, - ); - - const allResults = await collectAllResults(generator); - - // Should have parsed the tool call - const toolCallResults = allResults.filter( - (r): r is AssistantChatMessage[] => - r && r[0] && isAssistantMessageWithToolCalls(r[0]), - ); - - expect(toolCallResults.length).toBeGreaterThan(0); - - // Reconstruct the full arguments - let fullArgs = ""; - for (const toolResult of toolCallResults) { - fullArgs += toolResult[0].toolCalls?.[0]?.function?.arguments || ""; - } - - // Should be valid JSON - expect(() => JSON.parse(fullArgs)).not.toThrow(); - - const parsed = JSON.parse(fullArgs); - expect(parsed.json_array).toBeTruthy(); - - // The parsed array should be correct - const arrayValue = - typeof parsed.json_array === "string" - ? JSON.parse(parsed.json_array) - : parsed.json_array; - - expect(Array.isArray(arrayValue)).toBe(true); - expect(arrayValue).toHaveLength(3); - expect(arrayValue[0]).toBe("first item"); - expect(arrayValue[1]).toBe('second "quoted" item'); - expect(arrayValue[2]).toBe("third\nitem"); - }); - - it("simulates the exact user scenario that causes parsing issues", async () => { - // This simulates the exact scenario from example.txt that was causing issues - const userProblemDiff = `[ -"------- SEARCH - /** - * Divide the current result by a number - * @param {number} number - The number to divide by - * @returns {Calculator} - Returns this instance for method chaining - * @throws {Error} - Throws error if attempting to divide by zero - */ - divide(number) { - if (number === 0) { - throw new Error(\"Cannot divide by zero\"); - } - this.result /= number; - return this; - } -======= - /** - * Divide the current result by a number - * @param {number} number - The number to divide by - * @returns {Calculator} - Returns this instance for method chaining - * @throws {Error} - Throws error if attempting to divide by zero - */ - divide(number) { - if (number === 0) { - throw new Error(\"Cannot divide by zero\"); - } - this.result /= number; - return this; - } - - /** - * Raise the current result to the power of a number - * @param {number} number - The exponent to raise to - * @returns {Calculator} - Returns this instance for method chaining - */ - exp(number) { - this.result = Math.pow(this.result, number); - return this; - } -+++++++ REPLACE" -]`; - - // Test that the JSON string can be properly parsed and used - let parsed; - expect(() => { - parsed = JSON.parse(userProblemDiff); - }).not.toThrow(); - - expect(Array.isArray(parsed)).toBe(true); - expect(parsed!.length).toBe(1); - - const diffContent = parsed![0]; - expect(diffContent).toContain("------- SEARCH"); - expect(diffContent).toContain("======="); - expect(diffContent).toContain("+++++++ REPLACE"); - expect(diffContent).toContain("Cannot divide by zero"); - }); -}); diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts index bdd04a5e7..1fcf649e5 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.ts @@ -10,45 +10,13 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( toolCallId, extras, ) => { - const { filepath } = args; - let { diffs } = args; - - // Handle legacy parameter name and system message tools edge cases - if (!diffs && (args as any).diff) { - diffs = (args as any).diff; - } - - if (!diffs) { - throw new Error("Missing required parameter: diffs (or diff)"); - } + const { filepath, diffs } = args; const state = extras.getState(); const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; const streamId = uuid(); - // Handle the case where system message tools provide diffs as a JSON string - // instead of an actual array (due to JSON parsing/stringifying in system message tools) - let processedDiffs: string[]; - if (typeof diffs === "string") { - try { - const parsed = JSON.parse(diffs); - if (Array.isArray(parsed)) { - processedDiffs = parsed; - } else { - processedDiffs = [diffs]; - } - } catch (e) { - processedDiffs = [diffs]; - } - } else if (Array.isArray(diffs)) { - processedDiffs = diffs; - } else { - throw new Error( - "diffs parameter must be an array of strings or a JSON string representing an array", - ); - } - // Resolve the file path const resolvedFilepath = await resolveRelativePathInDir( filepath, @@ -60,16 +28,11 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( // Parse all search/replace blocks from all diff strings const allBlocks = []; - for (let diffIndex = 0; diffIndex < processedDiffs.length; diffIndex++) { - const blocks = parseAllSearchReplaceBlocks(processedDiffs[diffIndex]); + for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) { + const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]); if (blocks.length === 0) { throw new Error( - `No complete search/replace blocks found in diff ${diffIndex + 1}. Each diff must contain at least one complete SEARCH/REPLACE block with the format: -------- SEARCH -[content to find] -======= -[replacement content] -+++++++ REPLACE`, + `No complete search/replace blocks found in diff ${diffIndex + 1}`, ); } allBlocks.push(...blocks); From 8bc81c106b48179410b9a014e640bd62156e888d Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 24 Jul 2025 09:01:23 -0700 Subject: [PATCH 19/20] fix tool calls stopping after failure --- gui/src/redux/thunks/streamResponseAfterToolCall.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index ed16b5a5a..cd49cab0b 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -24,7 +24,7 @@ function areAllToolsDoneStreaming( // Only continue if all tool calls are complete const completedToolCalls = assistantMessage.toolCallStates.filter( - (tc) => tc.status === "done", + (tc) => tc.status === "done" || tc.status === "errored", ); return completedToolCalls.length === assistantMessage.toolCallStates.length; From 3dfe00dd272868adbc3ca0f1ea7b883987ecda03 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Mon, 28 Jul 2025 16:38:04 -0700 Subject: [PATCH 20/20] Nate/oneper-main (#6838) * update oneper to by default download build from man * republish instead of rebuilding * deafult to a pr * undo auto-release for now * force install in oneper * update oneper * don't run on this branch * feat: setup-cron and remove-cron --- .github/workflows/auto-release.yml | 5 +- .github/workflows/main-build.yaml | 105 +++++++++ .github/workflows/vscode-version-bump.yml | 7 +- package-lock.json | 2 +- scripts/oneper | 264 +++++++++++++++++++++- 5 files changed, 368 insertions(+), 15 deletions(-) create mode 100644 .github/workflows/main-build.yaml diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 43d65d5b5..031ed1fbe 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -4,8 +4,9 @@ on: push: branches: - nate/auto-main-release-draft - schedule: - - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday + # Not using this now because making drafts was just noisy. Will be useful when we are ready for automated releases. + # schedule: + # - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday workflow_dispatch: # Keep manual trigger option jobs: diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml new file mode 100644 index 000000000..75e4104ab --- /dev/null +++ b/.github/workflows/main-build.yaml @@ -0,0 +1,105 @@ +name: Main Branch Build + +# Download and republish VS Code extension artifacts when code is merged to main +on: + push: + branches: + - main + workflow_dispatch: + inputs: + test_pr_number: + description: "PR number to test with" + required: true + +jobs: + republish-pr-artifacts: + runs-on: ubuntu-latest + strategy: + matrix: + platform: [Linux, macOS] + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 2 # Get the last 2 commits to find the merge commit + + - name: Get merged PR number + id: get-pr + run: | + # Get the commit message of the merge commit + COMMIT_MSG=$(git log --format=%B -n 1 HEAD) + echo "Commit message: $COMMIT_MSG" + + # Extract PR number from merge commit message (format: "Merge pull request #123 from...") + PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723") + + if [ -z "$PR_NUMBER" ]; then + echo "❌ Could not extract PR number from commit message. This might not be a PR merge." + echo "Commit message was: $COMMIT_MSG" + exit 1 + fi + + echo "Found PR number: $PR_NUMBER" + echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT + + - name: Find PR workflow run + id: find-run + env: + PR_NUMBER: ${{ steps.get-pr.outputs.pr_number }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "🔍 Getting branch name for PR #$PR_NUMBER..." + + # Get the branch name for the PR + BRANCH_NAME=$(gh pr view "$PR_NUMBER" --repo "${{ github.repository }}" --json headRefName --jq '.headRefName') + + if [ -z "$BRANCH_NAME" ]; then + echo "❌ Could not find PR #$PR_NUMBER" + exit 1 + fi + + echo "Branch name: $BRANCH_NAME" + + # Get the latest successful workflow run for the branch + RUN_ID=$(gh run list \ + --repo "${{ github.repository }}" \ + --workflow="pr_checks.yaml" \ + --branch="$BRANCH_NAME" \ + --json databaseId,status,conclusion \ + --jq ".[] | select(.status == \"completed\" and .conclusion == \"success\") | .databaseId" \ + | head -1) + + if [ -z "$RUN_ID" ]; then + echo "❌ No successful workflow run found for PR #$PR_NUMBER (branch: $BRANCH_NAME)" + exit 1 + fi + + echo "Found successful workflow run: $RUN_ID" + echo "run_id=$RUN_ID" >> $GITHUB_OUTPUT + + - name: Download PR artifact + env: + RUN_ID: ${{ steps.find-run.outputs.run_id }} + PLATFORM: ${{ matrix.platform }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "đŸ“Ĩ Downloading vscode-extension-build-$PLATFORM artifact from run $RUN_ID..." + + # Create temporary directory for download + mkdir -p ./temp-download + + # Download the artifact from the PR workflow run + if ! gh run download "$RUN_ID" \ + --repo "${{ github.repository }}" \ + --name "vscode-extension-build-$PLATFORM" \ + --dir "./temp-download"; then + echo "❌ Failed to download artifact vscode-extension-build-$PLATFORM from run $RUN_ID" + exit 1 + fi + + echo "✅ Successfully downloaded artifact" + + - name: Republish as main branch artifact + uses: actions/upload-artifact@v4 + with: + name: vscode-extension-build-${{ matrix.platform }} + path: ./temp-download/* diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index c05da185f..a7aaee3d5 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -1,8 +1,9 @@ name: Create VS Code main release draft on: - schedule: - # Runs at 7 AM PST (15:00 UTC) every Friday - - cron: "0 15 * * 5" + # Not using this now because making drafts was just noisy. Will be useful when we are ready for automated releases. + # schedule: + # # Runs at 7 AM PST (15:00 UTC) every Friday + # - cron: "0 15 * * 5" workflow_dispatch: # Allows manual triggering diff --git a/package-lock.json b/package-lock.json index 0a2538840..b4289d422 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "wt-openai-adapters-tests", + "name": "continue", "lockfileVersion": 3, "requires": true, "packages": { diff --git a/scripts/oneper b/scripts/oneper index 52ad8623a..d9945f2a5 100755 --- a/scripts/oneper +++ b/scripts/oneper @@ -10,26 +10,33 @@ REPO="continuedev/continue" ONEPER_DIR="$HOME/.continue/.utils/oneper" show_help() { - echo "oneper - Install Continue VS Code extension from PR builds or latest pre-release" + echo "oneper - Install Continue VS Code extension from builds or latest pre-release" echo "" echo "Usage: oneper [options]" echo " oneper -h | --help" + echo " oneper install # Install latest build from main branch (default)" echo "" echo "Commands:" + echo " install Download and install VSIX from latest main branch build (default)" echo " install --pr [--platform ]" echo " Download and install VSIX from specified PR number" echo " Platform options: macos, linux (auto-detected by default)" echo " install --latest Install latest pre-release from VS Code marketplace" + echo " setup-cron Set up automatic updates every 10 minutes" + echo " remove-cron Remove automatic updates" echo " clean Remove all downloaded VSIX files from oneper cache" echo "" echo "Options:" echo " -h, --help Show this help message" - echo " --platform Specify platform for PR builds (macos, linux)" + echo " --platform Specify platform for builds (macos, linux)" echo "" echo "Examples:" + echo " oneper install # Install latest build from main branch" echo " oneper install --pr 123 # Install VSIX from PR #123" echo " oneper install --pr 123 --platform linux # Install Linux VSIX from PR #123" echo " oneper install --latest # Install latest pre-release" + echo " oneper setup-cron # Auto-update every 10 minutes" + echo " oneper remove-cron # Stop auto-updates" echo " oneper clean # Clear cached VSIX files" echo " oneper -h # Show help" echo "" @@ -74,6 +81,115 @@ ensure_oneper_dir() { fi } +install_from_main() { + local platform=${1:-$(detect_os)} # Auto-detect OS if not specified + + # Map platform names to GitHub runner OS names + local artifact_suffix + case "$platform" in + "macos") + artifact_suffix="macOS" + ;; + "linux") + artifact_suffix="Linux" + ;; + *) + echo "❌ Unknown platform: $platform" + echo " Supported platforms: macos, linux" + exit 1 + ;; + esac + + echo "🔍 Finding latest main branch build..." + + # Get the latest successful workflow run for main branch + local run_id=$(gh run list \ + --repo "$REPO" \ + --workflow="main-build.yaml" \ + --branch="main" \ + --json databaseId,status,conclusion \ + --jq ".[] | select(.status == \"completed\" and .conclusion == \"success\") | .databaseId" \ + | head -1) + + if [ -z "$run_id" ]; then + echo "❌ No successful main branch build found" + echo " Make sure there are recent commits to main with successful builds" + exit 1 + fi + + echo "✅ Found workflow run: https://github.com/$REPO/actions/runs/$run_id" + + # Try to get the original PR number from the workflow run + local original_pr=$(gh run view "$run_id" --repo "$REPO" --json displayTitle --jq '.displayTitle' | grep -o "pull request #[0-9]*" | grep -o "[0-9]*" || echo "") + + if [ -n "$original_pr" ]; then + echo "đŸ“Ļ This contains artifacts originally from PR #$original_pr" + fi + + echo "đŸ“Ĩ Downloading vscode-extension-build-$artifact_suffix artifact..." + + # Create temporary directory for download + local temp_dir=$(mktemp -d) + + # Download the artifact + if ! gh run download "$run_id" \ + --repo "$REPO" \ + --name "vscode-extension-build-$artifact_suffix" \ + --dir "$temp_dir"; then + echo "❌ Failed to download artifact vscode-extension-build-$artifact_suffix" + echo " Make sure the workflow run completed successfully for $platform" + rm -rf "$temp_dir" + exit 1 + fi + + # Find the VSIX file in the downloaded artifact + local vsix_file=$(find "$temp_dir" -name "*.vsix" | head -1) + + if [ -z "$vsix_file" ]; then + echo "❌ No VSIX file found in artifact" + rm -rf "$temp_dir" + exit 1 + fi + + # Extract version from the original VSIX filename (e.g., continue-1.1.66.vsix -> 1.1.66) + local original_filename=$(basename "$vsix_file") + local version=$(echo "$original_filename" | sed 's/continue-\(.*\)\.vsix/\1/') + + if [ -z "$version" ]; then + echo "âš ī¸ Could not extract version from filename: $original_filename" + version="unknown" + fi + + # Create new VSIX name with version and "main" suffix + local target_path="$ONEPER_DIR/continue-${version}-main.vsix" + + # Check if file already exists and notify about overwrite + if [ -f "$target_path" ]; then + echo "âš ī¸ Overwriting existing VSIX: $target_path" + fi + + echo "đŸ“Ļ Moving VSIX to: $target_path" + mv "$vsix_file" "$target_path" + + # Clean up temp directory + rm -rf "$temp_dir" + + # Install the extension + echo "🚀 Installing VS Code extension..." + if code --install-extension "$target_path" --force; then + echo "✅ Successfully installed Continue extension from main branch" + echo "📄 VSIX file saved to: $target_path" + echo "" + echo "💡 To use the new extension version, reload your VS Code window:" + echo " â€ĸ Press Ctrl+Shift+P (Cmd+Shift+P on Mac)" + echo " â€ĸ Type 'Developer: Reload Window' and press Enter" + echo " â€ĸ Or restart VS Code entirely" + else + echo "❌ Failed to install extension" + exit 1 + fi +} + install_from_pr() { local pr_number=$1 local platform=${2:-$(detect_os)} # Auto-detect OS if not specified @@ -194,7 +310,7 @@ install_from_pr() { install_latest() { echo "🚀 Installing latest pre-release Continue extension..." - if code --install-extension --pre-release Continue.continue; then + if code --install-extension --pre-release Continue.continue --force; then echo "✅ Successfully installed latest pre-release Continue extension" echo "" echo "💡 To use the new extension version, reload your VS Code window:" @@ -207,6 +323,112 @@ install_latest() { fi } +get_latest_main_run_id() { + gh run list \ + --repo "$REPO" \ + --workflow="main-build.yaml" \ + --branch="main" \ + --json databaseId,status,conclusion \ + --jq ".[] | select(.status == \"completed\" and .conclusion == \"success\") | .databaseId" \ + | head -1 +} + +check_and_install_if_new() { + local current_run_id=$(get_latest_main_run_id) + + if [ -z "$current_run_id" ]; then + echo "$(date): ❌ No successful main branch build found" >&2 + return 1 + fi + + local last_run_file="$ONEPER_DIR/last_installed_run" + local last_run_id="" + + if [ -f "$last_run_file" ]; then + last_run_id=$(cat "$last_run_file") + fi + + if [ "$current_run_id" != "$last_run_id" ]; then + echo "$(date): 🔄 New build detected (run $current_run_id), installing..." + + # Install from main silently + if install_from_main > /dev/null 2>&1; then + echo "$current_run_id" > "$last_run_file" + echo "$(date): ✅ Successfully installed new build from run $current_run_id" + else + echo "$(date): ❌ Failed to install new build" >&2 + return 1 + fi + else + echo "$(date): 🔍 No new builds (current: $current_run_id)" + fi +} + +setup_cron() { + echo "🔧 Setting up automatic updates every 10 minutes..." + + # Get the absolute path to this script + local script_path=$(realpath "$0") + + # Create a wrapper script that calls the check function + local cron_script="$ONEPER_DIR/oneper-cron.sh" + + cat > "$cron_script" << EOF +#!/bin/bash +# Auto-generated oneper cron script +export PATH="/usr/local/bin:/usr/bin:/bin:\$PATH" +cd "\$(dirname "$script_path")" +"$script_path" --cron-check +EOF + + chmod +x "$cron_script" + + # Create log file + local log_file="$ONEPER_DIR/oneper-cron.log" + touch "$log_file" + + # Add to crontab + local cron_line="*/10 * * * * $cron_script >> $log_file 2>&1" + + # Check if cron job already exists + if crontab -l 2>/dev/null | grep -q "oneper-cron.sh"; then + echo "âš ī¸ Oneper cron job already exists. Removing old one..." + crontab -l 2>/dev/null | grep -v "oneper-cron.sh" | crontab - + fi + + # Add new cron job + (crontab -l 2>/dev/null; echo "$cron_line") | crontab - + + echo "✅ Automatic updates configured!" + echo "📊 Logs will be written to: $log_file" + echo "🔍 Check status with: tail -f $log_file" + echo "" + echo "💡 To remove automatic updates: oneper remove-cron" +} + +remove_cron() { + echo "đŸ—‘ī¸ Removing automatic updates..." + + # Remove from crontab + if crontab -l 2>/dev/null | grep -q "oneper-cron.sh"; then + crontab -l 2>/dev/null | grep -v "oneper-cron.sh" | crontab - + echo "✅ Removed cron job" + else + echo "â„šī¸ No oneper cron job found" + fi + + # Clean up files + local cron_script="$ONEPER_DIR/oneper-cron.sh" + local log_file="$ONEPER_DIR/oneper-cron.log" + local last_run_file="$ONEPER_DIR/last_installed_run" + + [ -f "$cron_script" ] && rm "$cron_script" && echo "đŸ—‘ī¸ Removed cron script" + [ -f "$log_file" ] && rm "$log_file" && echo "đŸ—‘ī¸ Removed log file" + [ -f "$last_run_file" ] && rm "$last_run_file" && echo "đŸ—‘ī¸ Removed state file" + + echo "✅ Automatic updates removed successfully" +} + clean_cache() { if [ ! -d "$ONEPER_DIR" ]; then echo "📁 Oneper cache directory doesn't exist: $ONEPER_DIR" @@ -228,19 +450,28 @@ clean_cache() { } main() { - if [ $# -eq 0 ]; then - show_help - exit 1 - fi - - # Handle help flags first + # Handle special internal commands first case "$1" in + "--cron-check") + # Internal command used by cron job + ensure_oneper_dir + check_and_install_if_new + exit $? + ;; "-h"|"--help") show_help exit 0 ;; esac + # If no arguments, default to installing from main + if [ $# -eq 0 ]; then + check_dependencies + ensure_oneper_dir + install_from_main + exit 0 + fi + check_dependencies ensure_oneper_dir @@ -262,6 +493,15 @@ main() { "--latest") install_latest ;; + "--platform") + # Handle: oneper install --platform (install from main with specific platform) + local platform="$3" + install_from_main "$platform" + ;; + "") + # Handle: oneper install (install from main with auto-detected platform) + install_from_main + ;; *) echo "❌ Unknown install option: $2" show_help @@ -269,6 +509,12 @@ main() { ;; esac ;; + "setup-cron") + setup_cron + ;; + "remove-cron") + remove_cron + ;; "clean") clean_cache ;;