Merge branch 'dallin/search-replace-error-codes-con-3928' of https://github.com/continuedev/continue into dallin/search-replace-fallbacks-v2

This commit is contained in:
Dallin Romney 2025-09-19 17:42:12 -07:00
commit ffd3842097
88 changed files with 59852 additions and 5755 deletions

View file

@ -107,7 +107,7 @@ runs:
cd binary
npm run build
- name: Start test IDE
- name: Run tests
shell: bash
run: |
cd extensions/intellij
@ -115,21 +115,7 @@ runs:
Xvfb -ac :99 -screen 0 1920x1080x24 &
sleep 10
mkdir -p build/reports
./gradlew runIdeForUiTests &
- name: Wait for JB connection
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 30s
- name: Run tests
shell: bash
run: |
cd extensions/intellij
export DISPLAY=:99.0
./gradlew test
./gradlew test testIntegration
- name: Move video
if: ${{ failure() }}

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@3ebd8232440080aa8891909753f69d75a87b2c86
uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@3ebd8232440080aa8891909753f69d75a87b2c86
uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"

View file

@ -213,15 +213,15 @@ EOF
# Write prompt to temp file for better handling
PROMPT_FILE="/tmp/continue-prompt-$.txt"
cp review_prompt.txt "$PROMPT_FILE"
# Use timeout to prevent hanging (240 seconds = 4 minutes)
if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then
echo "Error: Continue CLI command failed"
echo "CLI error log:"
cat cli_error.log
# Create fallback review
cat > code_review.md << 'EOF'
# Use timeout to prevent hanging (240 seconds = 4 minutes)
if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then
echo "Error: Continue CLI command failed"
echo "CLI error log:"
cat cli_error.log
# Create fallback review
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
@ -231,9 +231,9 @@ EOF
- Check that the organization and config path are valid
- Ensure the Continue service is accessible
EOF
else
echo "Review generated successfully"
fi
else
echo "Review generated successfully"
fi
fi
- name: Upload Review Results

View file

@ -19,7 +19,7 @@ import {
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { DiffChar, DiffLine } from "..";
import { escapeForSVG, kebabOfThemeStr } from "../util/text";
interface CodeRendererOptions {
@ -228,6 +228,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
newDiffChars: DiffChar[],
): Promise<Buffer> {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
@ -236,13 +237,14 @@ export class CodeRenderer {
currLineOffsetFromTop,
newDiffLines,
);
// console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
options,
newDiffChars,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const borderColor = "#6b6b6b";
const lines = code.split("\n");
const actualHeight = lines.length * options.lineHeight;
@ -256,12 +258,11 @@ export class CodeRenderer {
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
<rect x="0" y="0" rx="2" ry="2" width="${options.dimensions.width}" height="${actualHeight}" fill="${backgroundColor}" stroke="${borderColor}" stroke-width="${strokeWidth}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
// console.log(svg);
return Buffer.from(svg, "utf8");
}
@ -269,11 +270,56 @@ export class CodeRenderer {
convertShikiHtmlToSvgGut(
shikiHtml: string,
options: ConversionOptions,
diffChars: DiffChar[],
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const lines = Array.from(document.querySelectorAll(".line"));
const additionSegmentsByLine = new Map<
number,
Array<{ start: number; end: number }>
>();
diffChars.forEach((diff) => {
if (
diff.type !== "new" ||
diff.newLineIndex === undefined ||
diff.newCharIndexInLine === undefined
) {
return;
}
if (diff.char.includes("\n")) {
return;
}
const start = diff.newCharIndexInLine;
const end = start + diff.char.length;
const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? [];
existing.push({ start, end });
additionSegmentsByLine.set(diff.newLineIndex, existing);
});
additionSegmentsByLine.forEach((segments, lineIndex) => {
segments.sort((a, b) => a.start - b.start);
const merged: Array<{ start: number; end: number }> = [];
segments.forEach((segment) => {
if (merged.length === 0) {
merged.push({ ...segment });
return;
}
const last = merged[merged.length - 1];
if (segment.start <= last.end) {
last.end = Math.max(last.end, segment.end);
} else {
merged.push({ ...segment });
}
});
additionSegmentsByLine.set(lineIndex, merged);
});
const svgLines = lines.map((line, index) => {
const spans = Array.from(line.childNodes)
.map((node) => {
@ -309,60 +355,37 @@ export class CodeRenderer {
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
const estimatedCharWidth = options.fontSize * 0.6;
const additionFill = "rgba(40, 167, 69, 0.25)";
const lineBackgrounds = lines
.map((line, index) => {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: classes.includes("diff add")
? "rgba(255, 255, 0, 0.2)"
: this.editorBackground;
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const isSingleLine = isFirst && isLast;
const radius = 10;
const segments = additionSegmentsByLine.get(index) ?? [];
const backgrounds: string[] = [];
// Handle single line case (both first and last)
if (isSingleLine) {
return `<path d="M ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight - radius}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
L ${radius} ${y + options.lineHeight}
Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
Z"
fill="${bgColor}" />`;
if (classes.includes("highlighted")) {
backgrounds.push(
`<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${this.editorLineHighlight}" shape-rendering="crispEdges" />`,
);
}
// SVG notes:
// By default SVGs have anti-aliasing on.
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
return isFirst
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
segments.forEach(({ start, end }) => {
const widthInChars = Math.max(end - start, 0);
if (widthInChars <= 0) {
return;
}
const x = start * estimatedCharWidth;
const segmentWidth = widthInChars * estimatedCharWidth;
backgrounds.push(
`<rect x="${x}" y="${y}" width="${segmentWidth}" height="${options.lineHeight}" fill="${additionFill}" shape-rendering="crispEdges" />`,
);
});
return backgrounds.join("\n");
})
.filter((bg) => bg.length > 0)
.join("\n");
return {
@ -394,6 +417,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
newDiffChars: DiffChar[],
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
@ -413,6 +437,7 @@ export class CodeRenderer {
options,
currLineOffsetFromTop,
newDiffLines,
newDiffChars,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}

View file

@ -52,6 +52,7 @@ class MCPConnection {
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public infos: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
@ -93,6 +94,7 @@ class MCPConnection {
return {
...this.options,
errors: this.errors,
infos: this.infos,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
@ -122,6 +124,7 @@ class MCPConnection {
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
this.infos = [];
this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
@ -280,6 +283,16 @@ class MCPConnection {
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
if (["uv", "uvx"].includes(command)) {
this.infos.push(
'Please install uv by following the installation guide: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a>',
);
}
if (["node", "npx"].includes(command)) {
this.infos.push(
'Please install npx by following the installation guide: <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">https://docs.npmjs.com/downloading-and-installing-node-js-and-npm</a>',
);
}
} else {
errorMessage += "Error: " + error.message;
}

View file

@ -142,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
infos: [],
isProtectedResource: false,
prompts: [],
resources: [],

View file

@ -17,8 +17,8 @@ import { DataLogger } from "./data/log";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
import Lemonade from "./llm/llms/Lemonade";
import Ollama from "./llm/llms/Ollama";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -729,20 +729,13 @@ export class Core {
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
return streamDiffLines(
data,
llm,
// rules included for edit, NOT apply
rulesToInclude: data.includeRulesInSystemMessage
? config.rules
: undefined,
input: data.input,
language: data.language,
overridePrompt: undefined,
abortController,
});
undefined,
data.includeRulesInSystemMessage ? config.rules : undefined,
);
});
on("cancelApply", async (msg) => {

View file

@ -1 +1,3 @@
export const EDIT_MODE_STREAM_ID = "edit-mode";
export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>";

View file

@ -1,7 +1,14 @@
import { ChatMessage, ILLM, Prediction, PromptLog } from "..";
import {
ChatMessage,
ILLM,
Prediction,
PromptLog,
type StreamDiffLinesType,
} from "..";
import { DEFAULT_MAX_TOKENS } from "../llm/constants";
import { countTokens } from "../llm/countTokens";
import { renderChatMessage } from "../util/messageContent";
import { APPLY_UNIQUE_TOKEN } from "./constants.js";
const INFINITE_STREAM_SAFETY = 0.9;
@ -17,6 +24,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
abortController: AbortController,
type: StreamDiffLinesType,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@ -28,8 +36,11 @@ export async function* recursiveStream(
let buffer = currentBuffer;
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm);
if (typeof prompt === "string") {
const generator = llm.streamComplete(prompt, abortController.signal, {
const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt;
const generator = llm.streamComplete(finalPrompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -62,7 +73,11 @@ export async function* recursiveStream(
}
}
} else {
const generator = llm.streamChat(prompt, abortController.signal, {
const promptMessages = injectApplyToken
? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN)
: prompt;
const generator = llm.streamChat(promptMessages, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -104,3 +119,36 @@ export async function* recursiveStream(
}
}
}
function shouldInjectApplyToken(llm: ILLM): boolean {
const model = llm.model?.toLowerCase() ?? "";
return (
llm.underlyingProviderName === "inception" && model.includes("mercury")
);
}
function appendTokenToLastMessage(
messages: ChatMessage[],
token: string,
): ChatMessage[] {
if (messages.length === 0) {
return messages;
}
const lastMessage = messages[messages.length - 1];
if (typeof lastMessage.content !== "string") {
return messages;
}
if (lastMessage.content.endsWith(token)) {
return messages;
}
const updatedMessages = [...messages];
updatedMessages[updatedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content + token,
};
return updatedMessages;
}

View file

@ -4,6 +4,7 @@ import {
ILLM,
Prediction,
RuleWithSource,
StreamDiffLinesPayload,
ToolResultChatMessage,
UserChatMessage,
} from "../";
@ -20,6 +21,7 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { defaultApplyPrompt } from "../llm/templates/edit/gpt";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@ -42,6 +44,20 @@ function constructEditPrompt(
});
}
function constructApplyPrompt(
originalCode: string,
newCode: string,
llm: ILLM,
) {
const template = llm.promptTemplates?.apply ?? defaultApplyPrompt;
const rendered = llm.renderPromptTemplate(template, [], {
original_code: originalCode,
new_code: newCode,
});
return rendered;
}
export async function* addIndentation(
diffLineGenerator: AsyncGenerator<DiffLine>,
indentation: string,
@ -58,27 +74,15 @@ function modelIsInept(model: string): boolean {
return !(model.includes("gpt") || model.includes("claude"));
}
export async function* streamDiffLines({
prefix,
highlighted,
suffix,
llm,
abortController,
input,
language,
overridePrompt,
rulesToInclude,
}: {
prefix: string;
highlighted: string;
suffix: string;
llm: ILLM;
abortController: AbortController;
input: string;
language: string | undefined;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
export async function* streamDiffLines(
options: StreamDiffLinesPayload,
llm: ILLM,
abortController: AbortController,
overridePrompt: ChatMessage[] | undefined,
rulesToInclude: RuleWithSource[] | undefined,
): AsyncGenerator<DiffLine> {
const { type, prefix, highlighted, suffix, input, language } = options;
void Telemetry.capture(
"inlineEdit",
{
@ -104,7 +108,9 @@ export async function* streamDiffLines({
// For apply can be overridden with simply apply prompt
let prompt =
overridePrompt ??
constructEditPrompt(prefix, highlighted, suffix, llm, input, language);
(type === "apply"
? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm)
: constructEditPrompt(prefix, highlighted, suffix, llm, input, language));
// Rules can be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
@ -159,7 +165,13 @@ export async function* streamDiffLines({
content: highlighted,
};
const completion = recursiveStream(llm, abortController, prompt, prediction);
const completion = recursiveStream(
llm,
abortController,
type,
prompt,
prediction,
);
let lines = streamLines(completion);

18
core/index.d.ts vendored
View file

@ -1330,6 +1330,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
infos: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
@ -1387,7 +1388,9 @@ export interface ApplyState {
autoFormattingDiff?: string;
}
export interface StreamDiffLinesPayload {
export type StreamDiffLinesType = "edit" | "apply";
interface StreamDiffLinesOptionsBase {
type: StreamDiffLinesType;
prefix: string;
highlighted: string;
suffix: string;
@ -1398,6 +1401,19 @@ export interface StreamDiffLinesPayload {
fileUri?: string;
}
interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase {
type: "edit";
}
interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase {
type: "apply";
newCode: string;
}
type StreamDiffLinesPayload =
| StreamDiffLinesOptionsApply
| StreamDiffLinesOptionsEdit;
export interface HighlightedCodePayload {
rangeInFileWithContents: RangeInFileWithContents;
prompt?: string;

View file

@ -1056,6 +1056,10 @@ export abstract class BaseLLM implements ILLM {
const msg = fromChatResponse(response);
yield msg;
completion = this._formatChatMessage(msg);
interaction?.logItem({
kind: "message",
message: msg,
});
} else {
// Stream true
const stream = this.openaiAdapter.chatCompletionStream(

View file

@ -2,6 +2,7 @@ import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js";
import { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
import OpenAI from "./OpenAI.js";
@ -96,40 +97,21 @@ class Inception extends OpenAI {
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (this.isNextEdit(messages)) {
messages = this.removeNextEditToken(messages);
// Use edit/completions endpoint.
const endpoint = new URL("edit/completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
messages: messages,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
messages = this.removeToken(messages, UNIQUE_TOKEN);
yield* this.streamSpecialEndpoint(
"edit/completions",
messages,
signal,
});
for await (const chunk of streamSse(resp)) {
if (chunk.choices?.[0]?.delta?.content) {
yield {
role: "assistant",
content: chunk.choices[0].delta.content,
};
}
}
options,
);
} else if (this.isApply(messages)) {
messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN);
yield* this.streamSpecialEndpoint(
"apply/completions",
messages,
signal,
options,
);
} else {
// Use regular chat/completions endpoint - call parent OpenAI implementation.
yield* super._streamChat(messages, signal, options);
@ -145,23 +127,68 @@ class Inception extends OpenAI {
);
}
private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] {
private isApply(messages: ChatMessage[]): boolean {
return messages.some(
(message) =>
typeof message.content === "string" &&
message.content.endsWith(APPLY_UNIQUE_TOKEN),
);
}
private removeToken(messages: ChatMessage[], token: string): ChatMessage[] {
const lastMessage = messages[messages.length - 1];
if (
typeof lastMessage?.content === "string" &&
lastMessage.content.endsWith(UNIQUE_TOKEN)
lastMessage.content.endsWith(token)
) {
const cleanedMessages = [...messages];
cleanedMessages[cleanedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
content: lastMessage.content.slice(0, -token.length),
};
return cleanedMessages;
}
return messages;
}
private async *streamSpecialEndpoint(
path: string,
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const endpoint = new URL(path, this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
messages,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp)) {
const content = chunk.choices?.[0]?.delta?.content;
if (content) {
yield { role: "assistant", content };
}
}
}
}
export default Inception;

View file

@ -71,3 +71,10 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
return paragraphs.join("\n\n");
};
export const defaultApplyPrompt: PromptTemplateFunction = (
history,
otherData,
) => {
return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`;
};

View file

@ -5,6 +5,7 @@ import { getMCPToolName } from "./mcpToolName";
const createMcpServer = (name: string): MCPServerStatus => ({
name,
errors: [],
infos: [],
prompts: [],
tools: [],
resources: [],

View file

@ -46,6 +46,6 @@ export enum ContinueErrorReason {
ParentDirectoryNotFound = "parent_directory_not_found",
// Other
Unspecificied = "unspecified",
Unspecified = "unspecified",
Unknown = "unknown",
}

File diff suppressed because it is too large Load diff

View file

@ -44,7 +44,9 @@
},
"homepage": "https://continue.dev",
"dependencies": {
"@sentry/profiling-node": "^9.43.0"
"@sentry/profiling-node": "^9.43.0",
"fdir": "^6.4.2",
"fzf": "^0.5.2"
},
"devDependencies": {
"@continuedev/config-yaml": "file:../../packages/config-yaml",

View file

@ -0,0 +1,233 @@
import * as fs from "fs";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
autoSelectOrganizationAndConfig,
createUpdatedAuthConfig,
} from "./orgSelection.js";
import type { AuthenticatedConfig } from "./workos.js";
// Mock dependencies
vi.mock("fs");
vi.mock("../config.js");
vi.mock("../env.js");
vi.mock("./workos.js");
const mockApiClient = {
listOrganizations: vi.fn(),
listAssistants: vi.fn(),
} as any; // Mock API client for testing
describe("orgSelection", () => {
const mockConfig: AuthenticatedConfig = {
userId: "user123",
userEmail: "user@example.com",
accessToken: "token123",
refreshToken: "refresh123",
expiresAt: Date.now() + 3600000,
organizationId: undefined,
configUri: undefined,
modelName: undefined,
};
beforeEach(async () => {
vi.clearAllMocks();
// Mock modules using vi.mocked
const configMod = await import("../config.js");
const envMod = await import("../env.js");
const workosMod = await import("./workos.js");
vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient);
vi.mocked(envMod.env).continueHome = "/mock/home";
vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {});
// Default: no local config
vi.mocked(fs.existsSync).mockReturnValue(false);
});
describe("createUpdatedAuthConfig", () => {
it("should update organization ID", () => {
const result = createUpdatedAuthConfig(mockConfig, "org123");
expect(result.organizationId).toBe("org123");
});
it("should update organization ID and config URI", () => {
const result = createUpdatedAuthConfig(
mockConfig,
"org123",
"slug://owner/assistant",
);
expect(result.organizationId).toBe("org123");
expect(result!.configUri).toBe("slug://owner/assistant");
});
it("should set personal organization", () => {
const result = createUpdatedAuthConfig(mockConfig, null);
expect(result.organizationId).toBe(null);
});
});
describe("autoSelectOrganizationAndConfig scenarios", () => {
it("Priority 1: Org with assistants → select first assistant", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [
{ id: "org1", name: "Org 1" },
{ id: "org2", name: "Org 2" },
],
});
// Mock API calls in order: org1 assistants, org2 assistants
mockApiClient.listAssistants.mockImplementation(
({ organizationId }: { organizationId?: string }) => {
if (organizationId === "org1") return Promise.resolve([]);
if (organizationId === "org2")
return Promise.resolve([
{ ownerSlug: "owner", packageSlug: "assistant1" },
]);
return Promise.resolve([]);
},
);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe("org2");
expect(result!.configUri).toBe("slug://owner/assistant1");
});
it("Priority 2: No org assistants → personal assistants exist", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants.mockImplementation(
({ organizationId }: { organizationId?: string }) => {
if (organizationId === "org1") return Promise.resolve([]);
if (organizationId === undefined)
return Promise.resolve([
{ ownerSlug: "personal", packageSlug: "my-assistant" },
]);
return Promise.resolve([]);
},
);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null); // personal org
expect(result!.configUri).toBe("slug://personal/my-assistant");
expect(mockApiClient.listAssistants).toHaveBeenCalledWith({
organizationId: undefined,
});
});
it("Priority 3: No assistants anywhere → local config.yaml exists", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toContain("config.yaml");
});
it("Priority 4: No assistants, no config.yaml → fallback", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toBeUndefined();
});
it("Multiple orgs with assistants → pick first one", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [
{ id: "org1", name: "Org 1" },
{ id: "org2", name: "Org 2" },
],
});
mockApiClient.listAssistants.mockImplementation(
({ organizationId }: { organizationId?: string }) => {
if (organizationId === "org1")
return Promise.resolve([
{ ownerSlug: "owner1", packageSlug: "assistant1" },
]);
if (organizationId === "org2")
return Promise.resolve([
{ ownerSlug: "owner2", packageSlug: "assistant2" },
]);
return Promise.resolve([]);
},
);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe("org1"); // First org wins
expect(result!.configUri).toBe("slug://owner1/assistant1");
});
it("Personal assistants API fails → fallback to config.yaml", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [{ id: "org1", name: "Org 1" }],
});
mockApiClient.listAssistants
.mockResolvedValueOnce([]) // org1: no assistants
.mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error
vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toContain("config.yaml");
});
it("Empty organizations list → check personal assistants", async () => {
mockApiClient.listOrganizations.mockResolvedValue({
organizations: [], // No orgs
});
mockApiClient.listAssistants.mockResolvedValue([
{ ownerSlug: "personal", packageSlug: "my-assistant" },
]);
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toBe("slug://personal/my-assistant");
});
it("API error → fallback with error message", async () => {
mockApiClient.listOrganizations.mockRejectedValue(
new Error("Network error"),
);
const consoleSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
const result = await autoSelectOrganizationAndConfig(mockConfig);
expect(result!.organizationId).toBe(null);
expect(result!.configUri).toBeUndefined();
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining("Error fetching organizations:"),
"Network error",
);
consoleSpy.mockRestore();
});
});
});

View file

@ -0,0 +1,155 @@
import * as fs from "fs";
import * as path from "path";
import chalk from "chalk";
import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js";
import { saveAuthConfig } from "../auth/workos.js";
import { getApiClient } from "../config.js";
import { env } from "../env.js";
/**
* Creates an updated AuthenticatedConfig with a new organization ID and optional config URI
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
organizationId: string | null | undefined,
configUri?: string | null,
): AuthenticatedConfig {
return {
userId: config.userId,
userEmail: config.userEmail,
accessToken: config.accessToken,
refreshToken: config.refreshToken,
expiresAt: config.expiresAt,
organizationId,
configUri: configUri ?? config.configUri,
modelName: config.modelName,
};
}
/**
* Check if an organization has available assistants
*/
async function hasOrgAssistants(
apiClient: ReturnType<typeof getApiClient>,
organizationId: string,
): Promise<boolean> {
try {
const assistants = await apiClient.listAssistants({ organizationId });
return assistants.length > 0;
} catch {
// If we can't check, assume no assistants
return false;
}
}
/**
* Get the first available assistant from an organization
*/
async function getFirstAssistant(
apiClient: ReturnType<typeof getApiClient>,
organizationId: string,
): Promise<string | null> {
try {
const assistants = await apiClient.listAssistants({ organizationId });
if (assistants.length > 0) {
const first = assistants[0];
return `${first.ownerSlug}/${first.packageSlug}`;
}
return null;
} catch {
return null;
}
}
/**
* Check if personal local config.yaml exists
*/
function hasPersonalLocalConfig(): boolean {
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
return fs.existsSync(defaultConfigPath);
}
/**
* Automatically select organization and configuration for authenticated config
* Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback
*/
export async function autoSelectOrganizationAndConfig(
authenticatedConfig: AuthenticatedConfig,
): Promise<AuthConfig> {
const apiClient = getApiClient(authenticatedConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
// Priority 1: Find any organization that has assistants - use first assistant
for (const org of organizations) {
const hasAssistants = await hasOrgAssistants(apiClient, org.id);
if (hasAssistants) {
// Get the first assistant from this org
const firstAssistantSlug = await getFirstAssistant(apiClient, org.id);
const configUri = firstAssistantSlug
? `slug://${firstAssistantSlug}`
: undefined;
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
org.id,
configUri,
);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
}
// Priority 2: Check if personal organization has assistants
try {
const personalAssistants = await apiClient.listAssistants({
organizationId: undefined,
});
if (personalAssistants.length > 0) {
const firstAssistant = personalAssistants[0];
const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`;
const configUri = `slug://${firstAssistantSlug}`;
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
null,
configUri,
);
saveAuthConfig(updatedConfig);
console.log(chalk.green("✓ Automatically selected personal assistant"));
return updatedConfig;
}
} catch {
// If personal assistants can't be fetched, continue to next priority
}
// Priority 3: If no assistants anywhere, use local config.yaml
if (hasPersonalLocalConfig()) {
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
null,
`file://${path.join(env.continueHome, "config.yaml")}`,
);
saveAuthConfig(updatedConfig);
console.log(chalk.green("✓ Using local config.yaml"));
return updatedConfig;
}
// no org assistants or config.yaml
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
} catch (error: any) {
console.error(
chalk.red("Error fetching organizations:"),
error.response?.data?.message || error.message || error,
);
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
}

View file

@ -16,7 +16,7 @@ import { saveAuthConfig } from "./workos.js";
*/
export function createUpdatedAuthConfig(
config: AuthenticatedConfig,
organizationId: string | null,
organizationId: string | null | undefined,
): AuthenticatedConfig {
return {
userId: config.userId,
@ -124,43 +124,3 @@ export async function handleCliOrgForAuthenticatedConfig(
saveAuthConfig(updatedConfig);
return updatedConfig;
}
/**
* Automatically select organization for authenticated config
*/
export async function autoSelectOrganization(
authenticatedConfig: AuthenticatedConfig,
): Promise<AuthConfig> {
const apiClient = getApiClient(authenticatedConfig.accessToken);
try {
const resp = await apiClient.listOrganizations();
const organizations = resp.organizations;
if (organizations.length === 0) {
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// Automatically select the first organization if available
const selectedOrg = organizations[0];
const selectedOrgId = selectedOrg.id;
const updatedConfig = createUpdatedAuthConfig(
authenticatedConfig,
selectedOrgId,
);
saveAuthConfig(updatedConfig);
return updatedConfig;
} catch (error: any) {
console.error(
chalk.red("Error fetching organizations:"),
error.response?.data?.message || error.message || error,
);
console.info(chalk.yellow("Continuing without organization selection."));
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
}

View file

@ -22,7 +22,7 @@ export interface AuthenticatedConfig {
accessToken: string;
refreshToken: string;
expiresAt: number;
organizationId: string | null; // null means personal organization
organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
modelName?: string; // Name of the selected model
}
@ -74,7 +74,9 @@ export function getAccessToken(config: AuthConfig): string | null {
/**
* Gets the organization ID from any auth config type
*/
export function getOrganizationId(config: AuthConfig): string | null {
export function getOrganizationId(
config: AuthConfig,
): string | null | undefined {
if (config === null) return null;
return config.organizationId;
}
@ -96,10 +98,9 @@ export function getModelName(config: AuthConfig): string | null {
}
// URI utility functions have been moved to ./uriUtils.ts
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
import {
autoSelectOrganization,
createUpdatedAuthConfig,
handleCliOrgForAuthenticatedConfig,
handleCliOrgForEnvironmentAuth,
} from "./workos.helpers.js";
@ -360,7 +361,7 @@ async function pollForDeviceToken(
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: tokenExpiresAt,
organizationId: null,
organizationId: undefined, // undefined triggers auto-selection, null means personal org selected
};
// Save the config
@ -563,20 +564,18 @@ export async function ensureOrganization(
);
}
// If already have organization ID (including null for personal), return as-is
if (authenticatedConfig.organizationId !== undefined) {
return authenticatedConfig;
// Only auto-select if user hasn't made any previous selections
// - organizationId === undefined means first-time setup
// - configUri being set means they've chosen a specific assistant/config
if (
authenticatedConfig.organizationId === undefined &&
!authenticatedConfig.configUri
) {
return autoSelectOrganizationAndConfig(authenticatedConfig);
}
// In headless mode, default to personal organization if none saved
if (isHeadless) {
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
saveAuthConfig(updatedConfig);
return updatedConfig;
}
// Need to select organization
return autoSelectOrganization(authenticatedConfig);
// User already has made a selection (org or config) - respect their choice
return authenticatedConfig;
}
/**

View file

@ -498,17 +498,12 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
const { permissionOverrides } = processCommandFlags(options);
// Initialize services with onboarding handled internally
const initResult = await initializeServices({
await initializeServices({
options,
headless: false,
toolPermissionOverrides: permissionOverrides,
});
// If onboarding was completed, show success message
if (initResult.wasOnboarded) {
console.log(chalk.green("✓ Setup complete! Starting chat..."));
}
// Start TUI with skipOnboarding since we already handled it
const tuiOptions: any = {
initialPrompt: prompt,

View file

@ -39,7 +39,7 @@ export function createLlmApi(
apiKey: accessToken ?? undefined,
env: {
apiKeyLocation: (model as any).apiKeyLocation,
orgScopeId: organizationId,
orgScopeId: organizationId ?? null,
proxyUrl:
(model as { onPremProxyUrl: string | undefined })
.onPremProxyUrl ?? undefined,

View file

@ -55,7 +55,7 @@ export async function loadConfiguration(
const config = await loadFromSource(
configSource,
accessToken,
organizationId,
organizationId ?? null,
apiClient,
);

View file

@ -1,256 +0,0 @@
import * as fs from "node:fs";
import * as path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
cleanupTestContext,
createTestConfig,
createTestContext,
runCLI,
type CLITestContext,
} from "../test-helpers/cli-helpers.js";
import { HOME_DIRECTORY_WARNING } from "../ui/IntroMessage.js";
describe("E2E: Home Directory Warning", () => {
let context: CLITestContext;
const testConfig = `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
describe("home directory detection", () => {
it("should NOT show warning in headless mode even when running from home directory", async () => {
await createTestConfig(context, testConfig);
// Simulate running from home directory using the isolated test dir
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath!, "test prompt"],
env: {
OPENAI_API_KEY: "test-key",
// Ensure home vars point to the isolated test dir
HOME: context.testDir,
USERPROFILE: context.testDir,
HOMEDRIVE: path.parse(context.testDir).root,
HOMEPATH: path.relative(
path.parse(context.testDir).root,
context.testDir,
),
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
},
timeout: 5000,
expectError: true,
});
// Should NOT contain the home directory warning in headless mode
const output = result.stdout + result.stderr;
expect(output).not.toContain(HOME_DIRECTORY_WARNING);
});
it("should show warning when running from home directory in TUI mode", async () => {
await createTestConfig(context, testConfig);
// Test TUI mode (without -p flag) from an isolated "home" directory
const result = await runCLI(context, {
args: ["--config", context.configPath!],
env: {
OPENAI_API_KEY: "test-key",
HOME: context.testDir,
USERPROFILE: context.testDir,
HOMEDRIVE: path.parse(context.testDir).root,
HOMEPATH: path.relative(
path.parse(context.testDir).root,
context.testDir,
),
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
},
timeout: 3000,
expectError: true,
});
// In TUI mode, if we get any meaningful output, check for warning
const output = result.stdout + result.stderr;
if (
output.includes("Continue") ||
output.includes("Agent") ||
output.includes("Model")
) {
expect(output).toContain(HOME_DIRECTORY_WARNING);
} else {
// TUI mode likely failed to start in test environment, which is expected
// The important thing is that it attempted TUI mode, not headless mode
expect(result.exitCode).toBeDefined();
}
});
it("should NOT show warning in headless mode regardless of platform", async () => {
await createTestConfig(context, testConfig);
// Test with different platform-specific environment variables
const platformEnvs: Record<string, string>[] = [
// Unix-style
{
HOME: context.testDir,
OPENAI_API_KEY: "test-key",
},
// Windows-style
{
USERPROFILE: context.testDir,
HOMEDRIVE: path.parse(context.testDir).root,
HOMEPATH: path.relative(
path.parse(context.testDir).root,
context.testDir,
),
OPENAI_API_KEY: "test-key",
},
];
for (const env of platformEnvs) {
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath!, "test prompt"],
env: {
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
...env,
},
timeout: 5000,
expectError: true,
});
// Should NOT contain warning in headless mode regardless of platform
const output = result.stdout + result.stderr;
expect(output).not.toContain(HOME_DIRECTORY_WARNING);
}
});
it("should NOT show warning in headless mode with symlinked home directories", async () => {
await createTestConfig(context, testConfig);
// Create a symlink to the isolated home directory to simulate symlinked home paths
const realHome = fs.realpathSync(context.testDir);
const linkPath = path.join(
path.dirname(realHome),
`${path.basename(realHome)}-link`,
);
try {
if (!fs.existsSync(linkPath)) {
fs.symlinkSync(realHome, linkPath, "dir");
}
} catch {
// If symlink creation fails (e.g., on Windows without privileges), skip this specific scenario
}
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath!, "test prompt"],
env: {
OPENAI_API_KEY: "test-key",
// Point HOME to the symlink while cwd remains the real path
HOME: fs.existsSync(linkPath) ? linkPath : realHome,
USERPROFILE: fs.existsSync(linkPath) ? linkPath : realHome,
HOMEDRIVE: path.parse(realHome).root,
HOMEPATH: path.relative(path.parse(realHome).root, realHome),
CONTINUE_GLOBAL_DIR: path.join(realHome, ".continue-global"),
},
timeout: 5000,
expectError: true,
});
// Should NOT detect home directory warning in headless mode even with resolved paths
const output = result.stdout + result.stderr;
expect(output).not.toContain(HOME_DIRECTORY_WARNING);
});
it("should work in TUI mode (when available)", async () => {
await createTestConfig(context, testConfig);
// Test TUI mode behavior (though it may fail in test environment)
const result = await runCLI(context, {
args: ["--config", context.configPath!],
env: {
OPENAI_API_KEY: "test-key",
HOME: context.testDir,
USERPROFILE: context.testDir,
HOMEDRIVE: path.parse(context.testDir).root,
HOMEPATH: path.relative(
path.parse(context.testDir).root,
context.testDir,
),
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
},
timeout: 3000,
expectError: true,
});
// Even if TUI fails to start properly in test environment,
// the warning should still be present in any output
const output = result.stdout + result.stderr;
if (output.includes("Continue")) {
// If we got any meaningful output, check for warning
expect(output).toContain(HOME_DIRECTORY_WARNING);
}
});
});
describe("edge cases", () => {
it("should handle case where home directory cannot be determined", async () => {
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath!, "test prompt"],
env: {
OPENAI_API_KEY: "test-key",
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
// Mask home directory environment variables so os.homedir() cannot derive a value
HOME: "",
USERPROFILE: "",
HOMEDRIVE: "",
HOMEPATH: "",
},
timeout: 5000,
expectError: true,
});
// Should not crash when home directory cannot be determined
expect(result.exitCode).toBeDefined();
const output = result.stdout + result.stderr;
// Should not show warning if home cannot be determined (and we're in headless mode anyway)
expect(output).not.toContain(HOME_DIRECTORY_WARNING);
});
it("should handle relative vs absolute path comparisons", async () => {
await createTestConfig(context, testConfig);
// Use a HOME that is equivalent but not identical (e.g., with './')
const altHome = path.join(context.testDir, ".");
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath!, "test prompt"],
env: {
OPENAI_API_KEY: "test-key",
HOME: altHome,
USERPROFILE: altHome,
HOMEDRIVE: path.parse(altHome).root,
HOMEPATH: path.relative(path.parse(altHome).root, altHome),
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"),
},
timeout: 5000,
expectError: true,
});
// Should handle path resolution correctly (no crash)
expect(result.exitCode).toBeDefined();
});
});
});

View file

@ -105,7 +105,10 @@ async function runOnboardingFlow(
if (choice === "1" || choice === "") {
const newAuthConfig = await login();
const result = await initialize(newAuthConfig, undefined);
const { ensureOrganization } = await import("./auth/workos.js");
const finalAuthConfig = await ensureOrganization(newAuthConfig);
const result = await initialize(finalAuthConfig, undefined);
return { ...result, wasOnboarded: true };
} else if (choice === "2") {
const apiKey = readlineSync.question(

View file

@ -59,24 +59,25 @@ describe("FileIndexService", () => {
expect(filePaths).toContain("README.md");
});
it("should filter files correctly", async () => {
it("should filter files correctly with fzf", async () => {
// Create test files
fs.writeFileSync("component.tsx", "export default () => <div></div>");
fs.writeFileSync("utils.ts", "export const util = () => {}");
fs.writeFileSync("styles.css", ".test { color: red; }");
fs.writeFileSync("readme.md", "# Documentation");
await service.initialize();
// Test filtering by extension
const tsFiles = service.filterFiles("ts");
expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true);
expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true);
expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false);
// Test filtering with more specific terms that won't fuzzy match
const tsxFiles = await service.filterFiles("tsx");
expect(tsxFiles.some((f) => f.path === "component.tsx")).toBe(true);
expect(tsxFiles.some((f) => f.path === "utils.ts")).toBe(false);
expect(tsxFiles.some((f) => f.path === "readme.md")).toBe(false);
// Test filtering by name
const componentFiles = service.filterFiles("component");
const componentFiles = await service.filterFiles("component");
expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true);
expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false);
expect(componentFiles.some((f) => f.path === "readme.md")).toBe(false);
});
it("should handle empty directory", async () => {
@ -123,7 +124,7 @@ describe("FileIndexService", () => {
await service.initialize();
const files = service.filterFiles("");
const files = await service.filterFiles("");
expect(files[0].path).toBe("alpha.js");
expect(files[1].path).toBe("beta.js");
expect(files[2].path).toBe("zebra.js");
@ -137,7 +138,7 @@ describe("FileIndexService", () => {
await service.initialize();
const filtered = service.filterFiles("test");
const filtered = await service.filterFiles("test");
// Should include both files that match the filter
expect(filtered.length).toBeGreaterThanOrEqual(2);
@ -155,7 +156,7 @@ describe("FileIndexService", () => {
await service.initialize();
const files = service.filterFiles("", 5);
const files = await service.filterFiles("", 5);
expect(files.length).toBe(5);
});
@ -173,4 +174,36 @@ describe("FileIndexService", () => {
await service.refreshIndex();
expect(service.getFiles().length).toBe(2);
});
it("should handle fuzzy search with AsyncFzf", async () => {
// Create test files for fuzzy matching
fs.writeFileSync("user-service.ts", "export class UserService {}");
fs.writeFileSync("user-model.ts", "export interface User {}");
fs.writeFileSync("config.json", "{}");
await service.initialize();
// Test fuzzy search (should match both user files)
const userFiles = await service.filterFiles("usmo"); // us(er) mo(del)
expect(userFiles.length).equal(1);
expect(userFiles.some((f) => f.path === "user-model.ts")).toBe(true);
});
it("should find files with @ symbols when searched with @ pattern", async () => {
// Create test file with @ symbols in the name
fs.writeFileSync("test@123.txt", "test content");
fs.writeFileSync("regular-file.js", "normal file");
fs.writeFileSync("other@456.md", "other content");
await service.initialize();
// Search for "test@123" - should match "test@123.txt"
const results = await service.filterFiles("test@123");
expect(results.length).equal(1);
expect(results.some((f) => f.path === "test@123.txt")).toBe(true);
// Should not match files that don't contain the @ pattern
expect(results.some((f) => f.path === "regular-file.js")).toBe(false);
});
});

View file

@ -1,9 +1,7 @@
import { glob, GlobOptionsWithFileTypesFalse } from "glob";
import { fdir } from "fdir";
import { AsyncFzf, FzfResultItem } from "fzf";
import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js";
import { getFileWatcher } from "../util/fileWatcher.js";
import { isGitRepo } from "../util/git.js";
import { isInHomeDirectory } from "../util/isInHomeDirectory.js";
import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js";
import { logger } from "../util/logger.js";
import { BaseService } from "./BaseService.js";
@ -12,6 +10,7 @@ import { serviceContainer } from "./ServiceContainer.js";
export interface FileItem {
path: string;
displayName: string;
positions?: Set<number>;
}
export interface FileIndexServiceState {
@ -21,9 +20,79 @@ export interface FileIndexServiceState {
}
export class FileIndexService extends BaseService<FileIndexServiceState> {
private fileSet = new Set<string>();
private fileWatcherInitialized = false;
private fileWatcherUnsubscribe: (() => void) | null = null;
private fzf: AsyncFzf<FileItem[]> | null = null;
// Helper to check if a file should be included based on FILE_PATTERNS
private shouldIncludeFile(filePath: string): boolean {
const fileName = filePath.split("/").pop()?.toLowerCase() || "";
const ext = fileName.split(".").pop();
// Check if file matches any of the original FILE_PATTERNS
const supportedExtensions = [
"ts",
"tsx",
"js",
"jsx",
"py",
"java",
"cpp",
"c",
"h",
"hpp",
"cs",
"go",
"rs",
"rb",
"php",
"swift",
"kt",
"scala",
"md",
"json",
"yaml",
"yml",
"xml",
"html",
"css",
"scss",
"sass",
"less",
"sql",
"sh",
"dockerfile",
"makefile",
"cmake",
"gradle",
"toml",
"ini",
"env",
"txt",
"log",
];
// Check extension match
if (ext && supportedExtensions.includes(ext)) {
return true;
}
// Check special file patterns
if (
fileName.startsWith("readme") ||
fileName.startsWith("license") ||
fileName.startsWith("changelog") ||
fileName === "package.json" ||
fileName === "cargo.toml" ||
fileName === "pyproject.toml" ||
fileName === "composer.json" ||
fileName === "gemfile" ||
fileName === ".gitignore" ||
fileName.startsWith(".env")
) {
return true;
}
return false;
}
constructor() {
super("FileIndexService", {
@ -35,23 +104,11 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
async doInitialize(): Promise<FileIndexServiceState> {
await this.performFullIndex();
this.setupFileWatcher();
return this.getState();
}
async cleanup(): Promise<void> {
if (this.fileWatcherUnsubscribe) {
this.fileWatcherUnsubscribe();
this.fileWatcherUnsubscribe = null;
}
// Stop the file watcher to prevent resource leaks
if (this.fileWatcherInitialized) {
const watcher = getFileWatcher();
watcher.stopWatching();
}
this.fileWatcherInitialized = false;
// No cleanup needed - no file watchers or subscriptions
}
/**
@ -65,37 +122,74 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
serviceContainer.set("fileIndex", currentState);
}
private async performFullIndex(): Promise<void> {
private async performFullIndex(
bypassTimeout: boolean = false,
): Promise<void> {
this.setState({ isIndexing: true, error: null });
try {
const inGitRepo = isGitRepo();
const currentDir = process.cwd();
logger.debug(`Starting file index in directory: ${currentDir}`);
if (isInHomeDirectory()) {
this.setState({
isIndexing: false,
error: "Skipping full index as in home directory",
// Create file indexing promise
const fileIndexPromise = new fdir()
.withFullPaths()
.withRelativePaths()
.filter((path) => {
// Use the helper function that implements original FILE_PATTERNS logic
return this.shouldIncludeFile(path);
})
.exclude((dirName) => {
// Exclude directories based on FILE_IGNORE_PATTERNS
for (const pattern of FILE_IGNORE_PATTERNS) {
if (pattern.startsWith("**/") && pattern.endsWith("/**")) {
const excludeDirName = pattern.slice(3, -3);
if (dirName === excludeDirName) {
return true;
}
}
}
return false;
})
.crawl(currentDir)
.withPromise();
let allFiles: string[];
if (bypassTimeout) {
// Manual refresh - wait for completion regardless of time
allFiles = await fileIndexPromise;
} else {
// Automatic indexing - race against 1-second timeout
const timeoutPromise = new Promise<"timeout">((resolve) => {
setTimeout(() => {
resolve("timeout");
}, 1000);
});
return;
const result = await Promise.race([fileIndexPromise, timeoutPromise]);
if (result === "timeout") {
this.setState({
files: [],
isIndexing: false,
error: "directory-too-large",
});
return;
}
allFiles = result as string[];
}
const allMatches = await this.throttledGlob(FILE_PATTERNS, {
maxDepth: inGitRepo ? 15 : 3,
ignore: FILE_IGNORE_PATTERNS,
dot: true,
absolute: false,
});
const uniqueFiles = [...new Set(allMatches)];
this.fileSet.clear();
uniqueFiles.forEach((file) => this.fileSet.add(file));
const files = uniqueFiles.map((path) => ({
const fileItems = allFiles.map((path) => ({
path,
displayName: path,
}));
this.setState({ files, isIndexing: false });
this.rebuildFzf(fileItems);
this.setState({ files: fileItems, isIndexing: false });
logger.debug(`Indexed ${fileItems.length} files`);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
@ -104,116 +198,10 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
}
}
private setupFileWatcher(): void {
if (this.fileWatcherInitialized) {
return;
}
// Only enable file watching in git repositories
// Outside git repos (like home directory), file watching causes performance issues
// and provides little value since files change less predictably
const inGitRepo = isGitRepo();
if (!inGitRepo) {
logger.debug("Skipping file watcher: not in a git repository");
return;
}
this.fileWatcherInitialized = true;
const watcher = getFileWatcher();
// Start watching the current directory
watcher.startWatching();
// Set up callback for incremental updates
this.fileWatcherUnsubscribe = watcher.onChange(() => {
this.handleFileSystemChange();
});
}
private async handleFileSystemChange(): Promise<void> {
try {
// Get current files from file system
const inGitRepo = isGitRepo();
const allMatches = await this.throttledGlob(FILE_PATTERNS, {
maxDepth: inGitRepo ? 15 : 3,
ignore: FILE_IGNORE_PATTERNS,
dot: true,
absolute: false,
});
const currentFiles = new Set(allMatches);
const previousFiles = this.fileSet;
// Find added and removed files
const addedFiles = [...currentFiles].filter(
(file) => !previousFiles.has(file),
);
const removedFiles = [...previousFiles].filter(
(file) => !currentFiles.has(file),
);
// Only update if there are actual changes
if (addedFiles.length > 0 || removedFiles.length > 0) {
// Update internal file set
this.fileSet = currentFiles;
// Create new files array
const files = [...currentFiles].map((path) => ({
path,
displayName: path,
}));
this.setState({ files });
}
} catch (error) {
logger.error("Error handling file system change:", error);
const errorMessage =
error instanceof Error ? error.message : String(error);
this.setState({ error: errorMessage });
}
}
private async throttledGlob(
patterns: string[],
options: GlobOptionsWithFileTypesFalse,
batchSize = 100,
delay = 20,
): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
const allMatches: string[] = [];
let processed = 0;
let streamEnded = false;
const globStream = glob.stream(patterns, options);
globStream.on("data", (file: string) => {
allMatches.push(file);
processed++;
if (processed % batchSize === 0) {
if (streamEnded) {
return;
}
globStream.pause();
setTimeout(() => {
if (streamEnded) {
return;
}
globStream.resume();
}, delay);
}
});
globStream.on("end", () => {
streamEnded = true;
resolve(allMatches);
});
globStream.on("error", (err) => {
streamEnded = true;
reject(err);
});
private rebuildFzf(files: FileItem[]): void {
this.fzf = new AsyncFzf(files, {
selector: (item: FileItem) => item.path,
casing: "case-insensitive",
});
}
@ -230,11 +218,14 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
return this.getState().error;
}
public async refreshIndex(): Promise<void> {
await this.performFullIndex();
public async refreshIndex(bypassTimeout: boolean = false): Promise<void> {
await this.performFullIndex(bypassTimeout);
}
public filterFiles(filterText: string, limit: number = 10): FileItem[] {
public async filterFiles(
filterText: string,
limit: number = 10,
): Promise<FileItem[]> {
const files = this.getFiles();
if (filterText.length === 0) {
@ -248,36 +239,16 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
.slice(0, limit);
}
const lowerFilter = filterText.toLowerCase();
// Use fzf for fuzzy search
if (!this.fzf) {
this.rebuildFzf(files);
}
return files
.filter((file) => {
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
.sort((a, b) => {
const aFileName = a.path.split("/").pop() || a.path;
const bFileName = b.path.split("/").pop() || b.path;
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, limit);
const results = await this.fzf!.find(filterText);
return results.slice(0, limit).map((entry: FzfResultItem<FileItem>) => ({
path: entry.item.path,
displayName: entry.item.displayName,
positions: entry.positions,
}));
}
}

View file

@ -1,8 +1,12 @@
import { Box, Text } from "ink";
import { Box, Text, useInput } from "ink";
import React, { useEffect, useState } from "react";
import { useServices } from "../hooks/useService.js";
import { FileIndexServiceState } from "../services/FileIndexService.js";
import {
FileIndexServiceState,
FileItem,
} from "../services/FileIndexService.js";
import { services } from "../services/index.js";
interface FileSearchUIProps {
filter: string;
@ -11,10 +15,45 @@ interface FileSearchUIProps {
onFilesUpdated?: (files: FileItem[]) => void;
}
interface FileItem {
path: string;
displayName: string;
}
// Highlighting component for matched characters
const HighlightedText: React.FC<{ text: string; positions?: Set<number> }> = ({
text,
positions,
}) => {
if (!positions || positions.size === 0) {
return <>{text}</>;
}
const chars = text.split("");
const elements: React.ReactNode[] = [];
chars.forEach((char, index) => {
if (positions.has(index)) {
elements.push(
<Text key={index} color="white">
{char}
</Text>,
);
} else {
elements.push(char);
}
});
return <>{elements}</>;
};
// Reusable container for consistent layout
const FileSearchContainer: React.FC<{ children: React.ReactNode }> = ({
children,
}) => (
<Box paddingX={1} marginX={1} marginBottom={1} flexDirection="column">
<Box marginTop={1}>{children}</Box>
</Box>
);
// Keyboard navigation shortcuts help text
const KEYBOARD_SHORTCUTS =
"↑/↓ to navigate, Enter to select, Tab to complete, Ctrl+r to refresh list";
const FileSearchUI: React.FC<FileSearchUIProps> = ({
filter,
@ -23,89 +62,97 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
}) => {
const [files, setFiles] = useState<FileItem[]>([]);
// Get file index service
const { services } = useServices<{
// Get file index service state for reactive updates
const { services: serviceStates } = useServices<{
fileIndex: FileIndexServiceState;
}>(["fileIndex"]);
const fileIndexService = services.fileIndex;
const fileIndexServiceState = serviceStates.fileIndex;
useEffect(() => {
if (!fileIndexService) {
if (!fileIndexServiceState) {
return;
}
// Get filtered files from the service
const filteredFiles = fileIndexService.files
.filter((file) => {
if (filter.length === 0) {
return true;
// Use the FileIndexService's filterFiles method which includes fzf fuzzy matching
const fetchFilteredFiles = async () => {
try {
// console.log(`FileSearchUI: Filtering files with "${filter}", total files in state:`, fileIndexServiceState?.files?.length);
const filteredFiles = await services.fileIndex.filterFiles(filter, 10);
// console.log(`FileSearchUI: Filtered to ${filteredFiles.length} files`);
setFiles(filteredFiles);
if (onFilesUpdated) {
onFilesUpdated(filteredFiles);
}
const lowerFilter = filter.toLowerCase();
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
.sort((a, b) => {
if (filter.length === 0) {
// Sort alphabetically when no filter
const aFileName = a.path.split("/").pop() || a.path;
const bFileName = b.path.split("/").pop() || b.path;
return aFileName.localeCompare(bFileName);
} catch (error) {
// Suppress expected "search cancelled" errors from AsyncFzf when typing fast
const errorMessage =
error instanceof Error ? error.message : String(error);
if (!errorMessage.includes("search cancelled")) {
console.error("Error filtering files:", error);
}
setFiles([]);
}
};
const lowerFilter = filter.toLowerCase();
const aFileName = a.path.split("/").pop() || a.path;
const bFileName = b.path.split("/").pop() || b.path;
fetchFilteredFiles();
}, [fileIndexServiceState?.files, filter, onFilesUpdated]);
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
setFiles(filteredFiles);
if (onFilesUpdated) {
onFilesUpdated(filteredFiles);
// Handle Ctrl+R to refresh file index
useInput((input, key) => {
if (key.ctrl && input === "r") {
services.fileIndex.refreshIndex(true); // Bypass timeout for manual refresh
}
}, [fileIndexService?.files, filter, onFilesUpdated]);
});
if (fileIndexService?.isIndexing) {
if (fileIndexServiceState?.error) {
// Special handling for directory too large error
if (fileIndexServiceState.error === "directory-too-large") {
return (
<FileSearchContainer>
<Text color="gray" dimColor>
Ctrl+r to refresh list (this may take several seconds)
</Text>
</FileSearchContainer>
);
}
// Other errors
return (
<Box paddingX={1} marginX={1} marginBottom={1}>
<Text color="gray">Indexing files...</Text>
</Box>
<FileSearchContainer>
<Text color="red">
Error indexing files: {fileIndexServiceState.error}
</Text>
</FileSearchContainer>
);
}
if (fileIndexService?.error) {
return (
<Box paddingX={1} marginX={1} marginBottom={1}>
<Text color="red">Error indexing files: {fileIndexService.error}</Text>
</Box>
);
}
if (files.length === 0 && !fileIndexServiceState?.isIndexing) {
// Only show "No matching files found" if:
// 1. There are files in the index (so it's not a system issue)
// 2. There's actually a search filter (not just "@")
if (
fileIndexServiceState?.files &&
fileIndexServiceState.files.length > 0 &&
filter.length > 0
) {
return (
<FileSearchContainer>
<Text color="gray" dimColor>
No matching files found
</Text>
</FileSearchContainer>
);
}
if (files.length === 0) {
// Show keyboard navigation hints
return (
<Box paddingX={1} marginX={1} marginBottom={1}>
<Text color="gray">No matching files found</Text>
</Box>
<FileSearchContainer>
<Text color="gray" dimColor>
{KEYBOARD_SHORTCUTS}
</Text>
</FileSearchContainer>
);
}
@ -118,7 +165,13 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
<Box key={file.path}>
<Text color="white" bold={isSelected}>
{" "}
<Text color="green">@{file.displayName}</Text>
<Text color="green" dimColor={!isSelected}>
@
<HighlightedText
text={file.displayName}
positions={file.positions}
/>
</Text>
</Text>
</Box>
);
@ -126,7 +179,7 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
<Box marginTop={1}>
<Text color="gray" dimColor>
↑/↓ to navigate, Enter to select, Tab to complete
{KEYBOARD_SHORTCUTS}
</Text>
</Box>
</Box>

View file

@ -4,16 +4,11 @@ import React, { useMemo } from "react";
import { getDisplayableAsciiArt } from "../asciiArt.js";
import { MCPService } from "../services/MCPService.js";
import { isInHomeDirectory } from "../util/isInHomeDirectory.js";
import { isModelCapable } from "../utils/modelCapability.js";
import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js";
import { TipsDisplay, shouldShowTip } from "./TipsDisplay.js";
// Export the warning message for testing
export const HOME_DIRECTORY_WARNING =
"Run cn in a project directory for the best experience (currently in home directory)";
interface IntroMessageProps {
config?: AssistantUnrolled;
model?: ModelConfig;
@ -27,8 +22,6 @@ const extractRuleNames = (rules: any[] = []): string[] => {
);
};
const userInHomeDirectory = isInHomeDirectory();
const IntroMessage: React.FC<IntroMessageProps> = ({
config,
model,
@ -139,14 +132,6 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
{renderMcpPrompts()}
{renderRules()}
{renderMcpServers()}
{/* Home directory warning */}
{userInHomeDirectory && (
<>
<Text color="yellow">{HOME_DIRECTORY_WARNING}</Text>
<Text> </Text>
</>
)}
</Box>
);
};

View file

@ -1,7 +1,7 @@
import {
TextBuffer,
COLLAPSE_SIZE,
RAPID_INPUT_THRESHOLD,
TextBuffer,
} from "./TextBuffer.js";
describe("TextBuffer", () => {
@ -313,231 +313,255 @@ describe("TextBuffer", () => {
});
});
describe("paste collapse", () => {
it("should not collapse short pasted text", () => {
const shortText = "hello world";
buffer.handleInput(shortText, { ctrl: false, meta: false } as any);
describe("paste detection and collapse", () => {
describe("basic collapse behavior", () => {
it("should not collapse short content", () => {
const shortText = "hello world";
buffer.handleInput(shortText, { ctrl: false, meta: false } as any);
expect(buffer.text).toBe("hello world");
});
expect(buffer.text).toBe("hello world");
it("should collapse content exceeding threshold", () => {
const longText = "a".repeat(COLLAPSE_SIZE + 1);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
});
it("should count lines correctly in placeholders", () => {
const multiLineText =
"line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1, 4 lines]");
});
});
it("should collapse long pasted text exceeding collapse threshold", () => {
const longText = "a".repeat(COLLAPSE_SIZE + 1);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
describe("expansion and state management", () => {
it("should expand collapsed content on demand", () => {
const longText = "content " + "a".repeat(COLLAPSE_SIZE);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
buffer.expandAllPasteBlocks();
expect(buffer.text).toBe(longText);
});
it("should increment paste counter for multiple pastes", () => {
const text1 = "a".repeat(COLLAPSE_SIZE + 1);
const text2 = "b".repeat(COLLAPSE_SIZE + 1);
buffer.handleInput(text1, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
buffer.insertText(" ");
buffer.handleInput(text2, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1] [Paste #2]");
});
it("should normalize line endings when expanding", () => {
const textWithMixedEndings =
"line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE);
buffer.handleInput(textWithMixedEndings, {
ctrl: false,
meta: false,
} as any);
buffer.flushPendingInput();
buffer.expandAllPasteBlocks();
const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
expect(buffer.text).toBe(expected);
});
it("should clear paste map after expansion", () => {
const longText = "a".repeat(COLLAPSE_SIZE + 1);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
buffer.expandAllPasteBlocks();
buffer.expandAllPasteBlocks(); // Second call should be no-op
expect(buffer.text).toBe(longText);
});
});
describe("rapid input detection (Terminal.app/Ghostty)", () => {
it("should detect large single input as rapid paste", () => {
const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1);
buffer.handleInput(rapidText, { ctrl: false, meta: false } as any);
expect(buffer.text).toBe(""); // Should be buffered
expect(buffer.isInRapidInputMode()).toBe(true);
buffer.flushPendingInput();
expect(buffer.text).toBe(rapidText); // < COLLAPSE_SIZE, so not collapsed
});
it("should combine multiple chunks into single paste", () => {
const chunk1 = "a".repeat(200);
const chunk2 = "b".repeat(700); // Combined > COLLAPSE_SIZE
buffer.handleInput(chunk1, { ctrl: false, meta: false } as any);
buffer.handleInput(chunk2, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
buffer.expandAllPasteBlocks();
expect(buffer.text).toBe(chunk1 + chunk2);
});
it("should detect 50+ char chunks as start of paste session", () => {
const smallChunk = "x".repeat(60); // >= 50, should trigger
const largeChunk = "y".repeat(800);
buffer.handleInput(smallChunk, { ctrl: false, meta: false } as any);
expect(buffer.text).toBe("");
buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
buffer.expandAllPasteBlocks();
expect(buffer.text).toBe(smallChunk + largeChunk);
});
});
describe("bracketed paste (iTerm2)", () => {
it("should handle bracketed paste sequences", () => {
const content = "function test() { return 'hello'; }" + "x".repeat(800);
buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any);
expect(buffer.isInPasteMode()).toBe(true);
expect(buffer.text).toBe("");
buffer.handleInput(content, { ctrl: false, meta: false } as any);
expect(buffer.text).toBe(""); // Nothing visible during paste
buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any);
expect(buffer.isInPasteMode()).toBe(false);
expect(buffer.text).toBe("[Paste #1]");
buffer.expandAllPasteBlocks();
expect(buffer.text).toBe(content);
});
it("should not collapse short bracketed content", () => {
const shortContent = "Hello world!";
buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any);
buffer.handleInput(shortContent, { ctrl: false, meta: false } as any);
buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any);
expect(buffer.text).toBe(shortContent);
});
it("should prioritize bracketed paste over rapid input", () => {
const largeContent = "x".repeat(1000);
buffer.handleInput("\u001b[200~", { ctrl: false, meta: false } as any);
buffer.handleInput(largeContent, { ctrl: false, meta: false } as any);
expect(buffer.isInPasteMode()).toBe(true);
expect(buffer.isInRapidInputMode()).toBe(false);
buffer.handleInput("\u001b[201~", { ctrl: false, meta: false } as any);
expect(buffer.text).toBe("[Paste #1]");
});
});
});
describe("timing behavior", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("should combine chunks within 200ms timing window", () => {
const chunk1 = "x".repeat(100);
const chunk2 = "y".repeat(800);
buffer.handleInput(chunk1, { ctrl: false, meta: false } as any);
vi.advanceTimersByTime(100); // Within 200ms window
buffer.handleInput(chunk2, { ctrl: false, meta: false } as any);
vi.advanceTimersByTime(250); // Finalize
expect(buffer.text).toBe("[Paste #1]");
});
it("should count lines correctly in collapsed text", () => {
const multiLineText = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1, 4 lines]");
});
it("should expand collapsed content on expandAllPasteBlocks", () => {
const longText = "hello " + "a".repeat(COLLAPSE_SIZE);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
// Verify it was collapsed
expect(buffer.text).toBe("[Paste #1]");
// Expand it
buffer.expandAllPasteBlocks();
// Verify it was expanded with normalized line endings
expect(buffer.text).toBe(longText);
expect(buffer.text).toBe(chunk1 + chunk2);
});
it("should handle typing before and after collapsed content", () => {
buffer.setText("before ");
buffer.setCursor(7);
it("should finalize buffered content after 200ms timeout", () => {
const chunk = "x".repeat(100);
buffer.handleInput(chunk, { ctrl: false, meta: false } as any);
expect(buffer.text).toBe("");
vi.advanceTimersByTime(250);
expect(buffer.text).toBe(chunk);
});
it("should separate sessions when timing window expires", () => {
const chunk1 = "a".repeat(60);
const chunk2 = "b".repeat(900);
buffer.handleInput(chunk1, { ctrl: false, meta: false } as any);
vi.advanceTimersByTime(300); // Exceed timing window
expect(buffer.text).toBe(chunk1);
buffer.handleInput(chunk2, { ctrl: false, meta: false } as any);
vi.advanceTimersByTime(250);
expect(buffer.text).toBe(chunk1 + "[Paste #1]");
});
});
describe("regression tests", () => {
it("should prevent typing during paste accumulation (Terminal.app fix)", () => {
const largeChunk = "x".repeat(100);
buffer.handleInput(largeChunk, { ctrl: false, meta: false } as any);
// Small typed input should not be mixed into paste
const typedChar = "a";
buffer.handleInput(typedChar, { ctrl: false, meta: false } as any);
expect(buffer.text).toBe("a");
const longText = "a".repeat(COLLAPSE_SIZE + 1);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("before [Paste #1]");
// Type after collapsed content
buffer.insertText(" after");
expect(buffer.text).toBe("before [Paste #1] after");
// Move cursor to beginning and type
buffer.setCursor(0);
buffer.insertText("start ");
expect(buffer.text).toBe("start before [Paste #1] after");
expect(buffer.text).toBe("a" + largeChunk);
});
it("should handle exactly collapse threshold without collapsing", () => {
const exactText = "a".repeat(COLLAPSE_SIZE); // exactly at threshold
buffer.handleInput(exactText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput(); // This will go into rapid input mode due to size
expect(buffer.text).toBe(exactText); // Should not be collapsed
});
it("should handle paste operations as single large inputs", () => {
// This simulates the most common paste scenario: a single large input
const longText = "x".repeat(COLLAPSE_SIZE + 1);
expect(longText.length).toBeGreaterThan(COLLAPSE_SIZE);
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
// Should be collapsed
expect(buffer.text).toBe("[Paste #1]");
});
it("should handle bracketed paste mode", () => {
// Simulate bracketed paste: start sequence, content, end sequence
// Start paste mode
buffer.handleInput("\u001b[200~", {} as any);
expect(buffer.isInPasteMode()).toBe(true);
// Add some content (in chunks like real paste)
const chunks = [
"Hello ",
"world! ",
"This is a long piece of text. ".repeat(30),
];
const totalContent = chunks.join("");
it("should preserve all chunks when expanding (content loss fix)", () => {
const chunks = ["a".repeat(1000), "b".repeat(1000), "c".repeat(1000)];
chunks.forEach((chunk) => {
buffer.handleInput(chunk, { ctrl: false, meta: false } as any);
});
// Text should NOT be visible during paste mode (to avoid visual bugs)
expect(buffer.text).toBe("");
// End paste mode
buffer.handleInput("\u001b[201~", {} as any);
expect(buffer.isInPasteMode()).toBe(false);
// Now should be collapsed if > COLLAPSE_SIZE
if (totalContent.length > COLLAPSE_SIZE) {
expect(buffer.text).toBe("[Paste #1]");
}
});
it("should not collapse short bracketed paste content", () => {
// Start paste mode
buffer.handleInput("\u001b[200~", {} as any);
// Add short content
const shortContent = "Hello world!";
buffer.handleInput(shortContent, { ctrl: false, meta: false } as any);
// End paste mode
buffer.handleInput("\u001b[201~", {} as any);
// Should not be collapsed
expect(buffer.text).toBe(shortContent);
});
it("should normalize line endings when expanding", () => {
const textWithCarriageReturns =
"line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE);
buffer.handleInput(textWithCarriageReturns, {
ctrl: false,
meta: false,
} as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1, 4 lines]");
buffer.expandAllPasteBlocks();
// Should have normalized line endings
const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
expect(buffer.text).toBe(expected);
});
it("should increment paste counter for multiple pastes", () => {
const longText1 = "a".repeat(COLLAPSE_SIZE + 1);
const longText2 = "b".repeat(COLLAPSE_SIZE + 1);
buffer.handleInput(longText1, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
buffer.insertText(" ");
buffer.handleInput(longText2, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1] [Paste #2]");
});
it("should detect rapid input above threshold", () => {
// Test that input above RAPID_INPUT_THRESHOLD triggers rapid input detection
const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1);
buffer.handleInput(rapidText, { ctrl: false, meta: false } as any);
// Should go into rapid input buffer (not displayed yet)
expect(buffer.text).toBe("");
expect(buffer.isInRapidInputMode()).toBe(true);
// Flush to finalize
buffer.flushPendingInput();
// Now should be displayed (but not collapsed since < COLLAPSE_SIZE)
expect(buffer.text).toBe(rapidText);
});
it("should combine split paste chunks", () => {
// Simulate macOS Terminal splitting paste
const firstChunk = "a".repeat(COLLAPSE_SIZE + 200); // Large first chunk
buffer.handleInput(firstChunk, { ctrl: false, meta: false } as any);
// First chunk goes into rapid input mode - no placeholder yet
expect(buffer.text).toBe("");
// Second chunk should be combined with the first (needs to be > 50 chars)
const secondChunk = "b".repeat(100); // Large enough to trigger split paste detection
buffer.handleInput(secondChunk, { ctrl: false, meta: false } as any);
// Flush to finalize the rapid input synchronously
buffer.flushPendingInput();
// Should show only one placeholder with combined content
expect(buffer.text).toBe("[Paste #1]");
// Verify the combined content is stored correctly
buffer.expandAllPasteBlocks();
const expectedContent = firstChunk + secondChunk;
expect(buffer.text).toBe(expectedContent);
expect(buffer.text).toBe(chunks.join(""));
expect(buffer.text.length).toBe(3000);
});
it("should expand paste blocks on submission (simulating Enter key behavior)", () => {
// Add some text before the paste
buffer.insertText("Command: ");
it("should handle complete paste-to-submit workflow", () => {
const pastedCode = 'console.log("test");' + "x".repeat(800);
// Add a large paste that gets collapsed
const pastedCode =
'function example() {\n console.log("hello");\n ' +
"x".repeat(COLLAPSE_SIZE);
buffer.handleInput(pastedCode, { ctrl: false, meta: false } as any);
buffer.flushPendingInput();
expect(buffer.text).toBe("[Paste #1]");
// Verify it's collapsed
expect(buffer.text).toBe("Command: [Paste #1, 3 lines]");
// Simulate what happens when user presses Enter - UserInput calls expandAllPasteBlocks()
// Simulate Enter key - expand before submission
buffer.expandAllPasteBlocks();
expect(buffer.text).toBe(pastedCode);
// Should now show the full content with normalized line endings
const expectedFullText =
'Command: function example() {\n console.log("hello");\n ' +
"x".repeat(COLLAPSE_SIZE);
expect(buffer.text).toBe(expectedFullText);
// Verify paste map is cleared after expansion
buffer.expandAllPasteBlocks(); // Should be no-op now
expect(buffer.text).toBe(expectedFullText); // Should remain the same
buffer.clear();
expect(buffer.text).toBe("");
});
});

View file

@ -305,7 +305,13 @@ export class TextBuffer {
const timeSinceLastInput = now - this._lastInputTime;
// If we're already in rapid input mode and this comes quickly, add to buffer
if (this._rapidInputBuffer.length > 0 && timeSinceLastInput < 100) {
// But only if it's a reasonably large chunk - small inputs are likely typing, not paste
// This prevents typed characters from being mixed into paste content during accumulation
if (
this._rapidInputBuffer.length > 0 &&
timeSinceLastInput < 200 &&
input.length >= 50
) {
this._rapidInputBuffer += input;
this._lastInputTime = now;
@ -323,8 +329,11 @@ export class TextBuffer {
// Fallback paste detection: some terminals send large pastes as rapid chunks
// instead of using bracketed paste mode. We detect this by timing between inputs.
// Only trigger for actually large chunks to avoid interfering with normal typing
if (input.length > RAPID_INPUT_THRESHOLD) {
// The >= 50 char threshold was restored to detect Terminal.app/Ghostty split pastes
if (
input.length > RAPID_INPUT_THRESHOLD ||
(input.length >= 50 && this._rapidInputBuffer.length === 0)
) {
this._rapidInputStartPos = this._cursor;
// Accumulate chunks without inserting to avoid visual flicker
@ -511,8 +520,7 @@ export class TextBuffer {
}
// Fallback: detect chunked paste operations
// Don't trigger rapid input detection for small inputs (e.g. single characters like "/" or "@")
if (input.length > 50 && this.handleRapidInput(input)) {
if (this.handleRapidInput(input)) {
return true;
}

View file

@ -167,8 +167,8 @@ const UserInput: React.FC<UserInputProps> = ({
>([]);
const { exit } = useApp();
// Get file index service
const { services } = useServices<{
// Get file index service state for reactive updates (unused but needed for service initialization)
useServices<{
fileIndex: FileIndexServiceState;
}>(["fileIndex"]);
@ -297,45 +297,39 @@ const UserInput: React.FC<UserInputProps> = ({
// Check if we're in a file search context
const beforeCursor = text.slice(0, cursor);
const lastAtIndex = beforeCursor.lastIndexOf("@");
if (lastAtIndex === -1) {
setShowFileSearch(false);
} else {
// Check if there's any whitespace between the last @ and cursor
const afterAt = beforeCursor.slice(lastAtIndex + 1);
if (afterAt.includes(" ") || afterAt.includes("\n")) {
setShowFileSearch(false);
} else {
// We're in a file search context - check if there are matching files
const fileIndexService = services.fileIndex;
if (fileIndexService) {
const filteredFiles = fileIndexService.files.filter((file) => {
if (afterAt.length === 0) {
return true;
}
const lowerFilter = afterAt.toLowerCase();
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
});
// If no files match, hide the dropdown to allow normal Enter behavior
if (filteredFiles.length === 0 && afterAt.length > 0) {
setShowFileSearch(false);
return;
// Find the first @ symbol that starts a file search context
// We need to find the last @ that has no space before it (or is at word boundary)
let firstAtIndex = -1;
for (let i = beforeCursor.length - 1; i >= 0; i--) {
if (beforeCursor[i] === "@") {
// Check if this @ is at the start of a word (preceded by space/newline or start of string)
const beforeAt = beforeCursor.slice(0, i);
const lastChar = beforeAt[beforeAt.length - 1];
if (i === 0 || lastChar === " " || lastChar === "\n") {
// Check if there's any space/newline between this @ and cursor
const afterThis = beforeCursor.slice(i + 1);
if (!afterThis.includes(" ") && !afterThis.includes("\n")) {
firstAtIndex = i;
break;
}
}
setShowFileSearch(true);
setFileSearchFilter(afterAt);
setSelectedFileIndex(0);
setShowSlashCommands(false);
setShowBashMode(false);
}
}
if (firstAtIndex === -1) {
setShowFileSearch(false);
} else {
// Get ALL text after the @ symbol (including subsequent @ symbols)
const afterAt = beforeCursor.slice(firstAtIndex + 1);
// We're in a file search context
setShowFileSearch(true);
setFileSearchFilter(afterAt);
setSelectedFileIndex(0);
setShowSlashCommands(false);
setShowBashMode(false);
}
};
// Get filtered commands for navigation - using the same sorting logic as SlashCommandUI
@ -385,15 +379,32 @@ const UserInput: React.FC<UserInputProps> = ({
// Handle file selection
const selectFile = async (filePath: string) => {
const beforeCursor = inputText.slice(0, cursorPosition);
const lastAtIndex = beforeCursor.lastIndexOf("@");
if (lastAtIndex !== -1) {
const beforeAt = inputText.slice(0, lastAtIndex);
// Find the first @ symbol that starts a file search context (same logic as updateFileSearchState)
let firstAtIndex = -1;
for (let i = beforeCursor.length - 1; i >= 0; i--) {
if (beforeCursor[i] === "@") {
// Check if this @ is at the start of a word (preceded by space/newline or start of string)
const beforeAt = beforeCursor.slice(0, i);
const lastChar = beforeAt[beforeAt.length - 1];
if (i === 0 || lastChar === " " || lastChar === "\n") {
// Check if there's any space/newline between this @ and cursor
const afterThis = beforeCursor.slice(i + 1);
if (!afterThis.includes(" ") && !afterThis.includes("\n")) {
firstAtIndex = i;
break;
}
}
}
}
if (firstAtIndex !== -1) {
const beforeAt = inputText.slice(0, firstAtIndex);
const afterCursor = inputText.slice(cursorPosition);
// Replace the partial file reference with the full file path
const newText = beforeAt + "@" + filePath + " " + afterCursor;
const newCursorPos = lastAtIndex + 1 + filePath.length + 1;
const newCursorPos = firstAtIndex + 1 + filePath.length + 1;
textBuffer.setText(newText);
textBuffer.setCursor(newCursorPos);
@ -410,7 +421,14 @@ const UserInput: React.FC<UserInputProps> = ({
const content = await fs.readFile(absolutePath, "utf-8");
onFileAttached(absolutePath, content);
} catch (error) {
console.error(`Error reading file ${filePath}:`, error);
// If file doesn't exist, just attach the filename without content
if (error instanceof Error && (error as any).code === "ENOENT") {
const path = await import("path");
const absolutePath = path.resolve(filePath);
onFileAttached(absolutePath, filePath);
} else {
console.error(`Error reading file ${filePath}:`, error);
}
}
}
}

View file

@ -0,0 +1,36 @@
import * as path from "path";
import { describe, expect, it, vi } from "vitest";
// Test the missing file handling logic directly
describe("UserInput - Missing File Handling", () => {
it("should handle selecting non-existent files gracefully", async () => {
const mockOnFileAttached = vi.fn();
// Simulate the selectFile logic for a missing file
const filePath = "missing-file.txt";
try {
const fs = await import("fs/promises");
const path = await import("path");
const absolutePath = path.resolve(filePath);
const content = await fs.readFile(absolutePath, "utf-8");
mockOnFileAttached(absolutePath, content);
} catch (error) {
// If file doesn't exist, just attach the filename without content
if (error instanceof Error && (error as any).code === "ENOENT") {
const path = await import("path");
const absolutePath = path.resolve(filePath);
mockOnFileAttached(absolutePath, filePath); // Just the filename for missing file
} else {
console.error(`Error reading file ${filePath}:`, error);
}
}
// Should have called onFileAttached with filename as content
expect(mockOnFileAttached).toHaveBeenCalledWith(
path.resolve(filePath),
filePath,
);
});
});

View file

@ -44,10 +44,11 @@ function formatMessageContentForDisplay(
interface MemoizedMessageProps {
item: ChatHistoryItem;
index: number;
hideBullet?: boolean;
}
export const MemoizedMessage = memo<MemoizedMessageProps>(
({ item, index }) => {
({ item, index, hideBullet = false }) => {
const { message, toolCallStates, conversationSummary } = item;
const isUser = message.role === "user";
const isSystem = message.role === "system";
@ -93,7 +94,7 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
{/* Render assistant message content if any */}
{message.content && (
<Box marginBottom={1}>
<Text color="white">●</Text>
<Text color="white">{hideBullet ? " " : "●"}</Text>
<Text> </Text>
<MarkdownRenderer
content={formatMessageContentForDisplay(message.content)}
@ -166,7 +167,7 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
return (
<Box key={index} marginBottom={1}>
<Text color={isUser ? "blue" : "white"}>●</Text>
<Text color={isUser ? "blue" : "white"}>{hideBullet ? " " : "●"}</Text>
<Text> </Text>
{isUser ? (
<Text color="gray">
@ -195,7 +196,8 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
JSON.stringify(prevToolStates) === JSON.stringify(nextToolStates) &&
prevProps.item.conversationSummary ===
nextProps.item.conversationSummary &&
prevProps.index === nextProps.index
prevProps.index === nextProps.index &&
prevProps.hideBullet === nextProps.hideBullet
);
},
);

View file

@ -7,6 +7,7 @@ import type { MCPService } from "../../services/MCPService.js";
import type { QueuedMessage } from "../../stream/messageQueue.js";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { IntroMessage } from "../IntroMessage.js";
import { splitChatHistory } from "../utils/historySplitting.js";
interface StaticChatContentProps {
showIntroMessage: boolean;
@ -15,8 +16,12 @@ interface StaticChatContentProps {
mcpService?: MCPService;
chatHistory: ChatHistoryItem[];
queuedMessages?: QueuedMessage[];
renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
refreshTrigger?: number; // Add a prop to trigger refresh from parent
renderMessage: (
item: ChatHistoryItem,
index: number,
allMessages?: ChatHistoryItem[],
) => React.ReactElement;
refreshTrigger?: number;
}
export const StaticChatContent: React.FC<StaticChatContentProps> = ({
@ -32,7 +37,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
const { columns, rows } = useTerminalSize();
const { stdout } = useStdout();
// State for managing static refresh with key-based remounting (gemini-cli approach)
// State for managing static refresh with key-based remounting
const [staticKey, setStaticKey] = useState(0);
const isInitialMount = useRef(true);
@ -69,15 +74,18 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
}
}, [refreshTrigger, refreshStatic]);
// Filter out system messages without content
const filteredChatHistory = React.useMemo(() => {
return chatHistory.filter(
// Filter out system messages without content and split large messages
const processedChatHistory = React.useMemo(() => {
const filtered = chatHistory.filter(
(item) => item.message.role !== "system" || item.message.content,
);
}, [chatHistory]);
// Split large messages into multiple history items
return splitChatHistory(filtered, columns);
}, [chatHistory, columns]);
// Split chat history into stable and pending items
// The last two items may have pending tool calls
// Keep more items static now that we've split large messages
const { staticItems, pendingItems } = React.useMemo(() => {
// Add intro message as first item if it should be shown
const staticItems: React.ReactElement[] = [];
@ -92,22 +100,24 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
);
}
// Since messages are now split into reasonably-sized chunks,
// we can keep more items static (only last 1-2 items dynamic)
const PENDING_ITEMS_COUNT = 1;
const stableCount = Math.max(
0,
filteredChatHistory.length - PENDING_ITEMS_COUNT,
processedChatHistory.length - PENDING_ITEMS_COUNT,
);
const stableHistory = filteredChatHistory.slice(0, stableCount);
const pendingHistory = filteredChatHistory.slice(stableCount);
const stableHistory = processedChatHistory.slice(0, stableCount);
const pendingHistory = processedChatHistory.slice(stableCount);
// Add stable messages to static items
stableHistory.forEach((item, index) => {
staticItems.push(renderMessage(item, index));
staticItems.push(renderMessage(item, index, processedChatHistory));
});
// Pending items will be rendered dynamically outside Static
const pendingItems = pendingHistory.map((item, index) =>
renderMessage(item, stableCount + index),
renderMessage(item, stableCount + index, processedChatHistory),
);
return {
@ -119,7 +129,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
config,
model,
mcpService,
filteredChatHistory,
processedChatHistory,
renderMessage,
]);

View file

@ -4,22 +4,38 @@ import type { ChatHistoryItem } from "../../../../../core/index.js";
import { MemoizedMessage } from "../components/MemoizedMessage.js";
export function useMessageRenderer() {
const renderMessage = useCallback((item: ChatHistoryItem, index: number) => {
// Generate a unique key by combining message role, content hash, and timestamp
// This provides a stable identifier that won't change during re-renders
const messageContent =
typeof item.message.content === "string"
? item.message.content
: JSON.stringify(item.message.content);
const renderMessage = useCallback(
(item: ChatHistoryItem, index: number, allMessages?: ChatHistoryItem[]) => {
// Generate a unique key by combining message role, content hash, and timestamp
// This provides a stable identifier that won't change during re-renders
const messageContent =
typeof item.message.content === "string"
? item.message.content
: JSON.stringify(item.message.content);
const toolCallsKey = item.toolCallStates
? item.toolCallStates.map((tc) => tc.toolCallId).join("-")
: "";
const toolCallsKey = item.toolCallStates
? item.toolCallStates.map((tc) => tc.toolCallId).join("-")
: "";
const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`;
// Check if this is a continuation of the previous message (same role)
const previousMessage =
allMessages && index > 0 ? allMessages[index - 1] : null;
const isContinuation =
previousMessage?.message.role === item.message.role;
return <MemoizedMessage key={uniqueKey} item={item} index={index} />;
}, []);
const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`;
return (
<MemoizedMessage
key={uniqueKey}
item={item}
index={index}
hideBullet={isContinuation}
/>
);
},
[],
);
return { renderMessage };
}

View file

@ -0,0 +1,58 @@
import type { ChatHistoryItem } from "core";
import { describe, expect, it } from "vitest";
import { splitChatHistory } from "./historySplitting.js";
// Helper to create a mock chat history item
function createMockChatHistoryItem(
content: string,
role: "user" | "assistant" = "assistant",
): ChatHistoryItem {
return {
message: {
role,
content,
},
} as ChatHistoryItem;
}
describe("messageHistorySplitting", () => {
describe("splitChatHistory", () => {
it("should split multiple large messages in chat history", () => {
const chatHistory = [
createMockChatHistoryItem("Short message 1"),
createMockChatHistoryItem(
Array(30).fill("Long message 1").join("\n\n"),
),
createMockChatHistoryItem("Short message 2"),
createMockChatHistoryItem(
Array(25).fill("Long message 2").join("\n\n"),
),
];
const result = splitChatHistory(chatHistory, 80);
// Should have more items than the original (due to splits)
expect(result.length).toBeGreaterThan(chatHistory.length);
// First and third messages should remain unchanged
expect(result[0].message.content).toBe("Short message 1");
});
it("should maintain order after splitting", () => {
const chatHistory = [
createMockChatHistoryItem("First"),
createMockChatHistoryItem(Array(30).fill("Long middle").join("\n\n")),
createMockChatHistoryItem("Last"),
];
const result = splitChatHistory(chatHistory, 80);
// First message should still be first
expect(result[0].message.content).toBe("First");
// Last message should still be last
expect(result[result.length - 1].message.content).toBe("Last");
});
});
});

View file

@ -0,0 +1,170 @@
import type { ChatHistoryItem } from "core";
import { findLastSafeSplitPoint } from "./messageSplitting.js";
const MAX_HEIGHT_BEFORE_SPLIT = 20;
/**
* Splits a chat history item into multiple items if its content is too large.
*
* This function prevents UI flickering by breaking large messages into manageable chunks.
* It only splits at safe markdown boundaries (paragraph breaks: \n\n) to preserve formatting.
*
* Splitting behavior:
* - User messages: Split only when they have natural paragraph breaks (\n\n)
* - Assistant messages: Split when content exceeds height threshold
* - System messages: Never split
* - Messages with tool calls: Never split
*
* Common use cases:
* - User pastes multiple paragraphs of text -> Split at paragraph boundaries
* - User writes one long paragraph -> Keep as single message
* - Assistant generates long response -> Split at paragraph breaks (\n\n)
*/
function splitChatHistoryItem(
item: ChatHistoryItem,
terminalWidth: number,
): ChatHistoryItem[] {
// Don't split non-text messages or messages with tool calls
if (item.toolCallStates?.length || typeof item.message.content !== "string") {
return [item];
}
// Don't split system messages
if (item.message.role === "system") {
return [item];
}
const content = item.message.content;
if (!shouldSplitContent(content, terminalWidth)) {
return [item];
}
return splitContentIntoHistoryItems(item, content, terminalWidth);
}
/**
* Splits content into multiple chat history items at safe markdown boundaries.
*/
function splitContentIntoHistoryItems(
originalItem: ChatHistoryItem,
content: string,
terminalWidth: number,
): ChatHistoryItem[] {
const items: ChatHistoryItem[] = [];
let remainingContent = content;
let itemIndex = 0;
while (remainingContent.length > 0) {
if (!shouldSplitContent(remainingContent, terminalWidth)) {
// Remaining content is small enough, add it as the final item
if (remainingContent.trim()) {
items.push({
...originalItem,
message: {
...originalItem.message,
content: remainingContent,
},
});
}
break;
}
// Find safe split point
const splitPoint = findLastSafeSplitPoint(remainingContent);
if (splitPoint === remainingContent.length) {
// No safe split point found, add as single large item
if (remainingContent.trim()) {
items.push({
...originalItem,
message: {
...originalItem.message,
content: remainingContent,
},
});
}
break;
}
// Split at the safe point
const beforeText = remainingContent.slice(0, splitPoint).trim();
remainingContent = remainingContent.slice(splitPoint).trim();
if (beforeText) {
items.push({
...originalItem,
message: {
...originalItem.message,
content: beforeText,
},
});
}
itemIndex++;
// Prevent infinite loops
if (itemIndex > 50) {
console.warn("Message splitting exceeded maximum iterations, stopping");
if (remainingContent.trim()) {
items.push({
...originalItem,
message: {
...originalItem.message,
content: remainingContent,
},
});
}
break;
}
}
return items;
}
/**
* Processes an entire chat history array, splitting large items into multiple items.
*/
export function splitChatHistory(
chatHistory: ChatHistoryItem[],
terminalWidth: number,
): ChatHistoryItem[] {
const result: ChatHistoryItem[] = [];
for (const item of chatHistory) {
const splitItems = splitChatHistoryItem(item, terminalWidth);
result.push(...splitItems);
}
return result;
}
/**
* Estimates the height in terminal rows that content will take when rendered.
*/
function estimateContentHeight(content: string, terminalWidth: number): number {
if (!content) return 0;
const lines = content.split("\n");
let totalHeight = 0;
for (const line of lines) {
if (line.length === 0) {
totalHeight += 1; // Empty line
} else {
// Account for line wrapping
totalHeight += Math.ceil(line.length / Math.max(terminalWidth - 2, 40));
}
}
return totalHeight;
}
/**
* Determines if content should be split based on its estimated height.
*/
function shouldSplitContent(content: string, terminalWidth: number): boolean {
const estimatedHeight = estimateContentHeight(content, terminalWidth);
return estimatedHeight > MAX_HEIGHT_BEFORE_SPLIT;
}

View file

@ -0,0 +1,54 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*
* NOTICE: This file has been modified from the original Gemini CLI source
* for integration with Continue CLI (cn)
*/
import { describe, expect, it } from "vitest";
import { findLastSafeSplitPoint } from "./messageSplitting.js";
describe("markdownUtilities", () => {
describe("findLastSafeSplitPoint", () => {
it("should split at the last double newline if not in a code block", () => {
const content = "paragraph1\n\nparagraph2\n\nparagraph3";
expect(findLastSafeSplitPoint(content)).toBe(24); // After the second \n\n
});
it("should return content.length if no safe split point is found", () => {
const content = "longstringwithoutanysafesplitpoint";
expect(findLastSafeSplitPoint(content)).toBe(content.length);
});
it("should prioritize splitting at \n\n over being at the very end of the string if the end is not in a code block", () => {
const content = "Some text here.\n\nAnd more text here.";
expect(findLastSafeSplitPoint(content)).toBe(17); // after the \n\n
});
it("should return content.length if the only \n\n is inside a code block and the end of content is not", () => {
const content = "```\nignore this\n\nnewline\n```KeepThis";
expect(findLastSafeSplitPoint(content)).toBe(content.length);
});
it("should correctly identify the last \n\n even if it is followed by text not in a code block", () => {
const content =
"First part.\n\nSecond part.\n\nThird part, then some more text.";
// Split should be after "Second part.\n\n"
// "First part.\n\n" is 13 chars. "Second part.\n\n" is 14 chars. Total 27.
expect(findLastSafeSplitPoint(content)).toBe(27);
});
it("should return content.length if content is empty", () => {
const content = "";
expect(findLastSafeSplitPoint(content)).toBe(0);
});
it("should return content.length if content has no newlines and no code blocks", () => {
const content = "Single line of text";
expect(findLastSafeSplitPoint(content)).toBe(content.length);
});
});
});

View file

@ -0,0 +1,128 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*
* NOTICE: This file has been modified from the original Gemini CLI source
* for integration with Continue CLI (cn)
*/
/*
**Background & Purpose:**
The `findSafeSplitPoint` function is designed to address the challenge of displaying or processing large, potentially streaming, pieces of Markdown text. When content (e.g., from an LLM like Gemini) arrives in chunks or grows too large for a single display unit (like a message bubble), it needs to be split. A naive split (e.g., just at a character limit) can break Markdown formatting, especially critical for multi-line elements like code blocks, lists, or blockquotes, leading to incorrect rendering.
This function aims to find an *intelligent* or "safe" index within the provided `content` string at which to make such a split, prioritizing the preservation of Markdown integrity.
**Key Expectations & Behavior (Prioritized):**
1. **No Split if Short Enough:**
* If `content.length` is less than or equal to `idealMaxLength`, the function should return `content.length` (indicating no split is necessary for length reasons).
2. **Code Block Integrity (Highest Priority for Safety):**
* The function must try to avoid splitting *inside* a fenced code block (i.e., between ` ``` ` and ` ``` `).
* If `idealMaxLength` falls within a code block:
* The function will attempt to return an index that splits the content *before* the start of that code block.
* If a code block starts at the very beginning of the `content` and `idealMaxLength` falls within it (meaning the block itself is too long for the first chunk), the function might return `0`. This effectively makes the first chunk empty, pushing the entire oversized code block to the second part of the split.
* When considering splits near code blocks, the function prefers to keep the entire code block intact in one of the resulting chunks.
3. **Markdown-Aware Newline Splitting (If Not Governed by Code Block Logic):**
* If `idealMaxLength` does not fall within a code block (or after code block considerations have been made), the function will look for natural break points by scanning backwards from `idealMaxLength`:
* **Paragraph Breaks:** It prioritizes splitting after a double newline (`\n\n`), as this typically signifies the end of a paragraph or a block-level element.
* **Single Line Breaks:** If no double newline is found in a suitable range, it will look for a single newline (`\n`).
* Any newline chosen as a split point must also not be inside a code block.
4. **Fall back to `idealMaxLength`:**
* If no "safer" split point (respecting code blocks or finding suitable newlines) is identified before or at `idealMaxLength`, and `idealMaxLength` itself is not determined to be an unsafe split point (e.g., inside a code block), the function may return a length larger than `idealMaxLength`, again it CANNOT break markdown formatting. This could happen with very long lines of text without Markdown block structures or newlines.
**In essence, `findSafeSplitPoint` tries to be a good Markdown citizen when forced to divide content, preferring structural boundaries over arbitrary character limits, with a strong emphasis on not corrupting code blocks.**
*/
/**
* Checks if a given character index within a string is inside a fenced (```) code block.
* @param content The full string content.
* @param indexToTest The character index to test.
* @returns True if the index is inside a code block's content, false otherwise.
*/
const isIndexInsideCodeBlock = (
content: string,
indexToTest: number,
): boolean => {
let fenceCount = 0;
let searchPos = 0;
while (searchPos < content.length) {
const nextFence = content.indexOf("```", searchPos);
if (nextFence === -1 || nextFence >= indexToTest) {
break;
}
fenceCount++;
searchPos = nextFence + 3;
}
return fenceCount % 2 === 1;
};
/**
* Finds the starting index of the code block that encloses the given index.
* Returns -1 if the index is not inside a code block.
* @param content The markdown content.
* @param index The index to check.
* @returns Start index of the enclosing code block or -1.
*/
const findEnclosingCodeBlockStart = (
content: string,
index: number,
): number => {
if (!isIndexInsideCodeBlock(content, index)) {
return -1;
}
let currentSearchPos = 0;
while (currentSearchPos < index) {
const blockStartIndex = content.indexOf("```", currentSearchPos);
if (blockStartIndex === -1 || blockStartIndex >= index) {
break;
}
const blockEndIndex = content.indexOf("```", blockStartIndex + 3);
if (blockStartIndex < index) {
if (blockEndIndex === -1 || index < blockEndIndex + 3) {
return blockStartIndex;
}
}
if (blockEndIndex === -1) break;
currentSearchPos = blockEndIndex + 3;
}
return -1;
};
export const findLastSafeSplitPoint = (content: string): number => {
const enclosingBlockStart = findEnclosingCodeBlockStart(
content,
content.length,
);
if (enclosingBlockStart !== -1) {
// The end of the content is contained in a code block. Split right before.
return enclosingBlockStart;
}
// Search for the last double newline (\n\n) not in a code block.
let searchStartIndex = content.length;
while (searchStartIndex >= 0) {
const dnlIndex = content.lastIndexOf("\n\n", searchStartIndex);
if (dnlIndex === -1) {
// No more double newlines found.
break;
}
const potentialSplitPoint = dnlIndex + 2;
if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) {
return potentialSplitPoint;
}
// If potentialSplitPoint was inside a code block,
// the next search should start *before* the \n\n we just found to ensure progress.
searchStartIndex = dnlIndex - 1;
}
// If no safe double newline is found, return content.length
// to keep the entire content as one piece.
return content.length;
};

View file

@ -5,5 +5,5 @@ src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json
video
.intellijPlatform
src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/*
!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json
src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/*
!src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue/config.json

View file

@ -1,26 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Test IDE" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value=""/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="runIdeForUiTests"/>
</list>
</option>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2">
<option name="Gradle.BeforeRunTask" enabled="true" tasks="clean"
externalProjectPath="$PROJECT_DIR$/extensions/intellij" vmOptions="" scriptParameters=""/>
</method>
</configuration>
</component>

View file

@ -1,7 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run e2e tests" type="CompoundRunConfigurationType">
<toRun name="Run Test IDE" type="GradleRunConfiguration" />
<toRun name="Run Tests" type="GradleRunConfiguration" />
<method v="2" />
</configuration>
</component>

View file

@ -179,55 +179,29 @@ This will generate a .zip file in `./build/distributions` with the version defin
## Testing
### e2e testing
Test commands:
#### Overview
- `./gradlew test` - to run **unit tests**
- `./gradlew testIntegration` - to run **e2e tests**
The e2e tests are written using [intellij-ui-test-robot](`https://github.com/JetBrains/intellij-ui-test-robot`). The
README for this project has a lot of helpful info on how to use the library.
### About e2e tests
Note that these tests fully take control of your mouse while executing.
The e2e tests are written using [intellij-ide-starter](https://github.com/JetBrains/intellij-ide-starter).
The first run of the e2e tests may take a while because the required IDE needs
to be downloaded. Note that these tests
fully take control of your mouse while executing.
#### Setup
If you are on macOS, you'll need to give IntelliJ permission to control your computer in order to run the e2e tests.
Open _System Settings_ and select `Privacy & Security` -> `Accessibility` and toggle the switch for IntelliJ.
Open `System Settings > Privacy & Security > Accessibility` and toggle the switch for IntelliJ.
#### Running the tests
#### Working with Intellij IDE Starter
Instantiate the test IDE as a background task:
The testing platform provides a rich DSL for most UI components in IntelliJ. However, if you want to interact with a
custom element, you can define your own XPath selector.
```sh
./gradlew clean runIdeForUiTests &
```
Once the IDE has loaded, you can run the tests. Note that you need to have the test IDE focused in order for the tests
to run.
```sh
./gradlew test
```
Run a single test
```sh
./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME"
```
#### Identifying selectors
While the `runIdeForUiTests` task is running, you can visit the following URL
to view the UI hierarchy of the running IDE:
<http://127.0.0.1:8082/>
#### Rebuilding the extension
To rebuild the extension with the latest source code, run the following:
```sh
./gradlew buildPlugin
```
This will update the contents of the extension that is loaded into the test IDE from
`build/idea-sandbox/plugins-uiTest/continue-intellij-extension`
To do this, run an e2e test and visit [localhost:63343/api/remote-driver/](http://localhost:63343/api/remote-driver/) to
view an HTML representation of the IDE's Swing component tree.
See [Integration Tests](https://plugins.jetbrains.com/docs/intellij/integration-tests-ui.html#searching-components) for
more details about this workflow.

View file

@ -1,17 +1,17 @@
import org.jetbrains.changelog.markdownToHTML
import org.jetbrains.intellij.platform.gradle.TestFrameworkType
import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask
import org.gradle.kotlin.dsl.intellijPlatform
fun environment(key: String) = providers.environmentVariable(key)
val remoteRobotVersion = "0.11.23"
val platformVersion: String by project
val pluginGroup: String by project
val pluginVersion: String by project
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
plugins {
kotlin("jvm") version "1.9.22"
kotlin("jvm") version "2.1.0"
id("org.jetbrains.intellij.platform") version "2.7.2"
id("org.jetbrains.changelog") version "2.1.2"
id("org.jetbrains.qodana") version "0.1.13"
@ -28,17 +28,28 @@ repositories {
}
}
sourceSets {
val testIntegration = create("testIntegration")
testIntegration.apply {
compileClasspath += sourceSets.main.get().output
runtimeClasspath += sourceSets.main.get().output
}
}
val testIntegrationImplementation: Configuration by configurations.getting {
extendsFrom(configurations.testImplementation.get())
}
dependencies {
intellijPlatform {
create("IC", platformVersion)
intellijIdeaCommunity(platformVersion)
plugins(listOf("org.jetbrains.plugins.terminal:241.14494.150"))
testFramework(TestFrameworkType.Platform)
testFramework(TestFrameworkType.Starter, "243.21565.193", configurationName = "testIntegrationImplementation")
}
implementation("com.posthog.java:posthog:1.2.0")
testImplementation("junit:junit:4.13.2")
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
testImplementation("io.mockk:mockk:1.14.2") {
// this transitive dependency (1.6.4) conflicts with built-in version (1.7.3)
// otherwise e2e tests (runIdeForUiTests) will have linkage errors
@ -47,6 +58,10 @@ dependencies {
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3
testIntegrationImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
testIntegrationImplementation("org.kodein.di:kodein-di-jvm:7.20.2")
testIntegrationImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.10.1")
}
kotlin {
@ -88,40 +103,6 @@ qodana {
showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false)
}
intellijPlatformTesting {
runIde {
// This task might not work locally because the binary tends to ignore CONTINUE_GLOBAL_DIR when a
// local Continue config is present. If you want to run the e2e tests locally, the most effective
// way is to temporarily disconnect from the network and run the tests again.
// todo: fix it properly
register("runIdeForUiTests") {
task {
environment(
"CONTINUE_GLOBAL_DIR",
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
)
jvmArgumentProviders += CommandLineArgumentProvider {
listOf(
"-Drobot-server.port=8082",
"-Dide.mac.message.dialogs.as.sheets=false",
"-Djb.privacy.policy.text=<!--999.999-->",
"-Djb.consents.confirmation.enabled=false",
"-Dide.mac.file.chooser.native=false",
"-DjbScreenMenuBar.enabled=false",
"-Dapple.laf.useScreenMenuBar=false",
"-Didea.trust.all.projects=true",
"-Dide.show.tips.on.startup.default.value=false",
"-Dide.browser.jcef.sandbox.enable=false"
)
}
}
plugins {
robotServerPlugin()
}
}
}
}
tasks {
withType<PrepareSandboxTask> {
from("../../binary/bin") {
@ -146,6 +127,17 @@ tasks {
test {
useJUnitPlatform()
environment("CONTINUE_GLOBAL_DIR", "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/test-continue")
jvmArgumentProviders += CommandLineArgumentProvider { listOf("-Dide.browser.jcef.sandbox.enable=false") }
}
}
val testIntegration = task<Test>("testIntegration") {
val integrationTestSourceSet = sourceSets.getByName("testIntegration")
testClassesDirs = integrationTestSourceSet.output.classesDirs
classpath = integrationTestSourceSet.runtimeClasspath
systemProperty("CONTINUE_PLUGIN_DIR", tasks.prepareSandbox.get().pluginDirectory.get().asFile)
environment("CONTINUE_GLOBAL_DIR", "${rootProject.projectDir}/src/testIntegration/kotlin/com/github/continuedev/continueintellijextension/test-continue")
useJUnitPlatform()
dependsOn(tasks.prepareSandbox)
}

View file

@ -61,26 +61,13 @@ class RejectDiffAction : AnAction() {
class FocusContinueInputWithoutClearAction : ContinueToolbarAction() {
override fun toolbarActionPerformed(project: Project) {
project.getBrowser()?.sendToWebview("focusContinueInputWithoutClear")
project.getBrowser()?.focusOnInput()
FocusActionUtil.sendHighlightedCodeWithMessageToWebview(project, "focusContinueInputWithoutClear")
}
}
class FocusContinueInputAction : ContinueToolbarAction() {
override fun toolbarActionPerformed(project: Project) =
focusContinueInput(project)
companion object {
fun focusContinueInput(project: Project?) {
val browser = project?.getBrowser()
?: return
browser.sendToWebview("focusContinueInputWithNewSession")
browser.focusOnInput()
val rif = EditorUtils.getEditor(project)?.getHighlightedRIF()
?: return
val code = HighlightedCodePayload(RangeInFileWithContents(rif.filepath, rif.range, rif.contents))
browser.sendToWebview("highlightedCode", code)
}
override fun toolbarActionPerformed(project: Project) {
FocusActionUtil.sendHighlightedCodeWithMessageToWebview(project, "focusContinueInputWithNewSession")
}
}
@ -115,5 +102,16 @@ class OpenLogsAction : AnAction() {
}
}
object FocusActionUtil {
fun sendHighlightedCodeWithMessageToWebview(project: Project?, messageType: String) {
val browser = project?.getBrowser()
?: return
browser.sendToWebview(messageType)
browser.focusOnInput()
val rif = EditorUtils.getEditor(project)?.getHighlightedRIF()
?: return
val code = HighlightedCodePayload(RangeInFileWithContents(rif.filepath, rif.range, rif.contents))
browser.sendToWebview("highlightedCode", code)
}
}

View file

@ -91,7 +91,8 @@ class ApplyToFileHandler(
highlighted = currentContent, // Current file content
suffix = "", // No suffix since we're rewriting the whole file
modelTitle = null, // No model needed for search/replace instant apply
includeRulesInSystemMessage = false // No LLM involved, just diff generation
includeRulesInSystemMessage = false, // No LLM involved, just diff generation
isApply = true
)
}
@ -145,7 +146,7 @@ class ApplyToFileHandler(
// Stream the diffs
diffStreamHandler.streamDiffLinesToEditor(
prompt, prefix, highlighted, suffix, llmTitle, false
prompt, prefix, highlighted, suffix, llmTitle, false, true
)
}

View file

@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.FileStats
import com.github.continuedev.continueintellijextension.FileType
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
@ -24,10 +25,11 @@ class FileUtils(
fun writeFile(fileUri: String, content: String) {
val path = VfsUtilCore.urlToPath(fileUri)
val pathDirectory = VfsUtil.getParentDir(path)
?: return
?: return LOG.warn("Parent directory is null for $path")
val vfsDirectory = VfsUtil.createDirectories(pathDirectory)
?: return LOG.warn("Could not create directories for $path")
val pathFilename = VfsUtil.extractFileName(path)
?: return
?: return LOG.warn("Could not get filename for $path")
runWriteAction {
val newFile = vfsDirectory.createChildData(this, pathFilename)
VfsUtil.saveText(newFile, content)
@ -107,4 +109,8 @@ class FileUtils(
}
return fileUri
}
private companion object {
private val LOG = Logger.getInstance(FileUtils::class.java)
}
}

View file

@ -97,7 +97,8 @@ class DiffStreamHandler(
highlighted: String,
suffix: String,
modelTitle: String?,
includeRulesInSystemMessage: Boolean
includeRulesInSystemMessage: Boolean,
isApply: Boolean
) {
isRunning = true
sendUpdate(ApplyStateStatus.STREAMING)
@ -112,7 +113,8 @@ class DiffStreamHandler(
language = virtualFile?.fileType?.name,
modelTitle = modelTitle,
includeRulesInSystemMessage = includeRulesInSystemMessage,
fileUri = virtualFile?.url
fileUri = virtualFile?.url,
isApply = isApply
),
null
) { response ->

View file

@ -205,7 +205,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, true
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true, false
)
}

View file

@ -1,4 +1,4 @@
import com.github.continuedev.continueintellijextension.actions.FocusContinueInputAction
import com.github.continuedev.continueintellijextension.actions.FocusActionUtil
import com.github.continuedev.continueintellijextension.editor.openInlineEdit
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsManager
@ -92,7 +92,7 @@ class ToolTipComponent(editor: Editor, x: Int, y: Int) :
editButton = StyledButton("Edit (${cmdCtrlChar}+I)")
addToChatButton.addActionListener { e: ActionEvent? ->
FocusContinueInputAction.focusContinueInput(editor.project)
FocusActionUtil.sendHighlightedCodeWithMessageToWebview(editor.project, "focusContinueInputWithNewSession")
editor.contentComponent.remove(this)
}
editButton.addActionListener { e: ActionEvent? ->

View file

@ -306,7 +306,8 @@ data class StreamDiffLinesPayload(
val language: String?,
val modelTitle: String?,
val includeRulesInSystemMessage: Boolean,
val fileUri: String?
val fileUri: String?,
val isApply: Boolean
)
data class AcceptOrRejectDiffPayload(

View file

@ -1,75 +0,0 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class Autocomplete {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) {
CommonSteps(remoteRobot).closeProject()
}
@Test
@Video
fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@visible_text='Main.java']")
).isNotEmpty()
}
idea {
with(textEditor()) {
val userMsg = "TEST_USER_MESSAGE_0"
editor.insertTextAtLine(0, 0, userMsg)
editor.clickOnOffset(userMsg.length)
keyboard {
enterText(" ")
}
waitFor(ofSeconds(20)) {
editor.hasText("TEST_LLM_RESPONSE_0")
}
}
}
}
}

View file

@ -1,96 +0,0 @@
/**
* Currently we can't test any actions in the GUI that involve clicks.
* See this open issue for details: https://github.com/JetBrains/intellij-ui-test-robot/issues/491
*/
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.*
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.github.continuedev.continueintellijextension.utils.getMetaKey
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.*
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class GUI {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
// If we don't wait for this, clicking on the GUI may fail because a popup displays
// while the `continue_tutorial.java` is loading.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}
idea {
step("Manually open the webview") {
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
waitFor(ofSeconds(10)) {
browser().isShowing
}
// Arbitrary timeout due to a bug where the webview will refresh
// and clear the editor state on first load
Thread.sleep(5000)
}
step("Verify we can highlight code and add to webview") {
val textToInsert = "Hello world!"
with(textEditor()) {
editor.insertTextAtLine(0, 0, textToInsert)
editor.selectText(textToInsert)
keyboard {
hotKey(getMetaKey(), VK_J)
}
}
waitFor(ofSeconds(10)) {
browser().findElementByContainsText(textToInsert).html.isNotEmpty()
}
}
}
}
}

View file

@ -1,96 +0,0 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.github.continuedev.continueintellijextension.utils.*
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.VK_I
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class InlineEdit {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
@Test
@Disabled("Failing in CI, seems like the timeout just needs to be increased")
@Video
fun submitInlineEdit(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}
idea {
with(textEditor()) {
val userMsg = "TEST_USER_MESSAGE_0"
editor.insertTextAtLine(0, 0, userMsg)
editor.selectText(userMsg)
keyboard {
hotKey(getMetaKey(), VK_I)
}
val textArea = find<ComponentFixture>(byXpath("//div[@class='CustomTextArea']"))
textArea.hasText("Enter instructions...")
val modelSelect = find<ComponentFixture>(byXpath("//div[@class='JComboBox']"))
modelSelect.hasText("TEST LLM")
keyboard {
enterText("Hello world!")
}
val enterBtn = find<ComponentFixture>(byXpath("//div[@class='CustomButton']"))
enterBtn.click()
val rejectText = "${getAltKeyLabel()}${getShiftKeyLabel()}N"
val acceptText = "${getAltKeyLabel()}${getShiftKeyLabel()}Y"
val acceptAllText = "Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)"
val rejectAllText = "Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)"
find<ComponentFixture>(byXpath("//div[@text='$rejectText']")).isShowing
find<ComponentFixture>(byXpath("//div[@text='$acceptText']")).isShowing
find<ComponentFixture>(byXpath("//div[@text='$acceptAllText']")).isShowing
find<ComponentFixture>(byXpath("//div[@text='$rejectAllText']")).isShowing
}
}
}
}

View file

@ -1,85 +0,0 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class Onboarding {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
idea {
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
// So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']")
).isNotEmpty()
}
// TODO: Need a good way to ensure this is the first test ran in the entire suite
// step("Verify Continue tutorial file is loaded") {
// find<ComponentFixture>(byXpath("//div[@visible_text='continue_tutorial.java']"))
// }
step("Manually open the webview") {
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
waitFor(ofSeconds(10)) {
browser().isShowing
}
}
step("Verify the onboarding card is present") {
waitFor(ofSeconds(30)) {
try {
browser().findElement("//*[@data-testid='onboarding-card']").html.isNotEmpty()
} catch (e: Exception) {
false
}
}
}
}
}
}

View file

@ -1,36 +0,0 @@
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/DialogFixture.kt
*/
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.data.RemoteComponent
import com.intellij.remoterobot.fixtures.CommonContainerFixture
import com.intellij.remoterobot.fixtures.ContainerFixture
import com.intellij.remoterobot.fixtures.FixtureName
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.stepsProcessing.step
import java.time.Duration
fun ContainerFixture.dialog(
title: String,
timeout: Duration = Duration.ofSeconds(30),
function: DialogFixture.() -> Unit = {}
): DialogFixture = step("Search for dialog with title $title") {
find<DialogFixture>(DialogFixture.byTitle(title), timeout).apply(function)
}
@FixtureName("Dialog")
class DialogFixture(
remoteRobot: RemoteRobot,
remoteComponent: RemoteComponent
) : CommonContainerFixture(remoteRobot, remoteComponent) {
companion object {
@JvmStatic
fun byTitle(title: String) = byXpath("title $title", "//div[@title='$title' and @class='MyDialog']")
}
val title: String
get() = callJs("component.getTitle();")
}

View file

@ -1,92 +0,0 @@
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/IdeaFrame.kt
*/
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.data.RemoteComponent
import com.intellij.remoterobot.fixtures.*
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.waitFor
import java.time.Duration
fun RemoteRobot.idea(function: IdeaFrame.() -> Unit) {
find<IdeaFrame>(timeout = Duration.ofSeconds(10)).apply(function)
}
@FixtureName("Idea frame")
@DefaultXpath("IdeFrameImpl type", "//div[@class='IdeFrameImpl']")
class IdeaFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) :
CommonContainerFixture(remoteRobot, remoteComponent) {
val projectViewTree
get() = find<ContainerFixture>(byXpath("ProjectViewTree", "//div[@class='ProjectViewTree']"))
val projectName
get() = step("Get project name") { return@step callJs<String>("component.getProject().getName()") }
val menuBar: JMenuBarFixture
get() = step("Menu...") {
return@step remoteRobot.find(JMenuBarFixture::class.java, JMenuBarFixture.byType())
}
@JvmOverloads
fun dumbAware(timeout: Duration = Duration.ofMinutes(5), function: () -> Unit) {
step("Wait for smart mode") {
waitFor(duration = timeout, interval = Duration.ofSeconds(5)) {
runCatching { isDumbMode().not() }.getOrDefault(false)
}
function()
step("..wait for smart mode again") {
waitFor(duration = timeout, interval = Duration.ofSeconds(5)) {
isDumbMode().not()
}
}
}
}
fun isDumbMode(): Boolean {
return callJs(
"""
const frameHelper = com.intellij.openapi.wm.impl.ProjectFrameHelper.getFrameHelper(component)
if (frameHelper) {
const project = frameHelper.getProject()
project ? com.intellij.openapi.project.DumbService.isDumb(project) : true
} else {
true
}
""", true
)
}
fun openFile(path: String) {
runJs(
"""
importPackage(com.intellij.openapi.fileEditor)
importPackage(com.intellij.openapi.vfs)
importPackage(com.intellij.openapi.wm.impl)
importClass(com.intellij.openapi.application.ApplicationManager)
const path = '$path'
const frameHelper = ProjectFrameHelper.getFrameHelper(component)
if (frameHelper) {
const project = frameHelper.getProject()
const projectPath = project.getBasePath()
const file = LocalFileSystem.getInstance().findFileByPath(projectPath + '/' + path)
const openFileFunction = new Runnable({
run: function() {
FileEditorManager.getInstance(project).openTextEditor(
new OpenFileDescriptor(
project,
file
), true
)
}
})
ApplicationManager.getApplication().invokeLater(openFileFunction)
}
""", true
)
}
}

View file

@ -1,27 +0,0 @@
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/WelcomeFrame.kt
*/
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.data.RemoteComponent
import com.intellij.remoterobot.fixtures.*
import com.intellij.remoterobot.search.locators.byXpath
import java.time.Duration
fun RemoteRobot.welcomeFrame(function: WelcomeFrame.() -> Unit) {
find(WelcomeFrame::class.java, Duration.ofSeconds(20)).apply(function)
}
@FixtureName("Welcome Frame")
@DefaultXpath("type", "//div[@class='FlatWelcomeFrame']")
class WelcomeFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) :
CommonContainerFixture(remoteRobot, remoteComponent) {
val createNewProjectLink
get() = actionLink(
byXpath(
"New Project",
"//div[(@class='MainButton' and @text='New Project') or (@accessiblename='New Project' and @class='JButton')]"
)
)
}

View file

@ -1,76 +0,0 @@
/**
* Notes:
* - `sendIntellijMessage` isn't working, but keeping this around as an example of how we might be able to implement
* - Below is an AI generated summary of what the problem might be based on troubleshooting attempts
* - For details, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/26714246086162--intellij-ui-test-robot-Error-when-attempting-to-click-on-DomElement-491
*
*
* The issue is with how the JCefBrowserFixture.executeJsInBrowser method handles JavaScript code execution.
* When trying to call window.postIntellijMessage, we're encountering these challenges:
*
* 1. **Double Injection Problem**: The postIntellijMessage function already uses JBCefJSQuery.inject internally.
* When we try to call it through executeJsInBrowser, we're essentially trying to pass it through another injection
* mechanism, creating nested injections that break.
*
* 2. **String Escaping Issues**: The way quotes are being escaped between the layers of execution is causing syntax
* errors in the final JavaScript that gets executed.
*
* 3. **Context Isolation**: The executeJsInBrowser method likely runs in a different execution context than where the
* function was defined, causing scope/reference issues.
*
* The key insight is that we cannot directly call a function that itself uses the JBCefJSQuery bridge through the test
* framework's executeJsInBrowser method. These bridge functions are designed to be called directly in the browser
* context, not through another layer of script injection.
*/
package com.github.continuedev.continueintellijextension.utils
import com.intellij.remoterobot.fixtures.JCefBrowserFixture
/**
* Utility functions for interacting with browser components in tests
*/
object BrowserUtils {
/**
* Sends a message to the webview using JCefBrowserFixture's executeJsInBrowser
*
* @param browser The JCefBrowserFixture to execute JavaScript in
* @param messageType The type of message to send
* @param messageData The data object to send as message payload
* @param messageId A unique ID for the message
*/
fun sendIntellijMessage(
browser: JCefBrowserFixture,
messageType: String,
messageData: Any,
messageId: String = "test-message-id"
) {
// Convert the messageData to a JSON string
val dataJson = when (messageData) {
is String -> "\"$messageData\""
else -> messageData.toString()
}
val jsCode = """
(function() {
window.postIntellijMessage(
"$messageType",
$dataJson,
"$messageId"
);
return true;
})();
""".trimIndent()
browser.executeJsInBrowser(jsCode)
}
}
// Extension function for JCefBrowserFixture for easier usage
fun JCefBrowserFixture.sendIntellijMessage(
messageType: String,
messageData: Any,
messageId: String = "test-message-id"
) {
BrowserUtils.sendIntellijMessage(this, messageType, messageData, messageId)
}

View file

@ -1,138 +0,0 @@
package com.github.continuedev.continueintellijextension.utils
/**
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/utils/RemoteRobotExtension.kt
*/
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ContainerFixture
import com.intellij.remoterobot.search.locators.byXpath
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import org.junit.jupiter.api.extension.AfterTestExecutionCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.lang.IllegalStateException
import java.lang.reflect.Method
import javax.imageio.ImageIO
class RemoteRobotExtension : AfterTestExecutionCallback, ParameterResolver {
private val url: String = System.getProperty("remote-robot-url") ?: "http://127.0.0.1:8082"
private val remoteRobot: RemoteRobot = if (System.getProperty("debug-retrofit")?.equals("enable") == true) {
val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder().apply {
this.addInterceptor(interceptor)
}.build()
RemoteRobot(url, client)
} else {
RemoteRobot(url)
}
private val client = OkHttpClient()
override fun supportsParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Boolean {
return parameterContext?.parameter?.type?.equals(RemoteRobot::class.java) ?: false
}
override fun resolveParameter(parameterContext: ParameterContext?, extensionContext: ExtensionContext?): Any {
return remoteRobot
}
override fun afterTestExecution(context: ExtensionContext?) {
val testMethod: Method = context?.requiredTestMethod ?: throw IllegalStateException("test method is null")
val testMethodName = testMethod.name
val testFailed: Boolean = context.executionException?.isPresent ?: false
if (testFailed) {
// saveScreenshot(testMethodName)
saveIdeaFrames(testMethodName)
saveHierarchy(testMethodName)
}
}
private fun saveScreenshot(testName: String) {
fetchScreenShot().save(testName)
}
private fun saveHierarchy(testName: String) {
val hierarchySnapshot =
saveFile(url, "build/reports", "hierarchy-$testName.html")
if (File("build/reports/styles.css").exists().not()) {
saveFile("$url/styles.css", "build/reports", "styles.css")
}
println("Hierarchy snapshot: ${hierarchySnapshot.absolutePath}")
}
private fun saveFile(url: String, folder: String, name: String): File {
val response = client.newCall(Request.Builder().url(url).build()).execute()
return File(folder).apply {
mkdirs()
}.resolve(name).apply {
writeText(response.body?.string() ?: "")
}
}
private fun BufferedImage.save(name: String) {
val bytes = ByteArrayOutputStream().use { b ->
ImageIO.write(this, "png", b)
b.toByteArray()
}
File("build/reports").apply { mkdirs() }.resolve("$name.png").writeBytes(bytes)
}
private fun saveIdeaFrames(testName: String) {
remoteRobot.findAll<ContainerFixture>(byXpath("//div[@class='IdeFrameImpl']")).forEachIndexed { n, frame ->
val pic = try {
frame.callJs<ByteArray>(
"""
importPackage(java.io)
importPackage(javax.imageio)
importPackage(java.awt.image)
const screenShot = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB);
component.paint(screenShot.getGraphics())
let pictureBytes;
const baos = new ByteArrayOutputStream();
try {
ImageIO.write(screenShot, "png", baos);
pictureBytes = baos.toByteArray();
} finally {
baos.close();
}
pictureBytes;
""", true
)
} catch (e: Throwable) {
e.printStackTrace()
throw e
}
pic.inputStream().use {
ImageIO.read(it)
}.save(testName + "_" + n)
}
}
private fun fetchScreenShot(): BufferedImage {
return remoteRobot.callJs<ByteArray>(
"""
importPackage(java.io)
importPackage(javax.imageio)
const screenShot = new java.awt.Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
let pictureBytes;
const baos = new ByteArrayOutputStream();
try {
ImageIO.write(screenShot, "png", baos);
pictureBytes = baos.toByteArray();
} finally {
baos.close();
}
pictureBytes;
"""
).inputStream().use {
ImageIO.read(it)
}
}
}

View file

@ -1,19 +0,0 @@
package com.github.continuedev.continueintellijextension.utils
/**
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/utils/StepsLogger.kt
*/
import com.intellij.remoterobot.stepsProcessing.StepLogger
import com.intellij.remoterobot.stepsProcessing.StepWorker
object StepsLogger {
private var initialized = false
@JvmStatic
fun init() {
if (initialized.not()) {
StepWorker.registerProcessor(StepLogger())
initialized = true
}
}
}

View file

@ -0,0 +1,48 @@
package com.github.continuedev.continueintellijextension
import com.automation.remarks.junit5.Video
import com.intellij.driver.sdk.ui.components.*
import com.intellij.driver.sdk.wait
import com.intellij.ide.starter.driver.engine.runIdeWithDriver
import com.intellij.ide.starter.ide.IdeProductProvider
import com.intellij.ide.starter.models.TestCase
import com.intellij.ide.starter.plugins.PluginConfigurator
import com.intellij.ide.starter.project.NoProject
import com.intellij.ide.starter.runner.Starter
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertTrue
import java.io.File
import kotlin.time.Duration.Companion.seconds
class Autocomplete {
@Video
@Test
fun testAutocomplete() {
val starter = Starter.newContext("testExample", TestCase(IdeProductProvider.IC, NoProject).withVersion("2024.3"))
PluginConfigurator(starter).installPluginFromFolder(File(System.getProperty("CONTINUE_PLUGIN_DIR")))
starter.runIdeWithDriver().useDriverAndCloseIde {
welcomeScreen {
createNewProjectButton.click()
button("Create").click()
}
ideFrame {
editorTabs {
clickTab("Main.java")
}
codeEditor {
keyboard {
enterText("TEST_USER_MESSAGE_0")
space()
}
wait(2.seconds)
keyboard {
tab()
}
assertTrue(text.contains("TEST_LLM_RESPONSE_0"))
}
}
}
}
}

View file

@ -41,10 +41,11 @@ const SVG_CONFIG = {
// filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4))
// drop-shadow(8px 8px 0px rgba(107, 166, 205, 0.3))
// drop-shadow(12px 12px 0px rgba(136, 194, 163, 0.2));`,
filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4))
drop-shadow(-2px 4px 0px rgba(107, 166, 205, 0.3))
drop-shadow(4px -2px 0px rgba(136, 194, 163, 0.2))
drop-shadow(-2px -2px 0px rgba(112, 114, 209, 0.2));`,
// filter: `drop-shadow(4px 4px 0px rgba(112, 114, 209, 0.4))
// drop-shadow(-2px 4px 0px rgba(107, 166, 205, 0.3))
// drop-shadow(4px -2px 0px rgba(136, 194, 163, 0.2))
// drop-shadow(-2px -2px 0px rgba(112, 114, 209, 0.2));`,
filter: "none",
radius: 3,
leftMargin: 40,
defaultText: "",
@ -413,6 +414,8 @@ export class NextEditWindowManager {
);
}
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
// Create and apply decoration with the text.
if (newEditRangeSlice !== "") {
try {
@ -423,6 +426,7 @@ export class NextEditWindowManager {
newEditRangeSlice,
this.editableRegionStartLine,
diffLines,
diffChars,
);
} catch (error) {
console.error("Failed to render window:", error);
@ -432,8 +436,6 @@ export class NextEditWindowManager {
}
}
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
this.renderDeletions(editor, diffChars);
// Reserve tab and esc to either accept or reject the displayed next edit contents.
@ -686,6 +688,7 @@ export class NextEditWindowManager {
text: string,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
diffChars: DiffChar[],
): Promise<
| { uri: vscode.Uri; dimensions: { width: number; height: number } }
| undefined
@ -710,6 +713,7 @@ export class NextEditWindowManager {
},
currLineOffsetFromTop,
newDiffLines,
diffChars,
);
return {
@ -733,12 +737,14 @@ export class NextEditWindowManager {
position: vscode.Position,
editableRegionStartLine: number,
newDiffLines: DiffLine[],
diffChars: DiffChar[],
): Promise<vscode.TextEditorDecorationType | undefined> {
const currLineOffsetFromTop = position.line - editableRegionStartLine;
const uriAndDimensions = await this.createCodeRender(
predictedCode,
currLineOffsetFromTop,
newDiffLines,
diffChars,
);
if (!uriAndDimensions) {
return undefined;
@ -857,6 +863,7 @@ export class NextEditWindowManager {
predictedCode: string,
editableRegionStartLine: number,
newDiffLines: DiffLine[],
diffChars: DiffChar[],
) {
// Capture document version to detect changes.
const docVersion = editor.document.version;
@ -868,6 +875,7 @@ export class NextEditWindowManager {
position,
editableRegionStartLine,
newDiffLines,
diffChars,
);
if (!decoration) {
console.error("Failed to create decoration for text:", predictedCode);
@ -944,7 +952,6 @@ export class NextEditWindowManager {
const deleteDecorationType = vscode.window.createTextEditorDecorationType({
backgroundColor: "rgba(255, 0, 0, 0.5)",
textDecoration: "line-through",
});
editor.setDecorations(deleteDecorationType, charsToDelete);

View file

@ -244,6 +244,7 @@ export class ApplyManager {
newCode: text,
toolCallId,
rulesToInclude: undefined, // No rules for apply
isApply: true,
});
} else {
// Non-streaming: accumulate LLM output, then apply via Myers diff
@ -295,17 +296,23 @@ export class ApplyManager {
const streamedLines: string[] = [];
// Use streamDiffLines to get the LLM output
const stream = streamDiffLines({
highlighted: rangeContent,
prefix,
suffix,
const stream = streamDiffLines(
{
highlighted: rangeContent,
prefix,
suffix,
input: prompt,
language: getMarkdownLanguageTagForFile(fileUri),
type: "apply",
newCode,
includeRulesInSystemMessage: false,
modelTitle: llm.title ?? llm.model,
},
llm,
rulesToInclude: undefined, // No rules for apply
input: prompt,
language: getMarkdownLanguageTagForFile(fileUri),
overridePrompt: undefined,
abortController,
});
undefined,
undefined,
);
// Accumulate all the streamed content
for await (const line of stream) {

View file

@ -0,0 +1,488 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as vscode from "vscode";
import { ContinueCompletionProvider } from "../completionProvider";
import * as NextEditLoggingServiceModule from "core/nextEdit/NextEditLoggingService";
import * as PrefetchQueueModule from "core/nextEdit/NextEditPrefetchQueue";
import * as NextEditProviderModule from "core/nextEdit/NextEditProvider";
import * as JumpManagerModule from "../../activation/JumpManager";
type MockNextEditProvider = ReturnType<typeof createMockNextEditProvider>;
type MockPrefetchQueue = ReturnType<typeof createMockPrefetchQueue>;
type MockJumpManager = ReturnType<typeof createMockJumpManager>;
const mockOutcome = {
completion: "suggested change",
diffLines: [],
editableRegionStartLine: 0,
editableRegionEndLine: 0,
} as any;
let mockNextEditProvider: MockNextEditProvider;
let mockPrefetchQueue: MockPrefetchQueue;
let mockJumpManager: MockJumpManager;
beforeEach(() => {
vi.clearAllMocks();
mockNextEditProvider = createMockNextEditProvider();
(NextEditProviderModule as any).__setMockNextEditProviderInstance(
mockNextEditProvider,
);
mockPrefetchQueue = createMockPrefetchQueue();
(PrefetchQueueModule as any).__setMockPrefetchQueueInstance(
mockPrefetchQueue,
);
mockJumpManager = createMockJumpManager();
(JumpManagerModule as any).__setMockJumpManagerInstance(mockJumpManager);
const mockLoggingService = createMockLoggingService();
(NextEditLoggingServiceModule as any).__setMockNextEditLoggingServiceInstance(
mockLoggingService,
);
(vscode.window as any).activeTextEditor = null;
});
describe("ContinueCompletionProvider triggering logic", () => {
it("starts a new chain when none exists", async () => {
const document = createDocument();
setActiveEditor(document);
const provider = buildProvider();
await provider.provideInlineCompletionItems(
document,
createPosition(),
createContext(),
createToken(),
);
expect(mockNextEditProvider.startChain).toHaveBeenCalledTimes(1);
expect(
mockNextEditProvider.provideInlineCompletionItems,
).toHaveBeenCalledTimes(1);
expect(mockNextEditProvider.deleteChain).not.toHaveBeenCalled();
});
it("clears an empty chain once in full file diff mode", async () => {
const document = createDocument();
setActiveEditor(document);
mockNextEditProvider.chainExists.mockReturnValue(true);
mockPrefetchQueue.__setProcessed([]);
mockPrefetchQueue.__setUnprocessed([]);
const provider = buildProvider();
await provider.provideInlineCompletionItems(
document,
createPosition(),
createContext(),
createToken(),
);
expect(mockNextEditProvider.deleteChain).toHaveBeenCalledTimes(1);
expect(mockNextEditProvider.startChain).toHaveBeenCalledTimes(1);
expect(
mockNextEditProvider.provideInlineCompletionItems,
).toHaveBeenCalledTimes(1);
});
it("returns null after clearing empty chain when no outcome is available", async () => {
const document = createDocument();
setActiveEditor(document);
mockNextEditProvider.chainExists.mockReturnValue(true);
mockPrefetchQueue.__setProcessed([]);
mockPrefetchQueue.__setUnprocessed([]);
mockNextEditProvider.provideInlineCompletionItems.mockResolvedValueOnce(
undefined,
);
const provider = buildProvider();
const result = await provider.provideInlineCompletionItems(
document,
createPosition(),
createContext(),
createToken(),
);
expect(result).toBeNull();
expect(mockNextEditProvider.deleteChain).toHaveBeenCalledTimes(1);
expect(mockNextEditProvider.startChain).toHaveBeenCalledTimes(1);
expect(
mockNextEditProvider.provideInlineCompletionItems,
).toHaveBeenCalledTimes(1);
});
it("uses queued outcomes when processed items exist", async () => {
const document = createDocument();
setActiveEditor(document);
mockNextEditProvider.chainExists.mockReturnValue(true);
mockPrefetchQueue.__setProcessed([
{
location: {
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
},
outcome: mockOutcome,
},
]);
mockJumpManager.suggestJump.mockResolvedValue(true);
const provider = buildProvider();
await provider.provideInlineCompletionItems(
document,
createPosition(),
createContext(),
createToken(),
);
expect(mockPrefetchQueue.dequeueProcessed).toHaveBeenCalledTimes(1);
expect(mockJumpManager.setCompletionAfterJump).toHaveBeenCalledTimes(1);
expect(mockNextEditProvider.startChain).not.toHaveBeenCalled();
expect(mockNextEditProvider.deleteChain).not.toHaveBeenCalled();
expect(
mockNextEditProvider.provideInlineCompletionItems,
).not.toHaveBeenCalled();
});
});
function buildProvider(options: { usingFullFileDiff?: boolean } = {}) {
const usingFullFileDiff = options.usingFullFileDiff ?? true;
const configHandler = {
loadConfig: vi.fn(async () => ({
config: { selectedModelByRole: { autocomplete: undefined } },
})),
} as any;
const ide = { ideUtils: {} } as any;
const webviewProtocol = {} as any;
const provider = new ContinueCompletionProvider(
configHandler,
ide,
webviewProtocol,
usingFullFileDiff,
);
provider.activateNextEdit();
return provider;
}
function createDocument(
text = "function example() {\n return true;\n}",
): vscode.TextDocument {
const lines = text.split("\n");
return {
uri: vscode.Uri.parse("file:///test"),
isUntitled: false,
getText: (range?: any) => {
if (!range) {
return text;
}
const startLine = range.start?.line ?? 0;
const endLine = range.end?.line ?? startLine;
const startChar = range.start?.character ?? 0;
const endChar = range.end?.character ?? lines[endLine]?.length ?? 0;
if (startLine === endLine) {
const lineText = lines[startLine] ?? "";
return lineText.slice(startChar, endChar);
}
return text;
},
lineAt: (position: any) => {
const lineNumber =
typeof position === "number" ? position : position.line;
const lineText = lines[lineNumber] ?? "";
const range = new (vscode.Range as any)(
new (vscode.Position as any)(lineNumber, 0),
new (vscode.Position as any)(lineNumber, lineText.length),
);
return {
lineNumber,
text: lineText,
range,
rangeIncludingLineBreak: range,
firstNonWhitespaceCharacterIndex: 0,
isEmptyOrWhitespace: lineText.trim().length === 0,
} as unknown as vscode.TextLine;
},
} as unknown as vscode.TextDocument;
}
function createContext(): any {
return {
triggerKind: (vscode.InlineCompletionTriggerKind as any).Automatic,
selectedCompletionInfo: undefined,
};
}
function createPosition(line = 0, character = 0) {
return new (vscode.Position as any)(line, character);
}
function createToken(): any {
return {
isCancellationRequested: false,
onCancellationRequested: vi.fn(),
};
}
function setActiveEditor(document: any, cursor = createPosition()) {
const selection = { active: cursor, anchor: cursor };
(vscode.window as any).activeTextEditor = {
document,
selection,
selections: [selection],
};
}
function createMockNextEditProvider() {
return {
chainExists: vi.fn(() => false),
startChain: vi.fn(),
deleteChain: vi.fn(async () => {}),
provideInlineCompletionItems: vi.fn(async () => mockOutcome),
provideInlineCompletionItemsWithChain: vi.fn(async () => mockOutcome),
markDisplayed: vi.fn(),
getChainLength: vi.fn(() => 0),
};
}
function createMockPrefetchQueue() {
let processedItems: any[] = [];
let unprocessedItems: any[] = [];
const queue: any = {
initialize: vi.fn(),
process: vi.fn(),
peekThreeProcessed: vi.fn(),
dequeueProcessed: vi.fn(() => processedItems.shift()),
enqueueProcessed: vi.fn((item: any) => {
processedItems.push(item);
}),
__setProcessed(items: any[]) {
processedItems = [...items];
},
__setUnprocessed(items: any[]) {
unprocessedItems = [...items];
},
};
Object.defineProperty(queue, "processedCount", {
get: () => processedItems.length,
});
Object.defineProperty(queue, "unprocessedCount", {
get: () => unprocessedItems.length,
});
return queue;
}
function createMockJumpManager() {
return {
isJumpInProgress: vi.fn(() => false),
setJumpInProgress: vi.fn(),
completionAfterJump: undefined,
clearCompletionAfterJump: vi.fn(),
setCompletionAfterJump: vi.fn(),
suggestJump: vi.fn(async () => false),
wasJumpJustAccepted: vi.fn(() => false),
};
}
function createMockLoggingService() {
return {
trackPendingCompletion: vi.fn(),
handleAbort: vi.fn(),
markDisplayed: vi.fn(),
cancelRejectionTimeout: vi.fn(),
deleteAbortController: vi.fn(),
cancel: vi.fn(),
};
}
vi.mock("vscode", () => {
class Position {
constructor(
public line: number,
public character: number,
) {}
}
class Range {
constructor(
public start: Position,
public end: Position,
) {}
}
class InlineCompletionItem {
public insertText: string;
public range: Range;
public command?: any;
constructor(insertText: string, range: Range, command?: any) {
this.insertText = insertText;
this.range = range;
this.command = command;
}
}
const window = {
activeTextEditor: null as any,
showErrorMessage: vi.fn(() => Promise.resolve(undefined)),
};
const workspace = {
notebookDocuments: [] as any[],
getConfiguration: vi.fn(() => ({ get: vi.fn() })),
};
return {
window,
workspace,
Uri: { parse: (value: string) => ({ toString: () => value }) },
Position,
Range,
InlineCompletionItem,
InlineCompletionTriggerKind: { Automatic: 0, Invoke: 1 },
NotebookCellKind: { Markup: 1 },
};
});
vi.mock("core/autocomplete/CompletionProvider", () => {
return {
CompletionProvider: class {
provideInlineCompletionItems = vi.fn();
markDisplayed = vi.fn();
},
};
});
vi.mock("core/autocomplete/util/processSingleLineCompletion", () => ({
processSingleLineCompletion: vi.fn((text: string) => ({
completionText: text,
range: { start: 0, end: text.length },
})),
}));
vi.mock("../statusBar", () => {
const StatusBarStatus = {
Enabled: "enabled",
Disabled: "disabled",
} as const;
return {
StatusBarStatus,
getStatusBarStatus: vi.fn(() => StatusBarStatus.Enabled),
setupStatusBar: vi.fn(),
stopStatusBarLoading: vi.fn(),
};
});
vi.mock("../GhostTextAcceptanceTracker", () => {
const instance = {
setExpectedGhostTextAcceptance: vi.fn(),
};
return {
GhostTextAcceptanceTracker: {
getInstance: () => instance,
},
};
});
vi.mock("../lsp", () => ({
getDefinitionsFromLsp: vi.fn(),
}));
vi.mock("../recentlyEdited", () => ({
RecentlyEditedTracker: class {
async getRecentlyEditedRanges() {
return [];
}
},
}));
vi.mock("../RecentlyVisitedRangesService", () => ({
RecentlyVisitedRangesService: class {
getSnippets() {
return [];
}
},
}));
vi.mock("../activation/NextEditWindowManager", () => ({
NextEditWindowManager: {
isInstantiated: vi.fn(() => false),
getInstance: vi.fn(),
},
}));
vi.mock("../../activation/JumpManager", () => {
let instance: any = null;
return {
JumpManager: {
getInstance: () => instance,
},
__setMockJumpManagerInstance(value: any) {
instance = value;
},
};
});
vi.mock("core/nextEdit/NextEditPrefetchQueue", () => {
let instance: any = null;
return {
PrefetchQueue: {
getInstance: () => instance,
},
__setMockPrefetchQueueInstance(value: any) {
instance = value;
},
};
});
vi.mock("core/nextEdit/NextEditProvider", () => {
let instance: any = null;
return {
NextEditProvider: {
initialize: vi.fn(() => instance),
getInstance: vi.fn(() => instance),
},
__setMockNextEditProviderInstance(value: any) {
instance = value;
},
};
});
vi.mock("core/nextEdit/NextEditLoggingService", () => {
let instance: any = null;
return {
NextEditLoggingService: {
getInstance: () => instance,
},
__setMockNextEditLoggingServiceInstance(value: any) {
instance = value;
},
};
});
vi.mock("core/nextEdit/diff/diff", () => ({
checkFim: vi.fn(() => ({ isFim: true, fimText: "ghost" })),
}));
vi.mock("../util/errorHandling", () => ({
handleLLMError: vi.fn(async () => false),
}));

View file

@ -330,10 +330,25 @@ export class ContinueCompletionProvider
// Determine why this method was triggered.
const isJumping = this.jumpManager.isJumpInProgress();
const chainExists = this.nextEditProvider.chainExists();
let chainExists = this.nextEditProvider.chainExists();
const processedCount = this.prefetchQueue.processedCount;
const unprocessedCount = this.prefetchQueue.unprocessedCount;
console.log("isJumping:", isJumping, "/ chainExists:", chainExists);
this.prefetchQueue.peekThreeProcessed();
let resetChainInFullFileDiff = false;
if (
chainExists &&
this.usingFullFileDiff &&
processedCount === 0 &&
unprocessedCount === 0
) {
// Skipping jump logic due to empty queues while using full file diff
await this.nextEditProvider.deleteChain();
chainExists = false;
resetChainInFullFileDiff = true;
}
if (isJumping && chainExists) {
// Case 2: Jumping (chain exists, jump was taken)
console.log("trigger reason: jumping");
@ -421,6 +436,7 @@ export class ContinueCompletionProvider
}
} else {
// Case 1: Typing (chain does not exist).
// if resetChainInFullFileDiff is true then we are Rebuilding next edit chain after clearing empty queues in full file diff mode
this.nextEditProvider.startChain();
const input: AutocompleteInput = {
@ -439,6 +455,15 @@ export class ContinueCompletionProvider
{ withChain: false, usingFullFileDiff: this.usingFullFileDiff },
);
if (
resetChainInFullFileDiff &&
(!outcome ||
(!outcome.completion && outcome.diffLines.length === 0))
) {
// No next edit outcome after resetting chain; returning null
return null;
}
// Start prefetching next edits if not using full file diff.
// NOTE: this is better off not awaited. fire and forget.
if (!this.usingFullFileDiff) {

View file

@ -8,8 +8,8 @@ import { EXTENSION_NAME } from "core/control-plane/env";
import { Core } from "core/core";
import { walkDirAsync } from "core/indexing/walkDir";
import { isModelInstaller } from "core/llm";
import { startLocalOllama } from "core/util/ollamaHelper";
import { startLocalLemonade } from "core/util/lemonadeHelper";
import { startLocalOllama } from "core/util/ollamaHelper";
import { getConfigJsonPath, getConfigYamlPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
@ -153,6 +153,7 @@ const getCommandsMap: (
llm,
range,
rulesToInclude: config.rules,
isApply: false,
});
}

View file

@ -302,6 +302,7 @@ export class VerticalDiffManager {
newCode,
toolCallId,
rulesToInclude,
isApply,
}: {
input: string;
llm: ILLM;
@ -311,6 +312,7 @@ export class VerticalDiffManager {
newCode?: string;
toolCallId?: string;
rulesToInclude: undefined | RuleWithSource[];
isApply: boolean;
}): Promise<string | undefined> {
void vscode.commands.executeCommand(
"setContext",
@ -468,17 +470,23 @@ export class VerticalDiffManager {
const streamedLines: string[] = [];
async function* recordedStream() {
const stream = streamDiffLines({
highlighted: rangeContent,
prefix,
suffix,
const stream = streamDiffLines(
{
highlighted: rangeContent,
prefix,
suffix,
input,
language: getMarkdownLanguageTagForFile(fileUri),
type: isApply ? "apply" : "edit",
newCode: newCode ?? "",
includeRulesInSystemMessage: !!rulesToInclude && !isApply,
modelTitle: llm.title ?? llm.model,
},
llm,
rulesToInclude,
input,
language: getMarkdownLanguageTagForFile(fileUri),
overridePrompt,
abortController,
});
overridePrompt,
rulesToInclude,
);
for await (const line of stream) {
if (line.type === "new" || line.type === "same") {

View file

@ -229,6 +229,7 @@ export class VsCodeMessenger {
new vscode.Position(end.line, end.character),
),
rulesToInclude: config.rules,
isApply: false,
});
// Log dev data

View file

@ -332,6 +332,7 @@ export class QuickEdit {
quickEdit: this.previousInput,
range: this.range,
rulesToInclude: rules,
isApply: false,
});
}

View file

@ -67,6 +67,9 @@ export default function AcceptRejectAllButtons({
<div className="flex flex-row items-center gap-1">
<XMarkIcon className="text-error h-4 w-4" />
<span className="hidden sm:inline">Reject</span>
<span className="text-lightgray -ml-1.5 hidden scale-75 text-xs md:inline">
{rejectShortcut}
</span>
</div>
</button>
</ToolTip>
@ -80,6 +83,9 @@ export default function AcceptRejectAllButtons({
<div className="flex flex-row items-center gap-1">
<CheckIcon className="text-success h-4 w-4" />
<span className="hidden sm:inline">Accept</span>
<span className="text-lightgray -ml-1.5 hidden scale-75 text-xs md:inline">
{acceptShortcut}
</span>
</div>
</button>
</ToolTip>

View file

@ -420,7 +420,7 @@ export function UnifiedTerminalCommand({
return (
<StyledTerminalContainer
fontSize={getFontSize()}
className="mb-4"
className="mx-2 mb-4"
data-testid="terminal-container"
>
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor !my-2 flex min-w-0 flex-col outline outline-1">

View file

@ -1,379 +0,0 @@
import { ConfigYaml, parseConfigYaml } from "@continuedev/config-yaml";
import {
ArrowPathIcon,
ChevronDownIcon,
CircleStackIcon,
CommandLineIcon,
GlobeAltIcon,
UserCircleIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { MCPServerStatus } from "core";
import { useContext, useMemo, useState } from "react";
import { ToolTip } from "../../../components/gui/Tooltip";
import EditBlockButton from "../../../components/mainInput/Lump/EditBlockButton";
import { Button, Card } from "../../../components/ui";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { updateConfig } from "../../../redux/slices/configSlice";
import { selectCurrentOrg } from "../../../redux/slices/profilesSlice";
import { ConfigHeader } from "../components/ConfigHeader";
interface MCPServerStatusProps {
server: MCPServerStatus;
serverFromYaml?: NonNullable<ConfigYaml["mcpServers"]>[number];
}
function MCPServerCard({ server, serverFromYaml }: MCPServerStatusProps) {
const [isExpanded, setIsExpanded] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
const config = useAppSelector((store) => store.config.config);
const dispatch = useAppDispatch();
const updateMCPServerStatus = (status: MCPServerStatus["status"]) => {
// optimistic config update
dispatch(
updateConfig({
...config,
mcpServerStatuses: config.mcpServerStatuses.map((s) =>
s.id === server.id
? {
...s,
status,
}
: s,
),
}),
);
};
const onAuthenticate = async () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/startAuthentication", server);
};
const onRemoveAuth = async () => {
updateMCPServerStatus("authenticating");
await ideMessenger.request("mcp/removeAuthentication", server);
};
const onRefresh = async () => {
updateMCPServerStatus("connecting");
ideMessenger.post("mcp/reloadServer", {
id: server.id,
});
};
const handleToggleExpanded = (e: React.MouseEvent) => {
// Don't expand if clicking on buttons
if ((e.target as HTMLElement).closest("button")) {
return;
}
setIsExpanded(!isExpanded);
};
return (
<div>
<div
className="hover:bg-input/50 -mx-2 flex cursor-pointer items-center justify-between rounded px-2 py-1"
onClick={handleToggleExpanded}
>
<div className="flex items-center gap-3">
<ChevronDownIcon
className={`text-description h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`}
/>
<div className="flex-1">
<h3
className={`text-sm font-medium ${server.errors && server.errors.length > 0 ? "text-error" : ""}`}
>
{server.name}
</h3>
</div>
</div>
<div className="flex items-center gap-2">
{server.isProtectedResource && (
<ToolTip
content={
server.status === "error"
? "Authenticate"
: server.status === "authenticating"
? "Authenticating..."
: "Remove authentication"
}
>
<Button
onClick={
server.status === "error"
? onAuthenticate
: server.status === "authenticating"
? undefined
: onRemoveAuth
}
variant="ghost"
size="sm"
className="text-description-muted hover:enabled:text-foreground my-0 h-6 w-6 p-0"
disabled={server.status === "authenticating"}
>
{server.status === "authenticating" ? (
<GlobeAltIcon className="animate-spin-slow h-4 w-4 flex-shrink-0" />
) : (
<UserCircleIcon className="h-4 w-4 flex-shrink-0" />
)}
</Button>
</ToolTip>
)}
<EditBlockButton
blockType={"mcpServers"}
block={serverFromYaml}
sourceFile={server.sourceFile}
/>
<ToolTip content="Refresh server">
<Button
onClick={onRefresh}
variant="ghost"
size="sm"
className="text-description-muted hover:enabled:text-foreground my-0 h-6 w-6 p-0"
>
<ArrowPathIcon className="h-4 w-4 flex-shrink-0" />
</Button>
</ToolTip>
<div
className="h-2 w-2 flex-shrink-0 rounded-full"
style={{
backgroundColor:
server.status === "connected"
? "#22c55e" // green-500
: server.status === "connecting"
? "#eab308" // yellow-500
: server.status === "not-connected"
? "#78716c" // stone-500
: "#ef4444", // red-500 for error
}}
/>
</div>
</div>
{isExpanded && server.status === "connected" && (
<div className="mt-3 pl-7">
{/* Tools, Prompts, Resources with counts */}
<div className="mb-3 flex flex-row items-center gap-6">
<ToolTip
className="flex flex-col gap-0.5"
content={
<>
{server.tools.map((tool, idx) => (
<div key={idx} className="flex flex-col gap-1">
<div className="flex flex-col">
<code className="font-semibold">{tool.name}</code>
{tool.description && (
<span className="mt-0.5 text-xs text-gray-400">
{tool.description}
</span>
)}
{tool.inputSchema?.properties &&
Object.keys(tool.inputSchema.properties).length >
0 && (
<div className="mt-1">
<span className="text-xs text-gray-500">
Args:
</span>
<div className="ml-2">
{Object.entries(
tool.inputSchema.properties,
).map(([paramName, paramSchema], paramIdx) => (
<div key={paramIdx} className="text-xs">
<code className="text-blue-400">
{paramName}
</code>
{paramSchema &&
typeof paramSchema === "object" &&
"type" in paramSchema && (
<span className="ml-1 text-gray-500">
({paramSchema.type})
</span>
)}
</div>
))}
</div>
</div>
)}
</div>
{idx < server.tools.length - 1 && (
<div className="my-1 border-b border-gray-600"></div>
)}
</div>
))}
{server.tools.length === 0 && (
<span className="text-lightgray">No tools</span>
)}
</>
}
>
<div className="flex cursor-zoom-in items-center gap-2 hover:opacity-80">
<WrenchScrewdriverIcon className="h-4 w-4 flex-shrink-0" />
<span className="text-sm">Tools: {server.tools.length}</span>
</div>
</ToolTip>
<ToolTip
className="flex flex-col gap-0.5"
content={
<>
{server.prompts.map((prompt, idx) => (
<code key={idx}>{prompt.name}</code>
))}
{server.prompts.length === 0 && (
<span className="text-lightgray">No prompts</span>
)}
</>
}
>
<div className="flex cursor-zoom-in items-center gap-2 hover:opacity-80">
<CommandLineIcon className="h-4 w-4 flex-shrink-0" />
<span className="text-sm">
Prompts: {server.prompts.length}
</span>
</div>
</ToolTip>
<ToolTip
className="flex flex-col gap-0.5"
content={
<>
{[...server.resources, ...server.resourceTemplates].map(
(resource, idx) => (
<code key={idx}>{resource.name}</code>
),
)}
{server.resources.length === 0 && (
<span className="text-lightgray">No resources</span>
)}
</>
}
>
<div className="flex cursor-zoom-in items-center gap-2 hover:opacity-80">
<CircleStackIcon className="h-4 w-4 flex-shrink-0" />
<span className="text-sm">
Resources:{" "}
{server.resources.length + server.resourceTemplates.length}
</span>
</div>
</ToolTip>
</div>
</div>
)}
{/* Error display below expandable section */}
{server.errors && server.errors.length > 0 && (
<div className="mt-2 space-y-1">
{server.errors.map((error, errorIndex) => (
<div
key={errorIndex}
className="text-error bg-error/10 rounded px-2 py-1 text-xs"
>
<div className="flex items-start justify-between gap-2">
<span className="flex-1">
{error.length > 150 ? error.substring(0, 150) + "..." : error}
</span>
{error.length > 150 && (
<Button
className="my-0 flex-shrink-0"
size="sm"
variant="ghost"
onClick={() =>
void ideMessenger.ide.showVirtualFile(server.name, error)
}
>
View full error
</Button>
)}
</div>
</div>
))}
</div>
)}
</div>
);
}
function McpSection() {
const currentOrg = useAppSelector(selectCurrentOrg);
const servers = useAppSelector(
(store) => store.config.config.mcpServerStatuses,
);
const { selectedProfile } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
const disableMcp = currentOrg?.policy?.allowMcpServers === false;
const isLocal = selectedProfile?.profileType === "local";
const mergedBlocks = useMemo(() => {
const parsed = selectedProfile?.rawYaml
? parseConfigYaml(selectedProfile?.rawYaml ?? "")
: undefined;
return (servers ?? []).map((doc, index) => ({
block: doc,
blockFromYaml: parsed?.mcpServers?.[index],
}));
}, [servers, selectedProfile]);
const handleAddMcpServer = () => {
if (isLocal) {
void ideMessenger.request("config/addLocalWorkspaceBlock", {
blockType: "mcpServers",
});
} else {
void ideMessenger.request("controlPlane/openUrl", {
path: "new?type=block&blockType=mcpServers",
orgSlug: undefined,
});
}
};
if (disableMcp) {
return (
<div className="flex flex-col items-center justify-center p-2">
<span className="text-description">
MCP servers are disabled in your organization
</span>
</div>
);
}
return (
<div>
<ConfigHeader
title="MCP Servers"
onAddClick={handleAddMcpServer}
addButtonTooltip="Add MCP server"
/>
<div className="mt-6">
{mergedBlocks && mergedBlocks.length > 0 ? (
mergedBlocks.map(({ block, blockFromYaml }, index) => (
<div key={block.id}>
<Card>
<MCPServerCard server={block} serverFromYaml={blockFromYaml} />
</Card>
{index < mergedBlocks.length - 1 && <div className="mb-4" />}
</div>
))
) : (
<Card>
<div className="flex flex-col items-center justify-center p-8 text-center">
<span className="text-description">
No MCP servers configured. Click the + button to add your first
server.
</span>
</div>
</Card>
)}
</div>
</div>
);
}
export { McpSection };

View file

@ -5,7 +5,6 @@ import {
CircleStackIcon,
CommandLineIcon,
GlobeAltIcon,
PlusIcon,
UserCircleIcon,
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
@ -268,6 +267,27 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
))}
</div>
)}
{server.infos && server.infos.length > 0 && (
<div className="mt-3 space-y-2">
{server.infos.map((info, infoIndex) => (
<Alert
key={infoIndex}
type="info"
size="sm"
className="transition-all"
onClick={() =>
void ideMessenger.ide.showVirtualFile(server.name, info)
}
>
<span
className="text-xs"
dangerouslySetInnerHTML={{ __html: info }}
/>
</Alert>
))}
</div>
)}
</div>
);
}

View file

@ -1,7 +1,4 @@
import {
ArrowRightIcon,
MagnifyingGlassIcon,
} from "@heroicons/react/24/outline";
import { ArrowRightIcon } from "@heroicons/react/24/outline";
import { ToolCallState } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { useState } from "react";
@ -62,7 +59,8 @@ export function ToolCallDiv({
// But we'd need a nicer place to put the truncate button and the X icon when tool call fails
if (
functionName === BuiltInToolNames.SingleFindAndReplace ||
functionName === BuiltInToolNames.MultiEdit
functionName === BuiltInToolNames.MultiEdit ||
functionName === BuiltInToolNames.RunTerminalCommand
) {
return (
<div className="flex flex-col px-1">

View file

@ -99,10 +99,12 @@ export const callToolById = createAsyncThunk<
throw new Error(result.error);
} else {
output = result.content.contextItems;
error = new ContinueError(
ContinueErrorReason.Unspecificied,
result.content.errorMessage,
);
error = result.content.errorMessage
? new ContinueError(
ContinueErrorReason.Unspecified,
result.content.errorMessage,
)
: undefined;
}
streamResponse = true;
}

View file

@ -60,7 +60,7 @@ export async function callClientTool(
e instanceof ContinueError
? e
: e instanceof Error
? new ContinueError(ContinueErrorReason.Unspecificied, e.message)
? new ContinueError(ContinueErrorReason.Unspecified, e.message)
: new ContinueError(ContinueErrorReason.Unknown),
output: undefined,
};

@ -0,0 +1 @@
Subproject commit 02fec6cd89f89d5a0e7e471bd7a63bdb75b42e49

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/config-yaml",
"version": "1.14.0",
"version": "1.17.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/config-yaml",
"version": "1.14.0",
"version": "1.17.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -158,4 +158,62 @@ describe("PackageIdentifier", () => {
"Unknown URI type: invalid",
);
});
it("should expand leading tilde when HOME is available", () => {
const originalHome = process.env.HOME;
const originalUserProfile = process.env.USERPROFILE;
try {
process.env.HOME = "/tmp/test-home";
delete process.env.USERPROFILE;
const decoded = decodePackageIdentifier("~/package.yaml");
expect(decoded).toEqual({
uriType: "file" as const,
fileUri: "/tmp/test-home/package.yaml",
});
} finally {
if (originalHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = originalHome;
}
if (originalUserProfile === undefined) {
delete process.env.USERPROFILE;
} else {
process.env.USERPROFILE = originalUserProfile;
}
}
});
it("should leave leading tilde when no home directory is available", () => {
const originalHome = process.env.HOME;
const originalUserProfile = process.env.USERPROFILE;
try {
delete process.env.HOME;
delete process.env.USERPROFILE;
const decoded = decodePackageIdentifier("~/package.yaml");
expect(decoded).toEqual({
uriType: "file" as const,
fileUri: "~/package.yaml",
});
} finally {
if (originalHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = originalHome;
}
if (originalUserProfile === undefined) {
delete process.env.USERPROFILE;
} else {
process.env.USERPROFILE = originalUserProfile;
}
}
});
});

View file

@ -1,4 +1,49 @@
import os from "node:os";
type ProcessWithEnv = {
env?: Record<string, string | undefined>;
};
function getProcessEnv(): Record<string, string | undefined> | undefined {
if (
typeof process !== "undefined" &&
process &&
typeof process === "object"
) {
return (process as ProcessWithEnv).env;
}
if (typeof globalThis !== "undefined") {
const maybeProcess = (globalThis as { process?: ProcessWithEnv }).process;
return maybeProcess?.env;
}
return undefined;
}
function getHomeDirectory(): string | undefined {
const env = getProcessEnv();
const fromHome = env?.HOME?.trim();
if (fromHome) {
return fromHome;
}
const fromUserProfile = env?.USERPROFILE?.trim();
if (fromUserProfile) {
return fromUserProfile;
}
return undefined;
}
function expandLeadingTilde(identifier: string): string {
const homeDirectory = getHomeDirectory();
if (!homeDirectory) {
return identifier;
}
// Only replace a leading ~ so relative paths like ../~file stay untouched
return homeDirectory + identifier.slice(1);
}
export interface PackageSlug {
ownerSlug: string;
@ -67,7 +112,7 @@ export function decodePackageIdentifier(identifier: string): PackageIdentifier {
else if (identifier.startsWith("~")) {
return {
uriType: "file",
fileUri: identifier.replace("~", os.homedir()),
fileUri: expandLeadingTilde(identifier),
};
}
// Otherwise, it's a slug

View file

@ -20,7 +20,7 @@
},
"../config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.14.0",
"version": "1.17.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -23,6 +23,7 @@ import { FimCreateParamsStreaming } from "./base.js";
// };
export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>";
export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>";
export const INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/";
export class InceptionApi extends OpenAIApi {
constructor(config: InceptionConfig) {
@ -38,37 +39,7 @@ export class InceptionApi extends OpenAIApi {
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const endpoint = new URL("edit/completions", this.apiBase);
const resp = await customFetch(this.config.requestOptions)(endpoint, {
method: "POST",
body: JSON.stringify({
model: body.model,
messages: body.messages,
max_tokens: body.max_tokens,
temperature: body.temperature,
top_p: body.top_p,
frequency_penalty: body.frequency_penalty,
presence_penalty: body.presence_penalty,
stop: body.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp as any)) {
if (chunk.choices?.[0]?.delta?.content) {
yield chatChunk({
content: chunk.choices[0].delta.content,
finish_reason: chunk.choices[0].finish_reason || null,
model: body.model,
});
}
}
yield* this.streamCustomEndpoint("edit/completions", body, signal);
}
// Add custom edit completions method (non-streaming).
@ -76,30 +47,7 @@ export class InceptionApi extends OpenAIApi {
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
const endpoint = new URL("edit/completions", this.apiBase);
const resp = await customFetch(this.config.requestOptions)(endpoint, {
method: "POST",
body: JSON.stringify({
model: body.model,
messages: body.messages,
max_tokens: body.max_tokens,
temperature: body.temperature,
top_p: body.top_p,
frequency_penalty: body.frequency_penalty,
presence_penalty: body.presence_penalty,
stop: body.stop,
stream: false, // Set to false for non-streaming
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
},
signal,
});
const data = await resp.json();
return data as ChatCompletion;
return this.nonStreamCustomEndpoint("edit/completions", body, signal);
}
// Override the regular chat stream method to route to edit endpoint for next edit requests.
@ -108,8 +56,11 @@ export class InceptionApi extends OpenAIApi {
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
if (this.isNextEdit(body.messages)) {
body.messages = this.removeNextEditToken(body.messages);
body.messages = this.removeToken(body.messages, UNIQUE_TOKEN);
yield* this.editCompletionStream(body, signal);
} else if (this.isApply(body.messages)) {
body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN);
yield* this.applyCompletionStream(body, signal);
} else {
yield* super.chatCompletionStream(body, signal);
}
@ -121,13 +72,30 @@ export class InceptionApi extends OpenAIApi {
signal: AbortSignal,
): Promise<ChatCompletion> {
if (this.isNextEdit(body.messages)) {
body.messages = this.removeNextEditToken(body.messages);
body.messages = this.removeToken(body.messages, UNIQUE_TOKEN);
return this.editCompletionNonStream(body, signal);
} else if (this.isApply(body.messages)) {
body.messages = this.removeToken(body.messages, APPLY_UNIQUE_TOKEN);
return this.applyCompletionNonStream(body, signal);
} else {
return super.chatCompletionNonStream(body, signal);
}
}
async *applyCompletionStream(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
yield* this.streamCustomEndpoint("apply/completions", body, signal);
}
async applyCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
return this.nonStreamCustomEndpoint("apply/completions", body, signal);
}
async *fimStream(
body: FimCreateParamsStreaming,
signal: AbortSignal,
@ -179,24 +147,103 @@ export class InceptionApi extends OpenAIApi {
);
}
private isApply(messages: ChatCompletionMessageParam[]): boolean {
return messages.some(
(message) =>
typeof message.content === "string" &&
message.content.endsWith(APPLY_UNIQUE_TOKEN),
);
}
// Remove the unique token from messages.
private removeNextEditToken(
private removeToken(
messages: ChatCompletionMessageParam[],
token: string,
): ChatCompletionMessageParam[] {
const lastMessage = messages[messages.length - 1];
if (
typeof lastMessage?.content === "string" &&
lastMessage.content.endsWith(UNIQUE_TOKEN)
lastMessage.content.endsWith(token)
) {
const cleanedMessages = [...messages];
cleanedMessages[cleanedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
content: lastMessage.content.slice(0, -token.length),
};
return cleanedMessages;
}
return messages;
}
private async *streamCustomEndpoint(
path: string,
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const endpoint = new URL(path, this.apiBase);
const resp = await customFetch(this.config.requestOptions)(endpoint, {
method: "POST",
body: JSON.stringify({
model: body.model,
messages: body.messages,
max_tokens: body.max_tokens,
temperature: body.temperature,
top_p: body.top_p,
frequency_penalty: body.frequency_penalty,
presence_penalty: body.presence_penalty,
stop: body.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp as any)) {
const deltaContent = chunk.choices?.[0]?.delta?.content;
if (deltaContent) {
yield chatChunk({
content: deltaContent,
finish_reason: chunk.choices[0].finish_reason || null,
model: body.model,
});
}
}
}
private async nonStreamCustomEndpoint(
path: string,
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
const endpoint = new URL(path, this.apiBase);
const resp = await customFetch(this.config.requestOptions)(endpoint, {
method: "POST",
body: JSON.stringify({
model: body.model,
messages: body.messages,
max_tokens: body.max_tokens,
temperature: body.temperature,
top_p: body.top_p,
frequency_penalty: body.frequency_penalty,
presence_penalty: body.presence_penalty,
stop: body.stop,
stream: false,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
},
signal,
});
const data = await resp.json();
return data as ChatCompletion;
}
}