merge-main
This commit is contained in:
commit
e382cddeed
112 changed files with 2673 additions and 1453 deletions
|
|
@ -44,11 +44,11 @@
|
|||
|
||||

|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
3
binary/package-lock.json
generated
3
binary/package-lock.json
generated
|
|
@ -48,7 +48,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
@ -67,6 +67,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
|
|||
|
|
@ -88,7 +88,6 @@ export class RootPathContextService {
|
|||
default:
|
||||
// const type = node.type;
|
||||
// console.log(getSyntaxTreeString(node));
|
||||
// debugger;
|
||||
|
||||
query = await getQueryForFile(
|
||||
filepath,
|
||||
|
|
@ -165,7 +164,6 @@ export class RootPathContextService {
|
|||
)) {
|
||||
const key = RootPathContextService.keyFromNode(parentKey, astNode);
|
||||
// const type = astNode.type;
|
||||
// debugger;
|
||||
|
||||
const foundInCache = this.cache.get(key);
|
||||
const newSnippets =
|
||||
|
|
|
|||
|
|
@ -127,7 +127,7 @@ async function configYamlToContinueConfig(
|
|||
models: [],
|
||||
tools: [...allTools],
|
||||
mcpServerStatuses: [],
|
||||
systemMessage: config.rules?.join("\n"),
|
||||
systemMessage: undefined,
|
||||
experimental: {
|
||||
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
|
||||
transport: {
|
||||
|
|
@ -211,15 +211,15 @@ async function configYamlToContinueConfig(
|
|||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
|
||||
try {
|
||||
const llms = await llmsFromModelConfig(
|
||||
const llms = await llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
config: continueConfig,
|
||||
});
|
||||
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
|
||||
import { IDE, IdeSettings, LLMOptions } from "../..";
|
||||
import { ContinueConfig, IDE, IdeSettings, LLMOptions } from "../..";
|
||||
import { BaseLLM } from "../../llm";
|
||||
import { LLMClasses } from "../../llm/llms";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
|
|
@ -13,22 +13,29 @@ function getModelClass(
|
|||
return LLMClasses.find((llm) => llm.providerName === model.provider);
|
||||
}
|
||||
|
||||
function getContinueProxyModelName(
|
||||
ownerSlug: string,
|
||||
packageSlug: string,
|
||||
model: ModelConfig,
|
||||
): string {
|
||||
return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
}
|
||||
// function getContinueProxyModelName(
|
||||
// ownerSlug: string,
|
||||
// packageSlug: string,
|
||||
// model: ModelConfig,
|
||||
// ): string {
|
||||
// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`;
|
||||
// }
|
||||
|
||||
async function modelConfigToBaseLLM(
|
||||
model: ModelConfig,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM | undefined> {
|
||||
async function modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
writeLog: (log: string) => Promise<void>;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM | undefined> {
|
||||
const cls = getModelClass(model);
|
||||
|
||||
if (!cls) {
|
||||
|
|
@ -50,7 +57,8 @@ async function modelConfigToBaseLLM(
|
|||
writeLog,
|
||||
uniqueId,
|
||||
title: model.name,
|
||||
systemMessage,
|
||||
systemMessage: config.systemMessage,
|
||||
rules: config.rules,
|
||||
promptTemplates: model.promptTemplates,
|
||||
capabilities: {
|
||||
tools: model.capabilities?.includes("tool_use"),
|
||||
|
|
@ -127,16 +135,25 @@ async function modelConfigToBaseLLM(
|
|||
return llm;
|
||||
}
|
||||
|
||||
async function autodetectModels(
|
||||
llm: BaseLLM,
|
||||
model: ModelConfig,
|
||||
ide: IDE,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
async function autodetectModels({
|
||||
llm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
llm: BaseLLM;
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
writeLog: (log: string) => Promise<void>;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
try {
|
||||
const modelNames = await llm.listModels();
|
||||
const detectedModels = await Promise.all(
|
||||
|
|
@ -146,8 +163,8 @@ async function autodetectModels(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
return await modelConfigToBaseLLM(
|
||||
{
|
||||
return await modelConfigToBaseLLM({
|
||||
model: {
|
||||
...model,
|
||||
model: modelName,
|
||||
name: modelName,
|
||||
|
|
@ -156,8 +173,8 @@ async function autodetectModels(
|
|||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
}),
|
||||
);
|
||||
return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[];
|
||||
|
|
@ -167,38 +184,46 @@ async function autodetectModels(
|
|||
}
|
||||
}
|
||||
|
||||
export async function llmsFromModelConfig(
|
||||
model: ModelConfig,
|
||||
ide: IDE,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
systemMessage: string | undefined,
|
||||
): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM(
|
||||
export async function llmsFromModelConfig({
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
ide: IDE;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
writeLog: (log: string) => Promise<void>;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM({
|
||||
model,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
if (!baseLlm) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (model.model === AUTODETECT) {
|
||||
const models = await autodetectModels(
|
||||
baseLlm,
|
||||
const models = await autodetectModels({
|
||||
llm: baseLlm,
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
systemMessage,
|
||||
);
|
||||
config,
|
||||
});
|
||||
return models;
|
||||
} else {
|
||||
return [baseLlm];
|
||||
|
|
|
|||
9
core/index.d.ts
vendored
9
core/index.d.ts
vendored
|
|
@ -1,6 +1,7 @@
|
|||
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
|
||||
import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -497,6 +498,7 @@ export interface LLMOptions {
|
|||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
rules?: Rule[];
|
||||
apiKey?: string;
|
||||
|
||||
// continueProperties
|
||||
|
|
@ -1143,6 +1145,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
@ -1314,7 +1317,7 @@ export interface ContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules?: Rule[];
|
||||
modelsByRole: Record<ModelRole, ILLM[]>;
|
||||
selectedModelByRole: Record<ModelRole, ILLM | null>;
|
||||
data?: DataDestination[];
|
||||
|
|
@ -1337,7 +1340,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
docs?: SiteIndexingConfig[];
|
||||
tools: Tool[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules?: string[];
|
||||
rules?: Rule[];
|
||||
usePlatform: boolean;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
modelsByRole: Record<ModelRole, ModelDescription[]>;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// @ts-nocheck
|
||||
// Generated by continue
|
||||
import { ChatMessage, MessagePart } from "../index.js";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
UserChatMessage,
|
||||
} from "../index.js";
|
||||
|
||||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
AsyncEncoder,
|
||||
|
|
@ -11,6 +17,8 @@ import {
|
|||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
import { isRuleActive } from "./rules/isRuleActive.js";
|
||||
import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -399,16 +407,127 @@ function chatMessageIsEmpty(message: ChatMessage): boolean {
|
|||
}
|
||||
}
|
||||
|
||||
function compileChatMessages(
|
||||
modelName: string,
|
||||
msgs: ChatMessage[] | undefined,
|
||||
contextLength: number,
|
||||
maxTokens: number,
|
||||
supportsImages: boolean,
|
||||
prompt: string | undefined = undefined,
|
||||
functions: any[] | undefined = undefined,
|
||||
systemMessage: string | undefined = undefined,
|
||||
): ChatMessage[] {
|
||||
function addSystemMessage({
|
||||
messages,
|
||||
systemMessage,
|
||||
originalMessages,
|
||||
}: {
|
||||
messages: ChatMessage[];
|
||||
systemMessage: string | undefined;
|
||||
originalMessages: ChatMessage[] | undefined;
|
||||
}): ChatMessage[] {
|
||||
if (
|
||||
!(systemMessage && systemMessage.trim() !== "") &&
|
||||
originalMessages?.[0]?.role !== "system"
|
||||
) {
|
||||
return messages;
|
||||
}
|
||||
|
||||
let content = "";
|
||||
if (originalMessages?.[0]?.role === "system") {
|
||||
content = renderChatMessage(originalMessages[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
const shouldAddNewLines = content !== "";
|
||||
if (shouldAddNewLines) {
|
||||
content += "\n\n";
|
||||
}
|
||||
content += systemMessage;
|
||||
}
|
||||
|
||||
const systemChatMsg: ChatMessage = {
|
||||
role: "system",
|
||||
content,
|
||||
};
|
||||
// Insert as second to last
|
||||
messages.splice(-1, 0, systemChatMsg);
|
||||
return messages;
|
||||
}
|
||||
|
||||
function getMessageStringContent(message?: UserChatMessage): string {
|
||||
if (!message) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
return message.content;
|
||||
}
|
||||
|
||||
// Handle MessagePart array
|
||||
return message.content
|
||||
.map((part) => {
|
||||
if (part.type === "text") {
|
||||
return part.text;
|
||||
}
|
||||
|
||||
return "";
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
const getSystemMessage = ({
|
||||
userMessage,
|
||||
rules,
|
||||
currentModel,
|
||||
}: {
|
||||
userMessage?: UserChatMessage;
|
||||
rules: Rule[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const messageStringContent = getMessageStringContent(userMessage);
|
||||
const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent);
|
||||
|
||||
return rules
|
||||
.filter((rule) => {
|
||||
return isRuleActive({
|
||||
rule,
|
||||
activePaths: filePathsFromMessage,
|
||||
currentModel,
|
||||
});
|
||||
})
|
||||
.map((rule) => {
|
||||
if (typeof rule === "string") {
|
||||
return rule;
|
||||
}
|
||||
return rule.rule;
|
||||
})
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
function getLastUserMessage(
|
||||
messages: ChatMessage[],
|
||||
): UserChatMessage | undefined {
|
||||
// Iterate backwards through messages to find the last user message
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].role === "user") {
|
||||
return messages[i] as UserChatMessage;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
contextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
prompt,
|
||||
functions,
|
||||
systemMessage,
|
||||
rules,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[] | undefined;
|
||||
contextLength: number;
|
||||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
prompt: string | undefined;
|
||||
functions: any[] | undefined;
|
||||
systemMessage: string | undefined;
|
||||
rules: Rule[];
|
||||
}): ChatMessage[] {
|
||||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
|
|
@ -425,29 +544,19 @@ function compileChatMessages(
|
|||
msgsCopy.push(promptMsg);
|
||||
}
|
||||
|
||||
if (
|
||||
(systemMessage && systemMessage.trim() !== "") ||
|
||||
msgs?.[0]?.role === "system"
|
||||
) {
|
||||
let content = "";
|
||||
if (msgs?.[0]?.role === "system") {
|
||||
content = renderChatMessage(msgs?.[0]);
|
||||
}
|
||||
if (systemMessage && systemMessage.trim() !== "") {
|
||||
const shouldAddNewLines = content !== "";
|
||||
if (shouldAddNewLines) {
|
||||
content += "\n\n";
|
||||
}
|
||||
content += systemMessage;
|
||||
}
|
||||
const systemChatMsg: ChatMessage = {
|
||||
role: "system",
|
||||
content,
|
||||
};
|
||||
// Insert as second to last
|
||||
// Later moved to top, but want second-priority to last user message
|
||||
msgsCopy.splice(-1, 0, systemChatMsg);
|
||||
}
|
||||
const lastUserMessage = getLastUserMessage(msgsCopy);
|
||||
|
||||
msgsCopy = addSystemMessage({
|
||||
messages: msgsCopy,
|
||||
systemMessage:
|
||||
systemMessage ??
|
||||
getSystemMessage({
|
||||
userMessage: lastUserMessage,
|
||||
rules,
|
||||
currentModel: modelName,
|
||||
}),
|
||||
originalMessages: msgs,
|
||||
});
|
||||
|
||||
let functionTokens = 0;
|
||||
if (functions) {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ModelRole } from "@continuedev/config-yaml";
|
||||
import { ModelRole, Rule } from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
import { findLlmInfo } from "@continuedev/llm-info";
|
||||
import {
|
||||
|
|
@ -143,6 +143,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
cacheBehavior?: CacheBehavior;
|
||||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
rules?: Rule[];
|
||||
|
||||
deployment?: string;
|
||||
apiVersion?: string;
|
||||
|
|
@ -242,6 +243,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.accountId = options.accountId;
|
||||
this.capabilities = options.capabilities;
|
||||
this.roles = options.roles;
|
||||
this.rules = options.rules;
|
||||
|
||||
this.deployment = options.deployment;
|
||||
this.apiVersion = options.apiVersion;
|
||||
|
|
@ -286,21 +288,17 @@ export abstract class BaseLLM implements ILLM {
|
|||
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
return compileChatMessages(
|
||||
options.model,
|
||||
messages,
|
||||
return compileChatMessages({
|
||||
modelName: options.model,
|
||||
msgs: messages,
|
||||
contextLength,
|
||||
options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
this.supportsImages(),
|
||||
undefined,
|
||||
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
prompt: undefined,
|
||||
functions,
|
||||
this.systemMessage,
|
||||
);
|
||||
}
|
||||
|
||||
private _getSystemMessage(): string | undefined {
|
||||
// TODO: Merge with config system message
|
||||
return this.systemMessage;
|
||||
systemMessage: this.systemMessage,
|
||||
rules: this.rules ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
private _templatePromptLikeMessages(prompt: string): string {
|
||||
|
|
@ -310,7 +308,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
|
||||
|
||||
const systemMessage = this._getSystemMessage();
|
||||
const systemMessage = this.systemMessage;
|
||||
if (systemMessage) {
|
||||
msgs.unshift({ role: "system", content: systemMessage });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
ConverseStreamCommand,
|
||||
ConverseStreamCommandOutput,
|
||||
InvokeModelCommand,
|
||||
Message
|
||||
Message,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
|
|
@ -12,7 +12,7 @@ import {
|
|||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions
|
||||
LLMOptions,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -52,10 +52,14 @@ class Bedrock extends BaseLLM {
|
|||
private _currentToolResponse: Partial<ToolUseState> | null = null;
|
||||
private _promptCachingMetrics: PromptCachingMetrics = {
|
||||
cacheReadInputTokens: 0,
|
||||
cacheWriteInputTokens: 0
|
||||
cacheWriteInputTokens: 0,
|
||||
};
|
||||
|
||||
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
|
||||
public requestOptions: {
|
||||
region?: string;
|
||||
credentials?: any;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
|
@ -121,12 +125,17 @@ class Bedrock extends BaseLLM {
|
|||
},
|
||||
);
|
||||
|
||||
const input = this._generateConverseInput(messages, { ...options, stream: true });
|
||||
const input = this._generateConverseInput(messages, {
|
||||
...options,
|
||||
stream: true,
|
||||
});
|
||||
const command = new ConverseStreamCommand(input);
|
||||
|
||||
let response: ConverseStreamCommandOutput;
|
||||
try {
|
||||
response = await client.send(command, { abortSignal: signal }) as ConverseStreamCommandOutput;
|
||||
response = (await client.send(command, {
|
||||
abortSignal: signal,
|
||||
})) as ConverseStreamCommandOutput;
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
|
|
@ -140,9 +149,9 @@ class Bedrock extends BaseLLM {
|
|||
// Reset cache metrics for new request
|
||||
this._promptCachingMetrics = {
|
||||
cacheReadInputTokens: 0,
|
||||
cacheWriteInputTokens: 0
|
||||
cacheWriteInputTokens: 0,
|
||||
};
|
||||
|
||||
|
||||
try {
|
||||
for await (const chunk of response.stream) {
|
||||
if (chunk.metadata?.usage) {
|
||||
|
|
@ -150,47 +159,69 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
|
||||
if (chunk.contentBlockDelta?.delta) {
|
||||
|
||||
const delta: any = chunk.contentBlockDelta.delta
|
||||
const delta: any = chunk.contentBlockDelta.delta;
|
||||
|
||||
// Handle text content
|
||||
if (chunk.contentBlockDelta.delta.text) {
|
||||
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: chunk.contentBlockDelta.delta.text,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle text content
|
||||
if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
|
||||
yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: (chunk.contentBlockDelta.delta as any).reasoningContent
|
||||
.text,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle signature for thinking
|
||||
if (delta.reasoningContent?.signature) {
|
||||
yield { role: "thinking", content: "", signature: delta.reasoningContent.signature };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
signature: delta.reasoningContent.signature,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle redacted thinking
|
||||
if (delta.redactedReasoning?.data) {
|
||||
yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: delta.redactedReasoning.data,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
|
||||
if (
|
||||
chunk.contentBlockDelta.delta.toolUse?.input &&
|
||||
this._currentToolResponse
|
||||
) {
|
||||
// Append the new input to the existing string
|
||||
if (this._currentToolResponse.input === undefined) {
|
||||
this._currentToolResponse.input = "";
|
||||
}
|
||||
this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input;
|
||||
this._currentToolResponse.input +=
|
||||
chunk.contentBlockDelta.delta.toolUse.input;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.contentBlockStart?.start) {
|
||||
const start: any = chunk.contentBlockStart.start
|
||||
const start: any = chunk.contentBlockStart.start;
|
||||
if (start.redactedReasoning) {
|
||||
yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: start.redactedReasoning.data,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -199,7 +230,7 @@ class Bedrock extends BaseLLM {
|
|||
this._currentToolResponse = {
|
||||
toolUseId: toolUse.toolUseId,
|
||||
name: toolUse.name,
|
||||
input: ""
|
||||
input: "",
|
||||
};
|
||||
}
|
||||
continue;
|
||||
|
|
@ -210,14 +241,16 @@ class Bedrock extends BaseLLM {
|
|||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input
|
||||
}
|
||||
}],
|
||||
toolCalls: [
|
||||
{
|
||||
id: this._currentToolResponse.toolUseId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: this._currentToolResponse.name,
|
||||
arguments: this._currentToolResponse.input,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
this._currentToolResponse = null;
|
||||
}
|
||||
|
|
@ -229,13 +262,16 @@ class Bedrock extends BaseLLM {
|
|||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`);
|
||||
throw new Error(
|
||||
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error processing Bedrock stream: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error processing Bedrock stream: Unknown error occurred");
|
||||
throw new Error(
|
||||
"Error processing Bedrock stream: Unknown error occurred",
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -252,39 +288,41 @@ class Bedrock extends BaseLLM {
|
|||
|
||||
const shouldCacheSystemMessage =
|
||||
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
|
||||
const enablePromptCaching = shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
|
||||
const enablePromptCaching =
|
||||
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
|
||||
|
||||
// Add header for prompt caching
|
||||
if (enablePromptCaching) {
|
||||
this.requestOptions.headers = {
|
||||
...this.requestOptions.headers,
|
||||
"x-amzn-bedrock-enablepromptcaching": "true"
|
||||
"x-amzn-bedrock-enablepromptcaching": "true",
|
||||
};
|
||||
}
|
||||
|
||||
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
const supportsTools =
|
||||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
|
||||
return {
|
||||
modelId: options.model,
|
||||
messages: convertedMessages,
|
||||
system: this.systemMessage ? (
|
||||
shouldCacheSystemMessage ?
|
||||
[
|
||||
{ text: this.systemMessage },
|
||||
{ cachePoint: { type: "default" } }
|
||||
] :
|
||||
[{ text: this.systemMessage }]
|
||||
) : undefined,
|
||||
toolConfig: supportsTools && options.tools ? {
|
||||
tools: options.tools.map(tool => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters
|
||||
system: this.systemMessage
|
||||
? shouldCacheSystemMessage
|
||||
? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }]
|
||||
: [{ text: this.systemMessage }]
|
||||
: undefined,
|
||||
toolConfig:
|
||||
supportsTools && options.tools
|
||||
? {
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
}
|
||||
}
|
||||
}))
|
||||
} : undefined,
|
||||
: undefined,
|
||||
inferenceConfig: {
|
||||
maxTokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -302,21 +340,28 @@ class Bedrock extends BaseLLM {
|
|||
.slice(0, 4),
|
||||
},
|
||||
additionalModelRequestFields: {
|
||||
"thinking": options.reasoning ? {
|
||||
"type": "enabled",
|
||||
"budget_tokens": options.reasoningBudgetTokens
|
||||
} : undefined,
|
||||
}
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private _convertMessage(message: ChatMessage, addCaching: boolean = false): Message | null {
|
||||
private _convertMessage(
|
||||
message: ChatMessage,
|
||||
addCaching: boolean = false,
|
||||
): Message | null {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cachePoint = addCaching ? { cachePoint: { type: "default" } } : undefined;
|
||||
const cachePoint = addCaching
|
||||
? { cachePoint: { type: "default" } }
|
||||
: undefined;
|
||||
|
||||
// Tool response handling
|
||||
if (message.role === "tool") {
|
||||
|
|
@ -328,12 +373,12 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
text: message.content || "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -346,8 +391,8 @@ class Bedrock extends BaseLLM {
|
|||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
}))
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -355,26 +400,27 @@ class Bedrock extends BaseLLM {
|
|||
if (message.redactedThinking) {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(Buffer.from(message.redactedThinking))
|
||||
}
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
content: [content],
|
||||
};
|
||||
} else {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature
|
||||
}
|
||||
|
||||
}
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
content: [content],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -387,7 +433,7 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
return {
|
||||
role: message.role,
|
||||
content
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -396,7 +442,7 @@ class Bedrock extends BaseLLM {
|
|||
const content: any[] = [];
|
||||
|
||||
// Process all parts first
|
||||
message.content.forEach(part => {
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "text") {
|
||||
content.push({ text: part.text });
|
||||
} else if (part.type === "imageUrl" && part.imageUrl) {
|
||||
|
|
@ -407,9 +453,9 @@ class Bedrock extends BaseLLM {
|
|||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64")
|
||||
}
|
||||
}
|
||||
bytes: Buffer.from(base64Data, "base64"),
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
|
|
@ -424,7 +470,7 @@ class Bedrock extends BaseLLM {
|
|||
|
||||
return {
|
||||
role: message.role,
|
||||
content
|
||||
content,
|
||||
} as Message;
|
||||
}
|
||||
return null;
|
||||
|
|
@ -439,22 +485,24 @@ class Bedrock extends BaseLLM {
|
|||
.filter((index) => index !== -1)
|
||||
.slice(-2);
|
||||
|
||||
const converted = filteredmessages.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
const converted = filteredmessages
|
||||
.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
|
||||
try {
|
||||
return this._convertMessage(message, addCaching);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean);
|
||||
try {
|
||||
return this._convertMessage(message, addCaching);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
|
@ -520,7 +568,6 @@ class Bedrock extends BaseLLM {
|
|||
return modelConfig.extractEmbeddings(responseBody);
|
||||
}
|
||||
|
||||
|
||||
private _getModelConfig() {
|
||||
const modelConfigs: { [key: string]: ModelConfig } = {
|
||||
cohere: {
|
||||
|
|
@ -558,7 +605,11 @@ class Bedrock extends BaseLLM {
|
|||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
credentials,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken || "",
|
||||
},
|
||||
});
|
||||
|
||||
// Base payload for both models
|
||||
|
|
@ -597,11 +648,15 @@ class Bedrock extends BaseLLM {
|
|||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`);
|
||||
throw new Error(
|
||||
`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
|
||||
}
|
||||
throw new Error("Error in BedrockReranker.rerank: Unknown error occurred");
|
||||
throw new Error(
|
||||
"Error in BedrockReranker.rerank: Unknown error occurred",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
59
core/llm/rules/isRuleActive.test.ts
Normal file
59
core/llm/rules/isRuleActive.test.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
describe("isRuleActive", () => {
|
||||
const rule = {
|
||||
name: "My Rule",
|
||||
rule: "Do no harm",
|
||||
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
|
||||
};
|
||||
|
||||
it("should return false when activePaths is empty", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: [],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when no matching paths exist", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["test.py", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true when both conditions are met", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when only glob matches but model doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx"],
|
||||
currentModel: "gpt-4",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when model matches but glob doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.ts"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
68
core/llm/rules/isRuleActive.ts
Normal file
68
core/llm/rules/isRuleActive.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { Rule } from "@continuedev/config-yaml";
|
||||
import { compileExpression } from "filtrex";
|
||||
import { minimatch } from "minimatch";
|
||||
|
||||
const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/;
|
||||
|
||||
const createGlobFunction = (activePaths: string[]) => {
|
||||
return (pattern: string) => {
|
||||
const result = activePaths.some((path) => minimatch(path, pattern));
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
const contains = (str: string, searchStr: string): boolean => {
|
||||
return str.includes(searchStr);
|
||||
};
|
||||
|
||||
const evaluateIf = ({
|
||||
condition,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
condition: string;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim();
|
||||
if (!expression) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const evaluate = compileExpression(expression, {
|
||||
extraFunctions: {
|
||||
glob: createGlobFunction(activePaths),
|
||||
contains,
|
||||
},
|
||||
constants: {
|
||||
"current.model.model": currentModel,
|
||||
},
|
||||
});
|
||||
|
||||
return evaluate({});
|
||||
} catch (error) {
|
||||
console.error("Error evaluating rule condition:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const isRuleActive = ({
|
||||
rule,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
rule: Rule;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}): boolean => {
|
||||
if (typeof rule === "string") {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (rule.if) {
|
||||
return evaluateIf({ condition: rule.if, activePaths, currentModel });
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
22
core/llm/utils/extractPathsFromCodeBlocks.ts
Normal file
22
core/llm/utils/extractPathsFromCodeBlocks.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
/**
|
||||
* Extracts file paths from markdown code blocks
|
||||
*/
|
||||
export function extractPathsFromCodeBlocks(content: string): string[] {
|
||||
// Match:
|
||||
// 1. Starting ```
|
||||
// 2. Optional language identifier
|
||||
// 3. Required whitespace
|
||||
// 4. File path (captured) that must contain a dot and extension
|
||||
const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
|
||||
const paths: string[] = [];
|
||||
let match;
|
||||
|
||||
while ((match = codeBlockRegex.exec(content)) !== null) {
|
||||
const path = match[1];
|
||||
if (path && !path.startsWith("```")) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
14
core/package-lock.json
generated
14
core/package-lock.json
generated
|
|
@ -13,7 +13,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
@ -32,6 +32,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -2976,9 +2977,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-yaml": {
|
||||
"version": "1.0.67",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz",
|
||||
"integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==",
|
||||
"version": "1.0.71",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz",
|
||||
"integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
|
|
@ -8587,6 +8588,11 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/filtrex": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz",
|
||||
"integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A=="
|
||||
},
|
||||
"node_modules/find-replace": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz",
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
@ -66,6 +66,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
|
|||
import type {
|
||||
ApplyState,
|
||||
CodeToEdit,
|
||||
ContextSubmenuItem,
|
||||
EditStatus,
|
||||
MessageContent,
|
||||
RangeInFileWithContents,
|
||||
|
|
@ -20,6 +19,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
streamId: string;
|
||||
curSelectedModelTitle: string;
|
||||
filepath?: string;
|
||||
toolCallId?: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "builtin_read_file",
|
||||
EditExistingFile = "builtin_edit_existing_file",
|
||||
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
|
||||
CreateNewFile = "builtin_create_new_file",
|
||||
RunTerminalCommand = "builtin_run_terminal_command",
|
||||
|
|
|
|||
|
|
@ -139,6 +139,7 @@ export async function callTool(
|
|||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
// Note: Custom GUI handling for edit
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
|
|
|
|||
37
core/tools/definitions/editFile.ts
Normal file
37
core/tools/definitions/editFile.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
new_contents: string;
|
||||
}
|
||||
|
||||
export const editFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.EditExistingFile,
|
||||
description:
|
||||
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "new_contents"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to edit, relative to the root of the workspace.",
|
||||
},
|
||||
new_contents: {
|
||||
type: "string",
|
||||
description: "The new file contents",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const resolvedFileUri = await inferResolvedUriFromRelativePath(
|
||||
|
|
@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
|||
extras.ide,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const exists = await extras.ide.fileExists(resolvedFileUri);
|
||||
if (exists) {
|
||||
throw new Error(
|
||||
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
|
||||
);
|
||||
}
|
||||
await extras.ide.writeFile(resolvedFileUri, args.contents);
|
||||
await extras.ide.openFile(resolvedFileUri);
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
description: getCleanUriPath(resolvedFileUri),
|
||||
content: "File created successfuly",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: resolvedFileUri,
|
||||
},
|
||||
},
|
||||
];
|
||||
} else {
|
||||
throw new Error("Failed to resolve path");
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { createNewFileTool } from "./definitions/createNewFile";
|
||||
import { editFileTool } from "./definitions/editFile";
|
||||
import { globSearchTool } from "./definitions/globSearch";
|
||||
import { grepSearchTool } from "./definitions/grepSearch";
|
||||
import { lsTool } from "./definitions/lsTool";
|
||||
|
|
@ -10,6 +11,7 @@ import { viewDiffTool } from "./definitions/viewDiff";
|
|||
|
||||
export const allTools = [
|
||||
readFileTool,
|
||||
editFileTool,
|
||||
createNewFileTool,
|
||||
runTerminalCommandTool,
|
||||
|
||||
|
|
|
|||
|
|
@ -28,11 +28,11 @@ To enable it, simply click the "Continue" button in the status bar at the bottom
|
|||
|
||||
Highlight a block of code, describe your code changes, and a diff will be streamed inline to your file which you can accept or reject.
|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||
For example, you might want to review code, write tests, or add a docstring.
|
||||
Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions.
|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.10
|
||||
pluginVersion=1.0.11
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager
|
|||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
|
|
@ -432,11 +433,43 @@ class IdeProtocolClient(
|
|||
dataElement.toString(),
|
||||
ApplyToFileParams::class.java
|
||||
)
|
||||
val filepath = params.filepath
|
||||
|
||||
val editor = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"streamId" to params.streamId,
|
||||
"status" to "streaming",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
))
|
||||
|
||||
|
||||
fun closeStream () {
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"numDiffs" to 0,
|
||||
"streamId" to params.streamId,
|
||||
"status" to "closed",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
))
|
||||
}
|
||||
|
||||
var editor: Editor? = null;
|
||||
|
||||
if (!filepath.isNullOrEmpty()) {
|
||||
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
|
||||
}
|
||||
}
|
||||
}
|
||||
editor = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
|
||||
if (editor == null) {
|
||||
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
|
@ -445,6 +478,7 @@ class IdeProtocolClient(
|
|||
WriteCommandAction.runWriteCommandAction(project) {
|
||||
editor.document.insertString(0, params.text)
|
||||
}
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
|
@ -490,6 +524,7 @@ class IdeProtocolClient(
|
|||
ToastType.ERROR, "Failed to fetch model configuration"
|
||||
)
|
||||
}
|
||||
closeStream()
|
||||
respond(null)
|
||||
return@launch
|
||||
}
|
||||
|
|
@ -528,7 +563,11 @@ class IdeProtocolClient(
|
|||
editor,
|
||||
rif?.range?.start?.line ?: 0,
|
||||
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
|
||||
{}, {})
|
||||
{},
|
||||
{},
|
||||
params.streamId,
|
||||
params.toolCallId
|
||||
)
|
||||
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
||||
|
|
|
|||
|
|
@ -27,14 +27,15 @@ class DiffStreamHandler(
|
|||
private val startLine: Int,
|
||||
private val endLine: Int,
|
||||
private val onClose: () -> Unit,
|
||||
private val onFinish: () -> Unit
|
||||
private val onFinish: () -> Unit,
|
||||
private val streamId: String?,
|
||||
private val toolCallId: String?
|
||||
) {
|
||||
private data class CurLineState(
|
||||
var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
|
||||
)
|
||||
|
||||
private var curLine = CurLineState(startLine)
|
||||
|
||||
private var isRunning: Boolean = false
|
||||
private var hasAcceptedOrRejectedBlock: Boolean = false
|
||||
|
||||
|
|
@ -48,8 +49,26 @@ class DiffStreamHandler(
|
|||
initUnfinishedRangeHighlights()
|
||||
}
|
||||
|
||||
private fun sendUpdate(status: String) {
|
||||
if(this.streamId == null) {
|
||||
return
|
||||
}
|
||||
val virtualFile = getVirtualFile()
|
||||
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"numDiffs" to this.diffBlocks.size,
|
||||
"streamId" to this.streamId,
|
||||
"status" to status,
|
||||
"fileContent" to "not implemented",
|
||||
"toolCallId" to this.toolCallId,
|
||||
"filepath" to virtualFile?.url
|
||||
))
|
||||
}
|
||||
|
||||
fun acceptAll() {
|
||||
editor.markupModel.removeAllHighlighters()
|
||||
editor.markupModel.removeAllHighlighters();
|
||||
sendUpdate("closed")
|
||||
|
||||
resetState()
|
||||
}
|
||||
|
||||
|
|
@ -62,6 +81,7 @@ class DiffStreamHandler(
|
|||
} else {
|
||||
undoChanges()
|
||||
}
|
||||
sendUpdate("closed")
|
||||
|
||||
resetState()
|
||||
}
|
||||
|
|
@ -70,6 +90,7 @@ class DiffStreamHandler(
|
|||
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String
|
||||
) {
|
||||
isRunning = true
|
||||
this.sendUpdate("streaming")
|
||||
|
||||
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
|
||||
val virtualFile = getVirtualFile()
|
||||
|
|
@ -83,6 +104,7 @@ class DiffStreamHandler(
|
|||
|
||||
if (response["done"] as? Boolean == true) {
|
||||
handleFinishedResponse()
|
||||
sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done")
|
||||
return@request
|
||||
}
|
||||
|
||||
|
|
@ -133,7 +155,10 @@ class DiffStreamHandler(
|
|||
}
|
||||
|
||||
if (diffBlocks.isEmpty()) {
|
||||
sendUpdate("closed")
|
||||
onClose()
|
||||
} else {
|
||||
sendUpdate("done")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -144,6 +169,7 @@ class DiffStreamHandler(
|
|||
)
|
||||
|
||||
diffBlocks.add(diffBlock)
|
||||
sendUpdate("streaming")
|
||||
|
||||
return diffBlock
|
||||
}
|
||||
|
|
@ -234,6 +260,7 @@ class DiffStreamHandler(
|
|||
undoManager.undo(fileEditor)
|
||||
}
|
||||
}
|
||||
sendUpdate("done")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
textArea.document.insertString(textArea.caretPosition, ", ", null)
|
||||
textArea.requestFocus()
|
||||
customPanelRef.get().finish()
|
||||
})
|
||||
},
|
||||
null,
|
||||
null
|
||||
)
|
||||
|
||||
val diffStreamService = project.service<DiffStreamService>()
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ data class ApplyToFileParams(
|
|||
val text: String,
|
||||
val streamId: String,
|
||||
val curSelectedModelTitle: String,
|
||||
val filepath: String?
|
||||
val filepath: String?,
|
||||
val toolCallId: String?
|
||||
)
|
||||
|
||||
data class InsertAtCursorParams(
|
||||
|
|
|
|||
|
|
@ -44,11 +44,11 @@
|
|||
|
||||

|
||||
|
||||
## Actions
|
||||
## Agent
|
||||
|
||||
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
|
||||
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
15
extensions/vscode/package-lock.json
generated
15
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.19",
|
||||
"version": "1.1.20",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.19",
|
||||
"version": "1.1.20",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/fetch": "^1.0.3",
|
||||
|
|
@ -88,7 +88,7 @@
|
|||
"ovsx": "^0.8.3",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^4.3.9",
|
||||
"vite": "^4.5.12",
|
||||
"vsce": "^2.15.0",
|
||||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
|
|
@ -106,7 +106,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
@ -125,6 +125,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -13321,9 +13322,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "4.5.9",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz",
|
||||
"integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==",
|
||||
"version": "4.5.12",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.12.tgz",
|
||||
"integrity": "sha512-qrMwavANtSz91nDy3zEiUHMtL09x0mniQsSMvDkNxuCBM1W5vriJ22hEmwTth6DhLSWsZnHBT0yHFAQXt6efGA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.19",
|
||||
"version": "1.1.20",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -625,7 +625,7 @@
|
|||
"ovsx": "^0.8.3",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^4.3.9",
|
||||
"vite": "^4.5.12",
|
||||
"vsce": "^2.15.0",
|
||||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
const { exec } = require("child_process");
|
||||
const fs = require("fs");
|
||||
|
||||
const version = JSON.parse(
|
||||
fs.readFileSync("./package.json", { encoding: "utf-8" }),
|
||||
).version;
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
let target;
|
||||
|
||||
|
|
@ -27,6 +31,6 @@ exec(command, (error) => {
|
|||
throw error;
|
||||
}
|
||||
console.log(
|
||||
"vsce package completed - extension created at extensions/vscode/build/continue-{version}.vsix",
|
||||
`vsce package completed - extension created at extensions/vscode/build/continue-${version}.vsix`,
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -247,6 +247,7 @@ async function processDiff(
|
|||
verticalDiffManager: VerticalDiffManager,
|
||||
newFileUri?: string,
|
||||
streamId?: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
captureCommandTelemetry(`${action}Diff`);
|
||||
|
||||
|
|
@ -280,6 +281,7 @@ async function processDiff(
|
|||
streamId,
|
||||
status: "closed",
|
||||
numDiffs: 0,
|
||||
toolCallId,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -190,6 +190,7 @@ export class VerticalDiffManager {
|
|||
diffStream: AsyncGenerator<DiffLine>,
|
||||
instant: boolean,
|
||||
streamId: string,
|
||||
toolCallId?: string,
|
||||
) {
|
||||
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
|
||||
|
||||
|
|
@ -226,6 +227,7 @@ export class VerticalDiffManager {
|
|||
numDiffs,
|
||||
fileContent,
|
||||
filepath: fileUri,
|
||||
toolCallId,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
|
@ -276,6 +278,7 @@ export class VerticalDiffManager {
|
|||
quickEdit?: string,
|
||||
range?: vscode.Range,
|
||||
newCode?: string,
|
||||
toolCallId?: string,
|
||||
): Promise<string | undefined> {
|
||||
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
|
||||
|
||||
|
|
@ -351,6 +354,7 @@ export class VerticalDiffManager {
|
|||
numDiffs,
|
||||
fileContent,
|
||||
filepath: fileUri,
|
||||
toolCallId,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -133,6 +133,7 @@ export class VsCodeMessenger {
|
|||
streamId: data.streamId,
|
||||
status: "streaming",
|
||||
fileContent: data.text,
|
||||
toolCallId: data.toolCallId,
|
||||
});
|
||||
|
||||
if (data.filepath) {
|
||||
|
|
@ -164,6 +165,7 @@ export class VsCodeMessenger {
|
|||
status: "closed",
|
||||
numDiffs: 0,
|
||||
fileContent: data.text,
|
||||
toolCallId: data.toolCallId,
|
||||
});
|
||||
|
||||
return;
|
||||
|
|
@ -211,6 +213,7 @@ export class VsCodeMessenger {
|
|||
diffLines,
|
||||
instant,
|
||||
data.streamId,
|
||||
data.toolCallId,
|
||||
);
|
||||
} else {
|
||||
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`;
|
||||
|
|
@ -232,6 +235,7 @@ export class VsCodeMessenger {
|
|||
undefined,
|
||||
rangeToApplyTo,
|
||||
data.text,
|
||||
data.toolCallId,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007
|
||||
},
|
||||
"include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"],
|
||||
|
|
|
|||
11
gui/package-lock.json
generated
11
gui/package-lock.json
generated
|
|
@ -7,7 +7,7 @@
|
|||
"name": "gui",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@headlessui/react": "^2.2.0",
|
||||
"@heroicons/react": "^2.0.18",
|
||||
"@reduxjs/toolkit": "^2.3.0",
|
||||
|
|
@ -111,7 +111,7 @@
|
|||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
|
|
@ -130,6 +130,7 @@
|
|||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"handlebars": "^4.7.8",
|
||||
|
|
@ -554,9 +555,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-yaml": {
|
||||
"version": "1.0.67",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz",
|
||||
"integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==",
|
||||
"version": "1.0.71",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz",
|
||||
"integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@continuedev/config-yaml": "^1.0.67",
|
||||
"@continuedev/config-yaml": "^1.0.71",
|
||||
"@headlessui/react": "^2.2.0",
|
||||
"@heroicons/react": "^2.0.18",
|
||||
"@reduxjs/toolkit": "^2.3.0",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { RouterProvider, createMemoryRouter } from "react-router-dom";
|
||||
import Layout from "./components/Layout";
|
||||
import { MainEditorProvider } from "./components/mainInput/TipTapEditor";
|
||||
import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders";
|
||||
import { VscThemeProvider } from "./context/VscTheme";
|
||||
import useSetup from "./hooks/useSetup";
|
||||
|
|
@ -57,9 +58,11 @@ function SetupListeners() {
|
|||
function App() {
|
||||
return (
|
||||
<VscThemeProvider>
|
||||
<SubmenuContextProvidersProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SubmenuContextProvidersProvider>
|
||||
<MainEditorProvider>
|
||||
<SubmenuContextProvidersProvider>
|
||||
<RouterProvider router={router} />
|
||||
</SubmenuContextProvidersProvider>
|
||||
</MainEditorProvider>
|
||||
<SetupListeners />
|
||||
</VscThemeProvider>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -2,14 +2,17 @@ import { SlashCommandDescription } from "core";
|
|||
import { useState } from "react";
|
||||
import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice";
|
||||
import { getParagraphNodeFromString } from "../mainInput/utils";
|
||||
import { useMainEditor } from "../mainInput/TipTapEditor";
|
||||
import { ConversationStarterCard } from "./ConversationStarterCard";
|
||||
|
||||
const NUM_CARDS_TO_RENDER = 5;
|
||||
|
||||
/**
|
||||
* Displays a grid of conversation starter cards for bookmarked slash commands
|
||||
*/
|
||||
export function ConversationStarterCards() {
|
||||
const dispatch = useAppDispatch();
|
||||
const { mainEditor } = useMainEditor();
|
||||
const [showAll, setShowAll] = useState(false);
|
||||
const { isCommandBookmarked } = useBookmarkedSlashCommands();
|
||||
const slashCommands = useAppSelector(
|
||||
|
|
@ -21,11 +24,7 @@ export function ConversationStarterCards() {
|
|||
);
|
||||
|
||||
function onClick(command: SlashCommandDescription) {
|
||||
if (command.prompt) {
|
||||
dispatch(
|
||||
setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)),
|
||||
);
|
||||
}
|
||||
mainEditor?.commands.insertPrompt(command);
|
||||
}
|
||||
|
||||
if (bookmarkedSlashCommands.length === 0) {
|
||||
|
|
|
|||
|
|
@ -5,9 +5,10 @@ import { themeIcons } from "seti-file-icons";
|
|||
|
||||
export interface FileIconProps {
|
||||
filename: string;
|
||||
height: string;
|
||||
width: string;
|
||||
height: `${number}px`;
|
||||
width: `${number}px`;
|
||||
}
|
||||
|
||||
export default function FileIcon({ filename, height, width }: FileIconProps) {
|
||||
const file = useMemo(() => {
|
||||
if (filename.includes(" (")) {
|
||||
|
|
@ -45,7 +46,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) {
|
|||
height: height,
|
||||
fill: color,
|
||||
flexShrink: 0,
|
||||
display: "block",
|
||||
display: "flex",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ import {
|
|||
newSession,
|
||||
selectIsInEditMode,
|
||||
setMode,
|
||||
updateApplyState,
|
||||
} from "../redux/slices/sessionSlice";
|
||||
import { setShowDialog } from "../redux/slices/uiSlice";
|
||||
import { exitEditMode } from "../redux/thunks";
|
||||
|
|
@ -125,20 +124,6 @@ const Layout = () => {
|
|||
[],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"updateApplyState",
|
||||
async (state) => {
|
||||
// dispatch(
|
||||
// updateCurCheckpoint({
|
||||
// filepath: state.filepath,
|
||||
// content: state.fileContent,
|
||||
// }),
|
||||
// );
|
||||
dispatch(updateApplyState(state));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"openOnboardingCard",
|
||||
async () => {
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ const HeaderButtonWithToolTip = React.forwardRef<
|
|||
</HeaderButton>
|
||||
|
||||
<ToolTip id={tooltipId} place={props.tooltipPlacement ?? "bottom"}>
|
||||
{props.text}
|
||||
<span className="text-xs">{props.text}</span>
|
||||
</ToolTip>
|
||||
</>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
|
|||
import ContextItemsPeek from "./belowMainInput/ContextItemsPeek";
|
||||
import { ToolbarOptions } from "./InputToolbar";
|
||||
import { Lump } from "./Lump";
|
||||
import TipTapEditor from "./tiptap/TipTapEditor";
|
||||
import { TipTapEditor } from "./TipTapEditor";
|
||||
|
||||
interface ContinueInputBoxProps {
|
||||
isEditMode?: boolean;
|
||||
|
|
|
|||
|
|
@ -98,11 +98,16 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
|
||||
const toolCallState = useAppSelector(selectCurrentToolCall);
|
||||
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
|
||||
const activeToolCallStreamId = useAppSelector(
|
||||
(store) => store.session.activeToolStreamId,
|
||||
);
|
||||
|
||||
const isEnterDisabled =
|
||||
props.disabled ||
|
||||
isEditModeAndNoCodeToEdit ||
|
||||
toolCallState?.status === "generated";
|
||||
toolCallState?.status === "generated" ||
|
||||
!!activeToolCallStreamId;
|
||||
|
||||
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
|
||||
|
||||
const supportsImages =
|
||||
|
|
|
|||
|
|
@ -9,11 +9,10 @@ import {
|
|||
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/HoverItem";
|
||||
import { useLump } from "./LumpContext";
|
||||
|
||||
interface BlockSettingsToolbarIcon {
|
||||
tooltip: string;
|
||||
|
|
@ -81,21 +80,19 @@ function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) {
|
|||
);
|
||||
}
|
||||
|
||||
interface BlockSettingsTopToolbarProps {
|
||||
selectedSection: string | null;
|
||||
setSelectedSection: (value: string | null) => void;
|
||||
}
|
||||
export function BlockSettingsTopToolbar() {
|
||||
const {
|
||||
isToolbarExpanded,
|
||||
toggleToolbar,
|
||||
selectedSection,
|
||||
setSelectedSection,
|
||||
} = useLump();
|
||||
|
||||
export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
|
||||
const isExpanded = useAppSelector(
|
||||
(state) => state.ui.isBlockSettingsToolbarExpanded,
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
const handleEllipsisClick = () => {
|
||||
if (isExpanded) {
|
||||
props.setSelectedSection(null);
|
||||
if (isToolbarExpanded) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
dispatch(toggleBlockSettingsToolbar());
|
||||
toggleToolbar();
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
@ -103,14 +100,14 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
|
|||
<div className="xs:flex hidden items-center justify-center text-gray-400">
|
||||
<BlockSettingsToolbarIcon
|
||||
className="-ml-1.5"
|
||||
icon={isExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
|
||||
tooltip={isExpanded ? "Collapse sections" : "Expand sections"}
|
||||
icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
|
||||
tooltip={isToolbarExpanded ? "Collapse sections" : "Expand sections"}
|
||||
isSelected={false}
|
||||
onClick={handleEllipsisClick}
|
||||
/>
|
||||
<div
|
||||
className="flex overflow-hidden transition-all duration-200"
|
||||
style={{ width: isExpanded ? `160px` : "0px" }}
|
||||
style={{ width: isToolbarExpanded ? `160px` : "0px" }}
|
||||
>
|
||||
<div className="flex">
|
||||
{sections.map((section) => (
|
||||
|
|
@ -118,10 +115,10 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
|
|||
key={section.id}
|
||||
icon={section.icon}
|
||||
tooltip={section.tooltip}
|
||||
isSelected={props.selectedSection === section.id}
|
||||
isSelected={selectedSection === section.id}
|
||||
onClick={() =>
|
||||
props.setSelectedSection(
|
||||
props.selectedSection === section.id ? null : section.id,
|
||||
setSelectedSection(
|
||||
selectedSection === section.id ? null : section.id,
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
|
|
|||
115
gui/src/components/mainInput/Lump/LumpContext.tsx
Normal file
115
gui/src/components/mainInput/Lump/LumpContext.tsx
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/**
|
||||
* Provides context for controlling the Lump component's visibility state
|
||||
*/
|
||||
import {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
|
||||
interface LumpContextType {
|
||||
isLumpVisible: boolean;
|
||||
selectedSection: string | null;
|
||||
displayedSection: string | null;
|
||||
isToolbarExpanded: boolean;
|
||||
hideLump: () => void;
|
||||
setSelectedSection: (section: string | null) => void;
|
||||
toggleToolbar: () => void;
|
||||
}
|
||||
|
||||
const LumpContext = createContext<LumpContextType | undefined>(undefined);
|
||||
|
||||
interface LumpProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider component that makes Lump state available to any child component
|
||||
*/
|
||||
export function LumpProvider({ children }: LumpProviderProps) {
|
||||
const [selectedSection, setSelectedSection] = useState<string | null>(null);
|
||||
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
const [isToolbarExpanded, setIsToolbarExpanded] = useState(true);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
|
||||
// Handle keyboard escape
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && selectedSection) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
},
|
||||
[selectedSection],
|
||||
);
|
||||
|
||||
// Function to hide the lump
|
||||
const hideLump = useCallback(() => {
|
||||
setSelectedSection(null);
|
||||
}, []);
|
||||
|
||||
// Function to toggle toolbar expanded state
|
||||
const toggleToolbar = useCallback(() => {
|
||||
setIsToolbarExpanded((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
// Update displayedSection and visibility when selectedSection changes
|
||||
useEffect(() => {
|
||||
if (selectedSection) {
|
||||
setDisplayedSection(selectedSection);
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
const timeout = setTimeout(() => {
|
||||
setDisplayedSection(null);
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}
|
||||
}, [selectedSection]);
|
||||
|
||||
// Reset when streaming starts
|
||||
useEffect(() => {
|
||||
if (isStreaming && selectedSection) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
}, [isStreaming, selectedSection]);
|
||||
|
||||
// Set up keyboard listener
|
||||
useEffect(() => {
|
||||
if (selectedSection) {
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => document.removeEventListener("keydown", handleKeyDown);
|
||||
}
|
||||
}, [selectedSection, handleKeyDown]);
|
||||
|
||||
return (
|
||||
<LumpContext.Provider
|
||||
value={{
|
||||
isLumpVisible: isVisible,
|
||||
selectedSection,
|
||||
displayedSection,
|
||||
isToolbarExpanded,
|
||||
hideLump,
|
||||
setSelectedSection,
|
||||
toggleToolbar,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</LumpContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook that lets any component access the Lump context
|
||||
*/
|
||||
export function useLump() {
|
||||
const context = useContext(LumpContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useLump must be used within a LumpProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
|
@ -21,11 +21,6 @@ const StopButton = styled.div`
|
|||
cursor: pointer;
|
||||
`;
|
||||
|
||||
interface TopToolbarProps {
|
||||
selectedSection: string | null;
|
||||
setSelectedSection: (value: string | null) => void;
|
||||
}
|
||||
|
||||
function GeneratingIndicator() {
|
||||
return (
|
||||
<div className="text-xs text-gray-400">
|
||||
|
|
@ -35,7 +30,7 @@ function GeneratingIndicator() {
|
|||
);
|
||||
}
|
||||
|
||||
export function LumpToolbar(props: TopToolbarProps) {
|
||||
export function LumpToolbar() {
|
||||
const dispatch = useAppDispatch();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
|
||||
|
|
@ -73,10 +68,5 @@ export function LumpToolbar(props: TopToolbarProps) {
|
|||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BlockSettingsTopToolbar
|
||||
selectedSection={props.selectedSection}
|
||||
setSelectedSection={props.setSelectedSection}
|
||||
/>
|
||||
);
|
||||
return <BlockSettingsTopToolbar />;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
vscCommandCenterInactiveBorder,
|
||||
vscInputBackground,
|
||||
} from "../..";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
import { LumpProvider, useLump } from "./LumpContext";
|
||||
import { LumpToolbar } from "./LumpToolbar";
|
||||
import { SelectedSection } from "./sections/SelectedSection";
|
||||
|
||||
|
|
@ -30,62 +29,34 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>`
|
|||
overflow-y: auto;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Main component that displays the toolbar and selected content section
|
||||
*/
|
||||
export function Lump() {
|
||||
const [selectedSection, setSelectedSection] = useState<string | null>(null);
|
||||
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
return (
|
||||
<LumpProvider>
|
||||
<LumpContent />
|
||||
</LumpProvider>
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedSection) {
|
||||
return;
|
||||
}
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [selectedSection]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isStreaming) {
|
||||
setSelectedSection(null);
|
||||
}
|
||||
}, [isStreaming]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSection) {
|
||||
setDisplayedSection(selectedSection);
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
const timeout = setTimeout(() => {
|
||||
setDisplayedSection(null);
|
||||
}, 300);
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
}
|
||||
}, [selectedSection]);
|
||||
/**
|
||||
* Internal component that consumes the LumpContext
|
||||
*/
|
||||
function LumpContent() {
|
||||
const { isLumpVisible, selectedSection } = useLump();
|
||||
|
||||
return (
|
||||
<LumpDiv>
|
||||
<div className="mt-0.5 px-2">
|
||||
<LumpToolbar
|
||||
selectedSection={selectedSection}
|
||||
setSelectedSection={setSelectedSection}
|
||||
/>
|
||||
<LumpToolbar />
|
||||
|
||||
<ContentDiv
|
||||
className="no-scrollbar pr-0.5"
|
||||
hasSection={!!selectedSection}
|
||||
isVisible={isVisible}
|
||||
isVisible={isLumpVisible}
|
||||
>
|
||||
<SelectedSection selectedSection={displayedSection} />
|
||||
<SelectedSection />
|
||||
</ContentDiv>
|
||||
</div>
|
||||
</LumpDiv>
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ export function ExploreBlocksButton(props: { blockType: string }) {
|
|||
|
||||
return (
|
||||
<GhostButton
|
||||
className="w-full cursor-pointer rounded px-2 text-center text-gray-400 hover:text-gray-300"
|
||||
className="w-full cursor-pointer rounded px-2 py-0.5 text-center text-gray-400 hover:text-gray-300"
|
||||
style={{
|
||||
fontSize: fontSize(-3),
|
||||
}}
|
||||
|
|
@ -60,7 +60,8 @@ export function ExploreBlocksButton(props: { blockType: string }) {
|
|||
}}
|
||||
>
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Icon className="h-3 w-3" /> {text}
|
||||
<Icon className="h-2.5 w-2.5 pr-1" />
|
||||
<span className="text-[11px]">{text}</span>
|
||||
</div>
|
||||
</GhostButton>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -3,44 +3,74 @@ import {
|
|||
PencilIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
|
||||
import { SlashCommandDescription } from "core";
|
||||
import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { fontSize } from "../../../../util";
|
||||
import { useMainEditor } from "../../TipTapEditor";
|
||||
import { useLump } from "../LumpContext";
|
||||
import { ExploreBlocksButton } from "./ExploreBlocksButton";
|
||||
|
||||
interface PromptRowProps {
|
||||
command: string;
|
||||
description: string;
|
||||
prompt: SlashCommandDescription;
|
||||
isBookmarked: boolean;
|
||||
setIsBookmarked: (isBookmarked: boolean) => void;
|
||||
onEdit?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a single prompt row with bookmark and edit controls
|
||||
*/
|
||||
function PromptRow({
|
||||
command,
|
||||
description,
|
||||
prompt,
|
||||
isBookmarked,
|
||||
setIsBookmarked,
|
||||
onEdit,
|
||||
}: PromptRowProps) {
|
||||
const { mainEditor } = useMainEditor();
|
||||
const { hideLump } = useLump();
|
||||
|
||||
const handlePromptClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
mainEditor?.commands.insertPrompt(prompt);
|
||||
hideLump();
|
||||
};
|
||||
|
||||
const handleBookmarkClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsBookmarked(!isBookmarked);
|
||||
};
|
||||
|
||||
const handleEditClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (onEdit) {
|
||||
onEdit();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-between gap-3"
|
||||
className="hover:bg-list-active hover:text-list-active-foreground flex items-center justify-between gap-3 rounded-md px-2 py-1 hover:cursor-pointer"
|
||||
onClick={handlePromptClick}
|
||||
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 className="flex min-w-0 flex-col">
|
||||
<span className="text-vscForeground shrink-0 font-medium">
|
||||
{prompt.name}
|
||||
</span>
|
||||
<span className="line-clamp-2 text-[11px] text-gray-400">
|
||||
{prompt.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}
|
||||
onClick={handleEditClick}
|
||||
/>
|
||||
<div
|
||||
onClick={() => setIsBookmarked(!isBookmarked)}
|
||||
onClick={handleBookmarkClick}
|
||||
className="cursor-pointer pt-0.5 text-gray-400 hover:brightness-125"
|
||||
>
|
||||
{isBookmarked ? (
|
||||
|
|
@ -54,8 +84,12 @@ function PromptRow({
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section that displays all available prompts with bookmarking functionality
|
||||
*/
|
||||
export function PromptsSection() {
|
||||
const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands();
|
||||
|
||||
const slashCommands = useAppSelector(
|
||||
(state) => state.config.config.slashCommands ?? [],
|
||||
);
|
||||
|
|
@ -78,8 +112,7 @@ export function PromptsSection() {
|
|||
{sortedCommands.map((prompt) => (
|
||||
<PromptRow
|
||||
key={prompt.name}
|
||||
command={prompt.name}
|
||||
description={prompt.description}
|
||||
prompt={prompt}
|
||||
isBookmarked={isCommandBookmarked(prompt.name)}
|
||||
setIsBookmarked={() => toggleBookmark(prompt)}
|
||||
onEdit={() => handleEdit(prompt)}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { parseConfigYaml } from "@continuedev/config-yaml";
|
||||
import { parseConfigYaml, Rule } from "@continuedev/config-yaml";
|
||||
import { ArrowsPointingOutIcon, PencilIcon } from "@heroicons/react/24/outline";
|
||||
import { useContext, useMemo } from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
|
|
@ -13,11 +13,12 @@ import {
|
|||
import { RootState } from "../../../../redux/store";
|
||||
import { fontSize } from "../../../../util";
|
||||
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
|
||||
import { useLump } from "../LumpContext";
|
||||
import { ExploreBlocksButton } from "./ExploreBlocksButton";
|
||||
|
||||
interface RuleCardProps {
|
||||
index: number;
|
||||
rule: string;
|
||||
rule: Rule;
|
||||
onClick: () => void;
|
||||
title: string;
|
||||
}
|
||||
|
|
@ -31,12 +32,32 @@ const RuleCard: React.FC<RuleCardProps> = ({ index, rule, onClick, title }) => {
|
|||
setDialogMessage(
|
||||
<div className="p-4 text-center">
|
||||
<h3>{title}</h3>
|
||||
<pre className="max-w-full overflow-x-scroll">{rule}</pre>
|
||||
<pre className="max-w-full overflow-x-scroll">
|
||||
{/** TODO: Render the rule in a more readable way */}
|
||||
{JSON.stringify(rule)}
|
||||
</pre>
|
||||
</div>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const renderRuleContent = () => {
|
||||
if (typeof rule === "string") {
|
||||
return <div>{rule}</div>;
|
||||
}
|
||||
|
||||
if (rule.rule) {
|
||||
return (
|
||||
<div>
|
||||
<div>{rule.rule}</div>
|
||||
{rule.if && <div className="text-gray-500">if: {rule.if}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <div>{JSON.stringify(rule)}</div>;
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
|
|
@ -62,7 +83,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ index, rule, onClick, title }) => {
|
|||
}}
|
||||
className="line-clamp-3 text-gray-400"
|
||||
>
|
||||
{rule}
|
||||
{renderRuleContent()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
|
|
@ -82,6 +103,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ index, rule, onClick, title }) => {
|
|||
export function RulesSection() {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { selectedProfile } = useAuth();
|
||||
const { hideLump } = useLump();
|
||||
|
||||
const rules = useSelector(
|
||||
(state: RootState) => state.config.config.rules ?? [],
|
||||
|
|
@ -97,11 +119,13 @@ export function RulesSection() {
|
|||
}));
|
||||
}, [rules]);
|
||||
|
||||
const openUrl = (path: string) =>
|
||||
const openUrl = (path: string) => {
|
||||
ideMessenger.request("controlPlane/openUrl", {
|
||||
path,
|
||||
orgSlug: undefined,
|
||||
});
|
||||
hideLump();
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
|
@ -113,11 +137,12 @@ export function RulesSection() {
|
|||
key={index}
|
||||
index={index}
|
||||
rule={rule.unrolledRule}
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
})
|
||||
}
|
||||
});
|
||||
hideLump();
|
||||
}}
|
||||
title="Locally Defined Rule"
|
||||
/>
|
||||
);
|
||||
|
|
@ -137,27 +162,25 @@ export function RulesSection() {
|
|||
);
|
||||
}
|
||||
|
||||
if (!rule.ruleFromYaml?.uses) {
|
||||
return null;
|
||||
if ("uses" in rule.ruleFromYaml) {
|
||||
const ruleSlug = rule.ruleFromYaml?.uses;
|
||||
|
||||
return (
|
||||
<RuleCard
|
||||
key={index}
|
||||
index={index}
|
||||
rule={rule.unrolledRule}
|
||||
onClick={() => openUrl(`${ruleSlug}/new-version`)}
|
||||
title={ruleSlug}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const ruleSlug = rule.ruleFromYaml?.uses;
|
||||
|
||||
return (
|
||||
<RuleCard
|
||||
key={index}
|
||||
index={index}
|
||||
rule={rule.unrolledRule}
|
||||
onClick={() => openUrl(`${ruleSlug}/new-version`)}
|
||||
title={ruleSlug}
|
||||
/>
|
||||
);
|
||||
// TODO: Handle rules as object with 'if'
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
<ExploreBlocksButton blockType="rules" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function useTypedDispatch() {
|
||||
throw new Error("Function not implemented.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { useLump } from "../LumpContext";
|
||||
import { ContextSection } from "./ContextSection";
|
||||
import DocsSection from "./docs/DocsSection";
|
||||
import { MCPSection } from "./MCPSection";
|
||||
|
|
@ -6,12 +7,13 @@ import { PromptsSection } from "./PromptsSection";
|
|||
import { RulesSection } from "./RulesSection";
|
||||
import { ToolPoliciesSection } from "./tool-policies/ToolPoliciesSection";
|
||||
|
||||
interface SelectedSectionProps {
|
||||
selectedSection: string | null;
|
||||
}
|
||||
/**
|
||||
* Renders the appropriate section based on the selected section in the Lump context
|
||||
*/
|
||||
export function SelectedSection() {
|
||||
const { displayedSection } = useLump();
|
||||
|
||||
export function SelectedSection(props: SelectedSectionProps) {
|
||||
switch (props.selectedSection) {
|
||||
switch (displayedSection) {
|
||||
case "models":
|
||||
return <ModelsSection />;
|
||||
case "rules":
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
import { fontSize } from "../../../../../util";
|
||||
import ConfirmationDialog from "../../../../dialogs/ConfirmationDialog";
|
||||
import EditBlockButton from "../../EditBlockButton";
|
||||
import { useLump } from "../../LumpContext";
|
||||
import { StatusIndicator } from "./StatusIndicator";
|
||||
interface IndexingStatusViewerProps {
|
||||
docConfig: SiteIndexingConfig;
|
||||
|
|
@ -24,6 +25,7 @@ function DocsIndexingStatus({
|
|||
}: IndexingStatusViewerProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const dispatch = useAppDispatch();
|
||||
const { hideLump } = useLump();
|
||||
|
||||
const status = useAppSelector(
|
||||
(store) => store.indexing.indexing.statuses[docConfig.startUrl],
|
||||
|
|
@ -78,7 +80,7 @@ function DocsIndexingStatus({
|
|||
if (hasDeleted) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-2 flex w-full flex-col">
|
||||
<div className="mt-1 flex w-full flex-col">
|
||||
<div
|
||||
className={`flex flex-row items-center justify-between gap-2 text-sm`}
|
||||
>
|
||||
|
|
@ -87,16 +89,10 @@ function DocsIndexingStatus({
|
|||
onClick={() => {
|
||||
if (status?.url) {
|
||||
ideMessenger.post("openUrl", status.url);
|
||||
hideLump();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{docConfig.faviconUrl ? (
|
||||
<img
|
||||
src={docConfig.faviconUrl}
|
||||
alt="doc icon"
|
||||
className="h-3 w-3"
|
||||
/>
|
||||
) : null}
|
||||
<p
|
||||
style={{
|
||||
fontSize: fontSize(-3),
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ function DocsIndexingStatuses() {
|
|||
(store) => store.indexing.indexing.statuses,
|
||||
);
|
||||
const { selectedProfile } = useAuth();
|
||||
|
||||
const mergedDocs = useMemo(() => {
|
||||
const parsed = selectedProfile?.rawYaml
|
||||
? parseConfigYaml(selectedProfile?.rawYaml ?? "")
|
||||
|
|
|
|||
117
gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx
Normal file
117
gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import { Editor } from "@tiptap/react";
|
||||
import { InputModifiers } from "core";
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { setMainEditorContentTrigger } from "../../../redux/slices/sessionSlice";
|
||||
import { useMainEditorWebviewListeners } from "./useMainEditorWebviewListeners";
|
||||
|
||||
/**
|
||||
* Context for accessing the main editor instance
|
||||
*/
|
||||
interface MainEditorContextType {
|
||||
/** The current main editor instance */
|
||||
mainEditor: Editor | null;
|
||||
/** Set the current main editor instance */
|
||||
setMainEditor: (editor: Editor | null) => void;
|
||||
/** The current input ID */
|
||||
inputId: string | null;
|
||||
/** Set the current input ID */
|
||||
setInputId: (id: string) => void;
|
||||
/** Reference to the execute content function */
|
||||
onEnterRef: React.MutableRefObject<(modifiers: InputModifiers) => void>;
|
||||
}
|
||||
|
||||
const MainEditorContext = createContext<MainEditorContextType | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
/**
|
||||
* Provider component that maintains a reference to the main editor
|
||||
*/
|
||||
export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const dispatch = useAppDispatch();
|
||||
const [mainEditor, setMainEditorInternal] = useState<Editor | null>(null);
|
||||
const [inputId, setInputId] = useState<string | null>(null);
|
||||
const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {});
|
||||
const editorFocusedRef = useRef<boolean>(false);
|
||||
const historyLength = useAppSelector((store) => store.session.history.length);
|
||||
|
||||
// Listen for changes to mainEditorContentTrigger in Redux
|
||||
const mainEditorContentTrigger = useAppSelector(
|
||||
(store) => store.session.mainEditorContentTrigger,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (mainEditor && mainEditorContentTrigger) {
|
||||
queueMicrotask(() => {
|
||||
mainEditor.commands.setContent(mainEditorContentTrigger);
|
||||
});
|
||||
// Clear the trigger after using it
|
||||
dispatch(setMainEditorContentTrigger(undefined));
|
||||
}
|
||||
}, [mainEditor, mainEditorContentTrigger, dispatch]);
|
||||
|
||||
// Update focused ref when editor focus state changes
|
||||
useEffect(() => {
|
||||
if (mainEditor) {
|
||||
const updateFocus = () => {
|
||||
editorFocusedRef.current = mainEditor.isFocused || false;
|
||||
};
|
||||
|
||||
mainEditor.on("focus", updateFocus);
|
||||
mainEditor.on("blur", updateFocus);
|
||||
|
||||
return () => {
|
||||
mainEditor.off("focus", updateFocus);
|
||||
mainEditor.off("blur", updateFocus);
|
||||
};
|
||||
}
|
||||
}, [mainEditor]);
|
||||
|
||||
// Set up main editor webview listeners when we have a valid editor and input ID
|
||||
useMainEditorWebviewListeners({
|
||||
editor: mainEditor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
inputId: inputId || "",
|
||||
editorFocusedRef,
|
||||
});
|
||||
|
||||
const setMainEditor = (newEditor: Editor | null) => {
|
||||
setMainEditorInternal(newEditor);
|
||||
};
|
||||
|
||||
const value: MainEditorContextType = {
|
||||
mainEditor,
|
||||
setMainEditor,
|
||||
inputId,
|
||||
setInputId,
|
||||
onEnterRef,
|
||||
};
|
||||
|
||||
return (
|
||||
<MainEditorContext.Provider value={value}>
|
||||
{children}
|
||||
</MainEditorContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to access the main editor context
|
||||
*/
|
||||
export const useMainEditor = (): MainEditorContextType => {
|
||||
const context = useContext(MainEditorContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useMainEditor must be used within a MainEditorProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
|
@ -7,19 +7,15 @@ import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
|
|||
import useUpdatingRef from "../../../hooks/useUpdatingRef";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { selectDefaultModel } from "../../../redux/slices/configSlice";
|
||||
import {
|
||||
selectIsInEditMode,
|
||||
setMainEditorContentTrigger,
|
||||
} from "../../../redux/slices/sessionSlice";
|
||||
import { selectIsInEditMode } from "../../../redux/slices/sessionSlice";
|
||||
import InputToolbar, { ToolbarOptions } from "../InputToolbar";
|
||||
import { ComboBoxItem } from "../types";
|
||||
import { DragOverlay } from "./DragOverlay";
|
||||
import { createEditorConfig, getPlaceholderText } from "./editorConfig";
|
||||
import { handleImageFile } from "./imageUtils";
|
||||
import { useEditorEventHandlers } from "./keyHandlers";
|
||||
import { InputBoxDiv } from "./StyledComponents";
|
||||
import { DragOverlay, InputBoxDiv } from "./components";
|
||||
import { useMainEditor } from "./MainEditorProvider";
|
||||
import "./TipTapEditor.css";
|
||||
import { useWebviewListeners } from "./useWebviewListeners";
|
||||
import { handleImageFile } from "./utils";
|
||||
import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig";
|
||||
import { useEditorEventHandlers } from "./utils/keyHandlers";
|
||||
|
||||
export interface TipTapEditorProps {
|
||||
availableContextProviders: ContextProviderDescription[];
|
||||
|
|
@ -34,13 +30,17 @@ export interface TipTapEditorProps {
|
|||
toolbarOptions?: ToolbarOptions;
|
||||
placeholder?: string;
|
||||
historyKey: string;
|
||||
|
||||
// TODO: This isn't actually used anywhere in this component, but it appears
|
||||
// to be pulled into some of our TipTap extensions.
|
||||
inputId: string;
|
||||
}
|
||||
|
||||
export const TIPPY_DIV_ID = "tippy-js-div";
|
||||
|
||||
function TipTapEditor(props: TipTapEditorProps) {
|
||||
export function TipTapEditor(props: TipTapEditorProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
const mainEditorContext = useMainEditor();
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
|
|
@ -57,6 +57,15 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
dispatch,
|
||||
});
|
||||
|
||||
// Register the main editor with the provider
|
||||
useEffect(() => {
|
||||
if (props.isMainInput && editor) {
|
||||
mainEditorContext.setMainEditor(editor);
|
||||
mainEditorContext.setInputId(props.inputId);
|
||||
mainEditorContext.onEnterRef.current = onEnterRef.current;
|
||||
}
|
||||
}, [editor, props.isMainInput, props.inputId, mainEditorContext, onEnterRef]);
|
||||
|
||||
const [shouldHideToolbar, setShouldHideToolbar] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -101,30 +110,6 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
}
|
||||
}, [props.isMainInput, isStreaming, editor]);
|
||||
|
||||
// This allows anywhere in the app to set the content of the main input
|
||||
const mainInputContentTrigger = useAppSelector(
|
||||
(store) => store.session.mainEditorContentTrigger,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!props.isMainInput || !mainInputContentTrigger) {
|
||||
return;
|
||||
}
|
||||
queueMicrotask(() => {
|
||||
editor?.commands.setContent(mainInputContentTrigger);
|
||||
});
|
||||
dispatch(setMainEditorContentTrigger(undefined));
|
||||
}, [editor, props.isMainInput, mainInputContentTrigger]);
|
||||
|
||||
// IDE event listeners
|
||||
useWebviewListeners({
|
||||
editor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
props,
|
||||
editorFocusedRef,
|
||||
});
|
||||
|
||||
const [showDragOverMsg, setShowDragOverMsg] = useState(false);
|
||||
|
||||
const [activeKey, setActiveKey] = useState<string | null>(null);
|
||||
|
|
@ -150,7 +135,6 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
editor,
|
||||
isOSREnabled: isOSREnabled,
|
||||
editorFocusedRef,
|
||||
isInEditMode,
|
||||
setActiveKey,
|
||||
});
|
||||
|
||||
|
|
@ -187,9 +171,6 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
setShouldHideToolbar(false);
|
||||
}, [cancelBlurTimeout]);
|
||||
|
||||
// TODO pass clear blur timeout to model and mode selectors
|
||||
// Seems like unnecessary for now?
|
||||
|
||||
return (
|
||||
<InputBoxDiv
|
||||
onFocus={handleFocus}
|
||||
|
|
@ -294,5 +275,3 @@ function TipTapEditor(props: TipTapEditorProps) {
|
|||
</InputBoxDiv>
|
||||
);
|
||||
}
|
||||
|
||||
export default TipTapEditor;
|
||||
|
|
@ -0,0 +1,235 @@
|
|||
import {
|
||||
ChevronDownIcon,
|
||||
EyeSlashIcon,
|
||||
XMarkIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { EyeIcon } from "@heroicons/react/24/solid";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
lightGray,
|
||||
vscBadgeBackground,
|
||||
vscCommandCenterInactiveBorder,
|
||||
vscEditorBackground,
|
||||
} from "../../..";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { getFontSize } from "../../../../util";
|
||||
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
|
||||
|
||||
const MAX_PREVIEW_HEIGHT = 100;
|
||||
const MAX_EXPANED_PREVIEW_HEIGHT = MAX_PREVIEW_HEIGHT * 3;
|
||||
|
||||
const PreviewDiv = styled.div<{
|
||||
borderColor?: string;
|
||||
}>`
|
||||
background-color: ${vscEditorBackground};
|
||||
border-radius: ${defaultBorderRadius};
|
||||
border: 0.5px solid ${(props) => props.borderColor || lightGray};
|
||||
margin-top: 4px;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
& div {
|
||||
background-color: ${vscEditorBackground};
|
||||
}
|
||||
`;
|
||||
|
||||
const ContentContainer = styled.div<{ expanded: boolean }>`
|
||||
position: relative;
|
||||
max-height: ${(props) =>
|
||||
props.expanded
|
||||
? `${MAX_EXPANED_PREVIEW_HEIGHT}px`
|
||||
: `${MAX_PREVIEW_HEIGHT}px`};
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
`;
|
||||
|
||||
const ScrollableContent = styled.div<{ shouldShowChevron: boolean }>`
|
||||
overflow-y: auto;
|
||||
padding-bottom: ${(props) => (props.shouldShowChevron ? "24px" : "0px")};
|
||||
`;
|
||||
|
||||
const ChevronContainer = styled.div`
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
background: ${vscEditorBackground};
|
||||
padding: 4px 0;
|
||||
z-index: 10;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Props for the ExpandableToolbarPreview component
|
||||
*/
|
||||
interface ExpandableToolbarPreviewProps {
|
||||
/** Title to display in the header */
|
||||
title: string;
|
||||
/** Optional icon to display next to the title */
|
||||
icon?: React.ReactNode;
|
||||
/** ID of the input this preview is associated with (for toolbar hiding logic) */
|
||||
inputId?: string;
|
||||
/** ID of the item being displayed (for toolbar hiding logic) */
|
||||
itemId?: string;
|
||||
/** Whether the preview is initially hidden (overridden if inputId and itemId are provided) */
|
||||
initiallyHidden?: boolean;
|
||||
/** Callback when the delete button is clicked */
|
||||
onDelete?: () => void;
|
||||
/** Callback when the title is clicked */
|
||||
onTitleClick?: (e: React.MouseEvent) => void;
|
||||
/** Border color of the preview */
|
||||
borderColor?: string;
|
||||
/* Whether the preview is selected */
|
||||
isSelected?: boolean;
|
||||
/** Content to display in the preview */
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* A generalized expandable preview component for displaying content with a header and expandable body
|
||||
*/
|
||||
export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) {
|
||||
// Get toolbar visibility state from Redux if inputId and itemId are provided
|
||||
const newestCodeblockForInputId = useAppSelector((store) =>
|
||||
props.inputId
|
||||
? store.session.newestToolbarPreviewForInput[props.inputId]
|
||||
: undefined,
|
||||
);
|
||||
|
||||
const calculatedInitiallyHidden = useMemo(() => {
|
||||
// If initiallyHidden is explicitly set to false, always start visible
|
||||
if (props.initiallyHidden === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Otherwise, use the inputId/itemId logic
|
||||
if (props.inputId && props.itemId) {
|
||||
return newestCodeblockForInputId !== props.itemId;
|
||||
}
|
||||
return props.initiallyHidden ?? false;
|
||||
}, [
|
||||
newestCodeblockForInputId,
|
||||
props.inputId,
|
||||
props.itemId,
|
||||
props.initiallyHidden,
|
||||
]);
|
||||
|
||||
const [hidden, setHidden] = useState(calculatedInitiallyHidden);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
// Track if user has manually toggled visibility
|
||||
const [userToggled, setUserToggled] = useState(false);
|
||||
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [contentDims, setContentDims] = useState({ width: 0, height: 0 });
|
||||
|
||||
useEffect(() => {
|
||||
// Only update hidden state from props if user hasn't manually toggled
|
||||
// or if initiallyHidden isn't explicitly set to false
|
||||
if (!userToggled || props.initiallyHidden !== false) {
|
||||
setHidden(calculatedInitiallyHidden);
|
||||
}
|
||||
}, [calculatedInitiallyHidden, userToggled, props.initiallyHidden]);
|
||||
useEffect(() => {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
setContentDims({
|
||||
width: contentRef.current?.scrollWidth ?? 0,
|
||||
height: contentRef.current?.scrollHeight ?? 0,
|
||||
});
|
||||
});
|
||||
|
||||
if (contentRef.current) {
|
||||
resizeObserver.observe(contentRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [contentRef]);
|
||||
|
||||
return (
|
||||
<PreviewDiv
|
||||
spellCheck={false}
|
||||
borderColor={
|
||||
props.isSelected ? vscBadgeBackground : vscCommandCenterInactiveBorder
|
||||
}
|
||||
className="find-widget-skip !my-0"
|
||||
>
|
||||
<div
|
||||
className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
|
||||
style={{
|
||||
fontSize: getFontSize() - 3,
|
||||
}}
|
||||
onClick={() => {
|
||||
setUserToggled(true);
|
||||
setHidden(!hidden);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex items-center gap-1 text-[11px] hover:underline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (props.onTitleClick) {
|
||||
props.onTitleClick(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{props.icon}
|
||||
{props.title}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<HeaderButtonWithToolTip text={hidden ? "Show" : "Hide"}>
|
||||
{hidden ? (
|
||||
<EyeIcon className="h-2.5 w-2.5" />
|
||||
) : (
|
||||
<EyeSlashIcon className="h-2.5 w-2.5" />
|
||||
)}
|
||||
</HeaderButtonWithToolTip>
|
||||
{props.onDelete && (
|
||||
<HeaderButtonWithToolTip
|
||||
text="Delete"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
props.onDelete?.();
|
||||
}}
|
||||
>
|
||||
<XMarkIcon className="h-2.5 w-2.5" />
|
||||
</HeaderButtonWithToolTip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hidden && (
|
||||
<ContentContainer expanded={isExpanded}>
|
||||
<ScrollableContent
|
||||
ref={contentRef}
|
||||
shouldShowChevron={contentDims.height > MAX_PREVIEW_HEIGHT}
|
||||
>
|
||||
{props.children}
|
||||
</ScrollableContent>
|
||||
|
||||
{contentDims.height > MAX_PREVIEW_HEIGHT && (
|
||||
<ChevronContainer>
|
||||
<HeaderButtonWithToolTip
|
||||
text={isExpanded ? "Collapse" : "Expand"}
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className="h-3 w-3 transition-all"
|
||||
style={{
|
||||
transform: isExpanded ? "rotate(180deg)" : "",
|
||||
}}
|
||||
onClick={() => setIsExpanded((v) => !v)}
|
||||
/>
|
||||
</HeaderButtonWithToolTip>
|
||||
</ChevronContainer>
|
||||
)}
|
||||
</ContentContainer>
|
||||
)}
|
||||
</PreviewDiv>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import {
|
||||
NodeViewWrapper as TiptapNodeViewWrapper,
|
||||
NodeViewWrapperProps as TiptapNodeViewWrapperProps,
|
||||
} from "@tiptap/react";
|
||||
import React from "react";
|
||||
|
||||
interface NodeViewWrapperProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const NodeViewWrapper: React.FC<NodeViewWrapperProps> = ({
|
||||
children,
|
||||
}) => {
|
||||
// Not setting this as a "p" will cause issues with foreign keyboards
|
||||
// See https://github.com/continuedev/continue/issues/3199
|
||||
const nodeViewWrapperTag: TiptapNodeViewWrapperProps["as"] = "p";
|
||||
|
||||
return (
|
||||
<TiptapNodeViewWrapper className="my-1.5" as={nodeViewWrapperTag}>
|
||||
{children}
|
||||
</TiptapNodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -8,8 +8,8 @@ import {
|
|||
vscForeground,
|
||||
vscInputBackground,
|
||||
vscInputBorderFocus,
|
||||
} from "../..";
|
||||
import { getFontSize } from "../../../util";
|
||||
} from "../../..";
|
||||
import { getFontSize } from "../../../../util";
|
||||
|
||||
export const InputBoxDiv = styled.div<{}>`
|
||||
resize: none;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export * from "./DragOverlay";
|
||||
export * from "./ExpandableToolbarPreview";
|
||||
export * from "./StyledComponents";
|
||||
|
|
@ -1,25 +1,16 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type MentionOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderHTML: (props: {
|
||||
options: MentionOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => DOMOutputSpec;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
|
||||
export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit");
|
||||
import Suggestion from "@tiptap/suggestion";
|
||||
import { MentionOptions } from "./types";
|
||||
|
||||
export const AddCodeToEdit = Node.create<MentionOptions>({
|
||||
name: "add-code-to-edit",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
HTMLAttributes: {
|
||||
class: "add-code-to-edit",
|
||||
},
|
||||
renderHTML({ options, node }) {
|
||||
return [
|
||||
"span",
|
||||
|
|
@ -29,7 +20,7 @@ export const AddCodeToEdit = Node.create<MentionOptions>({
|
|||
},
|
||||
suggestion: {
|
||||
char: "#",
|
||||
pluginKey: AddCodeToEditPluginKey,
|
||||
pluginKey: new PluginKey(this.name),
|
||||
allow: ({ state, range }) => {
|
||||
const $from = state.doc.resolve(range.from);
|
||||
const type = state.schema.nodes[this.name];
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { ReactNodeViewRenderer } from "@tiptap/react";
|
||||
import { CodeBlockComponent } from "../CodeBlockComponent";
|
||||
import { CodeBlockPreview } from "./CodeBlockPreview";
|
||||
|
||||
export const CodeBlockExtension = Node.create({
|
||||
name: "codeBlock",
|
||||
export const CodeBlock = Node.create({
|
||||
name: "code-block",
|
||||
|
||||
group: "block",
|
||||
|
||||
|
|
@ -37,6 +37,6 @@ export const CodeBlockExtension = Node.create({
|
|||
},
|
||||
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(CodeBlockComponent);
|
||||
return ReactNodeViewRenderer(CodeBlockPreview);
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
import { NodeViewProps } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { useContext, useMemo } from "react";
|
||||
import { vscBadgeBackground } from "../../../..";
|
||||
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
|
||||
import FileIcon from "../../../../FileIcon";
|
||||
import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview";
|
||||
import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview";
|
||||
import { NodeViewWrapper } from "../../components/NodeViewWrapper";
|
||||
|
||||
const backticksRegex = /`{3,}/gm;
|
||||
|
||||
/**
|
||||
* Component for displaying a code block in the TipTap editor
|
||||
*/
|
||||
export const CodeBlockPreview = ({
|
||||
node,
|
||||
deleteNode,
|
||||
selected,
|
||||
}: NodeViewProps) => {
|
||||
const item: ContextItemWithId = node.attrs.item;
|
||||
const inputId = node.attrs.inputId;
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const content = useMemo(() => {
|
||||
return dedent`${item.content}`;
|
||||
}, [item.content]);
|
||||
|
||||
const fence = useMemo(() => {
|
||||
const backticks = content.match(backticksRegex);
|
||||
return backticks ? backticks.sort().at(-1) + "`" : "```";
|
||||
}, [content]);
|
||||
|
||||
const handleTitleClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
if (item.id.providerTitle === "file" && item.uri?.value) {
|
||||
ideMessenger.post("showFile", {
|
||||
filepath: item.uri.value,
|
||||
});
|
||||
} else if (item.id.providerTitle === "code") {
|
||||
const rif = ctxItemToRifWithContents(item, true);
|
||||
ideMessenger.ide.showLines(
|
||||
rif.filepath,
|
||||
rif.range.start.line,
|
||||
rif.range.end.line,
|
||||
);
|
||||
} else {
|
||||
ideMessenger.post("showVirtualFile", {
|
||||
content: item.content,
|
||||
name: item.name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<NodeViewWrapper>
|
||||
<ExpandableToolbarPreview
|
||||
isSelected={selected}
|
||||
title={item.name}
|
||||
icon={<FileIcon height="16px" width="16px" filename={item.name} />}
|
||||
inputId={inputId}
|
||||
itemId={item.id.itemId}
|
||||
onDelete={() => deleteNode()}
|
||||
borderColor={selected ? vscBadgeBackground : undefined}
|
||||
onTitleClick={handleTitleClick}
|
||||
>
|
||||
<StyledMarkdownPreview
|
||||
source={`${fence}${getMarkdownLanguageTagForFile(item.name)} ${item.description}\n${content}\n${fence}`}
|
||||
/>
|
||||
</ExpandableToolbarPreview>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
export * from "./CodeBlock";
|
||||
|
|
@ -1,25 +1,17 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type MentionOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderHTML: (props: {
|
||||
options: MentionOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => DOMOutputSpec;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
|
||||
export const MentionPluginKey = new PluginKey("mention");
|
||||
import Suggestion from "@tiptap/suggestion";
|
||||
import { MentionOptions } from "./types";
|
||||
|
||||
export const Mention = Node.create<MentionOptions>({
|
||||
name: "mention",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
HTMLAttributes: {
|
||||
class: "mention",
|
||||
},
|
||||
|
||||
renderHTML({ options, node }) {
|
||||
return [
|
||||
"span",
|
||||
|
|
@ -29,7 +21,7 @@ export const Mention = Node.create<MentionOptions>({
|
|||
},
|
||||
suggestion: {
|
||||
char: "@",
|
||||
pluginKey: MentionPluginKey,
|
||||
pluginKey: new PluginKey(this.name),
|
||||
command: ({ editor, range, props }) => {
|
||||
// increase range.to by one when the next node is of type "text"
|
||||
// and starts with a space character
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { ReactNodeViewRenderer } from "@tiptap/react";
|
||||
import { ContextItemWithId, SlashCommandDescription } from "core";
|
||||
import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat";
|
||||
import { PromptBlockPreview } from "./PromptBlockPreview";
|
||||
|
||||
export interface PromptBlockOptions {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface PromptBlockAttributes {
|
||||
item: ContextItemWithId;
|
||||
inputId: string;
|
||||
}
|
||||
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
promptBlock: {
|
||||
/**
|
||||
* Insert a prompt block into the editor
|
||||
*/
|
||||
insertPrompt: (item: SlashCommandDescription) => ReturnType;
|
||||
|
||||
/**
|
||||
* Clear all prompt blocks from the editor
|
||||
*/
|
||||
clearPrompt: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension for adding prompt blocks to the TipTap editor
|
||||
*/
|
||||
export const PromptBlock = Node.create<PromptBlockOptions>({
|
||||
name: "prompt-block",
|
||||
group: "block",
|
||||
content: "inline*",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {
|
||||
class: "prompt-block",
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
item: {
|
||||
default: null,
|
||||
},
|
||||
inputId: {
|
||||
default: null,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [
|
||||
{
|
||||
tag: "prompt-block",
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
return ["prompt-block", mergeAttributes(HTMLAttributes), 0];
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(PromptBlockPreview);
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
insertPrompt:
|
||||
(prompt: SlashCommandDescription) =>
|
||||
({ chain }) => {
|
||||
const item: ContextItemWithId = {
|
||||
content: prompt.prompt ?? "",
|
||||
name: prompt.name,
|
||||
description: prompt.description,
|
||||
id: {
|
||||
providerTitle: "prompt",
|
||||
itemId: prompt.name,
|
||||
},
|
||||
};
|
||||
|
||||
return chain()
|
||||
.insertContentAt(0, {
|
||||
type: this.name,
|
||||
attrs: {
|
||||
item,
|
||||
inputId: MAIN_EDITOR_INPUT_ID,
|
||||
},
|
||||
})
|
||||
.focus("end")
|
||||
.run();
|
||||
},
|
||||
|
||||
// TODO: This could probably be greatly simplified with something along the lines of
|
||||
// `editor.commands.deleteNode(this.name)`, but was unable to get it working
|
||||
clearPrompt:
|
||||
() =>
|
||||
({ state, commands }) => {
|
||||
// Find all prompt-block nodes in the document
|
||||
const promptNodes: { pos: number; node: ProseMirrorNode }[] = [];
|
||||
state.doc.descendants((node, pos) => {
|
||||
if (node.type.name === this.name) {
|
||||
promptNodes.push({ pos, node });
|
||||
return false; // Don't descend into this node
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Delete all found prompt blocks
|
||||
// We process them in reverse order so that deleting one doesn't affect the position of others
|
||||
for (let i = promptNodes.length - 1; i >= 0; i--) {
|
||||
const { pos, node } = promptNodes[i];
|
||||
commands.deleteRange({ from: pos, to: pos + node.nodeSize });
|
||||
}
|
||||
|
||||
// Return true if we deleted any nodes
|
||||
return promptNodes.length > 0;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
|
||||
import { NodeViewProps } from "@tiptap/react";
|
||||
import { useContext } from "react";
|
||||
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
|
||||
import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview";
|
||||
import { NodeViewWrapper } from "../../components/NodeViewWrapper";
|
||||
import { PromptBlockAttributes } from "./PromptBlock";
|
||||
|
||||
/**
|
||||
* Component for prompt blocks in the Tiptap editor
|
||||
*/
|
||||
export const PromptBlockPreview = ({
|
||||
node,
|
||||
selected,
|
||||
editor,
|
||||
}: NodeViewProps) => {
|
||||
const { item, inputId } = node.attrs as PromptBlockAttributes;
|
||||
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const handleTitleClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
ideMessenger.post("showVirtualFile", {
|
||||
content: item.content,
|
||||
name: item.name,
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
editor.commands.clearPrompt();
|
||||
};
|
||||
|
||||
return (
|
||||
<NodeViewWrapper>
|
||||
<ExpandableToolbarPreview
|
||||
initiallyHidden={false}
|
||||
isSelected={selected}
|
||||
title={item.name}
|
||||
icon={<ChatBubbleLeftIcon className="h-3 w-3 pl-1 pr-0.5" />}
|
||||
inputId={inputId}
|
||||
itemId={item.id.itemId}
|
||||
onDelete={handleDelete}
|
||||
onTitleClick={handleTitleClick}
|
||||
>
|
||||
<div className="whitespace-pre-wrap px-3 py-1 text-xs">
|
||||
{item.content}
|
||||
</div>
|
||||
</ExpandableToolbarPreview>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
export * from "./PromptBlock";
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts)
|
||||
|
||||
import { Node } from "@tiptap/core";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
import { ComboBoxItem } from "../../types";
|
||||
|
||||
export type SlashCommandOptions = {
|
||||
suggestion: Omit<SuggestionOptions<ComboBoxItem, ComboBoxItem>, "editor">;
|
||||
};
|
||||
|
||||
export const SlashCommand = Node.create<SlashCommandOptions>({
|
||||
name: "slash-command",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
suggestion: {
|
||||
char: "/",
|
||||
pluginKey: new PluginKey(this.name),
|
||||
startOfLine: true,
|
||||
command: ({ editor, range, props }) => {
|
||||
// First delete the slash character and any text after it
|
||||
editor.chain().focus().deleteRange(range).run();
|
||||
|
||||
editor.commands.insertPrompt({
|
||||
name: props.title,
|
||||
description: props.description,
|
||||
prompt: props.content,
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
group: "inline",
|
||||
inline: true,
|
||||
selectable: false,
|
||||
atom: true,
|
||||
|
||||
// We don't need attributes since we won't be rendering any node
|
||||
addAttributes() {
|
||||
return {};
|
||||
},
|
||||
|
||||
// No need to parse HTML since we're not rendering anything
|
||||
parseHTML() {
|
||||
return [];
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
Suggestion({
|
||||
editor: this.editor,
|
||||
...this.options.suggestion,
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export * from "./AddCodeToEdit";
|
||||
export * from "./CodeBlock";
|
||||
export * from "./Mention";
|
||||
export * from "./Prompt";
|
||||
export * from "./SlashCommand";
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type MentionOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderHTML: (props: {
|
||||
options: MentionOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => DOMOutputSpec;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
4
gui/src/components/mainInput/TipTapEditor/index.ts
Normal file
4
gui/src/components/mainInput/TipTapEditor/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export * from "./extensions";
|
||||
export * from "./MainEditorProvider";
|
||||
export * from "./TipTapEditor";
|
||||
export * from "./utils";
|
||||
|
|
@ -1,43 +1,50 @@
|
|||
import { Editor } from "@tiptap/core";
|
||||
import { Editor } from "@tiptap/react";
|
||||
import { InputModifiers } from "core";
|
||||
import { rifWithContentsToContextItem } from "core/commands/util";
|
||||
import { MutableRefObject } from "react";
|
||||
import { useWebviewListener } from "../../../hooks/useWebviewListener";
|
||||
import {
|
||||
clearCodeToEdit,
|
||||
setNewestCodeblocksForInput,
|
||||
setNewestToolbarPreviewForInput,
|
||||
} from "../../../redux/slices/sessionSlice";
|
||||
import { AppDispatch } from "../../../redux/store";
|
||||
import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";
|
||||
import { TipTapEditorProps } from "./TipTapEditor";
|
||||
import { CodeBlock, PromptBlock } from "./extensions";
|
||||
|
||||
export function useWebviewListeners(options: {
|
||||
/**
|
||||
* Hook for setting up main editor specific webview listeners
|
||||
*/
|
||||
export function useMainEditorWebviewListeners({
|
||||
editor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
inputId,
|
||||
editorFocusedRef,
|
||||
}: {
|
||||
editor: Editor | null;
|
||||
onEnterRef: MutableRefObject<(modifiers: InputModifiers) => void>;
|
||||
dispatch: AppDispatch;
|
||||
historyLength: number;
|
||||
props: TipTapEditorProps;
|
||||
inputId: string;
|
||||
editorFocusedRef: MutableRefObject<boolean | undefined>;
|
||||
}) {
|
||||
const {
|
||||
editor,
|
||||
onEnterRef,
|
||||
dispatch,
|
||||
historyLength,
|
||||
props,
|
||||
editorFocusedRef,
|
||||
} = options;
|
||||
useWebviewListener(
|
||||
"isContinueInputFocused",
|
||||
async () => {
|
||||
return !!editorFocusedRef.current;
|
||||
},
|
||||
[editorFocusedRef],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"userInput",
|
||||
async (data) => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
editor?.commands.insertContent(data.input);
|
||||
if (!editor) return;
|
||||
editor.commands.insertContent(data.input);
|
||||
onEnterRef.current({ useCodebase: false, noContext: true });
|
||||
},
|
||||
[editor, onEnterRef.current, props.isMainInput],
|
||||
[editor, onEnterRef.current],
|
||||
);
|
||||
|
||||
useWebviewListener("jetbrains/editorInsetRefresh", async () => {
|
||||
|
|
@ -46,11 +53,7 @@ export function useWebviewListeners(options: {
|
|||
|
||||
useWebviewListener(
|
||||
"focusContinueInput",
|
||||
async (data) => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
async () => {
|
||||
dispatch(clearCodeToEdit());
|
||||
|
||||
if (historyLength > 0) {
|
||||
|
|
@ -61,52 +64,46 @@ export function useWebviewListeners(options: {
|
|||
}),
|
||||
);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.blur();
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[historyLength, editor, props.isMainInput],
|
||||
[historyLength, editor, dispatch],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusContinueInputWithoutClear",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusContinueInputWithNewSession",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
await dispatch(
|
||||
saveCurrentSession({
|
||||
openNewSession: true,
|
||||
generateTitle: true,
|
||||
}),
|
||||
);
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor, dispatch],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"highlightedCode",
|
||||
async (data) => {
|
||||
if (!props.isMainInput || !editor) {
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
|
||||
const contextItem = rifWithContentsToContextItem(
|
||||
data.rangeInFileWithContents,
|
||||
|
|
@ -114,31 +111,38 @@ export function useWebviewListeners(options: {
|
|||
|
||||
let index = 0;
|
||||
for (const el of editor.getJSON()?.content ?? []) {
|
||||
// Prevent exact duplicate code blocks
|
||||
if (el.attrs?.item?.name === contextItem.name) {
|
||||
return; // Prevent exact duplicate code blocks
|
||||
return;
|
||||
}
|
||||
if (el.type === "codeBlock") {
|
||||
|
||||
if (el.type === CodeBlock.name || el.type === PromptBlock.name) {
|
||||
index += 2;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
debugger;
|
||||
|
||||
editor
|
||||
.chain()
|
||||
.insertContentAt(index, {
|
||||
type: "codeBlock",
|
||||
type: CodeBlock.name,
|
||||
attrs: {
|
||||
item: contextItem,
|
||||
inputId: props.inputId,
|
||||
inputId,
|
||||
},
|
||||
})
|
||||
.run();
|
||||
|
||||
dispatch(
|
||||
setNewestCodeblocksForInput({
|
||||
inputId: props.inputId,
|
||||
setNewestToolbarPreviewForInput({
|
||||
inputId,
|
||||
contextItemId: contextItem.id.itemId,
|
||||
}),
|
||||
);
|
||||
|
||||
if (data.prompt) {
|
||||
editor.commands.focus("end");
|
||||
editor.commands.insertContent(data.prompt);
|
||||
|
|
@ -153,52 +157,42 @@ export function useWebviewListeners(options: {
|
|||
editor.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput, historyLength, onEnterRef.current],
|
||||
[editor, inputId, onEnterRef.current],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusEdit",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 20);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusEditWithoutClear",
|
||||
async () => {
|
||||
if (!props.isMainInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
editor?.commands.focus("end");
|
||||
}, 2000);
|
||||
},
|
||||
[editor, props.isMainInput],
|
||||
[editor],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"isContinueInputFocused",
|
||||
async () => {
|
||||
return props.isMainInput && !!editorFocusedRef.current;
|
||||
return !!editorFocusedRef.current;
|
||||
},
|
||||
[editorFocusedRef, props.isMainInput],
|
||||
!props.isMainInput,
|
||||
[editorFocusedRef],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"focusContinueSessionId",
|
||||
async (data) => {
|
||||
if (!props.isMainInput || !data.sessionId) {
|
||||
return;
|
||||
}
|
||||
if (!data.sessionId) return;
|
||||
|
||||
await dispatch(
|
||||
loadSession({
|
||||
sessionId: data.sessionId,
|
||||
|
|
@ -206,6 +200,6 @@ export function useWebviewListeners(options: {
|
|||
}),
|
||||
);
|
||||
},
|
||||
[props.isMainInput],
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
|
@ -11,32 +11,29 @@ import { InputModifiers } from "core";
|
|||
import { modelSupportsImages } from "core/llm/autodetect";
|
||||
import { usePostHog } from "posthog-js/react";
|
||||
import { useRef } from "react";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { useSubmenuContextProviders } from "../../../context/SubmenuContextProviders";
|
||||
import { useInputHistory } from "../../../hooks/useInputHistory";
|
||||
import useUpdatingRef from "../../../hooks/useUpdatingRef";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
import { selectUseActiveFile } from "../../../redux/selectors";
|
||||
import { selectDefaultModel } from "../../../redux/slices/configSlice";
|
||||
import {
|
||||
getContextProviderDropdownOptions,
|
||||
getSlashCommandDropdownOptions,
|
||||
} from ".";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { useSubmenuContextProviders } from "../../../../context/SubmenuContextProviders";
|
||||
import { useInputHistory } from "../../../../hooks/useInputHistory";
|
||||
import useUpdatingRef from "../../../../hooks/useUpdatingRef";
|
||||
import { useAppSelector } from "../../../../redux/hooks";
|
||||
import { selectUseActiveFile } from "../../../../redux/selectors";
|
||||
import { selectDefaultModel } from "../../../../redux/slices/configSlice";
|
||||
import {
|
||||
addCodeToEdit,
|
||||
selectHasCodeToEdit,
|
||||
selectIsInEditMode,
|
||||
} from "../../../redux/slices/sessionSlice";
|
||||
import { AppDispatch } from "../../../redux/store";
|
||||
import { exitEditMode } from "../../../redux/thunks";
|
||||
import { loadLastSession } from "../../../redux/thunks/session";
|
||||
import { getFontSize } from "../../../util";
|
||||
import { AddCodeToEdit } from "./extensions/AddCodeToEditExtension";
|
||||
import { CodeBlockExtension } from "./extensions/CodeBlockExtension";
|
||||
import { SlashCommand } from "./extensions/CommandsExtension";
|
||||
import { Mention } from "./extensions/MentionExtension";
|
||||
import {
|
||||
getContextProviderDropdownOptions,
|
||||
getSlashCommandDropdownOptions,
|
||||
} from "./getSuggestion";
|
||||
} from "../../../../redux/slices/sessionSlice";
|
||||
import { AppDispatch } from "../../../../redux/store";
|
||||
import { exitEditMode } from "../../../../redux/thunks";
|
||||
import { loadLastSession } from "../../../../redux/thunks/session";
|
||||
import { getFontSize } from "../../../../util";
|
||||
import * as ContinueExtensions from "../extensions";
|
||||
import { TipTapEditorProps } from "../TipTapEditor";
|
||||
import { handleImageFile } from "./imageUtils";
|
||||
import { TipTapEditorProps } from "./TipTapEditor";
|
||||
|
||||
export function getPlaceholderText(
|
||||
placeholder: TipTapEditorProps["placeholder"],
|
||||
|
|
@ -63,7 +60,6 @@ export function createEditorConfig(options: {
|
|||
|
||||
const posthog = usePostHog();
|
||||
|
||||
// #region Selectors
|
||||
const { getSubmenuContextItems } = useSubmenuContextProviders();
|
||||
const defaultModel = useAppSelector(selectDefaultModel);
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
|
|
@ -72,9 +68,7 @@ export function createEditorConfig(options: {
|
|||
const isInEditMode = useAppSelector(selectIsInEditMode);
|
||||
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
|
||||
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
|
||||
// #endregion
|
||||
|
||||
// #region Refs
|
||||
const inSubmenuRef = useRef<string | undefined>(undefined);
|
||||
const inDropdownRef = useRef(false);
|
||||
const defaultModelRef = useUpdatingRef(defaultModel);
|
||||
|
|
@ -90,8 +84,6 @@ export function createEditorConfig(options: {
|
|||
);
|
||||
const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey);
|
||||
|
||||
// #endregion
|
||||
|
||||
const enterSubmenu = async (editor: Editor, providerId: string) => {
|
||||
const contents = editor.getText();
|
||||
const indexOfAt = contents.lastIndexOf("@");
|
||||
|
|
@ -294,10 +286,7 @@ export function createEditorConfig(options: {
|
|||
},
|
||||
}),
|
||||
Text,
|
||||
Mention.configure({
|
||||
HTMLAttributes: {
|
||||
class: "mention",
|
||||
},
|
||||
ContinueExtensions.Mention.configure({
|
||||
suggestion: getContextProviderDropdownOptions(
|
||||
availableContextProvidersRef,
|
||||
getSubmenuContextItemsRef,
|
||||
|
|
@ -307,15 +296,8 @@ export function createEditorConfig(options: {
|
|||
inSubmenuRef,
|
||||
ideMessenger,
|
||||
),
|
||||
renderHTML: (props) => {
|
||||
return `@${props.node.attrs.label || props.node.attrs.id}`;
|
||||
},
|
||||
}),
|
||||
|
||||
AddCodeToEdit.configure({
|
||||
HTMLAttributes: {
|
||||
class: "add-code-to-edit",
|
||||
},
|
||||
ContinueExtensions.AddCodeToEdit.configure({
|
||||
suggestion: {
|
||||
...getContextProviderDropdownOptions(
|
||||
availableContextProvidersRef,
|
||||
|
|
@ -351,25 +333,22 @@ export function createEditorConfig(options: {
|
|||
},
|
||||
},
|
||||
}),
|
||||
SlashCommand.configure({
|
||||
HTMLAttributes: {
|
||||
class: "mention",
|
||||
},
|
||||
ContinueExtensions.SlashCommand.configure({
|
||||
suggestion: getSlashCommandDropdownOptions(
|
||||
availableSlashCommandsRef,
|
||||
onClose,
|
||||
onOpen,
|
||||
ideMessenger,
|
||||
dispatch,
|
||||
props.inputId,
|
||||
),
|
||||
renderText: (props) => {
|
||||
return props.node.attrs.label;
|
||||
},
|
||||
}),
|
||||
CodeBlockExtension,
|
||||
ContinueExtensions.PromptBlock,
|
||||
ContinueExtensions.CodeBlock,
|
||||
],
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: "outline-none -mt-1 overflow-hidden",
|
||||
class: "outline-none overflow-hidden",
|
||||
style: `font-size: ${getFontSize()}px;`,
|
||||
},
|
||||
},
|
||||
|
|
@ -6,10 +6,12 @@ import {
|
|||
} from "core";
|
||||
import { MutableRefObject } from "react";
|
||||
import tippy from "tippy.js";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import AtMentionDropdown from "../AtMentionDropdown";
|
||||
import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../types";
|
||||
import { TIPPY_DIV_ID } from "./TipTapEditor";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { AppDispatch } from "../../../../redux/store";
|
||||
import AtMentionDropdown from "../../AtMentionDropdown";
|
||||
import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types";
|
||||
import { TIPPY_DIV_ID } from "../TipTapEditor";
|
||||
import { SlashCommand } from "../extensions";
|
||||
|
||||
function getSuggestion(
|
||||
items: (props: { query: string }) => Promise<ComboBoxItem[]>,
|
||||
|
|
@ -196,6 +198,8 @@ export function getSlashCommandDropdownOptions(
|
|||
onClose: () => void,
|
||||
onOpen: () => void,
|
||||
ideMessenger: IIdeMessenger,
|
||||
dispatch: AppDispatch,
|
||||
inputId: string,
|
||||
) {
|
||||
const items = async ({ query }: { query: string }) => {
|
||||
const options = [...availableSlashCommandsRef.current];
|
||||
|
|
@ -215,7 +219,8 @@ export function getSlashCommandDropdownOptions(
|
|||
id: provider.title,
|
||||
title: provider.title,
|
||||
label: provider.title,
|
||||
type: (provider.type ?? "slashCommand") as ComboBoxItemType,
|
||||
type: (provider.type ?? SlashCommand.name) as ComboBoxItemType,
|
||||
content: provider.content,
|
||||
action: provider.action,
|
||||
}));
|
||||
|
||||
|
|
@ -232,6 +237,7 @@ export function getSlashCommandDropdownOptions(
|
|||
name: "",
|
||||
id: "",
|
||||
label: "",
|
||||
content: "",
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
|
||||
const IMAGE_RESOLUTION = 1024;
|
||||
|
||||
5
gui/src/components/mainInput/TipTapEditor/utils/index.ts
Normal file
5
gui/src/components/mainInput/TipTapEditor/utils/index.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export * from "./editorConfig";
|
||||
export * from "./getSuggestion";
|
||||
export * from "./imageUtils";
|
||||
export * from "./keyHandlers";
|
||||
export * from "./resolveEditorContent";
|
||||
|
|
@ -1,20 +1,18 @@
|
|||
import { Editor } from "@tiptap/react";
|
||||
import { KeyboardEvent } from "react";
|
||||
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../util";
|
||||
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../../../util";
|
||||
import {
|
||||
handleJetBrainsOSRMetaKeyIssues,
|
||||
handleVSCMetaKeyIssues,
|
||||
} from "../util/handleMetaKeyIssues";
|
||||
} from "../../util/handleMetaKeyIssues";
|
||||
|
||||
export function useEditorEventHandlers(options: {
|
||||
editor: Editor | null;
|
||||
isOSREnabled: boolean;
|
||||
editorFocusedRef: React.MutableRefObject<boolean | undefined>;
|
||||
isInEditMode: boolean;
|
||||
setActiveKey: (key: string | null) => void;
|
||||
}) {
|
||||
const { editor, isOSREnabled, editorFocusedRef, isInEditMode, setActiveKey } =
|
||||
options;
|
||||
const { editor, isOSREnabled, editorFocusedRef, setActiveKey } = options;
|
||||
|
||||
/**
|
||||
* This handles various issues with meta key actions
|
||||
|
|
@ -0,0 +1,341 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import { Paragraph } from "@tiptap/extension-paragraph";
|
||||
import { Text } from "@tiptap/extension-text";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
DefaultContextProvider,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { renderChatMessage, stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
|
||||
import { CodeBlock, Mention, SlashCommand } from "../extensions";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface ResolveEditorContentInput {
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
ideMessenger: IIdeMessenger;
|
||||
defaultContextProviders: DefaultContextProvider[];
|
||||
availableSlashCommands: SlashCommandDescription[];
|
||||
selectedModelTitle: string;
|
||||
dispatch: Dispatch;
|
||||
}
|
||||
|
||||
type ResolveEditorContentOutput = [
|
||||
ContextItemWithId[],
|
||||
RangeInFile[],
|
||||
MessageContent,
|
||||
(
|
||||
| {
|
||||
command: SlashCommandDescription;
|
||||
input: string;
|
||||
}
|
||||
| undefined
|
||||
),
|
||||
];
|
||||
|
||||
/**
|
||||
* This function converts the input from the editor to a string, resolving any context items
|
||||
* Context items are appended to the top of the prompt and then referenced within the input
|
||||
*/
|
||||
export async function resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands,
|
||||
selectedModelTitle,
|
||||
dispatch,
|
||||
}: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> {
|
||||
const { parts, contextItemAttrs, selectedCode, slashCommandName } =
|
||||
processEditorContent(editorState);
|
||||
|
||||
const slashCommandWithInput = processSlashCommand(
|
||||
slashCommandName,
|
||||
availableSlashCommands,
|
||||
parts,
|
||||
);
|
||||
|
||||
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(true));
|
||||
}
|
||||
|
||||
const contextItems = await gatherContextItems({
|
||||
contextItemAttrs,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
parts,
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(false));
|
||||
}
|
||||
|
||||
return [contextItems, selectedCode, parts, slashCommandWithInput];
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes editor content and extracts parts, context items, code, and slash commands
|
||||
*/
|
||||
function processEditorContent(editorState: JSONContent) {
|
||||
const contextItemAttrs: MentionAttrs[] = [];
|
||||
const selectedCode: RangeInFile[] = [];
|
||||
let slashCommandName: string | undefined;
|
||||
|
||||
const parts = (editorState?.content || []).reduce<MessagePart[]>(
|
||||
(parts, p) => {
|
||||
switch (p.type) {
|
||||
case Paragraph.name: {
|
||||
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
|
||||
|
||||
// Only take the first slash command
|
||||
if (foundSlashCommand && !slashCommandName) {
|
||||
slashCommandName = foundSlashCommand;
|
||||
}
|
||||
|
||||
contextItemAttrs.push(...ctxItems);
|
||||
|
||||
if (!text) return parts;
|
||||
|
||||
// Merge with previous text part if possible
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
return parts;
|
||||
}
|
||||
|
||||
return [...parts, { type: "text", text }];
|
||||
}
|
||||
|
||||
case CodeBlock.name: {
|
||||
if (!p.attrs?.item) {
|
||||
console.warn("codeBlock has no item attribute");
|
||||
return parts;
|
||||
}
|
||||
|
||||
const contextItem = p.attrs.item as ContextItemWithId;
|
||||
const rif = ctxItemToRifWithContents(contextItem, true);
|
||||
selectedCode.push(rif);
|
||||
|
||||
// If editing, only include in selectedCode
|
||||
if (contextItem.editing) {
|
||||
return parts;
|
||||
}
|
||||
|
||||
const fileExtension = getUriFileExtension(rif.filepath);
|
||||
const codeText = [
|
||||
"\n\n```",
|
||||
fileExtension,
|
||||
" ",
|
||||
contextItem.description,
|
||||
"\n",
|
||||
contextItem.content,
|
||||
"\n```",
|
||||
].join("");
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text +=
|
||||
"\n" + codeText;
|
||||
return parts;
|
||||
}
|
||||
|
||||
return [...parts, { type: "text", text: codeText }];
|
||||
}
|
||||
|
||||
case Image.name: {
|
||||
return [
|
||||
...parts,
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: p.attrs?.src },
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
default: {
|
||||
console.warn("Unexpected content type", p.type);
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { parts, contextItemAttrs, selectedCode, slashCommandName };
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes slash commands and prepares the command with input
|
||||
*/
|
||||
function processSlashCommand(
|
||||
slashCommandName: string | undefined,
|
||||
availableSlashCommands: SlashCommandDescription[],
|
||||
parts: MessagePart[],
|
||||
): { command: SlashCommandDescription; input: string } | undefined {
|
||||
if (!slashCommandName) return;
|
||||
|
||||
const command = availableSlashCommands.find(
|
||||
(c) => c.name === slashCommandName,
|
||||
);
|
||||
|
||||
if (!command) return;
|
||||
|
||||
const lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
|
||||
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
|
||||
|
||||
let input: string;
|
||||
|
||||
// Get input and add text of last slash command text back in to last text node
|
||||
if (lastTextPart) {
|
||||
// TODO: only input the slash cmd is currently using
|
||||
// improove this comment
|
||||
input = renderChatMessage({
|
||||
role: "user",
|
||||
content: lastTextPart.text,
|
||||
}).trimStart();
|
||||
lastTextPart.text = `/${command.name} ${lastTextPart.text}`;
|
||||
} else {
|
||||
input = "";
|
||||
parts.push({ type: "text", text: `/${command.name}` });
|
||||
}
|
||||
|
||||
return {
|
||||
command,
|
||||
input,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers context items from various sources
|
||||
*/
|
||||
async function gatherContextItems({
|
||||
contextItemAttrs,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
parts,
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
}: {
|
||||
contextItemAttrs: MentionAttrs[];
|
||||
modifiers: InputModifiers;
|
||||
ideMessenger: IIdeMessenger;
|
||||
defaultContextProviders: DefaultContextProvider[];
|
||||
parts: MessagePart[];
|
||||
selectedCode: RangeInFile[];
|
||||
selectedModelTitle: string;
|
||||
}): Promise<ContextItemWithId[]> {
|
||||
let contextItems: ContextItemWithId[] = [];
|
||||
|
||||
// Process context item attributes
|
||||
for (const item of contextItemAttrs) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: item.itemType === "contextProvider" ? item.id : item.itemType!,
|
||||
query: item.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
contextItems.push(...result.content);
|
||||
}
|
||||
}
|
||||
|
||||
// cmd+enter to use codebase
|
||||
if (modifiers.useCodebase) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: "codebase",
|
||||
query: "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
|
||||
if (result.status === "success") {
|
||||
contextItems.push(...result.content);
|
||||
}
|
||||
}
|
||||
|
||||
// Include default context providers
|
||||
const defaultContextItems = await Promise.all(
|
||||
defaultContextProviders.map(async (provider) => {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: provider.name,
|
||||
query: provider.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
return result.content;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
contextItems.push(...defaultContextItems.flat());
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
function findLastIndex<T>(
|
||||
array: T[],
|
||||
predicate: (value: T, index: number, obj: T[]) => boolean,
|
||||
): number {
|
||||
for (let i = array.length - 1; i >= 0; i--) {
|
||||
if (predicate(array[i], i, array)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // if no element satisfies the predicate
|
||||
}
|
||||
|
||||
function resolveParagraph(
|
||||
p: JSONContent,
|
||||
): [string, MentionAttrs[], string | undefined] {
|
||||
const contextItems: MentionAttrs[] = [];
|
||||
let slashCommand: string | undefined;
|
||||
|
||||
const text = (p.content || [])
|
||||
.map((child) => {
|
||||
switch (child.type) {
|
||||
case Text.name:
|
||||
return child.text;
|
||||
case Mention.name:
|
||||
contextItems.push(child.attrs as MentionAttrs);
|
||||
return child.attrs?.renderInlineAs ?? child.attrs?.label;
|
||||
case SlashCommand.name:
|
||||
if (!slashCommand) {
|
||||
slashCommand = child.attrs?.id;
|
||||
return "";
|
||||
}
|
||||
return child.attrs?.label;
|
||||
default:
|
||||
console.warn("Unexpected child type", child.type);
|
||||
return "";
|
||||
}
|
||||
})
|
||||
.join("")
|
||||
.trimStart();
|
||||
|
||||
return [text, contextItems, slashCommand];
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { vscBadgeBackground } from "../..";
|
||||
import CodeSnippetPreview from "../../markdown/CodeSnippetPreview";
|
||||
|
||||
export const CodeBlockComponent = (props: any) => {
|
||||
const { node, deleteNode, selected, editor, updateAttributes } = props;
|
||||
const item: ContextItemWithId = node.attrs.item;
|
||||
const inputId = node.attrs.inputId;
|
||||
// const contextItems = useSelector(
|
||||
// (store: RootState) =>
|
||||
// store.session.messages[store.session.messages.length - 1].contextItems,
|
||||
// );
|
||||
// const isFirstContextItem = item.id === contextItems[0]?.id;
|
||||
const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now
|
||||
|
||||
// Not setting this as a "p" will cause issues with foreign keyboards
|
||||
// See https://github.com/continuedev/continue/issues/3199
|
||||
const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p";
|
||||
|
||||
return (
|
||||
<NodeViewWrapper
|
||||
className="code-block-with-content"
|
||||
as={nodeViewWrapperTag}
|
||||
>
|
||||
<CodeSnippetPreview
|
||||
inputId={inputId}
|
||||
borderColor={
|
||||
isFirstContextItem
|
||||
? "#d0d"
|
||||
: selected
|
||||
? vscBadgeBackground
|
||||
: undefined
|
||||
}
|
||||
item={item}
|
||||
onDelete={() => {
|
||||
deleteNode();
|
||||
}}
|
||||
/>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
};
|
||||
|
|
@ -1,178 +0,0 @@
|
|||
// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts)
|
||||
|
||||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
|
||||
import { PluginKey } from "@tiptap/pm/state";
|
||||
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
|
||||
|
||||
export type SlashCommandOptions = {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
renderText: (props: {
|
||||
options: SlashCommandOptions;
|
||||
node: ProseMirrorNode;
|
||||
}) => string;
|
||||
suggestion: Omit<SuggestionOptions, "editor">;
|
||||
};
|
||||
|
||||
export const SlashCommandPluginKey = new PluginKey("slashcommand");
|
||||
|
||||
export const SlashCommand = Node.create<SlashCommandOptions>({
|
||||
name: "slashcommand",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
renderText({ options, node }) {
|
||||
return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`;
|
||||
},
|
||||
suggestion: {
|
||||
char: "/",
|
||||
pluginKey: SlashCommandPluginKey,
|
||||
startOfLine: true,
|
||||
command: ({ editor, range, props }) => {
|
||||
// increase range.to by one when the next node is of type "text"
|
||||
// and starts with a space character
|
||||
const nodeAfter = editor.view.state.selection.$to.nodeAfter;
|
||||
const overrideSpace = nodeAfter?.text?.startsWith(" ");
|
||||
|
||||
if (overrideSpace) {
|
||||
range.to += 1;
|
||||
}
|
||||
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(range, [
|
||||
{
|
||||
type: this.name,
|
||||
attrs: props,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: " ",
|
||||
},
|
||||
])
|
||||
.run();
|
||||
|
||||
window.getSelection()?.collapseToEnd();
|
||||
},
|
||||
allow: ({ state, range }) => {
|
||||
const $from = state.doc.resolve(range.from);
|
||||
const type = state.schema.nodes[this.name];
|
||||
const allow = !!$from.parent.type.contentMatch.matchType(type);
|
||||
|
||||
return allow;
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
group: "inline",
|
||||
|
||||
inline: true,
|
||||
|
||||
selectable: false,
|
||||
|
||||
atom: true,
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
id: {
|
||||
default: null,
|
||||
parseHTML: (element) => element.getAttribute("data-id"),
|
||||
renderHTML: (attributes) => {
|
||||
if (!attributes.id) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
"data-id": attributes.id,
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
label: {
|
||||
default: null,
|
||||
parseHTML: (element) => element.getAttribute("data-label"),
|
||||
renderHTML: (attributes) => {
|
||||
if (!attributes.label) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
"data-label": attributes.label,
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [
|
||||
{
|
||||
tag: `span[data-type="${this.name}"]`,
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
renderHTML({ node, HTMLAttributes }) {
|
||||
return [
|
||||
"span",
|
||||
mergeAttributes(
|
||||
{ "data-type": this.name },
|
||||
this.options.HTMLAttributes,
|
||||
HTMLAttributes,
|
||||
),
|
||||
this.options.renderText({
|
||||
options: this.options,
|
||||
node,
|
||||
}),
|
||||
];
|
||||
},
|
||||
|
||||
renderText({ node }) {
|
||||
return this.options.renderText({
|
||||
options: this.options,
|
||||
node,
|
||||
});
|
||||
},
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
Backspace: () =>
|
||||
this.editor.commands.command(({ tr, state }) => {
|
||||
let isSlashCommand = false;
|
||||
const { selection } = state;
|
||||
const { empty, anchor } = selection;
|
||||
|
||||
if (!empty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => {
|
||||
if (node.type.name === this.name) {
|
||||
isSlashCommand = true;
|
||||
tr.insertText(
|
||||
this.options.suggestion.char || "",
|
||||
pos,
|
||||
pos + node.nodeSize,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
return isSlashCommand;
|
||||
}),
|
||||
};
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
Suggestion({
|
||||
editor: this.editor,
|
||||
...this.options.suggestion,
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
|
|
@ -1,277 +0,0 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
DefaultContextProvider,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { renderChatMessage, stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { setIsGatheringContext } from "../../../redux/slices/sessionSlice";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface ResolveEditorContentInput {
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
ideMessenger: IIdeMessenger;
|
||||
defaultContextProviders: DefaultContextProvider[];
|
||||
availableSlashCommands: SlashCommandDescription[];
|
||||
selectedModelTitle: string;
|
||||
dispatch: Dispatch;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function converts the input from the editor to a string, resolving any context items
|
||||
* Context items are appended to the top of the prompt and then referenced within the input
|
||||
*/
|
||||
async function resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands,
|
||||
selectedModelTitle,
|
||||
dispatch,
|
||||
}: ResolveEditorContentInput): Promise<
|
||||
[
|
||||
ContextItemWithId[],
|
||||
RangeInFile[],
|
||||
MessageContent,
|
||||
(
|
||||
| {
|
||||
command: SlashCommandDescription;
|
||||
input: string;
|
||||
}
|
||||
| undefined
|
||||
),
|
||||
]
|
||||
> {
|
||||
let parts: MessagePart[] = [];
|
||||
let contextItemAttrs: MentionAttrs[] = [];
|
||||
const selectedCode: RangeInFile[] = [];
|
||||
let slashCommandName: string | undefined = undefined;
|
||||
let slashCommandWithInput:
|
||||
| { command: SlashCommandDescription; input: string }
|
||||
| undefined = undefined;
|
||||
if (editorState?.content) {
|
||||
for (const p of editorState.content) {
|
||||
if (p.type === "paragraph") {
|
||||
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
|
||||
// Only take the first slash command
|
||||
if (foundSlashCommand && typeof slashCommandName === "undefined") {
|
||||
slashCommandName = foundSlashCommand;
|
||||
}
|
||||
|
||||
contextItemAttrs.push(...ctxItems);
|
||||
|
||||
if (text === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({ type: "text", text });
|
||||
}
|
||||
} else if (p.type === "codeBlock") {
|
||||
if (p.attrs?.item) {
|
||||
const contextItem = p.attrs.item as ContextItemWithId;
|
||||
const rif = ctxItemToRifWithContents(contextItem, true);
|
||||
// If not editing, include codeblocks in the prompt
|
||||
// If editing is handled by selectedCode below
|
||||
if (!contextItem.editing) {
|
||||
const fileExtension = getUriFileExtension(rif.filepath);
|
||||
// let extName = relativeFilepath.split(".").slice(-1)[0];
|
||||
const text =
|
||||
"\n\n" +
|
||||
"```" +
|
||||
fileExtension +
|
||||
" " +
|
||||
contextItem.description +
|
||||
"\n" +
|
||||
contextItem.content +
|
||||
"\n```";
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({
|
||||
type: "text",
|
||||
text,
|
||||
});
|
||||
}
|
||||
}
|
||||
selectedCode.push(rif);
|
||||
} else {
|
||||
console.warn("codeBlock has no item attribute");
|
||||
}
|
||||
} else if (p.type === "image") {
|
||||
parts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: p.attrs?.src,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
console.warn("Unexpected content type", p.type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (slashCommandName) {
|
||||
const command = availableSlashCommands.find(
|
||||
(c) => c.name === slashCommandName,
|
||||
);
|
||||
if (command) {
|
||||
const lastTextIndex = findLastIndex(
|
||||
parts,
|
||||
(part) => part.type === "text",
|
||||
);
|
||||
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
|
||||
|
||||
let input: string;
|
||||
// Get input and add text of last slash command text back in to last text node
|
||||
if (lastTextPart) {
|
||||
input = renderChatMessage({
|
||||
role: "user",
|
||||
content: lastTextPart.text,
|
||||
}).trimStart();
|
||||
lastTextPart.text = `/${command.name} ${lastTextPart.text}`;
|
||||
} else {
|
||||
input = "";
|
||||
parts.push({ type: "text", text: `/${command.name}` });
|
||||
}
|
||||
|
||||
slashCommandWithInput = {
|
||||
command,
|
||||
input,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(true));
|
||||
}
|
||||
|
||||
let contextItemsText = "";
|
||||
let contextItems: ContextItemWithId[] = [];
|
||||
for (const item of contextItemAttrs) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: item.itemType === "contextProvider" ? item.id : item.itemType!,
|
||||
query: item.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
const resolvedItems = result.content;
|
||||
contextItems.push(...resolvedItems);
|
||||
for (const resolvedItem of resolvedItems) {
|
||||
contextItemsText += resolvedItem.content + "\n\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cmd+enter to use codebase
|
||||
if (modifiers.useCodebase) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: "codebase",
|
||||
query: "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
|
||||
if (result.status === "success") {
|
||||
const codebaseItems = result.content;
|
||||
contextItems.push(...codebaseItems);
|
||||
for (const codebaseItem of codebaseItems) {
|
||||
contextItemsText += codebaseItem.content + "\n\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Include default context providers
|
||||
const defaultContextItems = await Promise.all(
|
||||
defaultContextProviders.map(async (provider) => {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: provider.name,
|
||||
query: provider.query ?? "",
|
||||
fullInput: stripImages(parts),
|
||||
selectedCode,
|
||||
selectedModelTitle,
|
||||
});
|
||||
if (result.status === "success") {
|
||||
return result.content;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}),
|
||||
);
|
||||
contextItems.push(...defaultContextItems.flat());
|
||||
|
||||
if (contextItemsText !== "") {
|
||||
contextItemsText += "\n";
|
||||
}
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(false));
|
||||
}
|
||||
|
||||
return [contextItems, selectedCode, parts, slashCommandWithInput];
|
||||
}
|
||||
|
||||
function findLastIndex<T>(
|
||||
array: T[],
|
||||
predicate: (value: T, index: number, obj: T[]) => boolean,
|
||||
): number {
|
||||
for (let i = array.length - 1; i >= 0; i--) {
|
||||
if (predicate(array[i], i, array)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // if no element satisfies the predicate
|
||||
}
|
||||
|
||||
function resolveParagraph(
|
||||
p: JSONContent,
|
||||
): [string, MentionAttrs[], string | undefined] {
|
||||
let text = "";
|
||||
const contextItems: MentionAttrs[] = [];
|
||||
let slashCommand: string | undefined = undefined;
|
||||
for (const child of p.content || []) {
|
||||
if (child.type === "text") {
|
||||
text += text === "" ? child.text?.trimStart() : child.text;
|
||||
} else if (child.type === "mention") {
|
||||
text +=
|
||||
typeof child.attrs?.renderInlineAs === "string"
|
||||
? child.attrs.renderInlineAs
|
||||
: child.attrs?.label;
|
||||
contextItems.push(child.attrs as MentionAttrs);
|
||||
} else if (child.type === "slashcommand") {
|
||||
if (typeof slashCommand === "undefined") {
|
||||
slashCommand = child.attrs?.id;
|
||||
} else {
|
||||
text += child.attrs?.label;
|
||||
}
|
||||
} else {
|
||||
console.warn("Unexpected child type", child.type);
|
||||
}
|
||||
}
|
||||
return [text, contextItems, slashCommand];
|
||||
}
|
||||
|
||||
export default resolveEditorContent;
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { Editor } from "@tiptap/react";
|
||||
import { KeyboardEvent } from "react";
|
||||
import { getPlatform, isWebEnvironment } from "../../../util";
|
||||
import { CodeBlock } from "../TipTapEditor";
|
||||
|
||||
const isWebEnv = isWebEnvironment();
|
||||
|
||||
|
|
@ -103,7 +104,7 @@ export const handleJetBrainsMetaBackspace = (editor: Editor) => {
|
|||
for (let i = doc.content.childCount - 1; i >= 0; i--) {
|
||||
const node = doc.content.child(i);
|
||||
|
||||
if (node.type.name === "codeBlock") {
|
||||
if (node.type.name === CodeBlock.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,184 +0,0 @@
|
|||
import {
|
||||
ChevronDownIcon,
|
||||
EyeSlashIcon,
|
||||
XMarkIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { getFontSize } from "../../util";
|
||||
import FileIcon from "../FileIcon";
|
||||
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
|
||||
import StyledMarkdownPreview from "./StyledMarkdownPreview";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { EyeIcon } from "@heroicons/react/24/solid";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
|
||||
const PreviewMarkdownDiv = styled.div<{
|
||||
borderColor?: string;
|
||||
}>`
|
||||
background-color: ${vscEditorBackground};
|
||||
border-radius: ${defaultBorderRadius};
|
||||
border: 0.5px solid ${(props) => props.borderColor || lightGray};
|
||||
margin-top: 4px;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
& div {
|
||||
background-color: ${vscEditorBackground};
|
||||
}
|
||||
`;
|
||||
|
||||
interface CodeSnippetPreviewProps {
|
||||
item: ContextItemWithId;
|
||||
onDelete?: () => void;
|
||||
borderColor?: string;
|
||||
inputId: string;
|
||||
}
|
||||
|
||||
const MAX_PREVIEW_HEIGHT = 100;
|
||||
|
||||
const backticksRegex = /`{3,}/gm;
|
||||
|
||||
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const [localHidden, setLocalHidden] = useState<boolean | undefined>();
|
||||
const [isSizeLimited, setIsSizeLimited] = useState(true);
|
||||
|
||||
const newestCodeblockForInputId = useAppSelector(
|
||||
(store) => store.session.newestCodeblockForInput[props.inputId],
|
||||
);
|
||||
|
||||
const hidden = useMemo(() => {
|
||||
return localHidden ?? newestCodeblockForInputId !== props.item.id.itemId;
|
||||
}, [localHidden, newestCodeblockForInputId, props.item]);
|
||||
|
||||
const content = useMemo(() => {
|
||||
return dedent`${props.item.content}`;
|
||||
}, [props.item.content]);
|
||||
|
||||
const fence = useMemo(() => {
|
||||
const backticks = content.match(backticksRegex);
|
||||
return backticks ? backticks.sort().at(-1) + "`" : "```";
|
||||
}, [content]);
|
||||
|
||||
const codeBlockRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [codeblockDims, setCodeblockDims] = useState({ width: 0, height: 0 });
|
||||
useEffect(() => {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
setCodeblockDims({
|
||||
width: codeBlockRef.current?.scrollWidth ?? 0,
|
||||
height: codeBlockRef.current?.scrollHeight ?? 0,
|
||||
});
|
||||
});
|
||||
|
||||
if (codeBlockRef.current) {
|
||||
resizeObserver.observe(codeBlockRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [codeBlockRef]);
|
||||
|
||||
return (
|
||||
<PreviewMarkdownDiv
|
||||
spellCheck={false}
|
||||
borderColor={props.borderColor}
|
||||
className="find-widget-skip"
|
||||
>
|
||||
<div
|
||||
className="m-0 flex cursor-pointer items-center justify-between break-all border-b px-[5px] py-1.5 hover:opacity-90"
|
||||
style={{
|
||||
fontSize: getFontSize() - 3,
|
||||
}}
|
||||
onClick={() => {
|
||||
setLocalHidden(!hidden);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex items-center gap-1 hover:underline"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (
|
||||
props.item.id.providerTitle === "file" &&
|
||||
props.item.uri?.value
|
||||
) {
|
||||
ideMessenger.post("showFile", {
|
||||
filepath: props.item.uri.value,
|
||||
});
|
||||
} else if (props.item.id.providerTitle === "code") {
|
||||
const rif = ctxItemToRifWithContents(props.item, true);
|
||||
ideMessenger.ide.showLines(
|
||||
rif.filepath,
|
||||
rif.range.start.line,
|
||||
rif.range.end.line,
|
||||
);
|
||||
} else {
|
||||
ideMessenger.post("showVirtualFile", {
|
||||
content,
|
||||
name: props.item.name,
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FileIcon height="16px" width="16px" filename={props.item.name} />
|
||||
{props.item.name}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<HeaderButtonWithToolTip text={hidden ? "Show" : "Hide"}>
|
||||
{hidden ? (
|
||||
<EyeIcon width="1em" height="1em" />
|
||||
) : (
|
||||
<EyeSlashIcon width="1em" height="1em" />
|
||||
)}
|
||||
</HeaderButtonWithToolTip>
|
||||
<HeaderButtonWithToolTip
|
||||
text="Delete"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
props.onDelete?.();
|
||||
}}
|
||||
>
|
||||
<XMarkIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
contentEditable={false}
|
||||
className={`m-0 ${isSizeLimited ? "overflow-hidden" : "overflow-auto"} ${hidden ? "hidden" : ""}`}
|
||||
ref={codeBlockRef}
|
||||
style={{
|
||||
maxHeight: isSizeLimited ? MAX_PREVIEW_HEIGHT : undefined, // Could switch to max-h-[33vh] but then chevron icon shows when height can't change
|
||||
}}
|
||||
>
|
||||
<StyledMarkdownPreview
|
||||
source={`${fence}${getMarkdownLanguageTagForFile(props.item.name)} ${props.item.description}\n${content}\n${fence}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{codeblockDims.height > MAX_PREVIEW_HEIGHT && (
|
||||
<HeaderButtonWithToolTip
|
||||
className="absolute bottom-1 right-2"
|
||||
text={isSizeLimited ? "Expand" : "Collapse"}
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className="h-5 w-5 transition-all"
|
||||
style={{
|
||||
transform: isSizeLimited ? "" : "rotate(180deg)",
|
||||
}}
|
||||
onClick={() => setIsSizeLimited((v) => !v)}
|
||||
/>
|
||||
</HeaderButtonWithToolTip>
|
||||
)}
|
||||
</PreviewMarkdownDiv>
|
||||
);
|
||||
}
|
||||
|
||||
export default CodeSnippetPreview;
|
||||
|
|
@ -7,6 +7,7 @@ import Spinner from "../../gui/Spinner";
|
|||
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
|
||||
|
||||
interface ApplyActionsProps {
|
||||
disableManualApply?: boolean;
|
||||
applyState?: ApplyState;
|
||||
onClickAccept: () => void;
|
||||
onClickReject: () => void;
|
||||
|
|
@ -59,8 +60,8 @@ export default function ApplyActions(props: ApplyActionsProps) {
|
|||
);
|
||||
case "done":
|
||||
return (
|
||||
<div className="xs:pl-2 xs:pr-1 flex items-center rounded bg-zinc-700">
|
||||
<span className="max-xs:hidden xs:mr-1 text-xs text-gray-400">
|
||||
<div className="flex items-center sm:gap-1">
|
||||
<span className="max-xs:hidden text-center text-xs text-gray-400">
|
||||
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
|
||||
<span className="max-md:hidden">{` remaining`}</span>
|
||||
</span>
|
||||
|
|
@ -90,10 +91,15 @@ export default function ApplyActions(props: ApplyActionsProps) {
|
|||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.disableManualApply) {
|
||||
return null;
|
||||
}
|
||||
return applyButton("Reapply");
|
||||
}
|
||||
default:
|
||||
if (props.disableManualApply) {
|
||||
return null;
|
||||
}
|
||||
return applyButton("Apply");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import FileIcon from "../../FileIcon";
|
||||
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
|
||||
import { getLastNPathParts } from "core/util/uri";
|
||||
import { useContext } from "react";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
|
||||
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
|
||||
import FileIcon from "../../FileIcon";
|
||||
|
||||
export interface FileInfoProps {
|
||||
relativeFilepath: string;
|
||||
|
|
@ -23,17 +23,17 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
|
|||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full min-w-0 items-center">
|
||||
<div
|
||||
className="mr-0.5 flex w-full min-w-0 cursor-pointer items-center gap-0.5"
|
||||
onClick={onClickFileName}
|
||||
>
|
||||
<div
|
||||
className="flex cursor-pointer flex-row items-center gap-0.5"
|
||||
onClick={onClickFileName}
|
||||
>
|
||||
<div>
|
||||
<FileIcon height="20px" width="20px" filename={relativeFilepath} />
|
||||
<span className="w-full truncate hover:underline">
|
||||
{getLastNPathParts(relativeFilepath, 1)}
|
||||
{range && ` ${range}`}
|
||||
</span>
|
||||
</div>
|
||||
<span className="line-clamp-1 break-all hover:underline">
|
||||
{getLastNPathParts(relativeFilepath, 1)}
|
||||
{range && ` ${range}`}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
|
|||
import { debounce } from "lodash";
|
||||
import { useContext, useEffect, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import {
|
||||
defaultBorderRadius,
|
||||
vscCommandCenterInactiveBorder,
|
||||
|
|
@ -26,6 +25,8 @@ import GeneratingCodeLoader from "./GeneratingCodeLoader";
|
|||
import RunInTerminalButton from "./RunInTerminalButton";
|
||||
|
||||
const TopDiv = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
outline: 1px solid ${vscCommandCenterInactiveBorder};
|
||||
outline-offset: -0.5px;
|
||||
border-radius: ${defaultBorderRadius};
|
||||
|
|
@ -38,7 +39,6 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>`
|
|||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
background: inherit;
|
||||
font-size: ${getFontSize() - 2}px;
|
||||
padding: 4px 6px;
|
||||
margin: 0;
|
||||
|
|
@ -52,42 +52,32 @@ export interface StepContainerPreToolbarProps {
|
|||
relativeFilepath: string;
|
||||
isGeneratingCodeBlock: boolean;
|
||||
codeBlockIndex: number; // To track which codeblock we are applying
|
||||
codeBlockStreamId: string;
|
||||
range?: string;
|
||||
children: any;
|
||||
expanded?: boolean;
|
||||
hideApply?: boolean;
|
||||
disableManualApply?: boolean;
|
||||
}
|
||||
|
||||
export default function StepContainerPreToolbar(
|
||||
props: StepContainerPreToolbarProps,
|
||||
) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const streamIdRef = useRef<string>(uuidv4());
|
||||
const wasGeneratingRef = useRef(props.isGeneratingCodeBlock);
|
||||
const isInEditMode = useAppSelector(selectIsInEditMode);
|
||||
const [isExpanded, setIsExpanded] = useState(
|
||||
props.expanded ?? (isInEditMode ? false : true),
|
||||
);
|
||||
const [codeBlockContent, setCodeBlockContent] = useState("");
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
|
||||
const nextCodeBlockIndex = useAppSelector(
|
||||
(state) => state.session.codeBlockApplyStates.curIndex,
|
||||
);
|
||||
|
||||
const applyState = useAppSelector((state) =>
|
||||
selectApplyStateByStreamId(state, streamIdRef.current),
|
||||
selectApplyStateByStreamId(state, props.codeBlockStreamId),
|
||||
);
|
||||
|
||||
// This handles an edge case when the last node in the markdown syntax tree is a codeblock.
|
||||
// In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if
|
||||
// we are done generating based on whether the next node in the tree is not a codeblock.
|
||||
// The tree parsing logic for Remark is defined on page load, so we can't access state
|
||||
// during the actual tree parsing.
|
||||
const isGeneratingCodeBlock = !isStreaming
|
||||
? false
|
||||
: props.isGeneratingCodeBlock;
|
||||
|
||||
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
|
||||
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath);
|
||||
|
||||
|
|
@ -104,7 +94,7 @@ export default function StepContainerPreToolbar(
|
|||
);
|
||||
|
||||
ideMessenger.post("applyToFile", {
|
||||
streamId: streamIdRef.current,
|
||||
streamId: props.codeBlockStreamId,
|
||||
filepath: fileUri,
|
||||
text: codeBlockContent,
|
||||
curSelectedModelTitle: defaultModel.title,
|
||||
|
|
@ -135,19 +125,17 @@ export default function StepContainerPreToolbar(
|
|||
}
|
||||
}, [props.children, codeBlockContent]);
|
||||
|
||||
// Temporarily disabling auto apply for Edit mode
|
||||
// useEffect(() => {
|
||||
// const hasCompletedGenerating =
|
||||
// wasGeneratingRef.current && !isGeneratingCodeBlock;
|
||||
|
||||
// const shouldAutoApply = hasCompletedGenerating && isInEditMode;
|
||||
|
||||
// if (shouldAutoApply) {
|
||||
// onClickApply();
|
||||
// }
|
||||
|
||||
// wasGeneratingRef.current = isGeneratingCodeBlock;
|
||||
// }, [isGeneratingCodeBlock]);
|
||||
// if (hasCompletedGenerating) {
|
||||
// if (props.autoApply) {
|
||||
// onClickApply();
|
||||
// }
|
||||
// }
|
||||
// }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]);
|
||||
|
||||
async function onClickAcceptApply() {
|
||||
const fileUri = await inferResolvedUriFromRelativePath(
|
||||
|
|
@ -156,7 +144,7 @@ export default function StepContainerPreToolbar(
|
|||
);
|
||||
ideMessenger.post("acceptDiff", {
|
||||
filepath: fileUri,
|
||||
streamId: streamIdRef.current,
|
||||
streamId: props.codeBlockStreamId,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -167,7 +155,7 @@ export default function StepContainerPreToolbar(
|
|||
);
|
||||
ideMessenger.post("rejectDiff", {
|
||||
filepath: fileUri,
|
||||
streamId: streamIdRef.current,
|
||||
streamId: props.codeBlockStreamId,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -183,44 +171,40 @@ export default function StepContainerPreToolbar(
|
|||
|
||||
return (
|
||||
<TopDiv>
|
||||
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip">
|
||||
<div className="flex min-w-0 max-w-[45%] items-center">
|
||||
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
|
||||
<div className="flex max-w-72 flex-row items-center">
|
||||
<ChevronDownIcon
|
||||
onClick={onClickExpand}
|
||||
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
|
||||
className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
|
||||
isExpanded ? "rotate-0" : "-rotate-90"
|
||||
}`}
|
||||
/>
|
||||
<div className="w-full min-w-0">
|
||||
<FileInfo
|
||||
relativeFilepath={props.relativeFilepath}
|
||||
range={props.range}
|
||||
/>
|
||||
</div>
|
||||
<FileInfo
|
||||
relativeFilepath={props.relativeFilepath}
|
||||
range={props.range}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 max-sm:gap-1.5">
|
||||
{isGeneratingCodeBlock && (
|
||||
{props.isGeneratingCodeBlock ? (
|
||||
<GeneratingCodeLoader
|
||||
showLineCount={!isExpanded}
|
||||
codeBlockContent={codeBlockContent}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isGeneratingCodeBlock && (
|
||||
) : (
|
||||
<>
|
||||
<CopyButton text={props.codeBlockContent} />
|
||||
{props.hideApply ||
|
||||
(isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
|
||||
<RunInTerminalButton command={props.codeBlockContent} />
|
||||
) : (
|
||||
<ApplyActions
|
||||
applyState={applyState}
|
||||
onClickApply={onClickApply}
|
||||
onClickAccept={onClickAcceptApply}
|
||||
onClickReject={onClickRejectApply}
|
||||
/>
|
||||
))}
|
||||
{isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
|
||||
<RunInTerminalButton command={props.codeBlockContent} />
|
||||
) : (
|
||||
<ApplyActions
|
||||
disableManualApply={props.disableManualApply}
|
||||
applyState={applyState}
|
||||
onClickApply={onClickApply}
|
||||
onClickAccept={onClickAcceptApply}
|
||||
onClickReject={onClickRejectApply}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { memo, useEffect, useMemo } from "react";
|
||||
import { memo, useEffect, useMemo, useRef } from "react";
|
||||
import { useRemark } from "react-remark";
|
||||
import rehypeHighlight, { Options } from "rehype-highlight";
|
||||
import rehypeKatex from "rehype-katex";
|
||||
|
|
@ -17,7 +17,7 @@ import useUpdatingRef from "../../hooks/useUpdatingRef";
|
|||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { selectUIConfig } from "../../redux/slices/configSlice";
|
||||
import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols";
|
||||
import { getFontSize, isJetBrains } from "../../util";
|
||||
import { getFontSize } from "../../util";
|
||||
import { ToolTip } from "../gui/Tooltip";
|
||||
import FilenameLink from "./FilenameLink";
|
||||
import "./katex.css";
|
||||
|
|
@ -69,7 +69,7 @@ const StyledMarkdown = styled.div<{
|
|||
overflow-x: scroll;
|
||||
overflow-y: hidden;
|
||||
|
||||
padding: 16px 8px;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
code {
|
||||
|
|
@ -114,10 +114,6 @@ const StyledMarkdown = styled.div<{
|
|||
line-height: 1.5;
|
||||
}
|
||||
|
||||
> *:first-child {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
> *:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
|
@ -130,6 +126,9 @@ interface StyledMarkdownPreviewProps {
|
|||
scrollLocked?: boolean;
|
||||
itemIndex?: number;
|
||||
useParentBackgroundColor?: boolean;
|
||||
disableManualApply?: boolean;
|
||||
singleCodeblockStreamId?: string;
|
||||
expandCodeblocks?: boolean;
|
||||
}
|
||||
|
||||
const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-";
|
||||
|
|
@ -196,6 +195,29 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
}, [props.itemIndex, history, allSymbols]);
|
||||
const pastFileInfoRef = useUpdatingRef(pastFileInfo);
|
||||
|
||||
const isLastItem = useMemo(() => {
|
||||
return props.itemIndex && props.itemIndex === history.length - 1;
|
||||
}, [history.length, props.itemIndex]);
|
||||
const isLastItemRef = useUpdatingRef(isLastItem);
|
||||
|
||||
const isStreaming = useAppSelector((store) => store.session.isStreaming);
|
||||
const isStreamingRef = useUpdatingRef(isStreaming);
|
||||
|
||||
const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>(
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (props.singleCodeblockStreamId) {
|
||||
codeblockState.current = [
|
||||
{
|
||||
streamId: props.singleCodeblockStreamId,
|
||||
isGenerating: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
}, [props.singleCodeblockStreamId]);
|
||||
|
||||
const [reactContent, setMarkdownSource] = useRemark({
|
||||
remarkPlugins: [
|
||||
remarkTables,
|
||||
|
|
@ -219,8 +241,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
node.data = node.data || {};
|
||||
node.data.hProperties = node.data.hProperties || {};
|
||||
|
||||
node.data.hProperties["data-isgeneratingcodeblock"] =
|
||||
lastCodeNode === node;
|
||||
node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node;
|
||||
node.data.hProperties["data-codeblockcontent"] = node.value;
|
||||
|
||||
if (node.meta) {
|
||||
|
|
@ -282,8 +303,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
const { className, range } = preChildProps;
|
||||
const relativeFilePath = preChildProps["data-relativefilepath"];
|
||||
const codeBlockContent = preChildProps["data-codeblockcontent"];
|
||||
const isGeneratingCodeBlock =
|
||||
preChildProps["data-isgeneratingcodeblock"];
|
||||
|
||||
if (!props.isRenderingInStepContainer) {
|
||||
return <SyntaxHighlightedPre {...preProps} />;
|
||||
|
|
@ -291,11 +310,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
|
||||
const language = getLanguageFromClassName(className);
|
||||
|
||||
// If we don't have a filepath show the more basic toolbar
|
||||
// that is just action buttons on hover.
|
||||
// We also use this in JB since we haven't yet implemented
|
||||
// the logic forfileUri lazy apply.
|
||||
if (!relativeFilePath || isJetBrains()) {
|
||||
if (!relativeFilePath) {
|
||||
return (
|
||||
<StepContainerPreActionButtons
|
||||
language={language}
|
||||
|
|
@ -307,6 +322,21 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
);
|
||||
}
|
||||
|
||||
const isGeneratingCodeBlock =
|
||||
preChildProps["data-islastcodeblock"] &&
|
||||
isLastItemRef.current &&
|
||||
!isStreamingRef.current;
|
||||
|
||||
if (codeblockState.current[codeBlockIndex] === undefined) {
|
||||
codeblockState.current[codeBlockIndex] = {
|
||||
streamId: uuidv4(),
|
||||
isGenerating: isGeneratingCodeBlock,
|
||||
};
|
||||
} else {
|
||||
codeblockState.current[codeBlockIndex].isGenerating =
|
||||
isGeneratingCodeBlock;
|
||||
}
|
||||
|
||||
// We use a custom toolbar for codeblocks in the step container
|
||||
return (
|
||||
<StepContainerPreToolbar
|
||||
|
|
@ -316,6 +346,11 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
|
|||
relativeFilepath={relativeFilePath}
|
||||
isGeneratingCodeBlock={isGeneratingCodeBlock}
|
||||
range={range}
|
||||
codeBlockStreamId={
|
||||
codeblockState.current[codeBlockIndex].streamId
|
||||
}
|
||||
expanded={props.expandCodeblocks}
|
||||
disableManualApply={props.disableManualApply}
|
||||
>
|
||||
<SyntaxHighlightedPre {...preProps} />
|
||||
</StepContainerPreToolbar>
|
||||
|
|
|
|||
|
|
@ -10,7 +10,15 @@ export interface AssistantIconProps {
|
|||
export default function AssistantIcon({ assistant, size }: AssistantIconProps) {
|
||||
const sizeTw = size ?? 4;
|
||||
if (isLocalProfile(assistant)) {
|
||||
return <ComputerDesktopIcon className={`h-${sizeTw} w-${sizeTw}`} />;
|
||||
return (
|
||||
<div
|
||||
className={`h-${sizeTw} w-${sizeTw} bg-lightgray flex items-center justify-center rounded-full`}
|
||||
>
|
||||
<ComputerDesktopIcon
|
||||
className={`h-${sizeTw - 1} w-${sizeTw - 1} font-bold text-black`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
} else if (assistant.iconUrl) {
|
||||
return (
|
||||
<img
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import {
|
||||
ArrowTopRightOnSquareIcon,
|
||||
BuildingOfficeIcon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
Cog6ToothIcon,
|
||||
ExclamationTriangleIcon,
|
||||
|
|
@ -11,7 +10,7 @@ import { useContext, useEffect, useMemo, useRef } from "react";
|
|||
import { useAuth } from "../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { cycleProfile, selectProfileThunk } from "../../../redux";
|
||||
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
|
||||
import { useAppDispatch } from "../../../redux/hooks";
|
||||
import {
|
||||
fontSize,
|
||||
getMetaKeyLabel,
|
||||
|
|
@ -31,6 +30,7 @@ import { useNavigate } from "react-router-dom";
|
|||
import { vscCommandCenterInactiveBorder } from "../..";
|
||||
import { ROUTES } from "../../../util/navigation";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
import { useLump } from "../../mainInput/Lump/LumpContext";
|
||||
import { useFontSize } from "../../ui/font";
|
||||
import AssistantIcon from "./AssistantIcon";
|
||||
|
||||
|
|
@ -45,6 +45,8 @@ const AssistantSelectOption = ({
|
|||
selected,
|
||||
onClick,
|
||||
}: AssistantSelectOptionProps) => {
|
||||
const tinyFont = useFontSize(-4);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const hasFatalErrors = useMemo(() => {
|
||||
|
|
@ -79,25 +81,30 @@ const AssistantSelectOption = ({
|
|||
disabled={hasFatalErrors}
|
||||
onClick={!hasFatalErrors ? handleOptionClick : undefined}
|
||||
fontSizeModifier={-2}
|
||||
className={selected ? "bg-list-active text-list-active-foreground" : ""}
|
||||
>
|
||||
<div className="flex w-full flex-col gap-0.5">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<div className="mr-2 h-4 w-4 flex-shrink-0">
|
||||
<div
|
||||
className="flex w-full flex-col gap-0.5"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between bg-transparent">
|
||||
<div className="flex w-full items-center gap-1.5">
|
||||
<div className="flex h-4 w-4 flex-shrink-0">
|
||||
<AssistantIcon assistant={profile} />
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 flex-1 ${selected ? "font-bold" : ""}`}
|
||||
className={`line-clamp-1 flex-1 ${selected ? "font-semibold" : ""}`}
|
||||
>
|
||||
{profile.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<div>{selected ? <CheckIcon className="h-3 w-3" /> : null}</div>
|
||||
<div className="flex flex-row items-center gap-1">
|
||||
{!profile.errors?.length ? (
|
||||
isLocalProfile(profile) ? (
|
||||
<Cog6ToothIcon
|
||||
className="h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
|
@ -106,7 +113,7 @@ const AssistantSelectOption = ({
|
|||
/>
|
||||
) : (
|
||||
<ArrowTopRightOnSquareIcon
|
||||
className="h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
|
@ -143,9 +150,7 @@ export default function AssistantSelect() {
|
|||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const { selectedProfile, selectedOrganization } = useAuth();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const isLumpToolbarExpanded = useAppSelector(
|
||||
(state) => state.ui.isBlockSettingsToolbarExpanded,
|
||||
);
|
||||
const { isToolbarExpanded } = useLump();
|
||||
|
||||
const { profiles, session, login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -205,7 +210,7 @@ export default function AssistantSelect() {
|
|||
>
|
||||
<PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
|
||||
<span
|
||||
className={`line-clamp-1 select-none ${isLumpToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
className={`line-clamp-1 select-none ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
Create your first assistant
|
||||
</span>
|
||||
|
|
@ -227,7 +232,7 @@ export default function AssistantSelect() {
|
|||
<AssistantIcon size={3} assistant={selectedProfile} />
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 select-none ${isLumpToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
className={`line-clamp-1 select-none ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
{selectedProfile.title}
|
||||
</span>
|
||||
|
|
@ -239,9 +244,9 @@ export default function AssistantSelect() {
|
|||
</ListboxButton>
|
||||
|
||||
<Transition>
|
||||
<ListboxOptions className="pb-0">
|
||||
<ListboxOptions className="min-w-[200px] pb-0">
|
||||
<div
|
||||
className={`thin-scrollbar flex max-h-[300px] flex-col gap-1 overflow-y-auto py-1`}
|
||||
className={`thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto`}
|
||||
>
|
||||
{profiles?.map((profile, idx) => {
|
||||
return (
|
||||
|
|
@ -268,8 +273,13 @@ export default function AssistantSelect() {
|
|||
fontSizeModifier={-2}
|
||||
onClick={session ? onNewAssistant : () => login(false)}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<PlusIcon className="h-4 w-4 flex-shrink-0" />
|
||||
<div
|
||||
className="text-lightgray flex flex-row items-center gap-2"
|
||||
style={{
|
||||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<PlusIcon className="ml-0.5 h-3 w-3 flex-shrink-0" />
|
||||
New Assistant
|
||||
</div>
|
||||
</ListboxOption>
|
||||
|
|
@ -287,22 +297,32 @@ export default function AssistantSelect() {
|
|||
fontSize: tinyFont,
|
||||
}}
|
||||
>
|
||||
<span className="block">
|
||||
<span
|
||||
className="block"
|
||||
style={{
|
||||
fontSize: tinyFont - 1,
|
||||
}}
|
||||
>
|
||||
<code>{getMetaKeyLabel()} ⇧ '</code> to toggle
|
||||
</span>
|
||||
<div
|
||||
className="flex items-center gap-1"
|
||||
className="ml-auto flex items-center gap-1"
|
||||
onClick={() => navigate(ROUTES.CONFIG)}
|
||||
>
|
||||
{selectedOrganization?.iconUrl ? (
|
||||
<img
|
||||
src={selectedOrganization.iconUrl}
|
||||
className="h-4 w-4 rounded-full"
|
||||
className="h-3 w-3 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<BuildingOfficeIcon className="h-4 w-4" />
|
||||
)}
|
||||
<span className="hover:cursor-pointer hover:underline">
|
||||
<span
|
||||
className="hover:cursor-pointer hover:underline"
|
||||
style={{
|
||||
fontSize: tinyFont - 1,
|
||||
}}
|
||||
>
|
||||
{selectedOrganization?.name || "Personal"}
|
||||
</span>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -16,10 +16,14 @@ import {
|
|||
} from "../redux/slices/configSlice";
|
||||
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
|
||||
import {
|
||||
acceptToolCall,
|
||||
addContextItemsAtIndex,
|
||||
setInactive,
|
||||
setToolCallOutput,
|
||||
updateApplyState,
|
||||
} from "../redux/slices/sessionSlice";
|
||||
import { setTTSActive } from "../redux/slices/uiSlice";
|
||||
import { streamResponseAfterToolCall } from "../redux/thunks";
|
||||
import { refreshSessionMetadata } from "../redux/thunks/session";
|
||||
import { streamResponseThunk } from "../redux/thunks/streamResponse";
|
||||
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
|
||||
|
|
@ -245,6 +249,42 @@ function useSetup() {
|
|||
},
|
||||
[defaultModel],
|
||||
);
|
||||
|
||||
const activeToolStreamId = useAppSelector(
|
||||
(store) => store.session.activeToolStreamId,
|
||||
);
|
||||
useWebviewListener(
|
||||
"updateApplyState",
|
||||
async (state) => {
|
||||
// dispatch(
|
||||
// updateCurCheckpoint({
|
||||
// filepath: state.filepath,
|
||||
// content: state.fileContent,
|
||||
// }),
|
||||
// );
|
||||
dispatch(updateApplyState(state));
|
||||
if (
|
||||
activeToolStreamId &&
|
||||
state.streamId === activeToolStreamId[0] &&
|
||||
state.status === "closed"
|
||||
) {
|
||||
// const output: ContextItem = {
|
||||
// name: "Edit tool output",
|
||||
// content: "Completed edit",
|
||||
// description: "",
|
||||
// };
|
||||
dispatch(acceptToolCall());
|
||||
dispatch(setToolCallOutput([]));
|
||||
dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: activeToolStreamId[1],
|
||||
toolOutput: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[activeToolStreamId],
|
||||
);
|
||||
}
|
||||
|
||||
export default useSetup;
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import TimelineItem from "../../components/gui/TimelineItem";
|
|||
import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton";
|
||||
import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek";
|
||||
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
|
||||
import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils";
|
||||
import { useOnboardingCard } from "../../components/OnboardingCard";
|
||||
import StepContainer from "../../components/StepContainer";
|
||||
import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
|
||||
|
|
@ -75,6 +75,8 @@ const StepsDiv = styled.div`
|
|||
}
|
||||
`;
|
||||
|
||||
export const MAIN_EDITOR_INPUT_ID = "main-editor-input";
|
||||
|
||||
function fallbackRender({ error, resetErrorBoundary }: any) {
|
||||
// Call resetErrorBoundary() to reset the error boundary and retry the render.
|
||||
|
||||
|
|
@ -295,7 +297,7 @@ export function Chat() {
|
|||
|
||||
<StepsDiv
|
||||
ref={stepsDivRef}
|
||||
className={`mt-[2px] overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
|
||||
className={`mt-3 overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
|
||||
>
|
||||
{highlights}
|
||||
{history.map((item, index: number) => (
|
||||
|
|
@ -406,7 +408,7 @@ export function Chat() {
|
|||
onEnter={(editorState, modifiers, editor) =>
|
||||
sendInput(editorState, modifiers, undefined, editor)
|
||||
}
|
||||
inputId={"main-editor"}
|
||||
inputId={MAIN_EDITOR_INPUT_ID}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,9 +7,13 @@ interface CreateFileToolCallProps {
|
|||
}
|
||||
|
||||
export function CreateFile(props: CreateFileToolCallProps) {
|
||||
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "test.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``;
|
||||
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``;
|
||||
|
||||
return props.relativeFilepath ? (
|
||||
<StyledMarkdownPreview isRenderingInStepContainer={true} source={src} />
|
||||
<StyledMarkdownPreview
|
||||
isRenderingInStepContainer={true}
|
||||
source={src}
|
||||
disableManualApply={true}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
|
|
|
|||
54
gui/src/pages/gui/ToolCallDiv/EditFile.tsx
Normal file
54
gui/src/pages/gui/ToolCallDiv/EditFile.tsx
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { useMemo } from "react";
|
||||
import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview";
|
||||
import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
|
||||
type EditToolCallProps = {
|
||||
relativeFilePath: string;
|
||||
newContents: string;
|
||||
toolCallId?: string;
|
||||
};
|
||||
|
||||
export function EditFile(props: EditToolCallProps) {
|
||||
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``;
|
||||
|
||||
const isStreaming = useAppSelector((state) => state.session.isStreaming);
|
||||
const states = useAppSelector((store) => store.session.codeBlockApplyStates);
|
||||
|
||||
const applyState = useMemo(() => {
|
||||
return states.states.find(
|
||||
(state) => state.toolCallId && state.toolCallId === props.toolCallId,
|
||||
);
|
||||
}, [states, props.toolCallId]);
|
||||
|
||||
if (!props.relativeFilePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<StyledMarkdownPreview
|
||||
isRenderingInStepContainer={true}
|
||||
source={src}
|
||||
disableManualApply={true}
|
||||
singleCodeblockStreamId={applyState?.streamId}
|
||||
expandCodeblocks={false}
|
||||
/>
|
||||
{/* TODO better indicator of generation at bottom */}
|
||||
{/* {isStreaming && applyState?.status === "streaming" && (
|
||||
<div className={`m-2 flex items-center justify-center`}>
|
||||
Generating...
|
||||
</div>
|
||||
)} */}
|
||||
{!isStreaming && applyState?.status === "done" && (
|
||||
<div className={`m-2 flex items-center justify-center`}>
|
||||
<AcceptRejectAllButtons
|
||||
pendingApplyStates={[applyState]}
|
||||
onAcceptOrReject={async (outcome) => {}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
import { ToolCall, ToolCallDelta, ToolCallState } from "core";
|
||||
import { ToolCallDelta, ToolCallState } from "core";
|
||||
import { BuiltInToolNames } from "core/tools/builtIn";
|
||||
import { CreateFile } from "./CreateFile";
|
||||
import { EditFile } from "./EditFile";
|
||||
import { RunTerminalCommand } from "./RunTerminalCommand";
|
||||
|
||||
function FunctionSpecificToolCallDiv({
|
||||
|
|
@ -12,14 +14,22 @@ function FunctionSpecificToolCallDiv({
|
|||
const args = toolCallState.parsedArgs;
|
||||
|
||||
switch (toolCall.function?.name) {
|
||||
case "builtin_create_new_file":
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return (
|
||||
<CreateFile
|
||||
relativeFilepath={args.filepath}
|
||||
fileContents={args.contents}
|
||||
/>
|
||||
);
|
||||
case "builtin_run_terminal_command":
|
||||
case BuiltInToolNames.EditExistingFile:
|
||||
return (
|
||||
<EditFile
|
||||
relativeFilePath={args.filepath}
|
||||
newContents={args.new_contents}
|
||||
toolCallId={toolCall.id}
|
||||
/>
|
||||
);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return (
|
||||
<RunTerminalCommand
|
||||
command={args.command}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { createSelector } from "@reduxjs/toolkit";
|
||||
import { ComboBoxItemType } from "../../components/mainInput/types";
|
||||
import {
|
||||
ComboBoxItem,
|
||||
ComboBoxItemType,
|
||||
} from "../../components/mainInput/types";
|
||||
import { RootState } from "../store";
|
||||
|
||||
export const selectSlashCommandComboBoxInputs = createSelector(
|
||||
|
|
@ -11,7 +14,8 @@ export const selectSlashCommandComboBoxInputs = createSelector(
|
|||
title: cmd.name,
|
||||
description: cmd.description,
|
||||
type: "slashCommand" as ComboBoxItemType,
|
||||
};
|
||||
content: cmd.prompt,
|
||||
} as ComboBoxItem;
|
||||
}) || []
|
||||
);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import {
|
|||
ToolCallDelta,
|
||||
ToolCallState,
|
||||
} from "core";
|
||||
import { BuiltInToolNames } from "core/tools/builtIn";
|
||||
import { NEW_SESSION_TITLE } from "core/util/constants";
|
||||
import { incrementalParseJson } from "core/util/incrementalParseJson";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
|
|
@ -53,7 +54,8 @@ type SessionState = {
|
|||
states: ApplyState[];
|
||||
curIndex: number;
|
||||
};
|
||||
newestCodeblockForInput: Record<string, string>;
|
||||
activeToolStreamId?: [string, string];
|
||||
newestToolbarPreviewForInput: Record<string, string>;
|
||||
};
|
||||
|
||||
function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) {
|
||||
|
|
@ -91,7 +93,7 @@ const initialState: SessionState = {
|
|||
curIndex: 0,
|
||||
},
|
||||
lastSessionId: undefined,
|
||||
newestCodeblockForInput: {},
|
||||
newestToolbarPreviewForInput: {},
|
||||
};
|
||||
|
||||
export const sessionSlice = createSlice({
|
||||
|
|
@ -353,16 +355,32 @@ export const sessionSlice = createSlice({
|
|||
if (message.role === "assistant" && message.toolCalls?.[0]) {
|
||||
const toolCallDelta = message.toolCalls[0];
|
||||
if (
|
||||
toolCallDelta.id &&
|
||||
toolCallDelta.function?.arguments &&
|
||||
toolCallDelta.function?.name &&
|
||||
toolCallDelta.type
|
||||
!(
|
||||
toolCallDelta.id &&
|
||||
toolCallDelta.function?.arguments &&
|
||||
toolCallDelta.function?.name &&
|
||||
toolCallDelta.type
|
||||
)
|
||||
) {
|
||||
console.warn(
|
||||
"Received streamed tool call without required fields",
|
||||
toolCallDelta,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
toolCallDelta.id &&
|
||||
toolCallDelta.function?.name ===
|
||||
BuiltInToolNames.EditExistingFile
|
||||
) {
|
||||
const streamId = uuidv4();
|
||||
state.codeBlockApplyStates.states.push({
|
||||
streamId,
|
||||
toolCallId: toolCallDelta.id,
|
||||
status: "streaming",
|
||||
});
|
||||
state.activeToolStreamId = [streamId, toolCallDelta.id];
|
||||
}
|
||||
historyItem.toolCallState = toolCallDeltaToState(toolCallDelta);
|
||||
}
|
||||
state.history.push(historyItem);
|
||||
|
|
@ -626,6 +644,7 @@ export const sessionSlice = createSlice({
|
|||
toolCallState.status = "canceled";
|
||||
},
|
||||
acceptToolCall: (state) => {
|
||||
state.activeToolStreamId = undefined;
|
||||
const toolCallState = findCurrentToolCall(state.history);
|
||||
if (!toolCallState) return;
|
||||
|
||||
|
|
@ -648,7 +667,7 @@ export const sessionSlice = createSlice({
|
|||
const nextIndex = (currentIndex + 1) % modes.length;
|
||||
state.mode = modes[nextIndex] as MessageModes;
|
||||
},
|
||||
setNewestCodeblocksForInput: (
|
||||
setNewestToolbarPreviewForInput: (
|
||||
state,
|
||||
{
|
||||
payload,
|
||||
|
|
@ -657,7 +676,8 @@ export const sessionSlice = createSlice({
|
|||
contextItemId: string;
|
||||
}>,
|
||||
) => {
|
||||
state.newestCodeblockForInput[payload.inputId] = payload.contextItemId;
|
||||
state.newestToolbarPreviewForInput[payload.inputId] =
|
||||
payload.contextItemId;
|
||||
},
|
||||
},
|
||||
selectors: {
|
||||
|
|
@ -716,7 +736,7 @@ export const selectCurrentToolCall = createSelector(
|
|||
export const selectApplyStateByStreamId = createSelector(
|
||||
[
|
||||
(state: RootState) => state.session.codeBlockApplyStates.states,
|
||||
(state: RootState, streamId: string) => streamId,
|
||||
(state: RootState, streamId?: string) => streamId,
|
||||
],
|
||||
(states, streamId) => {
|
||||
return states.find((state) => state.streamId === streamId);
|
||||
|
|
@ -758,7 +778,7 @@ export const {
|
|||
addSessionMetadata,
|
||||
updateSessionMetadata,
|
||||
deleteSessionMetadata,
|
||||
setNewestCodeblocksForInput,
|
||||
setNewestToolbarPreviewForInput,
|
||||
cycleMode,
|
||||
} = sessionSlice.actions;
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ type UIState = {
|
|||
toolSettings: { [toolName: string]: ToolSetting };
|
||||
toolGroupSettings: { [toolGroupName: string]: ToolGroupSetting };
|
||||
ttsActive: boolean;
|
||||
isBlockSettingsToolbarExpanded: boolean;
|
||||
};
|
||||
|
||||
export const DEFAULT_TOOL_SETTING: ToolSetting = "allowedWithPermission";
|
||||
|
|
@ -45,6 +44,7 @@ export const uiSlice = createSlice({
|
|||
ttsActive: false,
|
||||
toolSettings: {
|
||||
[BuiltInToolNames.ReadFile]: "allowedWithoutPermission",
|
||||
[BuiltInToolNames.EditExistingFile]: "allowedWithPermission",
|
||||
[BuiltInToolNames.CreateNewFile]: "allowedWithPermission",
|
||||
[BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission",
|
||||
[BuiltInToolNames.GrepSearch]: "allowedWithoutPermission",
|
||||
|
|
@ -56,7 +56,6 @@ export const uiSlice = createSlice({
|
|||
toolGroupSettings: {
|
||||
BUILT_IN_GROUP_NAME: "include",
|
||||
},
|
||||
isBlockSettingsToolbarExpanded: true,
|
||||
} as UIState,
|
||||
reducers: {
|
||||
setOnboardingCard: (
|
||||
|
|
@ -124,10 +123,6 @@ export const uiSlice = createSlice({
|
|||
setTTSActive: (state, { payload }: PayloadAction<boolean>) => {
|
||||
state.ttsActive = payload;
|
||||
},
|
||||
toggleBlockSettingsToolbar: (state) => {
|
||||
state.isBlockSettingsToolbarExpanded =
|
||||
!state.isBlockSettingsToolbarExpanded;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -142,7 +137,6 @@ export const {
|
|||
toggleToolGroupSetting,
|
||||
addTool,
|
||||
setTTSActive,
|
||||
toggleBlockSettingsToolbar,
|
||||
} = uiSlice.actions;
|
||||
|
||||
export default uiSlice.reducer;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue