merge main

This commit is contained in:
Dallin Romney 2024-12-20 18:31:50 -08:00
commit 517a48689b
45 changed files with 478 additions and 285 deletions

View file

@ -1,11 +1,9 @@
import path from "node:path";
import ignore from "ignore";
import { IDE } from "../..";
import { getConfigJsonPath } from "../../util/paths";
import { HelperVars } from "../util/HelperVars";
import { findUriInDirs } from "../../util/uri";
import { HelperVars } from "../util/HelperVars";
async function isDisabledForFile(
currentFilepath: string,
@ -52,9 +50,8 @@ export async function shouldPrefilter(
}
// Check whether autocomplete is disabled for this file
if (
await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide)
) {
const disableInFiles = [...(helper.options.disableInFiles ?? []), "*.prompt"];
if (await isDisabledForFile(helper.filepath, disableInFiles, ide)) {
return true;
}

View file

@ -224,7 +224,9 @@ export class ConfigHandler {
return { config, errors };
}
getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
getSerializedConfig(): Promise<
ConfigResult<BrowserSerializedContinueConfig>
> {
return this.currentProfile.getSerializedConfig(
this.additionalContextProviders,
);
@ -235,7 +237,9 @@ export class ConfigHandler {
}
async loadConfig(): Promise<ContinueConfig> {
return this.currentProfile.loadConfig(this.additionalContextProviders);
return (
await this.currentProfile.loadConfig(this.additionalContextProviders)
).config!; // <-- TODO
}
async llmFromTitle(title?: string): Promise<ILLM> {

View file

@ -13,9 +13,9 @@ export interface ProfileDescription {
}
export class ProfileLifecycleManager {
private savedConfig: ContinueConfig | undefined;
private savedConfig: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfig?: BrowserSerializedContinueConfig;
private pendingConfigPromise?: Promise<ContinueConfig>;
private pendingConfigPromise?: Promise<ConfigResult<ContinueConfig>>;
constructor(private readonly profileLoader: IProfileLoader) {}
@ -46,35 +46,37 @@ export class ProfileLifecycleManager {
this.savedBrowserConfig = undefined;
this.pendingConfigPromise = undefined;
return this.profileLoader.doLoadConfig();
return this.loadConfig([], true);
}
async loadConfig(
additionalContextProviders: IContextProvider[],
): Promise<ContinueConfig> {
forceReload: boolean = false,
): Promise<ConfigResult<ContinueConfig>> {
// If we already have a config, return it
if (this.savedConfig) {
return this.savedConfig;
} else if (this.pendingConfigPromise) {
return this.pendingConfigPromise;
if (!forceReload) {
if (this.savedConfig) {
return this.savedConfig;
} else if (this.pendingConfigPromise) {
return this.pendingConfigPromise;
}
}
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
const { config: newConfig, errors } =
await this.profileLoader.doLoadConfig();
const result = await this.profileLoader.doLoadConfig();
if (newConfig) {
if (result.config) {
// Add registered context providers
newConfig.contextProviders = (newConfig.contextProviders ?? []).concat(
additionalContextProviders,
);
result.config.contextProviders = (
result.config.contextProviders ?? []
).concat(additionalContextProviders);
this.savedConfig = newConfig;
resolve(newConfig);
} else if (errors) {
this.savedConfig = result;
resolve(result);
} else if (result.errors) {
reject(
`Error in config.json: ${errors.map((item) => item.message).join(" | ")}`,
`Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`,
);
}
});
@ -87,11 +89,21 @@ export class ProfileLifecycleManager {
async getSerializedConfig(
additionalContextProviders: IContextProvider[],
): Promise<BrowserSerializedContinueConfig> {
): Promise<ConfigResult<BrowserSerializedContinueConfig>> {
if (!this.savedBrowserConfig) {
const continueConfig = await this.loadConfig(additionalContextProviders);
this.savedBrowserConfig = finalToBrowserConfig(continueConfig);
const result = await this.loadConfig(additionalContextProviders);
if (!result.config) {
return {
...result,
config: undefined,
};
}
this.savedBrowserConfig = finalToBrowserConfig(result.config);
}
return this.savedBrowserConfig;
return {
config: this.savedBrowserConfig,
errors: [],
configLoadInterrupted: false,
};
}
}

View file

@ -61,6 +61,8 @@ import {
getEsbuildBinaryPath,
} from "../util/paths";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -69,8 +71,6 @@ import {
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { ConfigValidationError, validateConfig } from "./validation.js";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
export interface ConfigResult<T> {
config: T | undefined;
@ -239,7 +239,9 @@ async function intermediateToFinalConfig(
workOsAccessToken: string | undefined,
loadPromptFiles: boolean = true,
allowFreeTrial: boolean = true,
): Promise<ContinueConfig> {
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
// Auto-detect models
let models: BaseLLM[] = [];
for (const desc of config.models) {
@ -490,37 +492,41 @@ async function intermediateToFinalConfig(
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
if (config.experimental?.modelContextProtocolServers) {
config.experimental.modelContextProtocolServers?.forEach(
async (server, index) => {
const mcpId = index.toString();
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
2000,
);
try {
await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
);
} catch (e: any) {
if (e.name !== "AbortError") {
throw e;
await Promise.all(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
const mcpId = index.toString();
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
}
clearTimeout(mcpConnectionTimeout);
},
const abortController = new AbortController();
try {
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
abortController.signal,
);
if (mcpError) {
errors.push(mcpError);
}
} catch (e: any) {
errors.push({
fatal: false,
message: `Failed to load MCP server: ${e.message}`,
});
if (e.name !== "AbortError") {
throw e;
}
}
},
) || [],
);
}
return continueConfig;
return { config: continueConfig, errors };
}
function finalToBrowserConfig(
@ -831,15 +837,20 @@ async function loadFullConfigNode(
}
// Convert to final config format
const finalConfig = await intermediateToFinalConfig(
intermediate,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
);
return { config: finalConfig, errors, configLoadInterrupted: false };
const { config: finalConfig, errors: finalErrors } =
await intermediateToFinalConfig(
intermediate,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
);
return {
config: finalConfig,
errors: [...(errors ?? []), ...finalErrors],
configLoadInterrupted: false,
};
}
export {

View file

@ -6,6 +6,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { ConfigValidationError } from "../../config/validation";
import MCPContextProvider from "../providers/MCPContextProvider";
export class MCPManagerSingleton {
@ -104,9 +105,6 @@ class MCPConnection {
try {
await this.connectPromise;
} catch (error) {
// Handle connection error if needed
throw error;
} finally {
// Reset the promise so future attempts can try again if necessary
this.connectPromise = null;
@ -117,7 +115,7 @@ class MCPConnection {
config: ContinueConfig,
mcpId: string,
signal: AbortSignal,
): Promise<void> {
): Promise<ConfigValidationError | undefined> {
try {
await Promise.race([
this.connectClient(),
@ -132,7 +130,10 @@ class MCPConnection {
throw new Error("Operation aborted");
}
if (!error.message.startsWith("StdioClientTransport already started")) {
console.error("Failed to connect client:", error);
return {
fatal: false,
message: `Failed to connect to MCP ${mcpId}: ${error.message}`,
};
}
}

View file

@ -12,12 +12,7 @@ import {
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import {
addContextProvider,
addModel,
addOpenAIKey,
deleteModel,
} from "./config/util";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
@ -47,9 +42,9 @@ import { TTS } from "./util/tts";
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import * as URI from "uri-js";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import type { IMessenger, Message } from "./protocol/messenger";
import * as URI from "uri-js";
import { localPathToUri } from "./util/pathToUri";
export class Core {
@ -124,9 +119,15 @@ export class Core {
this.messenger,
);
this.configHandler.onConfigUpdate(
(() => this.messenger.send("configUpdate", undefined)).bind(this),
);
this.configHandler.onConfigUpdate(async (result) => {
const serialized = await (
await this.configHandler.getSerializedConfig()
).config!;
this.messenger.send("configUpdate", {
config: serialized,
profileId: this.configHandler.currentProfile.profileId,
});
});
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
this.messenger.send("didChangeAvailableProfiles", { profiles }),
@ -269,9 +270,9 @@ export class Core {
await this.configHandler.openConfigProfile(msg.data.profileId);
});
on("config/reload", (msg) => {
on("config/reload", async (msg) => {
void this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();
return (await this.configHandler.getSerializedConfig()).config!; // <-- TODO
});
on("config/ideSettingsUpdate", (msg) => {
@ -369,7 +370,7 @@ export class Core {
on("config/getSerializedProfileInfo", async (msg) => {
return {
config: await this.configHandler.getSerializedConfig(),
config: (await this.configHandler.getSerializedConfig()).config!, // <-- TODO
profileId: this.configHandler.currentProfile.profileId,
};
});

View file

@ -228,7 +228,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
} catch (e) {
// If can't parse, assume malformatted code
console.error(`Error parsing ${compute.path}:`, e);
}
// Add snippets to sqlite
@ -293,7 +292,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
} catch (e) {
// If can't parse, assume malformatted code
console.error(`Error parsing ${addTag.path}:`, e);
}
for (const snippet of snippets) {

View file

@ -71,10 +71,16 @@ function constructSystemPrompt(
provider: string,
useTools: boolean,
): string | null {
if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) {
if (
useTools &&
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))
) {
return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES;
}
if (useTools && modelSupportsTools(model, provider)) {
} else if (
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))
) {
return SYSTEM_MESSAGE;
} else if (useTools && modelSupportsTools(model, provider)) {
return TOOL_USE_RULES;
}

View file

@ -49,6 +49,7 @@ import {
} from "./countTokens.js";
import {
fromChatCompletionChunk,
fromChatResponse,
LlmApiRequestType,
toChatBody,
toCompleteBody,
@ -445,11 +446,22 @@ export abstract class BaseLLM implements ILLM {
const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
let formatted = "";
for (const msg of msgsCopy) {
if ("content" in msg && Array.isArray(msg.content)) {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls) {
contentToShow = msg.toolCalls
?.map(
(toolCall) =>
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
)
.join("\n");
} else if ("content" in msg && Array.isArray(msg.content)) {
const content = renderChatMessage(msg);
msg.content = content;
}
formatted += `<${msg.role}>\n${msg.content || ""}\n\n`;
formatted += `<${msg.role}>\n${contentToShow}\n\n`;
}
return formatted;
}
@ -561,16 +573,27 @@ export abstract class BaseLLM implements ILLM {
let completion = "";
try {
if (this.shouldUseOpenAIAdapter("streamComplete") && this.openaiAdapter) {
for await (const chunk of this.openaiAdapter.completionStream(
{
...toCompleteBody(prompt, completionOptions),
stream: true,
},
signal,
)) {
const content = chunk.choices[0]?.text ?? "";
completion += content;
yield content;
if (completionOptions.stream === false) {
// Stream false
const response = await this.openaiAdapter.completionNonStream(
{ ...toCompleteBody(prompt, completionOptions), stream: false },
signal,
);
completion = response.choices[0]?.text ?? "";
yield completion;
} else {
// Stream true
for await (const chunk of this.openaiAdapter.completionStream(
{
...toCompleteBody(prompt, completionOptions),
stream: true,
},
signal,
)) {
const content = chunk.choices[0]?.text ?? "";
completion += content;
yield content;
}
}
} else {
for await (const chunk of this._streamComplete(
@ -705,17 +728,30 @@ export abstract class BaseLLM implements ILLM {
if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) {
let body = toChatBody(messages, completionOptions);
body = this.modifyChatBody(body);
const stream = this.openaiAdapter.chatCompletionStream(
{
...body,
stream: true,
},
signal,
);
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
yield result;
if (completionOptions.stream === false) {
// Stream false
const response = await this.openaiAdapter.chatCompletionNonStream(
{ ...body, stream: false },
signal,
);
const msg = fromChatResponse(response);
yield msg;
completion = renderChatMessage(msg);
} else {
// Stream true
const stream = this.openaiAdapter.chatCompletionStream(
{
...body,
stream: true,
},
signal,
);
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
yield result;
}
}
}
} else {

View file

@ -1,4 +1,5 @@
import { LLMOptions } from "../../index.js";
import { LlmApiRequestType } from "../openaiTypeConverters.js";
import OpenAI from "./OpenAI.js";
@ -9,6 +10,8 @@ class Azure extends OpenAI {
return false;
}
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
static defaultOptions: Partial<LLMOptions> = {
apiVersion: "2024-02-15-preview",
apiType: "azure",

View file

@ -93,9 +93,7 @@ class OpenAI extends BaseLLM {
}
private isO1Model(model?: string): boolean {
return (
!!model && (model.startsWith("o1-preview") || model.startsWith("o1-mini"))
);
return !!model && model.startsWith("o1");
}
protected supportsPrediction(model: string): boolean {

View file

@ -1,6 +1,7 @@
import { ConfigValidationError } from "../config/validation.js";
import type {
BrowserSerializedContinueConfig,
ContextItemWithId,
IndexingProgressUpdate,
IndexingStatus,
@ -8,7 +9,10 @@ import type {
} from "../index.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [undefined, void];
configUpdate: [
{ config: BrowserSerializedContinueConfig; profileId: string },
void,
];
configError: [ConfigValidationError[] | undefined, void];
getDefaultModelTitle: [undefined, string];
indexProgress: [IndexingProgressUpdate, void]; // Codebase

View file

@ -1,6 +1,7 @@
import { ToolImpl } from ".";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
const result = await extras.ide.getCurrentFile();
@ -15,6 +16,10 @@ export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
name: "Current file",
description: basename,
content: `\`\`\`${basename}\n${result.contents}\n\`\`\``,
uri: {
type: "file",
value: result.path,
},
},
];
};

View file

@ -1,13 +1,26 @@
import { ToolImpl } from ".";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
export const readFileImpl: ToolImpl = async (args, extras) => {
const content = await extras.ide.readFile(args.filepath);
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
extras.ide,
);
if (!firstUriMatch) {
throw new Error(`Could not find file ${args.filepath}`);
}
const content = await extras.ide.readFile(firstUriMatch);
return [
{
name: getUriPathBasename(args.filepath),
description: args.filepath,
content,
uri: {
type: "file",
value: firstUriMatch,
},
},
];
};

View file

@ -1,6 +1,6 @@
import { ChatDescriber } from "./chatDescriber";
import { testLLM } from "../test/fixtures";
import { LLMFullCompletionOptions } from "..";
import { testLLM } from "../test/fixtures";
import { ChatDescriber } from "./chatDescriber";
describe("ChatDescriber", () => {
beforeEach(() => {
@ -30,7 +30,7 @@ describe("ChatDescriber", () => {
expect(result).toBeUndefined();
});
it("should set completionOptions.maxTokens to 6", async () => {
it("should set completionOptions.maxTokens to 12", async () => {
const message = "Test message";
const completionOptions: LLMFullCompletionOptions = { temperature: 0.7 };
@ -38,7 +38,7 @@ describe("ChatDescriber", () => {
await ChatDescriber.describe(testLLM, completionOptions, message);
expect(completionOptions.maxTokens).toBe(6);
expect(completionOptions.maxTokens).toBe(ChatDescriber.maxTokens);
});
it("should call model.chat with correct parameters", async () => {

View file

@ -1,13 +1,14 @@
import { ILLM, LLMFullCompletionOptions } from "..";
import { removeQuotesAndEscapes, removeCodeBlocksAndTrim } from ".";
import { removeCodeBlocksAndTrim, removeQuotesAndEscapes } from ".";
import type { IMessenger } from "../protocol/messenger";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
export class ChatDescriber {
static maxTokens = 12;
static prompt: string | undefined =
"Given the following... please reply with a short summary that is 4-12 words in length, you should summarize what the user is asking for OR what the user is trying to accomplish. You should only respond with the summary, no additional text or explanation, you don't need ending punctuation.\n\n";
"Given the following... please reply with a short summary that is 4-8 words in length, you should summarize what the user is asking for OR what the user is trying to accomplish. You should only respond with the summary, no additional text or explanation, you don't need ending punctuation.\n\n";
static messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>;
static async describe(
@ -26,7 +27,7 @@ export class ChatDescriber {
return;
}
completionOptions.maxTokens = 6;
completionOptions.maxTokens = ChatDescriber.maxTokens;
// Prompt the user's current LLM for the title
const titleResponse = await model.chat(

View file

@ -36,6 +36,7 @@ export function findUriInDirs(
if (!uriComps.scheme) {
throw new Error(`Invalid uri: ${uri}`);
}
for (const dir of dirUriCandidates) {
const dirComps = URI.parse(dir);
@ -78,7 +79,6 @@ export function findUriInDirs(
}
}
// Not found
console.trace("Directory not found for uri", uri, dirUriCandidates);
return {
uri,
relativePathOrBasename: getUriPathBasename(uri),

View file

@ -25,9 +25,9 @@ You can include a specific file in your current workspace as context by typing [
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
## Entire codebase
## Codebase search
You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
You can automatically include relevant files from your codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
## Documentation site

View file

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

View file

@ -30,6 +30,7 @@ import java.nio.file.Paths
import javax.swing.*
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
@ -130,7 +131,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
val ideProtocolClient = IdeProtocolClient(
continuePluginService,
coroutineScope,
project.basePath,
project
)

View file

@ -32,10 +32,9 @@ import kotlin.coroutines.resume
class IdeProtocolClient(
private val continuePluginService: ContinuePluginService,
private val coroutineScope: CoroutineScope,
workspacePath: String?,
private val project: Project
) : DumbAware {
private val ide: IDE = IntelliJIDE(project, workspacePath, continuePluginService)
private val ide: IDE = IntelliJIDE(project, continuePluginService)
init {
// Setup config.json / config.ts save listeners
@ -389,7 +388,7 @@ class IdeProtocolClient(
ide.openUrl(url)
respond(null)
}
"insertAtCursor" -> {
val params = Gson().fromJson(
dataElement.toString(),

View file

@ -22,11 +22,13 @@ import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.containers.toArray
import kotlinx.coroutines.*
import java.awt.Desktop
import java.awt.Toolkit
@ -41,7 +43,6 @@ import java.nio.file.Paths
class IntelliJIDE(
private val project: Project,
private val workspacePath: String?,
private val continuePluginService: ContinuePluginService,
) : IDE {
@ -560,10 +561,6 @@ class IntelliJIDE(
return dirs
}
if (this.workspacePath != null) {
return arrayOf(this.workspacePath)
}
return arrayOf()
return listOfNotNull(project.guessProjectDir()?.url).toTypedArray()
}
}

View file

@ -1,4 +1,11 @@
import { EditorView, WebView, WebDriver, Key } from "vscode-extension-tester";
import {
EditorView,
WebView,
WebDriver,
Key,
WebElement,
VSBrowser,
} from "vscode-extension-tester";
import { expect } from "chai";
import { GUIActions } from "../actions/GUI.actions";
import { GUISelectors } from "../selectors/GUI.selectors";
@ -12,6 +19,7 @@ describe("GUI Test", () => {
before(async function () {
this.timeout(DEFAULT_TIMEOUT.XL);
await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver);
await GlobalActions.openTestWorkspace();
});
@ -184,6 +192,36 @@ describe("GUI Test", () => {
});
describe("Chat Paths", () => {
it("Open chat and type → open history → cmd+l → chat opens, empty and in focus", async () => {
const originalTextInput = await GUISelectors.getMessageInputFieldAtIndex(
view,
0,
);
await originalTextInput.click();
await originalTextInput.sendKeys("Hello");
expect(await originalTextInput.getText()).to.equal("Hello");
await view.switchBack();
await (await GUISelectors.getHistoryNavButton(view)).click();
await GUIActions.switchToReactIframe();
await view.switchBack();
await (await GUISelectors.getNewSessionNavButton(view)).click();
await GUIActions.switchToReactIframe();
const newTextInput = await TestUtils.waitForSuccess(() =>
GUISelectors.getMessageInputFieldAtIndex(view, 0),
);
const activeElement: WebElement = await driver.switchTo().activeElement();
const newTextInputHtml = await newTextInput.getAttribute("outerHTML");
const activeElementHtml = await activeElement.getAttribute("outerHTML");
expect(newTextInputHtml).to.equal(activeElementHtml);
const textInputValue = await newTextInput.getText();
expect(textInputValue).to.equal("");
}).timeout(DEFAULT_TIMEOUT.XL);
it("chat → history → chat", async () => {
const messagePair1 = TestUtils.generateTestMessagePair(1);
await GUIActions.sendMessage({

View file

@ -7,12 +7,15 @@ import {
Workbench,
WebView,
WebElement,
until,
} from "vscode-extension-tester";
import { DEFAULT_TIMEOUT } from "../constants";
import { GUISelectors } from "../selectors/GUI.selectors";
import { GUIActions } from "../actions/GUI.actions";
import { expect } from "chai";
import { TestUtils } from "../TestUtils";
import { Test } from "mocha";
import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions";
describe("Cmd+L Shortcut Test", () => {
let driver: WebDriver;
@ -74,9 +77,49 @@ describe("Cmd+L Shortcut Test", () => {
expect(await textInput.isDisplayed()).to.equal(true);
await GUIActions.executeFocusContinueInputShortcut(driver);
await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS);
expect(await textInput.isDisplayed()).to.equal(false);
}).timeout(DEFAULT_TIMEOUT.XL);
it("Send a message → focus code editor (not sidebar) → cmd+L → should focus sidebar and start a new session", async () => {
await GUIActions.executeFocusContinueInputShortcut(driver);
({ view } = await GUIActions.switchToReactIframe());
const { userMessage: userMessage0 } = TestUtils.generateTestMessagePair(0);
await GUIActions.sendMessage({
view,
message: userMessage0,
inputFieldIndex: 0,
});
await view.switchBack();
KeyboardShortcutsActions.HACK__typeWithSelect(editor, "hello");
await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS);
await GUIActions.executeFocusContinueInputShortcut(driver);
({ view } = await GUIActions.switchToReactIframe());
await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS);
const textInput = await TestUtils.waitForSuccess(() =>
GUISelectors.getMessageInputFieldAtIndex(view, 0),
);
const activeElement: WebElement = await driver.switchTo().activeElement();
const textInputHtml = await textInput.getAttribute("outerHTML");
const activeElementHtml = await activeElement.getAttribute("outerHTML");
expect(textInputHtml).to.equal(activeElementHtml);
await GUIActions.executeFocusContinueInputShortcut(driver);
await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS);
expect(await textInput.isDisplayed()).to.equal(false);
}).timeout(DEFAULT_TIMEOUT.XL * 1000);
it("Should create a code block when Cmd+L is pressed with text highlighted", async () => {
const text = "Hello, world!";

View file

@ -127,11 +127,6 @@
"default": false,
"markdownDescription": "Pause Continue's codebase index on start."
},
"continue.enableDebugLogs": {
"type": "boolean",
"default": false,
"markdownDescription": "Enable Continue Debug Logs in the Output panel."
},
"continue.remoteConfigServerUrl": {
"type": "string",
"default": null,

View file

@ -1,5 +1,4 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import { EXTENSION_NAME } from "core/control-plane/env";
import * as vscode from "vscode";
import { getTheme } from "./util/getTheme";
@ -19,42 +18,6 @@ export class ContinueGUIWebviewViewProvider
return !!this.webview;
}
private updateDebugLogsStatus() {
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
this.enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (!this.enableDebugLogs) {
this.outputChannel.hide();
}
}
// Show or hide the output channel on enableDebugLogs
private setupDebugLogsListener() {
vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration("continue.enableDebugLogs")) {
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
const enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (!enableDebugLogs) {
this.outputChannel.hide();
}
}
});
}
private async handleWebviewMessage(message: any) {
if (message.messageType === "log") {
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
const enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (message.level === "debug" && !enableDebugLogs) {
return; // Skip debug logs if enableDebugLogs is false
}
const timestamp = new Date().toISOString().split(".")[0];
const logMessage = `[${timestamp}] [${message.level.toUpperCase()}] ${message.text}`;
this.outputChannel.appendLine(logMessage);
}
}
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
@ -62,9 +25,6 @@ export class ContinueGUIWebviewViewProvider
): void | Thenable<void> {
this._webviewView = webviewView;
this._webview = webviewView.webview;
this._webview.onDidReceiveMessage((message) =>
this.handleWebviewMessage(message),
);
webviewView.webview.html = this.getSidebarContent(
this.extensionContext,
webviewView,
@ -73,8 +33,6 @@ export class ContinueGUIWebviewViewProvider
private _webview?: vscode.Webview;
private _webviewView?: vscode.WebviewView;
private outputChannel: vscode.OutputChannel;
private enableDebugLogs: boolean;
get isVisible() {
return this._webviewView?.visible;
@ -104,11 +62,6 @@ export class ContinueGUIWebviewViewProvider
private readonly windowId: string,
private readonly extensionContext: vscode.ExtensionContext,
) {
this.outputChannel = vscode.window.createOutputChannel("Continue");
this.enableDebugLogs = false;
this.updateDebugLogsStatus();
this.setupDebugLogsListener();
this.webviewProtocol = new VsCodeWebviewProtocol(
(async () => {
const configHandler = await this.configHandlerPromise;

View file

@ -602,7 +602,7 @@ class VsCodeIde implements IDE {
"pauseCodebaseIndexOnStart",
false,
),
enableDebugLogs: settings.get<boolean>("enableDebugLogs", false),
enableDebugLogs: false,
// settings.get<boolean>(
// "enableControlServerBeta",
// false,

View file

@ -136,7 +136,7 @@ export class VsCodeExtension {
this.configHandler = this.core.configHandler;
resolveConfigHandler?.(this.configHandler);
this.configHandler.reloadConfig();
this.configHandler.loadConfig();
this.verticalDiffManager = new VerticalDiffManager(
this.configHandler,
this.sidebar.webviewProtocol,
@ -161,14 +161,18 @@ export class VsCodeExtension {
});
this.configHandler.onConfigUpdate(
({ config: newConfig, errors, configLoadInterrupted }) => {
async ({ config: newConfig, errors, configLoadInterrupted }) => {
if (configLoadInterrupted) {
// Show error in status bar
setupStatusBar(undefined, undefined, true);
} else if (newConfig) {
setupStatusBar(undefined, undefined, false);
this.sidebar.webviewProtocol?.request("configUpdate", undefined);
const serialized = await this.configHandler.getSerializedConfig();
this.sidebar.webviewProtocol?.request("configUpdate", {
config: serialized.config!, // <-- TODO
profileId: this.configHandler.currentProfile.profileId,
});
this.tabAutocompleteModel.clearLlm();
@ -246,6 +250,9 @@ export class VsCodeExtension {
// Listen for file saving - use global file watcher so that changes
// from outside the window are also caught
fs.watchFile(getConfigJsonPath(), { interval: 1000 }, async (stats) => {
if (stats.size === 0) {
return;
}
await this.configHandler.reloadConfig();
});
@ -253,11 +260,17 @@ export class VsCodeExtension {
getConfigYamlPath("vscode"),
{ interval: 1000 },
async (stats) => {
if (stats.size === 0) {
return;
}
await this.configHandler.reloadConfig();
},
);
fs.watchFile(getConfigTsPath(), { interval: 1000 }, (stats) => {
if (stats.size === 0) {
return;
}
this.configHandler.reloadConfig();
});

View file

@ -16,7 +16,7 @@ import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProvide
const router = createMemoryRouter([
{
path: "/",
path: ROUTES.HOME,
element: <Layout />,
errorElement: <ErrorPage />,
children: [
@ -25,7 +25,7 @@ const router = createMemoryRouter([
element: <Chat />,
},
{
path: "/",
path: ROUTES.HOME,
element: <Chat />,
},
{

View file

@ -65,6 +65,44 @@ const Layout = () => {
const showDialog = useAppSelector((state) => state.ui.showDialog);
useWebviewListener(
"newSession",
async () => {
navigate(ROUTES.HOME);
await dispatch(
saveCurrentSession({
openNewSession: true,
}),
);
dispatch(exitEditMode());
},
[],
);
useWebviewListener(
"isContinueInputFocused",
async () => {
return false;
},
[location.pathname],
location.pathname === ROUTES.HOME,
);
useWebviewListener(
"focusContinueInputWithNewSession",
async () => {
navigate(ROUTES.HOME);
await dispatch(
saveCurrentSession({
openNewSession: true,
}),
);
dispatch(exitEditMode());
},
[location.pathname],
location.pathname === ROUTES.HOME,
);
useWebviewListener(
"openDialogMessage",
async (message) => {

View file

@ -7,7 +7,7 @@ export interface PageHeaderProps {
export default function PageHeader({ onClick, title }: PageHeaderProps) {
return (
<div className="bg-vsc-background sticky top-0 m-0 flex items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0">
<div className="bg-vsc-background sticky top-0 z-20 m-0 flex items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0">
<div
className="cursor-pointer transition-colors duration-200 hover:text-zinc-100"
onClick={onClick}

View file

@ -4,12 +4,12 @@ import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { vscBackground } from "..";
import { getFontSize } from "../../util";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import ResponseActions from "./ResponseActions";
import { useAppSelector } from "../../redux/hooks";
import { selectUIConfig } from "../../redux/slices/configSlice";
import { deleteMessage } from "../../redux/slices/sessionSlice";
import { getFontSize } from "../../util";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import ResponseActions from "./ResponseActions";
import ThinkingIndicator from "./ThinkingIndicator";
interface StepContainerProps {
@ -49,6 +49,7 @@ export default function StepContainer(props: StepContainerProps) {
// If not ending in punctuation or emoji, we assume the response got truncated
if (
content.trim() !== "" &&
!(
endingPunctuation.some((p) => content.endsWith(p)) ||
/\p{Emoji}/u.test(content.slice(-2))

View file

@ -5,9 +5,9 @@ import {
ArrowPathIcon,
ArrowTopRightOnSquareIcon,
CheckCircleIcon,
ExclamationTriangleIcon,
PauseCircleIcon,
TrashIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { updateIndexingStatus } from "../../redux/slices/indexingSlice";
@ -24,7 +24,7 @@ const STATUS_TO_ICON: Record<IndexingStatus["status"], any> = {
complete: CheckCircleIcon,
aborted: null,
pending: null,
failed: XMarkIcon, // Since we show an error message below
failed: ExclamationTriangleIcon, // Since we show an error message below
};
function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {

View file

@ -29,8 +29,7 @@ function DocsIndexingStatuses() {
<h3 className="mb-1 mt-0 text-xl">@docs indexes</h3>
{configDocs.length ? (
<SecondaryButton
className="border-vsc-foreground text-vsc-foreground enabled:hover:bg-vsc-background m-2 rounded border bg-inherit px-3 py-2 enabled:hover:cursor-pointer enabled:hover:opacity-90 disabled:text-gray-500"
type="submit"
className="flex h-7 flex-col items-center justify-center"
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));
@ -71,10 +70,11 @@ function DocsIndexingStatuses() {
</div>
)}
</span>
<div className="flex max-h-[170px] flex-col gap-1 overflow-x-hidden overflow-y-scroll pr-2">
<div className="flex max-h-[170px] flex-col gap-1 overflow-y-auto overflow-x-hidden pr-2">
<div>
{configDocs.length === 0 && (
<SecondaryButton
className="flex h-7 flex-col items-center justify-center"
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<AddDocsDialog />));

View file

@ -5,6 +5,7 @@ import {
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { getUriPathBasename } from "core/util/uri";
import { useContext, useMemo, useState } from "react";
import { AnimatedEllipsis, lightGray, vscBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
@ -13,7 +14,6 @@ import { selectIsGatheringContext } from "../../redux/slices/sessionSlice";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import { getIconFromDropdownItem } from "./MentionList";
import { getUriPathBasename } from "core/util/uri";
interface ContextItemsPeekProps {
contextItems?: ContextItemWithId[];
@ -71,7 +71,8 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) {
}
// Heuristic to check if it's a file
const shouldShowFileIcon = contextItem.content.includes("```");
const shouldShowFileIcon =
contextItem.content.includes("```") || contextItem.uri?.type === "file";
if (shouldShowFileIcon) {
return (

View file

@ -38,10 +38,10 @@ import {
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import AddDocsDialog from "../dialogs/AddDocsDialog";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { ComboBoxItem, ComboBoxItemType } from "./types";
const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
@ -120,7 +120,7 @@ const ItemsDiv = styled.div`
overflow-y: auto;
max-height: 330px;
padding: 0.2rem;
position: relative;
position: relative; // absolute to test tippy.js bug
background-color: ${vscQuickInputBackground};
/* backdrop-filter: blur(12px); */
@ -352,7 +352,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
}, [allItems]);
return (
<ItemsDiv className="items-container">
<ItemsDiv>
{querySubmenuItem ? (
<QueryInput
rows={1}

View file

@ -7,6 +7,7 @@ import Text from "@tiptap/extension-text";
import { Plugin } from "@tiptap/pm/state";
import { Editor, EditorContent, JSONContent, useEditor } from "@tiptap/react";
import { ContextProviderDescription, InputModifiers } from "core";
import { rifWithContentsToContextItem } from "core/commands/util";
import { modelSupportsImages } from "core/llm/autodetect";
import { debounce } from "lodash";
import { usePostHog } from "posthog-js/react";
@ -34,7 +35,22 @@ import { useInputHistory } from "../../hooks/useInputHistory";
import useIsOSREnabled from "../../hooks/useIsOSREnabled";
import useUpdatingRef from "../../hooks/useUpdatingRef";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import { selectDefaultModel } from "../../redux/slices/configSlice";
import {
addCodeToEdit,
clearCodeToEdit,
selectHasCodeToEdit,
selectIsInEditMode,
setMainEditorContentTrigger,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import {
loadLastSession,
loadSession,
saveCurrentSession,
} from "../../redux/thunks/session";
import {
getFontSize,
isJetBrains,
@ -55,22 +71,6 @@ import {
handleVSCMetaKeyIssues,
} from "./handleMetaKeyIssues";
import { ComboBoxItem } from "./types";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectDefaultModel } from "../../redux/slices/configSlice";
import {
addCodeToEdit,
clearCodeToEdit,
selectHasCodeToEdit,
selectIsInEditMode,
setMainEditorContentTrigger,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import {
loadLastSession,
loadSession,
saveCurrentSession,
} from "../../redux/thunks/session";
import { rifWithContentsToContextItem } from "core/commands/util";
const InputBoxDiv = styled.div<{ border?: string }>`
resize: none;
@ -647,6 +647,17 @@ function TipTapEditor(props: TipTapEditorProps) {
[props.onEnter, editor, props.isMainInput],
);
useEffect(() => {
if (props.isMainInput) {
/**
* I have a strong suspicion that many of the other focus
* commands are redundant, especially the ones inside
* useTimeout.
*/
editor.commands.focus();
}
}, [props.isMainInput, editor]);
// Re-focus main input after done generating
useEffect(() => {
if (editor && !isStreaming && props.isMainInput && document.hasFocus()) {
@ -986,6 +997,12 @@ function TipTapEditor(props: TipTapEditorProps) {
<HoverTextDiv>Hold ⇧ to drop image</HoverTextDiv>
</>
)}
<div
id="tippy-js-div"
style={{
position: "fixed",
}}
/>
</InputBoxDiv>
);
}

View file

@ -37,9 +37,15 @@ function getSuggestion(
return;
}
const container = document.getElementById("tippy-js-div");
if (!container) {
console.log("no container");
return;
}
popup = tippy("body", {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
appendTo: () => container,
content: component.element,
showOnCreate: true,
interactive: true,

View file

@ -114,7 +114,6 @@ async function resolveEditorContent({
}
const shouldGatherContext = modifiers.useCodebase || slashCommand;
if (shouldGatherContext) {
dispatch(setIsGatheringContext(true));
}
@ -189,7 +188,6 @@ async function resolveEditorContent({
parts = [{ type: "text", text: lastPart }];
}
}
if (shouldGatherContext) {
dispatch(setIsGatheringContext(false));
}

View file

@ -32,6 +32,7 @@ function FilenameLink({ rif }: FilenameLinkProps) {
<>
<span
data-tooltip-id={id}
data-tooltip-delay-show={500}
className="mx-[0.1em] mb-[0.15em] inline-flex cursor-pointer items-center gap-0.5 rounded-md pr-[0.2em] align-middle hover:ring-1"
onClick={onClick}
>

View file

@ -1,24 +1,24 @@
import { useCallback, useContext, useEffect, useRef } from "react";
import { VSC_THEME_COLOR_VARS } from "../components";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { AppDispatch } from "../redux/store";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
import { BrowserSerializedContinueConfig } from "core";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { setConfig, setConfigError } from "../redux/slices/configSlice";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import { updateDocsSuggestions } from "../redux/slices/miscSlice";
import {
setSelectedProfileId,
setInactive,
addContextItemsAtIndex,
setInactive,
setSelectedProfileId,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
function useSetup() {
const dispatch = useAppDispatch();
@ -29,16 +29,13 @@ function useSetup() {
);
const hasLoadedConfig = useRef(false);
const loadConfig = useCallback(
async (initial: boolean) => {
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
);
if (result.status === "error") {
return;
}
const { config, profileId } = result.content;
const handleConfigUpdate = useCallback(
async (
initial: boolean,
result: { config: BrowserSerializedContinueConfig; profileId: string },
) => {
const { config, profileId } = result;
if (initial && hasLoadedConfig.current) {
return;
}
@ -52,7 +49,21 @@ function useSetup() {
document.body.style.fontSize = `${config.ui.fontSize}px`;
}
},
[dispatch, ideMessenger, hasLoadedConfig],
[dispatch, hasLoadedConfig],
);
const loadConfig = useCallback(
async (initial: boolean) => {
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
);
if (result.status === "error") {
return;
}
await handleConfigUpdate(initial, result.content);
},
[ideMessenger, handleConfigUpdate],
);
// Load config from the IDE
@ -78,8 +89,11 @@ function useSetup() {
useWebviewListener(
"configUpdate",
async () => {
await loadConfig(false);
async (update) => {
if (!update) {
return;
}
await handleConfigUpdate(false, update);
},
[loadConfig],
);
@ -147,7 +161,7 @@ function useSetup() {
useWebviewListener(
"getCurrentSessionId",
async () => {
return sessionId
return sessionId;
},
[sessionId],
);

View file

@ -233,8 +233,8 @@ export function Chat() {
(
editorState: JSONContent,
modifiers: InputModifiers,
editor: Editor,
index?: number,
editorToClearOnSend?: Editor,
) => {
if (defaultModel?.provider === "free-trial") {
const u = getLocalStorage("ftc");
@ -268,7 +268,9 @@ export function Chat() {
streamResponseThunk({ editorState, modifiers, promptPreamble, index }),
);
editor.commands.clearContent(true);
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
}
// Increment localstorage counter for popup
const currentCount = getLocalStorage("mainTextEntryCounter");
@ -321,14 +323,8 @@ export function Chat() {
useWebviewListener(
"newSession",
async () => {
await dispatch(
saveCurrentSession({
openNewSession: true,
}),
);
// unwrapResult(response) // errors if session creation failed
mainTextInputRef.current?.focus?.();
dispatch(exitEditMode());
},
[mainTextInputRef],
);
@ -381,8 +377,8 @@ export function Chat() {
{isInEditMode && index === 0 && <CodeToEditCard />}
<ContinueInputBox
isEditMode={isInEditMode}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, editor, index)
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
@ -487,7 +483,9 @@ export function Chat() {
isMainInput
isEditMode={isInEditMode}
isLastUserInput={false}
onEnter={sendInput}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, undefined, editor)
}
/>
)}

View file

@ -12,14 +12,14 @@ function FunctionSpecificToolCallDiv({
const args = toolCallState.parsedArgs;
switch (toolCall.function.name) {
case "create_new_file":
case "builtin_create_new_file":
return (
<CreateFile
relativeFilepath={args.filepath}
fileContents={args.contents}
/>
);
case "run_terminal_command":
case "builtin_run_terminal_command":
return (
<RunTerminalCommand
command={args.command}

View file

@ -4,14 +4,14 @@ import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { table } from "table";
import { lightGray, vscBackground, vscInputBackground } from "../components";
import { CopyIconButton } from "../components/gui/CopyIconButton";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useNavigationListener } from "../hooks/useNavigationListener";
import { CopyIconButton } from "../components/gui/CopyIconButton";
const Th = styled.th`
padding: 0.5rem;
text-align: left;
border: 1px solid ${vscInputBackground};
border: 1px solid ${lightGray};
`;
const Tr = styled.tr`
@ -21,12 +21,12 @@ const Tr = styled.tr`
overflow-wrap: anywhere;
border: 1px solid ${vscInputBackground};
border: 1px solid ${lightGray};
`;
const Td = styled.td`
padding: 0.5rem;
border: 1px solid ${vscInputBackground};
border: 1px solid ${lightGray};
`;
function generateTable(data: unknown[][]) {

View file

@ -34,16 +34,7 @@ export function isMetaEquivalentKeyPressed({
}
export function getMetaKeyLabel(): string {
const platform = getPlatform();
switch (platform) {
case "mac":
return "⌘";
case "linux":
case "windows":
return "^";
default:
return "^";
}
return getPlatform() === "mac" ? "⌘" : "Ctrl";
}
export function getAltKeyLabel(): string {