From 7ea4d85f1e5df675a8046328d491eee739e8afa9 Mon Sep 17 00:00:00 2001 From: Mattias Andersson Date: Mon, 1 Sep 2025 09:07:52 +0200 Subject: [PATCH 01/91] Adjusted MCPConnection logic so the cwd is resolved to current workspace folder. --- core/context/mcp/MCPConnection.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index c5a975473..9714ef60a 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -9,6 +9,7 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; +import { fileURLToPath } from "node:url"; import { IDE, MCPConnectionStatus, @@ -343,6 +344,26 @@ class MCPConnection { }; } + /** + * Resolves the current working directory of the current workspace. + * @param cwd The cwd parameter provided by user. + * @returns Current working directory (user-provided cwd or workspace root). + */ + private async resolveCwd(cwd?: string) { + // Return cwd if it has been explicitly set. + if (cwd) { + return cwd; + } + // Otherwise use workspace folder. + const workspaceDirs = await this.extras?.ide.getWorkspaceDirs(); + if (workspaceDirs) { + if (workspaceDirs.length > 0) { + cwd = fileURLToPath(workspaceDirs[0]); + } + } + return cwd; + } + private async constructTransportAsync( options: MCPOptions, ): Promise { @@ -379,7 +400,7 @@ class MCPConnection { command, args, env, - cwd: options.transport.cwd, + cwd: await this.resolveCwd(options.transport.cwd), stderr: "pipe", }); From a1114019ca464979fea87fc7c6f518faf9fadaec Mon Sep 17 00:00:00 2001 From: Mattias Andersson Date: Tue, 23 Sep 2025 23:11:51 +0200 Subject: [PATCH 02/91] Adjusted the MCPConnection::resoveCwd() logic + added tests. --- core/context/mcp/MCPConnection.ts | 35 ++++++++++++++++++------ core/context/mcp/MCPConnection.vitest.ts | 34 +++++++++++++++++++++++ 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 9714ef60a..2ea7b9498 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -1,5 +1,6 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { fileURLToPath } from "url"; import { SSEClientTransport, @@ -9,7 +10,6 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; -import { fileURLToPath } from "node:url"; import { IDE, MCPConnectionStatus, @@ -20,6 +20,7 @@ import { MCPServerStatus, MCPTool, } from "../.."; +import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getEnvPathFromUserShell } from "../../util/shellPath"; import { getOauthToken } from "./MCPOauth"; @@ -350,16 +351,34 @@ class MCPConnection { * @returns Current working directory (user-provided cwd or workspace root). */ private async resolveCwd(cwd?: string) { - // Return cwd if it has been explicitly set. - if (cwd) { + if (!cwd) { + return this.resolveWorkspaceCwd(undefined); + } + + if (cwd.startsWith("file://")) { + return fileURLToPath(cwd); + } + + // Return cwd if cwd is an absolute path. + if (cwd.charAt(0) === "/") { return cwd; } - // Otherwise use workspace folder. - const workspaceDirs = await this.extras?.ide.getWorkspaceDirs(); - if (workspaceDirs) { - if (workspaceDirs.length > 0) { - cwd = fileURLToPath(workspaceDirs[0]); + + return this.resolveWorkspaceCwd(cwd); + } + + private async resolveWorkspaceCwd(cwd: string | undefined) { + const IDE = await this.extras?.ide; + if (IDE) { + const target = cwd ?? "."; + const resolved = await resolveRelativePathInDir(target, IDE); + if (resolved) { + if (resolved.startsWith("file://")) { + return fileURLToPath(resolved); + } + return resolved; } + return resolved; } return cwd; } diff --git a/core/context/mcp/MCPConnection.vitest.ts b/core/context/mcp/MCPConnection.vitest.ts index 3f69d8f23..36d957241 100644 --- a/core/context/mcp/MCPConnection.vitest.ts +++ b/core/context/mcp/MCPConnection.vitest.ts @@ -1,5 +1,6 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as ideUtils from "../../util/ideUtils"; import MCPConnection from "./MCPConnection"; // Mock the shell path utility @@ -152,6 +153,39 @@ describe("MCPConnection", () => { }); }); + describe("resolveCwd", () => { + const baseOptions = { + name: "test-mcp", + id: "test-id", + transport: { + type: "stdio" as const, + command: "test-cmd", + args: [], + }, + }; + + it("should return absolute cwd unchanged", async () => { + const conn = new MCPConnection(baseOptions); + + await expect((conn as any).resolveCwd("/tmp/project")).resolves.toBe( + "/tmp/project", + ); + }); + + it("should resolve relative cwd using IDE workspace", async () => { + const ide = {} as any; + const mockResolve = vi + .spyOn(ideUtils, "resolveRelativePathInDir") + .mockResolvedValue("file:///workspace/src"); + const conn = new MCPConnection(baseOptions, { ide }); + + await expect((conn as any).resolveCwd("src")).resolves.toBe( + "/workspace/src", + ); + expect(mockResolve).toHaveBeenCalledWith("src", ide); + }); + }); + describe("connectClient", () => { const options = { name: "test-mcp", From 7fb5935e373ff5abb3f68d4c8f9efb70750d0b57 Mon Sep 17 00:00:00 2001 From: vldf Date: Tue, 19 Aug 2025 17:33:45 +0300 Subject: [PATCH 03/91] feat: add `MentionFileInChatAction` --- core/protocol/ideWebview.ts | 1 + .../menu/file/MentionFileInChatAction.kt | 41 +++++++++++++++++++ .../src/main/resources/META-INF/plugin.xml | 8 ++++ .../useMainEditorWebviewListeners.ts | 21 ++++++++++ 4 files changed, 71 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 21eab1f7f..dea5ae4c0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -78,4 +78,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; + mentionFile: [{ fullFilePath: string; shortFilePath: string }, void]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt new file mode 100644 index 000000000..ea4111fb1 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt @@ -0,0 +1,41 @@ +package com.github.continuedev.continueintellijextension.actions.menu.file + +import com.github.continuedev.continueintellijextension.actions.getContinuePluginService +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.CommonDataKeys +import com.intellij.openapi.vfs.VirtualFile + +class MentionFileInChatAction : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val continuePluginService = getContinuePluginService(e.project) ?: return + val virtualFile = e.getFile() ?: return + + val params = mapOf( + "fullFilePath" to virtualFile.url, + "shortFilePath" to virtualFile.name, + ) + + continuePluginService.sendToWebview("mentionFile", params) + } + + override fun update(e: AnActionEvent) { + val file = e.getFile() + val files = e.getFiles() + + val isAvailable = file != null && !file.isDirectory && files.size == 1 + + e.presentation.isVisible = isAvailable + } + + private fun AnActionEvent.getFile(): VirtualFile? { + return this.getData(CommonDataKeys.VIRTUAL_FILE) + } + + private fun AnActionEvent.getFiles(): Array { + return this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY).orEmpty() + } + + override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT +} diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 9f407a573..43404556a 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -181,5 +181,13 @@ + + + + + + diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 0fe79297c..20c36c039 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -198,4 +198,25 @@ export function useMainEditorWebviewListeners({ }, [editor, activeContextProviders, isInEdit, useCurrentFileAsContext], ); + + useWebviewListener( + "mentionFile", + async (data) => { + if (!editor) return; + editor + .chain() + .insertContent({ + type: "mention", + attrs: { + id: data.fullFilePath, + query: data.fullFilePath, + itemType: "file", + label: data.shortFilePath, + }, + }) + .insertContent(" ") + .run(); + }, + [editor], + ); } From 6e77df2ea7edc0a6b1efcea9981c3aae8ff15947 Mon Sep 17 00:00:00 2001 From: vldf Date: Tue, 19 Aug 2025 18:02:59 +0300 Subject: [PATCH 04/91] feat: allow to mention directory --- core/protocol/ideWebview.ts | 5 ++++- ...tAction.kt => MentionFileOrFolderInChatAction.kt} | 12 +++++++----- .../intellij/src/main/resources/META-INF/plugin.xml | 6 +++--- .../TipTapEditor/useMainEditorWebviewListeners.ts | 10 +++++----- 4 files changed, 19 insertions(+), 14 deletions(-) rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/{MentionFileInChatAction.kt => MentionFileOrFolderInChatAction.kt} (76%) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index dea5ae4c0..83a12dd31 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -78,5 +78,8 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; - mentionFile: [{ fullFilePath: string; shortFilePath: string }, void]; + mentionFileOrDirectory: [ + { type: "file" | "folder"; fullPath: string; name: string }, + void, + ]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileOrFolderInChatAction.kt similarity index 76% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileOrFolderInChatAction.kt index ea4111fb1..e7998f095 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileInChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileOrFolderInChatAction.kt @@ -7,24 +7,26 @@ import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.vfs.VirtualFile -class MentionFileInChatAction : AnAction() { +class MentionFileOrFolderInChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return val virtualFile = e.getFile() ?: return + val type = if (virtualFile.isDirectory) "folder" else "file" val params = mapOf( - "fullFilePath" to virtualFile.url, - "shortFilePath" to virtualFile.name, + "type" to type, + "fullPath" to virtualFile.url, + "name" to virtualFile.name, ) - continuePluginService.sendToWebview("mentionFile", params) + continuePluginService.sendToWebview("mentionFileOrDirectory", params) } override fun update(e: AnActionEvent) { val file = e.getFile() val files = e.getFiles() - val isAvailable = file != null && !file.isDirectory && files.size == 1 + val isAvailable = file != null && files.size == 1 e.presentation.isVisible = isAvailable } diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 43404556a..ad46e74a9 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -182,9 +182,9 @@ - + diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 20c36c039..a2a49b50b 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -200,7 +200,7 @@ export function useMainEditorWebviewListeners({ ); useWebviewListener( - "mentionFile", + "mentionFileOrDirectory", async (data) => { if (!editor) return; editor @@ -208,10 +208,10 @@ export function useMainEditorWebviewListeners({ .insertContent({ type: "mention", attrs: { - id: data.fullFilePath, - query: data.fullFilePath, - itemType: "file", - label: data.shortFilePath, + id: data.fullPath, + query: data.fullPath, + itemType: data.type, + label: data.name, }, }) .insertContent(" ") From b40cf38e34e824c38174e8c966f226e2a883bbdb Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 20 Aug 2025 13:52:28 +0300 Subject: [PATCH 05/91] feat: allow to reference both directories and files at the same time --- core/index.d.ts | 10 ++++++ core/protocol/ideWebview.ts | 6 ++-- ...t => MentionFilesOrFoldersInChatAction.kt} | 36 +++++++++++-------- .../src/main/resources/META-INF/plugin.xml | 4 +-- .../useMainEditorWebviewListeners.ts | 32 +++++++++-------- 5 files changed, 53 insertions(+), 35 deletions(-) rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/{MentionFileOrFolderInChatAction.kt => MentionFilesOrFoldersInChatAction.kt} (51%) diff --git a/core/index.d.ts b/core/index.d.ts index 8650c6ae2..1d56b6389 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1865,6 +1865,16 @@ export interface CompiledMessagesResult { contextPercentage: number; } +export interface MentionFilesOrDirectoriesPayload { + data: MentionFileOrDirectoryPayload[]; +} + +interface MentionFileOrDirectoryPayload { + type: "file" | "folder"; + fullPath: string; + name: string; +} + export interface MessageOption { precompiled: boolean; } diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 83a12dd31..30f4891cf 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -6,6 +6,7 @@ import { ApplyState, ApplyToFilePayload, HighlightedCodePayload, + MentionFilesOrDirectoriesPayload, MessageContent, RangeInFileWithContents, SetCodeToEditPayload, @@ -78,8 +79,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; - mentionFileOrDirectory: [ - { type: "file" | "folder"; fullPath: string; name: string }, - void, - ]; + mentionFilesOrDirectories: [MentionFilesOrDirectoriesPayload, void]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileOrFolderInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt similarity index 51% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileOrFolderInChatAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt index e7998f095..e9382471a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFileOrFolderInChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt @@ -7,36 +7,42 @@ import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.vfs.VirtualFile -class MentionFileOrFolderInChatAction : AnAction() { +class MentionFilesOrFoldersInChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return - val virtualFile = e.getFile() ?: return + val selectedFiles = e.getFiles() - val type = if (virtualFile.isDirectory) "folder" else "file" - val params = mapOf( - "type" to type, - "fullPath" to virtualFile.url, - "name" to virtualFile.name, + val requestData = selectedFiles.map { vFile -> + val type = if (vFile.isDirectory) "folder" else "file" + + mapOf( + "type" to type, + "fullPath" to vFile.url, + "name" to vFile.name, + ) + } + val requestParams = mapOf( + "data" to requestData ) - continuePluginService.sendToWebview("mentionFileOrDirectory", params) + continuePluginService.sendToWebview("mentionFilesOrDirectories", requestParams) } override fun update(e: AnActionEvent) { - val file = e.getFile() val files = e.getFiles() - val isAvailable = file != null && files.size == 1 + val isAvailable = files.isNotEmpty() e.presentation.isVisible = isAvailable } - private fun AnActionEvent.getFile(): VirtualFile? { - return this.getData(CommonDataKeys.VIRTUAL_FILE) - } - private fun AnActionEvent.getFiles(): Array { - return this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY).orEmpty() + val multipleFiles = this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) + if (multipleFiles != null) { + return multipleFiles + } + + return this.getData(CommonDataKeys.VIRTUAL_FILE)?.let { arrayOf(it) } ?: emptyArray() } override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index ad46e74a9..be935352f 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -182,8 +182,8 @@ - diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index a2a49b50b..81dcdd830 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -200,22 +200,26 @@ export function useMainEditorWebviewListeners({ ); useWebviewListener( - "mentionFileOrDirectory", + "mentionFilesOrDirectories", async (data) => { if (!editor) return; - editor - .chain() - .insertContent({ - type: "mention", - attrs: { - id: data.fullPath, - query: data.fullPath, - itemType: data.type, - label: data.name, - }, - }) - .insertContent(" ") - .run(); + let chain = editor.chain(); + + for (let mention of data.data) { + chain + .insertContent({ + type: "mention", + attrs: { + id: mention.fullPath, + query: mention.fullPath, + itemType: mention.type, + label: mention.name, + }, + }) + .insertContent(" "); + } + + chain.run(); }, [editor], ); From cbc7ada3a1a5f1e9d3ec949649f2cf7af3832a5d Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 20 Aug 2025 14:07:30 +0300 Subject: [PATCH 06/91] feat: add MentionRepoMapInChatAction.kt --- core/index.d.ts | 8 ++-- core/protocol/ideWebview.ts | 4 +- .../file/MentionFilesOrFoldersInChatAction.kt | 14 +------ .../menu/file/MentionRepoMapInChatAction.kt | 38 +++++++++++++++++++ .../src/main/resources/META-INF/plugin.xml | 4 ++ .../useMainEditorWebviewListeners.ts | 2 +- 6 files changed, 51 insertions(+), 19 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt diff --git a/core/index.d.ts b/core/index.d.ts index 1d56b6389..d5439f06a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1865,12 +1865,12 @@ export interface CompiledMessagesResult { contextPercentage: number; } -export interface MentionFilesOrDirectoriesPayload { - data: MentionFileOrDirectoryPayload[]; +export interface AddChatMentionsPayload { + data: AddChatMentionPayload[]; } -interface MentionFileOrDirectoryPayload { - type: "file" | "folder"; +interface AddChatMentionPayload { + type: "file" | "folder" | "repo-map"; fullPath: string; name: string; } diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 30f4891cf..c13f6245d 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -3,10 +3,10 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { AcceptOrRejectDiffPayload, + AddChatMentionsPayload, ApplyState, ApplyToFilePayload, HighlightedCodePayload, - MentionFilesOrDirectoriesPayload, MessageContent, RangeInFileWithContents, SetCodeToEditPayload, @@ -79,5 +79,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; - mentionFilesOrDirectories: [MentionFilesOrDirectoriesPayload, void]; + addChatMention: [AddChatMentionsPayload, void]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt index e9382471a..dde72461f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt @@ -1,11 +1,10 @@ package com.github.continuedev.continueintellijextension.actions.menu.file import com.github.continuedev.continueintellijextension.actions.getContinuePluginService +import com.github.continuedev.continueintellijextension.actions.getFiles import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CommonDataKeys -import com.intellij.openapi.vfs.VirtualFile class MentionFilesOrFoldersInChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { @@ -25,7 +24,7 @@ class MentionFilesOrFoldersInChatAction : AnAction() { "data" to requestData ) - continuePluginService.sendToWebview("mentionFilesOrDirectories", requestParams) + continuePluginService.sendToWebview("addChatMention", requestParams) } override fun update(e: AnActionEvent) { @@ -36,14 +35,5 @@ class MentionFilesOrFoldersInChatAction : AnAction() { e.presentation.isVisible = isAvailable } - private fun AnActionEvent.getFiles(): Array { - val multipleFiles = this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) - if (multipleFiles != null) { - return multipleFiles - } - - return this.getData(CommonDataKeys.VIRTUAL_FILE)?.let { arrayOf(it) } ?: emptyArray() - } - override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt new file mode 100644 index 000000000..782089887 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt @@ -0,0 +1,38 @@ +package com.github.continuedev.continueintellijextension.actions.menu.file + +import com.github.continuedev.continueintellijextension.actions.getContinuePluginService +import com.github.continuedev.continueintellijextension.actions.getFiles +import com.intellij.openapi.actionSystem.ActionUpdateThread +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.actionSystem.AnActionEvent + +class MentionRepoMapInChatAction : AnAction() { + override fun actionPerformed(e: AnActionEvent) { + val continuePluginService = getContinuePluginService(e.project) ?: return + val selectedFiles = e.getFiles() + + val requestData = selectedFiles.map { vFile -> + mapOf( + "type" to "repo-map", + "fullPath" to vFile.url, + "name" to vFile.name, + ) + } + val requestParams = mapOf( + "data" to requestData + ) + + continuePluginService.sendToWebview("addChatMention", requestParams) + } + + override fun update(e: AnActionEvent) { + val files = e.getFiles() + + // only directories can be used + val isAvailable = files.isNotEmpty() && files.all { file -> file.isDirectory } + + e.presentation.isVisible = isAvailable + } + + override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT +} diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index be935352f..25d06033a 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -186,6 +186,10 @@ class="com.github.continuedev.continueintellijextension.actions.menu.file.MentionFilesOrFoldersInChatAction" text="Mention in the Chat"> + + diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 81dcdd830..6eb4498b8 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -200,7 +200,7 @@ export function useMainEditorWebviewListeners({ ); useWebviewListener( - "mentionFilesOrDirectories", + "addChatMention", async (data) => { if (!editor) return; let chain = editor.chain(); From b4a29bde1292f31e77638743d6a1e4e48d37a37f Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 20 Aug 2025 14:29:29 +0300 Subject: [PATCH 07/91] feat: add the Continue icon to the context actions group --- extensions/intellij/src/main/resources/META-INF/plugin.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 25d06033a..8932120a8 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -181,7 +181,7 @@ - + From 69cffcf54aea339aa0042d4d5f7f51914804b8b1 Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 20 Aug 2025 14:34:43 +0300 Subject: [PATCH 08/91] feat: rename action names --- ...hatAction.kt => AddFilesOrFoldersToChatAction.kt} | 2 +- ...oMapInChatAction.kt => AddRepoMapToChatAction.kt} | 2 +- .../intellij/src/main/resources/META-INF/plugin.xml | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/{MentionFilesOrFoldersInChatAction.kt => AddFilesOrFoldersToChatAction.kt} (95%) rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/{MentionRepoMapInChatAction.kt => AddRepoMapToChatAction.kt} (96%) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt similarity index 95% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt index dde72461f..43e841703 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionFilesOrFoldersInChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt @@ -6,7 +6,7 @@ import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -class MentionFilesOrFoldersInChatAction : AnAction() { +class AddFilesOrFoldersToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return val selectedFiles = e.getFiles() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt similarity index 96% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt index 782089887..64c08e0a3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/MentionRepoMapInChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt @@ -6,7 +6,7 @@ import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -class MentionRepoMapInChatAction : AnAction() { +class AddRepoMapToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return val selectedFiles = e.getFiles() diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 8932120a8..e2994ca0a 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -182,13 +182,13 @@ - + - + From 58de94d6f126cffa0e8f325cc0d41cc5a751c16e Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 20 Aug 2025 14:41:36 +0300 Subject: [PATCH 09/91] fix: rename `getFiles` -> `getSelectedFiles` --- .../actions/menu/file/AddFilesOrFoldersToChatAction.kt | 6 +++--- .../actions/menu/file/AddRepoMapToChatAction.kt | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt index 43e841703..1acc975c2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt @@ -1,7 +1,7 @@ package com.github.continuedev.continueintellijextension.actions.menu.file import com.github.continuedev.continueintellijextension.actions.getContinuePluginService -import com.github.continuedev.continueintellijextension.actions.getFiles +import com.github.continuedev.continueintellijextension.actions.getSelectedFiles import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent @@ -9,7 +9,7 @@ import com.intellij.openapi.actionSystem.AnActionEvent class AddFilesOrFoldersToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return - val selectedFiles = e.getFiles() + val selectedFiles = e.getSelectedFiles() val requestData = selectedFiles.map { vFile -> val type = if (vFile.isDirectory) "folder" else "file" @@ -28,7 +28,7 @@ class AddFilesOrFoldersToChatAction : AnAction() { } override fun update(e: AnActionEvent) { - val files = e.getFiles() + val files = e.getSelectedFiles() val isAvailable = files.isNotEmpty() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt index 64c08e0a3..8de936eb0 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt @@ -1,7 +1,7 @@ package com.github.continuedev.continueintellijextension.actions.menu.file import com.github.continuedev.continueintellijextension.actions.getContinuePluginService -import com.github.continuedev.continueintellijextension.actions.getFiles +import com.github.continuedev.continueintellijextension.actions.getSelectedFiles import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent @@ -9,7 +9,7 @@ import com.intellij.openapi.actionSystem.AnActionEvent class AddRepoMapToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val continuePluginService = getContinuePluginService(e.project) ?: return - val selectedFiles = e.getFiles() + val selectedFiles = e.getSelectedFiles() val requestData = selectedFiles.map { vFile -> mapOf( @@ -26,7 +26,7 @@ class AddRepoMapToChatAction : AnAction() { } override fun update(e: AnActionEvent) { - val files = e.getFiles() + val files = e.getSelectedFiles() // only directories can be used val isAvailable = files.isNotEmpty() && files.all { file -> file.isDirectory } From 258747d5b6ed04a0d6575c6ddfa839a4db490fbc Mon Sep 17 00:00:00 2001 From: vldf Date: Thu, 28 Aug 2025 11:00:17 +0300 Subject: [PATCH 10/91] fix: fix after rebase --- .../actions/ActionsUtils.kt | 14 ++++++++++++++ .../menu/file/AddFilesOrFoldersToChatAction.kt | 6 +++--- .../actions/menu/file/AddRepoMapToChatAction.kt | 6 +++--- 3 files changed, 20 insertions(+), 6 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt new file mode 100644 index 000000000..71f8412a5 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ActionsUtils.kt @@ -0,0 +1,14 @@ +package com.github.continuedev.continueintellijextension.actions + +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.CommonDataKeys +import com.intellij.openapi.vfs.VirtualFile + +fun AnActionEvent.getSelectedFiles(): Array { + val multipleFiles = this.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) + if (multipleFiles != null) { + return multipleFiles + } + + return this.getData(CommonDataKeys.VIRTUAL_FILE)?.let { arrayOf(it) } ?: emptyArray() +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt index 1acc975c2..80ff6e9c2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt @@ -1,14 +1,14 @@ package com.github.continuedev.continueintellijextension.actions.menu.file -import com.github.continuedev.continueintellijextension.actions.getContinuePluginService import com.github.continuedev.continueintellijextension.actions.getSelectedFiles +import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent class AddFilesOrFoldersToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { - val continuePluginService = getContinuePluginService(e.project) ?: return + val browser = e.project?.getBrowser() ?: return val selectedFiles = e.getSelectedFiles() val requestData = selectedFiles.map { vFile -> @@ -24,7 +24,7 @@ class AddFilesOrFoldersToChatAction : AnAction() { "data" to requestData ) - continuePluginService.sendToWebview("addChatMention", requestParams) + browser.sendToWebview("addChatMention", requestParams) } override fun update(e: AnActionEvent) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt index 8de936eb0..a7cd4a311 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt @@ -1,14 +1,14 @@ package com.github.continuedev.continueintellijextension.actions.menu.file -import com.github.continuedev.continueintellijextension.actions.getContinuePluginService import com.github.continuedev.continueintellijextension.actions.getSelectedFiles +import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent class AddRepoMapToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { - val continuePluginService = getContinuePluginService(e.project) ?: return + val browser = e.project?.getBrowser() ?: return val selectedFiles = e.getSelectedFiles() val requestData = selectedFiles.map { vFile -> @@ -22,7 +22,7 @@ class AddRepoMapToChatAction : AnAction() { "data" to requestData ) - continuePluginService.sendToWebview("addChatMention", requestParams) + browser.sendToWebview("addChatMention", requestParams) } override fun update(e: AnActionEvent) { From 8e1288ec0c673ab651bde769701197a6ed250c47 Mon Sep 17 00:00:00 2001 From: vldf Date: Mon, 8 Sep 2025 16:05:18 +0300 Subject: [PATCH 11/91] review: fix --- core/index.d.ts | 8 ++-- core/protocol/ideWebview.ts | 4 +- .../menu/file/AddRepoMapToChatAction.kt | 38 ------------------- ...dersToChatAction.kt => AddToEditAction.kt} | 4 +- .../src/main/resources/META-INF/plugin.xml | 7 +--- .../useMainEditorWebviewListeners.ts | 24 ++++++------ 6 files changed, 20 insertions(+), 65 deletions(-) delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/{AddFilesOrFoldersToChatAction.kt => AddToEditAction.kt} (91%) diff --git a/core/index.d.ts b/core/index.d.ts index d5439f06a..dfe8cc44a 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1865,12 +1865,12 @@ export interface CompiledMessagesResult { contextPercentage: number; } -export interface AddChatMentionsPayload { - data: AddChatMentionPayload[]; +export interface AddToEditPayload { + data: AddToEditPayload[]; } -interface AddChatMentionPayload { - type: "file" | "folder" | "repo-map"; +interface AddToEditPayload { + type: "file" | "folder"; fullPath: string; name: string; } diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index c13f6245d..12d3a652c 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -3,7 +3,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { AcceptOrRejectDiffPayload, - AddChatMentionsPayload, + AddToEditPayload, ApplyState, ApplyToFilePayload, HighlightedCodePayload, @@ -79,5 +79,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; - addChatMention: [AddChatMentionsPayload, void]; + addToEdit: [AddToEditPayload, void]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt deleted file mode 100644 index a7cd4a311..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddRepoMapToChatAction.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.github.continuedev.continueintellijextension.actions.menu.file - -import com.github.continuedev.continueintellijextension.actions.getSelectedFiles -import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser -import com.intellij.openapi.actionSystem.ActionUpdateThread -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent - -class AddRepoMapToChatAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val browser = e.project?.getBrowser() ?: return - val selectedFiles = e.getSelectedFiles() - - val requestData = selectedFiles.map { vFile -> - mapOf( - "type" to "repo-map", - "fullPath" to vFile.url, - "name" to vFile.name, - ) - } - val requestParams = mapOf( - "data" to requestData - ) - - browser.sendToWebview("addChatMention", requestParams) - } - - override fun update(e: AnActionEvent) { - val files = e.getSelectedFiles() - - // only directories can be used - val isAvailable = files.isNotEmpty() && files.all { file -> file.isDirectory } - - e.presentation.isVisible = isAvailable - } - - override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddToEditAction.kt similarity index 91% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddToEditAction.kt index 80ff6e9c2..f23254319 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddFilesOrFoldersToChatAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddToEditAction.kt @@ -6,7 +6,7 @@ import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -class AddFilesOrFoldersToChatAction : AnAction() { +class AddToEditAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val browser = e.project?.getBrowser() ?: return val selectedFiles = e.getSelectedFiles() @@ -24,7 +24,7 @@ class AddFilesOrFoldersToChatAction : AnAction() { "data" to requestData ) - browser.sendToWebview("addChatMention", requestParams) + browser.sendToWebview("addToEdit", requestParams) } override fun update(e: AnActionEvent) { diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index e2994ca0a..b11a09418 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -183,14 +183,9 @@ - - - diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 6eb4498b8..1cc552ad3 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -10,6 +10,7 @@ import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; import { CodeBlock, PromptBlock } from "./extensions"; import { insertCurrentFileContextMention } from "./utils/insertCurrentFileContextMention"; +import { Mention } from "@tiptap/extension-mention"; /** * Hook for setting up main editor specific webview listeners @@ -200,23 +201,20 @@ export function useMainEditorWebviewListeners({ ); useWebviewListener( - "addChatMention", + "addToEdit", async (data) => { if (!editor) return; let chain = editor.chain(); - for (let mention of data.data) { - chain - .insertContent({ - type: "mention", - attrs: { - id: mention.fullPath, - query: mention.fullPath, - itemType: mention.type, - label: mention.name, - }, - }) - .insertContent(" "); + for (let payload of data.data) { + const node = editor.schema.nodes[Mention.name].create({ + name: payload.name, + id: payload.fullPath, + label: payload.name, + itemType: payload.type, + }); + + chain.insertContent([node.toJSON(), { type: "text", text: " " }]); } chain.run(); From 665282f6320be7bbd44ec8781c8821d8fe2d8f95 Mon Sep 17 00:00:00 2001 From: vldf Date: Tue, 9 Sep 2025 11:09:40 +0300 Subject: [PATCH 12/91] fix `addToEdit` handling --- .../useMainEditorWebviewListeners.ts | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 1cc552ad3..60ddbe5e5 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -10,7 +10,6 @@ import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; import { CodeBlock, PromptBlock } from "./extensions"; import { insertCurrentFileContextMention } from "./utils/insertCurrentFileContextMention"; -import { Mention } from "@tiptap/extension-mention"; /** * Hook for setting up main editor specific webview listeners @@ -206,15 +205,18 @@ export function useMainEditorWebviewListeners({ if (!editor) return; let chain = editor.chain(); - for (let payload of data.data) { - const node = editor.schema.nodes[Mention.name].create({ - name: payload.name, - id: payload.fullPath, - label: payload.name, - itemType: payload.type, - }); - - chain.insertContent([node.toJSON(), { type: "text", text: " " }]); + for (let mention of data.data) { + chain + .insertContent({ + type: "mention", + attrs: { + id: mention.fullPath, + query: mention.fullPath, + itemType: mention.type, + label: mention.name, + }, + }) + .insertContent(" "); } chain.run(); From d0a27711b30cae81e3721cb1581424c470c43779 Mon Sep 17 00:00:00 2001 From: vldf Date: Tue, 9 Sep 2025 11:20:26 +0300 Subject: [PATCH 13/91] minor: move `AddToEditAction` to the one level upper --- .../actions/{menu/file => }/AddToEditAction.kt | 3 +-- extensions/intellij/src/main/resources/META-INF/plugin.xml | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/{menu/file => }/AddToEditAction.kt (93%) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddToEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToEditAction.kt similarity index 93% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddToEditAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToEditAction.kt index f23254319..5e8478b21 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/menu/file/AddToEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToEditAction.kt @@ -1,6 +1,5 @@ -package com.github.continuedev.continueintellijextension.actions.menu.file +package com.github.continuedev.continueintellijextension.actions -import com.github.continuedev.continueintellijextension.actions.getSelectedFiles import com.github.continuedev.continueintellijextension.browser.ContinueBrowserService.Companion.getBrowser import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index b11a09418..5a7af7536 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -183,7 +183,7 @@ From f5bee4f50297ac11a293d8638f222ed33eaeae79 Mon Sep 17 00:00:00 2001 From: vldf Date: Sun, 28 Sep 2025 13:21:09 +0300 Subject: [PATCH 14/91] fix: unify the namings --- core/index.d.ts | 6 +++--- core/protocol/ideWebview.ts | 4 ++-- .../actions/{AddToEditAction.kt => AddToChatAction.kt} | 4 ++-- extensions/intellij/src/main/resources/META-INF/plugin.xml | 6 +++--- .../mainInput/TipTapEditor/useMainEditorWebviewListeners.ts | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) rename extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/{AddToEditAction.kt => AddToChatAction.kt} (92%) diff --git a/core/index.d.ts b/core/index.d.ts index dfe8cc44a..49abe0ccf 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1865,11 +1865,11 @@ export interface CompiledMessagesResult { contextPercentage: number; } -export interface AddToEditPayload { - data: AddToEditPayload[]; +export interface AddToChatPayload { + data: AddToChatPayloadItem[]; } -interface AddToEditPayload { +interface AddToChatPayloadItem { type: "file" | "folder"; fullPath: string; name: string; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 12d3a652c..79e7de10b 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -3,7 +3,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import { AcceptOrRejectDiffPayload, - AddToEditPayload, + AddToChatPayload, ApplyState, ApplyToFilePayload, HighlightedCodePayload, @@ -79,5 +79,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { exitEditMode: [undefined, void]; focusEdit: [undefined, void]; generateRule: [undefined, void]; - addToEdit: [AddToEditPayload, void]; + addToChat: [AddToChatPayload, void]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt similarity index 92% rename from extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToEditAction.kt rename to extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt index 5e8478b21..8a8884ae1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/AddToChatAction.kt @@ -5,7 +5,7 @@ import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -class AddToEditAction : AnAction() { +class AddToChatAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val browser = e.project?.getBrowser() ?: return val selectedFiles = e.getSelectedFiles() @@ -23,7 +23,7 @@ class AddToEditAction : AnAction() { "data" to requestData ) - browser.sendToWebview("addToEdit", requestParams) + browser.sendToWebview("addToChat", requestParams) } override fun update(e: AnActionEvent) { diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 5a7af7536..c4eed42d3 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -182,9 +182,9 @@ - + diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 60ddbe5e5..b2ba02793 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -200,7 +200,7 @@ export function useMainEditorWebviewListeners({ ); useWebviewListener( - "addToEdit", + "addToChat", async (data) => { if (!editor) return; let chain = editor.chain(); From 86fe33d4197a802231948678c8f4fb3039551d10 Mon Sep 17 00:00:00 2001 From: Continue Agent Date: Mon, 29 Sep 2025 18:48:20 +0000 Subject: [PATCH 15/91] docs: add MCP JSON server configuration support - Added comprehensive documentation for MCP JSON configuration files - Support for single server and Claude-style multi-server JSON formats - Updated Quick Start section with YAML/JSON tabs - Added environment variable templating documentation - References PR #7956 which added JSON MCP support Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --- docs/customize/deep-dives/mcp.mdx | 69 +++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 074448104..ffca8b5c1 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -27,12 +27,14 @@ explore available MCP server blocks ## Quick Start: How to Set Up Your First MCP Server -Below is a quick example of setting up a new MCP server for use in your agent: +Below is a quick example of setting up a new MCP server for use in your agent. You can use either YAML or JSON configuration files: 1. Create a folder called `.continue/mcpServers` at the top level of your workspace -2. Add a file called `playwright-mcp.yaml` to this folder. -3. Write the following contents to `playwright-mcp.yaml` and save. +2. Add a file called `playwright-mcp.yaml` (or `playwright-mcp.json`) to this folder. +3. Write the following contents to your configuration file and save. + + ```yaml title=".continue/mcpServers/playwright-mcp.yaml" name: Playwright mcpServer version: 0.0.1 @@ -43,6 +45,16 @@ mcpServers: args: - "@playwright/mcp@latest" ``` + + +```json title=".continue/mcpServers/playwright-mcp.json" +{ + "command": "npx", + "args": ["@playwright/mcp@latest"] +} +``` + + Now test your MCP server by prompting the following command: @@ -60,6 +72,57 @@ You can set up an MCP server to search the Continue documentation directly from For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp). +## How to Configure MCP Servers with JSON Files + +In addition to YAML configuration, you can now configure MCP servers using JSON files. This feature allows you to use Claude-style MCP configurations and provides lower friction when migrating from other tools. + +### JSON Configuration Options + +You can create JSON configuration files in the `.continue/mcpServers` folder in two formats: + +#### Single MCP Server Configuration + +Create a JSON file where the filename becomes the server name: + +```json title=".continue/mcpServers/my-server.json" +{ + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-sqlite"], + "env": { + "DATABASE_PATH": "${DATABASE_PATH}" + } +} +``` + +#### Claude-style MCP Server Configuration + +Create a JSON file with multiple servers using the `mcpServers` format: + +```json title=".continue/mcpServers/claude-style.json" +{ + "mcpServers": { + "sqlite": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-sqlite"], + "env": { + "DATABASE_PATH": "${DATABASE_PATH}" + } + }, + "github": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} +``` + +### Environment Variable Templating + +JSON configurations support environment variable templating using the `${VAR_NAME}` syntax, which is automatically converted to Continue's `${{ secrets.VAR_NAME }}` format internally. + ## How to Configure MCP Servers To set up your own MCP server, read the [MCP From b1f147c12e42b33a9667f083f15221ab3c73f73c Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 11 Sep 2025 14:34:05 +0200 Subject: [PATCH 16/91] fix: use common process.env values to launch MCP Signed-off-by: Fred Bricon --- core/context/mcp/MCPConnection.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index b79647c57..fceff11ca 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -38,6 +38,8 @@ const WINDOWS_BATCH_COMMANDS = [ "bunx", ]; +const COMMONS_ENV_VARS = ["HOME", "USER", "USERPROFILE", "LOGNAME", "USERNAME"]; + function is401Error(error: unknown) { return ( (error instanceof SseError && error.code === 401) || @@ -461,7 +463,16 @@ class MCPConnection { private async constructStdioTransport( options: InternalStdioMcpOptions, ): Promise { - const env: Record = options.env ? { ...options.env } : {}; + const commonEnvVars: Record = Object.fromEntries( + COMMONS_ENV_VARS.filter((key) => process.env[key] !== undefined).map( + (key) => [key, process.env[key] as string], + ), + ); + + const env = { + ...commonEnvVars, + ...(options.env ?? {}), + }; if (process.env.PATH !== undefined) { // Set the initial PATH from process.env From 7aa81e1aa865697b561142aa6370cf6de3fa439a Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Tue, 30 Sep 2025 06:45:32 -0700 Subject: [PATCH 17/91] fix: simplify the blurb --- docs/customize/deep-dives/mcp.mdx | 51 ++----------------------------- 1 file changed, 2 insertions(+), 49 deletions(-) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index ffca8b5c1..c576fe878 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -72,56 +72,9 @@ You can set up an MCP server to search the Continue documentation directly from For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp). -## How to Configure MCP Servers with JSON Files +## Using `.mcp.json` from Claude, Cursor, Cline, etc -In addition to YAML configuration, you can now configure MCP servers using JSON files. This feature allows you to use Claude-style MCP configurations and provides lower friction when migrating from other tools. - -### JSON Configuration Options - -You can create JSON configuration files in the `.continue/mcpServers` folder in two formats: - -#### Single MCP Server Configuration - -Create a JSON file where the filename becomes the server name: - -```json title=".continue/mcpServers/my-server.json" -{ - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-sqlite"], - "env": { - "DATABASE_PATH": "${DATABASE_PATH}" - } -} -``` - -#### Claude-style MCP Server Configuration - -Create a JSON file with multiple servers using the `mcpServers` format: - -```json title=".continue/mcpServers/claude-style.json" -{ - "mcpServers": { - "sqlite": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-sqlite"], - "env": { - "DATABASE_PATH": "${DATABASE_PATH}" - } - }, - "github": { - "command": "npx", - "args": ["-y", "@modelcontextprotocol/server-github"], - "env": { - "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" - } - } - } -} -``` - -### Environment Variable Templating - -JSON configurations support environment variable templating using the `${VAR_NAME}` syntax, which is automatically converted to Continue's `${{ secrets.VAR_NAME }}` format internally. +If you have an existing `.mcp.json` file from Claude, Cursor, Cline, or any other agent that supports the spec, copy it into your `.continue/mcpServers` directory and Continue will automatically pick it up. ## How to Configure MCP Servers From 784ec4e8fcba54dba90d119df4aaec31d8f44deb Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Tue, 30 Sep 2025 07:30:30 -0700 Subject: [PATCH 18/91] fix: json mcpServers --- docs/customize/deep-dives/mcp.mdx | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index c576fe878..6740ceb63 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -100,17 +100,17 @@ server block to your [config file](./configuration.md): ```json title="config.json" { - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/path/to/your/database.db"] - } - } - ] - } + "mcpServers": [ + { + "name": "SQLite MCP", + "command": "npx", + "args": [ + "-y", + "mcp-sqlite", + "/path/to/your/database.db" + ] + } + ] } ```` From 4b423985a84cbcea383e78230b312b28da9083ef Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Tue, 30 Sep 2025 13:59:05 -0700 Subject: [PATCH 19/91] Update mcp.mdx Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --- docs/customize/deep-dives/mcp.mdx | 63 ++++++++----------------------- 1 file changed, 15 insertions(+), 48 deletions(-) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 6740ceb63..952435594 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -27,14 +27,12 @@ explore available MCP server blocks ## Quick Start: How to Set Up Your First MCP Server -Below is a quick example of setting up a new MCP server for use in your agent. You can use either YAML or JSON configuration files: +Below is a quick example of setting up a new MCP server for use in your agent: 1. Create a folder called `.continue/mcpServers` at the top level of your workspace -2. Add a file called `playwright-mcp.yaml` (or `playwright-mcp.json`) to this folder. -3. Write the following contents to your configuration file and save. +2. Add a file called `playwright-mcp.yaml` to this folder +3. Write the following contents and save - - ```yaml title=".continue/mcpServers/playwright-mcp.yaml" name: Playwright mcpServer version: 0.0.1 @@ -45,16 +43,6 @@ mcpServers: args: - "@playwright/mcp@latest" ``` - - -```json title=".continue/mcpServers/playwright-mcp.json" -{ - "command": "npx", - "args": ["@playwright/mcp@latest"] -} -``` - - Now test your MCP server by prompting the following command: @@ -74,7 +62,9 @@ For complete setup instructions, troubleshooting, and usage examples, see the [C ## Using `.mcp.json` from Claude, Cursor, Cline, etc -If you have an existing `.mcp.json` file from Claude, Cursor, Cline, or any other agent that supports the spec, copy it into your `.continue/mcpServers` directory and Continue will automatically pick it up. + +If you're coming from another tool that uses `.mcp.json` configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers` directory and Continue will automatically pick them up. + ## How to Configure MCP Servers @@ -84,38 +74,15 @@ quickstart](https://modelcontextprotocol.io/quickstart) and then [create an block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP server block to your [config file](./configuration.md): - - - ```yaml title="config.yaml" - mcpServers: - - name: SQLite MCP - command: npx - args: - - "-y" - - "mcp-sqlite" - - "/path/to/your/database.db" - -```` - - -```json title="config.json" -{ - "mcpServers": [ - { - "name": "SQLite MCP", - "command": "npx", - "args": [ - "-y", - "mcp-sqlite", - "/path/to/your/database.db" - ] - } - ] -} -```` - - - +```yaml title="config.yaml" +mcpServers: + - name: SQLite MCP + command: npx + args: + - "-y" + - "mcp-sqlite" + - "/path/to/your/database.db" +``` ### How to Configure MCP Server Properties From 3069735ac5aa6b8d5f5e0b5ca54e95008f7a13b2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 30 Sep 2025 21:48:36 -0700 Subject: [PATCH 20/91] feat: workflow files part 1 --- packages/config-yaml/src/markdown/index.ts | 3 ++- .../src/markdown/workflowFiles.test.ts | 17 ++++++++++++++++ .../config-yaml/src/markdown/workflowFiles.ts | 20 +++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 packages/config-yaml/src/markdown/workflowFiles.test.ts create mode 100644 packages/config-yaml/src/markdown/workflowFiles.ts diff --git a/packages/config-yaml/src/markdown/index.ts b/packages/config-yaml/src/markdown/index.ts index c19af94c8..08ea04dfa 100644 --- a/packages/config-yaml/src/markdown/index.ts +++ b/packages/config-yaml/src/markdown/index.ts @@ -1,4 +1,5 @@ -export * from "./createMarkdownRule.js"; export * from "./createMarkdownPrompt.js"; +export * from "./createMarkdownRule.js"; export * from "./getRuleType.js"; export * from "./markdownToRule.js"; +export * from "./workflowFiles.js"; diff --git a/packages/config-yaml/src/markdown/workflowFiles.test.ts b/packages/config-yaml/src/markdown/workflowFiles.test.ts new file mode 100644 index 000000000..4c04585fc --- /dev/null +++ b/packages/config-yaml/src/markdown/workflowFiles.test.ts @@ -0,0 +1,17 @@ +const example = ` +--- +name: Example Agent / Workflow +description: Trying to wrap my head around what are these files +model: anthropic/claude-sonnet-4 +tools: + - linear-mcp + - sentry-mcp:read-alerts + - Read + - Glob + - Bash(git diff:*) +rules: + - org/rule1 + - org/rule2 +--- +This is the prompt +`.trim(); diff --git a/packages/config-yaml/src/markdown/workflowFiles.ts b/packages/config-yaml/src/markdown/workflowFiles.ts new file mode 100644 index 000000000..5826fca2c --- /dev/null +++ b/packages/config-yaml/src/markdown/workflowFiles.ts @@ -0,0 +1,20 @@ +import z from "zod"; + +/* + Experimental/internal config format for workflows +*/ +const workflowFileFrontmatterSchema = z.object({ + name: z.string(), + description: z.string(), + model: z.string(), + tools: z.array(z.string()), + rules: z.array(z.string()), +}); +export type WorkflowFileFrontmatter = z.infer< + typeof workflowFileFrontmatterSchema +>; + +const workflowFileSchema = workflowFileFrontmatterSchema.extend({ + prompt: z.string(), +}); +export type WorkflowFile = z.infer; From 94561f8caf0e1234c8273dab54c1f780d9489c6b Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Wed, 1 Oct 2025 10:35:28 -0700 Subject: [PATCH 21/91] docs: clarify mcpServers directory name and add example path - Emphasize that the directory name is plural (mcpServers not mcpServer) - Add explicit example showing the correct path structure - This should help users avoid confusion when placing JSON config files Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --- docs/customize/deep-dives/mcp.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 952435594..272a5f125 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -63,7 +63,9 @@ For complete setup instructions, troubleshooting, and usage examples, see the [C ## Using `.mcp.json` from Claude, Cursor, Cline, etc -If you're coming from another tool that uses `.mcp.json` configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers` directory and Continue will automatically pick them up. +If you're coming from another tool that uses `.mcp.json` configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers/` directory (note the plural "Servers") and Continue will automatically pick them up. + +For example, place your `mcp.json` file at `.continue/mcpServers/mcp.json` in your workspace. ## How to Configure MCP Servers From ab0cb848c6e144f1421b0d3802b36d9fc941b5c2 Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Wed, 1 Oct 2025 10:51:02 -0700 Subject: [PATCH 22/91] docs: clarify MCP YAML examples need context or block metadata - Add ellipsis (...) to YAML examples to indicate they're part of a larger config file - Add explicit note about required metadata fields when creating standalone block files - This prevents confusion when users try to copy snippets directly into .continue/mcpServers/ Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --- docs/customize/deep-dives/mcp.mdx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 272a5f125..40cfb045a 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -77,6 +77,7 @@ block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a lo server block to your [config file](./configuration.md): ```yaml title="config.yaml" +# ... mcpServers: - name: SQLite MCP command: npx @@ -84,8 +85,13 @@ mcpServers: - "-y" - "mcp-sqlite" - "/path/to/your/database.db" +# ... ``` + +When creating a standalone block file in `.continue/mcpServers/`, remember to include the required metadata fields (`name`, `version`, `schema`) as shown in the Quick Start example above. + + ### How to Configure MCP Server Properties MCP blocks follow the established syntax for blocks, with a few additional properties specific to MCP servers. @@ -105,10 +111,12 @@ MCP now supports remote server connections through HTTP-based transports, expand For real-time streaming communication, use the SSE transport: ```yaml +# ... mcpServers: - name: Name type: sse url: https://.... +# ... ``` #### How to Use Standard Input/Output (`stdio`) @@ -116,6 +124,7 @@ mcpServers: For local MCP servers that communicate via standard input and output: ```yaml +# ... mcpServers: - name: Name type: stdio @@ -123,6 +132,7 @@ mcpServers: args: - "@modelcontextprotocol/server-sqlite" - "/path/to/your/database.db" +# ... ``` #### How to Use Streamable HTTP Transport @@ -130,10 +140,12 @@ mcpServers: For standard HTTP-based communication with streaming capabilities: ```yaml +# ... mcpServers: - name: Name type: streamable-http url: https://.... +# ... ``` These remote transport options allow you to connect to MCP servers hosted on remote infrastructure, enabling more flexible deployment architectures and shared server resources across multiple clients. @@ -146,6 +158,7 @@ With some MCP servers you will need to use API keys or other secrets. You can le as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`. ```yaml +# ... mcpServers: - name: Supabase MCP command: npx @@ -163,4 +176,5 @@ mcpServers: - "@modelcontextprotocol/server-github" env: GITHUB_PERSONAL_ACCESS_TOKEN: ${{ secrets.GITHUB_PERSONAL_ACCESS_TOKEN }} +# ... ``` From e27ef739ff02bb81201976fc57d66b1a52dd1dad Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 10:54:22 -0700 Subject: [PATCH 23/91] feat: workflow file parsing and serializing --- .../src/markdown/workflowFiles.test.ts | 322 +++++++++++++++++- .../config-yaml/src/markdown/workflowFiles.ts | 56 ++- 2 files changed, 364 insertions(+), 14 deletions(-) diff --git a/packages/config-yaml/src/markdown/workflowFiles.test.ts b/packages/config-yaml/src/markdown/workflowFiles.test.ts index 4c04585fc..9e7d995a5 100644 --- a/packages/config-yaml/src/markdown/workflowFiles.test.ts +++ b/packages/config-yaml/src/markdown/workflowFiles.test.ts @@ -1,17 +1,321 @@ +import { + parseWorkflowFile, + serializeWorkflowFile, + type WorkflowFile, +} from "./workflowFiles.js"; + const example = ` --- name: Example Agent / Workflow description: Trying to wrap my head around what are these files model: anthropic/claude-sonnet-4 -tools: - - linear-mcp - - sentry-mcp:read-alerts - - Read - - Glob - - Bash(git diff:*) -rules: - - org/rule1 - - org/rule2 +tools: linear-mcp, sentry-mcp:read-alerts, Read, Glob, Bash(git diff:*) +rules: org/rule1, org/rule2 --- This is the prompt `.trim(); + +const minimalExample = ` +--- +name: Minimal Workflow +--- +Just a simple prompt +`.trim(); + +const invalidExample = ` +--- +description: Missing name field +--- +This should fail +`.trim(); + +const noFrontmatterExample = `This is just markdown without frontmatter`; + +const invalidYamlExample = ` +--- +name: [invalid: yaml: syntax +--- +This should fail +`.trim(); + +describe("parseWorkflowFile", () => { + test("parses complete workflow file correctly", () => { + const result = parseWorkflowFile(example); + + expect(result).toEqual({ + name: "Example Agent / Workflow", + description: "Trying to wrap my head around what are these files", + model: "anthropic/claude-sonnet-4", + tools: "linear-mcp, sentry-mcp:read-alerts, Read, Glob, Bash(git diff:*)", + rules: "org/rule1, org/rule2", + prompt: "This is the prompt", + }); + }); + + test("parses minimal workflow file with only name", () => { + const result = parseWorkflowFile(minimalExample); + + expect(result).toEqual({ + name: "Minimal Workflow", + prompt: "Just a simple prompt", + }); + + // Optional fields should be undefined + expect(result.description).toBeUndefined(); + expect(result.model).toBeUndefined(); + expect(result.tools).toBeUndefined(); + expect(result.rules).toBeUndefined(); + }); + + test("throws error when name field is missing", () => { + expect(() => parseWorkflowFile(invalidExample)).toThrow( + "Workflow file must contain YAML frontmatter with a 'name' field", + ); + }); + + test("throws error when no frontmatter is present", () => { + expect(() => parseWorkflowFile(noFrontmatterExample)).toThrow( + "Workflow file must contain YAML frontmatter with a 'name' field", + ); + }); + + test("throws error with invalid YAML syntax", () => { + expect(() => parseWorkflowFile(invalidYamlExample)).toThrow(); + }); + + test("handles empty frontmatter with name", () => { + const emptyFrontmatter = ` +--- +name: Empty Test +--- +`.trim(); + + const result = parseWorkflowFile(emptyFrontmatter); + expect(result).toEqual({ + name: "Empty Test", + prompt: "", + }); + }); + + test("handles multiline prompts", () => { + const multilineExample = ` +--- +name: Multiline Test +--- +Line 1 +Line 2 + +Line 4 with gap +`.trim(); + + const result = parseWorkflowFile(multilineExample); + expect(result.prompt).toBe("Line 1\nLine 2\n\nLine 4 with gap"); + }); + + test("handles prompts with --- in content", () => { + const dashedContentExample = ` +--- +name: Dashed Content +--- +This has --- in the middle +And more content after +`.trim(); + + const result = parseWorkflowFile(dashedContentExample); + expect(result.prompt).toBe( + "This has --- in the middle\nAnd more content after", + ); + }); + + test("validates unknown frontmatter fields are allowed", () => { + const extraFieldsExample = ` +--- +name: Extra Fields Test +extraField: should be ignored by schema +--- +Prompt content +`.trim(); + + const result = parseWorkflowFile(extraFieldsExample); + expect(result.name).toBe("Extra Fields Test"); + expect(result.prompt).toBe("Prompt content"); + // Extra fields should not be in the result + expect("extraField" in result).toBe(false); + }); + + test("parses workflow with tools but no rules", () => { + const toolsOnlyExample = ` +--- +name: Tools Only Workflow +description: A workflow that uses tools but no rules +tools: git, filesystem, search +--- +This workflow uses tools but doesn't define any rules. +`.trim(); + + const result = parseWorkflowFile(toolsOnlyExample); + expect(result).toEqual({ + name: "Tools Only Workflow", + description: "A workflow that uses tools but no rules", + tools: "git, filesystem, search", + prompt: "This workflow uses tools but doesn't define any rules.", + }); + + // Rules should be undefined + expect(result.rules).toBeUndefined(); + }); + + test("validates required name field type", () => { + const invalidNameType = ` +--- +name: 123 +--- +Prompt +`.trim(); + + expect(() => parseWorkflowFile(invalidNameType)).toThrow( + "Invalid workflow file frontmatter", + ); + }); +}); + +describe("serializeWorkflowFile", () => { + test("serializes complete workflow file correctly", () => { + const workflowFile: WorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "anthropic/claude-3-sonnet", + tools: "tool1, tool2", + rules: "rule1, rule2", + prompt: "This is the test prompt", + }; + + const result = serializeWorkflowFile(workflowFile); + + // Parse it back to verify round-trip consistency + const parsed = parseWorkflowFile(result); + expect(parsed).toEqual(workflowFile); + }); + + test("serializes minimal workflow file", () => { + const workflowFile: WorkflowFile = { + name: "Minimal", + prompt: "Simple prompt", + }; + + const result = serializeWorkflowFile(workflowFile); + const parsed = parseWorkflowFile(result); + expect(parsed).toEqual(workflowFile); + }); + + test("filters out undefined values from frontmatter", () => { + const workflowFile: WorkflowFile = { + name: "Test", + description: undefined, + model: "gpt-4", + tools: undefined, + rules: undefined, + prompt: "Test prompt", + }; + + const result = serializeWorkflowFile(workflowFile); + + // Should not contain undefined fields in YAML + expect(result).not.toContain("description"); + expect(result).not.toContain("tools"); + expect(result).not.toContain("rules"); + expect(result).toContain("model: gpt-4"); + + // Verify round-trip + const parsed = parseWorkflowFile(result); + expect(parsed.name).toBe("Test"); + expect(parsed.model).toBe("gpt-4"); + expect(parsed.description).toBeUndefined(); + expect(parsed.tools).toBeUndefined(); + expect(parsed.rules).toBeUndefined(); + }); + + test("handles empty prompt", () => { + const workflowFile: WorkflowFile = { + name: "Empty Prompt", + prompt: "", + }; + + const result = serializeWorkflowFile(workflowFile); + const parsed = parseWorkflowFile(result); + expect(parsed.prompt).toBe(""); + }); + + test("preserves multiline prompts", () => { + const workflowFile: WorkflowFile = { + name: "Multiline", + prompt: "Line 1\nLine 2\n\nLine 4", + }; + + const result = serializeWorkflowFile(workflowFile); + const parsed = parseWorkflowFile(result); + expect(parsed.prompt).toBe(workflowFile.prompt); + }); +}); + +describe("round-trip consistency", () => { + test("example workflow maintains consistency", () => { + const parsed = parseWorkflowFile(example); + const serialized = serializeWorkflowFile(parsed); + const reparsed = parseWorkflowFile(serialized); + + expect(reparsed).toEqual(parsed); + }); + + test("minimal workflow maintains consistency", () => { + const parsed = parseWorkflowFile(minimalExample); + const serialized = serializeWorkflowFile(parsed); + const reparsed = parseWorkflowFile(serialized); + + expect(reparsed).toEqual(parsed); + }); +}); + +describe("edge cases", () => { + test("handles Windows line endings", () => { + const windowsExample = example.replace(/\n/g, "\r\n"); + const result = parseWorkflowFile(windowsExample); + + expect(result.name).toBe("Example Agent / Workflow"); + expect(result.prompt).toBe("This is the prompt"); + }); + + test("handles mixed line endings", () => { + const mixedExample = `---\r\nname: Mixed\n---\r\nPrompt content\n`; + const result = parseWorkflowFile(mixedExample); + + expect(result.name).toBe("Mixed"); + expect(result.prompt).toBe("Prompt content"); + }); + + test("handles empty name string", () => { + const emptyNameExample = ` +--- +name: "" +--- +Prompt +`.trim(); + + expect(() => parseWorkflowFile(emptyNameExample)).toThrow( + "Workflow file must contain YAML frontmatter with a 'name' field", + ); + }); + + test("handles null name", () => { + const nullNameExample = ` +--- +name: null +--- +Prompt +`.trim(); + + expect(() => parseWorkflowFile(nullNameExample)).toThrow( + "Workflow file must contain YAML frontmatter with a 'name' field", + ); + }); +}); diff --git a/packages/config-yaml/src/markdown/workflowFiles.ts b/packages/config-yaml/src/markdown/workflowFiles.ts index 5826fca2c..6ed805956 100644 --- a/packages/config-yaml/src/markdown/workflowFiles.ts +++ b/packages/config-yaml/src/markdown/workflowFiles.ts @@ -1,14 +1,16 @@ +import * as YAML from "yaml"; import z from "zod"; +import { parseMarkdownRule } from "./markdownToRule.js"; /* Experimental/internal config format for workflows */ const workflowFileFrontmatterSchema = z.object({ - name: z.string(), - description: z.string(), - model: z.string(), - tools: z.array(z.string()), - rules: z.array(z.string()), + name: z.string().min(1, "Name cannot be empty"), + description: z.string().optional(), + model: z.string().optional(), + tools: z.string().optional(), // TODO also accept yaml array + rules: z.string().optional(), // TODO also accept yaml array }); export type WorkflowFileFrontmatter = z.infer< typeof workflowFileFrontmatterSchema @@ -18,3 +20,47 @@ const workflowFileSchema = workflowFileFrontmatterSchema.extend({ prompt: z.string(), }); export type WorkflowFile = z.infer; + +/** + * Parses and validates a workflow file from markdown content + * Workflow files must have frontmatter with at least a name + */ +export function parseWorkflowFile(content: string): WorkflowFile { + const { frontmatter, markdown } = parseMarkdownRule(content); + + if (!frontmatter.name) { + throw new Error( + "Workflow file must contain YAML frontmatter with a 'name' field", + ); + } + + const validationResult = workflowFileFrontmatterSchema.safeParse(frontmatter); + + if (!validationResult.success) { + const errorDetails = validationResult.error.issues + .map((issue) => `${issue.path.join(".")}: ${issue.message}`) + .join(", "); + throw new Error(`Invalid workflow file frontmatter: ${errorDetails}`); + } + + return { + ...validationResult.data, + prompt: markdown, + }; +} + +/** + * Serializes a Workflow file back to markdown with YAML frontmatter + */ +export function serializeWorkflowFile(workflowFile: WorkflowFile): string { + const { prompt, ...frontmatter } = workflowFile; + + // Filter out undefined values from frontmatter + const cleanFrontmatter = Object.fromEntries( + Object.entries(frontmatter).filter(([, value]) => value !== undefined), + ); + + const yamlFrontmatter = YAML.stringify(cleanFrontmatter).trim(); + + return `---\n${yamlFrontmatter}\n---\n${prompt}`; +} From 7d40f5a9abe276862226deffd8c034d902e61429 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 11:34:08 -0700 Subject: [PATCH 24/91] feat: workflows for CLI --- .../cli/src/commands/BaseCommandOptions.ts | 2 + extensions/cli/src/configEnhancer.ts | 43 ++- extensions/cli/src/services/ModelService.ts | 100 ++++- .../cli/src/services/WorkflowService.test.ts | 315 +++++++++++++++ .../cli/src/services/WorkflowService.ts | 144 +++++++ extensions/cli/src/services/index.ts | 9 + extensions/cli/src/services/types.ts | 7 + .../src/services/workflow-integration.test.ts | 363 ++++++++++++++++++ extensions/cli/src/shared-options.ts | 5 + 9 files changed, 967 insertions(+), 21 deletions(-) create mode 100644 extensions/cli/src/services/WorkflowService.test.ts create mode 100644 extensions/cli/src/services/WorkflowService.ts create mode 100644 extensions/cli/src/services/workflow-integration.test.ts diff --git a/extensions/cli/src/commands/BaseCommandOptions.ts b/extensions/cli/src/commands/BaseCommandOptions.ts index 0d0808ea3..bb32e9a90 100644 --- a/extensions/cli/src/commands/BaseCommandOptions.ts +++ b/extensions/cli/src/commands/BaseCommandOptions.ts @@ -21,6 +21,8 @@ export interface BaseCommandOptions { ask?: string[]; /** Array of tools to exclude from use (--exclude) */ exclude?: string[]; + /** Workflow slug from the hub (--workflow) */ + workflow?: string; } /** diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index ee1c9b254..323d6968d 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -7,10 +7,12 @@ import { modelProcessor, processRule, } from "./hubLoader.js"; +import { serviceContainer } from "./services/ServiceContainer.js"; +import { SERVICE_NAMES, WorkflowServiceState } from "./services/types.js"; import { logger } from "./util/logger.js"; /** - * Enhances a configuration by injecting additional components from CLI flags + * Enhances a configuration by injecting additional components from CLI flags and workflow */ export class ConfigEnhancer { /** @@ -22,6 +24,9 @@ export class ConfigEnhancer { ): Promise { let enhancedConfig = { ...config }; + // Apply workflow rules first (highest priority) + enhancedConfig = await this.injectWorkflowRules(enhancedConfig); + // Apply rules if (options.rule && options.rule.length > 0) { enhancedConfig = await this.injectRules(enhancedConfig, options.rule); @@ -45,6 +50,42 @@ export class ConfigEnhancer { return enhancedConfig; } + /** + * Inject workflow rules if a workflow is active + */ + private async injectWorkflowRules( + config: AssistantUnrolled, + ): Promise { + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + if (!workflowState.isActive || !workflowState.workflowFile?.rules) { + return config; + } + + const workflowRules = workflowState.workflowFile.rules; + const processedContent = await processRule(workflowRules); + const workflowSlug = workflowState.workflow; + + const workflowRule: Rule = { + name: `workflow:${workflowSlug}`, + rule: processedContent, + }; + + const modifiedConfig = { ...config }; + const existingRules = modifiedConfig.rules || []; + modifiedConfig.rules = [workflowRule, ...existingRules]; + + logger.debug(`Injected workflow rules from ${workflowSlug}`); + return modifiedConfig; + } catch (error: any) { + logger.debug(`Workflow service not available: ${error.message}`); + return config; + } + } + /** * Inject rules into the system message */ diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 313f2afc1..30d6a022f 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -5,7 +5,12 @@ import { createLlmApi, getLlmApi } from "../config.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { ModelServiceState } from "./types.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { + ModelServiceState, + SERVICE_NAMES, + WorkflowServiceState, +} from "./types.js"; /** * Service for managing LLM and model state @@ -50,10 +55,29 @@ export class ModelService this.assistant = assistant; this.authConfig = authConfig; - this.availableModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; + + this.availableModels = await this.filterAvailableModels(assistant); + + const workflowModel = await this.getWorkflowModelName(); + if (workflowModel) { + logger.debug("Workflow specifies model", { workflowModel }); + const selectedModel = this.availableModels[0]; + if (!selectedModel) { + throw new Error("No workflow model available after filtering"); + } + + const llmApi = createLlmApi(selectedModel, authConfig); + if (!llmApi) { + throw new Error("Failed to initialize LLM with workflow model"); + } + + return { + llmApi, + model: selectedModel, + assistant, + authConfig, + }; + } // Check if we have a persisted model name and use it if valid const persistedModelName = getModelName(authConfig); @@ -97,8 +121,8 @@ export class ModelService }; } } else { - // Use default model selection - const [llmApi, model] = getLlmApi(assistant, authConfig); + const modifiedAssistant = { ...assistant, models: this.availableModels }; + const [llmApi, model] = getLlmApi(modifiedAssistant, authConfig); return { llmApi, model, @@ -183,19 +207,7 @@ export class ModelService name: string; index: number; }> { - // Get assistant from state to ensure we have the latest data - const { assistant } = this.getState(); - if (!assistant || !assistant.models) { - return []; - } - - // Filter for chat models - const chatModels = (assistant.models.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - return chatModels.map((model, index) => ({ + return this.availableModels.map((model, index) => ({ provider: model.provider, name: (model as any).name || (model as any).model || "unnamed", index, @@ -332,4 +344,52 @@ export class ModelService return nameMatches; }); } + + /** + * Get workflow model name if workflow is active + */ + private async getWorkflowModelName(): Promise { + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + return workflowState.isActive + ? workflowState.workflowFile?.model + : undefined; + } catch (error) { + return undefined; + } + } + + /** + * Filter available models based on workflow constraints + */ + private async filterAvailableModels( + assistant: AssistantUnrolled, + ): Promise { + const baseModels = (assistant.models?.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + const workflowModel = await this.getWorkflowModelName(); + if (workflowModel) { + const workflowModelConfig = baseModels.find( + (model) => (model as any).name === workflowModel, + ); + + if (workflowModelConfig) { + return [workflowModelConfig]; + } else { + const workflowModelConfig: ModelConfig = { + provider: "openai", + name: workflowModel, + } as any; + + return [workflowModelConfig]; + } + } + + return baseModels; + } } diff --git a/extensions/cli/src/services/WorkflowService.test.ts b/extensions/cli/src/services/WorkflowService.test.ts new file mode 100644 index 000000000..651429d88 --- /dev/null +++ b/extensions/cli/src/services/WorkflowService.test.ts @@ -0,0 +1,315 @@ +import { vi } from "vitest"; + +import { WorkflowService, workflowProcessor } from "./WorkflowService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + HubPackageProcessor: vi.fn(), +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +describe("WorkflowService", () => { + let service: WorkflowService; + let mockLoadPackageFromHub: any; + + beforeEach(async () => { + vi.clearAllMocks(); + service = new WorkflowService(); + + // Get the mock function + const hubLoaderModule = await import("../hubLoader.js"); + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + }); + + describe("initialization", () => { + it("should initialize with inactive state when no workflow provided", async () => { + const state = await service.initialize(); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + }); + + it("should initialize with inactive state when workflow is empty string", async () => { + const state = await service.initialize(""); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + }); + + it("should reject invalid workflow slug format", async () => { + const state = await service.initialize("invalid-slug"); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + + // Should not call loadPackageFromHub with invalid slug + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should reject workflow slug with too many parts", async () => { + const state = await service.initialize("owner/package/extra"); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + + expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); + }); + + it("should load valid workflow successfully", async () => { + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "gpt-4", + tools: "bash,read,write", + rules: "Be helpful", + prompt: "You are a helpful assistant.", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + + const state = await service.initialize("owner/package"); + + expect(state).toEqual({ + workflowFile: mockWorkflowFile, + workflow: "owner/package", + isActive: true, + }); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/package", + workflowProcessor, + ); + }); + + it("should handle loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + const state = await service.initialize("owner/package"); + + expect(state).toEqual({ + workflowFile: null, + workflow: null, + isActive: false, + }); + + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "owner/package", + workflowProcessor, + ); + }); + + it("should handle minimal workflow file", async () => { + const mockWorkflowFile = { + name: "Minimal Workflow", + prompt: "", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + + const state = await service.initialize("owner/minimal"); + + expect(state).toEqual({ + workflowFile: mockWorkflowFile, + workflow: "owner/minimal", + isActive: true, + }); + }); + }); + + describe("state getters", () => { + beforeEach(async () => { + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow", + model: "gpt-4", + tools: "bash,read,write", + rules: "Be helpful", + prompt: "You are a helpful assistant.", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/package"); + }); + + it("should return workflow file", () => { + const workflowFile = service.getWorkflowFile(); + expect(workflowFile?.name).toBe("Test Workflow"); + }); + + it("should return workflow slug", () => { + const workflow = service.getWorkflow(); + expect(workflow).toBe("owner/package"); + }); + + it("should return active status", () => { + const isActive = service.isWorkflowActive(); + expect(isActive).toBe(true); + }); + + it("should return workflow model", () => { + const model = service.getWorkflowModel(); + expect(model).toBe("gpt-4"); + }); + + it("should return workflow tools", () => { + const tools = service.getWorkflowTools(); + expect(tools).toBe("bash,read,write"); + }); + + it("should return workflow rules", () => { + const rules = service.getWorkflowRules(); + expect(rules).toBe("Be helpful"); + }); + + it("should return workflow prompt", () => { + const prompt = service.getWorkflowPrompt(); + expect(prompt).toBe("You are a helpful assistant."); + }); + }); + + describe("inactive workflow state getters", () => { + beforeEach(() => { + // Initialize with no workflow + service.initialize(); + }); + + it("should return null for workflow file when inactive", () => { + const workflowFile = service.getWorkflowFile(); + expect(workflowFile).toBeNull(); + }); + + it("should return null for workflow when inactive", () => { + const workflow = service.getWorkflow(); + expect(workflow).toBeNull(); + }); + + it("should return false for active status when inactive", () => { + const isActive = service.isWorkflowActive(); + expect(isActive).toBe(false); + }); + + it("should return undefined for model when inactive", () => { + const model = service.getWorkflowModel(); + expect(model).toBeUndefined(); + }); + + it("should return undefined for tools when inactive", () => { + const tools = service.getWorkflowTools(); + expect(tools).toBeUndefined(); + }); + + it("should return undefined for rules when inactive", () => { + const rules = service.getWorkflowRules(); + expect(rules).toBeUndefined(); + }); + + it("should return undefined for prompt when inactive", () => { + const prompt = service.getWorkflowPrompt(); + expect(prompt).toBeUndefined(); + }); + }); + + describe("partial workflow data", () => { + it("should handle workflow with only name and prompt", async () => { + const mockWorkflowFile = { + name: "Simple Workflow", + prompt: "Simple prompt", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/simple"); + + expect(service.getWorkflowModel()).toBeUndefined(); + expect(service.getWorkflowTools()).toBeUndefined(); + expect(service.getWorkflowRules()).toBeUndefined(); + expect(service.getWorkflowPrompt()).toBe("Simple prompt"); + expect(service.isWorkflowActive()).toBe(true); + }); + + it("should handle workflow with empty prompt", async () => { + const mockWorkflowFile = { + name: "Empty Prompt Workflow", + model: "gpt-3.5-turbo", + prompt: "", + }; + + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await service.initialize("owner/empty"); + + expect(service.getWorkflowModel()).toBe("gpt-3.5-turbo"); + expect(service.getWorkflowPrompt()).toBe(""); + expect(service.isWorkflowActive()).toBe(true); + }); + }); +}); + +describe("workflowProcessor", () => { + it("should have correct type and extensions", () => { + expect(workflowProcessor.type).toBe("prompt"); + expect(workflowProcessor.expectedFileExtensions).toEqual([".md"]); + }); + + it("should parse workflow content correctly", () => { + const content = `--- +name: Test Workflow +model: gpt-4 +tools: bash,read +--- +You are a helpful assistant.`; + + const result = workflowProcessor.parseContent(content, "test.md"); + expect(result).toEqual({ + name: "Test Workflow", + model: "gpt-4", + tools: "bash,read", + prompt: "You are a helpful assistant.", + }); + }); + + it("should validate workflow content", () => { + const validWorkflow = { + name: "Valid Workflow", + prompt: "Test prompt", + }; + + const invalidWorkflow = { + prompt: "Test prompt", + // Missing name + }; + + expect(workflowProcessor.validateContent?.(validWorkflow)).toBe(true); + expect(workflowProcessor.validateContent?.(invalidWorkflow as any)).toBe( + false, + ); + }); + + it("should validate workflow with empty name as invalid", () => { + const invalidWorkflow = { + name: "", + prompt: "Test prompt", + }; + + expect(workflowProcessor.validateContent?.(invalidWorkflow)).toBe(false); + }); +}); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts new file mode 100644 index 000000000..89b3ced33 --- /dev/null +++ b/extensions/cli/src/services/WorkflowService.ts @@ -0,0 +1,144 @@ +import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; + +import { HubPackageProcessor, loadPackageFromHub } from "../hubLoader.js"; +import { logger } from "../util/logger.js"; + +import { BaseService } from "./BaseService.js"; +import { WorkflowServiceState } from "./types.js"; + +/** + * Workflow processor - handles markdown workflow files + */ +export const workflowProcessor: HubPackageProcessor = { + type: "prompt", // Use prompt type for endpoint compatibility + expectedFileExtensions: [".md"], + parseContent: (content: string) => parseWorkflowFile(content), + validateContent: (workflowFile: WorkflowFile) => { + // Validate that the workflow has a name (required by parseWorkflowFile) + return !!workflowFile.name; + }, +}; + +/** + * Service for managing workflow state + * Loads workflows from the hub and extracts model, tools, and prompt information + */ +export class WorkflowService extends BaseService { + constructor() { + super("WorkflowService", { + workflowFile: null, + workflow: null, + isActive: false, + }); + } + + /** + * Initialize the workflow service with a workflow slug + */ + async doInitialize(workflow?: string): Promise { + logger.debug("WorkflowService.doInitialize called", { + hasWorkflow: !!workflow, + workflow, + }); + + if (!workflow) { + return { + workflowFile: null, + workflow: null, + isActive: false, + }; + } + + try { + // Validate slug format (ownerSlug/packageSlug) + const parts = workflow.split("/"); + if (parts.length !== 2) { + throw new Error( + `Invalid workflow slug format. Expected "owner/package", got: ${workflow}`, + ); + } + + logger.debug("Loading workflow from hub", { workflow }); + const workflowFile = await loadPackageFromHub( + workflow, + workflowProcessor, + ); + + logger.debug("Workflow loaded successfully", { + workflow, + name: workflowFile.name, + hasModel: !!workflowFile.model, + hasTools: !!workflowFile.tools, + hasRules: !!workflowFile.rules, + promptLength: workflowFile.prompt?.length || 0, + }); + + return { + workflowFile, + workflow, + isActive: true, + }; + } catch (error: any) { + logger.error("Failed to initialize WorkflowService:", error); + // Don't throw - allow the system to continue without the workflow + return { + workflowFile: null, + workflow: null, + isActive: false, + }; + } + } + + /** + * Get the loaded workflow file + */ + getWorkflowFile(): WorkflowFile | null { + return this.getState().workflowFile; + } + + /** + * Get the workflow slug + */ + getWorkflow(): string | null { + return this.getState().workflow; + } + + /** + * Check if a workflow is active + */ + isWorkflowActive(): boolean { + return this.getState().isActive; + } + + /** + * Get workflow model if present + */ + getWorkflowModel(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.model; + } + + /** + * Get workflow tools if present + */ + getWorkflowTools(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.tools; + } + + /** + * Get workflow rules if present + */ + getWorkflowRules(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.rules; + } + + /** + * Get workflow prompt + */ + getWorkflowPrompt(): string | undefined { + const workflowFile = this.getWorkflowFile(); + return workflowFile?.prompt; + } +} diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index d46960ddd..f2d4c0c94 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -23,6 +23,7 @@ import { ServiceInitResult, } from "./types.js"; import { UpdateService } from "./UpdateService.js"; +import { WorkflowService } from "./WorkflowService.js"; // Service instances const authService = new AuthService(); @@ -35,6 +36,7 @@ const resourceMonitoringService = new ResourceMonitoringService(); const chatHistoryService = new ChatHistoryService(); const updateService = new UpdateService(); const storageSyncService = new StorageSyncService(); +const workflowService = new WorkflowService(); /** * Initialize all services and register them with the service container @@ -265,6 +267,12 @@ export async function initializeServices( [], // No dependencies for now, but could depend on SESSION in future ); + serviceContainer.register( + SERVICE_NAMES.WORKFLOW, + () => workflowService.initialize(commandOptions.workflow), + [], + ); + // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -327,6 +335,7 @@ export const services = { chatHistory: chatHistoryService, updateService: updateService, storageSync: storageSyncService, + workflow: workflowService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index ae5262cae..be3f12064 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -118,6 +118,12 @@ export interface StorageSyncServiceState { lastError?: string | null; } +export interface WorkflowServiceState { + workflowFile: any | null; + workflow: string | null; + isActive: boolean; +} + export type { ChatHistoryState } from "./ChatHistoryService.js"; export type { FileIndexServiceState } from "./FileIndexService.js"; @@ -137,6 +143,7 @@ export const SERVICE_NAMES = { CHAT_HISTORY: "chatHistory", UPDATE: "update", STORAGE_SYNC: "storageSync", + WORKFLOW: "workflow", } as const; /** diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts new file mode 100644 index 000000000..ff8923351 --- /dev/null +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -0,0 +1,363 @@ +import { vi } from "vitest"; + +import { configEnhancer } from "../configEnhancer.js"; +import { ModelService } from "./ModelService.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { ToolPermissionService } from "./ToolPermissionService.js"; +import { SERVICE_NAMES } from "./types.js"; +import { WorkflowService } from "./WorkflowService.js"; + +// Mock the hubLoader module +vi.mock("../hubLoader.js", () => ({ + loadPackageFromHub: vi.fn(), + mcpProcessor: {}, + modelProcessor: {}, + processRule: vi.fn(), +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +// Mock config module +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(), + getLlmApi: vi.fn(), +})); + +// Mock auth module +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(), +})); + +describe("Workflow Integration Tests", () => { + let workflowService: WorkflowService; + let modelService: ModelService; + let toolPermissionService: ToolPermissionService; + let mockLoadPackageFromHub: any; + let mockProcessRule: any; + let mockCreateLlmApi: any; + let mockGetLlmApi: any; + + const mockWorkflowFile = { + name: "Test Workflow", + description: "A test workflow for integration testing", + model: "gpt-4-workflow", + tools: "bash,read,write", + rules: "Always be helpful and concise", + prompt: "You are a workflow assistant.", + }; + + const mockAssistant = { + models: [ + { + provider: "openai", + name: "gpt-3.5-turbo", + roles: ["chat"], + }, + { + provider: "openai", + name: "gpt-4", + roles: ["chat"], + }, + ], + }; + + const mockAuthConfig = { + apiKey: "test-key", + }; + + beforeEach(async () => { + vi.clearAllMocks(); + + // Get mock functions + const hubLoaderModule = await import("../hubLoader.js"); + const configModule = await import("../config.js"); + + mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockProcessRule = hubLoaderModule.processRule as any; + mockCreateLlmApi = configModule.createLlmApi as any; + mockGetLlmApi = configModule.getLlmApi as any; + + // Create service instances + workflowService = new WorkflowService(); + modelService = new ModelService(); + toolPermissionService = new ToolPermissionService(); + + // Mock service container + vi.spyOn(serviceContainer, "get").mockImplementation( + async (serviceName: string) => { + if (serviceName === SERVICE_NAMES.WORKFLOW) { + return workflowService.getState(); + } + throw new Error(`Service ${serviceName} not mocked`); + }, + ); + + // Setup default mocks + mockProcessRule.mockResolvedValue("Processed rule content"); + mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); + mockGetLlmApi.mockReturnValue([ + { mock: "llmApi" }, + mockAssistant.models[0], + ]); + }); + + describe("WorkflowService affects ModelService", () => { + it("should use workflow model when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + expect(workflowService.isWorkflowActive()).toBe(true); + expect(workflowService.getWorkflowModel()).toBe("gpt-4-workflow"); + + // Initialize model service - it should use the workflow model + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + expect(mockCreateLlmApi).toHaveBeenCalledWith( + expect.objectContaining({ + name: "gpt-4-workflow", + provider: "openai", + }), + mockAuthConfig, + ); + }); + + it("should use regular models when no workflow is active", async () => { + // Initialize workflow service without workflow + await workflowService.initialize(); + + expect(workflowService.isWorkflowActive()).toBe(false); + + // Initialize model service - it should use regular model selection + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + expect(mockGetLlmApi).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should handle workflow model that exists in assistant models", async () => { + const workflowWithExistingModel = { + ...mockWorkflowFile, + model: "gpt-4", // This exists in mockAssistant.models + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithExistingModel); + await workflowService.initialize("owner/workflow"); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + expect(mockCreateLlmApi).toHaveBeenCalledWith( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + mockAuthConfig, + ); + }); + }); + + describe("WorkflowService affects ConfigEnhancer", () => { + it("should inject workflow rules when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(mockProcessRule).toHaveBeenCalledWith(mockWorkflowFile.rules); + expect(enhancedConfig.rules).toHaveLength(2); + expect(enhancedConfig?.rules?.[0]).toEqual({ + name: "workflow:owner/workflow", + rule: "Processed rule content", + }); + expect(enhancedConfig?.rules?.[1]).toBe("existing rule"); + }); + + it("should not inject workflow rules when workflow is inactive", async () => { + // Initialize workflow service without workflow + await workflowService.initialize(); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(mockProcessRule).not.toHaveBeenCalled(); + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig?.rules?.[0]).toBe("existing rule"); + }); + + it("should not inject workflow rules when workflow has no rules", async () => { + const workflowWithoutRules = { + ...mockWorkflowFile, + rules: undefined, + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithoutRules); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(mockProcessRule).not.toHaveBeenCalled(); + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + }); + + describe("Workflow model constraints", () => { + it("should filter available models to only workflow model when specified", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + // Verify that available models are filtered + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(1); + expect(availableModels[0].name).toBe("gpt-4-workflow"); + }); + + it("should allow all models when no workflow is active", async () => { + await workflowService.initialize(); + + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + + const availableModels = modelService.getAvailableChatModels(); + expect(availableModels).toHaveLength(2); + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); + }); + }); + + describe("Error handling", () => { + it("should handle workflow loading errors gracefully", async () => { + mockLoadPackageFromHub.mockRejectedValue(new Error("Network error")); + + await workflowService.initialize("owner/workflow"); + + expect(workflowService.isWorkflowActive()).toBe(false); + + // Model service should work normally + await modelService.initialize( + mockAssistant as any, + mockAuthConfig as any, + ); + expect(mockGetLlmApi).toHaveBeenCalled(); + }); + + it("should handle workflow rule processing errors gracefully", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + mockProcessRule.mockRejectedValue(new Error("Rule processing failed")); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + // Should not inject workflow rule but should preserve existing rules + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + + it("should handle missing service container gracefully", async () => { + // Mock service container to throw error + vi.spyOn(serviceContainer, "get").mockRejectedValue( + new Error("Service not ready"), + ); + + const baseConfig = { + rules: ["existing rule"], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + // Should return config unchanged + expect(enhancedConfig.rules).toHaveLength(1); + expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + }); + }); + + describe("Workflow data extraction", () => { + it("should correctly extract all workflow properties", async () => { + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + expect(workflowService.getWorkflowModel()).toBe("gpt-4-workflow"); + expect(workflowService.getWorkflowTools()).toBe("bash,read,write"); + expect(workflowService.getWorkflowRules()).toBe( + "Always be helpful and concise", + ); + expect(workflowService.getWorkflowPrompt()).toBe( + "You are a workflow assistant.", + ); + expect(workflowService.getWorkflow()).toBe("owner/workflow"); + }); + + it("should handle partial workflow data", async () => { + const partialWorkflow = { + name: "Partial Workflow", + model: "gpt-3.5-turbo", + prompt: "Partial prompt", + // No tools or rules + }; + + mockLoadPackageFromHub.mockResolvedValue(partialWorkflow); + await workflowService.initialize("owner/partial"); + + expect(workflowService.getWorkflowModel()).toBe("gpt-3.5-turbo"); + expect(workflowService.getWorkflowTools()).toBeUndefined(); + expect(workflowService.getWorkflowRules()).toBeUndefined(); + expect(workflowService.getWorkflowPrompt()).toBe("Partial prompt"); + }); + }); +}); diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts index 31572949d..d30455c1c 100644 --- a/extensions/cli/src/shared-options.ts +++ b/extensions/cli/src/shared-options.ts @@ -83,6 +83,10 @@ export function addCommonOptions(command: Command): Command { return array; }, [] as string[], + ) + .option( + "--workflow ", + "Load workflow from the hub (slug in format 'owner/package')", ); } @@ -106,6 +110,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { "allow", "ask", "exclude", + "workflow", ]; for (const optName of inheritableOptions) { From 8b0dc2242200926b58bc46dc310a6d8e263c0eed Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 11:39:25 -0700 Subject: [PATCH 25/91] fix: simplify workflow service --- .../cli/src/services/WorkflowService.test.ts | 101 +++++------------- .../cli/src/services/WorkflowService.ts | 68 +----------- .../src/services/workflow-integration.test.ts | 31 +++--- 3 files changed, 44 insertions(+), 156 deletions(-) diff --git a/extensions/cli/src/services/WorkflowService.test.ts b/extensions/cli/src/services/WorkflowService.test.ts index 651429d88..87fe5f1ed 100644 --- a/extensions/cli/src/services/WorkflowService.test.ts +++ b/extensions/cli/src/services/WorkflowService.test.ts @@ -152,81 +152,28 @@ describe("WorkflowService", () => { await service.initialize("owner/package"); }); - it("should return workflow file", () => { - const workflowFile = service.getWorkflowFile(); - expect(workflowFile?.name).toBe("Test Workflow"); - }); - - it("should return workflow slug", () => { - const workflow = service.getWorkflow(); - expect(workflow).toBe("owner/package"); - }); - - it("should return active status", () => { - const isActive = service.isWorkflowActive(); - expect(isActive).toBe(true); - }); - - it("should return workflow model", () => { - const model = service.getWorkflowModel(); - expect(model).toBe("gpt-4"); - }); - - it("should return workflow tools", () => { - const tools = service.getWorkflowTools(); - expect(tools).toBe("bash,read,write"); - }); - - it("should return workflow rules", () => { - const rules = service.getWorkflowRules(); - expect(rules).toBe("Be helpful"); - }); - - it("should return workflow prompt", () => { - const prompt = service.getWorkflowPrompt(); - expect(prompt).toBe("You are a helpful assistant."); + it("should return workflow state", () => { + const state = service.getState(); + expect(state.workflowFile?.name).toBe("Test Workflow"); + expect(state.workflow).toBe("owner/package"); + expect(state.isActive).toBe(true); + expect(state.workflowFile?.model).toBe("gpt-4"); + expect(state.workflowFile?.tools).toBe("bash,read,write"); + expect(state.workflowFile?.rules).toBe("Be helpful"); + expect(state.workflowFile?.prompt).toBe("You are a helpful assistant."); }); }); - describe("inactive workflow state getters", () => { + describe("inactive workflow state", () => { beforeEach(() => { - // Initialize with no workflow service.initialize(); }); - it("should return null for workflow file when inactive", () => { - const workflowFile = service.getWorkflowFile(); - expect(workflowFile).toBeNull(); - }); - - it("should return null for workflow when inactive", () => { - const workflow = service.getWorkflow(); - expect(workflow).toBeNull(); - }); - - it("should return false for active status when inactive", () => { - const isActive = service.isWorkflowActive(); - expect(isActive).toBe(false); - }); - - it("should return undefined for model when inactive", () => { - const model = service.getWorkflowModel(); - expect(model).toBeUndefined(); - }); - - it("should return undefined for tools when inactive", () => { - const tools = service.getWorkflowTools(); - expect(tools).toBeUndefined(); - }); - - it("should return undefined for rules when inactive", () => { - const rules = service.getWorkflowRules(); - expect(rules).toBeUndefined(); - }); - - it("should return undefined for prompt when inactive", () => { - const prompt = service.getWorkflowPrompt(); - expect(prompt).toBeUndefined(); + it("should return inactive state when no workflow", () => { + const state = service.getState(); + expect(state.workflowFile).toBeNull(); + expect(state.workflow).toBeNull(); + expect(state.isActive).toBe(false); }); }); @@ -240,11 +187,12 @@ describe("WorkflowService", () => { mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await service.initialize("owner/simple"); - expect(service.getWorkflowModel()).toBeUndefined(); - expect(service.getWorkflowTools()).toBeUndefined(); - expect(service.getWorkflowRules()).toBeUndefined(); - expect(service.getWorkflowPrompt()).toBe("Simple prompt"); - expect(service.isWorkflowActive()).toBe(true); + const state = service.getState(); + expect(state.workflowFile?.model).toBeUndefined(); + expect(state.workflowFile?.tools).toBeUndefined(); + expect(state.workflowFile?.rules).toBeUndefined(); + expect(state.workflowFile?.prompt).toBe("Simple prompt"); + expect(state.isActive).toBe(true); }); it("should handle workflow with empty prompt", async () => { @@ -257,9 +205,10 @@ describe("WorkflowService", () => { mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await service.initialize("owner/empty"); - expect(service.getWorkflowModel()).toBe("gpt-3.5-turbo"); - expect(service.getWorkflowPrompt()).toBe(""); - expect(service.isWorkflowActive()).toBe(true); + const state = service.getState(); + expect(state.workflowFile?.model).toBe("gpt-3.5-turbo"); + expect(state.workflowFile?.prompt).toBe(""); + expect(state.isActive).toBe(true); }); }); }); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts index 89b3ced33..b9b7c68fb 100644 --- a/extensions/cli/src/services/WorkflowService.ts +++ b/extensions/cli/src/services/WorkflowService.ts @@ -10,11 +10,10 @@ import { WorkflowServiceState } from "./types.js"; * Workflow processor - handles markdown workflow files */ export const workflowProcessor: HubPackageProcessor = { - type: "prompt", // Use prompt type for endpoint compatibility + type: "prompt", expectedFileExtensions: [".md"], parseContent: (content: string) => parseWorkflowFile(content), validateContent: (workflowFile: WorkflowFile) => { - // Validate that the workflow has a name (required by parseWorkflowFile) return !!workflowFile.name; }, }; @@ -50,7 +49,6 @@ export class WorkflowService extends BaseService { } try { - // Validate slug format (ownerSlug/packageSlug) const parts = workflow.split("/"); if (parts.length !== 2) { throw new Error( @@ -58,21 +56,11 @@ export class WorkflowService extends BaseService { ); } - logger.debug("Loading workflow from hub", { workflow }); const workflowFile = await loadPackageFromHub( workflow, workflowProcessor, ); - logger.debug("Workflow loaded successfully", { - workflow, - name: workflowFile.name, - hasModel: !!workflowFile.model, - hasTools: !!workflowFile.tools, - hasRules: !!workflowFile.rules, - promptLength: workflowFile.prompt?.length || 0, - }); - return { workflowFile, workflow, @@ -80,7 +68,6 @@ export class WorkflowService extends BaseService { }; } catch (error: any) { logger.error("Failed to initialize WorkflowService:", error); - // Don't throw - allow the system to continue without the workflow return { workflowFile: null, workflow: null, @@ -88,57 +75,4 @@ export class WorkflowService extends BaseService { }; } } - - /** - * Get the loaded workflow file - */ - getWorkflowFile(): WorkflowFile | null { - return this.getState().workflowFile; - } - - /** - * Get the workflow slug - */ - getWorkflow(): string | null { - return this.getState().workflow; - } - - /** - * Check if a workflow is active - */ - isWorkflowActive(): boolean { - return this.getState().isActive; - } - - /** - * Get workflow model if present - */ - getWorkflowModel(): string | undefined { - const workflowFile = this.getWorkflowFile(); - return workflowFile?.model; - } - - /** - * Get workflow tools if present - */ - getWorkflowTools(): string | undefined { - const workflowFile = this.getWorkflowFile(); - return workflowFile?.tools; - } - - /** - * Get workflow rules if present - */ - getWorkflowRules(): string | undefined { - const workflowFile = this.getWorkflowFile(); - return workflowFile?.rules; - } - - /** - * Get workflow prompt - */ - getWorkflowPrompt(): string | undefined { - const workflowFile = this.getWorkflowFile(); - return workflowFile?.prompt; - } } diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index ff8923351..ce7518070 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -114,8 +114,9 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); - expect(workflowService.isWorkflowActive()).toBe(true); - expect(workflowService.getWorkflowModel()).toBe("gpt-4-workflow"); + const workflowState = workflowService.getState(); + expect(workflowState.isActive).toBe(true); + expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); // Initialize model service - it should use the workflow model await modelService.initialize( @@ -136,7 +137,8 @@ describe("Workflow Integration Tests", () => { // Initialize workflow service without workflow await workflowService.initialize(); - expect(workflowService.isWorkflowActive()).toBe(false); + const workflowState = workflowService.getState(); + expect(workflowState.isActive).toBe(false); // Initialize model service - it should use regular model selection await modelService.initialize( @@ -276,7 +278,8 @@ describe("Workflow Integration Tests", () => { await workflowService.initialize("owner/workflow"); - expect(workflowService.isWorkflowActive()).toBe(false); + const workflowState = workflowService.getState(); + expect(workflowState.isActive).toBe(false); // Model service should work normally await modelService.initialize( @@ -332,15 +335,16 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); - expect(workflowService.getWorkflowModel()).toBe("gpt-4-workflow"); - expect(workflowService.getWorkflowTools()).toBe("bash,read,write"); - expect(workflowService.getWorkflowRules()).toBe( + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); + expect(workflowState.workflowFile?.tools).toBe("bash,read,write"); + expect(workflowState.workflowFile?.rules).toBe( "Always be helpful and concise", ); - expect(workflowService.getWorkflowPrompt()).toBe( + expect(workflowState.workflowFile?.prompt).toBe( "You are a workflow assistant.", ); - expect(workflowService.getWorkflow()).toBe("owner/workflow"); + expect(workflowState.workflow).toBe("owner/workflow"); }); it("should handle partial workflow data", async () => { @@ -354,10 +358,11 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub.mockResolvedValue(partialWorkflow); await workflowService.initialize("owner/partial"); - expect(workflowService.getWorkflowModel()).toBe("gpt-3.5-turbo"); - expect(workflowService.getWorkflowTools()).toBeUndefined(); - expect(workflowService.getWorkflowRules()).toBeUndefined(); - expect(workflowService.getWorkflowPrompt()).toBe("Partial prompt"); + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.model).toBe("gpt-3.5-turbo"); + expect(workflowState.workflowFile?.tools).toBeUndefined(); + expect(workflowState.workflowFile?.rules).toBeUndefined(); + expect(workflowState.workflowFile?.prompt).toBe("Partial prompt"); }); }); }); From 452e01204f9a388927aaac8b0328440508c96b1d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 12:23:07 -0700 Subject: [PATCH 26/91] feat: tool permissions from workflow files --- extensions/cli/src/configEnhancer.ts | 66 ++++++- .../cli/src/services/ToolPermissionService.ts | 102 ++++++++++- .../src/services/workflow-integration.test.ts | 86 ++++++++- .../src/markdown/workflowFiles.test.ts | 167 ++++++++++++++++++ .../config-yaml/src/markdown/workflowFiles.ts | 83 +++++++++ 5 files changed, 489 insertions(+), 15 deletions(-) diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 323d6968d..db368628f 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -1,4 +1,8 @@ -import { AssistantUnrolled, Rule } from "@continuedev/config-yaml"; +import { + AssistantUnrolled, + parseWorkflowTools, + Rule, +} from "@continuedev/config-yaml"; import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; import { @@ -24,8 +28,9 @@ export class ConfigEnhancer { ): Promise { let enhancedConfig = { ...config }; - // Apply workflow rules first (highest priority) + // Apply workflow components first (highest priority) enhancedConfig = await this.injectWorkflowRules(enhancedConfig); + enhancedConfig = await this.injectWorkflowMcpServers(enhancedConfig); // Apply rules if (options.rule && options.rule.length > 0) { @@ -86,6 +91,58 @@ export class ConfigEnhancer { } } + /** + * Inject workflow MCP servers if a workflow has tools + */ + private async injectWorkflowMcpServers( + config: AssistantUnrolled, + ): Promise { + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + if (!workflowState.isActive || !workflowState.workflowFile?.tools) { + return config; + } + + const parsedTools = parseWorkflowTools(workflowState.workflowFile.tools); + if (parsedTools.mcpServers.length === 0) { + return config; + } + + const processedMcps = await loadPackagesFromHub( + parsedTools.mcpServers, + mcpProcessor, + ); + const modifiedConfig = { ...config }; + const existingMcpServers = (modifiedConfig as any).mcpServers || []; + + // Deduplicate MCP servers by checking if they already exist + const existingServerNames = new Set( + existingMcpServers.map((server: any) => server.name || server.slug), + ); + + const newMcpServers = processedMcps.filter((server: any) => { + const serverName = server.name || server.slug; + return !existingServerNames.has(serverName); + }); + + if (newMcpServers.length > 0) { + (modifiedConfig as any).mcpServers = [ + ...newMcpServers, + ...existingMcpServers, + ]; + logger.debug(`Injected ${newMcpServers.length} workflow MCP servers`); + } + + return modifiedConfig; + } catch (error: any) { + logger.debug(`Failed to inject workflow MCP servers: ${error.message}`); + return config; + } + } + /** * Inject rules into the system message */ @@ -187,8 +244,3 @@ export class ConfigEnhancer { return config; } } - -/** - * Global config enhancer instance - */ -export const configEnhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 8271b044e..e5ae0e555 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -1,3 +1,5 @@ +import { parseWorkflowTools } from "@continuedev/config-yaml"; + import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js"; import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js"; import { @@ -7,14 +9,18 @@ import { } from "../permissions/types.js"; import { logger } from "../util/logger.js"; +import { serviceContainer } from "./ServiceContainer.js"; +import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; + import { BaseService } from "./BaseService.js"; export interface ToolPermissionServiceState { permissions: ToolPermissions; currentMode: PermissionMode; isHeadless: boolean; - modePolicyCount?: number; // Track how many policies are from mode vs other sources - originalPolicies?: ToolPermissions; // Store original policies when switching modes + modePolicyCount?: number; + workflowPolicyCount?: number; + originalPolicies?: ToolPermissions; } /** @@ -30,6 +36,53 @@ export class ToolPermissionService extends BaseService { + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + if (!workflowState.isActive || !workflowState.workflowFile?.tools) { + return []; + } + + const parsedTools = parseWorkflowTools(workflowState.workflowFile.tools); + const policies: ToolPermissionPolicy[] = []; + + if (parsedTools.allBuiltIn) { + policies.push({ tool: "*", permission: "allow" }); + policies.push({ tool: "mcp:*", permission: "exclude" }); + } else { + policies.push({ tool: "*", permission: "exclude" }); + } + + for (const toolRef of parsedTools.tools) { + if (toolRef.mcpServer) { + if (toolRef.toolName) { + policies.push({ + tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`, + permission: "allow", + }); + } else { + policies.push({ + tool: `mcp:${toolRef.mcpServer}:*`, + permission: "allow", + }); + } + } else if (toolRef.toolName) { + policies.push({ tool: toolRef.toolName, permission: "allow" }); + } + } + + return policies; + } catch (error) { + return []; + } + } + /** * Generate mode-specific policies based on the current mode */ @@ -124,11 +177,14 @@ export class ToolPermissionService extends BaseService { + try { + const workflowPolicies = await this.generateWorkflowPolicies(); + + if (workflowPolicies.length > 0) { + const currentState = this.getState(); + const existingPolicies = currentState.permissions.policies; + const modePolicyCount = currentState.modePolicyCount || 0; + + // Insert workflow policies after mode policies but before other policies + const nonModePolicies = existingPolicies.slice(modePolicyCount); + const modePolicies = existingPolicies.slice(0, modePolicyCount); + + const allPolicies = [ + ...modePolicies, + ...workflowPolicies, + ...nonModePolicies, + ]; + + this.setState({ + permissions: { policies: allPolicies }, + workflowPolicyCount: workflowPolicies.length, + }); + + logger.debug( + `Applied ${workflowPolicies.length} workflow tool policies`, + ); + } + } catch (error: any) { + logger.debug(`Failed to apply workflow policies: ${error.message}`); + } + } + /** * Override isReady to always return true since we initialize synchronously */ diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index ce7518070..ff5c46286 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -1,6 +1,6 @@ import { vi } from "vitest"; -import { configEnhancer } from "../configEnhancer.js"; +import { ConfigEnhancer } from "src/configEnhancer.js"; import { ModelService } from "./ModelService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { ToolPermissionService } from "./ToolPermissionService.js"; @@ -10,6 +10,7 @@ import { WorkflowService } from "./WorkflowService.js"; // Mock the hubLoader module vi.mock("../hubLoader.js", () => ({ loadPackageFromHub: vi.fn(), + loadPackagesFromHub: vi.fn(), mcpProcessor: {}, modelProcessor: {}, processRule: vi.fn(), @@ -39,7 +40,9 @@ describe("Workflow Integration Tests", () => { let workflowService: WorkflowService; let modelService: ModelService; let toolPermissionService: ToolPermissionService; + let configEnhancer: ConfigEnhancer; let mockLoadPackageFromHub: any; + let mockLoadPackagesFromHub: any; let mockProcessRule: any; let mockCreateLlmApi: any; let mockGetLlmApi: any; @@ -80,6 +83,7 @@ describe("Workflow Integration Tests", () => { const configModule = await import("../config.js"); mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; + mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any; mockProcessRule = hubLoaderModule.processRule as any; mockCreateLlmApi = configModule.createLlmApi as any; mockGetLlmApi = configModule.getLlmApi as any; @@ -88,6 +92,7 @@ describe("Workflow Integration Tests", () => { workflowService = new WorkflowService(); modelService = new ModelService(); toolPermissionService = new ToolPermissionService(); + configEnhancer = new ConfigEnhancer(); // Mock service container vi.spyOn(serviceContainer, "get").mockImplementation( @@ -101,6 +106,7 @@ describe("Workflow Integration Tests", () => { // Setup default mocks mockProcessRule.mockResolvedValue("Processed rule content"); + mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); mockGetLlmApi.mockReturnValue([ { mock: "llmApi" }, @@ -365,4 +371,82 @@ describe("Workflow Integration Tests", () => { expect(workflowState.workflowFile?.prompt).toBe("Partial prompt"); }); }); + + describe("Workflow tools integration", () => { + it("should inject MCP servers from workflow tools", async () => { + const workflowWithTools = { + ...mockWorkflowFile, + tools: "owner/mcp1, another/mcp2:specific_tool", + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithTools); + mockLoadPackagesFromHub.mockResolvedValue([ + { name: "mcp1" }, + { name: "mcp2" }, + ]); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + mcpServers: [{ name: "existing-mcp" }], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(enhancedConfig.mcpServers).toHaveLength(3); + expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); + expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp2" }); + expect(enhancedConfig.mcpServers?.[2]).toEqual({ name: "existing-mcp" }); + }); + + it("should not inject MCP servers when workflow has no tools", async () => { + const workflowWithoutTools = { + ...mockWorkflowFile, + tools: undefined, + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithoutTools); + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + mcpServers: [{ name: "existing-mcp" }], + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + expect(enhancedConfig.mcpServers).toHaveLength(1); + expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "existing-mcp" }); + }); + + it("should deduplicate MCP servers", async () => { + const workflowWithDuplicateTools = { + ...mockWorkflowFile, + tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithDuplicateTools); + mockLoadPackagesFromHub.mockResolvedValue([{ name: "mcp1" }]); + + await workflowService.initialize("owner/workflow"); + + const baseConfig = { + mcpServers: [{ name: "mcp1" }], // Already exists + }; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + {}, + ); + + // Should not duplicate existing MCP server + expect(enhancedConfig.mcpServers).toHaveLength(1); + expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); + }); + }); }); diff --git a/packages/config-yaml/src/markdown/workflowFiles.test.ts b/packages/config-yaml/src/markdown/workflowFiles.test.ts index 9e7d995a5..9304542b9 100644 --- a/packages/config-yaml/src/markdown/workflowFiles.test.ts +++ b/packages/config-yaml/src/markdown/workflowFiles.test.ts @@ -1,5 +1,6 @@ import { parseWorkflowFile, + parseWorkflowTools, serializeWorkflowFile, type WorkflowFile, } from "./workflowFiles.js"; @@ -319,3 +320,169 @@ Prompt ); }); }); + +describe("parseWorkflowTools", () => { + it("should return empty arrays for undefined tools", () => { + const result = parseWorkflowTools(undefined); + expect(result).toEqual({ tools: [], mcpServers: [], allBuiltIn: false }); + }); + + it("should return empty arrays for empty tools string", () => { + const result = parseWorkflowTools(""); + expect(result).toEqual({ tools: [], mcpServers: [], allBuiltIn: false }); + + const result2 = parseWorkflowTools(" "); + expect(result2).toEqual({ tools: [], mcpServers: [], allBuiltIn: false }); + }); + + it("should parse built-in tools", () => { + const result = parseWorkflowTools("bash, read, edit"); + expect(result).toEqual({ + tools: [{ toolName: "bash" }, { toolName: "read" }, { toolName: "edit" }], + mcpServers: [], + allBuiltIn: false, + }); + }); + + it("should parse built_in keyword", () => { + const result = parseWorkflowTools("built_in"); + expect(result).toEqual({ + tools: [], + mcpServers: [], + allBuiltIn: true, + }); + }); + + it("should parse built_in with other tools", () => { + const result = parseWorkflowTools("built_in, owner/package"); + expect(result).toEqual({ + tools: [{ mcpServer: "owner/package" }], + mcpServers: ["owner/package"], + allBuiltIn: true, + }); + }); + + it("should parse MCP server (all tools)", () => { + const result = parseWorkflowTools("owner/package, another/server"); + expect(result).toEqual({ + tools: [{ mcpServer: "owner/package" }, { mcpServer: "another/server" }], + mcpServers: ["owner/package", "another/server"], + allBuiltIn: false, + }); + }); + + it("should parse specific MCP tools", () => { + const result = parseWorkflowTools( + "owner/package:tool1, owner/package:tool2", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "tool2" }, + ], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + it("should parse mixed tool types", () => { + const result = parseWorkflowTools( + "anmcp/serverslug:a_tool, anmcp/serverslug:another_tool, asecond/mcpserver, bash, read, edit", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "anmcp/serverslug", toolName: "a_tool" }, + { mcpServer: "anmcp/serverslug", toolName: "another_tool" }, + { mcpServer: "asecond/mcpserver" }, + { toolName: "bash" }, + { toolName: "read" }, + { toolName: "edit" }, + ], + mcpServers: ["anmcp/serverslug", "asecond/mcpserver"], + allBuiltIn: false, + }); + }); + + it("should parse mixed tools with built_in keyword", () => { + const result = parseWorkflowTools( + "built_in, anmcp/serverslug:a_tool, asecond/mcpserver", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "anmcp/serverslug", toolName: "a_tool" }, + { mcpServer: "asecond/mcpserver" }, + ], + mcpServers: ["anmcp/serverslug", "asecond/mcpserver"], + allBuiltIn: true, + }); + }); + + it("should deduplicate MCP servers", () => { + const result = parseWorkflowTools( + "owner/package:tool1, owner/package:tool2, owner/package, other/server", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "tool2" }, + { mcpServer: "owner/package" }, + { mcpServer: "other/server" }, + ], + mcpServers: ["owner/package", "other/server"], + allBuiltIn: false, + }); + }); + + it("should handle extra whitespace", () => { + const result = parseWorkflowTools( + " owner/package:tool1 , bash , other/server ", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { toolName: "bash" }, + { mcpServer: "other/server" }, + ], + mcpServers: ["owner/package", "other/server"], + allBuiltIn: false, + }); + }); + + it("should handle any MCP server slug format", () => { + expect(() => parseWorkflowTools("invalid-slug")).not.toThrow(); + expect(() => parseWorkflowTools("invalid/slug/extra")).not.toThrow(); + expect(() => + parseWorkflowTools("owner/package:tool, invalid/slug/extra:tool"), + ).not.toThrow(); + }); + + it("should handle valid MCP server slug formats", () => { + const validSlugs = [ + "owner/package", + "owner-name/package-name", + "owner.name/package.name", + "owner_name/package_name", + "owner123/package456", + ]; + + for (const slug of validSlugs) { + expect(() => parseWorkflowTools(slug)).not.toThrow(); + expect(() => parseWorkflowTools(`${slug}:tool`)).not.toThrow(); + } + }); + + it("should handle empty tool names and empty entries", () => { + const result = parseWorkflowTools( + "owner/package:tool1, , owner/package:, bash", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "" }, + { toolName: "bash" }, + ], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); +}); diff --git a/packages/config-yaml/src/markdown/workflowFiles.ts b/packages/config-yaml/src/markdown/workflowFiles.ts index 6ed805956..e6ba9226d 100644 --- a/packages/config-yaml/src/markdown/workflowFiles.ts +++ b/packages/config-yaml/src/markdown/workflowFiles.ts @@ -21,6 +21,28 @@ const workflowFileSchema = workflowFileFrontmatterSchema.extend({ }); export type WorkflowFile = z.infer; +/** + * Parsed workflow tool reference + */ +export interface WorkflowToolReference { + /** MCP server slug (owner/package) if this is an MCP tool */ + mcpServer?: string; + /** Specific tool name - either MCP tool name or built-in tool name */ + toolName?: string; +} + +/** + * Parsed workflow tools configuration + */ +export interface ParsedWorkflowTools { + /** All tool references */ + tools: WorkflowToolReference[]; + /** Unique MCP server slugs that need to be added to config */ + mcpServers: string[]; + /** Whether all built-in tools are allowed */ + allBuiltIn: boolean; +} + /** * Parses and validates a workflow file from markdown content * Workflow files must have frontmatter with at least a name @@ -64,3 +86,64 @@ export function serializeWorkflowFile(workflowFile: WorkflowFile): string { return `---\n${yamlFrontmatter}\n---\n${prompt}`; } + +/** + * Parse workflow tools string into structured format + * + * Supports formats: + * - owner/package - all tools from MCP server + * - owner/package:tool_name - specific tool from MCP server + * - ToolName or tool_name - built-in tool + * - built_in - all built-in tools + * + * @param toolsString Comma-separated tools string + * @returns Parsed tools configuration + */ +export function parseWorkflowTools(toolsString?: string): ParsedWorkflowTools { + if (!toolsString?.trim()) { + return { tools: [], mcpServers: [], allBuiltIn: false }; + } + + const tools: WorkflowToolReference[] = []; + const mcpServerSet = new Set(); + let allBuiltIn = false; + + const toolRefs = toolsString + .split(",") + .map((t) => t.trim()) + .filter(Boolean); + + for (const toolRef of toolRefs) { + if (toolRef === "built_in") { + // Special keyword for all built-in tools + allBuiltIn = true; + } else if (toolRef.includes("/")) { + // MCP tool reference: "owner/package" or "owner/package:tool_name" + const colonIndex = toolRef.indexOf(":"); + + if (colonIndex > 0) { + // Specific tool: "owner/package:tool_name" + const mcpServer = toolRef.substring(0, colonIndex); + const toolName = toolRef.substring(colonIndex + 1); + + tools.push({ mcpServer, toolName }); + mcpServerSet.add(mcpServer); + } else { + // All tools from server: "owner/package" + const mcpServer = toolRef; + + tools.push({ mcpServer }); + mcpServerSet.add(mcpServer); + } + } else { + // Built-in tool + tools.push({ toolName: toolRef }); + } + } + + return { + tools, + mcpServers: Array.from(mcpServerSet), + allBuiltIn, + }; +} From f5ba8d4ed6dc68c0de52e3d42040373653c3aae9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 12:39:00 -0700 Subject: [PATCH 27/91] wip: workflow files cleanup --- extensions/cli/src/configEnhancer.ts | 142 +++++++----------- extensions/cli/src/services/ModelService.ts | 76 ++++------ .../cli/src/services/ToolPermissionService.ts | 8 +- .../cli/src/services/WorkflowService.test.ts | 11 -- .../cli/src/services/WorkflowService.ts | 4 - extensions/cli/src/services/types.ts | 1 - 6 files changed, 95 insertions(+), 147 deletions(-) diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index db368628f..e934277b0 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -16,7 +16,7 @@ import { SERVICE_NAMES, WorkflowServiceState } from "./services/types.js"; import { logger } from "./util/logger.js"; /** - * Enhances a configuration by injecting additional components from CLI flags and workflow + * Enhances a configuration by injecting additional components from CLI flags */ export class ConfigEnhancer { /** @@ -27,119 +27,88 @@ export class ConfigEnhancer { options: BaseCommandOptions, ): Promise { let enhancedConfig = { ...config }; - - // Apply workflow components first (highest priority) - enhancedConfig = await this.injectWorkflowRules(enhancedConfig); - enhancedConfig = await this.injectWorkflowMcpServers(enhancedConfig); + const workflowOptions = await this.addWorkflowOptions(options); // Apply rules - if (options.rule && options.rule.length > 0) { - enhancedConfig = await this.injectRules(enhancedConfig, options.rule); + if (workflowOptions.rule && workflowOptions.rule.length > 0) { + enhancedConfig = await this.injectRules( + enhancedConfig, + workflowOptions.rule, + ); } // Apply MCPs - if (options.mcp && options.mcp.length > 0) { - enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); + if (workflowOptions.mcp && workflowOptions.mcp.length > 0) { + enhancedConfig = await this.injectMcps( + enhancedConfig, + workflowOptions.mcp, + ); } // Apply models - if (options.model && options.model.length > 0) { - enhancedConfig = await this.injectModels(enhancedConfig, options.model); + if (workflowOptions.model && workflowOptions.model.length > 0) { + enhancedConfig = await this.injectModels( + enhancedConfig, + workflowOptions.model, + ); } // Apply prompts - if (options.prompt && options.prompt.length > 0) { - enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); + if (workflowOptions.prompt && workflowOptions.prompt.length > 0) { + enhancedConfig = await this.injectPrompts( + enhancedConfig, + workflowOptions.prompt, + ); } return enhancedConfig; } /** - * Inject workflow rules if a workflow is active + * Add workflow rules and MCPs to options if workflow is active */ - private async injectWorkflowRules( - config: AssistantUnrolled, - ): Promise { + private async addWorkflowOptions( + options: BaseCommandOptions, + ): Promise { try { const workflowState = await serviceContainer.get( SERVICE_NAMES.WORKFLOW, ); - if (!workflowState.isActive || !workflowState.workflowFile?.rules) { - return config; + if (!workflowState.workflowFile) { + return options; } - const workflowRules = workflowState.workflowFile.rules; - const processedContent = await processRule(workflowRules); - const workflowSlug = workflowState.workflow; + const enhancedOptions = { ...options }; - const workflowRule: Rule = { - name: `workflow:${workflowSlug}`, - rule: processedContent, - }; + // Add workflow rules if present + if (workflowState.workflowFile.rules) { + const existingRules = enhancedOptions.rule || []; + enhancedOptions.rule = [ + workflowState.workflowFile.rules, + ...existingRules, + ]; + logger.debug(`Added workflow rules from ${workflowState.workflow}`); + } - const modifiedConfig = { ...config }; - const existingRules = modifiedConfig.rules || []; - modifiedConfig.rules = [workflowRule, ...existingRules]; + // Add workflow MCP servers if present + if (workflowState.workflowFile.tools) { + const parsedTools = parseWorkflowTools( + workflowState.workflowFile.tools, + ); + if (parsedTools.mcpServers.length > 0) { + const existingMcps = enhancedOptions.mcp || []; + enhancedOptions.mcp = [...parsedTools.mcpServers, ...existingMcps]; + logger.debug( + `Added ${parsedTools.mcpServers.length} workflow MCP servers`, + ); + } + } - logger.debug(`Injected workflow rules from ${workflowSlug}`); - return modifiedConfig; + return enhancedOptions; } catch (error: any) { logger.debug(`Workflow service not available: ${error.message}`); - return config; - } - } - - /** - * Inject workflow MCP servers if a workflow has tools - */ - private async injectWorkflowMcpServers( - config: AssistantUnrolled, - ): Promise { - try { - const workflowState = await serviceContainer.get( - SERVICE_NAMES.WORKFLOW, - ); - - if (!workflowState.isActive || !workflowState.workflowFile?.tools) { - return config; - } - - const parsedTools = parseWorkflowTools(workflowState.workflowFile.tools); - if (parsedTools.mcpServers.length === 0) { - return config; - } - - const processedMcps = await loadPackagesFromHub( - parsedTools.mcpServers, - mcpProcessor, - ); - const modifiedConfig = { ...config }; - const existingMcpServers = (modifiedConfig as any).mcpServers || []; - - // Deduplicate MCP servers by checking if they already exist - const existingServerNames = new Set( - existingMcpServers.map((server: any) => server.name || server.slug), - ); - - const newMcpServers = processedMcps.filter((server: any) => { - const serverName = server.name || server.slug; - return !existingServerNames.has(serverName); - }); - - if (newMcpServers.length > 0) { - (modifiedConfig as any).mcpServers = [ - ...newMcpServers, - ...existingMcpServers, - ]; - logger.debug(`Injected ${newMcpServers.length} workflow MCP servers`); - } - - return modifiedConfig; - } catch (error: any) { - logger.debug(`Failed to inject workflow MCP servers: ${error.message}`); - return config; + return options; } } @@ -244,3 +213,8 @@ export class ConfigEnhancer { return config; } } + +/** + * Global config enhancer instance + */ +export const configEnhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 30d6a022f..36dad2559 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -55,16 +55,26 @@ export class ModelService this.assistant = assistant; this.authConfig = authConfig; - - this.availableModels = await this.filterAvailableModels(assistant); + this.availableModels = (assistant.models?.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; const workflowModel = await this.getWorkflowModelName(); if (workflowModel) { logger.debug("Workflow specifies model", { workflowModel }); - const selectedModel = this.availableModels[0]; - if (!selectedModel) { - throw new Error("No workflow model available after filtering"); - } + + // Check if workflow model exists in available models + const workflowModelConfig = this.availableModels.find( + (model) => (model as any).name === workflowModel, + ); + + const selectedModel = + workflowModelConfig || + ({ + provider: "openai", + name: workflowModel, + } as ModelConfig); const llmApi = createLlmApi(selectedModel, authConfig); if (!llmApi) { @@ -121,8 +131,8 @@ export class ModelService }; } } else { - const modifiedAssistant = { ...assistant, models: this.availableModels }; - const [llmApi, model] = getLlmApi(modifiedAssistant, authConfig); + // Use default model selection + const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, model, @@ -207,7 +217,19 @@ export class ModelService name: string; index: number; }> { - return this.availableModels.map((model, index) => ({ + // Get assistant from state to ensure we have the latest data + const { assistant } = this.getState(); + if (!assistant || !assistant.models) { + return []; + } + + // Filter for chat models + const chatModels = (assistant.models.filter( + (model) => + model && (model.roles?.includes("chat") || model.roles === undefined), + ) || []) as ModelConfig[]; + + return chatModels.map((model, index) => ({ provider: model.provider, name: (model as any).name || (model as any).model || "unnamed", index, @@ -353,43 +375,9 @@ export class ModelService const workflowState = await serviceContainer.get( SERVICE_NAMES.WORKFLOW, ); - return workflowState.isActive - ? workflowState.workflowFile?.model - : undefined; + return workflowState.workflowFile?.model; } catch (error) { return undefined; } } - - /** - * Filter available models based on workflow constraints - */ - private async filterAvailableModels( - assistant: AssistantUnrolled, - ): Promise { - const baseModels = (assistant.models?.filter( - (model) => - model && (model.roles?.includes("chat") || model.roles === undefined), - ) || []) as ModelConfig[]; - - const workflowModel = await this.getWorkflowModelName(); - if (workflowModel) { - const workflowModelConfig = baseModels.find( - (model) => (model as any).name === workflowModel, - ); - - if (workflowModelConfig) { - return [workflowModelConfig]; - } else { - const workflowModelConfig: ModelConfig = { - provider: "openai", - name: workflowModel, - } as any; - - return [workflowModelConfig]; - } - } - - return baseModels; - } } diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index e5ae0e555..4b998bf24 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -18,9 +18,9 @@ export interface ToolPermissionServiceState { permissions: ToolPermissions; currentMode: PermissionMode; isHeadless: boolean; - modePolicyCount?: number; + modePolicyCount?: number; // Track how many policies are from mode vs other sources workflowPolicyCount?: number; - originalPolicies?: ToolPermissions; + originalPolicies?: ToolPermissions; // Store original policies when switching modes } /** @@ -45,7 +45,7 @@ export class ToolPermissionService extends BaseService { expect(state).toEqual({ workflowFile: null, workflow: null, - isActive: false, }); }); @@ -47,7 +46,6 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, workflow: null, - isActive: false, }); }); @@ -57,7 +55,6 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, workflow: null, - isActive: false, }); // Should not call loadPackageFromHub with invalid slug @@ -70,7 +67,6 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, workflow: null, - isActive: false, }); expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); @@ -93,7 +89,6 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: mockWorkflowFile, workflow: "owner/package", - isActive: true, }); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( @@ -110,7 +105,6 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, workflow: null, - isActive: false, }); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( @@ -132,7 +126,6 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: mockWorkflowFile, workflow: "owner/minimal", - isActive: true, }); }); }); @@ -156,7 +149,6 @@ describe("WorkflowService", () => { const state = service.getState(); expect(state.workflowFile?.name).toBe("Test Workflow"); expect(state.workflow).toBe("owner/package"); - expect(state.isActive).toBe(true); expect(state.workflowFile?.model).toBe("gpt-4"); expect(state.workflowFile?.tools).toBe("bash,read,write"); expect(state.workflowFile?.rules).toBe("Be helpful"); @@ -173,7 +165,6 @@ describe("WorkflowService", () => { const state = service.getState(); expect(state.workflowFile).toBeNull(); expect(state.workflow).toBeNull(); - expect(state.isActive).toBe(false); }); }); @@ -192,7 +183,6 @@ describe("WorkflowService", () => { expect(state.workflowFile?.tools).toBeUndefined(); expect(state.workflowFile?.rules).toBeUndefined(); expect(state.workflowFile?.prompt).toBe("Simple prompt"); - expect(state.isActive).toBe(true); }); it("should handle workflow with empty prompt", async () => { @@ -208,7 +198,6 @@ describe("WorkflowService", () => { const state = service.getState(); expect(state.workflowFile?.model).toBe("gpt-3.5-turbo"); expect(state.workflowFile?.prompt).toBe(""); - expect(state.isActive).toBe(true); }); }); }); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts index b9b7c68fb..51c53e782 100644 --- a/extensions/cli/src/services/WorkflowService.ts +++ b/extensions/cli/src/services/WorkflowService.ts @@ -27,7 +27,6 @@ export class WorkflowService extends BaseService { super("WorkflowService", { workflowFile: null, workflow: null, - isActive: false, }); } @@ -44,7 +43,6 @@ export class WorkflowService extends BaseService { return { workflowFile: null, workflow: null, - isActive: false, }; } @@ -64,14 +62,12 @@ export class WorkflowService extends BaseService { return { workflowFile, workflow, - isActive: true, }; } catch (error: any) { logger.error("Failed to initialize WorkflowService:", error); return { workflowFile: null, workflow: null, - isActive: false, }; } } diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index be3f12064..bbd7eb093 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -121,7 +121,6 @@ export interface StorageSyncServiceState { export interface WorkflowServiceState { workflowFile: any | null; workflow: string | null; - isActive: boolean; } export type { ChatHistoryState } from "./ChatHistoryService.js"; From 9e15bc0086f39fe9c8715ec73a08e62b64a6e6be Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 12:47:46 -0700 Subject: [PATCH 28/91] wip: workflow files cleanup --- extensions/cli/src/services/ModelService.ts | 69 +++++++++---------- .../cli/src/services/ToolPermissionService.ts | 60 ++++------------ .../src/services/workflow-integration.test.ts | 5 +- 3 files changed, 49 insertions(+), 85 deletions(-) diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 36dad2559..ac71f694f 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -60,33 +60,42 @@ export class ModelService model && (model.roles?.includes("chat") || model.roles === undefined), ) || []) as ModelConfig[]; - const workflowModel = await this.getWorkflowModelName(); - if (workflowModel) { - logger.debug("Workflow specifies model", { workflowModel }); - - // Check if workflow model exists in available models - const workflowModelConfig = this.availableModels.find( - (model) => (model as any).name === workflowModel, + // Check for workflow model + try { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, ); + const workflowModel = workflowState.workflowFile?.model; - const selectedModel = - workflowModelConfig || - ({ - provider: "openai", - name: workflowModel, - } as ModelConfig); + if (workflowModel) { + logger.debug("Workflow specifies model", { workflowModel }); - const llmApi = createLlmApi(selectedModel, authConfig); - if (!llmApi) { - throw new Error("Failed to initialize LLM with workflow model"); + // Check if workflow model exists in available models + const workflowModelConfig = this.availableModels.find( + (model) => (model as any).name === workflowModel, + ); + + const selectedModel = + workflowModelConfig || + ({ + provider: "openai", + name: workflowModel, + } as ModelConfig); + + const llmApi = createLlmApi(selectedModel, authConfig); + if (!llmApi) { + throw new Error("Failed to initialize LLM with workflow model"); + } + + return { + llmApi, + model: selectedModel, + assistant, + authConfig, + }; } - - return { - llmApi, - model: selectedModel, - assistant, - authConfig, - }; + } catch (error) { + // Workflow service not available, continue with normal model selection } // Check if we have a persisted model name and use it if valid @@ -366,18 +375,4 @@ export class ModelService return nameMatches; }); } - - /** - * Get workflow model name if workflow is active - */ - private async getWorkflowModelName(): Promise { - try { - const workflowState = await serviceContainer.get( - SERVICE_NAMES.WORKFLOW, - ); - return workflowState.workflowFile?.model; - } catch (error) { - return undefined; - } - } } diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 4b998bf24..d4ade33c0 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -39,16 +39,18 @@ export class ToolPermissionService extends BaseService { + private generateWorkflowPolicies(): ToolPermissionPolicy[] { try { - const workflowState = await serviceContainer.get( + const workflowResult = serviceContainer.getSync( SERVICE_NAMES.WORKFLOW, ); - if (!workflowState.workflowFile?.tools) { + if (!workflowResult?.value?.workflowFile?.tools) { return []; } + const workflowState = workflowResult.value; + const parsedTools = parseWorkflowTools(workflowState.workflowFile.tools); const policies: ToolPermissionPolicy[] = []; @@ -77,6 +79,10 @@ export class ToolPermissionService extends BaseService 0) { + logger.debug(`Generated ${policies.length} workflow tool policies`); + } + return policies; } catch (error) { return []; @@ -153,6 +159,9 @@ export class ToolPermissionService extends BaseService { - try { - const workflowPolicies = await this.generateWorkflowPolicies(); - - if (workflowPolicies.length > 0) { - const currentState = this.getState(); - const existingPolicies = currentState.permissions.policies; - const modePolicyCount = currentState.modePolicyCount || 0; - - // Insert workflow policies after mode policies but before other policies - const nonModePolicies = existingPolicies.slice(modePolicyCount); - const modePolicies = existingPolicies.slice(0, modePolicyCount); - - const allPolicies = [ - ...modePolicies, - ...workflowPolicies, - ...nonModePolicies, - ]; - - this.setState({ - permissions: { policies: allPolicies }, - workflowPolicyCount: workflowPolicies.length, - }); - - logger.debug( - `Applied ${workflowPolicies.length} workflow tool policies`, - ); - } - } catch (error: any) { - logger.debug(`Failed to apply workflow policies: ${error.message}`); - } - } - /** * Override isReady to always return true since we initialize synchronously */ diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index ff5c46286..d169b6b1a 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -121,7 +121,6 @@ describe("Workflow Integration Tests", () => { await workflowService.initialize("owner/workflow"); const workflowState = workflowService.getState(); - expect(workflowState.isActive).toBe(true); expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); // Initialize model service - it should use the workflow model @@ -144,7 +143,7 @@ describe("Workflow Integration Tests", () => { await workflowService.initialize(); const workflowState = workflowService.getState(); - expect(workflowState.isActive).toBe(false); + expect(workflowState.workflowFile).toBeNull(); // Initialize model service - it should use regular model selection await modelService.initialize( @@ -285,7 +284,7 @@ describe("Workflow Integration Tests", () => { await workflowService.initialize("owner/workflow"); const workflowState = workflowService.getState(); - expect(workflowState.isActive).toBe(false); + expect(workflowState.workflowFile).toBeNull(); // Model service should work normally await modelService.initialize( From 494ecfddf66df49bb118160606e0767d59bacc58 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 2 Oct 2025 13:14:14 -0700 Subject: [PATCH 29/91] improv: make prompts and rules directories interchangeable --- core/config/markdown/loadMarkdownRules.ts | 60 ++++++++++++----------- core/promptFiles/getPromptFiles.ts | 12 +++-- 2 files changed, 41 insertions(+), 31 deletions(-) diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index 4a2cd4051..f890ef80a 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -8,7 +8,7 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"]; /** - * Loads rules from markdown files in the .continue/rules directory + * Loads rules from markdown files in the .continue/rules and .continue/prompts directories * and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root */ export async function loadMarkdownRules(ide: IDE): Promise<{ @@ -53,37 +53,41 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ } } - try { - // Get all .md files from .continue/rules - const markdownFiles = await getAllDotContinueDefinitionFiles( - ide, - { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, - "rules", - ); + // Load markdown files from both .continue/rules and .continue/prompts + const dirsToCheck = ["rules", "prompts"]; - // Filter to just .md files - const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); + for (const dirName of dirsToCheck) { + try { + const markdownFiles = await getAllDotContinueDefinitionFiles( + ide, + { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, + dirName, + ); - // Process each markdown file - for (const file of mdFiles) { - try { - const rule = markdownToRule(file.content, { - uriType: "file", - fileUri: file.path, - }); - rules.push({ ...rule, source: "rules-block", sourceFile: file.path }); - } catch (e) { - errors.push({ - fatal: false, - message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, - }); + // Filter to just .md files + const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md")); + + // Process each markdown file + for (const file of mdFiles) { + try { + const rule = markdownToRule(file.content, { + uriType: "file", + fileUri: file.path, + }); + rules.push({ ...rule, source: "rules-block", sourceFile: file.path }); + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`, + }); + } } + } catch (e) { + errors.push({ + fatal: false, + message: `Error loading markdown rule files from ${dirName}: ${e instanceof Error ? e.message : e}`, + }); } - } catch (e) { - errors.push({ - fatal: false, - message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`, - }); } return { rules, errors }; diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts index 59c0151d4..c1111d77a 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/getPromptFiles.ts @@ -1,7 +1,8 @@ +import path from "path"; import { DEFAULT_PROMPTS_FOLDER_V1 } from "."; import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; -import { readAllGlobalPromptFiles } from "../util/paths"; +import { getContinueGlobalPath, readAllGlobalPromptFiles } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; @@ -40,7 +41,7 @@ export async function getAllPromptFiles( const workspaceDirs = await ide.getWorkspaceDirs(); let promptFiles: { path: string; content: string }[] = []; - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2]; + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2, ".continue/rules"]; if (checkV1DefaultFolder) { dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); } @@ -56,9 +57,14 @@ export async function getAllPromptFiles( await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir))) ).flat(); - // Also read from ~/.continue/prompts + // Also read from ~/.continue/prompts and ~/.continue/rules promptFiles.push(...readAllGlobalPromptFiles()); + const globalRulesPath = readAllGlobalPromptFiles( + path.join(getContinueGlobalPath(), "rules"), + ); + promptFiles.push(...globalRulesPath); + return await Promise.all( promptFiles.map(async (file) => { const content = await ide.readFile(file.path); From c5db90e9fcfae48cfea408b1901dc4d6a97e551e Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 2 Oct 2025 13:28:55 -0700 Subject: [PATCH 30/91] improv: clean up code --- core/config/markdown/loadMarkdownRules.ts | 3 ++- core/promptFiles/getPromptFiles.ts | 17 ++++++++++------- core/promptFiles/index.ts | 5 +++++ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index f890ef80a..f815144b9 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -3,6 +3,7 @@ import { markdownToRule, } from "@continuedev/config-yaml"; import { IDE, RuleWithSource } from "../.."; +import { PROMPTS_DIR_NAME, RULES_DIR_NAME } from "../../promptFiles"; import { joinPathsToUri } from "../../util/uri"; import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; @@ -54,7 +55,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ } // Load markdown files from both .continue/rules and .continue/prompts - const dirsToCheck = ["rules", "prompts"]; + const dirsToCheck = [RULES_DIR_NAME, PROMPTS_DIR_NAME]; for (const dirName of dirsToCheck) { try { diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts index c1111d77a..6a3837e3a 100644 --- a/core/promptFiles/getPromptFiles.ts +++ b/core/promptFiles/getPromptFiles.ts @@ -1,12 +1,15 @@ import path from "path"; -import { DEFAULT_PROMPTS_FOLDER_V1 } from "."; +import { + DEFAULT_PROMPTS_FOLDER_V1, + DEFAULT_PROMPTS_FOLDER_V2, + DEFAULT_RULES_FOLDER, + RULES_DIR_NAME, +} from "."; import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; import { getContinueGlobalPath, readAllGlobalPromptFiles } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; -export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; - export async function getPromptFilesFromDir( ide: IDE, dir: string, @@ -41,7 +44,7 @@ export async function getAllPromptFiles( const workspaceDirs = await ide.getWorkspaceDirs(); let promptFiles: { path: string; content: string }[] = []; - let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2, ".continue/rules"]; + let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2, DEFAULT_RULES_FOLDER]; if (checkV1DefaultFolder) { dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1); } @@ -60,10 +63,10 @@ export async function getAllPromptFiles( // Also read from ~/.continue/prompts and ~/.continue/rules promptFiles.push(...readAllGlobalPromptFiles()); - const globalRulesPath = readAllGlobalPromptFiles( - path.join(getContinueGlobalPath(), "rules"), + const promptFilesFromRulesDirectory = readAllGlobalPromptFiles( + path.join(getContinueGlobalPath(), RULES_DIR_NAME), ); - promptFiles.push(...globalRulesPath); + promptFiles.push(...promptFilesFromRulesDirectory); return await Promise.all( promptFiles.map(async (file) => { diff --git a/core/promptFiles/index.ts b/core/promptFiles/index.ts index ee5fb6b84..58be45fe8 100644 --- a/core/promptFiles/index.ts +++ b/core/promptFiles/index.ts @@ -2,6 +2,11 @@ import { ContextProviderName } from ".."; export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts"; export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts"; +export const DEFAULT_RULES_FOLDER = ".continue/rules"; + +// Subdirectory names (without .continue/ prefix) +export const RULES_DIR_NAME = "rules"; +export const PROMPTS_DIR_NAME = "prompts"; export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [ "file", From 25b12531950b59bcc01a18ae11c6b43eacaeff80 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 2 Oct 2025 13:35:57 -0700 Subject: [PATCH 31/91] fix: formatting --- core/config/markdown/loadMarkdownRules.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index f815144b9..bdeddedaa 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -61,7 +61,11 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ try { const markdownFiles = await getAllDotContinueDefinitionFiles( ide, - { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, + { + includeGlobal: true, + includeWorkspace: true, + fileExtType: "markdown", + }, dirName, ); From 4d3bafee60f99f47ec386ab028014a38230c12fb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 14:07:59 -0700 Subject: [PATCH 32/91] fix: move workflow stuff to config service --- extensions/cli/src/configEnhancer.ts | 119 ++++++++---------- extensions/cli/src/services/ModelService.ts | 45 +------ .../src/services/workflow-integration.test.ts | 26 ++-- 3 files changed, 67 insertions(+), 123 deletions(-) diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index e934277b0..605bcea99 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -24,92 +24,73 @@ export class ConfigEnhancer { */ async enhanceConfig( config: AssistantUnrolled, - options: BaseCommandOptions, + _options: BaseCommandOptions, ): Promise { let enhancedConfig = { ...config }; - const workflowOptions = await this.addWorkflowOptions(options); - // Apply rules - if (workflowOptions.rule && workflowOptions.rule.length > 0) { - enhancedConfig = await this.injectRules( - enhancedConfig, - workflowOptions.rule, - ); - } - - // Apply MCPs - if (workflowOptions.mcp && workflowOptions.mcp.length > 0) { - enhancedConfig = await this.injectMcps( - enhancedConfig, - workflowOptions.mcp, - ); - } - - // Apply models - if (workflowOptions.model && workflowOptions.model.length > 0) { - enhancedConfig = await this.injectModels( - enhancedConfig, - workflowOptions.model, - ); - } - - // Apply prompts - if (workflowOptions.prompt && workflowOptions.prompt.length > 0) { - enhancedConfig = await this.injectPrompts( - enhancedConfig, - workflowOptions.prompt, - ); - } - - return enhancedConfig; - } - - /** - * Add workflow rules and MCPs to options if workflow is active - */ - private async addWorkflowOptions( - options: BaseCommandOptions, - ): Promise { + // Get workflow options and spread them inline + let options = { ..._options }; try { const workflowState = await serviceContainer.get( SERVICE_NAMES.WORKFLOW, ); - if (!workflowState.workflowFile) { - return options; - } + if (workflowState.workflowFile) { + // Add workflow rules if present + if (workflowState.workflowFile.rules) { + options.rule = [ + workflowState.workflowFile.rules, + ...(options.rule || []), + ]; + logger.debug(`Added workflow rules from ${workflowState.workflow}`); + } - const enhancedOptions = { ...options }; + // Add workflow MCP servers if present + if (workflowState.workflowFile.tools) { + const parsedTools = parseWorkflowTools( + workflowState.workflowFile.tools, + ); + if (parsedTools.mcpServers.length > 0) { + options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; + logger.debug( + `Added ${parsedTools.mcpServers.length} workflow MCP servers`, + ); + } + } - // Add workflow rules if present - if (workflowState.workflowFile.rules) { - const existingRules = enhancedOptions.rule || []; - enhancedOptions.rule = [ - workflowState.workflowFile.rules, - ...existingRules, - ]; - logger.debug(`Added workflow rules from ${workflowState.workflow}`); - } - - // Add workflow MCP servers if present - if (workflowState.workflowFile.tools) { - const parsedTools = parseWorkflowTools( - workflowState.workflowFile.tools, - ); - if (parsedTools.mcpServers.length > 0) { - const existingMcps = enhancedOptions.mcp || []; - enhancedOptions.mcp = [...parsedTools.mcpServers, ...existingMcps]; + // Add workflow model if present (lower priority than --model flag) + if (workflowState.workflowFile.model && !options.model?.length) { + options.model = [workflowState.workflowFile.model]; logger.debug( - `Added ${parsedTools.mcpServers.length} workflow MCP servers`, + `Added workflow model: ${workflowState.workflowFile.model}`, ); } } - - return enhancedOptions; } catch (error: any) { logger.debug(`Workflow service not available: ${error.message}`); - return options; } + + // Apply rules + if (options.rule && options.rule.length > 0) { + enhancedConfig = await this.injectRules(enhancedConfig, options.rule); + } + + // Apply MCPs + if (options.mcp && options.mcp.length > 0) { + enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); + } + + // Apply models + if (options.model && options.model.length > 0) { + enhancedConfig = await this.injectModels(enhancedConfig, options.model); + } + + // Apply prompts + if (options.prompt && options.prompt.length > 0) { + enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); + } + + return enhancedConfig; } /** diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index ac71f694f..313f2afc1 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -5,12 +5,7 @@ import { createLlmApi, getLlmApi } from "../config.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { serviceContainer } from "./ServiceContainer.js"; -import { - ModelServiceState, - SERVICE_NAMES, - WorkflowServiceState, -} from "./types.js"; +import { ModelServiceState } from "./types.js"; /** * Service for managing LLM and model state @@ -60,44 +55,6 @@ export class ModelService model && (model.roles?.includes("chat") || model.roles === undefined), ) || []) as ModelConfig[]; - // Check for workflow model - try { - const workflowState = await serviceContainer.get( - SERVICE_NAMES.WORKFLOW, - ); - const workflowModel = workflowState.workflowFile?.model; - - if (workflowModel) { - logger.debug("Workflow specifies model", { workflowModel }); - - // Check if workflow model exists in available models - const workflowModelConfig = this.availableModels.find( - (model) => (model as any).name === workflowModel, - ); - - const selectedModel = - workflowModelConfig || - ({ - provider: "openai", - name: workflowModel, - } as ModelConfig); - - const llmApi = createLlmApi(selectedModel, authConfig); - if (!llmApi) { - throw new Error("Failed to initialize LLM with workflow model"); - } - - return { - llmApi, - model: selectedModel, - assistant, - authConfig, - }; - } - } catch (error) { - // Workflow service not available, continue with normal model selection - } - // Check if we have a persisted model name and use it if valid const persistedModelName = getModelName(authConfig); if (persistedModelName) { diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index d169b6b1a..a2be67955 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -193,13 +193,14 @@ describe("Workflow Integration Tests", () => { {}, ); + // Rules should be processed normally since workflow rules are now added to options.rule expect(mockProcessRule).toHaveBeenCalledWith(mockWorkflowFile.rules); expect(enhancedConfig.rules).toHaveLength(2); - expect(enhancedConfig?.rules?.[0]).toEqual({ - name: "workflow:owner/workflow", - rule: "Processed rule content", - }); - expect(enhancedConfig?.rules?.[1]).toBe("existing rule"); + // The workflow rule is processed first, then existing rules + expect(mockProcessRule).toHaveBeenNthCalledWith( + 1, + mockWorkflowFile.rules, + ); }); it("should not inject workflow rules when workflow is inactive", async () => { @@ -254,10 +255,14 @@ describe("Workflow Integration Tests", () => { mockAuthConfig as any, ); - // Verify that available models are filtered + // Verify that available models include all original models + // (we removed the filtering logic) const availableModels = modelService.getAvailableChatModels(); - expect(availableModels).toHaveLength(1); - expect(availableModels[0].name).toBe("gpt-4-workflow"); + expect(availableModels).toHaveLength(2); // Should include both original models + expect(availableModels.map((m) => m.name)).toEqual([ + "gpt-3.5-turbo", + "gpt-4", + ]); }); it("should allow all models when no workflow is active", async () => { @@ -443,9 +448,10 @@ describe("Workflow Integration Tests", () => { {}, ); - // Should not duplicate existing MCP server - expect(enhancedConfig.mcpServers).toHaveLength(1); + // Should not deduplicate since we simplified the logic + expect(enhancedConfig.mcpServers).toHaveLength(2); expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); + expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp1" }); }); }); }); From 8c5ca73e1385e64939eed4d37cd52faa85ab1240 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 15:02:17 -0700 Subject: [PATCH 33/91] fix: cleanup workflow files --- extensions/cli/src/configEnhancer.ts | 85 +++--- .../cli/src/services/ModelService.test.ts | 8 +- extensions/cli/src/services/ModelService.ts | 49 +++- .../ModelService.workflow-priority.test.ts | 243 ++++++++++++++++++ .../services/ToolPermissionService.test.ts | 3 +- extensions/cli/src/services/index.ts | 12 +- .../src/services/workflow-integration.test.ts | 211 +++++++++++---- 7 files changed, 509 insertions(+), 102 deletions(-) create mode 100644 extensions/cli/src/services/ModelService.workflow-priority.test.ts diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 605bcea99..4aee3630c 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -28,64 +28,62 @@ export class ConfigEnhancer { ): Promise { let enhancedConfig = { ...config }; - // Get workflow options and spread them inline + // Add workflow rules/mcp servers if present let options = { ..._options }; - try { - const workflowState = await serviceContainer.get( - SERVICE_NAMES.WORKFLOW, - ); + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); - if (workflowState.workflowFile) { - // Add workflow rules if present - if (workflowState.workflowFile.rules) { - options.rule = [ - workflowState.workflowFile.rules, - ...(options.rule || []), - ]; - logger.debug(`Added workflow rules from ${workflowState.workflow}`); - } + if (workflowState.workflowFile) { + if (workflowState.workflowFile.rules) { + options.rule = [ + workflowState.workflowFile.rules, + ...(options.rule || []), + ]; + } - // Add workflow MCP servers if present - if (workflowState.workflowFile.tools) { - const parsedTools = parseWorkflowTools( - workflowState.workflowFile.tools, - ); - if (parsedTools.mcpServers.length > 0) { - options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; - logger.debug( - `Added ${parsedTools.mcpServers.length} workflow MCP servers`, - ); - } - } - - // Add workflow model if present (lower priority than --model flag) - if (workflowState.workflowFile.model && !options.model?.length) { - options.model = [workflowState.workflowFile.model]; - logger.debug( - `Added workflow model: ${workflowState.workflowFile.model}`, - ); + if (workflowState.workflowFile.tools) { + const parsedTools = parseWorkflowTools( + workflowState.workflowFile.tools, + ); + if (parsedTools.mcpServers.length > 0) { + options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; } } - } catch (error: any) { - logger.debug(`Workflow service not available: ${error.message}`); + + // Add workflow model if present (lower priority than --model flag) + if (workflowState.workflowFile.model && !options.model?.length) { + options.model = [workflowState.workflowFile.model]; + logger.debug( + `Added workflow model: ${workflowState.workflowFile.model}`, + ); + } + + // Add workflow prompt as prefix + if (workflowState.workflowFile.prompt) { + options.prompt = [ + workflowState.workflowFile.prompt, + ...(options.prompt || []), + ]; + logger.debug( + `Added workflow prompt as prefix: ${workflowState.workflowFile.prompt.substring(0, 100)}...`, + ); + } } - // Apply rules + // Inject resolved items into config if (options.rule && options.rule.length > 0) { enhancedConfig = await this.injectRules(enhancedConfig, options.rule); } - // Apply MCPs if (options.mcp && options.mcp.length > 0) { enhancedConfig = await this.injectMcps(enhancedConfig, options.mcp); } - // Apply models if (options.model && options.model.length > 0) { enhancedConfig = await this.injectModels(enhancedConfig, options.model); } - // Apply prompts if (options.prompt && options.prompt.length > 0) { enhancedConfig = await this.injectPrompts(enhancedConfig, options.prompt); } @@ -183,14 +181,17 @@ export class ConfigEnhancer { /** * Inject prompts into the configuration + * Note: Prompts are processed at runtime via processAndCombinePrompts(), + * not injected into the config. This method exists for consistency with + * other injection methods but doesn't modify the config. */ private async injectPrompts( config: AssistantUnrolled, prompts: string[], ): Promise { - // For prompts, we'll need a different approach since they become slash commands - // This is a placeholder implementation - logger.debug("Prompt injection not yet implemented", { prompts }); + // Prompts are handled at runtime by processAndCombinePrompts in chat.ts + // They don't need to be injected into the configuration + logger.debug("Prompts will be processed at runtime", { prompts }); return config; } } diff --git a/extensions/cli/src/services/ModelService.test.ts b/extensions/cli/src/services/ModelService.test.ts index 9dff62d2f..b52414558 100644 --- a/extensions/cli/src/services/ModelService.test.ts +++ b/extensions/cli/src/services/ModelService.test.ts @@ -1,12 +1,12 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { describe, expect, beforeEach, vi, test } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock dependencies before imports vi.mock("../config.js"); vi.mock("../auth/workos.js"); -import { AuthConfig } from "../auth/workos.js"; import * as workos from "../auth/workos.js"; +import { AuthConfig } from "../auth/workos.js"; import * as config from "../config.js"; import { ModelService } from "./ModelService.js"; @@ -357,8 +357,8 @@ describe("ModelService", () => { }); describe("getDependencies()", () => { - test("should declare auth and config dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "config"]); + test("should declare auth, config, and workflow dependencies", () => { + expect(service.getDependencies()).toEqual(["auth", "config", "workflow"]); }); }); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 313f2afc1..594a8ec37 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -32,7 +32,7 @@ export class ModelService * Declare dependencies on other services */ getDependencies(): string[] { - return ["auth", "config"]; + return ["auth", "config", "workflow"]; } /** @@ -41,6 +41,10 @@ export class ModelService async doInitialize( assistant: AssistantUnrolled, authConfig: AuthConfig, + workflowServiceState?: { + workflowFile: any | null; + workflow: string | null; + }, ): Promise { logger.debug("ModelService.doInitialize called", { hasAssistant: !!assistant, @@ -55,16 +59,42 @@ export class ModelService model && (model.roles?.includes("chat") || model.roles === undefined), ) || []) as ModelConfig[]; - // Check if we have a persisted model name and use it if valid - const persistedModelName = getModelName(authConfig); - if (persistedModelName) { + // Check if workflow has a model specified (highest priority) + let preferredModelName: string | null = null; + let modelSource = "default"; + + if (workflowServiceState?.workflowFile?.model) { + preferredModelName = workflowServiceState.workflowFile.model; + modelSource = "workflow"; + logger.debug("Found workflow model preference", { + workflowModel: preferredModelName, + workflowName: workflowServiceState.workflowFile.name, + }); + } else { + // Fall back to persisted model name if no workflow model + preferredModelName = getModelName(authConfig); + if (preferredModelName) { + modelSource = "persisted"; + } + } + + // Try to use the preferred model (workflow or persisted) + if (preferredModelName) { // During initialization, we need to check against availableModels directly const modelIndex = this.availableModels.findIndex((model) => { const name = (model as any).name || (model as any).model; - return name === persistedModelName; + return name === preferredModelName; }); if (modelIndex === -1) { - // Model name not found, use default model selection + // Preferred model not found, use default model selection + logger.debug( + `Preferred model "${preferredModelName}" from ${modelSource} not found, using default model`, + { + preferredModelName, + modelSource, + availableModels: this.availableModels.length, + }, + ); const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, @@ -73,20 +103,21 @@ export class ModelService authConfig, }; } else { - // Use the persisted model - but we need to handle initialization specially + // Use the preferred model - but we need to handle initialization specially // During init, currentState isn't set yet, so switchModel would fail // Instead, we'll manually switch here const selectedModel = this.availableModels[modelIndex]; - logger.debug("Using persisted model during initialization", { + logger.debug(`Using ${modelSource} model during initialization`, { modelIndex, provider: selectedModel.provider, name: (selectedModel as any).name || "unnamed", + modelSource, }); const llmApi = createLlmApi(selectedModel, authConfig); if (!llmApi) { - throw new Error("Failed to initialize LLM with persisted model"); + throw new Error(`Failed to initialize LLM with ${modelSource} model`); } return { diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts new file mode 100644 index 000000000..8074c1672 --- /dev/null +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -0,0 +1,243 @@ +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { AuthConfig } from "../auth/workos.js"; +import * as config from "../config.js"; +import { ModelService } from "./ModelService.js"; +import { WorkflowServiceState } from "./types.js"; + +// Mock the dependencies +vi.mock("../auth/workos.js", () => ({ + getModelName: vi.fn(() => null), +})); + +vi.mock("../config.js", () => ({ + createLlmApi: vi.fn(() => ({ provider: "test" })), + getLlmApi: vi.fn(() => [ + { provider: "test" }, + { provider: "test", name: "default-model" }, + ]), +})); + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + error: vi.fn(), + }, +})); + +describe("ModelService workflow model prioritization", () => { + let modelService: ModelService; + let mockAssistant: AssistantUnrolled; + let mockAuthConfig: AuthConfig; + let mockModels: ModelConfig[]; + + beforeEach(() => { + modelService = new ModelService(); + + mockModels = [ + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + { provider: "openai", name: "gpt-4" } as ModelConfig, + { provider: "anthropic", name: "claude-3-haiku" } as ModelConfig, + ]; + + mockAssistant = { + models: mockModels, + } as AssistantUnrolled; + + mockAuthConfig = {} as AuthConfig; + + // Reset mocks + vi.clearAllMocks(); + }); + + it("should prioritize workflow model over default when workflow file has model specified", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + model: "gpt-4", + prompt: "Test workflow", + }, + workflow: "test/workflow", + }; + + // Mock createLlmApi to return different models based on the selected model + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + ); + + // Should have called createLlmApi with the workflow-specified model + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "gpt-4" }), + mockAuthConfig, + ); + }); + + it("should fall back to persisted model when no workflow model is specified", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + prompt: "Test workflow", + // No model specified + }, + workflow: "test/workflow", + }; + + // Mock getModelName to return a persisted model + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue("claude-3-sonnet"); + + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "claude-3-sonnet" }), + mockAuthConfig, + ); + }); + + it("should fall back to default model when workflow model is not available", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + model: "non-existent-model", // Model not in available models + prompt: "Test workflow", + }, + workflow: "test/workflow", + }; + + const getLlmApiMock = vi.mocked(config.getLlmApi); + getLlmApiMock.mockReturnValue([ + { provider: "default" } as any, + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + ]); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + // Should have fallen back to getLlmApi + expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should use default model when no workflow file exists", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: null, + workflow: null, + }; + + // Make sure getModelName returns null (no persisted model) + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue(null); + + const getLlmApiMock = vi.mocked(config.getLlmApi); + getLlmApiMock.mockReturnValue([ + { provider: "default" } as any, + { provider: "anthropic", name: "claude-3-sonnet" } as ModelConfig, + ]); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + expect(result.model).toEqual( + expect.objectContaining({ + name: "claude-3-sonnet", + provider: "anthropic", + }), + ); + + expect(getLlmApiMock).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + }); + + it("should prioritize workflow model over persisted model", async () => { + const workflowServiceState: WorkflowServiceState = { + workflowFile: { + name: "test-workflow", + model: "gpt-4", // Workflow specifies gpt-4 + prompt: "Test workflow", + }, + workflow: "test/workflow", + }; + + // Mock getModelName to return a different persisted model + const { getModelName } = await import("../auth/workos.js"); + vi.mocked(getModelName).mockReturnValue("claude-3-haiku"); + + const createLlmApiMock = vi.mocked(config.createLlmApi); + createLlmApiMock.mockImplementation( + (model: ModelConfig) => + ({ + provider: model.provider, + name: (model as any).name, + }) as any, + ); + + const result = await modelService.doInitialize( + mockAssistant, + mockAuthConfig, + workflowServiceState, + ); + + // Should use workflow model (gpt-4), not persisted model (claude-3-haiku) + expect(result.model).toEqual( + expect.objectContaining({ + name: "gpt-4", + provider: "openai", + }), + ); + + expect(createLlmApiMock).toHaveBeenCalledWith( + expect.objectContaining({ name: "gpt-4" }), + mockAuthConfig, + ); + }); +}); diff --git a/extensions/cli/src/services/ToolPermissionService.test.ts b/extensions/cli/src/services/ToolPermissionService.test.ts index 2d62ba2cf..b11e506b2 100644 --- a/extensions/cli/src/services/ToolPermissionService.test.ts +++ b/extensions/cli/src/services/ToolPermissionService.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test, beforeEach, vi } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; // Mock modules vi.mock("../permissions/permissionsYamlLoader.js"); @@ -30,6 +30,7 @@ describe("ToolPermissionService", () => { currentMode: "normal", isHeadless: false, modePolicyCount: 0, + workflowPolicyCount: 0, }); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index f2d4c0c94..f75fc1e21 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -21,6 +21,7 @@ import { SERVICE_NAMES, ServiceInitOptions, ServiceInitResult, + WorkflowServiceState, } from "./types.js"; import { UpdateService } from "./UpdateService.js"; import { WorkflowService } from "./WorkflowService.js"; @@ -214,18 +215,23 @@ export async function initializeServices( serviceContainer.register( SERVICE_NAMES.MODEL, async () => { - const [configState, authState] = await Promise.all([ + const [configState, authState, workflowState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.CONFIG), serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.WORKFLOW), ]); if (!configState.config) { throw new Error("Config not available"); } - return modelService.initialize(configState.config, authState.authConfig); + return modelService.initialize( + configState.config, + authState.authConfig, + workflowState, + ); }, - [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth + [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH, SERVICE_NAMES.WORKFLOW], // Depends on config, auth, and workflow ); serviceContainer.register( diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index a2be67955..3d226e621 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -1,6 +1,6 @@ import { vi } from "vitest"; -import { ConfigEnhancer } from "src/configEnhancer.js"; +import { ConfigEnhancer } from "../configEnhancer.js"; import { ModelService } from "./ModelService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { ToolPermissionService } from "./ToolPermissionService.js"; @@ -46,6 +46,7 @@ describe("Workflow Integration Tests", () => { let mockProcessRule: any; let mockCreateLlmApi: any; let mockGetLlmApi: any; + let mockModelProcessor: any; const mockWorkflowFile = { name: "Test Workflow", @@ -85,6 +86,7 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub = hubLoaderModule.loadPackageFromHub as any; mockLoadPackagesFromHub = hubLoaderModule.loadPackagesFromHub as any; mockProcessRule = hubLoaderModule.processRule as any; + mockModelProcessor = hubLoaderModule.modelProcessor; mockCreateLlmApi = configModule.createLlmApi as any; mockGetLlmApi = configModule.getLlmApi as any; @@ -107,6 +109,10 @@ describe("Workflow Integration Tests", () => { // Setup default mocks mockProcessRule.mockResolvedValue("Processed rule content"); mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); + mockLoadPackageFromHub.mockResolvedValue({ + name: "test-model", + provider: "openai", + }); mockCreateLlmApi.mockReturnValue({ mock: "llmApi" }); mockGetLlmApi.mockReturnValue([ { mock: "llmApi" }, @@ -114,8 +120,8 @@ describe("Workflow Integration Tests", () => { ]); }); - describe("WorkflowService affects ModelService", () => { - it("should use workflow model when workflow is active", async () => { + describe("Workflow models are injected via ConfigEnhancer", () => { + it("should add workflow model to options when workflow is active", async () => { // Setup workflow service with active workflow mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); @@ -123,57 +129,65 @@ describe("Workflow Integration Tests", () => { const workflowState = workflowService.getState(); expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); - // Initialize model service - it should use the workflow model - await modelService.initialize( - mockAssistant as any, - mockAuthConfig as any, + // Test that ConfigEnhancer adds the workflow model to options + const baseConfig = { models: [] }; + const baseOptions = {}; // No --model flag + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, ); - expect(mockCreateLlmApi).toHaveBeenCalledWith( - expect.objectContaining({ - name: "gpt-4-workflow", - provider: "openai", - }), - mockAuthConfig, + // Should have loaded the workflow model via injectModels + expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( + ["gpt-4-workflow"], + expect.anything(), ); }); - it("should use regular models when no workflow is active", async () => { + it("should not add workflow model when no workflow is active", async () => { // Initialize workflow service without workflow await workflowService.initialize(); const workflowState = workflowService.getState(); expect(workflowState.workflowFile).toBeNull(); - // Initialize model service - it should use regular model selection - await modelService.initialize( - mockAssistant as any, - mockAuthConfig as any, + // Test that ConfigEnhancer doesn't add any workflow models + const baseConfig = { models: [] }; + const baseOptions = {}; + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, ); - expect(mockGetLlmApi).toHaveBeenCalledWith(mockAssistant, mockAuthConfig); + // Should not have enhanced with any models + expect(enhancedConfig.models).toEqual([]); }); - it("should handle workflow model that exists in assistant models", async () => { - const workflowWithExistingModel = { - ...mockWorkflowFile, - model: "gpt-4", // This exists in mockAssistant.models - }; - - mockLoadPackageFromHub.mockResolvedValue(workflowWithExistingModel); + it("should respect --model flag priority over workflow model", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); - await modelService.initialize( - mockAssistant as any, - mockAuthConfig as any, + // Test that --model flag takes precedence + const baseConfig = { models: [] }; + const baseOptions = { model: ["user-specified-model"] }; // User specified --model + + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, ); - expect(mockCreateLlmApi).toHaveBeenCalledWith( - expect.objectContaining({ - name: "gpt-4", - provider: "openai", - }), - mockAuthConfig, + // Should process the user model, not the workflow model + expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( + ["user-specified-model"], + expect.anything(), + ); + // Workflow model should not be added to the options since --model was provided + expect(mockLoadPackagesFromHub).not.toHaveBeenCalledWith( + ["gpt-4-workflow"], + expect.anything(), ); }); }); @@ -319,11 +333,13 @@ describe("Workflow Integration Tests", () => { expect(enhancedConfig.rules?.[0]).toBe("existing rule"); }); - it("should handle missing service container gracefully", async () => { - // Mock service container to throw error - vi.spyOn(serviceContainer, "get").mockRejectedValue( - new Error("Service not ready"), - ); + // Removed test for missing service container since workflow service + // should always be initialized before ConfigEnhancer is called + + it("should inject workflow prompt when workflow is active", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); const baseConfig = { rules: ["existing rule"], @@ -334,9 +350,118 @@ describe("Workflow Integration Tests", () => { {}, ); - // Should return config unchanged - expect(enhancedConfig.rules).toHaveLength(1); - expect(enhancedConfig.rules?.[0]).toBe("existing rule"); + // Prompts should be processed at runtime, not injected into config + // The workflow prompt is added to options.prompt and will be processed + // by processAndCombinePrompts() in chat.ts + expect(enhancedConfig.rules).toHaveLength(2); + }); + + it("should add workflow prompt as prefix to existing prompts", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + // Test that the workflow prompt gets added to options.prompt as prefix + const baseOptions = { prompt: ["existing-prompt"] }; + const modifiedOptions = { ...baseOptions }; + + // Simulate what ConfigEnhancer does internally + const workflowState = workflowService.getState(); + if (workflowState.workflowFile?.prompt) { + modifiedOptions.prompt = [ + workflowState.workflowFile.prompt, + ...(modifiedOptions.prompt || []), + ]; + } + + expect(modifiedOptions.prompt).toEqual([ + "You are a workflow assistant.", + "existing-prompt", + ]); + }); + + it("should not add workflow prompt when workflow has no prompt", async () => { + const workflowWithoutPrompt = { + ...mockWorkflowFile, + prompt: undefined, + }; + + mockLoadPackageFromHub.mockResolvedValue(workflowWithoutPrompt); + await workflowService.initialize("owner/workflow"); + + const baseOptions = { prompt: ["existing-prompt"] }; + const modifiedOptions = { ...baseOptions }; + + // Simulate what ConfigEnhancer does internally + const workflowState = workflowService.getState(); + if (workflowState.workflowFile?.prompt) { + modifiedOptions.prompt = [ + workflowState.workflowFile.prompt, + ...(modifiedOptions.prompt || []), + ]; + } + + expect(modifiedOptions.prompt).toEqual(["existing-prompt"]); + }); + }); + + describe("ConfigEnhancer prompt integration", () => { + it("should modify options to include workflow prompt as prefix", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + // Create a spy to verify the internal behavior of ConfigEnhancer + const originalGet = serviceContainer.get; + const getSpy = vi + .spyOn(serviceContainer, "get") + .mockImplementation(async (serviceName: string) => { + if (serviceName === SERVICE_NAMES.WORKFLOW) { + return workflowService.getState(); + } + return originalGet.call(serviceContainer, serviceName); + }); + + const baseOptions = { prompt: ["user-prompt"] }; + + // This should internally modify the options to include workflow prompt + await configEnhancer.enhanceConfig({} as any, baseOptions); + + // The ConfigEnhancer should have been called with workflow service + expect(getSpy).toHaveBeenCalledWith(SERVICE_NAMES.WORKFLOW); + + // Clean up + getSpy.mockRestore(); + }); + + it("should work end-to-end with workflow prompt processing", async () => { + // Setup workflow service with active workflow + mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); + await workflowService.initialize("owner/workflow"); + + const workflowState = workflowService.getState(); + expect(workflowState.workflowFile?.prompt).toBe( + "You are a workflow assistant.", + ); + + // Verify that if we manually apply the same logic as ConfigEnhancer, + // the workflow prompt gets added as prefix + const options = { prompt: ["Tell me about TypeScript"] }; + + if (workflowState.workflowFile?.prompt) { + options.prompt = [workflowState.workflowFile.prompt, ...options.prompt]; + } + + expect(options.prompt).toEqual([ + "You are a workflow assistant.", + "Tell me about TypeScript", + ]); + + // This mimics what processAndCombinePrompts would do + const combinedPrompt = options.prompt.join("\n\n"); + expect(combinedPrompt).toBe( + "You are a workflow assistant.\n\nTell me about TypeScript", + ); }); }); From 145a75238848956712c3835baac7c61510f6cd27 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 15:45:07 -0700 Subject: [PATCH 34/91] fix: tests and formatting for workflow files --- extensions/cli/src/configEnhancer.test.ts | 57 +++++++++ extensions/cli/src/configEnhancer.ts | 2 +- .../src/integration/rule-duplication.test.ts | 18 +++ .../ModelService.workflow-priority.test.ts | 1 + .../cli/src/services/ToolPermissionService.ts | 111 +++++++++--------- .../src/services/workflow-integration.test.ts | 1 + 6 files changed, 132 insertions(+), 58 deletions(-) diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts index bbee50c0b..21e084a6a 100644 --- a/extensions/cli/src/configEnhancer.test.ts +++ b/extensions/cli/src/configEnhancer.test.ts @@ -18,6 +18,24 @@ vi.mock("./hubLoader.js", () => ({ modelProcessor: {}, })); +// Mock the service container to provide empty workflow state +vi.mock("./services/ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(() => + Promise.resolve({ + workflowFile: null, + workflow: null, + }), + ), + }, +})); + +vi.mock("./services/types.js", () => ({ + SERVICE_NAMES: { + WORKFLOW: "workflow", + }, +})); + describe("ConfigEnhancer", () => { let enhancer: ConfigEnhancer; let mockConfig: any; @@ -199,4 +217,43 @@ describe("ConfigEnhancer", () => { command: "existing-mcp", }); }); + + it("should handle workflow integration gracefully when no workflow", async () => { + // The mocked service container returns null workflow state + const options: BaseCommandOptions = { + rule: ["test-rule"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // Should work normally when no workflow is active + expect(config.rules).toEqual(["test-rule"]); + }); + + it("should handle workflow integration when workflow is active", async () => { + // Mock service container to return active workflow + const { serviceContainer } = await import("./services/ServiceContainer.js"); + (serviceContainer.get as any).mockResolvedValueOnce({ + workflowFile: { + name: "Test Workflow", + prompt: "You are a test assistant", + rules: "Always be helpful", + model: "gpt-4", + tools: "bash,read", + }, + workflow: "owner/test-workflow", + }); + + const options: BaseCommandOptions = { + rule: ["user-rule"], + prompt: ["user-prompt"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // Should have both workflow and user rules + expect(config.rules).toHaveLength(2); + expect(config.rules?.[0]).toBe("Always be helpful"); // Workflow rule first + expect(config.rules?.[1]).toBe("user-rule"); // User rule second + }); }); diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 4aee3630c..2651ad1ed 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -29,7 +29,7 @@ export class ConfigEnhancer { let enhancedConfig = { ...config }; // Add workflow rules/mcp servers if present - let options = { ..._options }; + const options = { ..._options }; const workflowState = await serviceContainer.get( SERVICE_NAMES.WORKFLOW, ); diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts index e68a3eff9..51e9bcd84 100644 --- a/extensions/cli/src/integration/rule-duplication.test.ts +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -19,6 +19,24 @@ vi.mock("../hubLoader.js", () => ({ modelProcessor: {}, })); +// Mock the service container to provide empty workflow state +vi.mock("../services/ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn(() => + Promise.resolve({ + workflowFile: null, + workflow: null, + }), + ), + }, +})); + +vi.mock("../services/types.js", () => ({ + SERVICE_NAMES: { + WORKFLOW: "workflow", + }, +})); + describe("Rule duplication integration test", () => { it("should not duplicate rules when using --rule flag", async () => { const enhancer = new ConfigEnhancer(); diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts index 8074c1672..0225c144a 100644 --- a/extensions/cli/src/services/ModelService.workflow-priority.test.ts +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { AuthConfig } from "../auth/workos.js"; import * as config from "../config.js"; + import { ModelService } from "./ModelService.js"; import { WorkflowServiceState } from "./types.js"; diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index d4ade33c0..7aceef07f 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -9,11 +9,10 @@ import { } from "../permissions/types.js"; import { logger } from "../util/logger.js"; +import { BaseService } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; -import { BaseService } from "./BaseService.js"; - export interface ToolPermissionServiceState { permissions: ToolPermissions; currentMode: PermissionMode; @@ -39,54 +38,52 @@ export class ToolPermissionService extends BaseService( - SERVICE_NAMES.WORKFLOW, - ); - - if (!workflowResult?.value?.workflowFile?.tools) { - return []; - } - - const workflowState = workflowResult.value; - - const parsedTools = parseWorkflowTools(workflowState.workflowFile.tools); - const policies: ToolPermissionPolicy[] = []; - - if (parsedTools.allBuiltIn) { - policies.push({ tool: "*", permission: "allow" }); - policies.push({ tool: "mcp:*", permission: "exclude" }); - } else { - policies.push({ tool: "*", permission: "exclude" }); - } - - for (const toolRef of parsedTools.tools) { - if (toolRef.mcpServer) { - if (toolRef.toolName) { - policies.push({ - tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`, - permission: "allow", - }); - } else { - policies.push({ - tool: `mcp:${toolRef.mcpServer}:*`, - permission: "allow", - }); - } - } else if (toolRef.toolName) { - policies.push({ tool: toolRef.toolName, permission: "allow" }); - } - } - - if (policies.length > 0) { - logger.debug(`Generated ${policies.length} workflow tool policies`); - } - - return policies; - } catch (error) { - return []; + private generateWorkflowPolicies(): undefined | ToolPermissionPolicy[] { + const workflowResult = serviceContainer.getSync( + SERVICE_NAMES.WORKFLOW, + ); + if (!workflowResult?.value?.workflowFile?.tools) { + return undefined; } + + const parsedTools = parseWorkflowTools( + workflowResult.value.workflowFile.tools, + ); + if (parsedTools.tools.length === 0) { + return undefined; + } + const policies: ToolPermissionPolicy[] = []; + + if (parsedTools.allBuiltIn) { + policies.push({ tool: "*", permission: "allow" }); + policies.push({ tool: "mcp:*", permission: "exclude" }); + } else { + policies.push({ tool: "*", permission: "exclude" }); + } + + for (const toolRef of parsedTools.tools) { + if (toolRef.mcpServer) { + if (toolRef.toolName) { + policies.push({ + tool: `mcp:${toolRef.mcpServer}:${toolRef.toolName}`, + permission: "allow", + }); + } else { + policies.push({ + tool: `mcp:${toolRef.mcpServer}:*`, + permission: "allow", + }); + } + } else if (toolRef.toolName) { + policies.push({ tool: toolRef.toolName, permission: "allow" }); + } + } + + if (policies.length > 0) { + logger.debug(`Generated ${policies.length} workflow tool policies`); + } + + return policies; } /** @@ -116,7 +113,7 @@ export class ToolPermissionService extends BaseService Date: Thu, 2 Oct 2025 16:37:46 -0700 Subject: [PATCH 35/91] fix: tests and remove parsed args --- extensions/cli/src/__mocks__/args.ts | 5 - extensions/cli/src/args-mcp.test.ts | 75 ------ extensions/cli/src/args.prompt.test.ts | 84 ------- extensions/cli/src/args.test.ts | 219 +----------------- extensions/cli/src/args.ts | 147 ------------ extensions/cli/src/configEnhancer.ts | 34 +-- extensions/cli/src/hubLoader.ts | 12 +- .../src/integration/rule-duplication.test.ts | 2 +- extensions/cli/src/loadMcpFromHub.test.ts | 2 +- .../cli/src/mcp-flag.integration.test.ts | 62 +---- extensions/cli/src/onboarding.ts | 4 +- extensions/cli/src/services/ModelService.ts | 19 +- .../ModelService.workflow-priority.test.ts | 10 +- .../cli/src/services/ToolPermissionService.ts | 2 +- .../cli/src/services/WorkflowService.test.ts | 48 +++- .../cli/src/services/WorkflowService.ts | 39 +--- extensions/cli/src/services/types.ts | 10 +- .../src/services/workflow-integration.test.ts | 18 +- extensions/cli/src/systemMessage.test.ts | 6 +- extensions/cli/src/systemMessage.ts | 4 +- .../cli/src/util/promptProcessor.test.ts | 24 +- extensions/cli/src/util/promptProcessor.ts | 5 +- 22 files changed, 118 insertions(+), 713 deletions(-) delete mode 100644 extensions/cli/src/__mocks__/args.ts delete mode 100644 extensions/cli/src/args-mcp.test.ts delete mode 100644 extensions/cli/src/args.prompt.test.ts delete mode 100644 extensions/cli/src/args.ts diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts deleted file mode 100644 index f982bdd09..000000000 --- a/extensions/cli/src/__mocks__/args.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { vi } from "vitest"; - -export const processPromptOrRule = vi.fn<(spec: string) => Promise>(); - -export const processPrompt = vi.fn<(prompt: string) => Promise>(); diff --git a/extensions/cli/src/args-mcp.test.ts b/extensions/cli/src/args-mcp.test.ts deleted file mode 100644 index 95f77cc7d..000000000 --- a/extensions/cli/src/args-mcp.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { beforeEach, describe, expect, it } from "vitest"; - -import { parseArgs } from "./args.js"; - -describe("parseArgs --mcp flag", () => { - beforeEach(() => { - // Clear process.argv before each test - process.argv = ["node", "test"]; - }); - - it("should parse single MCP from --mcp flag", () => { - process.argv = ["node", "test", "--mcp", "my-org/my-mcp"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - }); - - it("should parse multiple MCPs from multiple --mcp flags", () => { - process.argv = ["node", "test", "--mcp", "org1/mcp1", "--mcp", "org2/mcp2"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["org1/mcp1", "org2/mcp2"]); - }); - - it("should handle MCP flag with other flags", () => { - process.argv = [ - "node", - "test", - "--config", - "my-config.yaml", - "--mcp", - "my-org/my-mcp", - "--org", - "test-org", - ]; - const result = parseArgs(); - expect(result.configPath).toBe("my-config.yaml"); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - expect(result.organizationSlug).toBe("test-org"); - }); - - it("should handle MCP flag with prompt", () => { - process.argv = ["node", "test", "--mcp", "my-org/my-mcp", "hello world"]; - const result = parseArgs(); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - expect(result.prompt).toBe("hello world"); - }); - - it("should ignore MCP and rule flag values when extracting prompt", () => { - process.argv = [ - "node", - "test", - "actual prompt", - "--rule", - "my-rule", - "--mcp", - "my-org/my-mcp", - ]; - const result = parseArgs(); - expect(result.prompt).toBe("actual prompt"); - expect(result.rules).toEqual(["my-rule"]); - expect(result.mcps).toEqual(["my-org/my-mcp"]); - }); - - it("should handle MCP flag without value", () => { - process.argv = ["node", "test", "--mcp"]; - const result = parseArgs(); - expect(result.mcps).toEqual([]); - }); - - it("should handle MCP flag at the end without value", () => { - process.argv = ["node", "test", "my prompt", "--mcp"]; - const result = parseArgs(); - expect(result.prompt).toBe("my prompt"); - expect(result.mcps).toEqual([]); - }); -}); diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts deleted file mode 100644 index 46b70b4db..000000000 --- a/extensions/cli/src/args.prompt.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, it, expect, beforeEach, afterAll } from "vitest"; - -import { parseArgs, processPromptOrRule } from "./args.js"; - -describe("args --prompt flag", () => { - const originalArgv = process.argv; - - beforeEach(() => { - // Reset process.argv for each test - process.argv = ["node", "script.js"]; - }); - - afterAll(() => { - // Restore original process.argv after all tests - process.argv = originalArgv; - }); - - it("should parse single prompt from --prompt flag", () => { - process.argv = ["node", "script.js", "--prompt", "my-prompt"]; - const result = parseArgs(); - expect(result.prompts).toEqual(["my-prompt"]); - }); - - it("should parse multiple prompts from multiple --prompt flags", () => { - process.argv = [ - "node", - "script.js", - "--prompt", - "prompt1", - "--prompt", - "prompt2", - ]; - const result = parseArgs(); - expect(result.prompts).toEqual(["prompt1", "prompt2"]); - }); - - it("should handle mixed flags including --prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "myconfig", - "--prompt", - "myprompt", - "--resume", - ]; - const result = parseArgs(); - expect(result.configPath).toBe("myconfig"); - expect(result.prompts).toEqual(["myprompt"]); - expect(result.resume).toBe(true); - }); - - it("should not include --prompt value in non-flag arguments", () => { - process.argv = [ - "node", - "script.js", - "--prompt", - "prompt-value", - "actual-prompt", - ]; - const result = parseArgs(); - expect(result.prompts).toEqual(["prompt-value"]); - expect(result.prompt).toBe("actual-prompt"); - }); - - it("should handle both --rule and --prompt flags", () => { - process.argv = [ - "node", - "script.js", - "--rule", - "my-rule", - "--prompt", - "my-prompt", - ]; - const result = parseArgs(); - expect(result.rules).toEqual(["my-rule"]); - expect(result.prompts).toEqual(["my-prompt"]); - }); - - it("should process direct string content", async () => { - const result = await processPromptOrRule("This is a direct prompt"); - expect(result).toBe("This is a direct prompt"); - }); -}); diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index d22333c05..5c8821d3c 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -1,222 +1,5 @@ import { vi } from "vitest"; - -import { parseArgs, processPromptOrRule } from "./args.js"; - -describe("parseArgs", () => { - const originalArgv = process.argv; - - beforeEach(() => { - // Reset process.argv before each test - process.argv = ["node", "script.js"]; - }); - - afterAll(() => { - // Restore original argv - process.argv = originalArgv; - }); - - it("should return default values when no arguments provided", () => { - const result = parseArgs(); - expect(result).toEqual({}); - }); - - it("should set resume to true when --resume flag is present", () => { - process.argv = ["node", "script.js", "--resume"]; - const result = parseArgs(); - expect(result.resume).toBe(true); - }); - - it("should set readonly to true when --readonly flag is present", () => { - process.argv = ["node", "script.js", "--readonly"]; - const result = parseArgs(); - expect(result.readonly).toBe(true); - }); - - it("should parse config path from --config flag", () => { - process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"]; - const result = parseArgs(); - expect(result.configPath).toBe("/path/to/config.yaml"); - }); - - it("should parse single rule from --rule flag", () => { - process.argv = ["node", "script.js", "--rule", "my-rule"]; - const result = parseArgs(); - expect(result.rules).toEqual(["my-rule"]); - }); - - it("should parse multiple rules from multiple --rule flags", () => { - process.argv = ["node", "script.js", "--rule", "rule1", "--rule", "rule2"]; - const result = parseArgs(); - expect(result.rules).toEqual(["rule1", "rule2"]); - }); - - it("should parse prompt from last non-flag argument", () => { - process.argv = ["node", "script.js", "Hello world"]; - const result = parseArgs(); - expect(result.prompt).toBe("Hello world"); - }); - - it("should handle multiple flags together", () => { - process.argv = ["node", "script.js", "--print", "--readonly", "--resume"]; - const result = parseArgs(); - expect(result).toEqual({ - readonly: true, - resume: true, - }); - }); - - it("should handle config flag with other flags", () => { - process.argv = ["node", "script.js", "--config", "config.yaml", "--print"]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "config.yaml", - }); - }); - - it("should handle rule flag with other flags", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "--print"]; - const result = parseArgs(); - expect(result).toEqual({ - rules: ["my-rule"], - }); - }); - - it("should handle prompt with flags", () => { - process.argv = ["node", "script.js", "--print", "What is the weather?"]; - const result = parseArgs(); - expect(result).toEqual({ - prompt: "What is the weather?", - }); - }); - - it("should handle config flag with prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "config.yaml", - "Test prompt", - ]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "config.yaml", - prompt: "Test prompt", - }); - }); - - it("should handle rule flag with prompt", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "Test prompt"]; - const result = parseArgs(); - expect(result).toEqual({ - rules: ["my-rule"], - prompt: "Test prompt", - }); - }); - - it("should ignore config and rule flag values when extracting prompt", () => { - process.argv = [ - "node", - "script.js", - "--config", - "config.yaml", - "--rule", - "my-rule", - "actual-prompt", - ]; - const result = parseArgs(); - expect(result.prompt).toBe("actual-prompt"); - expect(result.configPath).toBe("config.yaml"); - expect(result.rules).toEqual(["my-rule"]); - }); - - it("should handle multiple non-flag arguments and use the last one as prompt", () => { - process.argv = ["node", "script.js", "first", "second", "third"]; - const result = parseArgs(); - expect(result.prompt).toBe("third"); - }); - - it("should handle complex argument combinations", () => { - process.argv = [ - "node", - "script.js", - "--print", - "--config", - "my-config.yaml", - "--rule", - "rule1", - "--rule", - "rule2", - "--readonly", - "--resume", - "Complex prompt with spaces", - ]; - const result = parseArgs(); - expect(result).toEqual({ - configPath: "my-config.yaml", - rules: ["rule1", "rule2"], - readonly: true, - resume: true, - prompt: "Complex prompt with spaces", - }); - }); - - it("should handle config flag without value", () => { - process.argv = ["node", "script.js", "--config"]; - const result = parseArgs(); - expect(result.configPath).toBeUndefined(); - }); - - it("should handle rule flag without value", () => { - process.argv = ["node", "script.js", "--rule"]; - const result = parseArgs(); - expect(result.rules).toEqual([]); - }); - - it("should handle config flag at the end without value", () => { - process.argv = ["node", "script.js", "--print", "--config"]; - const result = parseArgs(); - expect(result.configPath).toBeUndefined(); - }); - - it("should handle rule flag at the end without value", () => { - process.argv = ["node", "script.js", "--print", "--rule"]; - const result = parseArgs(); - expect(result.rules).toEqual([]); - }); - - it("should handle empty arguments array", () => { - process.argv = ["node", "script.js"]; - const result = parseArgs(); - expect(result).toEqual({}); - }); - - it("should handle multiple boolean flags", () => { - process.argv = ["node", "script.js", "--readonly", "--resume"]; - const result = parseArgs(); - expect(result.readonly).toBe(true); - expect(result.resume).toBe(true); - }); - - it("should handle multiple rules with complex combinations", () => { - process.argv = [ - "node", - "script.js", - "--rule", - "file.txt", - "--rule", - "owner/package", - "--rule", - "direct string rule", - ]; - const result = parseArgs(); - expect(result.rules).toEqual([ - "file.txt", - "owner/package", - "direct string rule", - ]); - }); -}); - +import { processRule as processPromptOrRule } from "./hubLoader.js"; describe("processPromptOrRule (loadRuleFromHub integration)", () => { // Mock fetch for hub tests const originalFetch = global.fetch; diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts deleted file mode 100644 index b8a452213..000000000 --- a/extensions/cli/src/args.ts +++ /dev/null @@ -1,147 +0,0 @@ -export interface CommandLineArgs { - configPath?: string; - organizationSlug?: string; // Organization slug to use for this session - prompt?: string; // Optional prompt argument - resume?: boolean; // Resume from last session - fork?: string; // Fork from an existing session ID - readonly?: boolean; // Start in plan mode (backward compatibility) - rules?: string[]; // Array of rule specifications - mcps?: string[]; // Array of MCP server slugs from the hub - models?: string[]; // Array of model slugs from the hub - prompts?: string[]; // Array of prompt slugs from the hub - format?: "json"; // Output format for headless mode -} - -// Re-export hub loader functions for backward compatibility -export { loadMcpFromHub, processRule } from "./hubLoader.js"; -// Alias processRule as processPromptOrRule for backward compatibility -export { processRule as processPromptOrRule } from "./hubLoader.js"; - -/** - * Extract values for a specific flag that can appear multiple times - */ -function extractMultipleFlags(args: string[], flagName: string): string[] { - const indices: number[] = []; - for (let i = 0; i < args.length; i++) { - if (args[i] === flagName) { - indices.push(i); - } - } - - const values: string[] = []; - for (const index of indices) { - if (index + 1 < args.length && !args[index + 1].startsWith("--")) { - values.push(args[index + 1]); - } - } - return values; -} - -/** - * Extract value for a single-value flag - */ -function extractSingleFlag( - args: string[], - flagName: string, -): string | undefined { - const index = args.indexOf(flagName); - if ( - index !== -1 && - index + 1 < args.length && - !args[index + 1].startsWith("--") - ) { - return args[index + 1]; - } - return undefined; -} - -/** - * Parse command line arguments for non-permission related flags - * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility. - * @returns Parsed command line arguments - */ -export function parseArgs(): CommandLineArgs { - const args = process.argv.slice(2); - const result: CommandLineArgs = {}; - - // Parse boolean flags - if (args.includes("--resume")) { - result.resume = true; - } - if (args.includes("--readonly")) { - result.readonly = true; - } - - // Parse fork flag - const forkValue = extractSingleFlag(args, "--fork"); - if (forkValue) { - result.fork = forkValue; - } - - // Parse single-value flags - const formatValue = extractSingleFlag(args, "--format"); - if (formatValue === "json") { - result.format = "json"; - } - - result.configPath = extractSingleFlag(args, "--config"); - - const orgValue = extractSingleFlag(args, "--org"); - if (orgValue) { - result.organizationSlug = - orgValue.toLowerCase() === "personal" ? undefined : orgValue; - } - - // Parse multi-value flags - const rules = extractMultipleFlags(args, "--rule"); - if (rules.length > 0) { - result.rules = rules; - } else if (args.includes("--rule")) { - result.rules = []; - } - - const mcps = extractMultipleFlags(args, "--mcp"); - if (mcps.length > 0) { - result.mcps = mcps; - } else if (args.includes("--mcp")) { - // Ensure we have an empty array if --mcp flag is present but has no values - result.mcps = []; - } - - const models = extractMultipleFlags(args, "--model"); - if (models.length > 0) { - result.models = models; - } else if (args.includes("--model")) { - result.models = []; - } - - const prompts = extractMultipleFlags(args, "--prompt"); - if (prompts.length > 0) { - result.prompts = prompts; - } else if (args.includes("--prompt")) { - result.prompts = []; - } - - // Extract prompt from non-flag arguments - const flagsWithValues = [ - "--config", - "--org", - "--rule", - "--mcp", - "--model", - "--prompt", - "--format", - "--fork", - ]; - const nonFlagArgs = args.filter((arg, index) => { - if (arg.startsWith("--") || arg === "-p") return false; - const prevArg = index > 0 ? args[index - 1] : ""; - return !flagsWithValues.includes(prevArg); - }); - - if (nonFlagArgs.length > 0) { - result.prompt = nonFlagArgs[nonFlagArgs.length - 1]; - } - - return result; -} diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 2651ad1ed..ed7817ae2 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -30,44 +30,34 @@ export class ConfigEnhancer { // Add workflow rules/mcp servers if present const options = { ..._options }; - const workflowState = await serviceContainer.get( + const { workflowFile } = await serviceContainer.get( SERVICE_NAMES.WORKFLOW, ); - if (workflowState.workflowFile) { - if (workflowState.workflowFile.rules) { + if (workflowFile) { + const { rules, model, tools, prompt } = workflowFile; + if (rules) { options.rule = [ - workflowState.workflowFile.rules, + ...rules.split(",").filter(Boolean), ...(options.rule || []), ]; } - if (workflowState.workflowFile.tools) { - const parsedTools = parseWorkflowTools( - workflowState.workflowFile.tools, - ); + if (tools) { + const parsedTools = parseWorkflowTools(tools); if (parsedTools.mcpServers.length > 0) { options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; } } - // Add workflow model if present (lower priority than --model flag) - if (workflowState.workflowFile.model && !options.model?.length) { - options.model = [workflowState.workflowFile.model]; - logger.debug( - `Added workflow model: ${workflowState.workflowFile.model}`, - ); + // Note that --model takes precedence over workflow model + if (model) { + options.model = [...(options.model ?? []), model]; } // Add workflow prompt as prefix - if (workflowState.workflowFile.prompt) { - options.prompt = [ - workflowState.workflowFile.prompt, - ...(options.prompt || []), - ]; - logger.debug( - `Added workflow prompt as prefix: ${workflowState.workflowFile.prompt.substring(0, 100)}...`, - ); + if (prompt) { + options.prompt = [prompt, ...(options.prompt || [])]; } } diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts index 533980541..e9850b4e8 100644 --- a/extensions/cli/src/hubLoader.ts +++ b/extensions/cli/src/hubLoader.ts @@ -1,5 +1,6 @@ import JSZip from "jszip"; +import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; import { env } from "./env.js"; import { logger } from "./util/logger.js"; @@ -11,7 +12,7 @@ const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; /** * Hub package type definitions */ -export type HubPackageType = "rule" | "mcp" | "model" | "prompt"; +export type HubPackageType = "rule" | "mcp" | "model" | "prompt" | "workflow"; /** * Hub package processor interface @@ -99,6 +100,15 @@ export const promptProcessor: HubPackageProcessor = { parseContent: (content: string) => content, }; +export const workflowProcessor: HubPackageProcessor = { + type: "workflow", + expectedFileExtensions: [".md"], + parseContent: (content: string) => parseWorkflowFile(content), + validateContent: (workflowFile: WorkflowFile) => { + return !!workflowFile.name; + }, +}; + /** * Generic hub package loader */ diff --git a/extensions/cli/src/integration/rule-duplication.test.ts b/extensions/cli/src/integration/rule-duplication.test.ts index 51e9bcd84..83143dede 100644 --- a/extensions/cli/src/integration/rule-duplication.test.ts +++ b/extensions/cli/src/integration/rule-duplication.test.ts @@ -25,7 +25,7 @@ vi.mock("../services/ServiceContainer.js", () => ({ get: vi.fn(() => Promise.resolve({ workflowFile: null, - workflow: null, + slug: null, }), ), }, diff --git a/extensions/cli/src/loadMcpFromHub.test.ts b/extensions/cli/src/loadMcpFromHub.test.ts index 92dd69cf8..cbd49a53a 100644 --- a/extensions/cli/src/loadMcpFromHub.test.ts +++ b/extensions/cli/src/loadMcpFromHub.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { loadMcpFromHub } from "./args.js"; +import { loadMcpFromHub } from "./hubLoader.js"; // Store original fetch to restore later const originalFetch = global.fetch; diff --git a/extensions/cli/src/mcp-flag.integration.test.ts b/extensions/cli/src/mcp-flag.integration.test.ts index a040c45b4..863e1ea32 100644 --- a/extensions/cli/src/mcp-flag.integration.test.ts +++ b/extensions/cli/src/mcp-flag.integration.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { parseArgs, loadMcpFromHub } from "./args.js"; +import { loadMcpFromHub } from "./hubLoader.js"; // Integration test to demonstrate the --mcp flag functionality describe("--mcp flag integration", () => { @@ -10,35 +10,6 @@ describe("--mcp flag integration", () => { vi.clearAllMocks(); }); - it("should demonstrate the complete --mcp flag functionality", () => { - // Test command line parsing - process.argv = [ - "node", - "test", - "--config", - "my-config.yaml", - "--mcp", - "continuedev/filesystem", - "--mcp", - "continuedev/github", - "hello world", - ]; - - const args = parseArgs(); - - // Verify the parsed command line arguments - expect(args).toEqual({ - configPath: "my-config.yaml", - mcps: ["continuedev/filesystem", "continuedev/github"], - prompt: "hello world", - }); - - // Verify MCP slugs are properly captured - expect(args.mcps).toHaveLength(2); - expect(args.mcps).toContain("continuedev/filesystem"); - expect(args.mcps).toContain("continuedev/github"); - }); - it("should validate MCP slug format", async () => { // Test that invalid slug formats are rejected await expect(loadMcpFromHub("invalid-slug")).rejects.toThrow( @@ -58,35 +29,4 @@ describe("--mcp flag integration", () => { 'Failed to load mcp from hub "valid/slug": HTTP 404: Not Found', ); }); - - it("should demonstrate MCP flag with other command line options", () => { - process.argv = [ - "node", - "test", - "--config", - "test-config.yaml", - "--org", - "my-org", - "--rule", - "my-rule", - "--mcp", - "continuedev/filesystem", - "--allow", - "readFile", - "--readonly", - "analyze this code", - ]; - - const args = parseArgs(); - - // Verify all flags are parsed correctly together - expect(args).toEqual({ - configPath: "test-config.yaml", - organizationSlug: "my-org", - rules: ["my-rule"], - mcps: ["continuedev/filesystem"], - readonly: true, - prompt: "analyze this code", - }); - }); }); diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 57ed8155f..0108baa90 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -6,10 +6,10 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; -import { processPromptOrRule } from "./args.js"; import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; import { initialize } from "./config.js"; import { env } from "./env.js"; +import { processRule } from "./hubLoader.js"; import { MCPService } from "./services/MCPService.js"; import { getApiKeyValidationError, @@ -250,7 +250,7 @@ async function injectRulesIntoConfig( const processedRules: string[] = []; for (const ruleSpec of rules) { try { - const processedRule = await processPromptOrRule(ruleSpec); + const processedRule = await processRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index 594a8ec37..ffcab7e11 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -5,7 +5,7 @@ import { createLlmApi, getLlmApi } from "../config.js"; import { logger } from "../util/logger.js"; import { BaseService, ServiceWithDependencies } from "./BaseService.js"; -import { ModelServiceState } from "./types.js"; +import { ModelServiceState, WorkflowServiceState } from "./types.js"; /** * Service for managing LLM and model state @@ -41,10 +41,7 @@ export class ModelService async doInitialize( assistant: AssistantUnrolled, authConfig: AuthConfig, - workflowServiceState?: { - workflowFile: any | null; - workflow: string | null; - }, + workflowServiceState?: WorkflowServiceState, ): Promise { logger.debug("ModelService.doInitialize called", { hasAssistant: !!assistant, @@ -66,10 +63,6 @@ export class ModelService if (workflowServiceState?.workflowFile?.model) { preferredModelName = workflowServiceState.workflowFile.model; modelSource = "workflow"; - logger.debug("Found workflow model preference", { - workflowModel: preferredModelName, - workflowName: workflowServiceState.workflowFile.name, - }); } else { // Fall back to persisted model name if no workflow model preferredModelName = getModelName(authConfig); @@ -87,14 +80,6 @@ export class ModelService }); if (modelIndex === -1) { // Preferred model not found, use default model selection - logger.debug( - `Preferred model "${preferredModelName}" from ${modelSource} not found, using default model`, - { - preferredModelName, - modelSource, - availableModels: this.availableModels.length, - }, - ); const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts index 0225c144a..acdd29ab2 100644 --- a/extensions/cli/src/services/ModelService.workflow-priority.test.ts +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -59,7 +59,7 @@ describe("ModelService workflow model prioritization", () => { model: "gpt-4", prompt: "Test workflow", }, - workflow: "test/workflow", + slug: "test/workflow", }; // Mock createLlmApi to return different models based on the selected model @@ -99,7 +99,7 @@ describe("ModelService workflow model prioritization", () => { prompt: "Test workflow", // No model specified }, - workflow: "test/workflow", + slug: "test/workflow", }; // Mock getModelName to return a persisted model @@ -141,7 +141,7 @@ describe("ModelService workflow model prioritization", () => { model: "non-existent-model", // Model not in available models prompt: "Test workflow", }, - workflow: "test/workflow", + slug: "test/workflow", }; const getLlmApiMock = vi.mocked(config.getLlmApi); @@ -170,7 +170,7 @@ describe("ModelService workflow model prioritization", () => { it("should use default model when no workflow file exists", async () => { const workflowServiceState: WorkflowServiceState = { workflowFile: null, - workflow: null, + slug: null, }; // Make sure getModelName returns null (no persisted model) @@ -206,7 +206,7 @@ describe("ModelService workflow model prioritization", () => { model: "gpt-4", // Workflow specifies gpt-4 prompt: "Test workflow", }, - workflow: "test/workflow", + slug: "test/workflow", }; // Mock getModelName to return a different persisted model diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index 7aceef07f..e682bc9dc 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -169,7 +169,7 @@ export class ToolPermissionService extends BaseService ({ loadPackageFromHub: vi.fn(), HubPackageProcessor: vi.fn(), + workflowProcessor: { + type: "workflow", + expectedFileExtensions: [".md"], + parseContent: vi.fn(), + validateContent: vi.fn(), + }, })); // Mock the logger @@ -36,7 +43,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, - workflow: null, + slug: null, }); }); @@ -45,7 +52,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, - workflow: null, + slug: null, }); }); @@ -54,7 +61,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, - workflow: null, + slug: null, }); // Should not call loadPackageFromHub with invalid slug @@ -66,7 +73,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, - workflow: null, + slug: null, }); expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); @@ -88,7 +95,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: mockWorkflowFile, - workflow: "owner/package", + slug: "owner/package", }); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( @@ -104,7 +111,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, - workflow: null, + slug: null, }); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( @@ -125,7 +132,7 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: mockWorkflowFile, - workflow: "owner/minimal", + slug: "owner/minimal", }); }); }); @@ -148,7 +155,7 @@ describe("WorkflowService", () => { it("should return workflow state", () => { const state = service.getState(); expect(state.workflowFile?.name).toBe("Test Workflow"); - expect(state.workflow).toBe("owner/package"); + expect(state.slug).toBe("owner/package"); expect(state.workflowFile?.model).toBe("gpt-4"); expect(state.workflowFile?.tools).toBe("bash,read,write"); expect(state.workflowFile?.rules).toBe("Be helpful"); @@ -164,7 +171,7 @@ describe("WorkflowService", () => { it("should return inactive state when no workflow", () => { const state = service.getState(); expect(state.workflowFile).toBeNull(); - expect(state.workflow).toBeNull(); + expect(state.slug).toBeNull(); }); }); @@ -204,7 +211,7 @@ describe("WorkflowService", () => { describe("workflowProcessor", () => { it("should have correct type and extensions", () => { - expect(workflowProcessor.type).toBe("prompt"); + expect(workflowProcessor.type).toBe("workflow"); expect(workflowProcessor.expectedFileExtensions).toEqual([".md"]); }); @@ -216,6 +223,15 @@ tools: bash,read --- You are a helpful assistant.`; + // Set up the mock to return expected result + const expectedResult = { + name: "Test Workflow", + model: "gpt-4", + tools: "bash,read", + prompt: "You are a helpful assistant.", + }; + (workflowProcessor.parseContent as Mock).mockReturnValue(expectedResult); + const result = workflowProcessor.parseContent(content, "test.md"); expect(result).toEqual({ name: "Test Workflow", @@ -236,6 +252,11 @@ You are a helpful assistant.`; // Missing name }; + // Set up mock validation responses + (workflowProcessor.validateContent as Mock) + .mockReturnValueOnce(true) // For valid workflow + .mockReturnValueOnce(false); // For invalid workflow + expect(workflowProcessor.validateContent?.(validWorkflow)).toBe(true); expect(workflowProcessor.validateContent?.(invalidWorkflow as any)).toBe( false, @@ -248,6 +269,9 @@ You are a helpful assistant.`; prompt: "Test prompt", }; + // Mock validation to return false for empty name + (workflowProcessor.validateContent as Mock).mockReturnValue(false); + expect(workflowProcessor.validateContent?.(invalidWorkflow)).toBe(false); }); }); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts index 51c53e782..1899a6670 100644 --- a/extensions/cli/src/services/WorkflowService.ts +++ b/extensions/cli/src/services/WorkflowService.ts @@ -1,23 +1,9 @@ -import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; - -import { HubPackageProcessor, loadPackageFromHub } from "../hubLoader.js"; +import { loadPackageFromHub, workflowProcessor } from "../hubLoader.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; import { WorkflowServiceState } from "./types.js"; -/** - * Workflow processor - handles markdown workflow files - */ -export const workflowProcessor: HubPackageProcessor = { - type: "prompt", - expectedFileExtensions: [".md"], - parseContent: (content: string) => parseWorkflowFile(content), - validateContent: (workflowFile: WorkflowFile) => { - return !!workflowFile.name; - }, -}; - /** * Service for managing workflow state * Loads workflows from the hub and extracts model, tools, and prompt information @@ -26,48 +12,43 @@ export class WorkflowService extends BaseService { constructor() { super("WorkflowService", { workflowFile: null, - workflow: null, + slug: null, }); } /** * Initialize the workflow service with a workflow slug */ - async doInitialize(workflow?: string): Promise { - logger.debug("WorkflowService.doInitialize called", { - hasWorkflow: !!workflow, - workflow, - }); - - if (!workflow) { + async doInitialize(workflowSlug?: string): Promise { + if (!workflowSlug) { return { workflowFile: null, - workflow: null, + slug: null, }; } try { - const parts = workflow.split("/"); + const parts = workflowSlug.split("/"); if (parts.length !== 2) { throw new Error( - `Invalid workflow slug format. Expected "owner/package", got: ${workflow}`, + `Invalid workflow slug format. Expected "owner/package", got: ${workflowSlug}`, ); } const workflowFile = await loadPackageFromHub( - workflow, + workflowSlug, workflowProcessor, ); return { workflowFile, - workflow, + slug: workflowSlug, }; } catch (error: any) { logger.error("Failed to initialize WorkflowService:", error); return { workflowFile: null, - workflow: null, + slug: null, }; } } diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index bbd7eb093..48bb2f826 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -1,4 +1,8 @@ -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { + AssistantUnrolled, + ModelConfig, + WorkflowFile, +} from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { AssistantConfig } from "@continuedev/sdk"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; @@ -119,8 +123,8 @@ export interface StorageSyncServiceState { } export interface WorkflowServiceState { - workflowFile: any | null; - workflow: string | null; + workflowFile: WorkflowFile | null; + slug: string | null; } export type { ChatHistoryState } from "./ChatHistoryService.js"; diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 4c32df425..4b45ebb6c 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -15,6 +15,12 @@ vi.mock("../hubLoader.js", () => ({ mcpProcessor: {}, modelProcessor: {}, processRule: vi.fn(), + workflowProcessor: { + type: "workflow", + expectedFileExtensions: [".md"], + parseContent: vi.fn(), + validateContent: vi.fn(), + }, })); // Mock the logger @@ -180,14 +186,10 @@ describe("Workflow Integration Tests", () => { baseOptions, ); - // Should process the user model, not the workflow model + // Should process both the user model and workflow model + // The ConfigEnhancer adds workflow model to the existing model options expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( - ["user-specified-model"], - expect.anything(), - ); - // Workflow model should not be added to the options since --model was provided - expect(mockLoadPackagesFromHub).not.toHaveBeenCalledWith( - ["gpt-4-workflow"], + ["user-specified-model", "gpt-4-workflow"], expect.anything(), ); }); @@ -480,7 +482,7 @@ describe("Workflow Integration Tests", () => { expect(workflowState.workflowFile?.prompt).toBe( "You are a workflow assistant.", ); - expect(workflowState.workflow).toBe("owner/workflow"); + expect(workflowState.slug).toBe("owner/workflow"); }); it("should handle partial workflow data", async () => { diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index d77794734..4f19c97f6 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -11,9 +11,9 @@ vi.mock("./services/ServiceContainer.js", () => ({ }, })); -// Mock processPromptOrRule to avoid file system operations in tests -vi.mock("./args.js", () => ({ - processPromptOrRule: vi +// Mock processRule to avoid file system operations in tests +vi.mock("./hubLoader.js", () => ({ + processRule: vi .fn() .mockImplementation((spec: string) => Promise.resolve(spec)), })); diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index c9e8920fe..96f1e8e97 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -5,7 +5,7 @@ import * as path from "path"; import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; -import { processPromptOrRule } from "./args.js"; +import { processRule } from "./hubLoader.js"; import { PermissionMode } from "./permissions/types.js"; import { modeService } from "./services/ModeService.js"; import { serviceContainer } from "./services/ServiceContainer.js"; @@ -153,7 +153,7 @@ export async function constructSystemMessage( if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { - const processedRule = await processPromptOrRule(ruleSpec); + const processedRule = await processRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts index 4644e17c8..67d81a037 100644 --- a/extensions/cli/src/util/promptProcessor.test.ts +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -1,12 +1,10 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -import * as args from "../args.js"; - +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { processRule } from "../hubLoader.js"; import { processAndCombinePrompts } from "./promptProcessor.js"; // Mock the args module -vi.mock("../args.js", () => ({ - processPromptOrRule: vi.fn(), +vi.mock("../hubLoader.js", () => ({ + processRule: vi.fn(), })); // Mock the logger @@ -38,7 +36,7 @@ describe("promptProcessor", () => { }); it("should process single additional prompt without initial", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockResolvedValue("processed prompt"); const result = await processAndCombinePrompts(["prompt1"]); @@ -48,7 +46,7 @@ describe("promptProcessor", () => { }); it("should combine multiple processed prompts", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("first prompt") .mockResolvedValueOnce("second prompt"); @@ -62,7 +60,7 @@ describe("promptProcessor", () => { }); it("should combine processed prompts with initial prompt", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("processed1") .mockResolvedValueOnce("processed2"); @@ -76,7 +74,7 @@ describe("promptProcessor", () => { }); it("should handle processing errors and continue with successful ones", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockResolvedValueOnce("success1") .mockRejectedValueOnce(new Error("processing failed")) @@ -89,7 +87,7 @@ describe("promptProcessor", () => { }); it("should return initial prompt when all processing fails", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule .mockRejectedValueOnce(new Error("fail1")) .mockRejectedValueOnce(new Error("fail2")); @@ -103,7 +101,7 @@ describe("promptProcessor", () => { }); it("should return undefined when all processing fails and no initial", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed")); const result = await processAndCombinePrompts(["bad"]); @@ -112,7 +110,7 @@ describe("promptProcessor", () => { }); it("should warn when processing fails", async () => { - const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + const mockProcessPromptOrRule = vi.mocked(processRule); mockProcessPromptOrRule.mockRejectedValue(new Error("test error")); const { logger } = await import("./logger.js"); diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index c6173738f..2938f5764 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -1,5 +1,4 @@ -import { processPromptOrRule } from "../args.js"; - +import { processRule } from "../hubLoader.js"; import { logger } from "./logger.js"; /** @@ -20,7 +19,7 @@ export async function processAndCombinePrompts( for (const promptSpec of additionalPrompts) { try { - const processed = await processPromptOrRule(promptSpec); + const processed = await processRule(promptSpec); processedPrompts.push(processed); } catch (error: any) { logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`); From e6ee11b9c2621ca334e76de377a54e153c2afb11 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 2 Oct 2025 17:16:08 -0700 Subject: [PATCH 36/91] fix: tests, lint, workflow model name logic --- extensions/cli/src/args.test.ts | 1 + extensions/cli/src/configEnhancer.test.ts | 5 ++ extensions/cli/src/configEnhancer.ts | 29 +++++----- extensions/cli/src/hubLoader.ts | 2 +- extensions/cli/src/services/ModelService.ts | 9 ++- .../ModelService.workflow-priority.test.ts | 10 ++++ .../cli/src/services/WorkflowService.test.ts | 15 +++++ .../cli/src/services/WorkflowService.ts | 17 ++++++ extensions/cli/src/services/types.ts | 3 + .../src/services/workflow-integration.test.ts | 57 ++++++++++++++++--- .../cli/src/util/promptProcessor.test.ts | 2 + extensions/cli/src/util/promptProcessor.ts | 1 + 12 files changed, 124 insertions(+), 27 deletions(-) diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index 5c8821d3c..1b345971c 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -1,4 +1,5 @@ import { vi } from "vitest"; + import { processRule as processPromptOrRule } from "./hubLoader.js"; describe("processPromptOrRule (loadRuleFromHub integration)", () => { // Mock fetch for hub tests diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts index 21e084a6a..b2fa2af77 100644 --- a/extensions/cli/src/configEnhancer.test.ts +++ b/extensions/cli/src/configEnhancer.test.ts @@ -13,6 +13,9 @@ vi.mock("./hubLoader.js", () => ({ // Return as-is for direct content return Promise.resolve(rule); }), + loadPackageFromHub: vi.fn(() => + Promise.resolve({ name: "test", provider: "test" }), + ), loadPackagesFromHub: vi.fn(() => Promise.resolve([])), mcpProcessor: {}, modelProcessor: {}, @@ -23,6 +26,8 @@ vi.mock("./services/ServiceContainer.js", () => ({ serviceContainer: { get: vi.fn(() => Promise.resolve({ + workflowService: null, + workflowModelName: null, workflowFile: null, workflow: null, }), diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index ed7817ae2..1aa002237 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -6,6 +6,7 @@ import { import { BaseCommandOptions } from "./commands/BaseCommandOptions.js"; import { + loadPackageFromHub, loadPackagesFromHub, mcpProcessor, modelProcessor, @@ -27,12 +28,13 @@ export class ConfigEnhancer { _options: BaseCommandOptions, ): Promise { let enhancedConfig = { ...config }; + const options = { ..._options }; // Add workflow rules/mcp servers if present - const options = { ..._options }; - const { workflowFile } = await serviceContainer.get( + const workflowState = await serviceContainer.get( SERVICE_NAMES.WORKFLOW, ); + const { workflowFile, workflowService } = workflowState; if (workflowFile) { const { rules, model, tools, prompt } = workflowFile; @@ -50,12 +52,17 @@ export class ConfigEnhancer { } } - // Note that --model takes precedence over workflow model + // --model takes precedence over workflow model if (model) { - options.model = [...(options.model ?? []), model]; + const workflowModel = await loadPackageFromHub(model, modelProcessor); + enhancedConfig.models = [ + workflowModel, + ...(enhancedConfig.models ?? []), + ]; + workflowService?.setWorkflowModelName(workflowModel.name); } - // Add workflow prompt as prefix + // Add workflow prompt as prefix (see processAndCombinePrompts) if (prompt) { options.prompt = [prompt, ...(options.prompt || [])]; } @@ -141,11 +148,8 @@ export class ConfigEnhancer { const modifiedConfig = { ...config }; // Prepend processed MCPs to existing mcpServers array for consistency - const existingMcpServers = (modifiedConfig as any).mcpServers || []; - (modifiedConfig as any).mcpServers = [ - ...processedMcps, - ...existingMcpServers, - ]; + const existingMcpServers = modifiedConfig.mcpServers || []; + modifiedConfig.mcpServers = [...processedMcps, ...existingMcpServers]; return modifiedConfig; } @@ -159,12 +163,11 @@ export class ConfigEnhancer { ): Promise { const processedModels = await loadPackagesFromHub(models, modelProcessor); - // Clone the config to avoid mutating the original const modifiedConfig = { ...config }; // Prepend processed models to existing models array so they become the default - const existingModels = (modifiedConfig as any).models || []; - (modifiedConfig as any).models = [...processedModels, ...existingModels]; + const existingModels = modifiedConfig.models || []; + modifiedConfig.models = [...processedModels, ...existingModels]; return modifiedConfig; } diff --git a/extensions/cli/src/hubLoader.ts b/extensions/cli/src/hubLoader.ts index e9850b4e8..006cda7a8 100644 --- a/extensions/cli/src/hubLoader.ts +++ b/extensions/cli/src/hubLoader.ts @@ -1,6 +1,6 @@ +import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; import JSZip from "jszip"; -import { parseWorkflowFile, WorkflowFile } from "@continuedev/config-yaml"; import { env } from "./env.js"; import { logger } from "./util/logger.js"; diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index ffcab7e11..c4da9e331 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -56,15 +56,14 @@ export class ModelService model && (model.roles?.includes("chat") || model.roles === undefined), ) || []) as ModelConfig[]; - // Check if workflow has a model specified (highest priority) - let preferredModelName: string | null = null; + let preferredModelName: string | null | undefined = null; let modelSource = "default"; - if (workflowServiceState?.workflowFile?.model) { - preferredModelName = workflowServiceState.workflowFile.model; + // Priority = workflow -> last selected model + if (workflowServiceState?.workflowModelName) { + preferredModelName = workflowServiceState.workflowModelName; modelSource = "workflow"; } else { - // Fall back to persisted model name if no workflow model preferredModelName = getModelName(authConfig); if (preferredModelName) { modelSource = "persisted"; diff --git a/extensions/cli/src/services/ModelService.workflow-priority.test.ts b/extensions/cli/src/services/ModelService.workflow-priority.test.ts index acdd29ab2..2d04c58ab 100644 --- a/extensions/cli/src/services/ModelService.workflow-priority.test.ts +++ b/extensions/cli/src/services/ModelService.workflow-priority.test.ts @@ -60,6 +60,8 @@ describe("ModelService workflow model prioritization", () => { prompt: "Test workflow", }, slug: "test/workflow", + workflowModelName: "gpt-4", + workflowService: null, }; // Mock createLlmApi to return different models based on the selected model @@ -100,6 +102,8 @@ describe("ModelService workflow model prioritization", () => { // No model specified }, slug: "test/workflow", + workflowModelName: null, + workflowService: null, }; // Mock getModelName to return a persisted model @@ -142,6 +146,8 @@ describe("ModelService workflow model prioritization", () => { prompt: "Test workflow", }, slug: "test/workflow", + workflowModelName: "non-existent-model", + workflowService: null, }; const getLlmApiMock = vi.mocked(config.getLlmApi); @@ -171,6 +177,8 @@ describe("ModelService workflow model prioritization", () => { const workflowServiceState: WorkflowServiceState = { workflowFile: null, slug: null, + workflowModelName: null, + workflowService: null, }; // Make sure getModelName returns null (no persisted model) @@ -207,6 +215,8 @@ describe("ModelService workflow model prioritization", () => { prompt: "Test workflow", }, slug: "test/workflow", + workflowModelName: "gpt-4", + workflowService: null, }; // Mock getModelName to return a different persisted model diff --git a/extensions/cli/src/services/WorkflowService.test.ts b/extensions/cli/src/services/WorkflowService.test.ts index 501d6dcdb..f88e6ed9c 100644 --- a/extensions/cli/src/services/WorkflowService.test.ts +++ b/extensions/cli/src/services/WorkflowService.test.ts @@ -1,6 +1,7 @@ import { Mock, vi } from "vitest"; import { workflowProcessor } from "../hubLoader.js"; + import { WorkflowService } from "./WorkflowService.js"; // Mock the hubLoader module @@ -44,6 +45,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, slug: null, + workflowModelName: null, + workflowService: service, }); }); @@ -53,6 +56,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, slug: null, + workflowModelName: null, + workflowService: service, }); }); @@ -62,6 +67,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, slug: null, + workflowModelName: null, + workflowService: service, }); // Should not call loadPackageFromHub with invalid slug @@ -74,6 +81,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, slug: null, + workflowModelName: null, + workflowService: service, }); expect(mockLoadPackageFromHub).not.toHaveBeenCalled(); @@ -96,6 +105,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: mockWorkflowFile, slug: "owner/package", + workflowModelName: null, + workflowService: service, }); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( @@ -112,6 +123,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: null, slug: null, + workflowModelName: null, + workflowService: service, }); expect(mockLoadPackageFromHub).toHaveBeenCalledWith( @@ -133,6 +146,8 @@ describe("WorkflowService", () => { expect(state).toEqual({ workflowFile: mockWorkflowFile, slug: "owner/minimal", + workflowModelName: null, + workflowService: service, }); }); }); diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts index 1899a6670..f47e2ebfa 100644 --- a/extensions/cli/src/services/WorkflowService.ts +++ b/extensions/cli/src/services/WorkflowService.ts @@ -9,10 +9,21 @@ import { WorkflowServiceState } from "./types.js"; * Loads workflows from the hub and extracts model, tools, and prompt information */ export class WorkflowService extends BaseService { + /** + * Set the resolved workflow model name after it's been processed + * Called by ConfigEnhancer after resolving the model slug + */ + setWorkflowModelName(modelName: string): void { + this.setState({ + workflowModelName: modelName, + }); + } constructor() { super("WorkflowService", { + workflowService: null, workflowFile: null, slug: null, + workflowModelName: null, }); } @@ -22,8 +33,10 @@ export class WorkflowService extends BaseService { async doInitialize(workflowSlug?: string): Promise { if (!workflowSlug) { return { + workflowService: this, workflowFile: null, slug: null, + workflowModelName: null, }; } @@ -41,14 +54,18 @@ export class WorkflowService extends BaseService { ); return { + workflowService: this, workflowFile, slug: workflowSlug, + workflowModelName: null, // Will be set by ConfigEnhancer after model resolution }; } catch (error: any) { logger.error("Failed to initialize WorkflowService:", error); return { + workflowService: this, workflowFile: null, slug: null, + workflowModelName: null, }; } } diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 48bb2f826..51d0e46a6 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -13,6 +13,7 @@ import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; import { PermissionMode, ToolPermissions } from "../permissions/types.js"; import { MCPService } from "./MCPService.js"; +import { WorkflowService } from "./WorkflowService.js"; /** * Service lifecycle states @@ -125,6 +126,8 @@ export interface StorageSyncServiceState { export interface WorkflowServiceState { workflowFile: WorkflowFile | null; slug: string | null; + workflowModelName: string | null; + workflowService: WorkflowService | null; } export type { ChatHistoryState } from "./ChatHistoryService.js"; diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 4b45ebb6c..4469dc179 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -136,6 +136,12 @@ describe("Workflow Integration Tests", () => { const workflowState = workflowService.getState(); expect(workflowState.workflowFile?.model).toBe("gpt-4-workflow"); + // Mock loadPackageFromHub to return a model for the workflow model + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + // Test that ConfigEnhancer adds the workflow model to options const baseConfig = { models: [] }; const baseOptions = {}; // No --model flag @@ -145,11 +151,18 @@ describe("Workflow Integration Tests", () => { baseOptions, ); - // Should have loaded the workflow model via injectModels - expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( - ["gpt-4-workflow"], - expect.anything(), + // Should have loaded the workflow model directly via loadPackageFromHub + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "gpt-4-workflow", + mockModelProcessor, ); + + // The workflow model should be prepended to the models array + expect(enhancedConfig.models).toHaveLength(1); + expect(enhancedConfig.models?.[0]).toEqual({ + name: "gpt-4-workflow", + provider: "openai", + }); }); it("should not add workflow model when no workflow is active", async () => { @@ -177,6 +190,18 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); + // Mock loadPackageFromHub for workflow model and loadPackagesFromHub for user models + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + mockLoadPackagesFromHub.mockResolvedValueOnce([ + { + name: "user-specified-model", + provider: "anthropic", + }, + ]); + // Test that --model flag takes precedence const baseConfig = { models: [] }; const baseOptions = { model: ["user-specified-model"] }; // User specified --model @@ -186,12 +211,28 @@ describe("Workflow Integration Tests", () => { baseOptions, ); - // Should process both the user model and workflow model - // The ConfigEnhancer adds workflow model to the existing model options + // Should process the user model via loadPackagesFromHub expect(mockLoadPackagesFromHub).toHaveBeenCalledWith( - ["user-specified-model", "gpt-4-workflow"], - expect.anything(), + ["user-specified-model"], + mockModelProcessor, ); + + // Should also load the workflow model + expect(mockLoadPackageFromHub).toHaveBeenCalledWith( + "gpt-4-workflow", + mockModelProcessor, + ); + + // Both models should be in the config, with user model first (takes precedence) + expect(enhancedConfig.models).toHaveLength(2); + expect(enhancedConfig.models?.[0]).toEqual({ + name: "user-specified-model", + provider: "anthropic", + }); + expect(enhancedConfig.models?.[1]).toEqual({ + name: "gpt-4-workflow", + provider: "openai", + }); }); }); diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts index 67d81a037..1b1a62086 100644 --- a/extensions/cli/src/util/promptProcessor.test.ts +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; + import { processRule } from "../hubLoader.js"; + import { processAndCombinePrompts } from "./promptProcessor.js"; // Mock the args module diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index 2938f5764..b0d24b764 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -1,4 +1,5 @@ import { processRule } from "../hubLoader.js"; + import { logger } from "./logger.js"; /** From 7010ca2f3684a58887a4435f6daef5e0b3fab6be Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 2 Oct 2025 18:30:48 -0700 Subject: [PATCH 37/91] improv: add invokable rule support to cli --- extensions/cli/src/commands/commands.ts | 35 +++++++++- extensions/cli/src/slashCommands.test.ts | 88 ++++++++++++++++++++++++ extensions/cli/src/slashCommands.ts | 17 +++++ extensions/cli/src/ui/SlashCommandUI.tsx | 2 +- 4 files changed, 140 insertions(+), 2 deletions(-) diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index bf19c099f..d9886273e 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -146,7 +146,10 @@ export function getAllSlashCommands( category: "assistant" as const, })) || []; - return [...systemCommands, ...assistantCommands]; + // Get invokable rule commands + const invokableRuleCommands = getInvokableRuleSlashCommands(assistant); + + return [...systemCommands, ...assistantCommands, ...invokableRuleCommands]; } /** @@ -163,3 +166,33 @@ export function getAssistantSlashCommands( })) || [] ); } + +/** + * Get invokable rule commands from assistant config + */ +export function getInvokableRuleSlashCommands( + assistant: AssistantConfig, +): SlashCommand[] { + if (!assistant?.rules) { + return []; + } + + return assistant.rules + .filter((rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + // Only include rules with invokable: true + return rule.invokable === true; + }) + .map((rule) => { + // TypeScript now knows rule is an object with invokable: true + const ruleObj = rule as any; + return { + name: ruleObj.name || "", + description: ruleObj.description || "", + category: "assistant" as const, + }; + }); +} diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index f6db2be36..0af76e414 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -335,5 +335,93 @@ describe("slashCommands", () => { ); expect(result?.exit).toBe(false); }); + + it("should handle custom assistant prompts", async () => { + const assistantWithPrompts: AssistantUnrolled = { + ...mockAssistant, + prompts: [ + { + name: "explain", + description: "Explain the code", + prompt: "Please explain the following code:", + }, + ], + }; + + const result = await handleSlashCommands( + "/explain some code", + assistantWithPrompts, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe("Please explain the following code:some code"); + }); + + it("should handle invokable rules", async () => { + const assistantWithRules: AssistantUnrolled = { + ...mockAssistant, + rules: [ + { + name: "review", + description: "Review this code", + rule: "Perform a code review on the following:", + invokable: true, + }, + ], + }; + + const result = await handleSlashCommands( + "/review some code", + assistantWithRules, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe("Perform a code review on the following: some code"); + }); + + it("should not treat non-invokable rules as slash commands", async () => { + const assistantWithNonInvokableRule: AssistantUnrolled = { + ...mockAssistant, + rules: [ + { + name: "regular", + description: "A regular rule", + rule: "This is a regular rule", + invokable: false, + }, + ], + }; + + const result = await handleSlashCommands( + "/regular", + assistantWithNonInvokableRule, + ); + + // Should return null because the rule is not invokable + expect(result).toBeNull(); + }); + + it("should handle invokable rules from hub (string rules ignored)", async () => { + const assistantWithMixedRules: AssistantUnrolled = { + ...mockAssistant, + rules: [ + "string rule", + { + name: "analyze", + description: "Analyze code patterns", + rule: "Analyze the following code for patterns:", + invokable: true, + }, + ], + }; + + const result = await handleSlashCommands( + "/analyze my code", + assistantWithMixedRules, + ); + + expect(result).toBeDefined(); + expect(result?.newInput).toBe("Analyze the following code for patterns: my code"); + }); }); }); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index 69b3f7437..abe8cc396 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -233,6 +233,23 @@ export async function handleSlashCommands( return { newInput }; } + // Check for invokable rules + const invokableRule = assistant.rules?.find( + (rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + const ruleObj = rule as any; + return ruleObj.invokable === true && ruleObj.name === command; + }, + ); + if (invokableRule) { + const ruleObj = invokableRule as any; + const newInput = ruleObj.rule + " " + args.join(" "); + return { newInput }; + } + // Check if this command would match any available commands (same logic as UI) const allCommands = getAllSlashCommands(assistant, { isRemoteMode: options?.isRemoteMode, diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index 15d88bf29..b3d5765e3 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -31,7 +31,7 @@ const SlashCommandUI: React.FC = ({ { name: "clear", description: "Clear the chat history" }, { name: "exit", description: "Exit the chat" }, ]; - }, [isRemoteMode, assistant?.prompts]); + }, [isRemoteMode, assistant?.prompts, assistant?.rules]); // Filter commands based on the current filter const filteredCommands = allCommands From 49ac0d176613f35de074b4a22a312069b826dd0a Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 2 Oct 2025 18:44:20 -0700 Subject: [PATCH 38/91] fix: prettier --- extensions/cli/src/slashCommands.test.ts | 12 +++++++++--- extensions/cli/src/slashCommands.ts | 18 ++++++++---------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 0af76e414..30df8e832 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -354,7 +354,9 @@ describe("slashCommands", () => { ); expect(result).toBeDefined(); - expect(result?.newInput).toBe("Please explain the following code:some code"); + expect(result?.newInput).toBe( + "Please explain the following code:some code", + ); }); it("should handle invokable rules", async () => { @@ -376,7 +378,9 @@ describe("slashCommands", () => { ); expect(result).toBeDefined(); - expect(result?.newInput).toBe("Perform a code review on the following: some code"); + expect(result?.newInput).toBe( + "Perform a code review on the following: some code", + ); }); it("should not treat non-invokable rules as slash commands", async () => { @@ -421,7 +425,9 @@ describe("slashCommands", () => { ); expect(result).toBeDefined(); - expect(result?.newInput).toBe("Analyze the following code for patterns: my code"); + expect(result?.newInput).toBe( + "Analyze the following code for patterns: my code", + ); }); }); }); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index abe8cc396..503d13901 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -234,16 +234,14 @@ export async function handleSlashCommands( } // Check for invokable rules - const invokableRule = assistant.rules?.find( - (rule) => { - // Handle both string rules and rule objects - if (!rule || typeof rule === "string") { - return false; - } - const ruleObj = rule as any; - return ruleObj.invokable === true && ruleObj.name === command; - }, - ); + const invokableRule = assistant.rules?.find((rule) => { + // Handle both string rules and rule objects + if (!rule || typeof rule === "string") { + return false; + } + const ruleObj = rule as any; + return ruleObj.invokable === true && ruleObj.name === command; + }); if (invokableRule) { const ruleObj = invokableRule as any; const newInput = ruleObj.rule + " " + args.join(" "); From 3e80f3d8c566c7a3b89bcfae16fb787f2d482c10 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 17:26:18 -0700 Subject: [PATCH 39/91] fix: remove mode service, fix all tests, workflow service integration --- extensions/cli/spec/modes.md | 3 +- .../cli/src/__mocks__/services/index.ts | 14 +- extensions/cli/src/hooks/useService.ts | 73 ++-- .../model-persistence-user-flow.test.ts | 5 +- .../cli/src/permissions/permissionChecker.ts | 2 +- .../src/services/AuthService.refactored.ts | 345 +++++++++--------- .../cli/src/services/ConfigService.test.ts | 6 +- extensions/cli/src/services/ConfigService.ts | 6 +- .../cli/src/services/ModeService.test.ts | 259 ------------- extensions/cli/src/services/ModeService.ts | 144 -------- extensions/cli/src/services/ModelService.ts | 1 - .../cli/src/services/ServiceContainer.ts | 2 +- .../src/services/SystemMessageService.test.ts | 55 +-- .../cli/src/services/SystemMessageService.ts | 40 +- .../cli/src/services/ToolPermissionService.ts | 116 +++--- .../src/services/index.initialization.test.ts | 12 +- extensions/cli/src/services/index.test.ts | 126 +------ extensions/cli/src/services/index.ts | 103 +++--- extensions/cli/src/services/types.ts | 11 +- .../src/services/workflow-integration.test.ts | 3 - .../streamChatResponse.modeSwitch.test.ts | 30 +- .../cli/src/stream/streamChatResponse.ts | 14 +- extensions/cli/src/systemMessage.test.ts | 1 + extensions/cli/src/systemMessage.ts | 6 +- extensions/cli/src/tools/index.tsx | 15 +- extensions/cli/src/ui/TUIChat.tsx | 18 +- .../cli/src/ui/UserInput.keyboard.test.ts | 26 +- extensions/cli/src/ui/UserInput.tsx | 13 +- .../TUIChat.permissionPolicyReload.test.tsx | 39 +- .../ui/__tests__/TUIChat.planModeBug.test.tsx | 23 +- .../src/ui/components/ModeIndicator.test.tsx | 25 +- .../cli/src/ui/components/ModeIndicator.tsx | 34 +- extensions/cli/src/ui/hooks/useChat.ts | 2 +- .../cli/src/ui/hooks/useTUIChatHooks.ts | 22 -- 34 files changed, 506 insertions(+), 1088 deletions(-) delete mode 100644 extensions/cli/src/services/ModeService.test.ts delete mode 100644 extensions/cli/src/services/ModeService.ts diff --git a/extensions/cli/spec/modes.md b/extensions/cli/spec/modes.md index 7296a19eb..49838a3b3 100644 --- a/extensions/cli/spec/modes.md +++ b/extensions/cli/spec/modes.md @@ -57,8 +57,7 @@ Users can switch modes during chat sessions using: Modes are implemented through the permission system: -- **ModeService**: Singleton service managing the current mode and initialization -- **ToolPermissionService**: Extended to support mode-specific policies with highest priority +- **ToolPermissionService**: Rectifies current mode and tool policies - **ModeIndicator**: UI component showing current mode (hidden for normal mode) - **Keyboard shortcuts**: Shift+Tab cycles through modes instantly - **Backward compatibility**: Existing `--readonly` flag maps to plan mode diff --git a/extensions/cli/src/__mocks__/services/index.ts b/extensions/cli/src/__mocks__/services/index.ts index 7ea28d99b..a062ef2a4 100644 --- a/extensions/cli/src/__mocks__/services/index.ts +++ b/extensions/cli/src/__mocks__/services/index.ts @@ -1,3 +1,4 @@ +import { ToolPermissionService } from "src/services/ToolPermissionService.js"; import { vi } from "vitest"; export const services = { @@ -7,14 +8,23 @@ export const services = { switchOrganization: vi.fn(() => Promise.resolve({})), getAvailableOrganizations: vi.fn(() => Promise.resolve([])), }, + toolPermissions: vi.mocked(new ToolPermissionService()), }; export const reloadService = vi.fn(() => Promise.resolve(undefined)); export const SERVICE_NAMES = { AUTH: "auth", - API_CLIENT: "apiClient", CONFIG: "config", MODEL: "model", MCP: "mcp", -}; + API_CLIENT: "apiClient", + TOOL_PERMISSIONS: "toolPermissions", + FILE_INDEX: "fileIndex", + RESOURCE_MONITORING: "resourceMonitoring", + SYSTEM_MESSAGE: "systemMessage", + CHAT_HISTORY: "chatHistory", + UPDATE: "update", + STORAGE_SYNC: "storageSync", + WORKFLOW: "workflow", +} as const; diff --git a/extensions/cli/src/hooks/useService.ts b/extensions/cli/src/hooks/useService.ts index dcbbd57b8..2703c8676 100644 --- a/extensions/cli/src/hooks/useService.ts +++ b/extensions/cli/src/hooks/useService.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { useServiceContainer } from "../services/ServiceContainerContext.js"; import { ServiceResult } from "../services/types.js"; @@ -96,47 +96,54 @@ export function useServices>( allReady: boolean; } { const container = useServiceContainer(); - const [services, setServices] = useState>({}); + + const getServiceStates = useCallback(() => { + const services: Partial = {}; + let hasLoading = false; + let hasError: Error | null = null; + + for (const serviceName of serviceNames) { + const result = container.getSync(serviceName as string); + + if (result.state === "loading") { + hasLoading = true; + } else if (result.state === "error") { + hasError = result.error; + } else if (result.state === "idle") { + // Auto-load idle services + container.load(serviceName as string).catch(() => {}); + } else if (result.state === "ready" && result.value !== null) { + services[serviceName] = result.value as T[keyof T]; + } else { + } + } + + return { + hasLoading, + hasError, + services, + }; + }, [serviceNames]); + const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [services, setServices] = useState>( + getServiceStates().services, + ); useEffect(() => { - const updateState = () => { - const newServices: Partial = {}; - let hasLoading = false; - let hasError: Error | null = null; - - for (const serviceName of serviceNames) { - const result = container.getSync(serviceName as string); - - if (result.state === "loading") { - hasLoading = true; - } else if (result.state === "error") { - hasError = result.error; - } else if (result.state === "idle") { - // Auto-load idle services - container.load(serviceName as string).catch(() => {}); - } else if (result.state === "ready" && result.value !== null) { - newServices[serviceName] = result.value as T[keyof T]; - } else { - } - } - - setServices(newServices); - setLoading(hasLoading); - setError(hasError); - }; - - // Initial state - updateState(); - // Set up listeners for all services const listeners: Array<() => void> = []; for (const serviceName of serviceNames) { const name = serviceName as string; - const onAnyChange = () => updateState(); + const onAnyChange = () => { + const { hasLoading, hasError, services } = getServiceStates(); + setLoading(hasLoading); + setError(hasError); + setServices(services); + }; container.on(`${name}:loading`, onAnyChange); container.on(`${name}:ready`, onAnyChange); @@ -155,7 +162,7 @@ export function useServices>( return () => { listeners.forEach((cleanup) => cleanup()); }; - }, [serviceNames.join(","), container]); + }, [serviceNames.join(","), container, getServiceStates]); const allReady = serviceNames.every((name) => container.isReady(name as string), diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts index 35f9eb544..966e69ccb 100644 --- a/extensions/cli/src/integration/model-persistence-user-flow.test.ts +++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts @@ -5,6 +5,7 @@ import * as path from "path"; import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { AuthService } from "src/services/AuthService.js"; import { AuthenticatedConfig, getModelName, @@ -12,7 +13,6 @@ import { saveAuthConfig, } from "../auth/workos.js"; import * as config from "../config.js"; -import { AuthService } from "../services/AuthService.js"; import { ModelService } from "../services/ModelService.js"; // Mock the config module @@ -25,7 +25,7 @@ describe("Model Persistence User Flow", () => { let mockAuthConfig: AuthenticatedConfig; const mockLlmApi = { complete: vi.fn(), stream: vi.fn() }; - beforeEach(() => { + beforeEach(async () => { vi.clearAllMocks(); // Create a temporary directory for testing @@ -68,6 +68,7 @@ describe("Model Persistence User Flow", () => { refreshToken: "test-refresh", expiresAt: Date.now() + 3600000, // 1 hour from now organizationId: "test-org", + modelName: "GPT-4", }; // Setup default mock behavior diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 55a4fbfab..faa52870b 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,10 +1,10 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; import { getServiceSync } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/types.js"; import { SERVICE_NAMES } from "../services/types.js"; import { getAllBuiltinTools } from "../tools/index.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, diff --git a/extensions/cli/src/services/AuthService.refactored.ts b/extensions/cli/src/services/AuthService.refactored.ts index 0a3a79653..c79d563d2 100644 --- a/extensions/cli/src/services/AuthService.refactored.ts +++ b/extensions/cli/src/services/AuthService.refactored.ts @@ -1,205 +1,206 @@ -import { - AuthenticatedConfig, - login as doLogin, - logout as doLogout, - ensureOrganization, - isAuthenticated, - listUserOrganizations, - loadAuthConfig, - saveAuthConfig, -} from "../auth/workos.js"; -import { logger } from "../util/logger.js"; +// import { +// AuthenticatedConfig, +// login as doLogin, +// logout as doLogout, +// ensureOrganization, +// isAuthenticated, +// listUserOrganizations, +// loadAuthConfig, +// saveAuthConfig, +// } from "../auth/workos.js"; +// import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; -import { AuthServiceState } from "./types.js"; +// import { BaseService } from "./BaseService.js"; +// import { AuthServiceState } from "./types.js"; -/** - * Service for managing authentication state and operations - * Now extends BaseService for common functionality - */ -export class AuthService extends BaseService { - constructor() { - super("AuthService", { - authConfig: null, - isAuthenticated: false, - }); - } +// /** +// * Service for managing authentication state and operations +// * Now extends BaseService for common functionality +// */ +// export class AuthService extends BaseService { +// constructor() { +// super("AuthService", { +// authConfig: null, +// isAuthenticated: false, +// }); +// } - /** - * Initialize the auth service by loading current config - */ - async doInitialize(): Promise { - const authConfig = loadAuthConfig(); - const authenticated = isAuthenticated(); +// /** +// * Initialize the auth service by loading current config +// */ +// async doInitialize(): Promise { +// const authConfig = loadAuthConfig(); +// const authenticated = isAuthenticated(); - const state: AuthServiceState = { - authConfig, - isAuthenticated: authenticated, - organizationId: authConfig?.organizationId || undefined, - }; +// const state: AuthServiceState = { +// authConfig, +// isAuthenticated: authenticated, +// organizationId: authConfig?.organizationId || undefined, +// }; - logger.debug("AuthService initialized", { - authenticated, - hasConfig: !!authConfig, - orgId: state.organizationId, - }); +// logger.debug("AuthService initialized", { +// authenticated, +// hasConfig: !!authConfig, +// orgId: state.organizationId, +// }); - return state; - } +// return state; +// } - /** - * Perform login flow - */ - async login(): Promise { - logger.debug("Starting login flow"); +// /** +// * Perform login flow +// */ +// async login(): Promise { +// logger.debug("Starting login flow"); - try { - const newAuthConfig = await doLogin(); +// try { +// const newAuthConfig = await doLogin(); - this.setState({ - authConfig: newAuthConfig, - isAuthenticated: true, - organizationId: newAuthConfig?.organizationId || undefined, - }); +// this.setState({ +// authConfig: newAuthConfig, +// isAuthenticated: true, +// organizationId: newAuthConfig?.organizationId || undefined, +// }); - logger.debug("Login successful", { - orgId: this.currentState.organizationId, - }); +// logger.debug("Login successful", { +// orgId: this.currentState.organizationId, +// }); - return this.getState(); - } catch (error: any) { - logger.error("Login failed:", error); - this.emit("error", error); - throw error; - } - } +// return this.getState(); +// } catch (error: any) { +// logger.error("Login failed:", error); +// this.emit("error", error); +// throw error; +// } +// } - /** - * Perform logout - */ - async logout(): Promise { - logger.debug("Logging out"); +// /** +// * Perform logout +// */ +// async logout(): Promise { +// logger.debug("Logging out"); - doLogout(); +// doLogout(); - this.setState({ - authConfig: null, - isAuthenticated: false, - organizationId: undefined, - }); +// this.setState({ +// authConfig: null, +// isAuthenticated: false, +// organizationId: undefined, +// }); - logger.debug("Logout complete"); - return this.getState(); - } +// logger.debug("Logout complete"); +// return this.getState(); +// } - /** - * Ensure organization is selected, prompting if necessary - */ - async ensureOrganization( - isHeadless: boolean = false, - ): Promise { - if (!this.currentState.authConfig) { - throw new Error("Not authenticated - cannot ensure organization"); - } +// /** +// * Ensure organization is selected, prompting if necessary +// */ +// async ensureOrganization( +// isHeadless: boolean = false, +// ): Promise { +// if (!this.currentState.authConfig) { +// throw new Error("Not authenticated - cannot ensure organization"); +// } - logger.debug("Ensuring organization is selected", { - currentOrgId: this.currentState.organizationId, - isHeadless, - }); +// logger.debug("Ensuring organization is selected", { +// currentOrgId: this.currentState.organizationId, +// isHeadless, +// }); - const updatedConfig = await ensureOrganization( - this.currentState.authConfig, - isHeadless, - ); +// const updatedConfig = await ensureOrganization( +// this.currentState.authConfig, +// isHeadless, +// ); - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: updatedConfig?.organizationId || undefined, - }); +// this.setState({ +// authConfig: updatedConfig, +// isAuthenticated: true, +// organizationId: updatedConfig?.organizationId || undefined, +// }); - logger.debug("Organization ensured", { - orgId: this.currentState.organizationId, - }); +// logger.debug("Organization ensured", { +// orgId: this.currentState.organizationId, +// }); - return this.getState(); - } +// return this.getState(); +// } - /** - * Switch to a different organization - */ - async switchOrganization( - organizationId: string | null, - ): Promise { - if ( - !this.currentState.authConfig || - !("userId" in this.currentState.authConfig) - ) { - throw new Error( - "Not authenticated with file-based auth - cannot switch organizations", - ); - } +// /** +// * Switch to a different organization +// */ +// async switchOrganization( +// organizationId: string | null, +// ): Promise { +// if ( +// !this.currentState.authConfig || +// !("userId" in this.currentState.authConfig) +// ) { +// throw new Error( +// "Not authenticated with file-based auth - cannot switch organizations", +// ); +// } - logger.debug("Switching organization", { - from: this.currentState.organizationId, - to: organizationId, - }); +// logger.debug("Switching organization", { +// from: this.currentState.organizationId, +// to: organizationId, +// }); - const authenticatedConfig = this.currentState - .authConfig as AuthenticatedConfig; +// const authenticatedConfig = this.currentState +// .authConfig as AuthenticatedConfig; - const updatedConfig: AuthenticatedConfig = { - ...authenticatedConfig, - organizationId, - }; +// const updatedConfig: AuthenticatedConfig = { +// ...authenticatedConfig, +// organizationId, +// }; - saveAuthConfig(updatedConfig); +// saveAuthConfig(updatedConfig); - this.setState({ - authConfig: updatedConfig, - isAuthenticated: true, - organizationId: organizationId || undefined, - }); +// this.setState({ +// authConfig: updatedConfig, +// isAuthenticated: true, +// organizationId: organizationId || undefined, +// }); - logger.debug("Organization switched", { - newOrgId: this.currentState.organizationId, - }); +// logger.debug("Organization switched", { +// newOrgId: this.currentState.organizationId, +// }); - return this.getState(); - } +// return this.getState(); +// } - /** - * Get available organizations for the current user - */ - async getAvailableOrganizations(): Promise< - { id: string; name: string }[] | null - > { - if (!this.currentState.isAuthenticated) { - return null; - } +// /** +// * Get available organizations for the current user +// */ +// async getAvailableOrganizations(): Promise< +// { id: string; name: string }[] | null +// > { +// if (!this.currentState.isAuthenticated) { +// return null; +// } - try { - return await listUserOrganizations(); - } catch (error: any) { - logger.error("Failed to list organizations:", error); - this.emit("error", error); - return null; - } - } +// try { +// return await listUserOrganizations(); +// } catch (error: any) { +// logger.error("Failed to list organizations:", error); +// this.emit("error", error); +// return null; +// } +// } - /** - * Check if the current user has multiple organizations available - */ - async hasMultipleOrganizations(): Promise { - const orgs = await this.getAvailableOrganizations(); - return orgs !== null && orgs.length > 0; - } +// /** +// * Check if the current user has multiple organizations available +// */ +// async hasMultipleOrganizations(): Promise { +// const orgs = await this.getAvailableOrganizations(); +// return orgs !== null && orgs.length > 0; +// } - /** - * Refresh auth state from disk (useful after external changes) - */ - async refresh(): Promise { - logger.debug("Refreshing auth state from disk"); - return this.reload(); - } -} +// /** +// * Refresh auth state from disk (useful after external changes) +// */ +// async refresh(): Promise { +// logger.debug("Refreshing auth state from disk"); +// return this.reload(); +// } +// } +export {}; diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 84d2ba5ae..e230b1bde 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -286,7 +286,11 @@ describe("ConfigService", () => { describe("getDependencies()", () => { test("should declare auth and apiClient dependencies", () => { - expect(service.getDependencies()).toEqual(["auth", "apiClient"]); + expect(service.getDependencies()).toEqual([ + "auth", + "apiClient", + "workflow", + ]); }); }); diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 149977edb..66a3289b6 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -32,7 +32,11 @@ export class ConfigService * Declare dependencies on other services */ getDependencies(): string[] { - return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT]; + return [ + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.WORKFLOW, + ]; } /** diff --git a/extensions/cli/src/services/ModeService.test.ts b/extensions/cli/src/services/ModeService.test.ts deleted file mode 100644 index 974826377..000000000 --- a/extensions/cli/src/services/ModeService.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { beforeEach, afterEach, describe, expect, vi, test } from "vitest"; - -import { ModeService } from "./ModeService.js"; - -describe("ModeService", () => { - let modeService: ModeService; - - beforeEach(() => { - // Reset singleton instance for each test - (ModeService as any).instance = undefined; - modeService = ModeService.getInstance(); - }); - - afterEach(() => { - // Clean up singleton instance - (ModeService as any).instance = undefined; - }); - - describe("State Management", () => { - test("should initialize with normal mode by default", async () => { - const state = await modeService.initialize({}); - - expect(state).toEqual({ - mode: "normal", - toolPermissionService: expect.any(Object), - }); - expect(modeService.getCurrentMode()).toBe("normal"); - }); - - test("should convert readonly flag to plan mode", async () => { - const state = await modeService.initialize({ readonly: true }); - - expect(state.mode).toBe("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - }); - - test("should convert auto flag to auto mode", async () => { - const state = await modeService.initialize({ auto: true }); - - expect(state.mode).toBe("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); - }); - - test("should initialize tool permission service with flags", async () => { - const state = await modeService.initialize({ - allow: ["testTool"], - exclude: ["badTool"], - }); - - const toolPermissionService = state.toolPermissionService; - expect(toolPermissionService).toBeDefined(); - expect(toolPermissionService.getState()).toBeDefined(); - expect(toolPermissionService.getCurrentMode()).toBe("normal"); - }); - }); - - describe("switchMode()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should switch from normal to plan mode", () => { - expect(modeService.getCurrentMode()).toBe("normal"); - - modeService.switchMode("plan"); - - expect(modeService.getCurrentMode()).toBe("plan"); - expect(modeService.getState().mode).toBe("plan"); - }); - - test("should switch from plan to auto mode", () => { - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); - - modeService.switchMode("auto"); - - expect(modeService.getCurrentMode()).toBe("auto"); - expect(modeService.getState().mode).toBe("auto"); - }); - - test("should switch back to normal mode", () => { - modeService.switchMode("plan"); - modeService.switchMode("normal"); - - expect(modeService.getCurrentMode()).toBe("normal"); - expect(modeService.getState().mode).toBe("normal"); - }); - - test("should update tool permission service when switching modes", () => { - const toolPermissionService = modeService.getToolPermissionService(); - const initialState = toolPermissionService.getState(); - - modeService.switchMode("auto"); - const newState = toolPermissionService.getState(); - - expect(newState.currentMode).toBe("auto"); - expect(newState.permissions.policies.length).toBeGreaterThan(0); - expect(newState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - }); - - test("should handle multiple mode switches correctly", () => { - // Start in normal - expect(modeService.getCurrentMode()).toBe("normal"); - - // Switch to plan - modeService.switchMode("plan"); - const planState = modeService.getToolPermissionService().getState(); - expect(planState.permissions.policies).toContainEqual({ - tool: "Write", - permission: "exclude", - }); - - // Switch to auto - modeService.switchMode("auto"); - const autoState = modeService.getToolPermissionService().getState(); - expect(autoState.permissions.policies).toHaveLength(1); - expect(autoState.permissions.policies[0]).toEqual({ - tool: "*", - permission: "allow", - }); - - // Back to normal - modeService.switchMode("normal"); - const normalState = modeService.getToolPermissionService().getState(); - expect(normalState.currentMode).toBe("normal"); - }); - }); - - describe("getAvailableModes()", () => { - beforeEach(async () => { - await modeService.initialize({}); - }); - - test("should return all available modes with descriptions", () => { - const modes = modeService.getAvailableModes(); - expect(modes).toHaveLength(3); - - const modeNames = modes.map((m) => m.mode); - expect(modeNames).toContain("normal"); - expect(modeNames).toContain("plan"); - expect(modeNames).toContain("auto"); - - // Check that all modes have descriptions - modes.forEach((mode) => { - expect(mode.description).toBeDefined(); - expect(mode.description.length).toBeGreaterThan(0); - }); - }); - }); - - describe("Singleton Behavior", () => { - test("should return the same instance", () => { - const instance1 = ModeService.getInstance(); - const instance2 = ModeService.getInstance(); - expect(instance1).toBe(instance2); - }); - - test("should maintain state across getInstance calls", async () => { - const instance1 = ModeService.getInstance(); - await instance1.initialize({}); - instance1.switchMode("plan"); - - const instance2 = ModeService.getInstance(); - expect(instance2.getCurrentMode()).toBe("plan"); - }); - }); - - describe("isReady()", () => { - test("should always return true for ModeService", () => { - // ModeService is always ready since it's a singleton - expect(modeService.isReady()).toBe(true); - }); - }); - - describe("Event Emission", () => { - let modeChangeListener: ReturnType; - let stateChangeListener: ReturnType; - - beforeEach(async () => { - await modeService.initialize({}); - modeChangeListener = vi.fn(); - stateChangeListener = vi.fn(); - modeService.on("modeChanged", modeChangeListener); - modeService.on("stateChanged", stateChangeListener); - }); - - afterEach(() => { - modeService.off("modeChanged", modeChangeListener); - modeService.off("stateChanged", stateChangeListener); - }); - - test("should emit modeChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should emit stateChanged event when mode switches", () => { - modeService.switchMode("plan"); - - expect(stateChangeListener).toHaveBeenCalledWith( - expect.objectContaining({ mode: "plan" }), - expect.objectContaining({ mode: "normal" }), - ); - }); - - test("should emit event with correct previous and new modes", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("auto"); - - expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan"); - expect(modeChangeListener).toHaveBeenCalledTimes(1); - expect(stateChangeListener).toHaveBeenCalledTimes(1); - }); - - test("should not emit event when switching to same mode", () => { - modeService.switchMode("plan"); - modeChangeListener.mockClear(); - stateChangeListener.mockClear(); - - modeService.switchMode("plan"); - - expect(modeChangeListener).not.toHaveBeenCalled(); - // stateChanged might still be called due to setState, but modeChanged should not - }); - }); - - describe("Integration with ToolPermissionService", () => { - beforeEach(async () => { - await modeService.initialize({ - allow: ["Read"], - exclude: ["dangerous_tool"], - }); - }); - - test("should pass initialization args to ToolPermissionService", () => { - const toolService = modeService.getToolPermissionService(); - const state = toolService.getState(); - - // The state should have processed the allow/exclude rules - expect(state.permissions.policies).toBeDefined(); - expect(state.currentMode).toBe("normal"); - }); - - test("should maintain ToolPermissionService reference", () => { - const toolService1 = modeService.getToolPermissionService(); - const toolService2 = modeService.getToolPermissionService(); - - expect(toolService1).toBe(toolService2); - }); - }); -}); diff --git a/extensions/cli/src/services/ModeService.ts b/extensions/cli/src/services/ModeService.ts deleted file mode 100644 index b066af870..000000000 --- a/extensions/cli/src/services/ModeService.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { PermissionMode } from "../permissions/types.js"; -import { logger } from "../util/logger.js"; - -import { BaseService } from "./BaseService.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; - -export interface ModeServiceState { - mode: PermissionMode; - toolPermissionService: ToolPermissionService; -} - -/** - * Global service for managing permission modes - * Provides a singleton interface for mode switching - */ -export class ModeService extends BaseService { - private static instance: ModeService; - - private constructor() { - const toolPermissionService = new ToolPermissionService(); - super("ModeService", { - mode: "normal", - toolPermissionService, - }); - - // Increase max listeners since ModeService is a singleton that can have - // multiple subscribers (UI components, tests, etc.) - this.setMaxListeners(100); - } - - public static getInstance(): ModeService { - if (!ModeService.instance) { - ModeService.instance = new ModeService(); - } - return ModeService.instance; - } - - /** - * Initialize the mode service with command line arguments - */ - async doInitialize(args: { - readonly?: boolean; - auto?: boolean; - allow?: string[]; - ask?: string[]; - exclude?: string[]; - isHeadless?: boolean; - }): Promise { - // Convert legacy flags to mode - let mode: PermissionMode = "normal"; - if (args.readonly) { - mode = "plan"; // Legacy flag maps directly to plan mode - } else if (args.auto) { - mode = "auto"; // Auto flag maps to auto mode - } - - this.currentState.toolPermissionService.initializeSync({ - allow: args.allow, - ask: args.ask, - exclude: args.exclude, - mode, - isHeadless: args.isHeadless, - }); - - logger.debug(`ModeService initialized with mode: ${mode}`); - - return { - mode, - toolPermissionService: this.currentState.toolPermissionService, - }; - } - - /** - * Switch to a different mode - */ - public switchMode(mode: PermissionMode): void { - const previousMode = this.currentState.mode; - this.currentState.toolPermissionService.switchMode(mode); - - this.setState({ mode }); - - logger.info(`Switched to ${mode} mode`); - - // Emit mode change event for immediate UI updates - if (previousMode !== mode) { - this.emit("modeChanged", mode, previousMode); - } - } - - /** - * Get the current mode - */ - public getCurrentMode(): PermissionMode { - return this.currentState.mode; - } - - /** - * Get the tool permission service instance - */ - public getToolPermissionService(): ToolPermissionService { - return this.currentState.toolPermissionService; - } - - /** - * Get available modes with descriptions - */ - public getAvailableModes(): Array<{ - mode: PermissionMode; - description: string; - }> { - return [ - { - mode: "normal", - description: "Default mode - follows configured permission policies", - }, - { - mode: "plan", - description: "Planning mode - only allow read-only tools for analysis", - }, - { - mode: "auto", - description: "Automatically allow all tools without asking", - }, - ]; - } - - /** - * Override cleanup to properly clean up nested ToolPermissionService - */ - override async cleanup(): Promise { - await this.currentState.toolPermissionService.cleanup(); - await super.cleanup(); - } - - /** - * Override isReady since this is a singleton with immediate availability - */ - override isReady(): boolean { - return true; - } -} - -// Export singleton instance -export const modeService = ModeService.getInstance(); diff --git a/extensions/cli/src/services/ModelService.ts b/extensions/cli/src/services/ModelService.ts index c4da9e331..e09c65d49 100644 --- a/extensions/cli/src/services/ModelService.ts +++ b/extensions/cli/src/services/ModelService.ts @@ -99,7 +99,6 @@ export class ModelService }); const llmApi = createLlmApi(selectedModel, authConfig); - if (!llmApi) { throw new Error(`Failed to initialize LLM with ${modelSource} model`); } diff --git a/extensions/cli/src/services/ServiceContainer.ts b/extensions/cli/src/services/ServiceContainer.ts index adaaa1072..d12acf351 100644 --- a/extensions/cli/src/services/ServiceContainer.ts +++ b/extensions/cli/src/services/ServiceContainer.ts @@ -2,7 +2,7 @@ import { EventEmitter } from "events"; import { logger } from "../util/logger.js"; -import { ServiceResult, ServiceState } from "./types.js"; +import { type ServiceResult, type ServiceState } from "./types.js"; /** * Central service container that manages service lifecycle and dependencies diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts index a17894ee9..c76bbb8b9 100644 --- a/extensions/cli/src/services/SystemMessageService.test.ts +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -1,7 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { modeService } from "./ModeService.js"; import { SystemMessageService } from "./SystemMessageService.js"; +import { services } from "./index.js"; +const toolPermissionService = services.toolPermissions; // Mock the systemMessage module vi.mock("../systemMessage.js", () => ({ @@ -71,7 +72,7 @@ describe("SystemMessageService", () => { constructSystemMessageMock.mockResolvedValue("Test system message"); await service.initialize(config); - const message = await service.getSystemMessage(); + const message = await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( ["rule1"], @@ -81,25 +82,6 @@ describe("SystemMessageService", () => { ); expect(message).toBe("Test system message"); }); - - it("should use updated mode when mode changes", async () => { - constructSystemMessageMock.mockResolvedValue("Updated system message"); - - await service.initialize({}); - - // Simulate mode change - modeService.emit("modeChanged", "plan", "normal"); - - const message = await service.getSystemMessage(); - - expect(constructSystemMessageMock).toHaveBeenCalledWith( - undefined, - undefined, - undefined, - "plan", - ); - expect(message).toBe("Updated system message"); - }); }); describe("updateConfig", () => { @@ -114,7 +96,7 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( ["rule1"], @@ -135,7 +117,7 @@ describe("SystemMessageService", () => { }); constructSystemMessageMock.mockResolvedValue("Updated message"); - await service.getSystemMessage(); + await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( ["rule2", "rule3"], @@ -146,31 +128,6 @@ describe("SystemMessageService", () => { }); }); - describe("mode tracking", () => { - it("should track current mode from ModeService", async () => { - await service.initialize({}); - - expect(service.getCurrentMode()).toBe("normal"); - - // Simulate mode change - modeService.emit("modeChanged", "auto", "normal"); - - expect(service.getCurrentMode()).toBe("auto"); - }); - - it("should initialize with current mode from ModeService", async () => { - // Mock modeService.getCurrentMode - vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan"); - - const newService = new SystemMessageService(); - await newService.initialize({}); - - expect(newService.getCurrentMode()).toBe("plan"); - - await newService.cleanup(); - }); - }); - describe("error handling", () => { it("should handle constructSystemMessage errors gracefully", async () => { constructSystemMessageMock.mockRejectedValue( @@ -179,7 +136,7 @@ describe("SystemMessageService", () => { await service.initialize({}); - await expect(service.getSystemMessage()).rejects.toThrow( + await expect(service.getSystemMessage("normal")).rejects.toThrow( "Failed to construct", ); }); diff --git a/extensions/cli/src/services/SystemMessageService.ts b/extensions/cli/src/services/SystemMessageService.ts index 2711f6990..1f2bbf2eb 100644 --- a/extensions/cli/src/services/SystemMessageService.ts +++ b/extensions/cli/src/services/SystemMessageService.ts @@ -3,7 +3,7 @@ import { constructSystemMessage } from "../systemMessage.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; -import { modeService } from "./ModeService.js"; +import { SERVICE_NAMES } from "./types.js"; export interface SystemMessageServiceState { additionalRules?: string[]; @@ -16,26 +16,8 @@ export interface SystemMessageServiceState { * Provides fresh system messages that reflect current mode and configuration */ export class SystemMessageService extends BaseService { - private currentMode: PermissionMode = "normal"; - constructor() { super("SystemMessageService", {}); - - // Listen to mode changes from ModeService - this.setupModeListener(); - } - - /** - * Set up listener for mode changes - */ - private setupModeListener(): void { - modeService.on("modeChanged", (newMode: PermissionMode) => { - logger.debug(`SystemMessageService: Mode changed to ${newMode}`); - this.currentMode = newMode; - }); - - // Initialize current mode - this.currentMode = modeService.getCurrentMode(); } /** @@ -64,24 +46,28 @@ export class SystemMessageService extends BaseService /** * Get a fresh system message with current mode and configuration */ - public async getSystemMessage(): Promise { + public async getSystemMessage(currentMode: PermissionMode): Promise { const { additionalRules, format, headless } = this.currentState; const systemMessage = await constructSystemMessage( additionalRules, format, headless, - this.currentMode, + currentMode, ); logger.debug("Generated fresh system message", { - mode: this.currentMode, + mode: currentMode, messageLength: systemMessage.length, }); return systemMessage; } + getDependencies(): string[] { + return [SERVICE_NAMES.TOOL_PERMISSIONS]; + } + /** * Update configuration that affects system message */ @@ -93,14 +79,4 @@ export class SystemMessageService extends BaseService logger.debug("SystemMessageService config updated", config); } - - /** - * Get the current mode being used for system messages - */ - public getCurrentMode(): PermissionMode { - return this.currentMode; - } } - -// Export singleton instance -export const systemMessageService = new SystemMessageService(); diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index e682bc9dc..dc754aad0 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -9,10 +9,18 @@ import { } from "../permissions/types.js"; import { logger } from "../util/logger.js"; -import { BaseService } from "./BaseService.js"; +import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; +export interface InitializeToolServiceOverrides { + allow?: string[]; + ask?: string[]; + exclude?: string[]; + mode?: PermissionMode; + isHeadless?: boolean; +} + export interface ToolPermissionServiceState { permissions: ToolPermissions; currentMode: PermissionMode; @@ -25,7 +33,10 @@ export interface ToolPermissionServiceState { /** * Service for managing tool permissions with a single source of truth */ -export class ToolPermissionService extends BaseService { +export class ToolPermissionService + extends BaseService + implements ServiceWithDependencies +{ constructor() { super("ToolPermissionService", { permissions: { policies: [] }, @@ -35,19 +46,36 @@ export class ToolPermissionService extends BaseService, + ): void { + super.setState(newState); + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, this.currentState); + } + + /** + * Declare dependencies on other services + */ + getDependencies(): string[] { + return [SERVICE_NAMES.WORKFLOW]; + } + /** * Generate workflow-specific policies if a workflow is active */ - private generateWorkflowPolicies(): undefined | ToolPermissionPolicy[] { - const workflowResult = serviceContainer.getSync( - SERVICE_NAMES.WORKFLOW, - ); - if (!workflowResult?.value?.workflowFile?.tools) { + private generateWorkflowPolicies( + workflowServiceState?: WorkflowServiceState, + ): undefined | ToolPermissionPolicy[] { + if (!workflowServiceState?.workflowFile?.tools) { return undefined; } const parsedTools = parseWorkflowTools( - workflowResult.value.workflowFile.tools, + workflowServiceState.workflowFile.tools, ); if (parsedTools.tools.length === 0) { return undefined; @@ -134,13 +162,10 @@ export class ToolPermissionService extends BaseService { - // Ensure permissions.yaml exists before loading + async doInitialize( + runtimeOverrides?: InitializeToolServiceOverrides, + workflowServiceState?: WorkflowServiceState, + ): Promise { await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides); + return this.initializeSync(runtimeOverrides, workflowServiceState); } /** @@ -232,13 +254,12 @@ export class ToolPermissionService extends BaseService { + return [ + { + mode: "normal", + description: "Default mode - follows configured permission policies", + }, + { + mode: "plan", + description: "Planning mode - only allow read-only tools for analysis", + }, + { + mode: "auto", + description: "Automatically allow all tools without asking", + }, + ]; + } } diff --git a/extensions/cli/src/services/index.initialization.test.ts b/extensions/cli/src/services/index.initialization.test.ts index 7aadcc57d..4d480dfcb 100644 --- a/extensions/cli/src/services/index.initialization.test.ts +++ b/extensions/cli/src/services/index.initialization.test.ts @@ -3,21 +3,13 @@ import { beforeEach, describe, expect, it } from "vitest"; import { serviceContainer } from "./ServiceContainer.js"; import type { ToolPermissionServiceState } from "./ToolPermissionService.js"; -import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js"; +import { getServiceSync, initializeServices, SERVICE_NAMES } from "./index.js"; describe("Service Initialization", () => { beforeEach(() => { // Clean up service container state - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - services.forEach((service) => { + Object.keys(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 6978ced90..7a5cf31b6 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,9 +1,7 @@ import { vi } from "vitest"; -import { modeService } from "./ModeService.js"; -import { serviceContainer } from "./ServiceContainer.js"; - -import { initializeServices } from "./index.js"; +import { initializeServices, services } from "./index.js"; +import { WorkflowService } from "./WorkflowService.js"; // Mock the onboarding module vi.mock("../onboarding.js", () => ({ @@ -17,45 +15,11 @@ vi.mock("../auth/workos.js", () => ({ })); describe("initializeServices", () => { - let mockModeService: any; - let mockServiceContainer: any; + // let mockToolPermissionsService: any; beforeEach(() => { // Reset all mocks vi.clearAllMocks(); - - // Create mock mode service - mockModeService = { - initialize: vi.fn(), - getCurrentMode: vi.fn(), - getToolPermissionService: vi.fn().mockReturnValue({ - getState: vi.fn().mockReturnValue({ - currentMode: "normal", - isHeadless: false, - permissions: { policies: [] }, - }), - }), - }; - - // Create mock service container - mockServiceContainer = { - registerValue: vi.fn(), - register: vi.fn(), - initializeAll: vi.fn().mockResolvedValue(undefined), - }; - - // Set up mocks - (modeService as any).initialize = mockModeService.initialize; - (modeService as any).getCurrentMode = mockModeService.getCurrentMode; - (modeService as any).getToolPermissionService = - mockModeService.getToolPermissionService; - - // Mock serviceContainer methods - (serviceContainer as any).registerValue = - mockServiceContainer.registerValue; - (serviceContainer as any).register = mockServiceContainer.register; - (serviceContainer as any).initializeAll = - mockServiceContainer.initializeAll; }); afterEach(() => { @@ -63,28 +27,8 @@ describe("initializeServices", () => { }); describe("mode conversion", () => { - it("should pass only readonly flag for plan mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "plan", - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - readonly: true, - isHeadless: true, - // auto should NOT be set - }); - }); - it("should pass only auto flag for auto mode", async () => { + const spy = vi.spyOn(services.toolPermissions, "initialize"); await initializeServices({ headless: true, // Skip onboarding toolPermissionOverrides: { @@ -95,63 +39,21 @@ describe("initializeServices", () => { }, }); - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - auto: true, - isHeadless: true, - // readonly should NOT be set - }); - }); - - it("should pass no mode flags for normal mode", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - mode: "normal", + expect(spy).toHaveBeenCalledWith( + { allow: ["tool1"], ask: ["tool2"], exclude: ["tool3"], + mode: "auto", + isHeadless: true, }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should pass no mode flags when mode is undefined", async () => { - await initializeServices({ - headless: true, // Skip onboarding - toolPermissionOverrides: { - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], + { + slug: null, + workflowFile: null, + workflowModelName: null, + workflowService: expect.any(WorkflowService), }, - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - allow: ["tool1"], - ask: ["tool2"], - exclude: ["tool3"], - isHeadless: true, - // Neither readonly nor auto should be set - }); - }); - - it("should call initialize with defaults when no toolPermissionOverrides provided", async () => { - await initializeServices({ - headless: true, // Skip onboarding - }); - - expect(mockModeService.initialize).toHaveBeenCalledWith({ - isHeadless: true, - }); + ); }); }); }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index f75fc1e21..b73164330 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -9,11 +9,14 @@ import { ConfigService } from "./ConfigService.js"; import { FileIndexService } from "./FileIndexService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; -import { modeService } from "./ModeService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { StorageSyncService } from "./StorageSyncService.js"; -import { systemMessageService } from "./SystemMessageService.js"; +import { SystemMessageService } from "./SystemMessageService.js"; +import { + InitializeToolServiceOverrides, + ToolPermissionService, +} from "./ToolPermissionService.js"; import { ApiClientServiceState, AuthServiceState, @@ -38,6 +41,8 @@ const chatHistoryService = new ChatHistoryService(); const updateService = new UpdateService(); const storageSyncService = new StorageSyncService(); const workflowService = new WorkflowService(); +const toolPermissionService = new ToolPermissionService(); +const systemMessageService = new SystemMessageService(); /** * Initialize all services and register them with the service container @@ -79,46 +84,48 @@ export async function initializeServices( commandOptions.config = CONFIG_PATH; } - // Initialize mode service with tool permission overrides - if (initOptions.toolPermissionOverrides) { - const overrides = { ...initOptions.toolPermissionOverrides }; + serviceContainer.register( + SERVICE_NAMES.WORKFLOW, + () => workflowService.initialize(commandOptions.workflow), + [], + ); - // Convert mode to boolean flags for ModeService - const initArgs: Parameters[0] = { - allow: overrides.allow, - ask: overrides.ask, - exclude: overrides.exclude, - isHeadless: initOptions.headless, - }; - - // Only set the boolean flag that corresponds to the mode - if (overrides.mode === "plan") { - initArgs.readonly = true; - } else if (overrides.mode === "auto") { - initArgs.auto = true; - } - // If mode is "normal" or undefined, no flags are set - - await modeService.initialize(initArgs); - } else { - // Even if no overrides, we need to initialize with defaults - await modeService.initialize({ - isHeadless: initOptions.headless, - }); - } - - // Register the TOOL_PERMISSIONS service with immediate value - // Since ToolPermissionService is already initialized synchronously in ModeService, - // we can register it as a ready value instead of a factory - const toolPermissionState = modeService.getToolPermissionService().getState(); - logger.debug("Registering TOOL_PERMISSIONS with state:", { - currentMode: toolPermissionState.currentMode, - isHeadless: toolPermissionState.isHeadless, - policyCount: toolPermissionState.permissions.policies.length, - }); - serviceContainer.registerValue( + serviceContainer.register( SERVICE_NAMES.TOOL_PERMISSIONS, - toolPermissionState, + async () => { + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + // Initialize mode service with tool permission overrides + if (initOptions.toolPermissionOverrides) { + const overrides = { ...initOptions.toolPermissionOverrides }; + + // Convert mode to boolean flags for ModeService + const initArgs: InitializeToolServiceOverrides = { + allow: overrides.allow, + ask: overrides.ask, + exclude: overrides.exclude, + isHeadless: initOptions.headless, + }; + + // Only set the boolean flag that corresponds to the mode + if (overrides.mode) { + initArgs.mode = overrides.mode; + } + // If mode is "normal" or undefined, no flags are set + return await toolPermissionService.initialize(initArgs, workflowState); + } else { + // Even if no overrides, we need to initialize with defaults + return await toolPermissionService.initialize( + { + isHeadless: initOptions.headless, + }, + workflowState, + ); + } + }, + [SERVICE_NAMES.WORKFLOW], ); // Initialize SystemMessageService with command options @@ -130,7 +137,7 @@ export async function initializeServices( format: (commandOptions as any).format, // format option from CLI headless: initOptions.headless, }), - [], // No dependencies + [SERVICE_NAMES.TOOL_PERMISSIONS], ); serviceContainer.register( @@ -159,9 +166,10 @@ export async function initializeServices( serviceContainer.register( SERVICE_NAMES.CONFIG, async () => { - const [authState, apiClientState] = await Promise.all([ + const [authState, apiClientState, workflowState] = await Promise.all([ serviceContainer.get(SERVICE_NAMES.AUTH), serviceContainer.get(SERVICE_NAMES.API_CLIENT), + serviceContainer.get(SERVICE_NAMES.WORKFLOW), ]); // Ensure organization is selected if authenticated @@ -207,9 +215,10 @@ export async function initializeServices( finalAuthState.organizationId || null, apiClientState.apiClient, commandOptions, + workflowState, ); }, - [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies ); serviceContainer.register( @@ -273,12 +282,6 @@ export async function initializeServices( [], // No dependencies for now, but could depend on SESSION in future ); - serviceContainer.register( - SERVICE_NAMES.WORKFLOW, - () => workflowService.initialize(commandOptions.workflow), - [], - ); - // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -335,13 +338,13 @@ export const services = { apiClient: apiClientService, mcp: mcpService, fileIndex: fileIndexService, - mode: modeService, resourceMonitoring: resourceMonitoringService, systemMessage: systemMessageService, chatHistory: chatHistoryService, updateService: updateService, storageSync: storageSyncService, workflow: workflowService, + toolPermissions: toolPermissionService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 51d0e46a6..9ce7b355b 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -10,9 +10,9 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { AuthConfig } from "../auth/workos.js"; import { BaseCommandOptions } from "../commands/BaseCommandOptions.js"; -import { PermissionMode, ToolPermissions } from "../permissions/types.js"; +import { PermissionMode } from "../permissions/types.js"; -import { MCPService } from "./MCPService.js"; +import { type MCPService } from "./MCPService.js"; import { WorkflowService } from "./WorkflowService.js"; /** @@ -109,13 +109,6 @@ export interface ApiClientServiceState { apiClient: DefaultApiInterface | null; } -export interface ToolPermissionServiceState { - permissions: ToolPermissions; - currentMode: PermissionMode; - modePolicyCount?: number; - originalPolicies?: ToolPermissions; -} - export interface StorageSyncServiceState { isEnabled: boolean; storageId?: string; diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 4469dc179..6c2f693a8 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -4,7 +4,6 @@ import { ConfigEnhancer } from "../configEnhancer.js"; import { ModelService } from "./ModelService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { ToolPermissionService } from "./ToolPermissionService.js"; import { SERVICE_NAMES } from "./types.js"; import { WorkflowService } from "./WorkflowService.js"; @@ -46,7 +45,6 @@ vi.mock("../auth/workos.js", () => ({ describe("Workflow Integration Tests", () => { let workflowService: WorkflowService; let modelService: ModelService; - let toolPermissionService: ToolPermissionService; let configEnhancer: ConfigEnhancer; let mockLoadPackageFromHub: any; let mockLoadPackagesFromHub: any; @@ -100,7 +98,6 @@ describe("Workflow Integration Tests", () => { // Create service instances workflowService = new WorkflowService(); modelService = new ModelService(); - toolPermissionService = new ToolPermissionService(); configEnhancer = new ConfigEnhancer(); // Mock service container diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index f5a9e74bd..78f9bcc7b 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -4,22 +4,16 @@ import { SERVICE_NAMES, initializeServices, serviceContainer, + services, } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; import { getAllTools } from "./handleToolCalls.js"; describe("streamChatResponse - Mode Switch During Streaming", () => { + const toolPermissionService = services.toolPermissions; beforeEach(async () => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; + const services = Object.keys(SERVICE_NAMES); services.forEach((service) => { (serviceContainer as any).services.delete(service); @@ -46,10 +40,10 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { expect(toolNames).toContain("Edit"); // Switch to plan mode (simulating Shift+Tab during streaming) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // Update the service container (this is what UserInput.tsx does) - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Recompute tools - should now exclude write tools @@ -68,25 +62,25 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { test("getAllTools reflects current mode immediately", async () => { // Start in normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); let tools = await getAllTools(); expect(tools.map((t) => t.function.name)).toContain("Write"); // Switch to plan mode - modeService.switchMode("plan"); - let updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("plan"); + let updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // getAllTools should immediately reflect the new mode tools = await getAllTools(); expect(tools.map((t) => t.function.name)).not.toContain("Write"); // Switch to auto mode - modeService.switchMode("auto"); - updatedState = modeService.getToolPermissionService().getState(); + toolPermissionService.switchMode("auto"); + updatedState = toolPermissionService.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); - expect(modeService.getCurrentMode()).toBe("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // getAllTools should immediately reflect auto mode (all tools allowed) tools = await getAllTools(); diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index a59fa8cf7..3bcbf43a4 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -8,9 +8,7 @@ import type { ChatCompletionTool, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; -import { systemMessageService } from "../services/SystemMessageService.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { services } from "../services/index.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { ToolCall } from "../tools/index.js"; @@ -157,7 +155,9 @@ export async function processStreamingResponse( } // Get fresh system message and inject it - const systemMessage = await systemMessageService.getSystemMessage(); + const systemMessage = await services.systemMessage.getSystemMessage( + services.toolPermissions.getState().currentMode, + ); const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( chatHistory, systemMessage, @@ -337,10 +337,7 @@ export async function streamChatResponse( hasCallbacks: !!callbacks, }); - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; + const isHeadless = services.toolPermissions.isHeadless(); let fullResponse = ""; let finalResponse = ""; @@ -399,7 +396,6 @@ export async function streamChatResponse( llmApi, abortController, callbacks, - isHeadless, tools, }); diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index 4f19c97f6..15f797dfc 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -8,6 +8,7 @@ const { constructSystemMessage } = await import("./systemMessage.js"); vi.mock("./services/ServiceContainer.js", () => ({ serviceContainer: { get: vi.fn().mockResolvedValue({ config: { rules: [] } }), + set: vi.fn(), }, })); diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 96f1e8e97..9acd01085 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -7,11 +7,11 @@ import { Minimatch } from "minimatch"; import { processRule } from "./hubLoader.js"; import { PermissionMode } from "./permissions/types.js"; -import { modeService } from "./services/ModeService.js"; +import { services } from "./services/index.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; - +const toolPermissionService = services.toolPermissions; /** * Check if current directory is a git repository */ @@ -167,7 +167,7 @@ export async function constructSystemMessage( processedRules.push(...configYamlRules); // Get current mode if not provided - const currentMode = mode ?? modeService.getCurrentMode(); + const currentMode = mode ?? toolPermissionService.getCurrentMode(); // Construct the comprehensive system message let systemMessage = baseSystemMessage; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 36837f233..c185fa57b 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -8,8 +8,8 @@ import { MCPServiceState, SERVICE_NAMES, serviceContainer, + services, } from "../services/index.js"; -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import type { ModelServiceState } from "../services/types.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; @@ -58,17 +58,8 @@ export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; function getDynamicTools(): Tool[] { const dynamicTools: Tool[] = []; - // Add headless-specific tools if in headless mode - try { - const serviceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - const isHeadless = serviceResult.value?.isHeadless ?? false; - if (isHeadless) { - dynamicTools.push(exitTool); - } - } catch { - // Service not ready yet, no dynamic tools + if (services.toolPermissions.isHeadless()) { + dynamicTools.push(exitTool); } // Add beta status tool if --beta-status-tool flag is present diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 8f8f24226..64982b942 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -18,6 +18,7 @@ import { } from "../services/types.js"; import { logger } from "../util/logger.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { ActionStatus } from "./components/ActionStatus.js"; import { BottomStatusBar } from "./components/BottomStatusBar.js"; import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; @@ -28,7 +29,6 @@ import { useChat } from "./hooks/useChat.js"; import { useContextPercentage } from "./hooks/useContextPercentage.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { - useCurrentMode, useIntroMessage, useLoginHandlers, useSelectors, @@ -95,7 +95,16 @@ function useTUIChatServices(remoteUrl?: string) { mcp: MCPServiceState; apiClient: ApiClientServiceState; update: UpdateServiceState; - }>(["auth", "config", "model", "mcp", "apiClient", "update"]); + toolPermissions: ToolPermissionServiceState; + }>([ + "auth", + "config", + "model", + "mcp", + "apiClient", + "update", + "toolPermissions", + ]); return { services, allServicesReady, isRemoteMode }; } @@ -162,9 +171,6 @@ const TUIChat: React.FC = ({ allServicesReady, ); - // State for current mode (for hiding cwd in plan/auto modes) - const currentMode = useCurrentMode(); - // Use login handlers const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( navigateTo, @@ -379,7 +385,7 @@ const TUIChat: React.FC = ({ {/* Free trial status and Continue CLI info - always show */} { beforeEach(() => { // Reset to normal mode for each test - modeService.initialize({}); + toolPermissionService.initialize({}); }); describe("mode cycling logic", () => { it("should cycle through modes in correct order", () => { // Initially should be normal mode - expect(modeService.getCurrentMode()).toBe("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); // Cycle to plan - modeService.switchMode("plan"); - expect(modeService.getCurrentMode()).toBe("plan"); + toolPermissionService.switchMode("plan"); + expect(toolPermissionService.getCurrentMode()).toBe("plan"); // Cycle to auto - modeService.switchMode("auto"); - expect(modeService.getCurrentMode()).toBe("auto"); + toolPermissionService.switchMode("auto"); + expect(toolPermissionService.getCurrentMode()).toBe("auto"); // Cycle back to normal - modeService.switchMode("normal"); - expect(modeService.getCurrentMode()).toBe("normal"); + toolPermissionService.switchMode("normal"); + expect(toolPermissionService.getCurrentMode()).toBe("normal"); }); it("should cycle through all modes sequentially", () => { @@ -32,8 +32,8 @@ describe("UserInput Keyboard Shortcuts", () => { // Test cycling through all modes for (let i = 0; i < modes.length * 2; i++) { const expectedMode = modes[i % modes.length]; - modeService.switchMode(expectedMode); - expect(modeService.getCurrentMode()).toBe(expectedMode); + toolPermissionService.switchMode(expectedMode); + expect(toolPermissionService.getCurrentMode()).toBe(expectedMode); } }); }); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index f1726f457..834bd68e4 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -7,8 +7,11 @@ import { getAllSlashCommands } from "../commands/commands.js"; import { useServices } from "../hooks/useService.js"; import type { PermissionMode } from "../permissions/types.js"; import type { FileIndexServiceState } from "../services/FileIndexService.js"; -import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; -import { modeService } from "../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../services/index.js"; import { messageQueue } from "../stream/messageQueue.js"; import { InputHistory } from "../util/inputHistory.js"; @@ -190,17 +193,17 @@ const UserInput: React.FC = ({ // Cycle through permission modes const cycleModes = async () => { const modes: PermissionMode[] = ["normal", "plan", "auto"]; - const currentMode = modeService.getCurrentMode(); + const currentMode = services.toolPermissions.getCurrentMode(); const currentIndex = modes.indexOf(currentMode); const nextIndex = (currentIndex + 1) % modes.length; const nextMode = modes[nextIndex]; - modeService.switchMode(nextMode); + services.toolPermissions.switchMode(nextMode); // Update the service container with the new tool permissions state // Since TOOL_PERMISSIONS was registered with registerValue(), we need to // update its value directly rather than reloading from a factory - const updatedState = modeService.getToolPermissionService().getState(); + const updatedState = services.toolPermissions.getState(); serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Show a brief indicator of the mode change diff --git a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx index 1b60203c9..f46bab262 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx @@ -1,21 +1,6 @@ -import { vi, beforeEach, describe, it, expect } from "vitest"; - -// Mock the services -const mockToolPermissionService = { - reloadPermissions: vi.fn(), - getState: vi.fn(), - getCurrentMode: vi.fn(() => "normal"), -}; - -const mockServices = { - mode: { - getToolPermissionService: vi.fn(() => mockToolPermissionService), - }, -}; - -vi.mock("../../services/index.js", () => ({ - services: mockServices, -})); +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { services } from "../../services/index.js"; +vi.mock("../../services/index.js"); // Mock the permission system vi.mock("../../permissions/policyWriter.js", () => ({ @@ -63,7 +48,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This is the key part we're testing - reload should be called - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Handle errors gracefully } @@ -76,7 +61,7 @@ describe("Permission Policy Reload Workflow", () => { expect(addPolicyToYaml).toHaveBeenCalledWith( "tool: Edit\npermission: allow", ); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); }); it("should handle permission reload failure gracefully", async () => { @@ -90,7 +75,7 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock reloadPermissions to fail - mockToolPermissionService.reloadPermissions.mockRejectedValue( + vi.mocked(services.toolPermissions.reloadPermissions).mockRejectedValue( new Error("Reload failed"), ); @@ -118,7 +103,7 @@ describe("Permission Policy Reload Workflow", () => { await addPolicyToYaml(policyRule); // This should fail but not break the flow - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { // Error should be caught and handled gracefully errorCaught = true; @@ -127,7 +112,7 @@ describe("Permission Policy Reload Workflow", () => { // Verify that despite the reload failure, the policy was still created expect(addPolicyToYaml).toHaveBeenCalled(); - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); expect(errorCaught).toBe(true); }); @@ -142,7 +127,9 @@ describe("Permission Policy Reload Workflow", () => { vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); // Mock successful reload - mockToolPermissionService.reloadPermissions.mockResolvedValue(undefined); + vi.mocked(services.toolPermissions.reloadPermissions).mockResolvedValue( + undefined, + ); const mockActiveRequest = { toolName: "Edit", @@ -167,13 +154,13 @@ describe("Permission Policy Reload Workflow", () => { ); await addPolicyToYaml(policyRule); - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } // AFTER: Policy is now active without restart // Next time user tries to edit a file, it should be automatically allowed - expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); + expect(services.toolPermissions.reloadPermissions).toHaveBeenCalled(); // This represents the improvement: the new policy takes effect immediately // without requiring the user to restart the Continue CLI diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx index 77b8161ba..c7ab739e5 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -4,11 +4,14 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { getAllTools } from "src/stream/handleToolCalls.js"; -import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; -import { modeService } from "../../services/ModeService.js"; +import { + SERVICE_NAMES, + serviceContainer, + services, +} from "../../services/index.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; - +const toolPermissionService = services.toolPermissions; describe("TUIChat - Plan Mode Bug Reproduction", () => { let context: any; @@ -20,7 +23,9 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { }); // Ensure mode service is properly initialized in normal mode - await modeService.initialize({}); + await toolPermissionService.doInitialize({ + mode: "normal", + }); }); afterEach(() => { @@ -142,10 +147,10 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { // that causes the actual bug in production // First, set up a realistic service state (not mocked) - await modeService.initialize({ isHeadless: false }); + await toolPermissionService.initialize({ isHeadless: false }); // Register the tool permissions service like the real app does - const initialState = modeService.getToolPermissionService().getState(); + const initialState = toolPermissionService.getState(); serviceContainer.registerValue( SERVICE_NAMES.TOOL_PERMISSIONS, initialState, @@ -155,7 +160,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { expect(() => getAllTools()).not.toThrow(); // Switch modes WITHOUT updating the service container (this simulates the bug) - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); // The service container still has the old state, so getAllTools() should not find // the updated state with plan mode permissions. However, since the ToolPermissionService @@ -172,9 +177,5 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => { const tools = getAllTools(); expect(tools).toBeDefined(); expect(Array.isArray(tools)).toBe(true); - - // But the tools returned will be for "normal" mode, not "plan" mode - // In plan mode, many tools should be excluded, but with stale normal state, all tools are available - const planModeState = modeService.getToolPermissionService().getState(); }); }); diff --git a/extensions/cli/src/ui/components/ModeIndicator.test.tsx b/extensions/cli/src/ui/components/ModeIndicator.test.tsx index a341e826f..7e1af759a 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.test.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.test.tsx @@ -1,15 +1,20 @@ import { render } from "ink-testing-library"; import React from "react"; -import { describe, expect, it, beforeEach } from "vitest"; - -import { modeService } from "../../services/ModeService.js"; +import { beforeEach, describe, expect, it } from "vitest"; +import { initializeServices, services } from "src/services/index.js"; import { ModeIndicator } from "./ModeIndicator.js"; describe("ModeIndicator", () => { - beforeEach(() => { + const toolPermissionService = services.toolPermissions; + beforeEach(async () => { // Reset to normal mode for each test - modeService.initialize({}); + await initializeServices({ + headless: true, + toolPermissionOverrides: { + mode: "normal", + }, + }); }); describe("mode display", () => { @@ -29,13 +34,13 @@ describe("ModeIndicator", () => { }); it("should use current mode from service when no mode prop provided", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("plan]"); }); it("should prioritize mode prop over service mode", () => { - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); const { lastFrame } = render(); expect(lastFrame()).toContain("auto]"); }); @@ -49,17 +54,17 @@ describe("ModeIndicator", () => { expect(lastFrame()).toBe(""); // Switch to plan - modeService.switchMode("plan"); + toolPermissionService.switchMode("plan"); rerender(); expect(lastFrame()).toContain("plan]"); // Switch to auto - modeService.switchMode("auto"); + toolPermissionService.switchMode("auto"); rerender(); expect(lastFrame()).toContain("auto]"); // Switch back to normal - modeService.switchMode("normal"); + toolPermissionService.switchMode("normal"); rerender(); expect(lastFrame()).toBe(""); }); diff --git a/extensions/cli/src/ui/components/ModeIndicator.tsx b/extensions/cli/src/ui/components/ModeIndicator.tsx index 05833df68..506237e08 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.tsx @@ -1,38 +1,20 @@ import { Text } from "ink"; -import React, { useEffect, useState } from "react"; +import React from "react"; +import { useServices } from "src/hooks/useService.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { SERVICE_NAMES } from "src/services/types.js"; import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; interface ModeIndicatorProps { mode?: PermissionMode; } const ModeIndicator: React.FC = ({ mode }) => { - const [currentMode, setCurrentMode] = useState( - mode || modeService.getCurrentMode(), - ); - - // Update mode when it changes (for cases where mode prop is not provided) - useEffect(() => { - if (!mode) { - // Listen for immediate mode changes - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - - // Set initial mode - setCurrentMode(modeService.getCurrentMode()); - - return () => { - modeService.off("modeChanged", handleModeChange); - }; - } else if (mode !== currentMode) { - setCurrentMode(mode); - } - }, [mode]); + const { services } = useServices<{ + toolPermissions: ToolPermissionServiceState; + }>([SERVICE_NAMES.TOOL_PERMISSIONS]); + const currentMode = mode ?? services.toolPermissions?.currentMode ?? "normal"; // Don't show indicator for normal mode to keep it clean if (currentMode === "normal") { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 5cb661333..4503bae53 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -749,7 +749,7 @@ export function useChat({ logger.debug(`Policy created: ${policyRule}`); // Reload permissions to pick up the new policy without requiring restart - await services.mode.getToolPermissionService().reloadPermissions(); + await services.toolPermissions.reloadPermissions(); } catch (error) { logger.error("Failed to create policy or reload permissions", { error, diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index 6025496f5..b4b55fa4a 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -1,7 +1,5 @@ import { useCallback, useEffect, useState } from "react"; -import type { PermissionMode } from "../../permissions/types.js"; -import { modeService } from "../../services/ModeService.js"; import { getGitBranch, getGitRemoteUrl, isGitRepo } from "../../util/git.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; @@ -150,26 +148,6 @@ export function useLoginHandlers( return { handleLoginPrompt, handleLoginTokenSubmit }; } -// Custom hook for mode tracking -export function useCurrentMode() { - const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode(), - ); - - useEffect(() => { - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; - - modeService.on("modeChanged", handleModeChange); - return () => { - modeService.off("modeChanged", handleModeChange); - }; - }, []); - - return currentMode; -} - // Custom hook to combine all selector logic export function useSelectors( configPath: string | undefined, From dcddb5429b4c7536115d7f8a41c74b317e6b0bbb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 17:47:13 -0700 Subject: [PATCH 40/91] fix: fix workflow tests --- extensions/cli/src/configEnhancer.test.ts | 19 ++++---- extensions/cli/src/configEnhancer.ts | 18 +++---- .../cli/src/services/ConfigService.test.ts | 21 +++++++- extensions/cli/src/services/ConfigService.ts | 3 ++ extensions/cli/src/services/index.ts | 2 +- .../src/services/workflow-integration.test.ts | 48 ++++++++----------- 6 files changed, 58 insertions(+), 53 deletions(-) diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts index b2fa2af77..3aaea15b4 100644 --- a/extensions/cli/src/configEnhancer.test.ts +++ b/extensions/cli/src/configEnhancer.test.ts @@ -237,8 +237,12 @@ describe("ConfigEnhancer", () => { it("should handle workflow integration when workflow is active", async () => { // Mock service container to return active workflow - const { serviceContainer } = await import("./services/ServiceContainer.js"); - (serviceContainer.get as any).mockResolvedValueOnce({ + const options: BaseCommandOptions = { + rule: ["user-rule"], + prompt: ["user-prompt"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options, { workflowFile: { name: "Test Workflow", prompt: "You are a test assistant", @@ -246,16 +250,11 @@ describe("ConfigEnhancer", () => { model: "gpt-4", tools: "bash,read", }, - workflow: "owner/test-workflow", + slug: "owner/test-workflow", + workflowModelName: null, + workflowService: null, }); - const options: BaseCommandOptions = { - rule: ["user-rule"], - prompt: ["user-prompt"], - }; - - const config = await enhancer.enhanceConfig(mockConfig, options); - // Should have both workflow and user rules expect(config.rules).toHaveLength(2); expect(config.rules?.[0]).toBe("Always be helpful"); // Workflow rule first diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 1aa002237..286cd3455 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -12,8 +12,7 @@ import { modelProcessor, processRule, } from "./hubLoader.js"; -import { serviceContainer } from "./services/ServiceContainer.js"; -import { SERVICE_NAMES, WorkflowServiceState } from "./services/types.js"; +import { WorkflowServiceState } from "./services/types.js"; import { logger } from "./util/logger.js"; /** @@ -26,18 +25,13 @@ export class ConfigEnhancer { async enhanceConfig( config: AssistantUnrolled, _options: BaseCommandOptions, + workflowState?: WorkflowServiceState, ): Promise { let enhancedConfig = { ...config }; const options = { ..._options }; - // Add workflow rules/mcp servers if present - const workflowState = await serviceContainer.get( - SERVICE_NAMES.WORKFLOW, - ); - const { workflowFile, workflowService } = workflowState; - - if (workflowFile) { - const { rules, model, tools, prompt } = workflowFile; + if (workflowState?.workflowFile) { + const { rules, model, tools, prompt } = workflowState?.workflowFile; if (rules) { options.rule = [ ...rules.split(",").filter(Boolean), @@ -59,7 +53,9 @@ export class ConfigEnhancer { workflowModel, ...(enhancedConfig.models ?? []), ]; - workflowService?.setWorkflowModelName(workflowModel.name); + workflowState?.workflowService?.setWorkflowModelName( + workflowModel.name, + ); } // Add workflow prompt as prefix (see processAndCombinePrompts) diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index e230b1bde..bb745dd7e 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -12,7 +12,7 @@ import * as configLoader from "../configLoader.js"; import { ConfigService } from "./ConfigService.js"; import { serviceContainer } from "./ServiceContainer.js"; -import { SERVICE_NAMES } from "./types.js"; +import { SERVICE_NAMES, WorkflowServiceState } from "./types.js"; describe("ConfigService", () => { let service: ConfigService; @@ -23,7 +23,12 @@ describe("ConfigService", () => { systemMessage: "Test system message", } as any; const mockApiClient = { get: vi.fn(), post: vi.fn() }; - + const mockWorkflowState: WorkflowServiceState = { + slug: null, + workflowFile: null, + workflowModelName: null, + workflowService: null, + }; beforeEach(() => { vi.clearAllMocks(); service = new ConfigService(); @@ -41,6 +46,7 @@ describe("ConfigService", () => { "/path/to/config.yaml", "org-123", mockApiClient as any, + mockWorkflowState, ); expect(state).toEqual({ @@ -60,6 +66,7 @@ describe("ConfigService", () => { undefined, "org-123", mockApiClient as any, + mockWorkflowState, ); expect(state).toEqual({ @@ -87,6 +94,7 @@ describe("ConfigService", () => { "/config.yaml", "org-123", mockApiClient as any, + mockWorkflowState, { rule: ["rule1", "rule2"] }, ); @@ -94,6 +102,7 @@ describe("ConfigService", () => { expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( mockConfig, { rule: ["rule1", "rule2"] }, + mockWorkflowState, ); expect(state.config).toEqual(expectedConfig); @@ -111,6 +120,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/old.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -140,6 +150,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/old.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -169,6 +180,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/config.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -201,6 +213,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, undefined, "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -225,6 +238,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/old.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -267,6 +281,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/old.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -304,6 +319,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/old.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); @@ -337,6 +353,7 @@ describe("ConfigService", () => { { accessToken: "token" } as any, "/old.yaml", "org-123", + mockWorkflowState, mockApiClient as any, ); diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 66a3289b6..1ed1948f4 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -11,6 +11,7 @@ import { ApiClientServiceState, ConfigServiceState, SERVICE_NAMES, + WorkflowServiceState, } from "./types.js"; /** @@ -47,6 +48,7 @@ export class ConfigService configPath: string | undefined, _organizationId: string | null, apiClient: DefaultApiInterface, + workflowState: WorkflowServiceState, injectedConfigOptions?: BaseCommandOptions, ): Promise { // Use the new streamlined config loader @@ -63,6 +65,7 @@ export class ConfigService config = await configEnhancer.enhanceConfig( config, injectedConfigOptions, + workflowState, ); logger.debug("Applied injected configuration"); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index b73164330..ac7244987 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -214,8 +214,8 @@ export async function initializeServices( configPath, finalAuthState.organizationId || null, apiClientState.apiClient, - commandOptions, workflowState, + commandOptions, ); }, [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 6c2f693a8..9313e93bd 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -3,8 +3,6 @@ import { vi } from "vitest"; import { ConfigEnhancer } from "../configEnhancer.js"; import { ModelService } from "./ModelService.js"; -import { serviceContainer } from "./ServiceContainer.js"; -import { SERVICE_NAMES } from "./types.js"; import { WorkflowService } from "./WorkflowService.js"; // Mock the hubLoader module @@ -100,16 +98,6 @@ describe("Workflow Integration Tests", () => { modelService = new ModelService(); configEnhancer = new ConfigEnhancer(); - // Mock service container - vi.spyOn(serviceContainer, "get").mockImplementation( - async (serviceName: string) => { - if (serviceName === SERVICE_NAMES.WORKFLOW) { - return workflowService.getState(); - } - throw new Error(`Service ${serviceName} not mocked`); - }, - ); - // Setup default mocks mockProcessRule.mockResolvedValue("Processed rule content"); mockLoadPackagesFromHub.mockResolvedValue([{ name: "test-mcp" }]); @@ -146,6 +134,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, baseOptions, + workflowState, ); // Should have loaded the workflow model directly via loadPackageFromHub @@ -176,6 +165,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, baseOptions, + workflowState, ); // Should not have enhanced with any models @@ -206,6 +196,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, baseOptions, + workflowService.getState(), ); // Should process the user model via loadPackagesFromHub @@ -246,6 +237,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); // Rules should be processed normally since workflow rules are now added to options.rule @@ -269,6 +261,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); expect(mockProcessRule).not.toHaveBeenCalled(); @@ -292,6 +285,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); expect(mockProcessRule).not.toHaveBeenCalled(); @@ -367,6 +361,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); // Should not inject workflow rule but should preserve existing rules @@ -389,6 +384,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); // Prompts should be processed at runtime, not injected into config @@ -452,27 +448,18 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); - // Create a spy to verify the internal behavior of ConfigEnhancer - const originalGet = serviceContainer.get; - const getSpy = vi - .spyOn(serviceContainer, "get") - .mockImplementation(async (serviceName: string) => { - if (serviceName === SERVICE_NAMES.WORKFLOW) { - return workflowService.getState(); - } - return originalGet.call(serviceContainer, serviceName); - }); - const baseOptions = { prompt: ["user-prompt"] }; // This should internally modify the options to include workflow prompt - await configEnhancer.enhanceConfig({} as any, baseOptions); + await configEnhancer.enhanceConfig( + {} as any, + baseOptions, + workflowService.getState(), + ); - // The ConfigEnhancer should have been called with workflow service - expect(getSpy).toHaveBeenCalledWith(SERVICE_NAMES.WORKFLOW); - - // Clean up - getSpy.mockRestore(); + // Verify that the workflow prompt was added to the options + // by checking that injectPrompts was called with workflow prompt prefixed + expect(baseOptions.prompt).toHaveLength(1); }); it("should work end-to-end with workflow prompt processing", async () => { @@ -564,6 +551,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); expect(enhancedConfig.mcpServers).toHaveLength(3); @@ -588,6 +576,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); expect(enhancedConfig.mcpServers).toHaveLength(1); @@ -612,6 +601,7 @@ describe("Workflow Integration Tests", () => { const enhancedConfig = await configEnhancer.enhanceConfig( baseConfig as any, {}, + workflowService.getState(), ); // Should not deduplicate since we simplified the logic From 164d5363809b9f856f4c26f39d305fe6916a2875 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 18:04:39 -0700 Subject: [PATCH 41/91] fix: tests, formatting, linting --- extensions/cli/src/configEnhancer.ts | 27 ++- .../model-persistence-user-flow.test.ts | 1 + .../cli/src/permissions/permissionChecker.ts | 3 +- .../cli/src/services/ConfigService.test.ts | 156 +++++++++--------- extensions/cli/src/services/ConfigService.ts | 23 ++- .../src/services/SystemMessageService.test.ts | 1 + extensions/cli/src/services/index.test.ts | 3 +- extensions/cli/src/services/index.ts | 10 +- extensions/cli/src/ui/TUIChat.tsx | 3 +- .../TUIChat.permissionPolicyReload.test.tsx | 1 + .../src/ui/components/ModeIndicator.test.tsx | 1 + .../cli/src/ui/components/ModeIndicator.tsx | 1 + 12 files changed, 130 insertions(+), 100 deletions(-) diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 286cd3455..e33be15c9 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -19,15 +19,13 @@ import { logger } from "./util/logger.js"; * Enhances a configuration by injecting additional components from CLI flags */ export class ConfigEnhancer { - /** - * Apply all enhancements to a configuration - */ - async enhanceConfig( + // added this for lint complexity rule + private async enhanceConfigFromWorkflow( config: AssistantUnrolled, _options: BaseCommandOptions, workflowState?: WorkflowServiceState, - ): Promise { - let enhancedConfig = { ...config }; + ) { + const enhancedConfig = { ...config }; const options = { ..._options }; if (workflowState?.workflowFile) { @@ -63,6 +61,23 @@ export class ConfigEnhancer { options.prompt = [prompt, ...(options.prompt || [])]; } } + return { options, enhancedConfig }; + } + /** + * Apply all enhancements to a configuration + */ + async enhanceConfig( + config: AssistantUnrolled, + _options: BaseCommandOptions, + workflowState?: WorkflowServiceState, + ): Promise { + const enhanced = await this.enhanceConfigFromWorkflow( + config, + _options, + workflowState, + ); + let { enhancedConfig } = enhanced; + const { options } = enhanced; // Inject resolved items into config if (options.rule && options.rule.length > 0) { diff --git a/extensions/cli/src/integration/model-persistence-user-flow.test.ts b/extensions/cli/src/integration/model-persistence-user-flow.test.ts index 966e69ccb..3aef05071 100644 --- a/extensions/cli/src/integration/model-persistence-user-flow.test.ts +++ b/extensions/cli/src/integration/model-persistence-user-flow.test.ts @@ -6,6 +6,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { AuthService } from "src/services/AuthService.js"; + import { AuthenticatedConfig, getModelName, diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index faa52870b..738de9a56 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -1,10 +1,11 @@ import type { ToolPolicy } from "@continuedev/terminal-security"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + import { getServiceSync } from "../services/index.js"; import { SERVICE_NAMES } from "../services/types.js"; import { getAllBuiltinTools } from "../tools/index.js"; -import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { PermissionCheckResult, diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index bb745dd7e..dbb313fb7 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -41,13 +41,13 @@ describe("ConfigService", () => { source: { type: "cli-flag", path: "/path/to/config.yaml" } as any, }); - const state = await service.initialize( - { accessToken: "token" } as any, - "/path/to/config.yaml", - "org-123", - mockApiClient as any, - mockWorkflowState, - ); + const state = await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/path/to/config.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); expect(state).toEqual({ config: mockConfig as any, @@ -61,13 +61,13 @@ describe("ConfigService", () => { source: { type: "default-agent" } as any, }); - const state = await service.initialize( - { accessToken: "token" } as any, - undefined, - "org-123", - mockApiClient as any, - mockWorkflowState, - ); + const state = await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: undefined, + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); expect(state).toEqual({ config: mockConfig as any, @@ -89,14 +89,14 @@ describe("ConfigService", () => { vi.mocked(configEnhancer.enhanceConfig).mockResolvedValue(expectedConfig); - const state = await service.initialize( - { accessToken: "token" } as any, - "/config.yaml", - "org-123", - mockApiClient as any, - mockWorkflowState, - { rule: ["rule1", "rule2"] }, - ); + const state = await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/config.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + injectedConfigOptions: { rule: ["rule1", "rule2"] }, + }); // Verify configEnhancer was called with the right parameters expect(vi.mocked(configEnhancer.enhanceConfig)).toHaveBeenCalledWith( @@ -116,13 +116,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); // Switch to new config const newConfig = { ...mockConfig, name: "new-assistant" } as any; @@ -146,13 +146,13 @@ describe("ConfigService", () => { }); test("should handle switch config errors", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); vi.mocked(configLoader.loadConfiguration).mockRejectedValue( new Error("Config not found"), @@ -176,13 +176,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/config.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/config.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); // Modify mock to return updated config const updatedConfig = { ...mockConfig, name: "updated-assistant" } as any; @@ -209,13 +209,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "default-agent" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - undefined, - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: undefined, + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); await expect( service.reload( @@ -234,13 +234,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); // Mock service container vi.mocked(workos.loadAuthConfig).mockReturnValue({ @@ -277,13 +277,13 @@ describe("ConfigService", () => { }); test("should handle missing API client", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); vi.mocked(workos.loadAuthConfig).mockReturnValue({ accessToken: "token", @@ -315,13 +315,13 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/old.yaml" } as any, }); - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); const listener = vi.fn(); service.on("stateChanged", listener); @@ -349,13 +349,13 @@ describe("ConfigService", () => { }); test("should emit error on switch failure", async () => { - await service.initialize( - { accessToken: "token" } as any, - "/old.yaml", - "org-123", - mockWorkflowState, - mockApiClient as any, - ); + await service.initialize({ + authConfig: { accessToken: "token" } as any, + configPath: "/old.yaml", + _organizationId: "org-123", + apiClient: mockApiClient as any, + workflowState: mockWorkflowState, + }); const errorListener = vi.fn(); service.on("error", errorListener); diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 1ed1948f4..62d5de72f 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -14,6 +14,14 @@ import { WorkflowServiceState, } from "./types.js"; +interface ConfigServiceInit { + authConfig: AuthConfig; + configPath: string | undefined; + _organizationId: string | null; + apiClient: DefaultApiInterface; + workflowState: WorkflowServiceState; + injectedConfigOptions?: BaseCommandOptions; +} /** * Service for managing configuration state and operations * Handles loading configs from files or assistant slugs @@ -43,14 +51,13 @@ export class ConfigService /** * Initialize the config service */ - async doInitialize( - authConfig: AuthConfig, - configPath: string | undefined, - _organizationId: string | null, - apiClient: DefaultApiInterface, - workflowState: WorkflowServiceState, - injectedConfigOptions?: BaseCommandOptions, - ): Promise { + async doInitialize({ + apiClient, + authConfig, + configPath, + workflowState, + injectedConfigOptions, + }: ConfigServiceInit): Promise { // Use the new streamlined config loader const { loadConfiguration } = await import("../configLoader.js"); const result = await loadConfiguration(authConfig, configPath, apiClient); diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts index c76bbb8b9..be289068b 100644 --- a/extensions/cli/src/services/SystemMessageService.test.ts +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { SystemMessageService } from "./SystemMessageService.js"; + import { services } from "./index.js"; const toolPermissionService = services.toolPermissions; diff --git a/extensions/cli/src/services/index.test.ts b/extensions/cli/src/services/index.test.ts index 7a5cf31b6..3e0109f19 100644 --- a/extensions/cli/src/services/index.test.ts +++ b/extensions/cli/src/services/index.test.ts @@ -1,8 +1,9 @@ import { vi } from "vitest"; -import { initializeServices, services } from "./index.js"; import { WorkflowService } from "./WorkflowService.js"; +import { initializeServices, services } from "./index.js"; + // Mock the onboarding module vi.mock("../onboarding.js", () => ({ initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }), diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index ac7244987..8eb58496c 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -209,14 +209,14 @@ export async function initializeServices( } } - return configService.initialize( - finalAuthState.authConfig, + return configService.initialize({ + authConfig: finalAuthState.authConfig, configPath, - finalAuthState.organizationId || null, - apiClientState.apiClient, + organizationIde: finalAuthState.organizationId || null, + apiClient: apiClientState.apiClient, workflowState, commandOptions, - ); + }); }, [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies ); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 64982b942..555c32829 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -7,6 +7,8 @@ import React, { useState, } from "react"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; + import { useServices } from "../hooks/useService.js"; import { ApiClientServiceState, @@ -18,7 +20,6 @@ import { } from "../services/types.js"; import { logger } from "../util/logger.js"; -import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { ActionStatus } from "./components/ActionStatus.js"; import { BottomStatusBar } from "./components/BottomStatusBar.js"; import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; diff --git a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx index f46bab262..c29727401 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; + import { services } from "../../services/index.js"; vi.mock("../../services/index.js"); diff --git a/extensions/cli/src/ui/components/ModeIndicator.test.tsx b/extensions/cli/src/ui/components/ModeIndicator.test.tsx index 7e1af759a..6301c2204 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.test.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.test.tsx @@ -3,6 +3,7 @@ import React from "react"; import { beforeEach, describe, expect, it } from "vitest"; import { initializeServices, services } from "src/services/index.js"; + import { ModeIndicator } from "./ModeIndicator.js"; describe("ModeIndicator", () => { diff --git a/extensions/cli/src/ui/components/ModeIndicator.tsx b/extensions/cli/src/ui/components/ModeIndicator.tsx index 506237e08..30cbd558c 100644 --- a/extensions/cli/src/ui/components/ModeIndicator.tsx +++ b/extensions/cli/src/ui/components/ModeIndicator.tsx @@ -4,6 +4,7 @@ import React from "react"; import { useServices } from "src/hooks/useService.js"; import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { SERVICE_NAMES } from "src/services/types.js"; + import type { PermissionMode } from "../../permissions/types.js"; interface ModeIndicatorProps { From 379ffe05509e30049f703e5f00fc8f1f04b9b812 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 18:21:29 -0700 Subject: [PATCH 42/91] fix: circular import --- extensions/cli/src/commands/serve.ts | 5 +- .../cli/src/services/SystemMessageService.ts | 2 +- extensions/cli/src/systemMessage.test.ts | 56 +++++++++++-------- extensions/cli/src/systemMessage.ts | 10 +--- 4 files changed, 41 insertions(+), 32 deletions(-) diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 8256ca6f1..0099a1d3e 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -29,6 +29,7 @@ import { getGitDiffSnapshot } from "../util/git.js"; import { logger } from "../util/logger.js"; import { readStdinSync } from "../util/stdin.js"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; import { streamChatResponseWithInterruption, @@ -72,9 +73,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { }); // Get initialized services from the service container - const [configState, modelState] = await Promise.all([ + const [configState, modelState, permissionsState] = await Promise.all([ getService(SERVICE_NAMES.CONFIG), getService(SERVICE_NAMES.MODEL), + getService(SERVICE_NAMES.TOOL_PERMISSIONS), ]); if (!configState.config || !modelState.llmApi || !modelState.model) { @@ -117,6 +119,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // Initialize session with system message const systemMessage = await constructSystemMessage( + permissionsState.currentMode, options.rule, undefined, true, diff --git a/extensions/cli/src/services/SystemMessageService.ts b/extensions/cli/src/services/SystemMessageService.ts index 1f2bbf2eb..44ae3098c 100644 --- a/extensions/cli/src/services/SystemMessageService.ts +++ b/extensions/cli/src/services/SystemMessageService.ts @@ -50,10 +50,10 @@ export class SystemMessageService extends BaseService const { additionalRules, format, headless } = this.currentState; const systemMessage = await constructSystemMessage( + currentMode, additionalRules, format, headless, - currentMode, ); logger.debug("Generated fresh system message", { diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index 15f797dfc..e419d0bac 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -24,7 +24,7 @@ const PLAN_MODE_STRING = "You are operating in _Plan Mode_"; describe("constructSystemMessage", () => { it("should return base system message with rules when additionalRules is provided", async () => { const rules = ["These are the rules for the assistant."]; - const result = await constructSystemMessage(rules); + const result = await constructSystemMessage("normal", rules); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -34,7 +34,7 @@ describe("constructSystemMessage", () => { it("should return base system message with agent content when no rules but agent file exists", async () => { // The implementation checks for agent files like AGENTS.md which exists in this project - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -42,7 +42,7 @@ describe("constructSystemMessage", () => { }); it("should include base system message components", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(""); @@ -51,27 +51,27 @@ describe("constructSystemMessage", () => { }); it("should handle whitespace-only rules message", async () => { - const result = await constructSystemMessage([" "]); + const result = await constructSystemMessage("normal", [" "]); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); }); it("should include working directory information", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Working directory:"); expect(result).toContain(""); }); it("should include platform information", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Platform:"); }); it("should include current date", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("Today's date:"); expect(result).toContain(new Date().toISOString().split("T")[0]); @@ -79,7 +79,7 @@ describe("constructSystemMessage", () => { it("should format rules section correctly", async () => { const rulesMessage = "Rule 1: Do this\nRule 2: Do that"; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -90,7 +90,7 @@ describe("constructSystemMessage", () => { const rulesMessage = `Rule 1: First rule Rule 2: Second rule Rule 3: Third rule`; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -99,7 +99,7 @@ Rule 3: Third rule`; it("should handle special characters in rules message", async () => { const rulesMessage = "Rule with characters & symbols!"; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -107,7 +107,7 @@ Rule 3: Third rule`; it("should handle very long rules message", async () => { const rulesMessage = "A".repeat(1000); - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -115,7 +115,7 @@ Rule 3: Third rule`; it("should combine rules and agent content when both are present", async () => { const rulesMessage = "These are the rules."; - const result = await constructSystemMessage([rulesMessage]); + const result = await constructSystemMessage("normal", [rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -124,7 +124,12 @@ Rule 3: Third rule`; }); it("should add headless mode instructions when headless is true", async () => { - const result = await constructSystemMessage(undefined, undefined, true); + const result = await constructSystemMessage( + "normal", + undefined, + undefined, + true, + ); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -135,7 +140,12 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is false", async () => { - const result = await constructSystemMessage(undefined, undefined, false); + const result = await constructSystemMessage( + "normal", + undefined, + undefined, + false, + ); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -143,7 +153,7 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is undefined", async () => { - const result = await constructSystemMessage(); + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -151,7 +161,7 @@ Rule 3: Third rule`; }); it("should add JSON format instructions when format is json", async () => { - const result = await constructSystemMessage(undefined, "json"); + const result = await constructSystemMessage("normal", undefined, "json"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain( @@ -163,10 +173,10 @@ Rule 3: Third rule`; it("should add plan mode instructions when mode is plan", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, false, - "plan", ); expect(result).toContain("You are an agent in the Continue CLI"); @@ -183,10 +193,10 @@ Rule 3: Third rule`; it("should not add plan mode instructions when mode is not plan", async () => { const result = await constructSystemMessage( + "normal", undefined, undefined, false, - "normal", ); expect(result).toContain("You are an agent in the Continue CLI"); @@ -196,8 +206,8 @@ Rule 3: Third rule`; ); }); - it("should not add plan mode instructions when mode is undefined", async () => { - const result = await constructSystemMessage(); + it("should not add plan mode instructions when mode is normal", async () => { + const result = await constructSystemMessage("normal"); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain(PLAN_MODE_STRING); @@ -208,10 +218,10 @@ Rule 3: Third rule`; it("should include basic plan mode description", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, false, - "plan", ); expect(result).toContain(PLAN_MODE_STRING); @@ -221,10 +231,10 @@ Rule 3: Third rule`; it("should combine plan mode with headless mode instructions", async () => { const result = await constructSystemMessage( + "plan", undefined, undefined, true, - "plan", ); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -236,10 +246,10 @@ Rule 3: Third rule`; it("should combine plan mode with JSON format instructions", async () => { const result = await constructSystemMessage( + "plan", undefined, "json", false, - "plan", ); expect(result).toContain( diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 9acd01085..d5dee238f 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -7,11 +7,10 @@ import { Minimatch } from "minimatch"; import { processRule } from "./hubLoader.js"; import { PermissionMode } from "./permissions/types.js"; -import { services } from "./services/index.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; -const toolPermissionService = services.toolPermissions; + /** * Check if current directory is a git repository */ @@ -125,10 +124,10 @@ async function getConfigYamlRules(): Promise { * @returns The comprehensive system message with base message and rules section */ export async function constructSystemMessage( + mode: PermissionMode, additionalRules?: string[], format?: "json", headless?: boolean, - mode?: PermissionMode, ): Promise { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; @@ -166,14 +165,11 @@ export async function constructSystemMessage( const configYamlRules = await getConfigYamlRules(); processedRules.push(...configYamlRules); - // Get current mode if not provided - const currentMode = mode ?? toolPermissionService.getCurrentMode(); - // Construct the comprehensive system message let systemMessage = baseSystemMessage; // Add plan mode specific instructions if in plan mode - if (currentMode === "plan") { + if (mode === "plan") { systemMessage += '\nYou are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.\n'; } else { From 475aa95e44274a0ef17b86e5373b7b793516aad7 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 18:24:45 -0700 Subject: [PATCH 43/91] fix: linting --- extensions/cli/src/commands/serve.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 0099a1d3e..bba7efa00 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -2,6 +2,7 @@ import chalk from "chalk"; import type { ChatHistoryItem } from "core/index.js"; import express, { Request, Response } from "express"; +import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { posthogService } from "src/telemetry/posthogService.js"; import { getAccessToken, getAssistantSlug } from "../auth/workos.js"; @@ -29,7 +30,6 @@ import { getGitDiffSnapshot } from "../util/git.js"; import { logger } from "../util/logger.js"; import { readStdinSync } from "../util/stdin.js"; -import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; import { streamChatResponseWithInterruption, From 99095bdcbda8ca36021cbec2293938cea166a55a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 19:46:06 -0700 Subject: [PATCH 44/91] fix: workflow e2e working --- extensions/cli/src/commands/chat.ts | 28 +++++++++-- extensions/cli/src/configEnhancer.ts | 50 +++++++++++++------ extensions/cli/src/services/ConfigService.ts | 4 +- .../cli/src/services/ToolPermissionService.ts | 14 +++--- .../cli/src/services/WorkflowService.ts | 6 +++ extensions/cli/src/services/index.ts | 4 +- 6 files changed, 75 insertions(+), 31 deletions(-) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index a954e8b34..dcaaa1412 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -12,7 +12,11 @@ import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; import { initializeServices, services } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; -import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; +import { + ModelServiceState, + SERVICE_NAMES, + WorkflowServiceState, +} from "../services/types.js"; import { loadSession, updateSessionHistory, @@ -474,9 +478,15 @@ async function runHeadlessMode( const { processAndCombinePrompts } = await import( "../util/promptProcessor.js" ); + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + const initialPrompt = + `${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() || + undefined; const initialUserInput = await processAndCombinePrompts( options.prompt, - prompt, + initialPrompt, ); let isFirstMessage = true; @@ -528,11 +538,13 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // Start active time tracking telemetryService.startActiveTime(); + options.workflow = "peter-parker/workflow-48"; + // options.headless = true; + // If not in headless mode, use unified initialization with TUI if (!options.headless) { // Process flags for TUI mode const { permissionOverrides } = processCommandFlags(options); - // Initialize services with onboarding handled internally await initializeServices({ options, @@ -540,9 +552,17 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { toolPermissionOverrides: permissionOverrides, }); + const workflowState = await serviceContainer.get( + SERVICE_NAMES.WORKFLOW, + ); + + const initialPrompt = + `${workflowState?.workflowFile?.prompt ?? ""}\n\n${prompt ?? ""}`.trim() || + undefined; + // Start TUI with skipOnboarding since we already handled it const tuiOptions: any = { - initialPrompt: prompt, + initialPrompt, resume: options.resume, fork: options.fork, config: options.config, diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index e33be15c9..49e464f2f 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -22,7 +22,7 @@ export class ConfigEnhancer { // added this for lint complexity rule private async enhanceConfigFromWorkflow( config: AssistantUnrolled, - _options: BaseCommandOptions, + _options: BaseCommandOptions | undefined, workflowState?: WorkflowServiceState, ) { const enhancedConfig = { ...config }; @@ -32,33 +32,51 @@ export class ConfigEnhancer { const { rules, model, tools, prompt } = workflowState?.workflowFile; if (rules) { options.rule = [ - ...rules.split(",").filter(Boolean), + ...rules + .split(",") + .filter(Boolean) + .map((r) => r.trim()), ...(options.rule || []), ]; } if (tools) { - const parsedTools = parseWorkflowTools(tools); - if (parsedTools.mcpServers.length > 0) { - options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; + try { + const parsedTools = parseWorkflowTools(tools); + if (parsedTools.mcpServers.length > 0) { + options.mcp = [...parsedTools.mcpServers, ...(options.mcp || [])]; + } + } catch (e) { + logger.error("Failed to parse workflow tools", e); } } // --model takes precedence over workflow model if (model) { - const workflowModel = await loadPackageFromHub(model, modelProcessor); - enhancedConfig.models = [ - workflowModel, - ...(enhancedConfig.models ?? []), - ]; - workflowState?.workflowService?.setWorkflowModelName( - workflowModel.name, - ); + try { + const workflowModel = await loadPackageFromHub(model, modelProcessor); + enhancedConfig.models = [ + workflowModel, + ...(enhancedConfig.models ?? []), + ]; + workflowState?.workflowService?.setWorkflowModelName( + workflowModel.name, + ); + } catch (e) { + logger.error("Failed to load workflow model", e); + } } - // Add workflow prompt as prefix (see processAndCombinePrompts) + // Workflow prompt is included as a slash command, initial kickoff is handled elsewhere if (prompt) { - options.prompt = [prompt, ...(options.prompt || [])]; + enhancedConfig.prompts = [ + { + name: `Workflow prompt (${workflowState.workflowFile.name})`, + prompt, + description: workflowState.workflowFile.description, + }, + ...(enhancedConfig.prompts ?? []), + ]; } } return { options, enhancedConfig }; @@ -68,7 +86,7 @@ export class ConfigEnhancer { */ async enhanceConfig( config: AssistantUnrolled, - _options: BaseCommandOptions, + _options?: BaseCommandOptions, workflowState?: WorkflowServiceState, ): Promise { const enhanced = await this.enhanceConfigFromWorkflow( diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index 62d5de72f..72f88540f 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -66,8 +66,8 @@ export class ConfigService // Apply injected config if provided if ( - injectedConfigOptions && - this.hasInjectedConfig(injectedConfigOptions) + workflowState?.workflowFile || + (injectedConfigOptions && this.hasInjectedConfig(injectedConfigOptions)) ) { config = await configEnhancer.enhanceConfig( config, diff --git a/extensions/cli/src/services/ToolPermissionService.ts b/extensions/cli/src/services/ToolPermissionService.ts index dc754aad0..a6fa5db1e 100644 --- a/extensions/cli/src/services/ToolPermissionService.ts +++ b/extensions/cli/src/services/ToolPermissionService.ts @@ -82,13 +82,6 @@ export class ToolPermissionService } const policies: ToolPermissionPolicy[] = []; - if (parsedTools.allBuiltIn) { - policies.push({ tool: "*", permission: "allow" }); - policies.push({ tool: "mcp:*", permission: "exclude" }); - } else { - policies.push({ tool: "*", permission: "exclude" }); - } - for (const toolRef of parsedTools.tools) { if (toolRef.mcpServer) { if (toolRef.toolName) { @@ -111,6 +104,13 @@ export class ToolPermissionService logger.debug(`Generated ${policies.length} workflow tool policies`); } + if (parsedTools.allBuiltIn) { + policies.push({ tool: "*", permission: "allow" }); + policies.push({ tool: "mcp:*", permission: "exclude" }); + } else { + policies.push({ tool: "*", permission: "exclude" }); + } + return policies; } diff --git a/extensions/cli/src/services/WorkflowService.ts b/extensions/cli/src/services/WorkflowService.ts index f47e2ebfa..cc0096af5 100644 --- a/extensions/cli/src/services/WorkflowService.ts +++ b/extensions/cli/src/services/WorkflowService.ts @@ -2,6 +2,7 @@ import { loadPackageFromHub, workflowProcessor } from "../hubLoader.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; +import { serviceContainer } from "./ServiceContainer.js"; import { WorkflowServiceState } from "./types.js"; /** @@ -69,4 +70,9 @@ export class WorkflowService extends BaseService { }; } } + + protected override setState(newState: Partial): void { + super.setState(newState); + serviceContainer.set("update", this.currentState); + } } diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 8eb58496c..a8d209d88 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -212,10 +212,10 @@ export async function initializeServices( return configService.initialize({ authConfig: finalAuthState.authConfig, configPath, - organizationIde: finalAuthState.organizationId || null, + // organizationId: finalAuthState.organizationId || null, apiClient: apiClientState.apiClient, workflowState, - commandOptions, + injectedConfigOptions: commandOptions, }); }, [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT, SERVICE_NAMES.WORKFLOW], // Dependencies From 236f139ffc8cd978d535d9806c5c3c1508a6d64f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Oct 2025 19:48:55 -0700 Subject: [PATCH 45/91] fix: lint/format --- extensions/cli/src/services/SystemMessageService.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts index be289068b..d925c88b1 100644 --- a/extensions/cli/src/services/SystemMessageService.test.ts +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -76,10 +76,10 @@ describe("SystemMessageService", () => { const message = await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", // Default mode ["rule1"], "json", true, - "normal", // Default mode ); expect(message).toBe("Test system message"); }); @@ -100,10 +100,10 @@ describe("SystemMessageService", () => { await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", ["rule1"], "json", false, - "normal", ); }); @@ -121,10 +121,10 @@ describe("SystemMessageService", () => { await service.getSystemMessage("normal"); expect(constructSystemMessageMock).toHaveBeenCalledWith( + "normal", ["rule2", "rule3"], "json", undefined, - "normal", ); }); }); From 89e2573c492ce0d66cdeb087a055be8da75d3c90 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 4 Oct 2025 14:45:49 -0700 Subject: [PATCH 46/91] fix: cubic feedback for workflow files --- extensions/cli/src/hooks/useService.ts | 2 +- .../src/services/workflow-integration.test.ts | 126 ++++++++++-------- .../streamChatResponse.getAllTools.test.ts | 11 +- .../streamChatResponse.modeSwitch.test.ts | 4 +- .../cli/src/stream/streamChatResponse.ts | 1 + .../src/markdown/workflowFiles.test.ts | 116 ++++++++++++++++ .../config-yaml/src/markdown/workflowFiles.ts | 8 ++ 7 files changed, 200 insertions(+), 68 deletions(-) diff --git a/extensions/cli/src/hooks/useService.ts b/extensions/cli/src/hooks/useService.ts index 2703c8676..d659652f4 100644 --- a/extensions/cli/src/hooks/useService.ts +++ b/extensions/cli/src/hooks/useService.ts @@ -123,7 +123,7 @@ export function useServices>( hasError, services, }; - }, [serviceNames]); + }, [serviceNames, container]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 9313e93bd..7c688d89c 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -379,6 +379,7 @@ describe("Workflow Integration Tests", () => { const baseConfig = { rules: ["existing rule"], + prompts: [], }; const enhancedConfig = await configEnhancer.enhanceConfig( @@ -387,34 +388,42 @@ describe("Workflow Integration Tests", () => { workflowService.getState(), ); - // Prompts should be processed at runtime, not injected into config - // The workflow prompt is added to options.prompt and will be processed - // by processAndCombinePrompts() in chat.ts + // Workflow prompt should be added to config.prompts + expect(enhancedConfig.prompts).toBeDefined(); + expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + prompt: "You are a workflow assistant.", + name: expect.stringContaining("Test Workflow"), + }); expect(enhancedConfig.rules).toHaveLength(2); }); - it("should add workflow prompt as prefix to existing prompts", async () => { + it("should add workflow prompt to config alongside other prompts", async () => { // Setup workflow service with active workflow mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); - // Test that the workflow prompt gets added to options.prompt as prefix - const baseOptions = { prompt: ["existing-prompt"] }; - const modifiedOptions = { ...baseOptions }; + const baseConfig = { + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + const baseOptions = {}; - // Simulate what ConfigEnhancer does internally - const workflowState = workflowService.getState(); - if (workflowState.workflowFile?.prompt) { - modifiedOptions.prompt = [ - workflowState.workflowFile.prompt, - ...(modifiedOptions.prompt || []), - ]; - } + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowService.getState(), + ); - expect(modifiedOptions.prompt).toEqual([ - "You are a workflow assistant.", - "existing-prompt", - ]); + // Workflow prompt should be prepended to existing prompts + expect(enhancedConfig.prompts).toHaveLength(2); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + name: expect.stringContaining("Test Workflow"), + prompt: "You are a workflow assistant.", + }); + expect(enhancedConfig.prompts?.[1]).toMatchObject({ + name: "Existing", + prompt: "existing-prompt", + }); }); it("should not add workflow prompt when workflow has no prompt", async () => { @@ -426,43 +435,53 @@ describe("Workflow Integration Tests", () => { mockLoadPackageFromHub.mockResolvedValue(workflowWithoutPrompt); await workflowService.initialize("owner/workflow"); - const baseOptions = { prompt: ["existing-prompt"] }; - const modifiedOptions = { ...baseOptions }; + const baseConfig = { + prompts: [{ name: "Existing", prompt: "existing-prompt" }], + }; + const baseOptions = {}; - // Simulate what ConfigEnhancer does internally - const workflowState = workflowService.getState(); - if (workflowState.workflowFile?.prompt) { - modifiedOptions.prompt = [ - workflowState.workflowFile.prompt, - ...(modifiedOptions.prompt || []), - ]; - } + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowService.getState(), + ); - expect(modifiedOptions.prompt).toEqual(["existing-prompt"]); + // Should only have the existing prompt, no workflow prompt added + expect(enhancedConfig.prompts).toHaveLength(1); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + name: "Existing", + prompt: "existing-prompt", + }); }); }); describe("ConfigEnhancer prompt integration", () => { - it("should modify options to include workflow prompt as prefix", async () => { + it("should add workflow prompt to config.prompts when workflow is active", async () => { // Setup workflow service with active workflow mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); const baseOptions = { prompt: ["user-prompt"] }; + const baseConfig = { prompts: [] }; - // This should internally modify the options to include workflow prompt - await configEnhancer.enhanceConfig( - {} as any, + // Enhance config with workflow state + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, baseOptions, workflowService.getState(), ); - // Verify that the workflow prompt was added to the options - // by checking that injectPrompts was called with workflow prompt prefixed - expect(baseOptions.prompt).toHaveLength(1); + // Verify that the workflow prompt was added to config.prompts + expect(enhancedConfig.prompts).toBeDefined(); + expect(enhancedConfig.prompts).toHaveLength(1); + expect(enhancedConfig.prompts?.[0]).toMatchObject({ + name: expect.stringContaining("Test Workflow"), + prompt: "You are a workflow assistant.", + description: "A test workflow for integration testing", + }); }); - it("should work end-to-end with workflow prompt processing", async () => { + it("should work end-to-end with workflow prompt in config", async () => { // Setup workflow service with active workflow mockLoadPackageFromHub.mockResolvedValue(mockWorkflowFile); await workflowService.initialize("owner/workflow"); @@ -472,24 +491,23 @@ describe("Workflow Integration Tests", () => { "You are a workflow assistant.", ); - // Verify that if we manually apply the same logic as ConfigEnhancer, - // the workflow prompt gets added as prefix - const options = { prompt: ["Tell me about TypeScript"] }; + const baseConfig = { prompts: [] }; + const baseOptions = { prompt: ["Tell me about TypeScript"] }; - if (workflowState.workflowFile?.prompt) { - options.prompt = [workflowState.workflowFile.prompt, ...options.prompt]; - } - - expect(options.prompt).toEqual([ - "You are a workflow assistant.", - "Tell me about TypeScript", - ]); - - // This mimics what processAndCombinePrompts would do - const combinedPrompt = options.prompt.join("\n\n"); - expect(combinedPrompt).toBe( - "You are a workflow assistant.\n\nTell me about TypeScript", + // Enhance config with workflow + const enhancedConfig = await configEnhancer.enhanceConfig( + baseConfig as any, + baseOptions, + workflowState, ); + + // Verify workflow prompt is added to config.prompts + expect(enhancedConfig.prompts).toBeDefined(); + expect(enhancedConfig.prompts?.length).toBeGreaterThan(0); + expect(enhancedConfig.prompts?.[0]?.prompt).toBe( + "You are a workflow assistant.", + ); + expect(enhancedConfig.prompts?.[0]?.name).toContain("Test Workflow"); }); }); diff --git a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index 8d8eb68a3..4564d20a9 100644 --- a/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -13,16 +13,7 @@ import { getAllTools } from "./streamChatResponse.js"; describe("getAllTools - Tool Filtering", () => { beforeEach(() => { // Clean up service container state before each test - const services = [ - SERVICE_NAMES.TOOL_PERMISSIONS, - SERVICE_NAMES.AUTH, - SERVICE_NAMES.API_CLIENT, - SERVICE_NAMES.CONFIG, - SERVICE_NAMES.MODEL, - SERVICE_NAMES.MCP, - ]; - - services.forEach((service) => { + Object.values(SERVICE_NAMES).forEach((service) => { // Reset service state (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); diff --git a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index 78f9bcc7b..b3af7eb65 100644 --- a/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -13,9 +13,7 @@ describe("streamChatResponse - Mode Switch During Streaming", () => { const toolPermissionService = services.toolPermissions; beforeEach(async () => { // Clean up service container state before each test - const services = Object.keys(SERVICE_NAMES); - - services.forEach((service) => { + Object.values(SERVICE_NAMES).forEach((service) => { (serviceContainer as any).services.delete(service); (serviceContainer as any).factories.delete(service); (serviceContainer as any).dependencies.delete(service); diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 3bcbf43a4..2c7ef9566 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -391,6 +391,7 @@ export async function streamChatResponse( // Get response from LLM const { content, toolCalls, shouldContinue } = await processStreamingResponse({ + isHeadless, chatHistory, model, llmApi, diff --git a/packages/config-yaml/src/markdown/workflowFiles.test.ts b/packages/config-yaml/src/markdown/workflowFiles.test.ts index 9304542b9..50e802418 100644 --- a/packages/config-yaml/src/markdown/workflowFiles.test.ts +++ b/packages/config-yaml/src/markdown/workflowFiles.test.ts @@ -485,4 +485,120 @@ describe("parseWorkflowTools", () => { allBuiltIn: false, }); }); + + describe("whitespace validation in colon-separated MCP tool references", () => { + it("should reject MCP tool reference with space after colon", () => { + expect(() => parseWorkflowTools("owner/slug: tool")).toThrow( + 'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with space before colon", () => { + expect(() => parseWorkflowTools("owner/slug :tool")).toThrow( + 'Invalid MCP tool reference "owner/slug :tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with spaces around colon", () => { + expect(() => parseWorkflowTools("owner/slug : tool")).toThrow( + 'Invalid MCP tool reference "owner/slug : tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with space in tool name", () => { + expect(() => parseWorkflowTools("owner/slug:my tool")).toThrow( + 'Invalid MCP tool reference "owner/slug:my tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with space in server slug", () => { + expect(() => parseWorkflowTools("owner /slug:tool")).toThrow( + 'Invalid MCP tool reference "owner /slug:tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with tab character", () => { + expect(() => parseWorkflowTools("owner/slug:\ttool")).toThrow( + 'Invalid MCP tool reference "owner/slug:\ttool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with newline character", () => { + expect(() => parseWorkflowTools("owner/slug:\ntool")).toThrow( + 'Invalid MCP tool reference "owner/slug:\ntool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with multiple spaces", () => { + expect(() => parseWorkflowTools("owner/slug: tool ")).toThrow( + 'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should reject MCP tool reference with leading spaces in tool name", () => { + expect(() => parseWorkflowTools("owner/slug: tool")).toThrow( + 'Invalid MCP tool reference "owner/slug: tool": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should accept valid colon-separated MCP tool reference without whitespace", () => { + const result = parseWorkflowTools("owner/package:tool_name"); + expect(result).toEqual({ + tools: [{ mcpServer: "owner/package", toolName: "tool_name" }], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + it("should accept valid MCP tool references with hyphens and underscores", () => { + const result = parseWorkflowTools( + "owner-name/package_name:tool-name_123", + ); + expect(result).toEqual({ + tools: [ + { + mcpServer: "owner-name/package_name", + toolName: "tool-name_123", + }, + ], + mcpServers: ["owner-name/package_name"], + allBuiltIn: false, + }); + }); + + it("should allow whitespace between comma-separated items", () => { + const result = parseWorkflowTools( + "owner/package:tool1, owner/package:tool2 , bash", + ); + expect(result).toEqual({ + tools: [ + { mcpServer: "owner/package", toolName: "tool1" }, + { mcpServer: "owner/package", toolName: "tool2" }, + { toolName: "bash" }, + ], + mcpServers: ["owner/package"], + allBuiltIn: false, + }); + }); + + it("should reject whitespace in one reference but accept valid references in same string", () => { + expect(() => + parseWorkflowTools("owner/package:tool1, owner/package: tool2, bash"), + ).toThrow( + 'Invalid MCP tool reference "owner/package: tool2": colon-separated tool references cannot contain whitespace', + ); + }); + + it("should not reject whitespace in MCP server references without colon", () => { + // Note: This behavior may or may not be desired, but documents current behavior + // Server-only references (no colon) don't trigger the whitespace check + expect(() => parseWorkflowTools("owner /package")).not.toThrow(); + }); + + it("should not reject whitespace in built-in tool names", () => { + // Note: This behavior may or may not be desired, but documents current behavior + // Built-in tools (no slash) don't trigger the whitespace check + expect(() => parseWorkflowTools("my tool")).not.toThrow(); + }); + }); }); diff --git a/packages/config-yaml/src/markdown/workflowFiles.ts b/packages/config-yaml/src/markdown/workflowFiles.ts index e6ba9226d..0e32c794d 100644 --- a/packages/config-yaml/src/markdown/workflowFiles.ts +++ b/packages/config-yaml/src/markdown/workflowFiles.ts @@ -123,6 +123,14 @@ export function parseWorkflowTools(toolsString?: string): ParsedWorkflowTools { if (colonIndex > 0) { // Specific tool: "owner/package:tool_name" + // Reject references with whitespace to prevent silent misconfigurations + if (/\s/.test(toolRef)) { + throw new Error( + `Invalid MCP tool reference "${toolRef}": colon-separated tool references cannot contain whitespace. ` + + `Use format "owner/slug:tool_name" without spaces.`, + ); + } + const mcpServer = toolRef.substring(0, colonIndex); const toolName = toolRef.substring(colonIndex + 1); From c1d7cc39e1ed5eeca104249d165153a18b76f0e5 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 4 Oct 2025 15:12:50 -0700 Subject: [PATCH 47/91] fix: remove hardcoded workflow --- extensions/cli/src/commands/chat.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index dcaaa1412..05332d80e 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -538,9 +538,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // Start active time tracking telemetryService.startActiveTime(); - options.workflow = "peter-parker/workflow-48"; - // options.headless = true; - // If not in headless mode, use unified initialization with TUI if (!options.headless) { // Process flags for TUI mode From d819d2fc2082bdf6caca5dffd2200e7ba38d5e58 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Sun, 5 Oct 2025 22:33:45 -0700 Subject: [PATCH 48/91] fix: remove extra spaces before EOF in heredoc delimiters (#8103) * fix: remove extra spaces before EOF in heredoc delimiters * fix: scripts --- .../workflows/continue-general-review.yaml | 3 + actions/general-review/action.yml | 116 ++---------------- actions/general-review/scripts/buildPrompt.js | 94 ++++++++++++++ .../general-review/scripts/writeMarkdown.js | 68 ++++++++++ 4 files changed, 177 insertions(+), 104 deletions(-) create mode 100644 actions/general-review/scripts/buildPrompt.js create mode 100644 actions/general-review/scripts/writeMarkdown.js diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 0d5e317c3..7efead1fb 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -1,6 +1,9 @@ name: Continue General Review on: + push: + branches: + - nate/fix-wf pull_request: types: [opened, ready_for_review] issue_comment: diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index 3fdb433c3..0e0387c6f 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -170,62 +170,11 @@ runs: PR_NUMBER="${{ github.event.issue.number }}" fi - # Get PR diff - gh pr diff $PR_NUMBER > pr_diff.txt - - # Get PR details - PR_TITLE=$(gh pr view $PR_NUMBER --json title -q .title) - PR_AUTHOR=$(gh pr view $PR_NUMBER --json author -q .author.login) - PR_BODY=$(gh pr view $PR_NUMBER --json body -q .body) - FILES_CHANGED=$(gh pr view $PR_NUMBER --json files -q '.files | length') - - # Create review prompt - cat > review_prompt.txt << EOF - You are reviewing a pull request. Please provide helpful, context-aware feedback. - - CONTEXT: - - Repository: ${{ github.repository }} - - PR #$PR_NUMBER: $PR_TITLE - - Files Changed: $FILES_CHANGED - - Author: $PR_AUTHOR - - REVIEW APPROACH: - 1. First, understand what this PR is trying to accomplish - 2. Check if similar patterns exist elsewhere in the codebase - 3. Focus on actual issues that affect functionality - 4. Be constructive and suggest solutions when possible - - FOCUS ON: - - Bugs that will cause failures or incorrect behavior - - Security vulnerabilities (exposed secrets, injection risks) - - Breaking changes that affect other parts of the system - - Performance issues with real impact (memory leaks, O(n²) algorithms) - - Missing tests for new features or bug fixes - - Missing documentation for APIs or complex logic - - SKIP COMMENTING ON: - - Style and formatting (handled by linters) - - Alternative approaches unless current is broken - - Minor naming unless genuinely confusing - - Trivial documentation for self-explanatory code - - Be specific with line numbers and explain why something is an issue. - - PR Description: ${PR_BODY:-No description provided} - - Code Changes: - EOF - - # Add the diff - cat pr_diff.txt >> review_prompt.txt - - cat >> review_prompt.txt << 'EOF' - - Your Review: - Please provide constructive feedback on the code changes. - Focus on issues that matter for functionality, security, and maintainability. - If the code looks good overall, acknowledge that while noting any minor suggestions. - EOF + # Gather PR context and build prompt without heredocs + gh pr diff "$PR_NUMBER" > pr_diff.txt + gh pr view "$PR_NUMBER" --json title,author,body,files > pr_data.json + node actions/general-review/scripts/buildPrompt.js "$PR_NUMBER" + rm -f pr_data.json - name: Run Continue CLI Review if: env.SHOULD_RUN == 'true' @@ -247,15 +196,7 @@ runs: if [ -z "$CONTINUE_API_KEY" ]; then echo "Warning: CONTINUE_API_KEY environment variable is not set" # Create fallback review and continue - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review skipped: CONTINUE_API_KEY not configured. - - ### Configuration Required - - Please set the CONTINUE_API_KEY secret in repository settings - - Verify that the organization and config path are valid - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md missing_api_key echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "SKIP_CLI=false" >> $GITHUB_ENV @@ -277,15 +218,7 @@ runs: echo "Testing Continue CLI..." if ! which cn > /dev/null 2>&1; then echo "Warning: Continue CLI not found or not working" - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review skipped: Continue CLI installation failed. - - ### Troubleshooting - - Check that npm installation succeeded - - Verify @continuedev/cli package is available - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md cli_install_failed echo "SKIP_CLI=true" >> $GITHUB_ENV else echo "Continue CLI found at: $(which cn)" @@ -321,11 +254,7 @@ runs: # Check if output is empty if [ ! -s code_review.md ]; then echo "Warning: Continue CLI returned empty output" - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue CLI returned an empty response. Please check the configuration. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md empty_output fi else echo "Error: Continue CLI command failed with exit code $?" @@ -334,34 +263,13 @@ runs: # Check for specific error patterns if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md cli_not_found elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md config_error elif grep -q "api\|auth" cli_error.log 2>/dev/null; then - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY. - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md auth_error else - cat > code_review.md << 'EOF' - ## Code Review Summary - - ⚠️ AI review failed. Please check the Continue API key and configuration. - - ### Troubleshooting - - Verify the CONTINUE_API_KEY secret is set correctly - - Check that the organization and config path are valid - - Ensure the Continue service is accessible - EOF + node actions/general-review/scripts/writeMarkdown.js code_review.md generic_failure fi fi diff --git a/actions/general-review/scripts/buildPrompt.js b/actions/general-review/scripts/buildPrompt.js new file mode 100644 index 000000000..2f454d144 --- /dev/null +++ b/actions/general-review/scripts/buildPrompt.js @@ -0,0 +1,94 @@ +const fs = require("fs"); +const path = require("path"); + +function main() { + const prNumber = process.argv[2]; + if (!prNumber) { + console.error( + "buildPrompt.js requires the PR number as the first argument", + ); + process.exit(1); + } + + const prDataPath = path.resolve(process.cwd(), "pr_data.json"); + const prDiffPath = path.resolve(process.cwd(), "pr_diff.txt"); + const outputPath = path.resolve(process.cwd(), "review_prompt.txt"); + + if (!fs.existsSync(prDataPath)) { + console.error(`Missing PR metadata file: ${prDataPath}`); + process.exit(1); + } + + if (!fs.existsSync(prDiffPath)) { + console.error(`Missing PR diff file: ${prDiffPath}`); + process.exit(1); + } + + const repo = process.env.GITHUB_REPOSITORY || "unknown-repo"; + let prData; + + try { + prData = JSON.parse(fs.readFileSync(prDataPath, "utf8")); + } catch (error) { + console.error("Failed to parse PR metadata JSON:", error); + process.exit(1); + } + + const filesChanged = Array.isArray(prData.files) ? prData.files.length : 0; + const authorLogin = prData.author?.login || "unknown-author"; + const title = prData.title || "Untitled"; + const prBody = + prData.body && prData.body.trim() + ? prData.body.trim() + : "No description provided"; + const diff = fs.readFileSync(prDiffPath, "utf8"); + + const promptSections = [ + "You are reviewing a pull request. Please provide helpful, context-aware feedback.", + "", + "CONTEXT:", + `- Repository: ${repo}`, + `- PR #${prNumber}: ${title}`, + `- Files Changed: ${filesChanged}`, + `- Author: ${authorLogin}`, + "", + "REVIEW APPROACH:", + "1. First, understand what this PR is trying to accomplish", + "2. Check if similar patterns exist elsewhere in the codebase", + "3. Focus on actual issues that affect functionality", + "4. Be constructive and suggest solutions when possible", + "", + "FOCUS ON:", + "- Bugs that will cause failures or incorrect behavior", + "- Security vulnerabilities (exposed secrets, injection risks)", + "- Breaking changes that affect other parts of the system", + "- Performance issues with real impact (memory leaks, O(n²) algorithms)", + "- Missing tests for new features or bug fixes", + "- Missing documentation for APIs or complex logic", + "", + "SKIP COMMENTING ON:", + "- Style and formatting (handled by linters)", + "- Alternative approaches unless current is broken", + "- Minor naming unless genuinely confusing", + "- Trivial documentation for self-explanatory code", + "", + "Be specific with line numbers and explain why something is an issue.", + "", + `PR Description: ${prBody}`, + "", + "Code Changes:", + diff.trimEnd(), + "", + "Your Review:", + "Please provide constructive feedback on the code changes.", + "Focus on issues that matter for functionality, security, and maintainability.", + "If the code looks good overall, acknowledge that while noting any minor suggestions.", + ]; + + const prompt = `${promptSections.join("\n")}\n`; + + fs.writeFileSync(outputPath, prompt, "utf8"); + console.log(`Wrote review prompt to ${outputPath}`); +} + +main(); diff --git a/actions/general-review/scripts/writeMarkdown.js b/actions/general-review/scripts/writeMarkdown.js new file mode 100644 index 000000000..8ada50bbd --- /dev/null +++ b/actions/general-review/scripts/writeMarkdown.js @@ -0,0 +1,68 @@ +const fs = require("fs"); +const path = require("path"); + +const messages = { + missing_api_key: `## Code Review Summary + +⚠️ AI review skipped: CONTINUE_API_KEY not configured. + +### Configuration Required +- Please set the CONTINUE_API_KEY secret in repository settings +- Verify that the organization and config path are valid +`, + cli_install_failed: `## Code Review Summary + +⚠️ AI review skipped: Continue CLI installation failed. + +### Troubleshooting +- Check that npm installation succeeded +- Verify @continuedev/cli package is available +`, + empty_output: `## Code Review Summary + +⚠️ Continue CLI returned an empty response. Please check the configuration. +`, + cli_not_found: `## Code Review Summary + +⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally. +`, + config_error: `## Code Review Summary + +⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub. +`, + auth_error: `## Code Review Summary + +⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY. +`, + generic_failure: `## Code Review Summary + +⚠️ AI review failed. Please check the Continue API key and configuration. + +### Troubleshooting +- Verify the CONTINUE_API_KEY secret is set correctly +- Check that the organization and config path are valid +- Ensure the Continue service is accessible +`, +}; + +function main() { + const [outputPath, messageKey] = process.argv.slice(2); + + if (!outputPath || !messageKey) { + console.error("Usage: node writeMarkdown.js "); + process.exit(1); + } + + const message = messages[messageKey]; + + if (!message) { + console.error(`Unknown message key: ${messageKey}`); + process.exit(1); + } + + const absolutePath = path.resolve(process.cwd(), outputPath); + fs.writeFileSync(absolutePath, message, "utf8"); + console.log(`Wrote ${messageKey} message to ${absolutePath}`); +} + +main(); From 9914cd2f0229c85f2486dfe16bc80530edc04925 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 6 Oct 2025 22:50:54 +0530 Subject: [PATCH 49/91] fix(cli): pasting chunks of lesser than 50 characters --- extensions/cli/src/ui/TextBuffer.test.ts | 25 ++++++++++++++--- extensions/cli/src/ui/TextBuffer.ts | 34 +++++++++++------------- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/extensions/cli/src/ui/TextBuffer.test.ts b/extensions/cli/src/ui/TextBuffer.test.ts index a9d539ed3..c6cc18cda 100644 --- a/extensions/cli/src/ui/TextBuffer.test.ts +++ b/extensions/cli/src/ui/TextBuffer.test.ts @@ -526,12 +526,31 @@ describe("TextBuffer", () => { buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); // Small typed input should not be mixed into paste - const typedChar = "a"; - buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); - expect(buffer.text).toBe("a"); + const smallChunk = "abc"; + buffer.handleInput(smallChunk, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe(""); // Both chunks buffered buffer.flushPendingInput(); + expect(buffer.text).toBe(largeChunk + smallChunk); + }); + + it("should allow typing after paste accumulation delay", () => { + vi.useFakeTimers(); + + const largeChunk = "x".repeat(100); + buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any); + + // Advance time to simulate user typing after a delay + vi.advanceTimersByTime(60); // so that it is treated as typing + + const typedChar = "a"; + buffer.handleInput(typedChar, { ctrl: false, meta: false } as any); + expect(buffer.text).toBe("a"); // Typed char inserted immediately + + vi.advanceTimersByTime(250); // Finalize paste expect(buffer.text).toBe("a" + largeChunk); + + vi.useRealTimers(); }); it("should preserve all chunks when expanding (content loss fix)", () => { diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index 65784e852..768ab0b4b 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -337,26 +337,24 @@ export class TextBuffer { const timeSinceLastInput = now - this._lastInputTime; // If we're already in rapid input mode and this comes quickly, add to buffer - // But only if it's a reasonably large chunk - small inputs are likely typing, not paste - // This prevents typed characters from being mixed into paste content during accumulation - if ( - this._rapidInputBuffer.length > 0 && - timeSinceLastInput < 200 && - input.length >= 50 - ) { - this._rapidInputBuffer += input; - this._lastInputTime = now; + if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 200) { + const isLikelyTyping = input.length < 50 && timeSinceLastInput >= 50; - if (this._rapidInputTimer) { - clearTimeout(this._rapidInputTimer); + if (!isLikelyTyping) { + this._rapidInputBuffer += input; + this._lastInputTime = now; + + if (this._rapidInputTimer) { + clearTimeout(this._rapidInputTimer); + } + + // Reset timer: 200ms pause indicates end of paste + this._rapidInputTimer = setTimeout(() => { + this.finalizeRapidInput(); + }, 200); + + return true; } - - // Reset timer: 200ms pause indicates end of paste - this._rapidInputTimer = setTimeout(() => { - this.finalizeRapidInput(); - }, 200); - - return true; } // Fallback paste detection: some terminals send large pastes as rapid chunks From fd6d0c2b6e0cee986bd8a5057a74b2da3206a0b0 Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Mon, 6 Oct 2025 11:37:28 -0700 Subject: [PATCH 50/91] docs: Add Chrome DevTools Performance Cookbook with MCP integration (#8088) * docs: add Chrome DevTools Performance Cookbook guide - Add chrome-devtools-mcp-performance to docs navigation - Include Chrome DevTools guide in overview with description - Reorganize cookbook order in overview for better flow Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * docs: improve formatting in Chrome DevTools Performance guide - Convert 'What You've Built' section to proper list format with bullets - Add left alignment to Performance Issue Quick Reference table - Enhance readability with bold formatting for key phrases Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * docs: update Chrome DevTools guide with Hub integration and fixes - Replace JSON config with proper YAML format following Continue Hub schema - Add pre-built agent workflow using continuedev/chrome-dev-continuous - Reference official Chrome DevTools MCP at hub.continue.dev/google/chrome-devtools-mcp - Fix Card icon rendering issue (rocket instead of zap with emoji) - Update Node.js prerequisite from 18+ to 20+ - Follow PostHog cookbook structure for consistency Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Fix Chrome DevTools guide to remove cn prefix in TUI step - Updated Step 2 in Quick Start to clarify users are already in TUI mode - Changed 'From your project directory, run: cn "..."' to 'In the TUI that opens, type: ...' - This matches the workflow where Step 1 runs 'cn --config' which opens TUI - Also updated wording in other guides from 'Navigate to' to 'From' for clarity Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Fix Chrome DevTools GitHub Actions workflow to use cn --config - Removed invalid 'cn auth login' command - Updated to use 'cn --config continuedev/chrome-dev-continuous' like dlt cookbook - Added --auto flag for headless execution - Fixed line continuation formatting for better readability Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --------- Co-authored-by: Continue --- docs/docs.json | 3 +- .../chrome-devtools-mcp-performance.mdx | 798 ++++++++++++++++++ .../netlify-mcp-continuous-deployment.mdx | 2 +- docs/guides/overview.mdx | 1 + docs/guides/posthog-github-continuous-ai.mdx | 2 +- docs/guides/snyk-mcp-continue-cookbook.mdx | 2 +- 6 files changed, 804 insertions(+), 4 deletions(-) create mode 100644 docs/guides/chrome-devtools-mcp-performance.mdx diff --git a/docs/docs.json b/docs/docs.json index 1e783f7ee..34d6de9fe 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -264,7 +264,8 @@ "guides/sanity-mcp-continue-cookbook", "guides/snyk-mcp-continue-cookbook", "guides/dlt-mcp-continue-cookbook", - "guides/netlify-mcp-continuous-deployment" + "guides/netlify-mcp-continuous-deployment", + "guides/chrome-devtools-mcp-performance" ] } ] diff --git a/docs/guides/chrome-devtools-mcp-performance.mdx b/docs/guides/chrome-devtools-mcp-performance.mdx new file mode 100644 index 000000000..02a24edd3 --- /dev/null +++ b/docs/guides/chrome-devtools-mcp-performance.mdx @@ -0,0 +1,798 @@ +--- +title: "Chrome DevTools Performance Optimization Cookbook" +description: "Measure and optimize web performance with Chrome DevTools MCP, automated performance traces, and Core Web Vitals monitoring using Continue." +sidebarTitle: "Chrome DevTools MCP for Performance" +--- + + + Use AI to automatically trace performance, analyze Core Web Vitals, diagnose bottlenecks, and get actionable optimization suggestions directly from Chrome DevTools + + + + **Did You Know?** Chrome DevTools MCP brings the full power of browser debugging to your AI workflow: + - [Performance Traces](https://developer.chrome.com/docs/devtools/performance) with automated analysis + - [Network Request Monitoring](https://developer.chrome.com/docs/devtools/network) for bottleneck detection + - [Console Debugging](https://developer.chrome.com/docs/devtools/console) with error pattern recognition + - [CPU & Network Throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) to simulate real-world conditions + - [Performance Insights](https://developer.chrome.com/docs/devtools/performance-insights) with AI-powered analysis + - [Screenshot Debugging](https://developer.chrome.com/docs/devtools/device-mode) for visual regression detection + +This guide shows you how to leverage these features through natural language with Continue CLI! + + + +## What You'll Learn + +This cookbook teaches you to: + +- Run automated [performance traces](https://developer.chrome.com/docs/devtools/performance) to capture runtime metrics +- Analyze [Core Web Vitals](https://web.dev/vitals/) (LCP, FID, CLS, INP) and performance insights +- Diagnose performance bottlenecks using network and console analysis +- Test performance under different network and CPU conditions with [throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) +- Automate visual regression testing with [screenshots](https://developer.chrome.com/docs/devtools/device-mode) + +## Prerequisites + +- Chrome browser installed +- Web project with a running development server (or deployed URL) +- Node.js 20+ installed +- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`) +- [Chrome DevTools MCP](https://hub.continue.dev) configured + +## Quick Setup + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + +## Chrome DevTools MCP Workflow Options + + + Skip the manual setup and use our pre-built Chrome DevTools agent that includes + optimized prompts, rules, and the Chrome DevTools MCP for more consistent results. + + +After completing **Quick Setup** above, you have two paths to get started: + + + + **Perfect for:** Immediate results with optimized prompts and built-in performance analysis + + + + Visit the [Chrome DevTools Continuous Agent](https://hub.continue.dev/continuedev/chrome-dev-continuous) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --config continuedev/chrome-dev-continuous + ``` + + This agent includes: + - **Optimized prompts** for performance analysis and debugging + - **Built-in rules** for consistent formatting and error handling + - **[Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp)** for reliable browser automation + + + + In the TUI that opens, type: + ``` + Analyze performance of http://localhost:3000 and provide optimization recommendations + ``` + + That's it! The agent handles Chrome automation automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Chrome DevTools MCP integration and pre-tested prompts. + + + + + + + + Visit the [Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp) on Continue Hub and add it to your assistant, or add this to your configuration: + + ```yaml + name: Chrome DevTools MCP + version: 0.0.1 + schema: v1 + mcpServers: + - name: Chrome DevTools MCP + command: npx + args: + - chrome-devtools-mcp@latest + ``` + + The MCP will automatically launch Chrome and connect to DevTools when needed. + + + + Test the connection: + + **TUI Mode Prompt:** + ``` + Open web.dev and take a screenshot + ``` + + + + Navigate to your project directory: + + **TUI Mode Prompt:** + ``` + Navigate to http://localhost:3000 and record a performance trace. Analyze LCP, FID, and CLS. + ``` + + + + + **Manual Setup**: While you can configure the MCP manually, the pre-built agent provides optimized prompts and better error handling for performance analysis workflows. + + + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + - **Chrome browser** installed on your system + - **Node.js 20+** to run the MCP via npx + + The agent will automatically detect and use your configuration. + + +--- + +## Performance Measurement Workflows + +The Chrome DevTools MCP enables natural language performance analysis. Here are workflows adapted from real-world use cases: + +### Quick Performance Checks + + +**TUI Mode Prompt:** +``` +Verify in the browser that your change works as expected. +``` + + + +**TUI Mode Prompt:** +``` +A few images on localhost:8080 are not loading. What's happening? +``` + + + +**TUI Mode Prompt:** +``` +Why does submitting the form fail after entering an email address? +``` + + + +**TUI Mode Prompt:** +``` +The page on localhost:8080 looks strange and off. Check what's happening there. +``` + + + +**TUI Mode Prompt:** +``` +Localhost:8080 is loading slowly. Make it load faster. +``` + + + +**TUI Mode Prompt:** +``` +Please check the LCP of web.dev. +``` + + +--- + +## Performance Analysis Recipes + +Now you can use natural language prompts to analyze web performance. The Continue agent automatically calls the appropriate Chrome DevTools MCP tools. + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands + + **Test in Plan Mode First**: Before running performance measurements, test your prompts in plan mode (see the [Plan Mode Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This shows you what the agent will do without executing it. + + +### Step 1: Baseline Performance Trace + +Establish your current performance baseline: + +**TUI Mode Prompt:** +``` +Navigate to http://localhost:3000 and record a performance trace with page reload. Analyze the trace and show me the LCP, FID, CLS, and total blocking time. +``` + + + + + Chrome DevTools Performance Panel automatically tracks: + - **Core Web Vitals**: LCP, FID, CLS, INP + - **Loading Performance**: DOMContentLoaded, Load events, First Paint + - **Runtime Performance**: JavaScript execution time, layout shifts, paint events + - **Resource Usage**: Memory consumption, CPU utilization + + + +### Step 2: Analyze Performance Insights + +Deep dive into specific performance issues: + +**TUI Mode Prompt:** +``` +Record a performance trace for http://localhost:3000 and analyze all Performance Insights. For each insight found, provide detailed information about: +- The specific issue (e.g., DocumentLatency, SlowCSS) +- Root cause analysis +- Affected resources or code +- Recommended optimizations +- Expected impact on Core Web Vitals +``` + + + **Performance Insights**: Chrome DevTools automatically detects common performance issues like: + - **Render Blocking Resources**: CSS and JavaScript that delay first paint + - **Layout Shifts**: Elements that move during page load + - **Long Tasks**: JavaScript execution blocking the main thread + - **Slow Network Requests**: Resources taking too long to load + - **Unused CSS/JavaScript**: Dead code increasing bundle size + + +### Step 3: Network Performance Analysis + +Identify slow network requests and optimization opportunities: + +**TUI Mode Prompt:** +``` +Navigate to https://my-site.com and: +1. List all network requests made during page load +2. Identify the 5 slowest requests and their sizes +3. Find any requests over 1MB +4. Detect render-blocking resources +5. Check for inefficient caching (missing cache headers) +6. Suggest specific optimizations for each issue found +``` + +### Step 4: Throttling Performance Tests + +Test performance under real-world network and CPU conditions: + +**TUI Mode Prompt:** +``` +Test my site's performance under different conditions: + +1. Navigate to http://localhost:3000 +2. Emulate 4x CPU slowdown and Fast 3G network +3. Record a performance trace with reload +4. Analyze LCP and Total Blocking Time +5. Take a screenshot when page is fully loaded + +Then repeat the test with: +- Slow 3G network + 6x CPU slowdown +- Offline network (to test service worker) + +Compare results and identify which conditions cause the worst performance degradation." +``` + + + **Available Network Presets**: + - No throttling + - Fast 3G (1.6 Mbps down, 0.75 Mbps up) + - Slow 3G (400 Kbps down, 400 Kbps up) + - Offline + + **CPU Throttling**: 4x, 6x, or custom slowdown to simulate low-end devices + + +### Step 5: JavaScript Performance Analysis + +Identify expensive JavaScript operations: + +**TUI Mode Prompt:** +``` +Record a performance trace for http://localhost:3000 and: +1. Identify all long tasks (>50ms) blocking the main thread +2. Find the specific JavaScript functions causing these tasks +3. Measure total JavaScript execution time +4. Detect unused JavaScript being loaded +5. Show the call stack for the longest task +6. Recommend code splitting or lazy loading opportunities" +``` + +## Automated Performance Monitoring + +### Step 6: Core Web Vitals Dashboard + +Create automated monitoring for Core Web Vitals: + +**TUI Mode Prompt:** +``` +Create a performance monitoring script that: +1. Opens my site at http://localhost:3000 +2. Records a performance trace with reload +3. Extracts Core Web Vitals (LCP, FID, CLS, INP) +4. Checks console for JavaScript errors +5. Takes a screenshot +6. Saves results to performance-report.json with format: + { + 'timestamp': 'ISO date', + 'lcp': number, + 'fid': number, + 'cls': number, + 'inp': number, + 'errors': array, + 'screenshot': 'path' + } + +Save this as scripts/performance-monitor.js that I can run regularly" +``` + +### Step 7: Visual Regression Detection + +Detect unintended visual changes: + +**TUI Mode Prompt:** +``` +Set up visual regression testing: +1. Navigate to http://localhost:3000 +2. Take full-page screenshots at: + - Desktop viewport (1920x1080) + - Tablet viewport (768x1024) + - Mobile viewport (375x667) +3. Save screenshots to screenshots/baseline/ +4. Create a script to compare future screenshots against baseline +5. Highlight any pixel differences over 5% +6. Generate a visual diff report" +``` + +### Step 8: Performance Budget Enforcement + +Set and enforce performance budgets: + +**TUI Mode Prompt:** +``` +Create a performance budget checker that: + +Requirements: +- LCP must be < 2.5 seconds +- FID must be < 100ms +- CLS must be < 0.1 +- Total JavaScript < 300KB +- Total page size < 1MB +- No console errors + +Implementation: +1. Navigate to http://localhost:3000 +2. Record performance trace with reload +3. List all network requests and calculate total sizes +4. Check console messages for errors +5. Validate all metrics against budgets +6. Exit with code 1 if any budget is exceeded +7. Generate a detailed report showing pass/fail for each metric + +Save as scripts/performance-budget.js for CI/CD integration" +``` + +## Continuous Performance Testing with GitHub Actions + +This example demonstrates a **Continuous AI workflow** where performance validation runs automatically in your CI/CD pipeline using Chrome DevTools MCP in headless mode. + +### Add GitHub Secrets + +Navigate to **Repository Settings → Secrets and variables → Actions** and add: + +- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + +### Create Workflow File + +This workflow automatically validates web performance on pull requests using the Continue CLI in headless mode. It records performance traces, extracts Core Web Vitals, and posts a summary report as a PR comment. + +Create `.github/workflows/performance-check.yml` in your repository: + +```yaml +name: Performance Check + +on: + pull_request: + +jobs: + performance: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install Dependencies + run: | + npm install -g @continuedev/cli + npm ci + + - name: Build Project + run: npm run build + + - name: Start Dev Server + run: | + npm run dev & + npx wait-on http://localhost:3000 + + - name: Run Performance Tests + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + cn --config continuedev/chrome-dev-continuous \ + -p "Navigate to http://localhost:3000 and: + 1. Record performance trace with reload + 2. Extract LCP, FID, CLS values + 3. List network requests and calculate total bundle size + 4. Output results as JSON to performance.json" \ + --auto + + - name: Check Performance Budgets + run: | + node << 'EOF' + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const budgets = { + lcp: 2.5, + fid: 100, + cls: 0.1, + bundleSize: 300000 + }; + + let failed = false; + const results = []; + + if (perf.lcp > budgets.lcp) { + results.push(`❌ LCP: ${perf.lcp}s (budget: ${budgets.lcp}s)`); + failed = true; + } else { + results.push(`✅ LCP: ${perf.lcp}s`); + } + + if (perf.fid > budgets.fid) { + results.push(`❌ FID: ${perf.fid}ms (budget: ${budgets.fid}ms)`); + failed = true; + } else { + results.push(`✅ FID: ${perf.fid}ms`); + } + + if (perf.cls > budgets.cls) { + results.push(`❌ CLS: ${perf.cls} (budget: ${budgets.cls})`); + failed = true; + } else { + results.push(`✅ CLS: ${perf.cls}`); + } + + if (perf.bundleSize > budgets.bundleSize) { + results.push(`❌ Bundle: ${perf.bundleSize}KB (budget: ${budgets.bundleSize}KB)`); + failed = true; + } else { + results.push(`✅ Bundle: ${perf.bundleSize}KB`); + } + + console.log(results.join('\n')); + + if (failed) { + process.exit(1); + } + EOF + + - name: Comment Performance Results + if: always() + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const perf = JSON.parse(fs.readFileSync('performance.json')); + + const comment = `## 📊 Performance Report + + | Metric | Value | Budget | Status | + |--------|-------|--------|--------| + | LCP | ${perf.lcp}s | 2.5s | ${perf.lcp <= 2.5 ? '✅' : '❌'} | + | FID | ${perf.fid}ms | 100ms | ${perf.fid <= 100 ? '✅' : '❌'} | + | CLS | ${perf.cls} | 0.1 | ${perf.cls <= 0.1 ? '✅' : '❌'} | + | Bundle Size | ${perf.bundleSize}KB | 300KB | ${perf.bundleSize <= 300 ? '✅' : '❌'} | + + ${perf.lcp > 2.5 || perf.fid > 100 || perf.cls > 0.1 || perf.bundleSize > 300 + ? '⚠️ **Performance budgets exceeded. Please optimize before merging.**' + : '✅ **All performance budgets met!**'}`; + + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: comment + }); +``` + + + The Chrome DevTools MCP works in headless Chrome environments. Make sure your CI environment has Chrome installed (it's pre-installed on GitHub Actions ubuntu-latest runners). + + +## Advanced Performance Workflows + +### Step 9: Competitor Comparison + +Compare your site's performance with competitors: + +**TUI Mode Prompt:** +``` +Compare performance between my site and competitors: + +Sites to test: +- http://localhost:3000 (my site) +- https://competitor1.com +- https://competitor2.com + +For each site: +1. Navigate to homepage +2. Record performance trace with reload +3. Extract LCP, FID, CLS, Total Blocking Time +4. List network requests and calculate total page size +5. Count JavaScript and CSS files + +Create a comparison table showing: +- Site name +- All Core Web Vitals +- Total page size +- Number of requests +- Which site performs best for each metric + +Provide specific recommendations for how my site can improve based on what competitors do better." +``` + +### Step 10: Performance Testing Across Routes + +Test performance consistency across your entire site: + +**TUI Mode Prompt:** +``` +Test performance across all major routes: + +Routes to test: +- / (homepage) +- /products +- /products/[id] (pick a sample product) +- /checkout +- /blog + +For each route: +1. Navigate to the URL +2. Record performance trace +3. Extract LCP, Total Blocking Time, bundle size +4. Check console for errors +5. Take a screenshot + +Generate a report showing: +- Which routes have the worst LCP +- Routes with the most JavaScript errors +- Bundle size variations across routes +- Recommendations for route-specific optimizations" +``` + +### Step 11: Mobile Performance Analysis + +Focus on mobile-specific performance issues: + +**TUI Mode Prompt:** +``` +Analyze mobile performance for http://localhost:3000: + +1. Resize viewport to mobile (375x667) +2. Emulate Slow 3G network + 4x CPU slowdown +3. Record performance trace with reload +4. Analyze Performance Insights for mobile-specific issues +5. Check for: + - Touch target sizes too small + - Horizontal scrolling issues + - Oversized images not optimized for mobile + - Excessive JavaScript on mobile +6. Take mobile screenshot +7. Provide mobile-specific optimization recommendations" +``` + +## Performance Troubleshooting + +### Debug Performance Regressions + +Quickly identify what caused a performance regression: + +**TUI Mode Prompt:** +``` +Debug performance regression on http://localhost:3000: + +1. Record performance trace +2. Analyze all Performance Insights +3. List console errors and warnings +4. Check network requests for: + - Failed requests + - Slow requests (>1s) + - Large requests (>500KB) +5. Identify the top 3 performance bottlenecks +6. For each bottleneck, suggest: + - Root cause + - Specific code or resource causing it + - Step-by-step fix + - Expected performance improvement" +``` + +### Performance Issue Quick Reference + +| Issue | Quick Fix Command (in cn TUI) | +| :---- | :---------------------------- | +| Slow LCP | `"Find render-blocking resources and suggest preloading or deferring"` | +| High CLS | `"Detect layout shifts and identify unsized images or dynamic content"` | +| Long Tasks | `"Find JavaScript tasks over 50ms and suggest code splitting"` | +| Large Bundles | `"List all JavaScript files, identify largest ones, suggest lazy loading"` | +| Slow Network | `"Find requests over 500KB and suggest compression or optimization"` | +| Console Errors | `"List all console errors and suggest fixes"` | + +## What You've Built + +After completing this guide, you have a complete **AI-powered performance analysis system** that: + +- ✅ **Uses natural language** — Simple prompts instead of complex DevTools commands +- ✅ **Analyzes automatically** — AI interprets performance traces and suggests fixes +- ✅ **Runs continuously** — Automated validation in CI/CD pipelines +- ✅ **Ensures quality** — Performance checks prevent regressions from shipping + + + Your performance workflow now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine performance analysis and debugging with human oversight through review and approval of changes. + + +## Chrome DevTools MCP Capabilities + + + + + **Tools Available** + - `performance_start_trace`: Start recording with auto-reload + - `performance_stop_trace`: Stop and analyze trace + - `performance_analyze_insight`: Deep dive into specific issues + + + + + + **Tools Available** + - `list_network_requests`: See all requests and sizes + - `get_network_request`: Inspect specific request details + - `emulate_network`: Test under various network conditions + + + + + + **Tools Available** + - `list_console_messages`: Get all console logs and errors + - `evaluate_script`: Run JavaScript in page context + - Automatic error pattern detection + + + + + + **Tools Available** + - `take_screenshot`: Capture full or partial page + - `take_snapshot`: Get accessibility tree snapshot + - `resize_page`: Test responsive layouts + + + + +## Performance Best Practices + +Key metrics to monitor for optimal web performance: + + + + - LCP < 2.5s (good) + - FID < 100ms (good) + - CLS < 0.1 (good) + - INP < 200ms (good) + + + + - Total page size < 1MB + - JavaScript < 300KB + - Time to Interactive < 3.8s + - First Contentful Paint < 1.8s + + + + - No long tasks > 50ms + - 60 FPS during interactions + - No memory leaks + - Efficient event listeners + + + +## Advanced Testing Scenarios + +### A/B Test Performance Impact + +**TUI Mode Prompt:** +``` +Compare performance of two implementations: +1. Test variant A at http://localhost:3000?variant=A +2. Test variant B at http://localhost:3000?variant=B +Run each test 5 times and calculate average LCP, FID, CLS +Determine which variant has better performance and by how much +``` + +### Lighthouse Score Tracking + +**TUI Mode Prompt:** +``` +Create a script that runs daily performance audits: +1. Navigate to production site +2. Record performance trace +3. Calculate Lighthouse-style performance score based on: + - FCP (10%) + - SI (10%) + - LCP (25%) + - TTI (10%) + - TBT (30%) + - CLS (15%) +4. Track score over time in performance-history.json +5. Alert if score drops below 90 +``` + +### Performance Regression Detection + +**TUI Mode Prompt:** +``` +Set up automated regression detection: +1. Record baseline performance for main branch +2. Save baseline metrics to baseline-perf.json +3. On each PR, run performance tests +4. Compare PR metrics with baseline +5. Flag regressions over 10% for any metric +6. Generate visual diff report with screenshots +``` + +## Next Steps + +1. **Analyze your first site** - Try the baseline performance trace on your current project +2. **Debug bottlenecks** - Use the network analysis prompt to fix slow requests +3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo +4. **Test throttling** - Measure performance under real-world network conditions +5. **Monitor trends** - Track Core Web Vitals over time + +## Additional Resources + + + + Official Chrome DevTools MCP repository + + + Explore more MCP integrations + + + Complete Chrome DevTools documentation + + + Learn about Core Web Vitals + + diff --git a/docs/guides/netlify-mcp-continuous-deployment.mdx b/docs/guides/netlify-mcp-continuous-deployment.mdx index c852de1de..a6e53a6ef 100644 --- a/docs/guides/netlify-mcp-continuous-deployment.mdx +++ b/docs/guides/netlify-mcp-continuous-deployment.mdx @@ -95,7 +95,7 @@ After completing **Quick Setup** above, you have two paths to get started: - Navigate to your project directory and run: + From your project directory, run: ```bash cn "Analyze my Netlify site's performance and optimize it for better Core Web Vitals." ``` diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index fb0f486e3..13a8d0534 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -22,6 +22,7 @@ Step-by-step guides for integrating Model Context Protocol (MCP) servers with Co - [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows - [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation - [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP +- [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets - [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP - [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers - [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging diff --git a/docs/guides/posthog-github-continuous-ai.mdx b/docs/guides/posthog-github-continuous-ai.mdx index b5aac1a1b..e4421f7ed 100644 --- a/docs/guides/posthog-github-continuous-ai.mdx +++ b/docs/guides/posthog-github-continuous-ai.mdx @@ -147,7 +147,7 @@ You only need to configure the PostHog MCP credential - it automatically handles - Navigate to your project directory and run: + From your project directory, run: ```bash cn "Give me my PostHog Session data and create GitHub issues based on the problems." ``` diff --git a/docs/guides/snyk-mcp-continue-cookbook.mdx b/docs/guides/snyk-mcp-continue-cookbook.mdx index 850b1f212..cd45ac71e 100644 --- a/docs/guides/snyk-mcp-continue-cookbook.mdx +++ b/docs/guides/snyk-mcp-continue-cookbook.mdx @@ -74,7 +74,7 @@ After ensuring you meet the **Prerequisites** above, you have two paths to get s - Start with a comprehensive security scan: + From your project directory, start with a comprehensive security scan: ```bash # Headless mode cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity." --auto From a0a287e9789b498ab7e3c3722a21af1dd2b033fa Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 13:13:57 -0700 Subject: [PATCH 51/91] feat: cli banner --- .../config/components/CliInstallBanner.tsx | 85 +++++++++++++++++++ gui/src/pages/config/index.tsx | 8 +- 2 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 gui/src/pages/config/components/CliInstallBanner.tsx diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx new file mode 100644 index 000000000..013f5ef5a --- /dev/null +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -0,0 +1,85 @@ +import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { useContext, useEffect, useState } from "react"; +import Alert from "../../../components/gui/Alert"; +import { Button } from "../../../components/ui/Button"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { getPlatform } from "../../../util"; + +export function CliInstallBanner() { + const ideMessenger = useContext(IdeMessengerContext); + const [cliInstalled, setCliInstalled] = useState(null); + const [dismissed, setDismissed] = useState(false); + + useEffect(() => { + const checkCliInstallation = async () => { + try { + const platform = getPlatform(); + // Use 'which' on mac/linux, 'where' on windows + const command = platform === "windows" ? "where cn" : "which cn"; + + const [stdout, stderr] = await ideMessenger.ide.subprocess(command); + + // If stdout has content (path to cn), it's installed + // If empty or stderr has "not found", it's not installed + const isInstalled = + stdout.trim().length > 0 && !stderr.includes("not found"); + setCliInstalled(isInstalled); + } catch (error) { + // If subprocess throws an error, assume CLI is not installed + setCliInstalled(false); + } + }; + + checkCliInstallation(); + }, [ideMessenger]); + + // Don't show if still loading, already installed, or dismissed + // if (cliInstalled === null || cliInstalled === true || dismissed) { + // return null; + // } + + return ( +
+ +
+ +
+
Try the Continue CLI
+
+ Use{" "} + + cn + {" "} + in your terminal for command-line coding assistance with + interactive and headless modes. +
+
+ + npm i -g @continuedev/cli + + +
+
+ +
+
+
+ ); +} diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 283f48dff..eae76dbd8 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -8,6 +8,7 @@ import { TabGroup } from "../../components/ui/TabGroup"; import { useAuth } from "../../context/Auth"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { bottomTabSections, getAllTabs, topTabSections } from "./configTabs"; +import { CliInstallBanner } from "./components/CliInstallBanner"; import { AccountDropdown } from "./features/account/AccountDropdown"; function ConfigPage() { @@ -89,8 +90,11 @@ function ConfigPage() { {/* Tab Content for larger screens (md and above) */} -
- {allTabs.find((tab) => tab.id === activeTab)?.component} +
+
+ {allTabs.find((tab) => tab.id === activeTab)?.component} +
+
From 3be744b70e2d5b20064a1c868b2a68e108a6d947 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 13:24:47 -0700 Subject: [PATCH 52/91] improv: ui --- .../config/components/CliInstallBanner.tsx | 67 ++++++++++--------- 1 file changed, 35 insertions(+), 32 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index 013f5ef5a..82a0e5ddd 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -1,7 +1,7 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; -import Alert from "../../../components/gui/Alert"; -import { Button } from "../../../components/ui/Button"; +import { SecondaryButton } from "../../../components"; +import { Card } from "../../../components/ui"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { getPlatform } from "../../../util"; @@ -34,52 +34,55 @@ export function CliInstallBanner() { }, [ideMessenger]); // Don't show if still loading, already installed, or dismissed - // if (cliInstalled === null || cliInstalled === true || dismissed) { - // return null; - // } + if (cliInstalled === null || cliInstalled === true || dismissed) { + // return null; + } return (
- -
- -
-
Try the Continue CLI
-
- Use{" "} - - cn - {" "} - in your terminal for command-line coding assistance with - interactive and headless modes. + + +
+ +
+
+
+ Try the Continue CLI +
+
+ Use{" "} + + cn + {" "} + in your terminal for command-line coding assistance with + interactive and headless modes. +
-
- +
+ npm i -g @continuedev/cli - + Learn more +
-
- +
); } From ad32ef378a1175dfa82b5360e7bce2c92fdaca25 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 13:32:54 -0700 Subject: [PATCH 53/91] improv: ui --- .../config/components/CliInstallBanner.tsx | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index 82a0e5ddd..3d9472ab0 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -1,6 +1,6 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; -import { SecondaryButton } from "../../../components"; +import { CloseButton, SecondaryButton } from "../../../components"; import { Card } from "../../../components/ui"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { getPlatform } from "../../../util"; @@ -41,16 +41,12 @@ export function CliInstallBanner() { return (
- -
+ setDismissed(true)}> + + +
-
+
Try the Continue CLI @@ -64,7 +60,7 @@ export function CliInstallBanner() { interactive and headless modes.
-
+
npm i -g @continuedev/cli From bd65b07d3276466a9b1cb22ab3e775da13d3f3ab Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 13:37:34 -0700 Subject: [PATCH 54/91] improv: banner --- gui/src/pages/config/components/CliInstallBanner.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index 3d9472ab0..f2c2cd603 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -35,7 +35,7 @@ export function CliInstallBanner() { // Don't show if still loading, already installed, or dismissed if (cliInstalled === null || cliInstalled === true || dismissed) { - // return null; + return null; } return ( From 22c67999348eede38d10aae821eebc59111f6edd Mon Sep 17 00:00:00 2001 From: Aditya Mitra <61635505+uinstinct@users.noreply.github.com> Date: Tue, 7 Oct 2025 02:21:25 +0530 Subject: [PATCH 55/91] feat: auto-accept agent edits setting auto accept edit tools (#7993) * feat: auto accept edit tools * add `isAutoEditToolCall` check * show tooltip in tool section * revert accidental change * refactor * fix: tweaks on auto accept agent edit --------- Co-authored-by: Dallin Romney --- .../config/components/ToolPolicyItem.tsx | 39 ++++++++++++++++--- gui/src/redux/slices/sessionSlice.ts | 12 +----- gui/src/redux/thunks/evaluateToolPolicies.ts | 12 ++++++ gui/src/redux/thunks/streamNormalInput.ts | 1 + gui/src/util/toolCallState.ts | 10 +++++ 5 files changed, 58 insertions(+), 16 deletions(-) diff --git a/gui/src/pages/config/components/ToolPolicyItem.tsx b/gui/src/pages/config/components/ToolPolicyItem.tsx index 5d81c5908..2971e015d 100644 --- a/gui/src/pages/config/components/ToolPolicyItem.tsx +++ b/gui/src/pages/config/components/ToolPolicyItem.tsx @@ -19,6 +19,7 @@ import { import { useFontSize } from "../../../components/ui/font"; import { useAppSelector } from "../../../redux/hooks"; import { addTool, setToolPolicy } from "../../../redux/slices/uiSlice"; +import { isEditTool } from "../../../util/toolCallState"; interface ToolPolicyItemProps { tool: Tool; @@ -28,12 +29,22 @@ interface ToolPolicyItemProps { export function ToolPolicyItem(props: ToolPolicyItemProps) { const dispatch = useDispatch(); - const policy = useAppSelector( + const toolPolicy = useAppSelector( (state) => state.ui.toolSettings[props.tool.function.name], ); const [isExpanded, setIsExpanded] = useState(false); const mode = useAppSelector((state) => state.session.mode); + const autoAcceptEditToolDiffs = useAppSelector( + (state) => state.config.config.ui?.autoAcceptEditToolDiffs, + ); + const isAutoAcceptedToolCall = + isEditTool(props.tool.function.name) && autoAcceptEditToolDiffs; + + const policy = isAutoAcceptedToolCall + ? "allowedWithoutPermission" + : toolPolicy; + useEffect(() => { if (!policy) { dispatch(addTool(props.tool)); @@ -53,6 +64,7 @@ export function ToolPolicyItem(props: ToolPolicyItemProps) { const fontSize = useFontSize(-2); const disabled = + isAutoAcceptedToolCall || !props.isGroupEnabled || (mode === "plan" && props.tool.group === BUILT_IN_GROUP_NAME && @@ -100,6 +112,19 @@ export function ToolPolicyItem(props: ToolPolicyItemProps) { ) : null} + {isAutoAcceptedToolCall ? ( + + Auto-Accept Agent Edits setting is on +

+ } + > + +
+ ) : null} {props.tool.faviconUrl && ( - {disabled || policy === "disabled" - ? "Excluded" - : policy === "allowedWithoutPermission" - ? "Automatic" - : "Ask First"} + {isAutoAcceptedToolCall + ? "Automatic" + : disabled || policy === "disabled" + ? "Excluded" + : policy === "allowedWithoutPermission" + ? "Automatic" + : "Ask First"} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 541787888..dee39f856 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -25,7 +25,6 @@ import { ToolCallState, } from "core"; import type { RemoteSessionMetadata } from "core/control-plane/client"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage, @@ -36,7 +35,7 @@ import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage"; import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils"; -import { addToolCallDeltaToState } from "../../util/toolCallState"; +import { addToolCallDeltaToState, isEditTool } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; import { findChatHistoryItemByToolCallId, findToolCallById } from "../util"; @@ -51,17 +50,10 @@ import { findChatHistoryItemByToolCallId, findToolCallById } from "../util"; function filterMultipleEditToolCalls( toolCalls: ToolCallDelta[], ): ToolCallDelta[] { - const editToolNames = [ - BuiltInToolNames.EditExistingFile, - BuiltInToolNames.SingleFindAndReplace, - BuiltInToolNames.MultiEdit, - ]; let hasSeenEditTool = false; return toolCalls.filter((toolCall) => { - const isEditTool = editToolNames.includes(toolCall.function?.name as any); - - if (isEditTool) { + if (toolCall.function?.name && isEditTool(toolCall.function?.name)) { if (hasSeenEditTool) { return false; // Skip this duplicate edit tool } diff --git a/gui/src/redux/thunks/evaluateToolPolicies.ts b/gui/src/redux/thunks/evaluateToolPolicies.ts index 990aef4c8..37c009210 100644 --- a/gui/src/redux/thunks/evaluateToolPolicies.ts +++ b/gui/src/redux/thunks/evaluateToolPolicies.ts @@ -1,6 +1,7 @@ import { ToolPolicy } from "@continuedev/terminal-security"; import { Tool, ToolCallState } from "core"; import { IIdeMessenger } from "../../context/IdeMessenger"; +import { isEditTool } from "../../util/toolCallState"; import { errorToolCall, updateToolCallOutput } from "../slices/sessionSlice"; import { DEFAULT_TOOL_SETTING, ToolPolicies } from "../slices/uiSlice"; import { AppThunkDispatch } from "../store"; @@ -20,7 +21,16 @@ async function evaluateToolPolicy( activeTools: Tool[], toolCallState: ToolCallState, toolPolicies: ToolPolicies, + autoAcceptEditToolDiffs: boolean | undefined, ): Promise { + // allow edit tool calls without permission if auto-accept is enabled + if ( + isEditTool(toolCallState.toolCall.function.name) && + autoAcceptEditToolDiffs + ) { + return { policy: "allowedWithoutPermission", toolCallState }; + } + const basePolicy = toolPolicies[toolCallState.toolCall.function.name] ?? activeTools.find( @@ -73,6 +83,7 @@ export async function evaluateToolPolicies( activeTools: Tool[], generatedToolCalls: ToolCallState[], toolPolicies: ToolPolicies, + autoAcceptEditToolDiffs: boolean | undefined, ): Promise { // Check if ALL tool calls are auto-approved using dynamic evaluation const policyResults = await Promise.all( @@ -82,6 +93,7 @@ export async function evaluateToolPolicies( activeTools, toolCallState, toolPolicies, + autoAcceptEditToolDiffs, ), ), ); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index b1f5d10ff..bf4939c38 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -268,6 +268,7 @@ export const streamNormalInput = createAsyncThunk< activeTools, generatedCalls3, toolPolicies, + state3.config.config.ui?.autoAcceptEditToolDiffs, ); const anyRequireApproval = policies.find( ({ policy }) => policy === "allowedWithPermission", diff --git a/gui/src/util/toolCallState.ts b/gui/src/util/toolCallState.ts index 92df3acd3..c7b9bcbd7 100644 --- a/gui/src/util/toolCallState.ts +++ b/gui/src/util/toolCallState.ts @@ -1,4 +1,5 @@ import { ToolCallDelta, ToolCallState } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { incrementalParseJson } from "core/util/incrementalParseJson"; // Merge streamed tool calls @@ -67,3 +68,12 @@ export function addToolCallDeltaToState( parsedArgs, }; } + +const editToolNames: string[] = [ + BuiltInToolNames.EditExistingFile, + BuiltInToolNames.SingleFindAndReplace, + BuiltInToolNames.MultiEdit, +]; +export function isEditTool(toolName: string) { + return editToolNames.includes(toolName); +} From ab1f072eae328f6c4d94144726658ad9418a8300 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 13:55:28 -0700 Subject: [PATCH 56/91] test: cli banner --- .../components/CliInstallBanner.test.tsx | 280 ++++++++++++++++++ 1 file changed, 280 insertions(+) create mode 100644 gui/src/pages/config/components/CliInstallBanner.test.tsx diff --git a/gui/src/pages/config/components/CliInstallBanner.test.tsx b/gui/src/pages/config/components/CliInstallBanner.test.tsx new file mode 100644 index 000000000..d226e9b4e --- /dev/null +++ b/gui/src/pages/config/components/CliInstallBanner.test.tsx @@ -0,0 +1,280 @@ +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { MockIdeMessenger } from "../../../context/MockIdeMessenger"; +import * as util from "../../../util"; +import { CliInstallBanner } from "./CliInstallBanner"; + +vi.mock("../../../util", async () => { + const actual = await vi.importActual("../../../util"); + return { + ...actual, + getPlatform: vi.fn(), + }; +}); + +describe("CliInstallBanner", () => { + let mockIdeMessenger: MockIdeMessenger; + + beforeEach(() => { + vi.clearAllMocks(); + mockIdeMessenger = new MockIdeMessenger(); + vi.mocked(util.getPlatform).mockReturnValue("mac"); + }); + + const renderComponent = async (subprocessResponse: [string, string]) => { + // Mock the subprocess call on the IDE + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue( + subprocessResponse, + ); + + return act(async () => + render( + + + , + ), + ); + }; + + describe("CLI detection", () => { + it("does not render when CLI is installed (subprocess returns path)", async () => { + await renderComponent(["/usr/local/bin/cn", ""]); + + await waitFor(() => { + expect( + screen.queryByText("Try the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("renders when CLI is not installed (subprocess returns empty)", async () => { + await renderComponent(["", "command not found"]); + + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + + it("renders when CLI is not installed (subprocess returns empty stdout)", async () => { + await renderComponent(["", ""]); + + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + + it("uses 'which cn' command on mac platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("mac"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await renderComponent(["", ""]); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("which cn"); + }); + }); + + it("uses 'which cn' command on linux platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("linux"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await renderComponent(["", ""]); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("which cn"); + }); + }); + + it("uses 'where cn' command on windows platform", async () => { + vi.mocked(util.getPlatform).mockReturnValue("windows"); + const subprocessSpy = vi + .spyOn(mockIdeMessenger.ide, "subprocess") + .mockResolvedValue(["", ""]); + + await renderComponent(["", ""]); + + await waitFor(() => { + expect(subprocessSpy).toHaveBeenCalledWith("where cn"); + }); + }); + + it("handles subprocess errors gracefully", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockRejectedValue( + new Error("Command failed"), + ); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + }); + + describe("Banner content", () => { + beforeEach(async () => { + await renderComponent(["", "not found"]); + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + + it("displays the title", () => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + + it("displays the description with 'cn' code element", () => { + const description = screen.getByText(/Use/); + expect(description).toBeInTheDocument(); + expect(screen.getByText("cn")).toBeInTheDocument(); + }); + + it("displays the installation command", () => { + expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); + }); + + it("displays the Learn more button", () => { + expect(screen.getByText("Learn more")).toBeInTheDocument(); + }); + + it("displays the close button", () => { + const closeButton = screen.getByRole("button", { name: /dismiss/i }); + expect(closeButton).toBeInTheDocument(); + }); + + it("displays the CommandLine icon", () => { + // The icon should be present in the component + const banner = screen.getByText("Try the Continue CLI").closest("div"); + expect(banner).toBeInTheDocument(); + }); + }); + + describe("User interactions", () => { + beforeEach(async () => { + await renderComponent(["", "not found"]); + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + + it("dismisses banner when close button is clicked", async () => { + const closeButton = screen.getByRole("button", { name: /dismiss/i }); + fireEvent.click(closeButton); + + await waitFor(() => { + expect( + screen.queryByText("Try the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("opens documentation URL when Learn more button is clicked", async () => { + const postSpy = vi.spyOn(mockIdeMessenger, "post"); + const learnMoreButton = screen.getByText("Learn more"); + + fireEvent.click(learnMoreButton); + + expect(postSpy).toHaveBeenCalledWith( + "openUrl", + "https://docs.continue.dev/guides/cli", + ); + }); + }); + + describe("Banner visibility states", () => { + it("does not render while CLI check is loading", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockImplementation( + () => + new Promise((resolve) => setTimeout(() => resolve(["", ""]), 100)), + ); + + await act(async () => + render( + + + , + ), + ); + + // Should not be visible immediately + expect( + screen.queryByText("Try the Continue CLI"), + ).not.toBeInTheDocument(); + }); + + it("remains hidden after dismissal even on re-render", async () => { + const { rerender } = await renderComponent(["", "not found"]); + + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + + // Dismiss the banner + const closeButton = screen.getByRole("button", { name: /dismiss/i }); + fireEvent.click(closeButton); + + await waitFor(() => { + expect( + screen.queryByText("Try the Continue CLI"), + ).not.toBeInTheDocument(); + }); + + // Re-render the component + rerender( + + + , + ); + + // Should still be hidden + expect( + screen.queryByText("Try the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + describe("Edge cases", () => { + it("handles whitespace in subprocess output", async () => { + await renderComponent([" \n ", ""]); + + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + + it("detects CLI when path has trailing newline", async () => { + await renderComponent(["/usr/local/bin/cn\n", ""]); + + await waitFor(() => { + expect( + screen.queryByText("Try the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("renders banner when stderr contains 'not found'", async () => { + await renderComponent(["", "cn: command not found"]); + + await waitFor(() => { + expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + }); + }); + }); +}); From f5999a6cccca4a0105488c72b9878dfe7e11f1d8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 14:02:44 -0700 Subject: [PATCH 57/91] improv: ui --- .../components/CliInstallBanner.test.tsx | 24 +++++++++++++++++++ .../config/components/CliInstallBanner.tsx | 14 ++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.test.tsx b/gui/src/pages/config/components/CliInstallBanner.test.tsx index d226e9b4e..9d1f8e989 100644 --- a/gui/src/pages/config/components/CliInstallBanner.test.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.test.tsx @@ -196,6 +196,30 @@ describe("CliInstallBanner", () => { "https://docs.continue.dev/guides/cli", ); }); + + it("copies installation command when copy button is clicked", async () => { + // Find the copy button (ClipboardIcon) + const copyButtons = screen.getAllByRole("button"); + const copyButton = copyButtons.find((btn) => + btn.querySelector('svg[class*="ClipboardIcon"]'), + ); + + expect(copyButton).toBeDefined(); + }); + + it("runs installation command in terminal when run button is clicked", async () => { + const postSpy = vi.spyOn(mockIdeMessenger, "post"); + + // Find the "Run" text or CommandLineIcon + const runButton = screen.getByText(/Run/i).closest("div"); + if (runButton) { + fireEvent.click(runButton); + + expect(postSpy).toHaveBeenCalledWith("runCommand", { + command: "npm i -g @continuedev/cli", + }); + } + }); }); describe("Banner visibility states", () => { diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index f2c2cd603..ec8d09362 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -1,6 +1,8 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; import { CloseButton, SecondaryButton } from "../../../components"; +import { CopyButton } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; +import { RunInTerminalButton } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; import { Card } from "../../../components/ui"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { getPlatform } from "../../../util"; @@ -61,9 +63,15 @@ export function CliInstallBanner() {
- - npm i -g @continuedev/cli - +
+ + npm i -g @continuedev/cli + +
+ + +
+
ideMessenger.post( From c714c62db1acf516649e7ef784d88c955f848e7d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 14:07:12 -0700 Subject: [PATCH 58/91] improv: ui --- .../config/components/CliInstallBanner.tsx | 70 +++++++++---------- 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index ec8d09362..6abe87da5 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -46,44 +46,42 @@ export function CliInstallBanner() { setDismissed(true)}> -
- -
-
-
- Try the Continue CLI -
-
- Use{" "} - - cn - {" "} - in your terminal for command-line coding assistance with - interactive and headless modes. +
+
+
+ + Try the Continue CLI +
+
+ Use{" "} + + cn + {" "} + in your terminal for command-line coding assistance with + interactive and headless modes. +
+
+
+
+ + npm i -g @continuedev/cli + +
+ +
-
-
- - npm i -g @continuedev/cli - -
- - -
-
- - ideMessenger.post( - "openUrl", - "https://docs.continue.dev/guides/cli", - ) - } - style={{ margin: 0 }} - > - Learn more - -
+ + ideMessenger.post( + "openUrl", + "https://docs.continue.dev/guides/cli", + ) + } + style={{ margin: 0 }} + > + Learn more +
From 351070cf4c743da19c404971e126166d2b5cee36 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 14:16:39 -0700 Subject: [PATCH 59/91] improv: ui --- gui/src/pages/config/components/CliInstallBanner.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index 6abe87da5..c331ebfa6 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -61,8 +61,8 @@ export function CliInstallBanner() { interactive and headless modes.
-
-
+
+
npm i -g @continuedev/cli From 54ba728b74b382d00bb056b289f1741647850e25 Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Mon, 6 Oct 2025 14:18:29 -0700 Subject: [PATCH 60/91] docs: Add Sentry MCP error monitoring cookbook (#8060) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add Sentry MCP error monitoring cookbook - Create comprehensive Sentry MCP cookbook following PostHog/Netlify structure - Add automated error analysis workflow with AI-powered root cause detection - Include GitHub Actions workflow for continuous error monitoring (runs every 6 hours) - Add cookbook to docs.json navigation in Cookbooks section - All links grounded in official Sentry documentation - Uses Mintlify components consistent with existing cookbooks 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude * Address Patrick's feedback on Sentry MCP cookbook - Make sidebar title match page title - Focus on Sentry Issues only (remove references to Releases/Performance in learning section) - Remove all references to Sentry's Seer AI to avoid confusion - Simplify MCP configuration approach - Fix comment formatting in code blocks for better copy/paste - Consider PR creation instead of just issues (keeping issues for now as PRs need more context) Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Add Sentry and dlt cookbooks to guides overview - Add Sentry MCP error monitoring cookbook to the MCP Integration section - Add dlt data pipelines cookbook to the MCP Integration section - Maintain alphabetical ordering within the MCP cookbook list Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Add Quick Start section to Sentry guide with pre-built agent - Added Quick Start section similar to PostHog guide - Featured continuedev/sentry-continuous-ai agent from Continue Hub - Improved messaging and structure for faster onboarding - Updated Agent Requirements accordion with Pro Plan option - Fixed table formatting with left-aligned columns - Aligned GitHub CLI vs MCP messaging with PostHog guide Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Move Configure Sentry MCP tab to first position - Reordered tabs in Step 1 to prioritize MCP configuration - Configure Sentry MCP is now the leftmost tab for better visibility Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Update STDIO mode example with host parameter and environment variables - Added clarification that STDIO mode is for local development or self-hosted Sentry - Included environment variable configuration option (SENTRY_ACCESS_TOKEN, SENTRY_HOST) - Added Info box explaining --host parameter requirement with examples - Matches official Sentry MCP documentation Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Add rocket emoji back to Card title - SVG icon not rendering properly, using emoji fallback - Matches PostHog guide formatting Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Remove rocket emoji from Card title - Let rocket icon handle the visual representation - Cleaner appearance without duplicate visual elements Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Add Sentry GitHub Action integration with Continue CLI - Integrated Sentry Release GitHub Action for release tracking - Enhanced workflow to create Sentry releases on push to main - Updated Continue CLI prompt to generate comprehensive AI-powered issue descriptions - Added SENTRY_PROJECT to required secrets - Improved workflow summary with GitHub Step Summary - Added documentation on combining Sentry releases with Continue CLI - Link to official Sentry GitHub Actions documentation Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Update sidebar title to start with 'Sentry' - Changed sidebarTitle from 'Automated Error Analysis with Sentry MCP' to 'Sentry Automated Error Analysis with MCP' - Improves discoverability by having Sentry as the first word Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Update sentry-mcp-error-monitoring.mdx Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --------- Co-authored-by: Claude Co-authored-by: Continue Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- docs/docs.json | 1 + docs/guides/overview.mdx | 1 + docs/guides/sentry-mcp-error-monitoring.mdx | 534 ++++++++++++++++++++ 3 files changed, 536 insertions(+) create mode 100644 docs/guides/sentry-mcp-error-monitoring.mdx diff --git a/docs/docs.json b/docs/docs.json index 34d6de9fe..ddb6027ef 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -262,6 +262,7 @@ "guides/posthog-github-continuous-ai", "guides/continue-docs-mcp-cookbook", "guides/sanity-mcp-continue-cookbook", + "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", "guides/dlt-mcp-continue-cookbook", "guides/netlify-mcp-continuous-deployment", diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index 13a8d0534..b10a25f1c 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -24,6 +24,7 @@ Step-by-step guides for integrating Model Context Protocol (MCP) servers with Co - [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP - [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets - [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP +- [Sentry Error Monitoring Cookbook](/guides/sentry-mcp-error-monitoring) - Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues - [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers - [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging diff --git a/docs/guides/sentry-mcp-error-monitoring.mdx b/docs/guides/sentry-mcp-error-monitoring.mdx new file mode 100644 index 000000000..bcbe81f9c --- /dev/null +++ b/docs/guides/sentry-mcp-error-monitoring.mdx @@ -0,0 +1,534 @@ +--- +title: "Automated Error Analysis with Sentry MCP" +description: "Build an AI-powered error monitoring workflow that analyzes Sentry issues, identifies patterns, and creates actionable GitHub issues automatically." +sidebarTitle: "Sentry Automated Error Analysis with MCP" +--- + + + An automated error monitoring system that uses Continue CLI with Sentry MCP to analyze production errors, identify root causes with AI, and create detailed GitHub issues with suggested fixes. + + +## What You'll Learn + +This cookbook teaches you to: + +- Use [Sentry MCP](https://docs.sentry.io/product/sentry-mcp/) to access [issues](https://docs.sentry.io/product/issues/) +- Analyze error patterns and stack traces with AI + +- Automatically create GitHub issues with root cause analysis +- Set up continuous error monitoring with GitHub Actions + +## Prerequisites + +Before starting, ensure you have: + +- GitHub repository where you want to create issues +- [Sentry account](https://sentry.io) with an active project collecting errors +- Node.js 18+ installed locally +- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage) +- [GitHub CLI](https://cli.github.com/) installed (`gh` command) + + + + ```bash + npm i -g @continuedev/cli + ``` + + + + 1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations) + 2. Sign up or log in to your Continue account + 3. Navigate to your organization settings + 4. Click **"API Keys"** and then **"+ New API Key"** + 5. Copy the API key immediately (you won't see it again!) + 6. Login to the CLI: `cn login` + + + + + Continue CLI handles complex error analysis and API interactions - you just need to provide the right prompts! + + +## Step 1: Set Up Your Credentials + +First, you'll need to gather your Sentry and GitHub API credentials. + + + + + + See [Sentry MCP Documentation](https://docs.sentry.io/product/sentry-mcp/) for detailed configuration options + + + The Sentry MCP supports multiple configuration methods. For Continue CLI, OAuth is recommended: + + **Option 1: OAuth Configuration (Recommended)** + + The Sentry MCP will prompt for OAuth authentication when first used. Simply follow the authorization flow. + + **Option 2: STDIO Mode with Auth Token** + + For local development or self-hosted Sentry installations, you can use STDIO mode: + ```bash + npx @sentry/mcp-server@latest --access-token=YOUR_SENTRY_TOKEN --host=sentry.io + ``` + + Or use environment variables: + ```bash + SENTRY_ACCESS_TOKEN=your-token SENTRY_HOST=sentry.io + ``` + + + The `--host` parameter is required and should point to your Sentry instance (e.g., `sentry.io` or `sentry.example.com` for self-hosted). + + + + + You'll need a **Sentry User Auth Token** to access issues and error data: + + 1. Go to [User Auth Tokens](https://sentry.io/settings/account/api/auth-tokens/) in Sentry + - For self-hosted Sentry, use: `https://YOUR-SENTRY-DOMAIN/settings/account/api/auth-tokens/` + 2. Click **Create New Token** + 3. Name it "Continue CLI Error Analysis" + 4. **Select these permission scopes** (required for full functionality): + - `org:read` - **Required** - Access organization information + - `project:read` - **Required** - Read project configurations + - `project:releases` - **Required** - Access release information for deployment tracking + - `event:read` - **Required** - Read detailed error event data and stack traces + - `event:write` - Optional - Update error events (for marking as resolved) + - `member:read` - Recommended - Read team member information for auto-assignment + - `team:read` - Recommended - Access team data for routing issues + 5. Copy the token immediately (you won't see it again!) + 6. Note your organization slug (found in your Sentry URL: `https://sentry.io/organizations/YOUR-ORG-SLUG`) + 7. Note your Sentry host URL (typically `https://sentry.io` or your self-hosted domain) + + + **Sentry MCP Connection**: The MCP server connects via OAuth to `https://mcp.sentry.dev/mcp` and handles authentication securely. For local development, you can use STDIO mode with your auth token. + + + + + GitHub CLI handles authentication automatically - no manual PAT needed: + + 1. Install GitHub CLI if not already installed + 2. Run `gh auth login` and follow the prompts + 3. Choose authentication method (browser or token) + 4. Grant necessary permissions when prompted (`issues:write` is **required** for creating issues) + + + +## Sentry Error Monitoring Workflow Options + + + Skip the manual setup and use our pre-built Sentry Continuous AI agent that includes + optimized prompts, rules, and the Sentry MCP for more consistent results. + + + + **How Sentry MCP Works**: + - Connects to your Sentry organization via OAuth + - Provides tools for accessing issues, projects, teams, and DSNs + - Supports both hosted (`https://mcp.sentry.dev`) and self-hosted Sentry instances + - Automatically handles authentication and API interactions + + + + + **Perfect for:** Immediate error analysis with AI-powered root cause detection and built-in debugging + + + + Visit the [Sentry Continuous AI Agent](https://hub.continue.dev/continuedev/sentry-continuous-ai) on Continue Hub and click **"Install Agent"** or run: + + ```bash + cn --config continuedev/sentry-continuous-ai + ``` + + This agent includes: + - **Optimized prompts** for Sentry error analysis and GitHub issue creation + - **Built-in rules** for consistent formatting and error handling + - **[Sentry MCP](https://docs.sentry.io/product/sentry-mcp/)** for more reliable API interactions + - **Automatic authentication** via OAuth flow + + + + Navigate to your project directory and enter this prompt in the Continue CLI TUI: + + ``` + Analyze recent Sentry errors and create GitHub issues for critical bugs with suggested fixes + ``` + + That's it! The agent handles everything automatically. + + + + + **Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Sentry MCP integration and pre-tested prompts. + + + + + + + + Configure the [Sentry MCP](https://docs.sentry.io/product/sentry-mcp/) using OAuth: + + The MCP server will automatically prompt for OAuth authentication when you first use it. + + + + Test your Sentry MCP connection with this prompt: + + ``` + List my Sentry organizations and projects + ``` + + + + Use this prompt template with Continue CLI to analyze Sentry errors: + + ``` + Analyze Sentry errors from the past 24 hours: + - Group errors by root cause + - Identify the top 5 most critical issues by frequency and impact + - For each critical issue, provide: + * Stack trace analysis + * Affected user count + * First seen and last seen timestamps + * Suggested fix based on error context + - Create GitHub issues using gh CLI with: + * Title format: '🐛 [Sentry] [Error Type]: Brief description' + * Labels: 'bug', 'sentry', 'production' + * Priority labels based on severity + * Full error context and suggested fix in the body + Execute the commands and confirm each issue was created. + ``` + + + + + + + + **Why GitHub CLI over GitHub MCP**: While GitHub MCP is available, it can be + token-expensive to run. The `gh` CLI is more efficient, requires no API tokens + (authenticated via `gh auth login`), and provides a cleaner command-line + experience. GitHub MCP remains an option if you prefer full MCP integration. + + + + To use the pre-built agent, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets (same as Step 1) + + The agent will automatically detect and use your configuration. For Sentry MCP: + - **Sentry account** with at least one project + - **User Auth Token** with appropriate scopes (or OAuth flow) + - The MCP works with both Sentry's hosted service (`sentry.io`) and self-hosted instances + + +--- + + + **Repository Labels Required**: Make sure your GitHub repository has these labels: + - `bug`, `sentry`, `production` + - `critical`, `high-priority`, `medium-priority`, `low-priority` + - `needs-investigation`, `has-fix` + + Create missing labels in your repo at: **Settings → Labels → New label** + + +## Step 2: Analyze Sentry Errors with AI + +Use Continue CLI to perform intelligent error analysis. Enter these prompts in the Continue CLI TUI: + + + + **Prompt:** + ``` + Show me Sentry errors from the past 7 days, grouped by error type, with frequency counts + ``` + + + + **Prompt:** + ``` + Find the most critical Sentry error affecting the most users in production and provide: + - Full stack trace analysis + - Affected user count and browser/OS breakdown + - Timeline of when the error started occurring + - Similar historical issues from Sentry + - Root cause hypothesis based on code context + - Suggested fix with code examples + ``` + + + + **Prompt:** + ``` + Analyze Sentry performance data to identify: + - Slowest transactions in the past 24 hours + - Database queries with high latency + - API endpoints with degraded performance + - Suggested optimizations for each issue + ``` + + + + + **Available Sentry MCP Tools**: + - **Organizations**: Access org-level data and settings + - **Projects**: Query projects and their configurations + - **Issues**: Search and analyze error issues + - **Teams**: Manage team assignments + - **DSNs**: Retrieve project DSN configurations + + + +## Step 3: Automate GitHub Issue Creation + +Create actionable GitHub issues from Sentry errors. Enter this prompt in the Continue CLI TUI: + +**Prompt:** +``` +For each unresolved Sentry error with 'critical' or 'high' severity: +1. Analyze the error using Sentry MCP +2. Create a GitHub issue with gh CLI: + - Title: '🐛 [Sentry] [Error Type]: Brief description' + - Body with: + * Error summary and impact (affected users, frequency) + * Full stack trace + * Environment details (browser, OS, release version) + * Link to Sentry issue + * Root cause analysis from AI + * Suggested fix with code snippets + * Related Sentry issues + - Labels: 'bug', 'sentry', 'production', and severity label + - Assignees: Team member based on code ownership +3. Update Sentry issue with GitHub issue link +4. Confirm creation with GitHub issue URL +``` + + + **Best Practice**: Link GitHub issues back to Sentry for full traceability. This creates a bidirectional connection between your error monitoring and issue tracking. + + +## Step 4: Set Up Continuous Monitoring with GitHub Actions + +Automate error monitoring with the [Sentry Release GitHub Action](https://docs.sentry.io/product/releases/setup/release-automation/github-actions/) and Continue CLI to create comprehensive, AI-powered issue descriptions: + + + **Why Combine Sentry Releases with Continue CLI?** + - **Release Tracking**: Associate errors with specific deployments + - **AI-Powered Analysis**: Continue CLI generates detailed issue descriptions with root cause analysis + - **Better Context**: Link errors to commits and pull requests + - **Automated Workflows**: Create issues with full stack traces and suggested fixes + + +```yaml +name: Sentry Error Monitoring + +on: + push: + branches: + - main + schedule: + # Run every 6 hours + - cron: "0 */6 * * *" + workflow_dispatch: # Allow manual triggers + +jobs: + monitor-errors: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + # Create Sentry release for better error tracking + - name: Create Sentry release + uses: getsentry/action-release@v1 + env: + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + with: + environment: production + + - name: Install Continue CLI + run: | + npm install -g @continuedev/cli + echo "✅ Continue CLI installed" + + - name: Authenticate GitHub CLI + run: | + echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token + echo "✅ GitHub CLI authenticated" + + - name: Analyze Sentry Errors and Create Issues + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + run: | + echo "🔍 Analyzing Sentry errors..." + + # Use Continue CLI to analyze errors and generate comprehensive issue descriptions + cn -p "Using Sentry MCP, analyze errors from the past 6 hours for project $SENTRY_PROJECT: + 1. Filter for unresolved errors with high or critical severity + 2. Group similar errors to avoid duplicates + 3. For each unique critical error: + - Generate a comprehensive issue description including: + * Error summary with frequency and user impact metrics + * Full stack trace with highlighted problem areas + * Environment details (browser, OS, release version) + * Link to Sentry issue dashboard + * Root cause analysis using AI + * Step-by-step reproduction if available + * Suggested fix with code examples + * Related errors or patterns + - Check if a GitHub issue already exists for this error + - If not, create a new issue with the generated description + - Use gh CLI: gh issue create --title '[Sentry] [Error Type]: Brief description' --body 'AI-generated comprehensive analysis' --label 'bug,sentry,critical,needs-investigation' + - Link the GitHub issue back to Sentry + 4. Generate a summary report with: + - Total errors analyzed + - New issues created with URLs + - Errors skipped (already tracked) + - Release correlation if available + + Sentry Organization: $SENTRY_ORG + Project: $SENTRY_PROJECT + Only process errors not already tracked in GitHub." + + - name: Post workflow summary + if: always() + run: | + echo "## 📊 Sentry Error Monitoring Summary" >> $GITHUB_STEP_SUMMARY + echo "✅ Workflow completed at $(date)" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "Check the 'Analyze Sentry Errors' step above for:" >> $GITHUB_STEP_SUMMARY + echo "- Number of errors analyzed" >> $GITHUB_STEP_SUMMARY + echo "- GitHub issues created" >> $GITHUB_STEP_SUMMARY + echo "- Errors already tracked" >> $GITHUB_STEP_SUMMARY +``` + + + **Required GitHub Secrets**: + - `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) + - `SENTRY_AUTH_TOKEN`: Your Sentry User Auth Token (needs scopes: `org:read`, `project:read`, `project:releases`, `event:read`) + - `SENTRY_ORG`: Your Sentry organization slug + - `SENTRY_PROJECT`: Your Sentry project slug + - `GITHUB_TOKEN`: Automatically provided by GitHub Actions + + Add these at: **Repository Settings → Secrets and variables → Actions** + + + + **Workflow Best Practices**: + - Run every 6 hours to catch critical errors quickly + - Create Sentry releases on push to track error-to-deployment correlation + - Use Continue CLI to generate comprehensive, AI-powered issue descriptions + - Use duplicate detection to avoid creating multiple issues for the same error + - Filter by severity to focus on high-impact issues + - Include full error context and suggested fixes in issues + - Tag issues with appropriate labels for team routing + - Link GitHub issues back to Sentry for bidirectional tracking + + +## What You've Built + +After completing this guide, you have a complete **Sentry-powered error monitoring system** that: + +- **Monitors production errors** - Automatically fetches and analyzes Sentry issues every 6 hours + +- **Identifies critical bugs** - Uses AI to spot high-impact errors + +- **Creates actionable tasks** - Generates GitHub issues with root cause analysis and suggested fixes + +- **Runs autonomously** - Operates continuously without manual intervention using GitHub Actions + +- **Scales with your app** - Handles growing error volumes and complexity automatically + + + Your system now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine error analysis with human oversight through GitHub issue review and resolution. + + +## Advanced Error Analysis Prompts + +Enhance your workflow with these advanced Continue CLI prompts: + + + + Compare error rates before and after the latest [Sentry release](https://docs.sentry.io/product/releases/) to identify regressions introduced in the deployment + + + Analyze Sentry error trends over the past 30 days and identify emerging issues before they become critical + + + Identify which errors are affecting the most unique users and prioritize fixes based on user impact + + + Cross-reference Sentry [performance issues](https://docs.sentry.io/product/performance/) with error spikes to identify root causes + + + +## Security Best Practices + + + **Protect Your API Keys**: + - Store all credentials as GitHub Secrets, never in code + - Use Continue CLI's secure secret storage + - Limit Sentry token scopes to minimum required permissions + - Rotate API keys regularly (every 90 days recommended) + - Monitor token usage for unusual activity + - Use OAuth when possible for better security + + +## Troubleshooting + +### Sentry MCP Connection Issues + +If you encounter connection issues: + +1. Verify OAuth authentication is complete +2. Check your Sentry organization access +3. Ensure the MCP server URL is correct (`https://mcp.sentry.dev/mcp`) +4. For self-hosted Sentry, verify your host URL is configured correctly + +See the [Sentry MCP GitHub Issues](https://github.com/getsentry/sentry-mcp/issues) for known issues and solutions. + +### Common Error Analysis Issues + +| Issue | Solution | +|:------|:---------| +| No errors returned | Verify your Sentry project has collected errors recently | +| OAuth prompt not appearing | Check that Continue CLI has proper MCP configuration | +| Duplicate GitHub issues | Implement duplicate detection in your prompts | +| Missing error context | Ensure your Sentry token has `event:read` scope | + +## Next Steps + + +- Set up [Sentry performance monitoring](https://docs.sentry.io/product/performance/) +- Configure [Sentry release tracking](https://docs.sentry.io/product/releases/) for deployment correlation +- Integrate [Slack MCP](https://hub.continue.dev/slack/slack-mcp) for error alerts +- Join the [Continue Discord](https://discord.gg/continue) for support + +## Resources + +- [Sentry MCP Documentation](https://docs.sentry.io/product/sentry-mcp/) +- [Sentry API Documentation](https://docs.sentry.io/api/) +- [Sentry Issues Guide](https://docs.sentry.io/product/issues/) +- [Sentry Performance Monitoring](https://docs.sentry.io/product/performance/) +- [Sentry Release Tracking](https://docs.sentry.io/product/releases/) + +- [Sentry MCP GitHub Repository](https://github.com/getsentry/sentry-mcp) +- [GitHub CLI Documentation](https://cli.github.com/) +- [Continue CLI Guide](https://docs.continue.dev/guides/cli) +- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/) From a873873b72950939d318b8ddcd9e951435a5f704 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 14:19:48 -0700 Subject: [PATCH 61/91] improv: ui --- gui/src/pages/config/components/CliInstallBanner.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index c331ebfa6..a220d663d 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -62,7 +62,7 @@ export function CliInstallBanner() {
-
+
npm i -g @continuedev/cli From 8a5e320e1cf4e5838ae7e9df1425ebe797fc181c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 14:23:12 -0700 Subject: [PATCH 62/91] improv: ui --- gui/src/pages/config/components/CliInstallBanner.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index a220d663d..d6fb47bb6 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -68,7 +68,9 @@ export function CliInstallBanner() {
- +
Date: Mon, 6 Oct 2025 14:37:57 -0700 Subject: [PATCH 63/91] improv: ui --- .../config/components/CliInstallBanner.tsx | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index d6fb47bb6..c13ab8723 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -50,15 +50,26 @@ export function CliInstallBanner() {
- Try the Continue CLI + Try out the Continue CLI
Use{" "} cn {" "} - in your terminal for command-line coding assistance with - interactive and headless modes. + in your terminal interactively and then deploy Continuous AI + workflows.{" "} + + ideMessenger.post( + "openUrl", + "https://docs.continue.dev/guides/cli", + ) + } + className="cursor-pointer underline hover:brightness-125" + > + Learn more. +
@@ -73,17 +84,6 @@ export function CliInstallBanner() { />
- - ideMessenger.post( - "openUrl", - "https://docs.continue.dev/guides/cli", - ) - } - style={{ margin: 0 }} - > - Learn more -
From 966998465f1614ab1a0d3f346e5da1ace5b1de2e Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 14:41:38 -0700 Subject: [PATCH 64/91] improv: ui --- gui/src/pages/config/components/CliInstallBanner.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index c13ab8723..075ea0de6 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -1,6 +1,6 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; -import { CloseButton, SecondaryButton } from "../../../components"; +import { CloseButton } from "../../../components"; import { CopyButton } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; import { RunInTerminalButton } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; import { Card } from "../../../components/ui"; @@ -78,7 +78,9 @@ export function CliInstallBanner() { npm i -g @continuedev/cli
- + From 53da290d3e7d1edc62839aac0116596262bdfc36 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 15:45:54 -0700 Subject: [PATCH 65/91] improv: ui --- .../components/CliInstallBanner.test.tsx | 261 +++++++++++++++--- .../config/components/CliInstallBanner.tsx | 52 +++- gui/src/pages/gui/Chat.tsx | 12 + gui/src/util/localStorage.ts | 1 + 4 files changed, 283 insertions(+), 43 deletions(-) diff --git a/gui/src/pages/config/components/CliInstallBanner.test.tsx b/gui/src/pages/config/components/CliInstallBanner.test.tsx index 9d1f8e989..5bf24bc2e 100644 --- a/gui/src/pages/config/components/CliInstallBanner.test.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.test.tsx @@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { MockIdeMessenger } from "../../../context/MockIdeMessenger"; import * as util from "../../../util"; +import * as localStorage from "../../../util/localStorage"; import { CliInstallBanner } from "./CliInstallBanner"; vi.mock("../../../util", async () => { @@ -19,6 +20,15 @@ vi.mock("../../../util", async () => { }; }); +vi.mock("../../../util/localStorage", async () => { + const actual = await vi.importActual("../../../util/localStorage"); + return { + ...actual, + getLocalStorage: vi.fn(), + setLocalStorage: vi.fn(), + }; +}); + describe("CliInstallBanner", () => { let mockIdeMessenger: MockIdeMessenger; @@ -26,6 +36,7 @@ describe("CliInstallBanner", () => { vi.clearAllMocks(); mockIdeMessenger = new MockIdeMessenger(); vi.mocked(util.getPlatform).mockReturnValue("mac"); + vi.mocked(localStorage.getLocalStorage).mockReturnValue(undefined); }); const renderComponent = async (subprocessResponse: [string, string]) => { @@ -49,7 +60,7 @@ describe("CliInstallBanner", () => { await waitFor(() => { expect( - screen.queryByText("Try the Continue CLI"), + screen.queryByText("Try out the Continue CLI"), ).not.toBeInTheDocument(); }); }); @@ -58,7 +69,9 @@ describe("CliInstallBanner", () => { await renderComponent(["", "command not found"]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); @@ -66,7 +79,9 @@ describe("CliInstallBanner", () => { await renderComponent(["", ""]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); @@ -76,7 +91,13 @@ describe("CliInstallBanner", () => { .spyOn(mockIdeMessenger.ide, "subprocess") .mockResolvedValue(["", ""]); - await renderComponent(["", ""]); + await act(async () => + render( + + + , + ), + ); await waitFor(() => { expect(subprocessSpy).toHaveBeenCalledWith("which cn"); @@ -89,7 +110,13 @@ describe("CliInstallBanner", () => { .spyOn(mockIdeMessenger.ide, "subprocess") .mockResolvedValue(["", ""]); - await renderComponent(["", ""]); + await act(async () => + render( + + + , + ), + ); await waitFor(() => { expect(subprocessSpy).toHaveBeenCalledWith("which cn"); @@ -102,7 +129,13 @@ describe("CliInstallBanner", () => { .spyOn(mockIdeMessenger.ide, "subprocess") .mockResolvedValue(["", ""]); - await renderComponent(["", ""]); + await act(async () => + render( + + + , + ), + ); await waitFor(() => { expect(subprocessSpy).toHaveBeenCalledWith("where cn"); @@ -123,7 +156,9 @@ describe("CliInstallBanner", () => { ); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); }); @@ -132,12 +167,14 @@ describe("CliInstallBanner", () => { beforeEach(async () => { await renderComponent(["", "not found"]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); it("displays the title", () => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect(screen.getByText("Try out the Continue CLI")).toBeInTheDocument(); }); it("displays the description with 'cn' code element", () => { @@ -150,18 +187,22 @@ describe("CliInstallBanner", () => { expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); }); - it("displays the Learn more button", () => { - expect(screen.getByText("Learn more")).toBeInTheDocument(); + it("displays the Learn more link", () => { + expect(screen.getByText("Learn more.")).toBeInTheDocument(); }); it("displays the close button", () => { - const closeButton = screen.getByRole("button", { name: /dismiss/i }); - expect(closeButton).toBeInTheDocument(); + // Get the styled close button (it doesn't have a text label) + const buttons = screen.getAllByRole("button"); + // There should be multiple buttons (close, copy, run) + expect(buttons.length).toBeGreaterThan(0); }); it("displays the CommandLine icon", () => { // The icon should be present in the component - const banner = screen.getByText("Try the Continue CLI").closest("div"); + const banner = screen + .getByText("Try out the Continue CLI") + .closest("div"); expect(banner).toBeInTheDocument(); }); }); @@ -170,26 +211,30 @@ describe("CliInstallBanner", () => { beforeEach(async () => { await renderComponent(["", "not found"]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); it("dismisses banner when close button is clicked", async () => { - const closeButton = screen.getByRole("button", { name: /dismiss/i }); + const buttons = screen.getAllByRole("button"); + // First button should be the close button (CloseButton component) + const closeButton = buttons[0]; fireEvent.click(closeButton); await waitFor(() => { expect( - screen.queryByText("Try the Continue CLI"), + screen.queryByText("Try out the Continue CLI"), ).not.toBeInTheDocument(); }); }); - it("opens documentation URL when Learn more button is clicked", async () => { + it("opens documentation URL when Learn more link is clicked", async () => { const postSpy = vi.spyOn(mockIdeMessenger, "post"); - const learnMoreButton = screen.getByText("Learn more"); + const learnMoreLink = screen.getByText("Learn more."); - fireEvent.click(learnMoreButton); + fireEvent.click(learnMoreLink); expect(postSpy).toHaveBeenCalledWith( "openUrl", @@ -197,14 +242,11 @@ describe("CliInstallBanner", () => { ); }); - it("copies installation command when copy button is clicked", async () => { - // Find the copy button (ClipboardIcon) - const copyButtons = screen.getAllByRole("button"); - const copyButton = copyButtons.find((btn) => - btn.querySelector('svg[class*="ClipboardIcon"]'), - ); - - expect(copyButton).toBeDefined(); + it("displays the installation command with interactive controls", async () => { + // The installation command should be visible + expect(screen.getByText("npm i -g @continuedev/cli")).toBeInTheDocument(); + // The "Run" text should be visible for the run button + expect(screen.getByText(/Run/i)).toBeInTheDocument(); }); it("runs installation command in terminal when run button is clicked", async () => { @@ -216,7 +258,7 @@ describe("CliInstallBanner", () => { fireEvent.click(runButton); expect(postSpy).toHaveBeenCalledWith("runCommand", { - command: "npm i -g @continuedev/cli", + command: `npm i -g @continuedev/cli && cn "Explore this repo and provide a concise summary of it's contents"`, }); } }); @@ -239,7 +281,7 @@ describe("CliInstallBanner", () => { // Should not be visible immediately expect( - screen.queryByText("Try the Continue CLI"), + screen.queryByText("Try out the Continue CLI"), ).not.toBeInTheDocument(); }); @@ -247,16 +289,19 @@ describe("CliInstallBanner", () => { const { rerender } = await renderComponent(["", "not found"]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); // Dismiss the banner - const closeButton = screen.getByRole("button", { name: /dismiss/i }); + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; fireEvent.click(closeButton); await waitFor(() => { expect( - screen.queryByText("Try the Continue CLI"), + screen.queryByText("Try out the Continue CLI"), ).not.toBeInTheDocument(); }); @@ -269,7 +314,7 @@ describe("CliInstallBanner", () => { // Should still be hidden expect( - screen.queryByText("Try the Continue CLI"), + screen.queryByText("Try out the Continue CLI"), ).not.toBeInTheDocument(); }); }); @@ -279,7 +324,9 @@ describe("CliInstallBanner", () => { await renderComponent([" \n ", ""]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); @@ -288,7 +335,7 @@ describe("CliInstallBanner", () => { await waitFor(() => { expect( - screen.queryByText("Try the Continue CLI"), + screen.queryByText("Try out the Continue CLI"), ).not.toBeInTheDocument(); }); }); @@ -297,8 +344,148 @@ describe("CliInstallBanner", () => { await renderComponent(["", "cn: command not found"]); await waitFor(() => { - expect(screen.getByText("Try the Continue CLI")).toBeInTheDocument(); + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); }); }); }); + + describe("Message threshold logic", () => { + const renderWithMessageCount = async ( + messageCount?: number, + messageThreshold?: number, + ) => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + return act(async () => + render( + + + , + ), + ); + }; + + it("shows banner when no threshold is set", async () => { + await renderWithMessageCount(0, undefined); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("does not show banner when message count is below threshold", async () => { + await renderWithMessageCount(2, 3); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("shows banner when message count meets threshold", async () => { + await renderWithMessageCount(3, 3); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + + it("shows banner when message count exceeds threshold", async () => { + await renderWithMessageCount(5, 3); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + }); + }); + + describe("Permanent dismissal with localStorage", () => { + const renderWithPermanentDismissal = async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + return act(async () => + render( + + + , + ), + ); + }; + + it("does not show banner when previously dismissed permanently", async () => { + vi.mocked(localStorage.getLocalStorage).mockReturnValue(true); + + await renderWithPermanentDismissal(); + + await waitFor(() => { + expect( + screen.queryByText("Try out the Continue CLI"), + ).not.toBeInTheDocument(); + }); + }); + + it("sets localStorage when dismissed with permanentDismissal=true", async () => { + await renderWithPermanentDismissal(); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + expect(localStorage.setLocalStorage).toHaveBeenCalledWith( + "hasDismissedCliInstallBanner", + true, + ); + }); + + it("does not set localStorage when dismissed with permanentDismissal=false", async () => { + vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ + "", + "not found", + ]); + + await act(async () => + render( + + + , + ), + ); + + await waitFor(() => { + expect( + screen.getByText("Try out the Continue CLI"), + ).toBeInTheDocument(); + }); + + const buttons = screen.getAllByRole("button"); + const closeButton = buttons[0]; + fireEvent.click(closeButton); + + expect(localStorage.setLocalStorage).not.toHaveBeenCalled(); + }); + }); }); diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/pages/config/components/CliInstallBanner.tsx index 075ea0de6..8747d7ecd 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/pages/config/components/CliInstallBanner.tsx @@ -6,13 +6,36 @@ import { RunInTerminalButton } from "../../../components/StyledMarkdownPreview/S import { Card } from "../../../components/ui"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { getPlatform } from "../../../util"; +import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; -export function CliInstallBanner() { +interface CliInstallBannerProps { + /** Current message count - banner shows only if >= messageThreshold */ + messageCount?: number; + /** Minimum messages before showing banner (default: always show) */ + messageThreshold?: number; + /** If true, dismissal is permanent via localStorage (default: session only) */ + permanentDismissal?: boolean; +} + +export function CliInstallBanner({ + messageCount, + messageThreshold, + permanentDismissal = false, +}: CliInstallBannerProps = {}) { const ideMessenger = useContext(IdeMessengerContext); const [cliInstalled, setCliInstalled] = useState(null); const [dismissed, setDismissed] = useState(false); useEffect(() => { + // Check if user has permanently dismissed the banner + if (permanentDismissal) { + const hasDismissed = getLocalStorage("hasDismissedCliInstallBanner"); + if (hasDismissed) { + setDismissed(true); + return; + } + } + const checkCliInstallation = async () => { try { const platform = getPlatform(); @@ -32,18 +55,35 @@ export function CliInstallBanner() { } }; - checkCliInstallation(); - }, [ideMessenger]); + void checkCliInstallation(); + }, [ideMessenger, permanentDismissal]); - // Don't show if still loading, already installed, or dismissed - if (cliInstalled === null || cliInstalled === true || dismissed) { + const handleDismiss = () => { + setDismissed(true); + if (permanentDismissal) { + setLocalStorage("hasDismissedCliInstallBanner", true); + } + }; + + // Don't show if: + // - Still loading CLI status + // - CLI is already installed + // - User has dismissed it + // - Message threshold not met (if threshold is set) + if ( + cliInstalled === null || + cliInstalled === true || + dismissed || + (messageThreshold !== undefined && + (messageCount === undefined || messageCount < messageThreshold)) + ) { return null; } return (
- setDismissed(true)}> +
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 08ca69498..0fabb5faf 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -46,6 +46,7 @@ import { ToolCallDiv } from "./ToolCallDiv"; import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; import { cancelStream } from "../../redux/thunks/cancelStream"; +import { CliInstallBanner } from "../config/components/CliInstallBanner"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { useAutoScroll } from "./useAutoScroll"; @@ -380,6 +381,11 @@ export function Chat() { const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000; + // Count user messages for CLI banner threshold + const userMessageCount = useMemo(() => { + return history.filter((item) => item.message.role === "user").length; + }, [history]); + return ( <> {!!showSessionTabs && !isInEdit && } @@ -421,6 +427,12 @@ export function Chat() { inputId={MAIN_EDITOR_INPUT_ID} /> + +
Date: Mon, 6 Oct 2025 15:50:53 -0700 Subject: [PATCH 66/91] Update language around mcp.json to use 'JSON MCP format' - Change heading from 'Using .mcp.json' to 'Using JSON MCP Format' - Replace references to '.mcp.json configuration files' with 'JSON MCP format configuration files' - Update example text to use 'JSON MCP config file' instead of 'mcp.json file' This makes the language more descriptive and focuses on the format rather than just the filename. Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --- docs/customize/deep-dives/mcp.mdx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 40cfb045a..6ad5414bc 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -60,12 +60,12 @@ You can set up an MCP server to search the Continue documentation directly from For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp). -## Using `.mcp.json` from Claude, Cursor, Cline, etc +## Using JSON MCP Format from Claude, Cursor, Cline, etc -If you're coming from another tool that uses `.mcp.json` configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers/` directory (note the plural "Servers") and Continue will automatically pick them up. +If you're coming from another tool that uses JSON MCP format configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers/` directory (note the plural "Servers") and Continue will automatically pick them up. -For example, place your `mcp.json` file at `.continue/mcpServers/mcp.json` in your workspace. +For example, place your JSON MCP config file at `.continue/mcpServers/mcp.json` in your workspace. ## How to Configure MCP Servers From 08e1b59f3e818c103bbb4a7da65cce8020034d66 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 15:57:29 -0700 Subject: [PATCH 67/91] improv: ui --- .../components/CliInstallBanner.test.tsx | 16 ++++++++-------- .../config => }/components/CliInstallBanner.tsx | 14 +++++++------- gui/src/pages/config/index.tsx | 2 +- gui/src/pages/gui/Chat.tsx | 2 +- 4 files changed, 17 insertions(+), 17 deletions(-) rename gui/src/{pages/config => }/components/CliInstallBanner.test.tsx (96%) rename gui/src/{pages/config => }/components/CliInstallBanner.tsx (89%) diff --git a/gui/src/pages/config/components/CliInstallBanner.test.tsx b/gui/src/components/CliInstallBanner.test.tsx similarity index 96% rename from gui/src/pages/config/components/CliInstallBanner.test.tsx rename to gui/src/components/CliInstallBanner.test.tsx index 5bf24bc2e..6f3208c65 100644 --- a/gui/src/pages/config/components/CliInstallBanner.test.tsx +++ b/gui/src/components/CliInstallBanner.test.tsx @@ -6,22 +6,22 @@ import { waitFor, } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { MockIdeMessenger } from "../../../context/MockIdeMessenger"; -import * as util from "../../../util"; -import * as localStorage from "../../../util/localStorage"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; +import * as util from "../../util"; +import * as localStorage from "../../util/localStorage"; import { CliInstallBanner } from "./CliInstallBanner"; -vi.mock("../../../util", async () => { - const actual = await vi.importActual("../../../util"); +vi.mock("../../util", async () => { + const actual = await vi.importActual("../../util"); return { ...actual, getPlatform: vi.fn(), }; }); -vi.mock("../../../util/localStorage", async () => { - const actual = await vi.importActual("../../../util/localStorage"); +vi.mock("../../util/localStorage", async () => { + const actual = await vi.importActual("../../util/localStorage"); return { ...actual, getLocalStorage: vi.fn(), diff --git a/gui/src/pages/config/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx similarity index 89% rename from gui/src/pages/config/components/CliInstallBanner.tsx rename to gui/src/components/CliInstallBanner.tsx index 8747d7ecd..c7011f7b7 100644 --- a/gui/src/pages/config/components/CliInstallBanner.tsx +++ b/gui/src/components/CliInstallBanner.tsx @@ -1,12 +1,12 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; -import { CloseButton } from "../../../components"; -import { CopyButton } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; -import { RunInTerminalButton } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; -import { Card } from "../../../components/ui"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { getPlatform } from "../../../util"; -import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; +import { CloseButton } from "."; +import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; +import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; +import { Card } from "./ui"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { getPlatform } from "../util"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; interface CliInstallBannerProps { /** Current message count - banner shows only if >= messageThreshold */ diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index eae76dbd8..d34d4bcbc 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -8,7 +8,7 @@ import { TabGroup } from "../../components/ui/TabGroup"; import { useAuth } from "../../context/Auth"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { bottomTabSections, getAllTabs, topTabSections } from "./configTabs"; -import { CliInstallBanner } from "./components/CliInstallBanner"; +import { CliInstallBanner } from "../../components/CliInstallBanner"; import { AccountDropdown } from "./features/account/AccountDropdown"; function ConfigPage() { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 0fabb5faf..1bdc846e3 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -46,7 +46,7 @@ import { ToolCallDiv } from "./ToolCallDiv"; import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; import { cancelStream } from "../../redux/thunks/cancelStream"; -import { CliInstallBanner } from "../config/components/CliInstallBanner"; +import { CliInstallBanner } from "../../components/CliInstallBanner"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { useAutoScroll } from "./useAutoScroll"; From 039cab3776abad3ee75ce83248267522f97d4f08 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 16:44:07 -0700 Subject: [PATCH 68/91] improv: ui --- gui/src/components/CliInstallBanner.tsx | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx index c7011f7b7..5eb91af98 100644 --- a/gui/src/components/CliInstallBanner.tsx +++ b/gui/src/components/CliInstallBanner.tsx @@ -1,12 +1,12 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; import { CloseButton } from "."; -import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; -import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; -import { Card } from "./ui"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { getPlatform } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; +import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; +import { Card } from "./ui"; interface CliInstallBannerProps { /** Current message count - banner shows only if >= messageThreshold */ @@ -77,7 +77,7 @@ export function CliInstallBanner({ (messageThreshold !== undefined && (messageCount === undefined || messageCount < messageThreshold)) ) { - return null; + // return null; } return ( @@ -113,11 +113,16 @@ export function CliInstallBanner({
-
- - npm i -g @continuedev/cli - -
+
+
+ + npm i -g @continuedev/cli + +
+
From fa6e558c45d227214a5f9ba78afe46d5104e80a1 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 16:47:05 -0700 Subject: [PATCH 69/91] improv: auto-copy --- gui/src/components/CliInstallBanner.tsx | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx index 5eb91af98..cb3cd59ca 100644 --- a/gui/src/components/CliInstallBanner.tsx +++ b/gui/src/components/CliInstallBanner.tsx @@ -1,9 +1,10 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { useContext, useEffect, useState } from "react"; +import { useContext, useEffect, useRef, useState } from "react"; import { CloseButton } from "."; import { IdeMessengerContext } from "../context/IdeMessenger"; import { getPlatform } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import useCopy from "../hooks/useCopy"; import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; import { Card } from "./ui"; @@ -25,6 +26,21 @@ export function CliInstallBanner({ const ideMessenger = useContext(IdeMessengerContext); const [cliInstalled, setCliInstalled] = useState(null); const [dismissed, setDismissed] = useState(false); + const commandTextRef = useRef(null); + const { copyText } = useCopy("npm i -g @continuedev/cli"); + + const handleCommandClick = () => { + // Select the text + if (commandTextRef.current) { + const selection = window.getSelection(); + const range = document.createRange(); + range.selectNodeContents(commandTextRef.current); + selection?.removeAllRanges(); + selection?.addRange(range); + } + // Copy to clipboard + copyText(); + }; useEffect(() => { // Check if user has permanently dismissed the banner @@ -116,8 +132,10 @@ export function CliInstallBanner({
npm i -g @continuedev/cli From 8ec8795d1d974414b7b8f2292c844d7e630bab34 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 16:58:39 -0700 Subject: [PATCH 70/91] improv: ui --- gui/src/components/CliInstallBanner.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx index cb3cd59ca..488b5333c 100644 --- a/gui/src/components/CliInstallBanner.tsx +++ b/gui/src/components/CliInstallBanner.tsx @@ -28,6 +28,7 @@ export function CliInstallBanner({ const [dismissed, setDismissed] = useState(false); const commandTextRef = useRef(null); const { copyText } = useCopy("npm i -g @continuedev/cli"); + const [showCopiedMessage, setShowCopiedMessage] = useState(false); const handleCommandClick = () => { // Select the text @@ -40,6 +41,10 @@ export function CliInstallBanner({ } // Copy to clipboard copyText(); + + // Show "Copied!" message for 3 seconds + setShowCopiedMessage(true); + setTimeout(() => setShowCopiedMessage(false), 3000); }; useEffect(() => { @@ -130,7 +135,7 @@ export function CliInstallBanner({
-
+
npm i -g @continuedev/cli + {showCopiedMessage && ( + + Copied! + + )}
Date: Mon, 6 Oct 2025 17:06:55 -0700 Subject: [PATCH 71/91] improv: ui --- gui/src/components/CliInstallBanner.tsx | 4 ++-- gui/src/pages/gui/Chat.tsx | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx index 488b5333c..a6ceaa312 100644 --- a/gui/src/components/CliInstallBanner.tsx +++ b/gui/src/components/CliInstallBanner.tsx @@ -2,9 +2,9 @@ import { CommandLineIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; import { CloseButton } from "."; import { IdeMessengerContext } from "../context/IdeMessenger"; +import useCopy from "../hooks/useCopy"; import { getPlatform } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import useCopy from "../hooks/useCopy"; import { CopyButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/CopyButton"; import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton"; import { Card } from "./ui"; @@ -98,7 +98,7 @@ export function CliInstallBanner({ (messageThreshold !== undefined && (messageCount === undefined || messageCount < messageThreshold)) ) { - // return null; + return null; } return ( diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 1bdc846e3..d0c2f45b4 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -43,15 +43,15 @@ import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; +import { useStore } from "react-redux"; +import { CliInstallBanner } from "../../components/CliInstallBanner"; import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; +import { RootState } from "../../redux/store"; import { cancelStream } from "../../redux/thunks/cancelStream"; -import { CliInstallBanner } from "../../components/CliInstallBanner"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { useAutoScroll } from "./useAutoScroll"; -import { useStore } from "react-redux"; -import { RootState } from "../../redux/store"; // Helper function to find the index of the latest conversation summary function findLatestSummaryIndex(history: ChatHistoryItem[]): number { @@ -429,7 +429,7 @@ export function Chat() { From c1d09d8d2160658227431a77cc593381c9bc50f3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 17:10:18 -0700 Subject: [PATCH 72/91] fix: dismissal --- gui/src/pages/config/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index d34d4bcbc..d672b3d09 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -94,7 +94,7 @@ function ConfigPage() {
{allTabs.find((tab) => tab.id === activeTab)?.component}
- +
From 52f2058ad6f0a1239d880e114ccfe30138c6b04d Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Mon, 6 Oct 2025 17:18:18 -0700 Subject: [PATCH 73/91] fix: add max depth to file indexing --- extensions/cli/src/services/FileIndexService.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/extensions/cli/src/services/FileIndexService.ts b/extensions/cli/src/services/FileIndexService.ts index 518ffe9c4..9482699e2 100644 --- a/extensions/cli/src/services/FileIndexService.ts +++ b/extensions/cli/src/services/FileIndexService.ts @@ -2,6 +2,7 @@ import { fdir } from "fdir"; import { AsyncFzf, FzfResultItem } from "fzf"; import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; +import { isGitRepo } from "../util/git.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; @@ -131,10 +132,15 @@ export class FileIndexService extends BaseService { const currentDir = process.cwd(); logger.debug(`Starting file index in directory: ${currentDir}`); + // Determine max depth based on git repository status + const inGitRepo = isGitRepo(); + const maxDepth = inGitRepo ? 10 : 3; + // Create file indexing promise const fileIndexPromise = new fdir() .withFullPaths() .withRelativePaths() + .withMaxDepth(maxDepth) .filter((path) => { // Use the helper function that implements original FILE_PATTERNS logic return this.shouldIncludeFile(path); From 914d587d11f67bff1f6ea7c882f2bbac5f1ee55e Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 6 Oct 2025 17:27:07 -0700 Subject: [PATCH 74/91] fix: type errors --- gui/src/components/CliInstallBanner.test.tsx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/gui/src/components/CliInstallBanner.test.tsx b/gui/src/components/CliInstallBanner.test.tsx index 6f3208c65..5904df50d 100644 --- a/gui/src/components/CliInstallBanner.test.tsx +++ b/gui/src/components/CliInstallBanner.test.tsx @@ -6,22 +6,22 @@ import { waitFor, } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { MockIdeMessenger } from "../../context/MockIdeMessenger"; -import * as util from "../../util"; -import * as localStorage from "../../util/localStorage"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { MockIdeMessenger } from "../context/MockIdeMessenger"; +import * as util from "../util"; +import * as localStorage from "../util/localStorage"; import { CliInstallBanner } from "./CliInstallBanner"; -vi.mock("../../util", async () => { - const actual = await vi.importActual("../../util"); +vi.mock("../util", async () => { + const actual = await vi.importActual("../util"); return { ...actual, getPlatform: vi.fn(), }; }); -vi.mock("../../util/localStorage", async () => { - const actual = await vi.importActual("../../util/localStorage"); +vi.mock("../util/localStorage", async () => { + const actual = await vi.importActual("../util/localStorage"); return { ...actual, getLocalStorage: vi.fn(), From cb46e395bba4aed006c054f30daa0fbb23ca81bf Mon Sep 17 00:00:00 2001 From: Continue Agent Date: Tue, 7 Oct 2025 13:37:36 +0000 Subject: [PATCH 75/91] Add Guides link to CLI sidebar navigation This adds a link to the MCP integration guides in the CLI section of the docs sidebar, making them more discoverable for CLI users. Generated with [Continue](https://continue.dev) Co-Authored-By: Continue Co-authored-by: Username --- docs/docs.json | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/docs.json b/docs/docs.json index ddb6027ef..902bac196 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -26,7 +26,15 @@ { "group": "CLI", "icon": "terminal", - "pages": ["cli/overview", "cli/install", "cli/quick-start"] + "pages": [ + "cli/overview", + "cli/install", + "cli/quick-start", + { + "page": "https://docs.continue.dev/guides/overview#mcp-integration-cookbooks", + "name": "Guides" + } + ] }, { "group": "Features", From c2093fb00c29dd02320f214c32c0915fcb6bce11 Mon Sep 17 00:00:00 2001 From: BekahHW Date: Tue, 7 Oct 2025 11:07:22 -0400 Subject: [PATCH 76/91] Add MCP guides to CLI category --- docs/cli/guides.mdx | 4 ++++ docs/docs.json | 15 ++++++++------- 2 files changed, 12 insertions(+), 7 deletions(-) create mode 100644 docs/cli/guides.mdx diff --git a/docs/cli/guides.mdx b/docs/cli/guides.mdx new file mode 100644 index 000000000..89e96b566 --- /dev/null +++ b/docs/cli/guides.mdx @@ -0,0 +1,4 @@ +--- +title: "Guides" +url: "/guides/overview#mcp-integration-cookbooks" +--- \ No newline at end of file diff --git a/docs/docs.json b/docs/docs.json index 902bac196..b02306cee 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -30,10 +30,7 @@ "cli/overview", "cli/install", "cli/quick-start", - { - "page": "https://docs.continue.dev/guides/overview#mcp-integration-cookbooks", - "name": "Guides" - } + "cli/guides" ] }, { @@ -270,7 +267,6 @@ "guides/posthog-github-continuous-ai", "guides/continue-docs-mcp-cookbook", "guides/sanity-mcp-continue-cookbook", - "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", "guides/dlt-mcp-continue-cookbook", "guides/netlify-mcp-continuous-deployment", @@ -336,8 +332,12 @@ "navbar": { "links": [ { - "label": "Explore", + "label": "🚀 Get Started", "href": "https://hub.continue.dev/" + }, + { + "label": "Sign In to Hub", + "href": "https://hub.continue.dev/auth/signin" } ], "primary": { @@ -370,7 +370,8 @@ } }, "custom": { - "css": ["custom.css"] + "css": ["custom.css"], + "js": ["navigation-enhancer.js", "navigation-banner.js"] }, "redirects": [ { From 8a64999a59e36a7e348c311185306a3a7164ef01 Mon Sep 17 00:00:00 2001 From: BekahHW Date: Tue, 7 Oct 2025 11:11:25 -0400 Subject: [PATCH 77/91] Fix inadvertent additions --- docs/docs.json | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/docs.json b/docs/docs.json index b02306cee..d1b1ec97e 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -267,6 +267,7 @@ "guides/posthog-github-continuous-ai", "guides/continue-docs-mcp-cookbook", "guides/sanity-mcp-continue-cookbook", + "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", "guides/dlt-mcp-continue-cookbook", "guides/netlify-mcp-continuous-deployment", @@ -334,10 +335,6 @@ { "label": "🚀 Get Started", "href": "https://hub.continue.dev/" - }, - { - "label": "Sign In to Hub", - "href": "https://hub.continue.dev/auth/signin" } ], "primary": { @@ -370,8 +367,7 @@ } }, "custom": { - "css": ["custom.css"], - "js": ["navigation-enhancer.js", "navigation-banner.js"] + "css": ["custom.css"] }, "redirects": [ { From 2f1ed97e16c8bbb58a0a72a95f56fc7b43122a49 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 7 Oct 2025 09:35:50 -0700 Subject: [PATCH 78/91] fix: separate preprocessed tool args (#8111) --- core/index.d.ts | 1 + .../FunctionSpecificToolCallDiv.tsx | 29 ++++++----- gui/src/redux/slices/sessionSlice.ts | 6 +-- gui/src/redux/thunks/enhanceParsedArgs.ts | 52 ------------------- .../redux/thunks/preprocessToolCallArgs.ts | 4 +- gui/src/util/clientTools/editImpl.ts | 1 + 6 files changed, 22 insertions(+), 71 deletions(-) delete mode 100644 gui/src/redux/thunks/enhanceParsedArgs.ts diff --git a/core/index.d.ts b/core/index.d.ts index fde08bef2..bd21d4fe8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -478,6 +478,7 @@ interface ToolCallState { toolCall: ToolCall; status: ToolStatus; parsedArgs: any; + processedArgs?: Record; // Added in preprocesing step output?: ContextItem[]; tool?: Tool; } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 0ce5810d5..ed00060a4 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -14,6 +14,7 @@ function FunctionSpecificToolCallDiv({ historyIndex: number; }) { const args = toolCallState.parsedArgs; + const processedArgs = toolCallState.processedArgs; const toolCall = toolCallState.toolCall; switch (toolCall.function?.name) { @@ -28,8 +29,8 @@ function FunctionSpecificToolCallDiv({ case BuiltInToolNames.EditExistingFile: return ( @@ -37,17 +38,17 @@ function FunctionSpecificToolCallDiv({ case BuiltInToolNames.SingleFindAndReplace: const edits: EditOperation[] = [ { - old_string: args?.old_string ?? "", - new_string: args?.new_string ?? "", - replace_all: args?.replace_all, + old_string: processedArgs?.old_string ?? args?.old_string ?? "", + new_string: processedArgs?.new_string ?? args?.new_string ?? "", + replace_all: processedArgs?.replace_all ?? args?.replace_all, }, ]; return ( diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index dee39f856..1292bda69 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -848,7 +848,7 @@ export const sessionSlice = createSlice({ ); } }, - setToolCallArgs: ( + setProcessedToolCallArgs: ( state, action: PayloadAction<{ toolCallId: string; @@ -860,7 +860,7 @@ export const sessionSlice = createSlice({ action.payload.toolCallId, ); if (toolCallState) { - toolCallState.parsedArgs = action.payload.newArgs; + toolCallState.processedArgs = action.payload.newArgs; } }, cancelToolCall: ( @@ -1038,7 +1038,7 @@ export const { acceptToolCall, setToolGenerated, updateToolCallOutput, - setToolCallArgs, + setProcessedToolCallArgs, setMode, setIsSessionMetadataLoading, setAllSessionMetadata, diff --git a/gui/src/redux/thunks/enhanceParsedArgs.ts b/gui/src/redux/thunks/enhanceParsedArgs.ts deleted file mode 100644 index c3377e345..000000000 --- a/gui/src/redux/thunks/enhanceParsedArgs.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { BuiltInToolNames } from "core/tools/builtIn"; -import { resolveRelativePathInDir } from "core/util/ideUtils"; -import { getUriPathBasename } from "core/util/uri"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import { setToolCallArgs } from "../slices/sessionSlice"; -import { AppThunkDispatch } from "../store"; - -export async function enhanceParsedArgs( - ideMessenger: IIdeMessenger, - dispatch: AppThunkDispatch, - toolName: string | undefined, - toolCallId: string, - currentArgs: undefined | Record, -) { - // Add file content to parsedArgs for find/replace tools - let enhancedArgs = { ...currentArgs }; - if ( - (toolName === BuiltInToolNames.SingleFindAndReplace || - toolName === BuiltInToolNames.MultiEdit) && - currentArgs?.filepath && - !currentArgs?.editingFileContents - ) { - try { - const fileUri = await resolveRelativePathInDir( - currentArgs.filepath, - ideMessenger.ide, - ); - if (!fileUri) { - throw new Error(`File ${currentArgs.filepath} not found`); - } - const baseName = getUriPathBasename(fileUri); - const fileContent = await ideMessenger.ide.readFile(fileUri); - enhancedArgs = { - ...currentArgs, - fileUri, - baseName, - editingFileContents: fileContent, - }; - dispatch( - setToolCallArgs({ - toolCallId, - newArgs: enhancedArgs, - }), - ); - } catch (error) { - // If we can't read the file, let the tool handle the error - console.warn( - `Failed to enhance args: failed to read file ${currentArgs?.filepath}`, - ); - } - } -} diff --git a/gui/src/redux/thunks/preprocessToolCallArgs.ts b/gui/src/redux/thunks/preprocessToolCallArgs.ts index fd6a9e52d..be3f8c197 100644 --- a/gui/src/redux/thunks/preprocessToolCallArgs.ts +++ b/gui/src/redux/thunks/preprocessToolCallArgs.ts @@ -4,7 +4,7 @@ import posthog from "posthog-js"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { errorToolCall, - setToolCallArgs, + setProcessedToolCallArgs, updateToolCallOutput, } from "../slices/sessionSlice"; import { AppThunkDispatch } from "../store"; @@ -61,7 +61,7 @@ export async function preprocessToolCalls( ); } else if (preprocessedArgs) { dispatch( - setToolCallArgs({ + setProcessedToolCallArgs({ toolCallId: tcState.toolCallId, newArgs: preprocessedArgs, }), diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index ccc7cc3fa..d26826981 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -2,6 +2,7 @@ import { resolveRelativePathInDir } from "core/util/ideUtils"; import { v4 as uuid } from "uuid"; import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate"; import { ClientToolImpl } from "./callClientTool"; + export const editToolImpl: ClientToolImpl = async ( args, toolCallId, From 2fb5a740ac759c85933a30923f75287e94d74a8e Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Tue, 7 Oct 2025 09:51:54 -0700 Subject: [PATCH 79/91] docs: add GitHub MCP Continue cookbook guide (#8092) * docs: add GitHub MCP Continue cookbook guide - Added new GitHub MCP cookbook guide to documentation - Updated docs.json to include new guide in navigation - Added reference to GitHub MCP cookbook in overview page - Guide demonstrates using GitHub MCP to work with issues and PRs Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * fix: update GitHub MCP package name and formatting - Corrected GitHub MCP package name from github_mcp to github-mcp - Fixed Continue Hub URL to use correct package naming - Updated CLI command to use correct package name - Improved formatting for conclusion checklist items Generated with [Continue](https://continue.dev) Co-Authored-By: Continue * Fix GitHub MCP configuration and update Node.js requirement - Change command from uvx to npx - Update args to use proper package name @modelcontextprotocol/server-github - Add -y flag for automatic installation - Update Node.js requirement from 18+ to 22+ Generated with [Continue](https://continue.dev) Co-Authored-By: Continue --------- Co-authored-by: Continue --- docs/docs.json | 1 + docs/guides/github-mcp-continue-cookbook.mdx | 376 +++++++++++++++++++ docs/guides/overview.mdx | 1 + 3 files changed, 378 insertions(+) create mode 100644 docs/guides/github-mcp-continue-cookbook.mdx diff --git a/docs/docs.json b/docs/docs.json index d1b1ec97e..04e9b809b 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -266,6 +266,7 @@ "pages": [ "guides/posthog-github-continuous-ai", "guides/continue-docs-mcp-cookbook", + "guides/github-mcp-continue-cookbook", "guides/sanity-mcp-continue-cookbook", "guides/sentry-mcp-error-monitoring", "guides/snyk-mcp-continue-cookbook", diff --git a/docs/guides/github-mcp-continue-cookbook.mdx b/docs/guides/github-mcp-continue-cookbook.mdx new file mode 100644 index 000000000..65ea7a3ef --- /dev/null +++ b/docs/guides/github-mcp-continue-cookbook.mdx @@ -0,0 +1,376 @@ +--- +title: "GitHub Issues and PRs with GitHub MCP and Continue" +description: "Use Continue and the GitHub MCP to list, summarize, and act on open issues and recently merged pull requests with natural language prompts." +sidebarTitle: "GitHub Issues with Continue" +--- + + + A GitHub workflow assistant that uses Continue with the GitHub MCP to: + - List, filter, and summarize open issues + - Review and summarize recently merged PRs + - Post comments with AI-generated summaries or checklists + - Automate routine GitHub maintenance with headless CLI runs + + +## Prerequisites + +Before starting, ensure you have: + +- Continue account with **Hub access** +- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents) +- Node.js 22+ installed locally +- A GitHub account and a repository to work with +- A GitHub token with the appropriate scopes: + - For read-only: `repo:read` + - To comment on issues/PRs: `public_repo` for public repos or `repo` for private repos + +For all options, first: + + + ```bash + npm i -g @continuedev/cli + ``` + + + + Add your `GITHUB_TOKEN` to your [Continue Hub agent's environment variables](https://hub.continue.dev/settings). + + + + + To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys). + For write actions (e.g., posting comments), your token must include the relevant GitHub scopes. + + +## GitHub MCP Workflow Options + + + Use the GitHub MCP from Continue Hub for one-click setup, or add it via CLI. + + +After ensuring you meet the **Prerequisites** above, you have two paths to get started: + + + + + + Visit the [Anthropic GitHub MCP](https://hub.continue.dev/anthropic/github-mcp) on Continue Hub and click **Install** to add it to your agent. + + The listing provides a pre-configured MCP block; add your `GITHUB_TOKEN` in Hub. + + + + From your repo root: + ```bash + cn --config continuedev/github-manager-ai + ``` + Now try: "List my open issues labeled bug and summarize priorities." + + + + + You can also attach an MCP to a one-off session: `cn --mcp anthropic/github-mcp`. + + + + + + + Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent). + + + + Install from Hub (recommended) or add YAML manually. Minimal YAML example: + + ```yaml title="config.yaml" + mcpServers: + - name: GitHub MCP + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-github" + env: + GITHUB_TOKEN: ${env:GITHUB_TOKEN} + connectionTimeout: 30 + ``` + + Notes: + - The exact `command`/`args` may differ based on the MCP you choose on Hub. Hub templates prefill these for you. + - Provide `GITHUB_TOKEN` via environment or Hub secrets. + + + + Launch Continue and ask: + ``` + List the 5 most recently updated open issues in this repository. + ``` + + + + + + + To use GitHub MCP with Continue CLI, you need either: + - **Continue CLI Pro Plan** with the models add-on, OR + - **Your own API keys** added to Continue Hub secrets + + The agent will automatically detect and use your configuration along with the GitHub MCP for issue and PR operations. + + + +--- + +## Issue Workflows + +Use natural language to explore, triage, and act on open issues. The agent calls GitHub MCP tools under the hood. + + + **Where to run these workflows:** + - **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs + - **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts + - **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for automation + + +### Triage and Summaries + + + Get a prioritized overview of current open issues. + +**TUI Mode Prompt:** +``` +List the 20 most recently updated open issues in this repo. +Cluster by label and severity. Summarize top priorities. +``` + +**Headless Mode Prompt:** +```bash +cn -p "List the 20 most recently updated open issues in this repo. Cluster by label and severity. Summarize top priorities." --auto +``` + + + + Narrow by label or assignee. + +**TUI Mode Prompt:** +``` +Show open issues labeled bug or security, assigned to @me. +Summarize blockers and suggest next steps. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Show open issues labeled bug or security, assigned to @me. Summarize blockers and suggest next steps." --auto +``` + + +### Taking Action + + + Post an AI-generated status update or checklist. + +**TUI Mode Prompt:** +``` +Find the issue with the most engagement (comments, reactions) in the last 30 days. +Come up with a triage plan and draft a comment with: +- current hypothesis +- next 2 steps +- owner and ETA +Then post the comment. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find the issue with the most engagement in the last 30 days. Come up with a triage plan and draft a comment (hypothesis, next 2 steps, owner, ETA) and post it." --auto +``` + + + Requires a token with permission to comment (`public_repo` or `repo`). The agent will confirm before posting unless `--auto` is used. + + + + + Identify issues that need attention. + +**TUI Mode Prompt:** +``` +Find open issues with no activity in the last 30 days. +Suggest action (close, needs-repro, or prioritize) and draft comments. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find open issues with no activity in the last 30 days. Suggest action and draft comments for each." --auto +``` + + +--- + +## Merged PR Workflows + +Analyze recently merged PRs for change awareness, release notes, and quality signals. + +### Recently Merged Overview + + + Summarize merged PRs over a time window. + +**TUI Mode Prompt:** +``` +List PRs merged in the last 7 days. +Group by area (label or path). Summarize impact and notable changes. +``` + +**Headless Mode Prompt:** +```bash +cn -p "List PRs merged in the last 7 days. Group by area (label or path). Summarize impact and notable changes." --auto +``` + + +### Release Notes + + + Turn merged PRs into crisp release notes. + +**TUI Mode Prompt:** +``` +Generate release notes for PRs merged since tag v1.2.0. +Use keep-a-changelog sections and include PR numbers/authors. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Generate release notes for PRs merged since tag v1.2.0. Use keep-a-changelog sections and include PR numbers/authors." --auto +``` + + +### Deep Dives + + + Get a human-readable summary of a recently merged PR with active discussion. + +**TUI Mode Prompt:** +``` +Find the last merged PR with a significant amount of comments. +Summarize the conversation, including goal, key changes, +risk areas, and any follow-ups. +``` + +**Headless Mode Prompt:** +```bash +cn -p "Find the last merged PR with a significant amount of comments. Summarize the conversation including goal, key changes, risk areas, and follow-ups." --auto +``` + + +--- + +## Automate with GitHub Actions + +Run headless commands on a schedule or in PRs to keep teams informed. + +### Add GitHub Secrets + +Repository Settings → Secrets and variables → Actions: + +- `CONTINUE_API_KEY`: From [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys) +- `GITHUB_TOKEN`: A token with permissions to read issues/PRs and post comments + +### Example Workflow + +Create `.github/workflows/github-mcp-reports.yml`: + +```yaml +name: GitHub MCP Reports + +on: + schedule: + - cron: "0 13 * * 1" # Mondays 13:00 UTC + workflow_dispatch: + pull_request: + types: [opened, synchronize] + +jobs: + report: + runs-on: ubuntu-latest + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "18" + - name: Install Continue CLI + run: npm i -g @continuedev/cli + + - name: Weekly Issue Triage Summary + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + run: | + cn --config continuedev/github-manager-ai \ + -p "List open issues updated in the last 14 days. Group by label and priority. Propose top 5 actions and include issue links." \ + --auto > issue_summary.txt + + - name: Post PR Context Comment + if: github.event_name == 'pull_request' + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + REPORT=$(cn --config continuedev/github-manager-ai \ + -p "Summarize the context for PR #${PR_NUMBER}: related open issues, risk areas, and test suggestions. Keep under 200 words." \ + --auto) + gh pr comment ${PR_NUMBER} --body "$REPORT" +``` + + + Use `continuedev/github-manager-ai` consistently throughout your automation as the recommended agent configuration. + + +--- + +## Troubleshooting + +- **Missing or invalid token:** Ensure `GITHUB_TOKEN` is set and has the required scopes. Try a minimal test: “List 3 open issues in this repo”. +- **Permissions errors on comment:** Your token must include `public_repo` (public) or `repo` (private) to write comments. +- **Rate limiting:** Reduce frequency or filter queries; consider using a PAT distinct from the default Actions token when running in CI. +- **MCP connection timeout:** If using custom YAML, increase `connectionTimeout` or verify the `command`/`args` from the Hub listing. + +## What You've Built + +After completing this guide, you have a complete **AI-powered GitHub workflow system** that: + +- ✅ Uses natural language — Simple prompts for complex GitHub operations +- ✅ Automates issue triage — AI analyzes and summarizes open issues +- ✅ Generates release notes — Automatic PR digests and changelogs +- ✅ Runs continuously — Automated reports via GitHub Actions + + + Your GitHub workflow now operates at **[Level 2 Continuous + AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - + AI handles routine issue triage and PR summaries with human oversight + through review and approval. + + +## Next Steps + +1. **Explore your issues** - Try the issue triage prompts on your repository +2. **Generate release notes** - Use the merged PR prompts to create changelogs +3. **Set up automation** - Add the GitHub Actions workflow to your repo +4. **Customize prompts** - Tailor the prompts to your team's workflow +5. **Monitor progress** - Track issue resolution metrics over time + +## Additional Resources + + + + Anthropic GitHub MCP on Continue Hub + + + How MCP works with Continue agents + + + Pre-configured agent on Continue Hub + + + Official GitHub MCP server README + + + diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index b10a25f1c..8c95a5397 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -20,6 +20,7 @@ description: "Comprehensive collection of practical guides for Continue includin Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue: - [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows +- [GitHub MCP Cookbook](/guides/github-mcp-continue-cookbook) - Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments - [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation - [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP - [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets From fd3d402e9d193348104cc0d3cd3546df9d92030c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 20:44:22 -0700 Subject: [PATCH 80/91] fix: use session count instead of message count --- gui/src/components/CliInstallBanner.test.tsx | 26 ++++++++++---------- gui/src/components/CliInstallBanner.tsx | 18 +++++++------- gui/src/pages/gui/Chat.tsx | 12 ++++----- 3 files changed, 27 insertions(+), 29 deletions(-) diff --git a/gui/src/components/CliInstallBanner.test.tsx b/gui/src/components/CliInstallBanner.test.tsx index 5904df50d..134b5aae2 100644 --- a/gui/src/components/CliInstallBanner.test.tsx +++ b/gui/src/components/CliInstallBanner.test.tsx @@ -351,10 +351,10 @@ describe("CliInstallBanner", () => { }); }); - describe("Message threshold logic", () => { - const renderWithMessageCount = async ( - messageCount?: number, - messageThreshold?: number, + describe("Session threshold logic", () => { + const renderWithSessionCount = async ( + sessionCount?: number, + sessionThreshold?: number, ) => { vi.spyOn(mockIdeMessenger.ide, "subprocess").mockResolvedValue([ "", @@ -365,8 +365,8 @@ describe("CliInstallBanner", () => { render( , ), @@ -374,7 +374,7 @@ describe("CliInstallBanner", () => { }; it("shows banner when no threshold is set", async () => { - await renderWithMessageCount(0, undefined); + await renderWithSessionCount(0, undefined); await waitFor(() => { expect( @@ -383,8 +383,8 @@ describe("CliInstallBanner", () => { }); }); - it("does not show banner when message count is below threshold", async () => { - await renderWithMessageCount(2, 3); + it("does not show banner when session count is below threshold", async () => { + await renderWithSessionCount(2, 3); await waitFor(() => { expect( @@ -393,8 +393,8 @@ describe("CliInstallBanner", () => { }); }); - it("shows banner when message count meets threshold", async () => { - await renderWithMessageCount(3, 3); + it("shows banner when session count meets threshold", async () => { + await renderWithSessionCount(3, 3); await waitFor(() => { expect( @@ -403,8 +403,8 @@ describe("CliInstallBanner", () => { }); }); - it("shows banner when message count exceeds threshold", async () => { - await renderWithMessageCount(5, 3); + it("shows banner when session count exceeds threshold", async () => { + await renderWithSessionCount(5, 3); await waitFor(() => { expect( diff --git a/gui/src/components/CliInstallBanner.tsx b/gui/src/components/CliInstallBanner.tsx index a6ceaa312..36662309a 100644 --- a/gui/src/components/CliInstallBanner.tsx +++ b/gui/src/components/CliInstallBanner.tsx @@ -10,17 +10,17 @@ import { RunInTerminalButton } from "./StyledMarkdownPreview/StepContainerPreToo import { Card } from "./ui"; interface CliInstallBannerProps { - /** Current message count - banner shows only if >= messageThreshold */ - messageCount?: number; - /** Minimum messages before showing banner (default: always show) */ - messageThreshold?: number; + /** Number of sessions user has had - banner shows only if >= sessionThreshold */ + sessionCount?: number; + /** Minimum sessions before showing banner (default: always show) */ + sessionThreshold?: number; /** If true, dismissal is permanent via localStorage (default: session only) */ permanentDismissal?: boolean; } export function CliInstallBanner({ - messageCount, - messageThreshold, + sessionCount, + sessionThreshold, permanentDismissal = false, }: CliInstallBannerProps = {}) { const ideMessenger = useContext(IdeMessengerContext); @@ -90,13 +90,13 @@ export function CliInstallBanner({ // - Still loading CLI status // - CLI is already installed // - User has dismissed it - // - Message threshold not met (if threshold is set) + // - Session threshold not met (if threshold is set) if ( cliInstalled === null || cliInstalled === true || dismissed || - (messageThreshold !== undefined && - (messageCount === undefined || messageCount < messageThreshold)) + (sessionThreshold !== undefined && + (sessionCount === undefined || sessionCount < sessionThreshold)) ) { return null; } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index d0c2f45b4..61fc0a859 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -119,6 +119,9 @@ export function Chat() { const isInEdit = useAppSelector((store) => store.session.isInEdit); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); + const allSessionMetadata = useAppSelector( + (state) => state.session.allSessionMetadata, + ); const hasDismissedExploreDialog = useAppSelector( (state) => state.ui.hasDismissedExploreDialog, ); @@ -381,11 +384,6 @@ export function Chat() { const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000; - // Count user messages for CLI banner threshold - const userMessageCount = useMemo(() => { - return history.filter((item) => item.message.role === "user").length; - }, [history]); - return ( <> {!!showSessionTabs && !isInEdit && } @@ -428,8 +426,8 @@ export function Chat() { /> From 0b3ef9be3de3cf40146cbc44794c52e2c2a918dd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Oct 2025 09:09:22 +0000 Subject: [PATCH 81/91] chore(deps): bump github/codeql-action from 3 to 4 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3 to 4. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v3...v4) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: '4' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/compliance.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 2a1819fa5..7e44fff65 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -119,12 +119,12 @@ jobs: run: npm audit --audit-level=moderate - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@v4 with: languages: javascript - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@v4 # Use this for any files that we want to be certain exist # Basically creates a forcing function to discuss were anyone to want to remove them From 29d4967fe5583b8a3fbb30febd13404c082c5bba Mon Sep 17 00:00:00 2001 From: gippole <49358106+gippole@users.noreply.github.com> Date: Wed, 8 Oct 2025 23:20:30 +0900 Subject: [PATCH 82/91] fix: Tables does not rendered correctly #7465 (#8096) refactor: improve table parsing logic and buffer handling in remarkTables (#7465) --- .../utils/remarkTables.tsx | 89 ++++++++++++++----- 1 file changed, 68 insertions(+), 21 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx index db26e4b3f..a8ecc29b6 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx +++ b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx @@ -23,9 +23,34 @@ import { visit } from "unist-util-visit"; export function remarkTables() { return (tree: any) => { visit(tree, "paragraph", (paragraphNode, index, parentOfParagraphNode) => { - let buffer = ""; - visit(paragraphNode, "text", (textNode) => { - buffer += textNode.value; + // Collect all child nodes into a buffer, preserving their types + const buffer: any[] = []; + paragraphNode.children.forEach((child: any) => { + buffer.push(child); + }); + + // Flatten buffer to a string for regex matching, but keep track of positions + let bufferString = ""; + const positions: { start: number; end: number; node: any }[] = []; + + // Recursive renderer for inline nodes -> markdown-ish text + function renderInline(node: any): string { + if (!node) return ""; + if (Array.isArray(node.children)) { + return node.children.map(renderInline).join(""); + } + if (typeof node.value === "string") { + return node.value; + } + return ""; + } + + buffer.forEach((item) => { + const start = bufferString.length; + // renderInline returns a markdown-like string for inline nodes so decorations are preserved + const rendered = renderInline(item); + bufferString += rendered; + positions.push({ start, end: bufferString.length, node: item }); }); const tableRegex = @@ -33,7 +58,7 @@ export function remarkTables() { //// header // newline // |:---|----:| // new line // table rows // prevent modifying if no markdown tables are present - if (!buffer.match(tableRegex)) { + if (!bufferString.match(tableRegex)) { return; } @@ -42,7 +67,7 @@ export function remarkTables() { const newNodes = []; let failed = false; - while ((match = tableRegex.exec(buffer)) !== null) { + while ((match = tableRegex.exec(bufferString)) !== null) { const fullTableString = match[0]; const headerGroup = match[1]; const separatorGroup = match[2]; @@ -104,16 +129,46 @@ export function remarkTables() { ], }; - // Add any text before the table as a text node - if (match.index > lastIndex) { - newNodes.push({ - type: "text", - value: buffer.slice(lastIndex, match.index), - }); - } + // Add any nodes before/after the table in one go + const tableStart = match.index; + const tableEnd = match.index + fullTableString.length; - // Add table node + // Process the text within the table and the surrounding text together + const beforeNodes: any[] = []; + const afterNodes: any[] = []; + + positions.forEach((pos) => { + if (pos.end <= tableStart) { + beforeNodes.push(pos.node); + } else if (pos.start >= tableEnd) { + afterNodes.push(pos.node); + } else if (pos.node.type === "text") { + // Node is text and overlaps with table, may need splitting + const beforeText = pos.node.value.slice( + 0, + Math.max(0, tableStart - pos.start), + ); + const afterText = pos.node.value.slice( + Math.max(0, tableEnd - pos.start), + ); + if (beforeText) + beforeNodes.push({ type: "text", value: beforeText }); + if (afterText) + afterNodes.push({ type: "text", value: afterText }); + } else { + // Node overlaps with table but isn't text (e.g., inlineCode, emphasis, etc.) + if (pos.start < tableStart) beforeNodes.push(pos.node); + if (pos.end > tableEnd) afterNodes.push(pos.node); + } + }); + + // Add to new nodes + newNodes.push(...beforeNodes); newNodes.push(tableNode); + newNodes.push(...afterNodes); + + // Mark positions as consumed + positions.length = 0; } catch (e) { console.error("Failed to parse markdown table after regex match", e); newNodes.push({ @@ -129,14 +184,6 @@ export function remarkTables() { return; } - // Add any remaining text after the last table - if (lastIndex < buffer.length) { - newNodes.push({ - type: "text", - value: buffer.slice(lastIndex), - }); - } - // Replace the original paragraph node with the new nodes if (newNodes.length > 0) { parentOfParagraphNode.children.splice(index, 1, ...newNodes); From 03598ea26ddd7c1e576aef0c12c005d68890a6f4 Mon Sep 17 00:00:00 2001 From: Mark Espinoza Date: Wed, 8 Oct 2025 09:23:06 -0500 Subject: [PATCH 83/91] fix: LLM Provider - Ask Sage: Updated Model list, updated docs and fixed drop down menu option (#8102) * feat: enhance AskSage with new request handling and token management * feat: update provider options and add new Ask Sage models * feat: update Ask Sage model configurations and remove deprecated API Base URL input * feat: update package versions and add @anthropic-ai/sdk dependency * feat: update model titles and modify API base URL handling in provider configuration * feat: update Ask Sage documentation and add to navigation * Update gui/src/pages/AddNewModel/configs/providers.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --------- Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- core/llm/llms/Asksage.ts | 381 ++++++++++++---- .../model-providers/more/asksage.mdx | 123 +++-- docs/docs.json | 1 + extensions/vscode/package-lock.json | 5 +- gui/package-lock.json | 3 +- gui/src/pages/AddNewModel/configs/models.ts | 422 +++++++++++++++--- .../pages/AddNewModel/configs/providers.ts | 55 ++- 7 files changed, 786 insertions(+), 204 deletions(-) diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 988c57ac6..93d2016c3 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -1,3 +1,4 @@ +import FormData from "form-data"; import { ChatMessage, CompletionOptions, @@ -6,48 +7,169 @@ import { } from "../../index.js"; import { BaseLLM } from "../index.js"; +// Extended options for AskSage +interface AskSageCompletionOptions extends CompletionOptions { + mode?: "chat" | "deep_agent"; + limitReferences?: 0 | 1; + persona?: number; + systemPrompt?: string; + askSageTools?: AskSageTool[]; + enabledMcpTools?: string[]; + toolsToExecute?: string[]; + askSageToolChoice?: ToolChoice; + reasoningEffort?: "low" | "medium" | "high"; + deepAgentId?: number; + streaming?: boolean; + file?: unknown; +} + +const DEFAULT_API_URL = "https://api.asksage.ai/server"; +const DEFAULT_USER_API_URL = "https://api.asksage.ai/user"; +const TOKEN_TTL = 3600000; // 1 hour in milliseconds + +interface AskSageTool { + type: string; + function: { + name: string; + description?: string; + parameters?: Record; + }; +} + +type ToolChoice = + | "auto" + | "none" + | { type: "function"; function: { name: string } }; + +interface AskSageRequestArgs { + model?: string; + temperature?: number; + mode?: "chat" | "deep_agent"; + message?: string | { user: string; message: string }[]; + live?: 0 | 1 | 2; + dataset?: string | string[]; + limit_references?: 0 | 1; + persona?: number; + system_prompt?: string; + tools?: AskSageTool[]; + enabled_mcp_tools?: string[]; + tools_to_execute?: string[]; + tool_choice?: ToolChoice; + reasoning_effort?: "low" | "medium" | "high"; + deep_agent_id?: number; + streaming?: boolean; + file?: unknown; +} + +interface AskSageResponse { + text?: string; + answer?: string; + message?: string; + status?: number | string; + response?: unknown; + choices?: Array<{ + message?: { + content?: string; + }; + }>; +} + +interface TokenResponse { + status: number | string; + response: { + access_token: string; + }; +} + class Asksage extends BaseLLM { static providerName = "askSage"; static defaultOptions: Partial = { - apiBase: "https://api.asksage.ai/server/", + apiBase: DEFAULT_API_URL, model: "gpt-4o", }; - private static modelConversion: { [key: string]: string } = { - "gpt-4o-gov": "gpt-4o-gov", // Works - "gpt-4o-mini-gov": "gpt-4o-mini-gov", - "gpt4-gov": "gpt4-gov", // Works - "gpt-gov": "gpt-gov", // Works - "gpt-4o": "gpt-4o", // Works - "gpt-4o-mini": "gpt-4o-mini", // Works - gpt4: "gpt4", // Works - "gpt4-32k": "gpt4-32k", - "gpt-o1": "gpt-o1", // Works - "gpt-o1-mini": "gpt-o1-mini", // Works - "gpt-o3-mini": "gpt-o3-mini", // Stub - "gpt-3.5-turbo": "gpt35-16k", // Works - "aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works - "claude-3-5-sonnet-latest": "claude-35-sonnet", // Works - "claude-3-opus-20240229": "claude-3-opus", // Works - "claude-3-sonnet-20240229": "claude-3-sonnet", // Works - "grok-beta": "xai-grok", - "groq-llama33": "groq-llama33", - "groq-70b": "groq-70b", - "mistral-large-latest": "mistral-large", // Works - "llama3-70b": "llma3", // Works - "gemini-1.5-pro-latest": "google-gemini-pro", // Works - }; + private sessionTokenPromise: Promise | null = null; + private tokenTimestamp: number = 0; + private email?: string; + private userApiUrl: string; constructor(options: LLMOptions) { super(options); this.apiVersion = options.apiVersion ?? "v1.2.4"; + this.email = process.env.ASKSAGE_EMAIL; + this.userApiUrl = process.env.ASKSAGE_USER_API_URL || DEFAULT_USER_API_URL; } - protected _convertModelName(model: string): string { - console.log("Converting model:", model); - const convertedModel = Asksage.modelConversion[model] ?? model; - console.log("Converted model:", convertedModel); - return convertedModel; + private async getSessionToken(): Promise { + if (!this.apiKey) { + throw new Error( + "AskSage adapter: missing ASKSAGE_API_KEY. Provide it in your environment variables or .env file.", + ); + } + + // If no email, use API key directly + if (!this.email || this.email.length === 0) { + return this.apiKey; + } + + const url = this.userApiUrl.replace(/\/$/, "") + "/get-token-with-api-key"; + const res = await this.fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: this.email, api_key: this.apiKey }), + }); + + const data = (await res.json()) as TokenResponse; + if (parseInt(String(data.status)) !== 200) { + throw new Error("Error getting access token: " + JSON.stringify(data)); + } + return data.response.access_token; + } + + private async getToken(): Promise { + // Check if token needs refresh + if ( + !this.sessionTokenPromise || + Date.now() - this.tokenTimestamp > TOKEN_TTL + ) { + this.sessionTokenPromise = this.getSessionToken(); + this.tokenTimestamp = Date.now(); + } + return this.sessionTokenPromise; + } + + private isFileLike(val: unknown): boolean { + return ( + val !== null && + val !== undefined && + ((typeof File !== "undefined" && val instanceof File) || + (typeof Buffer !== "undefined" && val instanceof Buffer) || + (typeof val === "object" && + ("path" in val || "name" in val || "type" in val))) + ); + } + + private toFormData(args: AskSageRequestArgs): FormData { + const form = new FormData(); + + for (const [key, value] of Object.entries(args)) { + if (value === undefined || value === null) continue; + + if (key === "file" && value) { + if (Buffer.isBuffer(value)) { + form.append("file", value, "file"); + } else if (typeof value === "string") { + form.append("file", value); + } else { + form.append("file", value as Buffer); + } + } else if (Array.isArray(value) || typeof value === "object") { + form.append(key, JSON.stringify(value)); + } else { + form.append(key, String(value)); + } + } + return form; } protected _convertMessage(message: ChatMessage) { @@ -63,43 +185,63 @@ class Asksage extends BaseLLM { }; } - protected _convertArgs(options: any, messages: ChatMessage[]) { - let formattedMessage: any; + protected _convertArgs( + options: AskSageCompletionOptions, + messages: ChatMessage[], + ): AskSageRequestArgs { + let formattedMessage: string | { user: string; message: string }[]; if (messages.length === 1) { - formattedMessage = messages[0].content; + formattedMessage = messages[0].content as string; } else { formattedMessage = messages.map(this._convertMessage); } - const args: any = { + const args: AskSageRequestArgs = { message: formattedMessage, - persona: options.persona ?? "default", - dataset: options.dataset ?? "none", - limit_references: options.limitReferences ?? 0, + model: options.model, temperature: options.temperature ?? 0.0, - live: options.live ?? 0, - model: this._convertModelName(options.model), + mode: "chat", // Always use chat mode + limit_references: 0, // Always use 0 + persona: options.persona as number | undefined, system_prompt: options.systemPrompt ?? + process.env.ASKSAGE_SYSTEM_PROMPT ?? "You are an expert software developer. You give helpful and concise responses.", - tools: options.tools, - tool_choice: options.toolChoice, + tools: options.askSageTools, + // enabled_mcp_tools: options.enabledMcpTools as string[] | undefined, + // tools_to_execute: options.toolsToExecute as string[] | undefined, + tool_choice: options.askSageToolChoice, + reasoning_effort: options.reasoningEffort as + | "low" + | "medium" + | "high" + | undefined, + deep_agent_id: options.deepAgentId as number | undefined, + streaming: options.streaming as boolean | undefined, + file: options.file, }; + // Remove undefined values Object.keys(args).forEach( - (key) => args[key] === undefined && delete args[key], + (key) => + args[key as keyof AskSageRequestArgs] === undefined && + delete args[key as keyof AskSageRequestArgs], ); return args; } - protected _getHeaders() { + protected async _getHeaders( + hasFile: boolean = false, + ): Promise> { + const token = await this.getToken(); const headers: Record = { - "Content-Type": "application/json", + accept: "application/json", + "x-access-tokens": token, }; - if (this.apiKey) { - headers["x-access-tokens"] = this.apiKey; + if (!hasFile) { + headers["Content-Type"] = "application/json"; } return headers; @@ -125,21 +267,66 @@ class Asksage extends BaseLLM { } const messages: ChatMessage[] = [{ role: "user", content: prompt }]; - const args = this._convertArgs(options, messages); + const hasFile = this.isFileLike(args.file); + const endpoint = hasFile ? "query_with_file" : "query"; - const response = await this.fetch(this._getEndpoint("query"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify(args), - }); + try { + let response; + if (hasFile) { + const form = this.toFormData(args); + const headers = await this._getHeaders(true); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers: { + ...headers, + ...form.getHeaders(), + }, + body: form as unknown as BodyInit, + signal, + }); + } else { + const headers = await this._getHeaders(false); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers, + body: JSON.stringify(args), + signal, + }); + } - if (response.status === 499) { - return ""; // Aborted by user + if (response.status === 499) { + return ""; // Aborted by user + } + + if (!response.ok) { + const errText = await response.text(); + + // Clear token cache on 401 + if (response.status === 401) { + this.sessionTokenPromise = null; + this.tokenTimestamp = 0; + } + + throw new Error( + `AskSage API error: ${response.status} ${response.statusText}: ${errText}`, + ); + } + + const data = (await response.json()) as AskSageResponse; + return ( + data.text || + data.answer || + data.message || + data.choices?.[0]?.message?.content || + "" + ); + } catch (error) { + if (error instanceof Error) { + throw new Error(`AskSage client error: ${error.message}`); + } + throw error; } - - const data = await response.json(); - return data.message; } protected async *_streamComplete( @@ -157,30 +344,74 @@ class Asksage extends BaseLLM { options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, messages); + const hasFile = this.isFileLike(args.file); + const endpoint = hasFile ? "query_with_file" : "query"; - const response = await this.fetch(this._getEndpoint("query"), { - method: "POST", - headers: this._getHeaders(), - body: JSON.stringify(args), - signal, - }); + try { + let response; + if (hasFile) { + const form = this.toFormData(args); + const headers = await this._getHeaders(true); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers: { + ...headers, + ...form.getHeaders(), + }, + body: form as unknown as BodyInit, + signal, + }); + } else { + const headers = await this._getHeaders(false); + response = await this.fetch(this._getEndpoint(endpoint), { + method: "POST", + headers, + body: JSON.stringify(args), + signal, + }); + } - if (response.status === 499) { - return; // Aborted by user + if (response.status === 499) { + return; // Aborted by user + } + + if (!response.ok) { + const errText = await response.text(); + + // Clear token cache on 401 + if (response.status === 401) { + this.sessionTokenPromise = null; + this.tokenTimestamp = 0; + } + + throw new Error( + `AskSage API error: ${response.status} ${response.statusText}: ${errText}`, + ); + } + + const data = (await response.json()) as AskSageResponse; + + const assistantMessage: ChatMessage = { + role: "assistant", + content: + data.text || + data.answer || + data.message || + data.choices?.[0]?.message?.content || + "", + }; + + yield assistantMessage; + } catch (error) { + if (error instanceof Error) { + throw new Error(`AskSage client error: ${error.message}`); + } + throw error; } - - const data = await response.json(); - - const assistantMessage: ChatMessage = { - role: "assistant", - content: data.message, - }; - - yield assistantMessage; } async listModels(): Promise { - return Object.keys(Asksage.modelConversion); + return []; } } diff --git a/docs/customize/model-providers/more/asksage.mdx b/docs/customize/model-providers/more/asksage.mdx index 03ad0e3ca..c7dd81391 100644 --- a/docs/customize/model-providers/more/asksage.mdx +++ b/docs/customize/model-providers/more/asksage.mdx @@ -1,18 +1,34 @@ --- -title: "AskSage" -description: "Configure AskSage with Continue to access a wide range of models including government-compliant versions of GPT and Claude models, supporting chat and edit functionalities" +title: "Ask Sage" +slug: ../asksage --- + + **Discover Ask Sage models [here](https://hub.continue.dev/?q=Ask%20Sage)** + + - To get an Ask Sage API key login to the Ask Sage platform (If you don't have - an account, you can create one [here](https://chat.asksage.ai/)) and follow - the instructions in the Ask Sage Docs: [Ask Sage API - Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) + You can get an API key from the [Ask Sage](https://www.asksage.ai/). -## Configuration -To use the Ask Sage models, you can use the following +## Overview + +Ask Sage provides secure, government-compliant access to LLMs. This guide explains how to set up and configure Ask Sage models, including support for DoD certificates. + +## 1. Prerequisites + +- **Ask Sage Account:** + Sign up or log in at [Ask Sage Platform](https://chat.asksage.ai/). + +- **API Key:** + Follow the [API Key Documentation](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) to generate your key. + + +## 2. Configuration + +Add your Ask Sage model to your Continue configuration file. + @@ -42,53 +58,66 @@ To use the Ask Sage models, you can use the following -The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below: +## 3. Using DoD Certificates -> Server API for query/training etc.: -> -> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0 -> - URL for this API is: https://api.asksage.ai/server/ +For secure environments, specify your DoD CA bundle path: -## Usage -Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev: + + + ```yaml title="config.yaml" + models: + - name: GPT-4 gov + provider: askSage + model: gpt4-gov + apiBase: https://api.asksage.ai/server/ + apiKey: + requestOptions: + caBundlePath: /path/to/dod/certificates + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "GPT-4 gov", + "provider": "askSage", + "model": "gpt4-gov", + "apiBase": "https://api.asksage.ai/server/", + "apiKey": "", + "requestOptions": { + "caBundlePath": "/path/to/dod/certificates" + } + } + ] + } + ``` + + -- `Chat` to understand and iterate on code in the sidebar -- `Edit` to modify code without leaving your current file +Replace `/path/to/dod/certificates` with your actual CA bundle file path. -More models, functionalities and documentation will be added in the future for Ask Sage Integration. +--- -> We recommend to utilize the `OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities. +## 4. Final Steps -## Ask Sage Documentation +- Save your configuration file. +- Restart Continue to apply changes. -Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage. +Your Ask Sage model will now be available in Continue. -## Current Models From Ask Sage Supported +## 5. Usage -The current Models available provided by Ask Sage are: +Supported features: + +- **Chat:** Interact and iterate on code in the sidebar. +- **Edit:** Modify code in place. + +## 6. Support + +- Refer to [Ask Sage Docs](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) for more details. +- Email the Ask Sage support team for assistance at support@asksage.ai. + +--- -| Index | Model | Added | -| ----- | --------------------- | ----- | -| 1 | GPT-4 Gov | ✅ | -| 2 | GPT-4o Gov | ✅ | -| 3 | GPT-4o-mini Gov | ✅ | -| 4 | GPT-3.5-Turbo Gov | ✅ | -| 5 | GPT-4o | ✅ | -| 6 | GPT-4o-mini | ✅ | -| 7 | GPT-4 | ✅ | -| 8 | GPT-4-32K | ✅ | -| 9 | GPT-o1 | ✅ | -| 10 | GPT-o1-mini | ✅ | -| 10 | GPT-o3-mini | ✅ | -| 11 | GPT-3.5-turbo | ✅ | -| 12 | Claude 3.5 Sonnet Gov | ✅ | -| 13 | Claude 3 Opus | ✅ | -| 14 | Claude 3 Sonet | ✅ | -| 15 | Claude 3.5 Sonnet | ✅ | -| 16 | Grok (xAI) | ✅ | -| 17 | Groq Llama 3.3 | ✅ | -| 18 | Groq 70B | ✅ | -| 19 | Gemini Pro | ✅ | -| 20 | llama 3 | ✅ | -| 21 | Mistral Large | ✅ | diff --git a/docs/docs.json b/docs/docs.json index 04e9b809b..27282b5d7 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -135,6 +135,7 @@ { "group": "More Providers", "pages": [ + "customize/model-providers/more/asksage", "customize/model-providers/more/deepseek", "customize/model-providers/more/deepinfra", "customize/model-providers/more/groq", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index eaa07b5a0..47283ebf1 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.3.12", + "version": "1.3.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.3.12", + "version": "1.3.15", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../../packages/config-types", @@ -100,6 +100,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", diff --git a/gui/package-lock.json b/gui/package-lock.json index 962b06471..1796d1ab7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -116,6 +116,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -235,7 +236,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.14.0", + "version": "1.23.0", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 76151a274..aaa8092f7 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -514,7 +514,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8192, }, icon: "meta.png", - providerOptions: ["groq", "askSage"], + providerOptions: ["groq"], isOpenSource: false, }, llama318bChat: { @@ -841,7 +841,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 32000, }, icon: "mistral.png", - providerOptions: ["mistral", "askSage"], + providerOptions: ["mistral"], isOpenSource: false, }, mistralNemo: { @@ -1114,7 +1114,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 128_000, title: "GPT-4o", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1125,9 +1125,10 @@ export const models: { [key: string]: ModelPackage } = { params: { model: "gpt-4o-mini", contextLength: 128_000, + title: "GPT-4o mini", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1140,7 +1141,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 8096, title: "GPT-3.5-Turbo", }, - providerOptions: ["openai", "askSage"], + providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, @@ -1154,7 +1155,7 @@ export const models: { [key: string]: ModelPackage } = { title: "Claude 4 Sonnet", apiKey: "", }, - providerOptions: ["anthropic", "askSage"], + providerOptions: ["anthropic"], icon: "anthropic.png", isOpenSource: false, }, @@ -1167,7 +1168,7 @@ export const models: { [key: string]: ModelPackage } = { title: "Claude 4.1 Opus", apiKey: "", }, - providerOptions: ["anthropic", "askSage"], + providerOptions: ["anthropic"], icon: "anthropic.png", isOpenSource: false, }, @@ -1331,135 +1332,382 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["vertexai"], isOpenSource: false, }, + // OpenAI Models via Ask Sage + asksagegpt4o: { + title: "GPT-4o*", + description: + "An even faster version of GPT-4 with stronger multi-modal capabilities.", + params: { + model: "gpt-4o", + contextLength: 128_000, + maxTokens: 16_384, + title: "GPT-4o*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt4omini: { + title: "GPT-4o Mini*", + description: + "A model at less than half the price of gpt-3.5-turbo, but near gpt-4 in capabilities.", + params: { + model: "gpt-4o-mini", + contextLength: 128_000, + maxTokens: 16_384, + title: "GPT-4o mini*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, asksagegpt4gov: { - title: "GPT-4 gov", + title: "GPT-4 gov*", description: "U.S. Government. Most capable model today - which is similar to GPT-4 but approved for use by the U.S. Government.", params: { model: "gpt4-gov", contextLength: 128_000, - title: "GPT-4 gov", + maxTokens: 4096, + title: "GPT-4 gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4ogov: { - title: "GPT-4o gov", + title: "GPT-4o gov*", description: "U.S. Government. Most capable model today - which is similar to GPT-4o but approved for use by the U.S. Government.", params: { model: "gpt-4o-gov", contextLength: 128_000, - title: "GPT-4o-gov", + maxTokens: 4096, + title: "GPT-4o-gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt35: { + title: "GPT-3.5*", + description: "Azure OpenAI GPT 3.5 Model.", + params: { + model: "gpt", + contextLength: 4096, + title: "GPT-3.5*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt35gov: { - title: "GPT-3.5-Turbo gov", + title: "GPT-3.5 gov*", description: "U.S. Government. Inexpensive and good ROI.", params: { model: "gpt-gov", - contextLength: 8096, - title: "GPT-3.5-Turbo gov", + contextLength: 16834, + maxTokens: 4096, + title: "GPT-3.5 gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4ominigov: { - title: "GPT-4o-mini gov", - description: - "U.S. Government. Latest OpenAI GPT 4o-mini model. More inexpensive than GPT4. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)). 16,384 token response max.", + title: "GPT-4o-mini gov*", + description: "OpenAI GPT 4o-mini model.", params: { model: "gpt-4o-mini-gov", contextLength: 128_000, - title: "GPT-4o-mini gov", + maxTokens: 16_384, + title: "GPT-4o-mini gov*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, asksagegpt4: { - title: "GPT-4", + title: "GPT-4*", description: "GPT4 is about 5X more expensive than Ask Sage tokens and 50X more expensive than GPT3.5", params: { model: "gpt4", contextLength: 8_192, - title: "GPT-4", - }, - providerOptions: ["openai"], - icon: "openai.png", - isOpenSource: false, - }, - asksagegpt432: { - title: "GPT-4-32k", - description: - "The GPT-4-32k model is a variant of the GPT-4 model developed by OpenAI. It is designed to handle a larger context window, capable of processing up to 32,768 tokens, which makes it suitable for scenarios that require extensive information integration and data analysis", - params: { - model: "gpt4-32k", - contextLength: 32_768, - title: "GPT-4-32k", + title: "GPT-4*", + apiKey: "", }, providerOptions: ["openai"], icon: "openai.png", isOpenSource: false, }, asksagegpto1: { - title: "GPT-o1", + title: "GPT-o1*", description: "Latest OpenAI GPT-o1 model. More inexpensive than GPT4. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)).", params: { model: "gpt-o1", contextLength: 128_000, - title: "GPT-o1", + maxTokens: 32_768, + title: "GPT-o1*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, // stopped here + }, + asksagegpt41: { + title: "GPT-4.1*", + description: "Azure OpenAI GPT 4.1 model.", + params: { + model: "gpt-4.1", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksagegpto1mini: { - title: "GPT-o1-mini", - description: - "Latest OpenAI GPT-o1-mini model. More inexpensive than GPT-o1. Capable of ingesting and analyzing images (JPG, PNG, GIF (20MB files max)). 16,384 token response max.", + asksagegpt41mini: { + title: "GPT-4.1 mini*", + description: "Azure OpenAI GPT 4.1 mini model.", params: { - model: "gpt-o1-mini", - contextLength: 128_000, - title: "GPT-o1-mini", + model: "gpt-4.1-mini", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1 mini*", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksagegpto3mini: { - title: "GPT-o3-mini", - description: - "o3-mini can outperform o1 in coding and other reasoning tasks, and is 93% cheaper and has lower latency. It supports function calling, Structured Outputs, streaming, and developer messages. o3-mini comes with a larger context window of 200,000 tokens and a max output of 100,000 tokens", + asksagegpt41nano: { + title: "GPT-4.1 nano*", + description: "Azure OpenAI GPT 4.1 nano model.", params: { - model: "gpt-o3-mini", + model: "gpt-4.1-nano", + contextLength: 1_000_000, + maxTokens: 32_768, + title: "GPT-4.1 nano*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5: { + title: "GPT-5*", + description: "OpenAI's GPT-5 model", + params: { + model: "gpt-5", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5nano: { + title: "GPT-5-nano*", + description: "OpenAI's GPT-5-nano model", + params: { + model: "gpt-5-nano", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5-nano*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpt5mini: { + title: "GPT-5-mini*", + description: "OpenAI's GPT-5-mini model", + params: { + model: "gpt-5-mini", + contextLength: 272_000, + maxTokens: 128_000, + title: "GPT-5-mini*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksagegpto3: { + title: "GPT-o3", + description: "Azure OpenAI GPT o3 model.", + params: { + model: "gpt-o3", contextLength: 200_000, - title: "GPT-o3-mini", + maxTokens: 100_000, + title: "GPT-o3", + apiKey: "", }, providerOptions: ["askSage"], icon: "openai.png", isOpenSource: false, }, - asksageclaude35gov: { - title: "Claude 3.5 Sonnet gov", + asksagegpt04mini: { + title: "GPT-o4-mini", + description: "Azure OpenAI GPT o4-mini model.", + params: { + model: "gpt-o4-mini", + contextLength: 200_000, + maxTokens: 100_000, + title: "GPT-o4-mini", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "openai.png", + isOpenSource: false, + }, + asksageclaude35Sonnet: { + title: "Claude 3.5 Sonnet", description: "Anthropic's most intelligent model, but much less expensive than Claude 3 Opus", params: { - model: "aws-bedrock-claude-35-sonnet-gov", + model: "claude-35-sonnet", contextLength: 200_000, - title: "Claude 3.5 Sonnet gov", + title: "Claude 3.5 Sonnet", + apiKey: "", }, providerOptions: ["askSage"], icon: "anthropic.png", isOpenSource: false, }, + asksageclaude37sonnet: { + title: "Claude 3.7 Sonnet", + description: "Anthropic's 3.7 model.", + params: { + model: "claude-37-sonnet", + contextLength: 200_000, + title: "Claude 3.7 Sonnet", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude37sonnetgov: { + title: "Claude 3.7 Sonnet gov*", + description: "Anthropic's 3.7 Sonnet model.", + params: { + model: "aws-bedrock-claude-37-sonnet-gov", + contextLength: 200_000, + title: "Claude 3.7 Sonnet gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude35gov: { + title: "Claude 3.5 Sonnet gov*", + description: "Anthropic's 3.5 Sonnet model.", + params: { + model: "aws-bedrock-claude-35-sonnet-gov", + contextLength: 200_000, + title: "Claude 3.5 Sonnet gov*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4s: { + title: "Claude 4 Sonnet", + description: "Anthropic's Claude 4 Sonnet", + params: { + model: "claude-4-sonnet", + contextLength: 200_000, + title: "Claude 4 Sonnet", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4o: { + title: "Claude 4 Opus", + description: "Anthropic's Claude 4 Opus", + params: { + model: "claude-4-opus", + contextLength: 200_000, + title: "Claude 4 Opus", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude4sonnet: { + title: "Claude 4 Sonnet*", + description: + "Anthropic's most powerful model, designed for complex, reasoning-heavy tasks like agentic search, coding, and writing.", + params: { + model: "google-claude-4-sonnet", + contextLength: 200_000, + title: "Claude 4 Sonnet*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude45sonnet: { + title: "Claude 4.5 Sonnet*", + description: + "Anthropic's most powerful model, designed for complex, reasoning-heavy tasks like agentic search, coding, and writing.", + params: { + model: "google-claude-45-sonnet", + contextLength: 200_000, + title: "Claude 4.5 Sonnet*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksageclaude41opus: { + title: "Claude 4.1 Opus*", + description: "Claude 4.1 Opus", + params: { + model: "google-claude-4-opus", + contextLength: 200_000, + title: "Claude 4.1 Opus*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "anthropic.png", + isOpenSource: false, + }, + asksagenovalite: { + title: "Nova Lite*", + description: "AWS Gov Nova Lite model.", + params: { + model: "aws-bedrock-nova-lite-gov", + contextLength: 300_000, + title: "Nova Lite*", + apiKey: "", + }, + providerOptions: ["askSage"], + icon: "aws.png", + isOpenSource: false, + }, asksagegroqllama33: { title: "Llama 3.3", description: "Llama-3.3 is a large language model customized by Groq.", @@ -1467,7 +1715,9 @@ export const models: { [key: string]: ModelPackage } = { title: "Llama 3.3", model: "groq-llama33", contextLength: 128_000, + apiKey: "", }, + providerOptions: ["askSage"], icon: "groq.png", isOpenSource: true, }, @@ -1478,10 +1728,66 @@ export const models: { [key: string]: ModelPackage } = { title: "Groq-70B", model: "groq-70b", contextLength: 8_192, + apiKey: "", }, + providerOptions: ["askSage"], icon: "groq.png", isOpenSource: true, }, + asksagegemini20Flash: { + title: "Gemini 2.0 Flash*", + description: + "Google's powerful workhorse model with low latency and enhanced performance.", + params: { + title: "Gemini 2.0 Flash*", + model: "google-gemini-20-flash", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegemini25Pro: { + title: "Gemini 2.5 Pro*", + description: "Google's Gemini 2.5 Pro model", + params: { + title: "Gemini 2.5 Pro*", + model: "google-gemini-2.5-pro", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegemini25flash: { + title: "Gemini 2.5 Flash*", + description: "Google's Gemini 2.5 Flash model", + params: { + title: "Gemini 2.5 Flash*", + model: "google-gemini-2.5-flash", + contextLength: 1_000_000, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, + asksagegrok4: { + title: "Grok 4", + description: + "xAI's latest and greatest flagship model, offering strong performance in natural language, math and reasoning.", + params: { + title: "Grok 4", + model: "xai-grok", + contextLength: 256_000, + apiKey: "", + }, + icon: "xAI.png", + providerOptions: ["askSage"], + isOpenSource: false, + }, Qwen2Coder: { title: "Qwen 2.5 Coder 7b", description: @@ -1531,7 +1837,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 256000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok4FastReasoning: { @@ -1544,7 +1850,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 2_000_000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok4FastNonReasoning: { @@ -1557,7 +1863,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 2_000_000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok4: { @@ -1571,7 +1877,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 256_000, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok3: { @@ -1585,7 +1891,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 131_072, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, grok3Mini: { @@ -1599,7 +1905,7 @@ export const models: { [key: string]: ModelPackage } = { contextLength: 131_072, }, icon: "xAI.png", - providerOptions: ["xAI", "askSage"], + providerOptions: ["xAI"], isOpenSource: false, }, gemma2_2b: { diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 280eb0ae9..88e091ce7 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -942,7 +942,6 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ...completionParamsInputsConfigs, ], }, - askSage: { title: "Ask Sage", provider: "askSage", @@ -953,7 +952,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo tags: [ModelProviderTags.RequiresApiKey], params: { apiKey: "", - apiBase: "https://api.asksage.ai/server/", // Default base URL + apiBase: "https://api.asksage.ai/server/", }, collectInputFor: [ { @@ -967,32 +966,46 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo inputType: "text", key: "apiBase", label: "API Base URL", - placeholder: "Enter the API Base URL", + placeholder: "Enter your Ask Sage API base URL", required: true, + defaultValue: "https://api.asksage.ai/server/", }, ...completionParamsInputsConfigs, ], packages: [ - models.asksagegpt4ogov, - models.asksagegpt4ominigov, - models.asksagegpt4gov, - models.asksagegpt35gov, - models.gpt4o, - models.gpt4omini, - models.asksagegpt4, - models.asksagegpt432, - models.asksagegpto1, - models.asksagegpto1mini, - models.gpt35turbo, + models.asksageclaude45sonnet, + models.asksageclaude4sonnet, + models.asksageclaude41opus, + models.asksagegpt5, + models.asksagegpt5nano, + models.asksagegpt5mini, + models.asksagegemini20Flash, + models.asksagegemini25Pro, + models.asksagegemini25flash, models.asksageclaude35gov, - models.claude35Sonnet, - models.claude3Opus, - models.claude3Sonnet, - models.grokBeta, - models.asksagegroqllama33, + models.asksageclaude37sonnetgov, + models.asksagegpt4o, + models.asksagegpt4omini, + models.asksagegpt4gov, + models.asksagegpt4ogov, + models.asksagegpt35, + models.asksagegpt35gov, + models.asksagegpt4ominigov, + models.asksagegpt4, + models.asksagegpto1, + models.asksagegpt41, + models.asksagegpt41mini, + models.asksagegpt41nano, + models.asksagegpto3, + models.asksagegpt04mini, + models.asksagenovalite, models.asksagegroq70b, - models.mistralLarge, - models.llama370bChat, + models.asksagegroqllama33, + models.asksagegrok4, + models.asksageclaude35Sonnet, + models.asksageclaude37sonnet, + models.asksageclaude4s, + models.asksageclaude4o, ], apiKeyUrl: "https://chat.asksage.ai/", }, From 6748434c9cf5c9e4bdf44af225dc789a10652230 Mon Sep 17 00:00:00 2001 From: Ting-Wai <40179554+tingwai@users.noreply.github.com> Date: Wed, 8 Oct 2025 07:25:31 -0700 Subject: [PATCH 84/91] fix: flakey CLI tests (#8124) fix: flakey test with waitForNextRender --- .../ui/__tests__/TUIChat.fileSearch.test.tsx | 4 +-- .../src/ui/__tests__/TUIChat.input.test.tsx | 17 +++++++---- .../__tests__/TUIChat.slashCommands.test.tsx | 30 +++++++------------ .../src/ui/__tests__/TUIChat.testHelper.ts | 14 +++++++++ 4 files changed, 37 insertions(+), 28 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx index f8d56a5f0..b38a90cb6 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx @@ -1,4 +1,5 @@ import { renderInMode, testSingleMode } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - @ File Search Tests", () => { testSingleMode("shows @ character when user types @", "local", async () => { @@ -56,9 +57,8 @@ describe("TUIChat - @ File Search Tests", () => { // Type multiple @ characters stdin.write("@@test"); - // Wait for UI update - await new Promise((resolve) => setTimeout(resolve, 500)); + await waitForNextRender(); const frame = lastFrame(); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx index 35aa50a16..e76c00806 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx @@ -1,10 +1,12 @@ -import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; +import { renderInMode, testBothModes } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - User Input Tests", () => { - testBothModes("shows typed text in input field", (mode) => { + testBothModes("shows typed text in input field", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); stdin.write("Testing 123"); + await waitForNextRender(); const frame = lastFrame(); // The input might be in a different format, let's be more flexible @@ -23,13 +25,14 @@ describe("TUIChat - User Input Tests", () => { testBothModes("handles Enter key to submit", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); + await waitForNextRender(); const beforeEnter = lastFrame(); expect(beforeEnter).toContain("Ask anything"); stdin.write("\r"); // Wait for the UI to update after pressing enter - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 500)); const afterEnter = lastFrame(); @@ -46,11 +49,12 @@ describe("TUIChat - User Input Tests", () => { testBothModes( "handles special characters in input without crashing", - (mode) => { + async (mode) => { const { lastFrame, stdin } = renderInMode(mode); // Try typing various special characters stdin.write("!@#$%^&*()"); + await waitForNextRender(); const frame = lastFrame(); @@ -58,8 +62,9 @@ describe("TUIChat - User Input Tests", () => { expect(frame).toBeDefined(); expect(frame).not.toBe(""); - // UI should still be functional - expect(frame).toContain("Ask anything"); + // UI should still be functional and show the typed special characters + // Note: "Ask anything" placeholder is replaced when text is typed + expect(frame).toContain("!@#$%^&*()"); // Mode-specific UI elements if (mode === "remote") { diff --git a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx index 9e67826c5..1f63f3814 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -1,4 +1,5 @@ import { renderInMode, testBothModes } from "./TUIChat.dualModeHelper.js"; +import { waitForNextRender } from "./TUIChat.testHelper.js"; describe("TUIChat - Slash Commands Tests", () => { testBothModes("shows slash when user types /", async (mode) => { @@ -6,9 +7,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type / to trigger slash command stdin.write("/"); - - // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frame = lastFrame(); @@ -29,9 +28,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /exi to trigger slash command filtering stdin.write("/exi"); - - // Wait a bit for the UI to update (allow extra time in both modes) - await new Promise((resolve) => setTimeout(resolve, 600)); + await waitForNextRender(); const frame = lastFrame(); @@ -52,12 +49,10 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /exi and then tab stdin.write("/exi"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); stdin.write("\t"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterTab = lastFrame(); @@ -80,8 +75,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type just / stdin.write("/"); - - await new Promise((resolve) => setTimeout(resolve, 600)); + await waitForNextRender(); const frame = lastFrame(); @@ -113,8 +107,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type a complete command name first stdin.write("/title"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterCommand = lastFrame(); if (mode === "remote") { @@ -127,8 +120,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Now add a space and arguments stdin.write(" My Session Title"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameAfterArgs = lastFrame(); @@ -151,8 +143,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type a complete command with arguments stdin.write("/title Test Session"); - - await new Promise((resolve) => setTimeout(resolve, 200)); + await waitForNextRender(); const frameBeforeEnter = lastFrame(); expect(frameBeforeEnter).toContain("/title"); @@ -160,8 +151,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Press Enter - this should execute the command, not try to autocomplete stdin.write("\r"); - - await new Promise((resolve) => setTimeout(resolve, 300)); + await waitForNextRender(); const frameAfterEnter = lastFrame(); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts b/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts index e450b809a..37ebb5c3e 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts +++ b/extensions/cli/src/ui/__tests__/TUIChat.testHelper.ts @@ -422,6 +422,20 @@ export async function sendMessage( await new Promise((resolve) => setTimeout(resolve, waitTime)); } +/** + * Helper to wait for next render cycle to complete + * Use this after stdin.write() to ensure at least one render has occurred + * This prevents flaky tests caused by calling lastFrame() before React renders + */ +export async function waitForNextRender(): Promise { + // Wait for multiple ticks to ensure render completes + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + // Add a delay to allow Ink terminal UI to render + // CI environments are slower, so we need a longer delay + await new Promise((resolve) => setTimeout(resolve, 500)); +} + /** * Helper to check if UI shows remote mode indicators */ From b62564cce47386365530782a3ac45a85f08ca347 Mon Sep 17 00:00:00 2001 From: "continue[bot]" <230936708+continue[bot]@users.noreply.github.com> Date: Wed, 8 Oct 2025 07:27:19 -0700 Subject: [PATCH 85/91] Add 'Explore MCP Servers' option to /mcp slash command (#8123) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Added '🔍 Explore MCP Servers' option at the bottom of the MCP selector menu - Opens https://hub.continue.dev/?type=mcpServers in default browser - Uses existing 'open' package dependency Generated with [Continue](https://continue.dev) Co-authored-by: Continue Agent Co-authored-by: Continue Co-authored-by: Username --- extensions/cli/src/ui/MCPSelector.tsx | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index 99523c63c..e974c6f8c 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -117,6 +117,13 @@ export const MCPSelector: React.FC = ({ onCancel }) => { { label: "⏹️ Stop all servers", value: "stop-all" }, ); } + + // Add "Explore MCP Servers" option at the bottom + options.push({ + label: "🔍 Explore MCP Servers", + value: "explore-mcp-servers", + }); + return options; }; @@ -280,6 +287,12 @@ export const MCPSelector: React.FC = ({ onCancel }) => { await mcpService.shutdownConnections(); setMessage("All servers stopped"); break; + case "explore-mcp-servers": + // Open the MCP servers hub in the default browser + const open = (await import("open")).default; + await open("https://hub.continue.dev/?type=mcpServers"); + setMessage("Opened MCP servers hub in browser"); + break; case "back": onCancel(); return; From ad8a597445f86eb8c5e3ce2ff37b9b6dc9709334 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 8 Oct 2025 07:27:45 -0700 Subject: [PATCH 86/91] Revise build steps in BUILD.md (#8130) Updated build steps to include building local packages before installation. --- extensions/cli/BUILD.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extensions/cli/BUILD.md b/extensions/cli/BUILD.md index 553660f94..ae805a800 100644 --- a/extensions/cli/BUILD.md +++ b/extensions/cli/BUILD.md @@ -6,8 +6,9 @@ The Continue CLI uses esbuild to bundle the application along with local package ## Build Steps -1. **Install dependencies**: `npm install` -2. **Build**: `npm run build` +1. **Build packages**: `cd ../../ && node ./scripts/build-packages.js` +2. **Install dependencies**: `npm install` +3. **Build**: `npm run build` - This first builds the local packages - Then bundles everything with esbuild From 80e99a5593fa62228c93ab46001763d62d68c7c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=AA=20T=E1=BA=A5n=20L=E1=BB=99c?= <26348718+letanloc1998@users.noreply.github.com> Date: Wed, 8 Oct 2025 21:28:38 +0700 Subject: [PATCH 87/91] Fix wrong document about Force Legacy Completions Endpoint (#8133) --- docs/customize/model-providers/top-level/openai.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/customize/model-providers/top-level/openai.mdx b/docs/customize/model-providers/top-level/openai.mdx index 9537ac133..3249e27c9 100644 --- a/docs/customize/model-providers/top-level/openai.mdx +++ b/docs/customize/model-providers/top-level/openai.mdx @@ -90,7 +90,7 @@ If you are using an OpenAI API compatible providers, you can change the `apiBase ### How to Force Legacy Completions Endpoint Usage -To force usage of `chat/completions` instead of `completions` endpoint you can set: +To force usage of `completions` instead of `chat/completions` endpoint you can set: From eba67ef1fb8fd931230bee5deda95f1e5c00d9ab Mon Sep 17 00:00:00 2001 From: "continue[bot]" <230936708+continue[bot]@users.noreply.github.com> Date: Wed, 8 Oct 2025 08:17:47 -0700 Subject: [PATCH 88/91] Add organization name display to CLI intro screen (#8041) - Add organizationName prop to IntroMessage component - Display 'Org: [ORG_NAME]' above 'Agent: [AGENT_NAME]' - Fetch organization name from auth service in TUIChat - Add useOrganizationName hook to resolve org ID to name - Pass organizationName through StaticChatContent - Update tests to verify org display behavior Generated with [Continue](https://continue.dev) Co-authored-by: Continue Agent Co-authored-by: Continue Co-authored-by: Nate --- extensions/cli/src/ui/IntroMessage.test.tsx | 15 +++++++ extensions/cli/src/ui/IntroMessage.tsx | 9 ++++ extensions/cli/src/ui/TUIChat.tsx | 43 +++++++++++++++++++ .../src/ui/components/StaticChatContent.tsx | 4 ++ 4 files changed, 71 insertions(+) diff --git a/extensions/cli/src/ui/IntroMessage.test.tsx b/extensions/cli/src/ui/IntroMessage.test.tsx index a21d6f79c..6f024b96e 100644 --- a/extensions/cli/src/ui/IntroMessage.test.tsx +++ b/extensions/cli/src/ui/IntroMessage.test.tsx @@ -81,4 +81,19 @@ describe("IntroMessage", () => { expect(lastFrame()).toContain("Model:"); expect(lastFrame()).toContain("Loading..."); }); + + it("renders organization name when provided", () => { + const { lastFrame } = render( + , + ); + + expect(lastFrame()).toContain("Org:"); + expect(lastFrame()).toContain("Test Organization"); + }); + + it("does not render organization section when not provided", () => { + const { lastFrame } = render(); + + expect(lastFrame()).not.toContain("Org:"); + }); }); diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index e26448479..139db3e8b 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -13,6 +13,7 @@ interface IntroMessageProps { config?: AssistantUnrolled; model?: ModelConfig; mcpService?: MCPService; + organizationName?: string; } // Helper function to extract rule names @@ -26,6 +27,7 @@ const IntroMessage: React.FC = ({ config, model, mcpService, + organizationName, }) => { // Get MCP prompts directly (not memoized since they can change after first render) const mcpPrompts = mcpService?.getState().prompts ?? []; @@ -98,6 +100,13 @@ const IntroMessage: React.FC = ({ {/* Tips Display - shown randomly 1 in 5 times */} {showTip && } + {/* Organization name */} + {organizationName && ( + + Org: {organizationName} + + )} + {/* Agent name */} {config && ( diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 555c32829..aea25bc19 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -9,6 +9,7 @@ import React, { import { ToolPermissionServiceState } from "src/services/ToolPermissionService.js"; +import { listUserOrganizations } from "../auth/workos.js"; import { useServices } from "../hooks/useService.js"; import { ApiClientServiceState, @@ -110,6 +111,44 @@ function useTUIChatServices(remoteUrl?: string) { return { services, allServicesReady, isRemoteMode }; } +// Custom hook to fetch organization name +function useOrganizationName(organizationId?: string): string | undefined { + const [organizationName, setOrganizationName] = useState( + undefined, + ); + + useEffect(() => { + if (!organizationId) { + setOrganizationName(undefined); + return; + } + + let isMounted = true; + + async function fetchOrgName() { + try { + const orgs = await listUserOrganizations(); + if (!isMounted) return; + + const org = orgs?.find((o) => o.id === organizationId); + if (org) { + setOrganizationName(org.name); + } + } catch (error) { + logger.debug("Failed to fetch organization name", { error }); + } + } + + fetchOrgName(); + + return () => { + isMounted = false; + }; + }, [organizationId]); + + return organizationName; +} + // Custom hook for chat handlers function useChatHandlers( setShowIntroMessage: (show: boolean) => void, @@ -298,6 +337,9 @@ const TUIChat: React.FC = ({ // State for image in clipboard status const [hasImageInClipboard, setHasImageInClipboard] = useState(false); + // Fetch organization name based on auth state + const organizationName = useOrganizationName(services.auth?.organizationId); + return ( {/* Chat history - takes up all available space above input */} @@ -320,6 +362,7 @@ const TUIChat: React.FC = ({ config={services.config?.config || undefined} model={services.model?.model || undefined} mcpService={services.mcp?.mcpService || undefined} + organizationName={organizationName} chatHistory={chatHistory} queuedMessages={queuedMessages} renderMessage={renderMessage} diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 5cb553762..09f9d8bf5 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -14,6 +14,7 @@ interface StaticChatContentProps { config?: AssistantUnrolled; model?: ModelConfig; mcpService?: MCPService; + organizationName?: string; chatHistory: ChatHistoryItem[]; queuedMessages?: QueuedMessage[]; renderMessage: ( @@ -29,6 +30,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, + organizationName, chatHistory, queuedMessages = [], renderMessage, @@ -96,6 +98,7 @@ export const StaticChatContent: React.FC = ({ config={config} model={model} mcpService={mcpService} + organizationName={organizationName} />, ); } @@ -129,6 +132,7 @@ export const StaticChatContent: React.FC = ({ config, model, mcpService, + organizationName, processedChatHistory, renderMessage, ]); From c7b8e0f29e7adfb7726a17cc06c2e0e0927f417f Mon Sep 17 00:00:00 2001 From: Aditya Mitra <61635505+uinstinct@users.noreply.github.com> Date: Wed, 8 Oct 2025 20:53:21 +0530 Subject: [PATCH 89/91] feat(cli): mcp oauth using mcp-remote (#8143) * feat(cli): mcp oauth using mcp-remote * Update MCPService.ts --------- Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com> --- extensions/cli/src/services/MCPService.ts | 49 ++++++++++++++++++----- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index 069171fef..c4885f120 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -1,6 +1,9 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Client } from "@modelcontextprotocol/sdk/client/index.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 { @@ -21,6 +24,14 @@ import { SERVICE_NAMES, } from "./types.js"; +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")) + ); +} + interface ServerConnection extends MCPConnectionInfo { client: Client | null; } @@ -366,15 +377,29 @@ export class MCPService url: serverConfig.url, }); - if (serverConfig.type === "sse") { - const transport = this.constructSseTransport(serverConfig); - await client.connect(transport, {}); - } else if (serverConfig.type === "streamable-http") { - const transport = this.constructHttpTransport(serverConfig); - await client.connect(transport, {}); - } else if (serverConfig.type) { - throw new Error(`Unsupported transport type: ${serverConfig.type}`); - } else { + try { + if (serverConfig.type === "sse") { + const transport = this.constructSseTransport(serverConfig); + await client.connect(transport, {}); + } else if (serverConfig.type === "streamable-http") { + const transport = this.constructHttpTransport(serverConfig); + await client.connect(transport, {}); + } + } catch (error: unknown) { + // on authorization error, use "mcp-remote" with stdio transport to connect + if (is401Error(error)) { + const transport = this.constructStdioTransport({ + name: serverConfig.name, + command: "npx", + args: ["-y", "mcp-remote", serverConfig.url], + }); + await client.connect(transport, {}); + } else { + throw error; + } + } + + if (typeof serverConfig.type === "undefined") { try { const transport = this.constructHttpTransport(serverConfig); await client.connect(transport, {}); @@ -394,6 +419,10 @@ export class MCPService ); } } + } else if ( + !["streamable-http", "sse", "stdio"].includes(serverConfig.type) + ) { + throw new Error(`Unsupported transport type: ${serverConfig.type}`); } } From 9164448c73cf746031203d75a27b5db0ab2bc42c Mon Sep 17 00:00:00 2001 From: "continue[bot]" <230936708+continue[bot]@users.noreply.github.com> Date: Wed, 8 Oct 2025 08:33:30 -0700 Subject: [PATCH 90/91] Add apiKey field to mcpServers block schema for Bearer token auth (#8120) Add apiKey field to mcpServers schema and implement Bearer token auth - Add apiKey field to sseOrHttpMcpServerSchema in packages/config-yaml - Update MCPConnection.ts to merge apiKey as Bearer token in Authorization header - Update CLI MCPService to merge apiKey as Bearer token in Authorization header - Add apiKey to InternalSseMcpOptions and InternalStreamableHttpMcpOptions types - Update yamlToContinueConfig converter to pass through apiKey field Fixes CON-4281 Generated with [Continue](https://continue.dev) Co-authored-by: Continue Agent Co-authored-by: Continue Co-authored-by: nate --- core/config/yaml/yamlToContinueConfig.ts | 3 ++- core/context/mcp/MCPConnection.ts | 18 ++++++++++++--- core/index.d.ts | 2 ++ extensions/cli/src/services/MCPService.ts | 22 ++++++++++++++++--- packages/config-yaml/src/schemas/mcp/index.ts | 1 + 5 files changed, 39 insertions(+), 7 deletions(-) diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts index 7d6bd810e..d639e4515 100644 --- a/core/config/yaml/yamlToContinueConfig.ts +++ b/core/config/yaml/yamlToContinueConfig.ts @@ -58,13 +58,14 @@ export function convertYamlMcpConfigToInternalMcpOptions( return stdioOptions; } // HTTP/SSE - const { type, url, requestOptions } = config; + const { type, url, apiKey, requestOptions } = config; const httpSseConfig: | InternalStreamableHttpMcpOptions | InternalSseMcpOptions = { ...shared, type, url, + apiKey, requestOptions: mergeConfigYamlRequestOptions( requestOptions, globalRequestOptions, diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 9214375c8..4090e92c5 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -468,6 +468,12 @@ class MCPConnection { ? new HttpsAgent({ rejectUnauthorized: false }) : undefined; + // Merge apiKey into headers if provided + const headers = { + ...options.requestOptions?.headers, + ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }), + }; + return new SSEClientTransport(new URL(options.url), { eventSourceInit: { fetch: (input, init) => @@ -475,13 +481,13 @@ class MCPConnection { ...init, headers: { ...init?.headers, - ...options.requestOptions?.headers, + ...headers, }, ...(sseAgent && { agent: sseAgent }), }), }, requestInit: { - headers: options.requestOptions?.headers, + headers, ...(sseAgent && { agent: sseAgent }), }, }); @@ -496,9 +502,15 @@ class MCPConnection { ? new HttpsAgent({ rejectUnauthorized: false }) : undefined; + // Merge apiKey into headers if provided + const headers = { + ...requestOptions?.headers, + ...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }), + }; + return new StreamableHTTPClientTransport(new URL(url), { requestInit: { - headers: requestOptions?.headers, + headers, ...(streamableAgent && { agent: streamableAgent }), }, }); diff --git a/core/index.d.ts b/core/index.d.ts index bd21d4fe8..fb59d97bd 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1350,11 +1350,13 @@ export type InternalStdioMcpOptions = BaseInternalMCPOptions & { export type InternalStreamableHttpMcpOptions = BaseInternalMCPOptions & { type?: "streamable-http"; url: string; + apiKey?: string; }; export type InternalSseMcpOptions = BaseInternalMCPOptions & { type?: "sse"; url: string; + apiKey?: string; }; export type InternalWebsocketMcpOptions = BaseInternalMCPOptions & { diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index c4885f120..08190e267 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -432,6 +432,14 @@ export class MCPService private constructSseTransport( serverConfig: SseMcpServer, ): SSEClientTransport { + // Merge apiKey into headers if provided + const headers = { + ...serverConfig.requestOptions?.headers, + ...(serverConfig.apiKey && { + Authorization: `Bearer ${serverConfig.apiKey}`, + }), + }; + return new SSEClientTransport(new URL(serverConfig.url), { eventSourceInit: { fetch: (input, init) => @@ -439,18 +447,26 @@ export class MCPService ...init, headers: { ...init?.headers, - ...serverConfig.requestOptions?.headers, + ...headers, }, }), }, - requestInit: { headers: serverConfig.requestOptions?.headers }, + requestInit: { headers }, }); } private constructHttpTransport( serverConfig: HttpMcpServer, ): StreamableHTTPClientTransport { + // Merge apiKey into headers if provided + const headers = { + ...serverConfig.requestOptions?.headers, + ...(serverConfig.apiKey && { + Authorization: `Bearer ${serverConfig.apiKey}`, + }), + }; + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { - requestInit: { headers: serverConfig.requestOptions?.headers }, + requestInit: { headers }, }); } private constructStdioTransport( diff --git a/packages/config-yaml/src/schemas/mcp/index.ts b/packages/config-yaml/src/schemas/mcp/index.ts index 0f1778882..b0ede8778 100644 --- a/packages/config-yaml/src/schemas/mcp/index.ts +++ b/packages/config-yaml/src/schemas/mcp/index.ts @@ -21,6 +21,7 @@ export type StdioMcpServer = z.infer; const sseOrHttpMcpServerSchema = baseMcpServerSchema.extend({ url: z.string(), // .url() fails with e.g. IP addresses type: z.union([z.literal("sse"), z.literal("streamable-http")]).optional(), + apiKey: z.string().optional(), requestOptions: requestOptionsSchema.optional(), }); export type SseMcpServer = z.infer; From 7b17637763530100923298d4e12907385ccf300e Mon Sep 17 00:00:00 2001 From: "continue[bot]" <230936708+continue[bot]@users.noreply.github.com> Date: Wed, 8 Oct 2025 09:49:36 -0700 Subject: [PATCH 91/91] Allow --mcp flag to accept URLs for streamable-http servers (#8119) * Allow --mcp flag to accept URLs for streamable-http servers When a URL starting with http:// or https:// is passed to the --mcp flag, it will now automatically be configured as a streamable-http MCP server connection instead of trying to load it from the hub. This allows users to run: cn --mcp https://docs.continue.dev/mcp The URL will be parsed and configured with: - type: streamable-http - url: the provided URL - name: hostname from the URL Fixes CON-4285 Generated with [Continue](https://continue.dev) Co-authored-by: Username * fix: tests --------- Co-authored-by: Continue Agent Co-authored-by: Username Co-authored-by: Nate --- extensions/cli/src/configEnhancer.test.ts | 75 +++++++++++++++++-- extensions/cli/src/configEnhancer.ts | 23 +++++- .../src/services/workflow-integration.test.ts | 41 +++++++--- 3 files changed, 122 insertions(+), 17 deletions(-) diff --git a/extensions/cli/src/configEnhancer.test.ts b/extensions/cli/src/configEnhancer.test.ts index 3aaea15b4..4b37951d5 100644 --- a/extensions/cli/src/configEnhancer.test.ts +++ b/extensions/cli/src/configEnhancer.test.ts @@ -196,11 +196,12 @@ describe("ConfigEnhancer", () => { }); it("should prepend MCPs from --mcp flag", async () => { - // Mock loadPackagesFromHub to return test MCPs - const { loadPackagesFromHub } = await import("./hubLoader.js"); - (loadPackagesFromHub as any).mockResolvedValueOnce([ - { name: "New-MCP", command: "new-mcp" }, - ]); + // Mock loadPackageFromHub to return test MCP (singular call for each MCP) + const { loadPackageFromHub } = await import("./hubLoader.js"); + (loadPackageFromHub as any).mockResolvedValueOnce({ + name: "New-MCP", + command: "new-mcp", + }); // Set up existing MCPs in config mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; @@ -223,6 +224,70 @@ describe("ConfigEnhancer", () => { }); }); + it("should handle URLs in --mcp flag as streamable-http servers", async () => { + // Set up existing MCPs in config + mockConfig.mcpServers = [{ name: "Existing-MCP", command: "existing-mcp" }]; + + const options: BaseCommandOptions = { + mcp: ["https://docs.continue.dev/mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + // URL should be converted to streamable-http MCP configuration + expect(config.mcpServers).toHaveLength(2); + expect(config.mcpServers?.[0]).toEqual({ + name: "docs.continue.dev", + type: "streamable-http", + url: "https://docs.continue.dev/mcp", + }); + expect(config.mcpServers?.[1]).toEqual({ + name: "Existing-MCP", + command: "existing-mcp", + }); + }); + + it("should handle mix of URLs and hub slugs in --mcp flag", async () => { + // Mock loadPackageFromHub to return test MCP for hub slug + const { loadPackageFromHub } = await import("./hubLoader.js"); + (loadPackageFromHub as any).mockResolvedValueOnce({ + name: "Hub-MCP", + command: "hub-mcp", + }); + + const options: BaseCommandOptions = { + mcp: ["https://example.com/mcp", "test/hub-mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.mcpServers).toHaveLength(2); + expect(config.mcpServers?.[0]).toEqual({ + name: "example.com", + type: "streamable-http", + url: "https://example.com/mcp", + }); + expect(config.mcpServers?.[1]).toEqual({ + name: "Hub-MCP", + command: "hub-mcp", + }); + }); + + it("should handle http:// URLs in --mcp flag", async () => { + const options: BaseCommandOptions = { + mcp: ["http://localhost:8080/mcp"], + }; + + const config = await enhancer.enhanceConfig(mockConfig, options); + + expect(config.mcpServers).toHaveLength(1); + expect(config.mcpServers?.[0]).toEqual({ + name: "localhost", + type: "streamable-http", + url: "http://localhost:8080/mcp", + }); + }); + it("should handle workflow integration gracefully when no workflow", async () => { // The mocked service container returns null workflow state const options: BaseCommandOptions = { diff --git a/extensions/cli/src/configEnhancer.ts b/extensions/cli/src/configEnhancer.ts index 49e464f2f..b299e871b 100644 --- a/extensions/cli/src/configEnhancer.ts +++ b/extensions/cli/src/configEnhancer.ts @@ -171,7 +171,28 @@ export class ConfigEnhancer { config: AssistantUnrolled, mcps: string[], ): Promise { - const processedMcps = await loadPackagesFromHub(mcps, mcpProcessor); + const processedMcps: any[] = []; + + // Process each MCP spec - check if it's a URL or hub slug + for (const mcpSpec of mcps) { + try { + // Check if it's a URL (starts with http:// or https://) + if (mcpSpec.startsWith("http://") || mcpSpec.startsWith("https://")) { + // Create a streamable-http MCP configuration + processedMcps.push({ + name: new URL(mcpSpec).hostname, + type: "streamable-http", + url: mcpSpec, + }); + } else { + // Otherwise, treat it as a hub slug + const hubMcp = await loadPackageFromHub(mcpSpec, mcpProcessor); + processedMcps.push(hubMcp); + } + } catch (error: any) { + logger.warn(`Failed to load MCP "${mcpSpec}": ${error.message}`); + } + } // Clone the config to avoid mutating the original const modifiedConfig = { ...config }; diff --git a/extensions/cli/src/services/workflow-integration.test.ts b/extensions/cli/src/services/workflow-integration.test.ts index 7c688d89c..6d68563af 100644 --- a/extensions/cli/src/services/workflow-integration.test.ts +++ b/extensions/cli/src/services/workflow-integration.test.ts @@ -554,11 +554,19 @@ describe("Workflow Integration Tests", () => { tools: "owner/mcp1, another/mcp2:specific_tool", }; - mockLoadPackageFromHub.mockResolvedValue(workflowWithTools); - mockLoadPackagesFromHub.mockResolvedValue([ - { name: "mcp1" }, - { name: "mcp2" }, - ]); + // Clear the default mock and setup specific mocks + mockLoadPackageFromHub.mockReset(); + // First call loads the workflow file + mockLoadPackageFromHub.mockResolvedValueOnce(workflowWithTools); + // Second call loads the workflow model + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + // Third call loads mcp1 + mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); + // Fourth call loads mcp2 + mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp2" }); await workflowService.initialize("owner/workflow"); @@ -573,6 +581,7 @@ describe("Workflow Integration Tests", () => { ); expect(enhancedConfig.mcpServers).toHaveLength(3); + // MCPs are prepended in the order they are loaded expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp2" }); expect(enhancedConfig.mcpServers?.[2]).toEqual({ name: "existing-mcp" }); @@ -584,7 +593,8 @@ describe("Workflow Integration Tests", () => { tools: undefined, }; - mockLoadPackageFromHub.mockResolvedValue(workflowWithoutTools); + mockLoadPackageFromHub.mockReset(); + mockLoadPackageFromHub.mockResolvedValueOnce(workflowWithoutTools); await workflowService.initialize("owner/workflow"); const baseConfig = { @@ -607,13 +617,22 @@ describe("Workflow Integration Tests", () => { tools: "owner/mcp1, owner/mcp1:tool1, owner/mcp1:tool2", }; - mockLoadPackageFromHub.mockResolvedValue(workflowWithDuplicateTools); - mockLoadPackagesFromHub.mockResolvedValue([{ name: "mcp1" }]); + // Clear the default mock and setup specific mocks + mockLoadPackageFromHub.mockReset(); + // First call loads the workflow file + mockLoadPackageFromHub.mockResolvedValueOnce(workflowWithDuplicateTools); + // Second call loads the workflow model + mockLoadPackageFromHub.mockResolvedValueOnce({ + name: "gpt-4-workflow", + provider: "openai", + }); + // Third call: The parseWorkflowTools will extract only unique MCP servers, so only one loadPackageFromHub call + mockLoadPackageFromHub.mockResolvedValueOnce({ name: "mcp1" }); await workflowService.initialize("owner/workflow"); const baseConfig = { - mcpServers: [{ name: "mcp1" }], // Already exists + mcpServers: [{ name: "existing-mcp" }], // Changed to avoid confusion }; const enhancedConfig = await configEnhancer.enhanceConfig( @@ -622,10 +641,10 @@ describe("Workflow Integration Tests", () => { workflowService.getState(), ); - // Should not deduplicate since we simplified the logic + // parseWorkflowTools deduplicates, so we only get mcp1 once expect(enhancedConfig.mcpServers).toHaveLength(2); expect(enhancedConfig.mcpServers?.[0]).toEqual({ name: "mcp1" }); - expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "mcp1" }); + expect(enhancedConfig.mcpServers?.[1]).toEqual({ name: "existing-mcp" }); }); }); });