Merge pull request #2 from alfasoftware/main

Merge main back into Autocomplete-fixes
This commit is contained in:
Ben J 2025-03-24 11:53:52 +00:00 • committed by GitHub
commit 0fe78258d0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
179 changed files with 4686 additions and 3997 deletions

4
.gitignore vendored
View file

@ -157,11 +157,15 @@ Icon?
notes.md
manual-testing-sandbox/.idea/**
manual-testing-sandbox/.continue/**
extensions/intellij/.idea/**
**/.idea/workspace.xml
**/.idea/usage.statistics.xml
**/.idea/shelf/
**/.idea/inspectionProfiles/Project_Default.xml
**/.idea/php.xml
extensions/intellij/bin
extensions/.continue-debug/

View file

@ -51,7 +51,7 @@
"@continuedev/config-yaml": "^1.0.63",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@continuedev/openai-adapters": "^1.0.18",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -10,6 +10,7 @@ export function slashFromCustomCommand(
return {
name: customCommand.name,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
run: async function* ({ input, llm, history, ide, completionOptions }) {
// Remove slash command prefix from input
let userInput = input;

View file

@ -1,6 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import { ContextItemWithId, RangeInFileWithContents } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { v4 as uuidv4 } from "uuid";
export function rifWithContentsToContextItem(
rif: RangeInFileWithContents,

View file

@ -387,16 +387,6 @@ export class ConfigHandler {
this.ideSettingsPromise,
);
// After login, default to the first org as the selected org
try {
const orgs = await this.controlPlaneClient.listOrganizations();
if (orgs.length) {
await this.setSelectedOrgId(orgs[0].id);
}
} catch (e) {
console.error("Failed to fetch control plane profiles: ", e);
}
this.fetchControlPlaneProfiles().catch(async (e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.loadLocalProfilesOnly();

View file

@ -28,7 +28,6 @@ import {
IdeType,
ILLM,
LLMOptions,
MCPOptions,
ModelDescription,
RerankerDescription,
SerializedContinueConfig,
@ -45,7 +44,6 @@ import ContinueProxyContextProvider from "../context/providers/ContinueProxyCont
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { useHub } from "../control-plane/env";
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
import { BaseLLM } from "../llm";
@ -401,8 +399,6 @@ async function intermediateToFinalConfig(
...(!config.disableIndexing
? [new CodebaseContextProvider(codebaseContextParams)]
: []),
// Add prompt files provider if enabled
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
@ -521,6 +517,8 @@ async function intermediateToFinalConfig(
contextProviders,
models,
tools: allTools,
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
modelsByRole: {
chat: models,
edit: models,
@ -541,53 +539,18 @@ async function intermediateToFinalConfig(
},
};
// Apply MCP if specified
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
function getMcpId(options: MCPOptions) {
return JSON.stringify(options);
}
if (config.experimental?.modelContextProtocolServers) {
await mcpManager.removeUnusedConnections(
config.experimental.modelContextProtocolServers.map(getMcpId),
);
}
if (config.experimental?.modelContextProtocolServers) {
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
5000,
);
await Promise.allSettled(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
try {
const mcpId = getMcpId(server);
const mcpConnection = mcpManager.createConnection(mcpId, server);
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
"MCP Server",
server.faviconUrl,
);
} catch (e) {
let errorMessage = "Failed to load MCP server";
if (e instanceof Error) {
errorMessage += ": " + e.message;
}
errors.push({
fatal: false,
message: errorMessage,
});
} finally {
clearTimeout(mcpConnectionTimeout);
}
},
) || [],
);
}
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server ${index + 1}`,
...server,
}),
),
false,
);
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
@ -667,11 +630,9 @@ async function finalToBrowserConfig(
models: final.models.map(llmToSerializedModelDescription),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map((s) => ({
name: s.name,
description: s.description,
params: s.params, // TODO: is this why params aren't referenced properly by slash commands?
})),
slashCommands: final.slashCommands?.map(
({ run, ...slashCommandDescription }) => slashCommandDescription,
),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
@ -681,6 +642,7 @@ async function finalToBrowserConfig(
rules: final.rules,
docs: final.docs,
tools: final.tools,
mcpServerStatuses: final.mcpServerStatuses,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
modelsByRole: Object.fromEntries(

View file

@ -2,6 +2,7 @@ import { ConfigJson } from "@continuedev/config-types";
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { PRODUCTION_ENV } from "../../control-plane/env.js";
import {
ContinueConfig,
IDE,
@ -10,7 +11,6 @@ import {
} from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { PRODUCTION_ENV } from "../../control-plane/env.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";

View file

@ -1,11 +1,10 @@
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";

View file

@ -6,18 +6,24 @@ import {
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
ContinueRcJson,
IDE,
IdeSettings,
SerializedContinueConfig,
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { encodeMCPToolUri } from "../../tools/callTool";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
@ -26,6 +32,7 @@ import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
export default async function doLoadConfig(
@ -93,15 +100,90 @@ export default async function doLoadConfig(
configLoadInterrupted = result.configLoadInterrupted;
}
// Rectify model selections for each role
if (newConfig) {
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
}
if (configLoadInterrupted || !newConfig) {
return { errors, config: newConfig, configLoadInterrupted: true };
}
// TODO using config result but result with non-fatal errors is an antipattern?
// Remove ability have undefined errors, just have an array
errors = [...(errors ?? [])];
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
// Add things from MCP servers
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
// Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;
});
newConfig.mcpServerStatuses = serializableStatuses;
for (const server of mcpServerStatuses) {
if (server.status === "connected") {
const serverTools: Tool[] = server.tools.map((tool) => ({
displayTitle: server.name + " " + tool.name,
function: {
description: tool.description,
name: tool.name,
parameters: tool.inputSchema,
},
faviconUrl: server.faviconUrl,
readonly: false,
type: "function" as const,
wouldLikeTo: "",
uri: encodeMCPToolUri(server.id, tool.name),
group: server.name,
}));
newConfig.tools.push(...serverTools);
const serverSlashCommands = server.prompts.map((prompt) =>
constructMcpSlashCommand(
server.client,
prompt.name,
prompt.description,
prompt.arguments?.map((a: any) => a.name),
),
);
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources.map((resource) => ({
title: resource.name,
description: resource.description ?? resource.name,
id: resource.uri,
icon: server.faviconUrl,
}));
if (submenuItems.length > 0) {
const serverContextProvider = new MCPContextProvider({
submenuItems,
mcpId: server.id,
});
newConfig.contextProviders.push(serverContextProvider);
}
}
}
// Detect duplicate tool names
const counts: Record<string, number> = {};
newConfig.tools.forEach((tool) => {
if (counts[tool.function.name]) {
counts[tool.function.name] = counts[tool.function.name] + 1;
} else {
counts[tool.function.name] = 1;
}
});
Object.entries(counts).forEach(([toolName, count]) => {
if (count > 1) {
errors!.push({
fatal: false,
message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`,
});
}
});
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());

View file

@ -1,4 +1,5 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ModelDescription, SerializedContinueConfig } from "../";
import { Telemetry } from "../util/posthog";

View file

@ -28,7 +28,6 @@ import CodebaseContextProvider from "../../context/providers/CodebaseContextProv
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider";
import { ControlPlaneClient } from "../../control-plane/client";
import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders";
import FreeTrial from "../../llm/llms/FreeTrial";
@ -111,7 +110,8 @@ async function configYamlToContinueConfig(
const continueConfig: ContinueConfig = {
slashCommands: [],
models: [],
tools: allTools,
tools: [...allTools],
mcpServerStatuses: [],
systemMessage: config.rules?.join("\n"),
experimental: {
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
@ -334,7 +334,6 @@ async function configYamlToContinueConfig(
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
new PromptFilesContextProvider({}),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
@ -368,52 +367,19 @@ async function configYamlToContinueConfig(
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Apply MCP if specified
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
if (config.mcpServers) {
await mcpManager.removeUnusedConnections(
config.mcpServers.map((s) => s.name),
);
}
await Promise.allSettled(
config.mcpServers?.map(async (server) => {
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
5000,
);
try {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
server.name,
server.faviconUrl,
);
} catch (e) {
let errorMessage = `Failed to load MCP server ${server.name}`;
if (e instanceof Error) {
errorMessage += ": " + e.message;
}
localErrors.push({
fatal: false,
message: errorMessage,
});
} finally {
clearTimeout(mcpConnectionTimeout);
}
}) ?? [],
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
transport: {
type: "stdio",
args: [],
...server,
},
})),
false,
);
return { config: continueConfig, errors: localErrors };

View file

@ -4,16 +4,23 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { encodeMCPToolUri } from "../../tools/callTool";
import MCPContextProvider from "../providers/MCPContextProvider";
import {
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
MCPResource,
MCPServerStatus,
MCPTool,
} from "../..";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
public onConnectionsRefreshed?: () => void;
private connections: Map<string, MCPConnection> = new Map();
private abortController: AbortController = new AbortController();
private constructor() {}
public static getInstance(): MCPManagerSingleton {
@ -46,18 +53,90 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
async removeUnusedConnections(keepIds: string[]) {
const toRemove = Array.from(this.connections.keys()).filter(
(k) => !keepIds.includes(k),
);
await Promise.all(toRemove.map((id) => this.removeConnection(id)));
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
let refresh = false;
// Remove any connections that are no longer in config
Array.from(this.connections.entries()).forEach(([id, connection]) => {
if (!servers.find((s) => s.id === id)) {
refresh = true;
connection.abortController.abort();
void connection.client.close();
this.connections.delete(id);
}
});
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
}
});
// NOTE the id is made by stringifying the options
if (refresh) {
void this.refreshConnections(forceRefresh);
}
}
async refreshConnection(serverId: string) {
const connection = this.connections.get(serverId);
if (!connection) {
throw new Error(`MCP Connection ${serverId} not found`);
}
await connection.connectClient(true, this.abortController.signal);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
}
async refreshConnections(force: boolean) {
this.abortController.abort();
this.abortController = new AbortController();
await Promise.race([
new Promise((resolve) => {
this.abortController.signal.addEventListener("abort", () => {
resolve(undefined);
});
}),
(async () => {
await Promise.all(
Array.from(this.connections.values()).map(async (connection) => {
await connection.connectClient(force, this.abortController.signal);
}),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();
}
})(),
]);
}
getStatuses(): (MCPServerStatus & { client: Client })[] {
return Array.from(this.connections.values()).map((connection) => ({
...connection.getStatus(),
client: connection.client,
}));
}
}
const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
class MCPConnection {
public client: Client;
private transport: Transport;
private connectionPromise: Promise<unknown> | null = null;
public abortController: AbortController;
public status: MCPConnectionStatus = "not-connected";
public errors: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
constructor(private readonly options: MCPOptions) {
this.transport = this.constructTransport(options);
@ -70,6 +149,8 @@ class MCPConnection {
capabilities: {},
},
);
this.abortController = new AbortController();
}
private constructTransport(options: MCPOptions): Transport {
@ -95,131 +176,170 @@ class MCPConnection {
}
}
private isConnected: boolean = false;
private connectPromise: Promise<void> | null = null;
private async connectClient() {
if (this.isConnected) {
// Already connected
return;
}
if (this.connectPromise) {
// Connection is already in progress; wait for it to complete
await this.connectPromise;
return;
}
this.connectPromise = (async () => {
await this.client.connect(this.transport);
this.isConnected = true;
})();
try {
await this.connectPromise;
} finally {
// Reset the promise so future attempts can try again if necessary
this.connectPromise = null;
}
getStatus(): MCPServerStatus {
return {
...this.options,
errors: this.errors,
prompts: this.prompts,
resources: this.resources,
tools: this.tools,
status: this.status,
};
}
async modifyConfig(
config: ContinueConfig,
mcpId: string,
signal: AbortSignal,
name: string,
faviconUrl: string | undefined,
) {
try {
await Promise.race([
this.connectClient(),
new Promise((_, reject) => {
signal.addEventListener("abort", () =>
reject(new Error("Connection timed out")),
);
}),
]);
} catch (error) {
if (error instanceof Error) {
const msg = error.message.toLowerCase();
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
throw new Error(
`command "${command}" not found. To use this MCP server, install the ${command} CLI.`,
);
} else if (
!error.message.startsWith("StdioClientTransport already started")
) {
// don't throw error if it's just a "server already running" case
throw error;
async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
if (!forceRefresh) {
// Already connected
if (this.status === "connected") {
return;
}
// Connection is already in progress; wait for it to complete
if (this.connectionPromise) {
await this.connectionPromise;
return;
}
}
this.status = "connecting";
this.tools = [];
this.prompts = [];
this.resources = [];
this.errors = [];
this.abortController.abort();
this.abortController = new AbortController();
this.connectionPromise = Promise.race([
// If aborted by a refresh or other, cancel and don't do anything
new Promise((resolve) => {
externalSignal.addEventListener("abort", () => {
resolve(undefined);
});
}),
new Promise((resolve) => {
this.abortController.signal.addEventListener("abort", () => {
resolve(undefined);
});
}),
(async () => {
const timeoutController = new AbortController();
const connectionTimeout = setTimeout(
() => timeoutController.abort(),
this.options.timeout ?? DEFAULT_MCP_TIMEOUT,
);
try {
await Promise.race([
new Promise((_, reject) => {
timeoutController.signal.addEventListener("abort", () => {
reject(new Error("Connection timed out"));
});
}),
(async () => {
this.transport = this.constructTransport(this.options);
try {
await this.client.connect(this.transport);
} catch (error) {
// Allow the case where for whatever reason is already connected
if (
error instanceof Error &&
error.message.startsWith(
"StdioClientTransport already started",
)
) {
await this.client.close();
await this.client.connect(this.transport);
} else {
throw error;
}
}
// TODO register server notification handlers
// this.client.transport?.onmessage(msg => console.log())
// this.client.setNotificationHandler(, notification => {
// console.log(notification)
// })
const capabilities = this.client.getServerCapabilities();
// Resources <—> Context Provider
if (capabilities?.resources) {
try {
const { resources } = await this.client.listResources(
{},
{ signal: timeoutController.signal },
);
this.resources = resources;
} catch (e) {
let errorMessage = `Error loading resources for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
// Tools <—> Tools
if (capabilities?.tools) {
try {
const { tools } = await this.client.listTools(
{},
{ signal: timeoutController.signal },
);
this.tools = tools;
} catch (e) {
let errorMessage = `Error loading tools for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
// Prompts <—> Slash commands
if (capabilities?.prompts) {
try {
const { prompts } = await this.client.listPrompts(
{},
{ signal: timeoutController.signal },
);
this.prompts = prompts;
} catch (e) {
let errorMessage = `Error loading prompts for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
this.status = "connected";
})(),
]);
} catch (error) {
// Otherwise it's a connection error
let errorMessage = `Failed to connect to MCP server ${this.options.name}`;
if (error instanceof Error) {
const msg = error.message.toLowerCase();
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
} else {
errorMessage += ": " + error.message;
}
}
this.status = "error";
this.errors.push(errorMessage);
} finally {
this.connectionPromise = null;
clearTimeout(connectionTimeout);
}
} else {
throw error;
}
}
})(),
]);
const capabilities = this.client.getServerCapabilities();
// Resources <—> Context Provider
if (capabilities?.resources) {
const { resources } = await this.client.listResources({}, { signal });
const submenuItems = resources.map((resource: any) => ({
title: resource.name,
description: resource.description,
id: resource.uri,
icon: faviconUrl,
}));
if (!config.contextProviders) {
config.contextProviders = [];
}
config.contextProviders.push(
new MCPContextProvider({
submenuItems,
mcpId,
}),
);
}
// Tools <—> Tools
if (capabilities?.tools) {
const { tools } = await this.client.listTools({}, { signal });
const continueTools: Tool[] = tools.map((tool: any) => ({
displayTitle: name + " " + tool.name,
function: {
description: tool.description,
name: tool.name,
parameters: tool.inputSchema,
},
faviconUrl,
readonly: false,
type: "function",
wouldLikeTo: `use the ${name} ${tool.name} tool`,
uri: encodeMCPToolUri(mcpId, tool.name),
}));
config.tools = [...continueTools, ...config.tools];
}
// Prompts <—> Slash commands
if (capabilities?.prompts) {
const { prompts } = await this.client.listPrompts({}, { signal });
if (!config.slashCommands) {
config.slashCommands = [];
}
const slashCommands: SlashCommand[] = prompts.map((prompt: any) =>
constructMcpSlashCommand(
this.client,
prompt.name,
prompt.description,
prompt.arguments?.map((a: any) => a.name),
),
);
config.slashCommands.push(...slashCommands);
}
await this.connectionPromise;
}
}

View file

@ -1,57 +0,0 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { parsePreamble } from "../../promptFiles/v2/parse";
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
class PromptFilesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "prompt-files",
displayTitle: "Prompt Files",
description: ".prompt files",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const rawContent = await extras.ide.readFile(query);
const preamble = parsePreamble(query, rawContent);
const [contextItems, body] = await renderPromptFileV2(rawContent, extras);
return [
...contextItems,
{
content: body,
name: preamble.name,
description: preamble.description,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const promptFiles = await getAllPromptFiles(
args.ide,
args.config.experimental?.promptPath,
// Note, NOT checking v1 default folder here, deprecated for context provider
);
return promptFiles.map((file) => {
const preamble = parsePreamble(file.path, file.content);
return {
id: file.path,
title: preamble.name,
description: preamble.description,
};
});
}
}
export default PromptFilesContextProvider;

View file

@ -22,7 +22,6 @@ import { DataLogger } from "./data/log";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { getAllSuggestedDocs } from "./indexing/docs/suggestions";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -43,6 +42,7 @@ import {
} from ".";
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import { MCPManagerSingleton } from "./context/mcp";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { llmStreamChat } from "./llm/streamChat";
@ -120,6 +120,13 @@ export class Core {
this.messenger,
);
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.onConnectionsRefreshed = async () => {
// This ensures that it triggers a NEW load after waiting for config promise to finish
await this.configHandler.loadConfig();
await this.configHandler.reloadConfig();
};
this.configHandler.onConfigUpdate(async (result) => {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
@ -344,6 +351,9 @@ export class Core {
return await this.configHandler.listOrganizations();
});
on("mcp/reloadServer", async (msg) => {
mcpManager.refreshConnection(msg.data.id);
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);
@ -796,14 +806,6 @@ export class Core {
// this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet
}
});
on("docs/getSuggestedDocs", async (msg) => {
if (hasRequestedDocs) {
return;
} // TODO, remove, hack because of rerendering
hasRequestedDocs = true;
const suggestedDocs = await getAllSuggestedDocs(this.ide);
this.messenger.send("docs/suggestions", suggestedDocs);
});
on("docs/initStatuses", async (msg) => {
void this.docsService.initStatuses();
});
@ -978,4 +980,3 @@ export class Core {
// private
}
let hasRequestedDocs = false;

124
core/index.d.ts vendored
View file

@ -43,13 +43,13 @@ export interface IndexingProgressUpdate {
desc: string;
shouldClearIndexes?: boolean;
status:
| "loading"
| "indexing"
| "done"
| "failed"
| "paused"
| "disabled"
| "cancelled";
| "loading"
| "indexing"
| "done"
| "failed"
| "paused"
| "disabled"
| "cancelled";
debugInfo?: string;
}
@ -316,7 +316,12 @@ export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
export type ChatMessageRole = "user" | "assistant" | "thinking" | "system" | "tool";
export type ChatMessageRole =
| "user"
| "assistant"
| "thinking"
| "system"
| "tool";
export type TextMessagePart = {
type: "text";
@ -434,7 +439,7 @@ export interface PromptLog {
completion: string;
}
export type MessageModes = "chat" | "edit";
export type MessageModes = "chat" | "edit" | "agent";
export type ToolStatus =
| "generating"
@ -692,10 +697,10 @@ export interface IDE {
getCurrentFile(): Promise<
| undefined
| {
isUntitled: boolean;
path: string;
contents: string;
}
isUntitled: boolean;
path: string;
contents: string;
}
>;
getLastFileSaveTimestamp?(): number;
@ -761,6 +766,7 @@ export interface ContinueSDK {
export interface SlashCommand {
name: string;
description: string;
prompt?: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
@ -864,11 +870,7 @@ export interface ContextProviderWithParams {
params: { [key: string]: any };
}
export interface SlashCommandDescription {
name: string;
description: string;
params?: { [key: string]: any };
}
export type SlashCommandDescription = Omit<SlashCommand, "run">;
export interface CustomCommand {
name: string;
@ -879,11 +881,11 @@ export interface CustomCommand {
export interface Prediction {
type: "content";
content:
| string
| {
type: "text";
text: string;
}[];
| string
| {
type: "text";
text: string;
}[];
}
export interface ToolExtras {
@ -907,6 +909,7 @@ export interface Tool {
readonly: boolean;
uri?: string;
faviconUrl?: string;
group: string;
}
interface ToolChoice {
@ -1043,8 +1046,54 @@ export interface SSEOptions {
export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
export interface MCPOptions {
name: string;
id: string;
transport: TransportOptions;
faviconUrl?: string;
timeout?: number;
}
export type MCPConnectionStatus =
| "connecting"
| "connected"
| "error"
| "not-connected";
export interface MCPPrompt {
name: string;
description?: string;
arguments?: {
name: string;
description?: string;
required?: boolean;
}[];
}
// Leaving here to ideate on
// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub"
export interface MCPResource {
name: string;
uri: string;
description?: string;
mimeType?: string;
}
export interface MCPTool {
name: string;
description?: string;
inputSchema: {
type: "object";
properties?: Record<string, any>;
};
}
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
prompts: MCPPrompt[];
tools: MCPTool[];
resources: MCPResource[];
}
export interface ContinueUIConfig {
@ -1070,6 +1119,11 @@ export interface ExperimentalModelRoles {
applyCodeBlock?: string;
}
export interface ExperimentalMCPOptions {
transport: TransportOptions;
faviconUrl?: string;
}
export type EditStatus =
| "not-started"
| "streaming"
@ -1153,7 +1207,7 @@ export interface ExperimentalConfig {
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
*/
useChromiumForDocsCrawling?: boolean;
modelContextProtocolServers?: MCPOptions[];
modelContextProtocolServers?: ExperimentalMCPOptions[];
}
export interface AnalyticsConfig {
@ -1224,9 +1278,9 @@ export interface Config {
embeddingsProvider?: EmbeddingsProviderDescription | ILLM;
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */
@ -1247,8 +1301,8 @@ export interface ContinueConfig {
systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands?: SlashCommand[];
contextProviders?: IContextProvider[];
slashCommands: SlashCommand[];
contextProviders: IContextProvider[];
disableSessionTitles?: boolean;
disableIndexing?: boolean;
userToken?: string;
@ -1258,6 +1312,7 @@ export interface ContinueConfig {
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: string[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
@ -1270,8 +1325,8 @@ export interface BrowserSerializedContinueConfig {
systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands?: SlashCommandDescription[];
contextProviders?: ContextProviderDescription[];
slashCommands: SlashCommandDescription[];
contextProviders: ContextProviderDescription[];
disableIndexing?: boolean;
disableSessionTitles?: boolean;
userToken?: string;
@ -1280,6 +1335,7 @@ export interface BrowserSerializedContinueConfig {
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: string[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
@ -1320,9 +1376,9 @@ export type PackageDetailsSuccess = PackageDetails & {
export type PackageDocsResult = {
packageInfo: ParsedPackageInfo;
} & (
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
export interface TerminalOptions {
reuseTerminal?: boolean;

View file

@ -1,129 +0,0 @@
import {
PackageDocsResult,
FilePathAndName,
PackageFilePathAndName,
IDE,
PackageDetails,
ParsedPackageInfo,
} from "../../..";
import { getUriPathBasename } from "../../../util/uri";
import { walkDir, walkDirs } from "../../walkDir";
import { PythonPackageCrawler } from "./packageCrawlers/Python";
import { NodePackageCrawler } from "./packageCrawlers/TsJs";
const PACKAGE_CRAWLERS = [NodePackageCrawler, PythonPackageCrawler];
export interface PackageCrawler {
packageRegistry: string;
getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[];
parsePackageFile(
file: PackageFilePathAndName,
contents: string,
): ParsedPackageInfo[];
getPackageDetails(packageInfo: ParsedPackageInfo): Promise<PackageDetails>;
}
export async function getAllSuggestedDocs(ide: IDE) {
const allFileUris = await walkDirs(ide);
const allFiles = allFileUris.map((uri) => ({
path: uri,
name: getUriPathBasename(uri),
}));
// Build map of language -> package files
const packageFilesByRegistry: Record<string, PackageFilePathAndName[]> = {};
for (const Crawler of PACKAGE_CRAWLERS) {
const crawler = new Crawler();
const packageFilePaths = crawler.getPackageFiles(allFiles);
packageFilesByRegistry[crawler.packageRegistry] = packageFilePaths;
}
// Get file contents for all unique package files
const uniqueFilePaths = Array.from(
new Set(
Object.values(packageFilesByRegistry).flatMap((files) =>
files.map((file) => file.path),
),
),
);
const fileContentsArray = await Promise.all(
uniqueFilePaths.map(async (path) => {
const contents = await ide.readFile(path);
return { path, contents };
}),
);
const fileContents = new Map(
fileContentsArray.map(({ path, contents }) => [path, contents]),
);
// Parse package files and build map of language -> packages
const packagesByCrawler: Record<string, ParsedPackageInfo[]> = {};
PACKAGE_CRAWLERS.forEach((Crawler) => {
const crawler = new Crawler();
packagesByCrawler[crawler.packageRegistry] = [];
const packageFiles = packageFilesByRegistry[crawler.packageRegistry];
packageFiles.forEach((file) => {
const contents = fileContents.get(file.path);
if (!contents) {
return;
}
const packages = crawler.parsePackageFile(file, contents);
packagesByCrawler[crawler.packageRegistry].push(...packages);
});
});
// Deduplicate packages per language
// TODO - this is where you would allow docs for different versions
// by e.g. using "name-version" as the map key instead of just name
// For now have not allowed
const registries = Object.keys(packagesByCrawler);
registries.forEach((registry) => {
const packages = packagesByCrawler[registry];
const uniquePackages = Array.from(
new Map(packages.map((pkg) => [pkg.name, pkg])).values(),
);
packagesByCrawler[registry] = uniquePackages;
});
// Get documentation links for all packages
const allDocsResults: PackageDocsResult[] = [];
await Promise.all(
PACKAGE_CRAWLERS.map(async (Crawler) => {
const crawler = new Crawler();
const packages = packagesByCrawler[crawler.packageRegistry];
const docsByRegistry = await Promise.all(
packages.map(async (packageInfo) => {
try {
const details = await crawler.getPackageDetails(packageInfo);
if (!details.docsLink) {
return {
packageInfo,
error: `No documentation link found for ${packageInfo.name}`,
};
}
return {
packageInfo,
details: {
...details,
docsLink: details.docsLink,
docsLinkWarning: details.docsLink.includes("github.com")
? "Github docs not supported, find the docs site"
: details.docsLink.includes("docs")
? undefined
: "May not be a docs site, check the URL",
},
};
} catch (error) {
return {
packageInfo,
error: `Error getting package details for ${packageInfo.name}`,
};
}
}),
);
allDocsResults.push(...docsByRegistry);
}),
);
return allDocsResults;
}

View file

@ -1,63 +0,0 @@
import { PackageCrawler } from "..";
import {
FilePathAndName,
PackageDetails,
PackageFilePathAndName,
ParsedPackageInfo,
} from "../../../..";
export class PythonPackageCrawler implements PackageCrawler {
packageRegistry = "pypi";
getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] {
// For Python, we typically look for files like requirements.txt or Pipfile
return files
.filter(
(file) => file.name === "requirements.txt" || file.name === "Pipfile",
)
.map((file) => ({
...file,
packageRegistry: "pypi",
}));
}
parsePackageFile(
file: PackageFilePathAndName,
contents: string,
): ParsedPackageInfo[] {
// Assume the fileContent is a string from a requirements.txt formatted file
return contents
.split("\n")
.map((line) => {
const [name, version] = line.split("==");
return { name, version, packageFile: file, language: "py" };
})
.filter((pkg) => pkg.name && pkg.version);
}
async getPackageDetails(
packageInfo: ParsedPackageInfo,
): Promise<PackageDetails> {
// Fetch metadata from PyPI to find the documentation link
const response = await fetch(
`https://pypi.org/pypi/${packageInfo.name}/json`,
);
if (!response.ok) {
throw new Error(`Could not fetch data for package ${packageInfo.name}`);
}
const data = await response.json();
const homePage = data?.info?.home_page as string | undefined;
return {
docsLink:
(data?.info?.project_urls?.Documentation as string | undefined) ??
homePage,
title: data?.info?.name as string | undefined,
description: data?.info?.summary as string | undefined,
repo:
(data?.info?.project_urls?.Repository as string | undefined) ??
homePage,
license: data?.info?.license as string | undefined,
};
}
}

View file

@ -1,77 +0,0 @@
import { PackageCrawler } from "..";
import {
FilePathAndName,
PackageDetails,
PackageFilePathAndName,
ParsedPackageInfo,
} from "../../../..";
export class NodePackageCrawler implements PackageCrawler {
packageRegistry = "npm";
getPackageFiles(files: FilePathAndName[]): PackageFilePathAndName[] {
// For Javascript/TypeScript, we look for package.json file
return files
.filter((file) => file.name === "package.json")
.map((file) => ({
...file,
packageRegistry: this.packageRegistry,
}));
}
parsePackageFile(
file: PackageFilePathAndName,
contents: string,
): ParsedPackageInfo[] {
// Parse the package.json content
const jsonData = JSON.parse(contents) as Record<string, Object>;
const dependencies = Object.entries(jsonData.dependencies || {}).concat(
Object.entries(jsonData.devDependencies || {}),
);
// Filter out types packages and check if typescript is present
let foundTypes = false;
const filtered = dependencies.filter(([name, _]) => {
if (name.startsWith("@types/")) {
foundTypes = true;
return false;
}
if (name.includes("typescript")) {
foundTypes = true;
}
return true;
});
return filtered.map(([name, version]) => ({
name,
version,
packageFile: file,
language: foundTypes ? "ts" : "js",
}));
}
async getPackageDetails(
packageInfo: ParsedPackageInfo,
): Promise<PackageDetails> {
const { name } = packageInfo;
// Fetch metadata from the NPM registry to find the documentation link
const response = await fetch(`https://registry.npmjs.org/${name}`);
if (!response.ok) {
throw new Error(`Could not fetch data for package ${name}`);
}
const data = await response.json();
// const dependencies = Object.keys(packageContentData.dependencies || {})
// .concat(Object.keys(packageContentData.devDependencies || {}));
// const usesTypescript = dependencies.includes("typescript");
return {
docsLink: data.homepage as string | undefined,
title: name, // package.json doesn't have specific title field
description: data.description as string | undefined,
repo: Array.isArray(data.repository)
? (data.respository[0]?.url as string | undefined)
: undefined,
license: data.license as string | undefined,
};
}
}

View file

@ -1,283 +0,0 @@
// Generated by continue
import { getAllSuggestedDocs } from "./index";
import { testIde } from "../../../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
} from "../../../test/testDir";
import fetch, { RequestInfo } from "node-fetch";
jest.mock("node-fetch", undefined, {
virtual: false,
});
describe.skip("getAllSuggestedDocs", () => {
beforeEach(() => {
setUpTestDir();
jest.clearAllMocks();
});
afterEach(() => {
tearDownTestDir();
jest.restoreAllMocks();
});
it("should return package docs for JavaScript and Python projects", async () => {
// Set up test files
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
express: "^4.17.1",
lodash: "^4.17.21",
},
devDependencies: {
typescript: "^4.0.0",
},
}),
],
["requirements.txt", "requests==2.25.1\nflask==1.1.2"],
]);
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("registry.npmjs.org/express")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
homepage: "https://expressjs.com/",
name: "express",
description: "Fast, unopinionated, minimalist web framework",
license: "MIT",
}),
}) as any;
} else if (url.toString().includes("registry.npmjs.org/lodash")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
homepage: "https://lodash.com/",
name: "lodash",
description: "Lodash modular utilities.",
license: "MIT",
}),
}) as any;
} else if (url.toString().includes("pypi.org/pypi/requests/json")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
info: {
home_page: "https://docs.python-requests.org/",
name: "requests",
summary: "Python HTTP for Humans.",
license: "Apache 2.0",
},
}),
}) as any;
} else if (url.toString().includes("pypi.org/pypi/flask/json")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
info: {
home_page: "https://palletsprojects.com/p/flask/",
name: "flask",
summary:
"A simple framework for building complex web applications.",
license: "BSD-3-Clause",
},
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(4);
expect(results).toEqual(
expect.arrayContaining([
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "express" }),
details: expect.objectContaining({
docsLink: "https://expressjs.com/",
}),
}),
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "lodash" }),
details: expect.objectContaining({
docsLink: "https://lodash.com/",
}),
}),
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "requests" }),
details: expect.objectContaining({
docsLink: "https://docs.python-requests.org/",
}),
}),
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "flask" }),
details: expect.objectContaining({
docsLink: "https://palletsprojects.com/p/flask/",
}),
}),
]),
);
// Verify no errors are present
results.forEach((result) => {
expect(result.error).toBeUndefined();
});
});
it("should handle packages without documentation links", async () => {
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
"no-docs-package": "^1.0.0",
},
}),
],
]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: RequestInfo | URL) => {
if (url.toString().includes("registry.npmjs.org/no-docs-package")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
name: "no-docs-package",
description: "A package without docs",
license: "MIT",
// No homepage provided
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].error).toContain(
"No documentation link found for no-docs-package",
);
expect(results[0].details).toBeUndefined();
});
it("should handle errors when fetching package details", async () => {
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
"error-package": "^1.0.0",
},
}),
],
]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("registry.npmjs.org/error-package")) {
return Promise.resolve({
ok: false,
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].error).toContain(
"Error getting package details for error-package",
);
expect(results[0].details).toBeUndefined();
});
it("should handle workspaces with no package files", async () => {
const results = await getAllSuggestedDocs(testIde);
expect(results).toEqual([]);
});
it("should handle packages with GitHub documentation links", async () => {
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
"github-docs-package": "^1.0.0",
},
}),
],
]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("registry.npmjs.org/github-docs-package")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
homepage: "https://github.com/user/repo",
name: "github-docs-package",
description: "A package with GitHub docs",
license: "MIT",
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].details?.docsLink).toBe("https://github.com/user/repo");
expect(results[0].details?.docsLinkWarning).toBe(
"Github docs not supported, find the docs site",
);
});
it("should handle packages with non-docs links", async () => {
addToTestDir([["requirements.txt", "non-docs-package==1.0.0"]]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("pypi.org/pypi/non-docs-package/json")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
info: {
home_page: "https://somewebsite.com",
name: "non-docs-package",
summary: "A package with non-docs homepage",
license: "MIT",
},
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].details?.docsLink).toBe("https://somewebsite.com");
expect(results[0].details?.docsLinkWarning).toBe(
"May not be a docs site, check the URL",
);
});
});

View file

@ -142,6 +142,7 @@ function testLLM(
type: "function",
wouldLikeTo: "Say hello",
readonly: true,
group: "Hello",
},
],
toolChoice: {

45
core/package-lock.json generated
View file

@ -4309,16 +4309,18 @@
}
},
"node_modules/@octokit/openapi-types": {
"version": "22.2.0",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-22.2.0.tgz",
"integrity": "sha512-QBhVjcUa9W7Wwhm6DBFu6ZZ+1/t/oYxqc2tp81Pi41YNuJinbFRx8B133qVOrAaBbF7D/m0Et6f9/pZt9Rc+tg=="
"version": "24.2.0",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-24.2.0.tgz",
"integrity": "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==",
"license": "MIT"
},
"node_modules/@octokit/plugin-paginate-rest": {
"version": "11.3.1",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-11.3.1.tgz",
"integrity": "sha512-ryqobs26cLtM1kQxqeZui4v8FeznirUsksiA+RYemMPJ7Micju0WSkv50dBksTuZks9O5cg4wp+t8fZ/cLY56g==",
"version": "11.4.4-cjs.2",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-11.4.4-cjs.2.tgz",
"integrity": "sha512-2dK6z8fhs8lla5PaOTgqfCGBxgAv/le+EhPs27KklPhm1bKObpu6lXzwfUEQ16ajXzqNrKMujsFyo9K2eaoISw==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.5.0"
"@octokit/types": "^13.7.0"
},
"engines": {
"node": ">= 18"
@ -4339,11 +4341,12 @@
}
},
"node_modules/@octokit/plugin-rest-endpoint-methods": {
"version": "13.2.2",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-13.2.2.tgz",
"integrity": "sha512-EI7kXWidkt3Xlok5uN43suK99VWqc8OaIMktY9d9+RNKl69juoTyxmLoWPIZgJYzi41qj/9zU7G/ljnNOJ5AFA==",
"version": "13.3.2-cjs.1",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-13.3.2-cjs.1.tgz",
"integrity": "sha512-VUjIjOOvF2oELQmiFpWA1aOPdawpyaCUqcEBc/UOUnj3Xp6DJGrJ1+bjUIIDzdHjnFNO6q57ODMfdEZnoBkCwQ==",
"license": "MIT",
"dependencies": {
"@octokit/types": "^13.5.0"
"@octokit/types": "^13.8.0"
},
"engines": {
"node": ">= 18"
@ -4380,25 +4383,27 @@
}
},
"node_modules/@octokit/rest": {
"version": "20.1.1",
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-20.1.1.tgz",
"integrity": "sha512-MB4AYDsM5jhIHro/dq4ix1iWTLGToIGk6cWF5L6vanFaMble5jTX/UBQyiv05HsWnwUtY8JrfHy2LWfKwihqMw==",
"version": "20.1.2",
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-20.1.2.tgz",
"integrity": "sha512-GmYiltypkHHtihFwPRxlaorG5R9VAHuk/vbszVoRTGXnAsY60wYLkh/E2XiFmdZmqrisw+9FaazS1i5SbdWYgA==",
"license": "MIT",
"dependencies": {
"@octokit/core": "^5.0.2",
"@octokit/plugin-paginate-rest": "11.3.1",
"@octokit/plugin-paginate-rest": "11.4.4-cjs.2",
"@octokit/plugin-request-log": "^4.0.0",
"@octokit/plugin-rest-endpoint-methods": "13.2.2"
"@octokit/plugin-rest-endpoint-methods": "13.3.2-cjs.1"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/@octokit/types": {
"version": "13.6.2",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.6.2.tgz",
"integrity": "sha512-WpbZfZUcZU77DrSW4wbsSgTPfKcp286q3ItaIgvSbBpZJlu6mnYXAkjZz6LVZPXkEvLIM8McanyZejKTYUHipA==",
"version": "13.10.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.10.0.tgz",
"integrity": "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==",
"license": "MIT",
"dependencies": {
"@octokit/openapi-types": "^22.2.0"
"@octokit/openapi-types": "^24.2.0"
}
},
"node_modules/@pkgjs/parseargs": {

View file

@ -53,16 +53,15 @@ export function slashCommandFromPromptFileV1(
path: string,
content: string,
): SlashCommand | null {
const { name, description, systemMessage, prompt, version } =
parsePromptFileV1V2(path, content);
if (version !== 1) {
return null;
}
const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
path,
content,
);
return {
name,
description,
prompt,
run: async function* (context) {
const originalSystemMessage = context.llm.systemMessage;
context.llm.systemMessage = systemMessage;

View file

@ -1,4 +1,5 @@
import * as YAML from "yaml";
import { getLastNPathParts } from "../../util/uri";
export function extractName(preamble: { name?: string }, path: string): string {

View file

@ -1,4 +1,5 @@
import * as YAML from "yaml";
import { getLastNPathParts } from "../../util/uri";
export function parsePromptFileV1V2(path: string, content: string) {

View file

@ -3,6 +3,7 @@ import { contextProviderClassFromName } from "../../context/providers";
import URLContextProvider from "../../context/providers/URLContextProvider";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { getPreambleAndBody } from "./parse";
async function resolveAttachment(

View file

@ -1,11 +1,15 @@
import { ConfigResult, ModelRole } from "@continuedev/config-yaml";
import {
ConfigResult,
DevDataLogEvent,
ModelRole,
} from "@continuedev/config-yaml";
import { AutocompleteInput } from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ConfigHandler";
import { OrganizationDescription } from "../config/ProfileLifecycleManager";
import { SharedConfigSchema } from "../config/sharedConfig";
import { GlobalContextModelSelections } from "../util/GlobalContext";
import { DevDataLogEvent } from "@continuedev/config-yaml";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@ -29,7 +33,6 @@ import type {
SlashCommandDescription,
ToolCall,
} from "../";
import { GlobalContextModelSelections } from "../util/GlobalContext";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
@ -94,6 +97,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"mcp/reloadServer": [
{
id: string;
},
void,
];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];

View file

@ -26,6 +26,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/openProfile",
"config/updateSharedConfig",
"config/updateSelectedModel",
"mcp/reloadServer",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@ -51,7 +52,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
"docs/getDetails",
//
@ -80,7 +80,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"docs/suggestions",
"didCloseFiles",
"didSelectOrganization",
];

View file

@ -37,6 +37,5 @@ export type ToWebviewFromIdeOrCoreProtocol = {
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
getCurrentSessionId: [undefined, string];
"docs/suggestions": [PackageDocsResult[], void];
"jetbrains/setColors": [Record<string, string>, void];
};

View file

@ -8,4 +8,5 @@ export enum BuiltInToolNames {
ExactSearch = "builtin_exact_search",
SearchWeb = "builtin_search_web",
ViewDiff = "builtin_view_diff",
}
}
export const BUILT_IN_GROUP_NAME = "Built-In";

View file

@ -1,10 +1,11 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const createNewFileTool: Tool = {
type: "function",
displayTitle: "Create New File",
wouldLikeTo: "create a new file",
group: BUILT_IN_GROUP_NAME,
readonly: false,
function: {
name: BuiltInToolNames.CreateNewFile,

View file

@ -1,11 +1,12 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const exactSearchTool: Tool = {
type: "function",
displayTitle: "Exact Search",
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ExactSearch,
description: "Perform an exact search over the repository using ripgrep.",

View file

@ -1,11 +1,12 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const readCurrentlyOpenFileTool: Tool = {
type: "function",
displayTitle: "Read Currently Open File",
wouldLikeTo: "read the current file",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ReadCurrentlyOpenFile,
description:

View file

@ -1,11 +1,12 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const readFileTool: Tool = {
type: "function",
displayTitle: "Read File",
wouldLikeTo: "read {{{ filepath }}}",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ReadFile,
description:

View file

@ -1,11 +1,12 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const runTerminalCommandTool: Tool = {
type: "function",
displayTitle: "Run Terminal Command",
wouldLikeTo: "run a terminal command",
readonly: false,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.RunTerminalCommand,
description:

View file

@ -1,12 +1,13 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const searchWebTool: Tool = {
type: "function",
displayTitle: "Search Web",
wouldLikeTo: 'search the web for "{{{ query }}}"',
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.SearchWeb,
description:

View file

@ -1,12 +1,13 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const viewDiffTool: Tool = {
type: "function",
displayTitle: "View Diff",
wouldLikeTo: "view a diff",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ViewDiff,
description: "View the current diff of working changes",

View file

@ -1,12 +1,13 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const viewRepoMapTool: Tool = {
type: "function",
displayTitle: "View Repo Map",
wouldLikeTo: "view the repository map",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ViewRepoMap,
description: "View the repository map",

View file

@ -1,11 +1,12 @@
import { Tool } from "../..";
import { BuiltInToolNames } from "../builtIn";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const viewSubdirectoryTool: Tool = {
type: "function",
displayTitle: "View Subdirectory",
wouldLikeTo: 'view the contents of "{{{ directory_path }}}"',
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.ViewSubdirectory,
description: "View the contents of a subdirectory",

View file

@ -2,10 +2,10 @@ import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { DevEventName } from "@continuedev/config-yaml";
import * as JSONC from "comment-json";
import dotenv from "dotenv";
import { DevEventName } from "@continuedev/config-yaml";
import { IdeType, SerializedContinueConfig } from "../";
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
import Types from "../config/types";

View file

@ -2,11 +2,11 @@
title: Prompt files
---
Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts.
Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub.
On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules).
Prompt files can also be stored within your project's root directory as `.prompt` files. See below.
:::info
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
:::
## Quick start
@ -25,7 +25,7 @@ Attached is a summary of the current Ruby on Rails application, including the @G
Now to use this prompt, you can highlight code and use <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> to select it in the Continue sidebar.
Then, type "@", select "Prompt files", and choose the one called "Rails Project". You can now ask any question as usual and the LLM will have the information from your .prompt file.
Then, type <kbd>/</kbd> and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file.
## Format

View file

@ -43,8 +43,8 @@ Prompts blocks are pre-written, reusable prompts that can be referenced at any t
Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files:
1. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and
2. Prompt blocks only show up as slash commands in Chat, not under the `@Prompt Files` context provider
1. Currently, prompt blocks cannot use context providers
2. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and
The `config.yaml` spec for `prompts` can be found [here](../../yaml-reference.md#prompts).
@ -52,4 +52,4 @@ The `config.yaml` spec for `prompts` can be found [here](../../yaml-reference.md
Data blocks allow you send your development data to custom destinations of your choice. Development data can be used for a variety of purposes, including analyzing usage, gathering insights, or fine-tuning models. You can read more about development data [here](../../customize/deep-dives/development-data.md). Explore data block examples [here](https://hub.continue.dev/explore/data).
Data destinations are configured in the[`data`](../../yaml-reference.md#data) section of `config.yaml`.
Data destinations are configured in the [`data`](../../yaml-reference.md#data) section of `config.yaml`.

View file

@ -126,12 +126,3 @@ class OpenConfigAction : AnAction() {
continuePluginService.sendToWebview("navigateTo", params)
}
}
class OpenMorePageAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val continuePluginService = getContinuePluginService(e.project) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
val params = mapOf("path" to "/more", "toggle" to true)
continuePluginService.sendToWebview("navigateTo", params)
}
}

View file

@ -69,7 +69,6 @@ class MessageTypes {
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"docs/suggestions",
"didCloseFiles",
"didSelectOrganization"
)
@ -94,6 +93,7 @@ class MessageTypes {
"config/openProfile",
"config/updateSharedConfig",
"config/updateSelectedModel",
"mcp/reloadServer",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@ -120,7 +120,6 @@ class MessageTypes {
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
"docs/getDetails",
//

View file

@ -140,19 +140,10 @@
<override-text place="GoToAction" text="Continue Config"/>
</action>
<action id="continue.openMorePage"
class="com.github.continuedev.continueintellijextension.actions.OpenMorePageAction"
icon="AllIcons.Actions.MoreHorizontal"
text="More"
description="More">
<override-text place="GoToAction" text="More"/>
</action>
<group id="ContinueSidebarActionsGroup">
<reference ref="continue.newContinueSession"/>
<reference ref="continue.viewHistory"/>
<reference ref="continue.openConfigPage"/>
<reference ref="continue.openMorePage"/>
</group>
<action id="continue.focusContinueInput"

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.13",
"version": "1.1.14",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -258,13 +258,6 @@
"title": "Navigate to a path",
"group": "Continue"
},
{
"command": "continue.openMorePage",
"category": "Continue",
"title": "More",
"icon": "$(ellipsis)",
"group": "Continue"
},
{
"command": "continue.writeCommentsForCode",
"category": "Continue",
@ -512,11 +505,6 @@
"command": "continue.openConfigPage",
"group": "navigation@4",
"when": "view == continue.continueGUIView"
},
{
"command": "continue.openMorePage",
"group": "navigation@6",
"when": "view == continue.continueGUIView"
}
],
"editor/title": [

View file

@ -1,6 +1,7 @@
const esbuild = require("esbuild");
const fs = require("fs");
const esbuild = require("esbuild");
const flags = process.argv.slice(2);
const esbuildConfig = {
@ -59,9 +60,9 @@ const esbuildConfig = {
// The watcher automatically notices changes to source files
// so the only thing it needs to be notified about is if the
// output file gets removed.
if (fs.existsSync (outFile)) {
console.log("VS Code Extension esbuild up to date");
return;
if (fs.existsSync(outFile)) {
console.log("VS Code Extension esbuild up to date");
return;
}
fs.watchFile(outFile, (current, previous) => {

View file

@ -284,6 +284,9 @@ async function processDiff(
}
await sidebar.webviewProtocol.request("exitEditMode", undefined);
// Save the file
await ide.saveFile(newOrCurrentUri);
}
function waitForSidebarReady(
@ -991,9 +994,6 @@ const getCommandsMap: (
vscode.commands.executeCommand("continue.focusContinueInput");
} else if (selectedOption === "$(screen-full) Open full screen chat") {
vscode.commands.executeCommand("continue.toggleFullScreen");
} else if (selectedOption === "$(question) Open help center") {
focusGUI();
vscode.commands.executeCommand("continue.navigateTo", "/more", true);
}
quickPick.dispose();
});
@ -1016,9 +1016,6 @@ const getCommandsMap: (
client.sendFeedback(feedback, lastLines);
}
},
"continue.openMorePage": () => {
vscode.commands.executeCommand("continue.navigateTo", "/more", true);
},
"continue.navigateTo": (path: string, toggle: boolean) => {
sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
focusGUI();

View file

@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/play_button.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Continue</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="../src/editorInset/main.tsx"></script>
</body>
</html>

View file

@ -1,19 +0,0 @@
import react from "@vitejs/plugin-react-swc";
import tailwindcss from "tailwindcss";
import { defineConfig } from "vite";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
build: {
// Change the output .js filename to not include a hash
rollupOptions: {
// external: ["vscode-webview"],
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
},
},
},
});

View file

@ -1,19 +1,16 @@
import { useDispatch } from "react-redux";
import { RouterProvider, createMemoryRouter } from "react-router-dom";
import Layout from "./components/Layout";
import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders";
import { VscThemeProvider } from "./context/VscTheme";
import useSetup from "./hooks/useSetup";
import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel";
import ConfigPage from "./pages/config";
import ConfigErrorPage from "./pages/config-error";
import ErrorPage from "./pages/error";
import Chat from "./pages/gui";
import History from "./pages/history";
import MigrationPage from "./pages/migration";
import MorePage from "./pages/More";
import Stats from "./pages/stats";
import { ROUTES } from "./util/navigation";
import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders";
import ConfigPage from "./pages/config";
const router = createMemoryRouter([
{
@ -45,10 +42,6 @@ const router = createMemoryRouter([
path: "/addModel/provider/:providerName",
element: <ConfigureProvider />,
},
{
path: "/more",
element: <MorePage />,
},
{
path: ROUTES.CONFIG_ERROR,
element: <ConfigErrorPage />,
@ -57,10 +50,6 @@ const router = createMemoryRouter([
path: ROUTES.CONFIG,
element: <ConfigPage />,
},
{
path: "/migration",
element: <MigrationPage />,
},
],
},
]);

View file

@ -1,9 +1,9 @@
import { useState, useEffect, useRef } from "react";
import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders";
import { Combobox } from "@headlessui/react";
import FileIcon from "../FileIcon";
import { useAppSelector } from "../../redux/hooks";
import { ContextSubmenuItemWithProvider } from "core";
import { useEffect, useRef, useState } from "react";
import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders";
import { useAppSelector } from "../../redux/hooks";
import FileIcon from "../FileIcon";
export interface AddFileComboboxProps {
onSelect: (filepaths: string[]) => void | Promise<void>;

View file

@ -0,0 +1,39 @@
import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
import { SlashCommandDescription } from "core";
import { useState } from "react";
import { defaultBorderRadius, vscInputBackground } from "..";
interface ConversationStarterCardProps {
command: SlashCommandDescription;
onClick: (command: SlashCommandDescription) => void;
}
export function ConversationStarterCard({
command,
onClick,
}: ConversationStarterCardProps) {
const [isHovered, setIsHovered] = useState(false);
return (
<div
className="mb-2 w-full shadow-md hover:cursor-pointer hover:brightness-110"
style={{
borderRadius: defaultBorderRadius,
backgroundColor: vscInputBackground,
}}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onClick={() => onClick(command)}
>
<div className="flex px-3 py-1.5">
<div className="mr-3 flex-shrink-0 self-start pt-0.5">
<ChatBubbleLeftIcon className="text-lightgray h-5 w-5" />
</div>
<div className="flex flex-1 flex-col">
<div className="text-xs font-medium">{command.name}</div>
<div className="text-lightgray text-xs">{command.description}</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,37 @@
import { SlashCommandDescription } from "core";
import { useAppDispatch } from "../../redux/hooks";
import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice";
import { getParagraphNodeFromString } from "../mainInput/utils";
import { ConversationStarterCard } from "./ConversationStarterCard";
import { useBookmarkedSlashCommands } from "./useBookmarkedSlashCommands";
const NUM_CARDS_TO_RENDER = 3;
export function ConversationStarterCards() {
const dispatch = useAppDispatch();
const { cmdsSortedByBookmark } = useBookmarkedSlashCommands();
function onClick(command: SlashCommandDescription) {
if (command.prompt) {
dispatch(
setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)),
);
}
}
if (!cmdsSortedByBookmark || cmdsSortedByBookmark.length === 0) {
return null;
}
return (
<div className="flex w-full max-w-full flex-col lg:grid lg:grid-cols-3 lg:gap-4">
{cmdsSortedByBookmark.slice(0, NUM_CARDS_TO_RENDER).map((command, i) => (
<ConversationStarterCard
key={command.name + i}
command={command}
onClick={onClick}
/>
))}
</div>
);
}

View file

@ -0,0 +1,45 @@
import { SlashCommandDescription } from "core";
import { sortCommandsByBookmarkStatus } from "../utils";
describe("sortCommandsByBookmarkStatus", () => {
const mockCommands: SlashCommandDescription[] = [
{
name: "command1",
description: "First command",
prompt: "This is command 1",
},
{
name: "command2",
description: "Second command",
prompt: "This is command 2",
},
{
name: "command3",
description: "Third command",
prompt: "This is command 3",
},
{
name: "command4",
description: "Fourth command",
prompt: "This is command 4",
},
];
it("should return commands in the same order when no bookmarks exist", () => {
const result = sortCommandsByBookmarkStatus(mockCommands, []);
expect(result).toEqual(mockCommands);
// Ensure it's a new array, not the original
expect(result).not.toBe(mockCommands);
});
it("should put bookmarked commands first", () => {
const bookmarkedCommands = ["command3", "command1"];
const result = sortCommandsByBookmarkStatus(
mockCommands,
bookmarkedCommands,
);
expect(result[0].name).toBe("command1");
expect(result[1].name).toBe("command3");
});
});

View file

@ -0,0 +1 @@
export * from "./ConversationStarterCards";

View file

@ -0,0 +1,69 @@
import { SlashCommandDescription } from "core";
import { usePostHog } from "posthog-js/react";
import { useMemo } from "react";
import {
bookmarkSlashCommand,
selectBookmarkedSlashCommands,
selectSelectedProfileId,
unbookmarkSlashCommand,
} from "../../redux";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { isDeprecatedCommandName, sortCommandsByBookmarkStatus } from "./utils";
export function useBookmarkedSlashCommands() {
const dispatch = useAppDispatch();
const posthog = usePostHog();
const slashCommands =
useAppSelector((state) => state.config.config.slashCommands) ?? [];
const selectedProfileId = useAppSelector(selectSelectedProfileId);
const bookmarkedCommands = useAppSelector(selectBookmarkedSlashCommands);
const filteredSlashCommands = slashCommands.filter(isDeprecatedCommandName);
// Create a map of command names to bookmark status
const bookmarkStatuses = useMemo(() => {
const statuses: Record<string, boolean> = {};
if (selectedProfileId) {
filteredSlashCommands.forEach((command) => {
statuses[command.name] = bookmarkedCommands.includes(command.name);
});
}
return statuses;
}, [filteredSlashCommands, bookmarkedCommands, selectedProfileId]);
// Sort commands by bookmark status
const cmdsSortedByBookmark = useMemo(
() =>
sortCommandsByBookmarkStatus(filteredSlashCommands, bookmarkedCommands),
[filteredSlashCommands, bookmarkedCommands],
);
const toggleBookmark = (command: SlashCommandDescription) => {
const isBookmarked = bookmarkStatuses[command.name];
posthog.capture("toggle_bookmarked_slash_command", {
isBookmarked,
});
if (isBookmarked) {
dispatch(
unbookmarkSlashCommand({
commandName: command.name,
}),
);
} else {
dispatch(
bookmarkSlashCommand({
commandName: command.name,
}),
);
}
};
return {
cmdsSortedByBookmark,
bookmarkStatuses,
toggleBookmark,
};
}

View file

@ -0,0 +1,49 @@
import { SlashCommandDescription } from "core";
import {
defaultSlashCommandsJetBrains,
defaultSlashCommandsVscode,
} from "core/config/default";
import { isJetBrains } from "../../util";
/**
* The commands filtered here are currently inserted into the slash commands array during
* intermediary config loading, but once we get the actual prompts for an assistant,
* they are overwritten.
*
* Additionally, these default commands are all deprecated.
*
* If we don't manually filter them out, then they are displayed in the UI
* while the assistant is still loading.
*
* Once these commands are no longer inserted during intermediary config loading,
* this function can be removed.
*/
export function isDeprecatedCommandName(command: SlashCommandDescription) {
const defaultCommands = isJetBrains()
? defaultSlashCommandsJetBrains
: defaultSlashCommandsVscode;
return !defaultCommands.find(
(defaultCommand) => defaultCommand.name === command.name,
);
}
/**
* Sorts commands with bookmarked ones first
* @param commands The list of commands to sort
* @param bookmarkedCommands An array of bookmarked command names
* @returns A new sorted array with bookmarked commands first
*/
export function sortCommandsByBookmarkStatus(
commands: SlashCommandDescription[],
bookmarkedCommands: string[],
): SlashCommandDescription[] {
return [...commands].sort((a, b) => {
const aIsBookmarked = bookmarkedCommands.includes(a.name);
const bIsBookmarked = bookmarkedCommands.includes(b.name);
if (aIsBookmarked && !bIsBookmarked) return -1;
if (!aIsBookmarked && bIsBookmarked) return 1;
return 0;
});
}

View file

@ -17,7 +17,7 @@ import {
import { setShowDialog } from "../redux/slices/uiSlice";
import { exitEditMode } from "../redux/thunks";
import { loadLastSession, saveCurrentSession } from "../redux/thunks/session";
import { getFontSize, isMetaEquivalentKeyPressed } from "../util";
import { fontSize, isMetaEquivalentKeyPressed } from "../util";
import { incrementFreeTrialCount } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
import TextDialog from "./dialogs";
@ -305,10 +305,7 @@ const Layout = () => {
<Footer />
</GridDiv>
</div>
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
<div style={{ fontSize: fontSize(-4) }} id="tooltip-portal-div" />
</LayoutTopDiv>
</AuthProvider>
);

View file

@ -1,15 +1,13 @@
import { OnboardingModes } from "core/protocol/core";
import { usePostHog } from "posthog-js/react";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
import { OnboardingModes } from "core/protocol/core";
import { useTutorialCard } from "../../../hooks/useTutorialCard";
import { useOnboardingCard } from "./useOnboardingCard";
export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) {
const posthog = usePostHog();
const ideMessenger = useContext(IdeMessengerContext);
const { openTutorialCard } = useTutorialCard();
const { close: closeOnboardingCard } = useOnboardingCard();
function submitOnboarding() {
@ -31,9 +29,6 @@ export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) {
// Local state
setLocalStorage("onboardingStatus", "Completed");
// Show tutorial card
openTutorialCard();
// Move to next step in onboarding
ideMessenger.post("showTutorial", undefined);
}

View file

@ -1,4 +1,5 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { fontSize } from "../util";
export interface PageHeaderProps {
onTitleClick?: () => void;
@ -15,7 +16,7 @@ export default function PageHeader({
}: PageHeaderProps) {
return (
<div
className={`bg-vsc-background sticky top-0 z-20 m-0 flex items-center justify-between bg-inherit py-0.5 ${
className={`bg-vsc-background sticky top-0 z-20 m-0 flex items-center justify-between bg-inherit ${
showBorder
? "border-0 border-b-[1px] border-solid border-b-zinc-700"
: ""
@ -25,11 +26,16 @@ export default function PageHeader({
{title && (
<>
<div
className="cursor-pointer transition-colors duration-200 hover:text-zinc-100"
className="flex cursor-pointer items-center transition-colors duration-200 hover:text-zinc-100"
onClick={onTitleClick}
>
<ArrowLeftIcon className="ml-3 inline-block h-3 w-3" />
<span className="m-2 inline-block text-base font-bold">
<span
className="mx-2 inline-block text-base font-bold"
style={{
fontSize: fontSize(-2),
}}
>
{title}
</span>
</div>

View file

@ -20,8 +20,10 @@ interface StepContainerProps {
}
const ContentDiv = styled.div<{ fontSize?: number }>`
padding-top: 4px;
padding-bottom: 4px;
padding: 4px;
padding-left: 6px;
padding-right: 6px;
background-color: ${vscBackground};
font-size: ${getFontSize()}px;
overflow: hidden;

View file

@ -1,26 +1,17 @@
import {
CheckIcon,
InformationCircleIcon,
PencilIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import { IndexingStatus, PackageDocsResult, SiteIndexingConfig } from "core";
import preIndexedDocs from "core/indexing/docs/preIndexedDocs";
import { InformationCircleIcon } from "@heroicons/react/24/outline";
import { IndexingStatus, SiteIndexingConfig } from "core";
import { usePostHog } from "posthog-js/react";
import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { Input, SecondaryButton } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { updateConfig } from "../../redux/slices/configSlice";
import { updateIndexingStatus } from "../../redux/slices/indexingSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import FileIcon from "../FileIcon";
import { ToolTip } from "../gui/Tooltip";
import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks";
import DocsIndexingPeeks from "../mainInput/Lump/sections/docs/DocsIndexingPeeks";
function AddDocsDialog() {
const config = useAppSelector((store) => store.config.config);
const posthog = usePostHog();
const dispatch = useDispatch();
@ -42,36 +33,6 @@ function AddDocsDialog() {
);
}, [indexingStatuses]);
const docsSuggestions = useAppSelector((store) => store.misc.docsSuggestions);
const configDocs = useAppSelector((store) => store.config.config.docs);
const sortedDocsSuggestions = useMemo(() => {
const docsFromConfig = configDocs ?? [];
// Don't show suggestions that are already in the config, indexing, and/or pre-indexed
const filtered = docsSuggestions.filter((sug) => {
const startUrl = sug.details?.docsLink;
return (
!docsFromConfig.find((d) => d.startUrl === startUrl) &&
!docsIndexingStatuses.find((s) => s.id === startUrl) &&
(startUrl ? !preIndexedDocs[startUrl] : true)
);
});
filtered.sort((a, b) => {
const rank = (result: PackageDocsResult) => {
if (result.error) {
return 2;
} else if (result.details?.docsLinkWarning) {
return 1;
} else {
return 0;
}
};
return rank(a) - rank(b);
});
return filtered;
}, [docsSuggestions, configDocs, docsIndexingStatuses]);
const isFormValid = startUrl && title;
useLayoutEffect(() => {
@ -118,59 +79,6 @@ function AddDocsDialog() {
);
}
const handleSelectSuggestion = (docsResult: PackageDocsResult) => {
if (docsResult.error || !docsResult.details) {
setTitle(docsResult.packageInfo.name);
setStartUrl("");
urlRef.current?.focus();
return;
}
const suggestedTitle =
docsResult.details.title ?? docsResult.packageInfo.name;
if (docsResult.details?.docsLinkWarning) {
setTitle(suggestedTitle);
setStartUrl(docsResult.details.docsLink);
urlRef.current?.focus();
return;
}
const siteIndexingConfig: SiteIndexingConfig = {
startUrl: docsResult.details.docsLink,
title: suggestedTitle,
faviconUrl: undefined,
};
ideMessenger.post("context/addDocs", siteIndexingConfig);
posthog.capture("add_docs_gui", { url: startUrl });
// Optimistic status update
dispatch(
updateConfig({
...config,
docs: [
...(config.docs?.filter(
(doc) => doc.startUrl !== docsResult.details.docsLink,
) ?? []),
{
startUrl: docsResult.details.docsLink,
title: suggestedTitle,
faviconUrl: undefined,
},
],
}),
updateIndexingStatus({
type: "docs",
description: "Initializing",
id: docsResult.details.docsLink,
progress: 0,
status: "indexing",
title: docsResult.details.title ?? docsResult.packageInfo.name,
url: docsResult.details.docsLink,
}),
);
};
return (
<div className="px-2 pt-4 sm:px-4">
<div className="">
@ -179,91 +87,10 @@ function AddDocsDialog() {
<p className="m-0 mt-2 p-0 text-stone-500">
For the @docs context provider
</p>
{!!sortedDocsSuggestions.length && (
<p className="m-0 mb-1 mt-4 p-0 font-semibold">Suggestions</p>
)}
<div className="border-lightgray max-h-[145px] overflow-y-scroll rounded-sm py-1 pr-2">
{sortedDocsSuggestions.map((docsResult) => {
const { error, details } = docsResult;
const { language, name, version } = docsResult.packageInfo;
const id = `${language}-${name}-${version}`;
return (
<div
key={id}
className="grid cursor-pointer grid-cols-[auto_minmax(0,1fr)_minmax(0,1fr)_auto] items-center px-1 py-1 hover:bg-gray-200/10"
onClick={() => {
handleSelectSuggestion(docsResult);
}}
>
<div className="pr-1">
{error || details?.docsLinkWarning ? (
<div>
<PencilIcon
data-tooltip-id={id + "-edit"}
className="text-lightgray h-3 w-3"
/>
<ToolTip id={id + "-edit"} place="bottom">
This may not be a docs page
</ToolTip>
</div>
) : (
<PlusIcon className="text-lightgray h-3.5 w-3.5" />
)}
</div>
<div className="flex items-center gap-0.5">
<div className="hidden sm:block">
<FileIcon
filename={`x.${language}`}
height="1rem"
width="1rem"
/>
</div>
<span className="lines lines-1">{name}</span>
</div>
<div>
{error || !details?.docsLink ? (
<span className="text-lightgray italic">
No docs link found
</span>
) : (
<div className="flex items-center gap-2">
{/* <div>
<LinkIcon className="h-2 w-2" />
</div> */}
<p
className="lines lines-1 m-0 p-0 hover:underline"
onClick={(e) => {
e.stopPropagation();
ideMessenger.post("openUrl", details.docsLink);
}}
>
{details.docsLink}
</p>
</div>
)}
</div>
<div
onClick={(e) => {
e.stopPropagation();
}}
>
<InformationCircleIcon
data-tooltip-id={id + "-info"}
className="text-lightgray h-3.5 w-3.5 select-none"
/>
<ToolTip id={id + "-info"} place="bottom">
<p className="m-0 p-0">{`Version: ${version}`}</p>
<p className="m-0 p-0">{`Found in ${docsResult.packageInfo.packageFile.path}`}</p>
</ToolTip>
</div>
</div>
);
})}
</div>
<div className="mt-3">
<form onSubmit={onSubmit} className="flex flex-col gap-1">
<div className="flex flex-row gap-2">
<label className="flex min-w-16 basis-1/4 flex-col gap-1">
<div className="flex flex-col gap-2">
<label className="flex w-full flex-col gap-1">
<div className="flex flex-row items-center gap-1">
<span>Title</span>
<div>
@ -287,7 +114,7 @@ function AddDocsDialog() {
/>
</label>
<label className="flex basis-3/4 flex-col gap-1">
<label className="flex w-full flex-col gap-1">
<div className="flex flex-row items-center gap-1">
<span className="lines lines-1 whitespace-nowrap">
Start URL
@ -313,9 +140,6 @@ function AddDocsDialog() {
}}
/>
</label>
{/* <div>
<PlusCircleIcon className="h-5 w-5 self-end" />
</div> */}
</div>
<div className="flex flex-row justify-end gap-2">
<SecondaryButton
@ -330,20 +154,19 @@ function AddDocsDialog() {
</div>
</div>
<DocsIndexingPeeks statuses={docsIndexingStatuses} />
<div className="flex flex-row items-end justify-between pb-3">
<div>
{docsIndexingStatuses.length ? (
<p className="mt-2 flex flex-row items-center gap-1 p-0 px-1 text-xs text-stone-500">
<CheckIcon className="h-3 w-3" />
It is safe to close this form while indexing
</p>
) : null}
</div>
{/* <Button className="min-w-16" onClick={closeDialog}>
Done
</Button> */}
</div>
{docsIndexingStatuses.length > 0 && (
<>
<DocsIndexingPeeks statuses={docsIndexingStatuses} />
<div className="flex flex-row items-end justify-between pb-3">
<div>
<InformationCircleIcon className="h-3 w-3" />
<p className="mt-2 flex flex-row items-center gap-1 p-0 px-1 text-xs text-stone-500">
Closing this dialog will not affect indexing progress
</p>
</div>
</div>
</>
)}
</div>
);
}

View file

@ -1,27 +1,38 @@
import React from "react";
import { vscButtonBackground } from "..";
type ToggleSwitchProps = {
isToggled: boolean;
onToggle: () => void;
text: string;
size?: number;
};
const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
isToggled,
onToggle,
text,
size = 16,
}) => {
return (
<div className="flex cursor-pointer select-none items-center justify-between gap-3">
<span className="truncate-right">{text}</span>
<div>
<div
className={`border-vsc-input-border bg-vsc-input-background flex h-4 w-8 items-center rounded-full border border-solid p-0.5`}
className={`border-vsc-input-border bg-vsc-input-background flex items-center rounded-full border border-solid`}
onClick={onToggle}
style={{
height: size,
width: size * 2,
padding: size / 8,
}}
>
<div className="relative h-full w-full">
<div
className={`absolute left-1/4 top-0 h-full w-1/2 transform rounded-full transition-all ${isToggled ? "translate-x-1/2 bg-green-500" : "-translate-x-1/2 bg-red-500"}`}
className={`absolute left-1/4 top-0 h-full w-1/2 transform rounded-full border-[0.2px] border-solid transition-all ${isToggled ? "translate-x-1/2 brightness-150" : "-translate-x-1/2 brightness-75"}`}
style={{
backgroundColor: isToggled ? vscButtonBackground : "",
}}
/>
</div>
</div>

View file

@ -1,10 +1,10 @@
import ReactDOM from "react-dom";
import { Tooltip } from "react-tooltip";
import { vscBackground, vscForeground, vscInputBorder } from "..";
import { getFontSize } from "../../util";
import { fontSize } from "../../util";
const TooltipStyles = {
fontSize: `${getFontSize() - 2}px`,
fontSize: fontSize(-2),
backgroundColor: vscBackground,
outline: `0.5px solid ${vscInputBorder}`,
color: vscForeground,
@ -25,7 +25,7 @@ export function ToolTip(props: any) {
return (
tooltipPortalDiv &&
ReactDOM.createPortal(
<Tooltip {...props} style={combinedStyles} opacity={1} />,
<Tooltip {...props} style={combinedStyles} opacity={1} delayShow={400} />,
tooltipPortalDiv,
)
);

View file

@ -1,5 +1,5 @@
import styled from "styled-components";
import { getFontSize, isJetBrains } from "../util";
import { getFontSize } from "../util";
export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
@ -59,6 +59,7 @@ export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, $
export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`;
export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`;
export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`;
export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`;
export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`;
@ -151,7 +152,7 @@ export const SecondaryButton = styled.button`
`;
export const GhostButton = styled.button`
padding: 10px 12px;
padding: 6px 8px;
margin: 8px 0;
border-radius: ${defaultBorderRadius};

View file

@ -1,8 +1,8 @@
import { useDispatch } from "react-redux";
import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline";
import { IndexingStatus } from "core";
import { useMemo } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline";
import { useAppSelector } from "../../redux/hooks";
import { setIndexingChatPeekHidden } from "../../redux/slices/indexingSlice";
@ -32,12 +32,7 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) {
if (hiddenPeeks[state.type]) return null;
return (
<div
className="flex flex-row items-center border-0 border-t border-solid border-t-zinc-700 px-3 py-0.5"
onClick={() => {
navigate("/more");
}}
>
<div className="flex flex-row items-center border-0 border-t border-solid border-t-zinc-700 px-3 py-0.5">
<div className="group flex flex-1 cursor-pointer flex-row items-center gap-2">
<div className={`flex flex-row items-center gap-2`}>
<p className="m-0 p-0 text-xs text-stone-500 group-hover:underline">

View file

@ -1,218 +0,0 @@
import { IndexingStatus, SiteIndexingConfig } from "core";
import { useContext, useMemo, useState } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import {
ArrowPathIcon,
ArrowTopRightOnSquareIcon,
CheckCircleIcon,
ExclamationTriangleIcon,
EyeIcon,
PauseCircleIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { updateIndexingStatus } from "../../redux/slices/indexingSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import ConfirmationDialog from "../dialogs/ConfirmationDialog";
import DocsDetailsDialog from "./DocsDetailsDialog";
interface IndexingStatusViewerProps {
docConfig: SiteIndexingConfig;
}
const STATUS_TO_ICON: Record<IndexingStatus["status"], any> = {
indexing: ArrowPathIcon,
paused: PauseCircleIcon,
complete: CheckCircleIcon,
aborted: null,
pending: null,
failed: ExclamationTriangleIcon, // Since we show an error message below
};
function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {
const config = useAppSelector((store) => store.config.config);
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useAppDispatch();
const status = useAppSelector(
(store) => store.indexing.indexing.statuses[docConfig.startUrl],
);
const reIndex = () =>
ideMessenger.post("indexing/reindex", {
type: "docs",
id: docConfig.startUrl,
});
const abort = () => {
ideMessenger.post("indexing/abort", {
type: "docs",
id: docConfig.startUrl,
});
// Optimistic abort status
if (status) {
dispatch(
updateIndexingStatus({ ...status, status: "aborted", progress: 0 }),
);
}
};
const [hasDeleted, setHasDeleted] = useState(false); // simple alternative to optimistic redux update
const onDelete = () => {
// optimistic update
dispatch(
setDialogMessage(
<ConfirmationDialog
title={`Delete ${docConfig.title}`}
text={`Are you sure you want to remove ${docConfig.title} from your configuration?`}
onConfirm={() => {
ideMessenger.post("context/removeDocs", {
startUrl: docConfig.startUrl,
});
setHasDeleted(true);
}}
/>,
),
);
dispatch(setShowDialog(true));
};
const progressPercentage = useMemo(() => {
if (!status) {
return 0;
}
return Math.min(100, Math.max(0, status.progress * 100)).toFixed(0);
}, [status?.progress]);
const Icon = STATUS_TO_ICON[status?.status];
const showProgressPercentage = progressPercentage !== "100";
if (hasDeleted) return null;
return (
<div className="mt-2 flex w-full flex-col">
<div
className={`flex flex-row items-center justify-between gap-2 text-sm`}
>
<div
className={`flex flex-row items-center gap-2 ${status?.url ? "cursor-pointer hover:underline" : ""}`}
onClick={() => {
if (status?.url) {
ideMessenger.post("openUrl", status.url);
}
}}
>
{docConfig.faviconUrl ? (
<img
src={docConfig.faviconUrl}
alt="doc icon"
className="h-4 w-4"
/>
) : null}
<p className="lines lines-1 m-0 p-0 text-left">
{docConfig.title ?? docConfig.startUrl}
</p>
<ArrowTopRightOnSquareIcon className="mb-0.5 h-3 w-3 text-stone-500" />
</div>
{status?.status === "pending" ? (
<div className="text-xs text-stone-500">Pending...</div>
) : (
<div className="flex flex-row items-center gap-1 text-stone-500">
{showProgressPercentage && (
<span className="text-xs">{progressPercentage}%</span>
)}
{status?.status !== "indexing" ? (
<TrashIcon
className="h-4 w-4 cursor-pointer text-stone-500 hover:brightness-125"
onClick={onDelete}
/>
) : null}
{Icon ? (
<Icon
className={`inline-block h-4 w-4 text-stone-500 ${
status?.status === "indexing" ? "animate-spin-slow" : ""
}`}
></Icon>
) : null}
</div>
)}
</div>
<div className="my-2 h-1.5 w-full rounded-md border border-solid border-gray-400">
<div
className={`h-full rounded-lg transition-all duration-200 ease-in-out ${
status?.status === "failed" ? "bg-red-600" : "bg-stone-500"
}`}
style={{
width: `${progressPercentage}%`,
}}
/>
</div>
<div className="flex flex-row items-center justify-between gap-4">
<span
className={`cursor-pointer whitespace-nowrap text-xs text-stone-500 ${config.disableIndexing ? "" : "underline"}`}
onClick={
config.disableIndexing
? undefined
: {
complete: reIndex,
indexing: abort,
failed: reIndex,
aborted: reIndex,
paused: () => {},
pending: () => {},
}[status?.status]
}
>
{config.disableIndexing
? "Indexing disabled"
: {
complete: "Click to re-index",
indexing: "Cancel indexing",
failed: "Click to retry",
aborted: "Click to index",
paused: "",
pending: "",
}[status?.status]}
</span>
<div className="flex flex-row items-center gap-1">
{status?.description === "Github rate limit exceeded" ? (
<span
className="lines lines-1 cursor-pointer text-right text-xs text-stone-500 underline"
onClick={() =>
ideMessenger.post(
"openUrl",
"https://docs.continue.dev/customize/deep-dives/docs#github",
)
}
>
{status.description}
</span>
) : (
<span className="lines lines-1 text-right text-xs text-stone-500">
{status?.description}
</span>
)}
{status?.status === "complete" ? (
<EyeIcon
className="h-4 w-4 cursor-pointer text-stone-500"
onClick={() => {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<DocsDetailsDialog startUrl={docConfig.startUrl} />,
),
);
}}
>
Add Docs
</EyeIcon>
) : null}
</div>
</div>
</div>
);
}
export default DocsIndexingStatus;

View file

@ -1,115 +0,0 @@
import { useDispatch } from "react-redux";
import { SecondaryButton } from "..";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import AddDocsDialog from "../dialogs/AddDocsDialog";
import DocsIndexingStatus from "./DocsIndexingStatus";
import { useAppSelector } from "../../redux/hooks";
import { useContext, useMemo } from "react";
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { IndexingStatus } from "core";
function DocsIndexingStatuses() {
const dispatch = useDispatch();
const config = useAppSelector((store) => store.config.config);
const ideMessenger = useContext(IdeMessengerContext);
const indexingStatuses = useAppSelector(
(store) => store.indexing.indexing.statuses,
);
const hasDocsProvider = useMemo(() => {
return !!config.contextProviders?.some(
(provider) => provider.title === "docs",
);
}, [config]);
// TODO - this might significantly impact performance during indexing
const sortedConfigDocs = useMemo(() => {
const sorter = (status: IndexingStatus["status"]) => {
// TODO - further sorting?
if (status === "indexing" || status === "paused") return 0;
if (status === "failed") return 1;
if (status === "aborted" || status === "pending") return 2;
return 3;
};
const docs = [...(config.docs ?? [])];
docs.sort((a, b) =>
sorter(indexingStatuses[b.startUrl]?.status ?? "pending") >
sorter(indexingStatuses[a.startUrl]?.status ?? "pending")
? -1
: 1,
);
return docs;
}, [config, indexingStatuses]);
return (
<div className="flex flex-col gap-1">
<div className="flex flex-row items-center justify-between">
<h3 className="mb-0 mt-0 text-xl">@docs indexes</h3>
{sortedConfigDocs.length ? (
<SecondaryButton
className="!my-0 flex h-7 flex-col items-center justify-center"
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));
}}
>
Add
</SecondaryButton>
) : null}
</div>
<span className="text-xs text-stone-500">
{hasDocsProvider ? (
sortedConfigDocs.length ? (
"Manage your documentation sources"
) : (
"No docs yet"
)
) : (
<div className="flex flex-col gap-1 text-xs">
<div className="flex flex-row gap-1">
<div>
<ExclamationTriangleIcon className="h-4 w-4 text-stone-500" />
</div>
<span className="text-stone-500">
@docs is not in your config
</span>
</div>
<span
className="cursor-pointer text-stone-500 underline"
onClick={() => {
ideMessenger.post("config/addContextProvider", {
name: "docs",
params: {},
});
}}
>
Add @docs to my config
</span>
</div>
)}
</span>
<div className="flex max-h-[170px] flex-col gap-1 overflow-y-auto overflow-x-hidden pr-2">
<div>
{sortedConfigDocs.length === 0 && (
<SecondaryButton
className="flex h-7 flex-col items-center justify-center"
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));
}}
>
Add Docs
</SecondaryButton>
)}
</div>
{sortedConfigDocs.map((doc) => {
return <DocsIndexingStatus key={doc.startUrl} docConfig={doc} />;
})}
</div>
</div>
);
}
export default DocsIndexingStatuses;

View file

@ -1,25 +1,8 @@
import {
ArrowRightIcon,
ArrowUpOnSquareIcon,
AtSymbolIcon,
Bars3BottomLeftIcon,
BoltIcon,
BookOpenIcon,
BugAntIcon,
CircleStackIcon,
CodeBracketIcon,
CommandLineIcon,
CpuChipIcon,
DocumentTextIcon,
ExclamationTriangleIcon,
FolderIcon,
FolderOpenIcon,
GlobeAltIcon,
MagnifyingGlassIcon,
PaperClipIcon,
ChatBubbleLeftIcon,
PlusIcon,
SparklesIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { Editor } from "@tiptap/react";
import {
@ -39,57 +22,23 @@ import {
vscListActiveBackground,
vscListActiveForeground,
vscQuickInputBackground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import AddDocsDialog from "../dialogs/AddDocsDialog";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { DiscordIcon } from "../svg/DiscordIcon";
import { GithubIcon } from "../svg/GithubIcon";
import { GitlabIcon } from "../svg/GitlabIcon";
import { GoogleIcon } from "../svg/GoogleIcon";
import { ComboBoxItem, ComboBoxItemType } from "./types";
const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
file: FolderIcon,
code: CodeBracketIcon,
terminal: CommandLineIcon,
diff: PlusIcon,
search: MagnifyingGlassIcon,
url: GlobeAltIcon,
open: FolderOpenIcon,
codebase: SparklesIcon,
problems: ExclamationTriangleIcon,
folder: FolderIcon,
docs: BookOpenIcon,
web: GlobeAltIcon,
clipboard: PaperClipIcon,
database: CircleStackIcon,
postgres: CircleStackIcon,
debugger: BugAntIcon,
os: CpuChipIcon,
tree: Bars3BottomLeftIcon,
"prompt-files": DocumentTextIcon,
"repo-map": FolderIcon,
"/clear": TrashIcon,
"/share": ArrowUpOnSquareIcon,
"/cmd": CommandLineIcon,
issue: GithubIcon,
discord: DiscordIcon,
google: GoogleIcon,
"gitlab-mr": GitlabIcon,
http: GlobeAltIcon,
trash: TrashIcon,
};
} from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import FileIcon from "../../FileIcon";
import SafeImg from "../../SafeImg";
import AddDocsDialog from "../../dialogs/AddDocsDialog";
import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip";
import { NAMED_ICONS } from "../icons";
import { ComboBoxItem, ComboBoxItemType } from "../types";
export function getIconFromDropdownItem(
id: string | undefined,
type: ComboBoxItemType,
) {
const typeIcon = type === "contextProvider" ? AtSymbolIcon : BoltIcon;
return id ? (ICONS_FOR_DROPDOWN[id] ?? typeIcon) : typeIcon;
const typeIcon =
type === "contextProvider" ? AtSymbolIcon : ChatBubbleLeftIcon;
return id ? (NAMED_ICONS[id] ?? typeIcon) : typeIcon;
}
function DropdownIcon(props: { className?: string; item: ComboBoxItem }) {
@ -180,7 +129,7 @@ const QueryInput = styled.textarea`
resize: none;
`;
interface MentionListProps {
interface AtMentionDropdownProps {
items: ComboBoxItem[];
command: (item: any) => void;
@ -189,7 +138,7 @@ interface MentionListProps {
onClose: () => void;
}
const MentionList = forwardRef((props: MentionListProps, ref) => {
const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
@ -506,10 +455,9 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
) : (
<ItemDiv className="item">No results</ItemDiv>
)}
{/* </CustomScrollbarDiv> */}
</>
)}
</ItemsDiv>
);
});
export default MentionList;
export default AtMentionDropdown;

View file

@ -1,74 +0,0 @@
import { PlayIcon, StopIcon } from "@heroicons/react/24/outline";
import styled from "styled-components";
import { Button } from "..";
import { getFontSize } from "../../util";
const StyledButton = styled(Button)<{
color?: string | null;
isDisabled: boolean;
showStop: boolean;
}>`
margin: auto;
margin-top: 8px;
margin-bottom: 16px;
display: grid;
width: 130px;
grid-template-columns: 22px 1fr;
align-items: center;
background-color: ${(props) =>
`${props.color || "#be1b55"}${props.showStop ? "33" : ""}`};
opacity: ${(props) => (props.isDisabled ? 0.5 : 1.0)};
border: 1px solid
${(props) => (props.showStop ? props.color || "#be1b55" : "transparent")};
cursor: ${(props) => (props.isDisabled ? "default" : "pointer")};
&:hover:enabled {
background-color: ${(props) =>
`${props.color || "#be1b55"}${props.showStop ? "33" : ""}`};
${(props) =>
props.isDisabled
? "cursor: default;"
: `
opacity: 0.7;
`}
}
`;
function ContinueButton(props: {
onClick?: () => void;
hidden?: boolean;
disabled: boolean;
showStop: boolean;
}) {
return (
<StyledButton
showStop={props.showStop}
hidden={props.hidden}
style={{ fontSize: `${getFontSize() - 4}px` }}
className="m-auto"
onClick={props.disabled ? undefined : props.onClick}
isDisabled={props.disabled}
>
{props.showStop ? (
<>
<StopIcon width="18px" height="18px" />
STOP
</>
) : (
<>
{window.vscMediaUrl ? (
<img src={`${window.vscMediaUrl}/play_button.png`} height="18px" />
) : (
<PlayIcon width="18px" height="18px" />
)}
CONTINUE
</>
)}
</StyledButton>
);
}
export default ContinueButton;

View file

@ -1,14 +1,14 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { useDispatch } from "react-redux";
import { useMemo, useState } from "react";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
import ContextItemsPeek from "./ContextItemsPeek";
import TipTapEditor from "./TipTapEditor";
import { useAppSelector } from "../../redux/hooks";
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
import ContextItemsPeek from "./belowMainInput/ContextItemsPeek";
import { ToolbarOptions } from "./InputToolbar";
import { useMemo } from "react";
import { Lump } from "./Lump";
import TipTapEditor from "./tiptap/TipTapEditor";
interface ContinueInputBoxProps {
isEditMode?: boolean;
@ -113,9 +113,12 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}
: {};
const [lumpOpen, setLumpOpen] = useState(true);
return (
<div className={`${props.hidden ? "hidden" : ""}`}>
<div className={`relative flex flex-col px-2`}>
{props.isMainInput && <Lump open={lumpOpen} setOpen={setLumpOpen} />}
<GradientBorder
loading={isStreaming && props.isLastUserInput ? 1 : 0}
borderColor={
@ -132,6 +135,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
availableSlashCommands={filteredSlashCommands}
historyKey={historyKey}
toolbarOptions={toolbarOptions}
lumpOpen={lumpOpen}
setLumpOpen={setLumpOpen}
inputId={props.inputId}
/>
</GradientBorder>

View file

@ -21,6 +21,7 @@ import {
import { exitEditMode } from "../../redux/thunks";
import { loadLastSession } from "../../redux/thunks/session";
import {
fontSize,
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
@ -28,8 +29,8 @@ import {
} from "../../util";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import HoverItem from "./InputToolbar/HoverItem";
import ToggleToolsButton from "./InputToolbar/ToggleToolsButton";
import ModeSelect from "../modelSelection/ModeSelect";
import HoverItem from "./InputToolbar/bottom/HoverItem";
const StyledDiv = styled.div<{ isHidden?: boolean }>`
padding-top: 4px;
@ -75,7 +76,6 @@ export interface ToolbarOptions {
interface InputToolbarProps {
onEnter?: (modifiers: InputModifiers) => void;
onAddContextItem?: () => void;
onAddSlashCommand?: () => void;
onClick?: () => void;
onImageFileSelected?: (file: File) => void;
hidden?: boolean;
@ -83,6 +83,8 @@ interface InputToolbarProps {
toolbarOptions?: ToolbarOptions;
disabled?: boolean;
isMainInput?: boolean;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
}
function InputToolbar(props: InputToolbarProps) {
@ -113,6 +115,7 @@ function InputToolbar(props: InputToolbarProps) {
className="find-widget-skip flex"
>
<div className="flex items-center justify-start gap-2 whitespace-nowrap">
<ModeSelect />
<ModelSelect />
<div className="xs:flex -mb-1 hidden items-center text-gray-400 transition-colors duration-200">
{props.toolbarOptions?.hideImageUpload ||
@ -132,7 +135,7 @@ function InputToolbar(props: InputToolbarProps) {
/>
<HoverItem className="">
<PhotoIcon
className="h-4 w-4 hover:brightness-125"
className="h-3 w-3 hover:brightness-125"
data-tooltip-id="image-tooltip"
onClick={(e) => {
fileInputRef.current?.click();
@ -148,7 +151,7 @@ function InputToolbar(props: InputToolbarProps) {
<HoverItem onClick={props.onAddContextItem}>
<AtSymbolIcon
data-tooltip-id="add-context-item-tooltip"
className="h-4 w-4 hover:brightness-125"
className="h-3 w-3 hover:brightness-125"
/>
<ToolTip id="add-context-item-tooltip" place="top-middle">
@ -156,12 +159,15 @@ function InputToolbar(props: InputToolbarProps) {
</ToolTip>
</HoverItem>
)}
<ToggleToolsButton disabled={!toolsSupported} />
</div>
</div>
<div className="flex items-center gap-2 whitespace-nowrap text-gray-400">
<div
className="flex items-center gap-2 whitespace-nowrap text-gray-400"
style={{
fontSize: fontSize(-3),
}}
>
{!props.toolbarOptions?.hideUseCodebase && !isInEditMode && (
<div
className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}

View file

@ -1,178 +0,0 @@
import { Listbox } from "@headlessui/react";
import {
EllipsisHorizontalCircleIcon as EllipsisHorizontalIcon,
WrenchScrewdriverIcon as WrenchScrewdriverIconOutline,
} from "@heroicons/react/24/outline";
import { WrenchScrewdriverIcon as WrenchScrewdriverIconSolid } from "@heroicons/react/24/solid";
import { useEffect, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { lightGray, vscForeground } from "../..";
import { useAppSelector } from "../../../redux/hooks";
import { toggleUseTools } from "../../../redux/slices/uiSlice";
import { ToolTip } from "../../gui/Tooltip";
import InfoHover from "../../InfoHover";
import HoverItem from "./HoverItem";
import PopoverTransition from "./PopoverTransition";
import ToolDropdownItem from "./ToolDropdownItem";
import { selectIsInEditMode } from "../../../redux/slices/sessionSlice";
interface ToolDropdownProps {
disabled: boolean;
}
export default function ToolDropdown(props: ToolDropdownProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const dispatch = useDispatch();
const [isDropdownOpen, setDropdownOpen] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const useTools = useAppSelector((state) => state.ui.useTools);
const availableTools = useAppSelector((state) => state.config.config.tools);
const [showAbove, setShowAbove] = useState(false);
const isInEditMode = useAppSelector(selectIsInEditMode);
const ToolsIcon = useTools
? WrenchScrewdriverIconSolid
: WrenchScrewdriverIconOutline;
useEffect(() => {
const checkPosition = () => {
if (buttonRef.current) {
const rect = buttonRef.current.getBoundingClientRect();
const windowHeight = window.innerHeight;
const spaceBelow = windowHeight - rect.bottom;
setShowAbove(spaceBelow < 250);
}
};
if (isDropdownOpen) {
checkPosition();
}
}, [isDropdownOpen]);
const isDisabled = props.disabled || isInEditMode;
return (
<HoverItem onClick={() => !isDisabled && dispatch(toggleUseTools())}>
<div
data-tooltip-id="tools-tooltip"
className={`-ml-1 -mt-1 flex flex-row items-center gap-1.5 rounded-md px-1 py-0.5 text-xs ${
(useTools || isHovered) && !isDisabled ? "bg-lightgray/30" : ""
} ${isDisabled ? "cursor-not-allowed opacity-50" : ""}`}
>
<ToolsIcon
className={`h-4 w-4 text-gray-400 ${
isDisabled ? "cursor-not-allowed" : ""
}`}
onMouseEnter={() => !isDisabled && setIsHovered(true)}
onMouseLeave={() => !isDisabled && setIsHovered(false)}
/>
{isDisabled && (
<ToolTip id="tools-tooltip" place="top-middle">
{isInEditMode
? "Tool use not supported in edit mode"
: "This model does not support tool use"}
</ToolTip>
)}
{!useTools && !isDisabled && (
<ToolTip id="tools-tooltip" place="top-middle">
Enable tool usage
</ToolTip>
)}
{useTools && !isDisabled && (
<>
<span className="hidden align-top sm:flex">Tools</span>
<div className="relative">
<Listbox
value={null}
onChange={() => {}}
as="div"
onClick={(e) => e.stopPropagation()}
disabled={isDisabled}
>
{({ open }) => (
<>
<Listbox.Button
ref={buttonRef}
onClick={(e) => {
e.stopPropagation();
setDropdownOpen(!isDropdownOpen);
}}
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent px-0 outline-none"
aria-disabled={isDisabled}
>
<EllipsisHorizontalIcon className="h-3 w-3 cursor-pointer hover:brightness-125" />
</Listbox.Button>
<PopoverTransition
show={open}
afterLeave={() => setDropdownOpen(false)}
>
<Listbox.Options
className={`bg-vsc-editor-background border-lightgray/50 absolute -left-32 z-50 mb-1 min-w-fit whitespace-nowrap rounded-md border border-solid px-1 py-0 shadow-lg ${showAbove ? "bottom-full" : ""}`}
static
>
<div className="sticky">
<div
className="mb-1 flex items-center gap-2 px-2 py-1 text-xs"
style={{
color: vscForeground,
borderBottom: `1px solid ${lightGray}`,
}}
>
Tool policies{" "}
<InfoHover
id={"tool-policies"}
size={"3"}
msg={
<div
className="gap-0 *:m-1 *:text-left"
style={{ fontSize: "10px" }}
>
<p>
<span className="text-green-500">
Automatic:
</span>{" "}
Can be used without asking
</p>
<p>
<span className="text-yellow-500">
Allowed:
</span>{" "}
Will ask before using
</p>
<p>
<span className="text-red-500">
Disabled:
</span>{" "}
Cannot be used
</p>
</div>
}
/>
</div>
</div>
<div className="max-h-48 overflow-y-auto overflow-x-hidden pr-2">
{availableTools.map((tool: any) => (
<Listbox.Option
key={tool.function.name}
value="addAllFiles"
className="text-vsc-foreground block w-full cursor-pointer text-left text-xs brightness-75 hover:brightness-125"
>
<ToolDropdownItem tool={tool} />
</Listbox.Option>
))}
</div>
</Listbox.Options>
</PopoverTransition>
</>
)}
</Listbox>
</div>
</>
)}
</div>
</HoverItem>
);
}

View file

@ -1,66 +0,0 @@
import { Tool } from "core";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addTool, toggleToolSetting } from "../../../redux/slices/uiSlice";
import { RootState } from "../../../redux/store";
interface ToolDropdownItemProps {
tool: Tool;
}
function ToolDropdownItem(props: ToolDropdownItemProps) {
const dispatch = useDispatch();
const settings = useSelector(
(state: RootState) => state.ui.toolSettings[props.tool.function.name],
);
useEffect(() => {
if (!settings) {
dispatch(addTool(props.tool));
}
}, [props.tool.function.name, settings]);
if (!settings) {
return null;
}
return (
<div
className="flex w-full items-center justify-between gap-2 px-2 py-1"
onClick={(e) => {
dispatch(toggleToolSetting(props.tool.function.name));
e.stopPropagation();
e.preventDefault();
}}
>
<span className="flex items-center gap-1">
{props.tool.faviconUrl && (
<img
src={props.tool.faviconUrl}
alt={props.tool.displayTitle}
className="h-4 w-4"
/>
)}
{props.tool.displayTitle}{" "}
{/* <InfoHover
id={`tool-policy-row-${props.tool.function.name}`}
size={"3"}
msg={props.tool.function.description}
/> */}
</span>
<div className="flex cursor-pointer gap-2 pr-4">
{(settings === "allowedWithPermission" || settings === undefined) && (
<span className="text-yellow-500">Allowed</span>
)}
{settings === "allowedWithoutPermission" && (
<span className="text-green-500">Automatic</span>
)}
{settings === "disabled" && (
<span className="text-red-500">Disabled</span>
)}
</div>
</div>
);
}
export default ToolDropdownItem;

View file

@ -1,7 +1,7 @@
import styled from "styled-components";
const HoverItem = styled.span<{ isActive?: boolean }>`
padding: 0 4px;
const HoverItem = styled.span<{ isActive?: boolean; px?: number }>`
padding: 0 ${(props) => props.px ?? 4}px;
padding-top: 2px;
padding-bottom: 2px;
cursor: pointer;

View file

@ -0,0 +1,99 @@
import { InformationCircleIcon } from "@heroicons/react/24/outline";
import { Tool } from "core";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../../../redux/hooks";
import { addTool, toggleToolSetting } from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import { ToolTip } from "../../../gui/Tooltip";
interface ToolDropdownItemProps {
tool: Tool;
duplicatesDetected: boolean;
excluded: boolean;
}
function ToolDropdownItem(props: ToolDropdownItemProps) {
const dispatch = useDispatch();
const settings = useAppSelector(
(state) => state.ui.toolSettings[props.tool.function.name],
);
useEffect(() => {
if (!settings) {
dispatch(addTool(props.tool));
}
}, [props.tool.function.name, settings]);
if (!settings) {
return null;
}
return (
<div
className="flex items-center justify-between gap-2 px-2 py-0.5"
style={{
fontSize: fontSize(-3),
}}
onClick={(e) => {
dispatch(toggleToolSetting(props.tool.function.name));
e.stopPropagation();
e.preventDefault();
}}
>
<div className="flex flex-1 flex-row items-center gap-1">
{props.duplicatesDetected ? (
<>
<div>
<InformationCircleIcon
data-tooltip-id={props.tool.displayTitle + "-duplicate-warning"}
className="h-3 w-3 cursor-help text-yellow-500"
/>
</div>
<ToolTip
id={props.tool.displayTitle + "-duplicate-warning"}
place="bottom"
className="flex flex-wrap items-center"
>
<p className="m-0 p-0">
<span>Duplicate tool name</span>{" "}
<code>{props.tool.function.name}</code>{" "}
<span>
detected. Permissions will conflict and usage may be
unpredictable
</span>
</p>
</ToolTip>
</>
) : null}
<span className="lines lines-1 flex items-center gap-1">
{props.tool.faviconUrl && (
<img
src={props.tool.faviconUrl}
alt={props.tool.displayTitle}
className="h-4 w-4"
/>
)}
{props.tool.function.name}{" "}
</span>
</div>
{props.excluded ? (
<span className="text-lightgray">Excluded</span>
) : (
<div className="flex cursor-pointer gap-2">
{(settings === "allowedWithPermission" || settings === undefined) && (
<span className="text-yellow-500">Ask First</span>
)}
{settings === "allowedWithoutPermission" && (
<span className="text-green-500">Automatic</span>
)}
{settings === "disabled" && (
<span className="text-lightgray">Excluded</span>
)}
</div>
)}
</div>
);
}
export default ToolDropdownItem;

View file

@ -0,0 +1,79 @@
import { Tool } from "core";
import { useMemo } from "react";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import ToggleSwitch from "../../../gui/Switch";
import ToolDropdownItem from "./ToolDropdownItem";
export const ToolPermissionsDialog = () => {
const availableTools = useAppSelector((state) => state.config.config.tools);
const toolGroupSettings = useAppSelector(
(store) => store.ui.toolGroupSettings,
);
const dispatch = useAppDispatch();
const toolsByGroup = useMemo(() => {
const byGroup: Record<string, Tool[]> = {};
for (const tool of availableTools) {
if (!byGroup[tool.group]) {
byGroup[tool.group] = [];
}
byGroup[tool.group].push(tool);
}
return Object.entries(byGroup);
}, [availableTools]);
// Detect duplicate tool names
const duplicateDetection = useMemo(() => {
const counts: Record<string, number> = {};
availableTools.forEach((tool) => {
if (counts[tool.function.name]) {
counts[tool.function.name] = counts[tool.function.name] + 1;
} else {
counts[tool.function.name] = 1;
}
});
return Object.fromEntries(
Object.entries(counts).map(([k, v]) => [k, v > 1]),
);
}, [availableTools]);
return (
<>
{toolsByGroup.map(([groupName, tools]) => (
<div key={groupName} className="mt-2 flex flex-col pr-1">
<div className="flex flex-row items-center justify-between px-1 pr-3">
<h3
className="m-0 p-0 font-bold"
style={{
fontSize: fontSize(-2),
}}
>
{groupName}
</h3>
<ToggleSwitch
isToggled={toolGroupSettings[groupName] !== "exclude"}
onToggle={() => dispatch(toggleToolGroupSetting(groupName))}
text=""
size={10}
/>
</div>
<div className="relative flex flex-col p-1">
{tools.map((tool) => (
<ToolDropdownItem
key={tool.uri + tool.function.name}
tool={tool}
duplicatesDetected={duplicateDetection[tool.function.name]}
excluded={toolGroupSettings[groupName] === "exclude"}
/>
))}
{toolGroupSettings[groupName] === "exclude" && (
<div className="absolute right-0 top-0 h-full w-full cursor-not-allowed"></div>
)}
</div>
</div>
))}
</>
);
};

View file

@ -0,0 +1,22 @@
import { EllipsisHorizontalIcon } from "@heroicons/react/24/outline";
import { ToolbarOptions } from "../../InputToolbar";
import HoverItem from "../bottom/HoverItem";
interface TopInputToolbarProps {
toolbarOptions?: ToolbarOptions;
onAddContextItem?: () => void;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
}
export function TopInputToolbar(props: TopInputToolbarProps) {
return (
<div className="-mb-2 -mt-1 flex items-center">
<HoverItem
onClick={() => props.setLumpOpen(!props.lumpOpen)}
className="ml-auto"
>
<EllipsisHorizontalIcon className="h-3 w-3 text-gray-400 hover:brightness-125" />
</HoverItem>
</div>
);
}

View file

@ -0,0 +1,135 @@
import {
BookOpenIcon,
ChatBubbleLeftIcon,
ChevronLeftIcon,
CubeIcon,
EllipsisHorizontalIcon,
PencilIcon,
Squares2X2Icon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { vscBadgeBackground, vscBadgeForeground } from "../..";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
import HoverItem from "../InputToolbar/bottom/HoverItem";
interface BlockSettingsToolbarIcon {
tooltip: string;
icon: React.ComponentType<any>;
itemCount?: number;
onClick: () => void;
isSelected?: boolean;
}
interface Section {
id: string;
tooltip: string;
icon: React.ComponentType<any>;
}
const sections: Section[] = [
{ id: "models", tooltip: "Models", icon: CubeIcon },
{ id: "rules", tooltip: "Rules", icon: PencilIcon },
{ id: "docs", tooltip: "Docs", icon: BookOpenIcon },
{ id: "prompts", tooltip: "Prompts", icon: ChatBubbleLeftIcon },
{ id: "tools", tooltip: "Tools", icon: WrenchScrewdriverIcon },
{ id: "mcp", tooltip: "MCP", icon: Squares2X2Icon },
];
function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) {
return (
<HoverItem px={0} onClick={props.onClick}>
<div
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
props.onClick();
}
}}
style={{
backgroundColor: props.isSelected ? vscBadgeBackground : undefined,
}}
className={`relative flex select-none items-center rounded-full px-1 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50`}
>
<props.icon
className="h-3 w-3 hover:brightness-125"
style={{
color: props.isSelected ? vscBadgeForeground : undefined,
}}
aria-hidden="true"
/>
<div
style={{ fontSize: fontSize(-3) }}
className={`overflow-hidden transition-all duration-200 ${
props.isSelected ? "ml-1 w-auto opacity-100" : "w-0 opacity-0"
}`}
>
<span
className="whitespace-nowrap"
style={{ color: vscBadgeForeground }}
>
{props.tooltip}
</span>
</div>
</div>
</HoverItem>
);
}
interface BlockSettingsTopToolbarProps {
selectedSection: string | null;
setSelectedSection: (value: string | null) => void;
}
export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
const isExpanded = useAppSelector(
(state) => state.ui.isBlockSettingsToolbarExpanded,
);
const dispatch = useAppDispatch();
const handleEllipsisClick = () => {
if (isExpanded) {
props.setSelectedSection(null);
}
dispatch(toggleBlockSettingsToolbar());
};
return (
<div className="flex w-full items-center justify-between">
<div className="xs:flex hidden items-center justify-center text-gray-400">
<BlockSettingsToolbarIcon
icon={isExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
tooltip={isExpanded ? "Collapse sections" : "Expand sections"}
isSelected={false}
onClick={handleEllipsisClick}
/>
<div
className="flex overflow-hidden transition-all duration-200"
style={{ width: isExpanded ? `160px` : "0px" }}
>
<div className="flex">
{sections.map((section) => (
<BlockSettingsToolbarIcon
key={section.id}
icon={section.icon}
tooltip={section.tooltip}
isSelected={props.selectedSection === section.id}
onClick={() =>
props.setSelectedSection(
props.selectedSection === section.id ? null : section.id,
)
}
/>
))}
</div>
</div>
</div>
<div className="ml-auto">
<AssistantSelect />
</div>
</div>
);
}

View file

@ -0,0 +1,73 @@
import { useContext } from "react";
import styled from "styled-components";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
clearLastEmptyResponse,
setInactive,
} from "../../../redux/slices/sessionSlice";
import { getFontSize, getMetaKeyLabel } from "../../../util";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
const Container = styled.div`
display: flex;
justify-content: flex-end;
width: 100%;
`;
const StopButton = styled.div`
font-size: ${getFontSize() - 3}px;
padding: 2px;
padding-right: 4px;
cursor: pointer;
`;
interface TopToolbarProps {
selectedSection: string | null;
setSelectedSection: (value: string | null) => void;
}
export function LumpToolbar(props: TopToolbarProps) {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
if (ttsActive) {
return (
<Container>
<StopButton
className="text-gray-400"
onClick={() => {
ideMessenger.post("tts/kill", undefined);
}}
>
■ Stop TTS
</StopButton>
</Container>
);
}
if (isStreaming) {
return (
<Container>
<StopButton
className="text-gray-400"
onClick={() => {
dispatch(setInactive());
dispatch(clearLastEmptyResponse());
}}
>
{getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
}
return (
<BlockSettingsTopToolbar
selectedSection={props.selectedSection}
setSelectedSection={props.setSelectedSection}
/>
);
}

View file

@ -0,0 +1,75 @@
import { useEffect, useState } from "react";
import styled from "styled-components";
import {
defaultBorderRadius,
vscCommandCenterInactiveBorder,
vscInputBackground,
} from "../..";
import { LumpToolbar } from "./LumpToolbar";
import { SelectedSection } from "./sections/SelectedSection";
interface LumpProps {
open: boolean;
setOpen: (open: boolean) => void;
}
const LumpDiv = styled.div<{ open: boolean }>`
background-color: ${vscInputBackground};
margin-left: 4px;
margin-right: 4px;
border-radius: ${defaultBorderRadius} ${defaultBorderRadius} 0 0;
border-top: 1px solid ${vscCommandCenterInactiveBorder};
border-left: 1px solid ${vscCommandCenterInactiveBorder};
border-right: 1px solid ${vscCommandCenterInactiveBorder};
`;
const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>`
transition:
max-height 0.3s ease-in-out,
margin 0.3s ease-in-out,
opacity 0.2s ease-in-out;
max-height: ${(props) => (props.hasSection ? "200px" : "0px")};
margin: ${(props) => (props.hasSection ? "4px 0" : "0")};
opacity: ${(props) => (props.isVisible ? "1" : "0")};
overflow-y: auto;
`;
export function Lump(props: LumpProps) {
const { open, setOpen } = props;
const [selectedSection, setSelectedSection] = useState<string | null>(null);
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
if (selectedSection) {
setDisplayedSection(selectedSection);
setIsVisible(true);
} else {
setIsVisible(false);
// Delay clearing the displayed section until after the fade-out
const timeout = setTimeout(() => {
setDisplayedSection(null);
}, 300); // Match the transition duration
return () => clearTimeout(timeout);
}
}, [selectedSection]);
if (!open) {
return null;
}
return (
<LumpDiv open={open}>
<div className="mt-0.5 px-2">
<LumpToolbar
selectedSection={selectedSection}
setSelectedSection={setSelectedSection}
/>
<ContentDiv hasSection={!!selectedSection} isVisible={isVisible}>
<SelectedSection selectedSection={displayedSection} />
</ContentDiv>
</div>
</LumpDiv>
);
}

View file

@ -0,0 +1,54 @@
import { PlusIcon } from "@heroicons/react/24/outline";
import { useContext } from "react";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch } from "../../../../redux/hooks";
import {
setDialogMessage,
setShowDialog,
} from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import AddDocsDialog from "../../../dialogs/AddDocsDialog";
export function AddBlockButton(props: { blockType: string }) {
const { selectedProfile } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useAppDispatch();
const handleClick = () => {
if (selectedProfile?.profileType === "local") {
switch (props.blockType) {
case "docs":
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));
break;
default:
ideMessenger.request("config/openProfile", {
profileId: selectedProfile.id,
});
}
} else {
ideMessenger.request("controlPlane/openUrl", {
path: `new?type=block&blockType=${props.blockType}`,
orgSlug: undefined,
});
}
};
return (
<div
className="cursor-pointer rounded px-2 pb-1 text-center text-gray-400 hover:text-gray-300"
style={{
fontSize: fontSize(-3),
}}
onClick={(e) => {
e.preventDefault();
handleClick();
}}
>
<div className="flex items-center justify-center gap-1">
<PlusIcon className="h-3 w-3" /> Add
</div>
</div>
);
}

View file

@ -0,0 +1,3 @@
export function ContextSection() {
return <div>Context content</div>;
}

View file

@ -0,0 +1,5 @@
import MCPServersPreview from "../../../../pages/config/MCPServersPreview";
export function MCPSection() {
return <MCPServersPreview />;
}

View file

@ -0,0 +1,110 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ModelDescription } from "core";
import { useContext } from "react";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import ModelRoleSelector from "../../../../pages/config/ModelRoleSelector";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import {
selectDefaultModel,
setDefaultModel,
updateConfig,
} from "../../../../redux/slices/configSlice";
import { isJetBrains } from "../../../../util";
export function ModelsSection() {
const { selectedProfile } = useAuth();
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const config = useAppSelector((state) => state.config.config);
const jetbrains = isJetBrains();
const selectedChatModel = useAppSelector(selectDefaultModel);
function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) {
if (!selectedProfile) {
return;
}
// Optimistic update
dispatch(
updateConfig({
...config,
selectedModelByRole: {
...config.selectedModelByRole,
[role]: model,
},
}),
);
ideMessenger.post("config/updateSelectedModel", {
profileId: selectedProfile.id,
role,
title: model?.title ?? null,
});
}
// TODO use handleRoleUpdate for chat
function handleChatModelSelection(model: ModelDescription | null) {
if (!model) {
return;
}
dispatch(setDefaultModel({ title: model.title }));
}
return (
<div className="text-[${getFontSize() - 1}px] grid grid-cols-1 gap-x-2 gap-y-1 sm:grid-cols-[auto_1fr]">
<ModelRoleSelector
displayName="Chat"
description="Used in the chat interface"
models={config.modelsByRole.chat}
selectedModel={
selectedChatModel
? {
title: selectedChatModel.title,
provider: selectedChatModel.provider,
model: selectedChatModel.model,
}
: null
}
onSelect={(model) => handleChatModelSelection(model)}
/>
<ModelRoleSelector
displayName="Autocomplete"
description="Used to generate code completion suggestions"
models={config.modelsByRole.autocomplete}
selectedModel={config.selectedModelByRole.autocomplete}
onSelect={(model) => handleRoleUpdate("autocomplete", model)}
/>
{/* Jetbrains has a model selector inline */}
{!jetbrains && (
<ModelRoleSelector
displayName="Edit"
description="Used for inline edits"
models={config.modelsByRole.edit}
selectedModel={config.selectedModelByRole.edit}
onSelect={(model) => handleRoleUpdate("edit", model)}
/>
)}
<ModelRoleSelector
displayName="Apply"
description="Used to apply generated codeblocks to files"
models={config.modelsByRole.apply}
selectedModel={config.selectedModelByRole.apply}
onSelect={(model) => handleRoleUpdate("apply", model)}
/>
<ModelRoleSelector
displayName="Embed"
description="Used to generate and query embeddings for the @codebase and @docs context providers"
models={config.modelsByRole.embed}
selectedModel={config.selectedModelByRole.embed}
onSelect={(model) => handleRoleUpdate("embed", model)}
/>
<ModelRoleSelector
displayName="Rerank"
description="Used for reranking results from the @codebase and @docs context providers"
models={config.modelsByRole.rerank}
selectedModel={config.selectedModelByRole.rerank}
onSelect={(model) => handleRoleUpdate("rerank", model)}
/>
</div>
);
}

View file

@ -0,0 +1,80 @@
import {
BookmarkIcon as BookmarkOutline,
PencilIcon,
} from "@heroicons/react/24/outline";
import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
import { fontSize } from "../../../../util";
import { useBookmarkedSlashCommands } from "../../../ConversationStarters/useBookmarkedSlashCommands";
import { AddBlockButton } from "./AddBlockButton";
interface PromptRowProps {
command: string;
description: string;
isBookmarked: boolean;
setIsBookmarked: (isBookmarked: boolean) => void;
onEdit?: () => void;
}
function PromptRow({
command,
description,
isBookmarked,
setIsBookmarked,
onEdit,
}: PromptRowProps) {
return (
<div
className="flex items-center justify-between"
style={{
fontSize: fontSize(-3),
}}
>
<div className="flex min-w-0 gap-2">
<span className="text-vscForeground shrink-0">{command}</span>
<span className="truncate text-gray-400">{description}</span>
</div>
<div className="flex items-center gap-2">
<PencilIcon
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
onClick={onEdit}
/>
<div
onClick={() => setIsBookmarked(!isBookmarked)}
className="cursor-pointer pt-0.5 text-gray-400"
>
{isBookmarked ? (
<BookmarkSolid className="h-3 w-3" />
) : (
<BookmarkOutline className="h-3 w-3" />
)}
</div>
</div>
</div>
);
}
export function PromptsSection() {
const { cmdsSortedByBookmark, bookmarkStatuses, toggleBookmark } =
useBookmarkedSlashCommands();
const handleEdit = (prompt: any) => {
// Handle edit action here
console.log("Editing prompt:", prompt);
};
return (
<div className="flex flex-col gap-1">
{cmdsSortedByBookmark?.map((prompt, i) => (
<PromptRow
key={prompt.name}
command={prompt.name}
description={prompt.description}
isBookmarked={bookmarkStatuses[prompt.name]}
setIsBookmarked={() => toggleBookmark(prompt)}
onEdit={() => handleEdit(prompt)}
/>
))}
<AddBlockButton blockType="prompts" />
</div>
);
}

View file

@ -1,11 +1,14 @@
import { parseConfigYaml } from "@continuedev/config-yaml";
import { PencilSquareIcon } from "@heroicons/react/24/outline";
import { PencilIcon } from "@heroicons/react/24/outline";
import { useContext, useMemo } from "react";
import { useSelector } from "react-redux";
import HeaderButtonWithToolTip from "../../../components/gui/HeaderButtonWithToolTip";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { RootState } from "../../../redux/store";
import { defaultBorderRadius, vscCommandCenterActiveBorder } from "../../..";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { RootState } from "../../../../redux/store";
import { fontSize } from "../../../../util";
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
import { AddBlockButton } from "./AddBlockButton";
interface RuleCardProps {
index: number;
@ -23,23 +26,42 @@ const RuleCard: React.FC<RuleCardProps> = ({ index, rule, onClick, title }) => {
};
return (
<div className="rounded-lg bg-[#1e1e1e] p-4 transition-colors hover:bg-[#252525]">
<div
style={{
borderRadius: defaultBorderRadius,
border: `1px solid ${vscCommandCenterActiveBorder}`,
}}
className="px-2 py-1 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="mb-2 font-mono text-sm text-[#9cdcfe]">{title}</div>
<div className="whitespace-pre-wrap font-mono text-sm text-gray-300">
<div
className="text-vsc-foreground mb-1"
style={{
fontSize: fontSize(-2),
}}
>
{title}
</div>
<div
style={{
fontSize: fontSize(-3),
whiteSpace: "pre-line",
}}
className="text-gray-400"
>
{truncateRule(rule)}
</div>
</div>
<HeaderButtonWithToolTip onClick={onClick} text="Edit">
<PencilSquareIcon className="h-4 w-4 transition-colors group-hover:text-blue-400" />
<PencilIcon className="h-3 w-3 text-gray-400" />
</HeaderButtonWithToolTip>
</div>
</div>
);
};
export function RulesPreview() {
export function RulesSection() {
const ideMessenger = useContext(IdeMessengerContext);
const { selectedProfile } = useAuth();
@ -65,10 +87,6 @@ export function RulesPreview() {
return (
<div className="space-y-4">
<h2 className="mb-4 text-lg font-semibold text-gray-200">
Assistant Rules
</h2>
{mergedRules.length === 0 ? (
<div className="rounded-lg bg-[#1e1e1e] p-6">
<p className="italic text-gray-400">No rules defined yet</p>
@ -124,6 +142,7 @@ export function RulesPreview() {
})}
</div>
)}
<AddBlockButton blockType="rules" />
</div>
);
}

View file

@ -0,0 +1,32 @@
import { ContextSection } from "./ContextSection";
import DocsSection from "./docs/DocsSection";
import { MCPSection } from "./MCPSection";
import { ModelsSection } from "./ModelsSection";
import { PromptsSection } from "./PromptsSection";
import { RulesSection } from "./RulesSection";
import { ToolsSection } from "./ToolsSection";
interface SelectedSectionProps {
selectedSection: string | null;
}
export function SelectedSection(props: SelectedSectionProps) {
switch (props.selectedSection) {
case "models":
return <ModelsSection />;
case "rules":
return <RulesSection />;
case "docs":
return <DocsSection />;
case "prompts":
return <PromptsSection />;
case "context":
return <ContextSection />;
case "tools":
return <ToolsSection />;
case "mcp":
return <MCPSection />;
default:
return null;
}
}

View file

@ -0,0 +1,7 @@
import { ToolPermissionsDialog } from "../../InputToolbar/bottom/ToolPermissionsDialog";
interface ToolsSectionProps {}
export function ToolsSection({}: ToolsSectionProps) {
return <ToolPermissionsDialog />;
}

View file

@ -1,38 +1,15 @@
import {
CheckIcon,
InformationCircleIcon,
PencilIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import {
DocsIndexingDetails,
IndexingStatus,
PackageDocsResult,
SiteIndexingConfig,
} from "core";
import preIndexedDocs from "core/indexing/docs/preIndexedDocs";
import { DocsIndexingDetails } from "core";
import { usePostHog } from "posthog-js/react";
import {
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { useCallback, useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Input, SecondaryButton } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { updateConfig } from "../../redux/slices/configSlice";
import { updateIndexingStatus } from "../../redux/slices/indexingSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import FileIcon from "../FileIcon";
import { ToolTip } from "../gui/Tooltip";
import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks";
import { Tooltip } from "react-tooltip";
import { SecondaryButton } from "../../../..";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../../redux/hooks";
import {
setDialogMessage,
setShowDialog,
} from "../../../../../redux/slices/uiSlice";
interface DocsDetailsDialogProps {
startUrl: string;
}

View file

@ -1,9 +1,11 @@
import { useDispatch } from "react-redux";
import { IndexingStatus } from "core";
import { useMemo } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { useAppSelector } from "../../redux/hooks";
import {
setDialogMessage,
setShowDialog,
} from "../../../../../redux/slices/uiSlice";
export interface DocsIndexingPeekProps {
status: IndexingStatus;
@ -21,7 +23,7 @@ function DocsIndexingPeek({ status }: DocsIndexingPeekProps) {
<div
className="flex cursor-pointer flex-row items-center gap-2 rounded-md px-1 text-stone-500 hover:bg-gray-700/10"
onClick={() => {
navigate("/more");
// navigate("/more"); TODO
dispatch(setShowDialog(false));
dispatch(setDialogMessage(undefined));
}}
@ -56,17 +58,10 @@ interface DocsIndexingPeeksProps {
function DocsIndexingPeekList({ statuses }: DocsIndexingPeeksProps) {
return (
<div className="border-vsc-input-border mt-2 flex flex-col border-0 border-t border-solid pt-2">
<p className="mx-0 my-1.5 p-0 px-1 font-semibold text-stone-500">
Currently Indexing:
</p>
<div className="max-h-[100px] overflow-y-auto pr-2">
{statuses.length ? (
statuses.map((status) => {
return <DocsIndexingPeek key={status.id} status={status} />;
})
) : (
<p className="m-0 pl-1 font-semibold text-stone-500">None</p>
)}
{statuses.map((status) => {
return <DocsIndexingPeek key={status.id} status={status} />;
})}
</div>
</div>
);

View file

@ -0,0 +1,188 @@
import { ConfigYaml } from "@continuedev/config-yaml";
import {
ArrowPathIcon,
ArrowTopRightOnSquareIcon,
PencilIcon,
StopIcon,
} from "@heroicons/react/24/outline";
import { SiteIndexingConfig } from "core";
import { useContext, useMemo, useState } from "react";
import { useAuth } from "../../../../../context/Auth";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { updateIndexingStatus } from "../../../../../redux/slices/indexingSlice";
import {
setDialogMessage,
setShowDialog,
} from "../../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../../util";
import ConfirmationDialog from "../../../../dialogs/ConfirmationDialog";
import { StatusIndicator } from "./StatusIndicator";
interface IndexingStatusViewerProps {
docConfig: SiteIndexingConfig;
docFromYaml?: NonNullable<ConfigYaml["docs"]>[number];
}
function isUsesBlock(block: any): block is { uses: string } {
return typeof block !== "string" && "uses" in block;
}
function DocsIndexingStatus({
docConfig,
docFromYaml,
}: IndexingStatusViewerProps) {
const ideMessenger = useContext(IdeMessengerContext);
const { selectedProfile } = useAuth();
const dispatch = useAppDispatch();
const status = useAppSelector(
(store) => store.indexing.indexing.statuses[docConfig.startUrl],
);
const reIndex = () =>
ideMessenger.post("indexing/reindex", {
type: "docs",
id: docConfig.startUrl,
});
const abort = () => {
ideMessenger.post("indexing/abort", {
type: "docs",
id: docConfig.startUrl,
});
// Optimistic abort status
if (status) {
dispatch(
updateIndexingStatus({ ...status, status: "aborted", progress: 0 }),
);
}
};
const [hasDeleted, setHasDeleted] = useState(false); // simple alternative to optimistic redux update
const onDelete = () => {
// optimistic update
dispatch(
setDialogMessage(
<ConfirmationDialog
title={`Delete ${docConfig.title}`}
text={`Are you sure you want to remove ${docConfig.title} from your configuration?`}
onConfirm={() => {
ideMessenger.post("context/removeDocs", {
startUrl: docConfig.startUrl,
});
setHasDeleted(true);
}}
/>,
),
);
dispatch(setShowDialog(true));
};
const openUrl = (path: string) =>
ideMessenger.request("controlPlane/openUrl", {
path,
orgSlug: undefined,
});
const handleEdit = () => {
console.log("edit", docFromYaml);
if (selectedProfile?.profileType === "local") {
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
} else if (docFromYaml && isUsesBlock(docFromYaml)) {
openUrl(`${docFromYaml.uses}/new-version`);
} else if (selectedProfile?.fullSlug) {
const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`;
openUrl(`${slug}/new-version`);
}
};
const progressPercentage = useMemo(() => {
if (!status) {
return 0;
}
return Math.min(100, Math.max(0, status.progress * 100)).toFixed(0);
}, [status?.progress]);
if (hasDeleted) return null;
return (
<div className="mt-2 flex w-full flex-col">
<div
className={`flex flex-row items-center justify-between gap-2 text-sm`}
>
<div
className={`flex flex-row items-center gap-1`}
onClick={() => {
if (status?.url) {
ideMessenger.post("openUrl", status.url);
}
}}
>
<StatusIndicator
status={status?.status}
hoverMessage={
status?.status === "failed" ? status?.debugInfo : undefined
}
/>
{docConfig.faviconUrl ? (
<img
src={docConfig.faviconUrl}
alt="doc icon"
className="h-3 w-3"
/>
) : null}
<p
style={{
fontSize: fontSize(-3),
}}
className={`lines lines-1 m-0 p-0 text-left ${status?.url ? "cursor-pointer hover:underline" : ""}`}
>
{docConfig.title ?? docConfig.startUrl}
</p>
<ArrowTopRightOnSquareIcon className="h-2 w-2 text-gray-400" />
</div>
<div className="flex flex-row items-center gap-2">
<div className="flex flex-row items-center gap-1 text-gray-400">
{status?.status === "indexing" && (
<span
className="text-xs"
style={{
fontSize: fontSize(-3),
}}
>
{progressPercentage}%
</span>
)}
{status?.status === "indexing" && (
<StopIcon
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
onClick={abort}
/>
)}
{["aborted", "complete", "failed"].includes(
status?.status ?? "",
) && (
<ArrowPathIcon
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
onClick={reIndex}
/>
)}
<PencilIcon
className="h-3 w-3 cursor-pointer text-gray-400 hover:brightness-125"
onClick={handleEdit}
/>
{/* Removed StatusIndicator from here */}
</div>
</div>
</div>
</div>
);
}
export default DocsIndexingStatus;

View file

@ -0,0 +1,78 @@
import { parseConfigYaml } from "@continuedev/config-yaml";
import { IndexingStatus } from "core";
import { useMemo } from "react";
import { useDispatch } from "react-redux";
import { useAuth } from "../../../../../context/Auth";
import { useAppSelector } from "../../../../../redux/hooks";
import { AddBlockButton } from "../AddBlockButton";
import DocsIndexingStatus from "./DocsIndexingStatus";
function DocsIndexingStatuses() {
const dispatch = useDispatch();
const config = useAppSelector((store) => store.config.config);
const indexingStatuses = useAppSelector(
(store) => store.indexing.indexing.statuses,
);
const { selectedProfile } = useAuth();
const mergedDocs = useMemo(() => {
const parsed = selectedProfile?.rawYaml
? parseConfigYaml(selectedProfile?.rawYaml ?? "")
: undefined;
return (config.docs ?? []).map((doc, index) => ({
doc,
docFromYaml: parsed?.docs?.[index],
}));
}, [config.docs, selectedProfile?.rawYaml]);
const sortedConfigDocs = useMemo(() => {
const sorter = (status: IndexingStatus["status"]) => {
if (status === "complete") return 0;
if (status === "indexing" || status === "paused") return 1;
if (status === "failed") return 2;
if (status === "aborted" || status === "pending") return 3;
return 4;
};
const docs = [...mergedDocs];
docs.sort((a, b) => {
const statusA = indexingStatuses[a.doc.startUrl]?.status ?? "pending";
const statusB = indexingStatuses[b.doc.startUrl]?.status ?? "pending";
// First, compare by status
const statusCompare = sorter(statusA) - sorter(statusB);
if (statusCompare !== 0) return statusCompare;
// If status is the same, sort by presence of icon
const hasIconA = !!a.doc.faviconUrl;
const hasIconB = !!b.doc.faviconUrl;
return hasIconB === hasIconA ? 0 : hasIconB ? 1 : -1;
});
return docs;
}, [mergedDocs, indexingStatuses]);
return (
<div className="flex flex-col gap-1">
<div className="flex flex-col gap-1 overflow-y-auto overflow-x-hidden pr-2">
{sortedConfigDocs.map((docConfig) => {
return (
<div
key={docConfig.doc.startUrl}
className="flex items-center gap-2"
>
<div className="flex-grow">
<DocsIndexingStatus
docFromYaml={docConfig.docFromYaml}
docConfig={docConfig.doc}
/>
</div>
</div>
);
})}
</div>
<AddBlockButton blockType="docs" />
</div>
);
}
export default DocsIndexingStatuses;

View file

@ -0,0 +1,44 @@
import { IndexingStatus } from "core";
import { ToolTip } from "../../../../gui/Tooltip";
interface StatusIndicatorProps {
status?: IndexingStatus["status"];
className?: string;
size?: number;
hoverMessage?: string;
}
const STATUS_TO_COLOR: Record<IndexingStatus["status"], string> = {
indexing: "bg-yellow-500",
paused: "bg-blue-500",
complete: "bg-green-500",
aborted: "bg-gray-500",
pending: "bg-gray-300",
failed: "bg-red-500",
};
export function StatusIndicator({
status,
className = "",
size = 2,
hoverMessage,
}: StatusIndicatorProps) {
if (!status) return null;
const indicator = (
<div
data-tooltip-id={hoverMessage ? "status-tooltip" : undefined}
data-tooltip-content={hoverMessage}
className={`h-${size} w-${size} rounded-full ${STATUS_TO_COLOR[status]} ${
status === "indexing" ? "animate-pulse" : ""
} ${className}`}
/>
);
return (
<>
{indicator}
{hoverMessage && <ToolTip id="status-tooltip" />}
</>
);
}

File diff suppressed because it is too large Load diff

View file

@ -1,100 +0,0 @@
import {
ArrowRightStartOnRectangleIcon,
BookOpenIcon,
ClipboardDocumentIcon,
Cog6ToothIcon,
PencilSquareIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { lightGray } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { isJetBrains } from "../../util";
import Shortcut from "../gui/Shortcut";
interface TutorialCardProps {
onClose: () => void;
}
export function TutorialCard({ onClose }: TutorialCardProps) {
const ideMessenger = useContext(IdeMessengerContext);
const jetbrains = isJetBrains();
return (
<div
className="border-0.5 border-lightGray bg-vsc-background m-1 max-w-96 rounded-md border-solid px-3 py-3 sm:px-5"
data-testid={`tutorial-card`}
>
<div className="flex items-center justify-between">
<h3 className="m-0 p-0"></h3>
<div
onClick={onClose}
className="cursor-pointer items-center justify-center"
>
<XMarkIcon className="h-5 w-5" />
</div>
</div>
<ul className="space-y-4 pl-0" style={{ color: lightGray }}>
{!jetbrains && (
<li className="flex items-start">
<ArrowRightStartOnRectangleIcon className="h-4 w-4 pr-3 align-middle" />
<span>
<span
className="cursor-pointer underline"
onClick={() =>
ideMessenger.post("vscode/openMoveRightMarkdown", undefined)
}
>
Move Chat panel to the right
</span>{" "}
for the cleanest experience
</span>
</li>
)}
<li className="flex items-start">
<div>
<PencilSquareIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
Highlight code and press <Shortcut>meta I</Shortcut> to quickly make
natural language edits
</span>
</li>
<li className="flex items-start">
<div>
<ClipboardDocumentIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
Highlight code and press <Shortcut>meta L</Shortcut> to add it to
the chat window
</span>
</li>
<li className="flex items-start">
<div>
<Cog6ToothIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
Click the gear icon in the upper right to configure Continue
</span>
</li>
<li className="flex items-start">
<div>
<BookOpenIcon className="h-4 w-4 pr-3 align-middle" />
</div>
<span>
<a
className="cursor-pointer text-inherit underline hover:text-inherit"
onClick={() =>
ideMessenger.post("openUrl", "https://docs.continue.dev")
}
>
Read our documentation
</a>{" "}
to learn more
</span>
</li>
</ul>
</div>
);
}

View file

@ -7,13 +7,14 @@ import { ContextItemWithId } from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { getUriPathBasename } from "core/util/uri";
import { useContext, useMemo, useState } from "react";
import { AnimatedEllipsis, lightGray, vscBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { selectIsGatheringContext } from "../../redux/slices/sessionSlice";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import { getIconFromDropdownItem } from "./MentionList";
import { AnimatedEllipsis, lightGray, vscBackground } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import { selectIsGatheringContext } from "../../../redux/slices/sessionSlice";
import FileIcon from "../../FileIcon";
import SafeImg from "../../SafeImg";
import { getIconFromDropdownItem } from "../AtMentionDropdown";
import { NAMED_ICONS } from "../icons";
interface ContextItemsPeekProps {
contextItems?: ContextItemWithId[];
@ -59,13 +60,28 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
const dimensions = "18px";
if (contextItem.icon) {
const NamedIcon = contextItem.icon
? NAMED_ICONS[contextItem.icon]
: undefined;
return (
<SafeImg
className="mr-2 flex-shrink-0 rounded-md p-1"
src={contextItem.icon}
height={dimensions}
width={dimensions}
fallback={null}
fallback={
NamedIcon ? (
<div
className="mr-2 flex-shrink-0"
style={{
height: dimensions,
width: dimensions,
}}
>
<NamedIcon />
</div>
) : null
}
/>
);
}

View file

@ -1,6 +1,6 @@
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscForeground } from "..";
import { getFontSize } from "../../util";
import { defaultBorderRadius, lightGray, vscForeground } from "../..";
import { getFontSize } from "../../../util";
export const NewSessionButton = styled.div`
width: fit-content;

View file

@ -4,9 +4,9 @@ import { ChevronUpIcon } from "@heroicons/react/24/solid";
import { ChatHistoryItem } from "core";
import { useEffect, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscBackground } from "..";
import { getFontSize } from "../../util";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { defaultBorderRadius, lightGray, vscBackground } from "../..";
import { getFontSize } from "../../../util";
import StyledMarkdownPreview from "../../markdown/StyledMarkdownPreview";
const SpoilerButton = styled.div`
background-color: ${vscBackground};

Some files were not shown because too many files have changed in this diff Show more