Merge branch 'main' of https://github.com/continuedev/continue into dallin/prompt-tools

This commit is contained in:
Dallin Romney 2025-06-23 14:14:12 -07:00
commit 2c352ea7c3
69 changed files with 1417 additions and 660 deletions

View file

@ -0,0 +1,7 @@
---
name: Update docs from GitHub PR
description: Provide a PR link to update docs based on
alwaysApply: false
---
When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view <PR_URL> --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style.

View file

@ -0,0 +1,4 @@
If the user's request is vague and you don't have enough information to confidently answer, you can either
- In Chat OR Agent mode, stop and ask questions to clarify before proceeding
- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available.

View file

@ -0,0 +1,6 @@
---
name: Programming principles
description: Guidelines for coding fundamentals in this project
---
Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions.

View file

@ -0,0 +1 @@
Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions.

View file

@ -6,25 +6,23 @@ rules:
rule: >-
For unit testing in this project:
1. The project uses Vitest and Jest for testing. Prefer Vitest
1. The project uses Jest as the testing framework
2. Run tests from within the specific package directory (e.g., `cd core && ..`
2. Run tests using `npm test` from within the specific package/module
directory
3. For vitest tests,
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module
directory: `cd [directory] && vitest -- [test file path]`
3. Command structure: `cd [directory] && npm test -- [test file path]`
4. For jest tests,
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module
directory: `cd [directory] && npm test -- [test file path]`
- The test script uses experimental VM modules via NODE_OPTIONS flag
4. The test script uses experimental VM modules via NODE_OPTIONS flag
5. Test files follow the pattern `*.test.ts`
6. Tests must import Jest with `import { jest } from "@jest/globals";`
7. Run tests from within the specific package directory (e.g., `cd core`
for core module tests)
8. Write tests as top-level `test()` functions - DO NOT use `describe()`
5. For both
- Write tests as top-level `test()` functions - DO NOT use `describe()`
blocks
9. Include the function name being tested in the test description for
- Include the function name being tested in the test description for
clarity

View file

@ -0,0 +1,5 @@
---
globs: "extensions/vscode/src/commands.ts"
---
When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry.

View file

@ -1,5 +1,6 @@
import { ctxItemToRifWithContents } from "./util";
import { describe, expect, it } from "vitest";
import { ContextItemWithId, RangeInFileWithContents } from "../index";
import { ctxItemToRifWithContents } from "./util";
describe("ctxItemToRifWithContents", () => {
it("should parse start and end lines from the item name when format is valid", () => {

View file

@ -1,4 +1,5 @@
import { Chunk } from "../../../";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -23,7 +24,8 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
await Telemetry.captureError("no_reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
let embeddingsChunks: Chunk[] = [];
@ -32,6 +34,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings:", error);
}
@ -40,6 +43,10 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
await Telemetry.captureError(
"no_reranker_recently_edited_retrieval",
error,
);
console.error("Error retrieving recently edited files:", error);
}
@ -53,6 +60,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,5 +1,6 @@
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -20,7 +21,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
await Telemetry.captureError("reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
let embeddingsChunks: Chunk[] = [];
@ -29,6 +31,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
await Telemetry.captureError("reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings chunks:", error);
}
@ -37,6 +40,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_recently_edited_retrieval", error);
console.error("Error retrieving recently edited files chunks:", error);
}
@ -50,6 +54,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,4 +1,5 @@
import * as crypto from "crypto";
import { expect, test } from "vitest";
import { LicenseKeyData, validateLicenseKey } from "./mdm";
// We'll create a real key pair once for all tests

View file

@ -1,13 +1,22 @@
import { DevDataLogEvent } from "@continuedev/config-yaml";
import fs from "fs";
import path from "path";
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { IdeInfo, IdeSettings } from "..";
import { Core } from "../core";
import { getDevDataFilePath } from "../util/paths";
import { DataLogger } from "./log";
// Only mock fetch, not fs
jest.mock("@continuedev/fetch");
vi.mock("@continuedev/fetch");
const TEST_EVENT: DevDataLogEvent = {
name: "tokensGenerated",
@ -54,7 +63,7 @@ describe("DataLogger", () => {
beforeEach(() => {
// Reset mocks
jest.clearAllMocks();
vi.clearAllMocks();
// Remove test file if it exists
if (fs.existsSync(testFilePath)) {
@ -67,7 +76,7 @@ describe("DataLogger", () => {
// Mock core and required promises
dataLogger.core = {
configHandler: {
loadConfig: jest.fn().mockResolvedValue({
loadConfig: vi.fn().mockResolvedValue({
config: {
data: [],
},
@ -78,7 +87,7 @@ describe("DataLogger", () => {
},
},
controlPlaneClient: {
getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
},
},
} as unknown as Core;
@ -184,7 +193,6 @@ describe("DataLogger", () => {
// Read file contents and verify
const fileContent = fs.readFileSync(filepath, "utf8");
console.log("debug1 filecontent", fileContent);
expect(fileContent).toContain('"eventName":"chatInteraction"');
expect(fileContent).toContain('"prompt":"Hello, world!"');
expect(fileContent).toContain('"completion":"Hello, world!"');
@ -195,10 +203,10 @@ describe("DataLogger", () => {
describe("logDevData", () => {
it("should log data locally and to configured destinations", async () => {
// Spy on logLocalData and logToOneDestination
const logLocalDataSpy = jest
const logLocalDataSpy = vi
.spyOn(dataLogger, "logLocalData")
.mockResolvedValue();
const logToOneDestinationSpy = jest
const logToOneDestinationSpy = vi
.spyOn(dataLogger, "logToOneDestination")
.mockResolvedValue();
@ -212,7 +220,7 @@ describe("DataLogger", () => {
},
};
dataLogger.core!.configHandler.loadConfig = jest
dataLogger.core!.configHandler.loadConfig = vi
.fn()
.mockResolvedValue(mockConfig);

View file

@ -1,3 +1,5 @@
import { describe, expect, test } from "vitest";
import { dedent } from "../util";
import { myersDiff } from "./myers";

View file

@ -1,6 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import { streamDiff } from "../diff/streamDiff.js";
@ -54,12 +56,7 @@ function displayDiff(diff: DiffLine[]) {
}
async function expectDiff(file: string) {
const testFilePath = path.join(
__dirname,
"diff",
"test-examples",
file + ".diff",
);
const testFilePath = path.join(__dirname, "test-examples", file + ".diff");
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
const [oldText, newText, expectedDiff] = testFileContents
.split("\n---\n")

View file

@ -1,8 +1,8 @@
// Generated by continue
import { matchLine, streamLines, generateLines } from "./util";
import { describe, expect, it, vi } from "vitest";
import { ChatMessage } from "../index";
import { jest } from "@jest/globals";
import { generateLines, matchLine, streamLines } from "./util";
describe.skip("matchLine", () => {
it("should match empty lines if the first old line is also empty", () => {
@ -146,7 +146,7 @@ describe("streamLines", () => {
content: "line4",
};
// const spy = jest.spyOn(messageContentModule, "renderChatMessage");
// const spy = vi.spyOn(messageContentModule, "renderChatMessage");
async function* streamCompletion(): AsyncGenerator<ChatMessage> {
yield messageChunk1;
@ -164,7 +164,7 @@ describe("streamLines", () => {
});
it("should log lines if log parameter is true", async () => {
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
async function* streamCompletion(): AsyncGenerator<string> {
yield "line1\nline2\n";

4
core/index.d.ts vendored
View file

@ -783,7 +783,7 @@ export interface IDE {
getSearchResults(query: string, maxResults?: number): Promise<string>;
getFileResults(pattern: string): Promise<string[]>;
getFileResults(pattern: string, maxResults?: number): Promise<string[]>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;
@ -1604,12 +1604,12 @@ export interface RuleWithSource {
slug?: string;
source: RuleSource;
globs?: string | string[];
regex?: string | string[];
rule: string;
description?: string;
ruleFile?: string;
alwaysApply?: boolean;
}
export interface CompleteOnboardingPayload {
mode: OnboardingModes;
provider?: string;

View file

@ -63,13 +63,12 @@ export async function* chunkDocument({
resolve({
...chunkWithoutId,
digest,
index,
index: index++,
filepath,
});
})();
}),
);
index++;
}
for await (const chunk of chunkPromises) {
if (!chunk) {

View file

@ -7,6 +7,7 @@ import {
} from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { getCleanUriPath } from "../../util/uri";
import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { RulePolicies } from "./types";
@ -52,6 +53,47 @@ const matchesGlobs = (
return false;
};
/**
* Checks if file content matches any of the provided regex regex
*
* @param fileContent - The content of the file to check
* @param regex - A single regex pattern string or array of regex pattern strings
* @returns true if the content matches any pattern (or if no regex is provided), false otherwise
*/
const contentMatchesRegex = (
fileContent: string,
regex: string | string[],
): boolean => {
// Handle single string pattern
if (typeof regex === "string") {
try {
const expression = new RegExp(regex);
return expression.test(fileContent);
} catch (e) {
console.error(`Invalid regex pattern: ${regex}`, e);
return false;
}
}
// Handle array of regex
if (Array.isArray(regex)) {
if (regex.length === 0) return true;
// Content must match at least one pattern
return regex.some((pattern) => {
try {
const regex = new RegExp(pattern);
return regex.test(fileContent);
} catch (e) {
console.error(`Invalid regex pattern: ${pattern}`, e);
return false;
}
});
}
return false;
};
/**
* Determines if a file path is within a specific directory or its subdirectories
*
@ -103,25 +145,67 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
return true;
}
// Root-level rules with no globs are implicitly global
if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
// Root-level rules with no globs or regex are implicitly global
if (
isRootLevelRule(rule) &&
!rule.globs &&
!rule.regex &&
rule.alwaysApply !== false
) {
return true;
}
return false;
};
const checkGlobsAndRegex = ({
rule,
filePaths,
fileContents,
}: {
rule: RuleWithSource;
filePaths: string[];
fileContents: Record<string, string>;
}) => {
const matchingFiles = rule.globs
? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
: filePaths;
// If no files match the globs, don't apply the rule
if (matchingFiles.length === 0) {
return false;
}
// Now check for pattern matches in file contents if regex are specified
if (rule.regex) {
// Check if any of the matching files also match the content regex
return matchingFiles.some((filePath) => {
const content = fileContents[filePath];
// If we don't have the content, we can't check regex
if (!content) return false;
return contentMatchesRegex(content, rule.regex!);
});
}
// If we have no regex or if we couldn't check regex (no content),
// just go with the glob matches
return matchingFiles.length > 0;
};
/**
* Determines if a rule should be applied based on its alwaysApply property and file path matching
* Determines if a rule should be applied based on its properties and file matching
*
* @param rule - The rule to check
* @param filePaths - Array of file paths to check against the rule's globs
* @param fileContents - Map of file paths to their contents for pattern matching
* @param rulePolicies - Optional policies that can override normal rule behavior
* @returns true if the rule should be applied, false otherwise
*/
export const shouldApplyRule = (
rule: RuleWithSource,
filePaths: string[],
rulePolicies: RulePolicies = {},
fileContents: Record<string, string> = {},
): boolean => {
const policy = rulePolicies[rule.name || ""];
@ -157,40 +241,27 @@ export const shouldApplyRule = (
isFileInDirectory(filePath, ruleDirPath),
);
// If no files are in this directory, don't apply the rule
if (filesInRuleDirectory.length === 0) {
return false;
}
// If we have globs, check if any files in this directory match them
if (rule.globs) {
return filesInRuleDirectory.some((filePath) =>
matchesGlobs(filePath, rule.globs),
);
}
// No globs but files are in this directory, so apply the rule
return true;
return checkGlobsAndRegex({
filePaths: filesInRuleDirectory,
fileContents,
rule,
});
}
// For root-level rules:
// If alwaysApply is explicitly false, only apply if there are globs AND they match
if (rule.alwaysApply === false) {
if (!rule.globs) {
return false;
}
return filePaths.some((path) => matchesGlobs(path, rule.globs));
// If alwaysApply is explicitly false, we need to check globs and/or regex
if (
rule.alwaysApply === false &&
rule.globs === undefined &&
rule.regex === undefined
) {
return false;
}
// Default behavior for root rules with globs:
// - Only apply if they match the globs
if (rule.globs) {
return filePaths.some((path) => matchesGlobs(path, rule.globs));
}
// This point should not be reached as we've handled all cases above
return false;
return checkGlobsAndRegex({
filePaths,
fileContents,
rule,
});
};
/**
@ -220,10 +291,34 @@ export const getApplicableRules = (
// Combine file paths from both sources
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
// Create a map of file paths to their contents for pattern matching
const fileContents: Record<string, string> = {};
// Extract contents from context items with file URIs
contextItems.forEach((item) => {
if (item.uri?.type === "file" && item.uri?.value) {
fileContents[item.uri.value] = item.content;
}
});
// Extract contents from code blocks in the message for paths that don't have content yet
if (userMessage) {
const messageContent = renderChatMessage(userMessage);
filePathsFromMessage.forEach((path) => {
// Only extract content if we don't already have it from context items
if (!fileContents[path]) {
const blockContent = extractContentFromCodeBlock(messageContent, path);
if (blockContent) {
fileContents[path] = blockContent;
}
}
});
}
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
// and path matching in a consistent way
const applicableRules = rules.filter((rule) =>
shouldApplyRule(rule, allFilePaths, rulePolicies),
shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
);
return applicableRules;

View file

@ -1,6 +1,14 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { shouldApplyRule } from "./getSystemMessageWithRules";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import {
getApplicableRules,
shouldApplyRule,
} from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule colocation glob matching", () => {
@ -244,3 +252,228 @@ describe("Rule policies", () => {
).toBe(false);
});
});
describe("Content pattern matching", () => {
it("should apply rules when file content matches pattern", () => {
// Rule with pattern to match React component files
const reactComponentRule: RuleWithSource = {
name: "React Component Rule",
rule: "Follow React component standards",
regex: "export (function|const) \\w+.*\\(",
source: "rules-block",
ruleFile: "src/components/rules.md",
};
// File that matches the pattern
const filePath = "src/components/Button.tsx";
const fileContents = {
[filePath]:
"export function Button() { return <button>Click me</button> }",
};
expect(
shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
).toBe(true);
// File that doesn't match the pattern
const nonMatchingContents = {
[filePath]:
"import React from 'react'; // Just an import, not a component",
};
expect(
shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
).toBe(false);
});
it("should support multiple regex regex as an array", () => {
// Rule with multiple regex
const multiPatternRule: RuleWithSource = {
name: "Multi-Pattern Rule",
rule: "Apply to functions or classes",
regex: ["function\\s+\\w+", "class\\s+\\w+"],
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
// Content with function - should match
const functionContent = {
[filePath]: "function formatDate(date) { return date.toISOString(); }",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
).toBe(true);
// Content with class - should match
const classContent = {
[filePath]:
"class DateFormatter { format(date) { return date.toISOString(); } }",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
).toBe(true);
// Content with neither - should not match
const nonMatchingContent = {
[filePath]: "const PI = 3.14159;",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
).toBe(false);
});
it("should apply rules based on both globs and regex when both are specified", () => {
// Rule with both glob and pattern restrictions
const typescriptClassRule: RuleWithSource = {
name: "TypeScript Class Rule",
rule: "Follow class standards in TypeScript",
globs: "**/*.ts",
regex: "class\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
};
const tsFilePath = "src/models/User.ts";
const jsFilePath = "src/models/Product.js";
// TypeScript file with class - should match
const tsClassContent = {
[tsFilePath]: "export class User { constructor(public name: string) {} }",
};
expect(
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
).toBe(true);
// TypeScript file without class - should not match
const tsNonClassContent = {
[tsFilePath]: "export const createUser = (name: string) => ({ name });",
};
expect(
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
).toBe(false);
// JavaScript file with class - should not match due to glob
const jsClassContent = {
[jsFilePath]:
"export class Product { constructor(name) { this.name = name; } }",
};
expect(
shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
).toBe(false);
});
it("should extract file content from messages for pattern matching", () => {
// Rule with pattern
const arrowFunctionRule: RuleWithSource = {
name: "Arrow Function Rule",
rule: "Use arrow functions for better this binding",
regex: "const\\s+\\w+\\s*=\\s*\\(",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
// Message with code block containing a matching pattern
const messageWithArrowFn: UserChatMessage = {
role: "user",
content:
"Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
};
// Create context item to match the file in the message
const contextItem: ContextItemWithId = {
id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
uri: { type: "file", value: "src/utils/formatter.ts" },
content: "const format = (date) => {\n return date.toISOString();\n};",
name: "formatter.ts",
description: "Utility formatter",
};
// Should match the pattern
const applicableRules = getApplicableRules(
messageWithArrowFn,
[arrowFunctionRule],
[contextItem],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Arrow Function Rule");
// Message with code block that doesn't match the pattern
const messageWithoutArrowFn: UserChatMessage = {
role: "user",
content:
"Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
};
// Context item with non-matching content
const nonMatchingContextItem: ContextItemWithId = {
id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
uri: { type: "file", value: "src/utils/formatter.ts" },
content: "function format(date) {\n return date.toISOString();\n}",
name: "formatter.ts",
description: "Utility formatter",
};
// Should not match the pattern
const nonApplicableRules = getApplicableRules(
messageWithoutArrowFn,
[arrowFunctionRule],
[nonMatchingContextItem],
);
expect(nonApplicableRules).toHaveLength(0);
});
it("should handle invalid regex regex gracefully", () => {
// Rule with invalid regex pattern
const invalidRegexRule: RuleWithSource = {
name: "Invalid Regex Rule",
rule: "This rule has an invalid regex pattern",
regex: "([unclosed parenthesis",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
const fileContents = {
[filePath]: "function helper() { return true; }",
};
// Should not throw an error but gracefully not apply the rule
expect(
shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
).toBe(false);
});
it("should respect directory restrictions for pattern rules", () => {
// Rule with pattern in a nested directory
const nestedPatternRule: RuleWithSource = {
name: "Nested Pattern Rule",
rule: "Apply only to model files with interfaces",
regex: "interface\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
};
// File in the correct directory with matching content
const modelFilePath = "src/models/User.ts";
const modelContents = {
[modelFilePath]: "export interface User { id: string; name: string; }",
};
expect(
shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
).toBe(true);
// File outside the directory with matching content - should not match
const utilFilePath = "src/utils/types.ts";
const utilContents = {
[utilFilePath]:
"export interface Config { apiUrl: string; timeout: number; }",
};
expect(
shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
).toBe(false);
});
});

View file

@ -0,0 +1,94 @@
import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
describe("extractContentFromCodeBlock", () => {
it("should extract content from code block with language and filepath", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
"const x = 1;",
);
});
it("should extract content from code block with filepath only (no language)", () => {
const content = "```test.js\nclass Calculator { }\n```";
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"class Calculator { }",
);
});
it("should extract content from code block with line ranges", () => {
const content = "```js test.js (19-25)\nfunction test() {}\n```";
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"function test() {}",
);
});
it("should handle multiple code blocks and find the right one", () => {
const content =
"```typescript src/main.ts\nconst x = 1;\n```\n" +
"```test.js\nclass Calculator { }\n```\n" +
"```js utils.js (19-25)\nfunction test() {}\n```";
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
"const x = 1;",
);
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"class Calculator { }",
);
expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
"function test() {}",
);
});
it("should handle paths with special regex characters", () => {
const content =
"```typescript src/special+chars.ts[123]\nconst special = true;\n```";
expect(
extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
).toBe("const special = true;");
});
it("should handle multiline content", () => {
const content =
"```typescript src/multi-line.ts\n" +
"function example() {\n" +
" const x = 1;\n" +
" return x + 2;\n" +
"}\n" +
"```";
const expected =
"function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
expected,
);
});
it("should return undefined when path doesn't exist in any code block", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(
extractContentFromCodeBlock(content, "nonexistent.ts"),
).toBeUndefined();
});
it("should extract content when the path has directory structure", () => {
const content =
"```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
expect(
extractContentFromCodeBlock(content, "src/components/Button.jsx"),
).toBe("const Button = () => <button>Click me</button>;");
});
it("should match exact paths only", () => {
const content =
"```typescript src/utils.ts\nconst util = {};\n```\n" +
"```typescript src/utils/index.ts\nconst index = {};\n```";
expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
"const util = {};",
);
expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
"const index = {};",
);
});
});

View file

@ -0,0 +1,33 @@
/**
* Extracts content from code blocks with given path
* @param content The full message content
* @param path The file path to look for
* @returns The content of the code block if found, undefined otherwise
*/
export function extractContentFromCodeBlock(
content: string,
path: string,
): string | undefined {
// Escape special characters in the path for regex
const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Match the code block with this path
// This regex looks for:
// 1. Code block start with the path (```[language] path)
// 2. The content until the closing ```
// The path can be:
// - With language: ```typescript src/main.ts
// - Without language: ```src/main.ts
// - With line ranges: ```js src/main.ts (1-10)
const regex = new RegExp(
`\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
"m",
);
const match = content.match(regex);
if (match && match[1]) {
return match[1];
}
return undefined;
}

View file

@ -30,7 +30,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
openUrl: [string, void];
runCommand: [{ command: string; options?: TerminalOptions }, void];
getSearchResults: [{ query: string; maxResults?: number }, string];
getFileResults: [{ pattern: string }, string[]];
getFileResults: [{ pattern: string; maxResults?: number }, string[]];
subprocess: [{ command: string; cwd?: string }, [string, string]];
saveFile: [{ filepath: string }, void];
fileExists: [{ filepath: string }, boolean];

View file

@ -163,7 +163,7 @@ export class ReverseMessageIde {
});
this.on("getFileResults", (data) => {
return this.ide.getFileResults(data.pattern);
return this.ide.getFileResults(data.pattern, data.maxResults);
});
this.on("getProblems", (data) => {

View file

@ -37,6 +37,11 @@ export const createRuleBlock: Tool = {
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
},
regex: {
type: "string",
description:
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
},
},
},
},

View file

@ -12,7 +12,8 @@ export const globSearchTool: Tool = {
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FileGlobSearch,
description: "Search for files in the project",
description:
"Search for files in the project. Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],

View file

@ -7,16 +7,24 @@ export type CreateRuleBlockArgs = Pick<
Required<RuleWithSource>,
"rule" | "description" | "alwaysApply" | "name"
> &
Pick<RuleWithSource, "globs">;
Pick<RuleWithSource, "globs" | "regex">;
export const createRuleBlockImpl: ToolImpl = async (
args: CreateRuleBlockArgs,
extras,
) => {
const fileContent = createRuleMarkdown(args.name, args.rule, {
// Create options object with the fields that createRuleMarkdown expects
const options: any = {
description: args.description,
globs: args.globs,
});
};
// Add regex if provided
if (args.regex) {
options.regex = args.regex;
}
const fileContent = createRuleMarkdown(args.name, args.rule, options);
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);

View file

@ -1,12 +1,28 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
const MAX_AGENT_GLOB_RESULTS = 100;
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
const results = await extras.ide.getFileResults(args.pattern);
return [
const results = await extras.ide.getFileResults(
args.pattern,
MAX_AGENT_GLOB_RESULTS,
);
const contextItems: ContextItem[] = [
{
name: "File results",
description: "Results from file glob search",
content: results.join("\n"),
},
];
// In case of truncation, add a warning
if (results.length === MAX_AGENT_GLOB_RESULTS) {
contextItems.push({
name: "Truncation warning",
description: "Inform the model that results were truncated",
content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`,
});
}
return contextItems;
};

View file

@ -238,7 +238,10 @@ class FileSystemIde implements IDE {
return "";
}
async getFileResults(pattern: string): Promise<string[]> {
async getFileResults(
pattern: string,
maxResults?: number,
): Promise<string[]> {
return [];
}

View file

@ -4,6 +4,7 @@ import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
import { IdeInfo } from "../index.js";
import type { PostHog as PostHogType } from "posthog-node";
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
export enum PosthogFeatureFlag {
AutocompleteTimeout = "autocomplete-timeout",
@ -37,6 +38,24 @@ export class Telemetry {
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
/**
* Convenience method for capturing errors in a single event
*/
static async captureError(errorName: string, error: unknown) {
if (!(error instanceof Error)) {
return;
}
await Telemetry.capture(
"extension_error_caught",
{
errorName,
message: error.message,
stack: extractMinimalStackTraceInfo(error.stack),
},
false,
);
}
static async capture(
event: string,
properties: { [key: string]: any },

View file

@ -31,7 +31,8 @@ Continue includes several built-in tools which provide the model access to IDE f
- **Read file** (`builtin_read_file`): read the contents of a file within the project
- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file
- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model
- **Grep search** (`builtin_grep_search`): perform a `ripgrep` search within the project. Results are limited to 100 results and 5000 characters (model is warned if this is exceeded)
- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project
- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root
- **Search web** (`builtin_search_web`): Perform a web search to get top results
- **View diff** (`builtin_view_diff`): View the current working git diff

View file

@ -63,6 +63,7 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark
- `name` (**required** for YAML): A display name/title for the rule
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
- `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`).
- `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context.
- `alwaysApply`: true - Always include the rule, regardless of file context
- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.24
pluginVersion=1.0.25
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -0,0 +1,56 @@
# Continue JetBrains Extension
## Project Purpose
JetBrains/IntelliJ extension for Continue AI code assistant. Provides chat, autocomplete, inline edit, and agent features within JetBrains IDEs.
## Architecture
- **Language**: Kotlin (JDK 17), Gradle build
- **Communication**: stdin/stdout message passing with core binary from `../../binary`
- **UI**: Embeds React webview from `../../gui`
- **Platform**: IntelliJ Platform Plugin (IDEA, PyCharm, WebStorm, etc.)
## Key Source Structure
```
src/main/kotlin/com/github/continuedev/continueintellijextension/
├── continue/ # Core integration (CoreMessenger, IntelliJIde, IdeProtocolClient)
├── autocomplete/ # Code completion logic
├── editor/ # Diff handling, inline edits
├── toolWindow/ # Main UI panel
├── services/ # Settings, plugin lifecycle
├── actions/ # Keyboard shortcuts, menu actions
├── protocol/ # Message type definitions
└── constants/ # App constants, paths
src/main/resources/
├── META-INF/plugin.xml # Plugin configuration
└── webview/ # Embedded React UI assets
```
## Core Files
- `IntelliJIde.kt`: Main IDE interface implementation
- `CoreMessenger.kt`: Binary communication handler
- `plugin.xml`: Plugin manifest and extension points
- `build.gradle.kts`: Build configuration
- `ContinuePluginService.kt`: Main service orchestrator
## Message Protocol
JSON messages between Extension ↔ Core ↔ GUI. Message types in `constants/MessageTypes.kt`. Extension relays messages between core binary and webview.
## Testing
- Unit tests: `src/test/kotlin/`
- E2E tests: UI automation with intellij-ui-test-robot
- Test command: `./gradlew test`
- Debug: `runIde` Gradle task
## Key Integration Points
- File operations via IntelliJ VFS
- Editor integration for diffs/autocomplete
- Git operations for repository context
- Settings via IntelliJ platform storage

View file

@ -365,7 +365,7 @@ class IdeProtocolClient(
dataElement.toString(),
GetFileResultsParams::class.java
)
val results = ide.getFileResults(params.pattern)
val results = ide.getFileResults(params.pattern, params.maxResults)
respond(results)
}

View file

@ -315,11 +315,11 @@ class IntelliJIDE(
return getOpenFiles()
}
override suspend fun getFileResults(pattern: String): List<String> {
override suspend fun getFileResults(pattern: String, maxResults: Int?): List<String> {
val ideInfo = this.getIdeInfo()
if (ideInfo.remoteName == "local") {
try {
val command = GeneralCommandLine(
var commandArgs = mutableListOf<String>(
ripgrep,
"--files",
"--iglob",
@ -327,8 +327,14 @@ class IntelliJIDE(
"--ignore-file",
".continueignore",
"--ignore-file",
".gitignore",
".gitignore"
)
if (maxResults != null) {
commandArgs.add("--max-count")
commandArgs.add(maxResults.toString())
}
val command = GeneralCommandLine(commandArgs)
command.setWorkDirectory(project.basePath)
val results = ExecUtil.execAndGetOutput(command).stdout

View file

@ -23,7 +23,7 @@ typealias getTagsParams = String
data class GetSearchResultsParams(val query: String, val maxResults: Int?)
data class GetFileResultsParams(val pattern: String)
data class GetFileResultsParams(val pattern: String, val maxResults: Int?)
data class SaveFileParams(val filepath: String)

View file

@ -159,7 +159,7 @@ interface IDE {
suspend fun getSearchResults(query: String, maxResults: Int?): String
suspend fun getFileResults(pattern: String): List<String>
suspend fun getFileResults(pattern: String, maxResults: Int?): List<String>
// Note: This should be a `Pair<String, String>` but we use `List<Any>` because the keys of `Pair`
// will serialize to `first and `second` rather than `0` and `1` like in JavaScript

View file

@ -30,14 +30,14 @@ export class AutocompleteActions {
expect(ghostText1).to.equal(messagePair1.llmResponse);
}
public static async forceCompletion(editor: TextEditor): Promise<string> {
public static async forceCompletion(editor: TextEditor): Promise<string> {
await editor.setText("def main():\n ");
await editor.moveCursor(2, 5);
await new Workbench().executeCommand("Continue: Force Autocomplete");
const ghostText = await TestUtils.waitForSuccess(() =>
AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver)
AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver),
);
return ghostText;

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.48",
"version": "1.1.49",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.48",
"version": "1.1.49",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.49",
"version": "1.1.50",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -0,0 +1,6 @@
The `extensions/vscode` folder contains code for the "Continue" VS Code Extension. Continue is a coding assistant extension which extends IDE functionality with AI.
Core IDE functionality, such as reading files, is implemented using the `VSCodeIDE` class. Code to enable editing/diff streaming into the editor, code suggestion autocompletion, and more can also be found in this directory.
Shared code that has abstract logic for the extension is in `core/`. Avoid importing code from `core/` directly where possible. Core is designed to be bundalable as a binary. Use `core.invoke` to send messages to the
- see `core/protocol/core.ts` for a list of commands VS Code can post/request to Core
- see `core/portocol/ide.ts` for a list of commands/message types core can post/request to VS Code

View file

@ -433,8 +433,10 @@ class VsCodeIde implements IDE {
});
}
async getFileResults(pattern: string): Promise<string[]> {
const MAX_FILE_RESULTS = 200;
async getFileResults(
pattern: string,
maxResults?: number,
): Promise<string[]> {
if (vscode.env.remoteName) {
// TODO better tests for this remote search implementation
// throw new Error("Ripgrep not supported, this workspace is remote");
@ -501,7 +503,7 @@ class VsCodeIde implements IDE {
const results = await vscode.workspace.findFiles(
pattern,
ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
MAX_FILE_RESULTS,
maxResults,
);
return results.map((result) => vscode.workspace.asRelativePath(result));
} else {
@ -515,12 +517,20 @@ class VsCodeIde implements IDE {
".continueignore",
"--ignore-file",
".gitignore",
...(maxResults ? ["--max-count", String(maxResults)] : []),
]);
results.push(dirResults);
}
return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS);
const allResults = results.join("\n").split("\n");
if (maxResults) {
// In the case of multiple workspaces, maxResults will be applied to each workspace
// And then the combined results will also be truncated
return allResults.slice(0, maxResults);
} else {
return allResults;
}
}
}

View file

@ -324,7 +324,7 @@ export class VsCodeMessenger {
return ide.getSearchResults(msg.data.query, msg.data.maxResults);
});
this.onWebviewOrCore("getFileResults", async (msg) => {
return ide.getFileResults(msg.data.pattern);
return ide.getFileResults(msg.data.pattern, msg.data.maxResults);
});
this.onWebviewOrCore("subprocess", async (msg) => {
return ide.subprocess(msg.data.command, msg.data.cwd);

View file

@ -0,0 +1,51 @@
import {
ArrowRightEndOnRectangleIcon,
UserCircleIcon as UserCircleIconOutline,
} from "@heroicons/react/24/outline";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import { useAuth } from "../../context/Auth";
import { ListboxOption, useFontSize } from "../ui";
interface AccountOptionProps {
onClose: () => void;
}
export function AccountOption({ onClose }: AccountOptionProps) {
const { session, logout, login } = useAuth();
const tinyFont = useFontSize(-4);
// No account option for on-prem deployments
if (session && isOnPremSession(session)) {
return null;
}
async function handleClick() {
if (session) {
logout();
} else {
await login(false);
}
onClose();
}
return (
<ListboxOption
value={session ? "log-out" : "sign-in"}
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={handleClick}
>
<div
className="text-description flex flex-row items-center"
style={{ fontSize: tinyFont }}
>
{session ? (
<ArrowRightEndOnRectangleIcon className="mr-1 h-3 w-3" />
) : (
<UserCircleIconOutline className="mr-1 h-3 w-3" />
)}
{session ? "Log out" : "Sign in"}
</div>
</ListboxOption>
);
}

View file

@ -1,13 +1,13 @@
import { ComputerDesktopIcon, SparklesIcon } from "@heroicons/react/24/outline";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import { isLocalProfile } from "../../../util";
import { isLocalProfile } from "../../util";
export interface AssistantIconProps {
assistant: ProfileDescription;
size?: number;
}
export default function AssistantIcon({ assistant, size }: AssistantIconProps) {
export function AssistantIcon({ assistant, size }: AssistantIconProps) {
const sizeTw = size ?? 4;
if (isLocalProfile(assistant)) {
return (

View file

@ -0,0 +1,118 @@
import {
ArrowTopRightOnSquareIcon,
Cog6ToothIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import { useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch } from "../../redux/hooks";
import { setSelectedProfile } from "../../redux/slices/profilesSlice";
import { isLocalProfile } from "../../util";
import { ROUTES } from "../../util/navigation";
import { useLump } from "../mainInput/Lump/LumpContext";
import { ListboxOption, useFontSize } from "../ui";
import { AssistantIcon } from "./AssistantIcon";
interface AssistantOptionProps {
profile: ProfileDescription;
selected: boolean;
onClick: () => void;
}
export function AssistantOption({
profile,
selected,
onClick,
}: AssistantOptionProps) {
const tinyFont = useFontSize(-4);
const navigate = useNavigate();
const { setSelectedSection } = useLump();
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const hasFatalErrors = useMemo(() => {
return !!profile.errors?.find((error) => error.fatal);
}, [profile.errors]);
function handleOptionClick() {
// optimistic update
dispatch(setSelectedProfile(profile.id));
// notify core which will handle actual update
ideMessenger.post("didChangeSelectedProfile", {
id: profile.id,
});
onClick();
}
function handleConfigure() {
ideMessenger.post("config/openProfile", { profileId: profile.id });
onClick();
}
function handleClickError() {
if (profile.id === "local") {
navigate(ROUTES.HOME);
setSelectedSection("error");
} else {
ideMessenger.post("config/openProfile", { profileId: profile.id });
}
onClick();
}
return (
<ListboxOption
value={profile.id}
disabled={hasFatalErrors}
onClick={!hasFatalErrors ? handleOptionClick : undefined}
fontSizeModifier={-2}
className={selected ? "bg-list-active text-list-active-foreground" : ""}
>
<div className="flex w-full items-center justify-between gap-2">
<div className="flex w-full items-center gap-2">
<div className="flex h-4 w-4 flex-shrink-0">
<AssistantIcon size={3.5} assistant={profile} />
</div>
<span
className={`line-clamp-1 flex-1 ${selected ? "font-semibold" : ""}`}
>
{profile.title}
</span>
</div>
<div className="flex flex-row items-center gap-1">
{profile.errors && profile.errors?.length > 0 && (
<ExclamationTriangleIcon
data-tooltip-id={`${profile.id}-errors-tooltip`}
className="text-error h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleClickError();
}}
/>
)}
{isLocalProfile(profile) ? (
<Cog6ToothIcon
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
) : (
<ArrowTopRightOnSquareIcon
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
)}
</div>
</div>
</ListboxOption>
);
}

View file

@ -0,0 +1,54 @@
import { ArrowPathIcon } from "@heroicons/react/24/outline";
import { useState } from "react";
import { useAuth } from "../../context/Auth";
import { cn } from "../../util/cn";
import { AssistantOption } from "./AssistantOption";
interface AssistantOptionsProps {
selectedProfileId: string | undefined;
onClose: () => void;
}
export function AssistantOptions({
selectedProfileId,
onClose,
}: AssistantOptionsProps) {
const [loading, setLoading] = useState(false);
const { profiles, refreshProfiles } = useAuth();
return (
<>
{/* Assistants Section Header */}
<div className="flex gap-1.5 px-3 pb-1 pt-2">
<label className="text-vsc-foreground font-semibold">Assistants</label>
<div
className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"
onClick={async (e) => {
e.stopPropagation();
setLoading(true);
await refreshProfiles();
setLoading(false);
}}
>
<ArrowPathIcon
className={cn(
"text-description h-2.5 w-2.5",
loading && "animate-spin-slow",
)}
/>
</div>
</div>
<div className="thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto">
{profiles?.map((profile, idx) => (
<AssistantOption
key={idx}
profile={profile}
onClick={onClose}
selected={profile.id === selectedProfileId}
/>
))}
</div>
</>
);
}

View file

@ -4,12 +4,6 @@ import {
} from "@heroicons/react/24/outline";
import { UserCircleIcon } from "@heroicons/react/24/solid";
import { useContext } from "react";
import {
Listbox,
ListboxButton,
ListboxOption,
ListboxOptions,
} from "../../components/ui/Listbox";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
@ -17,10 +11,29 @@ import {
selectCurrentOrg,
setSelectedOrgId,
} from "../../redux/slices/profilesSlice";
import {
Listbox,
ListboxButton,
ListboxOption,
ListboxOptions,
} from "../ui/Listbox";
interface ScopeSelectProps {
onSelect?: () => void;
}
function getOrgIcon(org: { name: string; iconUrl?: string | null }) {
if (org.iconUrl) {
return (
<img src={org.iconUrl} alt="" className="h-3.5 w-3.5 rounded-full" />
);
}
const IconComponent =
org.name === "Personal" ? UserCircleIcon : BuildingOfficeIcon;
return <IconComponent className="h-3.5 w-3.5" />;
}
export function ScopeSelect({ onSelect }: ScopeSelectProps) {
const { organizations } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
@ -39,10 +52,6 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) {
onSelect?.();
};
const CurScopeEntityFallBackIcon = selectedOrgId
? BuildingOfficeIcon
: UserCircleIcon;
const selectedDisplay = currentOrg ?? {
name: "Personal",
iconUrl: null,
@ -53,27 +62,19 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) {
<div className="relative">
<ListboxButton className="hover:bg-list-active hover:text-list-active-foreground w-full min-w-[140px] justify-between px-4 py-2 sm:min-w-[200px]">
<div className="flex items-center gap-2">
{selectedDisplay?.iconUrl ? (
<img src={selectedDisplay.iconUrl} alt="" className="h-5 w-5" />
) : (
<CurScopeEntityFallBackIcon className="h-5 w-5" />
)}
{getOrgIcon(selectedDisplay)}
<span className="truncate">
{selectedDisplay?.name || "Select Organization"}
</span>
</div>
<ChevronUpDownIcon className="h-5 w-5" aria-hidden="true" />
<ChevronUpDownIcon className="h-3.5 w-3.5" aria-hidden="true" />
</ListboxButton>
<ListboxOptions className="z-[1000] min-w-[140px] pt-0.5 sm:min-w-[200px]">
{organizations.map((org) => (
<ListboxOption key={org.id} value={org.id} className="py-2">
<div className="flex items-center gap-2">
{org.iconUrl ? (
<img src={org.iconUrl} alt="" className="h-5 w-5" />
) : (
<BuildingOfficeIcon className="h-5 w-5" />
)}
{getOrgIcon(org)}
<span>{org.name}</span>
</div>
</ListboxOption>

View file

@ -0,0 +1,38 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import type { ProfileDescription } from "core/config/ConfigHandler";
import { fontSize } from "../../util";
import { useLump } from "../mainInput/Lump/LumpContext";
import { ListboxButton } from "../ui";
import { AssistantIcon } from "./AssistantIcon";
interface SelectedAssistantButtonProps {
selectedProfile: ProfileDescription;
}
export function SelectedAssistantButton({
selectedProfile,
}: SelectedAssistantButtonProps) {
const { isToolbarExpanded } = useLump();
return (
<ListboxButton
data-testid="assistant-select-button"
className="text-description border-none bg-transparent hover:brightness-125"
style={{ fontSize: fontSize(-3) }}
>
<div className="flex flex-row items-center gap-1.5">
<div className="h-3 w-3 flex-shrink-0 select-none">
<AssistantIcon size={3} assistant={selectedProfile} />
</div>
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
{selectedProfile.title}
</span>
</div>
<ChevronDownIcon
className="h-2 w-2 flex-shrink-0 select-none"
aria-hidden="true"
/>
</ListboxButton>
);
}

View file

@ -0,0 +1,171 @@
import { PlusIcon } from "@heroicons/react/24/outline";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import { useContext, useEffect, useRef } from "react";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
selectCurrentOrg,
setSelectedProfile,
} from "../../redux/slices/profilesSlice";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { useLump } from "../mainInput/Lump/LumpContext";
import {
Listbox,
ListboxOption,
ListboxOptions,
Transition,
useFontSize,
} from "../ui";
import { AccountOption } from "./AccountOption";
import { AssistantOptions } from "./AssistantOptions";
import { ScopeSelect } from "./ScopeSelect";
import { SelectedAssistantButton } from "./SelectedAssistantButton";
export function AssistantAndOrgListbox() {
const dispatch = useAppDispatch();
const listboxRef = useRef<HTMLDivElement>(null);
const currentOrg = useAppSelector(selectCurrentOrg);
const ideMessenger = useContext(IdeMessengerContext);
const { isToolbarExpanded } = useLump();
const { profiles, selectedProfile, session, login, organizations } =
useAuth();
const smallFont = useFontSize(-3);
const tinyFont = useFontSize(-4);
const shouldRenderOrgInfo =
session && organizations.length > 1 && !isOnPremSession(session);
function close() {
// Close the listbox by clicking outside or programmatically
const event = new KeyboardEvent("keydown", { key: "Escape" });
document.dispatchEvent(event);
}
function onNewAssistant() {
void ideMessenger.request("controlPlane/openUrl", {
path: "/new",
orgSlug: currentOrg?.slug,
});
close();
}
useEffect(() => {
let lastToggleTime = 0;
const DEBOUNCE_MS = 800;
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === "'" &&
isMetaEquivalentKeyPressed(event as any) &&
event.shiftKey
) {
const now = Date.now();
if (now - lastToggleTime >= DEBOUNCE_MS) {
lastToggleTime = now;
const profileIds = profiles?.map((profile) => profile.id) ?? [];
// In case of 1 or 0 profiles just does nothing
if (profileIds.length < 2) {
return;
}
let nextId = profileIds[0];
if (selectedProfile) {
const curIndex = profileIds.indexOf(selectedProfile.id);
const nextIndex = (curIndex + 1) % profileIds.length;
nextId = profileIds[nextIndex];
}
// Optimistic update
dispatch(setSelectedProfile(nextId));
ideMessenger.post("didChangeSelectedProfile", {
id: nextId,
});
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [currentOrg, selectedProfile]);
if (!selectedProfile) {
return (
<div
onClick={() => {
void ideMessenger.request("controlPlane/openUrl", {
path: "/new?type=assistant",
orgSlug: currentOrg?.slug,
});
}}
className="text-description flex cursor-pointer select-none items-center gap-1"
style={{ fontSize: smallFont }}
>
<PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
Create your first assistant
</span>
</div>
);
}
return (
<Listbox>
<div className="relative" ref={listboxRef}>
<SelectedAssistantButton selectedProfile={selectedProfile} />
<Transition>
<ListboxOptions className="-translate-x-1.5 pb-0">
{shouldRenderOrgInfo && (
<div className="border-border border-x-0 border-t-0 border-solid px-2 py-3">
<div className="flex flex-col gap-2 pb-1 pl-1">
<span className="text-description-muted flex items-center pb-1">
{session.account.id}
</span>
<label className="text-vsc-foreground font-semibold">
Organization
</label>
<ScopeSelect />
</div>
</div>
)}
<AssistantOptions
selectedProfileId={selectedProfile.id}
onClose={close}
/>
{/* Bottom Actions */}
<div className="border-border border-x-0 border-b-0 border-t border-solid">
<ListboxOption
value="new-assistant"
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={session ? onNewAssistant : () => login(false)}
>
<span
className="text-description flex flex-row items-center"
style={{ fontSize: tinyFont }}
>
<PlusIcon className="mr-1 h-3 w-3" /> New Assistant
</span>
</ListboxOption>
<AccountOption onClose={close} />
<div
className="text-description border-border flex items-center justify-between gap-1.5 border-x-0 border-b-0 border-t border-solid px-2 py-2"
style={{ fontSize: tinyFont }}
>
<span className="block" style={{ fontSize: tinyFont - 1 }}>
<code>{getMetaKeyLabel()} ⇧ '</code> to toggle assistant
</span>
</div>
</div>
</ListboxOptions>
</Transition>
</div>
</Listbox>
);
}

View file

@ -10,8 +10,8 @@ import {
defaultBorderRadius,
lightGray,
vscCommandCenterInactiveBorder,
} from "../..";
import { ToolTip } from "../../gui/Tooltip";
} from "..";
import { ToolTip } from "../gui/Tooltip";
export const OptionDiv = styled.div<{
isDisabled?: boolean;

View file

@ -1,11 +1,10 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { FreeTrialStatus } from "core/control-plane/client";
import { useContext } from "react";
import { Button, SecondaryButton, vscButtonBackground } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { fontSize } from "../../../util";
import { Listbox, ListboxButton, ListboxOptions, Transition } from "../../ui";
import { useFontSize } from "../../ui/font";
import { Button, SecondaryButton, vscButtonBackground } from ".";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { fontSize } from "../util";
import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui";
interface ProgressBarProps {
label: string;
@ -78,8 +77,6 @@ interface FreeTrialButtonProps {
export default function FreeTrialButton({
freeTrialStatus,
}: FreeTrialButtonProps) {
const smallFont = useFontSize(-3);
const tinyFont = useFontSize(-4);
const ideMessenger = useContext(IdeMessengerContext);
return (

View file

@ -1,4 +1,8 @@
import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import {
AtSymbolIcon,
LightBulbIcon,
PhotoIcon,
} from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
import { useContext, useRef } from "react";
@ -10,8 +14,10 @@ import {
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
import { exitEdit } from "../../redux/thunks/edit";
import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { cn } from "../../util/cn";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import { ModeSelect } from "../ModeSelect";
@ -51,6 +57,9 @@ function InputToolbar(props: InputToolbarProps) {
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const hasReasoningEnabled = useAppSelector(
(store) => store.session.hasReasoningEnabled,
);
const isEnterDisabled =
props.disabled ||
@ -143,6 +152,25 @@ function InputToolbar(props: InputToolbarProps) {
</ToolTip>
</HoverItem>
)}
{defaultModel?.provider === "anthropic" && (
<HoverItem
onClick={() =>
dispatch(setHasReasoningEnabled(!hasReasoningEnabled))
}
>
<LightBulbIcon
data-tooltip-id="model-reasoning-tooltip"
className={cn(
"h-3 w-3 hover:brightness-150",
hasReasoningEnabled && "brightness-200",
)}
/>
<ToolTip id="model-reasoning-tooltip" place="top">
Use Model Reasoning
</ToolTip>
</HoverItem>
)}
</div>
</div>

View file

@ -13,9 +13,8 @@ import { ReactNode, useContext, useEffect, useState } from "react";
import { vscBadgeForeground } from "../../..";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../redux/hooks";
import FreeTrialButton from "../../../FreeTrialButton";
import { ToolTip } from "../../../gui/Tooltip";
import AssistantSelect from "../../../modelSelection/platform/AssistantSelect";
import FreeTrialButton from "../../../modelSelection/platform/FreeTrialButton";
import { useFontSize } from "../../../ui/font";
import HoverItem from "../../InputToolbar/HoverItem";
import { useLump } from "../LumpContext";
@ -25,6 +24,7 @@ import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSecti
import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey";
import type { FreeTrialStatus } from "core/control-plane/client";
import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox";
interface BlockSettingsToolbarIcon {
title: string;
@ -236,7 +236,7 @@ export function BlockSettingsTopToolbar() {
{isUsingFreeTrial ? (
<FreeTrialButton freeTrialStatus={freeTrialStatus} />
) : (
<AssistantSelect />
<AssistantAndOrgListbox />
)}
<ToolTip id="assistant-select-tooltip" place="top">
{isUsingFreeTrial ? "View free trial usage" : "Select Assistant"}

View file

@ -1,388 +0,0 @@
import {
ArrowPathIcon,
ArrowTopRightOnSquareIcon,
BuildingOfficeIcon,
ChevronDownIcon,
Cog6ToothIcon,
ExclamationTriangleIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import type { ProfileDescription } from "core/config/ConfigHandler";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
selectCurrentOrg,
setSelectedOrgId,
setSelectedProfile,
} from "../../../redux/slices/profilesSlice";
import {
fontSize,
getMetaKeyLabel,
isLocalProfile,
isMetaEquivalentKeyPressed,
} from "../../../util";
import { cn } from "../../../util/cn";
import { ROUTES } from "../../../util/navigation";
import { useLump } from "../../mainInput/Lump/LumpContext";
import {
Listbox,
ListboxButton,
ListboxOption,
ListboxOptions,
Transition,
useFontSize,
} from "../../ui";
import AssistantIcon from "./AssistantIcon";
interface AssistantSelectOptionProps {
profile: ProfileDescription;
selected: boolean;
onClick: () => void;
}
const AssistantSelectOption = ({
profile,
selected,
onClick,
}: AssistantSelectOptionProps) => {
const tinyFont = useFontSize(-4);
const navigate = useNavigate();
const { setSelectedSection } = useLump();
const hasFatalErrors = useMemo(() => {
return !!profile.errors?.find((error) => error.fatal);
}, [profile.errors]);
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
function handleOptionClick() {
// optimistic update
dispatch(setSelectedProfile(profile.id));
// notify core which will handle actual update
ideMessenger.post("didChangeSelectedProfile", {
id: profile.id,
});
onClick();
}
function handleConfigure() {
ideMessenger.post("config/openProfile", { profileId: profile.id });
onClick();
}
function handleClickError() {
if (profile.id === "local") {
navigate(ROUTES.HOME);
setSelectedSection("error");
} else {
ideMessenger.post("config/openProfile", { profileId: profile.id });
}
onClick();
}
return (
<ListboxOption
value={profile.id}
disabled={hasFatalErrors}
onClick={!hasFatalErrors ? handleOptionClick : undefined}
fontSizeModifier={-2}
className={selected ? "bg-list-active text-list-active-foreground" : ""}
>
<div
className="flex w-full flex-col gap-0.5"
style={{
fontSize: tinyFont,
}}
>
<div className="flex w-full items-center justify-between gap-2 bg-transparent">
<div className="flex w-full items-center gap-1">
<div className="flex h-4 w-4 flex-shrink-0">
<AssistantIcon size={3.5} assistant={profile} />
</div>
<span
className={`line-clamp-1 flex-1 ${selected ? "font-semibold" : ""}`}
>
{profile.title}
</span>
</div>
<div className="flex flex-row items-center gap-1">
{profile.errors && profile.errors?.length > 0 && (
<ExclamationTriangleIcon
data-tooltip-id={`${profile.id}-errors-tooltip`}
className="text-error h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleClickError();
}}
/>
)}
{isLocalProfile(profile) ? (
<Cog6ToothIcon
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
) : (
<ArrowTopRightOnSquareIcon
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
handleConfigure();
}}
/>
)}
</div>
</div>
</div>
</ListboxOption>
);
};
export default function AssistantSelect() {
const dispatch = useAppDispatch();
const buttonRef = useRef<HTMLButtonElement>(null);
const currentOrg = useAppSelector(selectCurrentOrg);
const orgs = useAppSelector((store) => store.profiles.organizations);
const ideMessenger = useContext(IdeMessengerContext);
const { isToolbarExpanded } = useLump();
const [loading, setLoading] = useState(false);
const { profiles, session, login, selectedProfile, refreshProfiles } =
useAuth();
function close() {
if (buttonRef.current) {
buttonRef.current.click();
}
}
function onNewAssistant() {
ideMessenger.post("controlPlane/openUrl", {
path: "new",
orgSlug: currentOrg?.slug,
});
close();
}
useEffect(() => {
let lastToggleTime = 0;
const DEBOUNCE_MS = 800;
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === "'" &&
isMetaEquivalentKeyPressed(event as any) &&
event.shiftKey
) {
const now = Date.now();
if (now - lastToggleTime >= DEBOUNCE_MS) {
lastToggleTime = now;
const profileIds = profiles?.map((profile) => profile.id) ?? [];
// In case of 1 or 0 profiles just does nothing
if (profileIds.length < 2) {
return;
}
let nextId = profileIds[0];
if (selectedProfile) {
const curIndex = profileIds.indexOf(selectedProfile.id);
const nextIndex = (curIndex + 1) % profileIds.length;
nextId = profileIds[nextIndex];
}
// Optimistic update
dispatch(setSelectedProfile(nextId));
ideMessenger.post("didChangeSelectedProfile", {
id: nextId,
});
}
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [currentOrg, selectedProfile]);
const cycleOrgs = () => {
if (!session) {
void login(false);
return;
}
const orgIds = orgs.map((org) => org.id);
if (orgIds.length < 2) {
return;
}
let nextId = orgIds[0];
if (currentOrg) {
const curIndex = orgIds.indexOf(currentOrg.id);
const nextIndex = (curIndex + 1) % orgIds.length;
nextId = orgIds[nextIndex];
}
// Optimistic update
dispatch(setSelectedOrgId(nextId));
ideMessenger.post("didChangeSelectedOrg", {
id: nextId,
});
};
const tinyFont = useFontSize(-4);
const smallFont = useFontSize(-3);
if (!selectedProfile) {
return (
<div
onClick={() => {
void ideMessenger.request("controlPlane/openUrl", {
path: "/new?type=assistant",
orgSlug: currentOrg?.slug,
});
}}
className="text-description flex cursor-pointer select-none items-center gap-1"
style={{ fontSize: smallFont }}
>
<PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
Create your first assistant
</span>
</div>
);
}
return (
<Listbox>
<div className="relative">
<ListboxButton
data-testid="assistant-select-button"
ref={buttonRef}
className="text-description border-none bg-transparent hover:brightness-125"
style={{ fontSize: fontSize(-3) }}
>
<div className="flex flex-row items-center gap-1.5">
<div className="h-3 w-3 flex-shrink-0 select-none">
<AssistantIcon size={3} assistant={selectedProfile} />
</div>
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
{selectedProfile.title}
</span>
</div>
<ChevronDownIcon
className="h-2 w-2 flex-shrink-0 select-none"
aria-hidden="true"
/>
</ListboxButton>
<Transition>
<ListboxOptions className="pb-0">
<div className="flex gap-1.5 px-2.5 py-1">
<span className="font-semibold">Assistants</span>
<div
className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"
onClick={async (e) => {
e.stopPropagation();
setLoading(true);
await refreshProfiles();
setLoading(false);
buttonRef.current?.click();
}}
>
<ArrowPathIcon
className={cn(
"text-description h-2.5 w-2.5",
loading && "animate-spin-slow",
)}
/>
</div>
</div>
<div
className={`thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto`}
>
{profiles?.map((profile, idx) => {
return (
<AssistantSelectOption
key={idx}
profile={profile}
onClick={close}
selected={profile.id === selectedProfile.id}
/>
);
})}
</div>
<div className="flex flex-col">
<div className="flex flex-row items-center">
<ListboxOption
value={"new-assistant"}
fontSizeModifier={-2}
className="border-border w-full border-x-0 border-y border-solid"
onClick={session ? onNewAssistant : () => login(false)}
>
<div
className="text-description flex flex-row items-center gap-2"
style={{
fontSize: tinyFont,
}}
>
<PlusIcon className="ml-0.5 h-3 w-3 flex-shrink-0" />
New Assistant
</div>
</ListboxOption>
</div>
<div
className="text-description flex items-center justify-between gap-1.5 px-2 py-1"
style={{
fontSize: tinyFont,
}}
>
<span
className="block"
style={{
fontSize: tinyFont - 1,
}}
>
<code>{getMetaKeyLabel()} ⇧ '</code> to toggle
</span>
<div
className="ml-auto flex items-center gap-1"
onClick={cycleOrgs}
>
{currentOrg?.iconUrl ? (
<img
src={currentOrg.iconUrl}
className="h-2.5 w-2.5 rounded-full"
/>
) : (
<BuildingOfficeIcon className="h-4 w-4" />
)}
<span
className="hover:cursor-pointer hover:underline"
style={{
fontSize: tinyFont - 1,
}}
>
{currentOrg?.name || "Personal"}
</span>
</div>
</div>
</div>
</ListboxOptions>
</Transition>
</div>
</Listbox>
);
}

View file

@ -10,7 +10,6 @@ import React, {
useEffect,
useState,
} from "react";
import ConfirmationDialog from "../components/dialogs/ConfirmationDialog";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import {
@ -19,7 +18,6 @@ import {
setOrganizations,
setSelectedOrgId,
} from "../redux/slices/profilesSlice";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice";
import { IdeMessengerContext } from "./IdeMessenger";
interface AuthContextType {
@ -52,8 +50,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
const selectedProfile = useAppSelector(selectSelectedProfile);
const login: AuthContextType["login"] = (useOnboarding: boolean) => {
return new Promise((resolve) => {
ideMessenger
return new Promise(async (resolve) => {
await ideMessenger
.request("getControlPlaneSessionInfo", {
silent: false,
useOnboarding,
@ -73,27 +71,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
};
const logout = () => {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
confirmText="Yes, log out"
text="Are you sure you want to log out of Continue?"
onConfirm={() => {
ideMessenger.post("logoutOfControlPlane", undefined);
dispatch(
setOrganizations(orgs.filter((org) => org.id === "personal")),
);
dispatch(setSelectedOrgId("personal"));
setSession(undefined);
}}
onCancel={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
}}
/>,
),
);
ideMessenger.post("logoutOfControlPlane", undefined);
dispatch(setOrganizations(orgs.filter((org) => org.id === "personal")));
dispatch(setSelectedOrgId("personal"));
setSession(undefined);
};
useEffect(() => {

View file

@ -356,6 +356,16 @@ export const SubmenuContextProvidersProvider = ({
[loadSubmenuItems],
);
useWebviewListener(
"indexProgress",
async (data) => {
if (data.status === "done") {
loadSubmenuItems("dependsOnIndexing");
}
},
[loadSubmenuItems],
);
// Reload all submenu items on the initial config load
useEffect(() => {
if (!submenuContextProviders.length) {

View file

@ -20,6 +20,7 @@ import {
import {
acceptToolCall,
addContextItemsAtIndex,
setHasReasoningEnabled,
updateApplyState,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
@ -86,6 +87,13 @@ function ParallelListeners() {
setLocalStorage("fontSize", configResult.config.ui.fontSize);
document.body.style.fontSize = `${configResult.config.ui.fontSize}px`;
}
if (
configResult.config?.selectedModelByRole.chat?.completionOptions
?.reasoning
) {
dispatch(setHasReasoningEnabled(true));
}
},
[dispatch, hasDoneInitialConfigLoad],
);
@ -241,7 +249,7 @@ function ParallelListeners() {
dispatch(updateEditStateApplyState(state));
if (state.status === "closed") {
dispatch(exitEdit({}));
void dispatch(exitEdit({}));
}
} else {
// chat or agent

View file

@ -1,82 +0,0 @@
import { UserCircleIcon } from "@heroicons/react/24/solid";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import {
Button,
Popover,
PopoverButton,
PopoverPanel,
Transition,
} from "../../components/ui";
import { useAuth } from "../../context/Auth";
import { useAppSelector } from "../../redux/hooks";
import { selectCurrentOrg } from "../../redux/slices/profilesSlice";
import { ScopeSelect } from "./ScopeSelect";
export function AccountButton() {
const { session, logout, login, organizations } = useAuth();
const selectedOrg = useAppSelector(selectCurrentOrg);
if (!session) {
return (
<Button
variant="outline"
className="mb-1 whitespace-nowrap py-1"
onClick={() => login(false)}
>
Sign in
</Button>
);
}
// No login button for on-prem deployments
if (isOnPremSession(session)) {
return null;
}
return (
<Popover className="relative">
{({ close }) => (
<>
<PopoverButton className="bg-vsc-background hover:bg-vsc-input-background text-vsc-foreground my-0.5 flex cursor-pointer rounded-md border-none px-2">
<div className="flex items-center gap-1.5">
<span className="font-medium">
{selectedOrg === null ? "Personal" : selectedOrg.name}
</span>
<UserCircleIcon className="h-6 w-6" />
</div>
</PopoverButton>
<Transition>
<PopoverPanel className="bg-vsc-input-background xs:p-4 absolute right-0 mt-1 rounded-md border border-zinc-700 p-2 shadow-lg">
<div className="flex flex-col gap-3">
<div className="flex flex-col">
<span className="font-medium">{session.account.label}</span>
<span className="text-lightgray text-sm">
{session.account.id}
</span>
</div>
{organizations.length > 0 && (
<div className="flex flex-col gap-1">
<label className="text-vsc-foreground text-xs">
Organization
</label>
<ScopeSelect onSelect={close} />
</div>
)}
<Button
variant="ghost"
onClick={logout}
className="!mx-0 w-full"
>
Sign out
</Button>
</div>
</PopoverPanel>
</Transition>
</>
)}
</Popover>
);
}

View file

@ -9,7 +9,6 @@ import { useNavigate } from "react-router-dom";
import { PageHeader } from "../../components/PageHeader";
import { useNavigationListener } from "../../hooks/useNavigationListener";
import { fontSize } from "../../util";
import { AccountButton } from "./AccountButton";
import { HelpCenterSection } from "./HelpCenterSection";
import { IndexingSettingsSection } from "./IndexingSettingsSection";
import KeyboardShortcuts from "./KeyboardShortcuts";
@ -63,7 +62,6 @@ function ConfigPage() {
showBorder
onTitleClick={() => navigate("/")}
title="Chat"
rightContent={<AccountButton />}
/>
{/* Tab Headers */}

View file

@ -2,7 +2,6 @@ import { useNavigate } from "react-router-dom";
import { History } from "../../components/History";
import { PageHeader } from "../../components/PageHeader";
import { getFontSize } from "../../util";
import { AccountButton } from "../config/AccountButton";
export default function HistoryPage() {
const navigate = useNavigate();
@ -12,12 +11,7 @@ export default function HistoryPage() {
className="flex flex-1 flex-col overflow-auto"
style={{ fontSize: getFontSize() }}
>
<PageHeader
showBorder
onTitleClick={() => navigate("/")}
title="Chat"
rightContent={<AccountButton />}
/>
<PageHeader showBorder onTitleClick={() => navigate("/")} title="Chat" />
<History />
</div>
);

View file

@ -51,6 +51,7 @@ type SessionState = {
curIndex: number;
};
newestToolbarPreviewForInput: Record<string, string>;
hasReasoningEnabled?: boolean;
};
const initialState: SessionState = {
@ -594,6 +595,9 @@ export const sessionSlice = createSlice({
setIsInEdit: (state, action: PayloadAction<boolean>) => {
state.isInEdit = action.payload;
},
setHasReasoningEnabled: (state, action: PayloadAction<boolean>) => {
state.hasReasoningEnabled = action.payload;
},
setNewestToolbarPreviewForInput: (
state,
{
@ -691,6 +695,7 @@ export const {
deleteSessionMetadata,
setNewestToolbarPreviewForInput,
setIsInEdit,
setHasReasoningEnabled,
} = sessionSlice.actions;
export const { selectIsGatheringContext } = sessionSlice.selectors;

View file

@ -45,6 +45,14 @@ export const streamNormalInput = createAsyncThunk<
};
}
if (state.session.hasReasoningEnabled) {
completionOptions = {
...completionOptions,
reasoning: true,
reasoningBudgetTokens: completionOptions.reasoningBudgetTokens ?? 2048,
};
}
// Send request
const gen = extra.ideMessenger.llmStreamChat(
{

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.93",
"version": "1.0.94",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/config-yaml",
"version": "1.0.93",
"version": "1.0.94",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -34,6 +34,7 @@ export function createRuleMarkdown(
options: {
description?: string;
globs?: string | string[];
regex?: string | string[];
alwaysApply?: boolean;
} = {},
): string {
@ -44,6 +45,11 @@ export function createRuleMarkdown(
typeof options.globs === "string" ? options.globs.trim() : options.globs;
}
if (options.regex) {
frontmatter.regex =
typeof options.regex === "string" ? options.regex.trim() : options.regex;
}
if (options.description) {
frontmatter.description = options.description.trim();
}

View file

@ -1,5 +1,5 @@
import { PackageIdentifier } from "../browser.js";
import { markdownToRule } from "./markdownToRule.js";
import { getRuleName, markdownToRule } from "./markdownToRule.js";
describe("markdownToRule", () => {
// Use a mock PackageIdentifier for testing
@ -36,7 +36,7 @@ This is a test rule.`;
const result = markdownToRule(content, mockId);
expect(result.globs).toBe("**/test/**/*.kt");
expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should handle missing frontmatter", () => {
@ -47,7 +47,7 @@ This is a test rule without frontmatter.`;
const result = markdownToRule(content, mockId);
expect(result.globs).toBeUndefined();
expect(result.rule).toBe(content);
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should handle empty frontmatter", () => {
@ -63,7 +63,7 @@ This is a test rule with empty frontmatter.`;
expect(result.rule).toBe(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
);
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should handle frontmatter with whitespace", () => {
@ -78,7 +78,7 @@ This is a test rule.`;
const result = markdownToRule(content, mockId);
expect(result.globs).toBe("**/test/**/*.kt");
expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should handle Windows line endings (CRLF)", () => {
@ -95,7 +95,7 @@ This is a test rule.`;
expect(result.globs).toBe("**/test/**/*.kt");
// The result should be normalized to \n
expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should handle malformed frontmatter", () => {
@ -112,7 +112,7 @@ This is a test rule.`;
const result = markdownToRule(content, mockId);
expect(result.globs).toBeUndefined();
expect(result.rule).toBe(content);
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should use packageIdentifierToDisplayName if no heading or frontmatter name", () => {
@ -125,7 +125,7 @@ globs: "**/test/**/*.kt"
This is a test rule.`;
const result = markdownToRule(content, mockId);
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should use packageIdentifierToDisplayName if no heading or frontmatter name (no heading)", () => {
@ -136,7 +136,7 @@ globs: "**/test/**/*.kt"
This is a test rule without a heading.`;
const result = markdownToRule(content, mockId);
expect(result.name).toBe("/path/to/file"); // Should use packageIdentifierToDisplayName result
expect(result.name).toBe("to/file"); // Should use last two path segments
});
it("should include description from frontmatter", () => {
@ -171,3 +171,108 @@ This is a rule with alwaysApply explicitly set to false.`;
expect(result.alwaysApply).toBe(false);
});
});
describe("getRuleName", () => {
it("should return frontmatter name when provided", () => {
const frontmatter = { name: "Custom Rule Name" };
const id: PackageIdentifier = {
uriType: "file",
filePath: "/path/to/my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("Custom Rule Name");
});
it("should return last two path segments for file identifier when no name", () => {
const frontmatter = {};
const id: PackageIdentifier = {
uriType: "file",
filePath: "/long/path/to/rules/my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("rules/my-rule.md");
});
it("should handle file paths with backslashes", () => {
const frontmatter = {};
const id: PackageIdentifier = {
uriType: "file",
filePath: "C:\\long\\path\\to\\rules\\my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("rules/my-rule.md");
});
it("should handle mixed forward and back slashes", () => {
const frontmatter = {};
const id: PackageIdentifier = {
uriType: "file",
filePath: "/path/to\\rules/my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("rules/my-rule.md");
});
it("should handle single segment path", () => {
const frontmatter = {};
const id: PackageIdentifier = {
uriType: "file",
filePath: "my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("my-rule.md");
});
it("should handle two segment path", () => {
const frontmatter = {};
const id: PackageIdentifier = {
uriType: "file",
filePath: "rules/my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("rules/my-rule.md");
});
it("should return display name for non-file identifiers", () => {
const frontmatter = {};
const id: PackageIdentifier = {
uriType: "slug",
fullSlug: {
ownerSlug: "test-owner",
packageSlug: "my-rule-package",
versionSlug: "v1.0.0",
},
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("my-rule-package"); // packageIdentifierToDisplayName returns just the packageSlug
});
it("should prioritize frontmatter name over file path", () => {
const frontmatter = { name: "Override Name" };
const id: PackageIdentifier = {
uriType: "file",
filePath: "/very/long/path/to/rules/original-name.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("Override Name");
});
it("should handle empty string name in frontmatter by falling back to path", () => {
const frontmatter = { name: "" };
const id: PackageIdentifier = {
uriType: "file",
filePath: "/path/to/rules/my-rule.md",
};
const result = getRuleName(frontmatter, id);
expect(result).toBe("rules/my-rule.md"); // Empty string is falsy, so falls back to path logic
});
});

View file

@ -7,6 +7,7 @@ import { RuleObject } from "../schemas/index.js";
export interface RuleFrontmatter {
globs?: RuleObject["globs"];
regex?: RuleObject["regex"];
name?: RuleObject["name"];
description?: RuleObject["description"];
alwaysApply?: RuleObject["alwaysApply"];
@ -46,6 +47,28 @@ export function parseMarkdownRule(content: string): {
return { frontmatter: {}, markdown: normalizedContent };
}
export function getRuleName(
frontmatter: RuleFrontmatter,
id: PackageIdentifier,
): string {
if (frontmatter.name) {
return frontmatter.name;
}
const displayName = packageIdentifierToDisplayName(id);
// If it's a file identifier, extract the last two parts of the file path
if (id.uriType === "file") {
// Handle both forward slashes and backslashes, get the last two segments
const segments = displayName.split(/[/\\]/);
const lastTwoParts = segments.slice(-2);
return lastTwoParts.join("/");
}
// Otherwise return the display name as-is (for slug identifiers)
return displayName;
}
export function markdownToRule(
rule: string,
id: PackageIdentifier,
@ -53,9 +76,10 @@ export function markdownToRule(
const { frontmatter, markdown } = parseMarkdownRule(rule);
return {
name: frontmatter.name ?? packageIdentifierToDisplayName(id),
name: getRuleName(frontmatter, id),
rule: markdown,
globs: frontmatter.globs,
regex: frontmatter.regex,
description: frontmatter.description,
alwaysApply: frontmatter.alwaysApply,
};

View file

@ -50,6 +50,7 @@ const ruleObjectSchema = z.object({
rule: z.string(),
description: z.string().optional(),
globs: z.union([z.string(), z.array(z.string())]).optional(),
regex: z.union([z.string(), z.array(z.string())]).optional(),
alwaysApply: z.boolean().optional(),
});
const ruleSchema = z.union([z.string(), ruleObjectSchema]);

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.36",
"version": "1.0.40",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.36",
"version": "1.0.40",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.38",
"version": "1.0.40",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",