From 7c1e082535426596347d30aeb4c77e2bd11b22d4 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 28 Mar 2025 14:54:02 -0700 Subject: [PATCH 01/93] replace localhost host with 127.0.0.1 --- packages/fetch/package.json | 2 +- packages/fetch/src/fetch.ts | 6 +++--- packages/fetch/src/stream.ts | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 6a7097284..e0a924706 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.4", + "version": "1.0.5", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 01fc631db..d4e8145d0 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -15,9 +15,9 @@ export function fetchwithRequestOptions( init?: RequestInit, requestOptions?: RequestOptions, ): Promise { - let url = url_; - if (typeof url === "string") { - url = new URL(url); + const url = typeof url_ === "string" ? new URL(url_) : url_; + if (url.host === "localhost") { + url.host = "127.0.0.1"; } const TIMEOUT = 7200; // 7200 seconds = 2 hours diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index d0e8e4633..7f33e377d 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -2,6 +2,7 @@ export async function* toAsyncIterable( nodeReadable: NodeJS.ReadableStream, ): AsyncGenerator { for await (const chunk of nodeReadable) { + // @ts-expect-error yield chunk as Uint8Array; } } From d0e922dad4947ac8af4e9d0c76921da56cdc2953 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 11:15:47 -0700 Subject: [PATCH 02/93] feat: if rules --- packages/config-yaml/src/schemas/index.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1ca03b0b6..afc9c1afc 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -28,6 +28,12 @@ const docSchema = z.object({ faviconUrl: z.string().optional(), }); +const ruleObjectSchema = z.object({ + name: z.string(), + rule: z.string(), + if: z.string().optional(), +}); + export const blockItemWrapperSchema = (schema: T) => z.object({ uses: z.string(), @@ -95,7 +101,9 @@ export const blockSchema = baseConfigYamlSchema.and( z.object({ context: z.array(contextSchema).length(1) }), z.object({ data: z.array(dataSchema).length(1) }), z.object({ mcpServers: z.array(mcpServerSchema).length(1) }), - z.object({ rules: z.array(z.string()).length(1) }), + z.object({ + rules: z.array(z.union([z.string(), ruleObjectSchema])).length(1), + }), z.object({ prompts: z.array(promptSchema).length(1) }), z.object({ docs: z.array(docSchema).length(1) }), ]), From 4480ee3ac358e60182304e0e052c27ae45815e2f Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 11:30:24 -0700 Subject: [PATCH 03/93] fix: unset system message --- core/config/yaml/loadYaml.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f2fefbb39..feafd170c 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -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: { From 79780e8d60421568b92dbb3d63adba9c713a3dcc Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 11:31:43 -0700 Subject: [PATCH 04/93] refactor: simplify --- core/llm/index.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index 028bc42c3..1b250d808 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -298,11 +298,6 @@ export abstract class BaseLLM implements ILLM { ); } - private _getSystemMessage(): string | undefined { - // TODO: Merge with config system message - return this.systemMessage; - } - private _templatePromptLikeMessages(prompt: string): string { if (!this.templateMessages) { return prompt; @@ -310,7 +305,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 }); } @@ -601,6 +596,7 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); + debugger; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -765,6 +761,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { + debugger; let { completionOptions, logEnabled } = this._parseCompletionOptions(options); From 44212e45828bb72c035bf63de4c13342935dcf0f Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 13:09:28 -0700 Subject: [PATCH 05/93] fix: types --- core/config/yaml/loadYaml.ts | 6 +++--- core/config/yaml/models.ts | 27 ++++++++++++++++++--------- core/llm/index.ts | 5 +++-- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index feafd170c..bd15c6ce6 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -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, - ); + systemMessage: continueConfig.systemMessage, + }); if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { continueConfig.models.push(...llms); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index e9d5bd55c..92e29debb 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -29,6 +29,7 @@ async function modelConfigToBaseLLM( platformConfigMetadata: PlatformConfigMetadata | undefined, systemMessage: string | undefined, ): Promise { + debugger; const cls = getModelClass(model); if (!cls) { @@ -167,15 +168,23 @@ async function autodetectModels( } } -export async function llmsFromModelConfig( - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +export async function llmsFromModelConfig({ + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + systemMessage, +}: { + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + systemMessage: string | undefined; +}): Promise { const baseLlm = await modelConfigToBaseLLM( model, uniqueId, diff --git a/core/llm/index.ts b/core/llm/index.ts index 1b250d808..410a70dc4 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -189,6 +189,7 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; this.systemMessage = options.systemMessage; + // debugger; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; this.maxStopWords = options.maxStopWords ?? this.maxStopWords; @@ -596,7 +597,7 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); - debugger; + // debugger; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -761,7 +762,7 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { - debugger; + // debugger; let { completionOptions, logEnabled } = this._parseCompletionOptions(options); From 4b120e543e7c2cec0d33714cfebe88800604fbfd Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 13:15:26 -0700 Subject: [PATCH 06/93] fix: types --- core/config/yaml/loadYaml.ts | 2 +- core/config/yaml/models.ts | 96 +++++++++++++++++++++--------------- 2 files changed, 57 insertions(+), 41 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index bd15c6ce6..f157bf21d 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -218,7 +218,7 @@ async function configYamlToContinueConfig( ideSettings, writeLog, platformConfigMetadata, - systemMessage: continueConfig.systemMessage, + config: continueConfig, }); if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 92e29debb..5e5088df8 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -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, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function modelConfigToBaseLLM({ + model, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { debugger; const cls = getModelClass(model); @@ -51,7 +58,7 @@ async function modelConfigToBaseLLM( writeLog, uniqueId, title: model.name, - systemMessage, + systemMessage: config.systemMessage, promptTemplates: model.promptTemplates, capabilities: { tools: model.capabilities?.includes("tool_use"), @@ -128,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, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +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; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { try { const modelNames = await llm.listModels(); const detectedModels = await Promise.all( @@ -147,8 +163,8 @@ async function autodetectModels( return undefined; } - return await modelConfigToBaseLLM( - { + return await modelConfigToBaseLLM({ + model: { ...model, model: modelName, name: modelName, @@ -157,8 +173,8 @@ async function autodetectModels( ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); }), ); return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[]; @@ -175,7 +191,7 @@ export async function llmsFromModelConfig({ ideSettings, writeLog, platformConfigMetadata, - systemMessage, + config, }: { model: ModelConfig; ide: IDE; @@ -183,31 +199,31 @@ export async function llmsFromModelConfig({ ideSettings: IdeSettings; writeLog: (log: string) => Promise; platformConfigMetadata: PlatformConfigMetadata | undefined; - systemMessage: string | undefined; + config: ContinueConfig; }): Promise { - const baseLlm = await modelConfigToBaseLLM( + 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]; From be27552e3330b3a18ecb1065b6ab7210a4375826 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 13:43:14 -0700 Subject: [PATCH 07/93] fix: types --- core/package.json | 2 +- packages/config-yaml/src/load/unroll.ts | 3 ++- packages/config-yaml/src/schemas/index.ts | 10 ++++++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/core/package.json b/core/package.json index 205e3b778..5cbe16115 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml/dist", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index f376fbc84..60dabf710 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -17,6 +17,7 @@ import { blockSchema, ConfigYaml, configYamlSchema, + Rule, } from "../schemas/index.js"; import { useProxyForUnrenderedSecrets } from "./clientRender.js"; @@ -315,7 +316,7 @@ export async function unrollBlocks( // Rules are a bit different because they're just strings, so handle separately if (assistant.rules) { - const rules: string[] = []; + const rules: Rule[] = []; for (const rule of assistant.rules) { if (typeof rule === "string") { rules.push(rule); diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index afc9c1afc..3a394ba05 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -34,6 +34,12 @@ const ruleObjectSchema = z.object({ if: z.string().optional(), }); +const ruleSchema = z.union([z.string(), ruleObjectSchema]); + +export type Rule = z.infer; + +export type RuleObject = z.infer; + export const blockItemWrapperSchema = (schema: T) => z.object({ uses: z.string(), @@ -88,7 +94,7 @@ export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ context: z.array(contextSchema).optional(), data: z.array(dataSchema).optional(), mcpServers: z.array(mcpServerSchema).optional(), - rules: z.array(z.string()).optional(), + rules: z.array(ruleSchema).optional(), prompts: z.array(promptSchema).optional(), docs: z.array(docSchema).optional(), }); @@ -102,7 +108,7 @@ export const blockSchema = baseConfigYamlSchema.and( z.object({ data: z.array(dataSchema).length(1) }), z.object({ mcpServers: z.array(mcpServerSchema).length(1) }), z.object({ - rules: z.array(z.union([z.string(), ruleObjectSchema])).length(1), + rules: z.array(ruleSchema).length(1), }), z.object({ prompts: z.array(promptSchema).length(1) }), z.object({ docs: z.array(docSchema).length(1) }), From 5faecca09f27a7490b4050b7191197c74fe38299 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 13:52:02 -0700 Subject: [PATCH 08/93] fix: types --- packages/config-yaml/src/load/unroll.ts | 2 +- packages/config-yaml/src/schemas/index.ts | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 60dabf710..a41b965fc 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -320,7 +320,7 @@ export async function unrollBlocks( for (const rule of assistant.rules) { if (typeof rule === "string") { rules.push(rule); - } else { + } else if ("uses" in rule) { const blockConfigYaml = await resolveBlock( decodeFullSlug(rule.uses), rule.with, diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 3a394ba05..ae12c99a7 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -38,8 +38,6 @@ const ruleSchema = z.union([z.string(), ruleObjectSchema]); export type Rule = z.infer; -export type RuleObject = z.infer; - export const blockItemWrapperSchema = (schema: T) => z.object({ uses: z.string(), @@ -75,7 +73,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ rules: z .array( z.union([ - z.string(), + ruleSchema, z.object({ uses: z.string(), with: z.record(z.string()).optional(), From 82cad596c85d0ee0b17ceccdf1f6cca5811b8f94 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 13:53:48 -0700 Subject: [PATCH 09/93] fix: types --- core/config/yaml/models.ts | 1 + core/index.d.ts | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 5e5088df8..fd1a0beff 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -59,6 +59,7 @@ async function modelConfigToBaseLLM({ uniqueId, title: model.name, systemMessage: config.systemMessage, + rules: config.rules, promptTemplates: model.promptTemplates, capabilities: { tools: model.capabilities?.includes("tool_use"), diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..9a6a40c21 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,4 @@ -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 { @@ -497,6 +497,7 @@ export interface LLMOptions { templateMessages?: (messages: ChatMessage[]) => string; writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; + rules?: Rule[]; apiKey?: string; // continueProperties @@ -1312,7 +1313,7 @@ export interface ContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1335,7 +1336,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; From 5c49505f2071504481c17976670d883efebddb4a Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 14:20:24 -0700 Subject: [PATCH 10/93] fix: type errors --- extensions/vscode/package-lock.json | 2 +- gui/package-lock.json | 2 +- .../mainInput/Lump/sections/RulesSection.tsx | 39 +++++++++++-------- packages/config-yaml/src/load/unroll.ts | 4 +- 4 files changed, 26 insertions(+), 21 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3b3f05ad0..699444702 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml/dist", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index 78eb2e61d..e963d2cf2 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -111,7 +111,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "file:../packages/config-yaml/dist", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 4cb7b0051..3b25e2efa 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -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"; @@ -17,7 +17,7 @@ import { ExploreBlocksButton } from "./ExploreBlocksButton"; interface RuleCardProps { index: number; - rule: string; + rule: Rule; onClick: () => void; title: string; } @@ -31,7 +31,10 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { setDialogMessage(

{title}

-
{rule}
+
+            {/** TODO: Render the rule in a more readable way */}
+            {JSON.stringify(rule)}
+          
, ), ); @@ -62,7 +65,8 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { }} className="line-clamp-3 text-gray-400" > - {rule} + {/** TODO: Render the rule in a more readable way */} + {JSON.stringify(rule)}
@@ -137,21 +141,22 @@ export function RulesSection() { ); } - if (!rule.ruleFromYaml?.uses) { - return null; + if ("uses" in rule.ruleFromYaml) { + const ruleSlug = rule.ruleFromYaml?.uses; + + return ( + openUrl(`${ruleSlug}/new-version`)} + title={ruleSlug} + /> + ); } - const ruleSlug = rule.ruleFromYaml?.uses; - - return ( - openUrl(`${ruleSlug}/new-version`)} - title={ruleSlug} - /> - ); + // TODO: Handle rules as object with 'if' + return null; })}
diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index a41b965fc..5a7549ddd 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -314,11 +314,11 @@ export async function unrollBlocks( } } - // Rules are a bit different because they're just strings, so handle separately + // Rules are a bit different because they can be strings, so hanlde separately if (assistant.rules) { const rules: Rule[] = []; for (const rule of assistant.rules) { - if (typeof rule === "string") { + if (typeof rule === "string" || !("uses" in rule)) { rules.push(rule); } else if ("uses" in rule) { const blockConfigYaml = await resolveBlock( From b20b1ab5ee44d704619327a3b087b1290c634dd7 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 16:03:10 -0700 Subject: [PATCH 11/93] feat: filttrex --- core/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/core/package.json b/core/package.json index 5cbe16115..f4e12a2d8 100644 --- a/core/package.json +++ b/core/package.json @@ -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", From 1a1b854fda4630e136d0d18b4ea69e71a00ced1e Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 2 Apr 2025 16:05:39 -0700 Subject: [PATCH 12/93] feat: evaluate rule --- core/llm/rules/isRuleActive.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 core/llm/rules/isRuleActive.ts diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts new file mode 100644 index 000000000..205b98138 --- /dev/null +++ b/core/llm/rules/isRuleActive.ts @@ -0,0 +1,17 @@ +import { Rule } from "@continuedev/config-yaml"; + +const evaluateIf = (condition: string) => { + return true; +}; + +export const isRuleActive = (rule: Rule): boolean => { + if (typeof rule === "string") { + return true; + } + + if (rule.if) { + return evaluateIf(rule.if); + } + + return true; +}; From 466deef9d6ff183a31a45b12a28bca7e638f5c55 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 2 Apr 2025 21:52:12 -0700 Subject: [PATCH 13/93] fix bedrock reranker credentials --- core/llm/llms/Bedrock.ts | 253 ++++++++++++++++++++++++--------------- 1 file changed, 154 insertions(+), 99 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 573170ece..7fefbd329 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -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 | null = null; private _promptCachingMetrics: PromptCachingMetrics = { cacheReadInputTokens: 0, - cacheWriteInputTokens: 0 + cacheWriteInputTokens: 0, }; - public requestOptions: { region?: string; credentials?: any; headers?: Record }; + public requestOptions: { + region?: string; + credentials?: any; + headers?: Record; + }; 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", + ); } } } From ea72a5a87e426de567594429fe2cd5107fb268af Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 2 Apr 2025 21:52:40 -0700 Subject: [PATCH 14/93] bump --- extensions/intellij/gradle.properties | 2 +- extensions/vscode/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index b9c409a6d..506f6bf62 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -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 diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 769ed476b..15599a1c0 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -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" From f95cdfaf83569159cd7aed02134be7dd5f4029cf Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 08:45:54 -0700 Subject: [PATCH 15/93] feat: rule glob --- packages/config-yaml/src/load/unroll.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 5a7549ddd..92a0b0157 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -63,7 +63,7 @@ export function parseBlock(configYaml: string): Block { } } -const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; +export const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; export function getTemplateVariables(templatedYaml: string): string[] { const variables = new Set(); From 2ffb4aefeb01073c924beb1c203e60c586cf96bb Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 09:20:41 -0700 Subject: [PATCH 16/93] feat: extract paths --- core/llm/utils/extractPathsFromCodeBlocks.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 core/llm/utils/extractPathsFromCodeBlocks.ts diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts new file mode 100644 index 000000000..98494ba0f --- /dev/null +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -0,0 +1,16 @@ +/** + * Extracts file paths from markdown code blocks + */ +export function extractPathsFromCodeBlocks(content: string): string[] { + const codeBlockRegex = /```[\w-+#]*\s+([^\s(]+)(?:\s|$|\()/g; + const paths: string[] = []; + let match; + + while ((match = codeBlockRegex.exec(content)) !== null) { + if (match[1]) { + paths.push(match[1]); + } + } + + return paths; +} From 4156d83171712789ba60fb97c7deb68ebb6c1ae7 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 09:28:41 -0700 Subject: [PATCH 17/93] refactor: clean up code --- core/llm/countTokens.ts | 57 ++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 16ac82100..6136aad3e 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -384,6 +384,39 @@ function chatMessageIsEmpty(message: ChatMessage): boolean { } } +function addSystemMessage( + 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 compileChatMessages( modelName: string, msgs: ChatMessage[] | undefined, @@ -410,29 +443,7 @@ 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); - } + msgsCopy = addSystemMessage(msgsCopy, systemMessage, msgs); let functionTokens = 0; if (functions) { From 0c0d0c92f65c74378822c254286e83a9b25133f3 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 09:32:13 -0700 Subject: [PATCH 18/93] refactor: clean up code --- core/llm/countTokens.ts | 29 +++++++++++++++++++---------- core/llm/index.ts | 18 ++++++++++-------- 2 files changed, 29 insertions(+), 18 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 6136aad3e..75d7bf5ff 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -417,16 +417,25 @@ function addSystemMessage( return messages; } -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 compileChatMessages({ + modelName, + msgs, + contextLength, + maxTokens, + supportsImages, + prompt, + functions, + systemMessage, +}: { + modelName: string; + msgs: ChatMessage[] | undefined; + contextLength: number; + maxTokens: number; + supportsImages: boolean; + prompt: string | undefined; + functions: any[] | undefined; + systemMessage: string | undefined; +}): ChatMessage[] { let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) diff --git a/core/llm/index.ts b/core/llm/index.ts index 410a70dc4..23cba7702 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -166,6 +166,7 @@ export abstract class BaseLLM implements ILLM { protected openaiAdapter?: BaseLlmApi; constructor(_options: LLMOptions) { + // debugger; this._llmOptions = _options; // Set default options @@ -287,19 +288,20 @@ 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, - ); + systemMessage: this.systemMessage, + }); } private _templatePromptLikeMessages(prompt: string): string { + debugger; if (!this.templateMessages) { return prompt; } From a3bc2e13f976e8575cfe4d32316fa9452dc2c566 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 09:36:18 -0700 Subject: [PATCH 19/93] refactor: clean up code --- core/llm/countTokens.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 75d7bf5ff..f2bc7b37d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -384,11 +384,15 @@ function chatMessageIsEmpty(message: ChatMessage): boolean { } } -function addSystemMessage( - messages: ChatMessage[], - systemMessage: string | undefined, - originalMessages: ChatMessage[] | undefined, -): ChatMessage[] { +function addSystemMessage({ + messages, + systemMessage, + originalMessages, +}: { + messages: ChatMessage[]; + systemMessage: string | undefined; + originalMessages: ChatMessage[] | undefined; +}): ChatMessage[] { if ( !(systemMessage && systemMessage.trim() !== "") && originalMessages?.[0]?.role !== "system" @@ -452,7 +456,11 @@ function compileChatMessages({ msgsCopy.push(promptMsg); } - msgsCopy = addSystemMessage(msgsCopy, systemMessage, msgs); + msgsCopy = addSystemMessage({ + messages: msgsCopy, + systemMessage, + originalMessages: msgs, + }); let functionTokens = 0; if (functions) { From 0b07020d7dd9bf59ca1d804668a215174273625b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 09:51:36 -0700 Subject: [PATCH 20/93] fix: messages --- core/llm/countTokens.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index f2bc7b37d..b733e1783 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -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, @@ -421,6 +427,30 @@ function addSystemMessage({ return messages; } +const getSystemMessage = ({ + userMessage, +}: { + userMessage: UserChatMessage; + rules: Rule[]; +}) => { + if (systemMessage) { + return ""; + } + + return systemMessage; +}; + +function getLastUserMessage(messages: ChatMessage[]): ChatMessage | 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]; + } + } + + return undefined; +} + function compileChatMessages({ modelName, msgs, @@ -440,6 +470,7 @@ function compileChatMessages({ functions: any[] | undefined; systemMessage: string | undefined; }): ChatMessage[] { + debugger; let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) @@ -456,6 +487,8 @@ function compileChatMessages({ msgsCopy.push(promptMsg); } + const lastUserMessage = getLastUserMessage(msgsCopy); + msgsCopy = addSystemMessage({ messages: msgsCopy, systemMessage, From ccdc1b953e22ca4aa26e32b9e80bc31ea30f274c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 09:54:33 -0700 Subject: [PATCH 21/93] feat: if-rules --- core/llm/countTokens.ts | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index b733e1783..9336dbfb2 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -429,22 +429,26 @@ function addSystemMessage({ const getSystemMessage = ({ userMessage, + rules, }: { - userMessage: UserChatMessage; + userMessage?: UserChatMessage; rules: Rule[]; }) => { - if (systemMessage) { - return ""; - } + return "Respond in Spanish"; + // if (systemMessage) { + // return ""; + // } - return systemMessage; + // return systemMessage; }; -function getLastUserMessage(messages: ChatMessage[]): ChatMessage | undefined { +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]; + return messages[i] as UserChatMessage; } } @@ -491,7 +495,12 @@ function compileChatMessages({ msgsCopy = addSystemMessage({ messages: msgsCopy, - systemMessage, + systemMessage: + systemMessage ?? + getSystemMessage({ + userMessage: lastUserMessage, + rules: [], + }), originalMessages: msgs, }); From 0a13a4604d7607793bea66b9cea3e89353bf3af4 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 10:00:21 -0700 Subject: [PATCH 22/93] feat: if-rules --- core/llm/countTokens.ts | 5 ++++- core/llm/index.ts | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 9336dbfb2..e5b895556 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -434,6 +434,7 @@ const getSystemMessage = ({ userMessage?: UserChatMessage; rules: Rule[]; }) => { + debugger; return "Respond in Spanish"; // if (systemMessage) { // return ""; @@ -464,6 +465,7 @@ function compileChatMessages({ prompt, functions, systemMessage, + rules, }: { modelName: string; msgs: ChatMessage[] | undefined; @@ -473,6 +475,7 @@ function compileChatMessages({ prompt: string | undefined; functions: any[] | undefined; systemMessage: string | undefined; + rules: Rule[]; }): ChatMessage[] { debugger; let msgsCopy = msgs @@ -499,7 +502,7 @@ function compileChatMessages({ systemMessage ?? getSystemMessage({ userMessage: lastUserMessage, - rules: [], + rules, }), originalMessages: msgs, }); diff --git a/core/llm/index.ts b/core/llm/index.ts index 23cba7702..9b5d5ebdd 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -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; @@ -244,6 +245,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; @@ -297,6 +299,7 @@ export abstract class BaseLLM implements ILLM { prompt: undefined, functions, systemMessage: this.systemMessage, + rules: this.rules ?? [], }); } From 9baa4e93be7f9c2fe057e453237eaa9d1aaa8ff0 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 10:29:13 -0700 Subject: [PATCH 23/93] feat: if-rule --- core/llm/countTokens.ts | 34 ++++++++++++++++++++++++++++------ core/llm/rules/isRuleActive.ts | 2 +- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index e5b895556..85c49f73c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -17,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"]; @@ -427,6 +429,27 @@ function addSystemMessage({ 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, @@ -434,13 +457,12 @@ const getSystemMessage = ({ userMessage?: UserChatMessage; rules: Rule[]; }) => { + const messageStringContent = getMessageStringContent(userMessage); + const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); debugger; - return "Respond in Spanish"; - // if (systemMessage) { - // return ""; - // } - - // return systemMessage; + return rules.filter((rule) => { + return isRuleActive({ rule }); + }); }; function getLastUserMessage( diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 205b98138..b6952db59 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -4,7 +4,7 @@ const evaluateIf = (condition: string) => { return true; }; -export const isRuleActive = (rule: Rule): boolean => { +export const isRuleActive = ({ rule }: { rule: Rule }): boolean => { if (typeof rule === "string") { return true; } From f19b6b8abdb4dfb64c804efee851dee0bb00471c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 10:29:52 -0700 Subject: [PATCH 24/93] fix: type errors --- core/llm/countTokens.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 85c49f73c..c27b0e9a0 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -460,9 +460,11 @@ const getSystemMessage = ({ const messageStringContent = getMessageStringContent(userMessage); const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); debugger; - return rules.filter((rule) => { - return isRuleActive({ rule }); - }); + return rules + .filter((rule) => { + return isRuleActive({ rule }); + }) + .join("\n"); }; function getLastUserMessage( From 9cb5170b1a23552f917265dc330ff1e05838a3de Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 10:45:42 -0700 Subject: [PATCH 25/93] feat: get paths --- core/llm/utils/extractPathsFromCodeBlocks.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts index 98494ba0f..7573a1f6f 100644 --- a/core/llm/utils/extractPathsFromCodeBlocks.ts +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -2,13 +2,19 @@ * Extracts file paths from markdown code blocks */ export function extractPathsFromCodeBlocks(content: string): string[] { - const codeBlockRegex = /```[\w-+#]*\s+([^\s(]+)(?:\s|$|\()/g; + // 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) { - if (match[1]) { - paths.push(match[1]); + const path = match[1]; + if (path && !path.startsWith("```")) { + paths.push(path); } } From 8c5ca401d4fbda64eacf23cc0585e2c9830db345 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 10:47:42 -0700 Subject: [PATCH 26/93] feat: glob rules --- core/llm/countTokens.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index c27b0e9a0..efb7c4eee 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -459,11 +459,17 @@ const getSystemMessage = ({ }) => { const messageStringContent = getMessageStringContent(userMessage); const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); - debugger; + return rules .filter((rule) => { return isRuleActive({ rule }); }) + .map((rule) => { + if (typeof rule === "string") { + return rule; + } + return rule.rule; + }) .join("\n"); }; From 05a3eec21ed1c26aa4d9825e6be5e209cdb9563c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 11:49:16 -0700 Subject: [PATCH 27/93] fix: regex --- core/llm/countTokens.ts | 2 +- core/llm/rules/isRuleActive.ts | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index efb7c4eee..175e0ba75 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -507,7 +507,7 @@ function compileChatMessages({ systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { - debugger; + // debugger; let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index b6952db59..402b0f23d 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -1,10 +1,25 @@ import { Rule } from "@continuedev/config-yaml"; +const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; + const evaluateIf = (condition: string) => { + debugger; + + const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); + + if (!expression) { + return false; + } + return true; }; - -export const isRuleActive = ({ rule }: { rule: Rule }): boolean => { +export const isRuleActive = ({ + rule, + activePaths, +}: { + rule: Rule; + activePaths: string[]; +}): boolean => { if (typeof rule === "string") { return true; } From 6224af63d36e6b96b068c6d4230ee2315bd94d43 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 11:54:53 -0700 Subject: [PATCH 28/93] feat: if rules --- core/llm/rules/isRuleActive.test.ts | 55 +++++++++++++++++++++++++++++ core/llm/rules/isRuleActive.ts | 35 +++++++++++++++--- 2 files changed, 85 insertions(+), 5 deletions(-) create mode 100644 core/llm/rules/isRuleActive.test.ts diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts new file mode 100644 index 000000000..1afcd84a0 --- /dev/null +++ b/core/llm/rules/isRuleActive.test.ts @@ -0,0 +1,55 @@ +import { isRuleActive } from "./isRuleActive"; + +describe("isRuleActive", () => { + it("evaluates glob patterns correctly", () => { + const activePaths = ["src/foo.ts", "src/bar.tsx", "README.md"]; + + expect( + isRuleActive({ + rule: { + name: "Test Rule", + rule: "Some rule", + if: '${{ glob("src/*.ts") }}', + }, + activePaths, + }), + ).toBe(true); + + expect( + isRuleActive({ + rule: { + name: "Test Rule", + rule: "Some rule", + if: '${{ glob("*.md") }}', + }, + activePaths, + }), + ).toBe(true); + + expect( + isRuleActive({ + rule: { + name: "Test Rule", + rule: "Some rule", + if: '${{ glob("*.py") }}', + }, + activePaths, + }), + ).toBe(false); + }); + + it("evaluates combined conditions correctly", () => { + const activePaths = ["src/foo.ts"]; + + expect( + isRuleActive({ + rule: { + name: "Test Rule", + rule: "Some rule", + if: '${{ glob("src/*.ts") && current.model === "gpt-4" }}', + }, + activePaths, + }), + ).toBe(true); + }); +}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 402b0f23d..827c485d0 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -1,18 +1,43 @@ import { Rule } from "@continuedev/config-yaml"; +import { compileExpression } from "filtrex"; +import { minimatch } from "minimatch"; const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; -const evaluateIf = (condition: string) => { - debugger; +const createGlobFunction = (activePaths: string[]) => { + return (pattern: string) => { + return activePaths.some((path) => minimatch(path, pattern)); + }; +}; +const evaluateIf = (condition: string, activePaths: string[]) => { const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); if (!expression) { - return false; + return true; } - return true; + try { + const context = { + glob: createGlobFunction(activePaths), + current: { + model: "gpt-4", // Hardcoded for now + }, + }; + + const evaluate = compileExpression(expression, { + extraFunctions: { + glob: (pattern: string) => context.glob(pattern), + }, + }); + + return evaluate(context); + } catch (error) { + console.error("Error evaluating rule condition:", error); + return false; + } }; + export const isRuleActive = ({ rule, activePaths, @@ -25,7 +50,7 @@ export const isRuleActive = ({ } if (rule.if) { - return evaluateIf(rule.if); + return evaluateIf(rule.if, activePaths); } return true; From 2620064c53ecf7de3d61b34043d2c0450f68b13c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 12:27:22 -0700 Subject: [PATCH 29/93] feat: rules --- core/llm/countTokens.ts | 2 +- core/llm/rules/isRuleActive.ts | 15 ++++++--------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 175e0ba75..c710c80c9 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -462,7 +462,7 @@ const getSystemMessage = ({ return rules .filter((rule) => { - return isRuleActive({ rule }); + return isRuleActive({ rule, activePaths: filePathsFromMessage }); }) .map((rule) => { if (typeof rule === "string") { diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 827c485d0..01cf1d98d 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -12,26 +12,23 @@ const createGlobFunction = (activePaths: string[]) => { const evaluateIf = (condition: string, activePaths: string[]) => { const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); - if (!expression) { return true; } try { - const context = { - glob: createGlobFunction(activePaths), - current: { - model: "gpt-4", // Hardcoded for now - }, - }; + debugger; const evaluate = compileExpression(expression, { extraFunctions: { - glob: (pattern: string) => context.glob(pattern), + glob: createGlobFunction(activePaths), + }, + constants: { + current: { model: "gpt-4" }, // Hardcoded for now }, }); - return evaluate(context); + return evaluate({}); } catch (error) { console.error("Error evaluating rule condition:", error); return false; From 06b76d752fb4f83b14053fffe2f85cb819e39ae6 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 12:32:25 -0700 Subject: [PATCH 30/93] feat: if-rules --- core/llm/rules/isRuleActive.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 01cf1d98d..197a816bf 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -19,12 +19,14 @@ const evaluateIf = (condition: string, activePaths: string[]) => { try { debugger; - const evaluate = compileExpression(expression, { - extraFunctions: { - glob: createGlobFunction(activePaths), - }, + const evaluate = compileExpression(`current.model == "gpt-4"`, { + // extraFunctions: { + // glob: createGlobFunction(activePaths), + // }, constants: { - current: { model: "gpt-4" }, // Hardcoded for now + current: { + model: "gpt-4", + }, }, }); From a6dd5a83dedcae099f320a2da9362490eadde299 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 12:38:30 -0700 Subject: [PATCH 31/93] fix: if rules --- core/llm/rules/isRuleActive.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 197a816bf..a7c6f6fbe 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -19,10 +19,10 @@ const evaluateIf = (condition: string, activePaths: string[]) => { try { debugger; - const evaluate = compileExpression(`current.model == "gpt-4"`, { - // extraFunctions: { - // glob: createGlobFunction(activePaths), - // }, + const evaluate = compileExpression(expression, { + extraFunctions: { + glob: createGlobFunction(activePaths), + }, constants: { current: { model: "gpt-4", From b39cb836ad6180226d39abe85f5637a6e2dac44d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 12:40:46 -0700 Subject: [PATCH 32/93] fix: rules --- core/llm/rules/isRuleActive.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index a7c6f6fbe..1d701a65a 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -17,8 +17,6 @@ const evaluateIf = (condition: string, activePaths: string[]) => { } try { - debugger; - const evaluate = compileExpression(expression, { extraFunctions: { glob: createGlobFunction(activePaths), From 211fcb77407cd261f2bb26198667388ea6270a05 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 13:36:33 -0700 Subject: [PATCH 33/93] feat: if-rule --- core/llm/countTokens.ts | 10 +++++++++- core/llm/rules/isRuleActive.ts | 21 ++++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index c710c80c9..7d4e415de 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -453,16 +453,22 @@ function getMessageStringContent(message?: UserChatMessage): string { 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 }); + return isRuleActive({ + rule, + activePaths: filePathsFromMessage, + currentModel, + }); }) .map((rule) => { if (typeof rule === "string") { @@ -525,6 +531,7 @@ function compileChatMessages({ } const lastUserMessage = getLastUserMessage(msgsCopy); + debugger; msgsCopy = addSystemMessage({ messages: msgsCopy, @@ -533,6 +540,7 @@ function compileChatMessages({ getSystemMessage({ userMessage: lastUserMessage, rules, + currentModel: modelName, }), originalMessages: msgs, }); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 1d701a65a..aa1a40f33 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -10,7 +10,19 @@ const createGlobFunction = (activePaths: string[]) => { }; }; -const evaluateIf = (condition: string, activePaths: string[]) => { +const contains = (str: string, searchStr: string): boolean => { + return str.toLowerCase().includes(searchStr.toLowerCase()); +}; + +const evaluateIf = ({ + condition, + activePaths, + currentModel, +}: { + condition: string; + activePaths: string[]; + currentModel: string; +}) => { const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); if (!expression) { return true; @@ -20,10 +32,11 @@ const evaluateIf = (condition: string, activePaths: string[]) => { const evaluate = compileExpression(expression, { extraFunctions: { glob: createGlobFunction(activePaths), + contains, }, constants: { current: { - model: "gpt-4", + model: { model: currentModel }, }, }, }); @@ -38,16 +51,18 @@ const evaluateIf = (condition: string, activePaths: string[]) => { export const isRuleActive = ({ rule, activePaths, + currentModel, }: { rule: Rule; activePaths: string[]; + currentModel: string; }): boolean => { if (typeof rule === "string") { return true; } if (rule.if) { - return evaluateIf(rule.if, activePaths); + return evaluateIf({ condition: rule.if, activePaths, currentModel }); } return true; From 2b97efe5c6d045b461c76068c0e06df298d95902 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 14:00:15 -0700 Subject: [PATCH 34/93] fix: isRuleActive --- core/llm/rules/isRuleActive.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index aa1a40f33..9215f997d 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -6,12 +6,14 @@ const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; const createGlobFunction = (activePaths: string[]) => { return (pattern: string) => { - return activePaths.some((path) => minimatch(path, pattern)); + const result = activePaths.some((path) => minimatch(path, pattern)); + debugger; + return result; }; }; const contains = (str: string, searchStr: string): boolean => { - return str.toLowerCase().includes(searchStr.toLowerCase()); + return str.includes(searchStr); }; const evaluateIf = ({ @@ -29,6 +31,7 @@ const evaluateIf = ({ } try { + debugger; const evaluate = compileExpression(expression, { extraFunctions: { glob: createGlobFunction(activePaths), From 81acb446019a773ce2df98467e4dcb8e5c2a428e Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 14:03:14 -0700 Subject: [PATCH 35/93] fix: tests --- core/llm/rules/isRuleActive.test.ts | 72 +++++++++++++---------------- 1 file changed, 32 insertions(+), 40 deletions(-) diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts index 1afcd84a0..db7dc1f5c 100644 --- a/core/llm/rules/isRuleActive.test.ts +++ b/core/llm/rules/isRuleActive.test.ts @@ -1,55 +1,47 @@ import { isRuleActive } from "./isRuleActive"; describe("isRuleActive", () => { - it("evaluates glob patterns correctly", () => { - const activePaths = ["src/foo.ts", "src/bar.tsx", "README.md"]; + it("should correctly evaluate combined contains and glob conditions", () => { + const rule = { + name: "My Rule", + rule: "Do no harm", + if: "${{ and(contains(current.model.model, 'claude-3-7-sonnet'), glob('*.tsx')) }}", + }; + // Should be false when activePaths is empty expect( isRuleActive({ - rule: { - name: "Test Rule", - rule: "Some rule", - if: '${{ glob("src/*.ts") }}', - }, - activePaths, + rule, + activePaths: [], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + + // Should be false when no matching paths + expect( + isRuleActive({ + rule, + activePaths: ["test.py", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + + // Should be true when both conditions are met + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx", "main.js"], + currentModel: "claude-3-7-sonnet", }), ).toBe(true); + // Should be false when only glob matches expect( isRuleActive({ - rule: { - name: "Test Rule", - rule: "Some rule", - if: '${{ glob("*.md") }}', - }, - activePaths, - }), - ).toBe(true); - - expect( - isRuleActive({ - rule: { - name: "Test Rule", - rule: "Some rule", - if: '${{ glob("*.py") }}', - }, - activePaths, + rule, + activePaths: ["Component.tsx"], + currentModel: "gpt-4", }), ).toBe(false); }); - - it("evaluates combined conditions correctly", () => { - const activePaths = ["src/foo.ts"]; - - expect( - isRuleActive({ - rule: { - name: "Test Rule", - rule: "Some rule", - if: '${{ glob("src/*.ts") && current.model === "gpt-4" }}', - }, - activePaths, - }), - ).toBe(true); - }); }); From 6d27ac6777ba3a1992ff6753eee955ca7064d49e Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 14:05:53 -0700 Subject: [PATCH 36/93] test: rules --- core/llm/rules/isRuleActive.test.ts | 32 ++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts index db7dc1f5c..6d7bd0d04 100644 --- a/core/llm/rules/isRuleActive.test.ts +++ b/core/llm/rules/isRuleActive.test.ts @@ -1,14 +1,13 @@ import { isRuleActive } from "./isRuleActive"; describe("isRuleActive", () => { - it("should correctly evaluate combined contains and glob conditions", () => { - const rule = { - name: "My Rule", - rule: "Do no harm", - if: "${{ and(contains(current.model.model, 'claude-3-7-sonnet'), glob('*.tsx')) }}", - }; + const rule = { + name: "My Rule", + rule: "Do no harm", + if: "${{ and(contains(current.model.model, 'claude-3-7-sonnet') and glob('*.tsx')) }}", + }; - // Should be false when activePaths is empty + it("should return false when activePaths is empty", () => { expect( isRuleActive({ rule, @@ -16,8 +15,9 @@ describe("isRuleActive", () => { currentModel: "claude-3-7-sonnet", }), ).toBe(false); + }); - // Should be false when no matching paths + it("should return false when no matching paths exist", () => { expect( isRuleActive({ rule, @@ -25,8 +25,9 @@ describe("isRuleActive", () => { currentModel: "claude-3-7-sonnet", }), ).toBe(false); + }); - // Should be true when both conditions are met + it("should return true when both conditions are met", () => { expect( isRuleActive({ rule, @@ -34,8 +35,9 @@ describe("isRuleActive", () => { currentModel: "claude-3-7-sonnet", }), ).toBe(true); + }); - // Should be false when only glob matches + it("should return false when only glob matches but model doesn't", () => { expect( isRuleActive({ rule, @@ -44,4 +46,14 @@ describe("isRuleActive", () => { }), ).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); + }); }); From cb2e0a7c0e9330d9b79a3e9878c851b9eba92ade Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 14:48:00 -0700 Subject: [PATCH 37/93] fix: failing tests --- core/llm/rules/isRuleActive.test.ts | 2 +- core/llm/rules/isRuleActive.ts | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts index 6d7bd0d04..f50b9972a 100644 --- a/core/llm/rules/isRuleActive.test.ts +++ b/core/llm/rules/isRuleActive.test.ts @@ -4,7 +4,7 @@ describe("isRuleActive", () => { const rule = { name: "My Rule", rule: "Do no harm", - if: "${{ and(contains(current.model.model, 'claude-3-7-sonnet') and glob('*.tsx')) }}", + if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', }; it("should return false when activePaths is empty", () => { diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 9215f997d..47125c644 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -7,7 +7,6 @@ const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; const createGlobFunction = (activePaths: string[]) => { return (pattern: string) => { const result = activePaths.some((path) => minimatch(path, pattern)); - debugger; return result; }; }; @@ -31,16 +30,13 @@ const evaluateIf = ({ } try { - debugger; const evaluate = compileExpression(expression, { extraFunctions: { glob: createGlobFunction(activePaths), contains, }, constants: { - current: { - model: { model: currentModel }, - }, + "current.model.model": currentModel, }, }); From ea6b2344d0b2cde7def58de549e604142a40a353 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 14:55:37 -0700 Subject: [PATCH 38/93] fix: type errors --- core/llm/countTokens.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts index 6895e9269..92f9d92c5 100644 --- a/core/llm/countTokens.test.ts +++ b/core/llm/countTokens.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck // Generated by continue import { ChatMessage, MessagePart } from "../index.js"; import { From 2820f43503743ec33d1b12951f7f9fc261ee6cc5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 14:56:22 -0700 Subject: [PATCH 39/93] improv: clean up --- .../context/root-path-context/RootPathContextService.ts | 2 -- core/llm/countTokens.ts | 1 - core/llm/index.ts | 4 ---- 3 files changed, 7 deletions(-) diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 79b598f1e..7a29f8a8f 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -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 = diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 7d4e415de..241c0f29d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -513,7 +513,6 @@ function compileChatMessages({ systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { - // debugger; let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) diff --git a/core/llm/index.ts b/core/llm/index.ts index 9b5d5ebdd..42b63cafd 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -167,7 +167,6 @@ export abstract class BaseLLM implements ILLM { protected openaiAdapter?: BaseLlmApi; constructor(_options: LLMOptions) { - // debugger; this._llmOptions = _options; // Set default options @@ -191,7 +190,6 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; this.systemMessage = options.systemMessage; - // debugger; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; this.maxStopWords = options.maxStopWords ?? this.maxStopWords; @@ -602,7 +600,6 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); - // debugger; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -767,7 +764,6 @@ export abstract class BaseLLM implements ILLM { signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { - // debugger; let { completionOptions, logEnabled } = this._parseCompletionOptions(options); From d2545e48d2bba2fde0084e99cd0a78947ed4c573 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:21:35 -0700 Subject: [PATCH 40/93] improv: clean up code --- core/config/yaml/models.ts | 1 - core/llm/countTokens.ts | 1 - core/llm/index.ts | 1 - .../mainInput/Lump/sections/RulesSection.tsx | 23 +++++++++++++++---- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index fd1a0beff..6eabfd040 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -36,7 +36,6 @@ async function modelConfigToBaseLLM({ platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { - debugger; const cls = getModelClass(model); if (!cls) { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 241c0f29d..4f04a3925 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -530,7 +530,6 @@ function compileChatMessages({ } const lastUserMessage = getLastUserMessage(msgsCopy); - debugger; msgsCopy = addSystemMessage({ messages: msgsCopy, diff --git a/core/llm/index.ts b/core/llm/index.ts index 42b63cafd..cc7d7123c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -302,7 +302,6 @@ export abstract class BaseLLM implements ILLM { } private _templatePromptLikeMessages(prompt: string): string { - debugger; if (!this.templateMessages) { return prompt; } diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 3b25e2efa..6bb3d1637 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -40,6 +40,23 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { ); } + const renderRuleContent = () => { + if (typeof rule === "string") { + return
{rule}
; + } + + if (rule.rule) { + return ( +
+
{rule.rule}
+ {rule.if &&
if: {rule.if}
} +
+ ); + } + + return
{JSON.stringify(rule)}
; + }; + return (
= ({ index, rule, onClick, title }) => { }} className="line-clamp-3 text-gray-400" > - {/** TODO: Render the rule in a more readable way */} - {JSON.stringify(rule)} + {renderRuleContent()}
@@ -163,6 +179,3 @@ export function RulesSection() {
); } -function useTypedDispatch() { - throw new Error("Function not implemented."); -} From fccae8732e1a4f447ff0ab650e9ae717c2022ffc Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:23:12 -0700 Subject: [PATCH 41/93] fix: dependencies --- core/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/package.json b/core/package.json index f4e12a2d8..d709d6b8c 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "file:../packages/config-yaml/dist", + "@continuedev/config-yaml": "^1.0.67", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", From cc063fdd124d66515bdcb9e2c64f575b40cc99d8 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:25:00 -0700 Subject: [PATCH 42/93] fix: dependencies --- core/package-lock.json | 14 ++++++++++---- core/package.json | 2 +- gui/package-lock.json | 3 ++- package-lock.json | 4 ++-- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index 50df2a6f3..f92a977f8 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@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", @@ -2974,9 +2975,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.70", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.70.tgz", + "integrity": "sha512-0hwc2a2NyUDDNDAx23SOFfY4sV8EafuCow4JNpRzCz8swH3ZfO+vdOzKMIEzAzcYXcpjldsOAZsYE4iypu1L+Q==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -8585,6 +8586,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", diff --git a/core/package.json b/core/package.json index d709d6b8c..0287c2611 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index e963d2cf2..1769ac246 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -111,7 +111,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "file:../packages/config-yaml/dist", + "@continuedev/config-yaml": "^1.0.68", "@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", diff --git a/package-lock.json b/package-lock.json index 6a0a55705..cdfb21273 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,8 @@ "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", - "prettier-plugin-tailwindcss": "^0.6.8" + "prettier-plugin-tailwindcss": "^0.6.8", + "typescript": "^5.6.3" } }, "node_modules/@eslint-community/eslint-utils": { @@ -2976,7 +2977,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" From e4d1d8fda1e14102baeea732212436bac93e31c8 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 3 Apr 2025 15:25:35 -0700 Subject: [PATCH 43/93] readme for publishing --- packages/config-yaml/package.json | 2 +- packages/config-yaml/src/README.md | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index d7d96c4f0..703632362 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.67", + "version": "1.0.71", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/README.md b/packages/config-yaml/src/README.md index 4ef80cb49..550563891 100644 --- a/packages/config-yaml/src/README.md +++ b/packages/config-yaml/src/README.md @@ -15,3 +15,14 @@ This happens on the server, unless using local mode. ## Client rendering The unrolled config.yaml is then rendered on the client. This is done by replacing all user secret template variables with their values and replacing all other secrets with secret locations. + +## Publishing + +First, bump the version in `package.json` and then run: + +```bash +npm run build +npm publish --access public +``` + +Make sure you have an `NPM_TOKEN` set in your `packages/config-yaml/.env` file. From 8efb3be1b1f2253f9a7fd3035d8f0055de8f426e Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:25:49 -0700 Subject: [PATCH 44/93] fix: dependencies --- core/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/package.json b/core/package.json index 0287c2611..759c4705c 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.68", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", From 07bf42548cd75ce59f35055fd93e802e8025ffdb Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 3 Apr 2025 15:28:49 -0700 Subject: [PATCH 45/93] bump version --- core/package-lock.json | 14 ++++++++++---- core/package.json | 2 +- gui/package-lock.json | 11 ++++++----- gui/package.json | 2 +- packages/config-yaml/src/README.md | 6 +++--- 5 files changed, 21 insertions(+), 14 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index 50df2a6f3..41257b92f 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.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", @@ -2974,9 +2975,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", @@ -8585,6 +8586,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", diff --git a/core/package.json b/core/package.json index d709d6b8c..759c4705c 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.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", diff --git a/gui/package-lock.json b/gui/package-lock.json index e963d2cf2..025b11b27 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -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.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "file:../packages/config-yaml/dist", + "@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", diff --git a/gui/package.json b/gui/package.json index 3210a55f5..fa4b439af 100644 --- a/gui/package.json +++ b/gui/package.json @@ -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", diff --git a/packages/config-yaml/src/README.md b/packages/config-yaml/src/README.md index 550563891..c68cd8fdc 100644 --- a/packages/config-yaml/src/README.md +++ b/packages/config-yaml/src/README.md @@ -18,11 +18,11 @@ The unrolled config.yaml is then rendered on the client. This is done by replaci ## Publishing -First, bump the version in `package.json` and then run: +Make sure you are logged into the npm registry with `npm login`. + +Then, bump the version in `package.json` and then run: ```bash npm run build npm publish --access public ``` - -Make sure you have an `NPM_TOKEN` set in your `packages/config-yaml/.env` file. From 93c93a871fde3d5db1fabbef3c31632b6a7e49d8 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:42:38 -0700 Subject: [PATCH 46/93] fix: node modules eslint --- extensions/vscode/.eslintrc.json | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index f4973fa87..3bf3ca621 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -4,6 +4,7 @@ "project": "./tsconfig.json" }, "extends": ["../../.eslintrc.shared.json"], + "ignorePatterns": ["**/node_modules/**", "dist/**"], "rules": { "@typescript-eslint/naming-convention": "off" } From 648829fe007e9c5cf8ea8b7c22444817be8a8c69 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:46:51 -0700 Subject: [PATCH 47/93] Revert "fix: node modules eslint" This reverts commit 93c93a871fde3d5db1fabbef3c31632b6a7e49d8. --- extensions/vscode/.eslintrc.json | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index 3bf3ca621..f4973fa87 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -4,7 +4,6 @@ "project": "./tsconfig.json" }, "extends": ["../../.eslintrc.shared.json"], - "ignorePatterns": ["**/node_modules/**", "dist/**"], "rules": { "@typescript-eslint/naming-convention": "off" } From 384fb562e5aac023301d592a186982a4b575fe98 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:47:12 -0700 Subject: [PATCH 48/93] fix: dependencies --- binary/package-lock.json | 3 ++- extensions/vscode/package-lock.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index d1c773550..087f976bb 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.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", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 699444702..9e01ab495 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "file:../packages/config-yaml/dist", + "@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", From e83cd625eee9c2dc46a3868b0a8d2cea8e9da177 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:48:11 -0700 Subject: [PATCH 49/93] fix: tsconfig --- extensions/vscode/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b35899669..b353eb71f 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -17,6 +17,7 @@ "../../core/dist/**/*", "../../core/**/*.test.ts", "../../core/**/test/**/*", - "../../core/**/*.skip.ts" + "../../core/**/*.skip.ts", + "../../core/node_modules/**/*" ] } From c73c388e10f03893efbb6b743630ee89d4842150 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:48:59 -0700 Subject: [PATCH 50/93] Revert "fix: tsconfig" This reverts commit e83cd625eee9c2dc46a3868b0a8d2cea8e9da177. --- extensions/vscode/tsconfig.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b353eb71f..b35899669 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -17,7 +17,6 @@ "../../core/dist/**/*", "../../core/**/*.test.ts", "../../core/**/test/**/*", - "../../core/**/*.skip.ts", - "../../core/node_modules/**/*" + "../../core/**/*.skip.ts" ] } From 8549981e200e7e62f4a5895babc1c87c45b59db0 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 3 Apr 2025 15:51:17 -0700 Subject: [PATCH 51/93] fix: tsconfig --- extensions/vscode/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b35899669..a7a58f894 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -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"], From 9df325a71f3340c46820ac5335249095cda443ac Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 3 Apr 2025 16:51:42 -0700 Subject: [PATCH 52/93] feat: prompt blocks --- .continue/rules/use-tailwind-not-styled.md | 3 + core/index.d.ts | 1 + .../ConversationStarterCards.tsx | 32 +- gui/src/components/FileIcon.tsx | 6 +- .../gui/HeaderButtonWithToolTip.tsx | 2 +- .../components/mainInput/ContinueInputBox.tsx | 2 +- .../Lump/sections/docs/DocsIndexingStatus.tsx | 9 +- .../{tiptap => TipTapEditor}/DragOverlay.tsx | 0 .../StyledComponents.ts | 0 .../{tiptap => TipTapEditor}/TipTapEditor.css | 0 .../{tiptap => TipTapEditor}/TipTapEditor.tsx | 7 +- .../extensions/AddCodeToEditExtension.ts | 19 +- .../extensions/CodeBlockExtension.tsx | 8 +- .../extensions/MentionExtension.ts | 19 +- .../extensions/PromptExtension.ts | 81 ++++ .../extensions/SlashCommandExtension.ts} | 75 +++- .../TipTapEditor/extensions/index.ts | 5 + .../TipTapEditor/extensions/types.ts | 11 + .../toolbar-previews/CodeblockPreview.tsx | 100 +++++ .../toolbar-previews/ExpandablePreview.tsx | 186 ++++++++++ .../toolbar-previews/PromptBlockPreview.tsx | 61 ++++ .../TipTapEditor/toolbar-previews/index.ts | 2 + .../useWebviewListeners.ts | 6 +- .../utils}/editorConfig.ts | 59 ++- .../utils}/getSuggestion.ts | 25 +- .../utils}/imageUtils.ts | 2 +- .../mainInput/TipTapEditor/utils/index.ts | 5 + .../utils}/keyHandlers.ts | 8 +- .../utils/resolveEditorContent.ts | 345 ++++++++++++++++++ .../mainInput/tiptap/CodeBlockComponent.tsx | 42 --- .../mainInput/tiptap/resolveInput.ts | 277 -------------- .../mainInput/util/handleMetaKeyIssues.ts | 3 +- .../markdown/CodeSnippetPreview.tsx | 184 ---------- .../markdown/StyledMarkdownPreview.tsx | 6 +- gui/src/pages/gui/Chat.tsx | 8 +- gui/src/redux/selectors/index.ts | 8 +- gui/src/redux/store.ts | 4 +- gui/src/redux/thunks/gatherContext.ts | 2 +- gui/src/redux/thunks/updateFileSymbols.ts | 7 +- gui/tailwind.config.cjs | 2 + 40 files changed, 996 insertions(+), 626 deletions(-) create mode 100644 .continue/rules/use-tailwind-not-styled.md rename gui/src/components/mainInput/{tiptap => TipTapEditor}/DragOverlay.tsx (100%) rename gui/src/components/mainInput/{tiptap => TipTapEditor}/StyledComponents.ts (100%) rename gui/src/components/mainInput/{tiptap => TipTapEditor}/TipTapEditor.css (100%) rename gui/src/components/mainInput/{tiptap => TipTapEditor}/TipTapEditor.tsx (97%) rename gui/src/components/mainInput/{tiptap => TipTapEditor}/extensions/AddCodeToEditExtension.ts (88%) rename gui/src/components/mainInput/{tiptap => TipTapEditor}/extensions/CodeBlockExtension.tsx (75%) rename gui/src/components/mainInput/{tiptap => TipTapEditor}/extensions/MentionExtension.ts (90%) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts rename gui/src/components/mainInput/{tiptap/extensions/CommandsExtension.ts => TipTapEditor/extensions/SlashCommandExtension.ts} (66%) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/index.ts create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/types.ts create mode 100644 gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx create mode 100644 gui/src/components/mainInput/TipTapEditor/toolbar-previews/ExpandablePreview.tsx create mode 100644 gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx create mode 100644 gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts rename gui/src/components/mainInput/{tiptap => TipTapEditor}/useWebviewListeners.ts (97%) rename gui/src/components/mainInput/{tiptap => TipTapEditor/utils}/editorConfig.ts (90%) rename gui/src/components/mainInput/{tiptap => TipTapEditor/utils}/getSuggestion.ts (91%) rename gui/src/components/mainInput/{tiptap => TipTapEditor/utils}/imageUtils.ts (96%) create mode 100644 gui/src/components/mainInput/TipTapEditor/utils/index.ts rename gui/src/components/mainInput/{tiptap => TipTapEditor/utils}/keyHandlers.ts (90%) create mode 100644 gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts delete mode 100644 gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx delete mode 100644 gui/src/components/mainInput/tiptap/resolveInput.ts delete mode 100644 gui/src/components/markdown/CodeSnippetPreview.tsx diff --git a/.continue/rules/use-tailwind-not-styled.md b/.continue/rules/use-tailwind-not-styled.md new file mode 100644 index 000000000..8a3ec0b3d --- /dev/null +++ b/.continue/rules/use-tailwind-not-styled.md @@ -0,0 +1,3 @@ +Always use Tailwind classes, not styled components. + +If a component is using styled components, it should be converted to use Tailwind classes. diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..913d9167f 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,6 +1,7 @@ import { DataDestination, ModelRole } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; + declare global { interface Window { ide?: "vscode"; diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 7e0e2e183..b8004b472 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -1,9 +1,16 @@ import { SlashCommandDescription } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; +import { MAIN_EDITOR_INPUT_ID } from "../../pages/gui/Chat"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setMainEditorContentTrigger } from "../../redux/slices/sessionSlice"; -import { getParagraphNodeFromString } from "../mainInput/utils"; +import { + setMainEditorContentTrigger, + setNewestCodeblocksForInput, +} from "../../redux/slices/sessionSlice"; +import { + createParagraphNodeFromSlashCmdDescription, + createPromptBlockNodeFromSlashCmdDescription, +} from "../mainInput/TipTapEditor/extensions"; import { ConversationStarterCard } from "./ConversationStarterCard"; const NUM_CARDS_TO_RENDER = 5; @@ -21,11 +28,22 @@ export function ConversationStarterCards() { ); function onClick(command: SlashCommandDescription) { - if (command.prompt) { - dispatch( - setMainEditorContentTrigger(getParagraphNodeFromString(command.prompt)), - ); - } + dispatch( + setNewestCodeblocksForInput({ + inputId: MAIN_EDITOR_INPUT_ID, + contextItemId: command.name, + }), + ); + + dispatch( + setMainEditorContentTrigger({ + type: "doc", + content: [ + createPromptBlockNodeFromSlashCmdDescription(command), + createParagraphNodeFromSlashCmdDescription(command), + ], + }), + ); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 6f96e498d..ab0d338dd 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -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(" (")) { @@ -33,6 +34,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { ignore: "#586e75", }); + console.log({ file }); // Sanitize the SVG string before rendering it const { svg, color } = getIcon(file); const sanitizedSVG = DOMPurify.sanitize(svg); diff --git a/gui/src/components/gui/HeaderButtonWithToolTip.tsx b/gui/src/components/gui/HeaderButtonWithToolTip.tsx index 8c357d5ea..2ee4496fe 100644 --- a/gui/src/components/gui/HeaderButtonWithToolTip.tsx +++ b/gui/src/components/gui/HeaderButtonWithToolTip.tsx @@ -48,7 +48,7 @@ const HeaderButtonWithToolTip = React.forwardRef< - {props.text} + {props.text} ); diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index cf2b4cf46..30ddd30f2 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -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/TipTapEditor"; interface ContinueInputBoxProps { isEditMode?: boolean; diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx index 51b9d35c3..777d30e4e 100644 --- a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx @@ -78,7 +78,7 @@ function DocsIndexingStatus({ if (hasDeleted) return null; return ( -
+
@@ -90,13 +90,6 @@ function DocsIndexingStatus({ } }} > - {docConfig.faviconUrl ? ( - doc icon - ) : null}

; - renderHTML: (props: { - options: MentionOptions; - node: ProseMirrorNode; - }) => DOMOutputSpec; - suggestion: Omit; -}; +export const ADD_CODE_TO_EDIT_NAME = "add-code-to-edit"; -export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit"); +export const AddCodeToEditPluginKey = new PluginKey(ADD_CODE_TO_EDIT_NAME); -export const AddCodeToEdit = Node.create({ - name: "add-code-to-edit", +export const AddCodeToEditExtension = Node.create({ + name: ADD_CODE_TO_EDIT_NAME, addOptions() { return { diff --git a/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlockExtension.tsx similarity index 75% rename from gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeBlockExtension.tsx index aea6e18af..3618a69ba 100644 --- a/gui/src/components/mainInput/tiptap/extensions/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlockExtension.tsx @@ -1,9 +1,11 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeBlockComponent } from "../CodeBlockComponent"; +import { CodeblockPreview } from "../toolbar-previews/CodeblockPreview"; + +export const CODEBLOCK_NAME = "codeblock"; export const CodeBlockExtension = Node.create({ - name: "codeBlock", + name: CODEBLOCK_NAME, group: "block", @@ -37,6 +39,6 @@ export const CodeBlockExtension = Node.create({ }, addNodeView() { - return ReactNodeViewRenderer(CodeBlockComponent); + return ReactNodeViewRenderer(CodeblockPreview); }, }); diff --git a/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts index 364b241ee..b81d223b4 100644 --- a/gui/src/components/mainInput/tiptap/extensions/MentionExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts @@ -1,21 +1,14 @@ 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"; +import Suggestion from "@tiptap/suggestion"; +import { MentionOptions } from "./types"; -export type MentionOptions = { - HTMLAttributes: Record; - renderHTML: (props: { - options: MentionOptions; - node: ProseMirrorNode; - }) => DOMOutputSpec; - suggestion: Omit; -}; +export const MENTION_NAME = "mention"; -export const MentionPluginKey = new PluginKey("mention"); +export const MentionPluginKey = new PluginKey(MENTION_NAME); -export const Mention = Node.create({ - name: "mention", +export const MentionExtension = Node.create({ + name: MENTION_NAME, addOptions() { return { diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts new file mode 100644 index 000000000..d5c5b6d7b --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts @@ -0,0 +1,81 @@ +import { mergeAttributes, Node } from "@tiptap/core"; +import { ReactNodeViewRenderer } from "@tiptap/react"; +import { ContextItemWithId, SlashCommandDescription } from "core"; +import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; +import { PromptBlockPreview } from "../toolbar-previews/PromptBlockPreview"; + +export interface PromptOptions { + HTMLAttributes: Record; +} + +export const PROMPT_BLOCK_NAME = "prompt-block"; + +/** + * Extension for adding prompt blocks to the Tiptap editor + */ +export const PromptExtension = Node.create({ + name: PROMPT_BLOCK_NAME, + group: "block", + // atom: true, + // draggable: true, + + addOptions() { + return { + HTMLAttributes: {}, + }; + }, + + 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); + }, +}); + +/** + * Creates a prompt block node from a slash command description + * @param command The slash command description to create the block from + * @param inputId Optional input ID, defaults to main editor input ID + * @returns A node object representing the prompt block + */ +export const createPromptBlockNodeFromSlashCmdDescription = ( + command: SlashCommandDescription, + inputId: string = MAIN_EDITOR_INPUT_ID, +) => { + return { + type: PromptExtension.name, + attrs: { + item: { + content: command.prompt, + name: command.name, + description: command.description || "", + id: { + providerTitle: "prompt", + itemId: command.name, + }, + } as ContextItemWithId, + inputId, + }, + }; +}; diff --git a/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts similarity index 66% rename from gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts index 0c25d7cca..eb97e6227 100644 --- a/gui/src/components/mainInput/tiptap/extensions/CommandsExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts @@ -4,29 +4,31 @@ 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"; +import { ContextItemWithId, SlashCommandDescription } from "core"; +import { v4 as uuidv4 } from "uuid"; export type SlashCommandOptions = { HTMLAttributes: Record; - renderText: (props: { - options: SlashCommandOptions; - node: ProseMirrorNode; - }) => string; + renderText: (props: { node: ProseMirrorNode }) => string; suggestion: Omit; }; -export const SlashCommandPluginKey = new PluginKey("slashcommand"); +export const SLASH_CMD_NAME = "slash-command"; +export const SLASH_CMD_SUGGESTION_CHAR = "/"; -export const SlashCommand = Node.create({ - name: "slashcommand", +export const SlashCommandPluginKey = new PluginKey(SLASH_CMD_NAME); + +export const SlashCommandExtension = Node.create({ + name: SLASH_CMD_NAME, addOptions() { return { HTMLAttributes: {}, - renderText({ options, node }) { - return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`; + renderText({ node }) { + return node.attrs.label ?? node.attrs.id; }, suggestion: { - char: "/", + char: SLASH_CMD_SUGGESTION_CHAR, pluginKey: SlashCommandPluginKey, startOfLine: true, command: ({ editor, range, props }) => { @@ -54,6 +56,31 @@ export const SlashCommand = Node.create({ ]) .run(); + const promptId = uuidv4(); + + // Create a generic "promptToPromptBlockExtension" fn + // For here and in the conversation starters + + editor + .chain() + .focus() + .insertContentAt(0, { + type: "promptBlock", + attrs: { + item: { + content: props.content, + name: props.title, + description: props.description, + id: { + providerTitle: "prompt", + itemId: props.name, + }, + } as ContextItemWithId, + inputId: promptId, + }, + }) + .run(); + window.getSelection()?.collapseToEnd(); }, allow: ({ state, range }) => { @@ -124,7 +151,6 @@ export const SlashCommand = Node.create({ HTMLAttributes, ), this.options.renderText({ - options: this.options, node, }), ]; @@ -132,7 +158,6 @@ export const SlashCommand = Node.create({ renderText({ node }) { return this.options.renderText({ - options: this.options, node, }); }, @@ -176,3 +201,29 @@ export const SlashCommand = Node.create({ ]; }, }); + +/** + * Creates a paragraph node containing a slash command reference + * @param command The slash command description to create the reference from + * @returns A node object representing the paragraph with slash command + */ +export const createParagraphNodeFromSlashCmdDescription = ( + command: SlashCommandDescription, +) => { + return { + type: "paragraph", + content: [ + { + type: SlashCommandExtension.name, + attrs: { + id: command.name, + label: command.name, + }, + }, + { + type: "text", + text: " ", + }, + ], + }; +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts new file mode 100644 index 000000000..82bddd2a9 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -0,0 +1,5 @@ +export * from "./AddCodeToEditExtension"; +export * from "./CodeBlockExtension"; +export * from "./MentionExtension"; +export * from "./PromptExtension"; +export * from "./SlashCommandExtension"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/types.ts b/gui/src/components/mainInput/TipTapEditor/extensions/types.ts new file mode 100644 index 000000000..318b1062d --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/types.ts @@ -0,0 +1,11 @@ +import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { SuggestionOptions } from "@tiptap/suggestion"; + +export type MentionOptions = { + HTMLAttributes: Record; + renderHTML: (props: { + options: MentionOptions; + node: ProseMirrorNode; + }) => DOMOutputSpec; + suggestion: Omit; +}; diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx new file mode 100644 index 000000000..570e518c8 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx @@ -0,0 +1,100 @@ +import { + NodeViewProps, + NodeViewWrapper, + NodeViewWrapperProps, +} 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 { useAppSelector } from "../../../../redux/hooks"; +import FileIcon from "../../../FileIcon"; +import StyledMarkdownPreview from "../../../markdown/StyledMarkdownPreview"; +import { ExpandablePreview } from "./ExpandablePreview"; + +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 isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now + const ideMessenger = useContext(IdeMessengerContext); + + // 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"; + + const newestCodeblockForInputId = useAppSelector( + (store) => store.session.newestCodeblockForInput[inputId], + ); + + const initiallyHidden = useMemo(() => { + return newestCodeblockForInputId !== item.id.itemId; + }, [newestCodeblockForInputId, item.id.itemId]); + + 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, + }); + } + }; + + const borderColor = isFirstContextItem + ? "#d0d" + : selected + ? vscBadgeBackground + : undefined; + + return ( + + } + initiallyHidden={initiallyHidden} + onDelete={() => deleteNode()} + borderColor={borderColor} + onTitleClick={handleTitleClick} + > + + + + ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/ExpandablePreview.tsx b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/ExpandablePreview.tsx new file mode 100644 index 000000000..973700335 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/ExpandablePreview.tsx @@ -0,0 +1,186 @@ +import { + ChevronDownIcon, + EyeSlashIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { EyeIcon } from "@heroicons/react/24/solid"; +import { useEffect, useRef, useState } from "react"; +import styled from "styled-components"; +import { defaultBorderRadius, lightGray, vscEditorBackground } from "../../.."; +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 ExpandablePreview component + */ +interface ExpandablePreviewProps { + /** Title to display in the header */ + title: string; + /** Optional icon to display next to the title */ + icon?: React.ReactNode; + /** Whether the preview is initially hidden */ + 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; + /** 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 ExpandablePreview(props: ExpandablePreviewProps) { + const [hidden, setHidden] = useState(props.initiallyHidden ?? false); + const [isExpanded, setIsExpanded] = useState(false); + + const contentRef = useRef(null); + const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); + + 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 ( + + {/* Keep existing header code */} +

{ + setHidden(!hidden); + }} + > +
{ + e.stopPropagation(); + if (props.onTitleClick) { + props.onTitleClick(e); + } + }} + > + {props.icon} + {props.title} +
+
+ + {hidden ? ( + + ) : ( + + )} + + {props.onDelete && ( + { + e.stopPropagation(); + props.onDelete?.(); + }} + > + + + )} +
+
+ + {/* Updated content section */} + {!hidden && ( + + MAX_PREVIEW_HEIGHT} + > + {props.children} + + + {contentDims.height > MAX_PREVIEW_HEIGHT && ( + + + setIsExpanded((v) => !v)} + /> + + + )} + + )} + + ); +} diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx new file mode 100644 index 000000000..2e02f742c --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx @@ -0,0 +1,61 @@ +import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; +import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; +import { ContextItemWithId } from "core"; +import { useContext, useMemo } from "react"; +import { vscBadgeBackground } from "../../.."; +import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { useAppSelector } from "../../../../redux/hooks"; +import { ExpandablePreview } from "./ExpandablePreview"; + +/** + * Component for prompt blocks in the Tiptap editor + */ +export const PromptBlockPreview = (props: any) => { + const { node, deleteNode, selected } = props; + const item: ContextItemWithId = node.attrs.item; + const inputId = node.attrs.inputId; + const ideMessenger = useContext(IdeMessengerContext); + + // Not setting this as a "p" will cause issues with foreign keyboards + const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p"; + + const newestCodeblockForInputId = useAppSelector( + (store) => store.session.newestCodeblockForInput[inputId], + ); + + const initiallyHidden = useMemo(() => { + return newestCodeblockForInputId !== item.id.itemId; + }, [newestCodeblockForInputId, item.id.itemId]); + + console.log({ id: item.id.itemId, newestCodeblockForInputId }); + + const handleTitleClick = (e: React.MouseEvent) => { + e.stopPropagation(); + ideMessenger.post("showVirtualFile", { + content: item.content, + name: item.name, + }); + }; + + const borderColor = selected ? vscBadgeBackground : undefined; + + return ( + + } + initiallyHidden={initiallyHidden} + onDelete={() => deleteNode()} + borderColor={borderColor} + onTitleClick={handleTitleClick} + > +
+ {item.content} +
+
+
+ ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts new file mode 100644 index 000000000..183e0daa0 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts @@ -0,0 +1,2 @@ +export { CodeblockPreview } from "./CodeblockPreview"; +export { PromptBlockPreview as PromptPreview } from "./PromptBlockPreview"; diff --git a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useWebviewListeners.ts similarity index 97% rename from gui/src/components/mainInput/tiptap/useWebviewListeners.ts rename to gui/src/components/mainInput/TipTapEditor/useWebviewListeners.ts index 3a4694939..d98e72632 100644 --- a/gui/src/components/mainInput/tiptap/useWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useWebviewListeners.ts @@ -10,6 +10,7 @@ import { import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; import { TipTapEditorProps } from "./TipTapEditor"; +import { CodeBlockExtension } from "./extensions"; export function useWebviewListeners(options: { editor: Editor | null; @@ -117,7 +118,7 @@ export function useWebviewListeners(options: { if (el.attrs?.item?.name === contextItem.name) { return; // Prevent exact duplicate code blocks } - if (el.type === "codeBlock") { + if (el.type === CodeBlockExtension.name) { index += 2; } else { break; @@ -126,13 +127,14 @@ export function useWebviewListeners(options: { editor .chain() .insertContentAt(index, { - type: "codeBlock", + type: CodeBlockExtension.name, attrs: { item: contextItem, inputId: props.inputId, }, }) .run(); + dispatch( setNewestCodeblocksForInput({ inputId: props.inputId, diff --git a/gui/src/components/mainInput/tiptap/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/editorConfig.ts rename to gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 985cadc64..384d4aee6 100644 --- a/gui/src/components/mainInput/tiptap/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -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(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,7 +286,7 @@ export function createEditorConfig(options: { }, }), Text, - Mention.configure({ + ContinueExtensions.MentionExtension.configure({ HTMLAttributes: { class: "mention", }, @@ -312,7 +304,7 @@ export function createEditorConfig(options: { }, }), - AddCodeToEdit.configure({ + ContinueExtensions.AddCodeToEditExtension.configure({ HTMLAttributes: { class: "add-code-to-edit", }, @@ -351,7 +343,7 @@ export function createEditorConfig(options: { }, }, }), - SlashCommand.configure({ + ContinueExtensions.SlashCommandExtension.configure({ HTMLAttributes: { class: "mention", }, @@ -360,12 +352,19 @@ export function createEditorConfig(options: { onClose, onOpen, ideMessenger, + dispatch, + props.inputId, ), renderText: (props) => { return props.node.attrs.label; }, }), - CodeBlockExtension, + ContinueExtensions.PromptExtension.configure({ + HTMLAttributes: { + class: "prompt-block", + }, + }), + ContinueExtensions.CodeBlockExtension, ], editorProps: { attributes: { diff --git a/gui/src/components/mainInput/tiptap/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts similarity index 91% rename from gui/src/components/mainInput/tiptap/getSuggestion.ts rename to gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index f9faad863..c1cd5c23e 100644 --- a/gui/src/components/mainInput/tiptap/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -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 { setNewestCodeblocksForInput } from "../../../../redux/slices/sessionSlice"; +import { AppDispatch } from "../../../../redux/store"; +import AtMentionDropdown from "../../AtMentionDropdown"; +import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; +import { TIPPY_DIV_ID } from "../TipTapEditor"; function getSuggestion( items: (props: { query: string }) => Promise, @@ -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]; @@ -216,7 +220,17 @@ export function getSlashCommandDropdownOptions( title: provider.title, label: provider.title, type: (provider.type ?? "slashCommand") as ComboBoxItemType, - action: provider.action, + content: provider.content, + action: () => { + dispatch( + setNewestCodeblocksForInput({ + inputId, + contextItemId: provider.title, + }), + ); + + provider.action?.(); + }, })); if (query.length === 0 && commandItems.length === 0) { @@ -232,6 +246,7 @@ export function getSlashCommandDropdownOptions( name: "", id: "", label: "", + content: "", }); } diff --git a/gui/src/components/mainInput/tiptap/imageUtils.ts b/gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts similarity index 96% rename from gui/src/components/mainInput/tiptap/imageUtils.ts rename to gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts index 0803e5ab8..23de2dda1 100644 --- a/gui/src/components/mainInput/tiptap/imageUtils.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/imageUtils.ts @@ -1,4 +1,4 @@ -import { IIdeMessenger } from "../../../context/IdeMessenger"; +import { IIdeMessenger } from "../../../../context/IdeMessenger"; const IMAGE_RESOLUTION = 1024; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/index.ts b/gui/src/components/mainInput/TipTapEditor/utils/index.ts new file mode 100644 index 000000000..5ce05a866 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/utils/index.ts @@ -0,0 +1,5 @@ +export * from "./editorConfig"; +export * from "./getSuggestion"; +export * from "./imageUtils"; +export * from "./keyHandlers"; +export * from "./resolveEditorContent"; diff --git a/gui/src/components/mainInput/tiptap/keyHandlers.ts b/gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts similarity index 90% rename from gui/src/components/mainInput/tiptap/keyHandlers.ts rename to gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts index c25a53271..a102ba2f0 100644 --- a/gui/src/components/mainInput/tiptap/keyHandlers.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/keyHandlers.ts @@ -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; - 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 diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts new file mode 100644 index 000000000..5ffd77ffc --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -0,0 +1,345 @@ +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 { + CodeBlockExtension, + MentionExtension, + SlashCommandExtension, +} 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 + ), +]; + +/** + * 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( + (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 CodeBlockExtension.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 { + 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( + 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 MentionExtension.name: + contextItems.push(child.attrs as MentionAttrs); + return child.attrs?.renderInlineAs ?? child.attrs?.label; + case SlashCommandExtension.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]; +} + +/** + * 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 { + 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]; +} diff --git a/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx b/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx deleted file mode 100644 index e63e273ad..000000000 --- a/gui/src/components/mainInput/tiptap/CodeBlockComponent.tsx +++ /dev/null @@ -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 ( - - { - deleteNode(); - }} - /> - - ); -}; diff --git a/gui/src/components/mainInput/tiptap/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts deleted file mode 100644 index 76a868115..000000000 --- a/gui/src/components/mainInput/tiptap/resolveInput.ts +++ /dev/null @@ -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( - 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; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 9f9078303..6c9406830 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,6 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; +import { CodeBlockExtension } from "../TipTapEditor/extensions"; 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 === CodeBlockExtension.name) { continue; } diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx deleted file mode 100644 index 06717c5ee..000000000 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ /dev/null @@ -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(); - 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(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 ( - -
{ - setLocalHidden(!hidden); - }} - > -
{ - 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, - }); - } - }} - > - - {props.item.name} -
-
- - {hidden ? ( - - ) : ( - - )} - - { - e.stopPropagation(); - props.onDelete?.(); - }} - > - - -
-
-
- -
- - {codeblockDims.height > MAX_PREVIEW_HEIGHT && ( - - setIsSizeLimited((v) => !v)} - /> - - )} -
- ); -} - -export default CodeSnippetPreview; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index d968101d0..bc60451bf 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -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; } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index aea4bdadb..682671cbb 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -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() { 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} /> )} diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index bb7850dd5..cca27e6e2 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -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; }) || [] ); }, diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 8aff8e1de..f321f0dae 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -127,7 +127,9 @@ export function setupStore() { ideMessenger: new IdeMessenger(), }, }, - }).concat(logger), + }), + // This can be uncommented to get detailed Redux logs + // .concat(logger), }); } diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 1c38e965b..450471164 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -8,7 +8,7 @@ import { SlashCommandDescription, } from "core"; import * as URI from "uri-js"; -import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { selectDefaultModel } from "../slices/configSlice"; import { ThunkApiType } from "../store"; diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts index 05396c3ed..5f3e5e18d 100644 --- a/gui/src/redux/thunks/updateFileSymbols.ts +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -1,7 +1,8 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { ThunkApiType } from "../store"; -import { updateFileSymbols } from "../slices/sessionSlice"; import { ChatHistoryItem, ContextItemWithId } from "core"; +import { CodeBlockExtension } from "../../components/mainInput/TipTapEditor/extensions"; +import { updateFileSymbols } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; export function getContextItemsFromHistory( historyItems: ChatHistoryItem[], @@ -25,7 +26,7 @@ export function getContextItemsFromHistory( .flatMap((item) => item.editorState.content) .filter( (content) => - content?.type === "codeBlock" && + content?.type === CodeBlockExtension.name && content?.attrs?.item?.uri?.value && content.attrs.item.uri?.type === "file", ) diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index 67677e103..fe2b8c0e4 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -33,6 +33,8 @@ module.exports = { "vsc-editor-background": "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))", "vsc-input-border": "var(--vscode-input-border, #999998)", + "vsc-commandCenter-inactiveBorder": + "var(--vscode-commandCenter-inactiveBorder, #999998)", // Starting to make things less vsc-specific // TODO make it all non-IDE-specific naming From 57d46636c8f22808d3c18e9d01e48fc44bd3d368 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 3 Apr 2025 17:57:24 -0700 Subject: [PATCH 53/93] create main editor provider --- gui/src/App.tsx | 9 +- .../ConversationStarterCards.tsx | 23 ++-- .../TipTapEditor/MainEditorProvider.tsx | 117 ++++++++++++++++++ .../mainInput/TipTapEditor/TipTapEditor.tsx | 44 ++----- .../mainInput/TipTapEditor/index.ts | 3 + ...rs.ts => useMainEditorWebviewListeners.ts} | 96 +++++++------- 6 files changed, 190 insertions(+), 102 deletions(-) create mode 100644 gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx create mode 100644 gui/src/components/mainInput/TipTapEditor/index.ts rename gui/src/components/mainInput/TipTapEditor/{useWebviewListeners.ts => useMainEditorWebviewListeners.ts} (72%) diff --git a/gui/src/App.tsx b/gui/src/App.tsx index deb1e376f..257160320 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -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"; @@ -66,9 +67,11 @@ function SetupListeners() { function App() { return ( - - - + + + + + ); diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index b8004b472..07d0b0cdb 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -3,10 +3,8 @@ import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { MAIN_EDITOR_INPUT_ID } from "../../pages/gui/Chat"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { - setMainEditorContentTrigger, - setNewestCodeblocksForInput, -} from "../../redux/slices/sessionSlice"; +import { setNewestCodeblocksForInput } from "../../redux/slices/sessionSlice"; +import { useMainEditor } from "../mainInput/TipTapEditor"; import { createParagraphNodeFromSlashCmdDescription, createPromptBlockNodeFromSlashCmdDescription, @@ -17,6 +15,7 @@ const NUM_CARDS_TO_RENDER = 5; export function ConversationStarterCards() { const dispatch = useAppDispatch(); + const { mainEditor } = useMainEditor(); const [showAll, setShowAll] = useState(false); const { isCommandBookmarked } = useBookmarkedSlashCommands(); const slashCommands = useAppSelector( @@ -35,15 +34,13 @@ export function ConversationStarterCards() { }), ); - dispatch( - setMainEditorContentTrigger({ - type: "doc", - content: [ - createPromptBlockNodeFromSlashCmdDescription(command), - createParagraphNodeFromSlashCmdDescription(command), - ], - }), - ); + mainEditor?.commands.setContent({ + type: "doc", + content: [ + createPromptBlockNodeFromSlashCmdDescription(command), + createParagraphNodeFromSlashCmdDescription(command), + ], + }); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx b/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx new file mode 100644 index 000000000..874640aa5 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx @@ -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( + 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(null); + const [inputId, setInputId] = useState(null); + const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {}); + const editorFocusedRef = useRef(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 ( + + {children} + + ); +}; + +/** + * 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; +}; diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 6d20b2f1c..24a9d4aa6 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -7,16 +7,13 @@ 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 { useMainEditor } from "./MainEditorProvider"; import { InputBoxDiv } from "./StyledComponents"; import "./TipTapEditor.css"; -import { useWebviewListeners } from "./useWebviewListeners"; import { handleImageFile } from "./utils"; import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig"; import { useEditorEventHandlers } from "./utils/keyHandlers"; @@ -41,6 +38,7 @@ export const TIPPY_DIV_ID = "tippy-js-div"; function TipTapEditor(props: TipTapEditorProps) { const dispatch = useAppDispatch(); + const mainEditorContext = useMainEditor(); const ideMessenger = useContext(IdeMessengerContext); @@ -57,6 +55,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 +108,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(null); @@ -186,9 +169,6 @@ function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(false); }, [cancelBlurTimeout]); - // TODO pass clear blur timeout to model and mode selectors - // Seems like unnecessary for now? - return ( void>; dispatch: AppDispatch; historyLength: number; - props: TipTapEditorProps; + inputId: string; editorFocusedRef: MutableRefObject; }) { - 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 () => { @@ -47,11 +53,7 @@ export function useWebviewListeners(options: { useWebviewListener( "focusContinueInput", - async (data) => { - if (!props.isMainInput) { - return; - } - + async () => { dispatch(clearCodeToEdit()); if (historyLength > 0) { @@ -62,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, @@ -124,23 +120,25 @@ export function useWebviewListeners(options: { break; } } + editor .chain() .insertContentAt(index, { type: CodeBlockExtension.name, attrs: { item: contextItem, - inputId: props.inputId, + inputId, }, }) .run(); dispatch( setNewestCodeblocksForInput({ - inputId: props.inputId, + inputId, contextItemId: contextItem.id.itemId, }), ); + if (data.prompt) { editor.commands.focus("end"); editor.commands.insertContent(data.prompt); @@ -155,52 +153,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, @@ -208,6 +196,6 @@ export function useWebviewListeners(options: { }), ); }, - [props.isMainInput], + [], ); } From d4e1609d2a65aeeece6caa8620a1b45196f40c98 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 3 Apr 2025 18:15:30 -0700 Subject: [PATCH 54/93] feat: add slash command cmd --- .../ConversationStarterCards.tsx | 15 +-- ...ckExtension.tsx => CodeblockExtension.tsx} | 2 +- .../extensions/PromptExtension.ts | 33 +------ .../extensions/SlashCommandExtension.ts | 99 +++++++++++++------ .../TipTapEditor/extensions/index.ts | 4 +- .../useMainEditorWebviewListeners.ts | 6 +- .../TipTapEditor/utils/editorConfig.ts | 2 +- .../utils/resolveEditorContent.ts | 4 +- .../mainInput/util/handleMetaKeyIssues.ts | 4 +- gui/src/redux/thunks/updateFileSymbols.ts | 4 +- 10 files changed, 89 insertions(+), 84 deletions(-) rename gui/src/components/mainInput/TipTapEditor/extensions/{CodeBlockExtension.tsx => CodeblockExtension.tsx} (93%) diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 07d0b0cdb..6d29a1df6 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -5,14 +5,13 @@ import { MAIN_EDITOR_INPUT_ID } from "../../pages/gui/Chat"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { setNewestCodeblocksForInput } from "../../redux/slices/sessionSlice"; import { useMainEditor } from "../mainInput/TipTapEditor"; -import { - createParagraphNodeFromSlashCmdDescription, - createPromptBlockNodeFromSlashCmdDescription, -} from "../mainInput/TipTapEditor/extensions"; 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(); @@ -34,13 +33,7 @@ export function ConversationStarterCards() { }), ); - mainEditor?.commands.setContent({ - type: "doc", - content: [ - createPromptBlockNodeFromSlashCmdDescription(command), - createParagraphNodeFromSlashCmdDescription(command), - ], - }); + mainEditor?.commands.insertSlashCommand(command); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlockExtension.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension.tsx similarity index 93% rename from gui/src/components/mainInput/TipTapEditor/extensions/CodeBlockExtension.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension.tsx index 3618a69ba..9c36ec9c9 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlockExtension.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension.tsx @@ -4,7 +4,7 @@ import { CodeblockPreview } from "../toolbar-previews/CodeblockPreview"; export const CODEBLOCK_NAME = "codeblock"; -export const CodeBlockExtension = Node.create({ +export const CodeblockExtension = Node.create({ name: CODEBLOCK_NAME, group: "block", diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts index d5c5b6d7b..1b18e30b8 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts @@ -1,7 +1,5 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { ContextItemWithId, SlashCommandDescription } from "core"; -import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; import { PromptBlockPreview } from "../toolbar-previews/PromptBlockPreview"; export interface PromptOptions { @@ -16,8 +14,6 @@ export const PROMPT_BLOCK_NAME = "prompt-block"; export const PromptExtension = Node.create({ name: PROMPT_BLOCK_NAME, group: "block", - // atom: true, - // draggable: true, addOptions() { return { @@ -51,31 +47,4 @@ export const PromptExtension = Node.create({ addNodeView() { return ReactNodeViewRenderer(PromptBlockPreview); }, -}); - -/** - * Creates a prompt block node from a slash command description - * @param command The slash command description to create the block from - * @param inputId Optional input ID, defaults to main editor input ID - * @returns A node object representing the prompt block - */ -export const createPromptBlockNodeFromSlashCmdDescription = ( - command: SlashCommandDescription, - inputId: string = MAIN_EDITOR_INPUT_ID, -) => { - return { - type: PromptExtension.name, - attrs: { - item: { - content: command.prompt, - name: command.name, - description: command.description || "", - id: { - providerTitle: "prompt", - itemId: command.name, - }, - } as ContextItemWithId, - inputId, - }, - }; -}; +}); \ No newline at end of file diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts index eb97e6227..2c48ff56f 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts @@ -6,6 +6,8 @@ import { PluginKey } from "@tiptap/pm/state"; import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; import { ContextItemWithId, SlashCommandDescription } from "core"; import { v4 as uuidv4 } from "uuid"; +import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; +import { PROMPT_BLOCK_NAME } from "./PromptExtension"; export type SlashCommandOptions = { HTMLAttributes: Record; @@ -18,6 +20,22 @@ export const SLASH_CMD_SUGGESTION_CHAR = "/"; export const SlashCommandPluginKey = new PluginKey(SLASH_CMD_NAME); +declare module "@tiptap/core" { + interface Commands { + slashCommand: { + /** + * Insert a slash command and its associated prompt block + * @param command The slash command description + * @param inputId The input ID (defaults to MAIN_EDITOR_INPUT_ID) + */ + insertSlashCommand: ( + command: SlashCommandDescription, + inputId?: string, + ) => ReturnType; + }; + } +} + export const SlashCommandExtension = Node.create({ name: SLASH_CMD_NAME, @@ -58,9 +76,6 @@ export const SlashCommandExtension = Node.create({ const promptId = uuidv4(); - // Create a generic "promptToPromptBlockExtension" fn - // For here and in the conversation starters - editor .chain() .focus() @@ -200,30 +215,58 @@ export const SlashCommandExtension = Node.create({ }), ]; }, -}); -/** - * Creates a paragraph node containing a slash command reference - * @param command The slash command description to create the reference from - * @returns A node object representing the paragraph with slash command - */ -export const createParagraphNodeFromSlashCmdDescription = ( - command: SlashCommandDescription, -) => { - return { - type: "paragraph", - content: [ - { - type: SlashCommandExtension.name, - attrs: { - id: command.name, - label: command.name, + addCommands() { + return { + insertSlashCommand: + ( + command: SlashCommandDescription, + inputId: string = MAIN_EDITOR_INPUT_ID, + ) => + ({ chain }) => { + // Create the document with both a prompt block and the slash command paragraph + return chain() + .setContent({ + type: "doc", + content: [ + // Add the prompt block at the beginning + { + type: PROMPT_BLOCK_NAME, + attrs: { + item: { + content: command.prompt, + name: command.name, + description: command.description || "", + id: { + providerTitle: "prompt", + itemId: command.name, + }, + } as ContextItemWithId, + inputId, + }, + }, + // Add the paragraph with the slash command + { + type: "paragraph", + content: [ + { + type: this.name, + attrs: { + id: command.name, + label: command.name, + }, + }, + { + type: "text", + text: " ", + }, + ], + }, + ], + }) + .focus() + .run(); }, - }, - { - type: "text", - text: " ", - }, - ], - }; -}; + }; + }, +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts index 82bddd2a9..a790c5b0c 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -1,5 +1,5 @@ export * from "./AddCodeToEditExtension"; -export * from "./CodeBlockExtension"; +export * from "./CodeblockExtension"; export * from "./MentionExtension"; export * from "./PromptExtension"; -export * from "./SlashCommandExtension"; +export * from "./SlashCommandExtension"; \ No newline at end of file diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 43e9fdecc..90bfcd8cc 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -9,7 +9,7 @@ import { } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { CodeBlockExtension } from "./extensions"; +import { CodeblockExtension } from "./extensions"; /** * Hook for setting up main editor specific webview listeners @@ -114,7 +114,7 @@ export function useMainEditorWebviewListeners({ if (el.attrs?.item?.name === contextItem.name) { return; // Prevent exact duplicate code blocks } - if (el.type === CodeBlockExtension.name) { + if (el.type === CodeblockExtension.name) { index += 2; } else { break; @@ -124,7 +124,7 @@ export function useMainEditorWebviewListeners({ editor .chain() .insertContentAt(index, { - type: CodeBlockExtension.name, + type: CodeblockExtension.name, attrs: { item: contextItem, inputId, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 384d4aee6..d2c77529d 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -364,7 +364,7 @@ export function createEditorConfig(options: { class: "prompt-block", }, }), - ContinueExtensions.CodeBlockExtension, + ContinueExtensions.CodeblockExtension, ], editorProps: { attributes: { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index 5ffd77ffc..5476f100c 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -19,7 +19,7 @@ import { getUriFileExtension } from "core/util/uri"; import { IIdeMessenger } from "../../../../context/IdeMessenger"; import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice"; import { - CodeBlockExtension, + CodeblockExtension, MentionExtension, SlashCommandExtension, } from "../extensions"; @@ -86,7 +86,7 @@ function processEditorContent(editorState: JSONContent) { return [...parts, { type: "text", text }]; } - case CodeBlockExtension.name: { + case CodeblockExtension.name: { if (!p.attrs?.item) { console.warn("codeBlock has no item attribute"); return parts; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index 6c9406830..b147a5609 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,7 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; -import { CodeBlockExtension } from "../TipTapEditor/extensions"; +import { CodeblockExtension } from "../TipTapEditor/extensions"; const isWebEnv = isWebEnvironment(); @@ -104,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 === CodeBlockExtension.name) { + if (node.type.name === CodeblockExtension.name) { continue; } diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts index 5f3e5e18d..c237e4216 100644 --- a/gui/src/redux/thunks/updateFileSymbols.ts +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -1,6 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatHistoryItem, ContextItemWithId } from "core"; -import { CodeBlockExtension } from "../../components/mainInput/TipTapEditor/extensions"; +import { CodeblockExtension } from "../../components/mainInput/TipTapEditor/extensions"; import { updateFileSymbols } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -26,7 +26,7 @@ export function getContextItemsFromHistory( .flatMap((item) => item.editorState.content) .filter( (content) => - content?.type === CodeBlockExtension.name && + content?.type === CodeblockExtension.name && content?.attrs?.item?.uri?.value && content.attrs.item.uri?.type === "file", ) From 2baf137c0c6f008d647461899bf8697862ade9bd Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 3 Apr 2025 18:24:02 -0700 Subject: [PATCH 55/93] Update SlashCommandExtension.ts --- .../extensions/SlashCommandExtension.ts | 45 +++---------------- 1 file changed, 7 insertions(+), 38 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts index 2c48ff56f..d29246e5e 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts @@ -5,14 +5,14 @@ import { Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PluginKey } from "@tiptap/pm/state"; import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; import { ContextItemWithId, SlashCommandDescription } from "core"; -import { v4 as uuidv4 } from "uuid"; import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; +import { ComboBoxItem } from "../../types"; import { PROMPT_BLOCK_NAME } from "./PromptExtension"; export type SlashCommandOptions = { HTMLAttributes: Record; renderText: (props: { node: ProseMirrorNode }) => string; - suggestion: Omit; + suggestion: Omit, "editor">; }; export const SLASH_CMD_NAME = "slash-command"; @@ -59,42 +59,11 @@ export const SlashCommandExtension = Node.create({ range.to += 1; } - editor - .chain() - .focus() - .insertContentAt(range, [ - { - type: this.name, - attrs: props, - }, - { - type: "text", - text: " ", - }, - ]) - .run(); - - const promptId = uuidv4(); - - editor - .chain() - .focus() - .insertContentAt(0, { - type: "promptBlock", - attrs: { - item: { - content: props.content, - name: props.title, - description: props.description, - id: { - providerTitle: "prompt", - itemId: props.name, - }, - } as ContextItemWithId, - inputId: promptId, - }, - }) - .run(); + editor.commands.insertSlashCommand({ + name: props.title, + description: props.description, + prompt: props.content, + }); window.getSelection()?.collapseToEnd(); }, From e02741cb5e641388647bda2f486e05b360fc65a9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 19:04:28 -0700 Subject: [PATCH 56/93] edit tool first take --- core/tools/builtIn.ts | 1 + core/tools/callTool.ts | 3 ++ core/tools/definitions/editFile.ts | 28 +++++++++++++++ core/tools/implementations/editFile.ts | 22 ++++++++++++ core/tools/index.ts | 2 ++ .../StepContainerPreToolbar.tsx | 36 +++++++++++-------- .../markdown/StyledMarkdownPreview.tsx | 22 ++++++++++-- gui/src/redux/slices/uiSlice.ts | 1 + 8 files changed, 97 insertions(+), 18 deletions(-) create mode 100644 core/tools/definitions/editFile.ts create mode 100644 core/tools/implementations/editFile.ts diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index fa76358c9..4ac7ad4ae 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -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", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 25c56507c..2866124ef 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -4,6 +4,7 @@ import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; +import { editFileImpl } from "./implementations/editFile"; import { exactSearchImpl } from "./implementations/exactSearch"; import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; @@ -138,6 +139,8 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + case BuiltInToolNames.EditExistingFile: + return await editFileImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts new file mode 100644 index 000000000..1ff44f7c7 --- /dev/null +++ b/core/tools/definitions/editFile.ts @@ -0,0 +1,28 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +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: + "To edit an existing file, call this tool and follow the returned instructions. If you don't have the contents of the file, read it first.", + parameters: { + type: "object", + required: ["filepath"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to edit, relative to the root of the workspace.", + }, + }, + }, + }, +}; diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts new file mode 100644 index 000000000..80de79923 --- /dev/null +++ b/core/tools/implementations/editFile.ts @@ -0,0 +1,22 @@ +import { ToolImpl } from "."; +import { resolveRelativePathInDir } from "../../util/ideUtils"; + +export const EDIT_TOOL_CONTEXT_ITEM_NAME = "Edit Tool Instructions"; + +export const editFileImpl: ToolImpl = async (args, extras) => { + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + extras.ide, + ); + if (!firstUriMatch) { + throw new Error(`File ${args.filepath} does not exist.`); + } + return [ + { + name: EDIT_TOOL_CONTEXT_ITEM_NAME, + description: "Instructions for editing the file", + content: + "Edit Instructions: return the full new file contents in a codeblock. The codeblock header should be of the format '```language filepath'", + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index eea4ee79b..407510691 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { createNewFileTool } from "./definitions/createNewFile"; +import { editFileTool } from "./definitions/editFile"; import { exactSearchTool } from "./definitions/exactSearch"; import { lsTool } from "./definitions/lsTool"; import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; @@ -9,6 +10,7 @@ import { viewDiffTool } from "./definitions/viewDiff"; export const allTools = [ readFileTool, + editFileTool, createNewFileTool, runTerminalCommandTool, diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 46fa90d68..ec0000b2c 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -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, @@ -52,17 +51,18 @@ 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; + autoApply?: boolean; } export default function StepContainerPreToolbar( props: StepContainerPreToolbarProps, ) { const ideMessenger = useContext(IdeMessengerContext); - const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isInEditMode = useAppSelector(selectIsInEditMode); const [isExpanded, setIsExpanded] = useState( @@ -76,7 +76,7 @@ export default function StepContainerPreToolbar( ); 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. @@ -104,7 +104,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, filepath: fileUri, text: codeBlockContent, curSelectedModelTitle: defaultModel.title, @@ -135,19 +135,25 @@ 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(); - // } - + // console.log( + // wasGeneratingRef.current, + // isGeneratingCodeBlock, + // props.autoApply, + // ); // wasGeneratingRef.current = isGeneratingCodeBlock; - // }, [isGeneratingCodeBlock]); + // if (hasCompletedGenerating) { + // console.log("Completed generating", props.autoApply); + // if (props.autoApply) { + // onClickApply(); + // } + // // else if(isInEditMode) { + // // onClickApply(); + // // } + // } + // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( @@ -156,7 +162,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("acceptDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } @@ -167,7 +173,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("rejectDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index d968101d0..fbd6801b9 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -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"; @@ -196,6 +196,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }, [props.itemIndex, history, allSymbols]); const pastFileInfoRef = useUpdatingRef(pastFileInfo); + const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( + [], + ); + const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ remarkTables, @@ -282,8 +286,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 ; @@ -307,6 +309,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( ); } + const isGeneratingCodeBlock = + preChildProps["data-isgeneratingcodeblock"]; + + if (codeblockState.current[codeBlockIndex] === undefined) { + codeblockState.current[codeBlockIndex] = { + streamId: uuidv4(), + isGenerating: isGeneratingCodeBlock, + }; + } + const codeblockStreamId = + codeblockState.current[codeBlockIndex].streamId; + // We use a custom toolbar for codeblocks in the step container return ( diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 9ebf8969f..e7eccbad6 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -45,6 +45,7 @@ export const uiSlice = createSlice({ ttsActive: false, toolSettings: { [BuiltInToolNames.ReadFile]: "allowedWithoutPermission", + [BuiltInToolNames.EditExistingFile]: "allowedWithPermission", [BuiltInToolNames.CreateNewFile]: "allowedWithPermission", [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission", [BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission", From dca4685baca1ffea0e768bf0714f808a7399dc49 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 3 Apr 2025 19:14:08 -0700 Subject: [PATCH 57/93] delete cmd on click --- .../{ => components}/DragOverlay.tsx | 0 .../ExpandablePreview.tsx | 0 .../{ => components}/StyledComponents.ts | 4 +- .../TipTapEditor/components/index.ts | 3 + .../extensions/AddCodeToEditExtension.ts | 8 +- .../CodeblockExtension.tsx | 6 +- .../CodeblockExtension}/CodeblockPreview.tsx | 12 +- .../extensions/CodeblockExtension/index.ts | 1 + .../extensions/MentionExtension.ts | 8 +- .../extensions/PromptExtension.ts | 50 -------- .../PromptExtension}/PromptBlockPreview.tsx | 48 +++++--- .../PromptExtension/PromptExtension.ts | 108 ++++++++++++++++++ .../extensions/PromptExtension/index.ts | 1 + .../extensions/SlashCommandExtension.ts | 94 +++++++++++---- .../TipTapEditor/extensions/index.ts | 2 +- .../TipTapEditor/toolbar-previews/index.ts | 2 - .../TipTapEditor/utils/getSuggestion.ts | 3 +- 17 files changed, 237 insertions(+), 113 deletions(-) rename gui/src/components/mainInput/TipTapEditor/{ => components}/DragOverlay.tsx (100%) rename gui/src/components/mainInput/TipTapEditor/{toolbar-previews => components}/ExpandablePreview.tsx (100%) rename gui/src/components/mainInput/TipTapEditor/{ => components}/StyledComponents.ts (95%) create mode 100644 gui/src/components/mainInput/TipTapEditor/components/index.ts rename gui/src/components/mainInput/TipTapEditor/extensions/{ => CodeblockExtension}/CodeblockExtension.tsx (82%) rename gui/src/components/mainInput/TipTapEditor/{toolbar-previews => extensions/CodeblockExtension}/CodeblockPreview.tsx (87%) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts rename gui/src/components/mainInput/TipTapEditor/{toolbar-previews => extensions/PromptExtension}/PromptBlockPreview.tsx (57%) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts diff --git a/gui/src/components/mainInput/TipTapEditor/DragOverlay.tsx b/gui/src/components/mainInput/TipTapEditor/components/DragOverlay.tsx similarity index 100% rename from gui/src/components/mainInput/TipTapEditor/DragOverlay.tsx rename to gui/src/components/mainInput/TipTapEditor/components/DragOverlay.tsx diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/ExpandablePreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx similarity index 100% rename from gui/src/components/mainInput/TipTapEditor/toolbar-previews/ExpandablePreview.tsx rename to gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx diff --git a/gui/src/components/mainInput/TipTapEditor/StyledComponents.ts b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts similarity index 95% rename from gui/src/components/mainInput/TipTapEditor/StyledComponents.ts rename to gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts index 2aca4f1be..f994b53d6 100644 --- a/gui/src/components/mainInput/TipTapEditor/StyledComponents.ts +++ b/gui/src/components/mainInput/TipTapEditor/components/StyledComponents.ts @@ -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; diff --git a/gui/src/components/mainInput/TipTapEditor/components/index.ts b/gui/src/components/mainInput/TipTapEditor/components/index.ts new file mode 100644 index 000000000..266d7e1c3 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/components/index.ts @@ -0,0 +1,3 @@ +export * from "./DragOverlay"; +export * from "./ExpandablePreview"; +export * from "./StyledComponents"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts index 2aeedadf3..519074bb1 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts @@ -3,12 +3,8 @@ import { PluginKey } from "@tiptap/pm/state"; import Suggestion from "@tiptap/suggestion"; import { MentionOptions } from "./types"; -export const ADD_CODE_TO_EDIT_NAME = "add-code-to-edit"; - -export const AddCodeToEditPluginKey = new PluginKey(ADD_CODE_TO_EDIT_NAME); - export const AddCodeToEditExtension = Node.create({ - name: ADD_CODE_TO_EDIT_NAME, + name: "add-code-to-edit", addOptions() { return { @@ -22,7 +18,7 @@ export const AddCodeToEditExtension = Node.create({ }, 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]; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockExtension.tsx similarity index 82% rename from gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockExtension.tsx index 9c36ec9c9..a43c1e9d2 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockExtension.tsx @@ -1,11 +1,9 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeblockPreview } from "../toolbar-previews/CodeblockPreview"; - -export const CODEBLOCK_NAME = "codeblock"; +import { CodeblockPreview } from "./CodeblockPreview"; export const CodeblockExtension = Node.create({ - name: CODEBLOCK_NAME, + name: "codeblock", group: "block", diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockPreview.tsx similarity index 87% rename from gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockPreview.tsx index 570e518c8..66812b1df 100644 --- a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/CodeblockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockPreview.tsx @@ -7,12 +7,12 @@ 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 { useAppSelector } from "../../../../redux/hooks"; -import FileIcon from "../../../FileIcon"; -import StyledMarkdownPreview from "../../../markdown/StyledMarkdownPreview"; -import { ExpandablePreview } from "./ExpandablePreview"; +import { vscBadgeBackground } from "../../../.."; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { useAppSelector } from "../../../../../redux/hooks"; +import FileIcon from "../../../../FileIcon"; +import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; +import { ExpandablePreview } from "../../components/ExpandablePreview"; const backticksRegex = /`{3,}/gm; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts new file mode 100644 index 000000000..f0a5fadde --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts @@ -0,0 +1 @@ +export * from "./CodeblockExtension"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts index b81d223b4..3719cbc14 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts @@ -3,12 +3,8 @@ import { PluginKey } from "@tiptap/pm/state"; import Suggestion from "@tiptap/suggestion"; import { MentionOptions } from "./types"; -export const MENTION_NAME = "mention"; - -export const MentionPluginKey = new PluginKey(MENTION_NAME); - export const MentionExtension = Node.create({ - name: MENTION_NAME, + name: "mention", addOptions() { return { @@ -22,7 +18,7 @@ export const MentionExtension = Node.create({ }, 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 diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts deleted file mode 100644 index 1b18e30b8..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { mergeAttributes, Node } from "@tiptap/core"; -import { ReactNodeViewRenderer } from "@tiptap/react"; -import { PromptBlockPreview } from "../toolbar-previews/PromptBlockPreview"; - -export interface PromptOptions { - HTMLAttributes: Record; -} - -export const PROMPT_BLOCK_NAME = "prompt-block"; - -/** - * Extension for adding prompt blocks to the Tiptap editor - */ -export const PromptExtension = Node.create({ - name: PROMPT_BLOCK_NAME, - group: "block", - - addOptions() { - return { - HTMLAttributes: {}, - }; - }, - - 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); - }, -}); \ No newline at end of file diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptBlockPreview.tsx similarity index 57% rename from gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptBlockPreview.tsx index 2e02f742c..891c8edb6 100644 --- a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/PromptBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptBlockPreview.tsx @@ -1,19 +1,27 @@ import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; -import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; -import { ContextItemWithId } from "core"; +import { + NodeViewProps, + NodeViewWrapper, + NodeViewWrapperProps, +} from "@tiptap/react"; import { useContext, useMemo } from "react"; -import { vscBadgeBackground } from "../../.."; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { useAppSelector } from "../../../../redux/hooks"; -import { ExpandablePreview } from "./ExpandablePreview"; +import { vscBadgeBackground } from "../../../.."; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { useAppSelector } from "../../../../../redux/hooks"; +import { ExpandablePreview } from "../../components/ExpandablePreview"; +import { PromptAttributes } from "./PromptExtension"; /** * Component for prompt blocks in the Tiptap editor */ -export const PromptBlockPreview = (props: any) => { - const { node, deleteNode, selected } = props; - const item: ContextItemWithId = node.attrs.item; - const inputId = node.attrs.inputId; +export const PromptBlockPreview = ({ + node, + deleteNode, + selected, + editor, +}: NodeViewProps) => { + const { item, inputId } = node.attrs as PromptAttributes; + const ideMessenger = useContext(IdeMessengerContext); // Not setting this as a "p" will cause issues with foreign keyboards @@ -27,8 +35,6 @@ export const PromptBlockPreview = (props: any) => { return newestCodeblockForInputId !== item.id.itemId; }, [newestCodeblockForInputId, item.id.itemId]); - console.log({ id: item.id.itemId, newestCodeblockForInputId }); - const handleTitleClick = (e: React.MouseEvent) => { e.stopPropagation(); ideMessenger.post("showVirtualFile", { @@ -37,6 +43,20 @@ export const PromptBlockPreview = (props: any) => { }); }; + const handleDelete = () => { + // Use the clearSlashCommand command to properly clean up everything + if (editor) { + // Make sure this runs after the current event loop cycle + // to avoid React state update conflicts + setTimeout(() => { + editor.commands.clearSlashCommand(); + }, 0); + } else { + // Fallback to deleteNode if editor is not available + deleteNode(); + } + }; + const borderColor = selected ? vscBadgeBackground : undefined; return ( @@ -48,7 +68,7 @@ export const PromptBlockPreview = (props: any) => { title={item.name} icon={} initiallyHidden={initiallyHidden} - onDelete={() => deleteNode()} + onDelete={handleDelete} borderColor={borderColor} onTitleClick={handleTitleClick} > @@ -58,4 +78,4 @@ export const PromptBlockPreview = (props: any) => { ); -}; +}; \ No newline at end of file diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts new file mode 100644 index 000000000..0921fe614 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts @@ -0,0 +1,108 @@ +import { mergeAttributes, Node } from "@tiptap/core"; +import { ReactNodeViewRenderer } from "@tiptap/react"; +import { ContextItemWithId } from "core"; +import { Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { PromptBlockPreview } from "./PromptBlockPreview"; + +export interface PromptOptions { + HTMLAttributes: Record; +} + +export interface PromptAttributes { + item: ContextItemWithId; + inputId: string; +} + +declare module "@tiptap/core" { + interface Commands { + promptBlock: { + /** + * Insert a prompt block into the editor + */ + insertPrompt: (item: ContextItemWithId, inputId: string) => ReturnType; + + /** + * Clear all prompt blocks from the editor + */ + clearPrompt: () => ReturnType; + }; + } +} + +/** + * Extension for adding prompt blocks to the Tiptap editor + */ +export const PromptExtension = Node.create({ + name: "prompt-block", + group: "block", + + addOptions() { + return { + HTMLAttributes: {}, + }; + }, + + 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: (item: ContextItemWithId, inputId: string) => + ({ commands }) => { + return commands.insertContent({ + type: this.name, + attrs: { + item, + inputId, + }, + }); + }, + + 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; + }, + }; + }, +}); \ No newline at end of file diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts new file mode 100644 index 000000000..c9c12a825 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts @@ -0,0 +1 @@ +export * from "./PromptExtension"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts index d29246e5e..e8a9b3006 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts @@ -7,7 +7,7 @@ import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; import { ContextItemWithId, SlashCommandDescription } from "core"; import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; import { ComboBoxItem } from "../../types"; -import { PROMPT_BLOCK_NAME } from "./PromptExtension"; +import { PromptExtension } from "./PromptExtension/PromptExtension"; export type SlashCommandOptions = { HTMLAttributes: Record; @@ -26,12 +26,13 @@ declare module "@tiptap/core" { /** * Insert a slash command and its associated prompt block * @param command The slash command description - * @param inputId The input ID (defaults to MAIN_EDITOR_INPUT_ID) */ - insertSlashCommand: ( - command: SlashCommandDescription, - inputId?: string, - ) => ReturnType; + insertSlashCommand: (command: SlashCommandDescription) => ReturnType; + + /** + * Clear the slash command content from the editor + */ + clearSlashCommand: () => ReturnType; }; } } @@ -148,8 +149,12 @@ export const SlashCommandExtension = Node.create({ addKeyboardShortcuts() { return { - Backspace: () => - this.editor.commands.command(({ tr, state }) => { + Backspace: () => { + // Get a reference to the editor + const editor = this.editor; + + // First try to find if we're at a slash command + const result = editor.commands.command(({ tr, state }) => { let isSlashCommand = false; const { selection } = state; const { empty, anchor } = selection; @@ -172,7 +177,21 @@ export const SlashCommandExtension = Node.create({ }); return isSlashCommand; - }), + }); + + // If we found and processed a slash command, also call clearSlashCommand + // to remove the prompt block + if (result) { + // We need to do this with a small delay to ensure the transaction + // above completes first + setTimeout(() => { + editor.commands.clearSlashCommand(); + }, 0); + return true; + } + + return false; + }, }; }, @@ -192,25 +211,31 @@ export const SlashCommandExtension = Node.create({ command: SlashCommandDescription, inputId: string = MAIN_EDITOR_INPUT_ID, ) => - ({ chain }) => { + ({ commands, chain }) => { + if (!command.prompt) { + return false; + } + + const contextItem: ContextItemWithId = { + content: command.prompt, + name: command.name, + description: command.description || "", + id: { + providerTitle: "prompt", + itemId: command.name, + }, + }; + // Create the document with both a prompt block and the slash command paragraph return chain() .setContent({ type: "doc", content: [ - // Add the prompt block at the beginning + // First insert the prompt using the PromptExtension command { - type: PROMPT_BLOCK_NAME, + type: PromptExtension.name, attrs: { - item: { - content: command.prompt, - name: command.name, - description: command.description || "", - id: { - providerTitle: "prompt", - itemId: command.name, - }, - } as ContextItemWithId, + item: contextItem, inputId, }, }, @@ -236,6 +261,33 @@ export const SlashCommandExtension = Node.create({ .focus() .run(); }, + + clearSlashCommand: + () => + ({ commands, state }) => { + // First clear all prompt blocks using the PromptExtension command + commands.clearPrompt(); + + // Then find and remove all slash command nodes + let found = false; + const slashNodes: { pos: number; node: ProseMirrorNode }[] = []; + + state.doc.descendants((node, pos) => { + if (node.type.name === this.name) { + slashNodes.push({ pos, node }); + found = true; + } + return true; + }); + + // Delete all found slash command nodes in reverse order + for (let i = slashNodes.length - 1; i >= 0; i--) { + const { pos, node } = slashNodes[i]; + commands.deleteRange({ from: pos, to: pos + node.nodeSize }); + } + + return found; + }, }; }, }); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts index a790c5b0c..ef316d4f0 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -2,4 +2,4 @@ export * from "./AddCodeToEditExtension"; export * from "./CodeblockExtension"; export * from "./MentionExtension"; export * from "./PromptExtension"; -export * from "./SlashCommandExtension"; \ No newline at end of file +export * from "./SlashCommandExtension"; diff --git a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts b/gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts deleted file mode 100644 index 183e0daa0..000000000 --- a/gui/src/components/mainInput/TipTapEditor/toolbar-previews/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { CodeblockPreview } from "./CodeblockPreview"; -export { PromptBlockPreview as PromptPreview } from "./PromptBlockPreview"; diff --git a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index c1cd5c23e..ad3eb515e 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -12,6 +12,7 @@ import { AppDispatch } from "../../../../redux/store"; import AtMentionDropdown from "../../AtMentionDropdown"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; import { TIPPY_DIV_ID } from "../TipTapEditor"; +import { SlashCommandExtension } from "../extensions"; function getSuggestion( items: (props: { query: string }) => Promise, @@ -219,7 +220,7 @@ export function getSlashCommandDropdownOptions( id: provider.title, title: provider.title, label: provider.title, - type: (provider.type ?? "slashCommand") as ComboBoxItemType, + type: (provider.type ?? SlashCommandExtension.name) as ComboBoxItemType, content: provider.content, action: () => { dispatch( From 9c0f43342e6ba576c5105d810eda8101ec238426 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:08:48 -0700 Subject: [PATCH 58/93] edit tool ui take zero --- core/tools/definitions/editFile.ts | 13 +++++++++++-- .../markdown/StyledMarkdownPreview.tsx | 3 ++- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 19 +++++++++++++++++++ .../FunctionSpecificToolCallDiv.tsx | 15 ++++++++++++--- 4 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/EditFile.tsx diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 1ff44f7c7..6ee5cee6b 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,6 +1,11 @@ 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", @@ -12,16 +17,20 @@ export const editFileTool: Tool = { function: { name: BuiltInToolNames.EditExistingFile, description: - "To edit an existing file, call this tool and follow the returned instructions. If you don't have the contents of the file, read it first.", + "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"], + 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", + }, }, }, }, diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index fbd6801b9..4c2635ce1 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -130,6 +130,7 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; + autoApplyCodeblocks?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -330,7 +331,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( relativeFilepath={relativeFilePath} isGeneratingCodeBlock={isGeneratingCodeBlock} range={range} - autoApply={false} + autoApply={props.autoApplyCodeblocks} codeBlockStreamId={codeblockStreamId} > diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx new file mode 100644 index 000000000..0dee7ab2b --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -0,0 +1,19 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; + +type EditToolCallProps = { + relativeFilePath: string; + newContents: string; +}; + +export function EditFile(props: EditToolCallProps) { + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + + return props.relativeFilePath ? ( + + ) : null; +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 52b41f505..8592960eb 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -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,21 @@ function FunctionSpecificToolCallDiv({ const args = toolCallState.parsedArgs; switch (toolCall.function?.name) { - case "builtin_create_new_file": + case BuiltInToolNames.CreateNewFile: return ( ); - case "builtin_run_terminal_command": + case BuiltInToolNames.EditExistingFile: + return ( + + ); + case BuiltInToolNames.RunTerminalCommand: return ( Date: Thu, 3 Apr 2025 20:46:19 -0700 Subject: [PATCH 59/93] error if already exists" --- core/tools/implementations/createNewFile.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index b5d5e6c1b..cf8746328 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -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 too 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 []; }; From e595ce871f7cf21f19d946641c7415594fac7a27 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:17:04 -0700 Subject: [PATCH 60/93] edit tool call div --- extensions/vscode/package-lock.json | 4 ++-- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 1 + gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c01a1eb12..a26290f1a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.18", + "version": "1.1.19", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.18", + "version": "1.1.19", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 0dee7ab2b..56ee77ef3 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -14,6 +14,7 @@ export function EditFile(props: EditToolCallProps) { isRenderingInStepContainer={true} source={src} autoApplyCodeblocks={true} + hideApply={true} /> ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 8592960eb..ee8726fae 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -25,7 +25,7 @@ function FunctionSpecificToolCallDiv({ return ( ); case BuiltInToolNames.RunTerminalCommand: From 95016e5c3c67a7f79c602d6826197eaf3c303363 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 20:57:16 -0700 Subject: [PATCH 61/93] merge create tool updates --- .../StepContainerPreToolbar.tsx | 21 +++++++++---------- .../markdown/StyledMarkdownPreview.tsx | 2 ++ gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 8 +++++-- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index ec0000b2c..1a67e2cb4 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -216,17 +216,16 @@ export default function StepContainerPreToolbar( {!isGeneratingCodeBlock && ( <> - {props.hideApply || - (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - - ) : ( - - ))} + {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( + + ) : props.hideApply ? null : ( + + )} )}
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 4c2635ce1..4aed38536 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -131,6 +131,7 @@ interface StyledMarkdownPreviewProps { itemIndex?: number; useParentBackgroundColor?: boolean; autoApplyCodeblocks?: boolean; + hideApply?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -333,6 +334,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( range={range} autoApply={props.autoApplyCodeblocks} codeBlockStreamId={codeblockStreamId} + hideApply={props.hideApply} > diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index bca805f45..9829ef64b 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -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 ? ( - + ) : null; } From 2780b588f749b6743bc8514d32d854c4b6aa6653 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:19:40 -0700 Subject: [PATCH 62/93] edit tool autoapply --- .../StepContainerPreToolbar.tsx | 30 +++++++------------ 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 1a67e2cb4..26fdb6261 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -135,25 +135,17 @@ export default function StepContainerPreToolbar( } }, [props.children, codeBlockContent]); - // useEffect(() => { - // const hasCompletedGenerating = - // wasGeneratingRef.current && !isGeneratingCodeBlock; - // console.log( - // wasGeneratingRef.current, - // isGeneratingCodeBlock, - // props.autoApply, - // ); - // wasGeneratingRef.current = isGeneratingCodeBlock; - // if (hasCompletedGenerating) { - // console.log("Completed generating", props.autoApply); - // if (props.autoApply) { - // onClickApply(); - // } - // // else if(isInEditMode) { - // // onClickApply(); - // // } - // } - // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); + useEffect(() => { + const hasCompletedGenerating = + wasGeneratingRef.current && !isGeneratingCodeBlock; + + wasGeneratingRef.current = isGeneratingCodeBlock; + if (hasCompletedGenerating) { + if (props.autoApply) { + onClickApply(); + } + } + }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( From af9b80f4731275d0e5c97c8d931beafa6fd0e431 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:43:59 -0700 Subject: [PATCH 63/93] toolbar styling --- gui/src/components/FileIcon.tsx | 2 +- .../StepContainerPreToolbar/FileInfo.tsx | 25 ++++++++++--------- .../StepContainerPreToolbar.tsx | 25 ++++++++----------- 3 files changed, 25 insertions(+), 27 deletions(-) diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 6f96e498d..0f2b729cb 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -45,7 +45,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { height: height, fill: color, flexShrink: 0, - display: "block", + display: "flex", }} /> ); diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c2f09a24a..06defbeac 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -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,18 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { } return ( -
-
+
+
- - {getLastNPathParts(relativeFilepath, 1)} - {range && ` ${range}`} -
+ + asdfasdfasdfasdfasdfasdfasdf + {getLastNPathParts(relativeFilepath, 1)} + {range && ` ${range}`} +
); }; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 26fdb6261..776192e45 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -25,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}; @@ -37,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; @@ -181,31 +182,27 @@ export default function StepContainerPreToolbar( return ( - -
+ +
-
- -
+
- {isGeneratingCodeBlock && ( + {isGeneratingCodeBlock ? ( - )} - - {!isGeneratingCodeBlock && ( + ) : ( <> {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( From ac27ec97d7044d2aedeeea85247c13dd0f8fd0ab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:44:15 -0700 Subject: [PATCH 64/93] cleanup --- gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index 06defbeac..ee46ccee8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -31,7 +31,6 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
- asdfasdfasdfasdfasdfasdfasdf {getLastNPathParts(relativeFilepath, 1)} {range && ` ${range}`} From 2c8cee9fd42fc8f18c9e6e37781e27276dae2786 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 3 Apr 2025 22:32:28 -0700 Subject: [PATCH 65/93] feat: handle deletions --- gui/src/components/FileIcon.tsx | 1 - .../mainInput/TipTapEditor/TipTapEditor.tsx | 6 +- .../components/ExpandablePreview.tsx | 5 +- .../components/NodeViewWrapper.tsx | 23 ++++++ ...odeToEditExtension.ts => AddCodeToEdit.ts} | 6 +- .../CodeBlock.tsx} | 6 +- .../CodeBlockPreview.tsx} | 24 +++--- .../extensions/CodeBlock/index.ts | 1 + .../extensions/CodeblockExtension/index.ts | 1 - .../{MentionExtension.ts => Mention.ts} | 7 +- .../PromptBlock.ts} | 59 ++++++++------- .../PromptBlockPreview.tsx | 34 ++------- .../TipTapEditor/extensions/Prompt/index.ts | 1 + .../extensions/PromptExtension/index.ts | 1 - ...ashCommandExtension.ts => SlashCommand.ts} | 74 +++++++++---------- .../TipTapEditor/extensions/index.ts | 10 +-- .../mainInput/TipTapEditor/index.ts | 1 + .../useMainEditorWebviewListeners.ts | 8 +- .../TipTapEditor/utils/editorConfig.ts | 32 ++------ .../TipTapEditor/utils/getSuggestion.ts | 4 +- .../utils/resolveEditorContent.ts | 12 +-- .../mainInput/util/handleMetaKeyIssues.ts | 4 +- gui/src/redux/thunks/updateFileSymbols.ts | 4 +- 23 files changed, 154 insertions(+), 170 deletions(-) create mode 100644 gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx rename gui/src/components/mainInput/TipTapEditor/extensions/{AddCodeToEditExtension.ts => AddCodeToEdit.ts} (97%) rename gui/src/components/mainInput/TipTapEditor/extensions/{CodeblockExtension/CodeblockExtension.tsx => CodeBlock/CodeBlock.tsx} (78%) rename gui/src/components/mainInput/TipTapEditor/extensions/{CodeblockExtension/CodeblockPreview.tsx => CodeBlock/CodeBlockPreview.tsx} (86%) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts rename gui/src/components/mainInput/TipTapEditor/extensions/{MentionExtension.ts => Mention.ts} (97%) rename gui/src/components/mainInput/TipTapEditor/extensions/{PromptExtension/PromptExtension.ts => Prompt/PromptBlock.ts} (56%) rename gui/src/components/mainInput/TipTapEditor/extensions/{PromptExtension => Prompt}/PromptBlockPreview.tsx (65%) create mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts delete mode 100644 gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts rename gui/src/components/mainInput/TipTapEditor/extensions/{SlashCommandExtension.ts => SlashCommand.ts} (79%) diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index ab0d338dd..5d364bf03 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -34,7 +34,6 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { ignore: "#586e75", }); - console.log({ file }); // Sanitize the SVG string before rendering it const { svg, color } = getIcon(file); const sanitizedSVG = DOMPurify.sanitize(svg); diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 24a9d4aa6..2c340c843 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -10,9 +10,8 @@ import { selectDefaultModel } from "../../../redux/slices/configSlice"; import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; -import { DragOverlay } from "./DragOverlay"; +import { DragOverlay, InputBoxDiv } from "./components"; import { useMainEditor } from "./MainEditorProvider"; -import { InputBoxDiv } from "./StyledComponents"; import "./TipTapEditor.css"; import { handleImageFile } from "./utils"; import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig"; @@ -31,6 +30,9 @@ 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; } diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx index 973700335..a6b886b05 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx @@ -87,6 +87,10 @@ export function ExpandablePreview(props: ExpandablePreviewProps) { const contentRef = useRef(null); const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); + useEffect(() => { + setHidden(props.initiallyHidden ?? false); + }, [props.initiallyHidden]); + useEffect(() => { const resizeObserver = new ResizeObserver(() => { setContentDims({ @@ -154,7 +158,6 @@ export function ExpandablePreview(props: ExpandablePreviewProps) {
- {/* Updated content section */} {!hidden && ( = ({ + 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 ( + + {children} + + ); +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts similarity index 97% rename from gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts index 519074bb1..87b524435 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEditExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts @@ -3,12 +3,14 @@ import { PluginKey } from "@tiptap/pm/state"; import Suggestion from "@tiptap/suggestion"; import { MentionOptions } from "./types"; -export const AddCodeToEditExtension = Node.create({ +export const AddCodeToEdit = Node.create({ name: "add-code-to-edit", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "add-code-to-edit", + }, renderHTML({ options, node }) { return [ "span", diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockExtension.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx similarity index 78% rename from gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockExtension.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx index a43c1e9d2..e96c567c4 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockExtension.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlock.tsx @@ -1,8 +1,8 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { CodeblockPreview } from "./CodeblockPreview"; +import { CodeBlockPreview } from "./CodeBlockPreview"; -export const CodeblockExtension = Node.create({ +export const CodeBlock = Node.create({ name: "codeblock", group: "block", @@ -37,6 +37,6 @@ export const CodeblockExtension = Node.create({ }, addNodeView() { - return ReactNodeViewRenderer(CodeblockPreview); + return ReactNodeViewRenderer(CodeBlockPreview); }, }); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx similarity index 86% rename from gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockPreview.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx index 66812b1df..cf7eb7885 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/CodeblockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -1,8 +1,4 @@ -import { - NodeViewProps, - NodeViewWrapper, - NodeViewWrapperProps, -} from "@tiptap/react"; +import { NodeViewProps } from "@tiptap/react"; import { ContextItemWithId } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; import { dedent, getMarkdownLanguageTagForFile } from "core/util"; @@ -13,13 +9,14 @@ import { useAppSelector } from "../../../../../redux/hooks"; import FileIcon from "../../../../FileIcon"; import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; import { ExpandablePreview } from "../../components/ExpandablePreview"; +import { NodeViewWrapper } from "../../components/NodeViewWrapper"; const backticksRegex = /`{3,}/gm; /** * Component for displaying a code block in the TipTap editor */ -export const CodeblockPreview = ({ +export const CodeBlockPreview = ({ node, deleteNode, selected, @@ -29,10 +26,6 @@ export const CodeblockPreview = ({ const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now const ideMessenger = useContext(IdeMessengerContext); - // 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"; - const newestCodeblockForInputId = useAppSelector( (store) => store.session.newestCodeblockForInput[inputId], ); @@ -41,6 +34,12 @@ export const CodeblockPreview = ({ return newestCodeblockForInputId !== item.id.itemId; }, [newestCodeblockForInputId, item.id.itemId]); + console.log({ + newestCodeblockForInputId, + id: item.id.itemId, + initiallyHidden, + }); + const content = useMemo(() => { return dedent`${item.content}`; }, [item.content]); @@ -79,10 +78,7 @@ export const CodeblockPreview = ({ : undefined; return ( - + } diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts new file mode 100644 index 000000000..ca111193d --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/index.ts @@ -0,0 +1 @@ +export * from "./CodeBlock"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts deleted file mode 100644 index f0a5fadde..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeblockExtension/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./CodeblockExtension"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts similarity index 97% rename from gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts index 3719cbc14..bfd48b0f6 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/MentionExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Mention.ts @@ -3,12 +3,15 @@ import { PluginKey } from "@tiptap/pm/state"; import Suggestion from "@tiptap/suggestion"; import { MentionOptions } from "./types"; -export const MentionExtension = Node.create({ +export const Mention = Node.create({ name: "mention", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "mention", + }, + renderHTML({ options, node }) { return [ "span", diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts similarity index 56% rename from gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts index 0921fe614..287a79e4a 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts @@ -1,14 +1,14 @@ import { mergeAttributes, Node } from "@tiptap/core"; +import { Node as ProseMirrorNode } from "@tiptap/pm/model"; import { ReactNodeViewRenderer } from "@tiptap/react"; import { ContextItemWithId } from "core"; -import { Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PromptBlockPreview } from "./PromptBlockPreview"; -export interface PromptOptions { +export interface PromptBlockOptions { HTMLAttributes: Record; } -export interface PromptAttributes { +export interface PromptBlockAttributes { item: ContextItemWithId; inputId: string; } @@ -32,13 +32,15 @@ declare module "@tiptap/core" { /** * Extension for adding prompt blocks to the Tiptap editor */ -export const PromptExtension = Node.create({ +export const PromptBlock = Node.create({ name: "prompt-block", group: "block", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "prompt-block", + }, }; }, @@ -71,7 +73,8 @@ export const PromptExtension = Node.create({ addCommands() { return { - insertPrompt: (item: ContextItemWithId, inputId: string) => + insertPrompt: + (item: ContextItemWithId, inputId: string) => ({ commands }) => { return commands.insertContent({ type: this.name, @@ -82,27 +85,29 @@ export const PromptExtension = Node.create({ }); }, - 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 + 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; - }); - - // 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; - }, + + // Return true if we deleted any nodes + return promptNodes.length > 0; + }, }; }, -}); \ No newline at end of file +}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx similarity index 65% rename from gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptBlockPreview.tsx rename to gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx index 891c8edb6..002740692 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/PromptBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx @@ -1,32 +1,25 @@ import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; -import { - NodeViewProps, - NodeViewWrapper, - NodeViewWrapperProps, -} from "@tiptap/react"; +import { NodeViewProps } from "@tiptap/react"; import { useContext, useMemo } from "react"; import { vscBadgeBackground } from "../../../.."; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import { useAppSelector } from "../../../../../redux/hooks"; import { ExpandablePreview } from "../../components/ExpandablePreview"; -import { PromptAttributes } from "./PromptExtension"; +import { NodeViewWrapper } from "../../components/NodeViewWrapper"; +import { PromptBlockAttributes } from "./PromptBlock"; /** * Component for prompt blocks in the Tiptap editor */ export const PromptBlockPreview = ({ node, - deleteNode, selected, editor, }: NodeViewProps) => { - const { item, inputId } = node.attrs as PromptAttributes; + const { item, inputId } = node.attrs as PromptBlockAttributes; const ideMessenger = useContext(IdeMessengerContext); - // Not setting this as a "p" will cause issues with foreign keyboards - const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p"; - const newestCodeblockForInputId = useAppSelector( (store) => store.session.newestCodeblockForInput[inputId], ); @@ -44,26 +37,13 @@ export const PromptBlockPreview = ({ }; const handleDelete = () => { - // Use the clearSlashCommand command to properly clean up everything - if (editor) { - // Make sure this runs after the current event loop cycle - // to avoid React state update conflicts - setTimeout(() => { - editor.commands.clearSlashCommand(); - }, 0); - } else { - // Fallback to deleteNode if editor is not available - deleteNode(); - } + editor.commands.clearSlashCommand(); }; const borderColor = selected ? vscBadgeBackground : undefined; return ( - + } @@ -78,4 +58,4 @@ export const PromptBlockPreview = ({ ); -}; \ No newline at end of file +}; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts new file mode 100644 index 000000000..3a72d7bd3 --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/index.ts @@ -0,0 +1 @@ +export * from "./PromptBlock"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts deleted file mode 100644 index c9c12a825..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/PromptExtension/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./PromptExtension"; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts similarity index 79% rename from gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts rename to gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts index e8a9b3006..4b5517c87 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommandExtension.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts @@ -1,13 +1,15 @@ // Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts) import { mergeAttributes, Node } from "@tiptap/core"; +import Document from "@tiptap/extension-document"; +import Paragraph from "@tiptap/extension-paragraph"; import { Node as ProseMirrorNode } from "@tiptap/pm/model"; import { PluginKey } from "@tiptap/pm/state"; import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; import { ContextItemWithId, SlashCommandDescription } from "core"; import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; import { ComboBoxItem } from "../../types"; -import { PromptExtension } from "./PromptExtension/PromptExtension"; +import { PromptBlock } from "./Prompt/PromptBlock"; export type SlashCommandOptions = { HTMLAttributes: Record; @@ -15,11 +17,6 @@ export type SlashCommandOptions = { suggestion: Omit, "editor">; }; -export const SLASH_CMD_NAME = "slash-command"; -export const SLASH_CMD_SUGGESTION_CHAR = "/"; - -export const SlashCommandPluginKey = new PluginKey(SLASH_CMD_NAME); - declare module "@tiptap/core" { interface Commands { slashCommand: { @@ -37,18 +34,20 @@ declare module "@tiptap/core" { } } -export const SlashCommandExtension = Node.create({ - name: SLASH_CMD_NAME, +export const SlashCommand = Node.create({ + name: "slash-command", addOptions() { return { - HTMLAttributes: {}, + HTMLAttributes: { + class: "mention", + }, renderText({ node }) { return node.attrs.label ?? node.attrs.id; }, suggestion: { - char: SLASH_CMD_SUGGESTION_CHAR, - pluginKey: SlashCommandPluginKey, + char: "/", + pluginKey: new PluginKey(this.name), startOfLine: true, command: ({ editor, range, props }) => { // increase range.to by one when the next node is of type "text" @@ -141,12 +140,6 @@ export const SlashCommandExtension = Node.create({ ]; }, - renderText({ node }) { - return this.options.renderText({ - node, - }); - }, - addKeyboardShortcuts() { return { Backspace: () => { @@ -211,7 +204,7 @@ export const SlashCommandExtension = Node.create({ command: SlashCommandDescription, inputId: string = MAIN_EDITOR_INPUT_ID, ) => - ({ commands, chain }) => { + ({ chain }) => { if (!command.prompt) { return false; } @@ -226,14 +219,17 @@ export const SlashCommandExtension = Node.create({ }, }; - // Create the document with both a prompt block and the slash command paragraph + // Right now this inserts at the beginning of the document, which removes codeblocks. + // This is the current behavior of slash commands, eg codeblocks aren't sent. + // Once this bug if fixed, we should instead insert prompt block at the beginning of the document + // without clearing the codeblocks. return chain() .setContent({ - type: "doc", + type: Document.name, content: [ // First insert the prompt using the PromptExtension command { - type: PromptExtension.name, + type: PromptBlock.name, attrs: { item: contextItem, inputId, @@ -241,7 +237,7 @@ export const SlashCommandExtension = Node.create({ }, // Add the paragraph with the slash command { - type: "paragraph", + type: Paragraph.name, content: [ { type: this.name, @@ -264,29 +260,25 @@ export const SlashCommandExtension = Node.create({ clearSlashCommand: () => - ({ commands, state }) => { - // First clear all prompt blocks using the PromptExtension command - commands.clearPrompt(); + ({ editor }) => { + editor.commands.clearPrompt(); - // Then find and remove all slash command nodes - let found = false; - const slashNodes: { pos: number; node: ProseMirrorNode }[] = []; + editor.commands.command(({ tr, state }) => { + let hasDeleted = false; - state.doc.descendants((node, pos) => { - if (node.type.name === this.name) { - slashNodes.push({ pos, node }); - found = true; - } - return true; + // Find all slash command nodes in the document + state.doc.descendants((node, pos) => { + if (node.type.name === this.name) { + // Delete the node at the found position + tr.delete(pos, pos + node.nodeSize); + hasDeleted = true; + } + }); + + return hasDeleted; }); - // Delete all found slash command nodes in reverse order - for (let i = slashNodes.length - 1; i >= 0; i--) { - const { pos, node } = slashNodes[i]; - commands.deleteRange({ from: pos, to: pos + node.nodeSize }); - } - - return found; + return true; }, }; }, diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts index ef316d4f0..06426b9c3 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -1,5 +1,5 @@ -export * from "./AddCodeToEditExtension"; -export * from "./CodeblockExtension"; -export * from "./MentionExtension"; -export * from "./PromptExtension"; -export * from "./SlashCommandExtension"; +export * from "./AddCodeToEdit"; +export * from "./CodeBlock"; +export * from "./Mention"; +export * from "./Prompt"; +export * from "./SlashCommand"; diff --git a/gui/src/components/mainInput/TipTapEditor/index.ts b/gui/src/components/mainInput/TipTapEditor/index.ts index 51f6eba38..b2d446398 100644 --- a/gui/src/components/mainInput/TipTapEditor/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/index.ts @@ -1,3 +1,4 @@ +export * from "./extensions"; export * from "./MainEditorProvider"; export * from "./TipTapEditor"; export * from "./utils"; diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 90bfcd8cc..bedb3df50 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -9,7 +9,7 @@ import { } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { CodeblockExtension } from "./extensions"; +import { CodeBlock } from "./extensions"; /** * Hook for setting up main editor specific webview listeners @@ -114,7 +114,7 @@ export function useMainEditorWebviewListeners({ if (el.attrs?.item?.name === contextItem.name) { return; // Prevent exact duplicate code blocks } - if (el.type === CodeblockExtension.name) { + if (el.type === CodeBlock.name) { index += 2; } else { break; @@ -124,7 +124,7 @@ export function useMainEditorWebviewListeners({ editor .chain() .insertContentAt(index, { - type: CodeblockExtension.name, + type: CodeBlock.name, attrs: { item: contextItem, inputId, @@ -132,6 +132,8 @@ export function useMainEditorWebviewListeners({ }) .run(); + console.log("id: ", contextItem.id.itemId); + dispatch( setNewestCodeblocksForInput({ inputId, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index d2c77529d..8addede87 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -286,10 +286,7 @@ export function createEditorConfig(options: { }, }), Text, - ContinueExtensions.MentionExtension.configure({ - HTMLAttributes: { - class: "mention", - }, + ContinueExtensions.Mention.configure({ suggestion: getContextProviderDropdownOptions( availableContextProvidersRef, getSubmenuContextItemsRef, @@ -299,15 +296,8 @@ export function createEditorConfig(options: { inSubmenuRef, ideMessenger, ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, }), - - ContinueExtensions.AddCodeToEditExtension.configure({ - HTMLAttributes: { - class: "add-code-to-edit", - }, + ContinueExtensions.AddCodeToEdit.configure({ suggestion: { ...getContextProviderDropdownOptions( availableContextProvidersRef, @@ -343,10 +333,7 @@ export function createEditorConfig(options: { }, }, }), - ContinueExtensions.SlashCommandExtension.configure({ - HTMLAttributes: { - class: "mention", - }, + ContinueExtensions.SlashCommand.configure({ suggestion: getSlashCommandDropdownOptions( availableSlashCommandsRef, onClose, @@ -355,20 +342,13 @@ export function createEditorConfig(options: { dispatch, props.inputId, ), - renderText: (props) => { - return props.node.attrs.label; - }, }), - ContinueExtensions.PromptExtension.configure({ - HTMLAttributes: { - class: "prompt-block", - }, - }), - ContinueExtensions.CodeblockExtension, + ContinueExtensions.PromptBlock, + ContinueExtensions.CodeBlock, ], editorProps: { attributes: { - class: "outline-none -mt-1 overflow-hidden", + class: "outline-none overflow-hidden", style: `font-size: ${getFontSize()}px;`, }, }, diff --git a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index ad3eb515e..b553b6d9a 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -12,7 +12,7 @@ import { AppDispatch } from "../../../../redux/store"; import AtMentionDropdown from "../../AtMentionDropdown"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; import { TIPPY_DIV_ID } from "../TipTapEditor"; -import { SlashCommandExtension } from "../extensions"; +import { SlashCommand } from "../extensions"; function getSuggestion( items: (props: { query: string }) => Promise, @@ -220,7 +220,7 @@ export function getSlashCommandDropdownOptions( id: provider.title, title: provider.title, label: provider.title, - type: (provider.type ?? SlashCommandExtension.name) as ComboBoxItemType, + type: (provider.type ?? SlashCommand.name) as ComboBoxItemType, content: provider.content, action: () => { dispatch( diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index 5476f100c..34962eed4 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -18,11 +18,7 @@ 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 { - CodeblockExtension, - MentionExtension, - SlashCommandExtension, -} from "../extensions"; +import { CodeBlock, Mention, SlashCommand } from "../extensions"; interface MentionAttrs { label: string; @@ -86,7 +82,7 @@ function processEditorContent(editorState: JSONContent) { return [...parts, { type: "text", text }]; } - case CodeblockExtension.name: { + case CodeBlock.name: { if (!p.attrs?.item) { console.warn("codeBlock has no item attribute"); return parts; @@ -280,10 +276,10 @@ function resolveParagraph( switch (child.type) { case Text.name: return child.text; - case MentionExtension.name: + case Mention.name: contextItems.push(child.attrs as MentionAttrs); return child.attrs?.renderInlineAs ?? child.attrs?.label; - case SlashCommandExtension.name: + case SlashCommand.name: if (!slashCommand) { slashCommand = child.attrs?.id; return ""; diff --git a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts index b147a5609..bc45d19f1 100644 --- a/gui/src/components/mainInput/util/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/util/handleMetaKeyIssues.ts @@ -1,7 +1,7 @@ import { Editor } from "@tiptap/react"; import { KeyboardEvent } from "react"; import { getPlatform, isWebEnvironment } from "../../../util"; -import { CodeblockExtension } from "../TipTapEditor/extensions"; +import { CodeBlock } from "../TipTapEditor"; const isWebEnv = isWebEnvironment(); @@ -104,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 === CodeblockExtension.name) { + if (node.type.name === CodeBlock.name) { continue; } diff --git a/gui/src/redux/thunks/updateFileSymbols.ts b/gui/src/redux/thunks/updateFileSymbols.ts index c237e4216..49e259421 100644 --- a/gui/src/redux/thunks/updateFileSymbols.ts +++ b/gui/src/redux/thunks/updateFileSymbols.ts @@ -1,6 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ChatHistoryItem, ContextItemWithId } from "core"; -import { CodeblockExtension } from "../../components/mainInput/TipTapEditor/extensions"; +import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions"; import { updateFileSymbols } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -26,7 +26,7 @@ export function getContextItemsFromHistory( .flatMap((item) => item.editorState.content) .filter( (content) => - content?.type === CodeblockExtension.name && + content?.type === CodeBlock.name && content?.attrs?.item?.uri?.value && content.attrs.item.uri?.type === "file", ) From 1a63ea756df3827c27f6d114d03044460d004baf Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 23:41:05 -0700 Subject: [PATCH 66/93] hacky apply implementation --- core/core.ts | 18 ++- core/index.d.ts | 1 + core/protocol/core.ts | 2 +- core/protocol/ide.ts | 11 ++ core/protocol/ideWebview.ts | 12 -- core/tools/implementations/editFile.ts | 16 ++- core/util/filesystem.ts | 4 + .../continue/IntelliJIde.kt | 117 +++++++++++++++++- .../continueintellijextension/protocol/ide.kt | 1 - extensions/vscode/src/VsCodeIde.ts | 13 +- .../vscode/src/extension/VsCodeMessenger.ts | 4 +- .../StepContainerPreToolbar.tsx | 21 ++-- .../markdown/StyledMarkdownPreview.tsx | 21 +++- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 13 +- gui/src/redux/slices/sessionSlice.ts | 8 ++ gui/src/redux/thunks/callTool.ts | 6 + 16 files changed, 215 insertions(+), 53 deletions(-) diff --git a/core/core.ts b/core/core.ts index 11fecffb2..911ea0072 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,6 +36,7 @@ import { TTS } from "./util/tts"; import { DiffLine, + ToolExtras, type ContextItemId, type IDE, type IndexingProgressUpdate, @@ -871,7 +872,8 @@ export class Core { } }); - on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { + on("tools/call", async (msg) => { + const { toolCall, selectedModelTitle, applyStreamId } = msg.data; const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -887,6 +889,19 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + let applyToFile: ToolExtras["applyToFile"] = undefined; + if (applyStreamId) { + applyToFile = async (path: string, contents: string) => { + return await this.messenger.request("applyToFile", { + filepath: path, + text: contents, + streamId: applyStreamId, + curSelectedModelTitle: + config.selectedModelByRole.apply?.title ?? selectedModelTitle, + }); + }; + } + const contextItems = await callTool( tool, JSON.parse(toolCall.function.arguments || "{}"), @@ -896,6 +911,7 @@ export class Core { fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), tool, + applyToFile, }, ); diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..5b2b482ed 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -891,6 +891,7 @@ export interface ToolExtras { llm: ILLM; fetch: FetchFunction; tool: Tool; + applyToFile?: (path: string, content: string) => Promise; } export interface Tool { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 03940c283..f92f70a50 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -193,7 +193,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string }, + { toolCall: ToolCall; selectedModelTitle: string; applyStreamId?: string }, { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 5b2a7ab1f..9b3d030f6 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -23,6 +23,17 @@ export interface GetGhTokenArgs { export type ToIdeFromWebviewOrCoreProtocol = { // Methods from IDE type + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath?: string; + }, + void, + ]; getIdeInfo: [undefined, IdeInfo]; getWorkspaceDirs: [undefined, string[]]; writeFile: [{ path: string; contents: string }, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..03074b95f 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, - ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -12,17 +11,6 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB - applyToFile: [ - { - text: string; - streamId: string; - curSelectedModelTitle: string; - filepath?: string; - }, - void, - ]; overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index 80de79923..deac3cc54 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -1,8 +1,6 @@ import { ToolImpl } from "."; import { resolveRelativePathInDir } from "../../util/ideUtils"; -export const EDIT_TOOL_CONTEXT_ITEM_NAME = "Edit Tool Instructions"; - export const editFileImpl: ToolImpl = async (args, extras) => { const firstUriMatch = await resolveRelativePathInDir( args.filepath, @@ -11,12 +9,18 @@ export const editFileImpl: ToolImpl = async (args, extras) => { if (!firstUriMatch) { throw new Error(`File ${args.filepath} does not exist.`); } + if (!extras.applyToFile) { + throw new Error("Failed to apply to file: invalid apply stream id"); + } + if (!extras.llm.title) { + throw new Error("Failed to apply to file: no model selected"); + } + await extras.applyToFile(firstUriMatch, args.new_contents); return [ { - name: EDIT_TOOL_CONTEXT_ITEM_NAME, - description: "Instructions for editing the file", - content: - "Edit Instructions: return the full new file contents in a codeblock. The codeblock header should be of the format '```language filepath'", + name: "Edit results", + description: `Result of editing ${args.filepath}`, + content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs, prompt them to do so`, }, ]; }; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 3c6963071..573838caa 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -242,6 +242,10 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + async applyToFile() { + throw new Error("not implemented"); + } + async subprocess(command: string, cwd?: string): Promise<[string, string]> { return ["", ""]; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 7e68cf007..ce1eea771 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -7,6 +7,8 @@ import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil +import com.intellij.find.FindModel +import com.intellij.find.impl.FindInProjectUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity @@ -20,8 +22,10 @@ import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir +import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager @@ -46,7 +50,6 @@ class IntelliJIDE( private val gitService = GitService(project, continuePluginService) - private val ripgrep: String init { @@ -309,12 +312,116 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getSearchResults(query: String): String { - val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") - command.setWorkDirectory(project.basePath) - return ExecUtil.execAndGetOutput(command).stdout + override suspend fun getFileResults(pattern: String): List { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "--files", + "--iglob", + pattern, + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + ) + + command.setWorkDirectory(project.basePath) + val results = ExecUtil.execAndGetOutput(command).stdout + return results.split("\n") + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // Leaving in here for ideas + // val projectBasePath = project.basePath ?: return emptyList() + // val scope = GlobalSearchScope.projectScope(project) + // + // // Get all ignore patterns from .continueignore files + // val ignorePatterns = mutableSetOf() + // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> + // VfsUtil.collectChildrenRecursively(root).forEach { file -> + // if (file.name == ".continueignore") { + // file.inputStream.bufferedReader().useLines { lines -> + // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) + // } + // } + // } + // } + // + // return FilenameIndex.getAllFilesByExt(project, "*", scope) + // .filter { file -> + // val relativePath = file.path.removePrefix("$projectBasePath/") + // // Check if file matches pattern and isn't ignored + // PatternUtil.(relativePath, pattern) && + // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } + // } + // .map { it.path.removePrefix("$projectBasePath/") } + } } + override suspend fun getSearchResults(query: String): String { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "-i", + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + "-C", + "2", + "--heading", + "-e", + query, + "." + ) + + command.setWorkDirectory(project.basePath) + return ExecUtil.execAndGetOutput(command).stdout + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // For remote workspaces, use JetBrains search functionality + // val searchResults = StringBuilder() + // ApplicationManager.getApplication().invokeAndWait { + // val options = FindModel().apply { + // stringToFind = query + // isCaseSensitive = false + // isRegularExpressions = false + // isWholeWordsOnly = false + // searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc. + // isMultiline = true // Allow matching across multiple lines + // } + // + // val progressIndicator = EmptyProgressIndicator() + // val presentation = FindUsagesProcessPresentation( + // UsageViewPresentation() + // ) + // val filesToSearch = ProjectFileIndex.getInstance(project) + // .iterateContent(::ArrayList) + // .filterNot { it.isDirectory } + // .toSet() + // + // + // FindInProjectUtil.findUsages( + // options, + // project, + // progressIndicator, + // presentation, + // filesToSearch + // ) { result -> + // val virtualFile = result.virtualFile + // searchResults.append(virtualFile.path).append("\n") + // searchResults.append("${result..trim()}\n") + // true // continue searching + // } + // } + // return searchResults.toString() + } + } + + override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") val builder = ProcessBuilder(commandList) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 5ce49e80a..0e16eeba6 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,7 +23,6 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) - data class SaveFileParams(val filepath: String) data class FileExistsParams(val filepath: String) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 883039263..504acce2b 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -8,13 +8,6 @@ import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; -import { Repository } from "./otherExtensions/git"; -import { SecretStorage } from "./stubs/SecretStorage"; -import { VsCodeIdeUtils } from "./util/ideUtils"; -import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; -import { VsCodeWebviewProtocol } from "./webviewProtocol"; - import type { ContinueRcJson, FileStatsMap, @@ -29,6 +22,12 @@ import type { TerminalOptions, Thread, } from "core"; +import { executeGotoProvider } from "./autocomplete/lsp"; +import { Repository } from "./otherExtensions/git"; +import { SecretStorage } from "./stubs/SecretStorage"; +import { VsCodeIdeUtils } from "./util/ideUtils"; +import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23669305a..43987c4b8 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -128,7 +128,7 @@ export class VsCodeMessenger { ); }); - this.onWebview("applyToFile", async ({ data }) => { + this.onWebviewOrCore("applyToFile", async ({ data }) => { webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "streaming", diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 776192e45..e9393f384 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -57,7 +57,6 @@ export interface StepContainerPreToolbarProps { children: any; expanded?: boolean; hideApply?: boolean; - autoApply?: boolean; } export default function StepContainerPreToolbar( @@ -136,17 +135,17 @@ export default function StepContainerPreToolbar( } }, [props.children, codeBlockContent]); - useEffect(() => { - const hasCompletedGenerating = - wasGeneratingRef.current && !isGeneratingCodeBlock; + // useEffect(() => { + // const hasCompletedGenerating = + // wasGeneratingRef.current && !isGeneratingCodeBlock; - wasGeneratingRef.current = isGeneratingCodeBlock; - if (hasCompletedGenerating) { - if (props.autoApply) { - onClickApply(); - } - } - }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); + // wasGeneratingRef.current = isGeneratingCodeBlock; + // if (hasCompletedGenerating) { + // if (props.autoApply) { + // onClickApply(); + // } + // } + // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 4aed38536..5137c63b9 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -130,8 +130,8 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; - autoApplyCodeblocks?: boolean; hideApply?: boolean; + firstCodeblockStreamId?: string; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -199,7 +199,14 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const pastFileInfoRef = useUpdatingRef(pastFileInfo); const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( - [], + props.firstCodeblockStreamId + ? [ + { + streamId: props.firstCodeblockStreamId, + isGenerating: false, + }, + ] + : [], ); const [reactContent, setMarkdownSource] = useRemark({ @@ -319,9 +326,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( streamId: uuidv4(), isGenerating: isGeneratingCodeBlock, }; + } else { + codeblockState.current[codeBlockIndex].isGenerating = + isGeneratingCodeBlock; } - const codeblockStreamId = - codeblockState.current[codeBlockIndex].streamId; // We use a custom toolbar for codeblocks in the step container return ( @@ -332,8 +340,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( relativeFilepath={relativeFilePath} isGeneratingCodeBlock={isGeneratingCodeBlock} range={range} - autoApply={props.autoApplyCodeblocks} - codeBlockStreamId={codeblockStreamId} + codeBlockStreamId={ + codeblockState.current[codeBlockIndex].streamId + } hideApply={props.hideApply} > diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 56ee77ef3..f1c528966 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,5 +1,9 @@ import { getMarkdownLanguageTagForFile } from "core/util"; +import { useMemo } from "react"; +import { v4 as uuidv4 } from "uuid"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setLastApplyToolStreamId } from "../../../redux/slices/sessionSlice"; type EditToolCallProps = { relativeFilePath: string; @@ -7,14 +11,21 @@ type EditToolCallProps = { }; export function EditFile(props: EditToolCallProps) { + const dispatch = useAppDispatch(); const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + const streamId = useMemo(() => { + const id = uuidv4(); + dispatch(setLastApplyToolStreamId({ streamId: id })); + return id; + }, []); + return props.relativeFilePath ? ( ) : null; } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 5aa714acc..88ac4e3b4 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -54,6 +54,7 @@ type SessionState = { curIndex: number; }; newestCodeblockForInput: Record; + lastApplyToolStreamId?: string; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -637,6 +638,12 @@ export const sessionSlice = createSlice({ toolCallState.status = "calling"; }, + setLastApplyToolStreamId: ( + state, + action: PayloadAction<{ streamId: string }>, + ) => { + state.lastApplyToolStreamId = action.payload.streamId; + }, setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, @@ -759,6 +766,7 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestCodeblocksForInput, + setLastApplyToolStreamId, cycleMode, } = sessionSlice.actions; diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 34ae00390..82ec08f0f 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,4 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { @@ -34,6 +35,11 @@ export const callTool = createAsyncThunk( const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, selectedModelTitle: defaultModel.title, + applyStreamId: + toolCallState.toolCall.function.name === + BuiltInToolNames.EditExistingFile + ? state.session.lastApplyToolStreamId + : undefined, }); if (result.status === "success") { From 2a8cb6d524cc9fda0226290a462dc8e87034b99c Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 4 Apr 2025 12:47:23 +0530 Subject: [PATCH 67/93] improve(package.js): show the version when vsce packages --- extensions/vscode/scripts/package.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/scripts/package.js b/extensions/vscode/scripts/package.js index 35ad7d24f..2fd5177eb 100644 --- a/extensions/vscode/scripts/package.js +++ b/extensions/vscode/scripts/package.js @@ -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`, ); }); From 1bc816b1f1bf43c354f153a43d3875cb4273d21d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 00:38:33 -0700 Subject: [PATCH 68/93] edit file apply state --- core/tools/implementations/editFile.ts | 5 +- .../StepContainerPreToolbar/ApplyActions.tsx | 12 +++-- .../StepContainerPreToolbar.tsx | 5 +- .../markdown/StyledMarkdownPreview.tsx | 4 +- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 54 +++++++++++++------ gui/src/redux/slices/sessionSlice.ts | 37 ++++++++----- 7 files changed, 80 insertions(+), 39 deletions(-) diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index deac3cc54..6862b29f2 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -12,15 +12,12 @@ export const editFileImpl: ToolImpl = async (args, extras) => { if (!extras.applyToFile) { throw new Error("Failed to apply to file: invalid apply stream id"); } - if (!extras.llm.title) { - throw new Error("Failed to apply to file: no model selected"); - } await extras.applyToFile(firstUriMatch, args.new_contents); return [ { name: "Edit results", description: `Result of editing ${args.filepath}`, - content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs, prompt them to do so`, + content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs. Prompt them to do so in your response`, }, ]; }; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 71e7ca9cf..0da1c5c7f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -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 ( -
- +
+ {`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`} {` remaining`} @@ -90,10 +91,15 @@ export default function ApplyActions(props: ApplyActionsProps) { ); } - + if (props.disableManualApply) { + return null; + } return applyButton("Reapply"); } default: + if (props.disableManualApply) { + return null; + } return applyButton("Apply"); } } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index e9393f384..375fd7ab8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -56,7 +56,7 @@ export interface StepContainerPreToolbarProps { range?: string; children: any; expanded?: boolean; - hideApply?: boolean; + disableManualApply?: boolean; } export default function StepContainerPreToolbar( @@ -206,8 +206,9 @@ export default function StepContainerPreToolbar( {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - ) : props.hideApply ? null : ( + ) : ( diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 9829ef64b..45396dc23 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -13,7 +13,7 @@ export function CreateFile(props: CreateFileToolCallProps) { ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index f1c528966..b3cb2bb63 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,9 +1,9 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; -import { v4 as uuidv4 } from "uuid"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import { useAppDispatch } from "../../../redux/hooks"; -import { setLastApplyToolStreamId } from "../../../redux/slices/sessionSlice"; +import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; type EditToolCallProps = { relativeFilePath: string; @@ -11,21 +11,45 @@ type EditToolCallProps = { }; export function EditFile(props: EditToolCallProps) { - const dispatch = useAppDispatch(); const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + const dispatch = useAppDispatch(); + + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const lastApplyToolStreamId = useAppSelector( + (state) => state.session.lastApplyToolStreamId, + ); const streamId = useMemo(() => { - const id = uuidv4(); - dispatch(setLastApplyToolStreamId({ streamId: id })); - return id; + return lastApplyToolStreamId; }, []); - return props.relativeFilePath ? ( - - ) : null; + console.log("STREAM ID", streamId); + + const applyState = useAppSelector((state) => + selectApplyStateByStreamId(state, streamId), + ); + + if (!props.relativeFilePath) { + return null; + } + + return ( + <> + + + {!isStreaming && applyState?.status === "done" && ( +
+ {}} + /> +
+ )} + + ); } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 88ac4e3b4..51af56ee7 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -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"; @@ -354,16 +355,25 @@ 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.function?.name === + BuiltInToolNames.EditExistingFile + ) { + state.lastApplyToolStreamId = uuidv4(); + } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -638,12 +648,6 @@ export const sessionSlice = createSlice({ toolCallState.status = "calling"; }, - setLastApplyToolStreamId: ( - state, - action: PayloadAction<{ streamId: string }>, - ) => { - state.lastApplyToolStreamId = action.payload.streamId; - }, setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, @@ -723,7 +727,17 @@ 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); + }, +); + +export const selectLastEditToolApplyState = createSelector( + [ + (state: RootState) => state.session.codeBlockApplyStates.states, + (state: RootState) => state.session.lastApplyToolStreamId, ], (states, streamId) => { return states.find((state) => state.streamId === streamId); @@ -766,7 +780,6 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestCodeblocksForInput, - setLastApplyToolStreamId, cycleMode, } = sessionSlice.actions; From 4683a20c2fbc0c70fe5457221743bd6a15749a3b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 00:51:31 -0700 Subject: [PATCH 69/93] cleanup --- core/tools/implementations/editFile.ts | 4 +- core/util/filesystem.ts | 4 - .../continue/IntelliJIde.kt | 115 +----------------- .../continueintellijextension/protocol/ide.kt | 1 + extensions/vscode/src/VsCodeIde.ts | 13 +- manual-testing-sandbox/requirements.txt | 2 +- 6 files changed, 15 insertions(+), 124 deletions(-) diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index 6862b29f2..26156352b 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -16,8 +16,8 @@ export const editFileImpl: ToolImpl = async (args, extras) => { return [ { name: "Edit results", - description: `Result of editing ${args.filepath}`, - content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs. Prompt them to do so in your response`, + description: `Edited ${args.filepath}`, + content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, }, ]; }; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 573838caa..3c6963071 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -242,10 +242,6 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - async applyToFile() { - throw new Error("not implemented"); - } - async subprocess(command: string, cwd?: string): Promise<[string, string]> { return ["", ""]; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index ce1eea771..7e68cf007 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -7,8 +7,6 @@ import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil -import com.intellij.find.FindModel -import com.intellij.find.impl.FindInProjectUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity @@ -22,10 +20,8 @@ import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir -import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager @@ -50,6 +46,7 @@ class IntelliJIDE( private val gitService = GitService(project, continuePluginService) + private val ripgrep: String init { @@ -312,115 +309,11 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getFileResults(pattern: String): List { - val ideInfo = this.getIdeInfo() - if (ideInfo.remoteName == "local") { - val command = GeneralCommandLine( - ripgrep, - "--files", - "--iglob", - pattern, - "--ignore-file", - ".continueignore", - "--ignore-file", - ".gitignore", - ) - - command.setWorkDirectory(project.basePath) - val results = ExecUtil.execAndGetOutput(command).stdout - return results.split("\n") - } else { - throw NotImplementedError("Ripgrep not supported, this workspace is remote") - - // Leaving in here for ideas - // val projectBasePath = project.basePath ?: return emptyList() - // val scope = GlobalSearchScope.projectScope(project) - // - // // Get all ignore patterns from .continueignore files - // val ignorePatterns = mutableSetOf() - // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> - // VfsUtil.collectChildrenRecursively(root).forEach { file -> - // if (file.name == ".continueignore") { - // file.inputStream.bufferedReader().useLines { lines -> - // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) - // } - // } - // } - // } - // - // return FilenameIndex.getAllFilesByExt(project, "*", scope) - // .filter { file -> - // val relativePath = file.path.removePrefix("$projectBasePath/") - // // Check if file matches pattern and isn't ignored - // PatternUtil.(relativePath, pattern) && - // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } - // } - // .map { it.path.removePrefix("$projectBasePath/") } - } - } - override suspend fun getSearchResults(query: String): String { - val ideInfo = this.getIdeInfo() - if (ideInfo.remoteName == "local") { - val command = GeneralCommandLine( - ripgrep, - "-i", - "--ignore-file", - ".continueignore", - "--ignore-file", - ".gitignore", - "-C", - "2", - "--heading", - "-e", - query, - "." - ) - - command.setWorkDirectory(project.basePath) - return ExecUtil.execAndGetOutput(command).stdout - } else { - throw NotImplementedError("Ripgrep not supported, this workspace is remote") - - // For remote workspaces, use JetBrains search functionality - // val searchResults = StringBuilder() - // ApplicationManager.getApplication().invokeAndWait { - // val options = FindModel().apply { - // stringToFind = query - // isCaseSensitive = false - // isRegularExpressions = false - // isWholeWordsOnly = false - // searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc. - // isMultiline = true // Allow matching across multiple lines - // } - // - // val progressIndicator = EmptyProgressIndicator() - // val presentation = FindUsagesProcessPresentation( - // UsageViewPresentation() - // ) - // val filesToSearch = ProjectFileIndex.getInstance(project) - // .iterateContent(::ArrayList) - // .filterNot { it.isDirectory } - // .toSet() - // - // - // FindInProjectUtil.findUsages( - // options, - // project, - // progressIndicator, - // presentation, - // filesToSearch - // ) { result -> - // val virtualFile = result.virtualFile - // searchResults.append(virtualFile.path).append("\n") - // searchResults.append("${result..trim()}\n") - // true // continue searching - // } - // } - // return searchResults.toString() - } + val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") + command.setWorkDirectory(project.basePath) + return ExecUtil.execAndGetOutput(command).stdout } - override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 0e16eeba6..5ce49e80a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,6 +23,7 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) + data class SaveFileParams(val filepath: String) data class FileExistsParams(val filepath: String) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 504acce2b..883039263 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -8,6 +8,13 @@ import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; +import { executeGotoProvider } from "./autocomplete/lsp"; +import { Repository } from "./otherExtensions/git"; +import { SecretStorage } from "./stubs/SecretStorage"; +import { VsCodeIdeUtils } from "./util/ideUtils"; +import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; + import type { ContinueRcJson, FileStatsMap, @@ -22,12 +29,6 @@ import type { TerminalOptions, Thread, } from "core"; -import { executeGotoProvider } from "./autocomplete/lsp"; -import { Repository } from "./otherExtensions/git"; -import { SecretStorage } from "./stubs/SecretStorage"; -import { VsCodeIdeUtils } from "./util/ideUtils"; -import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; -import { VsCodeWebviewProtocol } from "./webviewProtocol"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt index 87f2e654b..9de6f14df 100644 --- a/manual-testing-sandbox/requirements.txt +++ b/manual-testing-sandbox/requirements.txt @@ -54,4 +54,4 @@ aiohttp==3.7.4 # Others jupyter==1.0.0 gunicorn==20.1.0 -psycopg2==2.9.1 \ No newline at end of file +psycopg2==2.9.1 From 8f556c0b014b16f9586a8cccca0b8a4fcfc36711 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 01:02:48 -0700 Subject: [PATCH 70/93] move to custom edit impl --- core/index.d.ts | 1 - core/protocol/core.ts | 2 +- core/protocol/ide.ts | 11 -------- core/protocol/ideWebview.ts | 12 +++++++++ core/tools/callTool.ts | 6 ++--- core/tools/implementations/editFile.ts | 24 +---------------- .../vscode/src/extension/VsCodeMessenger.ts | 4 +-- gui/src/redux/thunks/callTool.ts | 27 ++++++++++++++----- manual-testing-sandbox/requirements.txt | 2 +- 9 files changed, 41 insertions(+), 48 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 5b2b482ed..ba97377d3 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -891,7 +891,6 @@ export interface ToolExtras { llm: ILLM; fetch: FetchFunction; tool: Tool; - applyToFile?: (path: string, content: string) => Promise; } export interface Tool { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f92f70a50..03940c283 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -193,7 +193,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string; applyStreamId?: string }, + { toolCall: ToolCall; selectedModelTitle: string }, { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 9b3d030f6..5b2a7ab1f 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -23,17 +23,6 @@ export interface GetGhTokenArgs { export type ToIdeFromWebviewOrCoreProtocol = { // Methods from IDE type - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB - applyToFile: [ - { - text: string; - streamId: string; - curSelectedModelTitle: string; - filepath?: string; - }, - void, - ]; getIdeInfo: [undefined, IdeInfo]; getWorkspaceDirs: [undefined, string[]]; writeFile: [{ path: string; contents: string }, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 03074b95f..a7cd16e5b 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,6 +4,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, + ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -11,6 +12,17 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath?: string; + }, + void, + ]; overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 2866124ef..2a04cb828 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -4,7 +4,6 @@ import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; -import { editFileImpl } from "./implementations/editFile"; import { exactSearchImpl } from "./implementations/exactSearch"; import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; @@ -139,8 +138,9 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); - case BuiltInToolNames.EditExistingFile: - return await editFileImpl(args, extras); + // Custom GUI handling for edit + // case BuiltInToolNames.EditExistingFile: + // return await editFileImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index 26156352b..cb829af6a 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -1,23 +1 @@ -import { ToolImpl } from "."; -import { resolveRelativePathInDir } from "../../util/ideUtils"; - -export const editFileImpl: ToolImpl = async (args, extras) => { - const firstUriMatch = await resolveRelativePathInDir( - args.filepath, - extras.ide, - ); - if (!firstUriMatch) { - throw new Error(`File ${args.filepath} does not exist.`); - } - if (!extras.applyToFile) { - throw new Error("Failed to apply to file: invalid apply stream id"); - } - await extras.applyToFile(firstUriMatch, args.new_contents); - return [ - { - name: "Edit results", - description: `Edited ${args.filepath}`, - content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, - }, - ]; -}; +// Edit has custom handling on the GUI side diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 43987c4b8..23669305a 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,7 +18,6 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; -import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -29,6 +28,7 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -128,7 +128,7 @@ export class VsCodeMessenger { ); }); - this.onWebviewOrCore("applyToFile", async ({ data }) => { + this.onWebview("applyToFile", async ({ data }) => { webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "streaming", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 82ec08f0f..8df0ccfa9 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,5 +1,4 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { @@ -35,11 +34,6 @@ export const callTool = createAsyncThunk( const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, selectedModelTitle: defaultModel.title, - applyStreamId: - toolCallState.toolCall.function.name === - BuiltInToolNames.EditExistingFile - ? state.session.lastApplyToolStreamId - : undefined, }); if (result.status === "success") { @@ -76,3 +70,24 @@ export const callTool = createAsyncThunk( } }, ); + +// export const editFileImpl: ToolImpl = async (args, extras) => { +// const firstUriMatch = await resolveRelativePathInDir( +// args.filepath, +// extras.ide, +// ); +// if (!firstUriMatch) { +// throw new Error(`File ${args.filepath} does not exist.`); +// } +// if (!extras.applyToFile) { +// throw new Error("Failed to apply to file: invalid apply stream id"); +// } +// await extras.applyToFile(firstUriMatch, args.new_contents); +// return [ +// { +// name: "Edit results", +// description: `Edited ${args.filepath}`, +// content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, +// }, +// ]; +// }; diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt index 9de6f14df..87f2e654b 100644 --- a/manual-testing-sandbox/requirements.txt +++ b/manual-testing-sandbox/requirements.txt @@ -54,4 +54,4 @@ aiohttp==3.7.4 # Others jupyter==1.0.0 gunicorn==20.1.0 -psycopg2==2.9.1 +psycopg2==2.9.1 \ No newline at end of file From e1ff2a9e57f21740672edddb24b45d8968d4d67b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 02:07:43 -0700 Subject: [PATCH 71/93] custom gui approach --- core/core.ts | 17 +--- gui/src/hooks/useSetup.ts | 8 ++ gui/src/redux/slices/sessionSlice.ts | 12 +-- gui/src/redux/thunks/callTool.ts | 121 ++++++++++++++++++--------- 4 files changed, 95 insertions(+), 63 deletions(-) diff --git a/core/core.ts b/core/core.ts index 911ea0072..b1393f8cd 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,7 +36,6 @@ import { TTS } from "./util/tts"; import { DiffLine, - ToolExtras, type ContextItemId, type IDE, type IndexingProgressUpdate, @@ -873,7 +872,7 @@ export class Core { }); on("tools/call", async (msg) => { - const { toolCall, selectedModelTitle, applyStreamId } = msg.data; + const { toolCall, selectedModelTitle } = msg.data; const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -889,19 +888,6 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - let applyToFile: ToolExtras["applyToFile"] = undefined; - if (applyStreamId) { - applyToFile = async (path: string, contents: string) => { - return await this.messenger.request("applyToFile", { - filepath: path, - text: contents, - streamId: applyStreamId, - curSelectedModelTitle: - config.selectedModelByRole.apply?.title ?? selectedModelTitle, - }); - }; - } - const contextItems = await callTool( tool, JSON.parse(toolCall.function.arguments || "{}"), @@ -911,7 +897,6 @@ export class Core { fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), tool, - applyToFile, }, ); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index d90259a9b..f1909afc5 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -17,6 +17,7 @@ import { import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { addContextItemsAtIndex, + selectLastEditToolApplyState, setInactive, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; @@ -245,6 +246,13 @@ function useSetup() { }, [defaultModel], ); + + const lastEditToolApplyState = useAppSelector(selectLastEditToolApplyState); + useEffect(() => { + ideMessenger.post("showToast", ["info", "updated last apply state"]); + // dispatch(setToolCallOutput(output)); + // dispatch(acceptToolCall()); + }, [lastEditToolApplyState]); } export default useSetup; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 51af56ee7..544a8c401 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,7 +21,6 @@ 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"; @@ -368,12 +367,6 @@ export const sessionSlice = createSlice({ ); } - if ( - toolCallDelta.function?.name === - BuiltInToolNames.EditExistingFile - ) { - state.lastApplyToolStreamId = uuidv4(); - } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -559,7 +552,9 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - + setLastToolApplyStreamId: (state, { payload }: PayloadAction) => { + state.lastApplyToolStreamId = payload; + }, updateCurCheckpoint: ( state, { payload }: PayloadAction<{ filepath: string; content: string }>, @@ -781,6 +776,7 @@ export const { deleteSessionMetadata, setNewestCodeblocksForInput, cycleMode, + setLastToolApplyStreamId, } = sessionSlice.actions; export const { diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 8df0ccfa9..190c25ccf 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,10 +1,17 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { ContextItem } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; +import { EditToolArgs } from "core/tools/definitions/editFile"; +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { v4 as uuidv4 } from "uuid"; +import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { acceptToolCall, cancelToolCall, setCalling, + setLastToolApplyStreamId, setToolCallOutput, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -31,28 +38,46 @@ export const callTool = createAsyncThunk( dispatch(setCalling()); - const result = await extra.ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - selectedModelTitle: defaultModel.title, - }); + let errorMessage = ""; + let output: ContextItem[] | undefined = undefined; - if (result.status === "success") { - const contextItems = result.content.contextItems; - dispatch(setToolCallOutput(contextItems)); - dispatch(acceptToolCall()); - - // Send to the LLM to continue the conversation - const response = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCall.id, - toolOutput: contextItems, - }), + if ( + toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile + ) { + const newToolStreamId = uuidv4(); + dispatch(setLastToolApplyStreamId(newToolStreamId)); + const args = JSON.parse( + toolCallState.toolCall.function.arguments || "{}", ); - unwrapResult(response); + try { + await customGuiEditImpl( + args, + extra.ideMessenger, + newToolStreamId, + defaultModel.title, + ); + } catch (e) { + errorMessage = "Failed to call edit tool"; + if (e instanceof Error) { + errorMessage = e.message; + } + } } else { + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + selectedModelTitle: defaultModel.title, + }); + if (result.status === "error") { + errorMessage = result.error; + } else { + output = result.content.contextItems; + } + } + + if (errorMessage) { dispatch(cancelToolCall()); - const output = await dispatch( + const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, toolOutput: [ @@ -60,34 +85,52 @@ export const callTool = createAsyncThunk( icon: "problems", name: "Tool Call Error", description: "Tool Call Failed", - content: `The tool call failed with the message:\n\n${result.error}\n\nPlease try something else or request further instructions.`, + content: `The tool call failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, hidden: false, }, ], }), ); - unwrapResult(output); + unwrapResult(wrapped); + } else if (output) { + dispatch(setToolCallOutput(output)); + dispatch(acceptToolCall()); + + // Send to the LLM to continue the conversation + const wrapped = await dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCall.id, + toolOutput: output, + }), + ); + unwrapResult(wrapped); } + // okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool }, ); -// export const editFileImpl: ToolImpl = async (args, extras) => { -// const firstUriMatch = await resolveRelativePathInDir( -// args.filepath, -// extras.ide, -// ); -// if (!firstUriMatch) { -// throw new Error(`File ${args.filepath} does not exist.`); -// } -// if (!extras.applyToFile) { -// throw new Error("Failed to apply to file: invalid apply stream id"); -// } -// await extras.applyToFile(firstUriMatch, args.new_contents); -// return [ -// { -// name: "Edit results", -// description: `Edited ${args.filepath}`, -// content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, -// }, -// ]; -// }; +async function customGuiEditImpl( + args: EditToolArgs, + ideMessenger: IIdeMessenger, + streamId: string, + modelTitle: string, +) { + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + ideMessenger.ide, + ); + if (!firstUriMatch) { + return [ + { + name: "Edit failure", + description: `editing ${args.filepath}`, + content: `Failed to edit ${args.filepath}: does not exist`, + }, + ]; + } + ideMessenger.post("applyToFile", { + streamId, + text: args.new_contents, + curSelectedModelTitle: modelTitle, + }); +} From 2efd3ff03a17b3a58d4c950ad9393dda3f82cb78 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:16:18 -0700 Subject: [PATCH 72/93] working and disable input when pending tool call stream --- core/core.ts | 3 +- core/index.d.ts | 1 + core/protocol/ideWebview.ts | 2 +- core/tools/definitions/exactSearch.ts | 2 +- core/tools/implementations/editFile.ts | 1 - .../protocol/ideWebview.kt | 3 +- extensions/vscode/src/commands.ts | 2 + .../vscode/src/diff/vertical/manager.ts | 4 ++ .../vscode/src/extension/VsCodeMessenger.ts | 5 ++- gui/src/components/mainInput/InputToolbar.tsx | 7 ++- .../markdown/StyledMarkdownPreview.tsx | 21 +++++---- gui/src/hooks/useSetup.ts | 44 +++++++++++++++---- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 33 +++++++------- .../FunctionSpecificToolCallDiv.tsx | 1 + gui/src/redux/slices/sessionSlice.ts | 32 +++++++------- gui/src/redux/thunks/callTool.ts | 22 ++++------ 16 files changed, 112 insertions(+), 71 deletions(-) delete mode 100644 core/tools/implementations/editFile.ts diff --git a/core/core.ts b/core/core.ts index b1393f8cd..11fecffb2 100644 --- a/core/core.ts +++ b/core/core.ts @@ -871,8 +871,7 @@ export class Core { } }); - on("tools/call", async (msg) => { - const { toolCall, selectedModelTitle } = msg.data; + on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..98f724fda 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1141,6 +1141,7 @@ export interface ApplyState { numDiffs?: number; filepath?: string; fileContent?: string; + toolCallId?: string; } export interface RangeInFileWithContents { diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..6aae337f0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -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, ]; diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index d20db3cec..7f6e03d6b 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -6,7 +6,7 @@ export const exactSearchTool: Tool = { displayTitle: "Exact Search", wouldLikeTo: 'search for "{{{ query }}}" in the repository', isCurrently: 'getting search results for "{{{ query }}}"', - hasAlready: 'retreived search results for "{{{ query }}}"', + hasAlready: 'retrieved search results for "{{{ query }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts deleted file mode 100644 index cb829af6a..000000000 --- a/core/tools/implementations/editFile.ts +++ /dev/null @@ -1 +0,0 @@ -// Edit has custom handling on the GUI side diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 07988ad0e..5c587c54d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -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( diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 836360e51..32d240d5f 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -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, }); } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 34c3345ac..4d4256a1f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -190,6 +190,7 @@ export class VerticalDiffManager { diffStream: AsyncGenerator, 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 { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -351,6 +354,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23669305a..98fe8489b 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -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; @@ -232,6 +234,7 @@ export class VsCodeMessenger { undefined, rangeToApplyTo, data.text, + data.toolCallId, ); } }); diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 3d0a38cec..27c034721 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -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 = diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index b473bb6f0..52ede7cbd 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -131,7 +131,7 @@ interface StyledMarkdownPreviewProps { itemIndex?: number; useParentBackgroundColor?: boolean; disableManualApply?: boolean; - firstCodeblockStreamId?: string; + singleCodeblockStreamId?: string; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -199,15 +199,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const pastFileInfoRef = useUpdatingRef(pastFileInfo); const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( - props.firstCodeblockStreamId - ? [ - { - streamId: props.firstCodeblockStreamId, - isGenerating: false, - }, - ] - : [], + [], ); + useEffect(() => { + if (props.singleCodeblockStreamId) { + codeblockState.current = [ + { + streamId: props.singleCodeblockStreamId, + isGenerating: false, + }, + ]; + } + }, [props.singleCodeblockStreamId]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index f1909afc5..914b96089 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,9 +1,9 @@ -import { useCallback, useContext, useEffect, useRef } from "react"; +import { useCallback, useContext, useEffect, useMemo, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { ConfigResult } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig } from "core"; +import { BrowserSerializedContinueConfig, ContextItem } from "core"; import { initializeProfilePreferencesThunk, selectProfileThunk, @@ -16,11 +16,13 @@ import { } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { + acceptToolCall, addContextItemsAtIndex, - selectLastEditToolApplyState, setInactive, + setToolCallOutput, } 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"; @@ -247,12 +249,38 @@ function useSetup() { [defaultModel], ); - const lastEditToolApplyState = useAppSelector(selectLastEditToolApplyState); + const activeToolStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); + const applyStates = useAppSelector( + (store) => store.session.codeBlockApplyStates, + ); + const activeToolApplyState = useMemo(() => { + if (!activeToolStreamId) { + return undefined; + } + return applyStates.states.find( + (state) => state.streamId && state.streamId === activeToolStreamId, + ); + }, [applyStates, activeToolStreamId]); + useEffect(() => { - ideMessenger.post("showToast", ["info", "updated last apply state"]); - // dispatch(setToolCallOutput(output)); - // dispatch(acceptToolCall()); - }, [lastEditToolApplyState]); + if (activeToolApplyState?.status === "closed") { + const output: ContextItem = { + name: "Edit tool output", + content: "Completed edit", + description: "", + }; + dispatch(acceptToolCall()); + dispatch(setToolCallOutput([output])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolApplyState.toolCallId!, + toolOutput: [output], + }), + ); + } + }, [activeToolApplyState?.status]); } export default useSetup; diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index b3cb2bb63..56263b0a1 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -2,32 +2,25 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; +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 dispatch = useAppDispatch(); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const lastApplyToolStreamId = useAppSelector( - (state) => state.session.lastApplyToolStreamId, - ); - const streamId = useMemo(() => { - return lastApplyToolStreamId; - }, []); + const states = useAppSelector((store) => store.session.codeBlockApplyStates); - console.log("STREAM ID", streamId); - - const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, streamId), - ); + const applyState = useMemo(() => { + return states.states.find( + (state) => state.toolCallId && state.toolCallId === props.toolCallId, + ); + }, [states, props.toolCallId]); if (!props.relativeFilePath) { return null; @@ -39,11 +32,15 @@ export function EditFile(props: EditToolCallProps) { isRenderingInStepContainer={true} source={src} disableManualApply={true} - firstCodeblockStreamId={streamId} + singleCodeblockStreamId={applyState?.streamId} /> - + {isStreaming && applyState?.status === "streaming" && ( +
+ Generating... +
+ )} {!isStreaming && applyState?.status === "done" && ( -
+
{}} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index ee8726fae..55ed79e2a 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -26,6 +26,7 @@ function FunctionSpecificToolCallDiv({ ); case BuiltInToolNames.RunTerminalCommand: diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 544a8c401..bf22a1858 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -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"; @@ -54,7 +55,7 @@ type SessionState = { curIndex: number; }; newestCodeblockForInput: Record; - lastApplyToolStreamId?: string; + activeToolStreamId?: string; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -367,6 +368,19 @@ export const sessionSlice = createSlice({ ); } + if ( + toolCallDelta.id && + toolCallDelta.function?.name === + BuiltInToolNames.EditExistingFile + ) { + const streamId = uuidv4(); + state.codeBlockApplyStates.states.push({ + streamId, + toolCallId: toolCallDelta.id, + status: "streaming", + }); + state.activeToolStreamId = streamId; + } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -552,9 +566,7 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - setLastToolApplyStreamId: (state, { payload }: PayloadAction) => { - state.lastApplyToolStreamId = payload; - }, + updateCurCheckpoint: ( state, { payload }: PayloadAction<{ filepath: string; content: string }>, @@ -632,6 +644,7 @@ export const sessionSlice = createSlice({ toolCallState.status = "canceled"; }, acceptToolCall: (state) => { + state.activeToolStreamId = undefined; const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -729,16 +742,6 @@ export const selectApplyStateByStreamId = createSelector( }, ); -export const selectLastEditToolApplyState = createSelector( - [ - (state: RootState) => state.session.codeBlockApplyStates.states, - (state: RootState) => state.session.lastApplyToolStreamId, - ], - (states, streamId) => { - return states.find((state) => state.streamId === streamId); - }, -); - export const { updateFileSymbols, setContextItemsAtIndex, @@ -776,7 +779,6 @@ export const { deleteSessionMetadata, setNewestCodeblocksForInput, cycleMode, - setLastToolApplyStreamId, } = sessionSlice.actions; export const { diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 190c25ccf..7ee80973f 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -3,7 +3,6 @@ import { ContextItem } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { EditToolArgs } from "core/tools/definitions/editFile"; import { resolveRelativePathInDir } from "core/util/ideUtils"; -import { v4 as uuidv4 } from "uuid"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; @@ -11,7 +10,6 @@ import { acceptToolCall, cancelToolCall, setCalling, - setLastToolApplyStreamId, setToolCallOutput, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -44,17 +42,19 @@ export const callTool = createAsyncThunk( if ( toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile ) { - const newToolStreamId = uuidv4(); - dispatch(setLastToolApplyStreamId(newToolStreamId)); const args = JSON.parse( toolCallState.toolCall.function.arguments || "{}", ); try { + if (!state.session.activeToolStreamId) { + throw new Error("Invalid apply state"); + } await customGuiEditImpl( args, extra.ideMessenger, - newToolStreamId, + state.session.activeToolStreamId, defaultModel.title, + toolCallState.toolCallId, ); } catch (e) { errorMessage = "Failed to call edit tool"; @@ -85,7 +85,7 @@ export const callTool = createAsyncThunk( icon: "problems", name: "Tool Call Error", description: "Tool Call Failed", - content: `The tool call failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, + content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, hidden: false, }, ], @@ -114,23 +114,19 @@ async function customGuiEditImpl( ideMessenger: IIdeMessenger, streamId: string, modelTitle: string, + toolCallId: string, ) { const firstUriMatch = await resolveRelativePathInDir( args.filepath, ideMessenger.ide, ); if (!firstUriMatch) { - return [ - { - name: "Edit failure", - description: `editing ${args.filepath}`, - content: `Failed to edit ${args.filepath}: does not exist`, - }, - ]; + throw new Error(`${args.filepath} does not exist`); } ideMessenger.post("applyToFile", { streamId, text: args.new_contents, curSelectedModelTitle: modelTitle, + toolCallId, }); } From 05c0d85942c853d806ccb866122e25e97e8d015d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:17:13 -0700 Subject: [PATCH 73/93] cleanup --- gui/src/components/mainInput/InputToolbar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 27c034721..20e40d9a9 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -106,7 +106,7 @@ function InputToolbar(props: InputToolbarProps) { props.disabled || isEditModeAndNoCodeToEdit || toolCallState?.status === "generated" || - activeToolCallStreamId; + !!activeToolCallStreamId; const toolsSupported = defaultModel && modelSupportsTools(defaultModel); From 05c092b3022913c7a879f4b2c739783cab8e4108 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:39:51 -0700 Subject: [PATCH 74/93] remove useeffect --- gui/src/components/Layout.tsx | 15 ------- gui/src/hooks/useSetup.ts | 62 +++++++++++++++------------- gui/src/redux/slices/sessionSlice.ts | 4 +- gui/src/redux/thunks/callTool.ts | 2 +- 4 files changed, 36 insertions(+), 47 deletions(-) diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 5b70f2e62..0f52d3d0b 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -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 () => { diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 914b96089..25b1a7fc0 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useRef } from "react"; +import { useCallback, useContext, useEffect, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -20,6 +20,7 @@ import { addContextItemsAtIndex, setInactive, setToolCallOutput, + updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import { streamResponseAfterToolCall } from "../redux/thunks"; @@ -252,35 +253,38 @@ function useSetup() { const activeToolStreamId = useAppSelector( (store) => store.session.activeToolStreamId, ); - const applyStates = useAppSelector( - (store) => store.session.codeBlockApplyStates, + 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([output])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolStreamId[1], + toolOutput: [output], + }), + ); + } + }, + [activeToolStreamId], ); - const activeToolApplyState = useMemo(() => { - if (!activeToolStreamId) { - return undefined; - } - return applyStates.states.find( - (state) => state.streamId && state.streamId === activeToolStreamId, - ); - }, [applyStates, activeToolStreamId]); - - useEffect(() => { - if (activeToolApplyState?.status === "closed") { - const output: ContextItem = { - name: "Edit tool output", - content: "Completed edit", - description: "", - }; - dispatch(acceptToolCall()); - dispatch(setToolCallOutput([output])); - dispatch( - streamResponseAfterToolCall({ - toolCallId: activeToolApplyState.toolCallId!, - toolOutput: [output], - }), - ); - } - }, [activeToolApplyState?.status]); } export default useSetup; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index bf22a1858..1813f9af2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -55,7 +55,7 @@ type SessionState = { curIndex: number; }; newestCodeblockForInput: Record; - activeToolStreamId?: string; + activeToolStreamId?: [string, string]; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -379,7 +379,7 @@ export const sessionSlice = createSlice({ toolCallId: toolCallDelta.id, status: "streaming", }); - state.activeToolStreamId = streamId; + state.activeToolStreamId = [streamId, toolCallDelta.id]; } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 7ee80973f..b1cf85650 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -52,7 +52,7 @@ export const callTool = createAsyncThunk( await customGuiEditImpl( args, extra.ideMessenger, - state.session.activeToolStreamId, + state.session.activeToolStreamId[0], defaultModel.title, toolCallState.toolCallId, ); From c50fbbbb4f6d3afa1f6bad105b761ef647e964b1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:48:49 -0700 Subject: [PATCH 75/93] tool call id for instant apply --- extensions/vscode/src/extension/VsCodeMessenger.ts | 1 + gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 98fe8489b..05f307c55 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -213,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.`; diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 56263b0a1..2ff34d489 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -34,11 +34,12 @@ export function EditFile(props: EditToolCallProps) { disableManualApply={true} singleCodeblockStreamId={applyState?.streamId} /> - {isStreaming && applyState?.status === "streaming" && ( + {/* TODO better indicator of generation at bottom */} + {/* {isStreaming && applyState?.status === "streaming" && (
Generating...
- )} + )} */} {!isStreaming && applyState?.status === "done" && (
Date: Fri, 4 Apr 2025 08:38:32 -0700 Subject: [PATCH 76/93] code cleanup --- .../ConversationStarterCards.tsx | 4 +- .../components/mainInput/ContinueInputBox.tsx | 2 +- .../mainInput/TipTapEditor/TipTapEditor.tsx | 4 +- ...eview.tsx => ExpandableToolbarPreview.tsx} | 55 +++++++++--- .../TipTapEditor/components/index.ts | 2 +- .../extensions/CodeBlock/CodeBlock.tsx | 2 +- .../extensions/CodeBlock/CodeBlockPreview.tsx | 34 ++----- .../extensions/Prompt/PromptBlock.ts | 4 +- .../extensions/Prompt/PromptBlockPreview.tsx | 25 ++---- .../useMainEditorWebviewListeners.ts | 6 +- .../TipTapEditor/utils/getSuggestion.ts | 4 +- .../utils/resolveEditorContent.ts | 88 +++++++++---------- gui/src/redux/slices/sessionSlice.ts | 11 +-- 13 files changed, 121 insertions(+), 120 deletions(-) rename gui/src/components/mainInput/TipTapEditor/components/{ExpandablePreview.tsx => ExpandableToolbarPreview.tsx} (75%) diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index 6d29a1df6..a680fa201 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -3,7 +3,7 @@ import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; import { MAIN_EDITOR_INPUT_ID } from "../../pages/gui/Chat"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setNewestCodeblocksForInput } from "../../redux/slices/sessionSlice"; +import { setNewestToolbarPreviewForInput } from "../../redux/slices/sessionSlice"; import { useMainEditor } from "../mainInput/TipTapEditor"; import { ConversationStarterCard } from "./ConversationStarterCard"; @@ -27,7 +27,7 @@ export function ConversationStarterCards() { function onClick(command: SlashCommandDescription) { dispatch( - setNewestCodeblocksForInput({ + setNewestToolbarPreviewForInput({ inputId: MAIN_EDITOR_INPUT_ID, contextItemId: command.name, }), diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 30ddd30f2..14777acb6 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -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 "./TipTapEditor/TipTapEditor"; +import { TipTapEditor } from "./TipTapEditor"; interface ContinueInputBoxProps { isEditMode?: boolean; diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index 2c340c843..3e52cfe8f 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -38,7 +38,7 @@ export interface TipTapEditorProps { export const TIPPY_DIV_ID = "tippy-js-div"; -function TipTapEditor(props: TipTapEditorProps) { +export function TipTapEditor(props: TipTapEditorProps) { const dispatch = useAppDispatch(); const mainEditorContext = useMainEditor(); @@ -275,5 +275,3 @@ function TipTapEditor(props: TipTapEditorProps) { ); } - -export default TipTapEditor; diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx similarity index 75% rename from gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx rename to gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index a6b886b05..9dd68df28 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandablePreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -4,9 +4,16 @@ import { XMarkIcon, } from "@heroicons/react/24/outline"; import { EyeIcon } from "@heroicons/react/24/solid"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscEditorBackground } from "../../.."; +import { + defaultBorderRadius, + lightGray, + vscBadgeBackground, + vscCommandCenterInactiveBorder, + vscEditorBackground, +} from "../../.."; +import { useAppSelector } from "../../../../redux/hooks"; import { getFontSize } from "../../../../util"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; @@ -58,14 +65,18 @@ const ChevronContainer = styled.div` `; /** - * Props for the ExpandablePreview component + * Props for the ExpandableToolbarPreview component */ -interface ExpandablePreviewProps { +interface ExpandableToolbarPreviewProps { /** Title to display in the header */ title: string; /** Optional icon to display next to the title */ icon?: React.ReactNode; - /** Whether the preview is initially hidden */ + /** 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; @@ -73,6 +84,8 @@ interface ExpandablePreviewProps { 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; } @@ -80,16 +93,35 @@ interface ExpandablePreviewProps { /** * A generalized expandable preview component for displaying content with a header and expandable body */ -export function ExpandablePreview(props: ExpandablePreviewProps) { - const [hidden, setHidden] = useState(props.initiallyHidden ?? false); +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 (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); const contentRef = useRef(null); const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); useEffect(() => { - setHidden(props.initiallyHidden ?? false); - }, [props.initiallyHidden]); + setHidden(calculatedInitiallyHidden); + }, [calculatedInitiallyHidden]); useEffect(() => { const resizeObserver = new ResizeObserver(() => { @@ -111,10 +143,11 @@ export function ExpandablePreview(props: ExpandablePreviewProps) { return ( - {/* Keep existing header code */}
{ const item: ContextItemWithId = node.attrs.item; const inputId = node.attrs.inputId; - const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now const ideMessenger = useContext(IdeMessengerContext); - const newestCodeblockForInputId = useAppSelector( - (store) => store.session.newestCodeblockForInput[inputId], - ); - - const initiallyHidden = useMemo(() => { - return newestCodeblockForInputId !== item.id.itemId; - }, [newestCodeblockForInputId, item.id.itemId]); - - console.log({ - newestCodeblockForInputId, - id: item.id.itemId, - initiallyHidden, - }); - const content = useMemo(() => { return dedent`${item.content}`; }, [item.content]); @@ -71,26 +55,22 @@ export const CodeBlockPreview = ({ } }; - const borderColor = isFirstContextItem - ? "#d0d" - : selected - ? vscBadgeBackground - : undefined; - return ( - } - initiallyHidden={initiallyHidden} + inputId={inputId} + itemId={item.id.itemId} onDelete={() => deleteNode()} - borderColor={borderColor} + borderColor={selected ? vscBadgeBackground : undefined} onTitleClick={handleTitleClick} > - + ); }; diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts index 287a79e4a..5cbe10767 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts @@ -30,7 +30,7 @@ declare module "@tiptap/core" { } /** - * Extension for adding prompt blocks to the Tiptap editor + * Extension for adding prompt blocks to the TipTap editor */ export const PromptBlock = Node.create({ name: "prompt-block", @@ -85,6 +85,8 @@ export const PromptBlock = Node.create({ }); }, + // 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 }) => { diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx index 002740692..899cbdd37 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx @@ -1,10 +1,8 @@ import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline"; import { NodeViewProps } from "@tiptap/react"; -import { useContext, useMemo } from "react"; -import { vscBadgeBackground } from "../../../.."; +import { useContext } from "react"; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; -import { useAppSelector } from "../../../../../redux/hooks"; -import { ExpandablePreview } from "../../components/ExpandablePreview"; +import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; import { NodeViewWrapper } from "../../components/NodeViewWrapper"; import { PromptBlockAttributes } from "./PromptBlock"; @@ -20,14 +18,6 @@ export const PromptBlockPreview = ({ const ideMessenger = useContext(IdeMessengerContext); - const newestCodeblockForInputId = useAppSelector( - (store) => store.session.newestCodeblockForInput[inputId], - ); - - const initiallyHidden = useMemo(() => { - return newestCodeblockForInputId !== item.id.itemId; - }, [newestCodeblockForInputId, item.id.itemId]); - const handleTitleClick = (e: React.MouseEvent) => { e.stopPropagation(); ideMessenger.post("showVirtualFile", { @@ -40,22 +30,21 @@ export const PromptBlockPreview = ({ editor.commands.clearSlashCommand(); }; - const borderColor = selected ? vscBadgeBackground : undefined; - return ( - } - initiallyHidden={initiallyHidden} + inputId={inputId} + itemId={item.id.itemId} onDelete={handleDelete} - borderColor={borderColor} onTitleClick={handleTitleClick} >
{item.content}
-
+
); }; diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index bedb3df50..69feed370 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -5,7 +5,7 @@ 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"; @@ -132,10 +132,8 @@ export function useMainEditorWebviewListeners({ }) .run(); - console.log("id: ", contextItem.id.itemId); - dispatch( - setNewestCodeblocksForInput({ + setNewestToolbarPreviewForInput({ inputId, contextItemId: contextItem.id.itemId, }), diff --git a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index b553b6d9a..399701e9d 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -7,7 +7,7 @@ import { import { MutableRefObject } from "react"; import tippy from "tippy.js"; import { IIdeMessenger } from "../../../../context/IdeMessenger"; -import { setNewestCodeblocksForInput } from "../../../../redux/slices/sessionSlice"; +import { setNewestToolbarPreviewForInput } from "../../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../../redux/store"; import AtMentionDropdown from "../../AtMentionDropdown"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; @@ -224,7 +224,7 @@ export function getSlashCommandDropdownOptions( content: provider.content, action: () => { dispatch( - setNewestCodeblocksForInput({ + setNewestToolbarPreviewForInput({ inputId, contextItemId: provider.title, }), diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index 34962eed4..63ebad23c 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -50,6 +50,50 @@ type ResolveEditorContentOutput = [ ), ]; +/** + * 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 { + 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 */ @@ -295,47 +339,3 @@ function resolveParagraph( return [text, contextItems, slashCommand]; } - -/** - * 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 { - 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]; -} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 5aa714acc..f7c9756d2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -53,7 +53,7 @@ type SessionState = { states: ApplyState[]; curIndex: number; }; - newestCodeblockForInput: Record; + newestToolbarPreviewForInput: Record; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -91,7 +91,7 @@ const initialState: SessionState = { curIndex: 0, }, lastSessionId: undefined, - newestCodeblockForInput: {}, + newestToolbarPreviewForInput: {}, }; export const sessionSlice = createSlice({ @@ -648,7 +648,7 @@ export const sessionSlice = createSlice({ const nextIndex = (currentIndex + 1) % modes.length; state.mode = modes[nextIndex] as MessageModes; }, - setNewestCodeblocksForInput: ( + setNewestToolbarPreviewForInput: ( state, { payload, @@ -657,7 +657,8 @@ export const sessionSlice = createSlice({ contextItemId: string; }>, ) => { - state.newestCodeblockForInput[payload.inputId] = payload.contextItemId; + state.newestToolbarPreviewForInput[payload.inputId] = + payload.contextItemId; }, }, selectors: { @@ -758,7 +759,7 @@ export const { addSessionMetadata, updateSessionMetadata, deleteSessionMetadata, - setNewestCodeblocksForInput, + setNewestToolbarPreviewForInput, cycleMode, } = sessionSlice.actions; From 709eb6361f93e9f9257e9b165b377e72f2ed0edd Mon Sep 17 00:00:00 2001 From: Ty Dunn Date: Fri, 4 Apr 2025 12:23:43 -0700 Subject: [PATCH 77/93] replace actions with agent in root README --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index fc07289d7..dffa26b4f 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## 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 -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif)
From 6e11b246bc0d9f1b8f36c68fa60e635cf8c7b964 Mon Sep 17 00:00:00 2001 From: Ty Dunn Date: Fri, 4 Apr 2025 12:26:10 -0700 Subject: [PATCH 78/93] actions --> agent in vs code readme --- extensions/vscode/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/README.md b/extensions/vscode/README.md index 9470b2d5e..1bc087276 100644 --- a/extensions/vscode/README.md +++ b/extensions/vscode/README.md @@ -44,11 +44,11 @@ ![edit](docs/static/img/edit.gif) -## 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 -![actions](docs/static/img/actions.gif) +![agent](docs/static/img/agent.gif)
From a835cfa40c726042c550c7f133ada60881e3f798 Mon Sep 17 00:00:00 2001 From: Ty Dunn Date: Fri, 4 Apr 2025 12:27:12 -0700 Subject: [PATCH 79/93] actions --> agent in JetBrains readme --- extensions/intellij/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/intellij/README.md b/extensions/intellij/README.md index dccf4a7f1..45a1f05f0 100644 --- a/extensions/intellij/README.md +++ b/extensions/intellij/README.md @@ -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.
From 36289b25802816d6b37ba930ecc083ca4f3e4c66 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Apr 2025 19:54:10 +0000 Subject: [PATCH 80/93] build(deps-dev): bump vite from 4.5.9 to 4.5.12 in /extensions/vscode Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.5.9 to 4.5.12. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/v4.5.12/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v4.5.12/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 4.5.12 dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- extensions/vscode/package-lock.json | 12 ++++++------ extensions/vscode/package.json | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index bef92c30c..c03168bf9 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.18", + "version": "1.1.20", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.18", + "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" }, @@ -13322,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": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 15599a1c0..4167b8dcc 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -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" }, From e88485348c8b53e9f19d1f9fc0c8b33dd5266df7 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 12:57:03 -0700 Subject: [PATCH 81/93] feat: dallin's feedback --- .continue/rules/use-tailwind-not-styled.md | 3 - .../ConversationStarterCards.tsx | 11 +- .../components/mainInput/Lump/LumpContext.tsx | 51 ++++ gui/src/components/mainInput/Lump/index.tsx | 103 ++++---- .../Lump/sections/ExploreBlocksButton.tsx | 5 +- .../Lump/sections/PromptsSection.tsx | 51 +++- .../mainInput/Lump/sections/RulesSection.tsx | 16 +- .../Lump/sections/docs/DocsIndexingStatus.tsx | 3 + .../Lump/sections/docs/DocsSection.tsx | 1 - .../components/ExpandableToolbarPreview.tsx | 21 +- .../components/NodeViewWrapper.tsx | 2 +- .../extensions/Prompt/PromptBlock.ts | 35 ++- .../extensions/Prompt/PromptBlockPreview.tsx | 3 +- .../TipTapEditor/extensions/SlashCommand.ts | 243 +----------------- .../useMainEditorWebviewListeners.ts | 10 +- .../TipTapEditor/utils/getSuggestion.ts | 12 +- 16 files changed, 227 insertions(+), 343 deletions(-) delete mode 100644 .continue/rules/use-tailwind-not-styled.md create mode 100644 gui/src/components/mainInput/Lump/LumpContext.tsx diff --git a/.continue/rules/use-tailwind-not-styled.md b/.continue/rules/use-tailwind-not-styled.md deleted file mode 100644 index 8a3ec0b3d..000000000 --- a/.continue/rules/use-tailwind-not-styled.md +++ /dev/null @@ -1,3 +0,0 @@ -Always use Tailwind classes, not styled components. - -If a component is using styled components, it should be converted to use Tailwind classes. diff --git a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx index a680fa201..776c0721b 100644 --- a/gui/src/components/ConversationStarters/ConversationStarterCards.tsx +++ b/gui/src/components/ConversationStarters/ConversationStarterCards.tsx @@ -1,9 +1,7 @@ import { SlashCommandDescription } from "core"; import { useState } from "react"; import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands"; -import { MAIN_EDITOR_INPUT_ID } from "../../pages/gui/Chat"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setNewestToolbarPreviewForInput } from "../../redux/slices/sessionSlice"; import { useMainEditor } from "../mainInput/TipTapEditor"; import { ConversationStarterCard } from "./ConversationStarterCard"; @@ -26,14 +24,7 @@ export function ConversationStarterCards() { ); function onClick(command: SlashCommandDescription) { - dispatch( - setNewestToolbarPreviewForInput({ - inputId: MAIN_EDITOR_INPUT_ID, - contextItemId: command.name, - }), - ); - - mainEditor?.commands.insertSlashCommand(command); + mainEditor?.commands.insertPrompt(command); } if (bookmarkedSlashCommands.length === 0) { diff --git a/gui/src/components/mainInput/Lump/LumpContext.tsx b/gui/src/components/mainInput/Lump/LumpContext.tsx new file mode 100644 index 000000000..4e93777ea --- /dev/null +++ b/gui/src/components/mainInput/Lump/LumpContext.tsx @@ -0,0 +1,51 @@ +/** + * Provides context for controlling the Lump component's visibility state + */ +import { createContext, ReactNode, useContext } from "react"; + +interface LumpContextType { + isLumpVisible: boolean; + selectedSection: string | null; + hideLump: () => void; + setSelectedSection: (section: string | null) => void; +} + +const LumpContext = createContext(undefined); + +interface LumpProviderProps { + children: ReactNode; + isLumpVisible: boolean; + selectedSection: string | null; + hideLump: () => void; + setSelectedSection: (section: string | null) => void; +} + +/** + * Provider component that makes Lump state available to any child component + */ +export function LumpProvider({ + children, + isLumpVisible, + selectedSection, + hideLump, + setSelectedSection, +}: LumpProviderProps) { + return ( + + {children} + + ); +} + +/** + * 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; +} diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index 57276ad56..df1875c86 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useCallback, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, @@ -6,6 +6,7 @@ import { vscInputBackground, } from "../.."; import { useAppSelector } from "../../../redux/hooks"; +import { LumpProvider } from "./LumpContext"; import { LumpToolbar } from "./LumpToolbar"; import { SelectedSection } from "./sections/SelectedSection"; @@ -30,64 +31,78 @@ 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(null); const [displayedSection, setDisplayedSection] = useState(null); const [isVisible, setIsVisible] = useState(false); const isStreaming = useAppSelector((state) => state.session.isStreaming); - useEffect(() => { - if (!selectedSection) { - return; - } - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Escape") { + // Handle keyboard escape + const handleKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === "Escape" && selectedSection) { setSelectedSection(null); } - }; - document.addEventListener("keydown", handleKeyDown); - return () => { - document.removeEventListener("keydown", handleKeyDown); - }; - }, [selectedSection]); + }, + [selectedSection], + ); - useEffect(() => { - if (isStreaming) { - setSelectedSection(null); - } - }, [isStreaming]); + // Function to hide the lump + const hideLump = useCallback(() => { + setSelectedSection(null); + }, []); - useEffect(() => { - if (selectedSection) { + // Reset when streaming starts + if (isStreaming && selectedSection) { + setSelectedSection(null); + } + + // Update displayedSection and visibility when selectedSection changes + if (selectedSection) { + if (displayedSection !== selectedSection || !isVisible) { setDisplayedSection(selectedSection); setIsVisible(true); - } else { - setIsVisible(false); - const timeout = setTimeout(() => { - setDisplayedSection(null); - }, 300); - return () => { - clearTimeout(timeout); - }; } - }, [selectedSection]); + } else if (isVisible) { + setIsVisible(false); + setTimeout(() => { + setDisplayedSection(null); + }, 300); + } + + // Set up keyboard listener + if (selectedSection) { + document.addEventListener("keydown", handleKeyDown); + } else { + document.removeEventListener("keydown", handleKeyDown); + } return ( - -
- + + +
+ - - - -
-
+ + + +
+
+ ); } diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx index ad2212ac7..6885870df 100644 --- a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -50,7 +50,7 @@ export function ExploreBlocksButton(props: { blockType: string }) { return (
- {text} + + {text}
); diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index 6ad536809..1ff27c16c 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -3,44 +3,70 @@ 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 (
- {command} - {description} + {prompt.name} + {prompt.description}
setIsBookmarked(!isBookmarked)} + onClick={handleBookmarkClick} className="cursor-pointer pt-0.5 text-gray-400 hover:brightness-125" > {isBookmarked ? ( @@ -54,8 +80,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 +108,7 @@ export function PromptsSection() { {sortedCommands.map((prompt) => ( toggleBookmark(prompt)} onEdit={() => handleEdit(prompt)} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 4cb7b0051..43c338b49 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -13,6 +13,7 @@ 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 { @@ -82,6 +83,7 @@ const RuleCard: React.FC = ({ 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 +99,13 @@ export function RulesSection() { })); }, [rules]); - const openUrl = (path: string) => + const openUrl = (path: string) => { ideMessenger.request("controlPlane/openUrl", { path, orgSlug: undefined, }); + hideLump(); + }; return (
@@ -113,11 +117,12 @@ export function RulesSection() { key={index} index={index} rule={rule.unrolledRule} - onClick={() => + onClick={() => { ideMessenger.post("config/openProfile", { profileId: undefined, - }) - } + }); + hideLump(); + }} title="Locally Defined Rule" /> ); @@ -158,6 +163,3 @@ export function RulesSection() {
); } -function useTypedDispatch() { - throw new Error("Function not implemented."); -} diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx index 777d30e4e..9189a794c 100644 --- a/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsIndexingStatus.tsx @@ -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], @@ -87,6 +89,7 @@ function DocsIndexingStatus({ onClick={() => { if (status?.url) { ideMessenger.post("openUrl", status.url); + hideLump(); } }} > diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx index 27796aecb..cbe7e6e72 100644 --- a/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx @@ -14,7 +14,6 @@ function DocsIndexingStatuses() { (store) => store.indexing.indexing.statuses, ); const { selectedProfile } = useAuth(); - const mergedDocs = useMemo(() => { const parsed = selectedProfile?.rawYaml ? parseConfigYaml(selectedProfile?.rawYaml ?? "") diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index 9dd68df28..16e959ebb 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -102,6 +102,12 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { ); 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; } @@ -116,13 +122,19 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { 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(null); const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); useEffect(() => { - setHidden(calculatedInitiallyHidden); - }, [calculatedInitiallyHidden]); - + // 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({ @@ -146,7 +158,7 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { borderColor={ props.isSelected ? vscBadgeBackground : vscCommandCenterInactiveBorder } - className="find-widget-skip" + className="find-widget-skip !my-0" >
{ + setUserToggled(true); setHidden(!hidden); }} > diff --git a/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx b/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx index 1dc7ccd51..ac1a67836 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/NodeViewWrapper.tsx @@ -16,7 +16,7 @@ export const NodeViewWrapper: React.FC = ({ const nodeViewWrapperTag: TiptapNodeViewWrapperProps["as"] = "p"; return ( - + {children} ); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts index 5cbe10767..b35a637ea 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts @@ -1,7 +1,8 @@ import { mergeAttributes, Node } from "@tiptap/core"; import { Node as ProseMirrorNode } from "@tiptap/pm/model"; import { ReactNodeViewRenderer } from "@tiptap/react"; -import { ContextItemWithId } from "core"; +import { ContextItemWithId, SlashCommandDescription } from "core"; +import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat"; import { PromptBlockPreview } from "./PromptBlockPreview"; export interface PromptBlockOptions { @@ -19,7 +20,7 @@ declare module "@tiptap/core" { /** * Insert a prompt block into the editor */ - insertPrompt: (item: ContextItemWithId, inputId: string) => ReturnType; + insertPrompt: (item: SlashCommandDescription) => ReturnType; /** * Clear all prompt blocks from the editor @@ -35,6 +36,7 @@ declare module "@tiptap/core" { export const PromptBlock = Node.create({ name: "prompt-block", group: "block", + content: "inline*", addOptions() { return { @@ -74,15 +76,28 @@ export const PromptBlock = Node.create({ addCommands() { return { insertPrompt: - (item: ContextItemWithId, inputId: string) => - ({ commands }) => { - return commands.insertContent({ - type: this.name, - attrs: { - item, - inputId, + (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 diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx index 899cbdd37..8a1095d80 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx @@ -27,12 +27,13 @@ export const PromptBlockPreview = ({ }; const handleDelete = () => { - editor.commands.clearSlashCommand(); + editor.commands.clearPrompt(); }; return ( } diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts index 4b5517c87..892d80355 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts @@ -1,191 +1,50 @@ // Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts) -import { mergeAttributes, Node } from "@tiptap/core"; -import Document from "@tiptap/extension-document"; -import Paragraph from "@tiptap/extension-paragraph"; -import { Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { Node } from "@tiptap/core"; import { PluginKey } from "@tiptap/pm/state"; import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; -import { ContextItemWithId, SlashCommandDescription } from "core"; -import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat"; import { ComboBoxItem } from "../../types"; -import { PromptBlock } from "./Prompt/PromptBlock"; export type SlashCommandOptions = { - HTMLAttributes: Record; - renderText: (props: { node: ProseMirrorNode }) => string; suggestion: Omit, "editor">; }; -declare module "@tiptap/core" { - interface Commands { - slashCommand: { - /** - * Insert a slash command and its associated prompt block - * @param command The slash command description - */ - insertSlashCommand: (command: SlashCommandDescription) => ReturnType; - - /** - * Clear the slash command content from the editor - */ - clearSlashCommand: () => ReturnType; - }; - } -} - export const SlashCommand = Node.create({ name: "slash-command", addOptions() { return { - HTMLAttributes: { - class: "mention", - }, - renderText({ node }) { - return node.attrs.label ?? node.attrs.id; - }, suggestion: { char: "/", pluginKey: new PluginKey(this.name), 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(" "); + // First delete the slash character and any text after it + editor.chain().focus().deleteRange(range).run(); - if (overrideSpace) { - range.to += 1; - } - - editor.commands.insertSlashCommand({ + editor.commands.insertPrompt({ name: props.title, description: props.description, prompt: props.content, }); - - 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, + // We don't need attributes since we won't be rendering any node 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, - }; - }, - }, - }; + return {}; }, + // No need to parse HTML since we're not rendering anything 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({ - node, - }), - ]; - }, - - addKeyboardShortcuts() { - return { - Backspace: () => { - // Get a reference to the editor - const editor = this.editor; - - // First try to find if we're at a slash command - const result = 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; - }); - - // If we found and processed a slash command, also call clearSlashCommand - // to remove the prompt block - if (result) { - // We need to do this with a small delay to ensure the transaction - // above completes first - setTimeout(() => { - editor.commands.clearSlashCommand(); - }, 0); - return true; - } - - return false; - }, - }; + return []; }, addProseMirrorPlugins() { @@ -196,90 +55,4 @@ export const SlashCommand = Node.create({ }), ]; }, - - addCommands() { - return { - insertSlashCommand: - ( - command: SlashCommandDescription, - inputId: string = MAIN_EDITOR_INPUT_ID, - ) => - ({ chain }) => { - if (!command.prompt) { - return false; - } - - const contextItem: ContextItemWithId = { - content: command.prompt, - name: command.name, - description: command.description || "", - id: { - providerTitle: "prompt", - itemId: command.name, - }, - }; - - // Right now this inserts at the beginning of the document, which removes codeblocks. - // This is the current behavior of slash commands, eg codeblocks aren't sent. - // Once this bug if fixed, we should instead insert prompt block at the beginning of the document - // without clearing the codeblocks. - return chain() - .setContent({ - type: Document.name, - content: [ - // First insert the prompt using the PromptExtension command - { - type: PromptBlock.name, - attrs: { - item: contextItem, - inputId, - }, - }, - // Add the paragraph with the slash command - { - type: Paragraph.name, - content: [ - { - type: this.name, - attrs: { - id: command.name, - label: command.name, - }, - }, - { - type: "text", - text: " ", - }, - ], - }, - ], - }) - .focus() - .run(); - }, - - clearSlashCommand: - () => - ({ editor }) => { - editor.commands.clearPrompt(); - - editor.commands.command(({ tr, state }) => { - let hasDeleted = false; - - // Find all slash command nodes in the document - state.doc.descendants((node, pos) => { - if (node.type.name === this.name) { - // Delete the node at the found position - tr.delete(pos, pos + node.nodeSize); - hasDeleted = true; - } - }); - - return hasDeleted; - }); - - return true; - }, - }; - }, }); diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 69feed370..6e7808ba7 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -9,7 +9,7 @@ import { } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; -import { CodeBlock } from "./extensions"; +import { CodeBlock, PromptBlock } from "./extensions"; /** * Hook for setting up main editor specific webview listeners @@ -111,16 +111,20 @@ export function useMainEditorWebviewListeners({ 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.name) { + + if (el.type === CodeBlock.name || el.type === PromptBlock.name) { index += 2; } else { break; } } + debugger; + editor .chain() .insertContentAt(index, { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts index 399701e9d..8c0613a4a 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/getSuggestion.ts @@ -7,7 +7,6 @@ import { import { MutableRefObject } from "react"; import tippy from "tippy.js"; import { IIdeMessenger } from "../../../../context/IdeMessenger"; -import { setNewestToolbarPreviewForInput } from "../../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../../redux/store"; import AtMentionDropdown from "../../AtMentionDropdown"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types"; @@ -222,16 +221,7 @@ export function getSlashCommandDropdownOptions( label: provider.title, type: (provider.type ?? SlashCommand.name) as ComboBoxItemType, content: provider.content, - action: () => { - dispatch( - setNewestToolbarPreviewForInput({ - inputId, - contextItemId: provider.title, - }), - ); - - provider.action?.(); - }, + action: provider.action, })); if (query.length === 0 && commandItems.length === 0) { From 1710c2032f35219a65a6ce1ee15d50dfbef009e9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 13:14:44 -0700 Subject: [PATCH 82/93] fix apply for jetgrains --- .../continue/IdeProtocolClient.kt | 45 ++++++++++++++++++- .../editor/DiffStreamHandler.kt | 33 ++++++++++++-- .../editor/InlineEditAction.kt | 5 ++- .../markdown/StyledMarkdownPreview.tsx | 8 +--- gui/src/redux/thunks/callTool.ts | 6 ++- 5 files changed, 84 insertions(+), 13 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 95270f26b..75f393172 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -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 @@ -423,11 +424,45 @@ 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 +//// } +// } +// } else { +// } + editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + closeStream() respond(null) return@launch } @@ -436,6 +471,7 @@ class IdeProtocolClient( WriteCommandAction.runWriteCommandAction(project) { editor.document.insertString(0, params.text) } + closeStream() respond(null) return@launch } @@ -481,6 +517,7 @@ class IdeProtocolClient( ToastType.ERROR, "Failed to fetch model configuration" ) } + closeStream() respond(null) return@launch } @@ -519,7 +556,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) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 55df303a8..f6cf5972f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -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") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index faaf7d058..fd910308d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -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.register(diffStreamHandler, editor) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 52ede7cbd..d10a3dab7 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -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"; @@ -305,11 +305,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 ( Date: Fri, 4 Apr 2025 13:52:41 -0700 Subject: [PATCH 83/93] move toolbar to lumpprovider --- .../Lump/BlockSettingsTopToolbar.tsx | 19 ++++++++----------- .../components/mainInput/Lump/LumpContext.tsx | 15 ++++++++++++++- gui/src/components/mainInput/Lump/index.tsx | 8 ++++++++ .../platform/AssistantSelect.tsx | 11 +++++------ gui/src/redux/slices/uiSlice.ts | 7 ------- 5 files changed, 35 insertions(+), 25 deletions(-) diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index ebef0251b..9d8c79ccc 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -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; @@ -87,15 +86,13 @@ interface BlockSettingsTopToolbarProps { } export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) { - const isExpanded = useAppSelector( - (state) => state.ui.isBlockSettingsToolbarExpanded, - ); - const dispatch = useAppDispatch(); + const { isToolbarExpanded, toggleToolbar } = useLump(); + const handleEllipsisClick = () => { - if (isExpanded) { + if (isToolbarExpanded) { props.setSelectedSection(null); } - dispatch(toggleBlockSettingsToolbar()); + toggleToolbar(); }; return ( @@ -103,14 +100,14 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
{sections.map((section) => ( diff --git a/gui/src/components/mainInput/Lump/LumpContext.tsx b/gui/src/components/mainInput/Lump/LumpContext.tsx index 4e93777ea..8b6417f6f 100644 --- a/gui/src/components/mainInput/Lump/LumpContext.tsx +++ b/gui/src/components/mainInput/Lump/LumpContext.tsx @@ -6,8 +6,10 @@ import { createContext, ReactNode, useContext } from "react"; interface LumpContextType { isLumpVisible: boolean; selectedSection: string | null; + isToolbarExpanded: boolean; hideLump: () => void; setSelectedSection: (section: string | null) => void; + toggleToolbar: () => void; } const LumpContext = createContext(undefined); @@ -16,8 +18,10 @@ interface LumpProviderProps { children: ReactNode; isLumpVisible: boolean; selectedSection: string | null; + isToolbarExpanded: boolean; hideLump: () => void; setSelectedSection: (section: string | null) => void; + toggleToolbar: () => void; } /** @@ -27,12 +31,21 @@ export function LumpProvider({ children, isLumpVisible, selectedSection, + isToolbarExpanded, hideLump, setSelectedSection, + toggleToolbar, }: LumpProviderProps) { return ( {children} diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index df1875c86..b9df37108 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -38,6 +38,7 @@ export function Lump() { const [selectedSection, setSelectedSection] = useState(null); const [displayedSection, setDisplayedSection] = useState(null); const [isVisible, setIsVisible] = useState(false); + const [isToolbarExpanded, setIsToolbarExpanded] = useState(true); const isStreaming = useAppSelector((state) => state.session.isStreaming); // Handle keyboard escape @@ -55,6 +56,11 @@ export function Lump() { setSelectedSection(null); }, []); + // Function to toggle toolbar expanded state + const toggleToolbar = useCallback(() => { + setIsToolbarExpanded((prev) => !prev); + }, []); + // Reset when streaming starts if (isStreaming && selectedSection) { setSelectedSection(null); @@ -84,8 +90,10 @@ export function Lump() {
diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 36495145d..2c8fc2d68 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -11,7 +11,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 +31,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"; @@ -143,9 +144,7 @@ export default function AssistantSelect() { const buttonRef = useRef(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 +204,7 @@ export default function AssistantSelect() { > Create your first assistant @@ -227,7 +226,7 @@ export default function AssistantSelect() {
{selectedProfile.title} diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 7bb7fb3fd..13efdfa1a 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -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"; @@ -56,7 +55,6 @@ export const uiSlice = createSlice({ toolGroupSettings: { BUILT_IN_GROUP_NAME: "include", }, - isBlockSettingsToolbarExpanded: true, } as UIState, reducers: { setOnboardingCard: ( @@ -124,10 +122,6 @@ export const uiSlice = createSlice({ setTTSActive: (state, { payload }: PayloadAction) => { state.ttsActive = payload; }, - toggleBlockSettingsToolbar: (state) => { - state.isBlockSettingsToolbarExpanded = - !state.isBlockSettingsToolbarExpanded; - }, }, }); @@ -142,7 +136,6 @@ export const { toggleToolGroupSetting, addTool, setTTSActive, - toggleBlockSettingsToolbar, } = uiSlice.actions; export default uiSlice.reducer; From 34ae653841b3933872248cf34100d25b068ef229 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 14:04:31 -0700 Subject: [PATCH 84/93] open new editor with file --- .../continue/IdeProtocolClient.kt | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 75f393172..d8905445e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -448,17 +448,15 @@ class IdeProtocolClient( 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 -//// } -// } -// } else { -// } - editor = FileEditorManager.getInstance(project).selectedTextEditor + 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") From 8a7d7acb0304b255541ccbd59aa83f5c2fd4e74b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 14:07:03 -0700 Subject: [PATCH 85/93] more lump provider centralization --- .../Lump/BlockSettingsTopToolbar.tsx | 22 ++-- .../components/mainInput/Lump/LumpContext.tsx | 85 +++++++++++--- .../components/mainInput/Lump/LumpToolbar.tsx | 14 +-- gui/src/components/mainInput/Lump/index.tsx | 104 +++++------------- .../Lump/sections/SelectedSection.tsx | 12 +- 5 files changed, 114 insertions(+), 123 deletions(-) diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 9d8c79ccc..64a477cbb 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -80,17 +80,17 @@ function BlockSettingsToolbarIcon(props: BlockSettingsToolbarIcon) { ); } -interface BlockSettingsTopToolbarProps { - selectedSection: string | null; - setSelectedSection: (value: string | null) => void; -} - -export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) { - const { isToolbarExpanded, toggleToolbar } = useLump(); +export function BlockSettingsTopToolbar() { + const { + isToolbarExpanded, + toggleToolbar, + selectedSection, + setSelectedSection, + } = useLump(); const handleEllipsisClick = () => { if (isToolbarExpanded) { - props.setSelectedSection(null); + setSelectedSection(null); } toggleToolbar(); }; @@ -115,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, ) } /> diff --git a/gui/src/components/mainInput/Lump/LumpContext.tsx b/gui/src/components/mainInput/Lump/LumpContext.tsx index 8b6417f6f..92c5dbd6c 100644 --- a/gui/src/components/mainInput/Lump/LumpContext.tsx +++ b/gui/src/components/mainInput/Lump/LumpContext.tsx @@ -1,11 +1,20 @@ /** * Provides context for controlling the Lump component's visibility state */ -import { createContext, ReactNode, useContext } from "react"; +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; @@ -16,31 +25,73 @@ const LumpContext = createContext(undefined); interface LumpProviderProps { children: ReactNode; - isLumpVisible: boolean; - selectedSection: string | null; - isToolbarExpanded: boolean; - hideLump: () => void; - setSelectedSection: (section: string | null) => void; - toggleToolbar: () => void; } /** * Provider component that makes Lump state available to any child component */ -export function LumpProvider({ - children, - isLumpVisible, - selectedSection, - isToolbarExpanded, - hideLump, - setSelectedSection, - toggleToolbar, -}: LumpProviderProps) { +export function LumpProvider({ children }: LumpProviderProps) { + const [selectedSection, setSelectedSection] = useState(null); + const [displayedSection, setDisplayedSection] = useState(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 ( void; -} - -export function LumpToolbar(props: TopToolbarProps) { +export function LumpToolbar() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const ttsActive = useAppSelector((state) => state.ui.ttsActive); @@ -60,10 +55,5 @@ export function LumpToolbar(props: TopToolbarProps) { ); } - return ( - - ); + return ; } diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index b9df37108..de432f1d1 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -1,12 +1,10 @@ -import { useCallback, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, vscCommandCenterInactiveBorder, vscInputBackground, } from "../.."; -import { useAppSelector } from "../../../redux/hooks"; -import { LumpProvider } from "./LumpContext"; +import { LumpProvider, useLump } from "./LumpContext"; import { LumpToolbar } from "./LumpToolbar"; import { SelectedSection } from "./sections/SelectedSection"; @@ -35,82 +33,32 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>` * Main component that displays the toolbar and selected content section */ export function Lump() { - const [selectedSection, setSelectedSection] = useState(null); - const [displayedSection, setDisplayedSection] = useState(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); - }, []); - - // Reset when streaming starts - if (isStreaming && selectedSection) { - setSelectedSection(null); - } - - // Update displayedSection and visibility when selectedSection changes - if (selectedSection) { - if (displayedSection !== selectedSection || !isVisible) { - setDisplayedSection(selectedSection); - setIsVisible(true); - } - } else if (isVisible) { - setIsVisible(false); - setTimeout(() => { - setDisplayedSection(null); - }, 300); - } - - // Set up keyboard listener - if (selectedSection) { - document.addEventListener("keydown", handleKeyDown); - } else { - document.removeEventListener("keydown", handleKeyDown); - } - return ( - - -
- - - - - -
-
+ + ); } + +/** + * Internal component that consumes the LumpContext + */ +function LumpContent() { + const { isLumpVisible, selectedSection } = useLump(); + + return ( + +
+ + + + + +
+
+ ); +} diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 28dc37c28..e592d13ff 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -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 { ToolsSection } from "./ToolsSection"; -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 ; case "rules": From fee9b5f51695d8f6aedaa0e59be988635dbaae7d Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 14:21:30 -0700 Subject: [PATCH 86/93] Update PromptsSection.tsx --- .../mainInput/Lump/sections/PromptsSection.tsx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index 1ff27c16c..8ea7a37d3 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -50,15 +50,19 @@ function PromptRow({ return (
-
- {prompt.name} - {prompt.description} +
+ + {prompt.name} + + + {prompt.description} +
Date: Fri, 4 Apr 2025 14:35:43 -0700 Subject: [PATCH 87/93] isGenerating logic fix --- .../StepContainerPreToolbar.tsx | 12 +----------- .../markdown/StyledMarkdownPreview.tsx | 18 +++++++++++++++--- gui/src/hooks/useSetup.ts | 16 ++++++++-------- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 1 + gui/src/redux/thunks/callTool.ts | 14 +++++++++++++- 5 files changed, 38 insertions(+), 23 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 375fd7ab8..f09ed1a9f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -69,7 +69,6 @@ export default function StepContainerPreToolbar( props.expanded ?? (isInEditMode ? false : true), ); const [codeBlockContent, setCodeBlockContent] = useState(""); - const isStreaming = useAppSelector((state) => state.session.isStreaming); const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, @@ -79,15 +78,6 @@ export default function StepContainerPreToolbar( 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); @@ -196,7 +186,7 @@ export default function StepContainerPreToolbar(
- {isGeneratingCodeBlock ? ( + {props.isGeneratingCodeBlock ? ( { + 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 = [ @@ -235,8 +245,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) { @@ -318,7 +327,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } const isGeneratingCodeBlock = - preChildProps["data-isgeneratingcodeblock"]; + preChildProps["data-islastcodeblock"] && + isLastItemRef.current && + !isStreamingRef.current; if (codeblockState.current[codeBlockIndex] === undefined) { codeblockState.current[codeBlockIndex] = { @@ -342,6 +353,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( codeBlockStreamId={ codeblockState.current[codeBlockIndex].streamId } + expanded={props.expandCodeblocks} disableManualApply={props.disableManualApply} > diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 25b1a7fc0..ded57ee08 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -3,7 +3,7 @@ import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { ConfigResult } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig, ContextItem } from "core"; +import { BrowserSerializedContinueConfig } from "core"; import { initializeProfilePreferencesThunk, selectProfileThunk, @@ -268,17 +268,17 @@ function useSetup() { state.streamId === activeToolStreamId[0] && state.status === "closed" ) { - const output: ContextItem = { - name: "Edit tool output", - content: "Completed edit", - description: "", - }; + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; dispatch(acceptToolCall()); - dispatch(setToolCallOutput([output])); + dispatch(setToolCallOutput([])); dispatch( streamResponseAfterToolCall({ toolCallId: activeToolStreamId[1], - toolOutput: [output], + toolOutput: [], }), ); } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 2ff34d489..80927e6e7 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -33,6 +33,7 @@ export function EditFile(props: EditToolCallProps) { source={src} disableManualApply={true} singleCodeblockStreamId={applyState?.streamId} + expandCodeblocks={false} /> {/* TODO better indicator of generation at bottom */} {/* {isStreaming && applyState?.status === "streaming" && ( diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 41557cb40..bf15e7ae8 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -11,6 +11,7 @@ import { cancelToolCall, setCalling, setToolCallOutput, + updateApplyState, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -61,6 +62,17 @@ export const callTool = createAsyncThunk( if (e instanceof Error) { errorMessage = e.message; } + if (state.session.activeToolStreamId?.[0]) { + dispatch( + updateApplyState({ + streamId: state.session.activeToolStreamId[0], + status: "closed", + toolCallId: toolCallState.toolCallId, + numDiffs: 0, + filepath: args.filepath, + }), + ); + } } } else { const result = await extra.ideMessenger.request("tools/call", { @@ -128,7 +140,7 @@ async function customGuiEditImpl( text: args.new_contents, curSelectedModelTitle: modelTitle, toolCallId, - filepath: firstUriMatch + filepath: firstUriMatch, }); if (apply.status === "error") { throw new Error(apply.error); From d898d9fe305c7a38d4deb1ab1b9172bb05759fab Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 14:43:10 -0700 Subject: [PATCH 88/93] assistant select cleanup --- .../modelSelection/platform/AssistantSelect.tsx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 2c8fc2d68..5219af10f 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -82,13 +82,13 @@ const AssistantSelectOption = ({ fontSizeModifier={-2} >
-
+
-
+
{profile.title} @@ -238,7 +238,7 @@ export default function AssistantSelect() { - +
@@ -281,7 +281,7 @@ export default function AssistantSelect() { />
{getMetaKeyLabel()} ⇧ ' to toggle
navigate(ROUTES.CONFIG)} > {selectedOrganization?.iconUrl ? ( From bf7cf661cc4357029492f067ca57b1a43401aaaa Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 15:45:03 -0700 Subject: [PATCH 89/93] feat: more cleanup --- .../modelSelection/platform/AssistantIcon.tsx | 10 +++- .../platform/AssistantSelect.tsx | 52 ++++++++++++++----- 2 files changed, 48 insertions(+), 14 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantIcon.tsx b/gui/src/components/modelSelection/platform/AssistantIcon.tsx index 9f4bfcd0b..c901bfdf4 100644 --- a/gui/src/components/modelSelection/platform/AssistantIcon.tsx +++ b/gui/src/components/modelSelection/platform/AssistantIcon.tsx @@ -10,7 +10,15 @@ export interface AssistantIconProps { export default function AssistantIcon({ assistant, size }: AssistantIconProps) { const sizeTw = size ?? 4; if (isLocalProfile(assistant)) { - return ; + return ( +
+ +
+ ); } else if (assistant.iconUrl) { return ( { + const tinyFont = useFontSize(-4); + const navigate = useNavigate(); const hasFatalErrors = useMemo(() => { @@ -81,10 +83,20 @@ const AssistantSelectOption = ({ onClick={!hasFatalErrors ? handleOptionClick : undefined} fontSizeModifier={-2} > -
+
-
-
+
+
+ {selected ? ( + + ) : null} +
+
-
-
{selected ? : null}
+
{!profile.errors?.length ? ( isLocalProfile(profile) ? ( { e.stopPropagation(); e.preventDefault(); @@ -107,7 +118,7 @@ const AssistantSelectOption = ({ /> ) : ( { e.stopPropagation(); e.preventDefault(); @@ -240,7 +251,7 @@ export default function AssistantSelect() {
{profiles?.map((profile, idx) => { return ( @@ -267,8 +278,13 @@ export default function AssistantSelect() { fontSizeModifier={-2} onClick={session ? onNewAssistant : () => login(false)} > -
- +
+ New Assistant
@@ -281,12 +297,17 @@ export default function AssistantSelect() { />
- + {getMetaKeyLabel()} ⇧ ' to toggle
)} - + {selectedOrganization?.name || "Personal"}
From 4969539a89e6cb78d5ac9d6b2501570bbcade718 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 15:45:46 -0700 Subject: [PATCH 90/93] Update AssistantSelect.tsx --- gui/src/components/modelSelection/platform/AssistantSelect.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 967e7cc77..0d45dface 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -317,7 +317,7 @@ export default function AssistantSelect() { {selectedOrganization?.iconUrl ? ( ) : ( From 1f77f8a1d0d053e79b48eb03a41b986bca1384b6 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 15:57:46 -0700 Subject: [PATCH 91/93] Update AssistantSelect.tsx --- .../modelSelection/platform/AssistantSelect.tsx | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 0d45dface..919e269ee 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -1,7 +1,6 @@ import { ArrowTopRightOnSquareIcon, BuildingOfficeIcon, - CheckIcon, ChevronDownIcon, Cog6ToothIcon, ExclamationTriangleIcon, @@ -82,6 +81,7 @@ const AssistantSelectOption = ({ disabled={hasFatalErrors} onClick={!hasFatalErrors ? handleOptionClick : undefined} fontSizeModifier={-2} + className={selected ? "bg-list-active text-list-active-foreground" : ""} >
-
- {selected ? ( - - ) : null} -
@@ -284,7 +279,7 @@ export default function AssistantSelect() { fontSize: tinyFont, }} > - + New Assistant
From 2056ccd39d983d918d851b3cf4d748ae37ef505f Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 4 Apr 2025 15:58:31 -0700 Subject: [PATCH 92/93] Update AssistantSelect.tsx --- gui/src/components/modelSelection/platform/AssistantSelect.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 919e269ee..0b20e2beb 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -279,7 +279,7 @@ export default function AssistantSelect() { fontSize: tinyFont, }} > - + New Assistant
From f2237c03994948e8df430d696954a2bc62cba61b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 17:10:24 -0700 Subject: [PATCH 93/93] cleanup --- core/tools/callTool.ts | 4 +--- core/tools/implementations/createNewFile.ts | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 2a04cb828..c81a0a6e4 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -138,9 +138,7 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); - // Custom GUI handling for edit - // case BuiltInToolNames.EditExistingFile: - // return await editFileImpl(args, extras); + // Note: Custom GUI handling for edit case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index cf8746328..5a89141eb 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -12,7 +12,7 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { const exists = await extras.ide.fileExists(resolvedFileUri); if (exists) { throw new Error( - `File ${args.filepath} already exists. Use the edit too to edit this file`, + `File ${args.filepath} already exists. Use the edit tool to edit this file`, ); } await extras.ide.writeFile(resolvedFileUri, args.contents);