Merge branch 'main' of https://github.com/continuedev/continue into dallin/workflow-files
This commit is contained in:
commit
598b7ab0c3
119 changed files with 3538 additions and 1422 deletions
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
|
|
@ -23,6 +23,7 @@
|
|||
"binary/build/**": true,
|
||||
"binary/out/**": true,
|
||||
"binary/tmp/**": true,
|
||||
"core/dist/**": true,
|
||||
"core/edit/lazy/test-examples/**": true,
|
||||
"core/llm/llamaTokenizer.js": true,
|
||||
"core/llm/llamaTokenizer.mjs": true,
|
||||
|
|
|
|||
118
core/autocomplete/postprocessing/index.test.ts
Normal file
118
core/autocomplete/postprocessing/index.test.ts
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { postprocessCompletion } from "./index";
|
||||
|
||||
describe("postprocessCompletion - removeBackticks", () => {
|
||||
const mockLLM = { model: "test-model" } as any;
|
||||
|
||||
it("should remove first line starting with ``` and last line that is ```", () => {
|
||||
const completion =
|
||||
"```typescript\nfunction hello() {\n return 'world';\n}\n```";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("function hello() {\n return 'world';\n}");
|
||||
});
|
||||
|
||||
it("should remove only first line if it starts with ```", () => {
|
||||
const completion = "```javascript\nconst x = 5;\nconsole.log(x);";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("const x = 5;\nconsole.log(x);");
|
||||
});
|
||||
|
||||
it("should remove only last line if it is ```", () => {
|
||||
const completion = "const y = 10;\nconsole.log(y);\n```";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("const y = 10;\nconsole.log(y);");
|
||||
});
|
||||
|
||||
it("should not modify completion without backticks", () => {
|
||||
const completion = "function test() {\n return true;\n}";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("function test() {\n return true;\n}");
|
||||
});
|
||||
|
||||
it("should handle completion with backticks in the middle", () => {
|
||||
const completion = "const str = `template ${literal}`;\nconsole.log(str);";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe(
|
||||
"const str = `template ${literal}`;\nconsole.log(str);",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle first line with leading whitespace before ```", () => {
|
||||
const completion = " ```python\ndef hello():\n pass\n```";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("def hello():\n pass");
|
||||
});
|
||||
|
||||
it("should handle last line with whitespace around ```", () => {
|
||||
const completion = "```\ncode here\n ``` ";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("code here");
|
||||
});
|
||||
|
||||
it("should handle single line completion", () => {
|
||||
const completion = "const x = 5;";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("const x = 5;");
|
||||
});
|
||||
|
||||
it("should handle empty completion", () => {
|
||||
const completion = "";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not remove ``` if it's not on its own line at the end", () => {
|
||||
const completion = "```typescript\nconst x = 5; // end```";
|
||||
const result = postprocessCompletion({
|
||||
completion,
|
||||
llm: mockLLM,
|
||||
prefix: "",
|
||||
suffix: "",
|
||||
});
|
||||
expect(result).toBe("const x = 5; // end```");
|
||||
});
|
||||
});
|
||||
|
|
@ -52,6 +52,38 @@ function isBlank(completion: string): boolean {
|
|||
return completion.trim().length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes markdown code block delimiters from completion.
|
||||
* Removes the first line if it starts with "```" and the last line if it is exactly "```".
|
||||
*/
|
||||
function removeBackticks(completion: string): string {
|
||||
const lines = completion.split("\n");
|
||||
|
||||
if (lines.length === 0) {
|
||||
return completion;
|
||||
}
|
||||
|
||||
let startIdx = 0;
|
||||
let endIdx = lines.length;
|
||||
|
||||
// Remove first line if it starts with ```
|
||||
if (lines[0].trimStart().startsWith("```")) {
|
||||
startIdx = 1;
|
||||
}
|
||||
|
||||
// Remove last line if it is exactly ```
|
||||
if (lines.length > startIdx && lines[lines.length - 1].trim() === "```") {
|
||||
endIdx = lines.length - 1;
|
||||
}
|
||||
|
||||
// If we removed lines, return the modified completion
|
||||
if (startIdx > 0 || endIdx < lines.length) {
|
||||
return lines.slice(startIdx, endIdx).join("\n");
|
||||
}
|
||||
|
||||
return completion;
|
||||
}
|
||||
|
||||
export function postprocessCompletion({
|
||||
completion,
|
||||
llm,
|
||||
|
|
@ -156,5 +188,8 @@ export function postprocessCompletion({
|
|||
completion = completion.slice(1);
|
||||
}
|
||||
|
||||
// Remove markdown code block delimiters
|
||||
completion = removeBackticks(completion);
|
||||
|
||||
return completion;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,6 @@ export function convertCustomCommandToSlashCommand(
|
|||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "json-custom-command",
|
||||
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
|
||||
sourceFile: customCommand.sourceFile,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,6 @@ export function convertPromptBlockToSlashCommand(
|
|||
description: prompt.description ?? "",
|
||||
prompt: prompt.prompt,
|
||||
source: "yaml-prompt-block",
|
||||
promptFile: prompt.sourceFile, // Align with the sourceFile property
|
||||
sourceFile: prompt.sourceFile,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ export function slashCommandFromPromptFile(
|
|||
description,
|
||||
prompt,
|
||||
source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
|
||||
promptFile: path,
|
||||
sourceFile: path,
|
||||
overrideSystemMessage: systemMessage,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ export function convertRuleBlockToSlashCommand(
|
|||
description: rule.description ?? "",
|
||||
prompt: rule.rule,
|
||||
source: "invokable-rule",
|
||||
promptFile: rule.ruleFile,
|
||||
sourceFile: rule.sourceFile,
|
||||
slug: rule.slug,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ describe("convertRuleBlockToSlashCommand", () => {
|
|||
rule: "Review this code for best practices",
|
||||
description: "Performs a code review",
|
||||
source: "rules-block",
|
||||
ruleFile: "/path/to/rules.yaml",
|
||||
sourceFile: "file:///path/to/rules.yaml",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
|
|
@ -20,7 +20,7 @@ describe("convertRuleBlockToSlashCommand", () => {
|
|||
description: "Performs a code review",
|
||||
prompt: "Review this code for best practices",
|
||||
source: "invokable-rule",
|
||||
promptFile: "/path/to/rules.yaml",
|
||||
sourceFile: "file:///path/to/rules.yaml",
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export async function getWorkspaceContinueRuleDotFiles(ide: IDE) {
|
|||
const content = await ide.readFile(dotFile);
|
||||
rules.push({
|
||||
rule: content,
|
||||
ruleFile: dotFile,
|
||||
sourceFile: dotFile,
|
||||
source: ".continuerules",
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,13 +12,12 @@ import { getGlobalFolderWithName } from "../util/paths";
|
|||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { getUriPathBasename, joinPathsToUri } from "../util/uri";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./getWorkspaceContinueRuleDotFiles";
|
||||
import { SUPPORTED_AGENT_FILES } from "./markdown";
|
||||
export function isContinueConfigRelatedUri(uri: string): boolean {
|
||||
return (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith("AGENTS.md") ||
|
||||
uri.endsWith("AGENT.md") ||
|
||||
uri.endsWith("CLAUDE.md") ||
|
||||
!!SUPPORTED_AGENT_FILES.find((file) => uri.endsWith(`/${file}`)) ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") &&
|
||||
(uri.endsWith(".yaml") ||
|
||||
|
|
|
|||
|
|
@ -26,20 +26,30 @@ export class CodebaseRulesCache {
|
|||
}
|
||||
async update(ide: IDE, uri: string) {
|
||||
const content = await ide.readFile(uri);
|
||||
const { relativePathOrBasename } = findUriInDirs(
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const { relativePathOrBasename, foundInDir } = findUriInDirs(
|
||||
uri,
|
||||
await ide.getWorkspaceDirs(),
|
||||
workspaceDirs,
|
||||
);
|
||||
if (!foundInDir) {
|
||||
console.warn(
|
||||
`Failed to load codebase rule ${uri}: URI not found in workspace`,
|
||||
);
|
||||
}
|
||||
const rule = markdownToRule(
|
||||
content,
|
||||
{
|
||||
uriType: "file",
|
||||
fileUri: uri,
|
||||
},
|
||||
relativePathOrBasename,
|
||||
);
|
||||
const rule = markdownToRule(content, {
|
||||
uriType: "file",
|
||||
fileUri: relativePathOrBasename,
|
||||
});
|
||||
const ruleWithSource: RuleWithSource = {
|
||||
...rule,
|
||||
source: "colocated-markdown",
|
||||
ruleFile: uri,
|
||||
sourceFile: uri,
|
||||
};
|
||||
const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri);
|
||||
const matchIdx = this.rules.findIndex((r) => r.sourceFile === uri);
|
||||
if (matchIdx === -1) {
|
||||
this.rules.push(ruleWithSource);
|
||||
} else {
|
||||
|
|
@ -47,7 +57,7 @@ export class CodebaseRulesCache {
|
|||
}
|
||||
}
|
||||
remove(uri: string) {
|
||||
this.rules = this.rules.filter((r) => r.ruleFile !== uri);
|
||||
this.rules = this.rules.filter((r) => r.sourceFile !== uri);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -75,20 +85,32 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
|
|||
for (const filePath of rulesMdFiles) {
|
||||
try {
|
||||
const content = await ide.readFile(filePath);
|
||||
const { relativePathOrBasename } = findUriInDirs(
|
||||
const { relativePathOrBasename, foundInDir, uri } = findUriInDirs(
|
||||
filePath,
|
||||
await ide.getWorkspaceDirs(),
|
||||
);
|
||||
const rule = markdownToRule(content, {
|
||||
uriType: "file",
|
||||
fileUri: relativePathOrBasename,
|
||||
});
|
||||
if (foundInDir) {
|
||||
const lastSlashIndex = relativePathOrBasename.lastIndexOf("/");
|
||||
const parentDir = relativePathOrBasename.substring(0, lastSlashIndex);
|
||||
const rule = markdownToRule(
|
||||
content,
|
||||
{
|
||||
uriType: "file",
|
||||
fileUri: uri,
|
||||
},
|
||||
parentDir,
|
||||
);
|
||||
|
||||
rules.push({
|
||||
...rule,
|
||||
source: "colocated-markdown",
|
||||
ruleFile: filePath,
|
||||
});
|
||||
rules.push({
|
||||
...rule,
|
||||
source: "colocated-markdown",
|
||||
sourceFile: filePath,
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Failed to load codebase rule ${uri}: URI not found in workspace dirs`,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { markdownToRule } from "@continuedev/config-yaml";
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { IDE } from "../..";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import { findUriInDirs, getUriPathBasename } from "../../util/uri";
|
||||
import { loadCodebaseRules } from "./loadCodebaseRules";
|
||||
|
||||
// Mock dependencies
|
||||
|
|
@ -14,14 +13,10 @@ vi.mock("@continuedev/config-yaml", () => ({
|
|||
markdownToRule: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../util/uri", () => ({
|
||||
findUriInDirs: vi.fn(),
|
||||
getUriPathBasename: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("loadCodebaseRules", () => {
|
||||
// Mock IDE with properly typed mock functions
|
||||
const mockIde = {
|
||||
fileExists: vi.fn().mockImplementation(() => true),
|
||||
readFile: vi.fn() as unknown as IDE["readFile"] & {
|
||||
mockImplementation: Function;
|
||||
},
|
||||
|
|
@ -30,52 +25,45 @@ describe("loadCodebaseRules", () => {
|
|||
},
|
||||
} as unknown as IDE;
|
||||
|
||||
// Setup test files
|
||||
const mockFiles = [
|
||||
"src/rules.md",
|
||||
"src/redux/rules.md",
|
||||
"src/components/rules.md",
|
||||
"src/utils/helper.ts", // Non-rules file
|
||||
".continue/rules.md", // This should also be loaded
|
||||
];
|
||||
|
||||
// Mock rule content
|
||||
const mockRuleContent: Record<string, string> = {
|
||||
"src/rules.md": "# General Rules\nFollow coding standards",
|
||||
"src/redux/rules.md":
|
||||
"file:///workspace/src/rules.md":
|
||||
"# General Rules\nFollow coding standards",
|
||||
"file:///workspace/src/redux/rules.md":
|
||||
'---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit',
|
||||
"src/components/rules.md":
|
||||
"file:///workspace/src/components/rules.md":
|
||||
'---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components',
|
||||
".continue/rules.md": "# Global Rules\nFollow project guidelines",
|
||||
"file:///workspace/.continue/rules.md":
|
||||
"# Global Rules\nFollow project guidelines",
|
||||
};
|
||||
|
||||
// Mock converted rules
|
||||
const mockConvertedRules: Record<string, any> = {
|
||||
"src/rules.md": {
|
||||
"file:///workspace/src/rules.md": {
|
||||
name: "General Rules",
|
||||
rule: "Follow coding standards",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
sourceFile: "file:///workspace/src/rules.md",
|
||||
},
|
||||
"src/redux/rules.md": {
|
||||
"file:///workspace/src/redux/rules.md": {
|
||||
name: "Redux Rules",
|
||||
rule: "Use Redux Toolkit",
|
||||
globs: "**/*.{ts,tsx}",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
sourceFile: "file:///workspace/src/redux/rules.md",
|
||||
},
|
||||
"src/components/rules.md": {
|
||||
"file:///workspace/src/components/rules.md": {
|
||||
name: "Component Rules",
|
||||
rule: "Use functional components",
|
||||
globs: ["**/*.tsx", "**/*.jsx"],
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "file:///workspace/src/components/rules.md",
|
||||
},
|
||||
".continue/rules.md": {
|
||||
"file:///workspace/.continue/rules.md": {
|
||||
name: "Global Rules",
|
||||
rule: "Follow project guidelines",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: "file:///workspace/.continue/rules.md",
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -84,20 +72,13 @@ describe("loadCodebaseRules", () => {
|
|||
vi.resetAllMocks();
|
||||
|
||||
// Mock walkDirs to return our test files
|
||||
(walkDirs as any).mockResolvedValue(mockFiles);
|
||||
(walkDirs as any).mockResolvedValue([
|
||||
...Object.keys(mockRuleContent),
|
||||
"file:///workspace/src/utils/helper.ts", // Non-rules file
|
||||
]);
|
||||
|
||||
// Mock getWorkspaceDirs to return a workspace directory
|
||||
(mockIde.getWorkspaceDirs as any).mockResolvedValue(["/workspace"]);
|
||||
|
||||
// Mock getUriPathBasename to return just the filename
|
||||
(getUriPathBasename as any).mockImplementation((path: string) => {
|
||||
return path.split("/").pop() || "";
|
||||
});
|
||||
|
||||
// Mock findUriInDirs to return relative path
|
||||
(findUriInDirs as any).mockImplementation((uri: string) => {
|
||||
return { relativePathOrBasename: uri };
|
||||
});
|
||||
(mockIde.getWorkspaceDirs as any).mockResolvedValue(["file:///workspace"]);
|
||||
|
||||
// Mock readFile to return content based on path
|
||||
(mockIde.readFile as any).mockImplementation((path: string) => {
|
||||
|
|
@ -123,20 +104,36 @@ describe("loadCodebaseRules", () => {
|
|||
|
||||
// Should read all rules.md files
|
||||
expect(mockIde.readFile).toHaveBeenCalledTimes(4);
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith("src/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith("src/redux/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith("src/components/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith(
|
||||
"file:///workspace/src/rules.md",
|
||||
);
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith(
|
||||
"file:///workspace/src/redux/rules.md",
|
||||
);
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith(
|
||||
"file:///workspace/src/components/rules.md",
|
||||
);
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith(
|
||||
"file:///workspace/.continue/rules.md",
|
||||
);
|
||||
|
||||
// Should convert all rules
|
||||
expect(markdownToRule).toHaveBeenCalledTimes(4);
|
||||
|
||||
// Should return all rules
|
||||
expect(rules).toHaveLength(4);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/redux/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/src/rules.md"],
|
||||
);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/src/redux/rules.md"],
|
||||
);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/src/components/rules.md"],
|
||||
);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/.continue/rules.md"],
|
||||
);
|
||||
|
||||
// Should not have errors
|
||||
expect(errors).toHaveLength(0);
|
||||
|
|
@ -145,7 +142,7 @@ describe("loadCodebaseRules", () => {
|
|||
it("should handle errors when reading a rule file", async () => {
|
||||
// Setup mock to throw for a specific file
|
||||
(mockIde.readFile as any).mockImplementation((path: string) => {
|
||||
if (path === "src/redux/rules.md") {
|
||||
if (path === "file:///workspace/src/redux/rules.md") {
|
||||
return Promise.reject(new Error("Failed to read file"));
|
||||
}
|
||||
return Promise.resolve(mockRuleContent[path] || "");
|
||||
|
|
@ -155,14 +152,20 @@ describe("loadCodebaseRules", () => {
|
|||
|
||||
// Should still return other rules
|
||||
expect(rules).toHaveLength(3);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/src/rules.md"],
|
||||
);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/src/components/rules.md"],
|
||||
);
|
||||
expect(rules).toContainEqual(
|
||||
mockConvertedRules["file:///workspace/.continue/rules.md"],
|
||||
);
|
||||
|
||||
// Should have one error
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0].message).toContain(
|
||||
"Failed to parse colocated rule file src/redux/rules.md",
|
||||
"Failed to parse colocated rule file file:///workspace/src/redux/rules.md: Failed to read file",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import {
|
|||
markdownToRule,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { IDE, RuleWithSource } from "../..";
|
||||
import { findUriInDirs, joinPathsToUri } from "../../util/uri";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
|
||||
export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"];
|
||||
|
|
@ -25,26 +25,29 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
|
|||
let agentFileFound = false;
|
||||
for (const fileName of SUPPORTED_AGENT_FILES) {
|
||||
try {
|
||||
const agentFilePath = joinPathsToUri(workspaceDir, fileName);
|
||||
const agentContent = await ide.readFile(agentFilePath);
|
||||
const agentFileUri = joinPathsToUri(workspaceDir, fileName);
|
||||
const exists = await ide.fileExists(agentFileUri);
|
||||
if (exists) {
|
||||
const agentContent = await ide.readFile(agentFileUri);
|
||||
|
||||
const rule = markdownToRule(agentContent, {
|
||||
uriType: "file",
|
||||
fileUri: agentFileUri,
|
||||
});
|
||||
rules.push({
|
||||
...rule,
|
||||
source: "agent-file",
|
||||
sourceFile: agentFileUri,
|
||||
alwaysApply: true,
|
||||
});
|
||||
agentFileFound = true;
|
||||
}
|
||||
|
||||
const rule = markdownToRule(agentContent, {
|
||||
uriType: "file",
|
||||
fileUri: agentFilePath,
|
||||
});
|
||||
rules.push({
|
||||
...rule,
|
||||
source: "agent-file",
|
||||
ruleFile: agentFilePath,
|
||||
alwaysApply: true,
|
||||
});
|
||||
agentFileFound = true;
|
||||
break; // Use the first found agent file in this workspace
|
||||
} catch (e) {
|
||||
// File doesn't exist or can't be read, continue to next file
|
||||
}
|
||||
}
|
||||
|
||||
if (agentFileFound) {
|
||||
break; // Use agent file from first workspace that has one
|
||||
}
|
||||
|
|
@ -64,15 +67,11 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
|
|||
// Process each markdown file
|
||||
for (const file of mdFiles) {
|
||||
try {
|
||||
const { relativePathOrBasename } = findUriInDirs(
|
||||
file.path,
|
||||
await ide.getWorkspaceDirs(),
|
||||
);
|
||||
const rule = markdownToRule(file.content, {
|
||||
uriType: "file",
|
||||
fileUri: relativePathOrBasename,
|
||||
fileUri: file.path,
|
||||
});
|
||||
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
|
||||
rules.push({ ...rule, source: "rules-block", sourceFile: file.path });
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "Root Rule",
|
||||
rule: "Follow project standards",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
// Nested directory rule without globs - should only apply to files in that directory
|
||||
|
|
@ -25,7 +25,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "React Components Rule",
|
||||
rule: "Use functional components with hooks",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
// No explicit globs - should implicitly only apply to files in that directory
|
||||
},
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ describe("Rule Colocation Application", () => {
|
|||
rule: "Use Redux Toolkit for state management",
|
||||
globs: "src/redux/**/*.{ts,tsx}",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
sourceFile: "src/redux/rules.md",
|
||||
},
|
||||
|
||||
// Directory rule with specific file extension glob
|
||||
|
|
@ -44,7 +44,7 @@ describe("Rule Colocation Application", () => {
|
|||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only apply to .tsx files
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
},
|
||||
|
||||
// Rule for a specific subdirectory with its own glob
|
||||
|
|
@ -53,7 +53,7 @@ describe("Rule Colocation Application", () => {
|
|||
rule: "Follow API utility conventions",
|
||||
globs: "**/*.ts", // Only TypeScript files in this directory
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/utils/api/rules.md",
|
||||
sourceFile: "src/utils/api/rules.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -184,7 +184,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "Implied Components Rule",
|
||||
rule: "Use React component best practices",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
// No explicit globs - should infer from directory
|
||||
};
|
||||
|
||||
|
|
@ -234,7 +234,7 @@ describe("Rule Colocation Application", () => {
|
|||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only apply to .tsx files
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
// Test with TSX component file - should apply
|
||||
|
|
@ -281,7 +281,7 @@ describe("Rule Colocation Application", () => {
|
|||
rule: "Follow API utility conventions",
|
||||
globs: "**/*.ts", // Only TypeScript files in this directory
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/utils/api/rules.md",
|
||||
sourceFile: "src/utils/api/rules.md",
|
||||
};
|
||||
|
||||
// Test with file in the API utils directory - should apply
|
||||
|
|
@ -314,9 +314,9 @@ describe("Rule Colocation Application", () => {
|
|||
// it should automatically create an implicit glob pattern for that directory.
|
||||
|
||||
function createRuleWithAutomaticGlobInference(
|
||||
ruleFilePath: string,
|
||||
sourceFilePath: string,
|
||||
): RuleWithSource {
|
||||
const directory = path.dirname(ruleFilePath);
|
||||
const directory = path.dirname(sourceFilePath);
|
||||
// The expected behavior would be to create an implicit glob like this:
|
||||
const expectedGlob = `${directory}/**/*`;
|
||||
|
||||
|
|
@ -324,7 +324,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: `Inferred Rule for ${directory}`,
|
||||
rule: `Follow standards for ${directory}`,
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ruleFilePath,
|
||||
sourceFile: sourceFilePath,
|
||||
// In a fixed implementation, these globs would be automatically inferred
|
||||
// globs: expectedGlob,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import { getControlPlaneEnv } from "../../control-plane/env.js";
|
|||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { initSlashCommand } from "../../promptFiles/initPrompt";
|
||||
import { getConfigDependentToolDefinitions } from "../../tools";
|
||||
import { encodeMCPToolUri } from "../../tools/callTool";
|
||||
import { getMCPToolName } from "../../tools/mcpToolName";
|
||||
|
|
@ -171,6 +172,8 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
}
|
||||
|
||||
newConfig.slashCommands.push(initSlashCommand);
|
||||
|
||||
const proxyContextProvider = newConfig.contextProviders?.find(
|
||||
(cp) => cp.description.title === "continue-proxy",
|
||||
);
|
||||
|
|
@ -210,6 +213,13 @@ export default async function doLoadConfig(options: {
|
|||
newConfig.mcpServerStatuses = serializableStatuses;
|
||||
|
||||
for (const server of mcpServerStatuses) {
|
||||
server.errors.forEach((error) => {
|
||||
// MCP errors will also show as config loading errors
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: error,
|
||||
});
|
||||
});
|
||||
if (server.status === "connected") {
|
||||
const serverTools: Tool[] = server.tools.map((tool) => ({
|
||||
displayTitle: server.name + " " + tool.name,
|
||||
|
|
|
|||
|
|
@ -78,8 +78,9 @@ declare global {
|
|||
|
||||
export interface ILLM extends LLMOptions {
|
||||
get providerName(): string;
|
||||
|
||||
|
||||
uniqueId: string;
|
||||
lastRequestId?: string;
|
||||
model: string;
|
||||
|
||||
title?: string;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
import { IDE } from "../..";
|
||||
import { getContinueGlobalPath } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
const BLOCK_TYPE_CONFIG: Record<
|
||||
|
|
@ -114,8 +115,13 @@ export async function findAvailableFilename(
|
|||
blockType: BlockType,
|
||||
fileExists: (uri: string) => Promise<boolean>,
|
||||
extension?: string,
|
||||
isGlobal?: boolean,
|
||||
): Promise<string> {
|
||||
const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
|
||||
// Differentiate filename based on whether its a global rule or a workspace rule
|
||||
const baseFilename =
|
||||
blockType === "rules" && isGlobal
|
||||
? "global-rule"
|
||||
: `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
|
||||
const fileExtension = extension ?? getFileExtension(blockType);
|
||||
let counter = 0;
|
||||
let fileUri: string;
|
||||
|
|
@ -156,3 +162,28 @@ export async function createNewWorkspaceBlockFile(
|
|||
await ide.writeFile(fileUri, fileContent);
|
||||
await ide.openFile(fileUri);
|
||||
}
|
||||
|
||||
export async function createNewGlobalRuleFile(ide: IDE): Promise<void> {
|
||||
try {
|
||||
const globalDir = getContinueGlobalPath();
|
||||
|
||||
// Create the rules subdirectory within the global directory
|
||||
const rulesDir = joinPathsToUri(globalDir, "rules");
|
||||
|
||||
const fileUri = await findAvailableFilename(
|
||||
rulesDir,
|
||||
"rules",
|
||||
ide.fileExists.bind(ide),
|
||||
undefined,
|
||||
true, // isGlobal = true for global rules
|
||||
);
|
||||
|
||||
const fileContent = getFileContent("rules");
|
||||
|
||||
await ide.writeFile(fileUri, fileContent);
|
||||
|
||||
await ide.openFile(fileUri);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
description: rule.description,
|
||||
ruleFile: rule.sourceFile,
|
||||
sourceFile: rule.sourceFile,
|
||||
alwaysApply: rule.alwaysApply,
|
||||
invokable: rule.invokable ?? false,
|
||||
};
|
||||
|
|
@ -48,12 +48,12 @@ export function convertYamlMcpConfigToInternalMcpOptions(
|
|||
if ("command" in config) {
|
||||
const { args, command, cwd, env, type } = config;
|
||||
const stdioOptions: InternalStdioMcpOptions = {
|
||||
...shared,
|
||||
type,
|
||||
command,
|
||||
args,
|
||||
cwd,
|
||||
env,
|
||||
...shared,
|
||||
};
|
||||
return stdioOptions;
|
||||
}
|
||||
|
|
@ -62,13 +62,13 @@ export function convertYamlMcpConfigToInternalMcpOptions(
|
|||
const httpSseConfig:
|
||||
| InternalStreamableHttpMcpOptions
|
||||
| InternalSseMcpOptions = {
|
||||
...shared,
|
||||
type,
|
||||
url,
|
||||
requestOptions: mergeConfigYamlRequestOptions(
|
||||
requestOptions,
|
||||
globalRequestOptions,
|
||||
),
|
||||
...shared,
|
||||
};
|
||||
return httpSseConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -88,11 +88,11 @@ class MCPConnection {
|
|||
this.abortController = new AbortController();
|
||||
}
|
||||
|
||||
async disconnect() {
|
||||
this.status = "not-connected";
|
||||
async disconnect(disable = false) {
|
||||
this.abortController.abort();
|
||||
await this.client.close();
|
||||
await this.transport.close();
|
||||
this.status = disable ? "disabled" : "not-connected";
|
||||
}
|
||||
|
||||
getStatus(): MCPServerStatus {
|
||||
|
|
@ -110,6 +110,9 @@ class MCPConnection {
|
|||
}
|
||||
|
||||
async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
|
||||
if (this.status === "disabled") {
|
||||
return;
|
||||
}
|
||||
if (!forceRefresh) {
|
||||
// Already connected
|
||||
if (this.status === "connected") {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ export class MCPManagerSingleton {
|
|||
|
||||
public onConnectionsRefreshed?: () => void;
|
||||
public connections: Map<string, MCPConnection> = new Map();
|
||||
private disconnectedServers: string[] = [];
|
||||
|
||||
private abortController: AbortController = new AbortController();
|
||||
|
||||
|
|
@ -21,16 +20,20 @@ export class MCPManagerSingleton {
|
|||
return MCPManagerSingleton.instance;
|
||||
}
|
||||
|
||||
addDisconnectedServer(serverId: string) {
|
||||
this.disconnectedServers.push(serverId);
|
||||
}
|
||||
removeDisconnectedServer(serverId: string) {
|
||||
this.disconnectedServers = this.disconnectedServers.filter(
|
||||
(server) => server !== serverId,
|
||||
);
|
||||
}
|
||||
getDisconnectedServers() {
|
||||
return this.disconnectedServers;
|
||||
async setEnabled(serverId: string, enabled: boolean) {
|
||||
const conn = this.connections.get(serverId);
|
||||
if (conn) {
|
||||
if (enabled) {
|
||||
conn.status = "not-connected";
|
||||
await this.refreshConnection(serverId);
|
||||
} else {
|
||||
try {
|
||||
await conn.disconnect(true);
|
||||
} catch (e) {
|
||||
console.error(`Error disconnecting from MCP server ${serverId}`, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createConnection(id: string, options: InternalMcpOptions): MCPConnection {
|
||||
|
|
@ -47,15 +50,6 @@ export class MCPManagerSingleton {
|
|||
return this.connections.get(id);
|
||||
}
|
||||
|
||||
async removeConnection(id: string) {
|
||||
const connection = this.connections.get(id);
|
||||
if (connection) {
|
||||
await connection.client.close();
|
||||
}
|
||||
|
||||
this.connections.delete(id);
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
if (this.connections.size > 0) {
|
||||
await Promise.allSettled(
|
||||
|
|
@ -169,19 +163,9 @@ export class MCPManagerSingleton {
|
|||
}),
|
||||
(async () => {
|
||||
await Promise.all(
|
||||
Array.from(this.connections.values())
|
||||
.filter(
|
||||
(connection) =>
|
||||
!this.disconnectedServers.some(
|
||||
(s) => s === connection.options.id,
|
||||
),
|
||||
)
|
||||
.map(async (connection) => {
|
||||
await connection.connectClient(
|
||||
force,
|
||||
this.abortController.signal,
|
||||
);
|
||||
}),
|
||||
Array.from(this.connections.values()).map(async (connection) => {
|
||||
await connection.connectClient(force, this.abortController.signal);
|
||||
}),
|
||||
);
|
||||
if (this.onConnectionsRefreshed) {
|
||||
this.onConnectionsRefreshed();
|
||||
|
|
|
|||
|
|
@ -94,28 +94,6 @@ describe("MCPManagerSingleton", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("removeConnection", () => {
|
||||
it("should remove connection and close client", async () => {
|
||||
// Create a spy on the close method
|
||||
const connection = manager.createConnection(
|
||||
"test-id",
|
||||
testOptions,
|
||||
) as TestMCPConnection;
|
||||
const closeSpy = vi.spyOn(connection.client, "close");
|
||||
|
||||
await manager.removeConnection("test-id");
|
||||
|
||||
expect(closeSpy).toHaveBeenCalled();
|
||||
expect(manager.getConnection("test-id")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle non-existent connection", async () => {
|
||||
await expect(
|
||||
manager.removeConnection("non-existent"),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("setConnections", () => {
|
||||
it("should add new connections", () => {
|
||||
const servers = [testOptions];
|
||||
|
|
|
|||
|
|
@ -22,11 +22,11 @@ class RulesContextProvider extends BaseContextProvider {
|
|||
// This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case
|
||||
// Can eventually pull in more metadata, but this is experimental
|
||||
private getIdFromRule(rule: RuleWithSource): string {
|
||||
return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule;
|
||||
return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.rule;
|
||||
}
|
||||
|
||||
private getNameFromRule(rule: RuleWithSource): string {
|
||||
return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source;
|
||||
return rule.name ?? rule.slug ?? rule.sourceFile ?? rule.source;
|
||||
}
|
||||
|
||||
private getDescriptionFromRule(rule: RuleWithSource): string {
|
||||
|
|
@ -37,10 +37,10 @@ class RulesContextProvider extends BaseContextProvider {
|
|||
rule: RuleWithSource,
|
||||
appUrl: string,
|
||||
): ContextItemUri | undefined {
|
||||
if (rule.ruleFile) {
|
||||
if (rule.sourceFile) {
|
||||
return {
|
||||
type: "file",
|
||||
value: rule.ruleFile,
|
||||
value: rule.sourceFile,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ const SUPPORTED_MODEL_TITLE_FAMILIES = [
|
|||
"claude-3",
|
||||
"llama3.1",
|
||||
"llama3.2",
|
||||
"gemini-1.5",
|
||||
"gemini-2.5",
|
||||
"gpt-4",
|
||||
];
|
||||
|
||||
|
|
|
|||
40
core/core.ts
40
core/core.ts
|
|
@ -63,7 +63,10 @@ import {
|
|||
setupProviderConfig,
|
||||
setupQuickstartConfig,
|
||||
} from "./config/onboarding";
|
||||
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
|
||||
import {
|
||||
createNewGlobalRuleFile,
|
||||
createNewWorkspaceBlockFile,
|
||||
} from "./config/workspace/workspaceBlocks";
|
||||
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
|
||||
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
|
||||
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
|
||||
|
|
@ -410,11 +413,19 @@ export class Core {
|
|||
);
|
||||
});
|
||||
|
||||
on("config/addGlobalRule", async (msg) => {
|
||||
try {
|
||||
await createNewGlobalRuleFile(this.ide);
|
||||
await this.configHandler.reloadConfig(
|
||||
"Global rule created (config/addGlobalRule message)",
|
||||
);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
on("config/openProfile", async (msg) => {
|
||||
await this.configHandler.openConfigProfile(
|
||||
msg.data.profileId,
|
||||
msg.data?.element,
|
||||
);
|
||||
await this.configHandler.openConfigProfile(msg.data.profileId);
|
||||
});
|
||||
|
||||
on("config/ideSettingsUpdate", async (msg) => {
|
||||
|
|
@ -483,20 +494,10 @@ export class Core {
|
|||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
MCPManagerSingleton.getInstance().removeDisconnectedServer(msg.data.id);
|
||||
});
|
||||
on("mcp/disconnectServer", async (msg) => {
|
||||
const mcpConnection = MCPManagerSingleton.getInstance().getConnection(
|
||||
msg.data.id,
|
||||
);
|
||||
if (!mcpConnection)
|
||||
throw new Error(`MCP connection with id ${msg.data.id} not found`);
|
||||
MCPManagerSingleton.getInstance().addDisconnectedServer(msg.data.id);
|
||||
await mcpConnection.disconnect();
|
||||
await this.configHandler.refreshAll("MCP Servers disconnected");
|
||||
});
|
||||
on("mcp/getDisconnectedServers", async (_msg) => {
|
||||
return MCPManagerSingleton.getInstance().getDisconnectedServers();
|
||||
on("mcp/setServerEnabled", async (msg) => {
|
||||
const { id, enabled } = msg.data;
|
||||
await MCPManagerSingleton.getInstance().setEnabled(id, enabled);
|
||||
});
|
||||
on("mcp/getPrompt", async (msg) => {
|
||||
const { serverName, promptName, args } = msg.data;
|
||||
|
|
@ -825,7 +826,6 @@ export class Core {
|
|||
if (data?.shouldClearIndexes) {
|
||||
await this.codeBaseIndexer.clearIndexes();
|
||||
}
|
||||
|
||||
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
|
||||
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
|
|
@ -929,7 +929,7 @@ export class Core {
|
|||
});
|
||||
|
||||
on("files/closed", async ({ data }) => {
|
||||
console.log("deleteChain called from files/closed");
|
||||
console.debug("deleteChain called from files/closed");
|
||||
await NextEditProvider.getInstance().deleteChain();
|
||||
|
||||
try {
|
||||
|
|
|
|||
11
core/index.d.ts
vendored
11
core/index.d.ts
vendored
|
|
@ -99,6 +99,8 @@ export interface ILLM
|
|||
|
||||
autocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
|
||||
lastRequestId?: string;
|
||||
|
||||
complete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
|
|
@ -918,7 +920,8 @@ export interface SlashCommand extends SlashCommandDescription {
|
|||
export interface SlashCommandWithSource extends SlashCommandDescription {
|
||||
run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
sourceFile?: string;
|
||||
slug?: string;
|
||||
overrideSystemMessage?: string;
|
||||
}
|
||||
|
||||
|
|
@ -936,7 +939,8 @@ export type SlashCommandSource =
|
|||
export interface SlashCommandDescWithSource extends SlashCommandDescription {
|
||||
isLegacy: boolean; // Maps to if slashcommand.run exists
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
sourceFile?: string;
|
||||
slug?: string;
|
||||
mcpServerName?: string;
|
||||
mcpArgs?: MCPPromptArgs;
|
||||
}
|
||||
|
|
@ -1278,6 +1282,7 @@ export type TransportOptions =
|
|||
| StreamableHTTPOptions;
|
||||
|
||||
export type MCPConnectionStatus =
|
||||
| "disabled"
|
||||
| "connecting"
|
||||
| "connected"
|
||||
| "error"
|
||||
|
|
@ -1854,7 +1859,7 @@ export interface RuleWithSource {
|
|||
regex?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
sourceFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
invokable?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -193,12 +193,15 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
isFromAutoDetect?: boolean;
|
||||
|
||||
lastRequestId: string | undefined;
|
||||
|
||||
private _llmOptions: LLMOptions;
|
||||
|
||||
protected openaiAdapter?: BaseLlmApi;
|
||||
|
||||
constructor(_options: LLMOptions) {
|
||||
this._llmOptions = _options;
|
||||
this.lastRequestId = undefined;
|
||||
|
||||
// Set default options
|
||||
const options = {
|
||||
|
|
@ -594,6 +597,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
): AsyncGenerator<string> {
|
||||
this.lastRequestId = undefined;
|
||||
const { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
|
|
@ -623,6 +627,9 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
|
||||
this.lastRequestId = (chunk as any).id;
|
||||
}
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
const content = renderChatMessage(result);
|
||||
|
|
@ -706,6 +713,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
) {
|
||||
this.lastRequestId = undefined;
|
||||
const { completionOptions, logEnabled, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
|
|
@ -745,6 +753,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
{ ...toCompleteBody(prompt, completionOptions), stream: false },
|
||||
signal,
|
||||
);
|
||||
this.lastRequestId = response.id ?? this.lastRequestId;
|
||||
completion = response.choices[0]?.text ?? "";
|
||||
yield completion;
|
||||
} else {
|
||||
|
|
@ -756,6 +765,9 @@ export abstract class BaseLLM implements ILLM {
|
|||
},
|
||||
signal,
|
||||
)) {
|
||||
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
|
||||
this.lastRequestId = (chunk as any).id;
|
||||
}
|
||||
const content = chunk.choices[0]?.text ?? "";
|
||||
completion += content;
|
||||
interaction?.logItem({
|
||||
|
|
@ -835,6 +847,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
) {
|
||||
this.lastRequestId = undefined;
|
||||
const { completionOptions, logEnabled, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
|
|
@ -876,6 +889,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
},
|
||||
signal,
|
||||
);
|
||||
this.lastRequestId = result.id ?? this.lastRequestId;
|
||||
completion = result.choices[0].text;
|
||||
} else {
|
||||
completion = await this._complete(prompt, signal, completionOptions);
|
||||
|
|
@ -985,6 +999,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
options: LLMFullCompletionOptions = {},
|
||||
messageOptions?: MessageOption,
|
||||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
this.lastRequestId = undefined;
|
||||
let { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
const interaction = logEnabled
|
||||
|
|
@ -1054,6 +1069,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
{ ...body, stream: false },
|
||||
signal,
|
||||
);
|
||||
this.lastRequestId = response.id ?? this.lastRequestId;
|
||||
const msg = fromChatResponse(response);
|
||||
yield msg;
|
||||
completion = this._formatChatMessage(msg);
|
||||
|
|
@ -1071,6 +1087,12 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
if (
|
||||
!this.lastRequestId &&
|
||||
typeof (chunk as any).id === "string"
|
||||
) {
|
||||
this.lastRequestId = (chunk as any).id;
|
||||
}
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
completion += this._formatChatMessage(result);
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ describe("alwaysApply Behavior", () => {
|
|||
alwaysApply: true,
|
||||
globs: "**/*.tsx", // Should be ignored since alwaysApply is true
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Test with no file context
|
||||
|
|
@ -83,7 +83,7 @@ describe("alwaysApply Behavior", () => {
|
|||
alwaysApply: false,
|
||||
globs: "**/*.tsx",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Rule with alwaysApply: false and no globs
|
||||
|
|
@ -93,7 +93,7 @@ describe("alwaysApply Behavior", () => {
|
|||
alwaysApply: false,
|
||||
// No globs
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
// Test with no file context
|
||||
|
|
@ -131,7 +131,7 @@ describe("alwaysApply Behavior", () => {
|
|||
name: "Default No Globs Rule",
|
||||
rule: "Default rule with no globs",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
// No alwaysApply, no globs
|
||||
};
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ describe("alwaysApply Behavior", () => {
|
|||
rule: "Default rule with globs",
|
||||
globs: "**/*.tsx",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
// No alwaysApply, with globs
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ describe("Rule application with alwaysApply", () => {
|
|||
rule: "This rule should always be applied",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/always-apply.md",
|
||||
sourceFile: ".continue/always-apply.md",
|
||||
};
|
||||
|
||||
// Create a colocated rule in a nested directory
|
||||
|
|
@ -23,7 +23,7 @@ describe("Rule application with alwaysApply", () => {
|
|||
name: "Nested Directory Rule",
|
||||
rule: "This rule applies to files in the nested directory",
|
||||
source: "rules-block",
|
||||
ruleFile: "nested-folder/rules.md",
|
||||
sourceFile: "nested-folder/rules.md",
|
||||
};
|
||||
|
||||
it("should apply alwaysApply rules even with no file references", () => {
|
||||
|
|
@ -145,7 +145,7 @@ describe("Rule application with alwaysApply", () => {
|
|||
rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: "src/some/path.md",
|
||||
sourceFile: "src/some/path.md",
|
||||
};
|
||||
|
||||
// Message with no code blocks or file references
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ describe("File Path Protocol Matching", () => {
|
|||
name: "Rule with file:// protocol",
|
||||
rule: "This is a test rule",
|
||||
source: "rules-block",
|
||||
ruleFile: "file:///Users/user/project/nested-folder/rules.md",
|
||||
sourceFile: "file:///Users/user/project/nested-folder/rules.md",
|
||||
};
|
||||
|
||||
it("should match relative paths with file:// protocol paths", () => {
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@ const isFileInDirectory = (
|
|||
* Checks if a rule is a root-level rule (.continue directory or no file path)
|
||||
*/
|
||||
const isRootLevelRule = (rule: RuleWithSource): boolean => {
|
||||
return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between
|
||||
return !rule.sourceFile || rule.sourceFile.includes(".continue/"); // sourceFile path is absolute - hence we need to check for it in between
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -230,8 +230,8 @@ export const shouldApplyRule = (
|
|||
const isRootRule = isRootLevelRule(rule);
|
||||
|
||||
// For non-root rules, we need to check if any files are in the rule's directory
|
||||
if (!isRootRule && rule.ruleFile) {
|
||||
const ruleDirectory = getCleanUriPath(rule.ruleFile);
|
||||
if (!isRootRule && rule.sourceFile) {
|
||||
const ruleDirectory = getCleanUriPath(rule.sourceFile);
|
||||
const lastSlashIndex = ruleDirectory.lastIndexOf("/");
|
||||
const ruleDirPath =
|
||||
lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : "";
|
||||
|
|
@ -325,7 +325,7 @@ export const getApplicableRules = (
|
|||
};
|
||||
|
||||
export function getRuleId(rule: RuleWithSource): string {
|
||||
return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
|
||||
return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.source;
|
||||
}
|
||||
|
||||
export const getSystemMessageWithRules = ({
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ describe("Rule colocation glob matching", () => {
|
|||
name: "Components Rule",
|
||||
rule: "Use functional components with hooks",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
// No explicit globs - should only apply to files in src/components/ directory
|
||||
};
|
||||
|
||||
|
|
@ -43,7 +43,7 @@ describe("Rule colocation glob matching", () => {
|
|||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only .tsx files
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
// Should only apply to .tsx files in src/components/ directory
|
||||
};
|
||||
|
||||
|
|
@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => {
|
|||
name: "Root Rule",
|
||||
rule: "Follow project standards",
|
||||
source: "rules-block",
|
||||
ruleFile: "/path/to/repo/.continue/rules.md",
|
||||
sourceFile: "/path/to/repo/.continue/rules.md",
|
||||
// No restriction, should apply to all files
|
||||
};
|
||||
|
||||
|
|
@ -89,7 +89,7 @@ describe("Rule colocation glob matching", () => {
|
|||
rule: "Follow these guidelines always",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: "src/specific/rules.md",
|
||||
sourceFile: "src/specific/rules.md",
|
||||
// Should apply to all files regardless of directory
|
||||
};
|
||||
|
||||
|
|
@ -107,7 +107,7 @@ describe("Rule colocation glob matching", () => {
|
|||
rule: "This rule should never apply",
|
||||
alwaysApply: false,
|
||||
source: "rules-block",
|
||||
ruleFile: "src/specific/rules.md",
|
||||
sourceFile: "src/specific/rules.md",
|
||||
// Should never apply since alwaysApply is false and there are no globs
|
||||
};
|
||||
|
||||
|
|
@ -121,7 +121,7 @@ describe("Rule colocation glob matching", () => {
|
|||
rule: "Apply to TS files but not test files",
|
||||
globs: ["**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"],
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
sourceFile: "src/utils/rules.md",
|
||||
// Should only apply to non-test TS files in src/utils/
|
||||
};
|
||||
|
||||
|
|
@ -147,7 +147,7 @@ describe("Rule policies", () => {
|
|||
name: "Components Rule",
|
||||
rule: "Use functional components with hooks",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
const testFiles = ["src/components/Button.tsx"];
|
||||
|
|
@ -167,7 +167,7 @@ describe("Rule policies", () => {
|
|||
rule: "This rule would normally always apply",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
const offPolicies: RulePolicies = {
|
||||
|
|
@ -212,7 +212,7 @@ describe("Rule policies", () => {
|
|||
name: "Root Rule",
|
||||
rule: "Follow project standards",
|
||||
source: "rules-block",
|
||||
ruleFile: "/my/project/.continue/rules.md",
|
||||
sourceFile: "/my/project/.continue/rules.md",
|
||||
};
|
||||
|
||||
// Off policy should override even global rules
|
||||
|
|
@ -238,7 +238,7 @@ describe("Rule policies", () => {
|
|||
alwaysApply: true,
|
||||
globs: "**/*.ts",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
sourceFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
// Off policy should win over everything
|
||||
|
|
@ -261,7 +261,7 @@ describe("Content pattern matching", () => {
|
|||
rule: "Follow React component standards",
|
||||
regex: "export (function|const) \\w+.*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
// File that matches the pattern
|
||||
|
|
@ -293,7 +293,7 @@ describe("Content pattern matching", () => {
|
|||
rule: "Apply to functions or classes",
|
||||
regex: ["function\\s+\\w+", "class\\s+\\w+"],
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
sourceFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
|
|
@ -332,7 +332,7 @@ describe("Content pattern matching", () => {
|
|||
globs: "**/*.ts",
|
||||
regex: "class\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
sourceFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
const tsFilePath = "src/models/User.ts";
|
||||
|
|
@ -371,7 +371,7 @@ describe("Content pattern matching", () => {
|
|||
rule: "Use arrow functions for better this binding",
|
||||
regex: "const\\s+\\w+\\s*=\\s*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
sourceFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
// Message with code block containing a matching pattern
|
||||
|
|
@ -433,7 +433,7 @@ describe("Content pattern matching", () => {
|
|||
rule: "This rule has an invalid regex pattern",
|
||||
regex: "([unclosed parenthesis",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
sourceFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
|
|
@ -454,7 +454,7 @@ describe("Content pattern matching", () => {
|
|||
rule: "Apply only to model files with interfaces",
|
||||
regex: "interface\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
sourceFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
// File in the correct directory with matching content
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ describe("Implicit global rules application", () => {
|
|||
name: "Implicit Global Rule",
|
||||
rule: "This rule should be applied to all messages (implicit global)",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/global-rule.md",
|
||||
sourceFile: ".continue/global-rule.md",
|
||||
// No alwaysApply specified
|
||||
// No globs specified
|
||||
};
|
||||
|
|
@ -19,7 +19,7 @@ describe("Implicit global rules application", () => {
|
|||
rule: "This rule should always be applied (explicit global)",
|
||||
alwaysApply: true,
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/explicit-global.md",
|
||||
sourceFile: ".continue/explicit-global.md",
|
||||
};
|
||||
|
||||
// Create a colocated rule in a nested directory
|
||||
|
|
@ -27,7 +27,7 @@ describe("Implicit global rules application", () => {
|
|||
name: "Nested Directory Rule",
|
||||
rule: "This rule applies to files in the nested directory",
|
||||
source: "rules-block",
|
||||
ruleFile: "nested-folder/rules.md",
|
||||
sourceFile: "nested-folder/rules.md",
|
||||
};
|
||||
|
||||
it("should apply rules with no alwaysApply and no globs to all messages, even with no file references", () => {
|
||||
|
|
@ -63,7 +63,7 @@ describe("Implicit global rules application", () => {
|
|||
name: "Root No Globs Rule",
|
||||
rule: "This is a root-level rule with no globs",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
// No alwaysApply, no globs
|
||||
};
|
||||
|
||||
|
|
@ -119,7 +119,7 @@ describe("Implicit global rules application", () => {
|
|||
name: "Assistant Guidelines",
|
||||
rule: "SOLID Design Principles - Coding Assistant Guidelines",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
// No alwaysApply, no globs - should still apply
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ describe("Nested directory rules application", () => {
|
|||
name: "Nested Folder Rule",
|
||||
rule: "HELLO WORLD THIS IS A RULE",
|
||||
source: "rules-block",
|
||||
ruleFile: "manual-testing-sandbox/nested-folder/rules.md",
|
||||
sourceFile: "manual-testing-sandbox/nested-folder/rules.md",
|
||||
// No globs specified
|
||||
};
|
||||
|
||||
|
|
@ -22,7 +22,7 @@ describe("Nested directory rules application", () => {
|
|||
name: "Global Rule",
|
||||
rule: "SOLID Design Principles - Coding Agent Guidelines",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
};
|
||||
|
||||
it("should apply nested directory rules to files in that directory", () => {
|
||||
|
|
@ -103,7 +103,7 @@ describe("Nested directory rules application", () => {
|
|||
rule: "Follow Python best practices for src directory",
|
||||
globs: "**/*.py", // This should only match .py files in src/ and subdirectories
|
||||
source: "rules-block",
|
||||
ruleFile: "src/rules.md",
|
||||
sourceFile: "src/rules.md",
|
||||
};
|
||||
|
||||
// A rule in utils/ that targets *.py files
|
||||
|
|
@ -112,7 +112,7 @@ describe("Nested directory rules application", () => {
|
|||
rule: "Follow Python best practices for utils directory",
|
||||
globs: "**/*.py", // This should only match .py files in utils/ and subdirectories
|
||||
source: "rules-block",
|
||||
ruleFile: "utils/rules.md",
|
||||
sourceFile: "utils/rules.md",
|
||||
};
|
||||
|
||||
// A file in src/
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
name: "General Rule",
|
||||
rule: "Follow coding standards",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
sourceFile: "src/rules.md",
|
||||
},
|
||||
|
||||
// Redux-specific rule with specific directory/file type pattern
|
||||
|
|
@ -19,7 +19,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
rule: "Use Redux Toolkit",
|
||||
globs: "src/redux/**/*.{ts,tsx}",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
sourceFile: "src/redux/rules.md",
|
||||
},
|
||||
|
||||
// Component-specific rule with array of globs
|
||||
|
|
@ -28,7 +28,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
rule: "Use functional components",
|
||||
globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"],
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
sourceFile: "src/components/rules.md",
|
||||
},
|
||||
|
||||
// Rule with explicit alwaysApply: true
|
||||
|
|
@ -38,7 +38,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
alwaysApply: true,
|
||||
globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
// Rule with explicit alwaysApply: false
|
||||
|
|
@ -48,7 +48,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
alwaysApply: false,
|
||||
// No globs, so should never apply
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
sourceFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
// Rule with explicit alwaysApply: false but with globs
|
||||
|
|
@ -58,7 +58,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
alwaysApply: false,
|
||||
globs: "src/utils/**/*.ts",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
sourceFile: "src/utils/rules.md",
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -128,7 +128,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
// Fix: Specify the exact path prefix to restrict to this directory structure
|
||||
globs: "src/features/auth/utils/**/*.ts",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/features/auth/utils/rules.md",
|
||||
sourceFile: "src/features/auth/utils/rules.md",
|
||||
};
|
||||
|
||||
it("should apply nested rules to files in the same directory and subdirectories", () => {
|
||||
|
|
@ -158,7 +158,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
// Testing with standard pattern instead
|
||||
globs: "src/**/[!.]*.ts",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
sourceFile: "src/rules.md",
|
||||
};
|
||||
|
||||
it("should apply to matching files that are not excluded", () => {
|
||||
|
|
@ -175,7 +175,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
|
||||
alwaysApply: false,
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
sourceFile: "src/rules.md",
|
||||
};
|
||||
|
||||
// Using alwaysApply:false with a more specific test
|
||||
|
|
|
|||
|
|
@ -27,14 +27,14 @@ export function getRuleSourceDisplayName(rule: RuleWithSource): string {
|
|||
case "model-options-chat":
|
||||
return "Base System Chat Message";
|
||||
case "agent-file":
|
||||
if (rule.ruleFile) {
|
||||
return getLastNPathParts(rule.ruleFile, 2);
|
||||
if (rule.sourceFile) {
|
||||
return getLastNPathParts(rule.sourceFile, 2);
|
||||
} else {
|
||||
return "Agent file";
|
||||
}
|
||||
case "colocated-markdown":
|
||||
if (rule.ruleFile) {
|
||||
return getLastNPathParts(rule.ruleFile, 2);
|
||||
if (rule.sourceFile) {
|
||||
return getLastNPathParts(rule.sourceFile, 2);
|
||||
} else {
|
||||
return "rules.md";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
|
||||
it("should return true for Gemini models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe(
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
|
@ -139,7 +139,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
|
||||
it("should return true for all Gemini models", () => {
|
||||
expect(supportsFn("gemini-pro")).toBe(true);
|
||||
expect(supportsFn("gemini-1.5-pro")).toBe(true);
|
||||
expect(supportsFn("gemini-ultra")).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -150,7 +149,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
|
||||
it("should handle case insensitivity", () => {
|
||||
expect(supportsFn("GEMINI-pro")).toBe(true);
|
||||
expect(supportsFn("Gemini-1.5-Pro")).toBe(true);
|
||||
expect(supportsFn("Gemini-2.5-Pro")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
|
||||
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { getControlPlaneEnvSync } from "../control-plane/env";
|
||||
import { DataLogger } from "../data/log";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
import { NextEditOutcome } from "./types";
|
||||
|
|
@ -93,6 +95,9 @@ export class NextEditLoggingService {
|
|||
outcome.accepted = true;
|
||||
outcome.aborted = false;
|
||||
this.logNextEditOutcome(outcome);
|
||||
if (outcome.requestId) {
|
||||
void this.logAcceptReject(outcome.requestId, true);
|
||||
}
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
}
|
||||
|
|
@ -111,6 +116,9 @@ export class NextEditLoggingService {
|
|||
outcome.accepted = false;
|
||||
outcome.aborted = false;
|
||||
this.logNextEditOutcome(outcome);
|
||||
if (outcome.requestId) {
|
||||
void this.logAcceptReject(outcome.requestId, false);
|
||||
}
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
}
|
||||
|
|
@ -121,6 +129,7 @@ export class NextEditLoggingService {
|
|||
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}
|
||||
|
||||
if (this._outcomes.has(completionId)) {
|
||||
this._outcomes.delete(completionId);
|
||||
}
|
||||
|
|
@ -142,6 +151,9 @@ export class NextEditLoggingService {
|
|||
outcome.accepted = false;
|
||||
outcome.aborted = false;
|
||||
this.logNextEditOutcome(outcome);
|
||||
if (outcome.requestId) {
|
||||
void this.logAcceptReject(outcome.requestId, false);
|
||||
}
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
this._outcomes.delete(completionId);
|
||||
}, COUNT_COMPLETION_REJECTED_AFTER);
|
||||
|
|
@ -245,4 +257,30 @@ export class NextEditLoggingService {
|
|||
// const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture("nextEditOutcome", outcome, true);
|
||||
}
|
||||
|
||||
private async logAcceptReject(
|
||||
requestId: string,
|
||||
accepted: boolean,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!Telemetry.client) {
|
||||
return;
|
||||
}
|
||||
|
||||
const controlPlaneEnv = getControlPlaneEnvSync("production");
|
||||
await fetchwithRequestOptions(
|
||||
new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
requestId,
|
||||
accepted,
|
||||
}),
|
||||
},
|
||||
);
|
||||
} catch (error) {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -309,6 +309,7 @@ export abstract class BaseNextEditModelProvider {
|
|||
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
|
||||
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
|
||||
uniqueId: await outcomeCtx.ide.getUniqueId(),
|
||||
requestId: outcomeCtx.llm.lastRequestId,
|
||||
timestamp: Date.now(),
|
||||
fileUri: outcomeCtx.helper.filepath,
|
||||
workspaceDirUri:
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
|
|||
completionId: string;
|
||||
gitRepo?: string;
|
||||
uniqueId: string;
|
||||
requestId?: string;
|
||||
timestamp: number;
|
||||
|
||||
// New for Next Edit.
|
||||
|
|
|
|||
|
|
@ -4,81 +4,6 @@ import { walkDir } from "../indexing/walkDir";
|
|||
import { readAllGlobalPromptFiles } from "../util/paths";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
// The hardcoded init prompt content
|
||||
const INIT_PROMPT_CONTENT = `name: Init
|
||||
description: Initialize Codebase
|
||||
---
|
||||
You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
|
||||
|
||||
## Step 1: Check Required Tools
|
||||
First, verify that you have access to the necessary tools:
|
||||
- builtin_file_glob_search: To discover project files
|
||||
- builtin_read_file: To analyze file contents
|
||||
- builtin_ls: To explore directory structure
|
||||
- builtin_create_new_file: To generate the CONTINUE.md file
|
||||
|
||||
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
|
||||
|
||||
## Step 2: Project Analysis
|
||||
Analyze the project structure and key files to understand:
|
||||
- The programming languages and frameworks used
|
||||
- The overall architecture and organization
|
||||
- Key components and their responsibilities
|
||||
- Important configuration files
|
||||
- Build/deployment system
|
||||
|
||||
## Step 3: Generate CONTINUE.md
|
||||
Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
|
||||
|
||||
1. **Project Overview**
|
||||
- Brief description of the project's purpose
|
||||
- Key technologies used
|
||||
- High-level architecture
|
||||
|
||||
2. **Getting Started**
|
||||
- Prerequisites (required software, dependencies)
|
||||
- Installation instructions
|
||||
- Basic usage examples
|
||||
- Running tests
|
||||
|
||||
3. **Project Structure**
|
||||
- Overview of main directories and their purpose
|
||||
- Key files and their roles
|
||||
- Important configuration files
|
||||
|
||||
4. **Development Workflow**
|
||||
- Coding standards or conventions
|
||||
- Testing approach
|
||||
- Build and deployment process
|
||||
- Contribution guidelines
|
||||
|
||||
5. **Key Concepts**
|
||||
- Domain-specific terminology
|
||||
- Core abstractions
|
||||
- Design patterns used
|
||||
|
||||
6. **Common Tasks**
|
||||
- Step-by-step guides for frequent development tasks
|
||||
- Examples of common operations
|
||||
|
||||
7. **Troubleshooting**
|
||||
- Common issues and their solutions
|
||||
- Debugging tips
|
||||
|
||||
8. **References**
|
||||
- Links to relevant documentation
|
||||
- Important resources
|
||||
|
||||
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
|
||||
|
||||
## Step 4: Finalize
|
||||
After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
|
||||
1. Review and edit the file as needed
|
||||
2. Commit it to their repository to share with their team
|
||||
3. Explain that Continue will automatically load this file into context when working with the project
|
||||
|
||||
Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
|
||||
export async function getPromptFilesFromDir(
|
||||
|
|
@ -131,20 +56,11 @@ export async function getAllPromptFiles(
|
|||
await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
|
||||
).flat();
|
||||
|
||||
// Also read from ~/.continue/.prompts
|
||||
// Also read from ~/.continue/prompts
|
||||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
||||
// Add hardcoded init prompt
|
||||
promptFiles.push({
|
||||
path: "builtin:/init.prompt",
|
||||
content: INIT_PROMPT_CONTENT,
|
||||
});
|
||||
|
||||
return await Promise.all(
|
||||
promptFiles.map(async (file) => {
|
||||
if (file.path.startsWith("builtin:")) {
|
||||
return file;
|
||||
}
|
||||
const content = await ide.readFile(file.path);
|
||||
return { path: file.path, content };
|
||||
}),
|
||||
|
|
|
|||
86
core/promptFiles/initPrompt.ts
Normal file
86
core/promptFiles/initPrompt.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import { SlashCommandWithSource } from "..";
|
||||
import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants";
|
||||
import { BuiltInToolNames } from "../tools/builtIn";
|
||||
|
||||
const initFilename = "CONTINUE.md";
|
||||
|
||||
// Prompt for init slash command
|
||||
export const INIT_PROMPT_CONTENT = `
|
||||
You are an expert development assistant. Your task is to create a comprehensive ${initFilename} project guide for the user's codebase to help them and their team better understand and work with the project.
|
||||
|
||||
## Step 1: Check Required Tools
|
||||
First, verify that you have access to the necessary tools:
|
||||
- ${BuiltInToolNames.FileGlobSearch}: To discover project files
|
||||
- ${BuiltInToolNames.ReadFile}: To analyze file contents
|
||||
- ${BuiltInToolNames.LSTool}: To explore directory structure
|
||||
- ${BuiltInToolNames.CreateNewFile}: To generate the ${initFilename} file
|
||||
|
||||
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
|
||||
|
||||
## Step 2: Project Analysis
|
||||
Analyze the project structure and key files to understand:
|
||||
- The programming languages and frameworks used
|
||||
- The overall architecture and organization
|
||||
- Key components and their responsibilities
|
||||
- Important configuration files
|
||||
- Build/deployment system
|
||||
|
||||
## Step 3: Generate ${initFilename}
|
||||
Create a comprehensive ${initFilename} file in the .continue/rules/ directory with the following sections:
|
||||
|
||||
1. **Project Overview**
|
||||
- Brief description of the project's purpose
|
||||
- Key technologies used
|
||||
- High-level architecture
|
||||
|
||||
2. **Getting Started**
|
||||
- Prerequisites (required software, dependencies)
|
||||
- Installation instructions
|
||||
- Basic usage examples
|
||||
- Running tests
|
||||
|
||||
3. **Project Structure**
|
||||
- Overview of main directories and their purpose
|
||||
- Key files and their roles
|
||||
- Important configuration files
|
||||
|
||||
4. **Development Workflow**
|
||||
- Coding standards or conventions
|
||||
- Testing approach
|
||||
- Build and deployment process
|
||||
- Contribution guidelines
|
||||
|
||||
5. **Key Concepts**
|
||||
- Domain-specific terminology
|
||||
- Core abstractions
|
||||
- Design patterns used
|
||||
|
||||
6. **Common Tasks**
|
||||
- Step-by-step guides for frequent development tasks
|
||||
- Examples of common operations
|
||||
|
||||
7. **Troubleshooting**
|
||||
- Common issues and their solutions
|
||||
- Debugging tips
|
||||
|
||||
8. **References**
|
||||
- Links to relevant documentation
|
||||
- Important resources
|
||||
|
||||
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
|
||||
|
||||
## Step 4: Finalize
|
||||
After creating the .continue/rules/${initFilename} file, provide a summary of what you've created and remind the user to:
|
||||
1. Review and edit the file as needed
|
||||
2. Commit it to their repository to share with their team
|
||||
3. Explain that Continue will automatically load this file into context when working with the project
|
||||
|
||||
Also inform the user that they can create additional ${RULES_MARKDOWN_FILENAME} files in subdirectories for more specific documentation related to those components.
|
||||
`.trim();
|
||||
|
||||
export const initSlashCommand: SlashCommandWithSource = {
|
||||
name: "Init",
|
||||
description: "Initialize Codebase",
|
||||
source: "built-in",
|
||||
prompt: INIT_PROMPT_CONTENT,
|
||||
};
|
||||
|
|
@ -93,6 +93,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
void,
|
||||
];
|
||||
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
|
||||
"config/addGlobalRule": [undefined, void];
|
||||
"config/newPromptFile": [undefined, void];
|
||||
"config/newAssistantFile": [undefined, void];
|
||||
"config/ideSettingsUpdate": [IdeSettings, void];
|
||||
|
|
@ -117,10 +118,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
),
|
||||
void,
|
||||
];
|
||||
"config/openProfile": [
|
||||
{ profileId: string | undefined; element?: { sourceFile?: string } },
|
||||
void,
|
||||
];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
"config/updateSelectedModel": [
|
||||
{
|
||||
|
|
@ -147,8 +145,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
"mcp/disconnectServer": [{ id: string }, void];
|
||||
"mcp/getDisconnectedServers": [undefined, string[]];
|
||||
"mcp/setServerEnabled": [{ id: string; enabled: boolean }, void];
|
||||
"mcp/getPrompt": [
|
||||
{
|
||||
serverName: string;
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"config/newAssistantFile",
|
||||
"config/ideSettingsUpdate",
|
||||
"config/addLocalWorkspaceBlock",
|
||||
"config/addGlobalRule",
|
||||
"config/getSerializedProfileInfo",
|
||||
"config/deleteModel",
|
||||
"config/refreshProfiles",
|
||||
|
|
@ -32,8 +33,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"mcp/getPrompt",
|
||||
"mcp/startAuthentication",
|
||||
"mcp/removeAuthentication",
|
||||
"mcp/disconnectServer",
|
||||
"mcp/getDisconnectedServers",
|
||||
"mcp/setServerEnabled",
|
||||
"context/getContextItems",
|
||||
"context/getSymbolsForFiles",
|
||||
"context/loadSubmenuItems",
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "default-chat",
|
||||
rule: "Always use semicolons",
|
||||
alwaysApply: true,
|
||||
ruleFile: "/path/to/rule1.md",
|
||||
sourceFile: "/path/to/rule1.md",
|
||||
},
|
||||
{
|
||||
name: "Rule with Globs",
|
||||
|
|
@ -18,7 +18,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Use TypeScript",
|
||||
globs: "**/*.ts",
|
||||
ruleFile: "/path/to/rule2.md",
|
||||
sourceFile: "/path/to/rule2.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -38,7 +38,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Use consistent formatting",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/agent-rule1.md",
|
||||
sourceFile: "/path/to/agent-rule1.md",
|
||||
},
|
||||
{
|
||||
name: "Agent Rule 2",
|
||||
|
|
@ -46,7 +46,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "default-agent",
|
||||
rule: "Follow naming conventions",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/agent-rule2.md",
|
||||
sourceFile: "/path/to/agent-rule2.md",
|
||||
},
|
||||
// These should be filtered out
|
||||
{
|
||||
|
|
@ -55,7 +55,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "default-chat",
|
||||
rule: "Always use semicolons",
|
||||
alwaysApply: true,
|
||||
ruleFile: "/path/to/rule1.md",
|
||||
sourceFile: "/path/to/rule1.md",
|
||||
},
|
||||
{
|
||||
name: "Rule with Globs",
|
||||
|
|
@ -63,7 +63,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Use TypeScript",
|
||||
globs: "**/*.ts",
|
||||
ruleFile: "/path/to/rule2.md",
|
||||
sourceFile: "/path/to/rule2.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -84,7 +84,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Some rule content",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/no-desc-rule.md",
|
||||
sourceFile: "/path/to/no-desc-rule.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -104,7 +104,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Some rule content",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/no-name-rule.md",
|
||||
sourceFile: "/path/to/no-name-rule.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -117,7 +117,7 @@ describe("getRequestRuleDescription", () => {
|
|||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should handle rules with missing ruleFile", () => {
|
||||
it("should handle rules with missing sourceFile", () => {
|
||||
const rules: RuleWithSource[] = [
|
||||
{
|
||||
name: "Rule Without File",
|
||||
|
|
@ -144,7 +144,7 @@ describe("getRequestRuleDescription", () => {
|
|||
description: "This should be filtered out",
|
||||
source: "rules-block",
|
||||
rule: "Some rule",
|
||||
ruleFile: "/path/to/rule.md",
|
||||
sourceFile: "/path/to/rule.md",
|
||||
// alwaysApply is undefined, which is truthy in the filter condition
|
||||
},
|
||||
{
|
||||
|
|
@ -153,7 +153,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Some rule",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/valid-rule.md",
|
||||
sourceFile: "/path/to/valid-rule.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -175,7 +175,7 @@ describe("getRequestRuleDescription", () => {
|
|||
rule: "Some rule",
|
||||
alwaysApply: false,
|
||||
globs: "**/*.ts",
|
||||
ruleFile: "/path/to/rule1.md",
|
||||
sourceFile: "/path/to/rule1.md",
|
||||
},
|
||||
{
|
||||
name: "Rule with array globs",
|
||||
|
|
@ -184,7 +184,7 @@ describe("getRequestRuleDescription", () => {
|
|||
rule: "Some rule",
|
||||
alwaysApply: false,
|
||||
globs: ["**/*.ts", "**/*.js"],
|
||||
ruleFile: "/path/to/rule2.md",
|
||||
sourceFile: "/path/to/rule2.md",
|
||||
},
|
||||
{
|
||||
name: "Valid Agent Rule",
|
||||
|
|
@ -192,7 +192,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Some rule",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/valid-rule.md",
|
||||
sourceFile: "/path/to/valid-rule.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -224,7 +224,7 @@ describe("getRequestRuleDescription", () => {
|
|||
source: "rules-block",
|
||||
rule: "Follow this guideline",
|
||||
alwaysApply: false,
|
||||
ruleFile: "/path/to/single-rule.md",
|
||||
sourceFile: "/path/to/single-rule.md",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
|
|||
// Find the rule by name in the config
|
||||
const rule = extras.config.rules.find((r) => r.name === name);
|
||||
|
||||
if (!rule || !rule.ruleFile) {
|
||||
if (!rule || !rule.sourceFile) {
|
||||
throw new Error(`Rule with name "${name}" not found or has no file path`);
|
||||
}
|
||||
|
||||
|
|
@ -18,7 +18,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
|
|||
content: rule.rule,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: rule.ruleFile,
|
||||
value: rule.sourceFile,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ export type GlobalContextType = {
|
|||
selectedModelsByProfileId: {
|
||||
[profileId: string]: GlobalContextModelSelections;
|
||||
};
|
||||
cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users
|
||||
|
||||
/**
|
||||
* This is needed to handle the case where a JetBrains user has created
|
||||
|
|
|
|||
|
|
@ -186,7 +186,7 @@
|
|||
"pages": [
|
||||
"hub/introduction",
|
||||
{
|
||||
"group": "agents",
|
||||
"group": "Agents",
|
||||
"icon": "robot",
|
||||
"pages": [
|
||||
"hub/agents/intro",
|
||||
|
|
@ -222,6 +222,11 @@
|
|||
"hub/secrets/secret-resolution"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Workflows",
|
||||
"icon": "cloud",
|
||||
"pages": ["hub/workflows/intro"]
|
||||
},
|
||||
"hub/sharing",
|
||||
"hub/source-control"
|
||||
]
|
||||
|
|
|
|||
|
|
@ -290,7 +290,7 @@ cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan." --auto
|
|||
|
||||
## Continuous Security with GitHub Actions
|
||||
|
||||
This example demonstrates a **Continuous AI workflow** where security scanning runs automatically in your CI/CD pipeline Headless Mode Prompt in headless mode (`cn -p`) with Snyk MCP.
|
||||
This example demonstrates a **Continuous AI workflow** where security scanning runs automatically on pull requests, generates AI-powered mitigation suggestions, and posts them as PR comments.
|
||||
|
||||
<Info>
|
||||
|
||||
|
|
@ -310,15 +310,11 @@ Navigate to **Repository Settings → Secrets and variables → Actions** and ad
|
|||
Create `.github/workflows/snyk-security.yml` in your repository:
|
||||
|
||||
```yaml
|
||||
name: Security Scanning with Snyk MCP
|
||||
name: Snyk Security Scanning
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "0 8 * * *" # Daily at 8 AM UTC
|
||||
|
||||
jobs:
|
||||
security-scan:
|
||||
|
|
@ -326,60 +322,259 @@ jobs:
|
|||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git diff
|
||||
|
||||
- name: Get Changed Files
|
||||
id: changed-files
|
||||
run: |
|
||||
echo "📝 Getting changed files since main branch..."
|
||||
CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ')
|
||||
echo "changed_files=$CHANGED_FILES" >> $GITHUB_OUTPUT
|
||||
echo "Changed files: $CHANGED_FILES"
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "18"
|
||||
node-version: '18'
|
||||
|
||||
- name: Install Snyk CLI
|
||||
run: |
|
||||
npm install -g snyk
|
||||
echo "✅ Snyk CLI installed"
|
||||
|
||||
- name: Install Continue CLI
|
||||
run: |
|
||||
npm install -g @continuedev/cli
|
||||
echo "✅ Continue CLI installed"
|
||||
|
||||
- name: Authenticate Continue CLI
|
||||
- name: Validate Secrets
|
||||
run: |
|
||||
if [ -z "${{ secrets.SNYK_TOKEN }}" ]; then
|
||||
echo "❌ Error: SNYK_TOKEN secret is not set"
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "${{ secrets.CONTINUE_API_KEY }}" ]; then
|
||||
echo "⚠️ Warning: CONTINUE_API_KEY not set - AI mitigation suggestions will be skipped"
|
||||
fi
|
||||
echo "✅ Required secrets validated"
|
||||
|
||||
- name: Authenticate Snyk
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
run: |
|
||||
snyk auth "$SNYK_TOKEN"
|
||||
echo "✅ Snyk authenticated"
|
||||
|
||||
- name: Run Security Scans
|
||||
id: security-scan
|
||||
continue-on-error: true
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
CHANGED_FILES: ${{ steps.changed-files.outputs.changed_files }}
|
||||
run: |
|
||||
SCAN_FAILED=0
|
||||
|
||||
if [ -n "$CHANGED_FILES" ]; then
|
||||
echo "🔍 Running targeted scan on changed files..."
|
||||
echo "Changed files: $CHANGED_FILES"
|
||||
FILE_ARGS=""
|
||||
for file in $CHANGED_FILES; do
|
||||
if [[ "$file" =~ \.(js|jsx|ts|tsx|py|java|go|rb)$ ]]; then
|
||||
FILE_ARGS="$FILE_ARGS --file=$file"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "$FILE_ARGS" ]; then
|
||||
echo "🔍 Running Snyk Code scan on changed files..."
|
||||
snyk code test $FILE_ARGS --severity-threshold=high --json > snyk-code-results.json || {
|
||||
echo "❌ Snyk Code found high severity issues in changed files"
|
||||
SCAN_FAILED=1
|
||||
}
|
||||
else
|
||||
echo "⚠️ No scannable code files changed, skipping Snyk Code scan"
|
||||
echo '{"runs": [{"results": []}]}' > snyk-code-results.json
|
||||
fi
|
||||
else
|
||||
echo "⚠️ No changed files detected, creating empty results"
|
||||
echo '{"runs": [{"results": []}]}' > snyk-code-results.json
|
||||
fi
|
||||
|
||||
echo "📦 Checking dependencies..."
|
||||
snyk test --severity-threshold=high --json > snyk-oss-results.json || {
|
||||
echo "❌ Snyk Open Source found high severity issues"
|
||||
SCAN_FAILED=1
|
||||
}
|
||||
|
||||
if [ $SCAN_FAILED -eq 1 ]; then
|
||||
echo "scan_status=failed" >> $GITHUB_OUTPUT
|
||||
echo "⚠️ Scans completed with issues - continuing to generate mitigation suggestions"
|
||||
else
|
||||
echo "scan_status=passed" >> $GITHUB_OUTPUT
|
||||
echo "✅ All security scans passed"
|
||||
fi
|
||||
|
||||
- name: Generate AI Mitigation Suggestions
|
||||
if: always() && steps.security-scan.outputs.scan_status == 'failed'
|
||||
continue-on-error: true
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
run: |
|
||||
cn auth login --api-key "$CONTINUE_API_KEY"
|
||||
echo "✅ Continue CLI authenticated"
|
||||
echo "🤖 Generating AI-powered mitigation suggestions..."
|
||||
|
||||
- name: Run Security Scans
|
||||
# Create a summary of findings for Continue CLI
|
||||
FINDINGS_SUMMARY=$(cat snyk-code-results.json snyk-oss-results.json | jq -r '
|
||||
if .runs then
|
||||
.runs[0].results[] | "Code Issue: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri) (Severity: \(.level))"
|
||||
elif .vulnerabilities then
|
||||
.vulnerabilities[] | "Dependency Issue: \(.title) in \(.packageName)@\(.version) (Severity: \(.severity))"
|
||||
else
|
||||
empty
|
||||
end
|
||||
' | head -20)
|
||||
|
||||
if [ -n "$FINDINGS_SUMMARY" ]; then
|
||||
echo "📋 Security findings to analyze:"
|
||||
echo "$FINDINGS_SUMMARY"
|
||||
echo ""
|
||||
|
||||
# Use Continue CLI to generate mitigation suggestions
|
||||
PROMPT="Analyze these Snyk security findings and provide specific, actionable mitigation steps for each issue. Focus on: 1) Root cause, 2) Immediate fix, 3) Long-term prevention. Findings: $FINDINGS_SUMMARY. Provide clear, prioritized recommendations."
|
||||
|
||||
cn --config continuedev/snyk-continuous-ai -p "$PROMPT" --auto > mitigation-suggestions.md || {
|
||||
echo "⚠️ Warning: Could not generate AI suggestions"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if [ -f mitigation-suggestions.md ]; then
|
||||
echo "✅ AI mitigation suggestions generated"
|
||||
echo ""
|
||||
echo "--- Mitigation Suggestions ---"
|
||||
cat mitigation-suggestions.md
|
||||
fi
|
||||
else
|
||||
echo "⚠️ No findings to analyze"
|
||||
fi
|
||||
|
||||
- name: Post Mitigation Summary to PR
|
||||
if: steps.security-scan.outputs.scan_status == 'failed' && hashFiles('mitigation-suggestions.md') != ''
|
||||
continue-on-error: true
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
echo "🔍 Running code vulnerability scan..."
|
||||
cn -p "Run Snyk Code scan with severity high on this repo.
|
||||
Fail if any high issues are present." --auto
|
||||
if [ -f mitigation-suggestions.md ]; then
|
||||
echo "💬 Posting mitigation summary to PR..."
|
||||
|
||||
echo "📦 Checking dependencies..."
|
||||
cn -p "Run Snyk Open Source on this repo.
|
||||
Fail on fixable high issues." --auto
|
||||
# Create PR comment with mitigation suggestions
|
||||
cat > pr-comment.md <<'EOF'
|
||||
## 🛡️ Snyk Mitigation Summary
|
||||
|
||||
Snyk has identified security issues in this PR. Here are AI-generated mitigation recommendations:
|
||||
|
||||
EOF
|
||||
|
||||
cat mitigation-suggestions.md >> pr-comment.md
|
||||
|
||||
cat >> pr-comment.md <<EOF
|
||||
|
||||
---
|
||||
**Scan Details:**
|
||||
- 📊 Full report available in workflow artifacts
|
||||
- 🔍 Review the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for complete details
|
||||
- 🤖 Generated with Continue CLI + Snyk
|
||||
|
||||
_This is an automated security analysis. Please review and address the findings before merging._
|
||||
EOF
|
||||
|
||||
gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md
|
||||
|
||||
echo "✅ Mitigation summary posted to PR"
|
||||
else
|
||||
echo "⚠️ No mitigation suggestions file found"
|
||||
fi
|
||||
|
||||
- name: Generate Security Report
|
||||
if: always()
|
||||
continue-on-error: true
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
run: |
|
||||
cn -p "Generate a markdown security report summarizing:
|
||||
- Total vulnerabilities by severity
|
||||
- Top 3 critical issues (if any)
|
||||
- Recommended next steps
|
||||
Save to security-report.md" --auto
|
||||
echo "📊 Generating security report..."
|
||||
{
|
||||
echo "# Security Scan Report"
|
||||
echo ""
|
||||
echo "**Date:** $(date -u +"%Y-%m-%d %H:%M:%S UTC")"
|
||||
echo "**Branch:** ${{ github.ref_name }}"
|
||||
echo "**Commit:** ${{ github.sha }}"
|
||||
echo "**Status:** ${{ steps.security-scan.outputs.scan_status }}"
|
||||
echo ""
|
||||
|
||||
echo "## Snyk Code Scan Results"
|
||||
if [ -f snyk-code-results.json ]; then
|
||||
jq -r '.runs[0].results[] | "- **\(.level | ascii_upcase)**: \(.message.text) in \(.locations[0].physicalLocation.artifactLocation.uri)"' snyk-code-results.json || echo "No code issues found"
|
||||
else
|
||||
echo "No scan results available"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
echo "## Snyk Open Source Scan Results"
|
||||
if [ -f snyk-oss-results.json ]; then
|
||||
jq -r '.vulnerabilities[] | "- **\(.severity | ascii_upcase)**: \(.title) (\(.packageName)@\(.version))"' snyk-oss-results.json || echo "No dependency issues found"
|
||||
else
|
||||
echo "No scan results available"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
if [ -f mitigation-suggestions.md ]; then
|
||||
echo "## AI-Powered Mitigation Suggestions"
|
||||
echo ""
|
||||
cat mitigation-suggestions.md
|
||||
fi
|
||||
} > scan-results.md
|
||||
|
||||
if [ -f scan-results.md ]; then
|
||||
echo "✅ Security report generated successfully"
|
||||
cat scan-results.md
|
||||
else
|
||||
echo "⚠️ Warning: scan-results.md was not created"
|
||||
fi
|
||||
|
||||
- name: Upload Security Report
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: security-report-${{ github.run_number }}
|
||||
path: security-report.md
|
||||
retention-days: 30
|
||||
name: security-scan-results
|
||||
path: |
|
||||
scan-results.md
|
||||
snyk-code-results.json
|
||||
snyk-oss-results.json
|
||||
mitigation-suggestions.md
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Fail if Security Issues Found
|
||||
if: steps.security-scan.outputs.scan_status == 'failed'
|
||||
run: |
|
||||
echo "❌ Security scan failed - high severity issues found"
|
||||
echo "📋 Review the security report artifact for details and mitigation suggestions"
|
||||
exit 1
|
||||
```
|
||||
|
||||
<Info>
|
||||
The Snyk MCP requires authentication via the SNYK_TOKEN environment variable in CI/CD environments.
|
||||
The Continue agent uses this token to authenticate Snyk operations automatically.
|
||||
**About SNYK_TOKEN**: The workflow uses the SNYK_TOKEN in two ways:
|
||||
1. **Direct Snyk CLI authentication** - Authenticates the Snyk CLI for running scans
|
||||
2. **Continue CLI access** - Available as an environment variable when Continue generates AI mitigation suggestions
|
||||
|
||||
The `cn` agent automatically uses the SNYK_TOKEN when needed for Snyk MCP operations.
|
||||
</Info>
|
||||
|
||||
<Info>
|
||||
This workflow demonstrates several advanced features:
|
||||
- **Changed Files Detection**: Only scans files modified in the PR
|
||||
- **AI Mitigation**: Uses Continue CLI to generate actionable mitigation steps
|
||||
- **PR Comments**: Automatically posts mitigation suggestions as PR comments
|
||||
- **Comprehensive Reporting**: Generates detailed security reports with artifacts
|
||||
</Info>
|
||||
|
||||
## Security Guardrails
|
||||
|
|
|
|||
97
docs/hub/workflows/intro.mdx
Normal file
97
docs/hub/workflows/intro.mdx
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
---
|
||||
title: "Introduction"
|
||||
description: "Run Continuous AI workflows in the background"
|
||||
---
|
||||
|
||||
<Info>
|
||||
Workflows are in beta. Please share any feedback with us in [GitHub discussions](https://github.com/continuedev/continue/discussions/8051).
|
||||
</Info>
|
||||
|
||||
Workflows are a way to run and manage background agents in Continue. You can use them for:
|
||||
- Addressing small nitpicks and bugs
|
||||
- Building boilerplate-heavy features
|
||||
- Investigating an issue to kickstart your work
|
||||
- [Automated security scanning](../../guides/snyk-mcp-continue-cookbook)
|
||||
- Running repeatable tasks with your own rules, prompts, and MCP servers
|
||||
- Much more!
|
||||
|
||||
## Quickstart
|
||||
|
||||
To run your first workflow
|
||||
|
||||
1. Go to [hub.continue.dev/agents](https://hub.continue.dev/agents)
|
||||
|
||||

|
||||
|
||||
2. Connect with your GitHub account
|
||||
3. Enter the prompt for your agent
|
||||
|
||||
## Example Workflow Tasks
|
||||
|
||||
Here are some example tasks you can try with your workflows:
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Bug Fixes & Code Quality">
|
||||
|
||||
- "Fix the TypeError in api/users.ts where the user object might be undefined"
|
||||
- "Add null checks to all database query results in the services/ directory"
|
||||
- "Fix all ESLint warnings in the components folder"
|
||||
- "Update deprecated React lifecycle methods to hooks in legacy components"
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Feature Development">
|
||||
|
||||
- "Create a new REST endpoint for user profile updates with validation and error handling"
|
||||
- "Add pagination to the products list page with previous/next buttons"
|
||||
- "Implement dark mode toggle using Tailwind CSS classes across all pages"
|
||||
- "Add unit tests for the authentication service using Jest"
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Security & Compliance">
|
||||
|
||||
- "Scan the codebase for hardcoded API keys and move them to environment variables"
|
||||
- "Add input sanitization to all user-facing form fields"
|
||||
- "Update all npm packages with known security vulnerabilities"
|
||||
- "Implement rate limiting on the /api/login endpoint"
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Documentation & Boilerplate">
|
||||
|
||||
- "Add JSDoc comments to all exported functions in the utils/ directory"
|
||||
- "Create a README.md for the new payment-processing module with setup instructions"
|
||||
- "Generate TypeScript interfaces for all API response schemas"
|
||||
- "Add error handling boilerplate to all async functions missing try-catch blocks"
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Investigation & Analysis">
|
||||
|
||||
- "Investigate why the login API is returning 500 errors intermittently and suggest fixes"
|
||||
- "Analyze the performance bottleneck in the data processing pipeline"
|
||||
- "Review the database schema for the orders table and suggest optimizations"
|
||||
- "Find all TODO comments related to authentication and create a summary"
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Refactoring">
|
||||
|
||||
- "Extract the repeated validation logic in controllers into a shared utility function"
|
||||
- "Convert all class components in src/legacy to functional components with hooks"
|
||||
- "Rename all instances of 'userId' to 'accountId' across the codebase"
|
||||
- "Split the 500-line UserService.ts into smaller, single-responsibility services"
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## How to use background agents
|
||||
|
||||
The practice of using background agents, which we call Continuous AI, requires practice and forethought to set up the right guiderails and habits to fit your development workflow, much like learning to work with a larger engineering team. We are constantly sharing our learnings on the [Continuous AI Blog](https://blog.continue.dev), but these few high-level tips are a great way to quickly become successful with workflows:
|
||||
|
||||
- Practice first with the [Continue CLI](../../guides/cli) in "TUI mode". The same agent that powers our CLI is used for workflows, so you can easily test your prompts locally.
|
||||
- Identify and begin with tasks that you are confident can be accomplished by Continue. For example, ask Continue to fix a small bug where you already know the solution is simple.
|
||||
- Once you have merged a PR created by Continue, be increasingly ambitious with your tasks. By being willing to start tasks that might not succeed on the first try, you will learn about prompting best practices and limitations of current language models.
|
||||
- Use thorough prompts. Workflows can run for a long time to complete their task, so it is worthwhile to invest in sharing all of the important details.
|
||||
- Discuss the use of workflows with your team. Truly embracing Continuous AI likely means acknowledging that a higher volume of PRs will be created and adjusting your code review habits.
|
||||
BIN
docs/images/hub/workflows/images/workflows-setup.png
Normal file
BIN
docs/images/hub/workflows/images/workflows-setup.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 145 KiB |
|
|
@ -8,6 +8,7 @@ import nodeFetch from "node-fetch";
|
|||
import open from "open";
|
||||
|
||||
import { getApiClient } from "../config.js";
|
||||
// eslint-disable-next-line import/order
|
||||
import { env } from "../env.js";
|
||||
if (!globalThis.fetch) {
|
||||
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
|
||||
|
|
@ -96,13 +97,24 @@ export function getConfigUri(config: AuthConfig): string | null {
|
|||
|
||||
/**
|
||||
* Gets the model name from any auth config type
|
||||
* For unauthenticated users or when auth config has no modelName, checks GlobalContext
|
||||
*/
|
||||
export function getModelName(config: AuthConfig): string | null {
|
||||
if (config === null) return null;
|
||||
return config.modelName || null;
|
||||
// Priority 1: Logged-in users with modelName in auth config
|
||||
if (config !== null && config.modelName) {
|
||||
return config.modelName;
|
||||
}
|
||||
|
||||
// Priority 2: Fall back to GlobalContext (for logged-out users or logged-in without modelName)
|
||||
return getPersistedModelName();
|
||||
}
|
||||
|
||||
// URI utility functions have been moved to ./uriUtils.ts
|
||||
import {
|
||||
getPersistedModelName,
|
||||
persistModelName,
|
||||
} from "../util/modelPersistence.js";
|
||||
|
||||
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
|
||||
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
|
||||
import {
|
||||
|
|
@ -214,21 +226,30 @@ export function updateConfigUri(configUri: string | null): void {
|
|||
|
||||
/**
|
||||
* Updates the model name in the authentication configuration
|
||||
* Returns the updated config so the caller can update in-memory state
|
||||
* For unauthenticated users, saves to GlobalContext
|
||||
*/
|
||||
export function updateModelName(modelName: string | null): void {
|
||||
export function updateModelName(modelName: string | null): AuthConfig {
|
||||
// If using CONTINUE_API_KEY environment variable, don't save anything
|
||||
if (process.env.CONTINUE_API_KEY) {
|
||||
return;
|
||||
return loadAuthConfig();
|
||||
}
|
||||
|
||||
const config = loadAuthConfig();
|
||||
|
||||
// If logged in, save to auth.json
|
||||
if (config && isAuthenticatedConfig(config)) {
|
||||
const updatedConfig: AuthenticatedConfig = {
|
||||
...config,
|
||||
modelName: modelName || undefined,
|
||||
};
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
|
||||
// If logged out, save to GlobalContext
|
||||
persistModelName(modelName);
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -3,12 +3,18 @@ import chalk from "chalk";
|
|||
import { login as workosLogin } from "../auth/workos.js";
|
||||
import { gracefulExit } from "../util/exit.js";
|
||||
|
||||
import { chat } from "./chat.js";
|
||||
|
||||
export async function login() {
|
||||
console.info(chalk.yellow("Logging in to Continue..."));
|
||||
|
||||
try {
|
||||
await workosLogin();
|
||||
console.info(chalk.green("Successfully logged in!"));
|
||||
|
||||
// Start the CLI session after successful login
|
||||
console.info(chalk.blue("Starting Continue CLI..."));
|
||||
await chat();
|
||||
} catch (error: any) {
|
||||
console.error(chalk.red(`Login failed: ${error.message}`));
|
||||
await gracefulExit(1);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import { render } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
|
||||
import { env } from "../env.js";
|
||||
import { listSessions, loadSessionById } from "../session.js";
|
||||
import { SessionSelector } from "../ui/SessionSelector.js";
|
||||
import { ApiRequestError, post } from "../util/apiClient.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { chat } from "./chat.js";
|
||||
|
|
@ -27,26 +26,19 @@ function setSessionId(sessionId: string): void {
|
|||
}
|
||||
|
||||
export async function getTunnelForAgent(agentId: string): Promise<string> {
|
||||
const authConfig = loadAuthConfig();
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
|
||||
const resp = await fetch(
|
||||
new URL(`agents/${encodeURIComponent(agentId)}/tunnel`, env.apiBase),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!resp.ok) {
|
||||
throw new Error(
|
||||
`Failed to get tunnel for agent ${agentId}: ${await resp.text()}`,
|
||||
try {
|
||||
const response = await post<{ url: string }>(
|
||||
`agents/${encodeURIComponent(agentId)}/tunnel`,
|
||||
);
|
||||
return response.data.url;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError) {
|
||||
throw new Error(
|
||||
`Failed to get tunnel for agent ${agentId}: ${error.response || error.statusText}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const data = await resp.json();
|
||||
return data.url;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -8,11 +8,13 @@ vi.mock("../env.js");
|
|||
vi.mock("../telemetry/telemetryService.js");
|
||||
vi.mock("../ui/index.js");
|
||||
vi.mock("../util/git.js");
|
||||
vi.mock("../util/exit.js");
|
||||
|
||||
const mockWorkos = vi.mocked(await import("../auth/workos.js"));
|
||||
const mockEnv = vi.mocked(await import("../env.js"));
|
||||
const mockGit = vi.mocked(await import("../util/git.js"));
|
||||
const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js"));
|
||||
const mockExit = vi.mocked(await import("../util/exit.js"));
|
||||
|
||||
// Mock fetch globally
|
||||
const mockFetch = vi.fn();
|
||||
|
|
@ -62,6 +64,10 @@ describe("remote command", () => {
|
|||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => ({
|
||||
id: "test-agent-id",
|
||||
url: "ws://test-url.com",
|
||||
|
|
@ -70,6 +76,9 @@ describe("remote command", () => {
|
|||
});
|
||||
|
||||
mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
|
||||
|
||||
// Mock gracefulExit to prevent process.exit during tests
|
||||
mockExit.gracefulExit.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("should include idempotency key in request body when provided", async () => {
|
||||
|
|
@ -151,10 +160,18 @@ describe("remote command", () => {
|
|||
mockFetch
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }),
|
||||
})
|
||||
.mockResolvedValue({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => ({
|
||||
id: "test-agent-id",
|
||||
url: "ws://test-url.com",
|
||||
|
|
@ -187,6 +204,10 @@ describe("remote command", () => {
|
|||
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
headers: {
|
||||
get: (name: string) =>
|
||||
name === "content-type" ? "application/json" : null,
|
||||
},
|
||||
json: async () => tunnelResponse,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
import chalk from "chalk";
|
||||
|
||||
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
|
||||
import { env } from "../env.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startRemoteTUIChat } from "../ui/index.js";
|
||||
import {
|
||||
ApiRequestError,
|
||||
AuthenticationRequiredError,
|
||||
post,
|
||||
} from "../util/apiClient.js";
|
||||
import { gracefulExit } from "../util/exit.js";
|
||||
import { getRepoUrl } from "../util/git.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
|
@ -28,12 +32,6 @@ type AgentCreationResponse = TunnelResponse & {
|
|||
id: string;
|
||||
};
|
||||
|
||||
class AuthenticationRequiredError extends Error {
|
||||
constructor() {
|
||||
super("Not authenticated. Please run 'cn login' first.");
|
||||
}
|
||||
}
|
||||
|
||||
export async function remote(
|
||||
prompt: string | undefined,
|
||||
options: RemoteCommandOptions = {},
|
||||
|
|
@ -46,19 +44,12 @@ export async function remote(
|
|||
return;
|
||||
}
|
||||
|
||||
const accessToken = requireAccessToken();
|
||||
|
||||
if (options.id) {
|
||||
await connectExistingAgent(
|
||||
options.id,
|
||||
accessToken,
|
||||
actualPrompt,
|
||||
options.start,
|
||||
);
|
||||
await connectExistingAgent(options.id, actualPrompt, options.start);
|
||||
return;
|
||||
}
|
||||
|
||||
await createAndConnectRemoteEnvironment(accessToken, actualPrompt, options);
|
||||
await createAndConnectRemoteEnvironment(actualPrompt, options);
|
||||
} catch (error) {
|
||||
await handleRemoteError(error);
|
||||
}
|
||||
|
|
@ -99,29 +90,12 @@ async function connectToRemoteUrl(
|
|||
await launchRemoteTUI(remoteUrl, prompt);
|
||||
}
|
||||
|
||||
function requireAccessToken(): string {
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
if (!authConfig) {
|
||||
throw new AuthenticationRequiredError();
|
||||
}
|
||||
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationRequiredError();
|
||||
}
|
||||
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
async function connectExistingAgent(
|
||||
agentId: string,
|
||||
accessToken: string,
|
||||
prompt: string | undefined,
|
||||
startOnly?: boolean,
|
||||
) {
|
||||
const tunnel = await fetchAgentTunnel(agentId, accessToken);
|
||||
const tunnel = await fetchAgentTunnel(agentId);
|
||||
|
||||
if (startOnly) {
|
||||
printStartJson({
|
||||
|
|
@ -142,30 +116,24 @@ async function connectExistingAgent(
|
|||
}
|
||||
|
||||
async function createAndConnectRemoteEnvironment(
|
||||
accessToken: string,
|
||||
prompt: string | undefined,
|
||||
options: RemoteCommandOptions,
|
||||
) {
|
||||
const requestBody = buildAgentRequestBody(options, prompt);
|
||||
|
||||
const response = await fetch(new URL("agents", env.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to create remote environment: ${response.status} ${errorText}`,
|
||||
);
|
||||
let result: AgentCreationResponse;
|
||||
try {
|
||||
const response = await post<AgentCreationResponse>("agents", requestBody);
|
||||
result = response.data;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError) {
|
||||
throw new Error(
|
||||
`Failed to create remote environment: ${error.status} ${error.response || error.statusText}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const result = (await response.json()) as AgentCreationResponse;
|
||||
|
||||
if (options.start) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
|
|
@ -216,26 +184,18 @@ function buildAgentRequestBody(
|
|||
return body;
|
||||
}
|
||||
|
||||
async function fetchAgentTunnel(agentId: string, accessToken: string) {
|
||||
const response = await fetch(
|
||||
new URL(`agents/${agentId}/tunnel`, env.apiBase),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to create tunnel for agent ${agentId}: ${response.status} ${errorText}`,
|
||||
);
|
||||
async function fetchAgentTunnel(agentId: string) {
|
||||
try {
|
||||
const response = await post<TunnelResponse>(`agents/${agentId}/tunnel`);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
if (error instanceof ApiRequestError) {
|
||||
throw new Error(
|
||||
`Failed to create tunnel for agent ${agentId}: ${error.status} ${error.response || error.statusText}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return (await response.json()) as TunnelResponse;
|
||||
}
|
||||
|
||||
async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) {
|
||||
|
|
|
|||
|
|
@ -259,6 +259,32 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
});
|
||||
});
|
||||
|
||||
// POST /pause - Pause the current agent run (like pressing escape in TUI)
|
||||
app.post("/pause", async (_req: Request, res: Response) => {
|
||||
state.lastActivity = Date.now();
|
||||
|
||||
// Check if there's anything to pause
|
||||
if (!state.isProcessing) {
|
||||
return res.json({
|
||||
success: false,
|
||||
message: "No active processing to pause",
|
||||
});
|
||||
}
|
||||
|
||||
// Abort the current processing
|
||||
if (state.currentAbortController) {
|
||||
state.currentAbortController.abort();
|
||||
}
|
||||
|
||||
// Set isProcessing to false
|
||||
state.isProcessing = false;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Agent run paused",
|
||||
});
|
||||
});
|
||||
|
||||
// GET /diff - Return git diff against main branch
|
||||
app.get("/diff", async (_req: Request, res: Response) => {
|
||||
state.lastActivity = Date.now();
|
||||
|
|
@ -343,6 +369,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
" POST /permission - Approve/reject tool (body: { requestId, approved })",
|
||||
),
|
||||
);
|
||||
console.log(chalk.dim(" POST /pause - Pause the current agent run"));
|
||||
console.log(
|
||||
chalk.dim(" GET /diff - Get git diff against main branch"),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -115,7 +115,7 @@ models:
|
|||
|
||||
if (configExists) {
|
||||
const configContent = await fs.readFile(configPath, "utf-8");
|
||||
expect(configContent).toContain("anthropic/claude-4-sonnet");
|
||||
expect(configContent).toContain("anthropic/claude-sonnet-4-5");
|
||||
expect(configContent).toContain(
|
||||
"ANTHROPIC_API_KEY: TEST-test-invalid-key-format",
|
||||
);
|
||||
|
|
|
|||
209
extensions/cli/src/e2e/headless-permission-error.test.ts
Normal file
209
extensions/cli/src/e2e/headless-permission-error.test.ts
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
/**
|
||||
* E2E test for headless mode permission errors
|
||||
* Verifies that when a tool requires permission in headless mode,
|
||||
* an appropriate error message is displayed suggesting the --auto flag
|
||||
*/
|
||||
import * as http from "http";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
cleanupTestContext,
|
||||
createTestContext,
|
||||
runCLI,
|
||||
} from "../test-helpers/cli-helpers.js";
|
||||
import {
|
||||
cleanupMockLLMServer,
|
||||
setupMockLLMTest,
|
||||
type MockLLMServer,
|
||||
} from "../test-helpers/mock-llm-server.js";
|
||||
|
||||
describe("E2E: Headless Mode Permission Errors", () => {
|
||||
let context: any;
|
||||
let mockServer: MockLLMServer;
|
||||
|
||||
beforeEach(async () => {
|
||||
context = await createTestContext();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (mockServer) {
|
||||
await cleanupMockLLMServer(mockServer);
|
||||
}
|
||||
await cleanupTestContext(context);
|
||||
});
|
||||
it("should display error message with --auto suggestion when tool requires permission", async () => {
|
||||
// Set up mock LLM to return a tool call that requires permission (Write tool)
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
|
||||
req.on("end", () => {
|
||||
if (req.method === "POST" && req.url === "/chat/completions") {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
});
|
||||
|
||||
// Send a Write tool call (requires permission by default)
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
|
||||
);
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
|
||||
);
|
||||
|
||||
// Send usage data
|
||||
res.write(
|
||||
`data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
|
||||
);
|
||||
|
||||
// End the stream
|
||||
res.write(`data: [DONE]\n\n`);
|
||||
res.end();
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end("Not found");
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Run CLI in headless mode without permission flags
|
||||
const result = await runCLI(context, {
|
||||
args: ["-p", "--config", context.configPath, "Create a file test.txt"],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Expect non-zero exit code
|
||||
expect(result.exitCode).toBe(1);
|
||||
|
||||
// Verify the error message contains the expected information
|
||||
expect(result.stderr).toContain("requires permission");
|
||||
expect(result.stderr).toContain("headless mode");
|
||||
expect(result.stderr).toContain("--auto");
|
||||
expect(result.stderr).toContain("--allow");
|
||||
expect(result.stderr).toContain("--exclude");
|
||||
}, 20000);
|
||||
|
||||
it("should succeed with --auto flag when tool requires permission", async () => {
|
||||
// Set up mock LLM to return a Write tool call
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
|
||||
req.on("end", () => {
|
||||
if (req.method === "POST" && req.url === "/chat/completions") {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
});
|
||||
|
||||
// Send a Write tool call
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
|
||||
);
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
|
||||
);
|
||||
|
||||
// Send usage data
|
||||
res.write(
|
||||
`data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
|
||||
);
|
||||
|
||||
// End the stream
|
||||
res.write(`data: [DONE]\n\n`);
|
||||
res.end();
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end("Not found");
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Run CLI with --auto flag
|
||||
const result = await runCLI(context, {
|
||||
args: [
|
||||
"-p",
|
||||
"--auto",
|
||||
"--config",
|
||||
context.configPath,
|
||||
"Create a file test.txt",
|
||||
],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Should succeed
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).not.toContain("requires permission");
|
||||
}, 20000);
|
||||
|
||||
it("should succeed with --allow flag for specific tool", async () => {
|
||||
// Set up mock LLM to return a Write tool call
|
||||
mockServer = await setupMockLLMTest(context, {
|
||||
customHandler: (req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => {
|
||||
body += chunk.toString();
|
||||
});
|
||||
|
||||
req.on("end", () => {
|
||||
if (req.method === "POST" && req.url === "/chat/completions") {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
});
|
||||
|
||||
// Send a Write tool call
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_write","type":"function","function":{"name":"Write"}}]},"index":0}]}\n\n`,
|
||||
);
|
||||
res.write(
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"filepath\\":\\"test.txt\\",\\"content\\":\\"hello\\"}"}}]},"index":0}]}\n\n`,
|
||||
);
|
||||
|
||||
// Send usage data
|
||||
res.write(
|
||||
`data: {"usage":{"prompt_tokens":10,"completion_tokens":20}}\n\n`,
|
||||
);
|
||||
|
||||
// End the stream
|
||||
res.write(`data: [DONE]\n\n`);
|
||||
res.end();
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end("Not found");
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Run CLI with --allow Write flag
|
||||
const result = await runCLI(context, {
|
||||
args: [
|
||||
"-p",
|
||||
"--allow",
|
||||
"Write",
|
||||
"--config",
|
||||
context.configPath,
|
||||
"Create a file test.txt",
|
||||
],
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
// Should succeed
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).not.toContain("requires permission");
|
||||
}, 20000);
|
||||
});
|
||||
205
extensions/cli/src/integration/model-persistence-e2e.test.ts
Normal file
205
extensions/cli/src/integration/model-persistence-e2e.test.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
updateModelName,
|
||||
} from "../auth/workos.js";
|
||||
import * as config from "../config.js";
|
||||
import { ModelService } from "../services/ModelService.js";
|
||||
import { persistModelName } from "../util/modelPersistence.js";
|
||||
|
||||
// Mock the config module
|
||||
vi.mock("../config.js");
|
||||
|
||||
describe("Model Persistence End-to-End", () => {
|
||||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
let mockAuthConfig: AuthenticatedConfig;
|
||||
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Create a temporary directory for testing
|
||||
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
|
||||
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
|
||||
process.env.CONTINUE_GLOBAL_DIR = testDir;
|
||||
|
||||
// Clear GlobalContext for clean test state
|
||||
persistModelName(null);
|
||||
|
||||
mockAssistant = {
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
name: "GPT-4",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
name: "Claude 3.5 Sonnet",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-opus-20240229",
|
||||
name: "Claude 3 Opus",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000, // 1 hour from now
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
// Setup default mock behavior
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Cleanup
|
||||
if (fs.existsSync(testDir)) {
|
||||
fs.rmSync(testDir, { recursive: true });
|
||||
}
|
||||
if (originalContinueHome) {
|
||||
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
|
||||
} else {
|
||||
delete process.env.CONTINUE_GLOBAL_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
test("should restore model selection after restart", async () => {
|
||||
// Step 1: Initial session - user starts with default model (GPT-4)
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
let service = new ModelService();
|
||||
let state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
console.log("Initial model:", state.model?.name);
|
||||
expect(state.model?.name).toBe("GPT-4");
|
||||
|
||||
// Step 2: User switches to Claude 3.5 Sonnet (index 1)
|
||||
await service.switchModel(1);
|
||||
state = service.getState();
|
||||
|
||||
console.log("After switch:", state.model?.name);
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Step 3: Persist the model choice (this should happen in useModelSelector)
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it was saved to auth.json
|
||||
const savedConfig = loadAuthConfig();
|
||||
console.log("Saved model name:", getModelName(savedConfig));
|
||||
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Step 4: Simulate restart - create new service instance
|
||||
// Load fresh auth config from disk (this is what the real code does)
|
||||
const freshAuthConfig = loadAuthConfig();
|
||||
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
|
||||
|
||||
service = new ModelService();
|
||||
state = await service.initialize(mockAssistant, freshAuthConfig);
|
||||
|
||||
// Step 5: Verify the persisted model is restored
|
||||
console.log("After restart:", state.model?.name);
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
expect(state.model?.provider).toBe("anthropic");
|
||||
});
|
||||
|
||||
test("should handle model name mismatch gracefully", async () => {
|
||||
// Save auth config with a model that doesn't exist
|
||||
mockAuthConfig.modelName = "Non-existent Model";
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
|
||||
const service = new ModelService();
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
// Should fall back to first available model (GPT-4)
|
||||
expect(state.model?.name).toBe("GPT-4");
|
||||
});
|
||||
|
||||
test("should check both name and model fields when matching", async () => {
|
||||
// Some configs might have model field instead of name
|
||||
const assistantWithModelField = {
|
||||
...mockAssistant,
|
||||
models: [
|
||||
{
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
// No name field, just model
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
// No name field, just model
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig.modelName = "claude-3-5-sonnet-20241022";
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
|
||||
const service = new ModelService();
|
||||
const state = await service.initialize(
|
||||
assistantWithModelField,
|
||||
mockAuthConfig,
|
||||
);
|
||||
|
||||
// Should match by model field
|
||||
expect(state.model?.model).toBe("claude-3-5-sonnet-20241022");
|
||||
});
|
||||
|
||||
test("should persist model through multiple switches", async () => {
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
const service = new ModelService();
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
// Switch to Claude 3.5 Sonnet
|
||||
await service.switchModel(1);
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getModelName(loadAuthConfig())).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Switch to Claude 3 Opus
|
||||
await service.switchModel(2);
|
||||
updateModelName("Claude 3 Opus");
|
||||
expect(getModelName(loadAuthConfig())).toBe("Claude 3 Opus");
|
||||
|
||||
// Restart and verify last selection
|
||||
const freshAuthConfig = loadAuthConfig();
|
||||
console.log("Fresh auth config model name:", getModelName(freshAuthConfig));
|
||||
|
||||
const newService = new ModelService();
|
||||
const state = await newService.initialize(mockAssistant, freshAuthConfig);
|
||||
expect(state.model?.name).toBe("Claude 3 Opus");
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,245 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
updateModelName,
|
||||
} from "../auth/workos.js";
|
||||
import * as config from "../config.js";
|
||||
import { ModelService } from "../services/ModelService.js";
|
||||
import {
|
||||
getPersistedModelName,
|
||||
persistModelName,
|
||||
} from "../util/modelPersistence.js";
|
||||
|
||||
// Mock the config module
|
||||
vi.mock("../config.js");
|
||||
|
||||
describe("Model Persistence for Unauthenticated Users", () => {
|
||||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Create a temporary directory for testing
|
||||
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
|
||||
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
|
||||
process.env.CONTINUE_GLOBAL_DIR = testDir;
|
||||
|
||||
// Clear GlobalContext for clean test state
|
||||
persistModelName(null);
|
||||
|
||||
mockAssistant = {
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
name: "GPT-4",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
name: "Claude 3.5 Sonnet",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-opus-20240229",
|
||||
name: "Claude 3 Opus",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
// Setup default mock behavior
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Cleanup
|
||||
if (fs.existsSync(testDir)) {
|
||||
fs.rmSync(testDir, { recursive: true });
|
||||
}
|
||||
if (originalContinueHome) {
|
||||
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
|
||||
} else {
|
||||
delete process.env.CONTINUE_GLOBAL_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
test("should persist model selection for logged-out users", () => {
|
||||
// User is logged out (no auth config)
|
||||
const authConfig = loadAuthConfig();
|
||||
expect(authConfig).toBeNull();
|
||||
|
||||
// User switches model
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it was saved to GlobalContext
|
||||
const persistedModel = getPersistedModelName();
|
||||
expect(persistedModel).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// Verify getModelName returns it for null config
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should restore model selection on next session for logged-out users", async () => {
|
||||
// Session 1: User is logged out and switches model
|
||||
const authConfig = loadAuthConfig();
|
||||
expect(authConfig).toBeNull();
|
||||
|
||||
const modelService = new ModelService();
|
||||
await modelService.initialize(mockAssistant, authConfig);
|
||||
|
||||
await modelService.switchModel(1);
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Session 2: User reopens CLI (still logged out)
|
||||
const newAuthConfig = loadAuthConfig();
|
||||
expect(newAuthConfig).toBeNull();
|
||||
|
||||
const newModelService = new ModelService();
|
||||
const state = await newModelService.initialize(
|
||||
mockAssistant,
|
||||
newAuthConfig,
|
||||
);
|
||||
|
||||
// Should restore Claude 3.5 Sonnet
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should handle multiple model switches for logged-out users", () => {
|
||||
updateModelName("GPT-4");
|
||||
expect(getModelName(null)).toBe("GPT-4");
|
||||
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
updateModelName("Claude 3 Opus");
|
||||
expect(getModelName(null)).toBe("Claude 3 Opus");
|
||||
});
|
||||
|
||||
test("should clear model selection when set to null", () => {
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getModelName(null)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
updateModelName(null);
|
||||
expect(getModelName(null)).toBeNull();
|
||||
});
|
||||
|
||||
test("should preserve GlobalContext model when user logs in", () => {
|
||||
// User is logged out with a persisted model
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// User logs in (simulated by having auth.json)
|
||||
const authPath = path.join(testDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
}),
|
||||
);
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
expect(authConfig).not.toBeNull();
|
||||
|
||||
// GlobalContext model should still exist
|
||||
expect(getPersistedModelName()).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// When auth config has no modelName, it should fall back to GlobalContext
|
||||
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should use auth config model when both exist", () => {
|
||||
// Clear previous state
|
||||
updateModelName(null);
|
||||
|
||||
// Set GlobalContext model
|
||||
updateModelName("GPT-4");
|
||||
expect(getPersistedModelName()).toBe("GPT-4");
|
||||
|
||||
// Create auth config with different model
|
||||
const authPath = path.join(testDir, "auth.json");
|
||||
fs.writeFileSync(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
modelName: "Claude 3.5 Sonnet",
|
||||
}),
|
||||
);
|
||||
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
// Auth config should take precedence
|
||||
expect(getModelName(authConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should not save to GlobalContext when using CONTINUE_API_KEY", () => {
|
||||
// Clear any existing model
|
||||
updateModelName(null);
|
||||
expect(getPersistedModelName()).toBeNull();
|
||||
|
||||
// Capture original value to restore after test
|
||||
const originalApiKey = process.env.CONTINUE_API_KEY;
|
||||
process.env.CONTINUE_API_KEY = "test-api-key";
|
||||
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Should not be saved to GlobalContext
|
||||
expect(getPersistedModelName()).toBeNull();
|
||||
|
||||
// Restore original value
|
||||
if (originalApiKey === undefined) {
|
||||
delete process.env.CONTINUE_API_KEY;
|
||||
} else {
|
||||
process.env.CONTINUE_API_KEY = originalApiKey;
|
||||
}
|
||||
});
|
||||
|
||||
test("should work across config changes for logged-out users", async () => {
|
||||
// User switches model with one config
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
const modelService = new ModelService();
|
||||
let state = await modelService.initialize(mockAssistant, null);
|
||||
expect(state.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// User switches to a different model
|
||||
await modelService.switchModel(2);
|
||||
updateModelName("Claude 3 Opus");
|
||||
|
||||
// Create new service (simulating restart)
|
||||
const newModelService = new ModelService();
|
||||
state = await newModelService.initialize(mockAssistant, null);
|
||||
expect(state.model?.name).toBe("Claude 3 Opus");
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
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
|
||||
vi.mock("../config.js");
|
||||
|
||||
describe("Model Persistence User Flow", () => {
|
||||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
let mockAuthConfig: AuthenticatedConfig;
|
||||
const mockLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Create a temporary directory for testing
|
||||
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
|
||||
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
|
||||
process.env.CONTINUE_GLOBAL_DIR = testDir;
|
||||
|
||||
mockAssistant = {
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
name: "GPT-4",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-5-sonnet-20241022",
|
||||
name: "Claude 3.5 Sonnet",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: "anthropic",
|
||||
model: "claude-3-opus-20240229",
|
||||
name: "Claude 3 Opus",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000, // 1 hour from now
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
// Setup default mock behavior
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
vi.mocked(config.createLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Cleanup
|
||||
if (fs.existsSync(testDir)) {
|
||||
fs.rmSync(testDir, { recursive: true });
|
||||
}
|
||||
if (originalContinueHome) {
|
||||
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
|
||||
} else {
|
||||
delete process.env.CONTINUE_GLOBAL_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
test("should persist model choice exactly as user experiences it", async () => {
|
||||
console.log("\n=== SESSION 1: User opens cn and switches model ===");
|
||||
|
||||
// Session 1: User starts CLI
|
||||
// Save initial auth config (what happens after login)
|
||||
saveAuthConfig(mockAuthConfig);
|
||||
console.log("1. Initial auth.json saved");
|
||||
|
||||
// Initialize ModelService (what happens on CLI start)
|
||||
const modelService = new ModelService();
|
||||
const state = await modelService.initialize(mockAssistant, mockAuthConfig);
|
||||
console.log("2. Initial model:", state.model?.name);
|
||||
expect(state.model?.name).toBe("GPT-4");
|
||||
|
||||
// User switches to Claude 3.5 Sonnet via UI
|
||||
await modelService.switchModel(1);
|
||||
const modelInfo = modelService.getModelInfo();
|
||||
console.log("3. User switched to:", modelInfo?.name);
|
||||
expect(modelInfo?.name).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// useModelSelector calls updateModelName
|
||||
const { updateModelName } = await import("../auth/workos.js");
|
||||
const updatedAuthConfig = updateModelName("Claude 3.5 Sonnet");
|
||||
console.log("4. Model name persisted to disk");
|
||||
|
||||
// Verify it was saved
|
||||
const savedConfig = loadAuthConfig();
|
||||
console.log("5. Read back from disk:", getModelName(savedConfig));
|
||||
expect(getModelName(savedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
|
||||
// User closes CLI
|
||||
console.log("6. User exits CLI\n");
|
||||
|
||||
console.log("=== SESSION 2: User reopens cn ===");
|
||||
|
||||
// Session 2: User restarts CLI
|
||||
// Initialize AuthService (loads from disk)
|
||||
const authService = new AuthService();
|
||||
const authState = await authService.initialize();
|
||||
console.log(
|
||||
"7. AuthService loaded, modelName in auth:",
|
||||
getModelName(authState.authConfig),
|
||||
);
|
||||
|
||||
// Initialize ModelService with fresh auth state
|
||||
const newModelService = new ModelService();
|
||||
const newState = await newModelService.initialize(
|
||||
mockAssistant,
|
||||
authState.authConfig,
|
||||
);
|
||||
console.log(
|
||||
"8. ModelService initialized with model:",
|
||||
newState.model?.name,
|
||||
);
|
||||
|
||||
// EXPECTATION: Should restore Claude 3.5 Sonnet
|
||||
expect(newState.model?.name).toBe("Claude 3.5 Sonnet");
|
||||
expect(newState.model?.provider).toBe("anthropic");
|
||||
console.log("✅ Model persisted correctly!\n");
|
||||
});
|
||||
});
|
||||
194
extensions/cli/src/integration/model-persistence.test.ts
Normal file
194
extensions/cli/src/integration/model-persistence.test.ts
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
updateModelName,
|
||||
} from "../auth/workos.js";
|
||||
import { persistModelName } from "../util/modelPersistence.js";
|
||||
|
||||
describe("Model Persistence Integration", () => {
|
||||
let testDir: string;
|
||||
let originalContinueHome: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create a temporary directory for testing
|
||||
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
|
||||
originalContinueHome = process.env.CONTINUE_GLOBAL_DIR;
|
||||
process.env.CONTINUE_GLOBAL_DIR = testDir;
|
||||
|
||||
// Clear GlobalContext for clean test state
|
||||
persistModelName(null);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Cleanup
|
||||
if (fs.existsSync(testDir)) {
|
||||
fs.rmSync(testDir, { recursive: true });
|
||||
}
|
||||
if (originalContinueHome) {
|
||||
process.env.CONTINUE_GLOBAL_DIR = originalContinueHome;
|
||||
} else {
|
||||
delete process.env.CONTINUE_GLOBAL_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
test("should persist model name when user selects a model", () => {
|
||||
// Create initial auth config without model name
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
// User selects a model
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config and verify model name is persisted
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should update model name when user switches models", () => {
|
||||
// Create initial auth config with a model
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
modelName: "GPT-4",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
// User switches to a different model
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config and verify new model name
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBe("Claude 3.5 Sonnet");
|
||||
});
|
||||
|
||||
test("should preserve other auth config fields when updating model", () => {
|
||||
// Create initial auth config
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
configUri: "slug://owner/my-config",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
// Update model name
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config and verify all fields are preserved
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(loadedConfig).toMatchObject({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
organizationId: "test-org",
|
||||
configUri: "slug://owner/my-config",
|
||||
modelName: "Claude 3.5 Sonnet",
|
||||
});
|
||||
});
|
||||
|
||||
test("should clear model name when set to null", () => {
|
||||
// Create initial auth config with a model
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
modelName: "GPT-4",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
|
||||
// Clear model name
|
||||
updateModelName(null);
|
||||
|
||||
// Load config and verify model name is cleared
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBeNull();
|
||||
});
|
||||
|
||||
test("should return null for model name when not authenticated and no GlobalContext", () => {
|
||||
// No auth config exists and no GlobalContext model
|
||||
persistModelName(null); // Ensure GlobalContext is clear
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBeNull();
|
||||
});
|
||||
|
||||
test("should not persist model name when using CONTINUE_API_KEY", () => {
|
||||
// Clear GlobalContext first
|
||||
persistModelName(null);
|
||||
|
||||
// Capture original value to restore after test
|
||||
const originalApiKey = process.env.CONTINUE_API_KEY;
|
||||
// Set environment variable
|
||||
process.env.CONTINUE_API_KEY = "test-api-key";
|
||||
|
||||
// Try to update model name
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Load config - should be environment auth config without model name
|
||||
const loadedConfig = loadAuthConfig();
|
||||
expect(getModelName(loadedConfig)).toBeNull();
|
||||
|
||||
// Restore original value
|
||||
if (originalApiKey === undefined) {
|
||||
delete process.env.CONTINUE_API_KEY;
|
||||
} else {
|
||||
process.env.CONTINUE_API_KEY = originalApiKey;
|
||||
}
|
||||
});
|
||||
|
||||
test("should persist model name in auth.json file with correct format", () => {
|
||||
// Create and save auth config
|
||||
const authConfig: AuthenticatedConfig = {
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: "test-org",
|
||||
};
|
||||
|
||||
saveAuthConfig(authConfig);
|
||||
updateModelName("Claude 3.5 Sonnet");
|
||||
|
||||
// Read the raw file content
|
||||
const authPath = path.join(testDir, "auth.json");
|
||||
const rawContent = fs.readFileSync(authPath, "utf8");
|
||||
const parsedContent = JSON.parse(rawContent);
|
||||
|
||||
// Verify the file structure
|
||||
expect(parsedContent).toHaveProperty("userId", "test-user");
|
||||
expect(parsedContent).toHaveProperty("userEmail", "test@example.com");
|
||||
expect(parsedContent).toHaveProperty("organizationId", "test-org");
|
||||
expect(parsedContent).toHaveProperty("modelName", "Claude 3.5 Sonnet");
|
||||
|
||||
// Verify it's pretty-printed (has indentation)
|
||||
expect(rawContent).toContain("\n ");
|
||||
});
|
||||
});
|
||||
66
extensions/cli/src/stream/streamChatResponse.helpers.test.ts
Normal file
66
extensions/cli/src/stream/streamChatResponse.helpers.test.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { PreprocessedToolCall } from "../tools/types.js";
|
||||
|
||||
import { handleHeadlessPermission } from "./streamChatResponse.helpers.js";
|
||||
|
||||
describe("streamChatResponse.helpers", () => {
|
||||
describe("handleHeadlessPermission", () => {
|
||||
it("should display error message and exit when tool requires permission in headless mode", async () => {
|
||||
// Mock the tool call
|
||||
const toolCall: PreprocessedToolCall = {
|
||||
id: "call_123",
|
||||
name: "Write",
|
||||
arguments: { filepath: "test.txt", content: "hello" },
|
||||
argumentsStr: '{"filepath":"test.txt","content":"hello"}',
|
||||
startNotified: false,
|
||||
tool: {
|
||||
name: "Write",
|
||||
displayName: "Write",
|
||||
description: "Write to a file",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
},
|
||||
run: vi.fn(),
|
||||
isBuiltIn: true,
|
||||
},
|
||||
};
|
||||
|
||||
// Mock safeStderr to capture output
|
||||
const stderrOutputs: string[] = [];
|
||||
vi.doMock("../init.js", () => ({
|
||||
safeStderr: (message: string) => {
|
||||
stderrOutputs.push(message);
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock gracefulExit to prevent actual process exit
|
||||
let exitCode: number | undefined;
|
||||
vi.doMock("../util/exit.js", () => ({
|
||||
gracefulExit: async (code: number) => {
|
||||
exitCode = code;
|
||||
},
|
||||
}));
|
||||
|
||||
// Call the function (it should exit gracefully)
|
||||
try {
|
||||
await handleHeadlessPermission(toolCall);
|
||||
} catch (error) {
|
||||
// Expected to throw after exit
|
||||
}
|
||||
|
||||
// Verify error message was displayed
|
||||
const fullOutput = stderrOutputs.join("");
|
||||
expect(fullOutput).toContain("requires permission");
|
||||
expect(fullOutput).toContain("headless mode");
|
||||
expect(fullOutput).toContain("--auto");
|
||||
expect(fullOutput).toContain("--allow");
|
||||
expect(fullOutput).toContain("--exclude");
|
||||
expect(fullOutput).toContain("Write");
|
||||
|
||||
// Verify it tried to exit with code 1
|
||||
expect(exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -51,25 +51,30 @@ export function handlePermissionDenied(
|
|||
}
|
||||
|
||||
// Helper function to handle headless mode permission
|
||||
export function handleHeadlessPermission(
|
||||
export async function handleHeadlessPermission(
|
||||
toolCall: PreprocessedToolCall,
|
||||
): never {
|
||||
): Promise<never> {
|
||||
const allBuiltinTools = getAllBuiltinTools();
|
||||
const tool = allBuiltinTools.find((t) => t.name === toolCall.name);
|
||||
const toolName = tool?.displayName || toolCall.name;
|
||||
|
||||
console.error(
|
||||
`Error: Tool '${toolName}' requires permission but cn is running in headless mode.`,
|
||||
// Import safeStderr to bypass console blocking in headless mode
|
||||
const { safeStderr } = await import("../init.js");
|
||||
safeStderr(
|
||||
`Error: Tool '${toolName}' requires permission but cn is running in headless mode.\n`,
|
||||
);
|
||||
console.error(`If you want to allow this tool, use --allow ${toolName}.`);
|
||||
console.error(
|
||||
`If you don't want the tool to be included, use --exclude ${toolName}.`,
|
||||
safeStderr(
|
||||
`If you want to allow all tools without asking, use cn -p --auto "your prompt".\n`,
|
||||
);
|
||||
safeStderr(`If you want to allow this tool, use --allow ${toolName}.\n`);
|
||||
safeStderr(
|
||||
`If you don't want the tool to be included, use --exclude ${toolName}.\n`,
|
||||
);
|
||||
|
||||
// Use graceful exit to flush telemetry even in headless denial
|
||||
// Note: We purposely trigger an async exit without awaiting in this sync path
|
||||
import("../util/exit.js").then(({ gracefulExit }) => gracefulExit(1));
|
||||
// Throw to satisfy the never return type; process will exit shortly
|
||||
const { gracefulExit } = await import("../util/exit.js");
|
||||
await gracefulExit(1);
|
||||
// This line will never be reached, but TypeScript needs it for the 'never' return type
|
||||
throw new Error("Exiting due to headless permission requirement");
|
||||
}
|
||||
|
||||
|
|
@ -133,7 +138,7 @@ export async function checkToolPermissionApproval(
|
|||
return { approved: true };
|
||||
} else if (permissionCheck.permission === "ask") {
|
||||
if (isHeadless) {
|
||||
handleHeadlessPermission(toolCall);
|
||||
await handleHeadlessPermission(toolCall);
|
||||
}
|
||||
const userApproved = await requestUserPermission(toolCall, callbacks);
|
||||
return userApproved
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import { multiEditTool } from "./multiEdit.js";
|
|||
import { readFileTool } from "./readFile.js";
|
||||
import { runTerminalCommandTool } from "./runTerminalCommand.js";
|
||||
import { searchCodeTool } from "./searchCode.js";
|
||||
import { statusTool } from "./status.js";
|
||||
import {
|
||||
type Tool,
|
||||
type ToolCall,
|
||||
|
|
@ -70,6 +71,11 @@ function getDynamicTools(): Tool[] {
|
|||
// Service not ready yet, no dynamic tools
|
||||
}
|
||||
|
||||
// Add beta status tool if --beta-status-tool flag is present
|
||||
if (process.argv.includes("--beta-status-tool")) {
|
||||
dynamicTools.push(statusTool);
|
||||
}
|
||||
|
||||
return dynamicTools;
|
||||
}
|
||||
|
||||
|
|
|
|||
78
extensions/cli/src/tools/status.ts
Normal file
78
extensions/cli/src/tools/status.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import {
|
||||
ApiRequestError,
|
||||
AuthenticationRequiredError,
|
||||
post,
|
||||
} from "../util/apiClient.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { Tool } from "./types.js";
|
||||
|
||||
/**
|
||||
* Extract the agent ID from the --id command line flag
|
||||
*/
|
||||
function getAgentIdFromArgs(): string | undefined {
|
||||
const args = process.argv;
|
||||
const idIndex = args.indexOf("--id");
|
||||
if (idIndex !== -1 && idIndex + 1 < args.length) {
|
||||
return args[idIndex + 1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export const statusTool: Tool = {
|
||||
name: "Status",
|
||||
displayName: "Status",
|
||||
description: `Set the current status of your task for the user to see
|
||||
|
||||
The available statuses are:
|
||||
- PLANNING: You are creating a plan before beginning implementation
|
||||
- WORKING: The task is in progress
|
||||
- DONE: The task is complete
|
||||
- BLOCKED: You need further information from the user in order to proceed
|
||||
|
||||
You should use this tool to notify the user whenever the state of your work changes. By default, the status is assumed to be "PLANNING" prior to you setting a different status.`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["status"],
|
||||
properties: {
|
||||
status: {
|
||||
type: "string",
|
||||
description: "The status value to set",
|
||||
},
|
||||
},
|
||||
},
|
||||
readonly: true,
|
||||
isBuiltIn: true,
|
||||
run: async (args: { status: string }): Promise<string> => {
|
||||
try {
|
||||
// Get agent ID from --id flag
|
||||
const agentId = getAgentIdFromArgs();
|
||||
if (!agentId) {
|
||||
const errorMessage =
|
||||
"Agent ID is required. Please use the --id flag with cn serve.";
|
||||
logger.error(errorMessage);
|
||||
return `Error: ${errorMessage}`;
|
||||
}
|
||||
|
||||
// Call the API endpoint using shared client
|
||||
await post(`agents/${agentId}/status`, { status: args.status });
|
||||
|
||||
logger.info(`Status: ${args.status}`);
|
||||
return `Status set: ${args.status}`;
|
||||
} catch (error) {
|
||||
if (error instanceof AuthenticationRequiredError) {
|
||||
logger.error(error.message);
|
||||
return "Error: Authentication required";
|
||||
}
|
||||
|
||||
if (error instanceof ApiRequestError) {
|
||||
return `Error setting status: ${error.status} ${error.response || error.statusText}`;
|
||||
}
|
||||
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
logger.error(`Error setting status: ${errorMessage}`);
|
||||
return `Error setting status: ${errorMessage}`;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -264,6 +264,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
configPath,
|
||||
setChatHistory,
|
||||
handleClear,
|
||||
setStaticRefreshTrigger,
|
||||
);
|
||||
|
||||
// Session selection handler
|
||||
|
|
|
|||
|
|
@ -611,6 +611,30 @@ describe("TextBuffer", () => {
|
|||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it("should limit ctrl+u deletion to current line", () => {
|
||||
const text = "first line\nsecond line\nthird";
|
||||
buffer.setText(text);
|
||||
buffer.setCursor(text.indexOf("second line") + "second line".length);
|
||||
|
||||
const result = buffer.handleInput("u", { ctrl: true } as any);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe("first line\n\nthird");
|
||||
expect(buffer.cursor).toBe("first line\n".length);
|
||||
});
|
||||
|
||||
it("should limit ctrl+k deletion to current line", () => {
|
||||
const text = "first line\nsecond line\nthird";
|
||||
buffer.setText(text);
|
||||
buffer.setCursor(text.indexOf("second line"));
|
||||
|
||||
const result = buffer.handleInput("k", { ctrl: true } as any);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe("first line\n\nthird");
|
||||
expect(buffer.cursor).toBe(text.indexOf("second line"));
|
||||
});
|
||||
|
||||
it("should handle arrow keys", () => {
|
||||
let result = buffer.handleInput("", { leftArrow: true } as any);
|
||||
expect(result).toBe(true);
|
||||
|
|
@ -644,6 +668,38 @@ describe("TextBuffer", () => {
|
|||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it("should delete to start of line with meta+backspace", () => {
|
||||
const text = "first line\nsecond line\nthird line";
|
||||
buffer.setText(text);
|
||||
const cursorPosition = text.indexOf("second line") + "second line".length;
|
||||
buffer.setCursor(cursorPosition);
|
||||
|
||||
const result = buffer.handleInput("", {
|
||||
meta: true,
|
||||
backspace: true,
|
||||
} as any);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe("first line\n\nthird line");
|
||||
expect(buffer.cursor).toBe("first line\n".length);
|
||||
});
|
||||
|
||||
it("should delete to end of line with meta+delete", () => {
|
||||
const text = "first line\nsecond line\nthird line";
|
||||
buffer.setText(text);
|
||||
const cursorPosition = text.indexOf("second line");
|
||||
buffer.setCursor(cursorPosition);
|
||||
|
||||
const result = buffer.handleInput("", {
|
||||
meta: true,
|
||||
delete: true,
|
||||
} as any);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe("first line\n\nthird line");
|
||||
expect(buffer.cursor).toBe(cursorPosition);
|
||||
});
|
||||
|
||||
it("should handle option key sequences", () => {
|
||||
const result = buffer.handleInput("\u001b\u007f", {} as any);
|
||||
expect(result).toBe(true);
|
||||
|
|
|
|||
|
|
@ -137,6 +137,38 @@ export class TextBuffer {
|
|||
}
|
||||
}
|
||||
|
||||
private deleteLineBackward(): void {
|
||||
if (this._cursor === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastNewline = this._text.lastIndexOf("\n", this._cursor - 1);
|
||||
const lineStart = lastNewline === -1 ? 0 : lastNewline + 1;
|
||||
|
||||
if (lineStart === this._cursor) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._text =
|
||||
this._text.slice(0, lineStart) + this._text.slice(this._cursor);
|
||||
this._cursor = lineStart;
|
||||
}
|
||||
|
||||
private deleteLineForward(): void {
|
||||
if (this._cursor >= this._text.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextNewline = this._text.indexOf("\n", this._cursor);
|
||||
const lineEnd = nextNewline === -1 ? this._text.length : nextNewline;
|
||||
|
||||
if (lineEnd === this._cursor) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._text = this._text.slice(0, this._cursor) + this._text.slice(lineEnd);
|
||||
}
|
||||
|
||||
moveToStart(): void {
|
||||
this._cursor = 0;
|
||||
}
|
||||
|
|
@ -402,13 +434,10 @@ export class TextBuffer {
|
|||
this.moveToEnd();
|
||||
return true;
|
||||
case "u":
|
||||
// Delete from cursor to start of line
|
||||
this._text = this._text.slice(this._cursor);
|
||||
this._cursor = 0;
|
||||
this.deleteLineBackward();
|
||||
return true;
|
||||
case "k":
|
||||
// Delete from cursor to end of line
|
||||
this._text = this._text.slice(0, this._cursor);
|
||||
this.deleteLineForward();
|
||||
return true;
|
||||
case "w":
|
||||
this.deleteWordBackward();
|
||||
|
|
@ -422,8 +451,12 @@ export class TextBuffer {
|
|||
}
|
||||
|
||||
private handleMetaKey(input: string, key: Key): boolean {
|
||||
if (key.backspace || key.delete) {
|
||||
this.deleteWordBackward();
|
||||
if (key.backspace) {
|
||||
this.deleteLineBackward();
|
||||
return true;
|
||||
}
|
||||
if (key.delete) {
|
||||
this.deleteLineForward();
|
||||
return true;
|
||||
}
|
||||
if (key.leftArrow) {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
serviceContainer,
|
||||
services,
|
||||
} from "../../services/index.js";
|
||||
import { ModelServiceState } from "../../services/types.js";
|
||||
import { AuthServiceState, ModelServiceState } from "../../services/types.js";
|
||||
import { useNavigation } from "../context/NavigationContext.js";
|
||||
|
||||
interface ModelOption {
|
||||
|
|
@ -21,11 +21,13 @@ interface UseModelSelectorProps {
|
|||
messageType: "system";
|
||||
}) => void;
|
||||
onModelSwitch?: () => void;
|
||||
onRefreshUI?: () => void;
|
||||
}
|
||||
|
||||
export function useModelSelector({
|
||||
onMessage,
|
||||
onModelSwitch,
|
||||
onRefreshUI,
|
||||
}: UseModelSelectorProps) {
|
||||
const { closeCurrentScreen } = useNavigation();
|
||||
|
||||
|
|
@ -44,8 +46,17 @@ export function useModelSelector({
|
|||
);
|
||||
|
||||
// Persist the model choice using the actual model name
|
||||
// and update the auth service state to reflect the change
|
||||
if (modelInfo?.name) {
|
||||
updateModelName(modelInfo.name);
|
||||
const updatedAuthConfig = updateModelName(modelInfo.name);
|
||||
|
||||
// Update the AUTH service state in the container with the new config
|
||||
// This ensures that when MODEL service is reloaded, it gets the updated auth config
|
||||
const currentAuthState = services.auth.getState();
|
||||
serviceContainer.set<AuthServiceState>(SERVICE_NAMES.AUTH, {
|
||||
...currentAuthState,
|
||||
authConfig: updatedAuthConfig,
|
||||
});
|
||||
}
|
||||
|
||||
onMessage({
|
||||
|
|
@ -58,6 +69,11 @@ export function useModelSelector({
|
|||
if (onModelSwitch) {
|
||||
onModelSwitch();
|
||||
}
|
||||
|
||||
// Force UI refresh to update the IntroMessage with new model
|
||||
if (onRefreshUI) {
|
||||
onRefreshUI();
|
||||
}
|
||||
} catch (error: any) {
|
||||
onMessage({
|
||||
role: "system",
|
||||
|
|
|
|||
|
|
@ -175,6 +175,7 @@ export function useSelectors(
|
|||
configPath: string | undefined,
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<any[]>>,
|
||||
handleClear: () => void,
|
||||
setStaticRefreshTrigger?: React.Dispatch<React.SetStateAction<number>>,
|
||||
): {
|
||||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
|
|
@ -205,6 +206,12 @@ export function useSelectors(
|
|||
},
|
||||
]);
|
||||
},
|
||||
onRefreshUI: () => {
|
||||
// Force a UI refresh to update the IntroMessage with new model
|
||||
if (setStaticRefreshTrigger) {
|
||||
setStaticRefreshTrigger((prev) => prev + 1);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
|
|||
283
extensions/cli/src/util/apiClient.test.ts
Normal file
283
extensions/cli/src/util/apiClient.test.ts
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
ApiRequestError,
|
||||
AuthenticationRequiredError,
|
||||
del,
|
||||
get,
|
||||
makeAuthenticatedRequest,
|
||||
post,
|
||||
put,
|
||||
} from "./apiClient.js";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../auth/workos.js", () => ({
|
||||
loadAuthConfig: vi.fn(),
|
||||
getAccessToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../env.js", () => ({
|
||||
env: {
|
||||
apiBase: "https://api.continue.dev",
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
|
||||
describe("apiClient", () => {
|
||||
let mockLoadAuthConfig: any;
|
||||
let mockGetAccessToken: any;
|
||||
const mockFetch = vi.mocked(global.fetch);
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Get mocked functions
|
||||
const authModule = await import("../auth/workos.js");
|
||||
mockLoadAuthConfig = vi.mocked(authModule.loadAuthConfig);
|
||||
mockGetAccessToken = vi.mocked(authModule.getAccessToken);
|
||||
|
||||
// Setup default successful authentication
|
||||
mockLoadAuthConfig.mockReturnValue({ some: "config" });
|
||||
mockGetAccessToken.mockReturnValue("test-access-token");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("makeAuthenticatedRequest", () => {
|
||||
test("should make successful API request", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: { get: vi.fn().mockReturnValue("application/json") },
|
||||
json: vi.fn().mockResolvedValue({ data: "test" }),
|
||||
} as unknown as Response);
|
||||
|
||||
const result = await makeAuthenticatedRequest("test-endpoint", {
|
||||
method: "POST",
|
||||
body: { key: "value" },
|
||||
});
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("test-endpoint", "https://api.continue.dev"),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-access-token",
|
||||
},
|
||||
body: JSON.stringify({ key: "value" }),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
data: { data: "test" },
|
||||
status: 200,
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle non-JSON response", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: { get: vi.fn().mockReturnValue("text/plain") },
|
||||
text: vi.fn().mockResolvedValue("plain text response"),
|
||||
} as unknown as Response);
|
||||
|
||||
const result = await makeAuthenticatedRequest("test-endpoint");
|
||||
|
||||
expect(result.data).toBe("plain text response");
|
||||
});
|
||||
|
||||
test("should throw AuthenticationRequiredError when no auth config", async () => {
|
||||
mockLoadAuthConfig.mockReturnValue(null);
|
||||
|
||||
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
|
||||
AuthenticationRequiredError,
|
||||
);
|
||||
});
|
||||
|
||||
test("should throw AuthenticationRequiredError when no access token", async () => {
|
||||
mockGetAccessToken.mockReturnValue(null);
|
||||
|
||||
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
|
||||
AuthenticationRequiredError,
|
||||
);
|
||||
});
|
||||
|
||||
test("should throw ApiRequestError on API error", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
statusText: "Not Found",
|
||||
headers: { get: vi.fn() },
|
||||
text: vi.fn().mockResolvedValue("Resource not found"),
|
||||
} as unknown as Response);
|
||||
|
||||
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
|
||||
ApiRequestError,
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle network error", async () => {
|
||||
mockFetch.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
await expect(makeAuthenticatedRequest("test-endpoint")).rejects.toThrow(
|
||||
"Request failed: Network error",
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle string body", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: { get: vi.fn().mockReturnValue("application/json") },
|
||||
json: vi.fn().mockResolvedValue({ success: true }),
|
||||
} as unknown as Response);
|
||||
|
||||
await makeAuthenticatedRequest("test-endpoint", {
|
||||
method: "POST",
|
||||
body: "raw string body",
|
||||
});
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
body: "raw string body",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("should merge custom headers", async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: { get: vi.fn().mockReturnValue("application/json") },
|
||||
json: vi.fn().mockResolvedValue({}),
|
||||
} as unknown as Response);
|
||||
|
||||
await makeAuthenticatedRequest("test-endpoint", {
|
||||
headers: { "Custom-Header": "custom-value" },
|
||||
});
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-access-token",
|
||||
"Custom-Header": "custom-value",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("convenience methods", () => {
|
||||
beforeEach(() => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: { get: vi.fn().mockReturnValue("application/json") },
|
||||
json: vi.fn().mockResolvedValue({ success: true }),
|
||||
} as unknown as Response);
|
||||
});
|
||||
|
||||
test("get method should make GET request", async () => {
|
||||
await get("test-endpoint");
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
test("post method should make POST request", async () => {
|
||||
await post("test-endpoint", { data: "test" });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ data: "test" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("put method should make PUT request", async () => {
|
||||
await put("test-endpoint", { data: "test" });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ data: "test" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("del method should make DELETE request", async () => {
|
||||
await del("test-endpoint");
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.any(URL),
|
||||
expect.objectContaining({ method: "DELETE" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("error classes", () => {
|
||||
test("AuthenticationRequiredError should have correct properties", () => {
|
||||
const error = new AuthenticationRequiredError();
|
||||
|
||||
expect(error.name).toBe("AuthenticationRequiredError");
|
||||
expect(error.message).toBe(
|
||||
"Not authenticated. Please run 'cn login' first.",
|
||||
);
|
||||
});
|
||||
|
||||
test("AuthenticationRequiredError should accept custom message", () => {
|
||||
const customMessage = "Custom auth error";
|
||||
const error = new AuthenticationRequiredError(customMessage);
|
||||
|
||||
expect(error.message).toBe(customMessage);
|
||||
});
|
||||
|
||||
test("ApiRequestError should have correct properties", () => {
|
||||
const error = new ApiRequestError(404, "Not Found", "Resource not found");
|
||||
|
||||
expect(error.name).toBe("ApiRequestError");
|
||||
expect(error.status).toBe(404);
|
||||
expect(error.statusText).toBe("Not Found");
|
||||
expect(error.response).toBe("Resource not found");
|
||||
expect(error.message).toContain("404");
|
||||
expect(error.message).toContain("Not Found");
|
||||
expect(error.message).toContain("Resource not found");
|
||||
});
|
||||
|
||||
test("ApiRequestError should work without response text", () => {
|
||||
const error = new ApiRequestError(500, "Internal Server Error");
|
||||
|
||||
expect(error.response).toBeUndefined();
|
||||
expect(error.message).toContain("500");
|
||||
expect(error.message).toContain("Internal Server Error");
|
||||
expect(error.message).not.toContain("undefined");
|
||||
});
|
||||
});
|
||||
});
|
||||
193
extensions/cli/src/util/apiClient.ts
Normal file
193
extensions/cli/src/util/apiClient.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
/* eslint-disable max-classes-per-file */
|
||||
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
|
||||
import { env } from "../env.js";
|
||||
|
||||
import { logger } from "./logger.js";
|
||||
|
||||
export interface ApiRequestOptions {
|
||||
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
||||
body?: Record<string, unknown> | string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
data: T;
|
||||
status: number;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface ApiError extends Error {
|
||||
status: number;
|
||||
statusText: string;
|
||||
response?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication error thrown when user is not authenticated
|
||||
*/
|
||||
export class AuthenticationRequiredError extends Error {
|
||||
constructor(message = "Not authenticated. Please run 'cn login' first.") {
|
||||
super(message);
|
||||
this.name = "AuthenticationRequiredError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* API error thrown when the request fails
|
||||
*/
|
||||
export class ApiRequestError extends Error implements ApiError {
|
||||
status: number;
|
||||
statusText: string;
|
||||
response?: string;
|
||||
|
||||
constructor(status: number, statusText: string, response?: string) {
|
||||
const message = response
|
||||
? `API request failed: ${status} ${statusText} - ${response}`
|
||||
: `API request failed: ${status} ${statusText}`;
|
||||
super(message);
|
||||
this.name = "ApiRequestError";
|
||||
this.status = status;
|
||||
this.statusText = statusText;
|
||||
this.response = response;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an authenticated API request to the Continue API
|
||||
* Handles authentication, error handling, and response parsing
|
||||
*/
|
||||
export async function makeAuthenticatedRequest<T = any>(
|
||||
endpoint: string,
|
||||
options: ApiRequestOptions = {},
|
||||
): Promise<ApiResponse<T>> {
|
||||
// Handle authentication
|
||||
const authConfig = loadAuthConfig();
|
||||
if (!authConfig) {
|
||||
throw new AuthenticationRequiredError();
|
||||
}
|
||||
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationRequiredError(
|
||||
"No access token available. Please run 'cn login' first.",
|
||||
);
|
||||
}
|
||||
|
||||
// Prepare request options
|
||||
const { method = "GET", body, headers = {} } = options;
|
||||
|
||||
const requestOptions: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
...headers,
|
||||
},
|
||||
};
|
||||
|
||||
// Add body if provided
|
||||
if (body) {
|
||||
requestOptions.body =
|
||||
typeof body === "string" ? body : JSON.stringify(body);
|
||||
}
|
||||
|
||||
try {
|
||||
// Make the request
|
||||
const url = new URL(endpoint, env.apiBase);
|
||||
logger.debug(`Making ${method} request to: ${url.toString()}`);
|
||||
|
||||
const response = await fetch(url, requestOptions);
|
||||
|
||||
// Handle error responses
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
logger.error(`API request failed: ${response.status} ${errorText}`);
|
||||
throw new ApiRequestError(
|
||||
response.status,
|
||||
response.statusText,
|
||||
errorText,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse response
|
||||
let data: T;
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
data = await response.json();
|
||||
} else {
|
||||
// If not JSON, return the text as data
|
||||
data = (await response.text()) as T;
|
||||
}
|
||||
|
||||
logger.debug(`API request successful: ${response.status}`);
|
||||
|
||||
return {
|
||||
data,
|
||||
status: response.status,
|
||||
ok: response.ok,
|
||||
};
|
||||
} catch (error) {
|
||||
// Re-throw our custom errors
|
||||
if (
|
||||
error instanceof AuthenticationRequiredError ||
|
||||
error instanceof ApiRequestError
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Handle network/other errors
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
logger.error(`Network/request error: ${errorMessage}`);
|
||||
throw new Error(`Request failed: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function for GET requests
|
||||
*/
|
||||
export async function get<T = any>(
|
||||
endpoint: string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<ApiResponse<T>> {
|
||||
return makeAuthenticatedRequest<T>(endpoint, { method: "GET", headers });
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function for POST requests
|
||||
*/
|
||||
export async function post<T = any>(
|
||||
endpoint: string,
|
||||
body?: Record<string, unknown> | string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<ApiResponse<T>> {
|
||||
return makeAuthenticatedRequest<T>(endpoint, {
|
||||
method: "POST",
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function for PUT requests
|
||||
*/
|
||||
export async function put<T = any>(
|
||||
endpoint: string,
|
||||
body?: Record<string, unknown> | string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<ApiResponse<T>> {
|
||||
return makeAuthenticatedRequest<T>(endpoint, {
|
||||
method: "PUT",
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience function for DELETE requests
|
||||
*/
|
||||
export async function del<T = any>(
|
||||
endpoint: string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<ApiResponse<T>> {
|
||||
return makeAuthenticatedRequest<T>(endpoint, { method: "DELETE", headers });
|
||||
}
|
||||
19
extensions/cli/src/util/modelPersistence.ts
Normal file
19
extensions/cli/src/util/modelPersistence.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { GlobalContext } from "core/util/GlobalContext.js";
|
||||
|
||||
/**
|
||||
* Get the persisted model name for CLI from GlobalContext
|
||||
* Used for unauthenticated users
|
||||
*/
|
||||
export function getPersistedModelName(): string | null {
|
||||
const globalContext = new GlobalContext();
|
||||
return globalContext.get("cliSelectedModel") ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the model name for CLI to GlobalContext
|
||||
* Used for unauthenticated users
|
||||
*/
|
||||
export function persistModelName(modelName: string | null): void {
|
||||
const globalContext = new GlobalContext();
|
||||
globalContext.update("cliSelectedModel", modelName ?? undefined);
|
||||
}
|
||||
|
|
@ -12,7 +12,7 @@ describe("updateAnthropicModelInYaml", () => {
|
|||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("version: 1.0.0");
|
||||
expect(result).toContain("schema: v1");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
||||
|
|
@ -21,7 +21,7 @@ describe("updateAnthropicModelInYaml", () => {
|
|||
const result = updateAnthropicModelInYaml(invalidYaml, testApiKey);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
});
|
||||
|
|
@ -44,7 +44,7 @@ models:
|
|||
expect(result).toContain("# My Continue config");
|
||||
expect(result).toContain("# List of available models");
|
||||
expect(result).toContain("uses: openai/gpt-4");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
||||
|
|
@ -55,7 +55,7 @@ version: 1.0.0
|
|||
schema: v1
|
||||
# List of available models
|
||||
models:
|
||||
- uses: anthropic/claude-4-sonnet
|
||||
- uses: anthropic/claude-sonnet-4-5
|
||||
with:
|
||||
ANTHROPIC_API_KEY: old-key
|
||||
`;
|
||||
|
|
@ -64,7 +64,7 @@ models:
|
|||
|
||||
expect(result).toContain("# My Continue config");
|
||||
expect(result).toContain("# List of available models");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
expect(result).not.toContain("old-key");
|
||||
});
|
||||
|
|
@ -84,7 +84,7 @@ models:
|
|||
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
|
||||
|
||||
expect(result).toContain("uses: openai/gpt-4");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
|
||||
});
|
||||
|
|
@ -94,7 +94,7 @@ models:
|
|||
version: 1.0.0
|
||||
schema: v1
|
||||
models:
|
||||
- uses: anthropic/claude-4-sonnet
|
||||
- uses: anthropic/claude-sonnet-4-5
|
||||
with:
|
||||
ANTHROPIC_API_KEY: old-anthropic-key
|
||||
- uses: openai/gpt-4
|
||||
|
|
@ -104,7 +104,7 @@ models:
|
|||
|
||||
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
|
||||
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("uses: openai/gpt-4");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
|
||||
|
|
@ -112,7 +112,7 @@ models:
|
|||
|
||||
// Should only have one anthropic model
|
||||
const anthropicMatches = result.match(
|
||||
/uses: anthropic\/claude-4-sonnet/g,
|
||||
/uses: anthropic\/claude-sonnet-4-5/g,
|
||||
);
|
||||
expect(anthropicMatches).toHaveLength(1);
|
||||
});
|
||||
|
|
@ -130,7 +130,7 @@ schema: v1
|
|||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("models:");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
||||
|
|
@ -147,7 +147,7 @@ models: []
|
|||
);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
});
|
||||
|
|
@ -189,7 +189,7 @@ models: "not an array"
|
|||
|
||||
const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
|
||||
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: anthropic/claude-sonnet-4-5");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ export function updateAnthropicModelInYaml(
|
|||
apiKey: string,
|
||||
): string {
|
||||
const newModel: ModelConfig = {
|
||||
uses: "anthropic/claude-4-sonnet",
|
||||
uses: "anthropic/claude-sonnet-4-5",
|
||||
with: {
|
||||
ANTHROPIC_API_KEY: apiKey,
|
||||
},
|
||||
|
|
@ -62,7 +62,7 @@ export function updateAnthropicModelInYaml(
|
|||
|
||||
// Filter out existing anthropic models
|
||||
config.models = config.models.filter(
|
||||
(model: any) => !model || model.uses !== "anthropic/claude-4-sonnet",
|
||||
(model: any) => !model || model.uses !== "anthropic/claude-sonnet-4-5",
|
||||
);
|
||||
|
||||
// Add the new anthropic model
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
pluginGroup=com.github.continuedev.continueintellijextension
|
||||
pluginVersion=1.0.46
|
||||
pluginVersion=1.0.47
|
||||
platformVersion=2024.1
|
||||
kotlin.stdlib.default.dependency=false
|
||||
org.gradle.configuration-cache=true
|
||||
|
|
|
|||
|
|
@ -29,7 +29,9 @@ import java.nio.charset.StandardCharsets
|
|||
import java.nio.file.Paths
|
||||
import javax.swing.*
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.module.Module
|
||||
import com.intellij.openapi.module.ModuleManager
|
||||
import com.intellij.openapi.project.ModuleListener
|
||||
import com.intellij.openapi.roots.ModuleRootManager
|
||||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.openapi.vfs.newvfs.BulkFileListener
|
||||
|
|
@ -39,6 +41,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
|
|||
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
|
||||
import com.intellij.ide.ui.LafManagerListener
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import com.intellij.util.Function
|
||||
|
||||
fun showTutorial(project: Project) {
|
||||
val tutorialFileName = getTutorialFileName()
|
||||
|
|
@ -193,6 +196,41 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
}
|
||||
})
|
||||
|
||||
// Handle workspace directories changes
|
||||
connection.subscribe(
|
||||
ModuleListener.TOPIC,
|
||||
object : ModuleListener {
|
||||
override fun modulesAdded(project: Project, modules: MutableList<out Module>) {
|
||||
|
||||
val allModulePaths = ModuleManager.getInstance(project).modules
|
||||
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } }
|
||||
|
||||
val topLevelModulePaths = allModulePaths
|
||||
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }
|
||||
|
||||
continuePluginService.workspacePaths = topLevelModulePaths.toTypedArray();
|
||||
}
|
||||
|
||||
override fun moduleRemoved(project: Project, module: Module) {
|
||||
val removedPaths = ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } ;
|
||||
continuePluginService.workspacePaths = continuePluginService.workspacePaths?.toList()?.filter { path -> removedPaths.none {removedPath -> path == removedPath }}?.toTypedArray();
|
||||
}
|
||||
|
||||
override fun modulesRenamed(
|
||||
project: Project,
|
||||
modules: MutableList<out Module>,
|
||||
oldNameProvider: Function<in Module, String>
|
||||
) {
|
||||
val allModulePaths = ModuleManager.getInstance(project).modules
|
||||
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } }
|
||||
|
||||
val topLevelModulePaths = allModulePaths
|
||||
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }
|
||||
|
||||
continuePluginService.workspacePaths = topLevelModulePaths.toTypedArray()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
|
||||
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
|
||||
|
|
|
|||
|
|
@ -94,6 +94,7 @@ class MessageTypes {
|
|||
"mcp/reloadServer",
|
||||
"mcp/startAuthentication",
|
||||
"mcp/removeAuthentication",
|
||||
"mcp/setServerEnabled",
|
||||
"mcp/getPrompt",
|
||||
"context/getContextItems",
|
||||
"context/getSymbolsForFiles",
|
||||
|
|
|
|||
|
|
@ -968,11 +968,6 @@
|
|||
"enum": [
|
||||
"chat-bison-001",
|
||||
"gemini-pro",
|
||||
"gemini-1.5-pro-latest",
|
||||
"gemini-1.5-pro",
|
||||
"gemini-1.5-flash-latest",
|
||||
"gemini-1.5-flash",
|
||||
"gemini-1.5-flash-8b",
|
||||
"gemini-2.0-flash-exp",
|
||||
"gemini-2.0-flash",
|
||||
"gemini-2.0-flash-thinking-exp-01-21",
|
||||
|
|
@ -1624,12 +1619,7 @@
|
|||
"command-r",
|
||||
"command-r-plus",
|
||||
"chat-bison-001",
|
||||
"gemini-pro",
|
||||
"gemini-1.5-pro-latest",
|
||||
"gemini-1.5-pro",
|
||||
"gemini-2.5-pro",
|
||||
"gemini-1.5-flash-latest",
|
||||
"gemini-1.5-flash",
|
||||
"mistral-tiny",
|
||||
"mistral-small",
|
||||
"mistral-medium",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.3.13",
|
||||
"version": "1.3.15",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
|
|
@ -192,13 +192,13 @@ export class JumpManager {
|
|||
// identical to the completion content,
|
||||
// then we don't have to jump.
|
||||
if (completionContent !== undefined) {
|
||||
console.log("completionContent is not null");
|
||||
console.debug("completionContent is not null");
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
|
||||
if (editor) {
|
||||
try {
|
||||
const completionLines = completionContent.split("\n");
|
||||
console.log("completionLines:", completionLines);
|
||||
console.debug("completionLines:", completionLines);
|
||||
|
||||
// Get document content at jump location spanning multiple lines.
|
||||
const document = editor.document;
|
||||
|
|
@ -212,7 +212,7 @@ export class JumpManager {
|
|||
if (endLine - startLine + 1 < completionLines.length) {
|
||||
// Not enough lines in document, so content can't be identical.
|
||||
// Proceed to jump!
|
||||
console.log(
|
||||
console.debug(
|
||||
"Not enough lines in document to match completion content",
|
||||
);
|
||||
} else {
|
||||
|
|
@ -224,12 +224,12 @@ export class JumpManager {
|
|||
const lineText = document.lineAt(documentLine).text;
|
||||
if (lineText !== completionLines[i]) {
|
||||
contentMatches = false;
|
||||
console.log(`Line ${i + 1} doesn't match`);
|
||||
console.debug(`Line ${i + 1} doesn't match`);
|
||||
}
|
||||
}
|
||||
|
||||
if (contentMatches) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"Skipping jump as content is identical at jump location",
|
||||
);
|
||||
return false; // Exit early, don't suggest jump.
|
||||
|
|
@ -242,20 +242,20 @@ export class JumpManager {
|
|||
}
|
||||
}
|
||||
|
||||
console.log("this._jumpInProgress");
|
||||
console.debug("this._jumpInProgress");
|
||||
this._jumpInProgress = true;
|
||||
this._oldCursorPosition = currentPosition;
|
||||
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) {
|
||||
console.log("No active editor, cannot suggest jump");
|
||||
console.debug("No active editor, cannot suggest jump");
|
||||
this._jumpInProgress = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
const visibleRanges = editor.visibleRanges;
|
||||
if (visibleRanges.length === 0) {
|
||||
console.log("No visible ranges in editor, cannot suggest jump");
|
||||
console.debug("No visible ranges in editor, cannot suggest jump");
|
||||
this._jumpInProgress = false;
|
||||
return false;
|
||||
}
|
||||
|
|
@ -375,7 +375,7 @@ export class JumpManager {
|
|||
"continue.rejectJump",
|
||||
async () => {
|
||||
if (this._jumpDecorationVisible) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"deleteChain from JumpManager.ts: rejectJump and decoration visible",
|
||||
);
|
||||
NextEditProvider.getInstance().deleteChain();
|
||||
|
|
@ -447,7 +447,7 @@ export class JumpManager {
|
|||
"jumpManager",
|
||||
async (e, state) => {
|
||||
if (state.jumpInProgress || state.jumpJustAccepted) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"JumpManager: jump in progress or just accepted, preserving chain",
|
||||
);
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -165,7 +165,7 @@ export class NextEditWindowManager {
|
|||
private constructor() {
|
||||
this.theme = getThemeString();
|
||||
|
||||
console.log(
|
||||
console.debug(
|
||||
"Next Edit Theme initialized:",
|
||||
this.theme
|
||||
? `Theme exists: ${JSON.stringify(this.theme)}`
|
||||
|
|
@ -269,7 +269,7 @@ export class NextEditWindowManager {
|
|||
|
||||
// Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
|
||||
this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => {
|
||||
console.log(
|
||||
console.debug(
|
||||
"deleteChain from NextEditWindowManager.ts: hide next edit command",
|
||||
);
|
||||
NextEditProvider.getInstance().deleteChain();
|
||||
|
|
@ -616,7 +616,7 @@ export class NextEditWindowManager {
|
|||
) {
|
||||
this.theme = getThemeString();
|
||||
await this.codeRenderer.setTheme(this.theme);
|
||||
console.log(
|
||||
console.debug(
|
||||
"Theme updated:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
);
|
||||
|
|
@ -630,7 +630,7 @@ export class NextEditWindowManager {
|
|||
vscode.window.onDidChangeActiveColorTheme(async () => {
|
||||
this.theme = getThemeString();
|
||||
await this.codeRenderer.setTheme(this.theme);
|
||||
console.log(
|
||||
console.debug(
|
||||
"Active theme changed:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
);
|
||||
|
|
@ -792,7 +792,7 @@ export class NextEditWindowManager {
|
|||
|
||||
// Check if line numbers are valid.
|
||||
if (range.start.line < 0 || range.start.line >= doc.lineCount) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"Invalid start line:",
|
||||
range.start.line,
|
||||
"doc lines:",
|
||||
|
|
@ -802,7 +802,7 @@ export class NextEditWindowManager {
|
|||
}
|
||||
|
||||
if (range.end.line < 0 || range.end.line >= doc.lineCount) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"Invalid end line:",
|
||||
range.end.line,
|
||||
"doc lines:",
|
||||
|
|
@ -819,7 +819,7 @@ export class NextEditWindowManager {
|
|||
range.start.character < 0 ||
|
||||
range.start.character > startLine.text.length
|
||||
) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"Invalid start character:",
|
||||
range.start.character,
|
||||
"line length:",
|
||||
|
|
@ -829,7 +829,7 @@ export class NextEditWindowManager {
|
|||
}
|
||||
|
||||
if (range.end.character < 0 || range.end.character > endLine.text.length) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"Invalid end character:",
|
||||
range.end.character,
|
||||
"line length:",
|
||||
|
|
@ -884,7 +884,7 @@ export class NextEditWindowManager {
|
|||
|
||||
// Check if document changed during async operation.
|
||||
if (editor.document.version !== docVersion) {
|
||||
console.log("Document changed during decoration creation, aborting");
|
||||
console.debug("Document changed during decoration creation, aborting");
|
||||
decoration.dispose();
|
||||
return;
|
||||
}
|
||||
|
|
@ -991,7 +991,7 @@ export class NextEditWindowManager {
|
|||
"nextEditWindowManager",
|
||||
async (e, state) => {
|
||||
if (state.nextEditWindowAccepted) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"NextEditWindowManager: Edit was just accepted, preserving chain",
|
||||
);
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -330,7 +330,7 @@ export class SelectionChangeManager {
|
|||
return false;
|
||||
}
|
||||
|
||||
console.log(
|
||||
console.debug(
|
||||
"defaultFallbackHandler: deleteChain called from onDidChangeTextEditorSelection",
|
||||
);
|
||||
await NextEditProvider.getInstance().deleteChain();
|
||||
|
|
|
|||
|
|
@ -333,7 +333,7 @@ export class ContinueCompletionProvider
|
|||
let chainExists = this.nextEditProvider.chainExists();
|
||||
const processedCount = this.prefetchQueue.processedCount;
|
||||
const unprocessedCount = this.prefetchQueue.unprocessedCount;
|
||||
console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
|
||||
console.debug("isJumping:", isJumping, "/ chainExists:", chainExists);
|
||||
this.prefetchQueue.peekThreeProcessed();
|
||||
|
||||
let resetChainInFullFileDiff = false;
|
||||
|
|
@ -351,7 +351,7 @@ export class ContinueCompletionProvider
|
|||
|
||||
if (isJumping && chainExists) {
|
||||
// Case 2: Jumping (chain exists, jump was taken)
|
||||
console.log("trigger reason: jumping");
|
||||
console.debug("trigger reason: jumping");
|
||||
|
||||
// Reset jump state.
|
||||
this.jumpManager.setJumpInProgress(false);
|
||||
|
|
@ -380,7 +380,7 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
} else if (chainExists) {
|
||||
// Case 3: Accepting next edit outcome (chain exists, jump is not taken).
|
||||
console.log("trigger reason: accepting");
|
||||
console.debug("trigger reason: accepting");
|
||||
|
||||
// Try suggesting jump for each location.
|
||||
let isJumpSuggested = false;
|
||||
|
|
@ -428,7 +428,7 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
|
||||
if (!isJumpSuggested) {
|
||||
console.log(
|
||||
console.debug(
|
||||
"No suitable jump location found after trying all positions",
|
||||
);
|
||||
this.nextEditProvider.deleteChain();
|
||||
|
|
@ -642,7 +642,7 @@ export class ContinueCompletionProvider
|
|||
|
||||
if (isFim) {
|
||||
if (!fimText) {
|
||||
console.log("deleteChain from completionProvider.ts: !fimText");
|
||||
console.debug("deleteChain from completionProvider.ts: !fimText");
|
||||
this.nextEditProvider.deleteChain();
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -679,7 +679,7 @@ export class ContinueCompletionProvider
|
|||
// Only time we ever reach this point would be after the jump was taken, or if its after the very first repsonse.
|
||||
// In case of jump, this is impossible, as the JumpManager wouldn't have suggested a jump here in the first place.
|
||||
// In case of initial response, we suggested a jump.
|
||||
console.log(
|
||||
console.debug(
|
||||
"deleteChain from completionProvider.ts: diffLines.length === 0",
|
||||
);
|
||||
NextEditProvider.getInstance().deleteChain();
|
||||
|
|
@ -718,7 +718,7 @@ export class ContinueCompletionProvider
|
|||
if (selectedCompletionInfo) {
|
||||
const { text, range } = selectedCompletionInfo;
|
||||
if (!outcome.completion.startsWith(text)) {
|
||||
console.log(
|
||||
console.debug(
|
||||
`Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
|
||||
range,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { IContextProvider } from "core";
|
||||
import { ConfigHandler } from "core/config/ConfigHandler";
|
||||
|
|
@ -10,6 +11,7 @@ import {
|
|||
getConfigJsonPath,
|
||||
getConfigTsPath,
|
||||
getConfigYamlPath,
|
||||
getContinueGlobalPath,
|
||||
} from "core/util/paths";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
|
|
@ -232,7 +234,9 @@ export class VsCodeExtension {
|
|||
timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY &&
|
||||
!NextEditWindowManager.getInstance().hasAccepted()
|
||||
) {
|
||||
console.log("VsCodeExtension: typing in progress, preserving chain");
|
||||
console.debug(
|
||||
"VsCodeExtension: typing in progress, preserving chain",
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -463,6 +467,18 @@ export class VsCodeExtension {
|
|||
void this.configHandler.reloadConfig("config.ts updated - fs file watch");
|
||||
});
|
||||
|
||||
// watch global rules directory for changes
|
||||
const globalRulesDir = path.join(getContinueGlobalPath(), "rules");
|
||||
if (fs.existsSync(globalRulesDir)) {
|
||||
fs.watch(globalRulesDir, { recursive: true }, (eventType, filename) => {
|
||||
if (filename && filename.endsWith(".md")) {
|
||||
void this.configHandler.reloadConfig(
|
||||
"Global rules directory updated - fs file watch",
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
vscode.workspace.onDidChangeTextDocument(async (event) => {
|
||||
if (event.contentChanges.length > 0) {
|
||||
selectionManager.documentChanged();
|
||||
|
|
@ -503,8 +519,22 @@ export class VsCodeExtension {
|
|||
});
|
||||
});
|
||||
|
||||
vscode.workspace.onDidChangeWorkspaceFolders(async (event) => {
|
||||
const dirs = vscode.workspace.workspaceFolders?.map(
|
||||
(folder) => folder.uri,
|
||||
);
|
||||
|
||||
this.ideUtils.setWokspaceDirectories(dirs);
|
||||
|
||||
this.core.invoke("index/forceReIndex", {
|
||||
dirs: [
|
||||
...event.added.map((folder) => folder.uri.toString()),
|
||||
...event.removed.map((folder) => folder.uri.toString()),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
vscode.workspace.onDidOpenTextDocument(async (event) => {
|
||||
console.log("onDidOpenTextDocument");
|
||||
const ast = await getAst(event.fileName, event.getText());
|
||||
if (ast) {
|
||||
DocumentHistoryTracker.getInstance().addDocument(
|
||||
|
|
|
|||
|
|
@ -74,6 +74,10 @@ export class VsCodeIdeUtils {
|
|||
return this._workspaceDirectories;
|
||||
}
|
||||
|
||||
setWokspaceDirectories(dirs: vscode.Uri[] | undefined): void {
|
||||
this._workspaceDirectories = dirs;
|
||||
}
|
||||
|
||||
getUniqueId() {
|
||||
return getUniqueId();
|
||||
}
|
||||
|
|
|
|||
69
gui/src/components/DropdownButton.tsx
Normal file
69
gui/src/components/DropdownButton.tsx
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline";
|
||||
import { ToolTip } from "./gui/Tooltip";
|
||||
import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "./ui";
|
||||
|
||||
interface DropdownOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface DropdownButtonProps {
|
||||
title: string;
|
||||
options: DropdownOption[];
|
||||
onOptionClick: (value: string) => void;
|
||||
addButtonTooltip?: string;
|
||||
className?: string;
|
||||
variant?: "default" | "sm";
|
||||
}
|
||||
|
||||
export function DropdownButton({
|
||||
title,
|
||||
options,
|
||||
onOptionClick,
|
||||
addButtonTooltip,
|
||||
className = "",
|
||||
variant = "default",
|
||||
}: DropdownButtonProps) {
|
||||
const isSmall = variant === "sm";
|
||||
const titleSize = isSmall ? "text-sm font-semibold" : "text-xl font-semibold";
|
||||
const marginBottom = isSmall ? "mb-2" : "mb-4";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${marginBottom} flex items-center justify-between ${className}`}
|
||||
>
|
||||
<h3 className={`my-0 ${titleSize}`}>{title}</h3>
|
||||
<Listbox value={null} onChange={() => {}}>
|
||||
<div className="relative">
|
||||
<ToolTip content={addButtonTooltip}>
|
||||
<ListboxButton
|
||||
className={`ring-offset-background focus-visible:ring-ring border-description hover:enabled:bg-input hover:enabled:text-foreground text-description inline-flex h-7 items-center justify-center gap-1 whitespace-nowrap rounded-md border border-solid bg-transparent px-1.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`}
|
||||
aria-label={addButtonTooltip}
|
||||
>
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
<ChevronDownIcon className="h-3 w-3" />
|
||||
</ListboxButton>
|
||||
</ToolTip>
|
||||
<ListboxOptions className="min-w-32 max-w-36" anchor="bottom end">
|
||||
{options.map((option) => (
|
||||
<ListboxOption
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
className={({ active }: { active: boolean }) =>
|
||||
`relative flex cursor-default select-none items-center gap-3 py-2 pl-4 pr-4 ${
|
||||
active
|
||||
? "bg-list-active text-list-active-foreground"
|
||||
: "text-foreground"
|
||||
}`
|
||||
}
|
||||
onClick={() => onOptionClick(option.value)}
|
||||
>
|
||||
<span className="block truncate">{option.label}</span>
|
||||
</ListboxOption>
|
||||
))}
|
||||
</ListboxOptions>
|
||||
</div>
|
||||
</Listbox>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { useContext, useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
|
|
@ -10,7 +10,7 @@ export const FatalErrorIndicator = () => {
|
|||
const { refreshProfiles } = useAuth();
|
||||
const configError = useAppSelector((store) => store.config.configError);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const hasFatalErrors = useMemo(() => {
|
||||
|
|
@ -18,10 +18,11 @@ export const FatalErrorIndicator = () => {
|
|||
}, [configError]);
|
||||
|
||||
const configLoading = useAppSelector((state) => state.config.loading);
|
||||
|
||||
const showConfigPage = () => {
|
||||
navigate(CONFIG_ROUTES.AGENTS);
|
||||
};
|
||||
// const onAgentsPage = location.
|
||||
const currentPath = `${location.pathname}${location.search}`;
|
||||
|
||||
const { selectedProfile } = useAuth();
|
||||
|
||||
|
|
@ -64,9 +65,11 @@ export const FatalErrorIndicator = () => {
|
|||
Reload
|
||||
</div>
|
||||
)}
|
||||
<div onClick={showConfigPage} className="cursor-pointer underline">
|
||||
View
|
||||
</div>
|
||||
{currentPath !== CONFIG_ROUTES.AGENTS && (
|
||||
<div onClick={showConfigPage} className="cursor-pointer underline">
|
||||
View
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Alert>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -38,7 +38,14 @@ const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
|
|||
{isToggled && !!showIfToggled && showIfToggled}
|
||||
<div
|
||||
className={`border-command-border bg-vsc-input-background relative flex items-center rounded-full border border-solid`}
|
||||
onClick={disabled ? undefined : onToggle}
|
||||
onClick={
|
||||
disabled
|
||||
? undefined
|
||||
: (e) => {
|
||||
e.stopPropagation();
|
||||
onToggle();
|
||||
}
|
||||
}
|
||||
style={{
|
||||
height: size,
|
||||
width: size * 2,
|
||||
|
|
|
|||
|
|
@ -1,58 +0,0 @@
|
|||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { PencilIcon } from "@heroicons/react/24/outline";
|
||||
import { useContext } from "react";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
|
||||
type SectionKey = Exclude<
|
||||
keyof ConfigYaml,
|
||||
"name" | "version" | "schema" | "metadata" | "env" | "requestOptions"
|
||||
>;
|
||||
|
||||
interface EditBlockButtonProps<T extends SectionKey> {
|
||||
blockType: T;
|
||||
block?: NonNullable<Omit<ConfigYaml, "env">[T]>[number];
|
||||
className?: string;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
function isUsesBlock(block: any): block is { uses: string } {
|
||||
return typeof block !== "string" && "uses" in block;
|
||||
}
|
||||
|
||||
export default function EditBlockButton<T extends SectionKey>({
|
||||
block,
|
||||
blockType,
|
||||
className = "",
|
||||
sourceFile,
|
||||
}: EditBlockButtonProps<T>) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { selectedProfile } = useAuth();
|
||||
|
||||
const openUrl = (path: string) =>
|
||||
ideMessenger.request("controlPlane/openUrl", {
|
||||
path,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
|
||||
const handleEdit = () => {
|
||||
if (selectedProfile?.profileType === "local") {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
element: { sourceFile },
|
||||
});
|
||||
} else if (block && isUsesBlock(block)) {
|
||||
void openUrl(`${block.uses}/new-version`);
|
||||
} else if (selectedProfile?.fullSlug) {
|
||||
const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`;
|
||||
void openUrl(`${slug}/new-version`);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PencilIcon
|
||||
className={`h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125 ${className}`}
|
||||
onClick={handleEdit}
|
||||
/>
|
||||
);
|
||||
}
|
||||
66
gui/src/components/mainInput/Lump/useEditBlock.ts
Normal file
66
gui/src/components/mainInput/Lump/useEditBlock.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import { ModelDescription } from "core";
|
||||
import { useContext } from "react";
|
||||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
|
||||
export function useEditBlock() {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { selectedProfile } = useAuth();
|
||||
|
||||
return (slug?: string, sourceFile?: string) => {
|
||||
if (slug) {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: `${slug}/new-version`,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
} else if (sourceFile) {
|
||||
ideMessenger.post("openFile", {
|
||||
path: sourceFile,
|
||||
});
|
||||
} else if (
|
||||
selectedProfile?.profileType === "local" &&
|
||||
selectedProfile?.uri
|
||||
) {
|
||||
ideMessenger.post("openFile", {
|
||||
path: selectedProfile.uri,
|
||||
});
|
||||
} else if (
|
||||
selectedProfile?.fullSlug?.ownerSlug &&
|
||||
selectedProfile?.fullSlug.packageSlug
|
||||
) {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}/new-version`,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
} else {
|
||||
// Local etc
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function useEditModel() {
|
||||
const editBlock = useEditBlock();
|
||||
return (model?: ModelDescription | null) => {
|
||||
editBlock(undefined, model?.sourceFile);
|
||||
};
|
||||
}
|
||||
|
||||
export function useEditDoc() {
|
||||
const editBlock = useEditBlock();
|
||||
return (
|
||||
docConfig?: { uses?: string } | { name: string; sourceFile?: string },
|
||||
) => {
|
||||
if (!docConfig) {
|
||||
editBlock(undefined, undefined);
|
||||
return;
|
||||
}
|
||||
if ("name" in docConfig) {
|
||||
editBlock(undefined, docConfig.sourceFile);
|
||||
} else {
|
||||
editBlock(docConfig.uses, undefined);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -13,8 +13,8 @@ export async function getPromptV2ContextRequests(
|
|||
}
|
||||
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
|
||||
const visitedFiles = new Set<string>();
|
||||
if (command.promptFile) {
|
||||
visitedFiles.add(command.promptFile);
|
||||
if (command.sourceFile) {
|
||||
visitedFiles.add(command.sourceFile);
|
||||
}
|
||||
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { cn } from "../../util/cn";
|
||||
|
||||
interface CardProps extends React.ComponentProps<"div"> {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
|
@ -5,8 +7,8 @@ interface CardProps extends React.ComponentProps<"div"> {
|
|||
export function Card({ children, className = "", ...props }: CardProps) {
|
||||
return (
|
||||
<div
|
||||
className={`bg-editor rounded-default space-y-0 px-4 py-3 ${className}`}
|
||||
{...props}
|
||||
className={cn("bg-editor rounded-default space-y-0 px-4 py-3", className)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -856,46 +856,6 @@ export const models: { [key: string]: ModelPackage } = {
|
|||
icon: "mistral.png",
|
||||
isOpenSource: true,
|
||||
},
|
||||
geminiPro: {
|
||||
title: "Gemini Pro",
|
||||
description: "A highly capable model created by Google DeepMind",
|
||||
params: {
|
||||
title: "Gemini Pro",
|
||||
model: "gemini-pro",
|
||||
contextLength: 32_000,
|
||||
apiKey: "<API_KEY>",
|
||||
},
|
||||
icon: "gemini.png",
|
||||
providerOptions: ["gemini"],
|
||||
isOpenSource: false,
|
||||
},
|
||||
gemini15Pro: {
|
||||
title: "Gemini 1.5 Pro",
|
||||
description: "A newer Gemini model with 1M token context length",
|
||||
params: {
|
||||
title: "Gemini 1.5 Pro",
|
||||
model: "gemini-1.5-pro-latest",
|
||||
contextLength: 2_000_000,
|
||||
apiKey: "<API_KEY>",
|
||||
},
|
||||
icon: "gemini.png",
|
||||
providerOptions: ["gemini", "askSage"],
|
||||
isOpenSource: false,
|
||||
},
|
||||
gemini15Flash: {
|
||||
title: "Gemini 1.5 Flash",
|
||||
description:
|
||||
"Fast and versatile multimodal model for scaling across diverse tasks",
|
||||
params: {
|
||||
title: "Gemini 1.5 Flash",
|
||||
model: "gemini-1.5-flash-latest",
|
||||
contextLength: 1_000_000,
|
||||
apiKey: "<API_KEY>",
|
||||
},
|
||||
icon: "gemini.png",
|
||||
providerOptions: ["gemini"],
|
||||
isOpenSource: false,
|
||||
},
|
||||
gemini20Flash: {
|
||||
title: "Gemini 2.0 Flash",
|
||||
description:
|
||||
|
|
@ -1358,31 +1318,6 @@ export const models: { [key: string]: ModelPackage } = {
|
|||
providerOptions: ["watsonx"],
|
||||
isOpenSource: false,
|
||||
},
|
||||
VertexGemini15Pro: {
|
||||
title: "Gemini 1.5 Pro",
|
||||
description: "A newer Gemini model with 1M token context length",
|
||||
params: {
|
||||
title: "Gemini 1.5 Pro",
|
||||
model: "gemini-1.5-pro-002",
|
||||
contextLength: 2_097_152,
|
||||
},
|
||||
icon: "gemini.png",
|
||||
providerOptions: ["vertexai"],
|
||||
isOpenSource: false,
|
||||
},
|
||||
VertexGemini15Flash: {
|
||||
title: "Gemini 1.5 Flash",
|
||||
description:
|
||||
"Fast and versatile multimodal model for scaling across diverse tasks",
|
||||
params: {
|
||||
title: "Gemini 1.5 Flash",
|
||||
model: "gemini-1.5-flash-002",
|
||||
contextLength: 1_048_576,
|
||||
},
|
||||
icon: "gemini.png",
|
||||
providerOptions: ["vertexai"],
|
||||
isOpenSource: false,
|
||||
},
|
||||
vertexMistralLarge: {
|
||||
title: "Mistral Large",
|
||||
description:
|
||||
|
|
|
|||
|
|
@ -598,9 +598,6 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
|
|||
models.gemini20FlashLite,
|
||||
models.gemini20FlashImageGeneration,
|
||||
models.gemini25ProExp,
|
||||
models.gemini15Pro,
|
||||
models.geminiPro,
|
||||
models.gemini15Flash,
|
||||
],
|
||||
apiKeyUrl: "https://aistudio.google.com/app/apikey",
|
||||
},
|
||||
|
|
@ -925,11 +922,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
|
|||
longDescription:
|
||||
"Use the supported Vertex AI models - see [here](https://cloud.google.com/docs/authentication/provide-credentials-adc) to authenticate",
|
||||
icon: "vertexai.png",
|
||||
packages: [
|
||||
models.VertexGemini15Pro,
|
||||
models.VertexGemini15Flash,
|
||||
models.mistralLarge,
|
||||
],
|
||||
packages: [models.mistralLarge],
|
||||
collectInputFor: [
|
||||
{
|
||||
inputType: "project",
|
||||
|
|
@ -1000,7 +993,6 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
|
|||
models.asksagegroq70b,
|
||||
models.mistralLarge,
|
||||
models.llama370bChat,
|
||||
models.gemini15Pro,
|
||||
],
|
||||
apiKeyUrl: "https://chat.asksage.ai/",
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { PlusIcon } from "@heroicons/react/24/outline";
|
||||
import { ToolTip } from "../../../components/gui/Tooltip";
|
||||
import { Button } from "../../../components/ui";
|
||||
import { cn } from "../../../util/cn";
|
||||
|
||||
interface ConfigHeaderProps {
|
||||
title: string;
|
||||
|
|
@ -9,6 +10,7 @@ interface ConfigHeaderProps {
|
|||
addButtonTooltip?: string;
|
||||
className?: string;
|
||||
variant?: "default" | "sm";
|
||||
showAddButton?: boolean;
|
||||
}
|
||||
|
||||
export function ConfigHeader({
|
||||
|
|
@ -18,6 +20,7 @@ export function ConfigHeader({
|
|||
addButtonTooltip = "Add item",
|
||||
className = "",
|
||||
variant = "default",
|
||||
showAddButton = true,
|
||||
}: ConfigHeaderProps) {
|
||||
const isSmall = variant === "sm";
|
||||
const marginBottom = isSmall ? "mb-4" : "mb-6";
|
||||
|
|
@ -26,13 +29,16 @@ export function ConfigHeader({
|
|||
|
||||
return (
|
||||
<div
|
||||
className={`${marginBottom} flex items-center justify-between ${className}`}
|
||||
className={cn(
|
||||
`${marginBottom} flex items-center justify-between`,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<HeadingTag className={`my-0 ${titleSize}`}>{title}</HeadingTag>
|
||||
{subtext && <p className="text-description mt-1 text-sm">{subtext}</p>}
|
||||
</div>
|
||||
{onAddClick && (
|
||||
{showAddButton && onAddClick && (
|
||||
<ToolTip content={addButtonTooltip}>
|
||||
<Button
|
||||
onClick={onAddClick}
|
||||
|
|
|
|||
|
|
@ -1,60 +0,0 @@
|
|||
import Alert from "../../../components/gui/Alert";
|
||||
import { Card } from "../../../components/ui";
|
||||
import { useToolPolicies } from "../hooks/useToolPolicies";
|
||||
import { ToolPoliciesGroup } from "./ToolPoliciesGroup";
|
||||
|
||||
export function ToolPolicies() {
|
||||
const {
|
||||
mode,
|
||||
toolsByGroup,
|
||||
duplicateDetection,
|
||||
allToolsOff,
|
||||
message,
|
||||
expandedGroups,
|
||||
toggleGroup,
|
||||
toolGroupSettings,
|
||||
} = useToolPolicies();
|
||||
|
||||
if (toolsByGroup.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<span className="text-description text-sm italic">
|
||||
No tools available
|
||||
</span>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{(mode === "chat" || mode === "plan") && (
|
||||
<div className="mb-4">
|
||||
<Alert type="info" size="sm">
|
||||
<span className="text-2xs italic">{message}</span>
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{toolsByGroup.map(([groupName, tools]) => {
|
||||
const isGroupEnabled =
|
||||
!allToolsOff && toolGroupSettings[groupName] !== "exclude";
|
||||
const isExpanded = expandedGroups[groupName];
|
||||
|
||||
return (
|
||||
<ToolPoliciesGroup
|
||||
key={groupName}
|
||||
groupName={groupName}
|
||||
tools={tools}
|
||||
isGroupEnabled={isGroupEnabled}
|
||||
isExpanded={isExpanded}
|
||||
allToolsOff={allToolsOff}
|
||||
duplicateDetection={duplicateDetection}
|
||||
onToggleGroup={toggleGroup}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,87 +1,100 @@
|
|||
import { ChevronDownIcon } from "@heroicons/react/24/outline";
|
||||
import { Tool } from "core";
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
WrenchScrewdriverIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { useMemo, useState } from "react";
|
||||
import ToggleSwitch from "../../../components/gui/Switch";
|
||||
import { ToolTip } from "../../../components/gui/Tooltip";
|
||||
import { Card } from "../../../components/ui";
|
||||
import { useAppDispatch } from "../../../redux/hooks";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { toggleToolGroupSetting } from "../../../redux/slices/uiSlice";
|
||||
import { ToolPolicyItem } from "./ToolPolicyItem";
|
||||
|
||||
interface ToolPoliciesGroupProps {
|
||||
showIcon: boolean;
|
||||
groupName: string;
|
||||
tools: Tool[];
|
||||
isGroupEnabled: boolean;
|
||||
isExpanded: boolean;
|
||||
displayName: string;
|
||||
allToolsOff: boolean;
|
||||
duplicateDetection: Record<string, boolean>;
|
||||
onToggleGroup: (groupName: string) => void;
|
||||
}
|
||||
|
||||
export function ToolPoliciesGroup({
|
||||
showIcon,
|
||||
groupName,
|
||||
tools,
|
||||
isGroupEnabled,
|
||||
isExpanded,
|
||||
displayName,
|
||||
allToolsOff,
|
||||
duplicateDetection,
|
||||
onToggleGroup,
|
||||
}: ToolPoliciesGroupProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
const availableTools = useAppSelector((state) => state.config.config.tools);
|
||||
const tools = useMemo(() => {
|
||||
return availableTools.filter((t) => t.group === groupName);
|
||||
}, [availableTools, groupName]);
|
||||
|
||||
const toolGroupSettings = useAppSelector(
|
||||
(state) => state.ui.toolGroupSettings,
|
||||
);
|
||||
const isGroupEnabled = useMemo(() => {
|
||||
return toolGroupSettings[groupName] !== "exclude";
|
||||
}, [toolGroupSettings, groupName]);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex flex-col">
|
||||
<div
|
||||
className="-mx-2 flex cursor-pointer items-center justify-between gap-3 rounded px-2 py-2 hover:bg-gray-50 hover:bg-opacity-5"
|
||||
onClick={() => onToggleGroup(groupName)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<ChevronDownIcon
|
||||
className={`text-description h-3 w-3 transition-transform ${
|
||||
isExpanded ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-semibold">{groupName}</span>
|
||||
<div className="flex h-5 w-5 items-center justify-center rounded-full bg-gray-600 text-xs font-medium text-white">
|
||||
{tools.length}
|
||||
</div>
|
||||
<Card className="flex flex-1 flex-col p-0">
|
||||
<div
|
||||
className="flex cursor-pointer items-center justify-between gap-3 rounded px-2 py-2 hover:bg-gray-50 hover:bg-opacity-5"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<ChevronDownIcon
|
||||
className={`text-description h-3 w-3 transition-transform ${
|
||||
isExpanded ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
{showIcon && (
|
||||
<WrenchScrewdriverIcon className="h-4 w-4 flex-shrink-0" />
|
||||
)}
|
||||
<span className="text-sm font-semibold">{displayName}</span>
|
||||
<div className="flex h-5 w-5 items-center justify-center rounded-md bg-gray-600 px-0.5 text-xs font-medium text-white">
|
||||
{tools.length}
|
||||
</div>
|
||||
</div>
|
||||
<ToolTip
|
||||
content={
|
||||
allToolsOff
|
||||
? "Tools disabled in current mode"
|
||||
: isGroupEnabled
|
||||
? `Disable all tools in ${groupName} group`
|
||||
: `Enable all tools in ${groupName} group`
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<ToggleSwitch
|
||||
isToggled={isGroupEnabled}
|
||||
onToggle={() => dispatch(toggleToolGroupSetting(groupName))}
|
||||
text=""
|
||||
size={10}
|
||||
disabled={allToolsOff}
|
||||
/>
|
||||
</div>
|
||||
</ToolTip>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-3 space-y-1">
|
||||
{tools.map((tool) => (
|
||||
<ToolPolicyItem
|
||||
key={tool.uri + tool.function.name}
|
||||
tool={tool}
|
||||
duplicatesDetected={duplicateDetection[tool.function.name]}
|
||||
isGroupEnabled={isGroupEnabled}
|
||||
/>
|
||||
))}
|
||||
<ToolTip
|
||||
content={
|
||||
allToolsOff
|
||||
? "Tools disabled in current mode"
|
||||
: isGroupEnabled
|
||||
? `Disable all tools in ${groupName} group`
|
||||
: `Enable all tools in ${groupName} group`
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<ToggleSwitch
|
||||
isToggled={isGroupEnabled}
|
||||
onToggle={() => dispatch(toggleToolGroupSetting(groupName))}
|
||||
text=""
|
||||
size={10}
|
||||
disabled={allToolsOff}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</ToolTip>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-3 space-y-1 pl-2">
|
||||
{tools.map((tool) => (
|
||||
<ToolPolicyItem
|
||||
key={tool.uri + tool.function.name}
|
||||
tool={tool}
|
||||
duplicatesDetected={duplicateDetection[tool.function.name]}
|
||||
isGroupEnabled={isGroupEnabled}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -70,14 +70,14 @@ export function ToolPolicyItem(props: ToolPolicyItemProps) {
|
|||
fontSize,
|
||||
}}
|
||||
>
|
||||
<div className="-mx-2 flex flex-col rounded px-2 py-2 hover:bg-gray-50 hover:bg-opacity-5">
|
||||
<div className="flex flex-col rounded px-2 py-2 hover:bg-gray-50 hover:bg-opacity-5">
|
||||
<div className="flex flex-row items-start justify-between">
|
||||
<div
|
||||
className="flex flex-1 cursor-pointer flex-row items-start gap-1"
|
||||
className="flex flex-1 cursor-pointer flex-row items-start gap-1.5"
|
||||
onClick={() => setIsExpanded((val) => !val)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={`xs:flex mt-0.5 hidden h-3 w-3 flex-shrink-0 transition-all duration-200 ${isExpanded ? "rotate-90" : ""}`}
|
||||
className={`xs:flex hidden h-3 w-3 flex-shrink-0 pt-1 transition-all duration-200 ${isExpanded ? "rotate-90" : ""}`}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue