Merge branch 'main' into pe/mention-description-no-hover

This commit is contained in:
Nate Sesti 2025-05-01 19:27:51 -07:00 • committed by GitHub
commit fdeabb628d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
114 changed files with 1629 additions and 2210 deletions

View file

@ -7,6 +7,7 @@
"plugins": ["@typescript-eslint", "import"],
"rules": {
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",

View file

@ -16,9 +16,9 @@ jobs:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa
numOfAssignee: 1
- name: "Add default labels"
uses: actions-ecosystem/action-add-labels@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
labels: |
"needs-triage"
# - name: "Add default labels"
# uses: actions-ecosystem/action-add-labels@v1
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# labels: |
# "needs-triage"

View file

@ -7,7 +7,8 @@
"rules": {
"quotes": ["off", "double", {}],
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "off",
// This is important: when floating promises cause unhandled rejections, the JetBrains binary blows up
"@typescript-eslint/no-floating-promises": "error",
"import/order": "off",
"curly": "off",
"@typescript-eslint/semi": "off",

View file

@ -261,7 +261,9 @@ export class CompletionProvider {
// Save to cache
if (!outcome.cacheHit && helper.options.useCache) {
(await this.autocompleteCache).put(outcome.prefix, outcome.completion);
(await this.autocompleteCache)
.put(outcome.prefix, outcome.completion)
.catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
}
// When using the JetBrains extension, Mark as displayed

View file

@ -22,7 +22,13 @@ export class ImportDefinitionsService {
constructor(private readonly ide: IDE) {
ide.onDidChangeActiveTextEditor((filepath) => {
this.cache.initKey(filepath);
this.cache
.initKey(filepath)
.catch((e) =>
console.warn(
`Failed to initialize ImportDefinitionService: ${e.message}`,
),
);
});
}

View file

@ -3,16 +3,18 @@ export class ListenableGenerator<T> {
private _buffer: T[] = [];
private _listeners: Set<(value: T) => void> = new Set();
private _isEnded = false;
private _abortController: AbortController
private _abortController: AbortController;
constructor(
source: AsyncGenerator<T>,
private readonly onError: (e: any) => void,
abortController: AbortController
abortController: AbortController,
) {
this._source = source;
this._abortController = abortController;
this._start();
this._start().catch((e) =>
console.log(`Listenable generator failed: ${e.message}`),
);
}
public cancel() {

View file

@ -157,11 +157,11 @@ const mercuryMultifileFimTemplate: AutocompleteTemplate = {
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [
`<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`,
`<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n<|fim_prefix|>${prefix}`,
suffix,
];
}
return [prefix, suffix];
return [`<|fim_prefix|>${prefix}`, suffix];
}
const relativePaths = getShortestUniqueRelativeUriPaths(

View file

@ -349,7 +349,7 @@ export class ConfigHandler {
this.currentOrg = org;
if (profileId) {
this.setSelectedProfileId(profileId);
await this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig();

View file

@ -627,6 +627,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
baseAgentSystemMessage: llm.baseAgentSystemMessage,
baseChatSystemMessage: llm.baseChatSystemMessage,
requestOptions: llm.requestOptions,
promptTemplates: serializePromptTemplates(llm.promptTemplates),
@ -969,5 +970,6 @@ export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig,
type BrowserSerializedContinueConfig
};

View file

@ -235,10 +235,6 @@ declare global {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface Checkpoint {
[filepath: string]: string;
}
export interface Session {
sessionId: string;
title: string;
@ -423,8 +419,6 @@ declare global {
promptLogs?: PromptLog[];
toolCallState?: ToolCallState;
isGatheringContext?: boolean;
checkpoint?: Checkpoint;
isBeforeCheckpoint?: boolean;
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@ -1051,13 +1045,6 @@ declare global {
repoMapFileSelection?: string;
}
export type EditStatus =
| "not-started"
| "streaming"
| "accepting"
| "accepting:full-diff"
| "done";
export type ApplyStateStatus =
| "streaming" // Changes are being applied to the file
| "done" // All changes have been applied, awaiting user to accept/reject

View file

@ -1,35 +0,0 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
/*
TODO this is not functional
*/
export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): AssistantUnrolled {
return {
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
models: [
...configJson.models.map(
(model): ModelConfig => ({
model: model.model,
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat", "edit", "apply", "summarize"],
}),
),
// TODO
// tabAutocompleteModels
// embeddingsModels
// rerankModels
],
context: configJson.contextProviders?.map((provider) => ({
provider: provider.name,
params: provider.params,
})),
};
}

View file

@ -60,8 +60,9 @@ async function modelConfigToBaseLLM({
logger: llmLogger,
uniqueId,
title: model.name,
template: model.promptTemplates?.chatTemplate,
template: model.promptTemplates?.chat,
promptTemplates: model.promptTemplates,
baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
tools: model.capabilities?.includes("tool_use"),

View file

@ -349,8 +349,8 @@ export class Core {
return await this.configHandler.getSerializedConfig();
});
on("config/ideSettingsUpdate", (msg) => {
this.configHandler.updateIdeSettings(msg.data);
on("config/ideSettingsUpdate", async (msg) => {
await this.configHandler.updateIdeSettings(msg.data);
});
on("config/refreshProfiles", async (msg) => {
@ -389,7 +389,7 @@ export class Core {
});
on("mcp/reloadServer", async (msg) => {
MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
// Context providers
on("context/addDocs", async (msg) => {
@ -743,7 +743,7 @@ export class Core {
if (!config) {
return false;
}
const llm = config?.selectedModelByRole.chat;
if (!llm) {
throw new Error("No chat model selected");
@ -1034,10 +1034,9 @@ export class Core {
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
for await (const update of (
await this.codebaseIndexerPromise
).refreshDirs(paths, this.indexingCancellationController.signal)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
@ -1067,10 +1066,10 @@ export class Core {
return;
}
this.indexingCancellationController = new AbortController();
try{
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
try {
for await (const update of (
await this.codebaseIndexerPromise
).refreshFiles(files)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
@ -1093,18 +1092,18 @@ export class Core {
// private
handleIndexingError(e: any) {
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
void this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
}
}

1
core/edit/constants.ts Normal file
View file

@ -0,0 +1 @@
export const EDIT_MODE_STREAM_ID = "edit-mode";

View file

@ -161,9 +161,11 @@ export async function* streamDiffLines({
? llm.streamComplete(prompt, new AbortController().signal, {
raw: true,
prediction,
reasoning: false,
})
: llm.streamChat(prompt, new AbortController().signal, {
prediction,
reasoning: false,
});
let lines = streamLines(completion);

19
core/index.d.ts vendored
View file

@ -158,9 +158,7 @@ export interface ModelInstaller {
progressReporter?: (task: string, increment: number, total: number) => void,
): Promise<any>;
isInstallingModel(
modelName: string
): Promise<boolean>;
isInstallingModel(modelName: string): Promise<boolean>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
@ -248,10 +246,6 @@ export interface IContextProvider {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface Checkpoint {
[filepath: string]: string;
}
export interface Session {
sessionId: string;
title: string;
@ -464,8 +458,6 @@ export interface ChatHistoryItem {
promptLogs?: PromptLog[];
toolCallState?: ToolCallState;
isGatheringContext?: boolean;
checkpoint?: Checkpoint;
isBeforeCheckpoint?: boolean;
reasoning?: Reasoning;
}
@ -569,6 +561,7 @@ export interface LLMOptions {
title?: string;
uniqueId?: string;
baseAgentSystemMessage?: string;
baseChatSystemMessage?: string;
contextLength?: number;
maxStopWords?: number;
@ -1052,6 +1045,7 @@ export interface ModelDescription {
maxStopWords?: number;
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
baseAgentSystemMessage?: string;
baseChatSystemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
@ -1213,13 +1207,6 @@ export interface ExperimentalMCPOptions {
faviconUrl?: string;
}
export type EditStatus =
| "not-started"
| "streaming"
| "accepting"
| "accepting:full-diff"
| "done";
export type ApplyStateStatus =
| "not-started" // Apply state created but not necessarily streaming
| "streaming" // Changes are being applied to the file

View file

@ -57,7 +57,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
FOREIGN KEY (snippetId) REFERENCES code_snippets (id)
)`);
migrate("add_signature_column", async () => {
await migrate("add_signature_column", async () => {
const tableInfo = await db.all("PRAGMA table_info(code_snippets)");
const signatureColumnExists = tableInfo.some(
(column) => column.name === "signature",
@ -71,7 +71,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
}
});
migrate("delete_duplicate_code_snippets", async () => {
await migrate("delete_duplicate_code_snippets", async () => {
// Delete duplicate entries in code_snippets
await db.exec(`
DELETE FROM code_snippets
@ -256,7 +256,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
progress: i / results.compute.length,
status: "indexing",
};
markComplete([compute], IndexResultType.Compute);
await markComplete([compute], IndexResultType.Compute);
}
// Delete
@ -278,7 +278,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
}
markComplete([del], IndexResultType.Delete);
await markComplete([del], IndexResultType.Delete);
}
// Add tag
@ -313,7 +313,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
}
markComplete([results.addTag[i]], IndexResultType.AddTag);
await markComplete([results.addTag[i]], IndexResultType.AddTag);
}
// Remove tag
@ -343,7 +343,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
}
markComplete([results.removeTag[i]], IndexResultType.RemoveTag);
await markComplete([results.removeTag[i]], IndexResultType.RemoveTag);
}
}

View file

@ -48,10 +48,10 @@ export class TestCodebaseIndex implements CodebaseIndex {
);
}
markComplete(results.compute, IndexResultType.Compute);
markComplete(results.addTag, IndexResultType.AddTag);
markComplete(results.del, IndexResultType.Delete);
markComplete(results.removeTag, IndexResultType.RemoveTag);
await markComplete(results.compute, IndexResultType.Compute);
await markComplete(results.addTag, IndexResultType.AddTag);
await markComplete(results.del, IndexResultType.Delete);
await markComplete(results.removeTag, IndexResultType.RemoveTag);
}
async getIndexedFilesForTags(tags: IndexTag[]): Promise<string[]> {

View file

@ -510,7 +510,7 @@ export default class DocsService {
} catch (e) {
if (e instanceof LLMError) {
// Report the error to the IDE
this.messenger?.request("reportError", e);
await this.messenger?.request("reportError", e);
}
this.handleStatusUpdate({
...fixedStatus,

View file

@ -1,4 +1,4 @@
import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder";
import { GPTAsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder";
describe("llama encoder", () => {
var tokenizer: LlamaAsyncEncoder;
@ -8,7 +8,7 @@ describe("llama encoder", () => {
});
afterAll(() => {
tokenizer.close();
tokenizer.close().catch((e) => {});
});
test("hello world", async () => {
@ -30,7 +30,7 @@ describe("tiktoken encoder", () => {
});
afterAll(() => {
tokenizer.close();
tokenizer.close().catch((e) => {});
});
test("hello world", async () => {

View file

@ -72,6 +72,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"sagemaker",
"continue-proxy",
"openrouter",
"venice",
"sambanova",
"vertexai",
"azure",
@ -96,7 +97,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"pixtral",
"llama3.2",
"llama-3.2",
"llama4"
"llama4",
];
function modelSupportsTools(modelDescription: ModelDescription) {

View file

@ -60,7 +60,7 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
export function constructMessages(
history: ChatHistoryItem[],
baseChatSystemMessage: string | undefined,
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
): ChatMessage[] {
const filteredHistory = history.filter(
@ -100,7 +100,7 @@ export function constructMessages(
| undefined;
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
baseSystemMessage: baseChatOrAgentSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
rules,
userMessage: lastUserMsg,
});

View file

@ -130,6 +130,7 @@ export abstract class BaseLLM implements ILLM {
title?: string;
baseChatSystemMessage?: string;
baseAgentSystemMessage?: string;
contextLength: number;
maxStopWords?: number | undefined;
completionOptions: CompletionOptions;
@ -196,6 +197,7 @@ export abstract class BaseLLM implements ILLM {
this.title = options.title;
this.uniqueId = options.uniqueId ?? "None";
this.baseAgentSystemMessage = options.baseAgentSystemMessage;
this.baseChatSystemMessage = options.baseChatSystemMessage;
this.contextLength =
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;

View file

@ -60,7 +60,7 @@ class Docker extends OpenAI implements ModelInstaller {
}
// Check if Docker Model Runner is active and enable it if needed
this.ensureModelRunnerEnabled();
this.ensureModelRunnerEnabled().catch((e) => {});
}
/**
@ -198,7 +198,7 @@ class Docker extends OpenAI implements ModelInstaller {
return { success: true, stdout, stderr };
} catch (error) {
console.error(`Failed to install Docker model ${targetModel}:`, error);
// Fix: Type check the error before accessing message property
// Fix: Type check the error before accessing message property
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(

View file

@ -35,14 +35,20 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
}
async doEmbedRequest(batch: string[]): Promise<number[][]> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
const resp = await this.fetch(new URL("embed", this.apiBase), {
method: "POST",
body: JSON.stringify({
inputs: batch,
}),
headers: {
"Content-Type": "application/json",
},
headers,
});
if (!resp.ok) {
const text = await resp.text();

View file

@ -14,18 +14,22 @@ class HuggingFaceTGI extends BaseLLM {
this.fetch(new URL("info", this.apiBase), {
method: "GET",
}).then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling Hugging Face TGI /info endpoint: ",
await response.text(),
);
return;
}
const json = await response.json();
this.model = json.model_id;
this.contextLength = Number.parseInt(json.max_input_length);
});
})
.then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling Hugging Face TGI /info endpoint: ",
await response.text(),
);
return;
}
const json = await response.json();
this.model = json.model_id;
this.contextLength = Number.parseInt(json.max_input_length);
})
.catch((e) => {
console.log(`Failed to list models for HuggingFace TGI: ${e.message}`);
});
}
private _convertArgs(options: CompletionOptions, prompt: string) {

22
core/llm/llms/Venice.ts Normal file
View file

@ -0,0 +1,22 @@
import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI";
class Venice extends OpenAI {
static providerName = "venice";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.venice.ai/api/v1",
};
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
const finalOptions = super._convertArgs(options, messages) as ChatCompletionCreateParams & { venice_parameters?: any };
if ("venice_parameters" in options && typeof options.venice_parameters === "object") {
finalOptions.venice_parameters = { ...options.venice_parameters };
}
return finalOptions;
}
}
export default Venice;

View file

@ -22,7 +22,11 @@ class VertexAI extends BaseLLM {
private clientPromise = new GoogleAuth({
scopes: "https://www.googleapis.com/auth/cloud-platform",
}).getClient();
})
.getClient()
.catch((e) => {
console.warn(`Failed to load credentials for Vertex AI: ${e.message}`);
});
private static getDefaultApiBaseFrom(options: LLMOptions) {
const { region, projectId } = options;
@ -60,8 +64,8 @@ class VertexAI extends BaseLLM {
async fetch(url: RequestInfo | URL, init?: RequestInit) {
const client = await this.clientPromise;
const { token } = await client.getAccessToken();
if (!token) {
const result = await client?.getAccessToken();
if (!result?.token) {
throw new Error(
"Could not get an access token. Set up your Google Application Default Credentials.",
);
@ -70,7 +74,7 @@ class VertexAI extends BaseLLM {
...init,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
Authorization: `Bearer ${result.token}`,
...init?.headers,
},
});
@ -370,8 +374,8 @@ class VertexAI extends BaseLLM {
protected async _embed(chunks: string[]): Promise<number[][]> {
const client = await this.clientPromise;
const { token } = await client.getAccessToken();
if (!token) {
const result = await client?.getAccessToken();
if (!result?.token) {
throw new Error(
"Could not get an access token. Set up your Google Application Default Credentials.",
);
@ -386,7 +390,7 @@ class VertexAI extends BaseLLM {
}),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
Authorization: `Bearer ${result.token}`,
},
},
);
@ -402,8 +406,4 @@ class VertexAI extends BaseLLM {
}
}
async function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
export default VertexAI;

View file

@ -16,19 +16,23 @@ class Vllm extends OpenAI {
this.fetch(this._getEndpoint("models"), {
method: "GET",
headers: this._getHeaders(),
}).then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling vLLM /models endpoint: ",
await response.text(),
);
return;
}
const json = await response.json();
const data = json.data[0];
this.model = data.id;
this.contextLength = Number.parseInt(data.max_model_len);
});
})
.then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling vLLM /models endpoint: ",
await response.text(),
);
return;
}
const json = await response.json();
const data = json.data[0];
this.model = data.id;
this.contextLength = Number.parseInt(data.max_model_len);
})
.catch((e) => {
console.log(`Failed to list models for vLLM: ${e.message}`);
});
}
}

View file

@ -57,6 +57,7 @@ import ContinueProxy from "./stubs/ContinueProxy";
import TestLLM from "./Test";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import Venice from "./Venice";
import VertexAI from "./VertexAI";
import Vllm from "./Vllm";
import Voyage from "./Voyage";
@ -109,6 +110,7 @@ export const LLMClasses = [
Cerebras,
Asksage,
Nebius,
Venice,
VertexAI,
xAI,
SiliconFlow,
@ -158,6 +160,7 @@ export async function llmFromDescription(
cls.defaultOptions?.completionOptions?.maxTokens,
},
baseChatSystemMessage,
baseAgentSystemMessage: baseChatSystemMessage,
logger: llmLogger,
uniqueId,
};

View file

@ -14,7 +14,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/fetch": "^1.0.6",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
@ -2925,9 +2925,9 @@
"link": true
},
"node_modules/@continuedev/fetch": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.4.tgz",
"integrity": "sha512-lFLMQMdyo3y5ZpgAxTtOLj3lvhQAQUoI96SPCXjdV6NQp2gF/XmmIadCD+Hfx03Iz750Y5PF8jYdrGTMFxwlaQ==",
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.6.tgz",
"integrity": "sha512-QpB9cHgEw5avoouFR0qm7/XTo44SrVfkGAmzbDTui2P9djj+DYvj+0yaJ8e/Ubyc5PUjFTUS2YnRar7NfYpHIg==",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",

View file

@ -48,7 +48,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/fetch": "^1.0.6",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",

View file

@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import type {
ApplyState,
CodeToEdit,
EditStatus,
MessageContent,
RangeInFileWithContents,
} from "../";
@ -50,9 +49,10 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
prompt: MessageContent;
range: RangeInFileWithContents;
},
void,
string | undefined,
];
"edit/exit": [{ shouldFocusEditor: boolean }, void];
"edit/addCurrentSelection": [undefined, void];
"edit/clearDecorations": [undefined, void];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
@ -71,7 +71,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
},
void,
];
addCodeToEdit: [CodeToEdit, void];
setCodeToEdit: [CodeToEdit, void];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
@ -87,8 +87,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
openOnboardingCard: [undefined, void];
applyCodeFromChat: [undefined, void];
updateApplyState: [ApplyState, void];
setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void];
exitEditMode: [undefined, void];
focusEdit: [undefined, void];
focusEditWithoutClear: [undefined, void];
};

View file

@ -0,0 +1,35 @@
# Venice
Venice.AI is a privacy focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data. To get started with Venice's API, either purchase a pro account, stake $VVV to obtain daily inference allotments or fund your account with USD and head over to https://venice.ai/settings/api. Venice hosts state of the art open-source AI models and supports the OpenAI API standard, allowing users to easily interact with the platform. Learn more about the Venice API at https://venice.ai/api.
Change `~/.continue/config.json` to look like the following.
```json title="config.json"
{
"models": [
{
"provider": "venice",
"title": "Autodetect",
"model": "AUTODETECT",
"apiKey": "..."
}
]
}
```
To utilize features offered by the venice API that are not apart of the standard OpenAI API schema, include these as `venice_parameters`
For example, to use models with no system prompt, you can explicitly turn off the feature like so:
```json title="config.json"
{
"completionOptions": {
"venice_parameters": {
"include_venice_system_prompt" : false
},
...
}
}
```
Learn more about available settings [here](https://docs.venice.ai/api-reference/api-spec).

View file

@ -100,6 +100,7 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc
- name: Huggingface TEI Embedder
provider: huggingface-tei
apiBase: http://localhost:8080
apiKey: <YOUR_TEI_API_KEY>
roles: [embed]
```
</TabItem>
@ -108,7 +109,8 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc
{
"embeddingsProvider": {
"provider": "huggingface-tei",
"apiBase": "http://localhost:8080"
"apiBase": "http://localhost:8080",
"apiKey": "<YOUR_TEI_API_KEY>"
}
}
```

View file

@ -11,7 +11,7 @@ The input you provide is included in the prompt.
## Code to Edit
The **entire contents** of each file (the current file for Jetbrains inline Edit, each `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
## Context Providers

View file

@ -20,7 +20,7 @@ Edit is recommended for small, targeted changes, such as
## Highlight code and activate
Highlight the block of code you would like to modify and press <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> to active Edit mode. You can also enter Edit mode by pressing <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> with no code highlighted.
Highlight the block of code you would like to modify and press <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> to active Edit mode. You can also enter Edit mode by pressing <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> with no code highlighted, which will default to editing the current file.
## Describe code changes
@ -48,32 +48,6 @@ You can also reject and accept diffs using the `Reject All` and `Accept All` but
Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor.
**_Add file combobox_**
![edit mode add file combobox](/img/edit-mode-add-files.png)
**_Add all open files dropdown_**
![edit mode add file combobox](/img/edit-mode-add-all-open-files.png)
### Single File Edit
If one file/range is present in `Code to Edit` on submission, Continue will prompt the Edit model and then automatically stream the diff into the editor.
![Edit mode single file diffs](/img/edit-mode-single-file-diff.png)
### Multi-File Edit
If multiple files/ranges are present in `Code to Edit` on submission, Continue will prompt the Edit model to output codeblocks per-file, which the user can then choose to apply and accept/reject independently.
**_Generated Content_**
![Edit mode multi file generated content](/img/edit-mode-multi-file-generation.png)
**_Diffs_**
![Edit mode multi file diffs](/img/edit-mode-multi-file-diffs.png)
## Jetbrains
In Jetbrains, Edit is implemented as an inline popup (see the header GIF example) for single-file edit. Multi-file edit mode is not currently implemented.
In Jetbrains, Edit is implemented as an inline popup. See the header GIF example.

View file

@ -8,33 +8,44 @@ keywords: [config, yaml, configuration, customize, customization]
## Introduction
Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally
Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded
from [the Hub](https://hub.continue.dev/explore/assistants) or locally
- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension
- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to
the extension
- Locally
- in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml`
- in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`.
The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml`
- in your workspace in a `/.continue/assistants` folder, with the same naming convention
:::info
Config YAML replaces [`config.json`](./json-reference.md), which is deprecated. View the **[Migration Guide](./yaml-migration.md)**.
Config YAML replaces [`config.json`](./json-reference.md), which is deprecated. View the \* \*[Migration Guide](./yaml-migration.md)\*\*.
:::
An assistant is made up of:
1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant
2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers.
2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as
models, docs, and context providers.
A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is.
A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In
`config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`),
but only has **ONE** item under whichever block type it is.
Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants).
Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks.
Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing
hub blocks.
### Using Blocks
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev).
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner
can be a user or organization (For example, if you want to use
the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks
are pulled from [https://hub.continue.dev](https://hub.continue.dev).
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other
`uses` clauses or explicit blocks of that type.
:::info
Note that local assistants cannot use blocks that require organization-level secrets.
@ -51,7 +62,9 @@ models:
### Local Blocks
It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally).
It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of
your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home
directory at `~/.continue` (these will automatically be applied globally).
Place your YAML files in the following folders:
@ -69,11 +82,13 @@ Blocks:
- `.continue/data` - for data
- `.continue/mcpServers` - for MCP Servers
You can find many examples of each of these block types on the [Continue Explore Page](https://hub.continue.dev/explore/models)
You can find many examples of each of these block types on
the [Continue Explore Page](https://hub.continue.dev/explore/models)
### Inputs
Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows:
Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use
mustache templating as follows:
```yaml title="Block config.yaml"
name: myprofile/custom-model
@ -157,7 +172,8 @@ The `schema` property specifies the schema version used for the `config.yaml`, e
### `models`
The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing.
The `models` section defines the language models used in your configuration. Models are used for functionalities such as
chat, editing, and summarizing.
**Properties:**
@ -165,11 +181,19 @@ The `models` section defines the language models used in your configuration. Mod
- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`).
- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`).
- `apiBase`: Can be used to override the default API base that is specified per model
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chatTemplate`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [`autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chatTemplate` property must be a valid template name, such as `llama3` or `anthropic`.
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`,
`edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is
not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
provider and model. Supported capabilities include `tool_use` and `image_input`.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
`chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
`autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chatTemplate` property must be a
valid template name, such as `llama3` or `anthropic`.
- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode:
- `baseSystemMessage`: Can be used to override the default system prompt.
- `baseSystemMessage`: Can be used to override the default system prompt for **Chat** mode.
<!-- - `baseAgentSystemMessage`: Can be used to override the default system prompt for **Agent** mode. <!-- This setting is experimental and hence is undocumented. -->
- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings:
- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens.
- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk.
@ -233,7 +257,8 @@ models:
### `context`
The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters.
The `context` section defines context providers, which supply additional information or context to the language models.
Each context provider can be configured with specific parameters.
More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx)
@ -266,13 +291,17 @@ context:
### `rules`
List of rules that the LLM should follow. These are concatenated into the system message for all [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Agent](./agent/how-to-use-it.md) requests. See the [rules deep dive](./customize/deep-dives/rules.md) for details.
List of rules that the LLM should follow. These are concatenated into the system message for
all [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Agent](./agent/how-to-use-it.md) requests.
See the [rules deep dive](./customize/deep-dives/rules.md) for details.
Explicit rules can either be simple text or an object with the following properties:
- `name` (**required**): A display name/title for the rule
- `rule` (**required**): The text content of the rule
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This
can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g.,
`["src/**/*.ts", "tests/**/*.ts"]`).
```yaml title="config.yaml"
rules:
@ -297,7 +326,8 @@ rules:
### `prompts`
A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text.
A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual
prompt text.
```yaml title="config.yaml"
prompts:
@ -320,7 +350,9 @@ List of documentation sites to index.
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
- `maxDepth`: Maximum link depth for crawling. Default `4`
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler.
@ -340,7 +372,8 @@ docs:
<!-- TODO is this correct? -->
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider.
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify
prompts, context, and tool use. Continue supports any MCP server with the MCP context provider.
**Properties:**
@ -373,7 +406,8 @@ Destinations to which [development data](./customize/deep-dives/development-data
- a file URL to a directory in which events will be dumpted to `.jsonl` files
- `schema` (**required**): the schema version of the JSON blobs to be sent
- `events`: an array of event names to include. Defaults to all events if not specified.
- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all`
- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
contents, prompts, and completions. Defaults to `all`
- `apiKey`: api key to be sent with request (Bearer header)
- `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models).

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

View file

@ -5,6 +5,7 @@
},
"extends": ["../../.eslintrc.shared.json"],
"rules": {
"@typescript-eslint/naming-convention": "off"
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "warn"
}
}

View file

@ -231,8 +231,9 @@
"function-network",
"scaleway",
"relace",
"morph",
"ovhcloud",
"morph"
"venice"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)",
@ -280,8 +281,9 @@
"### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings.",
"### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/).",
"### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys).",
"### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard).",
"### OVHcloud AI Endpoints is a serverless inference API that provides access to a curated selection of models (e.g., Llama, Mistral, Qwen, Deepseek). It is designed with security and data privacy in mind and is compliant with GDPR. To get started, create an API key on the OVHcloud [AI Endpoints website](https://endpoints.ai.cloud.ovh.net/). For more information, including pricing, visit the OVHcloud [AI Endpoints product page](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/).",
"### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard)."
"### Venice\n Venice.AI is a privacy-focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data.\nHosted models support the OpenAI API standard, providing seamless integration for users seeking privacy and flexibility.\nTo get started with the Venice API, either purchase a pro account, stake $VVV for daily inference allotments, or fund your account with USD.\nVisit the [API settings page](https://venice.ai/settings/api) or learn more at the [Venice API documentation](https://venice.ai/api)."
],
"type": "string"
},
@ -517,7 +519,8 @@
"xAI",
"kindo",
"scaleway",
"ovhcloud"
"ovhcloud",
"venice"
]
}
},
@ -1764,6 +1767,30 @@
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["venice"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": ["AUTODETECT"]
},
{
"type": "string"
}
]
}
}
}
}
]
},

View file

@ -1,14 +1,15 @@
{
"name": "continue",
"version": "1.1.29",
"version": "1.1.30",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.29",
"version": "1.1.30",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"@continuedev/fetch": "^1.0.3",
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",
@ -107,7 +108,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/fetch": "^1.0.6",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
@ -693,9 +694,9 @@
}
},
"node_modules/@continuedev/config-types": {
"version": "1.0.13",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.13.tgz",
"integrity": "sha512-5Qmy2x58uhW1GYknypFT/7iwxEJSbt8gMgfQReV7d6xjbJ09ISOTki3hIfCilKrTCo0gIY6pzKEfCoQkUTEi6Q==",
"version": "1.0.14",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz",
"integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==",
"dependencies": {
"zod": "^3.23.8"
}

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.29",
"version": "1.1.30",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -383,11 +383,6 @@
"mac": "cmd+i",
"key": "ctrl+i"
},
{
"command": "continue.focusEditWithoutClear",
"mac": "cmd+shift+i",
"key": "ctrl+shift+i"
},
{
"command": "continue.exitEditMode",
"mac": "escape",
@ -666,6 +661,7 @@
"vscode-extension-tester": "^8.10.0"
},
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"@continuedev/fetch": "^1.0.3",
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",

View file

@ -1,12 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
import * as os from "node:os";
import * as fs from "node:fs";
import {
ContextMenuConfig,
ILLM,
ModelInstaller,
RangeInFileWithContents,
} from "core";
import { ContextMenuConfig, ILLM, ModelInstaller } from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
import { ContinueServerClient } from "core/continueServer/stubs/client";
@ -17,10 +12,15 @@ import { walkDirAsync } from "core/indexing/walkDir";
import { isModelInstaller } from "core/llm";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { startLocalOllama } from "core/util/ollamaHelper";
import { getDevDataFilePath } from "core/util/paths";
import {
getConfigJsonPath,
getConfigYamlPath,
getDevDataFilePath,
} from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import readLastLines from "read-last-lines";
import * as vscode from "vscode";
import * as YAML from "yaml";
import {
getAutocompleteStatusBarDescription,
@ -40,7 +40,13 @@ import { Battery } from "./util/battery";
import { getMetaKeyLabel } from "./util/util";
import { VsCodeIde } from "./VsCodeIde";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist";
import {
addCodeToContextFromRange,
addEntireFileToContext,
addHighlightedCodeToContext,
} from "./util/addCode";
import { openEditorAndRevealRange } from "./util/vscode";
let fullScreenPanel: vscode.WebviewPanel | undefined;
@ -63,160 +69,6 @@ function captureCommandTelemetry(
Telemetry.capture(commandName, { isCommandEvent: true, ...properties });
}
function addCodeToContextFromRange(
range: vscode.Range,
webviewProtocol: VsCodeWebviewProtocol,
prompt?: string,
) {
const document = vscode.window.activeTextEditor?.document;
if (!document) {
return;
}
const rangeInFileWithContents = {
filepath: document.uri.toString(),
contents: document.getText(range),
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
prompt,
// Assume `true` since range selection is currently only used for quick actions/fixes
shouldRun: true,
});
}
function getRangeInFileWithContents(
allowEmpty?: boolean,
range?: vscode.Range,
): RangeInFileWithContents | null {
const editor = vscode.window.activeTextEditor;
if (editor) {
const selection = editor.selection;
const filepath = editor.document.uri.toString();
if (range) {
const contents = editor.document.getText(range);
return {
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
filepath,
contents,
};
}
if (selection.isEmpty && !allowEmpty) {
return null;
}
let selectionRange = new vscode.Range(selection.start, selection.end);
const document = editor.document;
// Select the context from the beginning of the selection start line to the selection start position
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
const textBeforeSelectionStart = document.getText(
new vscode.Range(beginningOfSelectionStartLine, selection.start),
);
// If there are only whitespace before the start of the selection, include the indentation
if (textBeforeSelectionStart.trim().length === 0) {
selectionRange = selectionRange.with({
start: beginningOfSelectionStartLine,
});
}
const contents = editor.document.getText(selectionRange);
return {
filepath,
contents,
range: {
start: {
line: selection.start.line,
character: selection.start.character,
},
end: {
line: selection.end.line,
character: selection.end.character,
},
},
};
}
return null;
}
async function addHighlightedCodeToContext(
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const rangeInFileWithContents = getRangeInFileWithContents();
if (rangeInFileWithContents) {
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
}
async function addEntireFileToContext(
uri: vscode.Uri,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(uri);
if (stat.type === vscode.FileType.Directory) {
const files = await vscode.workspace.fs.readDirectory(uri);
for (const [filename, type] of files) {
if (type === vscode.FileType.File) {
addEntireFileToContext(
vscode.Uri.joinPath(uri, filename),
webviewProtocol,
);
}
}
return;
}
// Get the contents of the file
const contents = (await vscode.workspace.fs.readFile(uri)).toString();
const rangeInFileWithContents = {
filepath: uri.toString(),
contents: contents,
range: {
start: {
line: 0,
character: 0,
},
end: {
line: contents.split(os.EOL).length - 1,
character: 0,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
function focusGUI() {
const fullScreenTab = getFullScreenTab();
if (fullScreenTab) {
@ -252,9 +104,10 @@ async function processDiff(
) {
captureCommandTelemetry(`${action}Diff`);
const currentFile = await ide.getCurrentFile();
let newOrCurrentUri = newFileUri;
if (!newOrCurrentUri) {
const currentFile = await ide.getCurrentFile();
newOrCurrentUri = currentFile?.path;
}
if (!newOrCurrentUri) {
@ -269,10 +122,6 @@ async function processDiff(
// Clear vertical diffs depending on action
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
@ -286,8 +135,6 @@ async function processDiff(
});
}
await sidebar.webviewProtocol.request("exitEditMode", undefined);
// Save the file
await ide.saveFile(newOrCurrentUri);
}
@ -538,102 +385,7 @@ const getCommandsMap: (
"continue.focusEdit": async (args?: QuickEditShowParams) => {
captureCommandTelemetry("focusEdit");
focusGUI();
sidebar.webviewProtocol?.request("focusEdit", undefined);
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const existingDiff = verticalDiffManager.getHandlerForFile(
editor.document.fileName,
);
// If there's a diff currently being applied, then we just toggle focus back to the input
if (existingDiff) {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
return;
}
const startFromCharZero = editor.selection.start.with(undefined, 0);
const document = editor.document;
let lastLine, lastChar;
// If the user selected onto a trailing line but didn't actually include any characters in it
// they don't want to include that line, so trim it off.
if (editor.selection.end.character === 0) {
// This is to prevent the rare case that the previous line gets selected when user
// is selecting nothing and the cursor is at the beginning of the line
if (editor.selection.end.line === editor.selection.start.line) {
lastLine = editor.selection.start.line;
} else {
lastLine = editor.selection.end.line - 1;
}
} else {
lastLine = editor.selection.end.line;
}
lastChar = document.lineAt(lastLine).range.end.character;
const endAtCharLast = new vscode.Position(lastLine, lastChar);
const range =
args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast);
editDecorationManager.addDecorations(editor, [range]);
const rangeInFileWithContents = getRangeInFileWithContents(true, range);
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addCodeToEdit",
rangeInFileWithContents,
);
// Un-select the current selection
editor.selection = new vscode.Selection(
editor.selection.anchor,
editor.selection.anchor,
);
}
},
"continue.focusEditWithoutClear": async () => {
captureCommandTelemetry("focusEditWithoutClear");
focusGUI();
sidebar.webviewProtocol?.request("focusEditWithoutClear", undefined);
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const document = editor.document;
const existingDiff = verticalDiffManager.getHandlerForFile(
document.fileName,
);
// If there's a diff currently being applied, then we just toggle focus back to the input
if (existingDiff) {
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
return;
}
const rangeInFileWithContents = getRangeInFileWithContents(false);
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addCodeToEdit",
rangeInFileWithContents,
);
} else {
const contents = document.getText();
sidebar.webviewProtocol?.request("addCodeToEdit", {
filepath: document.uri.toString(),
contents,
});
}
},
"continue.exitEditMode": async () => {
captureCommandTelemetry("exitEditMode");
@ -951,7 +703,7 @@ const getCommandsMap: (
if (core.configHandler.currentProfile?.profileDescription.id) {
core.invoke("config/updateSelectedModel", {
profileId:
core.configHandler.currentProfile?.profileDescription.id,
core.configHandler.currentProfile?.profileDescription.id,
role: "autocomplete",
title: selectedOption,
});
@ -1013,6 +765,35 @@ const getCommandsMap: (
);
}
},
"continue.convertConfigJsonToConfigYaml": async () => {
const configJson = fs.readFileSync(getConfigJsonPath(), "utf-8");
const parsed = JSON.parse(configJson);
const configYaml = convertJsonToYamlConfig(parsed);
const configYamlPath = getConfigYamlPath();
fs.writeFileSync(configYamlPath, YAML.stringify(configYaml));
// Open config.yaml
await openEditorAndRevealRange(
vscode.Uri.file(configYamlPath),
undefined,
undefined,
false,
);
vscode.window
.showInformationMessage(
"Your config.json has been converted to the new config.yaml format. If you need to switch back to config.json, you can delete or rename config.yaml.",
"Read the docs",
)
.then((selection) => {
if (selection === "Read the docs") {
vscode.env.openExternal(
vscode.Uri.parse("https://docs.continue.dev/yaml-migration"),
);
}
});
},
};
};

View file

@ -15,8 +15,10 @@ import {
import { stripImages } from "core/util/messageContent";
import * as vscode from "vscode";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { ApplyManager } from "../apply";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import {
getControlPlaneSessionInfo,
@ -188,6 +190,15 @@ export class VsCodeMessenger {
);
});
});
this.onWebview("edit/addCurrentSelection", async (msg) => {
const verticalDiffManager = await this.verticalDiffManagerPromise;
await addCurrentSelectionToEdit({
args: undefined,
editDecorationManager,
webviewProtocol: this.webviewProtocol,
verticalDiffManager,
});
});
this.onWebview("edit/sendPrompt", async (msg) => {
const prompt = msg.data.prompt;
const { start, end } = msg.data.range.range;
@ -210,39 +221,28 @@ export class VsCodeMessenger {
const fileAfterEdit = await verticalDiffManager.streamEdit({
input: stripImages(prompt),
llm: model,
streamId: "edit",
streamId: EDIT_MODE_STREAM_ID,
range: new vscode.Range(
new vscode.Position(start.line, start.character),
new vscode.Position(end.line, end.character),
),
rules: config.rules,
});
void this.webviewProtocol.request("setEditStatus", {
status: "accepting",
fileAfterEdit,
});
return fileAfterEdit;
});
this.onWebview("edit/exit", async (msg) => {
if (msg.data.shouldFocusEditor) {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
vscode.window.showTextDocument(activeEditor.document);
}
}
this.onWebview("edit/clearDecorations", async (msg) => {
editDecorationManager.clear();
});
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
this.onWebview(messageType, async (msg) => {
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
msg.messageId,
);
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
msg.messageId,
);
});
});

View file

@ -0,0 +1,30 @@
import { getConfigYamlPath } from "core/util/paths";
import * as fs from "fs";
import * as vscode from "vscode";
export class ConfigJsonConverterCodeLensProvider
implements vscode.CodeLensProvider
{
public provideCodeLenses(
document: vscode.TextDocument,
_: vscode.CancellationToken,
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
if (
!document.uri.fsPath.includes(".continue") ||
!document.uri.fsPath.endsWith("config.json")
) {
return [];
}
if (fs.existsSync(getConfigYamlPath())) {
return [];
}
return [
new vscode.CodeLens(new vscode.Range(0, 0, 0, 0), {
title: "config.json is being deprecated. Convert to config.yaml",
command: "continue.convertConfigJsonToConfigYaml",
}),
];
}
}

View file

@ -2,3 +2,5 @@ export { DownloadYamlExtensionCodeLensProvider } from "./DownloadYamlExtensionCo
export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider";
export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider";
export { VerticalDiffCodeLensProvider as VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider";
export { ConfigJsonConverterCodeLensProvider } from "./ConfigJsonConverterCodeLensProvider";

View file

@ -19,6 +19,8 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined;
let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined;
let quickActionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
let configJsonConverterCodeLensDisposable: vscode.Disposable | undefined =
undefined;
let downloadYamlExtensionCodeLensDisposable: vscode.Disposable | undefined =
undefined;
@ -98,6 +100,10 @@ export function registerAllCodeLensProviders(
tutorialCodeLensDisposable.dispose();
}
if (configJsonConverterCodeLensDisposable) {
configJsonConverterCodeLensDisposable.dispose();
}
if (downloadYamlExtensionCodeLensDisposable) {
downloadYamlExtensionCodeLensDisposable.dispose();
}
@ -116,6 +122,11 @@ export function registerAllCodeLensProviders(
new providers.SuggestionsCodeLensProvider(),
);
configJsonConverterCodeLensDisposable = registerCodeLensProvider(
"*",
new providers.ConfigJsonConverterCodeLensProvider(),
);
downloadYamlExtensionCodeLensDisposable = registerCodeLensProvider(
"yaml",
new providers.DownloadYamlExtensionCodeLensProvider(),
@ -131,6 +142,7 @@ export function registerAllCodeLensProviders(
context.subscriptions.push(verticalPerLineCodeLensProvider);
context.subscriptions.push(suggestionsCodeLensDisposable);
context.subscriptions.push(configJsonConverterCodeLensDisposable);
return { verticalDiffCodeLens };
}

View file

@ -0,0 +1,70 @@
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { getRangeInFileWithContents } from "../util/addCode";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import EditDecorationManager from "./EditDecorationManager";
import { QuickEditShowParams } from "./QuickEditQuickPick";
export async function addCurrentSelectionToEdit({
webviewProtocol,
verticalDiffManager,
args,
editDecorationManager,
}: {
webviewProtocol: VsCodeWebviewProtocol;
verticalDiffManager: VerticalDiffManager;
args: QuickEditShowParams | undefined;
editDecorationManager: EditDecorationManager;
}) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const existingDiff = verticalDiffManager.getHandlerForFile(
editor.document.fileName,
);
// If there's a diff currently being applied, then we just toggle focus back to the input
if (existingDiff) {
webviewProtocol?.request("focusContinueInput", undefined);
return;
}
const startFromCharZero = editor.selection.start.with(undefined, 0);
const document = editor.document;
let lastLine, lastChar;
// If the user selected onto a trailing line but didn't actually include any characters in it
// they don't want to include that line, so trim it off.
if (editor.selection.end.character === 0) {
// This is to prevent the rare case that the previous line gets selected when user
// is selecting nothing and the cursor is at the beginning of the line
if (editor.selection.end.line === editor.selection.start.line) {
lastLine = editor.selection.start.line;
} else {
lastLine = editor.selection.end.line - 1;
}
} else {
lastLine = editor.selection.end.line;
}
lastChar = document.lineAt(lastLine).range.end.character;
const endAtCharLast = new vscode.Position(lastLine, lastChar);
const range =
args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast);
editDecorationManager.clear();
editDecorationManager.addDecorations(editor, [range]);
const rangeInFileWithContents = getRangeInFileWithContents(true, range);
if (rangeInFileWithContents) {
webviewProtocol?.request("setCodeToEdit", rangeInFileWithContents);
// Un-select the current selection
editor.selection = new vscode.Selection(
editor.selection.anchor,
editor.selection.anchor,
);
}
}

View file

@ -0,0 +1,158 @@
import { RangeInFileWithContents } from "core";
import * as os from "node:os";
import * as vscode from "vscode";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
export function getRangeInFileWithContents(
allowEmpty?: boolean,
range?: vscode.Range,
): RangeInFileWithContents | null {
const editor = vscode.window.activeTextEditor;
if (editor) {
const selection = editor.selection;
const filepath = editor.document.uri.toString();
if (range) {
const contents = editor.document.getText(range);
return {
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
filepath,
contents,
};
}
if (selection.isEmpty && !allowEmpty) {
return null;
}
let selectionRange = new vscode.Range(selection.start, selection.end);
const document = editor.document;
// Select the context from the beginning of the selection start line to the selection start position
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
const textBeforeSelectionStart = document.getText(
new vscode.Range(beginningOfSelectionStartLine, selection.start),
);
// If there are only whitespace before the start of the selection, include the indentation
if (textBeforeSelectionStart.trim().length === 0) {
selectionRange = selectionRange.with({
start: beginningOfSelectionStartLine,
});
}
const contents = editor.document.getText(selectionRange);
return {
filepath,
contents,
range: {
start: {
line: selection.start.line,
character: selection.start.character,
},
end: {
line: selection.end.line,
character: selection.end.character,
},
},
};
}
return null;
}
export async function addHighlightedCodeToContext(
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const rangeInFileWithContents = getRangeInFileWithContents();
if (rangeInFileWithContents) {
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
}
export async function addEntireFileToContext(
uri: vscode.Uri,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(uri);
if (stat.type === vscode.FileType.Directory) {
const files = await vscode.workspace.fs.readDirectory(uri);
for (const [filename, type] of files) {
if (type === vscode.FileType.File) {
addEntireFileToContext(
vscode.Uri.joinPath(uri, filename),
webviewProtocol,
);
}
}
return;
}
// Get the contents of the file
const contents = (await vscode.workspace.fs.readFile(uri)).toString();
const rangeInFileWithContents = {
filepath: uri.toString(),
contents: contents,
range: {
start: {
line: 0,
character: 0,
},
end: {
line: contents.split(os.EOL).length - 1,
character: 0,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
export function addCodeToContextFromRange(
range: vscode.Range,
webviewProtocol: VsCodeWebviewProtocol,
prompt?: string,
) {
const document = vscode.window.activeTextEditor?.document;
if (!document) {
return;
}
const rangeInFileWithContents = {
filepath: document.uri.toString(),
contents: document.getText(range),
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
prompt,
// Assume `true` since range selection is currently only used for quick actions/fixes
shouldRun: true,
});
}

View file

@ -12,7 +12,8 @@
// "plugin:react/recommended"
],
"rules": {
"@typescript-eslint/naming-convention": "off"
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "warn"
},
"overrides": [
{

15
gui/package-lock.json generated
View file

@ -94,7 +94,7 @@
"tailwindcss": "^3.2.7",
"typescript": "^5.6.3",
"typescript-eslint": "^8.16.0",
"vite": "^6.3.2",
"vite": "^6.3.4",
"vitest": "^2.1.3"
},
"engines": {
@ -111,7 +111,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/fetch": "^1.0.6",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
@ -12374,17 +12374,18 @@
}
},
"node_modules/vite": {
"version": "6.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.2.tgz",
"integrity": "sha512-ZSvGOXKGceizRQIZSz7TGJ0pS3QLlVY/9hwxVh17W3re67je1RKYzFHivZ/t0tubU78Vkyb9WnHPENSBCzbckg==",
"version": "6.3.4",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.4.tgz",
"integrity": "sha512-BiReIiMS2fyFqbqNT/Qqt4CVITDU9M9vE+DKcVAsB+ZV0wvTKd+3hMbkpxz1b+NmEDMegpVbisKiAZOnvO92Sw==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.3",
"fdir": "^6.4.4",
"picomatch": "^4.0.2",
"postcss": "^8.5.3",
"rollup": "^4.34.9",
"tinyglobby": "^0.2.12"
"tinyglobby": "^0.2.13"
},
"bin": {
"vite": "bin/vite.js"

View file

@ -102,7 +102,7 @@
"tailwindcss": "^3.2.7",
"typescript": "^5.6.3",
"typescript-eslint": "^8.16.0",
"vite": "^6.3.2",
"vite": "^6.3.4",
"vitest": "^2.1.3"
},
"engine-strict": true,

BIN
gui/public/logos/venice.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View file

@ -3,7 +3,7 @@ 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";
import ParallelListeners from "./hooks/ParallelListeners";
import ConfigPage from "./pages/config";
import ErrorPage from "./pages/error";
import Chat from "./pages/gui";
@ -42,14 +42,9 @@ const router = createMemoryRouter([
]);
/*
Prevents entire app from rerendering continuously with useSetup in App
TODO - look into a more redux-esque way to do this
ParallelListeners prevents entire app from rerendering on any change in the listeners,
most of which interact with redux etc.
*/
export function SetupListeners() {
useSetup();
return <></>;
}
function App() {
return (
<VscThemeProvider>
@ -58,7 +53,7 @@ function App() {
<RouterProvider router={router} />
</SubmenuContextProvidersProvider>
</MainEditorProvider>
<SetupListeners />
<ParallelListeners />
</VscThemeProvider>
);
}

View file

@ -2,24 +2,26 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAppSelector } from "../redux/hooks";
import { selectIsSingleRangeEditOrInsertion } from "../redux/slices/sessionSlice";
import { getMetaKeyLabel } from "../util";
import { useFontSize } from "./ui/font";
export interface AcceptRejectAllButtonsProps {
pendingApplyStates: ApplyState[];
applyStates: ApplyState[];
onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void;
}
export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff";
export default function AcceptRejectAllButtons({
pendingApplyStates,
applyStates,
onAcceptOrReject,
}: AcceptRejectAllButtonsProps) {
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const ideMessenger = useContext(IdeMessengerContext);
const isSingleRangeEdit = useAppSelector(selectIsSingleRangeEditOrInsertion);
const tinyFont = useFontSize(-3);
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {
@ -33,39 +35,50 @@ export default function AcceptRejectAllButtons({
}
}
if (!pendingApplyStates.length) {
return null;
}
return (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<div className="flex flex-row items-center justify-evenly gap-2 p-1 px-3">
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("rejectDiff")}
data-testid="edit-reject-button"
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-600" />
{isSingleRangeEdit ? (
<span>Reject ({getMetaKeyLabel()}⇧⌫)</span>
) : (
<>
<span className="sm:hidden">Reject</span>
<span className="max-sm:hidden md:hidden">Reject all</span>
<span className="max-md:hidden">Reject all changes</span>
</>
)}
<div className="flex flex-row items-center gap-1">
<XMarkIcon className="h-4 w-4 text-red-600" />
<span>Reject</span>
<span className="xs:inline-block hidden">All</span>
</div>
<span
className="xs:inline-block hidden text-gray-400"
style={{
fontSize: tinyFont,
}}
>
({getMetaKeyLabel()}⇧⌫)
</span>
</button>
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("acceptDiff")}
data-testid="edit-accept-button"
>
<CheckIcon className="mr-1 h-4 w-4 text-green-600" />
{isSingleRangeEdit ? (
<span>Accept ({getMetaKeyLabel()}⇧⏎)</span>
) : (
<>
<span className="sm:hidden">Accept</span>
<span className="max-sm:hidden md:hidden">Accept all</span>
<span className="max-md:hidden">Accept all changes</span>
</>
)}
<div className="flex flex-row items-center gap-1">
<CheckIcon className="h-4 w-4 text-green-600" />
<span>Accept</span>
<span className="xs:inline-block hidden">All</span>
</div>
<span
className="xs:inline-block hidden text-gray-400"
style={{
fontSize: tinyFont,
}}
>
({getMetaKeyLabel()}⇧⏎)
</span>
</button>
</div>
);

View file

@ -1,66 +0,0 @@
import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline";
import { useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch } from "../../redux/hooks";
import { addCodeToEdit } from "../../redux/slices/sessionSlice";
import {
Listbox,
ListboxButton,
ListboxOption,
ListboxOptions,
} from "../ui/Listbox";
export interface AddFileButtonProps {
onClick: () => void;
}
export default function AddFileButton({ onClick }: AddFileButtonProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useAppDispatch();
async function handleAddAllOpenFiles() {
const openFiles = await ideMessenger.ide.getOpenFiles();
const filesData = await Promise.all(
openFiles.map(async (filepath) => {
const contents = await ideMessenger.ide.readFile(filepath);
return { filepath, contents };
}),
);
dispatch(addCodeToEdit(filesData));
}
return (
<Listbox onChange={handleAddAllOpenFiles}>
<div className="relative">
<ListboxButton
ref={buttonRef}
className="bg-vsc-editor-background m-0 rounded-md p-0"
>
<div
className="flex h-5 items-center justify-center gap-1 hover:brightness-125"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onClick();
}}
>
<PlusIcon className="text-vsc-foreground inline h-2.5 w-2.5 px-1 brightness-75" />
<span className="text-vsc-foreground xs:block hidden text-[10px] brightness-75">
Add file
</span>
</div>
<div className="border-lightgray/50 h-4 w-[1px] border-y-0 border-l-0 border-r border-solid" />
<ChevronDownIcon className="text-vsc-foreground h-2.5 w-2.5 cursor-pointer px-1 brightness-75 hover:brightness-125" />
</ListboxButton>
<ListboxOptions className="bg-vsc-editor-background" anchor="top end">
<ListboxOption value="addAllFiles">Add all open files</ListboxOption>
</ListboxOptions>
</div>
</Listbox>
);
}

View file

@ -1,143 +0,0 @@
import { ContextSubmenuItemWithProvider } from "core";
import { useEffect, useRef, useState } from "react";
import {
Combobox,
ComboboxButton,
ComboboxInput,
ComboboxOption,
ComboboxOptions,
} from "../../components/ui/Combobox";
import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders";
import { useAppSelector } from "../../redux/hooks";
import FileIcon from "../FileIcon";
export interface AddFileComboboxProps {
onSelect: (filepaths: string[]) => void | Promise<void>;
onEscape: () => void | Promise<void>;
}
export default function AddFileCombobox({
onSelect,
onEscape,
}: AddFileComboboxProps) {
const [query, setQuery] = useState("");
const [selectedFiles, setSelectedFiles] = useState<
ContextSubmenuItemWithProvider[]
>([]);
const inputRef = useRef<HTMLInputElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const { getSubmenuContextItems } = useSubmenuContextProviders();
const allFiles = getSubmenuContextItems("file", "");
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const remainingFiles = allFiles.filter(
(file) => !codeToEdit.find((code) => code.filepath === file.id),
);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
useEffect(() => {
// update selectedFiles showing only the files that are in codeToEdit
setSelectedFiles(
(prevSelectedFiles) =>
prevSelectedFiles.filter(
(file) =>
codeToEdit.findIndex((code) => code.filepath === file.id) !== -1,
),
);
}, [codeToEdit]);
const filteredFiles =
query === ""
? remainingFiles
: remainingFiles.filter((file) =>
file.title.toLowerCase().includes(query.toLowerCase()),
);
return (
<div className="pb-2 pl-3.5 pr-2">
<Combobox
multiple
value={selectedFiles}
onChange={(files) => {
setSelectedFiles(files);
void onSelect(files.map((file) => file.id));
buttonRef.current?.click();
setQuery("");
}}
>
{({ open }) => (
<div className="relative">
<ComboboxButton className="hidden" ref={buttonRef} />
<ComboboxInput
value={query}
ref={inputRef}
onClick={() => {
if (!open) {
buttonRef.current?.click();
}
}}
onFocus={() => {
buttonRef.current?.click();
}}
className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 text-xs focus:outline-none"
onChange={(event) => setQuery(event.target.value)}
placeholder="Type to search files..."
onKeyDown={(e) => {
if (e.key === "Escape" && !open) {
void onEscape();
}
}}
/>
<ComboboxOptions className="no-scrollbar bg-vsc-editor-background border-lightgray/50 absolute left-0 right-0 z-50 mt-1 max-h-60 overflow-y-auto overflow-x-hidden rounded-md border border-solid px-1 py-0 pl-0 pr-5 shadow-lg focus:outline-none">
{filteredFiles.length > 0 ? (
filteredFiles.map((file) => (
<ComboboxOption
key={file.id}
value={file}
className={({ active }) =>
`relative flex w-full cursor-pointer px-2 py-1 text-left text-xs ${
active
? "bg-list-active text-list-active-foreground"
: ""
}`
}
>
{({ active, selected }) => (
<div className="group flex w-full min-w-0 items-center gap-1">
<div className="flex min-w-0 flex-1 items-center gap-1">
<FileIcon
height="20px"
width="20px"
filename={file.title}
/>
<span className="truncate">{file.title}</span>
</div>
<span
className={`text-lightgray max-w-[30%] truncate ${
active || selected ? "visible" : "invisible"
} group-hover:visible`}
>
{file.description}
</span>
</div>
)}
</ComboboxOption>
))
) : (
<div className="text-list-active-foreground px-2 py-1 text-xs">
No results
</div>
)}
</ComboboxOptions>
</div>
)}
</Combobox>
</div>
);
}

View file

@ -1,109 +0,0 @@
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline";
import type { CodeToEdit } from "core";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import {
addCodeToEdit,
removeCodeToEdit,
} from "../../redux/slices/sessionSlice";
import AddFileButton from "./AddFileButton";
import AddFileCombobox from "./AddFileCombobox";
import CodeToEditListItem from "./CodeToEditListItem";
export default function CodeToEditCard() {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const [showAddFileCombobox, setShowAddFileCombobox] = useState(false);
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const itemCount =
codeToEdit.length === 0
? ""
: codeToEdit.length === 1
? "(1 item)"
: `(${codeToEdit.length} items)`;
function onDelete(rif: CodeToEdit) {
dispatch(removeCodeToEdit(rif));
}
async function onClickFilename(code: CodeToEdit) {
if ("range" in code) {
await ideMessenger.ide.showLines(
code.filepath,
code.range.start.line,
code.range.end.line,
);
} else {
await ideMessenger.ide.openFile(code.filepath);
}
}
async function onSelectFilesToAdd(uris: string[]) {
const filePromises = uris.map(async (uri) => {
const contents = await ideMessenger.ide.readFile(uri);
return { contents, filepath: uri };
});
const fileResults = await Promise.all(filePromises);
for (const file of fileResults) {
dispatch(addCodeToEdit(file));
}
}
return (
<div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg p-1">
<div className="text-lightgray flex items-center justify-between gap-1.5 py-1.5 pl-3 pr-2 text-xs">
<div className="flex items-center gap-1">
<span>Code to edit</span>
<span className="hidden sm:inline">{itemCount}</span>
</div>
<AddFileButton onClick={() => setShowAddFileCombobox(true)} />
</div>
{codeToEdit.length > 0 ? (
<ul className="no-scrollbar my-0 mb-1.5 max-h-[50vh] list-outside list-none overflow-y-auto pl-0">
{codeToEdit.map((code, i) => (
<CodeToEditListItem
key={code.filepath + i}
code={code}
onDelete={onDelete}
onClickFilename={onClickFilename}
/>
))}
</ul>
) : (
!showAddFileCombobox && (
<div
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground -mt-0.5 flex cursor-pointer items-center justify-center gap-1 rounded py-1 text-center text-xs transition-colors hover:bg-opacity-20"
onClick={() => setShowAddFileCombobox(true)}
>
<PlusIcon className="h-3.5 w-3.5" />
<span>Add a file to get started</span>
</div>
)
)}
{showAddFileCombobox && (
<div className="mr-2 flex items-center py-1">
<div className="flex-grow">
<AddFileCombobox
onSelect={onSelectFilesToAdd}
onEscape={() => setShowAddFileCombobox(false)}
/>
</div>
<XMarkIcon
onClick={() => {
setShowAddFileCombobox(false);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground mb-2 h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
</div>
)}
</div>
);
}

View file

@ -1,142 +0,0 @@
import {
ChevronDownIcon,
ChevronRightIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { CodeToEdit } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import {
getLastNUriRelativePathParts,
getUriPathBasename,
} from "core/util/uri";
import { useState } from "react";
import styled from "styled-components";
import FileIcon from "../FileIcon";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
export interface CodeToEditListItemProps {
code: CodeToEdit;
onDelete: (codeToEdit: CodeToEdit) => void | Promise<void>;
onClickFilename: (codeToEdit: CodeToEdit) => void | Promise<void>;
}
const NoPaddingWrapper = styled.div`
> * {
margin: 0 !important;
padding: 0 !important;
}
pre {
margin: 0 !important;
padding: 0px 0px 0px 10px !important;
}
`;
export default function CodeToEditListItem({
code,
onDelete,
onClickFilename,
}: CodeToEditListItemProps) {
const [showCodeSnippet, setShowCodeSnippet] = useState(false);
const fileName = getUriPathBasename(code.filepath);
const last2Parts = getLastNUriRelativePathParts(
window.workspacePaths ?? [],
code.filepath,
2,
);
let isInsertion = false;
let title = fileName;
if ("range" in code) {
const start = code.range.start.line + 1;
const end = code.range.end.line + 1;
isInsertion = start === end;
title += isInsertion
? ` - Inserting at line ${start}`
: ` (${start} - ${end})`;
}
const source =
"```" +
getMarkdownLanguageTagForFile(code.filepath) +
"\n" +
code.contents +
"\n" +
"```";
return (
<li
className="group flex cursor-pointer flex-col"
onClick={() => {
if (!isInsertion) {
setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet);
}
}}
>
<div
className={`hover:bg-lightgray hover:text-vsc-foreground flex items-center justify-between rounded px-2 py-0.5 transition-colors hover:bg-opacity-20 ${showCodeSnippet && "text-vsc-foreground bg-lightgray bg-opacity-20"}`}
>
<div className="flex w-4/5 min-w-0 items-center gap-0.5">
<FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
<div className="flex min-w-0 gap-1.5">
<span
className="flex-shrink-0 text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
void onClickFilename(code);
}}
>
{title}
</span>
<span className="text-lightgray invisible flex-grow truncate text-xs group-hover:visible">
{last2Parts}
</span>
</div>
</div>
<div className="invisible flex items-center group-hover:visible">
<div className={`flex items-center ${isInsertion ? "hidden" : ""}`}>
{showCodeSnippet ? (
<ChevronDownIcon
onClick={(e) => {
e.stopPropagation();
setShowCodeSnippet(false);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
) : (
<ChevronRightIcon
onClick={(e) => {
e.stopPropagation();
setShowCodeSnippet(true);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
)}
</div>
<div className="flex items-center">
<XMarkIcon
onClick={(e) => {
e.stopPropagation();
void onDelete(code);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
</div>
</div>
</div>
{showCodeSnippet && (
<div className="max-h-[25vh] overflow-y-auto px-1 py-2">
<NoPaddingWrapper>
<StyledMarkdownPreview source={source} />
</NoPaddingWrapper>
</div>
)}
</li>
);
}

View file

@ -1 +0,0 @@
export { default } from "./CodeToEditCard";

View file

@ -6,6 +6,7 @@ import { useNavigate } from "react-router-dom";
import { Input } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import {
deleteSession,
getSession,
@ -68,6 +69,7 @@ export function HistoryTableRow({
data-testid={`history-row-${index}`}
className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3"
onClick={async () => {
await dispatch(exitEditMode({}));
if (sessionMetadata.sessionId !== currentSessionId) {
await dispatch(
loadSession({

View file

@ -1,21 +1,16 @@
import { useEffect } from "react";
import { useContext, useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import styled from "styled-components";
import { CustomScrollbarDiv, defaultBorderRadius } from ".";
import { AuthProvider } from "../context/Auth";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { LocalStorageProvider } from "../context/LocalStorage";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { focusEdit, setEditStatus } from "../redux/slices/editModeState";
import {
addCodeToEdit,
newSession,
selectIsInEditMode,
setMode,
} from "../redux/slices/sessionSlice";
import { setCodeToEdit } from "../redux/slices/editModeState";
import { setShowDialog } from "../redux/slices/uiSlice";
import { exitEditMode } from "../redux/thunks";
import { loadLastSession, saveCurrentSession } from "../redux/thunks/session";
import { enterEditMode, exitEditMode } from "../redux/thunks/editMode";
import { saveCurrentSession } from "../redux/thunks/session";
import { fontSize, isMetaEquivalentKeyPressed } from "../util";
import { incrementFreeTrialCount } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
@ -23,6 +18,7 @@ import { FatalErrorIndicator } from "./config/FatalErrorNotice";
import TextDialog from "./dialogs";
import Footer from "./Footer";
import { LumpProvider } from "./mainInput/Lump/LumpContext";
import { useMainEditor } from "./mainInput/TipTapEditor";
import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard";
import OSRContextMenu from "./OSRContextMenu";
import PostHogPageView from "./PosthogPageView";
@ -46,24 +42,30 @@ const Layout = () => {
const location = useLocation();
const dispatch = useAppDispatch();
const onboardingCard = useOnboardingCard();
const ideMessenger = useContext(IdeMessengerContext);
const { mainEditor } = useMainEditor();
const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);
const showDialog = useAppSelector((state) => state.ui.showDialog);
const mode = useAppSelector((state) => state.session.mode);
useWebviewListener(
"newSession",
async () => {
navigate(ROUTES.HOME);
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
dispatch(exitEditMode());
if (mode === "edit") {
await dispatch(exitEditMode({}));
} else {
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
}
},
[],
[mode],
);
useWebviewListener(
@ -79,15 +81,22 @@ const Layout = () => {
"focusContinueInputWithNewSession",
async () => {
navigate(ROUTES.HOME);
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
dispatch(exitEditMode());
if (mode === "edit") {
await dispatch(
exitEditMode({
openNewSession: true,
}),
);
} else {
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
}
},
[location.pathname],
[location.pathname, mode],
location.pathname === ROUTES.HOME,
);
@ -138,66 +147,31 @@ const Layout = () => {
useWebviewListener(
"focusEdit",
async () => {
await dispatch(
saveCurrentSession({
openNewSession: false,
// Because this causes a lag before Edit mode is focused. TODO just have that happen in background
generateTitle: false,
}),
);
dispatch(newSession());
dispatch(focusEdit());
dispatch(setMode("edit"));
await ideMessenger.request("edit/addCurrentSelection", undefined);
await dispatch(enterEditMode({}));
mainEditor?.commands.focus();
},
[],
[ideMessenger, mainEditor],
);
useWebviewListener(
"focusEditWithoutClear",
async () => {
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
dispatch(focusEdit());
dispatch(setMode("edit"));
},
[],
);
useWebviewListener(
"addCodeToEdit",
"setCodeToEdit",
async (payload) => {
dispatch(addCodeToEdit(payload));
},
[navigate],
);
useWebviewListener(
"setEditStatus",
async ({ status, fileAfterEdit }) => {
dispatch(setEditStatus({ status, fileAfterEdit }));
dispatch(
setCodeToEdit({
codeToEdit: payload,
}),
);
},
[],
);
const isInEditMode = useAppSelector(selectIsInEditMode);
useWebviewListener(
"exitEditMode",
async () => {
if (!isInEditMode) {
return;
}
dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
await dispatch(exitEditMode({}));
},
[isInEditMode],
[],
);
useEffect(() => {

View file

@ -12,9 +12,9 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch } from "../../../redux/hooks";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import { updateSelectedModelByRole } from "../../../redux/thunks";
import OllamaModelDownload from "../components/OllamaModelDownload";
import { OllamaStatus } from "../components/OllamaStatus";
import { useSubmitOnboarding } from "../hooks";
import OllamaModelDownload from "./OllamaModelDownload";
import { OllamaStatus } from "./OllamaStatus";
const OLLAMA_CHECK_INTERVAL_MS = 3000;

View file

@ -5,8 +5,8 @@ import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
import Alert from "../../gui/Alert";
import { ReusableCard } from "../../ReusableCard";
import { TabTitle } from "../components/OnboardingCardTabs";
import OnboardingLocalTab from "../components/OnboardingLocalTab";
import { useOnboardingCard } from "../hooks";
import OnboardingLocalTab from "../tabs/OnboardingLocalTab";
import MainTab from "./tabs/main";
export interface OnboardingCardState {

View file

@ -1,3 +1,3 @@
export { default as Local } from "../components/OnboardingLocalTab";
export { default as Best } from "./OnboardingBestTab";
export { default as Local } from "./OnboardingLocalTab";
export { default as Quickstart } from "./OnboardingQuickstartTab";

View file

@ -1,87 +0,0 @@
import { ChatHistoryItem } from "core";
import { renderChatMessage } from "core/util/messageContent";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import { loadLastSession } from "../../redux/thunks/session";
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
import FeedbackButtons from "../FeedbackButtons";
import { CopyIconButton } from "../gui/CopyIconButton";
export interface EditActionsProps {
index: number;
item: ChatHistoryItem;
}
export default function EditActions({ index, item }: EditActionsProps) {
// const curCheckpointIndex = useSelector(
// (store: RootState) => store.state.curCheckpointIndex,
// );
const dispatch = useAppDispatch();
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const applyStates = useAppSelector(
(state) => state.session.codeBlockApplyStates.states,
);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const hasClosedAllStreams = applyStates.every(
(state) => state.status === "closed",
);
// const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex;
const hasPendingApplies = pendingApplyStates.length > 0;
if (isStreaming) return null;
return (
<div
className={`mx-2 mb-2 mt-2 flex h-7 items-center justify-between pb-0 text-xs text-gray-400`}
>
<div className="flex-1" />
{/* {isCurCheckpoint && (
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons pendingApplyStates={pendingApplyStates} />
)}
{hasClosedAllStreams && <UndoAndRedoButtons />}
</div>
)} */}
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
}
}}
/>
)}
{/* {hasClosedAllStreams && <UndoAndRedoButtons />} */}
</div>
<div className="flex flex-1 justify-end">
<CopyIconButton
tabIndex={-1}
text={renderChatMessage(item.message)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<FeedbackButtons item={item} />
</div>
</div>
);
}

View file

@ -1,12 +1,9 @@
import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { renderChatMessage } from "core/util/messageContent";
import { useAppSelector } from "../../redux/hooks";
import { selectIsInEditMode } from "../../redux/slices/sessionSlice";
import FeedbackButtons from "../FeedbackButtons";
import { CopyIconButton } from "../gui/CopyIconButton";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import EditActions from "./EditActions";
export interface ResponseActionsProps {
isTruncated: boolean;
@ -23,12 +20,6 @@ export default function ResponseActions({
isTruncated,
onDelete,
}: ResponseActionsProps) {
const isInEditMode = useAppSelector(selectIsInEditMode);
if (isInEditMode) {
return <EditActions index={index} item={item} />;
}
return (
<div className="mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs text-gray-400">
{isTruncated && (

View file

@ -1,62 +0,0 @@
import { useDispatch } from "react-redux";
import {
ArrowUturnLeftIcon,
ArrowUturnRightIcon,
} from "@heroicons/react/24/outline";
import { setCurCheckpointIndex } from "../../redux/slices/sessionSlice";
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
export default function UndoAndRedoButtons() {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((store) => store.session.history);
const curCheckpointIndex = useAppSelector(
(store) => store.session.curCheckpointIndex,
);
const shouldRenderRedo = false; // curCheckpointIndex !== checkpoints.length - 1;
async function handleUndoOrRedo(type: "undo" | "redo") {
const checkpointIndex = Math.max(
0,
type === "undo" ? curCheckpointIndex - 1 : curCheckpointIndex + 1,
);
const checkpoint = history[checkpointIndex]?.checkpoint ?? {};
for (const [filepath, cachedFileContent] of Object.entries(checkpoint)) {
ideMessenger.post("overwriteFile", {
filepath,
prevFileContent: cachedFileContent,
});
}
dispatch(setCurCheckpointIndex(checkpointIndex));
}
return (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleUndoOrRedo("undo")}
>
<ArrowUturnLeftIcon className="mr-2 h-3.5 w-3.5" />
Undo changes
</button>
{shouldRenderRedo && (
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleUndoOrRedo("redo")}
>
<ArrowUturnRightIcon className="mr-2 h-3.5 w-3.5" />
Redo changes
</button>
)}
</div>
);
}

View file

@ -11,10 +11,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useIdeMessengerRequest } from "../../../hooks";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { useAppSelector } from "../../../redux/hooks";
import {
selectApplyStateByStreamId,
selectIsInEditMode,
} from "../../../redux/slices/sessionSlice";
import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice";
import { getFontSize } from "../../../util";
import { isTerminalCodeBlock } from "../utils";
import { ApplyActions } from "./ApplyActions";
@ -74,10 +71,7 @@ export function StepContainerPreToolbar({
disableManualApply,
}: StepContainerPreToolbarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const isInEditMode = useAppSelector(selectIsInEditMode);
const [isExpanded, setIsExpanded] = useState(
expanded ?? (isInEditMode ? false : true),
);
const [isExpanded, setIsExpanded] = useState(expanded ?? true);
const [relativeFilepathUri, setRelativeFilepathUri] = useState<string | null>(
null,

View file

@ -1,15 +1,12 @@
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { OnboardingCard } from "../OnboardingCard";
import { PlatformOnboardingCard } from "../OnboardingCard/platform/PlatformOnboardingCard";
function FreeTrialOverDialog() {
const dispatch = useDispatch();
const history = useAppSelector((store) => store.session.history);
const usePlatform = useAppSelector(selectUseHub);
useEffect(() => {
if (history.length === 0) {
@ -20,11 +17,7 @@ function FreeTrialOverDialog() {
return (
<div className="flex-1">
{usePlatform ? (
<PlatformOnboardingCard isDialog />
) : (
<OnboardingCard isDialog />
)}
<PlatformOnboardingCard isDialog />
</div>
);
}

View file

@ -0,0 +1,180 @@
import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { CodeToEdit } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import { getUriPathBasename } from "core/util/uri";
import { useContext, useMemo, useState } from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { clearCodeToEdit } from "../../redux/slices/editModeState";
import { getMetaKeyLabel } from "../../util";
import FileIcon from "../FileIcon";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useFontSize } from "../ui/font";
const NoPaddingWrapper = styled.div`
> * {
margin: 0 !important;
padding: 0 !important;
}
pre {
margin: 0 !important;
padding: 0px 0px 0px 10px !important;
}
`;
interface CodeToEditItemProps {
code: CodeToEdit;
}
function CodeToEditItem({ code }: CodeToEditItemProps) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const [showCodeSnippet, setShowCodeSnippet] = useState(false);
function onDelete() {
dispatch(clearCodeToEdit());
ideMessenger.post("edit/clearDecorations", undefined);
}
const fileName = getUriPathBasename(code.filepath);
let isInsertion = false;
let title = fileName;
if ("range" in code) {
const start = code.range.start.line + 1;
const end = code.range.end.line + 1;
isInsertion = start === end;
title += isInsertion
? ` - Inserting at line ${start}`
: ` (${start} - ${end})`;
}
const source =
"```" +
getMarkdownLanguageTagForFile(code.filepath) +
"\n" +
code.contents +
"\n" +
"```";
async function onClickFilename() {
if ("range" in code) {
await ideMessenger.ide.showLines(
code.filepath,
code.range.start.line,
code.range.end.line,
);
} else {
await ideMessenger.ide.openFile(code.filepath);
}
}
const smallFont = useFontSize(-3);
const iconClass =
"text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20";
return (
<div className="flex flex-col gap-1 py-0.5">
<div className="group flex flex-row items-center justify-start gap-1.5 px-1">
<span
className="hidden flex-shrink-0 pl-2 font-semibold text-gray-400 sm:flex"
style={{
fontSize: smallFont,
}}
>
Code to edit
</span>
{/* <CodeBracketIcon className="h-3 w-3 flex-shrink-0 text-gray-400 sm:hidden" /> */}
<div
className={`hover:bg-lightgray flex flex-1 cursor-pointer items-center justify-between rounded transition-colors hover:bg-opacity-20 ${showCodeSnippet && "bg-lightgray bg-opacity-20"}`}
onClick={() => {
if (!isInsertion) {
setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet);
}
}}
>
<div className="flex items-center gap-0.5">
<FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
<span
className="line-clamp-1 text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
void onClickFilename();
}}
>
{title}
</span>
</div>
<div className="invisible flex items-center group-hover:visible">
<ChevronRightIcon
onClick={(e) => {
e.stopPropagation();
setShowCodeSnippet((val) => !val);
}}
className={`text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20 ${showCodeSnippet ? "rotate-90" : ""} ${isInsertion ? "hidden" : ""}`}
/>
<div className="flex items-center">
<XMarkIcon
onClick={(e) => {
e.stopPropagation();
void onDelete();
}}
className={iconClass}
/>
</div>
</div>
</div>
</div>
{showCodeSnippet && (
<div className="!m-0 max-h-48 overflow-y-auto !p-0">
<NoPaddingWrapper>
<StyledMarkdownPreview source={source} />
</NoPaddingWrapper>
</div>
)}
</div>
);
}
export default function CodeToEditCard() {
// Array from previous multi-file edit
const codeToEditArray = useAppSelector(
(state) => state.editModeState.codeToEdit,
);
const codeToEdit = useMemo(() => {
return codeToEditArray[0];
}, [codeToEditArray]);
const metaKeyLabel = useMemo(() => {
return getMetaKeyLabel();
}, []);
const tinyFont = useFontSize(-3);
return (
<div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg py-1">
{codeToEdit ? (
<CodeToEditItem code={codeToEdit} />
) : (
<>
<span
className="text-balance px-3 text-center font-semibold text-gray-400"
style={{
fontSize: tinyFont,
}}
>
{`To edit code, highlight it and press `}
<kbd>{metaKeyLabel}</kbd> <kbd>I</kbd>
</span>
</>
)}
</div>
);
}

View file

@ -11,7 +11,6 @@ import { Lump } from "./Lump";
import { TipTapEditor } from "./TipTapEditor";
interface ContinueInputBoxProps {
isEditMode?: boolean;
isLastUserInput: boolean;
isMainInput?: boolean;
onEnter: (
@ -82,36 +81,40 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const availableContextProviders = useAppSelector(
(state) => state.config.config.contextProviders,
);
const mode = useAppSelector((store) => store.session.mode);
const editModeState = useAppSelector((state) => state.editModeState);
const filteredSlashCommands = props.isEditMode ? [] : availableSlashCommands;
const filteredSlashCommands = useMemo(() => {
return mode === "edit" ? [] : availableSlashCommands;
}, [mode, availableSlashCommands]);
const filteredContextProviders = useMemo(() => {
if (!props.isEditMode) {
return availableContextProviders ?? [];
if (mode === "edit") {
return (
availableContextProviders?.filter(
(provider) =>
!EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title),
) ?? []
);
}
return (
availableContextProviders?.filter(
(provider) =>
!EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title),
) ?? []
);
}, [availableContextProviders]);
return availableContextProviders ?? [];
}, [availableContextProviders, mode]);
const historyKey = props.isEditMode ? "edit" : "chat";
const placeholder = props.isEditMode
? "Describe changes, '#' to add files"
: undefined;
const historyKey = mode === "edit" ? "edit" : "chat";
const placeholder = mode === "edit" ? "Describe changes" : undefined;
const toolbarOptions: ToolbarOptions = props.isEditMode
? {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText: editModeState.editStatus === "accepting" ? "Retry" : "Edit",
}
: {};
const toolbarOptions: ToolbarOptions =
mode === "edit"
? {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText:
editModeState.applyState.status === "done" ? "Retry" : "Edit",
}
: {};
return (
<div

View file

@ -0,0 +1,59 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
import { useMainEditor } from "./TipTapEditor";
const EditModeDetails = () => {
const isStreaming = useAppSelector((store) => store.session.isStreaming);
const mode = useAppSelector((store) => store.session.mode);
const dispatch = useAppDispatch();
const editApplyState = useAppSelector(
(store) => store.editModeState.applyState,
);
const { mainEditor } = useMainEditor();
const ideMessenger = useContext(IdeMessengerContext);
if (mode !== "edit") {
return null;
}
if (isStreaming) {
return null;
}
if (editApplyState.status === "done") {
const plural = editApplyState.numDiffs === 1 ? "" : "s";
return (
<>
<div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
<span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
</div>
<AcceptRejectAllButtons
applyStates={[editApplyState]}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(exitEditMode({}));
ideMessenger.post("focusEditor", undefined);
} else {
mainEditor?.commands.focus();
}
}}
/>
</>
);
}
// Will only still show if not all accepted
if (editApplyState.status === "closed") {
return (
<div>
<span></span>
</div>
);
}
// Not started/streaming
return null;
};
export default EditModeDetails;

View file

@ -1,7 +1,8 @@
import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
import { useRef } from "react";
import { useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import {
@ -9,12 +10,7 @@ import {
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import {
selectHasCodeToEdit,
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import { loadLastSession } from "../../redux/thunks/session";
import { exitEditMode } from "../../redux/thunks/editMode";
import {
getAltKeyLabel,
getMetaKeyLabel,
@ -49,20 +45,20 @@ interface InputToolbarProps {
function InputToolbar(props: InputToolbarProps) {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const defaultModel = useAppSelector(selectSelectedChatModel);
const useActiveFile = useAppSelector(selectUseActiveFile);
const isInEditMode = useAppSelector(selectIsInEditMode);
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const mode = useAppSelector((store) => store.session.mode);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const isEnterDisabled =
props.disabled ||
isEditModeAndNoCodeToEdit ||
(mode === "edit" && codeToEdit.length === 0) ||
toolCallState?.status === "generated" ||
(currentToolCallApplyState &&
currentToolCallApplyState.status !== "closed");
@ -91,13 +87,13 @@ function InputToolbar(props: InputToolbarProps) {
}}
>
<div className="xs:gap-1.5 flex flex-row items-center gap-1">
<HoverItem data-tooltip-id="mode-select-tooltip">
<HoverItem data-tooltip-id="mode-select-tooltip" className="!p-0">
<ModeSelect />
<ToolTip id="mode-select-tooltip" place="top">
Select Mode
</ToolTip>
</HoverItem>
<HoverItem data-tooltip-id="model-select-tooltip">
<HoverItem data-tooltip-id="model-select-tooltip" className="!p-0">
<ModelSelect />
<ToolTip id="model-select-tooltip" place="top">
Select Model
@ -158,7 +154,7 @@ function InputToolbar(props: InputToolbarProps) {
fontSize: tinyFont,
}}
>
{!props.toolbarOptions?.hideUseCodebase && !isInEditMode && (
{!props.toolbarOptions?.hideUseCodebase && mode !== "edit" && (
<div
className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}
>
@ -188,16 +184,12 @@ function InputToolbar(props: InputToolbarProps) {
</div>
)}
{isInEditMode && (
{mode === "edit" && (
<HoverItem
className="hidden hover:underline sm:flex"
onClick={async (e) => {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
onClick={async () => {
dispatch(exitEditMode({}));
ideMessenger.post("focusEditor", undefined);
}}
>
<span>

View file

@ -12,9 +12,9 @@ import {
import { ReactNode } from "react";
import { vscBadgeForeground } from "../..";
import { useAppSelector } from "../../../redux/hooks";
import { fontSize } from "../../../util";
import { ToolTip } from "../../gui/Tooltip";
import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
import { useFontSize } from "../../ui/font";
import HoverItem from "../InputToolbar/HoverItem";
import { useLump } from "./LumpContext";
import { ErrorsSectionTooltip } from "./sections/errors/ErrorsSectionTooltip";
@ -74,8 +74,9 @@ function BlockSettingsToolbarIcon(
const isErrorSection = props.sectionId === "error";
const id = `block-settings-toolbar-icon-${props.sectionId}`;
return (
const fontSize = useFontSize(-3);
return (
<>
<HoverItem
px={0}
@ -98,7 +99,7 @@ function BlockSettingsToolbarIcon(
? "bg-red-600"
: "bg-badge"
: undefined
} relative flex select-none items-center rounded-full px-1 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 ${props.className || ""}`}
} relative flex select-none items-center rounded-full px-[3px] transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 sm:px-1 ${props.className || ""}`}
>
<props.icon
className={`h-[13px] w-[13px] flex-shrink-0 hover:brightness-125 ${
@ -110,7 +111,7 @@ function BlockSettingsToolbarIcon(
aria-hidden="true"
/>
<div
style={{ fontSize: fontSize(-3) }}
style={{ fontSize }}
className={`overflow-hidden transition-all duration-200 ${
props.isSelected ? "ml-1 w-auto opacity-100" : "w-0 opacity-0"
}`}
@ -123,7 +124,6 @@ function BlockSettingsToolbarIcon(
</span>
</div>
</div>
</HoverItem>
<ToolTip delayShow={700} id={id}>
{props.tooltip}
@ -156,7 +156,7 @@ export function BlockSettingsTopToolbar() {
);
return (
<div className="flex w-full items-center justify-between gap-4">
<div className="flex flex-1 items-center justify-between gap-2">
<div className="flex flex-row">
<div className="xs:flex hidden items-center justify-center text-gray-400">
<BlockSettingsToolbarIcon
@ -191,7 +191,10 @@ export function BlockSettingsTopToolbar() {
</div>
</div>
<div className="flex gap-0.5">
<HoverItem data-tooltip-id="assistant-select-tooltip">
<HoverItem
data-tooltip-id="assistant-select-tooltip"
className="!m-0 !p-0"
>
<AssistantSelect />
<ToolTip id="assistant-select-tooltip" place="top">
Select Assistant

View file

@ -18,6 +18,7 @@ import {
setDialogMessage,
setShowDialog,
} from "../../../../redux/slices/uiSlice";
import { getBaseSystemMessage } from "../../../../util";
import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip";
import { useFontSize } from "../../../ui/font";
import { ExploreBlocksButton } from "./ExploreBlocksButton";
@ -182,8 +183,7 @@ export function RulesSection() {
}
// Add a displayed rule for the base system chat message when in chat mode
if (mode === "chat" || mode === "agent") {
const baseMessage =
config.selectedModelByRole.chat?.baseChatSystemMessage;
const baseMessage = getBaseSystemMessage(config.selectedModelByRole.chat, mode)
if (baseMessage) {
rules.unshift({
rule: baseMessage,

View file

@ -4,7 +4,7 @@ export const ErrorsSectionTooltip = () => {
const configError = useAppSelector((store) => store.config.configError);
const numErrors = configError?.length ?? 0;
const plural = numErrors > 1 ? "s" : "";
const plural = numErrors === 1 ? "" : "s";
return (
<div>

View file

@ -7,7 +7,6 @@ import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
import useUpdatingRef from "../../../hooks/useUpdatingRef";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { selectSelectedChatModel } from "../../../redux/slices/configSlice";
import { selectIsInEditMode } from "../../../redux/slices/sessionSlice";
import InputToolbar, { ToolbarOptions } from "../InputToolbar";
import { ComboBoxItem } from "../types";
import { DragOverlay, InputBoxDiv } from "./components";
@ -48,9 +47,9 @@ export function TipTapEditor(props: TipTapEditorProps) {
const defaultModel = useAppSelector(selectSelectedChatModel);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const isInEditMode = useAppSelector(selectIsInEditMode);
const historyLength = useAppSelector((store) => store.session.history.length);
const mode = useAppSelector((store) => store.session.mode);
const { editor, onEnterRef } = createEditorConfig({
props,
ideMessenger,
@ -82,13 +81,16 @@ export function TipTapEditor(props: TipTapEditorProps) {
}, [editor, props.placeholder, historyLength]);
useEffect(() => {
if (isInEditMode) {
setShouldHideToolbar(false);
}
if (props.isMainInput) {
editor?.commands.clearContent(true);
}
}, [editor, isInEditMode, props.isMainInput]);
}, [editor, props.isMainInput]);
useEffect(() => {
if (mode === "edit") {
setShouldHideToolbar(false);
}
}, [mode]);
const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
@ -148,7 +150,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
const handleBlur = useCallback(
(e: React.FocusEvent) => {
if (isInEditMode) {
if (mode === "edit") {
return;
}
// Check if the new focus target is within our InputBoxDiv
@ -163,7 +165,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
setShouldHideToolbar(true);
}, 100);
},
[isInEditMode, blurTimeout],
[mode, blurTimeout],
);
const handleFocus = useCallback(() => {

View file

@ -1,189 +0,0 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import { MentionOptions } from "./types";
export const AddCodeToEdit = Node.create<MentionOptions>({
name: "add-code-to-edit",
addOptions() {
return {
HTMLAttributes: {
class: "add-code-to-edit",
},
renderHTML({ options, node }) {
return [
"span",
this.HTMLAttributes,
`${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`,
];
},
suggestion: {
char: "#",
pluginKey: new PluginKey(this.name),
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);
// Check if there's a space after the "#"
const textFrom = range.from;
const textTo = state.selection.$to.pos;
const text = state.doc.textBetween(textFrom, textTo);
const hasSpace = text.includes(" ");
return allow && !hasSpace;
},
},
};
},
group: "inline",
inline: true,
selectable: false,
atom: true,
addAttributes() {
return {
id: {
default: null,
parseHTML: (element) => element.getAttribute("data-id"),
renderHTML: (attributes) => {
if (!attributes.id) {
return {};
}
return {
"data-id": attributes.id,
};
},
},
label: {
default: null,
parseHTML: (element) => element.getAttribute("data-label"),
renderHTML: (attributes) => {
if (!attributes.label) {
return {};
}
return {
"data-label": attributes.label,
};
},
},
renderInlineAs: {
default: null,
parseHTML: (element) => element.getAttribute("data-renderInlineAs"),
renderHTML: (attributes) => {
if (typeof attributes.renderInlineAs !== "string") {
return {};
}
return {
"data-renderInlineAs": attributes.renderInlineAs,
};
},
},
query: {
default: null,
parseHTML: (element) => element.getAttribute("data-query"),
renderHTML: (attributes) => {
if (!attributes.query) {
return {};
}
return {
"data-query": attributes.query,
};
},
},
itemType: {
default: null,
parseHTML: (element) => element.getAttribute("data-itemType"),
renderHTML: (attributes) => {
if (!attributes.itemType) {
return {};
}
return {
"data-itemType": attributes.itemType,
};
},
},
};
},
parseHTML() {
return [
{
tag: `span[data-type="${this.name}"]`,
},
];
},
renderHTML({ node, HTMLAttributes }) {
const html = this.options.renderHTML({
options: this.options,
node,
});
if (typeof html === "string") {
return [
"span",
mergeAttributes(
{ "data-type": this.name },
this.options.HTMLAttributes,
HTMLAttributes,
),
html,
];
}
return html;
},
addKeyboardShortcuts() {
return {
Backspace: () =>
this.editor.commands.command(({ tr, state }) => {
let isMention = 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) {
isMention = true;
tr.insertText(
this.options.suggestion.char || "",
pos,
pos + node.nodeSize,
);
return false;
}
});
return isMention;
}),
};
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
];
},
});

View file

@ -1,4 +1,3 @@
export * from "./AddCodeToEdit";
export * from "./CodeBlock";
export * from "./Mention";
export * from "./Prompt";

View file

@ -3,10 +3,8 @@ import { InputModifiers } from "core";
import { rifWithContentsToContextItem } from "core/commands/util";
import { MutableRefObject } from "react";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import {
clearCodeToEdit,
setNewestToolbarPreviewForInput,
} from "../../../redux/slices/sessionSlice";
import { clearCodeToEdit } from "../../../redux/slices/editModeState";
import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice";
import { AppDispatch } from "../../../redux/store";
import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";
import { CodeBlock, PromptBlock } from "./extensions";
@ -158,26 +156,6 @@ export function useMainEditorWebviewListeners({
[editor, inputId, onEnterRef.current],
);
useWebviewListener(
"focusEdit",
async () => {
setTimeout(() => {
editor?.commands.focus("end");
}, 20);
},
[editor],
);
useWebviewListener(
"focusEditWithoutClear",
async () => {
setTimeout(() => {
editor?.commands.focus("end");
}, 2000);
},
[editor],
);
useWebviewListener(
"isContinueInputFocused",
async () => {

View file

@ -22,14 +22,8 @@ import useUpdatingRef from "../../../../hooks/useUpdatingRef";
import { useAppSelector } from "../../../../redux/hooks";
import { selectUseActiveFile } from "../../../../redux/selectors";
import { selectSelectedChatModel } 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 { exitEditMode } from "../../../../redux/thunks/editMode";
import { getFontSize, isJetBrains } from "../../../../util";
import * as ContinueExtensions from "../extensions";
import { TipTapEditorProps } from "../TipTapEditor";
@ -87,15 +81,14 @@ export function createEditorConfig(options: {
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const useActiveFile = useAppSelector(selectUseActiveFile);
const historyLength = useAppSelector((store) => store.session.history.length);
const isInEditMode = useAppSelector(selectIsInEditMode);
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
const mode = useAppSelector((store) => store.session.mode);
const modeRef = useUpdatingRef(mode);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const inSubmenuRef = useRef<string | undefined>(undefined);
const inDropdownRef = useRef(false);
const defaultModelRef = useUpdatingRef(defaultModel);
const isStreamingRef = useUpdatingRef(isStreaming);
const isInEditModeRef = useUpdatingRef(isInEditMode);
const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems);
const availableContextProvidersRef = useUpdatingRef(
props.availableContextProviders,
@ -267,24 +260,23 @@ export function createEditorConfig(options: {
return false;
},
Escape: () => {
if (inDropdownRef.current) {
return false;
}
// In JetBrains, this is how we close the sidebar when the input box is focused
if (isJetBrains()) {
ideMessenger.post("closeSidebar", undefined);
return true;
}
if (inDropdownRef.current || !isInEditModeRef.current) {
ideMessenger.post("focusEditor", undefined);
return true;
}
(async () => {
await dispatch(
loadLastSession({
saveCurrentSession: false,
if (modeRef.current === "edit") {
dispatch(
exitEditMode({
openNewSession: false,
}),
);
dispatch(exitEditMode());
})();
}
ideMessenger.post("focusEditor", undefined);
return true;
},
@ -325,42 +317,6 @@ export function createEditorConfig(options: {
ideMessenger,
),
}),
ContinueExtensions.AddCodeToEdit.configure({
suggestion: {
...getContextProviderDropdownOptions(
availableContextProvidersRef,
getSubmenuContextItemsRef,
enterSubmenu,
onClose,
onOpen,
inSubmenuRef,
ideMessenger,
),
allow: () => isInEditModeRef.current,
command: async ({ editor, range, props }) => {
editor.chain().focus().insertContentAt(range, "").run();
const filepath = props.id;
const contents = await ideMessenger.ide.readFile(filepath);
dispatch(
addCodeToEdit({
filepath,
contents,
}),
);
},
items: async ({ query }) => {
// Only display files in the dropdown
const results = getSubmenuContextItemsRef.current("file", query);
return results.map((result) => ({
...result,
label: result.title,
type: "file",
query: result.id,
icon: result.icon,
}));
},
},
}),
ContinueExtensions.SlashCommand.configure({
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
@ -389,7 +345,7 @@ export function createEditorConfig(options: {
if (!editor) {
return;
}
if (isStreaming || isEditModeAndNoCodeToEdit) {
if (isStreaming || (codeToEdit.length === 0 && mode === "edit")) {
return;
}
@ -406,7 +362,7 @@ export function createEditorConfig(options: {
props.onEnter(json, modifiers, editor);
},
[props.onEnter, editor, props.isMainInput],
[props.onEnter, editor, props.isMainInput, codeToEdit, mode],
);
return { editor, onEnterRef };

View file

@ -8,23 +8,15 @@ import {
} from "@heroicons/react/24/outline";
import { MessageModes } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo } from "react";
import styled from "styled-components";
import { lightGray } from "..";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import {
cycleMode,
selectCurrentMode,
setMode,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import {
loadLastSession,
saveCurrentSession,
} from "../../redux/thunks/session";
import { setMode } from "../../redux/slices/sessionSlice";
import { enterEditMode, exitEditMode } from "../../redux/thunks/editMode";
import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util";
import { useMainEditor } from "../mainInput/TipTapEditor";
import {
Listbox,
ListboxButton,
@ -40,12 +32,12 @@ const ShortcutText = styled.span`
function ModeSelect() {
const dispatch = useAppDispatch();
const mode = useAppSelector(selectCurrentMode);
const mode = useAppSelector((store) => store.session.mode);
const selectedModel = useAppSelector(selectSelectedChatModel);
const currentSession = useAppSelector((state) => state.session);
const [newSessionInitialized, setNewSessionInitialized] = useState(false);
const agentModeSupported = selectedModel && modelSupportsTools(selectedModel);
const agentModeSupported = useMemo(() => {
return selectedModel && modelSupportsTools(selectedModel);
}, [selectedModel]);
const { mainEditor } = useMainEditor();
const jetbrains = useMemo(() => {
return isJetBrains();
}, []);
@ -74,59 +66,79 @@ function ModeSelect() {
}
}, [mode, agentModeSupported, dispatch, selectedModel]);
const cycleMode = useCallback(async () => {
const modes: MessageModes[] = jetbrains
? ["chat", "agent"]
: ["chat", "agent", "edit"];
const currentIndex = modes.indexOf(mode);
const nextMode = modes[(currentIndex + 1) % modes.length];
if (mode === "edit") {
await dispatch(
exitEditMode({
goToMode: nextMode,
}),
);
} else {
if (nextMode === "edit") {
await dispatch(
enterEditMode({
returnToMode: mode,
}),
);
} else {
dispatch(setMode(nextMode));
}
}
mainEditor?.commands.focus();
}, [jetbrains, mode, mainEditor]);
const selectMode = useCallback(
async (newMode: MessageModes) => {
if (newMode === mode) {
return;
}
if (newMode === "edit") {
await dispatch(
enterEditMode({
returnToMode: mode,
}),
);
} else {
if (mode === "edit") {
await dispatch(
exitEditMode({
goToMode: newMode,
}),
);
} else {
dispatch(setMode(newMode));
}
}
mainEditor?.commands.focus();
},
[mode, mainEditor],
);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "." && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
dispatch(cycleMode({ isJetBrains: jetbrains }));
void cycleMode();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [dispatch, mode, jetbrains]);
useWebviewListener("newSession", async () => {
setNewSessionInitialized(true);
});
useEffect(() => {
if (currentSession.history.length > 0) {
setNewSessionInitialized(false);
}
}, [currentSession.history]);
}, [cycleMode]);
return (
<Listbox
value={mode}
onChange={async (newMode) => {
if (newMode === mode) {
return;
}
dispatch(setMode(newMode));
if (newMode === "edit" || newSessionInitialized) {
// generate a new session for edit mode and if user opened a new session explicitly
await dispatch(
saveCurrentSession({
generateTitle: false,
openNewSession: true,
}),
);
} else if (mode === "edit") {
// load last session if the previous mode was edit
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
}
}}
>
<Listbox value={mode} onChange={selectMode}>
<div className="relative">
<ListboxButton
data-testid="mode-select-button"
className="gap-1 border-none px-2 py-0.5 text-gray-400 transition-colors duration-200"
className="xs:px-2 gap-1 border-none px-1.5 py-0.5 text-gray-400 transition-colors duration-200"
style={{
backgroundColor: `${lightGray}33`,
borderRadius: "9999px",
@ -142,24 +154,6 @@ function ModeSelect() {
/>
</ListboxButton>
<ListboxOptions className="min-w-32 max-w-48">
<ListboxOption value="agent" disabled={!agentModeSupported}>
<div className="flex flex-row items-center gap-1.5">
<SparklesIcon className="h-3 w-3" />
<span className="">Agent</span>
</div>
{mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
{!agentModeSupported && <span> (Not supported)</span>}
</ListboxOption>
<ListboxOption value="chat">
<div className="flex flex-row items-center gap-1.5">
<ChatBubbleLeftIcon className="h-3 w-3" />
<span className="">Chat</span>
<ShortcutText>{getMetaKeyLabel()}L</ShortcutText>
</div>
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
{!jetbrains && (
<ListboxOption value="edit">
<div className="flex flex-row items-center gap-1.5">
@ -170,6 +164,23 @@ function ModeSelect() {
{mode === "edit" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
)}
<ListboxOption value="chat">
<div className="flex flex-row items-center gap-1.5">
<ChatBubbleLeftIcon className="h-3 w-3" />
<span className="">Chat</span>
<ShortcutText>{getMetaKeyLabel()}L</ShortcutText>
</div>
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
<ListboxOption value="agent" disabled={!agentModeSupported}>
<div className="flex flex-row items-center gap-1.5">
<SparklesIcon className="h-3 w-3" />
<span className="">Agent</span>
</div>
{mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
{!agentModeSupported && <span> (Not supported)</span>}
</ListboxOption>
<div className="text-lightgray px-2 py-1">
{metaKeyLabel}. for next mode

View file

@ -12,9 +12,6 @@ import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import AddModelForm from "../../forms/AddModelForm";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { updateSelectedModelByRole } from "../../redux/thunks";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
@ -123,12 +120,12 @@ function ModelOption({
function ModelSelect() {
const dispatch = useAppDispatch();
const isInEditMode = useAppSelector(selectIsInEditMode);
const mode = useAppSelector((store) => store.session.mode);
const config = useAppSelector((state) => state.config.config);
let selectedModel = null;
let allModels = null;
if (isInEditMode) {
if (mode === "edit") {
allModels = config.modelsByRole.edit;
selectedModel = config.selectedModelByRole.edit;
}
@ -158,14 +155,14 @@ function ModelSelect() {
useEffect(() => {
setOptions(
allModels.map((model) => {
return {
value: model.title,
title: modelSelectTitle(model),
apiKey: model.apiKey,
};
}),
return {
value: model.title,
title: modelSelectTitle(model),
apiKey: model.apiKey,
};
}),
);
}, [isInEditMode, config]);
}, [config]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
@ -225,7 +222,7 @@ function ModelSelect() {
dispatch(
updateSelectedModelByRole({
selectedProfile,
role: isInEditMode ? "edit" : "chat",
role: mode === "edit" ? "edit" : "chat",
modelTitle: val,
}),
);

View file

@ -2,6 +2,7 @@ import { useCallback, useContext, useEffect, useRef } from "react";
import { VSC_THEME_COLOR_VARS } from "../components";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { FromCoreProtocol } from "core/protocol";
import {
initializeProfilePreferences,
@ -11,10 +12,11 @@ import {
} from "../redux";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
import { setConfigResult } from "../redux/slices/configSlice";
import {
selectSelectedChatModel,
setConfigResult,
} from "../redux/slices/configSlice";
setLastNonEditSessionEmpty,
updateEditStateApplyState,
} from "../redux/slices/editModeState";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import {
acceptToolCall,
@ -31,11 +33,11 @@ import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
function useSetup() {
function ParallelListeners() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((store) => store.session.history);
const defaultModel = useAppSelector(selectSelectedChatModel);
const selectedProfileId = useAppSelector(
(store) => store.profiles.selectedProfileId,
);
@ -81,10 +83,6 @@ function useSetup() {
const initialLoadAuthAndConfig = useCallback(
async (initial: boolean) => {
// const authResult = await ideMessenger.request(
// "auth/getState",
// undefined
// )
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
@ -259,34 +257,47 @@ function useSetup() {
useWebviewListener(
"updateApplyState",
async (state) => {
dispatch(updateApplyState(state));
if (state.streamId === EDIT_MODE_STREAM_ID) {
dispatch(updateEditStateApplyState(state));
} else {
// chat or agent
dispatch(updateApplyState(state));
// Handle apply status updates that are associated with current tool call
if (
state.status === "closed" &&
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// Handle apply status updates that are associated with current tool call
if (
state.status === "closed" &&
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
}
},
[currentToolCallApplyState, history],
);
const mode = useAppSelector((store) => store.session.mode);
useEffect(() => {
if (mode !== "edit") {
dispatch(setLastNonEditSessionEmpty(history.length === 0));
}
}, [mode, history]);
return <></>;
}
export default useSetup;
export default ParallelListeners;

View file

@ -996,4 +996,24 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
],
apiKeyUrl: "https://cloud.siliconflow.cn/account/ak",
},
venice: {
title: "Venice",
provider: "venice",
icon: "venice.png",
description: "Venice.",
tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your Venice API key",
required: true,
},
],
packages: [
{...models.AUTODETECT}
],
apiKeyUrl: "https://venice.ai/chat"
}
};

View file

@ -1,13 +1,13 @@
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
import { newSession } from "../redux/slices/sessionSlice";
import { GithubIcon } from "../components/svg/GithubIcon";
import { DiscordIcon } from "../components/svg/DiscordIcon";
import { useContext, useEffect, useState } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { Button, SecondaryButton } from "../components";
import { ArrowPathIcon, FlagIcon } from "@heroicons/react/24/outline";
import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
import { Button, SecondaryButton } from "../components";
import { DiscordIcon } from "../components/svg/DiscordIcon";
import { GithubIcon } from "../components/svg/GithubIcon";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { newSession } from "../redux/slices/sessionSlice";
const ErrorPage: React.FC = () => {
const error: any = useRouteError();
@ -61,16 +61,16 @@ const ErrorPage: React.FC = () => {
Report the issue on GitHub or Discord:
</p>
<div className="flex space-x-4">
<div className="mt-2 flex flex-row flex-wrap justify-center gap-2">
<SecondaryButton
onClick={() => openUrl(GITHUB_LINK)}
className="flex w-full items-center justify-center space-x-2 rounded-lg px-4 py-2 text-base text-white"
className="flex items-center justify-center space-x-2 rounded-lg px-4 py-2 text-base text-white"
>
<GithubIcon size={20} /> <span className="ml-2">GitHub</span>
</SecondaryButton>
<SecondaryButton
onClick={() => openUrl(DISCORD_LINK)}
className="flex w-full items-center justify-center rounded-lg text-base"
className="flex items-center justify-center rounded-lg text-base"
>
<DiscordIcon size={20} /> <span className="ml-2">Discord</span>
</SecondaryButton>

View file

@ -1,6 +1,6 @@
import { renderWithProviders } from "../../util/test/render";
import { screen, waitFor } from "@testing-library/dom";
import { act, fireEvent } from "@testing-library/react";
import { act } from "@testing-library/react";
import { renderWithProviders } from "../../util/test/render";
import { Chat } from "./Chat";
describe("Chat page test", () => {
@ -23,8 +23,8 @@ describe("Chat page test", () => {
);
});
// Check that it switched to Edit mode
expect(await screen.findByText("Edit")).toBeInTheDocument();
// Check that it switched to Agent mode
expect(await screen.findByText("Agent")).toBeInTheDocument();
act(() => {
document.dispatchEvent(
@ -35,8 +35,8 @@ describe("Chat page test", () => {
);
});
// Check that it switched to Agent mode
expect(await screen.findByText("Agent")).toBeInTheDocument();
// Check that it switched to Edit mode
expect(await screen.findByText("Edit")).toBeInTheDocument();
});
it.skip("should send a message and receive a response", async () => {

View file

@ -5,16 +5,22 @@ import {
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers, RangeInFileWithContents } from "core";
import { InputModifiers } from "core";
import { streamResponse } from "core/llm/stream";
import { renderChatMessage, stripImages } from "core/util/messageContent";
import { renderChatMessage } from "core/util/messageContent";
import { usePostHog } from "posthog-js/react";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { ErrorBoundary } from "react-error-boundary";
import styled from "styled-components";
import { Button, lightGray, vscBackground } from "../../components";
import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons";
import CodeToEditCard from "../../components/CodeToEditCard";
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog";
import { useFindWidget } from "../../components/find/FindWidget";
@ -22,24 +28,18 @@ 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/TipTapEditor/utils";
import { useOnboardingCard } from "../../components/OnboardingCard";
import StepContainer from "../../components/StepContainer";
import { TabBar } from "../../components/TabBar/TabBar";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import {
selectCurrentToolCall,
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { submitEdit } from "../../redux/slices/editModeState";
import {
newSession,
selectIsInEditMode,
selectIsSingleRangeEditOrInsertion,
updateToolCallOutput,
} from "../../redux/slices/sessionSlice";
import {
@ -48,7 +48,7 @@ import {
setShowDialog,
} from "../../redux/slices/uiSlice";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import { streamEditThunk } from "../../redux/thunks/editMode";
import { loadLastSession } from "../../redux/thunks/session";
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
@ -56,7 +56,9 @@ import {
FREE_TRIAL_LIMIT_REQUESTS,
incrementFreeTrialCount,
} from "../../util/freeTrial";
import getMultifileEditPrompt from "../../util/getMultifileEditPrompt";
import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
import EditModeDetails from "../../components/mainInput/EditModeDetails";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
@ -106,7 +108,9 @@ export function Chat() {
const showSessionTabs = useAppSelector(
(store) => store.config.config.ui?.showSessionTabs,
);
const selectedChatModel = useAppSelector(selectSelectedChatModel);
const selectedModels = useAppSelector(
(store) => store.config?.config.selectedModelByRole,
);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
@ -115,25 +119,20 @@ export function Chat() {
const showChatScrollbar = useAppSelector(
(state) => state.config.config.ui?.showChatScrollbar,
);
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const mode = useAppSelector((store) => store.session.mode);
const applyStates = useAppSelector(
(state) => state.session.codeBlockApplyStates.states,
);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const hasPendingApplies = pendingApplyStates.length > 0;
const isInEditMode = useAppSelector(selectIsInEditMode);
const isSingleRangeEditOrInsertion = useAppSelector(
selectIsSingleRangeEditOrInsertion,
);
const lastSessionId = useAppSelector((state) => state.session.lastSessionId);
const useHub = useAppSelector(selectUseHub);
const hasDismissedExploreDialog = useAppSelector(
(state) => state.ui.hasDismissedExploreDialog,
);
const jetbrains = isJetBrains();
const jetbrains = useMemo(() => {
return isJetBrains();
}, []);
useEffect(() => {
// Cmd + Backspace to delete current step
@ -151,7 +150,7 @@ export function Chat() {
return () => {
window.removeEventListener("keydown", listener);
};
}, [isStreaming]);
}, [isStreaming, jetbrains]);
const { widget, highlights } = useFindWidget(stepsDivRef);
@ -179,7 +178,20 @@ export function Chat() {
"Cannot submit message while awaiting tool call apply",
);
}
if (selectedChatModel?.provider === "free-trial") {
const model =
mode === "edit"
? (selectedModels?.edit ?? selectedModels?.chat)
: selectedModels?.chat;
if (!model) {
return;
}
if (mode === "edit" && codeToEdit.length === 0) {
return;
}
if (model.provider === "free-trial") {
const newCount = incrementFreeTrialCount();
if (newCount === FREE_TRIAL_LIMIT_REQUESTS) {
@ -206,21 +218,19 @@ export function Chat() {
}
}
if (isSingleRangeEditOrInsertion) {
handleSingleRangeEditOrInsertion(editorState);
return;
}
if (mode === "edit") {
dispatch(
streamEditThunk({
editorState,
codeToEdit,
}),
);
} else {
dispatch(streamResponseThunk({ editorState, modifiers, index }));
const promptPreamble = isInEditMode
? getMultifileEditPrompt(codeToEdit)
: undefined;
dispatch(
streamResponseThunk({ editorState, modifiers, promptPreamble, index }),
);
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
}
}
// Increment localstorage counter for popup
@ -236,47 +246,9 @@ export function Chat() {
setLocalStorage("mainTextEntryCounter", 1);
}
},
[
history,
selectedChatModel,
streamResponse,
isSingleRangeEditOrInsertion,
codeToEdit,
toolCallState,
],
[history, selectedModels, streamResponse, mode, codeToEdit, toolCallState],
);
async function handleSingleRangeEditOrInsertion(editorState: JSONContent) {
if (!selectedChatModel) {
console.error("No selected chat model");
return;
}
const [contextItems, __, userInstructions, _] = await resolveEditorContent({
editorState,
modifiers: {
noContext: true,
useCodebase: false,
},
ideMessenger,
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
});
const prompt = [
...contextItems.map((item) => item.content),
stripImages(userInstructions),
].join("\n\n");
ideMessenger.post("edit/sendPrompt", {
prompt,
range: codeToEdit[0] as RangeInFileWithContents,
});
dispatch(submitEdit(prompt));
}
useWebviewListener(
"newSession",
async () => {
@ -314,8 +286,6 @@ export function Chat() {
useAutoScroll(stepsDivRef, history);
const showPageHeader = isInEditMode || useHub;
return (
<>
{widget}
@ -324,7 +294,7 @@ export function Chat() {
<StepsDiv
ref={stepsDivRef}
className={`mt-3 overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
>
{highlights}
{history.map((item, index: number) => (
@ -342,9 +312,7 @@ export function Chat() {
>
{item.message.role === "user" ? (
<>
{isInEditMode && index === 0 && <CodeToEditCard />}
<ContinueInputBox
isEditMode={isInEditMode}
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
@ -421,19 +389,24 @@ export function Chat() {
))}
</StepsDiv>
<div className={"relative"}>
{isInEditMode && history.length === 0 && <CodeToEditCard />}
{isInEditMode && history.length > 0 ? null : (
<>
{!isStreaming && mode !== "edit" && (
<AcceptRejectAllButtons
applyStates={applyStates}
onAcceptOrReject={async () => {}}
/>
)}
{mode === "edit" && <CodeToEditCard />}
<ContinueInputBox
isMainInput
isEditMode={isInEditMode}
isLastUserInput={false}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, undefined, editor)
}
inputId={MAIN_EDITOR_INPUT_ID}
/>
)}
<EditModeDetails />
</>
<div
style={{
@ -442,7 +415,7 @@ export function Chat() {
>
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
<div className="xs:inline hidden">
{history.length === 0 && lastSessionId && !isInEditMode && (
{history.length === 0 && lastSessionId && mode !== "edit" && (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {
@ -461,30 +434,9 @@ export function Chat() {
)}
</div>
</div>
{hasPendingApplies && isSingleRangeEditOrInsertion && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
}
}}
/>
)}
{!hasDismissedExploreDialog && <ExploreDialogWatcher />}
{history.length === 0 && (
<EmptyChatBody
useHub={useHub}
showOnboardingCard={onboardingCard.show}
/>
<EmptyChatBody showOnboardingCard={onboardingCard.show} />
)}
</div>
</div>

View file

@ -4,18 +4,15 @@ import { OnboardingCard } from "../../components/OnboardingCard";
import { PlatformOnboardingCard } from "../../components/OnboardingCard/platform/PlatformOnboardingCard";
export interface EmptyChatBodyProps {
useHub: boolean;
showOnboardingCard?: boolean;
}
export function EmptyChatBody({
useHub,
showOnboardingCard,
}: EmptyChatBodyProps) {
export function EmptyChatBody({ showOnboardingCard }: EmptyChatBodyProps) {
if (showOnboardingCard) {
return (
<div className="mx-2 mt-6">
{useHub ? (
{true ? (
// For now we are excluding local onboarding options other than ollama
<PlatformOnboardingCard isDialog={false} />
) : (
<OnboardingCard isDialog={false} />

View file

@ -11,7 +11,6 @@ import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { selectSelectedProfile } from "../../redux/";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { isLocalProfile } from "../../util";
@ -26,7 +25,7 @@ function parseErrorMessage(fullErrMsg: string): string {
const msg = fullErrMsg.split("\n\n").slice(1).join("\n\n");
try {
const parsed = JSON.parse(msg);
return parsed.error ?? parsed.message ?? msg;
return JSON.stringify(parsed.error ?? parsed.message ?? msg);
} catch (e) {
return msg;
}
@ -36,7 +35,6 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const selectedModel = useAppSelector(selectSelectedChatModel);
const hubEnabled = useAppSelector(selectUseHub);
const selectedProfile = useAppSelector(selectSelectedProfile);
const { session, refreshProfiles } = useAuth();
@ -180,17 +178,14 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
if (statusCode === 401) {
errorContent = (
<div className="flex flex-col gap-2">
{hubEnabled &&
session &&
selectedProfile &&
!isLocalProfile(selectedProfile) && (
<div className="flex flex-col gap-1">
<span>{`If your hub secret values may have changed, refresh your assistants`}</span>
<SecondaryButton onClick={handleRefreshProfiles}>
Refresh assistant secrets
</SecondaryButton>
</div>
)}
{session && selectedProfile && !isLocalProfile(selectedProfile) && (
<div className="flex flex-col gap-1">
<span>{`If your hub secret values may have changed, refresh your assistants`}</span>
<SecondaryButton onClick={handleRefreshProfiles}>
Refresh assistant secrets
</SecondaryButton>
</div>
)}
<span>{`It's possible that your API key is invalid.`}</span>
<div className="flex flex-row flex-wrap gap-2">
{checkKeysButton}

View file

@ -1,7 +1,6 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons";
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
@ -41,29 +40,13 @@ export function EditFile(props: EditToolCallProps) {
}
return (
<>
<StyledMarkdownPreview
isRenderingInStepContainer
disableManualApply
source={src}
forceStreamId={applyState?.streamId}
expandCodeblocks={false}
itemIndex={props.historyIndex}
/>
{/* TODO better indicator of generation at bottom */}
{/* {isStreaming && applyState?.status === "streaming" && (
<div className={`m-2 flex items-center justify-center`}>
Generating...
</div>
)} */}
{!isStreaming && applyState?.status === "done" && (
<div className={`m-2 flex items-center justify-center`}>
<AcceptRejectAllButtons
pendingApplyStates={[applyState]}
onAcceptOrReject={async (outcome) => {}}
/>
</div>
)}
</>
<StyledMarkdownPreview
isRenderingInStepContainer
disableManualApply
source={src}
forceStreamId={applyState?.streamId}
expandCodeblocks={false}
itemIndex={props.historyIndex}
/>
);
}

View file

@ -46,6 +46,3 @@ export const selectUseActiveFile = createSelector(
[(state: RootState) => state.config.config.experimental?.defaultContext],
(defaultContext) => defaultContext?.includes("activeFile" as any),
);
export const selectUseHub = (state: RootState) =>
state.config.config.usePlatform;

View file

@ -1,82 +1,76 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { EditStatus, MessageContent } from "core";
import { ApplyState, CodeToEdit, MessageModes } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
export interface EditModeState {
editStatus: EditStatus;
previousInputs: MessageContent[];
fileAfterEdit?: string;
// Array because of previous multi-file edit functionality
// Keeping array to not break persisted redux for now
codeToEdit: CodeToEdit[];
applyState: ApplyState;
returnToMode: MessageModes;
lastNonEditSessionWasEmpty: boolean;
}
export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
streamId: EDIT_MODE_STREAM_ID,
status: "not-started",
};
const initialState: EditModeState = {
editStatus: "not-started",
previousInputs: [],
applyState: INITIAL_EDIT_APPLY_STATE,
codeToEdit: [],
returnToMode: "chat",
lastNonEditSessionWasEmpty: false,
};
export const editModeStateSlice = createSlice({
name: "editModeState",
initialState,
reducers: {
focusEdit: (state) => {
state.editStatus = "not-started";
state.previousInputs = [];
state.fileAfterEdit = undefined;
setReturnToModeAfterEdit: (
state,
{ payload }: PayloadAction<MessageModes>,
) => {
state.returnToMode = payload;
},
submitEdit: (state, { payload }: PayloadAction<MessageContent>) => {
state.previousInputs.push(payload);
state.editStatus = "streaming";
updateEditStateApplyState: (
state,
{ payload }: PayloadAction<ApplyState>,
) => {
state.applyState = {
...state.applyState,
...payload,
};
},
setEditStatus: (
setCodeToEdit: (
state,
{
payload,
}: PayloadAction<{ status: EditStatus; fileAfterEdit?: string }>,
}: PayloadAction<{
codeToEdit: CodeToEdit | CodeToEdit[];
}>,
) => {
// Only allow valid transitions
const currentStatus = state.editStatus;
if (currentStatus === "not-started" && payload.status === "streaming") {
state.editStatus = payload.status;
} else if (
currentStatus === "streaming" &&
payload.status === "accepting"
) {
state.editStatus = payload.status;
state.fileAfterEdit = payload.fileAfterEdit;
} else if (currentStatus === "accepting" && payload.status === "done") {
state.editStatus = payload.status;
} else if (
currentStatus === "accepting:full-diff" &&
payload.status === "done"
) {
state.editStatus = payload.status;
} else if (
currentStatus === "accepting" &&
payload.status === "accepting:full-diff"
) {
state.editStatus = payload.status;
} else if (
currentStatus === "accepting:full-diff" &&
payload.status === "accepting"
) {
state.editStatus = payload.status;
} else if (currentStatus === "done" && payload.status === "not-started") {
state.editStatus = payload.status;
}
state.codeToEdit = Array.isArray(payload.codeToEdit)
? payload.codeToEdit
: [payload.codeToEdit];
},
addPreviousInput: (state, { payload }: PayloadAction<MessageContent>) => {
state.previousInputs.push(payload);
clearCodeToEdit: (state) => {
state.codeToEdit = [];
},
setEditDone: (state) => {
state.editStatus = "done";
state.previousInputs = [];
setLastNonEditSessionEmpty: (
state,
{ payload }: PayloadAction<boolean>,
) => {
state.lastNonEditSessionWasEmpty = payload;
},
},
selectors: {},
});
export const {
setEditStatus,
addPreviousInput,
setEditDone,
submitEdit,
focusEdit,
setReturnToModeAfterEdit,
clearCodeToEdit,
setCodeToEdit,
updateEditStateApplyState,
setLastNonEditSessionEmpty,
} = editModeStateSlice.actions;
export default editModeStateSlice.reducer;

View file

@ -10,7 +10,6 @@ import {
ApplyState,
ChatHistoryItem,
ChatMessage,
CodeToEdit,
ContextItem,
ContextItemWithId,
FileSymbolMap,
@ -44,8 +43,6 @@ type SessionState = {
title: string;
id: string;
streamAborter: AbortController;
codeToEdit: CodeToEdit[];
curCheckpointIndex: number;
mainEditorContentTrigger?: JSONContent | undefined;
symbols: FileSymbolMap;
mode: MessageModes;
@ -56,34 +53,13 @@ type SessionState = {
newestToolbarPreviewForInput: Record<string, string>;
};
function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) {
if (a.filepath !== b.filepath || a.contents !== b.contents) {
return false;
}
if ("range" in a && "range" in b) {
const rangeA = a.range;
const rangeB = b.range;
return (
rangeA.start.line === rangeB.start.line &&
rangeA.end.line === rangeB.end.line
);
}
// If neither has a range, they are considered equal in this context
return !("range" in a) && !("range" in b);
}
const initialState: SessionState = {
allSessionMetadata: [],
history: [],
isStreaming: false,
title: NEW_SESSION_TITLE,
id: uuidv4(),
curCheckpointIndex: 0,
streamAborter: new AbortController(),
codeToEdit: [],
symbols: {},
mode: "chat",
codeBlockApplyStates: {
@ -200,8 +176,6 @@ export const sessionSlice = createSlice({
},
contextItems: [],
});
state.curCheckpointIndex = Math.floor(index / 2);
} else {
// New input/response messages
state.history = state.history.concat([
@ -223,8 +197,6 @@ export const sessionSlice = createSlice({
contextItems: [],
},
]);
state.curCheckpointIndex = Math.floor((state.history.length - 1) / 2); // TODO this feels really fragile
}
state.isStreaming = true;
@ -454,12 +426,10 @@ export const sessionSlice = createSlice({
state.history = payload.history as any;
state.title = payload.title;
state.id = payload.sessionId;
state.curCheckpointIndex = 0;
} else {
state.history = [];
state.title = NEW_SESSION_TITLE;
state.id = uuidv4();
state.curCheckpointIndex = 0;
}
},
updateSessionTitle: (state, { payload }: PayloadAction<string>) => {
@ -551,19 +521,6 @@ export const sessionSlice = createSlice({
state.history[state.history.length - 1].contextItems = contextItems;
},
updateCurCheckpoint: (
state,
{ payload }: PayloadAction<{ filepath: string; content: string }>,
) => {
const checkpoint = state.history[state.curCheckpointIndex].checkpoint;
if (checkpoint) {
checkpoint[payload.filepath] = payload.content;
}
},
setCurCheckpointIndex: (state, { payload }: PayloadAction<number>) => {
state.curCheckpointIndex = payload;
},
updateApplyState: (state, { payload }: PayloadAction<ApplyState>) => {
const applyState = state.codeBlockApplyStates.states.find(
(state) => state.streamId === payload.streamId,
@ -584,31 +541,7 @@ export const sessionSlice = createSlice({
resetNextCodeBlockToApplyIndex: (state) => {
state.codeBlockApplyStates.curIndex = 0;
},
addCodeToEdit: (
state,
{ payload }: PayloadAction<CodeToEdit | CodeToEdit[]>,
) => {
const entries = Array.isArray(payload) ? payload : [payload];
const newEntries = entries.filter(
(entry) =>
!state.codeToEdit.some((existingEntry) =>
isCodeToEditEqual(existingEntry, entry),
),
);
if (newEntries.length > 0) {
state.codeToEdit.push(...newEntries);
}
},
removeCodeToEdit: (state, { payload }: PayloadAction<CodeToEdit>) => {
state.codeToEdit = state.codeToEdit.filter(
(entry) => !isCodeToEditEqual(entry, payload),
);
},
clearCodeToEdit: (state) => {
state.codeToEdit = [];
},
// TOOL CALL STATE
setToolGenerated: (
state,
@ -698,14 +631,6 @@ export const sessionSlice = createSlice({
setMode: (state, action: PayloadAction<MessageModes>) => {
state.mode = action.payload;
},
cycleMode: (state, action: PayloadAction<{ isJetBrains: boolean }>) => {
const modes = action.payload.isJetBrains
? ["chat", "agent"]
: ["chat", "edit", "agent"];
const currentIndex = modes.indexOf(state.mode);
const nextIndex = (currentIndex + 1) % modes.length;
state.mode = modes[nextIndex] as MessageModes;
},
setNewestToolbarPreviewForInput: (
state,
{
@ -724,26 +649,6 @@ export const sessionSlice = createSlice({
const curHistoryItem = state.history.at(-1);
return curHistoryItem?.isGatheringContext || false;
},
selectIsInEditMode: (state) => {
return state.mode === "edit";
},
selectCurrentMode: (state) => {
return state.mode;
},
selectIsSingleRangeEditOrInsertion: (state) => {
if (state.mode !== "edit") {
return false;
}
const isInsertion = state.codeToEdit.length === 0;
const selectIsSingleRangeEdit =
state.codeToEdit.length === 1 && "range" in state.codeToEdit[0];
return selectIsSingleRangeEdit || isInsertion;
},
selectHasCodeToEdit: (state) => {
return state.codeToEdit.length > 0;
},
},
extraReducers: (builder) => {
addPassthroughCases(builder, [streamResponseThunk]);
@ -806,14 +711,9 @@ export const {
setMainEditorContentTrigger,
deleteMessage,
setIsGatheringContext,
updateCurCheckpoint,
setCurCheckpointIndex,
resetNextCodeBlockToApplyIndex,
updateApplyState,
abortStream,
clearCodeToEdit,
addCodeToEdit,
removeCodeToEdit,
setToolCallCalling,
cancelToolCall,
errorToolCall,
@ -826,15 +726,8 @@ export const {
updateSessionMetadata,
deleteSessionMetadata,
setNewestToolbarPreviewForInput,
cycleMode,
} = sessionSlice.actions;
export const {
selectIsGatheringContext,
selectIsInEditMode,
selectCurrentMode,
selectIsSingleRangeEditOrInsertion,
selectHasCodeToEdit,
} = sessionSlice.selectors;
export const { selectIsGatheringContext } = sessionSlice.selectors;
export default sessionSlice.reducer;

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