Merge branch 'main' into nate/paste-tip
This commit is contained in:
commit
87ef441c99
43 changed files with 1085 additions and 806 deletions
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Detailed PR Review
|
||||
uses: continuedev/continue/actions/detailed-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
|
||||
uses: continuedev/continue/actions/detailed-review@80c679747b7c7b2624d15db31ff5bdadc9681c65
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: continuedev
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Continue PR Review Action
|
||||
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
|
||||
uses: continuedev/continue/actions/general-review@80c679747b7c7b2624d15db31ff5bdadc9681c65
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "continuedev"
|
||||
|
|
|
|||
4
.github/workflows/respond-to-cubic.yaml
vendored
4
.github/workflows/respond-to-cubic.yaml
vendored
|
|
@ -29,7 +29,7 @@ jobs:
|
|||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
|
@ -132,7 +132,7 @@ jobs:
|
|||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
|
|
|||
|
|
@ -35,25 +35,25 @@ Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Con
|
|||
|
||||
## Agent
|
||||
|
||||
[Agent](/features/agent/quick-start) to work on development tasks together with AI
|
||||
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
|
||||
|
||||

|
||||
|
||||
## Chat
|
||||
|
||||
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
|
||||

|
||||
|
||||
## Edit
|
||||
|
||||
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
|
||||

|
||||
|
||||
## Autocomplete
|
||||
|
||||
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import {
|
||||
SSEClientTransport,
|
||||
SseError,
|
||||
|
|
@ -8,7 +6,8 @@ import {
|
|||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { Agent as HttpsAgent } from "https";
|
||||
import {
|
||||
IDE,
|
||||
MCPConnectionStatus,
|
||||
|
|
@ -393,6 +392,11 @@ class MCPConnection {
|
|||
case "websocket":
|
||||
return new WebSocketClientTransport(new URL(options.transport.url));
|
||||
case "sse":
|
||||
const sseAgent =
|
||||
options.transport.requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
return new SSEClientTransport(new URL(options.transport.url), {
|
||||
eventSourceInit: {
|
||||
fetch: (input, init) =>
|
||||
|
|
@ -404,17 +408,27 @@ class MCPConnection {
|
|||
| Record<string, string>
|
||||
| undefined),
|
||||
},
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
}),
|
||||
},
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
requestInit: {
|
||||
headers: options.transport.requestOptions?.headers,
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
},
|
||||
});
|
||||
case "streamable-http":
|
||||
return new StreamableHTTPClientTransport(
|
||||
new URL(options.transport.url),
|
||||
{
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
const { url, requestOptions } = options.transport;
|
||||
const streamableAgent =
|
||||
requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
return new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: {
|
||||
headers: requestOptions?.headers,
|
||||
...(streamableAgent && { agent: streamableAgent }),
|
||||
},
|
||||
);
|
||||
});
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
|
|
|
|||
|
|
@ -668,6 +668,8 @@ export class Core {
|
|||
return queue.dequeueProcessed() || null;
|
||||
});
|
||||
|
||||
// NOTE: This is not used unless prefetch is used.
|
||||
// At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching.
|
||||
on("nextEdit/queue/processOne", async (msg) => {
|
||||
console.log("nextEdit/queue/processOne");
|
||||
const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ export enum EditableRegionStrategy {
|
|||
Static = "static",
|
||||
}
|
||||
|
||||
/**
|
||||
* This was an attempt to find next edit locations deterministically.
|
||||
* I was intending to use this in tandem with the prefetching logic, but we are not using it anymore.
|
||||
*/
|
||||
export async function getNextEditableRegion(
|
||||
strategy: EditableRegionStrategy,
|
||||
ctx: any,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,11 @@ export interface ProcessedItem {
|
|||
/**
|
||||
* Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts
|
||||
*/
|
||||
/**
|
||||
* This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain.
|
||||
* I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background.
|
||||
* Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea.
|
||||
*/
|
||||
export class PrefetchQueue {
|
||||
private static instance: PrefetchQueue | null = null;
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js";
|
|||
import { AutocompleteInput } from "../autocomplete/util/types.js";
|
||||
import { isSecurityConcern } from "../indexing/ignore.js";
|
||||
import { modelSupportsNextEdit } from "../llm/autodetect.js";
|
||||
import { countTokens } from "../llm/countTokens.js";
|
||||
import { localPathOrUriToPath } from "../util/pathToUri.js";
|
||||
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
|
||||
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
|
||||
|
|
@ -45,6 +44,14 @@ const ERRORS_TO_IGNORE = [
|
|||
"operation was aborted",
|
||||
];
|
||||
|
||||
/**
|
||||
* This is the next edit analogue to autocomplete's CompletionProvider.
|
||||
* You will see a lot of similar if not identical methods to CompletionProvider methods.
|
||||
* All logic used to live inside this class, but that became untenable quickly.
|
||||
* I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it.
|
||||
* Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc.
|
||||
* There being a singleton also gives a lot of guarantees about the state of the next edit state machine.
|
||||
*/
|
||||
export class NextEditProvider {
|
||||
private static instance: NextEditProvider | null = null;
|
||||
|
||||
|
|
@ -62,7 +69,6 @@ export class NextEditProvider {
|
|||
private currentEditChainId: string | null = null;
|
||||
private previousRequest: AutocompleteInput | null = null;
|
||||
private previousCompletions: NextEditOutcome[] = [];
|
||||
// private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
|
||||
|
||||
// Model-specific provider instance.
|
||||
private modelProvider: BaseNextEditModelProvider | null = null;
|
||||
|
|
@ -223,14 +229,14 @@ export class NextEditProvider {
|
|||
|
||||
this.currentEditChainId = null;
|
||||
this.previousCompletions = [];
|
||||
// TODO: this should be cleaned up in the prefetch queue.
|
||||
// this.nextEditableRegionsInTheCurrentChain = [];
|
||||
|
||||
if (this.previousRequest) {
|
||||
const fileContent = (
|
||||
await this.ide.readFile(this.previousRequest.filepath)
|
||||
).toString();
|
||||
|
||||
const ast = await getAst(this.previousRequest.filepath, fileContent);
|
||||
|
||||
if (ast) {
|
||||
DocumentHistoryTracker.getInstance().push(
|
||||
localPathOrUriToPath(this.previousRequest.filepath),
|
||||
|
|
@ -253,6 +259,9 @@ export class NextEditProvider {
|
|||
return this.previousCompletions.length === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the main entry point to this class.
|
||||
*/
|
||||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
|
|
@ -370,6 +379,8 @@ export class NextEditProvider {
|
|||
throw new Error("Model provider not initialized");
|
||||
}
|
||||
|
||||
// NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets.
|
||||
// Use getAllSnippets if snippet gathering becomes noticably slow.
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
|
|
@ -445,6 +456,9 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
// Send prompts to LLM (using only user prompt for fine-tuned models).
|
||||
// prompts[1] extracts the user prompt from the system-user prompt pair.
|
||||
// NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
|
||||
// Mercury Coder currently does not support streaming.
|
||||
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
|
||||
stream: false,
|
||||
});
|
||||
|
|
@ -484,7 +498,7 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
if (outcome) {
|
||||
// Handle NextEditProvider-specific state
|
||||
// Handle NextEditProvider-specific state.
|
||||
this.previousCompletions.push(outcome);
|
||||
|
||||
// Mark as displayed for JetBrains
|
||||
|
|
@ -494,97 +508,6 @@ export class NextEditProvider {
|
|||
return outcome;
|
||||
}
|
||||
|
||||
private _calculateOptimalEditableRegion(
|
||||
helper: HelperVars,
|
||||
heuristic: "fourChars" | "tokenizer" = "tokenizer",
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
} {
|
||||
const cursorLine = helper.pos.line;
|
||||
const fileLines = helper.fileLines;
|
||||
const MAX_TOKENS = 512;
|
||||
|
||||
// Initialize with cursor line.
|
||||
let editableRegionStartLine = cursorLine;
|
||||
let editableRegionEndLine = cursorLine;
|
||||
|
||||
// Get initial content and token count.
|
||||
let currentContent = fileLines[cursorLine];
|
||||
let totalTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(currentContent, helper.modelName)
|
||||
: Math.ceil(currentContent.length / 4);
|
||||
|
||||
// Expand outward alternating between adding lines above and below.
|
||||
let addingAbove = true;
|
||||
|
||||
while (totalTokens < MAX_TOKENS) {
|
||||
let addedLine = false;
|
||||
|
||||
if (addingAbove) {
|
||||
// Try to add a line above.
|
||||
if (editableRegionStartLine > 0) {
|
||||
editableRegionStartLine--;
|
||||
const lineContent = fileLines[editableRegionStartLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
} else {
|
||||
// Try to add a line below.
|
||||
if (editableRegionEndLine < fileLines.length - 1) {
|
||||
editableRegionEndLine++;
|
||||
const lineContent = fileLines[editableRegionEndLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
}
|
||||
|
||||
// If we can't add in the current direction, try the other.
|
||||
if (!addedLine) {
|
||||
// If we're already at both file boundaries, we're done.
|
||||
if (
|
||||
editableRegionStartLine === 0 &&
|
||||
editableRegionEndLine === fileLines.length - 1
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
// If we couldn't add in one direction, force the next attempt in the other direction.
|
||||
addingAbove = !addingAbove;
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we exceeded the token limit, revert the last addition.
|
||||
if (totalTokens > MAX_TOKENS) {
|
||||
if (addingAbove) {
|
||||
editableRegionStartLine++;
|
||||
} else {
|
||||
editableRegionEndLine--;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Alternate between adding above and below for balanced context.
|
||||
addingAbove = !addingAbove;
|
||||
}
|
||||
|
||||
return {
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
};
|
||||
}
|
||||
|
||||
private async _markDisplayedIfJetBrains(
|
||||
completionId: string,
|
||||
outcome: NextEditOutcome,
|
||||
|
|
@ -595,6 +518,12 @@ export class NextEditProvider {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a wrapper around provideInlineCompletionItems.
|
||||
* This is invoked when we call the model in the background using prefetch.
|
||||
* It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch.
|
||||
* You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`.
|
||||
*/
|
||||
public async provideInlineCompletionItemsWithChain(
|
||||
ctx: {
|
||||
completionId: string;
|
||||
|
|
|
|||
|
|
@ -1,259 +0,0 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
|
||||
import { HelperVars } from "../autocomplete/util/HelperVars.js";
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import { NextEditProvider } from "./NextEditProvider.js";
|
||||
|
||||
// Mock the countTokens function
|
||||
vi.mock("../llm/countTokens.js", () => ({
|
||||
countTokens: (text: string) => {
|
||||
// Simple mock that counts 1 token per character for predictable tests
|
||||
return text.length;
|
||||
},
|
||||
}));
|
||||
|
||||
// Create a helper function to set up the test context
|
||||
function createMockHelper(
|
||||
fileContents: string,
|
||||
cursorLine: number,
|
||||
): HelperVars {
|
||||
const fileLines = fileContents.split("\n");
|
||||
|
||||
return {
|
||||
fileLines,
|
||||
fileContents,
|
||||
pos: { line: cursorLine, character: 0 },
|
||||
modelName: "gpt-4",
|
||||
lang: { name: "typescript" },
|
||||
filepath: "test/file.ts",
|
||||
workspaceUris: ["test/workspace"],
|
||||
options: {},
|
||||
input: { completionId: "test-completion-id" },
|
||||
} as unknown as HelperVars;
|
||||
}
|
||||
|
||||
// TODO: Add more tests for other methods.
|
||||
describe("_calculateOptimalEditableRegion", () => {
|
||||
let nextEditProvider: NextEditProvider;
|
||||
let mockConfigHandler: ConfigHandler;
|
||||
let mockIde: IDE;
|
||||
let mockGetLlm: () => Promise<ILLM | undefined>;
|
||||
let mockOnError: (e: any) => void;
|
||||
let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create comprehensive mocks for all dependencies
|
||||
mockConfigHandler = {
|
||||
loadConfig: vi.fn().mockResolvedValue({ config: {} }),
|
||||
} as unknown as ConfigHandler;
|
||||
|
||||
mockIde = {
|
||||
readFile: vi.fn().mockResolvedValue(""),
|
||||
getWorkspaceDirs: vi.fn().mockResolvedValue([]),
|
||||
getRepoName: vi.fn().mockResolvedValue("test-repo"),
|
||||
getUniqueId: vi.fn().mockResolvedValue("test-id"),
|
||||
getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }),
|
||||
onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => {
|
||||
// Return a disposable object that does nothing when disposed
|
||||
return {
|
||||
dispose: () => {},
|
||||
};
|
||||
}),
|
||||
} as unknown as IDE;
|
||||
|
||||
mockGetLlm = vi.fn().mockResolvedValue({
|
||||
model: "gpt-4",
|
||||
providerName: "openai",
|
||||
underlyingProviderName: "openai",
|
||||
completionOptions: {},
|
||||
chat: vi.fn(),
|
||||
});
|
||||
|
||||
mockOnError = vi.fn();
|
||||
mockGetDefinitionsFromLsp = vi.fn();
|
||||
|
||||
// Initialize NextEditProvider with mocked dependencies
|
||||
nextEditProvider = NextEditProvider.initialize(
|
||||
mockConfigHandler,
|
||||
mockIde,
|
||||
mockGetLlm,
|
||||
mockOnError,
|
||||
mockGetDefinitionsFromLsp,
|
||||
"default",
|
||||
);
|
||||
|
||||
// Expose the private method for testing
|
||||
// This is a bit of a hack, but necessary for testing private methods
|
||||
(nextEditProvider as any)._calculateOptimalEditableRegion = (
|
||||
NextEditProvider.prototype as any
|
||||
)._calculateOptimalEditableRegion.bind(nextEditProvider);
|
||||
});
|
||||
|
||||
// Test cases remain the same as before...
|
||||
it("should include only the cursor line when it already exceeds token limit", () => {
|
||||
// Create a mock helper with a very long cursor line (>500 characters)
|
||||
const longLine = "X".repeat(600);
|
||||
const helper = createMockHelper(longLine, 0);
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(0);
|
||||
});
|
||||
|
||||
it("should expand symmetrically when possible", () => {
|
||||
// Create content with identical lines and cursor in the middle
|
||||
const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each
|
||||
const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5)
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should expand 5 lines in each direction (total 11 lines) for symmetry
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(10);
|
||||
});
|
||||
|
||||
it("should expand asymmetrically when hitting a file boundary", () => {
|
||||
// Create content with cursor near the top
|
||||
const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each
|
||||
const helper = createMockHelper(lines, 1); // Cursor near the top (line 1)
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should include more lines below since it can't expand much above
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
// Should include many more lines below to reach token limit
|
||||
expect(result.editableRegionEndLine).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it("should handle files with varying line lengths", () => {
|
||||
// Create content with varying line lengths
|
||||
const fileContents = [
|
||||
"Short line", // 10 chars
|
||||
"A".repeat(100), // 100 chars
|
||||
"Medium length line here", // 24 chars
|
||||
"B".repeat(200), // 200 chars
|
||||
"Another typical line of code", // 28 chars
|
||||
].join("\n");
|
||||
|
||||
const helper = createMockHelper(fileContents, 2); // Cursor on the medium line
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should include all lines since total tokens < 500
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(4);
|
||||
});
|
||||
|
||||
it("should respect the token limit and not include too many lines", () => {
|
||||
// Create content with many small lines (10 chars each)
|
||||
const lines = Array(600).fill("C".repeat(10)).join("\n");
|
||||
const helper = createMockHelper(lines, 300); // Cursor in the middle
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Each line is 10 chars = 10 tokens per line with our mock.
|
||||
// So with 500 token limit, we should get 50 lines total.
|
||||
// 25 above, 25 below, +1 current
|
||||
const totalLines =
|
||||
result.editableRegionEndLine - result.editableRegionStartLine + 1;
|
||||
expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line)
|
||||
});
|
||||
|
||||
it("should use character approximation when using fourChars heuristic", () => {
|
||||
// In this test, we're setting up a situation where tiktoken and fourChars would give different results
|
||||
// Creating 5 lines, each 100 characters
|
||||
const lines = Array(10).fill("D".repeat(100)).join("\n");
|
||||
const helper = createMockHelper(lines, 2); // Cursor in the middle
|
||||
|
||||
// Mock for tiktoken counting (1 char = 1 token)
|
||||
//@ts-ignore
|
||||
const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Mock for fourChars counting (1 token = 4 chars)
|
||||
// This should include more lines since each line is counted as 25 tokens instead of 100
|
||||
//@ts-ignore
|
||||
const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"fourChars",
|
||||
);
|
||||
|
||||
// The fourChars approach should include more lines since it estimates fewer tokens per line
|
||||
expect(
|
||||
fourCharsResult.editableRegionEndLine -
|
||||
fourCharsResult.editableRegionStartLine,
|
||||
).toBeGreaterThan(
|
||||
tokenizerResult.editableRegionEndLine -
|
||||
tokenizerResult.editableRegionStartLine,
|
||||
);
|
||||
});
|
||||
|
||||
it("should include the entire file if it's within token limit", () => {
|
||||
// Create a small file
|
||||
const smallFile = "Small file\nwith just\na few lines\nof text";
|
||||
const helper = createMockHelper(smallFile, 1);
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should include all lines
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(3);
|
||||
});
|
||||
|
||||
it("should prioritize balanced context when token limit allows", () => {
|
||||
// Create content with alternating long and short lines
|
||||
const fileContents = [
|
||||
"Short", // 5 chars
|
||||
"E".repeat(80), // 80 chars
|
||||
"Also short", // 10 chars
|
||||
"F".repeat(80), // 80 chars
|
||||
"Another short one", // 17 chars
|
||||
"G".repeat(80), // 80 chars
|
||||
"Final short line", // 16 chars
|
||||
].join("\n");
|
||||
|
||||
const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3)
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should try to include equal number of lines above and below cursor
|
||||
const linesAbove = result.editableRegionStartLine;
|
||||
const linesBelow =
|
||||
helper.fileLines.length - 1 - result.editableRegionEndLine;
|
||||
|
||||
// Difference between lines above and below should be minimal
|
||||
expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -19,6 +19,11 @@ import {
|
|||
} from "../types.js";
|
||||
import { isWhitespaceOnlyDeletion } from "../utils.js";
|
||||
|
||||
/**
|
||||
* This class is used as an abstract base class for model-specific providers.
|
||||
* This and its children are responsible for pre/post processing of prompts and outcomes.
|
||||
* Different next edit models have very different requirements.
|
||||
*/
|
||||
export abstract class BaseNextEditModelProvider {
|
||||
protected readonly modelName: string;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,12 @@
|
|||
import { MCPServerStatus, MCPTool } from "..";
|
||||
|
||||
export function getMCPToolName(server: MCPServerStatus, tool: MCPTool) {
|
||||
const serverPrefix = server.name.split(" ").join("_").toLowerCase();
|
||||
// Replace any sequence of non-alphanumeric characters with a single underscore
|
||||
const serverPrefix = server.name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "") // Remove leading/trailing underscores
|
||||
.replace(/_+/g, "_"); // Replace multiple sequential underscores with single underscore
|
||||
|
||||
if (tool.name.startsWith(serverPrefix)) {
|
||||
return tool.name;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,3 +56,54 @@ test("getMCPToolName - handles mixed case in server names", () => {
|
|||
const result = getMCPToolName(server, tool);
|
||||
expect(result).toBe("gitlab_create_merge_request");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with special characters (parentheses)", () => {
|
||||
const server = createMcpServer("Linear MCP (SSE)");
|
||||
const tool = createMCPTool("create_issue");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("linear_mcp_sse_create_issue");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with dots and other special characters", () => {
|
||||
const server = createMcpServer("My.Server@Test!");
|
||||
const tool = createMCPTool("test_action");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("my_server_test_test_action");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with multiple consecutive special characters", () => {
|
||||
const server = createMcpServer("Server@@##Name");
|
||||
const tool = createMCPTool("action");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores (no hyphens or multiple underscores)
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("server_name_action");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with hyphens", () => {
|
||||
const server = createMcpServer("My-Server-Name");
|
||||
const tool = createMCPTool("test_action");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("my_server_name_test_action");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles multiple consecutive underscores in server name", () => {
|
||||
const server = createMcpServer("Linear__MCP");
|
||||
const tool = createMCPTool("create_issue");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and single underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).not.toMatch(/__/);
|
||||
expect(result).toBe("linear_mcp_create_issue");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -335,6 +335,8 @@ The HttpContextProvider makes a POST request to the url passed in the configurat
|
|||
- provider: http
|
||||
params:
|
||||
url: "https://api.example.com/v1/users"
|
||||
headers:
|
||||
- Authorization: "Bearer <token>"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
|
|
@ -409,7 +411,8 @@ You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
|||
## Deprecated Context Providers
|
||||
|
||||
<Note>
|
||||
To provide conext beyond the built-in context providers, we now recommend using [MCP Servers](/customization/mcp-tools)
|
||||
To provide conext beyond the built-in context providers, we now recommend
|
||||
using [MCP Servers](/customization/mcp-tools)
|
||||
</Note>
|
||||
|
||||
View the [deprecated context providers](/reference/deprecated-context-providers) for documentation on:
|
||||
|
|
@ -427,4 +430,4 @@ View the [deprecated context providers](/reference/deprecated-context-providers)
|
|||
- `@Issue` - GitHub issues
|
||||
- `@Url` - URL content
|
||||
- `@Search` - Codebase search
|
||||
- `@Web` - Web search results
|
||||
- `@Web` - Web search results
|
||||
|
|
|
|||
|
|
@ -231,6 +231,7 @@
|
|||
"guides/understanding-assistants",
|
||||
"guides/codebase-documentation-awareness",
|
||||
"guides/cli",
|
||||
"guides/continuous-ai",
|
||||
"guides/plan-mode-guide",
|
||||
"guides/ollama-guide",
|
||||
"guides/running-continue-without-internet",
|
||||
|
|
|
|||
207
docs/guides/continuous-ai.mdx
Normal file
207
docs/guides/continuous-ai.mdx
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
---
|
||||
title: "Continuous AI: A Developer's Guide"
|
||||
description: "Learn how to integrate intelligent automation into development workflows, making AI assistance as natural as syntax highlighting. Implement systematic AI workflows that compound productivity gains over time."
|
||||
---
|
||||
|
||||
Continuous AI is the integration of intelligent automation directly into development workflows, making AI assistance as natural and reliable as syntax highlighting or code completion. Its purpose is to amplify developer intent at every stage of the coding process.
|
||||
|
||||
Think of it this way: DevOps automated the mechanical aspects of software delivery—building, testing, deploying. Continuous AI automates the intelligence aspects—understanding context, making suggestions, adapting to patterns, and learning from developer feedback.
|
||||
|
||||
## Why Continuous AI Matters Now
|
||||
|
||||
The same market forces that made DevOps inevitable are now driving Continuous AI adoption:
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Developer Behavior is Shifting" icon="chart-line">
|
||||
Engineering teams are rapidly adopting AI tools, with many seeing
|
||||
significant productivity improvements in their workflows.
|
||||
</Card>
|
||||
|
||||
<Card title="Economic Pressure" icon="dollar-sign">
|
||||
AI-assisted coding is contributing measurable increases in developer output,
|
||||
creating competitive advantages for early adopters.
|
||||
</Card>
|
||||
|
||||
<Card title="Tooling Maturity" icon="wrench">
|
||||
Unlike DevOps, Continuous AI can be implemented incrementally on existing
|
||||
development stacks without major infrastructure changes.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
The teams that implement systematic AI workflows first create advantages that compound over time.
|
||||
|
||||
## The Continuous AI Maturity Model
|
||||
|
||||
Teams typically progress through three stages when adopting Continuous AI:
|
||||
|
||||
<Accordion title="Level 1: Manual AI Assistance">
|
||||
You prompt the AI when you remember, and it completes the task. This is great for quick productivity boosts but remains highly manual and inconsistent.
|
||||
|
||||
**Example**: Using AI to draft a function or suggest a test case only when you think to ask for it.
|
||||
|
||||
**Continue Implementation**: Using [Chat](/features/chat/quick-start) or [Edit](/features/edit/quick-start) mode for one-off coding tasks.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Level 2: Workflow Automation">
|
||||
AI handles routine tasks with human oversight. This is where teams start seeing compounding gains.
|
||||
|
||||
**Examples**:
|
||||
|
||||
- AI adds missing documentation during PR review
|
||||
- Automatic code formatting and style corrections
|
||||
- Generated unit tests for new functions
|
||||
- Updated issue tracking when branches are merged
|
||||
|
||||
**Continue Implementation**: Using [Continue CLI](/guides/cli) with custom rules and integrations into CI/CD pipelines.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Level 3: Zero-Intervention Workflows">
|
||||
AI autonomously completes processes end-to-end without human input, but only for very specific, low-risk workflows.
|
||||
|
||||
**Examples**:
|
||||
|
||||
- AI merges safe dependency updates after automated tests pass
|
||||
- Automatic documentation updates when code changes
|
||||
- Self-healing test suites that fix themselves based on failure patterns
|
||||
|
||||
**Continue Implementation**: Fully automated [agents](/features/agent/quick-start) with strict permissions and safety guardrails.
|
||||
|
||||
</Accordion>
|
||||
|
||||
## Building Your Continuous AI Workflow
|
||||
|
||||
### Start with Level 1 → Level 2: Pick One Workflow
|
||||
|
||||
Don't try to automate everything at once. Choose a specific daily friction point:
|
||||
|
||||
```bash
|
||||
# Example: Automated code review comments
|
||||
git diff | cn -p "review this diff and suggest improvements following our team standards"
|
||||
|
||||
# Example: Generate missing tests
|
||||
cn -p "create unit tests for the functions in src/auth.js"
|
||||
|
||||
# Example: Update documentation
|
||||
cn -p "update the README with the new API endpoints from the recent changes"
|
||||
```
|
||||
|
||||
### Configure Team-Wide Intelligence
|
||||
|
||||
The most effective Continuous AI is tuned to your codebase, standards, and practices:
|
||||
|
||||
```yaml config.yaml
|
||||
rules:
|
||||
- name: code-review
|
||||
description: "Review code following team standards"
|
||||
rule: "Review following our TypeScript style guide and security practices"
|
||||
context:
|
||||
- "docs/style-guide.md"
|
||||
- "security-checklist.md"
|
||||
```
|
||||
|
||||
### Implement Progressive Permissions
|
||||
|
||||
Use Continue CLI's permission system to gradually expand AI capabilities:
|
||||
|
||||
```yaml ~/.continue/permissions.yaml
|
||||
permissions:
|
||||
- allow: "Bash(git*)" # Git commands are safe
|
||||
- ask: "Write(**/*.ts)" # Ask before modifying TypeScript files
|
||||
- deny: "Bash(rm*)" # Never allow deletions
|
||||
```
|
||||
|
||||
### Measure What Matters: Intervention Rate
|
||||
|
||||
Track how often you need to correct AI output. Lower intervention rates mean higher trust and compounding productivity gains.
|
||||
|
||||
## Real-World Implementation Patterns
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Pattern 1: The Async Triage Bot">
|
||||
Imagine setting up an AI agent that checks new GitHub issues every morning and leaves the first helpful response. This lightens the load for maintainers and ensures community members feel heard quickly.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Pattern 2: The PR Review Assistant">
|
||||
AI can automatically review new pull requests for security, performance, and style issues. The reviewer still has the final say, but the assistant highlights common problems and speeds up the feedback loop.
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Pattern 3: The Documentation Guardian">
|
||||
Whenever code changes, AI can scan for mismatches in documentation and suggest updates. This keeps docs current without relying on developers to remember every detail.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
## Best Practices for Sustainable Continuous AI
|
||||
|
||||
<CardGroup>
|
||||
<Card title="Human-AI Collaboration" icon="handshake">
|
||||
AI should amplify human intelligence, not replace it. Always validate AI
|
||||
suggestions rather than blindly accepting them.
|
||||
</Card>
|
||||
|
||||
<Card title="Start Small, Scale Thoughtfully" icon="seedling">
|
||||
Begin with low-risk, high-value automations. Gradually expand as you build
|
||||
trust and understanding.
|
||||
</Card>
|
||||
|
||||
<Card title="Customize for Your Context" icon="cog">
|
||||
Generic AI suggestions are often wrong or irrelevant. Configure AI to
|
||||
understand your specific patterns and requirements.
|
||||
</Card>
|
||||
|
||||
<Card title="Build Safety Guardrails" icon="shield">
|
||||
Use permission systems, code review processes, and testing to ensure AI
|
||||
actions are safe and reversible.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Common Pitfalls to Avoid
|
||||
|
||||
<Warning>
|
||||
**Over-automation**: Don't automate processes you don't fully understand
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
**Ignoring Context**: AI works best when it understands your codebase and team
|
||||
practices
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
**Skipping Safety**: Always implement proper permissions and review processes
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
**Vanity Metrics**: Focus on intervention rate and actual time saved, not "AI
|
||||
suggestions generated"
|
||||
</Warning>
|
||||
|
||||
## Getting Started Today
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Continue CLI">
|
||||
```bash npm i -g @continuedev/cli ```
|
||||
</Step>
|
||||
|
||||
<Step title="Pick One Workflow">Choose a daily friction point to automate</Step>
|
||||
|
||||
<Step title="Set Permissions">Configure safe boundaries for AI actions</Step>
|
||||
|
||||
<Step title="Measure Impact">Track intervention rates and time saved</Step>
|
||||
|
||||
<Step title="Iterate and Expand">Gradually add more automated workflows</Step>
|
||||
</Steps>
|
||||
|
||||
## The Competitive Advantage
|
||||
|
||||
Teams implementing Continuous AI are coding faster and building institutional intelligence that scales with their organization. While others manually perform routine tasks, your AI handles the repetitive work so your team can focus on innovation and complex problem-solving.
|
||||
|
||||
## What's Next?
|
||||
|
||||
As AI capabilities continue to improve and tooling matures, we're moving toward a world where intelligent assistance is as fundamental to development as version control or IDEs. The teams that start building these capabilities now will have refined systems, cultural readiness, and institutional knowledge when Continuous AI becomes the industry standard.
|
||||
|
||||
Ready to amplify your development workflow with Continuous AI? Start with one simple automation and build from there.
|
||||
|
||||
<Card title="Want to dive deeper?" icon="rocket">
|
||||
Check out our guides on [Continue CLI](/guides/cli) and [Understanding
|
||||
Assistants](/guides/understanding-assistants).
|
||||
</Card>
|
||||
|
|
@ -34,15 +34,15 @@ curl -fsSL https://ollama.ai/install.sh | sh
|
|||
After installation, start the Ollama service:
|
||||
|
||||
```bash
|
||||
# Check Ollama version - verify it's installed
|
||||
ollama --version
|
||||
|
||||
# Start Ollama (runs in background)
|
||||
ollama serve
|
||||
|
||||
# Verify it's running
|
||||
curl http://localhost:11434
|
||||
# Should return "Ollama is running"
|
||||
|
||||
# Check Ollama version
|
||||
ollama --version
|
||||
```
|
||||
|
||||
### Step 3: Download Models
|
||||
|
|
|
|||
|
|
@ -9,6 +9,11 @@ description: "Comprehensive collection of practical guides for Continue includin
|
|||
- [How to Self-Host a Model](/guides/how-to-self-host-a-model) - Self-hosting AI models
|
||||
- [Running Continue Without Internet](/guides/running-continue-without-internet) - Offline development setup
|
||||
|
||||
## Continuous AI
|
||||
|
||||
- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows
|
||||
- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue
|
||||
|
||||
## What Advanced Tutorials Are Available
|
||||
|
||||
- [Codebase and Documentation Awareness](/guides/codebase-documentation-awareness) - Make your agent aware of codebases and documentation
|
||||
|
|
|
|||
|
|
@ -229,9 +229,18 @@ async function loadUserAssistantWithFallback(
|
|||
|
||||
if (assistants.length > 0) {
|
||||
const result = assistants[0].configResult;
|
||||
if (result.errors?.length || !result.config) {
|
||||
if (!result.config) {
|
||||
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
|
||||
}
|
||||
|
||||
const errors = result.errors;
|
||||
if (errors?.some((e: any) => e.fatal)) {
|
||||
throw new Error(
|
||||
errors.map((e: any) => e.message).join("\n") ??
|
||||
"Failed to load assistant.",
|
||||
);
|
||||
}
|
||||
|
||||
return result.config as AssistantUnrolled;
|
||||
}
|
||||
|
||||
|
|
@ -373,8 +382,12 @@ async function loadAssistantSlug(
|
|||
});
|
||||
|
||||
const result = resp.configResult;
|
||||
if (result.errors?.length || !result.config) {
|
||||
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
|
||||
const errors = result.errors;
|
||||
if (errors?.some((e: any) => e.fatal)) {
|
||||
throw new Error(
|
||||
errors.map((e: any) => e.message).join("\n") ??
|
||||
"Failed to load assistant.",
|
||||
);
|
||||
}
|
||||
|
||||
return result.config as AssistantUnrolled;
|
||||
|
|
|
|||
|
|
@ -1,240 +1,107 @@
|
|||
import { runTerminalCommandTool } from "./runTerminalCommand.js";
|
||||
|
||||
describe("runTerminalCommandTool", () => {
|
||||
const TEST_TIMEOUT_MS = 1000; // 1 second for tests
|
||||
const isWindows = process.platform === "win32";
|
||||
const isMac = process.platform === "darwin";
|
||||
const isLinux = process.platform === "linux";
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.NODE_ENV = "test";
|
||||
process.env.TEST_TERMINAL_TIMEOUT = String(TEST_TIMEOUT_MS);
|
||||
});
|
||||
describe("basic platform-specific terminal execution", () => {
|
||||
it("should execute a simple echo command", async () => {
|
||||
let command: string;
|
||||
let expectedOutput: string;
|
||||
|
||||
afterAll(() => {
|
||||
delete process.env.TEST_TERMINAL_TIMEOUT;
|
||||
});
|
||||
describe("basic command execution", () => {
|
||||
it("should execute simple echo command and return stdout", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'hello world'",
|
||||
});
|
||||
expect(result.trim()).toBe("hello world");
|
||||
if (isWindows) {
|
||||
command = 'Write-Output "hello world"';
|
||||
expectedOutput = "hello world";
|
||||
} else {
|
||||
command = 'echo "hello world"';
|
||||
expectedOutput = "hello world";
|
||||
}
|
||||
|
||||
const result = await runTerminalCommandTool.run({ command });
|
||||
expect(result.trim()).toBe(expectedOutput);
|
||||
});
|
||||
|
||||
it("should execute pwd command and return current directory", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "pwd" });
|
||||
expect(result.trim()).toMatch(/^\/.*$/); // Should be an absolute path
|
||||
});
|
||||
it("should get current directory", async () => {
|
||||
let command: string;
|
||||
|
||||
if (isWindows) {
|
||||
command = "Get-Location | Select-Object -ExpandProperty Path";
|
||||
} else {
|
||||
command = "pwd";
|
||||
}
|
||||
|
||||
it("should execute directory listing command and return file listings", async () => {
|
||||
// Use a cross-platform command that works on both Unix and Windows
|
||||
const command = process.platform === "win32" ? "dir" : "ls -la .";
|
||||
const result = await runTerminalCommandTool.run({ command });
|
||||
|
||||
// On Windows, look for <DIR> entries, on Unix look for . and ..
|
||||
if (process.platform === "win32") {
|
||||
expect(result).toContain(".");
|
||||
if (isWindows) {
|
||||
// Windows paths like C:\path\to\dir
|
||||
expect(result.trim()).toMatch(/^[A-Za-z]:\\.*/);
|
||||
} else {
|
||||
expect(result).toContain(".");
|
||||
expect(result).toContain("..");
|
||||
// Unix paths like /path/to/dir
|
||||
expect(result.trim()).toMatch(/^\/.*$/);
|
||||
}
|
||||
});
|
||||
|
||||
it("should handle commands with multiple arguments", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'arg1' 'arg2' 'arg3'",
|
||||
});
|
||||
expect(result.trim()).toBe("arg1 arg2 arg3");
|
||||
it("should list directory contents", async () => {
|
||||
let command: string;
|
||||
|
||||
if (isWindows) {
|
||||
command = "Get-ChildItem | Select-Object -ExpandProperty Name";
|
||||
} else {
|
||||
command = "ls";
|
||||
}
|
||||
|
||||
const result = await runTerminalCommandTool.run({ command });
|
||||
// Should return some directory content (not empty)
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("should handle command that produces version info", async () => {
|
||||
// Node.js should be available on all platforms in CI
|
||||
const command = "node --version";
|
||||
const result = await runTerminalCommandTool.run({ command });
|
||||
|
||||
// Should contain version number (starts with v)
|
||||
expect(result.trim()).toMatch(/^v\d+\.\d+\.\d+/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should reject with error message for non-existent commands", async () => {
|
||||
await expect(
|
||||
runTerminalCommandTool.run({ command: "nonexistentcommand12345" }),
|
||||
).rejects.toMatch(/Error \(exit code 127\):/);
|
||||
});
|
||||
describe("basic error handling", () => {
|
||||
it("should handle non-existent commands", async () => {
|
||||
const command = "definitely-not-a-real-command-xyz123";
|
||||
|
||||
it("should handle commands with non-zero exit codes and stderr", async () => {
|
||||
await expect(
|
||||
runTerminalCommandTool.run({
|
||||
command: "sh -c 'echo error >&2; exit 1'",
|
||||
}),
|
||||
).rejects.toMatch(/Error \(exit code 1\): error/);
|
||||
});
|
||||
|
||||
it("should resolve when commands have non-zero exit codes but no stderr", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "sh -c 'exit 1'",
|
||||
});
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it("should handle commands that write to stderr", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: 'sh -c \'echo "error message" >&2; echo "success"\'',
|
||||
});
|
||||
expect(result).toContain("success");
|
||||
expect(result).toContain("Stderr: error message");
|
||||
});
|
||||
});
|
||||
|
||||
describe("timeout functionality", () => {
|
||||
it(
|
||||
"should timeout commands that produce no output for configured duration",
|
||||
async () => {
|
||||
// Create a command that sleeps longer than the timeout
|
||||
const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep 0.5s longer than timeout
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `sleep ${sleepDuration}`,
|
||||
});
|
||||
const endTime = Date.now();
|
||||
const elapsed = endTime - startTime;
|
||||
|
||||
// Should timeout within a reasonable margin of the configured timeout
|
||||
expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin
|
||||
expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin
|
||||
expect(result).toContain(
|
||||
`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`,
|
||||
);
|
||||
},
|
||||
TEST_TIMEOUT_MS + 2000,
|
||||
); // Set test timeout with buffer
|
||||
|
||||
it(
|
||||
"should not timeout commands that continuously produce output",
|
||||
async () => {
|
||||
// Create a command that produces output at intervals shorter than timeout
|
||||
const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
|
||||
const iterations = 3;
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `for i in $(seq 1 ${iterations}); do echo "output $i"; sleep ${outputInterval}; done`,
|
||||
});
|
||||
const endTime = Date.now();
|
||||
|
||||
// Should complete normally
|
||||
expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
|
||||
expect(result).toContain("output 1");
|
||||
expect(result).toContain(`output ${iterations}`);
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
},
|
||||
TEST_TIMEOUT_MS * 3,
|
||||
); // Set test timeout with buffer
|
||||
|
||||
it(
|
||||
"should reset timeout when command produces stderr output",
|
||||
async () => {
|
||||
// Create a command that produces stderr output periodically
|
||||
const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
|
||||
const iterations = 3;
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `for i in $(seq 1 ${iterations}); do echo "error $i" >&2; sleep ${outputInterval}; done; echo 'done'`,
|
||||
});
|
||||
const endTime = Date.now();
|
||||
|
||||
// Should complete normally
|
||||
expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
|
||||
expect(result).toContain("done");
|
||||
expect(result).toContain("Stderr: error 1");
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
},
|
||||
TEST_TIMEOUT_MS * 3,
|
||||
); // Set test timeout with buffer
|
||||
|
||||
it(
|
||||
"should include partial output when timing out",
|
||||
async () => {
|
||||
// Create a command that produces some output then stops
|
||||
const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep longer than timeout
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `echo 'initial output'; sleep ${sleepDuration}`,
|
||||
});
|
||||
|
||||
expect(result).toContain("initial output");
|
||||
expect(result).toContain(
|
||||
`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`,
|
||||
);
|
||||
},
|
||||
TEST_TIMEOUT_MS + 2000,
|
||||
); // Set test timeout with buffer
|
||||
});
|
||||
|
||||
describe("output handling", () => {
|
||||
it("should preserve line breaks in output", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "printf 'line1\\nline2\\nline3'",
|
||||
});
|
||||
expect(result).toContain("line1\nline2\nline3");
|
||||
});
|
||||
|
||||
it("should handle empty output", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "true" });
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it("should handle large output", async () => {
|
||||
// Generate a command that produces substantial output
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "seq 1 1000",
|
||||
});
|
||||
expect(result).toContain("1\n");
|
||||
expect(result).toContain("1000");
|
||||
// Count lines to ensure all output is captured
|
||||
const lines = result.trim().split("\n");
|
||||
expect(lines).toHaveLength(1000);
|
||||
});
|
||||
|
||||
it("should truncate output when it exceeds 5000 lines", async () => {
|
||||
// Generate a command that produces more than 5000 lines
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "seq 1 6000",
|
||||
});
|
||||
|
||||
// Should contain the truncation message
|
||||
expect(result).toContain(
|
||||
"[Output truncated to first 5000 lines of 6001 total]",
|
||||
await expect(runTerminalCommandTool.run({ command })).rejects.toMatch(
|
||||
/Error \(exit code|Command timed out|not found|not recognized/,
|
||||
);
|
||||
|
||||
// Should contain first line
|
||||
expect(result).toContain("1\n");
|
||||
|
||||
// Should contain line 5000 but not line 6000
|
||||
expect(result).toContain("5000");
|
||||
expect(result).not.toContain("6000");
|
||||
|
||||
// Count lines in the result - should be 5000 content lines + 2 truncation message lines
|
||||
const lines = result.split("\n");
|
||||
expect(lines).toHaveLength(5002); // 5000 content lines + empty line + truncation message
|
||||
});
|
||||
});
|
||||
|
||||
describe("command types", () => {
|
||||
it("should handle shell built-ins", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "echo $PWD" });
|
||||
expect(result.trim()).toMatch(/^\/.*$/);
|
||||
});
|
||||
|
||||
it("should handle commands with pipes", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'hello world' | wc -w",
|
||||
describe("platform-specific features", () => {
|
||||
if (isWindows) {
|
||||
it("should work with Windows commands", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "Write-Output $env:OS",
|
||||
});
|
||||
expect(result.trim()).toBe("Windows_NT");
|
||||
});
|
||||
expect(result.trim()).toBe("2");
|
||||
});
|
||||
}
|
||||
|
||||
it("should handle commands with redirections", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command:
|
||||
"echo 'test' > /tmp/test-file && cat /tmp/test-file && rm /tmp/test-file",
|
||||
if (isMac) {
|
||||
it("should work with macOS commands", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "uname -s",
|
||||
});
|
||||
expect(result.trim()).toBe("Darwin");
|
||||
});
|
||||
expect(result.trim()).toBe("test");
|
||||
});
|
||||
}
|
||||
|
||||
it("should handle commands with environment variables", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "TEST_VAR='hello' sh -c 'echo $TEST_VAR'",
|
||||
if (isLinux) {
|
||||
it("should work with Linux commands", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "uname -s",
|
||||
});
|
||||
expect(result.trim()).toBe("Linux");
|
||||
});
|
||||
expect(result.trim()).toBe("hello");
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,6 +8,21 @@ import {
|
|||
|
||||
import { Tool } from "./types.js";
|
||||
|
||||
// Helper function to use login shell on Unix/macOS and PowerShell on Windows
|
||||
function getShellCommand(command: string): { shell: string; args: string[] } {
|
||||
if (process.platform === "win32") {
|
||||
// Windows: Use PowerShell
|
||||
return {
|
||||
shell: "powershell.exe",
|
||||
args: ["-NoLogo", "-ExecutionPolicy", "Bypass", "-Command", command],
|
||||
};
|
||||
} else {
|
||||
// Unix/macOS: Use login shell to source .bashrc/.zshrc etc.
|
||||
const userShell = process.env.SHELL || "/bin/bash";
|
||||
return { shell: userShell, args: ["-l", "-c", command] };
|
||||
}
|
||||
}
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
name: "Bash",
|
||||
displayName: "Bash",
|
||||
|
|
@ -43,7 +58,9 @@ The command will be executed from the current working directory: ${process.cwd()
|
|||
},
|
||||
run: async ({ command }: { command: string }): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn("sh", ["-c", command]);
|
||||
// Use same shell logic as core implementation
|
||||
const { shell, args } = getShellCommand(command);
|
||||
const child = spawn(shell, args);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let timeoutId: NodeJS.Timeout;
|
||||
|
|
|
|||
|
|
@ -22,19 +22,19 @@
|
|||
|
||||
## Agent
|
||||
|
||||
[Agent](/features/agent/quick-start) to work on development tasks together with AI
|
||||
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
|
||||
|
||||
## Chat
|
||||
|
||||
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
|
||||
## Edit
|
||||
|
||||
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
|
||||
## Autocomplete
|
||||
|
||||
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -59,13 +59,24 @@ intellijPlatform {
|
|||
sinceBuild = "241"
|
||||
}
|
||||
}
|
||||
publishing {
|
||||
token = environment("PUBLISH_TOKEN")
|
||||
hidden = true
|
||||
val channel = if (isEap) "eap" else "default"
|
||||
channels = listOf(channel)
|
||||
}
|
||||
signing {
|
||||
certificateChain = environment("CERTIFICATE_CHAIN")
|
||||
privateKey = environment("PRIVATE_KEY")
|
||||
password = environment("PRIVATE_KEY_PASSWORD")
|
||||
}
|
||||
pluginVerification {
|
||||
ides {
|
||||
ide("IC", "2025.2")
|
||||
ide("IC", "2025.1")
|
||||
ide("IC", "2024.3")
|
||||
ide("IC", "2024.2")
|
||||
ide("IC", "2024.1")
|
||||
create("IC", "2025.2")
|
||||
create("IC", "2025.1")
|
||||
create("IC", "2024.3")
|
||||
create("IC", "2024.2")
|
||||
create("IC", "2024.1")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -122,19 +133,6 @@ tasks {
|
|||
check(pluginDescription.get().isNotEmpty()) { "Plugin description section not found in README.md" }
|
||||
}
|
||||
|
||||
signPlugin {
|
||||
certificateChain = environment("CERTIFICATE_CHAIN")
|
||||
privateKey = environment("PRIVATE_KEY")
|
||||
password = environment("PRIVATE_KEY_PASSWORD")
|
||||
}
|
||||
|
||||
publishPlugin {
|
||||
token = environment("PUBLISH_TOKEN")
|
||||
|
||||
val channel = if (isEap) "eap" else "default"
|
||||
channels = listOf(channel)
|
||||
}
|
||||
|
||||
runIde {
|
||||
val openProject = "$projectDir/../../manual-testing-sandbox"
|
||||
argumentProviders += CommandLineArgumentProvider {
|
||||
|
|
|
|||
|
|
@ -266,7 +266,8 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
project.service<ContinuePluginDisposable>()
|
||||
)
|
||||
|
||||
continuePluginService.coreMessenger = CoreMessenger(project, ideProtocolClient, coroutineScope)
|
||||
val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope)
|
||||
continuePluginService.coreMessengerManager = coreMessengerManager
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,9 +5,11 @@ import com.github.continuedev.continueintellijextension.constants.MessageTypes
|
|||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueBinaryProcess
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueProcessHandler
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.ContinueSocketProcess
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonSyntaxException
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
|
|
@ -15,14 +17,13 @@ import kotlinx.coroutines.CoroutineScope
|
|||
class CoreMessenger(
|
||||
private val project: Project,
|
||||
private val ideProtocolClient: IdeProtocolClient,
|
||||
|
||||
// todo: this scope is public only to cancel the coroutines on dispose in ContinuePluginService
|
||||
// todo: scope is created in ContinuePluginStartupActivity; refactor this/clean this up/encapsulate
|
||||
val coroutineScope: CoroutineScope
|
||||
val coroutineScope: CoroutineScope,
|
||||
private val onUnexpectedExit: () -> Unit
|
||||
) {
|
||||
private val gson = Gson()
|
||||
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
|
||||
private val process = startContinueProcess()
|
||||
private var process = startContinueProcess()
|
||||
private val log = Logger.getInstance(CoreMessenger::class.java.simpleName)
|
||||
|
||||
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
|
||||
val id = messageId ?: uuid()
|
||||
|
|
@ -33,15 +34,14 @@ class CoreMessenger(
|
|||
|
||||
private fun startContinueProcess(): ContinueProcessHandler {
|
||||
val isTcp = System.getenv("USE_TCP")?.toBoolean() ?: false
|
||||
return ContinueProcessHandler(coroutineScope, ::readProcessMessage) {
|
||||
if (isTcp)
|
||||
ContinueSocketProcess()
|
||||
else
|
||||
ContinueBinaryProcess()
|
||||
}
|
||||
val process = if (isTcp)
|
||||
ContinueSocketProcess()
|
||||
else
|
||||
ContinueBinaryProcess(onUnexpectedExit)
|
||||
return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
|
||||
}
|
||||
|
||||
private fun readProcessMessage(json: String) {
|
||||
private fun handleMessage(json: String) {
|
||||
val responseMap = tryToParse(json) ?: return
|
||||
val messageId = responseMap["messageId"].toString()
|
||||
val messageType = responseMap["messageType"].toString()
|
||||
|
|
@ -76,16 +76,19 @@ class CoreMessenger(
|
|||
try {
|
||||
gson.fromJson(json, Map::class.java)
|
||||
} catch (_: JsonSyntaxException) {
|
||||
LOG.warn("Invalid message JSON: $json") // example: NODE_ENV undefined
|
||||
log.warn("Invalid message JSON: $json") // example: NODE_ENV undefined
|
||||
null
|
||||
}
|
||||
|
||||
fun restart() {
|
||||
log.warn("Restarting Continue process")
|
||||
responseListeners.clear()
|
||||
process.restart()
|
||||
process.close()
|
||||
process = startContinueProcess()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private val LOG = Logger.getInstance(CoreMessenger::class.java.simpleName)
|
||||
fun close() {
|
||||
log.warn("Closing Continue process")
|
||||
process.close()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class CoreMessengerManager(
|
||||
project: Project,
|
||||
ideProtocolClient: IdeProtocolClient,
|
||||
private val coroutineScope: CoroutineScope
|
||||
) {
|
||||
val coreMessenger = CoreMessenger(project, ideProtocolClient, coroutineScope, ::onUnexpectedExit)
|
||||
private var backoffIntervalSeconds = 1
|
||||
private val log = Logger.getInstance(CoreMessengerManager::class.java)
|
||||
|
||||
private fun onUnexpectedExit() {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
delay(backoffIntervalSeconds.seconds)
|
||||
backoffIntervalSeconds *= 2
|
||||
log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds")
|
||||
coreMessenger.restart()
|
||||
} catch (e: Exception) {
|
||||
service<ContinuePostHogService>().capture("jetbrains_core_start_error", mapOf("error" to e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
/**
|
||||
* Starts at [initialDuration] and doubles on each call to [nextDuration] up to [maxDuration].
|
||||
*/
|
||||
class BackoffCalculator(
|
||||
private val initialDuration: Duration = 1.seconds,
|
||||
private val maxDuration: Duration = 30.seconds
|
||||
) {
|
||||
private var currentTime: Duration = initialDuration
|
||||
|
||||
init {
|
||||
require(initialDuration > 0.seconds)
|
||||
}
|
||||
|
||||
fun nextDuration(): Duration {
|
||||
val delay = currentTime
|
||||
val next = currentTime * 2.0
|
||||
currentTime = if (next <= maxDuration) next else maxDuration
|
||||
return delay
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,12 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
|
||||
import com.github.continuedev.continueintellijextension.proxy.ProxySettings
|
||||
import com.github.continuedev.continueintellijextension.utils.OS
|
||||
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
|
||||
import com.github.continuedev.continueintellijextension.utils.getOS
|
||||
import com.intellij.openapi.components.service
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.io.File
|
||||
|
|
@ -13,27 +16,47 @@ import java.nio.file.Files
|
|||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
class ContinueBinaryProcess() : ContinueProcess {
|
||||
class ContinueBinaryProcess(
|
||||
private val onUnexpectedExit: () -> Unit
|
||||
) : ContinueProcess {
|
||||
|
||||
private val process = start()
|
||||
private val process = startBinaryProcess()
|
||||
override val input: InputStream = process.inputStream
|
||||
override val output: OutputStream = process.outputStream
|
||||
|
||||
override fun close() =
|
||||
process.destroy()
|
||||
|
||||
private companion object {
|
||||
|
||||
private fun start(): Process {
|
||||
val path = getContinueBinaryPath()
|
||||
private fun startBinaryProcess(): Process {
|
||||
val path = getContinueBinaryPath()
|
||||
runBlocking(Dispatchers.IO) {
|
||||
setPermissions()
|
||||
val builder = ProcessBuilder(path)
|
||||
builder.environment() += ProxySettings.getSettings().toContinueEnvVars()
|
||||
return builder
|
||||
.directory(File(path).parentFile)
|
||||
.start()
|
||||
}
|
||||
|
||||
val builder = ProcessBuilder(path)
|
||||
builder.environment() += ProxySettings.getSettings().toContinueEnvVars()
|
||||
return builder
|
||||
.directory(File(path).parentFile)
|
||||
.start()
|
||||
.apply { onExit().thenRun(onUnexpectedExit).thenRun(::reportErrorTelemetry) }
|
||||
}
|
||||
|
||||
private fun reportErrorTelemetry() {
|
||||
var err = process.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
if (err != null) {
|
||||
// There are often "⚡️Done in Xms" messages, and we want everything after the last one
|
||||
val delimiter = "⚡ Done in"
|
||||
val doneIndex = err.lastIndexOf(delimiter)
|
||||
if (doneIndex != -1) {
|
||||
err = err.substring(doneIndex + delimiter.length)
|
||||
}
|
||||
}
|
||||
service<ContinueSentryService>().reportMessage("Core process exited with output: $err")
|
||||
service<ContinuePostHogService>().capture("jetbrains_core_exit", mapOf("error" to err))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
private fun setPermissions() {
|
||||
val os = getOS()
|
||||
when (os) {
|
||||
|
|
|
|||
|
|
@ -1,62 +1,49 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import com.github.continuedev.continueintellijextension.error.ContinuePostHogService
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import java.io.BufferedReader
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
|
||||
class ContinueProcessHandler(
|
||||
private val parentScope: CoroutineScope,
|
||||
private val readMessage: (String) -> (Unit),
|
||||
private val createProcess: () -> ContinueProcess
|
||||
parentScope: CoroutineScope,
|
||||
private val process: ContinueProcess,
|
||||
handleMessage: (String) -> (Unit)
|
||||
) {
|
||||
private val innerJob = Job()
|
||||
private val scope = CoroutineScope(parentScope.coroutineContext + innerJob)
|
||||
private val pendingWrites = Channel<String>(Channel.UNLIMITED)
|
||||
private val backoff = BackoffCalculator()
|
||||
private var processScope: CoroutineScope? = null
|
||||
private var process: ContinueProcess? = null
|
||||
private val writer = OutputStreamWriter(process.output)
|
||||
private val reader = BufferedReader(InputStreamReader(process.input))
|
||||
private val log = Logger.getInstance(ContinueProcessHandler::class.java)
|
||||
|
||||
init {
|
||||
restart()
|
||||
}
|
||||
|
||||
fun restart() {
|
||||
LOG.warn("Starting Continue process")
|
||||
processScope?.cancel()
|
||||
process?.close()
|
||||
|
||||
val handler = CoroutineExceptionHandler { _, e ->
|
||||
service<ContinueSentryService>().report(e)
|
||||
service<ContinuePostHogService>().capture("jetbrains_core_exit", mapOf("error" to e))
|
||||
|
||||
val backoffDuration = backoff.nextDuration()
|
||||
LOG.warn("Process failed! Restarting in $backoffDuration")
|
||||
parentScope.launch {
|
||||
delay(backoffDuration)
|
||||
restart()
|
||||
scope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
while (isActive) {
|
||||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
try {
|
||||
log.debug("Handle: $line")
|
||||
handleMessage(line)
|
||||
} catch (e: Exception) {
|
||||
service<ContinueSentryService>().report(e, "Error handling message: $line")
|
||||
}
|
||||
} else
|
||||
delay(100)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
service<ContinueSentryService>().report(e)
|
||||
}
|
||||
}
|
||||
|
||||
val job = SupervisorJob(parentScope.coroutineContext.job)
|
||||
processScope = CoroutineScope(parentScope.coroutineContext + job + handler)
|
||||
process = createProcess()
|
||||
|
||||
val reader = BufferedReader(InputStreamReader(process!!.input))
|
||||
val writer = OutputStreamWriter(process!!.output)
|
||||
|
||||
processScope!!.launch(Dispatchers.IO) {
|
||||
while (isActive) {
|
||||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty())
|
||||
readMessage(line)
|
||||
}
|
||||
}
|
||||
processScope!!.launch(Dispatchers.IO) {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
for (message in pendingWrites) {
|
||||
log.debug("Write: $message")
|
||||
writer.write(message)
|
||||
writer.write("\r\n")
|
||||
writer.flush()
|
||||
|
|
@ -67,7 +54,12 @@ class ContinueProcessHandler(
|
|||
fun write(message: String) =
|
||||
pendingWrites.trySend(message)
|
||||
|
||||
private companion object {
|
||||
private val LOG = Logger.getInstance(ContinueProcessHandler::class.java.simpleName)
|
||||
fun close() {
|
||||
innerJob.cancel()
|
||||
scope.launch(Dispatchers.IO) {
|
||||
reader.close()
|
||||
writer.close()
|
||||
process.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ class ProxyPoolingActivity : StartupActivity {
|
|||
|
||||
private fun onSettingsChanged(project: Project) {
|
||||
log.warn("Proxy settings changed, restarting")
|
||||
project.service<ContinuePluginService>().coreMessenger?.restart()
|
||||
project.service<ContinuePluginService>().coreMessengerManager?.coreMessenger?.restart()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ package com.github.continuedev.continueintellijextension.services
|
|||
|
||||
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueSentryService
|
||||
import com.intellij.openapi.application.ApplicationInfo
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.PersistentStateComponent
|
||||
import com.intellij.openapi.components.State
|
||||
|
|
@ -13,8 +13,6 @@ import com.intellij.openapi.project.DumbAware
|
|||
import com.intellij.util.concurrency.AppExecutorUtil
|
||||
import com.intellij.util.io.HttpRequests
|
||||
import com.intellij.util.messages.Topic
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.awt.GridBagConstraints
|
||||
import java.awt.GridBagLayout
|
||||
import java.io.File
|
||||
|
|
@ -118,12 +116,12 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
|
|||
val baseUrl = remoteServerUrl.removeSuffix("/")
|
||||
try {
|
||||
val url = "$baseUrl/sync"
|
||||
val responseBody = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
|
||||
val responseBody = HttpRequests.request(url)
|
||||
.tuner { connection ->
|
||||
if (token != null)
|
||||
connection.addRequestProperty("Authorization", "Bearer $token")
|
||||
}.readString()
|
||||
val response = Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
|
||||
val response = Gson().fromJson(responseBody, ContinueRemoteConfigSyncResponse::class.java)
|
||||
val file = File(getConfigJsonPath(URL(url).host))
|
||||
response.configJs.let { file.writeText(it!!) }
|
||||
response.configJson.let { file.writeText(it!!) }
|
||||
|
|
|
|||
|
|
@ -1,28 +1,34 @@
|
|||
package com.github.continuedev.continueintellijextension.services
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
|
||||
import com.github.continuedev.continueintellijextension.`continue`.DiffManager
|
||||
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
|
||||
import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager
|
||||
import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker
|
||||
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.EditorFactory
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.Disposer
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlin.properties.Delegates
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ContinuePluginService(private val project: Project) : Disposable, DumbAware {
|
||||
class ContinuePluginService(private val project: Project) : DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main)
|
||||
var listener: (() -> Unit)? = null
|
||||
var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ ->
|
||||
synchronized(this) { listener?.also { listener = null }?.invoke() }
|
||||
}
|
||||
var coreMessenger: CoreMessenger? = null
|
||||
var coreMessengerManager: CoreMessengerManager? = null
|
||||
val coreMessenger: CoreMessenger?
|
||||
get() = coreMessengerManager?.coreMessenger
|
||||
var workspacePaths: Array<String>? = null
|
||||
var windowId: String = uuid()
|
||||
var diffManager: DiffManager? = null
|
||||
|
|
@ -51,6 +57,14 @@ class ContinuePluginService(private val project: Project) : Disposable, DumbAwar
|
|||
}
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
coroutineScope.cancel()
|
||||
coreMessenger?.coroutineScope?.let {
|
||||
it.cancel()
|
||||
coreMessenger?.close()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a listener for protocolClient initialization.
|
||||
* Currently, only one needs to be processed. If there are more than one,
|
||||
|
|
@ -69,8 +83,4 @@ class ContinuePluginService(private val project: Project) : Disposable, DumbAwar
|
|||
listener()
|
||||
}
|
||||
}
|
||||
|
||||
override fun dispose() {
|
||||
coreMessenger?.coroutineScope?.cancel()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.process.BackoffCalculator
|
||||
import junit.framework.TestCase
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class BackoffCalculatorTest : TestCase() {
|
||||
|
||||
fun `test backoff`() {
|
||||
val backoff = BackoffCalculator(initialDuration = 1.seconds, maxDuration = 30.seconds)
|
||||
assertEquals(1.seconds, backoff.nextDuration())
|
||||
assertEquals(2.seconds, backoff.nextDuration())
|
||||
assertEquals(4.seconds, backoff.nextDuration())
|
||||
assertEquals(8.seconds, backoff.nextDuration())
|
||||
assertEquals(16.seconds, backoff.nextDuration())
|
||||
assertEquals(30.seconds, backoff.nextDuration())
|
||||
assertEquals(30.seconds, backoff.nextDuration())
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -30,25 +30,25 @@
|
|||
|
||||
## Agent
|
||||
|
||||
[Agent](/features/agent/quick-start) to work on development tasks together with AI
|
||||
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
|
||||
|
||||

|
||||
|
||||
## Chat
|
||||
|
||||
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
|
||||

|
||||
|
||||
## Edit
|
||||
|
||||
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
|
||||

|
||||
|
||||
## Autocomplete
|
||||
|
||||
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -66,6 +66,12 @@ export interface CompletionDataForAfterJump {
|
|||
currentPosition: vscode.Position;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is how we handle jumps and manage decoration object lifetime.
|
||||
* There are mainly three states the user can be in: not jumping, jumping in progress, and just jumped.
|
||||
* This can potentially be an enum for better readability, but there is logic here that relies on
|
||||
* the _jumpAccepted flag to determine whether we should delete chains.
|
||||
*/
|
||||
export class JumpManager {
|
||||
private static _instance: JumpManager | undefined;
|
||||
|
||||
|
|
@ -119,10 +125,6 @@ export class JumpManager {
|
|||
}
|
||||
|
||||
private _createSvgJumpIcon() {
|
||||
// if (!this._theme) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
const baseTextConfig = {
|
||||
y: SVG_CONFIG.getTextY(),
|
||||
"font-family": SVG_CONFIG.getFontFamily(),
|
||||
|
|
@ -130,6 +132,9 @@ export class JumpManager {
|
|||
};
|
||||
|
||||
try {
|
||||
// NOTE: it's critical to use svgBuilder.newInstance.
|
||||
// svgBuilder holds state of previously created SVGs,
|
||||
// so you end up with SVGs stacking on top of each other and being interleaved.
|
||||
const builder = svgBuilder.newInstance
|
||||
? svgBuilder.newInstance()
|
||||
: svgBuilder;
|
||||
|
|
@ -295,15 +300,6 @@ export class JumpManager {
|
|||
await this.clearJumpDecoration();
|
||||
|
||||
// Create a decoration for jump.
|
||||
// this._jumpDecoration = vscode.window.createTextEditorDecorationType({
|
||||
// before: {
|
||||
// contentText: "📍 Press Tab to jump, Esc to cancel",
|
||||
// color: new vscode.ThemeColor("editor.foreground"),
|
||||
// backgroundColor: new vscode.ThemeColor("editorHover.background"),
|
||||
// margin: `0 0 0 4px`,
|
||||
// },
|
||||
// });
|
||||
|
||||
if (!this._jumpDecoration) {
|
||||
this._createSvgJumpIcon(); // makes both the icon & decoration
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,6 +97,11 @@ export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND =
|
|||
export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND =
|
||||
"continue.nextEditWindow.acceptNextEditSuggestion";
|
||||
|
||||
/**
|
||||
* This is where we create SVG windows and deletion decorations for non-FIM next edit suggestions.
|
||||
* This class controls the decoration object lifetime.
|
||||
* The syntax highlighting and the actual building of SVG happens inside core/codeRenderer/CodeRenderer.ts.
|
||||
*/
|
||||
export class NextEditWindowManager {
|
||||
private static instance: NextEditWindowManager | undefined;
|
||||
|
||||
|
|
@ -492,9 +497,6 @@ export class NextEditWindowManager {
|
|||
this.mostRecentCompletionId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept the current next edit suggestion by inserting it at cursor position.
|
||||
*/
|
||||
/**
|
||||
* Accept the current next edit suggestion by inserting it at cursor position.
|
||||
*/
|
||||
|
|
@ -840,15 +842,6 @@ export class NextEditWindowManager {
|
|||
editor: vscode.TextEditor,
|
||||
position: vscode.Position,
|
||||
): vscode.Position {
|
||||
// Create a position that's offset spaces to the right of the cursor.
|
||||
|
||||
// const line = editor.document.lineAt(position.line);
|
||||
// const offsetChar = Math.min(
|
||||
// position.character + SVG_CONFIG.cursorOffset,
|
||||
// line.text.length,
|
||||
// );
|
||||
// return new vscode.Position(position.line, offsetChar);
|
||||
|
||||
// Place decoration at the end of the current line
|
||||
const line = editor.document.lineAt(position.line);
|
||||
return new vscode.Position(position.line, line.text.length);
|
||||
|
|
|
|||
|
|
@ -106,6 +106,8 @@ interface HandlerRegistration {
|
|||
* - After current event is processed, queued events are handled sequentially.
|
||||
* - Ensures all events are processed in the order they were received.
|
||||
* - NOTE: I'm not sure if we even want to queue these events...
|
||||
*
|
||||
* Case n: Other cases that I didn't catch.
|
||||
*/
|
||||
export class SelectionChangeManager {
|
||||
private static instance: SelectionChangeManager;
|
||||
|
|
|
|||
|
|
@ -141,6 +141,12 @@ export class ContinueCompletionProvider
|
|||
this.prefetchQueue.initialize(this.usingFullFileDiff);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the entry point to the autocomplete and next edit logic.
|
||||
* @param document The text document containing the current cursor position.
|
||||
* @param position The current cursor position.
|
||||
* @param context Contextual information about the inline completion request.
|
||||
*/
|
||||
public async provideInlineCompletionItems(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
|
|
@ -154,6 +160,11 @@ export class ContinueCompletionProvider
|
|||
// 2. Jumping (chain exists, jump was taken)
|
||||
// 3. Accepting (chain exists, jump is not taken)
|
||||
|
||||
/* START OF CONTEXT GATHERING BOILERPLATE */
|
||||
|
||||
// The code in this block is meant for gathering context for autocomplete and next edit requests.
|
||||
// e.g. filepath, cursor position, editor, notebook-ness, etc.
|
||||
|
||||
const enableTabAutocomplete =
|
||||
getStatusBarStatus() === StatusBarStatus.Enabled;
|
||||
if (token.isCancellationRequested || !enableTabAutocomplete) {
|
||||
|
|
@ -279,12 +290,44 @@ export class ContinueCompletionProvider
|
|||
recentlyEditedRanges,
|
||||
};
|
||||
|
||||
/* END OF CONTEXT GATHERING BOILERPLATE */
|
||||
|
||||
/* START OF MODEL OUTCOME RECEIVING BLOCK */
|
||||
|
||||
// Throughout this function, we choose whether we want an autocomplete or a next edit request.
|
||||
// The conditional logic below is pretty convoluted, so it would be a good idea to refactor.
|
||||
// The idea was to re-use as much code as possible, but in hindsight I should've just made different functions.
|
||||
// this.isNextEditActive is the boolean that determines whether we use autocomplete vs. next edit.
|
||||
|
||||
// You will also see mentions of this.usingFullFileDiff.
|
||||
// This was initially a flag for whether we should let the model output a full file as an output (or to the best of its abilities).
|
||||
// It ended up becoming a Mercury Coder vs. non-Mercury Coder flag, and is now used to determine whether we should prefetch next edits.
|
||||
// This is a good place to refactor on.
|
||||
// In the future, it will be desirable to have a map where we split models into different next edit requirements and capabilities,
|
||||
// Then use the model's name to retrieve all of its requirements (or better yet, have a model-specific logic inside children class).
|
||||
|
||||
// Prefetching is also a relic of the past.
|
||||
// Before, I envisioned that we should call the model in the background to get next next edits.
|
||||
// Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea.
|
||||
|
||||
let outcome: AutocompleteOutcome | NextEditOutcome | undefined;
|
||||
|
||||
// TODO: We can probably decide here if we want to do the jumping logic.
|
||||
// If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager.
|
||||
// It would simplify the logic quite substantially.
|
||||
|
||||
// Here, we introduce the concept of jumping and chains.
|
||||
// Jump and chain are next edit-specific concepts, and autocomplete has nothing to do with it.
|
||||
// Next edit is rendered to the users in three modes:
|
||||
// 1. Default. This is the case where the user either hasn't seen a next edit suggestion, or has rejected the previous one.
|
||||
// We would render either a ghost text or an SVG with deletion decoration.
|
||||
|
||||
// 2. Jumping. This is the case where the user has just accepted a suggestion, and there are more suggestions in the chain to jump to.
|
||||
// We would render a Jump label suggesting the user to take the jump or reject.
|
||||
|
||||
// 3. Jumped. This is when the user just accepted the jump.
|
||||
// We grab the next edit suggestion from the chain and render that instead of calling the model.
|
||||
|
||||
// Determine why this method was triggered.
|
||||
const isJumping = this.jumpManager.isJumpInProgress();
|
||||
const chainExists = this.nextEditProvider.chainExists();
|
||||
|
|
@ -363,8 +406,8 @@ export class ContinueCompletionProvider
|
|||
currentPosition: jumpPosition,
|
||||
});
|
||||
|
||||
// Don't display anything yet.
|
||||
// This will be handled in Case 2.
|
||||
// Don't display anything yet. This will be handled in Case 2.
|
||||
// Recall from above that provideInlineCompletions runs on every cursor movement.
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
@ -378,7 +421,6 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
} else {
|
||||
// Case 1: Typing (chain does not exist).
|
||||
|
||||
this.nextEditProvider.startChain();
|
||||
|
||||
const input: AutocompleteInput = {
|
||||
|
|
@ -397,15 +439,14 @@ export class ContinueCompletionProvider
|
|||
{ withChain: false, usingFullFileDiff: this.usingFullFileDiff },
|
||||
);
|
||||
|
||||
// Start prefetching next edits.
|
||||
// NOTE: this might be better off not awaited.
|
||||
// Start prefetching next edits if not using full file diff.
|
||||
// NOTE: this is better off not awaited. fire and forget.
|
||||
if (!this.usingFullFileDiff) {
|
||||
this.prefetchQueue.process(ctx);
|
||||
}
|
||||
|
||||
// If initial outcome is null, suggest a jump instead.
|
||||
// Calling this method again will call it with
|
||||
// chain active but jump not suggested yet.
|
||||
// Calling this method again will call it with chain active but jump not suggested yet.
|
||||
if (
|
||||
!outcome ||
|
||||
(!outcome.completion && outcome.diffLines.length === 0)
|
||||
|
|
@ -465,8 +506,8 @@ export class ContinueCompletionProvider
|
|||
return null;
|
||||
}
|
||||
|
||||
// Marking the outcome as displayed saves the current outcome
|
||||
// as a value of the key completionId.
|
||||
// Marking the outcome as displayed saves the current outcome as a value of the key completionId.
|
||||
// NOTE: It seems like autocomplete relies on this to be considered accepted.
|
||||
if (this.isNextEditActive) {
|
||||
this.nextEditProvider.markDisplayed(
|
||||
completionId,
|
||||
|
|
@ -480,6 +521,15 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
this._lastShownCompletion = outcome;
|
||||
|
||||
/* END OF MODEL OUTCOME RECEIVING BLOCK */
|
||||
|
||||
/* START OF RENDERING BLOCK */
|
||||
|
||||
// Here we determine how to render the outcome received in the previous block.
|
||||
// We check whether the outcome is a FIM completion or not.
|
||||
// If FIM, we render a ghost text, and an SVG + deletion decoration if not.
|
||||
// If we are using autocomplete instead of next edit, we just render a ghost text.
|
||||
|
||||
// Construct the range/text to show
|
||||
const startPos = selectedCompletionInfo?.range.start ?? position;
|
||||
let range = new vscode.Range(startPos, startPos);
|
||||
|
|
@ -536,14 +586,6 @@ export class ContinueCompletionProvider
|
|||
const newEditRangeSlice = completionText;
|
||||
|
||||
// Get the contents of the old (current) editable region.
|
||||
// const editableRegionStartLine = Math.max(
|
||||
// currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
// 0,
|
||||
// );
|
||||
// const editableRegionEndLine = Math.min(
|
||||
// currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
// editor.document.lineCount - 1,
|
||||
// );
|
||||
const editableRegionStartLine = (outcome as NextEditOutcome)
|
||||
.editableRegionStartLine;
|
||||
const editableRegionEndLine = (outcome as NextEditOutcome)
|
||||
|
|
@ -581,10 +623,8 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
|
||||
// Track this ghost text for acceptance detection.
|
||||
// Ghost text acceptance can *technically* be acted upon in
|
||||
// the command handler for "continue.logNextEditOutcomeAccept",
|
||||
// but there is a substantial delay between accepting and logging,
|
||||
// which introduces a lot of race conditions with different event handlers.
|
||||
// Ghost text acceptance can *technically* be acted upon in the command handler for "continue.logNextEditOutcomeAccept".
|
||||
// However, there is a substantial delay between accepting and logging, which introduces a lot of race conditions with different event handlers.
|
||||
// Plus, separating these concerns seems to make sense logically as well.
|
||||
GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance(
|
||||
document,
|
||||
|
|
@ -640,6 +680,8 @@ export class ContinueCompletionProvider
|
|||
} finally {
|
||||
stopStatusBarLoading();
|
||||
}
|
||||
|
||||
/* END OF RENDERING BLOCK */
|
||||
}
|
||||
|
||||
willDisplay(
|
||||
|
|
|
|||
|
|
@ -84,6 +84,12 @@ export class VsCodeExtension {
|
|||
|
||||
private ARBITRARY_TYPING_DELAY = 2000;
|
||||
|
||||
/**
|
||||
* This is how you turn next edit on or off at the extension level.
|
||||
* This is called on config reload and autocomplete menu updates.
|
||||
* This is also the place you want to check to enable/disable next edit during e2e tests,
|
||||
* because it tends to stain other e2e tests and make them fail.
|
||||
*/
|
||||
private async updateNextEditState(
|
||||
context: vscode.ExtensionContext,
|
||||
): Promise<void> {
|
||||
|
|
@ -608,6 +614,8 @@ export class VsCodeExtension {
|
|||
.map((uri) => uri.toString());
|
||||
this.core.invoke("files/opened", { uris: initialOpenedFilePaths });
|
||||
|
||||
// This is how you would enable/disable next edit in the autocomplete menu.
|
||||
// See extensions/vscode/src/autocomplete/statusBar.ts.
|
||||
vscode.workspace.onDidChangeConfiguration(async (event) => {
|
||||
if (event.affectsConfiguration(EXTENSION_NAME)) {
|
||||
const settings = await this.ide.getIdeSettings();
|
||||
|
|
|
|||
353
gui/src/components/UnifiedTerminal/UnifiedTerminal.test.tsx
Normal file
353
gui/src/components/UnifiedTerminal/UnifiedTerminal.test.tsx
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
import { screen, waitFor } from "@testing-library/react";
|
||||
import { ToolCallState } from "core";
|
||||
import { renderWithProviders } from "../../util/test/render";
|
||||
import { UnifiedTerminalCommand } from "./UnifiedTerminal";
|
||||
|
||||
const MOCK_COMMAND = "npm test";
|
||||
const MOCK_OUTPUT = `Running tests...
|
||||
✓ Test 1 passed
|
||||
✓ Test 2 passed
|
||||
✗ Test 3 failed
|
||||
Error: Expected true but got false
|
||||
|
||||
Test Results:
|
||||
2 passed, 1 failed
|
||||
Total: 3 tests`;
|
||||
|
||||
const LONG_OUTPUT = Array.from({ length: 25 }, (_, i) => `Line ${i + 1}`).join(
|
||||
"\n",
|
||||
);
|
||||
const MOCK_TOOL_CALL_ID = "terminal-call-123";
|
||||
|
||||
const MOCK_ANSI_OUTPUT = `\u001b[32m✓\u001b[0m Test passed
|
||||
\u001b[31m✗\u001b[0m Test failed
|
||||
\u001b[1mBold text\u001b[0m
|
||||
\u001b[4mUnderlined text\u001b[0m`;
|
||||
|
||||
const MOCK_OUTPUT_WITH_LINKS = `Build successful!
|
||||
Visit https://example.com for more info
|
||||
Check www.github.com/user/repo
|
||||
Error logs at file:///tmp/error.log`;
|
||||
|
||||
// Mock the redux hooks
|
||||
const mockDispatch = vi.fn();
|
||||
const mockSelector = vi.fn();
|
||||
vi.mock("../../redux/hooks", () => ({
|
||||
useAppDispatch: () => mockDispatch,
|
||||
useAppSelector: () => mockSelector,
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("UnifiedTerminalCommand", () => {
|
||||
test("renders basic terminal command without output", async () => {
|
||||
const { user } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand command={MOCK_COMMAND} status="completed" />,
|
||||
);
|
||||
|
||||
// Should show the command
|
||||
expect(screen.getByText(`$ ${MOCK_COMMAND}`)).toBeInTheDocument();
|
||||
|
||||
// Should show terminal header
|
||||
expect(screen.getByText("Terminal")).toBeInTheDocument();
|
||||
|
||||
// Should show completed status icon (green dot)
|
||||
const terminalContainer = screen.getByTestId("terminal-container");
|
||||
expect(terminalContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("renders terminal command with output", async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={MOCK_OUTPUT}
|
||||
status="completed"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should show the command and output
|
||||
expect(screen.getByText(`$ ${MOCK_COMMAND}`)).toBeInTheDocument();
|
||||
|
||||
// Check that the output content exists in the container
|
||||
expect(container.textContent).toMatch(/Test 1 passed/);
|
||||
expect(container.textContent).toMatch(/Test 3 failed/);
|
||||
});
|
||||
|
||||
test("shows running state with blinking cursor", async () => {
|
||||
const mockToolCallState: ToolCallState = {
|
||||
status: "calling",
|
||||
toolCallId: MOCK_TOOL_CALL_ID,
|
||||
toolCall: {
|
||||
id: MOCK_TOOL_CALL_ID,
|
||||
type: "function",
|
||||
function: {
|
||||
name: "terminal",
|
||||
arguments: "{}",
|
||||
},
|
||||
},
|
||||
parsedArgs: {},
|
||||
};
|
||||
|
||||
const { user } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
status="running"
|
||||
toolCallState={mockToolCallState}
|
||||
toolCallId={MOCK_TOOL_CALL_ID}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should show running status
|
||||
expect(screen.getByText("Running")).toBeInTheDocument();
|
||||
|
||||
// Should show move to background link
|
||||
expect(screen.getByText("Move to background")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("can expand and collapse terminal", async () => {
|
||||
const { user, container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={MOCK_OUTPUT}
|
||||
status="completed"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should initially be expanded and show output
|
||||
expect(container.textContent).toMatch(/Test 1 passed/);
|
||||
|
||||
// Find and click the collapse chevron (SVG icon)
|
||||
const chevron = container.querySelector(
|
||||
'svg[class*="cursor-pointer"], .cursor-pointer svg',
|
||||
);
|
||||
expect(chevron).toBeInTheDocument();
|
||||
|
||||
if (chevron) {
|
||||
await user.click(chevron);
|
||||
|
||||
// After collapsing, output should not be visible
|
||||
await waitFor(() => {
|
||||
expect(container.textContent).not.toMatch(/Test 1 passed/);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("shows collapsible output for long content", async () => {
|
||||
const { user, container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={LONG_OUTPUT}
|
||||
status="completed"
|
||||
displayLines={15}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should show the "+X more lines" indicator
|
||||
expect(screen.getByText(/\+\d+ more lines/)).toBeInTheDocument();
|
||||
|
||||
// Should initially show only some of the last lines
|
||||
expect(container.textContent).toMatch(/Line 25/);
|
||||
|
||||
// Click to expand using the "+X more lines" button
|
||||
const expandButton = screen.getByText(/\+\d+ more lines/);
|
||||
await user.click(expandButton);
|
||||
|
||||
// Should now show all lines
|
||||
await waitFor(() => {
|
||||
expect(container.textContent).toMatch(/Line 1/);
|
||||
});
|
||||
|
||||
// Should show collapse option
|
||||
expect(screen.getByText(/Collapse/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("renders ANSI colors and formatting", async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={MOCK_ANSI_OUTPUT}
|
||||
status="completed"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should render ANSI content (check the container text since ANSI splits across elements)
|
||||
expect(container.textContent).toMatch(/Test passed/);
|
||||
expect(container.textContent).toMatch(/Test failed/);
|
||||
expect(container.textContent).toMatch(/Bold text/);
|
||||
expect(container.textContent).toMatch(/Underlined text/);
|
||||
|
||||
// Verify ANSI processing created styled spans
|
||||
const styledSpans = container.querySelectorAll('span[class*="sc-esYiGF"]');
|
||||
expect(styledSpans.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("handles links in output", async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={MOCK_OUTPUT_WITH_LINKS}
|
||||
status="completed"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should contain the link text in the output
|
||||
expect(container.textContent).toMatch(/https:\/\/example\.com/);
|
||||
expect(container.textContent).toMatch(/www\.github\.com/);
|
||||
|
||||
// Note: Link detection might create actual <a> tags or just display the URLs
|
||||
// The important thing is the URLs are visible in the output
|
||||
});
|
||||
|
||||
test("shows copy and run in terminal buttons when not running", async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={MOCK_OUTPUT}
|
||||
status="completed"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Look for toolbar elements - they may be hidden by responsive classes but exist in DOM
|
||||
const toolbarArea = container.querySelector('[class*="gap-2.5"]');
|
||||
expect(toolbarArea).toBeInTheDocument();
|
||||
|
||||
// Should contain SVG icons for copy/run operations
|
||||
const svgIcons = container.querySelectorAll("svg");
|
||||
expect(svgIcons.length).toBeGreaterThan(0);
|
||||
|
||||
// Should show "Run" text (may be hidden on small screens)
|
||||
expect(container.textContent).toMatch(/Run/);
|
||||
});
|
||||
|
||||
test("handles move to background action", async () => {
|
||||
const mockToolCallState: ToolCallState = {
|
||||
status: "calling",
|
||||
toolCallId: MOCK_TOOL_CALL_ID,
|
||||
toolCall: {
|
||||
id: MOCK_TOOL_CALL_ID,
|
||||
type: "function",
|
||||
function: {
|
||||
name: "terminal",
|
||||
arguments: "{}",
|
||||
},
|
||||
},
|
||||
parsedArgs: {},
|
||||
};
|
||||
|
||||
const { user } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
status="running"
|
||||
toolCallState={mockToolCallState}
|
||||
toolCallId={MOCK_TOOL_CALL_ID}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Find and click move to background link
|
||||
const moveToBackgroundLink = screen.getByText("Move to background");
|
||||
await user.click(moveToBackgroundLink);
|
||||
|
||||
// Should dispatch the move to background action
|
||||
expect(mockDispatch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("shows different status types correctly", async () => {
|
||||
// Test completed status
|
||||
const { rerender, container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
status="completed"
|
||||
statusMessage="Command completed successfully"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.textContent).toMatch(/Command completed successfully/);
|
||||
|
||||
// Test failed status
|
||||
rerender(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
status="failed"
|
||||
statusMessage="Command failed with exit code 1"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.textContent).toMatch(/Command failed with exit code 1/);
|
||||
|
||||
// Test background status
|
||||
rerender(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
status="background"
|
||||
statusMessage="Command moved to background"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.textContent).toMatch(/Command moved to background/);
|
||||
});
|
||||
|
||||
test("handles empty output gracefully", async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output=""
|
||||
status="completed"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should show command but no output section
|
||||
expect(screen.getByText(`$ ${MOCK_COMMAND}`)).toBeInTheDocument();
|
||||
|
||||
// Should not show any output content
|
||||
const outputElements = container.querySelectorAll(
|
||||
"pre code > div:not(:first-child)",
|
||||
);
|
||||
expect(outputElements.length).toBe(0);
|
||||
});
|
||||
|
||||
test("processes terminal content correctly for line limiting", async () => {
|
||||
const { container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={LONG_OUTPUT}
|
||||
status="completed"
|
||||
displayLines={10}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should show correct number of hidden lines
|
||||
expect(screen.getByText(/\+15 more lines/)).toBeInTheDocument();
|
||||
|
||||
// Should show the last lines
|
||||
expect(container.textContent).toMatch(/Line 25/);
|
||||
|
||||
// Should not initially show the first lines (Line 1-15 should be hidden)
|
||||
// The component shows last 10 lines (16-25) with a +15 more lines indicator
|
||||
expect(container.textContent).toMatch(/Line 16/);
|
||||
});
|
||||
|
||||
test("clicking on collapsible output toggles expansion", async () => {
|
||||
const { user, container } = await renderWithProviders(
|
||||
<UnifiedTerminalCommand
|
||||
command={MOCK_COMMAND}
|
||||
output={LONG_OUTPUT}
|
||||
status="completed"
|
||||
displayLines={10}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Click on the "+15 more lines" button to expand
|
||||
const expandButton = screen.getByText(/\+15 more lines/);
|
||||
await user.click(expandButton);
|
||||
|
||||
// Should expand and show all content
|
||||
await waitFor(() => {
|
||||
expect(container.textContent).toMatch(/Line 1/);
|
||||
});
|
||||
|
||||
// Should show collapse option after expansion
|
||||
expect(screen.getByText(/Collapse/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -418,7 +418,11 @@ export function UnifiedTerminalCommand({
|
|||
}, [command, output, hasOutput]);
|
||||
|
||||
return (
|
||||
<StyledTerminalContainer fontSize={getFontSize()} className="mb-4">
|
||||
<StyledTerminalContainer
|
||||
fontSize={getFontSize()}
|
||||
className="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">
|
||||
{/* Toolbar */}
|
||||
<div
|
||||
|
|
|
|||
|
|
@ -240,7 +240,6 @@ describe("FindAndReplaceDisplay", () => {
|
|||
fireEvent.click(toggleButton);
|
||||
|
||||
expect(screen.getByText("Error generating diff")).toBeInTheDocument();
|
||||
expect(screen.getByText("Test error")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should show 'No changes to display' when diff is empty", () => {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import { diffLines } from "diff";
|
|||
import { useContext, useMemo, useState } from "react";
|
||||
import { ApplyActions } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions";
|
||||
import { FileInfo } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo";
|
||||
import { useFontSize } from "../../../components/ui";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { useAppSelector } from "../../../redux/hooks";
|
||||
import {
|
||||
|
|
@ -34,15 +33,16 @@ export function FindAndReplaceDisplay({
|
|||
toolCallId,
|
||||
historyIndex,
|
||||
}: FindAndReplaceDisplayProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [isExpanded, setIsExpanded] = useState<boolean | undefined>(undefined);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const applyState: ApplyState | undefined = useAppSelector((state) =>
|
||||
selectApplyStateByToolCallId(state, toolCallId),
|
||||
);
|
||||
const fontSize = useFontSize();
|
||||
|
||||
const toolCallState = useAppSelector((state) =>
|
||||
selectToolCallById(state, toolCallId),
|
||||
);
|
||||
const showContent = isExpanded ?? toolCallState?.status === "generated";
|
||||
const config = useAppSelector((state) => state.config.config);
|
||||
|
||||
const displayName = useMemo(() => {
|
||||
|
|
@ -126,21 +126,21 @@ export function FindAndReplaceDisplay({
|
|||
const renderContainer = (content: React.ReactNode) => (
|
||||
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mx-2 my-1 flex min-w-0 flex-col outline outline-1">
|
||||
<div
|
||||
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex cursor-pointer items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
|
||||
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex cursor-pointer items-center justify-between gap-3 px-1.5 py-1 ${showContent ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
|
||||
onClick={() => {
|
||||
setIsExpanded((prev) => !prev);
|
||||
setIsExpanded(!showContent);
|
||||
}}
|
||||
>
|
||||
<div className="flex max-w-[50%] flex-row items-center text-xs">
|
||||
{statusIcon}
|
||||
<ChevronDownIcon
|
||||
data-testid="toggle-find-and-replace-diff"
|
||||
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer transition-all hover:brightness-125 ${
|
||||
isExpanded ? "rotate-0" : "-rotate-90"
|
||||
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer select-none transition-all hover:brightness-125 ${
|
||||
showContent ? "rotate-0" : "-rotate-90"
|
||||
}`}
|
||||
/>
|
||||
<FileInfo
|
||||
filepath={displayName}
|
||||
filepath={displayName || "..."}
|
||||
onClick={(e) => {
|
||||
if (!fileUri) {
|
||||
return;
|
||||
|
|
@ -170,14 +170,14 @@ export function FindAndReplaceDisplay({
|
|||
/>
|
||||
)}
|
||||
</div>
|
||||
{toolCallState?.status === "generated" || isExpanded ? content : null}
|
||||
{showContent ? content : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (diffResult?.error) {
|
||||
return renderContainer(
|
||||
<div className="text-error p-3 text-sm">
|
||||
<strong>Error generating diff</strong> {diffResult.error}
|
||||
<strong>Error generating diff</strong>
|
||||
</div>,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue