Merge branch 'main' into workspace-continue-env
This commit is contained in:
commit
42722ecabd
212 changed files with 13426 additions and 2478 deletions
|
|
@ -1 +0,0 @@
|
|||
Give concise responses.
|
||||
2
.github/workflows/jetbrains-release.yaml
vendored
2
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -481,7 +481,7 @@ jobs:
|
|||
|
||||
# Run Qodana inspections
|
||||
- name: Qodana - Code Inspection
|
||||
uses: JetBrains/qodana-action@v2025.1.0
|
||||
uses: JetBrains/qodana-action@v2025.1.1
|
||||
with:
|
||||
cache-default-branch-only: true
|
||||
|
||||
|
|
|
|||
10
.vscode/extensions.json
vendored
Normal file
10
.vscode/extensions.json
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"recommendations": [
|
||||
"Continue.continue",
|
||||
"vivaxy.vscode-conventional-commits",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"esbenp.prettier-vscode",
|
||||
"bradlc.vscode-tailwindcss",
|
||||
"YoavBls.pretty-ts-errors"
|
||||
]
|
||||
}
|
||||
7
.vscode/settings.json
vendored
7
.vscode/settings.json
vendored
|
|
@ -46,5 +46,10 @@
|
|||
// "sync/**": true
|
||||
},
|
||||
"eslint.workingDirectories": ["./core"],
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"conventionalCommits.showNewVersionNotes": false,
|
||||
"conventionalCommits.promptBody": false,
|
||||
"conventionalCommits.promptFooter": false,
|
||||
"conventionalCommits.promptScopes": true,
|
||||
"conventionalCommits.scopes": ["reg"]
|
||||
}
|
||||
|
|
|
|||
1
binary/package-lock.json
generated
1
binary/package-lock.json
generated
|
|
@ -74,6 +74,7 @@
|
|||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"ignore": "^5.3.1",
|
||||
"is-localhost-ip": "^2.0.0",
|
||||
"jinja-js": "0.1.8",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
"jsdom": "^24.0.0",
|
||||
|
|
|
|||
|
|
@ -279,10 +279,7 @@ export class ConfigHandler {
|
|||
if (options.includeWorkspace) {
|
||||
const assistantFiles = await getAllDotContinueYamlFiles(
|
||||
this.ide,
|
||||
{
|
||||
...options,
|
||||
includeGlobal: false, // Because the global comes from above
|
||||
},
|
||||
options,
|
||||
ASSISTANTS,
|
||||
);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
@ -841,7 +835,8 @@ declare global {
|
|||
| "llava"
|
||||
| "gemma"
|
||||
| "granite"
|
||||
| "llama3";
|
||||
| "llama3"
|
||||
| "codestral";
|
||||
|
||||
export interface RequestOptions {
|
||||
timeout?: number;
|
||||
|
|
@ -1051,13 +1046,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
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ export function addModel(
|
|||
(prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev),
|
||||
0,
|
||||
);
|
||||
if (numMatches !== 0) {
|
||||
if (numMatches !== undefined && numMatches > 0) {
|
||||
model.title = `${model.title} (${numMatches})`;
|
||||
}
|
||||
|
||||
|
|
@ -63,7 +63,7 @@ export function addModel(
|
|||
"name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev,
|
||||
0,
|
||||
);
|
||||
if (numMatches !== 0) {
|
||||
if (numMatches !== undefined && numMatches > 0) {
|
||||
model.title = `${model.title} (${numMatches})`;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ function convertYamlMcpToContinueMcp(
|
|||
args: server.args ?? [],
|
||||
env: server.env,
|
||||
},
|
||||
timeout: server.connectionTimeout
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -444,6 +445,7 @@ async function configYamlToContinueConfig(options: {
|
|||
args: [],
|
||||
...server,
|
||||
},
|
||||
timeout: server.connectionTimeout
|
||||
})),
|
||||
false,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ async function modelConfigToBaseLLM({
|
|||
title: model.name,
|
||||
template: model.promptTemplates?.chat,
|
||||
promptTemplates: model.promptTemplates,
|
||||
baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage,
|
||||
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
|
||||
capabilities: {
|
||||
tools: model.capabilities?.includes("tool_use"),
|
||||
|
|
|
|||
|
|
@ -55,6 +55,27 @@ describe("MCPConnection", () => {
|
|||
expect(conn.status).toBe("not-connected");
|
||||
});
|
||||
|
||||
it("should create instance with SSE transport and custom headers", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "sse" as const,
|
||||
url: "http://test.com/events",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"Authorization": "Bearer token123",
|
||||
"X-Custom-Header": "custom-value"
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
expect(conn).toBeInstanceOf(MCPConnection);
|
||||
expect(conn.status).toBe("not-connected");
|
||||
});
|
||||
|
||||
it("should throw on invalid transport type", () => {
|
||||
const options = {
|
||||
name: "test-mcp",
|
||||
|
|
@ -151,6 +172,21 @@ describe("MCPConnection", () => {
|
|||
expect(mockConnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle custom connection timeout', async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 11 });
|
||||
const mockConnect = jest
|
||||
.spyOn(Client.prototype, "connect")
|
||||
.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(resolve, 10)),
|
||||
);
|
||||
|
||||
const abortController = new AbortController();
|
||||
await conn.connectClient(false, abortController.signal);
|
||||
|
||||
expect(conn.status).toBe("connected");
|
||||
expect(mockConnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle connection timeout", async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 1 });
|
||||
const mockConnect = jest
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
MCPTool,
|
||||
} from "../..";
|
||||
|
||||
export const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds
|
||||
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
|
||||
|
||||
class MCPConnection {
|
||||
public client: Client;
|
||||
|
|
@ -55,7 +55,9 @@ class MCPConnection {
|
|||
private constructTransport(options: MCPOptions): Transport {
|
||||
switch (options.transport.type) {
|
||||
case "stdio":
|
||||
const env: Record<string, string> = options.transport.env || {};
|
||||
const env: Record<string, string> = options.transport.env
|
||||
? { ...options.transport.env }
|
||||
: {};
|
||||
if (process.env.PATH !== undefined) {
|
||||
env.PATH = process.env.PATH;
|
||||
}
|
||||
|
|
@ -67,7 +69,19 @@ class MCPConnection {
|
|||
case "websocket":
|
||||
return new WebSocketClientTransport(new URL(options.transport.url));
|
||||
case "sse":
|
||||
return new SSEClientTransport(new URL(options.transport.url));
|
||||
return new SSEClientTransport(new URL(options.transport.url), {
|
||||
eventSourceInit: {
|
||||
fetch: (input, init) =>
|
||||
fetch(input, {
|
||||
...init,
|
||||
headers: {
|
||||
...init?.headers,
|
||||
...(options.transport.requestOptions?.headers as Record<string, string> | undefined),
|
||||
}
|
||||
}),
|
||||
},
|
||||
requestInit: { headers: options.transport.requestOptions?.headers }
|
||||
});
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ const modelDescriptionSchema = z.object({
|
|||
"llava",
|
||||
"gemma",
|
||||
"llama3",
|
||||
"codestral",
|
||||
])
|
||||
.optional(),
|
||||
completionOptions: z
|
||||
|
|
|
|||
36
core/core.ts
36
core/core.ts
|
|
@ -63,32 +63,50 @@ import { llmStreamChat } from "./llm/streamChat";
|
|||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
||||
// This function is used for jetbrains inline edit and apply
|
||||
async function* streamDiffLinesGenerator(
|
||||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const data = msg.data;
|
||||
const {
|
||||
highlighted,
|
||||
prefix,
|
||||
suffix,
|
||||
input,
|
||||
language,
|
||||
modelTitle,
|
||||
includeRulesInSystemMessage,
|
||||
} = msg.data;
|
||||
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Failed to load config");
|
||||
}
|
||||
|
||||
const llm = config.selectedModelByRole.chat;
|
||||
// Title can be an edit, chat, or apply model
|
||||
// Fall back to chat
|
||||
const llm =
|
||||
config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
|
||||
config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
|
||||
config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
|
||||
config.selectedModelByRole.chat;
|
||||
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
throw new Error("No model selected");
|
||||
}
|
||||
|
||||
// rules included for edit, NOT apply
|
||||
const rules = includeRulesInSystemMessage ? config.rules : undefined;
|
||||
|
||||
for await (const diffLine of streamDiffLines({
|
||||
highlighted: data.highlighted,
|
||||
prefix: data.prefix,
|
||||
suffix: data.suffix,
|
||||
highlighted,
|
||||
prefix,
|
||||
suffix,
|
||||
llm,
|
||||
rules: config.rules,
|
||||
input: data.input,
|
||||
language: data.language,
|
||||
rulesToInclude: rules,
|
||||
input,
|
||||
language,
|
||||
onlyOneInsertion: false,
|
||||
overridePrompt: undefined,
|
||||
})) {
|
||||
|
|
|
|||
1
core/edit/constants.ts
Normal file
1
core/edit/constants.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export const EDIT_MODE_STREAM_ID = "edit-mode";
|
||||
102
core/edit/recursiveStream.ts
Normal file
102
core/edit/recursiveStream.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { ChatMessage, ILLM, Prediction, PromptLog } from "..";
|
||||
import { DEFAULT_MAX_TOKENS } from "../llm/constants";
|
||||
import { countTokens } from "../llm/countTokens";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
const INFINITE_STREAM_SAFETY = 0.9;
|
||||
|
||||
const DUD_PROMPT_LOG: PromptLog = {
|
||||
modelTitle: "",
|
||||
completionOptions: { model: "" },
|
||||
prompt: "",
|
||||
completion: "",
|
||||
};
|
||||
|
||||
const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
|
||||
|
||||
export async function* recursiveStream(
|
||||
llm: ILLM,
|
||||
prompt: ChatMessage[] | string,
|
||||
prediction: Prediction | undefined,
|
||||
currentBuffer = "",
|
||||
isContinuation = false,
|
||||
): AsyncGenerator<string | ChatMessage> {
|
||||
const maxTokens = llm.completionOptions?.maxTokens ?? DEFAULT_MAX_TOKENS;
|
||||
const safeTokens = maxTokens * INFINITE_STREAM_SAFETY;
|
||||
let totalTokens = 0;
|
||||
let buffer = currentBuffer;
|
||||
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
|
||||
|
||||
if (typeof prompt === "string") {
|
||||
const generator = llm.streamComplete(prompt, new AbortController().signal, {
|
||||
raw: true,
|
||||
prediction: undefined,
|
||||
reasoning: false,
|
||||
});
|
||||
|
||||
for await (const chunk of generator) {
|
||||
yield chunk;
|
||||
buffer += chunk;
|
||||
totalTokens += countTokens(chunk);
|
||||
|
||||
if (totalTokens >= safeTokens) {
|
||||
throw new Error(
|
||||
"Token limit reached. File/range likely too large for this edit",
|
||||
);
|
||||
// const continuationPrompt = `${RECURSIVE_PROMPT}:\n\n${buffer}`;
|
||||
|
||||
// await generator.return(DUD_PROMPT_LOG); // kill the previous generator
|
||||
|
||||
// // TODO - Prediction capabilities lost because of partial input
|
||||
// yield* recursiveStream(
|
||||
// llm,
|
||||
// continuationPrompt,
|
||||
// undefined,
|
||||
// buffer,
|
||||
// true,
|
||||
// ); // Recursively stream the continuation
|
||||
|
||||
// return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const generator = llm.streamChat(prompt, new AbortController().signal, {
|
||||
prediction,
|
||||
reasoning: false,
|
||||
});
|
||||
|
||||
for await (const chunk of generator) {
|
||||
yield chunk;
|
||||
const rendered = renderChatMessage(chunk);
|
||||
buffer += rendered;
|
||||
totalTokens += countTokens(chunk.content);
|
||||
|
||||
if (totalTokens >= safeTokens) {
|
||||
throw new Error(
|
||||
"Token limit reached. File/range likely too large for this edit",
|
||||
);
|
||||
// const continuationPrompt: ChatMessage[] = [
|
||||
// ...(isContinuation ? prompt.slice(0, -2) : prompt),
|
||||
// {
|
||||
// role: "assistant",
|
||||
// content: buffer,
|
||||
// },
|
||||
// {
|
||||
// role: "user",
|
||||
// content: RECURSIVE_PROMPT,
|
||||
// },
|
||||
// ];
|
||||
|
||||
// await generator.return(DUD_PROMPT_LOG);
|
||||
// yield* recursiveStream(
|
||||
// llm,
|
||||
// continuationPrompt,
|
||||
// undefined,
|
||||
// buffer,
|
||||
// true,
|
||||
// );
|
||||
// return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -22,8 +22,9 @@ import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRule
|
|||
import { gptEditPrompt } from "../llm/templates/edit";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
import { recursiveStream } from "./recursiveStream";
|
||||
|
||||
function constructPrompt(
|
||||
function constructEditPrompt(
|
||||
prefix: string,
|
||||
highlighted: string,
|
||||
suffix: string,
|
||||
|
|
@ -66,7 +67,7 @@ export async function* streamDiffLines({
|
|||
language,
|
||||
onlyOneInsertion,
|
||||
overridePrompt,
|
||||
rules,
|
||||
rulesToInclude,
|
||||
}: {
|
||||
prefix: string;
|
||||
highlighted: string;
|
||||
|
|
@ -76,7 +77,7 @@ export async function* streamDiffLines({
|
|||
language: string | undefined;
|
||||
onlyOneInsertion: boolean;
|
||||
overridePrompt: ChatMessage[] | undefined;
|
||||
rules: RuleWithSource[];
|
||||
rulesToInclude: RuleWithSource[] | undefined;
|
||||
}): AsyncGenerator<DiffLine> {
|
||||
void Telemetry.capture(
|
||||
"inlineEdit",
|
||||
|
|
@ -99,38 +100,38 @@ export async function* streamDiffLines({
|
|||
oldLines = [];
|
||||
}
|
||||
|
||||
// Defaults to creating an edit prompt
|
||||
// For apply can be overridden with simply apply prompt
|
||||
let prompt =
|
||||
overridePrompt ??
|
||||
constructPrompt(prefix, highlighted, suffix, llm, input, language);
|
||||
constructEditPrompt(prefix, highlighted, suffix, llm, input, language);
|
||||
|
||||
// Rules will be included with edit prompt
|
||||
// Rules can be included with edit prompt
|
||||
// If any rules are present this will result in using chat instead of legacy completion
|
||||
const lastUserMessage =
|
||||
typeof prompt === "string"
|
||||
? ({
|
||||
role: "user",
|
||||
content: prompt,
|
||||
} as UserChatMessage)
|
||||
: (findLast(
|
||||
prompt,
|
||||
(msg) => msg.role === "user" || msg.role === "tool",
|
||||
) as UserChatMessage | ToolResultChatMessage | undefined);
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
rules,
|
||||
userMessage: lastUserMessage,
|
||||
baseSystemMessage: undefined,
|
||||
});
|
||||
const systemMessage = rulesToInclude
|
||||
? getSystemMessageWithRules({
|
||||
rules: rulesToInclude,
|
||||
userMessage:
|
||||
typeof prompt === "string"
|
||||
? ({
|
||||
role: "user",
|
||||
content: prompt,
|
||||
} as UserChatMessage)
|
||||
: (findLast(
|
||||
prompt,
|
||||
(msg) => msg.role === "user" || msg.role === "tool",
|
||||
) as UserChatMessage | ToolResultChatMessage | undefined),
|
||||
baseSystemMessage: undefined,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (systemMessage) {
|
||||
if (typeof prompt === "string") {
|
||||
// Removed system prompt because it was causing it to be used for Apply
|
||||
// We should bring it back only for Edit
|
||||
prompt = [
|
||||
// {
|
||||
// role: "system",
|
||||
// content: systemMessage,
|
||||
// },
|
||||
{
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: prompt,
|
||||
|
|
@ -141,10 +142,10 @@ export async function* streamDiffLines({
|
|||
if (curSysMsg) {
|
||||
curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
|
||||
} else {
|
||||
// prompt.unshift({
|
||||
// role: "system",
|
||||
// content: systemMessage,
|
||||
// });
|
||||
prompt.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -156,17 +157,7 @@ export async function* streamDiffLines({
|
|||
content: highlighted,
|
||||
};
|
||||
|
||||
const completion =
|
||||
typeof prompt === "string"
|
||||
? llm.streamComplete(prompt, new AbortController().signal, {
|
||||
raw: true,
|
||||
prediction,
|
||||
reasoning: false,
|
||||
})
|
||||
: llm.streamChat(prompt, new AbortController().signal, {
|
||||
prediction,
|
||||
reasoning: false,
|
||||
});
|
||||
const completion = recursiveStream(llm, prompt, prediction);
|
||||
|
||||
let lines = streamLines(completion);
|
||||
|
||||
|
|
|
|||
30
core/index.d.ts
vendored
30
core/index.d.ts
vendored
|
|
@ -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;
|
||||
|
|
@ -917,7 +910,8 @@ export type TemplateType =
|
|||
| "llava"
|
||||
| "gemma"
|
||||
| "granite"
|
||||
| "llama3";
|
||||
| "llama3"
|
||||
| "codestral";
|
||||
|
||||
export interface RequestOptions {
|
||||
timeout?: number;
|
||||
|
|
@ -1052,6 +1046,7 @@ export interface ModelDescription {
|
|||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
baseAgentSystemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: { [key: string]: string };
|
||||
|
|
@ -1120,16 +1115,19 @@ export interface StdioOptions {
|
|||
command: string;
|
||||
args: string[];
|
||||
env?: Record<string, string>;
|
||||
requestOptions?: RequestOptions;
|
||||
}
|
||||
|
||||
export interface WebSocketOptions {
|
||||
type: "websocket";
|
||||
url: string;
|
||||
requestOptions?: RequestOptions;
|
||||
}
|
||||
|
||||
export interface SSEOptions {
|
||||
type: "sse";
|
||||
url: string;
|
||||
requestOptions?: RequestOptions;
|
||||
}
|
||||
|
||||
export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
|
||||
|
|
@ -1211,15 +1209,9 @@ export interface ExperimentalModelRoles {
|
|||
export interface ExperimentalMCPOptions {
|
||||
transport: TransportOptions;
|
||||
faviconUrl?: string;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
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
|
||||
|
|
@ -1507,8 +1499,10 @@ export interface RuleWithSource {
|
|||
name?: string;
|
||||
slug?: string;
|
||||
source:
|
||||
| "default"
|
||||
| "default-chat"
|
||||
| "default-agent"
|
||||
| "model-chat-options"
|
||||
| "model-agent-options"
|
||||
| "rules-block"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
anthropicTemplateMessages,
|
||||
chatmlTemplateMessages,
|
||||
codeLlama70bTemplateMessages,
|
||||
codestralTemplateMessages,
|
||||
deepseekTemplateMessages,
|
||||
gemmaTemplateMessage,
|
||||
graniteTemplateMessages,
|
||||
|
|
@ -295,6 +296,7 @@ function autodetectTemplateFunction(
|
|||
gemma: gemmaTemplateMessage,
|
||||
granite: graniteTemplateMessages,
|
||||
llama3: llama3TemplateMessages,
|
||||
codestral: codestralTemplateMessages,
|
||||
none: null,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -14,9 +14,11 @@ import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
|||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
const EDIT_MESSAGE = `\
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
|
|
@ -24,31 +26,31 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
|||
unmodified sections. For example:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... rest of code here ...
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of code here ...
|
||||
// ... existing code ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... rest of code here ...
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
In existing files, you should always restate the function or class that the snippet belongs to:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... rest of code here ...
|
||||
|
||||
// ... existing code ...
|
||||
|
||||
function exampleFunction() {
|
||||
// ... rest of code here ...
|
||||
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of code here ...
|
||||
|
||||
// ... rest of function ...
|
||||
}
|
||||
|
||||
// ... rest of code here ...
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
Since users have access to their complete file, they prefer reading only the
|
||||
|
|
@ -56,11 +58,29 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
|||
at the beginning, middle, or end of files using these "lazy" comments. Only
|
||||
provide the complete file when explicitly requested. Include a concise explanation
|
||||
of changes unless the user specifically asks for code only.
|
||||
`
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in chat mode.
|
||||
|
||||
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
|
||||
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
|
||||
${EDIT_MESSAGE}
|
||||
</important_rules>`;
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in agent mode.
|
||||
|
||||
${EDIT_MESSAGE}
|
||||
</important_rules>`;
|
||||
|
||||
export function constructMessages(
|
||||
messageMode: string,
|
||||
history: ChatHistoryItem[],
|
||||
baseChatSystemMessage: string | undefined,
|
||||
baseChatOrAgentSystemMessage: string | undefined,
|
||||
rules: RuleWithSource[],
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
|
|
@ -71,6 +91,14 @@ export function constructMessages(
|
|||
for (let i = 0; i < filteredHistory.length; i++) {
|
||||
const historyItem = filteredHistory[i];
|
||||
|
||||
if (messageMode === "chat") {
|
||||
const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage;
|
||||
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
|
||||
// remove all tool calls from the history
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (historyItem.message.role === "user") {
|
||||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(historyItem.message);
|
||||
|
|
@ -100,7 +128,7 @@ export function constructMessages(
|
|||
| undefined;
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
baseSystemMessage: baseChatOrAgentSystemMessage,
|
||||
rules,
|
||||
userMessage: lastUserMsg,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -355,7 +355,7 @@ function compileChatMessages({
|
|||
lastToolCallsMsg = msgsCopy.pop();
|
||||
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
|
||||
throw new Error(
|
||||
`Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`,
|
||||
`Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ class Cerebras extends OpenAI {
|
|||
private static modelConversion: { [key: string]: string } = {
|
||||
"llama3.1-8b": "llama3.1-8b",
|
||||
"llama3.1-70b": "llama3.1-70b",
|
||||
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct"
|
||||
};
|
||||
protected _convertModelName(model: string): string {
|
||||
return Cerebras.modelConversion[model] ?? model;
|
||||
|
|
|
|||
|
|
@ -31,26 +31,10 @@ const NON_CHAT_MODELS = [
|
|||
"ada",
|
||||
];
|
||||
|
||||
const CHAT_ONLY_MODELS = [
|
||||
"gpt-3.5-turbo",
|
||||
"gpt-3.5-turbo-0613",
|
||||
"gpt-3.5-turbo-16k",
|
||||
"gpt-4",
|
||||
"gpt-4-turbo",
|
||||
"gpt-4o",
|
||||
"gpt-35-turbo-16k",
|
||||
"gpt-35-turbo-0613",
|
||||
"gpt-35-turbo",
|
||||
"gpt-4-32k",
|
||||
"gpt-4-turbo-preview",
|
||||
"gpt-4-vision",
|
||||
"gpt-4-0125-preview",
|
||||
"gpt-4-1106-preview",
|
||||
"gpt-4o-mini",
|
||||
"o1-preview",
|
||||
"o1-mini",
|
||||
"o3-mini",
|
||||
];
|
||||
function isChatOnlyModel(model: string): boolean {
|
||||
// gpt and o-series models
|
||||
return model.startsWith("gpt") || model.startsWith("o");
|
||||
}
|
||||
|
||||
const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => {
|
||||
return messages?.map((message: any) => {
|
||||
|
|
@ -335,7 +319,7 @@ class OpenAI extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (
|
||||
!CHAT_ONLY_MODELS.includes(options.model) &&
|
||||
!isChatOnlyModel(options.model) &&
|
||||
this.supportsCompletions() &&
|
||||
(NON_CHAT_MODELS.includes(options.model) ||
|
||||
this.useLegacyCompletionsEndpoint ||
|
||||
|
|
|
|||
|
|
@ -160,6 +160,7 @@ export async function llmFromDescription(
|
|||
cls.defaultOptions?.completionOptions?.maxTokens,
|
||||
},
|
||||
baseChatSystemMessage,
|
||||
baseAgentSystemMessage: baseChatSystemMessage,
|
||||
logger: llmLogger,
|
||||
uniqueId,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -93,6 +93,15 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
|
|||
return prompt;
|
||||
}
|
||||
|
||||
// Llama2 template with added \n to prevent Codestral from continuing user message
|
||||
function codestralTemplateMessages(msgs: ChatMessage[]): string {
|
||||
let template = llama2TemplateMessages(msgs);
|
||||
if (template.length === 0) {
|
||||
return template;
|
||||
}
|
||||
return template + "\n";
|
||||
}
|
||||
|
||||
function anthropicTemplateMessages(messages: ChatMessage[]): string {
|
||||
const HUMAN_PROMPT = "\n\nHuman:";
|
||||
const AI_PROMPT = "\n\nAssistant:";
|
||||
|
|
@ -300,4 +309,5 @@ export {
|
|||
templateAlpacaMessages,
|
||||
xWinCoderTemplateMessages,
|
||||
zephyrTemplateMessages,
|
||||
codestralTemplateMessages,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -150,6 +150,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
input: string;
|
||||
language: string | undefined;
|
||||
modelTitle: string | undefined;
|
||||
includeRulesInSystemMessage: boolean;
|
||||
},
|
||||
AsyncGenerator<DiffLine>,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export const editFileTool: Tool = {
|
|||
changes: {
|
||||
type: "string",
|
||||
description:
|
||||
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock. Use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... rest of code here ...'",
|
||||
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@ export const logger = winston.createLogger({
|
|||
format: winston.format.json(),
|
||||
transports: [
|
||||
// Write all logs with importance level of `info` or higher to `info.log`
|
||||
new winston.transports.File({ filename: "e2e.log", level: "info" }),
|
||||
...(process.env.NODE_ENV === "test"
|
||||
? [new winston.transports.File({ filename: "e2e.log", level: "info" })]
|
||||
: []),
|
||||
// Normal console.log behavior
|
||||
new winston.transports.Console(),
|
||||
],
|
||||
|
|
|
|||
|
|
@ -134,7 +134,13 @@ Yes, in VS Code, if you don't want to be shown suggestions automatically you can
|
|||
|
||||
### Is there a shortcut to accept one line at a time?
|
||||
|
||||
This is a built-in feature of VS Code, but it's just a bit hidden. See this great [StackOverflow answer](https://stackoverflow.com/questions/72228174/accept-line-by-line-from-autocompletion/78001122#78001122) for more details.
|
||||
This is a built-in feature of VS Code, but it's just a bit hidden. Follow these settings to reassign the keyboard shortcuts in VS Code:
|
||||
1. Press `Ctrl+Shift+P`, type the command: `Preferences: Open Keyboard Shortcuts`, and enter the keyboard shortcuts settings page.
|
||||
2. Search for `editor.action.inlineSuggest.acceptNextLine`.
|
||||
3. Set the key binding to `Tab`.
|
||||
4. Set the trigger condition (when) to `inlineSuggestionVisible && !editorReadonly`.
|
||||
This will make multi-line completion (including continue and from VS Code built-in or other plugin snippets) still work, and you will see multi-line completion. However, Tab will only fill in one line at a time. Any unnecessary code can be canceled with `Esc`.
|
||||
If you need to apply all the code, just press `Tab` multiple times.
|
||||
|
||||
### How to turn off autocomplete
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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_**
|
||||
|
||||

|
||||
|
||||
**_Add all open files dropdown_**
|
||||
|
||||

|
||||
|
||||
### 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.
|
||||
|
||||

|
||||
|
||||
### 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_**
|
||||
|
||||

|
||||
|
||||
**_Diffs_**
|
||||
|
||||

|
||||
|
||||
## 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.
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ from [the Hub](https://hub.continue.dev/explore/assistants) or locally
|
|||
- 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:
|
||||
|
|
@ -189,10 +189,11 @@ chat, editing, and summarizing.
|
|||
- `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
|
||||
`autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chat` 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.
|
||||
|
|
@ -380,6 +381,7 @@ prompts, context, and tool use. Continue supports any MCP server with the MCP co
|
|||
- `command` (**required**): The command used to start the server.
|
||||
- `args`: An optional array of arguments for the command.
|
||||
- `env`: An optional map of environment variables for the server process.
|
||||
- `connectionTimeout`: An optional connection timeout number to the server in milliseconds.
|
||||
|
||||
**Example:**
|
||||
|
||||
|
|
|
|||
BIN
docs/static/img/edit-mode-add-all-open-files.png
vendored
BIN
docs/static/img/edit-mode-add-all-open-files.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB |
BIN
docs/static/img/edit-mode-add-files.png
vendored
BIN
docs/static/img/edit-mode-add-files.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 29 KiB |
BIN
docs/static/img/edit-mode-multi-file-diffs.png
vendored
BIN
docs/static/img/edit-mode-multi-file-diffs.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 256 KiB |
BIN
docs/static/img/edit-mode-multi-file-generation.png
vendored
BIN
docs/static/img/edit-mode-multi-file-generation.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 61 KiB |
BIN
docs/static/img/edit-mode-multi-file-output.png
vendored
BIN
docs/static/img/edit-mode-multi-file-output.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 71 KiB |
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.15
|
||||
pluginVersion=1.0.16
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.TelemetryService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
|
||||
import com.intellij.ide.plugins.PluginManager
|
||||
import com.intellij.openapi.components.service
|
||||
|
|
@ -59,18 +60,14 @@ class CoreMessengerManager(
|
|||
try {
|
||||
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
|
||||
|
||||
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val responseObject = response as Map<*, *>
|
||||
val responseContent = responseObject["content"] as Map<*, *>
|
||||
val result = responseContent["result"] as Map<*, *>
|
||||
val config = result["config"] as Map<String, Any>
|
||||
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val allowAnonymousTelemetry = response.castNestedOrNull<Boolean>("content", "result", "config", "allowAnonymousTelemetry")
|
||||
|
||||
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
|
||||
val telemetryService = service<TelemetryService>()
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
|
||||
telemetryService.setup(getMachineUniqueID())
|
||||
}
|
||||
val telemetryService = service<TelemetryService>()
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
|
||||
telemetryService.setup(getMachineUniqueID())
|
||||
}
|
||||
}
|
||||
|
||||
// On exit, use exponential backoff to create another CoreMessenger
|
||||
coreMessenger?.onDidExit {
|
||||
|
|
|
|||
|
|
@ -518,18 +518,10 @@ class IdeProtocolClient(
|
|||
null
|
||||
) { response ->
|
||||
try {
|
||||
val responseObject = response as Map<*, *>
|
||||
val responseContent = responseObject["content"] as Map<*, *>
|
||||
val result = responseContent["result"] as Map<*, *>
|
||||
val config = result["config"] as Map<*, *>
|
||||
|
||||
val selectedModels = config["selectedModelByRole"] as? Map<*, *>
|
||||
var applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *>
|
||||
val selectedModels = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "selectedModelByRole")
|
||||
|
||||
// If "apply" role model is not found, try "chat" role
|
||||
if (applyCodeBlockModel == null) {
|
||||
applyCodeBlockModel = selectedModels?.get("chat") as? Map<*, *>
|
||||
}
|
||||
val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
|
||||
|
||||
if (applyCodeBlockModel != null) {
|
||||
continuation.resume(applyCodeBlockModel)
|
||||
|
|
@ -596,7 +588,7 @@ class IdeProtocolClient(
|
|||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
||||
diffStreamHandler.streamDiffLinesToEditor(
|
||||
prompt, prefix, highlighted, suffix, llmTitle
|
||||
prompt, prefix, highlighted, suffix, llmTitle, false
|
||||
)
|
||||
|
||||
respond(null)
|
||||
|
|
|
|||
|
|
@ -87,7 +87,7 @@ class DiffStreamHandler(
|
|||
}
|
||||
|
||||
fun streamDiffLinesToEditor(
|
||||
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String
|
||||
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String, includeRulesInSystemMessage: Boolean
|
||||
) {
|
||||
isRunning = true
|
||||
this.sendUpdate("streaming")
|
||||
|
|
@ -96,7 +96,7 @@ class DiffStreamHandler(
|
|||
val virtualFile = getVirtualFile()
|
||||
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle), null
|
||||
"streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle, includeRulesInSystemMessage), null
|
||||
) { response ->
|
||||
if (!isRunning) return@request
|
||||
|
||||
|
|
@ -274,7 +274,8 @@ class DiffStreamHandler(
|
|||
highlighted: String,
|
||||
suffix: String,
|
||||
virtualFile: VirtualFile?,
|
||||
modelTitle: String
|
||||
modelTitle: String,
|
||||
includeRulesInSystemMessage: Boolean
|
||||
): Map<String, Any?> {
|
||||
return mapOf(
|
||||
"input" to input,
|
||||
|
|
@ -282,7 +283,8 @@ class DiffStreamHandler(
|
|||
"highlighted" to highlighted,
|
||||
"suffix" to suffix,
|
||||
"language" to virtualFile?.fileType?.name,
|
||||
"modelTitle" to modelTitle
|
||||
"modelTitle" to modelTitle,
|
||||
"includeRulesInSystemMessage" to includeRulesInSystemMessage,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.editor
|
|||
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
|
||||
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
|
||||
import com.intellij.openapi.Disposable
|
||||
|
|
@ -130,12 +131,11 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
val modelTitles = mutableListOf<String>()
|
||||
|
||||
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val content = (response as Map<String, Any>)["content"] as Map<String, Any>
|
||||
val result = content["result"] as Map<String, Any>
|
||||
val config = result["config"] as Map<String, Any>
|
||||
val models = config["modelsByRole"] as Map<String, Any>
|
||||
val editModels = models["edit"] as List<Map<String, Any>>
|
||||
modelTitles.addAll(editModels.map { it["title"] as String })
|
||||
val modelsByRole = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
|
||||
val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
|
||||
modelsByRole.castNestedOrNull<List<*>>(role)
|
||||
?.mapNotNull { it.castNestedOrNull<String>("title") }
|
||||
?.let(modelTitles::addAll)
|
||||
}
|
||||
|
||||
// This is a hacky way to not complicate getting model titles with coroutines
|
||||
|
|
@ -222,7 +222,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
|
||||
customPanelRef.get().enter()
|
||||
diffStreamHandler.streamDiffLinesToEditor(
|
||||
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret
|
||||
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -73,8 +73,7 @@ class VerticalDiffBlock(
|
|||
|
||||
deletedLines.add(deletedText.trimEnd())
|
||||
|
||||
// Unable to ensure that text length has not changed, so we need to get it again
|
||||
editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength))
|
||||
editor.document.deleteString(startOffset, endOffset)
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -80,4 +80,16 @@ fun uuid(): String {
|
|||
return UUID.randomUUID().toString()
|
||||
}
|
||||
|
||||
fun VirtualFile.toUriOrNull(): String? = fileSystem.getNioPath(this)?.toUri()?.toString()?.removeSuffix("/")
|
||||
fun VirtualFile.toUriOrNull(): String? = fileSystem.getNioPath(this)?.toUri()?.toString()?.removeSuffix("/")
|
||||
|
||||
inline fun <reified T> Any?.castNestedOrNull(vararg keys: String): T? {
|
||||
return getNestedOrNull(*keys) as? T
|
||||
}
|
||||
|
||||
fun Any?.getNestedOrNull(vararg keys: String): Any? {
|
||||
var result = this
|
||||
for (key in keys) {
|
||||
result = (result as? Map<*, *>)?.get(key) ?: return null
|
||||
}
|
||||
return result
|
||||
}
|
||||
4
extensions/intellij/src/main/resources/icons/close.svg
Normal file
4
extensions/intellij/src/main/resources/icons/close.svg
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
<!-- Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 14.25C11.4518 14.25 14.25 11.4518 14.25 8C14.25 4.54822 11.4518 1.75 8 1.75C4.54822 1.75 1.75 4.54822 1.75 8C1.75 11.4518 4.54822 14.25 8 14.25ZM4.54 5.46L5.45924 4.54076L8 7.08152L10.5408 4.54076L11.46 5.46L8.91924 8.00076L11.4592 10.5408L10.54 11.46L8 8.92L5.46 11.46L4.54076 10.5408L7.08076 8.00076L4.54 5.46Z" fill="#7F8B91" fill-opacity="0.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 656 B |
|
|
@ -1515,7 +1515,7 @@
|
|||
"then": {
|
||||
"properties": {
|
||||
"model": {
|
||||
"enum": ["llama3.1-8b", "llama3.1-70b"]
|
||||
"enum": ["llama3.1-8b", "llama3.1-70b", "llama-4-scout-17b-16e-instruct"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,6 +91,20 @@ export class GUIActions {
|
|||
await dropdownOption.click();
|
||||
};
|
||||
|
||||
public static selectModeFromDropdown = async (
|
||||
view: WebView,
|
||||
option: string,
|
||||
) => {
|
||||
const dropdownButton = await GUISelectors.getModeDropdownButton(view);
|
||||
await dropdownButton.click();
|
||||
|
||||
const dropdownOption = await TestUtils.waitForSuccess(() => {
|
||||
return GUISelectors.getModeDropdownOption(view, option);
|
||||
});
|
||||
|
||||
await dropdownOption.click();
|
||||
};
|
||||
|
||||
public static async sendMessage({
|
||||
view,
|
||||
message,
|
||||
|
|
|
|||
|
|
@ -67,6 +67,10 @@ export class GUISelectors {
|
|||
return SelectorUtils.getElementByDataTestId(view, "model-select-button");
|
||||
}
|
||||
|
||||
public static getModeDropdownButton(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(view, "mode-select-button");
|
||||
}
|
||||
|
||||
public static getFirstContextProviderDropdownItem(view: WebView) {
|
||||
return SelectorUtils.getElementByDataTestId(
|
||||
view,
|
||||
|
|
@ -104,6 +108,12 @@ export class GUISelectors {
|
|||
);
|
||||
}
|
||||
|
||||
public static getModeDropdownOption(view: WebView, option: string) {
|
||||
return view.findWebElement(
|
||||
By.xpath(`//*[@role="listbox"]//*[contains(text(), "${option}")]`),
|
||||
);
|
||||
}
|
||||
|
||||
public static getOnboardingTabButton(view: WebView, title: string) {
|
||||
return SelectorUtils.getElementByDataTestId(
|
||||
view,
|
||||
|
|
|
|||
|
|
@ -43,6 +43,8 @@ models:
|
|||
- chat
|
||||
- edit
|
||||
- apply
|
||||
capabilities:
|
||||
- tool_use
|
||||
|
||||
- name: SYSTEM MESSAGE MOCK LLM
|
||||
provider: mock
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@
|
|||
"provider": "mock",
|
||||
"title": "TOOL MOCK LLM",
|
||||
"model": "claude-3-5-sonnet-latest",
|
||||
"capabilities": {
|
||||
"tools": true
|
||||
},
|
||||
"requestOptions": {
|
||||
"extraBodyProperties": {
|
||||
"chatStream": [
|
||||
|
|
|
|||
|
|
@ -239,10 +239,13 @@ describe("GUI Test", () => {
|
|||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
});
|
||||
|
||||
describe("Chat with tools", () => {
|
||||
it("should render tool call", async () => {
|
||||
describe("Agent with tools", () => {
|
||||
beforeEach(async () => {
|
||||
await GUIActions.selectModelFromDropdown(view, "TOOL MOCK LLM");
|
||||
await GUIActions.selectModeFromDropdown(view, "Agent");
|
||||
});
|
||||
|
||||
it("should render tool call", async () => {
|
||||
const [messageInput] = await GUISelectors.getMessageInputFields(view);
|
||||
await messageInput.sendKeys("Hello");
|
||||
await messageInput.sendKeys(Key.ENTER);
|
||||
|
|
@ -260,10 +263,6 @@ describe("GUI Test", () => {
|
|||
it("should call tool after approval", async () => {
|
||||
await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);
|
||||
|
||||
await TestUtils.waitForSuccess(() =>
|
||||
GUIActions.selectModelFromDropdown(view, "TOOL MOCK LLM"),
|
||||
);
|
||||
|
||||
const [messageInput] = await GUISelectors.getMessageInputFields(view);
|
||||
await messageInput.sendKeys("Hello");
|
||||
await messageInput.sendKeys(Key.ENTER);
|
||||
|
|
@ -285,10 +284,6 @@ describe("GUI Test", () => {
|
|||
it("should cancel tool", async () => {
|
||||
await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);
|
||||
|
||||
await TestUtils.waitForSuccess(() =>
|
||||
GUIActions.selectModelFromDropdown(view, "TOOL MOCK LLM"),
|
||||
);
|
||||
|
||||
const [messageInput] = await GUISelectors.getMessageInputFields(view);
|
||||
await messageInput.sendKeys("Hello");
|
||||
await messageInput.sendKeys(Key.ENTER);
|
||||
|
|
|
|||
14
extensions/vscode/package-lock.json
generated
14
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.29",
|
||||
"version": "1.1.31",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.29",
|
||||
"version": "1.1.31",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -89,7 +89,7 @@
|
|||
"ovsx": "^0.8.3",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^4.5.13",
|
||||
"vite": "^4.5.14",
|
||||
"vsce": "^2.15.0",
|
||||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
|
|
@ -108,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",
|
||||
|
|
@ -13442,9 +13442,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "4.5.13",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.13.tgz",
|
||||
"integrity": "sha512-Hgp8IF/yZDzKsN1hQWOuQZbrKiaFsbQud+07jJ8h9m9PaHWkpvZ5u55Xw5yYjWRXwRQ4jwFlJvY7T7FUJG9MCA==",
|
||||
"version": "4.5.14",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.14.tgz",
|
||||
"integrity": "sha512-+v57oAaoYNnO3hIu5Z/tJRZjq5aHM2zDve9YZ8HngVHbhk66RStobhb1sqPMIPEleV6cNKYK4eGrAbE9Ulbl2g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.30",
|
||||
"version": "1.1.33",
|
||||
"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",
|
||||
|
|
@ -661,7 +656,7 @@
|
|||
"ovsx": "^0.8.3",
|
||||
"rimraf": "^5.0.5",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^4.5.13",
|
||||
"vite": "^4.5.14",
|
||||
"vsce": "^2.15.0",
|
||||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -209,10 +209,9 @@ async function package(target, os, arch, exe) {
|
|||
: `${target}${os === "linux" ? "-gnu" : ""}`
|
||||
}/index.node`,
|
||||
`out/node_modules/esbuild/lib/main.js`,
|
||||
`out/node_modules/esbuild/bin/esbuild`,
|
||||
]);
|
||||
}
|
||||
|
||||
(async () => {
|
||||
void (async () => {
|
||||
await package(target, os, arch, exe);
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ const isWinTarget = target?.startsWith("win");
|
|||
const isLinuxTarget = target?.startsWith("linux");
|
||||
const isMacTarget = target?.startsWith("darwin");
|
||||
|
||||
(async () => {
|
||||
void (async () => {
|
||||
console.log("[info] Packaging extension for target ", target);
|
||||
|
||||
// Generate and copy over config-yaml-schema.json
|
||||
|
|
@ -464,6 +464,9 @@ const isMacTarget = target?.startsWith("darwin");
|
|||
),
|
||||
);
|
||||
|
||||
// delete esbuild/bin because platform-specific @esbuild is downloaded
|
||||
fs.rmdirSync(`out/node_modules/esbuild/bin`, { recursive: true });
|
||||
|
||||
console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
|
||||
|
||||
// Copy over any worker files
|
||||
|
|
@ -530,6 +533,5 @@ const isMacTarget = target?.startsWith("darwin");
|
|||
}`,
|
||||
`out/node_modules/@lancedb/vectordb-${target}${isWinTarget ? "-msvc" : ""}${isLinuxTarget ? "-gnu" : ""}/index.node`,
|
||||
`out/node_modules/esbuild/lib/main.js`,
|
||||
`out/node_modules/esbuild/bin/esbuild`,
|
||||
]);
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -301,6 +301,9 @@ async function copyNodeModules() {
|
|||
),
|
||||
);
|
||||
|
||||
// delete esbuild/bin because platform-specific @esbuild is downloaded
|
||||
fs.rmdirSync(`out/node_modules/esbuild/bin`, {recursive: true});
|
||||
|
||||
console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,8 +76,8 @@ class VsCodeIde implements IDE {
|
|||
|
||||
async fileExists(uri: string): Promise<boolean> {
|
||||
try {
|
||||
await vscode.workspace.fs.stat(vscode.Uri.parse(uri));
|
||||
return true;
|
||||
const stat = await this.ideUtils.stat(vscode.Uri.parse(uri));
|
||||
return stat !== null;
|
||||
} catch (error) {
|
||||
if (error instanceof vscode.FileSystemError) {
|
||||
return false;
|
||||
|
|
@ -335,10 +335,10 @@ class VsCodeIde implements IDE {
|
|||
const pathToLastModified: FileStatsMap = {};
|
||||
await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const stat = await vscode.workspace.fs.stat(vscode.Uri.parse(file));
|
||||
const stat = await this.ideUtils.stat(vscode.Uri.parse(file), false /* No need to catch ENOPRO exceptions */);
|
||||
pathToLastModified[file] = {
|
||||
lastModified: stat.mtime,
|
||||
size: stat.size,
|
||||
lastModified: stat!.mtime,
|
||||
size: stat!.size,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
|
@ -400,7 +400,10 @@ class VsCodeIde implements IDE {
|
|||
vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
|
||||
const configs: ContinueRcJson[] = [];
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const files = await vscode.workspace.fs.readDirectory(workspaceDir);
|
||||
const files = await this.ideUtils.readDirectory(workspaceDir);
|
||||
if (files === null) {//Unlikely, but just in case...
|
||||
continue;
|
||||
}
|
||||
for (const [filename, type] of files) {
|
||||
if (
|
||||
(type === vscode.FileType.File ||
|
||||
|
|
@ -512,12 +515,15 @@ class VsCodeIde implements IDE {
|
|||
return openTextDocument.getText();
|
||||
}
|
||||
|
||||
const fileStats = await vscode.workspace.fs.stat(uri);
|
||||
if (fileStats.size > 10 * VsCodeIde.MAX_BYTES) {
|
||||
const fileStats = await this.ideUtils.stat(uri);
|
||||
if (fileStats === null || fileStats.size > 10 * VsCodeIde.MAX_BYTES) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const bytes = await vscode.workspace.fs.readFile(uri);
|
||||
const bytes = await this.ideUtils.readFile(uri);
|
||||
if (bytes === null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Truncate the buffer to the first MAX_BYTES
|
||||
const truncatedBytes = bytes.slice(0, VsCodeIde.MAX_BYTES);
|
||||
|
|
@ -599,7 +605,10 @@ class VsCodeIde implements IDE {
|
|||
|
||||
const ignoreGlobs: Set<string> = new Set();
|
||||
for (const file of ignoreFiles) {
|
||||
const content = await vscode.workspace.fs.readFile(file);
|
||||
const content = await this.ideUtils.readFile(file);
|
||||
if (content === null) {
|
||||
continue;
|
||||
}
|
||||
const filePath = vscode.workspace.asRelativePath(file);
|
||||
const fileDir = filePath
|
||||
.replace(/\\/g, "/")
|
||||
|
|
@ -743,7 +752,8 @@ class VsCodeIde implements IDE {
|
|||
}
|
||||
|
||||
async listDir(dir: string): Promise<[string, FileType][]> {
|
||||
return vscode.workspace.fs.readDirectory(vscode.Uri.parse(dir)) as any;
|
||||
const entries = await this.ideUtils.readDirectory(vscode.Uri.parse(dir));
|
||||
return entries === null? [] : entries as any;
|
||||
}
|
||||
|
||||
private getIdeSettingsSync(): IdeSettings {
|
||||
|
|
|
|||
|
|
@ -181,7 +181,7 @@ export class ApplyManager {
|
|||
range: rangeToApplyTo,
|
||||
newCode: text,
|
||||
toolCallId,
|
||||
rules: config.rules,
|
||||
rulesToInclude: undefined, // No rules for apply
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import * as vscode from "vscode";
|
|||
|
||||
import { handleLLMError } from "../util/errorHandling";
|
||||
import { showFreeTrialLoginMessage } from "../util/messages";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
import { getDefinitionsFromLsp } from "./lsp";
|
||||
|
|
@ -23,8 +24,6 @@ import {
|
|||
stopStatusBarLoading,
|
||||
} from "./statusBar";
|
||||
|
||||
import type { IDE } from "core";
|
||||
|
||||
interface VsCodeCompletionInput {
|
||||
document: vscode.TextDocument;
|
||||
position: vscode.Position;
|
||||
|
|
@ -61,13 +60,15 @@ export class ContinueCompletionProvider
|
|||
|
||||
private completionProvider: CompletionProvider;
|
||||
private recentlyVisitedRanges: RecentlyVisitedRangesService;
|
||||
private recentlyEditedTracker = new RecentlyEditedTracker();
|
||||
private recentlyEditedTracker: RecentlyEditedTracker;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly ide: VsCodeIde,
|
||||
private readonly webviewProtocol: VsCodeWebviewProtocol,
|
||||
) {
|
||||
this.recentlyEditedTracker = new RecentlyEditedTracker(ide.ideUtils);
|
||||
|
||||
async function getAutocompleteModel() {
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import { getSymbolsForSnippet } from "core/autocomplete/context/ranking";
|
|||
import { RecentlyEditedRange } from "core/autocomplete/util/types";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { VsCodeIdeUtils } from "../util/ideUtils";
|
||||
|
||||
type VsCodeRecentlyEditedRange = {
|
||||
uri: vscode.Uri;
|
||||
range: vscode.Range;
|
||||
|
|
@ -21,7 +23,7 @@ export class RecentlyEditedTracker {
|
|||
private recentlyEditedDocuments: VsCodeRecentlyEditedDocument[] = [];
|
||||
private static maxRecentlyEditedDocuments = 10;
|
||||
|
||||
constructor() {
|
||||
constructor(private ideUtils: VsCodeIdeUtils) {
|
||||
vscode.workspace.onDidChangeTextDocument((event) => {
|
||||
event.contentChanges.forEach((change) => {
|
||||
const editedRange = {
|
||||
|
|
@ -112,13 +114,15 @@ export class RecentlyEditedTracker {
|
|||
private async _getContentsForRange(
|
||||
entry: Omit<VsCodeRecentlyEditedRange, "lines" | "symbols">,
|
||||
): Promise<string> {
|
||||
return vscode.workspace.fs.readFile(entry.uri).then((content) =>
|
||||
content
|
||||
const content = await this.ideUtils.readFile(entry.uri);
|
||||
if (content === null) {
|
||||
return "";
|
||||
}
|
||||
return content
|
||||
.toString()
|
||||
.split("\n")
|
||||
.slice(entry.range.start.line, entry.range.end.line + 1)
|
||||
.join("\n"),
|
||||
);
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
public async getRecentlyEditedRanges(): Promise<RecentlyEditedRange[]> {
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ const statusBarItemText = (
|
|||
error?: boolean,
|
||||
) => {
|
||||
if (error) {
|
||||
return "$(alert) Continue (FATAL ERROR)";
|
||||
return "$(alert) Continue (config error)";
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,7 @@
|
|||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
|
||||
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";
|
||||
|
|
@ -47,8 +41,12 @@ import { getMetaKeyLabel } from "./util/util";
|
|||
import { VsCodeIde } from "./VsCodeIde";
|
||||
|
||||
import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist";
|
||||
import {
|
||||
addCodeToContextFromRange,
|
||||
addEntireFileToContext,
|
||||
addHighlightedCodeToContext,
|
||||
} from "./util/addCode";
|
||||
import { openEditorAndRevealRange } from "./util/vscode";
|
||||
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
|
||||
|
||||
let fullScreenPanel: vscode.WebviewPanel | undefined;
|
||||
|
||||
|
|
@ -71,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) {
|
||||
|
|
@ -260,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) {
|
||||
|
|
@ -277,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);
|
||||
|
||||
|
|
@ -294,8 +135,6 @@ async function processDiff(
|
|||
});
|
||||
}
|
||||
|
||||
await sidebar.webviewProtocol.request("exitEditMode", undefined);
|
||||
|
||||
// Save the file
|
||||
await ide.saveFile(newOrCurrentUri);
|
||||
}
|
||||
|
|
@ -387,7 +226,7 @@ const getCommandsMap: (
|
|||
llm,
|
||||
onlyOneInsertion,
|
||||
range,
|
||||
rules: config.rules,
|
||||
rulesToInclude: config.rules,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -546,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");
|
||||
|
|
@ -826,13 +570,14 @@ const getCommandsMap: (
|
|||
for await (const fileUri of walkDirAsync(uri.toString(), ide, {
|
||||
source: "vscode continue.selectFilesAsContext command",
|
||||
})) {
|
||||
addEntireFileToContext(
|
||||
await addEntireFileToContext(
|
||||
vscode.Uri.parse(fileUri),
|
||||
sidebar.webviewProtocol,
|
||||
ide.ideUtils
|
||||
);
|
||||
}
|
||||
} else {
|
||||
addEntireFileToContext(uri, sidebar.webviewProtocol);
|
||||
await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -959,7 +704,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,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,25 +1,32 @@
|
|||
import * as vscode from "vscode";
|
||||
|
||||
export const redDecorationType = vscode.window.createTextEditorDecorationType({
|
||||
isWholeLine: true,
|
||||
backgroundColor: { id: "diffEditor.removedLineBackground" },
|
||||
color: "#808080",
|
||||
outlineWidth: "1px",
|
||||
outlineStyle: "solid",
|
||||
outlineColor: { id: "diffEditor.removedTextBorder" },
|
||||
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
|
||||
});
|
||||
|
||||
export const greenDecorationType = vscode.window.createTextEditorDecorationType(
|
||||
{
|
||||
const removedLineDecorationType = (line: string) =>
|
||||
vscode.window.createTextEditorDecorationType({
|
||||
isWholeLine: true,
|
||||
backgroundColor: { id: "diffEditor.insertedLineBackground" },
|
||||
backgroundColor: { id: "diffEditor.removedLineBackground" },
|
||||
outlineWidth: "1px",
|
||||
outlineStyle: "solid",
|
||||
outlineColor: { id: "diffEditor.insertedTextBorder" },
|
||||
outlineColor: { id: "diffEditor.removedTextBorder" },
|
||||
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
|
||||
},
|
||||
);
|
||||
after: {
|
||||
contentText: line,
|
||||
color: "#808080",
|
||||
textDecoration: "none; white-space: pre",
|
||||
},
|
||||
// NOTE this has the effect of hiding text the user enters into a red line, which may cause linting errors
|
||||
// But probably worth saving the ugly effect of having the ghost text after entered text
|
||||
// And resolved upon accept/reject when line deleted anyways
|
||||
textDecoration: "none; display: none",
|
||||
});
|
||||
|
||||
const addedLineDecorationType = vscode.window.createTextEditorDecorationType({
|
||||
isWholeLine: true,
|
||||
backgroundColor: { id: "diffEditor.insertedLineBackground" },
|
||||
outlineWidth: "1px",
|
||||
outlineStyle: "solid",
|
||||
outlineColor: { id: "diffEditor.insertedTextBorder" },
|
||||
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
|
||||
});
|
||||
|
||||
export const indexDecorationType = vscode.window.createTextEditorDecorationType(
|
||||
{
|
||||
|
|
@ -35,13 +42,19 @@ export const belowIndexDecorationType =
|
|||
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
|
||||
});
|
||||
|
||||
export class DecorationTypeRangeManager {
|
||||
constructor(
|
||||
private decorationType: vscode.TextEditorDecorationType,
|
||||
private editor: vscode.TextEditor,
|
||||
) {}
|
||||
function translateRange(range: vscode.Range, lineOffset: number): vscode.Range {
|
||||
return new vscode.Range(
|
||||
range.start.translate(lineOffset),
|
||||
range.end.translate(lineOffset),
|
||||
);
|
||||
}
|
||||
|
||||
private ranges: vscode.Range[] = [];
|
||||
// Class for managing highlight decorations for added lines (e.g. GREEN)
|
||||
export class AddedLineDecorationManager {
|
||||
constructor(private editor: vscode.TextEditor) {}
|
||||
|
||||
ranges: vscode.Range[] = [];
|
||||
decorationType = addedLineDecorationType;
|
||||
|
||||
applyToNewEditor(newEditor: vscode.TextEditor) {
|
||||
this.editor = newEditor;
|
||||
|
|
@ -78,24 +91,10 @@ export class DecorationTypeRangeManager {
|
|||
this.editor.setDecorations(this.decorationType, this.ranges);
|
||||
}
|
||||
|
||||
getRanges() {
|
||||
return this.ranges;
|
||||
}
|
||||
|
||||
private translateRange(
|
||||
range: vscode.Range,
|
||||
lineOffset: number,
|
||||
): vscode.Range {
|
||||
return new vscode.Range(
|
||||
range.start.translate(lineOffset),
|
||||
range.end.translate(lineOffset),
|
||||
);
|
||||
}
|
||||
|
||||
shiftDownAfterLine(afterLine: number, offset: number) {
|
||||
for (let i = 0; i < this.ranges.length; i++) {
|
||||
if (this.ranges[i].start.line >= afterLine) {
|
||||
this.ranges[i] = this.translateRange(this.ranges[i], offset);
|
||||
this.ranges[i] = translateRange(this.ranges[i], offset);
|
||||
}
|
||||
}
|
||||
this.editor.setDecorations(this.decorationType, this.ranges);
|
||||
|
|
@ -107,5 +106,86 @@ export class DecorationTypeRangeManager {
|
|||
return this.ranges.splice(i, 1)[0];
|
||||
}
|
||||
}
|
||||
this.editor.setDecorations(this.decorationType, this.ranges);
|
||||
}
|
||||
}
|
||||
|
||||
// Class for managing ghost-text decorations for removed lines (e.g. RED)
|
||||
// Behavior is slightly different all around
|
||||
// because each line will have a unique decoration type
|
||||
export class RemovedLineDecorationManager {
|
||||
constructor(private editor: vscode.TextEditor) {}
|
||||
|
||||
ranges: {
|
||||
line: string;
|
||||
range: vscode.Range;
|
||||
decoration: vscode.TextEditorDecorationType;
|
||||
}[] = [];
|
||||
|
||||
applyToNewEditor(newEditor: vscode.TextEditor) {
|
||||
this.editor = newEditor;
|
||||
this.applyDecorations();
|
||||
}
|
||||
|
||||
addLines(startIndex: number, lines: string[]) {
|
||||
let i = 0;
|
||||
for (const line of lines) {
|
||||
this.ranges.push({
|
||||
line,
|
||||
range: new vscode.Range(
|
||||
startIndex + i,
|
||||
0,
|
||||
startIndex + i,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
),
|
||||
decoration: removedLineDecorationType(line),
|
||||
});
|
||||
i++;
|
||||
}
|
||||
this.applyDecorations();
|
||||
}
|
||||
|
||||
addLine(index: number, line: string) {
|
||||
this.addLines(index, [line]);
|
||||
}
|
||||
|
||||
applyDecorations() {
|
||||
this.ranges.forEach((r) => {
|
||||
this.editor.setDecorations(r.decoration, [r.range]);
|
||||
});
|
||||
}
|
||||
|
||||
// Removed decorations are always unique, so we'll always dispose
|
||||
clear() {
|
||||
this.ranges.forEach((r) => {
|
||||
r.decoration.dispose();
|
||||
});
|
||||
this.ranges = [];
|
||||
}
|
||||
|
||||
shiftDownAfterLine(afterLine: number, offset: number) {
|
||||
for (let i = 0; i < this.ranges.length; i++) {
|
||||
if (this.ranges[i].range.start.line >= afterLine) {
|
||||
this.ranges[i].range = translateRange(this.ranges[i].range, offset);
|
||||
}
|
||||
}
|
||||
this.applyDecorations();
|
||||
}
|
||||
|
||||
// Red ranges are always single-line, so to delete group, delete sequential ranges
|
||||
deleteRangesStartingAt(line: number) {
|
||||
for (let i = 0; i < this.ranges.length; i++) {
|
||||
if (this.ranges[i].range.start.line === line) {
|
||||
let sequential = 0;
|
||||
while (
|
||||
i + sequential < this.ranges.length &&
|
||||
this.ranges[i + sequential].range.start.line === line + sequential
|
||||
) {
|
||||
this.ranges[i + sequential].decoration.dispose();
|
||||
sequential++;
|
||||
}
|
||||
return this.ranges.splice(i, sequential);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,10 @@ import * as URI from "uri-js";
|
|||
import * as vscode from "vscode";
|
||||
|
||||
import {
|
||||
DecorationTypeRangeManager,
|
||||
AddedLineDecorationManager,
|
||||
RemovedLineDecorationManager,
|
||||
belowIndexDecorationType,
|
||||
greenDecorationType,
|
||||
indexDecorationType,
|
||||
redDecorationType,
|
||||
} from "./decorations";
|
||||
|
||||
import type { ApplyState, DiffLine } from "core";
|
||||
|
|
@ -28,7 +27,9 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
private cancelled = false;
|
||||
private newLinesAdded = 0;
|
||||
private deletionBuffer: string[] = [];
|
||||
private redDecorationManager: DecorationTypeRangeManager;
|
||||
private removedLineDecorations: RemovedLineDecorationManager;
|
||||
private addedLineDecorations: AddedLineDecorationManager;
|
||||
|
||||
private get fileUri() {
|
||||
return this.editor.document.uri.toString();
|
||||
}
|
||||
|
|
@ -56,15 +57,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
) {
|
||||
this.currentLineIndex = startLine;
|
||||
|
||||
this.redDecorationManager = new DecorationTypeRangeManager(
|
||||
redDecorationType,
|
||||
this.editor,
|
||||
);
|
||||
|
||||
this.greenDecorationManager = new DecorationTypeRangeManager(
|
||||
greenDecorationType,
|
||||
this.editor,
|
||||
);
|
||||
this.removedLineDecorations = new RemovedLineDecorationManager(this.editor);
|
||||
this.addedLineDecorations = new AddedLineDecorationManager(this.editor);
|
||||
|
||||
const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
|
||||
if (!editor) {
|
||||
|
|
@ -73,8 +67,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
// When we switch away and back to this editor, need to re-draw decorations
|
||||
if (URI.equal(editor.document.uri.toString(), this.fileUri)) {
|
||||
this.editor = editor;
|
||||
this.redDecorationManager.applyToNewEditor(editor);
|
||||
this.greenDecorationManager.applyToNewEditor(editor);
|
||||
this.removedLineDecorations.applyToNewEditor(editor);
|
||||
this.addedLineDecorations.applyToNewEditor(editor);
|
||||
this.updateIndexLineDecorations();
|
||||
this.refreshCodeLens();
|
||||
|
||||
|
|
@ -86,8 +80,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
}
|
||||
|
||||
private async insertDeletionBuffer() {
|
||||
const totalDeletedContent = this.deletionBuffer.join("\n");
|
||||
|
||||
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
|
||||
|
||||
|
|
@ -105,19 +97,19 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
return;
|
||||
}
|
||||
|
||||
// Insert the block of deleted lines
|
||||
// Insert the block of deleted lines as empty new lines
|
||||
await this.insertTextAboveLine(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
totalDeletedContent,
|
||||
"\n".repeat(this.deletionBuffer.length - 1),
|
||||
);
|
||||
|
||||
this.redDecorationManager.addLines(
|
||||
this.removedLineDecorations.addLines(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
this.deletionBuffer.length,
|
||||
this.deletionBuffer,
|
||||
);
|
||||
|
||||
// Shift green decorations downward
|
||||
this.greenDecorationManager.shiftDownAfterLine(
|
||||
this.addedLineDecorations.shiftDownAfterLine(
|
||||
this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
this.deletionBuffer.length,
|
||||
);
|
||||
|
|
@ -137,8 +129,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this.updateIndexLineDecorations();
|
||||
}
|
||||
|
||||
private greenDecorationManager: DecorationTypeRangeManager;
|
||||
|
||||
private async insertTextAboveLine(index: number, text: string) {
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
|
|
@ -165,7 +155,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
|
||||
private async insertLineAboveIndex(index: number, line: string) {
|
||||
await this.insertTextAboveLine(index, line);
|
||||
this.greenDecorationManager.addLine(index);
|
||||
this.addedLineDecorations.addLine(index);
|
||||
this.newLinesAdded++;
|
||||
}
|
||||
|
||||
|
|
@ -184,6 +174,25 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
);
|
||||
}
|
||||
|
||||
private async deleteRangeLines(ranges: vscode.Range[]) {
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
for (const range of ranges) {
|
||||
editBuilder.delete(
|
||||
new vscode.Range(
|
||||
range.start,
|
||||
new vscode.Position(range.end.line + 1, 0),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private updateIndexLineDecorations() {
|
||||
if (this.options.instant) {
|
||||
// We don't show progress on instant apply
|
||||
|
|
@ -215,51 +224,28 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
this.editor.setDecorations(indexDecorationType, []);
|
||||
}
|
||||
|
||||
public getLineDeltaBeforeLine(line: number) {
|
||||
// Returns the number of lines removed from a file when the diff currently active is closed
|
||||
let totalLineDelta = 0;
|
||||
for (const range of this.greenDecorationManager
|
||||
.getRanges()
|
||||
.sort((a, b) => a.start.line - b.start.line)) {
|
||||
if (range.start.line > line) {
|
||||
break;
|
||||
}
|
||||
|
||||
totalLineDelta -= range.end.line - range.start.line + 1;
|
||||
}
|
||||
|
||||
return totalLineDelta;
|
||||
}
|
||||
|
||||
async clear(accept: boolean) {
|
||||
vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"continue.streamingDiff",
|
||||
false,
|
||||
);
|
||||
const rangesToDelete = accept
|
||||
? this.redDecorationManager.getRanges()
|
||||
: this.greenDecorationManager.getRanges();
|
||||
|
||||
const removedRanges = this.removedLineDecorations.ranges;
|
||||
if (accept) {
|
||||
// Accept all: delete all the red ranges and clear green decorations
|
||||
await this.deleteRangeLines(removedRanges.map((r) => r.range));
|
||||
} else {
|
||||
// Reject all: Re-insert red lines, delete green ones
|
||||
for (const r of removedRanges) {
|
||||
await this.deleteRangeLines([r.range]);
|
||||
await this.insertTextAboveLine(r.range.start.line, r.line);
|
||||
}
|
||||
await this.deleteRangeLines(this.addedLineDecorations.ranges);
|
||||
}
|
||||
|
||||
this.clearDecorations();
|
||||
|
||||
await this.editor.edit(
|
||||
(editBuilder) => {
|
||||
for (const range of rangesToDelete) {
|
||||
editBuilder.delete(
|
||||
new vscode.Range(
|
||||
range.start,
|
||||
new vscode.Position(range.end.line + 1, 0),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
},
|
||||
);
|
||||
|
||||
this.options.onStatusUpdate(
|
||||
"closed",
|
||||
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
|
||||
|
|
@ -381,7 +367,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
) {
|
||||
if (numGreen > 0) {
|
||||
// Delete the editor decoration
|
||||
this.greenDecorationManager.deleteRangeStartingAt(startLine + numRed);
|
||||
this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed);
|
||||
if (!accept) {
|
||||
// Delete the actual lines
|
||||
await this.deleteLinesAt(startLine + numRed, numGreen);
|
||||
|
|
@ -389,20 +375,23 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
}
|
||||
|
||||
if (numRed > 0) {
|
||||
const rangeToDelete =
|
||||
this.redDecorationManager.deleteRangeStartingAt(startLine);
|
||||
const deleted =
|
||||
this.removedLineDecorations.deleteRangesStartingAt(startLine);
|
||||
|
||||
if (accept) {
|
||||
// Delete the actual lines
|
||||
await this.deleteLinesAt(startLine, numRed);
|
||||
await this.deleteLinesAt(startLine, numRed);
|
||||
if (deleted && !accept) {
|
||||
await this.insertTextAboveLine(
|
||||
startLine,
|
||||
deleted.map((r) => r.line).join("\n"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Shift everything below upward
|
||||
const offset = -(accept ? numRed : numGreen);
|
||||
|
||||
this.redDecorationManager.shiftDownAfterLine(startLine, offset);
|
||||
this.greenDecorationManager.shiftDownAfterLine(startLine, offset);
|
||||
this.removedLineDecorations.shiftDownAfterLine(startLine, offset);
|
||||
this.addedLineDecorations.shiftDownAfterLine(startLine, offset);
|
||||
|
||||
// Shift the codelens objects
|
||||
this.shiftCodeLensObjects(startLine, offset);
|
||||
|
|
@ -449,11 +438,11 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
return;
|
||||
}
|
||||
|
||||
//update decorations
|
||||
this.redDecorationManager.shiftDownAfterLine(startLine, lineDelta);
|
||||
this.greenDecorationManager.shiftDownAfterLine(startLine, lineDelta);
|
||||
// Update decorations
|
||||
this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
|
||||
this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
|
||||
|
||||
//update code lens
|
||||
// Update code lens
|
||||
this.shiftCodeLensObjects(startLine, lineDelta);
|
||||
}
|
||||
|
||||
|
|
@ -463,8 +452,8 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
}
|
||||
|
||||
clearDecorations() {
|
||||
this.redDecorationManager.clear();
|
||||
this.greenDecorationManager.clear();
|
||||
this.removedLineDecorations.clear();
|
||||
this.addedLineDecorations.clear();
|
||||
this.clearIndexLineDecorations();
|
||||
this.editorToVerticalDiffCodeLens.delete(this.fileUri);
|
||||
this.refreshCodeLens();
|
||||
|
|
@ -499,24 +488,27 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
// newline separated, because myersDiff() would consider
|
||||
// ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
|
||||
// "A\n" and "A\n\n" are unambiguous.
|
||||
//
|
||||
const oldFileContent = diffLines
|
||||
.filter((line) => line.type === "same" || line.type === "old")
|
||||
.map((line) => line.line)
|
||||
.join("\n") + "\n";
|
||||
const oldFileContent =
|
||||
diffLines
|
||||
.filter((line) => line.type === "same" || line.type === "old")
|
||||
.map((line) => line.line)
|
||||
.join("\n") + "\n";
|
||||
|
||||
const newFileContent = diffLines
|
||||
.filter((line) => line.type === "same" || line.type === "new")
|
||||
.map((line) => line.line)
|
||||
.join("\n") + "\n";
|
||||
const newFileContent =
|
||||
diffLines
|
||||
.filter((line) => line.type === "same" || line.type === "new")
|
||||
.map((line) => line.line)
|
||||
.join("\n") + "\n";
|
||||
|
||||
const diffs = myersDiff(oldFileContent, newFileContent);
|
||||
const myersDiffs = myersDiff(oldFileContent, newFileContent);
|
||||
|
||||
const myersDiffLines = diffs.map((diff) => diff.line).join("\n");
|
||||
const replaceContent = myersDiffs
|
||||
.map((diff) => (diff.type === "old" ? "" : diff.line))
|
||||
.join("\n");
|
||||
|
||||
// Then, we insert our diff lines
|
||||
await this.editor.edit((editBuilder) => {
|
||||
editBuilder.replace(this.range, myersDiffLines),
|
||||
editBuilder.replace(this.range, replaceContent),
|
||||
{
|
||||
undoStopAfter: false,
|
||||
undoStopBefore: false,
|
||||
|
|
@ -529,12 +521,12 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
|
||||
const codeLensBlocks: VerticalDiffCodeLens[] = [];
|
||||
|
||||
diffs.forEach((diff, index) => {
|
||||
myersDiffs.forEach((diff, index) => {
|
||||
if (diff.type === "old") {
|
||||
this.redDecorationManager.addLine(this.startLine + index);
|
||||
this.removedLineDecorations.addLine(this.startLine + index, diff.line);
|
||||
numRed++;
|
||||
} else if (diff.type === "new") {
|
||||
this.greenDecorationManager.addLine(this.startLine + index);
|
||||
this.addedLineDecorations.addLine(this.startLine + index);
|
||||
numGreen++;
|
||||
} else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
|
||||
codeLensBlocks.push({
|
||||
|
|
@ -551,7 +543,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
codeLensBlocks.push({
|
||||
numGreen,
|
||||
numRed,
|
||||
start: this.startLine + diffs.length - numRed - numGreen,
|
||||
start: this.startLine + myersDiffs.length - numRed - numGreen,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -259,8 +259,13 @@ export class VerticalDiffManager {
|
|||
this.enableDocumentChangeListener();
|
||||
} catch (e) {
|
||||
this.disableDocumentChangeListener();
|
||||
if (!handleLLMError(e)) {
|
||||
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
|
||||
const handled = await handleLLMError(e);
|
||||
if (!handled) {
|
||||
let message = "Error streaming diffs";
|
||||
if (e instanceof Error) {
|
||||
message += `: ${e.message}`;
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
} finally {
|
||||
vscode.commands.executeCommand(
|
||||
|
|
@ -280,7 +285,7 @@ export class VerticalDiffManager {
|
|||
range,
|
||||
newCode,
|
||||
toolCallId,
|
||||
rules,
|
||||
rulesToInclude,
|
||||
}: {
|
||||
input: string;
|
||||
llm: ILLM;
|
||||
|
|
@ -290,7 +295,7 @@ export class VerticalDiffManager {
|
|||
range?: vscode.Range;
|
||||
newCode?: string;
|
||||
toolCallId?: string;
|
||||
rules: RuleWithSource[];
|
||||
rulesToInclude: undefined | RuleWithSource[];
|
||||
}): Promise<string | undefined> {
|
||||
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
|
||||
|
||||
|
|
@ -344,11 +349,11 @@ export class VerticalDiffManager {
|
|||
// startLine += effectiveLineDelta;
|
||||
// endLine += effectiveLineDelta;
|
||||
|
||||
existingHandler.clear(false);
|
||||
await existingHandler.clear(false);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 200);
|
||||
setTimeout(resolve, 150);
|
||||
});
|
||||
|
||||
// Create new handler with determined start/end
|
||||
|
|
@ -443,7 +448,7 @@ export class VerticalDiffManager {
|
|||
prefix,
|
||||
suffix,
|
||||
llm,
|
||||
rules,
|
||||
rulesToInclude,
|
||||
input,
|
||||
language: getMarkdownLanguageTagForFile(fileUri),
|
||||
onlyOneInsertion: !!onlyOneInsertion,
|
||||
|
|
@ -466,10 +471,14 @@ export class VerticalDiffManager {
|
|||
return `${prefix}${streamedLines.join("\n")}${suffix}`;
|
||||
} catch (e) {
|
||||
this.disableDocumentChangeListener();
|
||||
if (!handleLLMError(e)) {
|
||||
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
|
||||
const handled = await handleLLMError(e);
|
||||
if (!handled) {
|
||||
let message = "Error streaming edit diffs";
|
||||
if (e instanceof Error) {
|
||||
message += `: ${e.message}`;
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
return undefined;
|
||||
} finally {
|
||||
vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
rulesToInclude: config.rules,
|
||||
});
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -413,7 +413,7 @@ export class VsCodeMessenger {
|
|||
});
|
||||
|
||||
this.onWebviewOrCore("reportError", async (msg) => {
|
||||
handleLLMError(msg.data);
|
||||
await handleLLMError(msg.data);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
70
extensions/vscode/src/quickEdit/AddCurrentSelection.ts
Normal file
70
extensions/vscode/src/quickEdit/AddCurrentSelection.ts
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -331,7 +331,7 @@ export class QuickEdit {
|
|||
llm: model,
|
||||
quickEdit: this.previousInput,
|
||||
range: this.range,
|
||||
rules,
|
||||
rulesToInclude: rules,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
164
extensions/vscode/src/util/addCode.ts
Normal file
164
extensions/vscode/src/util/addCode.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
import * as os from "node:os";
|
||||
|
||||
import { RangeInFileWithContents } from "core";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { VsCodeIdeUtils } from "./ideUtils";
|
||||
|
||||
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,
|
||||
ideUtils: VsCodeIdeUtils
|
||||
) {
|
||||
// If a directory, add all files in the directory
|
||||
const stat = await ideUtils.stat(uri);
|
||||
if (stat?.type === vscode.FileType.Directory) {
|
||||
const files = (await ideUtils.readDirectory(uri))!;//files can't be null if we reached this point
|
||||
for (const [filename, type] of files) {
|
||||
if (type === vscode.FileType.File) {
|
||||
addEntireFileToContext(
|
||||
vscode.Uri.joinPath(uri, filename),
|
||||
webviewProtocol,
|
||||
ideUtils
|
||||
);
|
||||
}
|
||||
}
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
|
@ -2,17 +2,15 @@ import { ILLM } from "core";
|
|||
import { isModelInstaller } from "core/llm";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
function supportSpecialHandling(error: any): boolean {
|
||||
let message: string | undefined = error.message;
|
||||
return message !== undefined && message.toLowerCase().includes("ollama");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param error Handles common LLM errors. Currently only handles Ollama-related errors.
|
||||
* @returns true if error is handled, false otherwise
|
||||
*/
|
||||
export async function handleLLMError(error: any): Promise<boolean> {
|
||||
if (!supportSpecialHandling(error)) {
|
||||
export async function handleLLMError(error: unknown): Promise<boolean> {
|
||||
if (!error || !(error instanceof Error) || !error.message) {
|
||||
return false;
|
||||
}
|
||||
if (!error.message.toLowerCase().includes("ollama")) {
|
||||
return false;
|
||||
}
|
||||
let message: string = error.message;
|
||||
|
|
@ -22,11 +20,11 @@ export async function handleLLMError(error: any): Promise<boolean> {
|
|||
options = ["Download Ollama"];
|
||||
} else if (message.includes("Ollama may not be running")) {
|
||||
options = ["Start Ollama"]; // We want "Start" to be the only choice
|
||||
} else if (message.includes("ollama run") && error.llm) {
|
||||
} else if (message.includes("ollama run") && "llm" in error) {
|
||||
//extract model name from error message matching the pattern "ollama run <model-name>"
|
||||
modelName = message.match(/`ollama run (.*)`/)?.[1];
|
||||
const llm = error.llm as ILLM;
|
||||
if (isModelInstaller(llm) && await llm.isInstallingModel(modelName!)){
|
||||
if (isModelInstaller(llm) && (await llm.isInstallingModel(modelName!))) {
|
||||
console.log(`${llm.providerName} already installing ${modelName}`);
|
||||
return false;
|
||||
}
|
||||
|
|
@ -43,7 +41,7 @@ export async function handleLLMError(error: any): Promise<boolean> {
|
|||
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
|
||||
} else if (val === "Start Ollama") {
|
||||
vscode.commands.executeCommand("continue.startLocalOllama");
|
||||
} else if (val === "Install Model" && error.llm) {
|
||||
} else if (val === "Install Model" && "llm" in error) {
|
||||
//Eventually, we might be able to support installing models for other LLM providers than Ollama
|
||||
vscode.commands.executeCommand(
|
||||
"continue.installModel",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
import { findUriInDirs } from "core/util/uri";
|
||||
import _ from "lodash";
|
||||
import * as vscode from "vscode";
|
||||
import * as URI from "uri-js";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { threadStopped } from "../debug/debug";
|
||||
import { VsCodeExtension } from "../extension/VsCodeExtension";
|
||||
import { GitExtension, Repository } from "../otherExtensions/git";
|
||||
|
|
@ -14,12 +16,14 @@ import {
|
|||
|
||||
import { getUniqueId, openEditorAndRevealRange } from "./vscode";
|
||||
|
||||
import type { Range, RangeInFile, Thread } from "core";
|
||||
import { findUriInDirs } from "core/util/uri";
|
||||
import type { Range, Thread } from "core";
|
||||
|
||||
const util = require("node:util");
|
||||
const asyncExec = util.promisify(require("node:child_process").exec);
|
||||
|
||||
const NO_FS_PROVIDER_ERROR = "ENOPRO";
|
||||
const UNSUPPORTED_SCHEMES: Set<string> = new Set();
|
||||
|
||||
export class VsCodeIdeUtils {
|
||||
visibleMessages: Set<string> = new Set();
|
||||
|
||||
|
|
@ -99,13 +103,114 @@ export class VsCodeIdeUtils {
|
|||
|
||||
async fileExists(uri: vscode.Uri): Promise<boolean> {
|
||||
try {
|
||||
await vscode.workspace.fs.stat(uri);
|
||||
return true;
|
||||
return (await this.stat(uri)) !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the entire contents of a file from the given URI.
|
||||
*
|
||||
* @param uri - The URI of the file to read.
|
||||
* @param ignoreMissingProviders - Optional flag to ignore missing file system providers for unsupported schemes.
|
||||
* Defaults to `true`.
|
||||
* @returns A promise that resolves to the file content as a `Uint8Array`, or `null` if the scheme is unsupported
|
||||
* or the provider is missing and `ignoreMissingProviders` is `true`.
|
||||
* If `ignoreMissingProviders` is `false`, it will throw an error for unsupported schemes or missing providers.
|
||||
* @throws Will rethrow any error that is not related to missing providers or unsupported schemes.
|
||||
*/
|
||||
async readFile(
|
||||
uri: vscode.Uri,
|
||||
ignoreMissingProviders: boolean = true,
|
||||
): Promise<Uint8Array | null> {
|
||||
return await this.fsOperation(
|
||||
uri,
|
||||
async (u) => {
|
||||
return await vscode.workspace.fs.readFile(u);
|
||||
},
|
||||
ignoreMissingProviders,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve metadata about a file from the given URI.
|
||||
*
|
||||
* @param uri - The URI of the file or directory to retrieve metadata about.
|
||||
* @param ignoreMissingProviders - Optional. If `true`, missing file system providers will be ignored. Defaults to `true`.
|
||||
* @returns A promise that resolves to a `vscode.FileStat` object containing the file metadata,
|
||||
* or `null` if the scheme is unsupported or the provider is missing and `ignoreMissingProviders` is `true`.
|
||||
*/
|
||||
async stat(
|
||||
uri: vscode.Uri,
|
||||
ignoreMissingProviders: boolean = true,
|
||||
): Promise<vscode.FileStat | null> {
|
||||
return await this.fsOperation(
|
||||
uri,
|
||||
async (u) => {
|
||||
return await vscode.workspace.fs.stat(uri);
|
||||
},
|
||||
ignoreMissingProviders,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all entries of a directory from the given URI.
|
||||
*
|
||||
* @param uri - The URI of the directory to read.
|
||||
* @param ignoreMissingProviders - Optional. If `true`, missing file system providers will be ignored. Defaults to `true`.
|
||||
* @returns A promise that resolves to an array of tuples, where each tuple contains the name of a directory entry
|
||||
* and its type (`vscode.FileType`), or `null` if the scheme is unsupported or the provider is missing and `ignoreMissingProviders` is `true`.
|
||||
*/
|
||||
async readDirectory(
|
||||
uri: vscode.Uri,
|
||||
ignoreMissingProviders: boolean = true,
|
||||
): Promise<[string, vscode.FileType][] | null> {
|
||||
return await this.fsOperation(
|
||||
uri,
|
||||
async (u) => {
|
||||
return await vscode.workspace.fs.readDirectory(uri);
|
||||
},
|
||||
ignoreMissingProviders,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a file system operation on the given URI using the provided delegate function.
|
||||
*
|
||||
* @template T The type of the result returned by the delegate function.
|
||||
* @param uri The URI on which the file system operation is to be performed.
|
||||
* @param delegate A function that performs the desired operation on the given URI.
|
||||
* @param ignoreMissingProviders Whether to ignore errors caused by missing file system providers. Defaults to `true`.
|
||||
* @returns A promise that resolves to the result of the delegate function, or `null` if the operation is skipped due to unsupported schemes or missing providers.
|
||||
* @throws Re-throws any error encountered during the operation, except for missing provider errors when `ignoreMissingProviders` is `true`.
|
||||
*/
|
||||
private async fsOperation<T>(
|
||||
uri: vscode.Uri,
|
||||
delegate: (uri: vscode.Uri) => T,
|
||||
ignoreMissingProviders: boolean = true,
|
||||
): Promise<T | null> {
|
||||
const scheme = uri.scheme;
|
||||
if (ignoreMissingProviders && UNSUPPORTED_SCHEMES.has(scheme)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await delegate(uri);
|
||||
} catch (err: any) {
|
||||
if (
|
||||
ignoreMissingProviders &&
|
||||
//see https://github.com/microsoft/vscode/blob/c9c54f9e775e5f57d97bef796797b5bc670c8150/src/vs/workbench/api/common/extHostFileSystemConsumer.ts#L230
|
||||
(err.name === NO_FS_PROVIDER_ERROR ||
|
||||
err.message?.includes(NO_FS_PROVIDER_ERROR))
|
||||
) {
|
||||
UNSUPPORTED_SCHEMES.add(scheme);
|
||||
console.log(`Ignoring missing provider error:`, err.message);
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
showVirtualFile(name: string, contents: string) {
|
||||
vscode.workspace
|
||||
.openTextDocument(
|
||||
|
|
@ -185,9 +290,11 @@ export class VsCodeIdeUtils {
|
|||
}
|
||||
|
||||
async readRangeInFile(uri: vscode.Uri, range: vscode.Range): Promise<string> {
|
||||
const contents = new TextDecoder().decode(
|
||||
await vscode.workspace.fs.readFile(uri),
|
||||
);
|
||||
const buffer = await this.readFile(uri);
|
||||
if (buffer === null) {
|
||||
return '';
|
||||
}
|
||||
const contents = new TextDecoder().decode(buffer);
|
||||
const lines = contents.split("\n");
|
||||
return `${lines
|
||||
.slice(range.start.line, range.end.line)
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -1 +0,0 @@
|
|||
export { default } from "./CodeToEditCard";
|
||||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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(() => {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 && (
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
@ -3,6 +3,8 @@ import { ApplyState } from "core";
|
|||
import { useEffect, useState } from "react";
|
||||
import { getMetaKeyLabel } from "../../../util";
|
||||
import Spinner from "../../gui/Spinner";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
import HoverItem from "../../mainInput/InputToolbar/HoverItem";
|
||||
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
|
||||
|
||||
interface ApplyActionsProps {
|
||||
|
|
@ -35,16 +37,24 @@ export function ApplyActions(props: ApplyActionsProps) {
|
|||
}
|
||||
|
||||
const applyButton = (text: string) => (
|
||||
<button
|
||||
data-testid="codeblock-toolbar-apply"
|
||||
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
|
||||
onClick={props.onClickApply}
|
||||
<HoverItem
|
||||
data-tooltip-id="codeblock-apply-code-button-tooltip"
|
||||
className="!p-0"
|
||||
>
|
||||
<div className="text-lightgray flex items-center gap-1">
|
||||
<PlayIcon className="h-3.5 w-3.5" />
|
||||
<span className="xs:inline hidden">{text}</span>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
data-testid="codeblock-toolbar-apply"
|
||||
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
|
||||
onClick={props.onClickApply}
|
||||
>
|
||||
<div className="text-lightgray flex items-center gap-1">
|
||||
<PlayIcon className="h-3.5 w-3.5" />
|
||||
<span className="xs:inline hidden">{text}</span>
|
||||
</div>
|
||||
</button>
|
||||
<ToolTip id="codeblock-apply-code-button-tooltip" place="top">
|
||||
{text} Code
|
||||
</ToolTip>
|
||||
</HoverItem>
|
||||
);
|
||||
|
||||
switch (props.applyState ? props.applyState.status : null) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline";
|
||||
import useCopy from "../../../hooks/useCopy";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
import HoverItem from "../../mainInput/InputToolbar/HoverItem";
|
||||
|
||||
interface CopyButtonProps {
|
||||
text: string;
|
||||
|
|
@ -9,17 +11,22 @@ export function CopyButton({ text }: CopyButtonProps) {
|
|||
const { copyText, copied } = useCopy(text);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125"
|
||||
onClick={copyText}
|
||||
>
|
||||
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
|
||||
{copied ? (
|
||||
<CheckIcon className="h-3.5 w-3.5 text-green-500 hover:brightness-125" />
|
||||
) : (
|
||||
<ClipboardIcon className="h-3.5 w-3.5 hover:brightness-125" />
|
||||
)}
|
||||
<HoverItem data-tooltip-id="codeblock-copy-button-tooltip" className="!p-0">
|
||||
<div
|
||||
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125"
|
||||
onClick={copyText}
|
||||
>
|
||||
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
|
||||
{copied ? (
|
||||
<CheckIcon className="h-3.5 w-3.5 text-green-500 hover:brightness-125" />
|
||||
) : (
|
||||
<ClipboardIcon className="h-3.5 w-3.5 hover:brightness-125" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ToolTip id="codeblock-copy-button-tooltip" place="top">
|
||||
Copy Code
|
||||
</ToolTip>
|
||||
</HoverItem>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { DocumentPlusIcon } from "@heroicons/react/24/outline";
|
||||
import { vscForeground } from "../..";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
import HoverItem from "../../mainInput/InputToolbar/HoverItem";
|
||||
|
||||
interface CreateFileButtonProps {
|
||||
onClick: () => void;
|
||||
|
|
@ -7,7 +9,10 @@ interface CreateFileButtonProps {
|
|||
|
||||
export function CreateFileButton({ onClick }: CreateFileButtonProps) {
|
||||
return (
|
||||
<>
|
||||
<HoverItem
|
||||
data-tooltip-id="codeblock-create-file-button-tooltip"
|
||||
className="!p-0"
|
||||
>
|
||||
<button
|
||||
data-testid="codeblock-toolbar-create"
|
||||
className={`text-lightgray flex items-center border-none bg-transparent pl-0 text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
|
||||
|
|
@ -20,6 +25,9 @@ export function CreateFileButton({ onClick }: CreateFileButtonProps) {
|
|||
</span>
|
||||
</div>
|
||||
</button>
|
||||
</>
|
||||
<ToolTip id="codeblock-create-file-button-tooltip" place="top">
|
||||
Create File with Code
|
||||
</ToolTip>
|
||||
</HoverItem>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline";
|
||||
import { ToolTip } from "../../gui/Tooltip";
|
||||
import HoverItem from "../../mainInput/InputToolbar/HoverItem";
|
||||
|
||||
/**
|
||||
* Button that inserts code at the current cursor position
|
||||
|
|
@ -9,13 +11,21 @@ interface InsertButtonProps {
|
|||
|
||||
export function InsertButton({ onInsert }: InsertButtonProps) {
|
||||
return (
|
||||
<div
|
||||
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125"
|
||||
onClick={onInsert}
|
||||
<HoverItem
|
||||
data-tooltip-id="codeblock-insert-button-tooltip"
|
||||
className="!p-0"
|
||||
>
|
||||
<div className="max-2xs:hidden flex items-center gap-1 transition-colors duration-200">
|
||||
<ArrowLeftEndOnRectangleIcon className="h-3.5 w-3.5" />
|
||||
<div
|
||||
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125"
|
||||
onClick={onInsert}
|
||||
>
|
||||
<div className="max-2xs:hidden flex items-center gap-1 transition-colors duration-200">
|
||||
<ArrowLeftEndOnRectangleIcon className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ToolTip id="codeblock-insert-button-tooltip" place="top">
|
||||
Insert Code
|
||||
</ToolTip>
|
||||
</HoverItem>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import {
|
|||
ChatBubbleLeftIcon,
|
||||
PlusIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { Editor } from "@tiptap/react";
|
||||
import { RangeInFile } from "core";
|
||||
import type { Editor } from "@tiptap/react";
|
||||
import type { RangeInFile } from "core";
|
||||
import {
|
||||
forwardRef,
|
||||
useContext,
|
||||
|
|
@ -32,7 +32,7 @@ import SafeImg from "../../SafeImg";
|
|||
import AddDocsDialog from "../../dialogs/AddDocsDialog";
|
||||
import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip";
|
||||
import { NAMED_ICONS } from "../icons";
|
||||
import { ComboBoxItem, ComboBoxItemType } from "../types";
|
||||
import type { ComboBoxItem, ComboBoxItemType } from "../types";
|
||||
|
||||
export function getIconFromDropdownItem(
|
||||
id: string | undefined,
|
||||
|
|
@ -509,7 +509,9 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
|
|||
) : (
|
||||
<DropdownIcon item={item} className="mr-2" />
|
||||
)}
|
||||
<span title={item.id} className="whitespace-nowrap">{item.title}</span>
|
||||
<span title={item.id} className="whitespace-nowrap">
|
||||
{item.title}
|
||||
</span>
|
||||
{" "}
|
||||
</div>
|
||||
<span
|
||||
|
|
@ -517,7 +519,12 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
|
|||
color: lightGray,
|
||||
float: "right",
|
||||
textAlign: "right",
|
||||
opacity: isSelected ? 1 : 0,
|
||||
opacity:
|
||||
subMenuTitle || item.type !== "contextProvider"
|
||||
? 1
|
||||
: isSelected
|
||||
? 1
|
||||
: 0,
|
||||
minWidth: "30px",
|
||||
}}
|
||||
className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap"
|
||||
|
|
|
|||
180
gui/src/components/mainInput/CodeToEditCard.tsx
Normal file
180
gui/src/components/mainInput/CodeToEditCard.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
59
gui/src/components/mainInput/EditModeDetails.tsx
Normal file
59
gui/src/components/mainInput/EditModeDetails.tsx
Normal 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;
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue