Merge branch 'main' into dallin/system-message-tools
This commit is contained in:
commit
0c9a238f71
112 changed files with 5231 additions and 1024 deletions
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
|
@ -11,6 +11,8 @@ body:
|
|||
attributes:
|
||||
label: Before submitting your bug report
|
||||
options:
|
||||
- label: I've tried using the "Ask AI" feature on the [Continue docs site](https://docs.continue.dev/) to see if the docs have an answer
|
||||
required: false
|
||||
- label: I believe this is a bug. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions
|
||||
required: false
|
||||
- label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue) that reports the same bug
|
||||
|
|
|
|||
9
.github/workflows/jetbrains-release.yaml
vendored
9
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -63,7 +63,6 @@ jobs:
|
|||
|
||||
- name: Bump version in gradle.properties
|
||||
run: |
|
||||
cd extensions/intellij
|
||||
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
|
||||
rm -rf tmp
|
||||
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
|
||||
|
|
@ -224,10 +223,6 @@ jobs:
|
|||
# apple-product-id: dev.continue.continue-binary
|
||||
# options: --options runtime --entitlements entitlements.xml
|
||||
|
||||
# Build plugin
|
||||
- name: Build plugin
|
||||
run: ./gradlew buildPlugin
|
||||
|
||||
# Publish the plugin to JetBrains Marketplace
|
||||
- name: Publish EAP Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
|
|
@ -237,7 +232,7 @@ jobs:
|
|||
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
|
||||
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
|
||||
RELEASE_CHANNEL: eap
|
||||
run: ./gradlew publishPlugin
|
||||
run: ./gradlew publishPlugin --info --stacktrace
|
||||
|
||||
- name: Publish Stable Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
|
|
@ -247,7 +242,7 @@ jobs:
|
|||
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
|
||||
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
|
||||
RELEASE_CHANNEL: default
|
||||
run: ./gradlew publishPlugin
|
||||
run: ./gradlew publishPlugin --info --stacktrace
|
||||
|
||||
# Prepare plugin archive content for creating artifact
|
||||
- name: Prepare Plugin Artifact
|
||||
|
|
|
|||
29
.github/workflows/pr_checks.yaml
vendored
29
.github/workflows/pr_checks.yaml
vendored
|
|
@ -50,7 +50,10 @@ jobs:
|
|||
|
||||
install-config-yaml:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -77,7 +80,10 @@ jobs:
|
|||
|
||||
install-openai-adapters:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -133,7 +139,10 @@ jobs:
|
|||
|
||||
install-core:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -381,7 +390,10 @@ jobs:
|
|||
install-vscode:
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -659,7 +671,10 @@ jobs:
|
|||
echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}"
|
||||
|
||||
vscode-package-extension:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
needs:
|
||||
[
|
||||
install-vscode,
|
||||
|
|
@ -716,7 +731,7 @@ jobs:
|
|||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: vscode-extension-build
|
||||
name: vscode-extension-build-${{ runner.os }}
|
||||
path: extensions/vscode/build
|
||||
|
||||
vscode-download-e2e-dependencies:
|
||||
|
|
@ -812,7 +827,7 @@ jobs:
|
|||
- name: Download build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: vscode-extension-build
|
||||
name: vscode-extension-build-Linux
|
||||
path: extensions/vscode/build
|
||||
|
||||
- name: Download e2e dependencies
|
||||
|
|
|
|||
2
.idea/gradle.xml
generated
2
.idea/gradle.xml
generated
|
|
@ -5,7 +5,7 @@
|
|||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
|
||||
<option name="gradleJvm" value="homebrew-17" />
|
||||
<option name="gradleJvm" value="#JAVA_HOME" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$/extensions/intellij" />
|
||||
|
|
|
|||
2
.idea/kotlinc.xml
generated
2
.idea/kotlinc.xml
generated
|
|
@ -1,6 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.9.0" />
|
||||
<option name="version" value="1.8.0" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -22,7 +22,13 @@
|
|||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.vitest.ts"],
|
||||
"files": [
|
||||
"**/*.test.ts",
|
||||
"**/*.test.tsx",
|
||||
"**/*.spec.ts",
|
||||
"**/*.spec.tsx",
|
||||
"**/*.vitest.ts"
|
||||
],
|
||||
"rules": {
|
||||
"max-lines-per-function": "off"
|
||||
}
|
||||
|
|
|
|||
146
core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts
Normal file
146
core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
import {
|
||||
collectAllLines,
|
||||
MarkdownBlockStateTracker,
|
||||
} from "../../../utils/markdownUtils";
|
||||
|
||||
import {
|
||||
processBlockNesting,
|
||||
shouldStopAtMarkdownBlock,
|
||||
} from "../../../utils/streamMarkdownUtils";
|
||||
|
||||
import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream";
|
||||
|
||||
/**
|
||||
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
|
||||
* Now includes markdown-aware processing to handle nested markdown blocks properly.
|
||||
*
|
||||
* @param {LineStream} rawLines - The input stream of lines to filter.
|
||||
* @param {string} filepath - Optional filepath to determine if this is a markdown file.
|
||||
* @yields {string} Filtered and processed lines from the code block.
|
||||
*
|
||||
* @description
|
||||
* This generator function performs the following tasks:
|
||||
* 1. Removes initial lines that should be removed before the actual code starts.
|
||||
* 2. For markdown files, applies nested markdown block logic to avoid premature termination.
|
||||
* 3. For mixed content, uses simplified processing to avoid premature termination.
|
||||
* 4. For traditional code blocks, uses original logic.
|
||||
* 5. Yields processed lines that are part of the actual code block content.
|
||||
*/
|
||||
export async function* filterCodeBlockLines(
|
||||
rawLines: LineStream,
|
||||
filepath?: string,
|
||||
): LineStream {
|
||||
// Collect all lines for analysis
|
||||
const allLines = await collectAllLines(rawLines);
|
||||
|
||||
// Check if it has nested markdown blocks (like ```markdown or ```md)
|
||||
const firstLine = allLines[0] || "";
|
||||
const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath);
|
||||
|
||||
// TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks)
|
||||
// But exclude cases where we have nested markdown blocks
|
||||
const hasMarkdownHeaders = allLines.some(
|
||||
(line) => line.trim().startsWith("#") && !line.trim().startsWith("```"),
|
||||
);
|
||||
|
||||
const hasCodeBlocks = allLines.some(
|
||||
(line) => line.trim().startsWith("```") && line.trim().length >= 3,
|
||||
);
|
||||
const isMixedContent =
|
||||
hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown;
|
||||
|
||||
// If this is mixed content, use simplified processing
|
||||
if (isMixedContent) {
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
const line = allLines[i];
|
||||
|
||||
// Skip initial wrapper lines if they exist
|
||||
if (i === 0 && shouldRemoveLineBeforeStart(line)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
yield line;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Original logic for non-mixed content
|
||||
let seenFirstFence = false;
|
||||
let nestCount = 0;
|
||||
|
||||
// Create optimized state tracker for markdown block analysis if needed
|
||||
let markdownStateTracker: MarkdownBlockStateTracker | undefined;
|
||||
if (hasNestedMarkdown) {
|
||||
markdownStateTracker = new MarkdownBlockStateTracker(allLines);
|
||||
}
|
||||
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
const line = allLines[i];
|
||||
|
||||
// Process block nesting logic for the first fence
|
||||
const nesting = processBlockNesting(
|
||||
line,
|
||||
seenFirstFence,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
if (nesting.shouldSkip) {
|
||||
continue; // Filter out starting ``` or START block
|
||||
}
|
||||
if (!seenFirstFence && nesting.newSeenFirstFence) {
|
||||
seenFirstFence = true;
|
||||
nestCount = 1;
|
||||
}
|
||||
|
||||
if (nestCount > 0) {
|
||||
// Inside a block including the outer block
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
// Ending a block with just backticks (```) or STOP
|
||||
|
||||
// For markdown files with nested markdown blocks, apply special logic
|
||||
if (
|
||||
hasNestedMarkdown &&
|
||||
line.trim() === "```" &&
|
||||
markdownStateTracker
|
||||
) {
|
||||
if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) {
|
||||
return; // Stop without yielding the final closing ```
|
||||
} else {
|
||||
// This is an inner block delimiter, yield it as content
|
||||
yield line;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Original logic for non-markdown files or simple cases
|
||||
nestCount--;
|
||||
if (nestCount === 0) {
|
||||
// We've closed the outer wrapper - stop without yielding the closing ```
|
||||
return;
|
||||
} else {
|
||||
// This is a nested block closing, yield it as content
|
||||
yield line;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
nestCount++;
|
||||
yield line;
|
||||
} else {
|
||||
// Otherwise just yield the line as content
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function shouldRemoveLineBeforeStart(line: string): boolean {
|
||||
return (
|
||||
line.trimStart().startsWith("```") ||
|
||||
line.trim() === "[CODE]" ||
|
||||
line.trim() === "<COMPLETION>" ||
|
||||
line.trim() === "<START EDITING HERE>" ||
|
||||
line.trim() === "{{FILL_HERE}}"
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,452 @@
|
|||
// eslint-disable-next-line max-lines-per-function
|
||||
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
|
||||
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
describe("filterCodeBlock", () => {
|
||||
let mockFullStop: Mock;
|
||||
|
||||
async function getLineGenerator(lines: any) {
|
||||
return (async function* () {
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
async function getFilteredLines(results: any) {
|
||||
const output = [];
|
||||
|
||||
for await (const line of results) {
|
||||
output.push(line);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockFullStop = vi.fn();
|
||||
});
|
||||
|
||||
it("should handle unfenced code", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;"]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with a code block", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with a complex code block", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"# Manual Testing Sandbox",
|
||||
"",
|
||||
"## Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"manual-testing-sandbox/",
|
||||
"├── readme.md # Project documentation",
|
||||
"├── package.json # Node.js dependencies and scripts",
|
||||
"├── tsconfig.json # TypeScript configuration",
|
||||
"├── jest.config.js # Jest testing configuration",
|
||||
"├── requirements.txt # Python dependencies",
|
||||
"├── Dockerfile # Docker container configuration",
|
||||
"├── data.json # Sample JSON data",
|
||||
"├── example.ipynb # Jupyter notebook example",
|
||||
"│",
|
||||
"├── src/ # Source code directory",
|
||||
"│ ├── example.ts # TypeScript example",
|
||||
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
|
||||
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
|
||||
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
|
||||
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
|
||||
"│",
|
||||
"├── react-calculator/ # React calculator application",
|
||||
"├── calculator_test/ # Java calculator implementation",
|
||||
"│ ├── Calculator.java # Calculator class",
|
||||
"│ └── Main.java # Main application entry",
|
||||
"│",
|
||||
"├── nested-folder/ # Nested project example",
|
||||
"│ ├── helloNested.py # Python script",
|
||||
"│ ├── package.json # Nested package configuration",
|
||||
"│ └── rules.md # Documentation",
|
||||
"│",
|
||||
"├── coverage/ # Test coverage reports",
|
||||
"├── logs/ # Application logs",
|
||||
"│",
|
||||
"└── Test Files # Various language examples",
|
||||
" ├── AdvancedPage.tsx # React TypeScript component",
|
||||
" ├── Calculator.java # Java calculator",
|
||||
" ├── program.cs # C# program",
|
||||
" ├── query.sql # SQL query example",
|
||||
" ├── test.css # CSS styles",
|
||||
" ├── test.html # HTML page",
|
||||
" ├── test.js # JavaScript code",
|
||||
" ├── test.kt # Kotlin example",
|
||||
" ├── test.php # PHP script",
|
||||
" ├── test.py # Python script",
|
||||
" ├── test.rb # Ruby script",
|
||||
" ├── test.rs # Rust code",
|
||||
" ├── test.sh # Shell script",
|
||||
" └── test.ts # TypeScript code",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"# Manual Testing Sandbox",
|
||||
"",
|
||||
"## Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"manual-testing-sandbox/",
|
||||
"├── readme.md # Project documentation",
|
||||
"├── package.json # Node.js dependencies and scripts",
|
||||
"├── tsconfig.json # TypeScript configuration",
|
||||
"├── jest.config.js # Jest testing configuration",
|
||||
"├── requirements.txt # Python dependencies",
|
||||
"├── Dockerfile # Docker container configuration",
|
||||
"├── data.json # Sample JSON data",
|
||||
"├── example.ipynb # Jupyter notebook example",
|
||||
"│",
|
||||
"├── src/ # Source code directory",
|
||||
"│ ├── example.ts # TypeScript example",
|
||||
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
|
||||
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
|
||||
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
|
||||
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
|
||||
"│",
|
||||
"├── react-calculator/ # React calculator application",
|
||||
"├── calculator_test/ # Java calculator implementation",
|
||||
"│ ├── Calculator.java # Calculator class",
|
||||
"│ └── Main.java # Main application entry",
|
||||
"│",
|
||||
"├── nested-folder/ # Nested project example",
|
||||
"│ ├── helloNested.py # Python script",
|
||||
"│ ├── package.json # Nested package configuration",
|
||||
"│ └── rules.md # Documentation",
|
||||
"│",
|
||||
"├── coverage/ # Test coverage reports",
|
||||
"├── logs/ # Application logs",
|
||||
"│",
|
||||
"└── Test Files # Various language examples",
|
||||
" ├── AdvancedPage.tsx # React TypeScript component",
|
||||
" ├── Calculator.java # Java calculator",
|
||||
" ├── program.cs # C# program",
|
||||
" ├── query.sql # SQL query example",
|
||||
" ├── test.css # CSS styles",
|
||||
" ├── test.html # HTML page",
|
||||
" ├── test.js # JavaScript code",
|
||||
" ├── test.kt # Kotlin example",
|
||||
" ├── test.php # PHP script",
|
||||
" ├── test.py # Python script",
|
||||
" ├── test.rb # Ruby script",
|
||||
" ├── test.rs # Rust code",
|
||||
" ├── test.sh # Shell script",
|
||||
" └── test.ts # TypeScript code",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with two code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should remove lines before the first valid line", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should remove outer blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```ts",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
it("should ignore ticks inside of code blocks such as tests", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```typescript",
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave single inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
it("should leave double inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact but not return trailing or leading text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"[CODE]",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"[/CODE]",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is included", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle non-markdown files normally with filepath parameter", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle simple markdown code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should remove the outer markdown wrapper, and return just the inner content.
|
||||
// The lack of an end tag should cause it to return all remaining lines.
|
||||
expect(filteredLines).toEqual([
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,6 +3,11 @@ import { distance } from "fastest-levenshtein";
|
|||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils";
|
||||
import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils";
|
||||
|
||||
export { filterCodeBlockLines } from "./filterCodeBlock";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
lines: LineStream;
|
||||
fullStop: () => void;
|
||||
|
|
@ -50,13 +55,72 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
|
|||
);
|
||||
}
|
||||
|
||||
function shouldChangeLineAndStop(line: string): string | undefined {
|
||||
/**
|
||||
* Shared utility for validating patterns in lines to avoid code duplication.
|
||||
* Checks if a pattern appears in a valid context (not inside quotes or identifiers).
|
||||
*/
|
||||
export function validatePatternInLine(
|
||||
line: string,
|
||||
pattern: string,
|
||||
): {
|
||||
isValid: boolean;
|
||||
patternIndex: number;
|
||||
beforePattern: string;
|
||||
} {
|
||||
const patternIndex = line.indexOf(pattern);
|
||||
|
||||
if (patternIndex === -1) {
|
||||
return { isValid: false, patternIndex: -1, beforePattern: "" };
|
||||
}
|
||||
|
||||
// Check if pattern is preceded by a non-whitespace character
|
||||
// If so, it might be part of an identifier, so don't handle it
|
||||
if (patternIndex > 0) {
|
||||
const charBefore = line[patternIndex - 1];
|
||||
if (charBefore && !charBefore.match(/\s/)) {
|
||||
return { isValid: false, patternIndex, beforePattern: "" };
|
||||
}
|
||||
}
|
||||
|
||||
// Check if pattern appears to be inside quotes
|
||||
// Simple heuristic: count unmatched quotes before the pattern
|
||||
const beforePattern = line.substring(0, patternIndex);
|
||||
const singleQuotes = (beforePattern.match(/'/g) || []).length;
|
||||
const doubleQuotes = (beforePattern.match(/"/g) || []).length;
|
||||
|
||||
// If there's an odd number of quotes before pattern, we're likely inside quotes
|
||||
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
|
||||
return { isValid: false, patternIndex, beforePattern };
|
||||
}
|
||||
|
||||
return { isValid: true, patternIndex, beforePattern };
|
||||
}
|
||||
|
||||
export function shouldChangeLineAndStop(line: string): string | undefined {
|
||||
if (line.trimStart() === "```") {
|
||||
return line;
|
||||
}
|
||||
|
||||
// Check if [/CODE] appears in the line
|
||||
if (line.includes(CODE_STOP_BLOCK)) {
|
||||
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
|
||||
const validation = validatePatternInLine(line, CODE_STOP_BLOCK);
|
||||
|
||||
if (!validation.isValid) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Get the trimmed line to check if [/CODE] is at logical start
|
||||
const trimmedLine = line.trimStart();
|
||||
|
||||
if (trimmedLine.startsWith(CODE_STOP_BLOCK)) {
|
||||
// [/CODE] is at the logical start (after whitespace only)
|
||||
if (trimmedLine === CODE_STOP_BLOCK) {
|
||||
return line; // Return the whole line including leading whitespace
|
||||
}
|
||||
}
|
||||
|
||||
// [/CODE] appears after some content (separated by whitespace) - return part before
|
||||
return validation.beforePattern.trimEnd();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -71,6 +135,32 @@ function isUselessLine(line: string): boolean {
|
|||
return hasUselessLine || trimmed.startsWith("// end");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the code block has nested markdown blocks.
|
||||
*/
|
||||
export function hasNestedMarkdownBlocks(
|
||||
firstLine: string,
|
||||
filepath?: string,
|
||||
): boolean {
|
||||
return (
|
||||
(firstLine.startsWith("```") &&
|
||||
headerIsMarkdown(firstLine.replace(/`/g, ""))) ||
|
||||
Boolean(filepath && isMarkdownFile(filepath))
|
||||
);
|
||||
}
|
||||
|
||||
// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function
|
||||
export function processBlockNesting(
|
||||
line: string,
|
||||
seenFirstFence: boolean,
|
||||
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
|
||||
return processBlockNestingUtil(
|
||||
line,
|
||||
seenFirstFence,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
}
|
||||
|
||||
export const USELESS_LINES = [""];
|
||||
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
|
||||
export const CODE_STOP_BLOCK = "[/CODE]";
|
||||
|
|
@ -138,7 +228,7 @@ export async function* avoidPathLine(
|
|||
// Sometimes the model with copy this pattern, which is unwanted
|
||||
for await (const line of stream) {
|
||||
if (line.startsWith(`${comment} Path: `)) {
|
||||
continue;
|
||||
continue; // continue in the Continue codebase! How meta!
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
|
|
@ -261,7 +351,40 @@ export async function* stopAtLines(
|
|||
linesToStopAt: string[] = LINES_TO_STOP_AT,
|
||||
): LineStream {
|
||||
for await (const line of stream) {
|
||||
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
|
||||
let shouldStop = false;
|
||||
|
||||
// Check each stop phrase
|
||||
for (const stopAt of linesToStopAt) {
|
||||
if (line.includes(stopAt)) {
|
||||
const validation = validatePatternInLine(line, stopAt);
|
||||
|
||||
if (!validation.isValid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the trimmed line to check if stop phrase is at logical start
|
||||
const trimmedLine = line.trimStart();
|
||||
|
||||
if (trimmedLine.startsWith(stopAt)) {
|
||||
// Stop phrase is at the logical start (after whitespace only) - should stop
|
||||
shouldStop = true;
|
||||
break;
|
||||
} else {
|
||||
// Stop phrase appears after some content - check if it's separated by whitespace
|
||||
const contentBeforeStopPhrase = validation.beforePattern.trimEnd();
|
||||
if (
|
||||
contentBeforeStopPhrase.length < validation.beforePattern.length
|
||||
) {
|
||||
// There's whitespace before the stop phrase, so it's properly separated
|
||||
shouldStop = true;
|
||||
break;
|
||||
}
|
||||
// If no whitespace separation, it's part of larger text, so continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldStop) {
|
||||
fullStop();
|
||||
break;
|
||||
}
|
||||
|
|
@ -329,64 +452,6 @@ export async function* removeTrailingWhitespace(
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
|
||||
*
|
||||
* @param {LineStream} rawLines - The input stream of lines to filter.
|
||||
* @yields {string} Filtered and processed lines from the code block.
|
||||
*
|
||||
* @description
|
||||
* This generator function performs the following tasks:
|
||||
* 1. Removes initial lines that should be removed before the actual code starts.
|
||||
* 2. Filters out ending code block markers (```) unless they are the last line.
|
||||
* 3. Handles special cases where lines should be changed and the stream should stop.
|
||||
* 4. Yields processed lines that are part of the actual code block content.
|
||||
*/
|
||||
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
|
||||
let seenFirstFence = false;
|
||||
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
|
||||
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
|
||||
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
|
||||
let nestCount = 0;
|
||||
|
||||
for await (const line of rawLines) {
|
||||
if (!seenFirstFence) {
|
||||
if (shouldRemoveLineBeforeStart(line)) {
|
||||
// Filter out starting ``` or START block
|
||||
continue;
|
||||
}
|
||||
// Regardless of a fence or START block start tracking the nesting level
|
||||
seenFirstFence = true;
|
||||
nestCount = 1;
|
||||
}
|
||||
|
||||
if (nestCount > 0) {
|
||||
// Inside a block including the outer block
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
// Ending a block with just backticks (```) or STOP
|
||||
nestCount--;
|
||||
if (nestCount === 0) {
|
||||
// if we are closing the outer block then exit early
|
||||
// only exit early if the outer block was started with a block
|
||||
// it it was text, we will never exit early
|
||||
return;
|
||||
} else {
|
||||
// otherwise just yield the line
|
||||
yield line;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
nestCount++;
|
||||
yield line;
|
||||
} else {
|
||||
// otherwise just yield the line
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out English explanations at the start of a code block.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
|
||||
|
||||
import {
|
||||
collectAllLines,
|
||||
MarkdownBlockStateTracker,
|
||||
} from "../../../utils/markdownUtils";
|
||||
import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils";
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function
|
||||
|
|
@ -174,6 +179,93 @@ describe("lineStream", () => {
|
|||
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should stop at lines with leading whitespace", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"let y = 10;",
|
||||
` ${lineStream.LINES_TO_STOP_AT[0]}`,
|
||||
"const z = 15;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should NOT stop when stop phrase is inside quotes", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
'console.log("# End of file. not really");',
|
||||
"let y = 10;",
|
||||
"const z = 15;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should not stop, should yield all lines
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
'console.log("# End of file. not really");',
|
||||
"let y = 10;",
|
||||
"const z = 15;",
|
||||
]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("should NOT stop when stop phrase is inside single quotes", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"const message = '# End of file. not really';",
|
||||
"let y = 10;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"const message = '# End of file. not really';",
|
||||
"let y = 10;",
|
||||
]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("should NOT stop when stop phrase is part of larger text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"// This function stops<STOP EDITING HERE>after processing",
|
||||
"let y = 10;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"// This function stops<STOP EDITING HERE>after processing",
|
||||
"let y = 10;",
|
||||
]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("should stop when stop phrase appears properly at start of content", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"let y = 10;",
|
||||
"# End of file. Done here",
|
||||
"const z = 15;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("skipPrefixes", () => {
|
||||
|
|
@ -301,6 +393,37 @@ describe("lineStream", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("should ignore ticks inside of code blocks such as tests", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```typescript",
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
|
|
@ -395,6 +518,119 @@ describe("lineStream", () => {
|
|||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is included", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"README.md",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle non-markdown files normally with filepath parameter", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle simple markdown code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"README.md",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should remove the outer markdown wrapper, and return just the inner content.
|
||||
// The lack of an end tag should cause it to return all remaining lines.
|
||||
expect(filteredLines).toEqual([
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterEnglishLinesAtStart", () => {
|
||||
|
|
@ -613,4 +849,453 @@ describe("lineStream", () => {
|
|||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for new helper functions
|
||||
|
||||
describe("hasNestedMarkdownBlocks", () => {
|
||||
it("should detect nested markdown blocks from first line", () => {
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true);
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should detect nested markdown blocks from filepath", () => {
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for non-markdown scenarios", () => {
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"),
|
||||
).toBe(false);
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle complex first line scenarios", () => {
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined),
|
||||
).toBe(true);
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectAllLines", () => {
|
||||
it("should collect all lines from a stream", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"line1",
|
||||
"line2",
|
||||
"line3",
|
||||
]);
|
||||
|
||||
const result = await collectAllLines(linesGenerator);
|
||||
|
||||
expect(result).toEqual(["line1", "line2", "line3"]);
|
||||
});
|
||||
|
||||
it("should handle empty stream", async () => {
|
||||
const linesGenerator = await getLineGenerator([]);
|
||||
|
||||
const result = await collectAllLines(linesGenerator);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle stream with empty lines", async () => {
|
||||
const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]);
|
||||
|
||||
const result = await collectAllLines(linesGenerator);
|
||||
|
||||
expect(result).toEqual(["", "line2", "", "line4"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldStopAtMarkdownBlock", () => {
|
||||
it("should return false when current line is not closing backticks", () => {
|
||||
const allLines = ["```markdown", "content", "more content"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle simple nested markdown case", () => {
|
||||
const allLines = ["```markdown", "# Title", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle complex nested markdown with inner code blocks", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"# Title",
|
||||
"```javascript",
|
||||
"console.log('hello');",
|
||||
"```",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
// At index 4 (first inner closing), should not stop
|
||||
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false);
|
||||
// At index 5 (outer closing), should stop
|
||||
expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle multiple bare backticks scenario", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"Content with ```inline code```",
|
||||
"```",
|
||||
"More content",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
// At index 2, should not stop (not the last bare backticks)
|
||||
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
|
||||
// At index 4, should stop (last bare backticks)
|
||||
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldChangeLineAndStop", () => {
|
||||
it("should handle [/CODE] at start of line", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop("[/CODE]");
|
||||
expect(result).toBe("[/CODE]");
|
||||
});
|
||||
|
||||
it("should handle [/CODE] with leading whitespace", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(" [/CODE]");
|
||||
expect(result).toBe(" [/CODE]");
|
||||
});
|
||||
|
||||
it("should return partial line before [/CODE] when at start/after whitespace", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
"some code [/CODE] more text",
|
||||
);
|
||||
expect(result).toBe("some code");
|
||||
});
|
||||
|
||||
it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => {
|
||||
// This test demonstrates the current bug - it WILL fail initially
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
'console.log("test [/CODE] end");',
|
||||
);
|
||||
expect(result).toBeUndefined(); // Should not trigger stopping
|
||||
});
|
||||
|
||||
it("should NOT trigger on [/CODE] in middle of identifier", () => {
|
||||
// Another case that shows the bug
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
'const var[/CODE]Name = "test";',
|
||||
);
|
||||
expect(result).toBeUndefined(); // Should not trigger stopping
|
||||
});
|
||||
|
||||
it("should handle ``` with trimStart correctly", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(" ```");
|
||||
expect(result).toBe(" ```");
|
||||
});
|
||||
|
||||
it("should NOT handle ``` in middle of line", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
'console.log("test ``` end");',
|
||||
);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MarkdownBlockState", () => {
|
||||
it("should initialize with correct state", () => {
|
||||
const allLines = ["```markdown", "content", "```", "more content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Test basic initialization - we can't directly test private properties,
|
||||
// but we can test the behavior through shouldStopAtPosition
|
||||
expect(state).toBeDefined();
|
||||
});
|
||||
|
||||
it("should correctly identify bare backticks positions", () => {
|
||||
const allLines = ["```markdown", "```", "content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// At position 1 (first bare backticks), should not stop
|
||||
expect(state.shouldStopAtPosition(1)).toBe(false);
|
||||
// At position 3 (last bare backticks), should stop
|
||||
expect(state.shouldStopAtPosition(3)).toBe(true);
|
||||
});
|
||||
|
||||
it("should maintain state across multiple calls", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"# Title",
|
||||
"```javascript",
|
||||
"console.log('test');",
|
||||
"```",
|
||||
"More content",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Process positions incrementally
|
||||
expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block
|
||||
expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block
|
||||
expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block
|
||||
});
|
||||
|
||||
it("should handle complex nesting scenarios efficiently", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"interface Config {",
|
||||
" name: string;",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"```bash",
|
||||
"npm install",
|
||||
"```",
|
||||
"",
|
||||
"Final notes",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Test multiple positions in sequence
|
||||
expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block
|
||||
expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block
|
||||
expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block
|
||||
});
|
||||
|
||||
it("should handle non-backtick lines correctly", () => {
|
||||
const allLines = ["```markdown", "regular content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Position 1 is not backticks, should return false
|
||||
expect(state.shouldStopAtPosition(1)).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle empty lines and edge cases", () => {
|
||||
const allLines = ["```markdown", "", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line
|
||||
expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks
|
||||
});
|
||||
|
||||
it("should reset nest count when reaching final bare backticks", () => {
|
||||
const allLines = ["```markdown", "content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// First call should stop and reset count
|
||||
expect(state.shouldStopAtPosition(2)).toBe(true);
|
||||
|
||||
// If we had more content, it should start fresh
|
||||
// (This tests the internal state management)
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldStopAtMarkdownBlock optimization", () => {
|
||||
it("should maintain performance benefits with state reuse", () => {
|
||||
const allLines = Array.from({ length: 100 }, (_, i) => {
|
||||
if (i === 0) return "```markdown";
|
||||
if (i === 99) return "```";
|
||||
if (i % 10 === 0) return "```javascript";
|
||||
if (i % 10 === 5) return "```";
|
||||
return `line ${i}`;
|
||||
});
|
||||
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Test that we can call multiple times without recomputing everything
|
||||
const start = performance.now();
|
||||
|
||||
// Test several positions in sequence
|
||||
for (let i = 10; i < 90; i += 10) {
|
||||
if (allLines[i].trim() === "```") {
|
||||
shouldStopAtMarkdownBlock(state, i);
|
||||
}
|
||||
}
|
||||
|
||||
const duration = performance.now() - start;
|
||||
expect(duration).toBeLessThan(10); // Should be very fast due to state caching
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterCodeBlockLines with optimized MarkdownBlockState", () => {
|
||||
it("should use optimized state tracker for markdown files", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown",
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"const config = { name: 'test' };",
|
||||
"```",
|
||||
"Final notes",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"README.md",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"const config = { name: 'test' };",
|
||||
"```",
|
||||
"Final notes",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should fall back to legacy behavior when no markdown nesting detected", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```typescript",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"script.ts",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should handle mixed markdown and code scenarios with optimization", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"## API Reference",
|
||||
"",
|
||||
"```javascript",
|
||||
"async function fetchData() {",
|
||||
" return await fetch('/api/data');",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"Usage notes and more documentation.",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"## API Reference",
|
||||
"",
|
||||
"```javascript",
|
||||
"async function fetchData() {",
|
||||
" return await fetch('/api/data');",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"Usage notes and more documentation.",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validatePatternInLine", () => {
|
||||
it("should return false when pattern is not found", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
"const x = 5;",
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(-1);
|
||||
expect(result.beforePattern).toBe("");
|
||||
});
|
||||
|
||||
it("should return false when pattern is preceded by non-whitespace", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
'const var[/CODE]Name = "test";',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(9);
|
||||
});
|
||||
|
||||
it("should return false when pattern is inside double quotes", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
'console.log("test [/CODE] end");',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(18);
|
||||
});
|
||||
|
||||
it("should return false when pattern is inside single quotes", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
"const message = 'test [/CODE] end';",
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(22);
|
||||
});
|
||||
|
||||
it("should return true when pattern is properly separated by whitespace", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
"some code [/CODE] more text",
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.patternIndex).toBe(10);
|
||||
expect(result.beforePattern).toBe("some code ");
|
||||
});
|
||||
|
||||
it("should return true when pattern is at start of line", () => {
|
||||
const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.patternIndex).toBe(0);
|
||||
expect(result.beforePattern).toBe("");
|
||||
});
|
||||
|
||||
it("should return true when pattern has only whitespace before it", () => {
|
||||
const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.patternIndex).toBe(4);
|
||||
expect(result.beforePattern).toBe(" ");
|
||||
});
|
||||
|
||||
it("should handle complex quote scenarios correctly", () => {
|
||||
// Unmatched quote should make it invalid
|
||||
const result1 = lineStream.validatePatternInLine(
|
||||
'const x = "unclosed quote [/CODE]',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result1.isValid).toBe(false);
|
||||
|
||||
// Matched quotes should make it valid
|
||||
const result2 = lineStream.validatePatternInLine(
|
||||
'const x = "closed"; [/CODE]',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result2.isValid).toBe(true);
|
||||
});
|
||||
|
||||
it("should work with different patterns", () => {
|
||||
const result1 = lineStream.validatePatternInLine(
|
||||
"# End of file. Done",
|
||||
"# End of file.",
|
||||
);
|
||||
expect(result1.isValid).toBe(true);
|
||||
|
||||
const result2 = lineStream.validatePatternInLine(" ```", "```");
|
||||
expect(result2.isValid).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -438,7 +438,7 @@ export class ConfigHandler {
|
|||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
errors: [{ message: "Current profile not found", fatal: true }],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
|
@ -494,7 +494,7 @@ export class ConfigHandler {
|
|||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
errors: [{ message: "Current profile not found", fatal: true }],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
|
@ -507,7 +507,7 @@ export class ConfigHandler {
|
|||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
errors: [{ message: "Current profile not found", fatal: true }],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1057,6 +1057,7 @@ declare global {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
originalFileContent?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
ruleFile: rule.sourceFile,
|
||||
alwaysApply: rule.alwaysApply,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -400,7 +400,10 @@ export class Core {
|
|||
|
||||
on("controlPlane/openUrl", async (msg) => {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
let url = `${env.APP_URL}${msg.data.path}`;
|
||||
const urlPath = msg.data.path.startsWith("/")
|
||||
? msg.data.path.slice(1)
|
||||
: msg.data.path;
|
||||
let url = `${env.APP_URL}${urlPath}`;
|
||||
if (msg.data.orgSlug) {
|
||||
url += `?org=${msg.data.orgSlug}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
import { ILLM } from "../..";
|
||||
import {
|
||||
filterLeadingNewline,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { dedent } from "../../util";
|
||||
|
||||
|
|
@ -90,11 +87,18 @@ export async function* getReplacementWithLlm(
|
|||
{ role: "assistant", content: assistantPrompt },
|
||||
],
|
||||
abortController.signal,
|
||||
{
|
||||
raw: true,
|
||||
prediction: undefined,
|
||||
reasoning: false,
|
||||
},
|
||||
);
|
||||
|
||||
let lines = streamLines(completion);
|
||||
lines = filterLeadingNewline(lines);
|
||||
lines = stopAtLines(lines, () => {}, ["```"]);
|
||||
// We want to retrive everything from the llm
|
||||
// then let the filterCodeBlocks function clean up for any trailing text.
|
||||
// if we stop here early, we run the risk of loosing inner markdown content.
|
||||
|
||||
for await (const line of lines) {
|
||||
yield line;
|
||||
|
|
|
|||
459
core/edit/lazy/streamLazyApply.test.ts
Normal file
459
core/edit/lazy/streamLazyApply.test.ts
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
import { streamLazyApply } from "./streamLazyApply";
|
||||
|
||||
// Mock LLM for testing
|
||||
class MockLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response for markdown file with nested blocks
|
||||
const lines = [
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
".",
|
||||
"├── src/",
|
||||
"│ └── main.js",
|
||||
"└── package.json",
|
||||
"```",
|
||||
"```",
|
||||
];
|
||||
|
||||
// Yield each line separately (more realistic streaming)
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockJavaScriptLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response for JavaScript file
|
||||
const lines = [
|
||||
"function calculateSum(a, b) {",
|
||||
" return a + b;",
|
||||
"}",
|
||||
"",
|
||||
"function calculateProduct(a, b) {",
|
||||
" return a * b;",
|
||||
"}",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockPythonLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response for Python file
|
||||
const lines = [
|
||||
"def calculate_sum(a, b):",
|
||||
" return a + b",
|
||||
"",
|
||||
"def calculate_product(a, b):",
|
||||
" return a * b",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockWithUnchangedCodeLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response with UNCHANGED_CODE markers
|
||||
const lines = [
|
||||
"function newFunction() {",
|
||||
" return 'new';",
|
||||
"}",
|
||||
"",
|
||||
"// ... unchanged code ...",
|
||||
"",
|
||||
"function anotherFunction() {",
|
||||
" return 'updated';",
|
||||
"}",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockTypeScriptLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
const lines = [
|
||||
"interface User {",
|
||||
" id: number;",
|
||||
" name: string;",
|
||||
"}",
|
||||
"",
|
||||
"function getUser(id: number): User {",
|
||||
" return { id, name: 'Test User' };",
|
||||
"}",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockEmptyLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Empty response
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
class MockSimpleLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
const lines = ["function test() {", " return true;", "}"];
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockRegularMarkdownLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate regular markdown with simple code block
|
||||
const lines = [
|
||||
"# Debug Test Folder",
|
||||
"The sole purpose of this folder is to open it when debugging.",
|
||||
"",
|
||||
"## File Structure",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"├── Dockerfile",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("streamLazyApply", () => {
|
||||
test("should handle markdown files with nested blocks without stopping early", async () => {
|
||||
const oldCode = "# Project\n\nBasic readme content.";
|
||||
const newCode = `# Project Structure
|
||||
|
||||
\`\`\`markdown README.md
|
||||
# Project Structure
|
||||
|
||||
\`\`\`
|
||||
.
|
||||
├── src/
|
||||
│ └── main.js
|
||||
└── package.json
|
||||
\`\`\`
|
||||
\`\`\``;
|
||||
const filename = "README.md";
|
||||
const llm = new MockLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines (not empty)
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the nested markdown content
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("```markdown README.md");
|
||||
expect(allContent).toContain("└── package.json");
|
||||
|
||||
// Should not have been truncated at the first ```
|
||||
expect(allContent).toContain("src/");
|
||||
});
|
||||
|
||||
test("should handle JavaScript files correctly", async () => {
|
||||
const oldCode = "function calculateSum(a, b) {\n return a + b;\n}";
|
||||
const newCode = `function calculateSum(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function calculateProduct(a, b) {
|
||||
return a * b;
|
||||
}`;
|
||||
const filename = "calculator.js";
|
||||
const llm = new MockJavaScriptLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the JavaScript functions
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("calculateSum");
|
||||
expect(allContent).toContain("calculateProduct");
|
||||
});
|
||||
|
||||
test("should handle Python files correctly", async () => {
|
||||
const oldCode = "def calculate_sum(a, b):\n return a + b";
|
||||
const newCode = `def calculate_sum(a, b):
|
||||
return a + b
|
||||
|
||||
def calculate_product(a, b):
|
||||
return a * b`;
|
||||
const filename = "calculator.py";
|
||||
const llm = new MockPythonLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the Python functions
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("calculate_sum");
|
||||
expect(allContent).toContain("calculate_product");
|
||||
});
|
||||
|
||||
test("should handle UNCHANGED_CODE markers in responses", async () => {
|
||||
const oldCode = `function oldFunction() {
|
||||
return 'old';
|
||||
}
|
||||
|
||||
function existingFunction() {
|
||||
return 'existing';
|
||||
}`;
|
||||
const newCode = `function newFunction() {
|
||||
return 'new';
|
||||
}
|
||||
|
||||
function existingFunction() {
|
||||
return 'existing';
|
||||
}
|
||||
|
||||
function anotherFunction() {
|
||||
return 'updated';
|
||||
}`;
|
||||
const filename = "example.js";
|
||||
const llm = new MockWithUnchangedCodeLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain new and updated functions
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("newFunction");
|
||||
expect(allContent).toContain("anotherFunction");
|
||||
});
|
||||
|
||||
test("should handle TypeScript files correctly", async () => {
|
||||
const oldCode = "interface User {\n id: number;\n}";
|
||||
const newCode = `interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function getUser(id: number): User {
|
||||
return { id, name: 'Test User' };
|
||||
}`;
|
||||
const filename = "user.ts";
|
||||
const llm = new MockTypeScriptLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain TypeScript interface and function
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("interface User");
|
||||
expect(allContent).toContain("getUser");
|
||||
expect(allContent).toContain("name: string");
|
||||
});
|
||||
|
||||
test("should work with empty LLM responses", async () => {
|
||||
const oldCode = "function test() { return 1; }";
|
||||
const newCode = "function test() { return 2; }";
|
||||
const filename = "test.js";
|
||||
const llm = new MockEmptyLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should handle empty response gracefully
|
||||
expect(diffLines).toBeDefined();
|
||||
});
|
||||
|
||||
test("should correctly identify markdown vs non-markdown files", async () => {
|
||||
// Test that our isMarkdownFile logic works
|
||||
const markdownFiles = ["README.md", "docs.markdown", "example.gfm"];
|
||||
const nonMarkdownFiles = [
|
||||
"script.js",
|
||||
"code.py",
|
||||
"style.css",
|
||||
"component.tsx",
|
||||
];
|
||||
|
||||
// This is more of a unit test, but verifies our file detection logic
|
||||
// We can test this indirectly by checking that different file types
|
||||
// are processed through different code paths
|
||||
|
||||
const oldCode = "function test() { return false; }";
|
||||
const newCode = "function test() { return true; }";
|
||||
const llm = new MockSimpleLLM() as any;
|
||||
|
||||
// Test each file type
|
||||
for (const filename of [...markdownFiles, ...nonMarkdownFiles]) {
|
||||
const abortController = new AbortController();
|
||||
const diffLines = [];
|
||||
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should work for all file types
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("test");
|
||||
}
|
||||
});
|
||||
|
||||
test("should handle regular markdown files with simple code blocks", async () => {
|
||||
const oldCode = "# Old Content";
|
||||
const newCode = `# Debug Test Folder
|
||||
The sole purpose of this folder is to open it when debugging.
|
||||
|
||||
## File Structure
|
||||
\`\`\`
|
||||
debug-test-folder/
|
||||
├── AdvancedPage.tsx
|
||||
├── Calculator.java
|
||||
├── Dockerfile
|
||||
└── test.ts
|
||||
\`\`\``;
|
||||
|
||||
const filename = "README.md";
|
||||
const llm = new MockRegularMarkdownLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines (not empty)
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the full file structure
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("Debug Test Folder");
|
||||
expect(allContent).toContain("File Structure");
|
||||
expect(allContent).toContain("debug-test-folder/");
|
||||
expect(allContent).toContain("├── AdvancedPage.tsx");
|
||||
expect(allContent).toContain("└── test.ts");
|
||||
|
||||
// Should not have been truncated at the opening ```
|
||||
expect(allContent).toContain("Calculator.java");
|
||||
expect(allContent).toContain("Dockerfile");
|
||||
});
|
||||
});
|
||||
|
|
@ -2,11 +2,11 @@ import {
|
|||
filterLeadingAndTrailingNewLineInsertion,
|
||||
filterLeadingNewline,
|
||||
removeTrailingWhitespace,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
|
||||
import { streamDiff } from "../../diff/streamDiff.js";
|
||||
import { LineStream, streamLines } from "../../diff/util.js";
|
||||
import { DiffLine, ILLM } from "../../index.js";
|
||||
import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js";
|
||||
|
||||
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
|
||||
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
|
||||
|
|
@ -44,9 +44,12 @@ export async function* streamLazyApply(
|
|||
}
|
||||
|
||||
let lazyCompletionLines = streamLines(lazyCompletion, true);
|
||||
// Process line output
|
||||
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
|
||||
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
|
||||
|
||||
lazyCompletionLines = stopAtLinesWithMarkdownSupport(
|
||||
lazyCompletionLines,
|
||||
filename,
|
||||
);
|
||||
|
||||
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
|
||||
lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines);
|
||||
|
||||
|
|
@ -92,7 +95,6 @@ async function* streamFillUnchangedCode(
|
|||
newLines.push(replacementLine);
|
||||
replacement += replacementLine + "\n";
|
||||
}
|
||||
|
||||
// Yield the buffered lines
|
||||
for (const bufferedLine of buffer) {
|
||||
yield bufferedLine;
|
||||
|
|
|
|||
|
|
@ -63,7 +63,8 @@ export async function* recursiveStream(
|
|||
}
|
||||
} else {
|
||||
const generator = llm.streamChat(prompt, abortController.signal, {
|
||||
prediction,
|
||||
raw: true,
|
||||
prediction: undefined,
|
||||
reasoning: false,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -55,11 +55,7 @@ export async function* addIndentation(
|
|||
}
|
||||
|
||||
function modelIsInept(model: string): boolean {
|
||||
return !(
|
||||
model.includes("gpt") ||
|
||||
model.includes("claude") ||
|
||||
model.includes("nova")
|
||||
);
|
||||
return !(model.includes("gpt") || model.includes("claude"));
|
||||
}
|
||||
|
||||
export async function* streamDiffLines({
|
||||
|
|
|
|||
1
core/index.d.ts
vendored
1
core/index.d.ts
vendored
|
|
@ -1361,6 +1361,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
originalFileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import path from "path";
|
||||
|
||||
import { shouldChunk } from "./chunk";
|
||||
import { Chunk, ChunkWithoutID } from "../../index.js";
|
||||
import { cleanupAsyncEncoders } from "../../llm/countTokens.js";
|
||||
import { chunkDocument, chunkDocumentWithoutId, shouldChunk } from "./chunk";
|
||||
|
||||
describe("shouldChunk", () => {
|
||||
test("should chunk a typescript file", () => {
|
||||
|
|
@ -28,6 +30,126 @@ describe("shouldChunk", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("chunkDocument", () => {
|
||||
afterAll(async () => {
|
||||
// Clean up the global async encoders to prevent Jest from hanging
|
||||
await cleanupAsyncEncoders();
|
||||
});
|
||||
|
||||
test("should return multiple chunks for large content with small maxChunkSize", async () => {
|
||||
const filepath = "/test/file.txt";
|
||||
const maxChunkSize = 10; // small limit
|
||||
const digest = "test-digest";
|
||||
|
||||
// Create content with multiple short lines - each line should fit within maxChunkSize
|
||||
const lines = ["short line", "another line", "third line"];
|
||||
const contents = lines.join("\n");
|
||||
|
||||
const chunks: Chunk[] = [];
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize,
|
||||
digest,
|
||||
})) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
// Verify chunks have valid content
|
||||
chunks.forEach((chunk) => {
|
||||
expect(chunk.content.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("should filter out chunks that exceed maxChunkSize in tokens", async () => {
|
||||
const filepath = "/test/large.txt";
|
||||
const maxChunkSize = 10; // small limit
|
||||
const digest = "test-digest-2";
|
||||
|
||||
const contents =
|
||||
"This is a much longer line with many words that will likely exceed the maxChunkSize token limit and should be filtered out by the chunkDocument function. This is a much longer line with many words that will likely exceed the maxChunkSize token limit and should be filtered out by the chunkDocument function.";
|
||||
|
||||
const chunks: Chunk[] = [];
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize,
|
||||
digest,
|
||||
})) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
// Verify that no chunks were created since the content exceeds maxChunkSize
|
||||
chunks.forEach((chunk) => {
|
||||
expect(chunk.content.length).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("chunkDocumentWithoutId", () => {
|
||||
afterAll(async () => {
|
||||
await cleanupAsyncEncoders();
|
||||
});
|
||||
|
||||
test("should return no chunks for empty content", async () => {
|
||||
const contents = "";
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.txt",
|
||||
contents,
|
||||
100,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("should chunk text files", async () => {
|
||||
const contents = "Line 1\nLine 2\nLine 3";
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.txt",
|
||||
contents,
|
||||
100,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks.length).toBeGreaterThan(0);
|
||||
expect(chunks[0].content).toContain("Line 1");
|
||||
});
|
||||
|
||||
test("should chunk for code files", async () => {
|
||||
const contents = "function test() {\n return 42;\n}";
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.js",
|
||||
contents,
|
||||
100,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks.length).toBeGreaterThan(0);
|
||||
expect(chunks[0].content).toContain("function test");
|
||||
});
|
||||
|
||||
test("should chunk large content", async () => {
|
||||
const contents = Array(100).fill("short line").join("\n"); // Large content with many lines
|
||||
const maxChunkSize = 50;
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.txt",
|
||||
contents,
|
||||
maxChunkSize,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks.length).toBeGreaterThan(1); // Should create multiple chunks
|
||||
chunks.forEach((chunk) => {
|
||||
expect(chunk.content.length).toBeGreaterThan(0); // Each chunk should have content
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function generateString(length: number) {
|
||||
return "a".repeat(length);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export type ChunkDocumentParam = {
|
|||
digest: string;
|
||||
};
|
||||
|
||||
async function* chunkDocumentWithoutId(
|
||||
export async function* chunkDocumentWithoutId(
|
||||
fileUri: string,
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 32_768;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
const DEFAULT_PRUNING_LENGTH = 128000;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
maxTokens: DEFAULT_MAX_TOKENS,
|
||||
|
|
@ -24,5 +25,6 @@ export {
|
|||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_PRUNING_LENGTH,
|
||||
PROXY_URL,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
// Generated by continue
|
||||
import { ChatMessage, MessagePart, ToolCall } from "../index.js";
|
||||
import {
|
||||
cleanupAsyncEncoders,
|
||||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
|
|
@ -27,7 +28,12 @@ describe.skip("countTokens", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe.skip("countTokensAsync", () => {
|
||||
describe("countTokensAsync", () => {
|
||||
afterAll(async () => {
|
||||
// Clean up the global async encoders to prevent Jest from hanging
|
||||
await cleanupAsyncEncoders();
|
||||
});
|
||||
|
||||
it("should count tokens asynchronously for a simple string", async () => {
|
||||
const content = "Hello world!";
|
||||
const tokenCount = await countTokensAsync(content, "gpt-4");
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
|
||||
import { DEFAULT_PRUNING_LENGTH } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
|
|
@ -409,14 +410,14 @@ function pruneRawPromptFromTop(
|
|||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
contextLength,
|
||||
knownContextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
tools,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[];
|
||||
contextLength: number;
|
||||
knownContextLength: number | undefined;
|
||||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
tools?: Tool[];
|
||||
|
|
@ -465,6 +466,7 @@ function compileChatMessages({
|
|||
toolTokens = countToolsTokens(tools, modelName);
|
||||
}
|
||||
|
||||
const contextLength = knownContextLength ?? DEFAULT_PRUNING_LENGTH;
|
||||
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
|
||||
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
|
||||
|
|
@ -480,12 +482,12 @@ function compileChatMessages({
|
|||
inputTokensAvailable -= lastMessagesTokens;
|
||||
|
||||
// Make sure there's enough context for the non-excludable items
|
||||
if (inputTokensAvailable < 0) {
|
||||
if (knownContextLength !== undefined && inputTokensAvailable < 0) {
|
||||
throw new Error(
|
||||
`Not enough context available to include the system message, last user message, and tools.
|
||||
There must be at least ${minOutputTokens} tokens remaining for output.
|
||||
Request had the following token counts:
|
||||
- contextLength: ${contextLength}
|
||||
- contextLength: ${knownContextLength}
|
||||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
|
|
@ -536,7 +538,14 @@ function compileChatMessages({
|
|||
};
|
||||
}
|
||||
|
||||
async function cleanupAsyncEncoders(): Promise<void> {
|
||||
try {
|
||||
await llamaAsyncEncoder.close();
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
export {
|
||||
cleanupAsyncEncoders,
|
||||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
|
|
|
|||
|
|
@ -145,7 +145,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
baseChatSystemMessage?: string;
|
||||
basePlanSystemMessage?: string;
|
||||
baseAgentSystemMessage?: string;
|
||||
contextLength: number;
|
||||
_contextLength: number | undefined;
|
||||
maxStopWords?: number | undefined;
|
||||
completionOptions: CompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
|
|
@ -220,8 +220,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.baseAgentSystemMessage = options.baseAgentSystemMessage;
|
||||
this.basePlanSystemMessage = options.basePlanSystemMessage;
|
||||
this.baseChatSystemMessage = options.baseChatSystemMessage;
|
||||
this.contextLength =
|
||||
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
|
||||
this._contextLength = options.contextLength ?? llmInfo?.contextLength;
|
||||
this.maxStopWords = options.maxStopWords ?? this.maxStopWords;
|
||||
this.completionOptions = {
|
||||
...options.completionOptions,
|
||||
|
|
@ -296,6 +295,10 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.sourceFile = options.sourceFile;
|
||||
}
|
||||
|
||||
get contextLength() {
|
||||
return this._contextLength ?? DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
return LLMConfigurationStatuses.VALID;
|
||||
}
|
||||
|
|
@ -896,7 +899,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
return compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: message,
|
||||
contextLength: this.contextLength,
|
||||
knownContextLength: this._contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
|
|
@ -945,7 +948,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
const { compiledChatMessages } = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
knownContextLength: this._contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
|
|
|
|||
|
|
@ -172,52 +172,10 @@ class Anthropic extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
async *handleResponse(
|
||||
response: any,
|
||||
stream: boolean | undefined,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.apiKey || this.apiKey === "") {
|
||||
throw new Error(
|
||||
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
|
||||
);
|
||||
}
|
||||
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": this.apiKey as string,
|
||||
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
|
||||
? { "anthropic-beta": "prompt-caching-2024-07-31" }
|
||||
: {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this.convertArgs(options),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (response.status === 499) {
|
||||
return; // Aborted by user
|
||||
}
|
||||
|
|
@ -237,7 +195,7 @@ class Anthropic extends BaseLLM {
|
|||
);
|
||||
}
|
||||
|
||||
if (options.stream === false) {
|
||||
if (stream === false) {
|
||||
const data = await response.json();
|
||||
const cost = data.usage
|
||||
? {
|
||||
|
|
@ -348,6 +306,55 @@ class Anthropic extends BaseLLM {
|
|||
usage,
|
||||
};
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.apiKey || this.apiKey === "") {
|
||||
throw new Error(
|
||||
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
|
||||
);
|
||||
}
|
||||
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": this.apiKey as string,
|
||||
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
|
||||
? { "anthropic-beta": "prompt-caching-2024-07-31" }
|
||||
: {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this.convertArgs(options),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
yield* this.handleResponse(response, options.stream);
|
||||
}
|
||||
}
|
||||
|
||||
export default Anthropic;
|
||||
|
|
|
|||
|
|
@ -200,6 +200,7 @@ class Gemini extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
isV1API: boolean,
|
||||
includeToolIds: boolean,
|
||||
): GeminiChatRequestBody {
|
||||
const toolCallIdToNameMap = new Map<string, string>();
|
||||
messages.forEach((msg) => {
|
||||
|
|
@ -231,7 +232,7 @@ class Gemini extends BaseLLM {
|
|||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: msg.toolCallId,
|
||||
id: includeToolIds ? msg.toolCallId : undefined,
|
||||
name: functionName || "unknown",
|
||||
response: {
|
||||
output: msg.content, // "output" key is opinionated - not all functions will output objects
|
||||
|
|
@ -406,7 +407,7 @@ class Gemini extends BaseLLM {
|
|||
const isV1API = !!this.apiBase?.includes("/v1/");
|
||||
|
||||
// Convert chat messages to contents
|
||||
const body = this.prepareBody(messages, options, isV1API);
|
||||
const body = this.prepareBody(messages, options, isV1API, true);
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ class HuggingFaceTGI extends BaseLLM {
|
|||
}
|
||||
const json = await response.json();
|
||||
this.model = json.model_id;
|
||||
this.contextLength = Number.parseInt(json.max_input_length);
|
||||
this._contextLength = Number.parseInt(json.max_input_length);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log(`Failed to list models for HuggingFace TGI: ${e.message}`);
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ class Mistral extends OpenAI {
|
|||
return Mistral.modelConversion[model] ?? model;
|
||||
}
|
||||
|
||||
protected _convertArgs(options: any, messages: ChatMessage[]) {
|
||||
_convertArgs(options: any, messages: ChatMessage[]) {
|
||||
const finalOptions = super._convertArgs(options, messages);
|
||||
|
||||
const lastMessage = finalOptions.messages[finalOptions.messages.length - 1];
|
||||
|
|
|
|||
|
|
@ -184,7 +184,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
let value = parts[2];
|
||||
switch (key) {
|
||||
case "num_ctx":
|
||||
this.contextLength =
|
||||
this._contextLength =
|
||||
options.contextLength ?? Number.parseInt(value);
|
||||
break;
|
||||
case "stop":
|
||||
|
|
|
|||
|
|
@ -254,24 +254,7 @@ class VertexAI extends BaseLLM {
|
|||
signal,
|
||||
});
|
||||
|
||||
if (response.status === 499) {
|
||||
return; // Aborted by user
|
||||
}
|
||||
|
||||
if (options.stream === false) {
|
||||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.content[0].text };
|
||||
return;
|
||||
}
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.type === "message_start") {
|
||||
console.log(value);
|
||||
}
|
||||
if (value.delta?.text) {
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
}
|
||||
}
|
||||
yield* this.anthropicInstance.handleResponse(response, options.stream);
|
||||
}
|
||||
|
||||
// Gemini
|
||||
|
|
@ -285,17 +268,19 @@ class VertexAI extends BaseLLM {
|
|||
this.apiBase,
|
||||
);
|
||||
|
||||
const body = this.geminiInstance.prepareBody(messages, options, false);
|
||||
// For some reason gemini through vertex does not support ids in functionResponses yet
|
||||
const body = this.geminiInstance.prepareBody(
|
||||
messages,
|
||||
options,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
for await (const message of this.geminiInstance.processGeminiResponse(
|
||||
streamResponse(response),
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
yield* this.geminiInstance.processGeminiResponse(streamResponse(response));
|
||||
}
|
||||
|
||||
private async *streamChatBison(
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ class Vllm extends OpenAI {
|
|||
const json = await response.json();
|
||||
const data = json.data[0];
|
||||
this.model = data.id;
|
||||
this.contextLength = Number.parseInt(data.max_model_len);
|
||||
this._contextLength = Number.parseInt(data.max_model_len);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log(`Failed to list models for vLLM: ${e.message}`);
|
||||
|
|
|
|||
|
|
@ -84,11 +84,12 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
return model.toLowerCase().includes("gemini");
|
||||
},
|
||||
vertexai: (model) => {
|
||||
const lowerCaseModel = model.toLowerCase();
|
||||
// All gemini models except flash 2.0 lite support function calling
|
||||
return (
|
||||
model.toLowerCase().includes("gemini") &&
|
||||
!model.toLowerCase().includes("lite")
|
||||
);
|
||||
if (lowerCaseModel.includes("lite")) {
|
||||
return false;
|
||||
}
|
||||
return ["claude", "gemini"].some((val) => lowerCaseModel.includes(val));
|
||||
},
|
||||
bedrock: (model) => {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ describe.skip("generateRepoMap", () => {
|
|||
});
|
||||
|
||||
// Set testLLM properties
|
||||
testLLM.contextLength = 2048;
|
||||
testLLM._contextLength = 2048;
|
||||
testLLM.countTokens = jest.fn().mockReturnValue(10);
|
||||
|
||||
// Act
|
||||
|
|
@ -115,7 +115,7 @@ describe.skip("generateRepoMap", () => {
|
|||
});
|
||||
|
||||
// Set testLLM properties
|
||||
testLLM.contextLength = 2048;
|
||||
testLLM._contextLength = 2048;
|
||||
testLLM.countTokens = jest.fn().mockReturnValue(10);
|
||||
|
||||
// Act
|
||||
|
|
@ -184,7 +184,7 @@ describe.skip("generateRepoMap", () => {
|
|||
.mockImplementation(() => {});
|
||||
|
||||
// Set testLLM properties
|
||||
testLLM.contextLength = 2048;
|
||||
testLLM._contextLength = 2048;
|
||||
testLLM.countTokens = jest.fn().mockReturnValue(10);
|
||||
|
||||
// Act
|
||||
|
|
|
|||
136
core/utils/markdownUtils.ts
Normal file
136
core/utils/markdownUtils.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
/**
|
||||
* Utility functions for working with markdown files and code blocks
|
||||
*/
|
||||
|
||||
/**
|
||||
* Determines if a code block header indicates markdown content
|
||||
*/
|
||||
export function headerIsMarkdown(header: string): boolean {
|
||||
return (
|
||||
header === "md" ||
|
||||
header === "markdown" ||
|
||||
header === "gfm" ||
|
||||
header === "github-markdown" ||
|
||||
header.includes(" md") ||
|
||||
header.includes(" markdown") ||
|
||||
header.includes(" gfm") ||
|
||||
header.includes(" github-markdown") ||
|
||||
header.split(" ")[0]?.split(".").pop() === "md" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "gfm"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a file is a markdown file based on its filepath.
|
||||
*/
|
||||
export function isMarkdownFile(filepath?: string): boolean {
|
||||
if (!filepath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ext = filepath.split(".").pop()?.toLowerCase() || "";
|
||||
return ["md", "markdown", "gfm"].includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* State tracker for markdown block analysis to avoid recomputing on each call.
|
||||
* Optimized to handle nested markdown code blocks.
|
||||
*/
|
||||
export class MarkdownBlockStateTracker {
|
||||
protected trimmedLines: string[];
|
||||
protected bareBacktickPositions: number[];
|
||||
private markdownNestCount: number = 0;
|
||||
private lastProcessedIndex: number = -1;
|
||||
|
||||
constructor(allLines: string[]) {
|
||||
this.trimmedLines = allLines.map((l) => l.trim());
|
||||
// Pre-compute positions of all bare backtick lines for faster lookup
|
||||
this.bareBacktickPositions = [];
|
||||
for (let i = 0; i < this.trimmedLines.length; i++) {
|
||||
if (this.trimmedLines[i].match(/^`+$/)) {
|
||||
this.bareBacktickPositions.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if we should stop at the given markdown block position.
|
||||
* Maintains state across calls to avoid redundant computation.
|
||||
*/
|
||||
shouldStopAtPosition(currentIndex: number): boolean {
|
||||
if (this.trimmedLines[currentIndex] !== "```") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Process any lines we haven't seen yet up to currentIndex
|
||||
for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) {
|
||||
const currentLine = this.trimmedLines[j];
|
||||
|
||||
if (this.markdownNestCount > 0) {
|
||||
// Inside a markdown block
|
||||
if (currentLine.match(/^`+$/)) {
|
||||
// Found bare backticks - check if this is the last one
|
||||
if (j === currentIndex) {
|
||||
const remainingBareBackticks =
|
||||
this.getRemainingBareBackticksAfter(j);
|
||||
if (remainingBareBackticks === 0) {
|
||||
this.markdownNestCount = 0;
|
||||
this.lastProcessedIndex = j;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (currentLine.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
this.markdownNestCount++;
|
||||
}
|
||||
} else {
|
||||
// Not inside a markdown block yet
|
||||
if (currentLine.startsWith("```")) {
|
||||
const header = currentLine.replaceAll("`", "");
|
||||
if (headerIsMarkdown(header)) {
|
||||
this.markdownNestCount = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.lastProcessedIndex = currentIndex;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Efficiently determines if there are remaining bare backticks after the given position.
|
||||
*/
|
||||
getRemainingBareBackticksAfter(currentIndex: number): number {
|
||||
return this.bareBacktickPositions.filter((pos) => pos > currentIndex)
|
||||
.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the line at the given index is a bare backtick line.
|
||||
*/
|
||||
isBareBacktickLine(index: number): boolean {
|
||||
return this.bareBacktickPositions.includes(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the trimmed lines array.
|
||||
*/
|
||||
getTrimmedLines(): string[] {
|
||||
return this.trimmedLines;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all lines from a LineStream into an array for analysis.
|
||||
*/
|
||||
export async function collectAllLines<T>(
|
||||
stream: AsyncGenerator<T>,
|
||||
): Promise<T[]> {
|
||||
const allLines: T[] = [];
|
||||
for await (const line of stream) {
|
||||
allLines.push(line);
|
||||
}
|
||||
return allLines;
|
||||
}
|
||||
306
core/utils/markdownUtils.vitest.ts
Normal file
306
core/utils/markdownUtils.vitest.ts
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
collectAllLines,
|
||||
headerIsMarkdown,
|
||||
isMarkdownFile,
|
||||
MarkdownBlockStateTracker,
|
||||
} from "./markdownUtils";
|
||||
|
||||
describe("headerIsMarkdown", () => {
|
||||
// Test exact match with common Markdown identifiers
|
||||
it("should identify exact matches with common Markdown identifiers", () => {
|
||||
expect(headerIsMarkdown("md")).toBe(true);
|
||||
expect(headerIsMarkdown("markdown")).toBe(true);
|
||||
expect(headerIsMarkdown("gfm")).toBe(true);
|
||||
expect(headerIsMarkdown("github-markdown")).toBe(true);
|
||||
});
|
||||
|
||||
// Test identifiers preceded by a space
|
||||
it("should identify identifiers preceded by a space", () => {
|
||||
expect(headerIsMarkdown("lang md")).toBe(true);
|
||||
expect(headerIsMarkdown("something markdown")).toBe(true);
|
||||
expect(headerIsMarkdown("language gfm")).toBe(true);
|
||||
expect(headerIsMarkdown("spec github-markdown")).toBe(true);
|
||||
});
|
||||
|
||||
// Test file extensions
|
||||
it("should identify file names with markdown extensions", () => {
|
||||
expect(headerIsMarkdown("example.md")).toBe(true);
|
||||
expect(headerIsMarkdown("document.markdown")).toBe(true);
|
||||
expect(headerIsMarkdown("readme.gfm")).toBe(true);
|
||||
});
|
||||
|
||||
// Test more complex cases with extensions
|
||||
it("should identify file names with markdown extensions followed by other text", () => {
|
||||
expect(headerIsMarkdown("example.md additional text")).toBe(true);
|
||||
expect(headerIsMarkdown("document.markdown with some description")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
|
||||
});
|
||||
|
||||
// Test non-markdown cases
|
||||
it("should not identify non-markdown headers", () => {
|
||||
expect(headerIsMarkdown("javascript")).toBe(false);
|
||||
expect(headerIsMarkdown("typescript")).toBe(false);
|
||||
expect(headerIsMarkdown("plain")).toBe(false);
|
||||
expect(headerIsMarkdown("python")).toBe(false);
|
||||
});
|
||||
|
||||
// Test edge cases
|
||||
it("should handle edge cases correctly", () => {
|
||||
expect(headerIsMarkdown("")).toBe(false);
|
||||
expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
|
||||
expect(headerIsMarkdown("readme md")).toBe(true);
|
||||
expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
|
||||
});
|
||||
|
||||
// Test case sensitivity
|
||||
it("should respect case sensitivity", () => {
|
||||
expect(headerIsMarkdown("MD")).toBe(false);
|
||||
expect(headerIsMarkdown("MARKDOWN")).toBe(false);
|
||||
expect(headerIsMarkdown("example.MD")).toBe(false);
|
||||
expect(headerIsMarkdown("lang MD")).toBe(false);
|
||||
});
|
||||
|
||||
// Test with special characters and spacing
|
||||
it("should handle special characters and spacing correctly", () => {
|
||||
expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
|
||||
expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
|
||||
expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
|
||||
expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
|
||||
});
|
||||
});
|
||||
|
||||
describe("isMarkdownFile", () => {
|
||||
it("should identify markdown files by .md extension", () => {
|
||||
expect(isMarkdownFile("README.md")).toBe(true);
|
||||
expect(isMarkdownFile("docs/guide.md")).toBe(true);
|
||||
expect(isMarkdownFile("/path/to/file.md")).toBe(true);
|
||||
});
|
||||
|
||||
it("should identify markdown files by .markdown extension", () => {
|
||||
expect(isMarkdownFile("README.markdown")).toBe(true);
|
||||
expect(isMarkdownFile("docs/guide.markdown")).toBe(true);
|
||||
expect(isMarkdownFile("/path/to/file.markdown")).toBe(true);
|
||||
});
|
||||
|
||||
it("should identify markdown files by .gfm extension", () => {
|
||||
expect(isMarkdownFile("README.gfm")).toBe(true);
|
||||
expect(isMarkdownFile("docs/guide.gfm")).toBe(true);
|
||||
expect(isMarkdownFile("/path/to/file.gfm")).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle case insensitive extensions", () => {
|
||||
expect(isMarkdownFile("README.MD")).toBe(true);
|
||||
expect(isMarkdownFile("guide.MARKDOWN")).toBe(true);
|
||||
expect(isMarkdownFile("file.GFM")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for non-markdown files", () => {
|
||||
expect(isMarkdownFile("script.js")).toBe(false);
|
||||
expect(isMarkdownFile("style.css")).toBe(false);
|
||||
expect(isMarkdownFile("data.json")).toBe(false);
|
||||
expect(isMarkdownFile("document.txt")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for undefined or empty filepath", () => {
|
||||
expect(isMarkdownFile(undefined)).toBe(false);
|
||||
expect(isMarkdownFile("")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for files without extensions", () => {
|
||||
expect(isMarkdownFile("README")).toBe(false);
|
||||
expect(isMarkdownFile("Dockerfile")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle files with multiple dots", () => {
|
||||
expect(isMarkdownFile("file.backup.md")).toBe(true);
|
||||
expect(isMarkdownFile("config.test.js")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MarkdownBlockStateTracker", () => {
|
||||
it("should initialize correctly with empty lines", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([]);
|
||||
expect(tracker.shouldStopAtPosition(0)).toBe(false);
|
||||
});
|
||||
|
||||
it("should initialize correctly with non-markdown lines", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"const x = 5;",
|
||||
"console.log(x);",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(0)).toBe(false);
|
||||
expect(tracker.shouldStopAtPosition(1)).toBe(false);
|
||||
});
|
||||
|
||||
it("should detect simple markdown blocks", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```markdown",
|
||||
"# Title",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening
|
||||
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content
|
||||
expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing
|
||||
});
|
||||
|
||||
it("should handle nested code blocks within markdown", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```md",
|
||||
"Here's some code:",
|
||||
"```javascript",
|
||||
"console.log('hello');",
|
||||
"```",
|
||||
"More content",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
|
||||
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
|
||||
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
|
||||
});
|
||||
|
||||
it("should handle multiple bare backticks", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```markdown",
|
||||
"Content with ```inline``` code",
|
||||
"```",
|
||||
"More content",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks
|
||||
expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks
|
||||
});
|
||||
|
||||
it("should handle non-markdown code blocks", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```javascript",
|
||||
"console.log('hello');",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block
|
||||
});
|
||||
|
||||
it("should handle mixed markdown types", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```gfm",
|
||||
"# GitHub Flavored Markdown",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(2)).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle state persistence across multiple calls", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```markdown",
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"interface Config {}",
|
||||
"```",
|
||||
"Final notes",
|
||||
"```",
|
||||
]);
|
||||
|
||||
// Process incrementally
|
||||
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
|
||||
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
|
||||
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
|
||||
});
|
||||
|
||||
it("should handle lines that are not closing backticks", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```markdown",
|
||||
"Regular content line",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks
|
||||
});
|
||||
|
||||
it("should provide access to trimmed lines", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
" ```markdown ",
|
||||
" # Title ",
|
||||
" ``` ",
|
||||
]);
|
||||
const trimmedLines = tracker.getTrimmedLines();
|
||||
expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]);
|
||||
});
|
||||
|
||||
it("should identify bare backtick lines correctly", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```markdown",
|
||||
"```",
|
||||
"content",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language
|
||||
expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks
|
||||
expect(tracker.isBareBacktickLine(2)).toBe(false); // Content
|
||||
expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks
|
||||
});
|
||||
|
||||
it("should count remaining bare backticks correctly", () => {
|
||||
const tracker = new MarkdownBlockStateTracker([
|
||||
"```markdown",
|
||||
"```",
|
||||
"content",
|
||||
"```",
|
||||
"more content",
|
||||
"```",
|
||||
]);
|
||||
expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening
|
||||
expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare
|
||||
expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare
|
||||
expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectAllLines", () => {
|
||||
async function* createAsyncGenerator<T>(items: T[]): AsyncGenerator<T> {
|
||||
for (const item of items) {
|
||||
yield item;
|
||||
}
|
||||
}
|
||||
|
||||
it("should collect all lines from a stream", async () => {
|
||||
const stream = createAsyncGenerator(["line1", "line2", "line3"]);
|
||||
const result = await collectAllLines(stream);
|
||||
expect(result).toEqual(["line1", "line2", "line3"]);
|
||||
});
|
||||
|
||||
it("should handle empty streams", async () => {
|
||||
const stream = createAsyncGenerator([]);
|
||||
const result = await collectAllLines(stream);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle streams with mixed types", async () => {
|
||||
const stream = createAsyncGenerator([1, "text", null, true]);
|
||||
const result = await collectAllLines(stream);
|
||||
expect(result).toEqual([1, "text", null, true]);
|
||||
});
|
||||
|
||||
it("should handle streams with empty strings", async () => {
|
||||
const stream = createAsyncGenerator(["", "line2", "", "line4"]);
|
||||
const result = await collectAllLines(stream);
|
||||
expect(result).toEqual(["", "line2", "", "line4"]);
|
||||
});
|
||||
|
||||
it("should handle large streams", async () => {
|
||||
const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`);
|
||||
const stream = createAsyncGenerator(largeArray);
|
||||
const result = await collectAllLines(stream);
|
||||
expect(result).toEqual(largeArray);
|
||||
});
|
||||
|
||||
it("should handle object streams", async () => {
|
||||
const objects = [
|
||||
{ type: "new", line: "const x = 5;" },
|
||||
{ type: "old", line: "let y = 10;" },
|
||||
];
|
||||
const stream = createAsyncGenerator(objects);
|
||||
const result = await collectAllLines(stream);
|
||||
expect(result).toEqual(objects);
|
||||
});
|
||||
});
|
||||
98
core/utils/streamMarkdownUtils.ts
Normal file
98
core/utils/streamMarkdownUtils.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { LineStream } from "../diff/util";
|
||||
import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils";
|
||||
|
||||
/**
|
||||
* Determines if we should stop at a markdown block based on nested markdown logic.
|
||||
* This handles the complex case where markdown blocks contain other markdown blocks.
|
||||
* Uses optimized state tracking to avoid redundant computation.
|
||||
*/
|
||||
export function shouldStopAtMarkdownBlock(
|
||||
stateTracker: MarkdownBlockStateTracker,
|
||||
currentIndex: number,
|
||||
): boolean {
|
||||
return stateTracker.shouldStopAtPosition(currentIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes block nesting logic and returns updated state.
|
||||
*/
|
||||
export function processBlockNesting(
|
||||
line: string,
|
||||
seenFirstFence: boolean,
|
||||
shouldRemoveLineBeforeStart: (line: string) => boolean,
|
||||
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
|
||||
if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) {
|
||||
return { newSeenFirstFence: false, shouldSkip: true };
|
||||
}
|
||||
|
||||
if (!seenFirstFence) {
|
||||
return { newSeenFirstFence: true, shouldSkip: false };
|
||||
}
|
||||
|
||||
return { newSeenFirstFence: seenFirstFence, shouldSkip: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream transformation that stops when encountering a markdown code block ending.
|
||||
* Handles nested markdown blocks in markdown files.
|
||||
*/
|
||||
export async function* stopAtLinesWithMarkdownSupport(
|
||||
lines: LineStream,
|
||||
filename: string,
|
||||
): LineStream {
|
||||
if (!isMarkdownFile(filename)) {
|
||||
for await (const line of lines) {
|
||||
if (line.trim() === "```") {
|
||||
return;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const allLines: string[] = [];
|
||||
for await (const line of lines) {
|
||||
allLines.push(line);
|
||||
}
|
||||
|
||||
const source = allLines.join("\n");
|
||||
if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) {
|
||||
// No nested markdown blocks detected, check for simple ``` stopping condition
|
||||
let foundStandaloneBackticks = false;
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
if (allLines[i].trim() === "```") {
|
||||
// Found standalone backticks, yield lines up to this point
|
||||
for (let j = 0; j < i; j++) {
|
||||
yield allLines[j];
|
||||
}
|
||||
foundStandaloneBackticks = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// No standalone backticks found, yield all lines
|
||||
if (!foundStandaloneBackticks) {
|
||||
for (const line of allLines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Use optimized state tracker for markdown block analysis
|
||||
const stateTracker = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
if (stateTracker.shouldStopAtPosition(i)) {
|
||||
for (let j = 0; j < i; j++) {
|
||||
yield allLines[j];
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, yield all lines
|
||||
for (const line of allLines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
102
core/utils/streamMarkdownUtils.vitest.ts
Normal file
102
core/utils/streamMarkdownUtils.vitest.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { LineStream } from "../diff/util";
|
||||
import {
|
||||
processBlockNesting,
|
||||
stopAtLinesWithMarkdownSupport,
|
||||
} from "./streamMarkdownUtils";
|
||||
|
||||
test("processBlockNesting correctly handles starting blocks", () => {
|
||||
// Mock function to determine which lines should be removed
|
||||
const shouldRemoveLineBeforeStart = (line: string) =>
|
||||
line === "[CODE]" || line === "```";
|
||||
|
||||
// Test not seeing first fence yet
|
||||
const result1 = processBlockNesting(
|
||||
"[CODE]",
|
||||
false,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
expect(result1.newSeenFirstFence).toBe(false);
|
||||
expect(result1.shouldSkip).toBe(true);
|
||||
|
||||
// Test not seeing first fence but line shouldn't be removed
|
||||
const result2 = processBlockNesting(
|
||||
"normal code",
|
||||
false,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
expect(result2.newSeenFirstFence).toBe(true);
|
||||
expect(result2.shouldSkip).toBe(false);
|
||||
|
||||
// Test already seen first fence
|
||||
const result3 = processBlockNesting(
|
||||
"more code",
|
||||
true,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
expect(result3.newSeenFirstFence).toBe(true);
|
||||
expect(result3.shouldSkip).toBe(false);
|
||||
});
|
||||
|
||||
test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => {
|
||||
// Create a mock line stream
|
||||
const mockLines = ["line 1", "line 2", "```", "line 4"];
|
||||
const lineStream: LineStream = (async function* () {
|
||||
for (const line of mockLines) {
|
||||
yield line;
|
||||
}
|
||||
})();
|
||||
|
||||
// Test with a non-markdown file
|
||||
const filename = "test.js";
|
||||
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
|
||||
|
||||
// Should only yield lines up to the backticks
|
||||
const collected = [];
|
||||
for await (const line of result) {
|
||||
collected.push(line);
|
||||
}
|
||||
|
||||
expect(collected).toEqual(["line 1", "line 2"]);
|
||||
});
|
||||
|
||||
test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => {
|
||||
// Create a mock line stream with markdown content - but NOT nested markdown blocks
|
||||
const mockLines = [
|
||||
"Some markdown text",
|
||||
"",
|
||||
"```javascript",
|
||||
"function test() {",
|
||||
" return true;",
|
||||
"}",
|
||||
"```",
|
||||
"More text",
|
||||
];
|
||||
|
||||
const lineStream: LineStream = (async function* () {
|
||||
for (const line of mockLines) {
|
||||
yield line;
|
||||
}
|
||||
})();
|
||||
|
||||
// Test with a markdown file
|
||||
const filename = "test.md";
|
||||
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
|
||||
|
||||
// Should yield everything since there's no nested markdown blocks
|
||||
const collected = [];
|
||||
for await (const line of result) {
|
||||
collected.push(line);
|
||||
}
|
||||
|
||||
// The function should stop at the standalone ``` line (not yield it or lines after)
|
||||
// This is the correct behavior - it stops when it encounters standalone backticks
|
||||
expect(collected).toEqual([
|
||||
"Some markdown text",
|
||||
"",
|
||||
"```javascript",
|
||||
"function test() {",
|
||||
" return true;",
|
||||
"}",
|
||||
]);
|
||||
});
|
||||
|
|
@ -20,7 +20,6 @@
|
|||
<option value="runIde"/>
|
||||
</list>
|
||||
</option>
|
||||
<option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>
|
||||
</ExternalSystemSettings>
|
||||
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
|
||||
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@
|
|||
<!-- <option value="runInspections" />-->
|
||||
<!-- </list>-->
|
||||
<!-- </option>-->
|
||||
<!-- <option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>-->
|
||||
<!-- </ExternalSystemSettings>-->
|
||||
<!-- <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>-->
|
||||
<!-- <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>-->
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@
|
|||
<option value="runIdeForUiTests"/>
|
||||
</list>
|
||||
</option>
|
||||
<option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>
|
||||
</ExternalSystemSettings>
|
||||
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
|
||||
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@
|
|||
<option value="test" />
|
||||
</list>
|
||||
</option>
|
||||
<option name="vmOptions" value="-Dide.browser.jcef.out-of-process.enabled=false"/>
|
||||
</ExternalSystemSettings>
|
||||
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
|
||||
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
|
||||
|
|
|
|||
|
|
@ -101,6 +101,32 @@ allow for changes to your `config.json` and other files during development, with
|
|||
|
||||
When using the `Run Continue` task, we automatically tail both prompt logs and IDE logs.
|
||||
|
||||
#### Viewing more IDE logs
|
||||
|
||||
You can selectively increase the log granularity (e.g., debug-level logs) as follows:
|
||||
|
||||
- Navigate to `Help | Diagnostic Tools | Debug Log Settings...`
|
||||
- Add a line in the format: `com.intellij.diagnostic:debug`
|
||||
|
||||
You can find more information about this feature in [official docs](https://youtrack.jetbrains.com/articles/SUPPORT-A-43/How-to-enable-debug-logging-in-IntelliJ-IDEA).
|
||||
|
||||
### Developing `build.plugin.kts`
|
||||
|
||||
If in doubt, check out the
|
||||
official [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template).
|
||||
These templates are the most up-to-date examples of how to correctly customize the plugin build scripts.
|
||||
|
||||
Also, check out
|
||||
the [useful recipes](https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-recipes.html)
|
||||
for common problems.
|
||||
|
||||
### Adding new extensions in `plugin.xml`
|
||||
|
||||
There's a tool called [JetBrains Platform Explorer](https://plugins.jetbrains.com/intellij-platform-explorer) that
|
||||
aggregates plugin metadata and allows you to filter by specific
|
||||
extension points. If you're having trouble implementing a feature that's not officially documented,
|
||||
you can learn from other open source plugins.
|
||||
|
||||
### Reloading changes
|
||||
|
||||
- `extensions/intellij`: Attempt to reload changed classes by selecting
|
||||
|
|
|
|||
|
|
@ -1,77 +1,75 @@
|
|||
import org.jetbrains.changelog.markdownToHTML
|
||||
|
||||
fun properties(key: String) = providers.gradleProperty(key)
|
||||
import org.jetbrains.intellij.platform.gradle.TestFrameworkType
|
||||
import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask
|
||||
|
||||
fun environment(key: String) = providers.environmentVariable(key)
|
||||
|
||||
fun Sync.prepareSandbox() {
|
||||
from("../../binary/bin") { into("${intellij.pluginName.get()}/core/") }
|
||||
}
|
||||
|
||||
val remoteRobotVersion = "0.11.23"
|
||||
val platformType: String by project
|
||||
val platformVersion: String by project
|
||||
val pluginGroup: String by project
|
||||
val pluginVersion: String by project
|
||||
val pluginSinceBuild: String by project
|
||||
val pluginRepositoryUrl: String by project
|
||||
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
|
||||
val pluginVersion = properties("pluginVersion").get()
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
kotlin("jvm") version "1.9.0"
|
||||
id("org.jetbrains.intellij") version "1.15.0"
|
||||
kotlin("jvm") version "1.8.0"
|
||||
id("org.jetbrains.intellij.platform") version "2.6.0"
|
||||
id("org.jetbrains.changelog") version "2.1.2"
|
||||
id("org.jetbrains.qodana") version "0.1.13"
|
||||
id("org.jetbrains.kotlinx.kover") version "0.7.3"
|
||||
kotlin("plugin.serialization") version "1.8.0"
|
||||
id("io.sentry.jvm.gradle") version "5.8.0"
|
||||
}
|
||||
|
||||
group = properties("pluginGroup").get()
|
||||
group = pluginGroup
|
||||
version = if (isEap) "$pluginVersion-eap" else pluginVersion
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") }
|
||||
intellijPlatform {
|
||||
defaultRepositories()
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
|
||||
implementation("com.posthog.java:posthog:1.+")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
|
||||
intellijPlatform {
|
||||
create(platformType, platformVersion)
|
||||
plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6"))
|
||||
testFramework(TestFrameworkType.Platform)
|
||||
}
|
||||
implementation("com.posthog.java:posthog:1.2.0")
|
||||
|
||||
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
|
||||
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
|
||||
testImplementation("io.mockk:mockk:1.14.2")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
|
||||
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
|
||||
testImplementation(kotlin("test"))
|
||||
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3
|
||||
}
|
||||
|
||||
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
|
||||
// 2022.2+.
|
||||
kotlin { jvmToolchain(17) }
|
||||
|
||||
// Configure Gradle IntelliJ Plugin - read more:
|
||||
// https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html
|
||||
intellij {
|
||||
pluginName = properties("pluginName")
|
||||
version = properties("platformVersion")
|
||||
type = properties("platformType")
|
||||
|
||||
// Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file.
|
||||
plugins =
|
||||
properties("platformPlugins").map {
|
||||
it.split(',').map(String::trim).filter(String::isNotEmpty)
|
||||
intellijPlatform {
|
||||
pluginConfiguration {
|
||||
ideaVersion {
|
||||
sinceBuild = pluginSinceBuild
|
||||
}
|
||||
}
|
||||
pluginVerification {
|
||||
ides {
|
||||
ide("IC", "2025.1.4")
|
||||
ide("IC", "2022.3.3")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configure Gradle Changelog Plugin - read more:
|
||||
// https://github.com/JetBrains/gradle-changelog-plugin
|
||||
changelog {
|
||||
groups.empty()
|
||||
repositoryUrl = properties("pluginRepositoryUrl")
|
||||
repositoryUrl = pluginRepositoryUrl
|
||||
}
|
||||
|
||||
// Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin
|
||||
qodana {
|
||||
cachePath = provider { file(".qodana").canonicalPath }
|
||||
reportPath = provider { file("build/reports/inspections").canonicalPath }
|
||||
|
|
@ -79,75 +77,52 @@ qodana {
|
|||
showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false)
|
||||
}
|
||||
|
||||
// Configure Gradle Kover Plugin - read more: https://github.com/Kotlin/kotlinx-kover#configuration
|
||||
koverReport { defaults { xml { onCheck = true } } }
|
||||
|
||||
intellijPlatformTesting {
|
||||
runIde {
|
||||
register("runIdeForUiTests") {
|
||||
task {
|
||||
environment(
|
||||
"CONTINUE_GLOBAL_DIR",
|
||||
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
|
||||
)
|
||||
jvmArgumentProviders += CommandLineArgumentProvider {
|
||||
listOf(
|
||||
"-Drobot-server.port=8082",
|
||||
"-Dide.mac.message.dialogs.as.sheets=false",
|
||||
"-Djb.privacy.policy.text=<!--999.999-->",
|
||||
"-Djb.consents.confirmation.enabled=false",
|
||||
"-Dide.mac.file.chooser.native=false",
|
||||
"-DjbScreenMenuBar.enabled=false",
|
||||
"-Dapple.laf.useScreenMenuBar=false",
|
||||
"-Didea.trust.all.projects=true",
|
||||
"-Dide.show.tips.on.startup.default.value=false",
|
||||
"-Dide.browser.jcef.jsQueryPoolSize=10000",
|
||||
"-Dide.browser.jcef.contextMenu.devTools.enabled=true"
|
||||
)
|
||||
}
|
||||
}
|
||||
plugins {
|
||||
robotServerPlugin()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks {
|
||||
downloadRobotServerPlugin {
|
||||
version = remoteRobotVersion
|
||||
}
|
||||
|
||||
prepareSandbox {
|
||||
prepareSandbox()
|
||||
}
|
||||
|
||||
prepareTestingSandbox {
|
||||
prepareSandbox()
|
||||
}
|
||||
|
||||
prepareUiTestingSandbox {
|
||||
prepareSandbox()
|
||||
}
|
||||
|
||||
wrapper {
|
||||
gradleVersion = properties("gradleVersion").get()
|
||||
withType<PrepareSandboxTask> {
|
||||
from("../../binary/bin") {
|
||||
into(pluginName.map { "$it/core" })
|
||||
}
|
||||
}
|
||||
|
||||
patchPluginXml {
|
||||
sinceBuild = properties("pluginSinceBuild")
|
||||
untilBuild = properties("pluginUntilBuild")
|
||||
pluginDescription =
|
||||
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
|
||||
val start = "<!-- Plugin description -->"
|
||||
val end = "<!-- Plugin description end -->"
|
||||
|
||||
with(it.lines()) {
|
||||
if (!containsAll(listOf(start, end))) {
|
||||
throw GradleException(
|
||||
"Plugin description section not found in README.md:\n$start ... $end"
|
||||
)
|
||||
}
|
||||
subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configure UI tests plugin
|
||||
// Read more: https://github.com/JetBrains/intellij-ui-test-robot
|
||||
runIdeForUiTests {
|
||||
environment(
|
||||
"CONTINUE_GLOBAL_DIR",
|
||||
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
|
||||
)
|
||||
systemProperty("robot-server.port", "8082")
|
||||
systemProperty("ide.mac.message.dialogs.as.sheets", "false")
|
||||
systemProperty("jb.privacy.policy.text", "<!--999.999-->")
|
||||
systemProperty("jb.consents.confirmation.enabled", "false")
|
||||
systemProperty("ide.mac.file.chooser.native", "false")
|
||||
systemProperty("jbScreenMenuBar.enabled", "false")
|
||||
systemProperty("apple.laf.useScreenMenuBar", "false")
|
||||
systemProperty("idea.trust.all.projects", "true")
|
||||
systemProperty("ide.show.tips.on.startup.default.value", "false")
|
||||
systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000")
|
||||
systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
|
||||
|
||||
// This is to ensure we load the GUI with OSR enabled. We have logic that
|
||||
// renders with OSR disabled below a particular IDE version.
|
||||
// See ContinueExtensionSettingsService.kt for more info.
|
||||
// Currently commented out however since test fail in CI with this version
|
||||
// intellij {
|
||||
// version = "2024.1"
|
||||
// }
|
||||
pluginDescription = providers.fileContents(layout.projectDirectory.file("README.md")).asText.get()
|
||||
.substringAfter("<!-- Plugin description -->")
|
||||
.substringBefore("<!-- Plugin description end -->")
|
||||
.let(::markdownToHTML)
|
||||
check(pluginDescription.get().isNotEmpty()) { "Plugin description section not found in README.md" }
|
||||
}
|
||||
|
||||
signPlugin {
|
||||
|
|
@ -164,8 +139,10 @@ tasks {
|
|||
}
|
||||
|
||||
runIde {
|
||||
val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox"
|
||||
args = listOf(dir, "$dir/test.kt")
|
||||
val openProject = "$projectDir/../../manual-testing-sandbox"
|
||||
argumentProviders += CommandLineArgumentProvider {
|
||||
listOf(openProject, "$openProject/test.kt")
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
|
|
|
|||
|
|
@ -1,26 +1,9 @@
|
|||
# IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html
|
||||
pluginGroup=com.github.continuedev.continueintellijextension
|
||||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.30
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginVersion=1.0.33
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
platformType=IC
|
||||
platformVersion=2022.3.3
|
||||
# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
#platformVersion = LATEST-EAP-SNAPSHOT
|
||||
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
|
||||
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
|
||||
platformPlugins=org.jetbrains.plugins.terminal
|
||||
# Gradle Releases -> https://github.com/gradle/gradle/releases
|
||||
gradleVersion=8.3
|
||||
# Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
|
||||
kotlin.stdlib.default.dependency=false
|
||||
# Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
|
||||
org.gradle.configuration-cache=true
|
||||
# Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
|
||||
org.gradle.caching=true
|
||||
# Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment
|
||||
systemProp.org.gradle.unsafe.kotlin.assignment=true
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1,8 +1,7 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
14
extensions/intellij/gradlew
vendored
14
extensions/intellij/gradlew
vendored
|
|
@ -145,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
|
|
@ -153,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
|
|
@ -202,11 +202,11 @@ fi
|
|||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager
|
|||
class RestartContinueProcess : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val pluginService = getContinuePluginService(e.project) ?: return
|
||||
pluginService.coreMessengerManager?.restart()
|
||||
pluginService.coreMessengerManager?.coreMessenger?.restart()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -112,8 +112,10 @@ class ContinueAuthService {
|
|||
val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken))
|
||||
val url = getControlPlaneUrl() + "/auth/refresh"
|
||||
val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
|
||||
.connect { connection -> connection.write(jsonBody.toByteArray()) }
|
||||
.toString()
|
||||
.connect {
|
||||
connection -> connection.write(jsonBody.toByteArray())
|
||||
connection.readString()
|
||||
}
|
||||
return gson.fromJson(response, RefreshTokenResponse::class.java)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,6 +29,9 @@ class ApplyToFileHandler(
|
|||
private val diffStreamService: DiffStreamService
|
||||
) {
|
||||
|
||||
// Store the original file content before applying changes
|
||||
private val originalFileContent: String? = editorUtils?.getDocumentText()
|
||||
|
||||
suspend fun handleApplyToFile() {
|
||||
// Notify webview that we're starting to stream
|
||||
notifyStreamStarted()
|
||||
|
|
@ -111,6 +114,7 @@ class ApplyToFileHandler(
|
|||
numDiffs = numDiffs,
|
||||
filepath = params.filepath,
|
||||
fileContent = params.text,
|
||||
originalFileContent = originalFileContent,
|
||||
toolCallId = params.toolCallId.toString()
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -17,11 +17,11 @@ class CoreMessenger(
|
|||
private val project: Project,
|
||||
private val ideProtocolClient: IdeProtocolClient,
|
||||
val coroutineScope: CoroutineScope,
|
||||
private val onExit: () -> Unit
|
||||
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)
|
||||
|
||||
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
|
||||
|
|
@ -36,7 +36,7 @@ class CoreMessenger(
|
|||
val process = if (isTcp)
|
||||
ContinueSocketProcess()
|
||||
else
|
||||
ContinueBinaryProcess(onExit)
|
||||
ContinueBinaryProcess(onUnexpectedExit)
|
||||
return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
|
||||
}
|
||||
|
||||
|
|
@ -81,7 +81,15 @@ class CoreMessenger(
|
|||
null
|
||||
}
|
||||
|
||||
fun killSubProcess() {
|
||||
fun restart() {
|
||||
log.warn("Restarting Continue process")
|
||||
responseListeners.clear()
|
||||
process.close()
|
||||
process = startContinueProcess()
|
||||
}
|
||||
|
||||
fun close() {
|
||||
log.warn("Closing Continue process")
|
||||
process.close()
|
||||
}
|
||||
}
|
||||
|
|
@ -9,37 +9,34 @@ 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(
|
||||
private val project: Project,
|
||||
private val ideProtocolClient: IdeProtocolClient,
|
||||
project: Project,
|
||||
ideProtocolClient: IdeProtocolClient,
|
||||
private val coroutineScope: CoroutineScope
|
||||
) {
|
||||
var coreMessenger: CoreMessenger = createCoreMessenger()
|
||||
private var lastBackoffInterval = 0.5
|
||||
val coreMessenger = CoreMessenger(project, ideProtocolClient, coroutineScope, ::onUnexpectedExit)
|
||||
private var backoffIntervalSeconds = 1
|
||||
private val log = Logger.getInstance(CoreMessengerManager::class.java)
|
||||
|
||||
init {
|
||||
setupAnonymousTelemetry()
|
||||
}
|
||||
|
||||
fun restart() {
|
||||
private fun onUnexpectedExit() {
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
coreMessenger.killSubProcess()
|
||||
lastBackoffInterval *= 2
|
||||
log.warn("Continue process exited, retrying in $lastBackoffInterval seconds")
|
||||
delay((lastBackoffInterval * 1000).toLong())
|
||||
coreMessenger = createCoreMessenger()
|
||||
delay(backoffIntervalSeconds.seconds)
|
||||
backoffIntervalSeconds *= 2
|
||||
log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds")
|
||||
coreMessenger.restart()
|
||||
} catch (e: Exception) {
|
||||
service<TelemetryService>().capture("jetbrains_core_start_error", mapOf("error" to e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createCoreMessenger() =
|
||||
CoreMessenger(project, ideProtocolClient, coroutineScope, ::restart)
|
||||
|
||||
private fun setupAnonymousTelemetry() {
|
||||
coreMessenger.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val allowAnonymousTelemetry =
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
|
|||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
|
|
@ -38,9 +39,7 @@ import java.awt.Toolkit
|
|||
import java.awt.datatransfer.DataFlavor
|
||||
import java.io.BufferedReader
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.InputStreamReader
|
||||
import java.nio.charset.Charset
|
||||
|
||||
class IntelliJIDE(
|
||||
private val project: Project,
|
||||
|
|
@ -49,7 +48,7 @@ class IntelliJIDE(
|
|||
) : IDE {
|
||||
|
||||
private val gitService = GitService(project, continuePluginService)
|
||||
|
||||
private val fileUtils = FileUtils()
|
||||
private val ripgrep: String = getRipgrepPath()
|
||||
|
||||
init {
|
||||
|
|
@ -204,16 +203,11 @@ class IntelliJIDE(
|
|||
return configs as List<ContinueRcJson>
|
||||
}
|
||||
|
||||
override suspend fun fileExists(filepath: String): Boolean {
|
||||
val file = UriUtils.uriToFile(filepath)
|
||||
return file.exists()
|
||||
}
|
||||
override suspend fun fileExists(filepath: String): Boolean =
|
||||
fileUtils.fileExists(filepath)
|
||||
|
||||
override suspend fun writeFile(path: String, contents: String) {
|
||||
val file = UriUtils.uriToFile(path)
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(contents)
|
||||
}
|
||||
override suspend fun writeFile(path: String, contents: String) =
|
||||
fileUtils.writeFile(path, contents)
|
||||
|
||||
override suspend fun showVirtualFile(title: String, contents: String) {
|
||||
val virtualFile = LightVirtualFile(title, contents)
|
||||
|
|
@ -321,38 +315,8 @@ class IntelliJIDE(
|
|||
}
|
||||
}
|
||||
|
||||
override suspend fun readFile(filepath: String): String {
|
||||
return try {
|
||||
val content = ApplicationManager.getApplication().runReadAction<String?> {
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path)
|
||||
if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
|
||||
return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
|
||||
}
|
||||
return@runReadAction null
|
||||
}
|
||||
|
||||
if (content != null) {
|
||||
content
|
||||
} else {
|
||||
val file = UriUtils.uriToFile(filepath)
|
||||
if (!file.exists() || file.isDirectory) return ""
|
||||
withContext(Dispatchers.IO) {
|
||||
FileInputStream(file).use { fis ->
|
||||
val sizeToRead = minOf(100000, file.length()).toInt()
|
||||
val buffer = ByteArray(sizeToRead)
|
||||
val bytesRead = fis.read(buffer, 0, sizeToRead)
|
||||
if (bytesRead <= 0) return@use ""
|
||||
String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
|
||||
// `\r` takes up unnecessary tokens
|
||||
.lineSequence().joinToString("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
""
|
||||
}
|
||||
}
|
||||
override suspend fun readFile(filepath: String): String =
|
||||
fileUtils.readFile(filepath)
|
||||
|
||||
override suspend fun readRangeInFile(filepath: String, range: Range): String {
|
||||
val fullContents = readFile(filepath)
|
||||
|
|
@ -661,13 +625,8 @@ class IntelliJIDE(
|
|||
}
|
||||
}
|
||||
|
||||
override suspend fun listDir(dir: String): List<List<Any>> {
|
||||
val files = UriUtils.uriToFile(dir).listFiles()?.map {
|
||||
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
|
||||
} ?: emptyList()
|
||||
|
||||
return files
|
||||
}
|
||||
override suspend fun listDir(dir: String): List<List<Any>> =
|
||||
fileUtils.listDir(dir)
|
||||
|
||||
override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
|
||||
return files.associateWith { file ->
|
||||
|
|
|
|||
|
|
@ -0,0 +1,69 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.file
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FileType
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.FileInputStream
|
||||
import java.nio.charset.Charset
|
||||
|
||||
class FileUtils {
|
||||
// todo: use VFS (it's moved from IntellijIde)
|
||||
|
||||
fun fileExists(uri: String): Boolean {
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
return file.exists()
|
||||
}
|
||||
|
||||
fun writeFile(uri: String, contents: String) {
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(contents)
|
||||
}
|
||||
|
||||
fun listDir(dir: String): List<List<Any>> {
|
||||
val files = UriUtils.uriToFile(dir).listFiles()?.map {
|
||||
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
|
||||
} ?: emptyList()
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
fun readFile(uri: String): String {
|
||||
return try {
|
||||
val content = ApplicationManager.getApplication().runReadAction<String?> {
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(uri).path)
|
||||
if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
|
||||
return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
|
||||
}
|
||||
return@runReadAction null
|
||||
}
|
||||
|
||||
if (content != null) {
|
||||
content
|
||||
} else {
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
if (!file.exists() || file.isDirectory) return ""
|
||||
FileInputStream(file).use { fis ->
|
||||
val sizeToRead = minOf(100000, file.length()).toInt()
|
||||
val buffer = ByteArray(sizeToRead)
|
||||
val bytesRead = fis.read(buffer, 0, sizeToRead)
|
||||
if (bytesRead <= 0) return@use ""
|
||||
val content = String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
|
||||
// Remove `\r` characters but preserve trailing newlines to prevent line count discrepancies
|
||||
val contentWithoutCR = content.replace("\r\n", "\n").replace("\r", "\n")
|
||||
contentWithoutCR
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
""
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
import com.github.continuedev.continueintellijextension.proxy.ProxySettings
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.github.continuedev.continueintellijextension.services.TelemetryService
|
||||
import com.github.continuedev.continueintellijextension.utils.OS
|
||||
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
|
||||
|
|
@ -14,7 +16,9 @@ import java.nio.file.Files
|
|||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
|
||||
class ContinueBinaryProcess(
|
||||
private val onUnexpectedExit: () -> Unit
|
||||
) : ContinueProcess {
|
||||
|
||||
private val process = startBinaryProcess()
|
||||
override val input: InputStream = process.inputStream
|
||||
|
|
@ -28,11 +32,16 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
|
|||
runBlocking(Dispatchers.IO) {
|
||||
setPermissions()
|
||||
}
|
||||
return ProcessBuilder(path).directory(File(path).parentFile)
|
||||
.start()
|
||||
.apply { onExit().thenRun(onExit).thenRun { reportErrorTelemetry() } }
|
||||
}
|
||||
|
||||
val builder = ProcessBuilder(path)
|
||||
val proxySettings = ProxySettings.getSettings()
|
||||
if (proxySettings.enabled)
|
||||
builder.environment() += "HTTP_PROXY" to proxySettings.proxy
|
||||
return builder
|
||||
.directory(File(path).parentFile)
|
||||
.start()
|
||||
.apply { onExit().thenRun(onUnexpectedExit).thenRun(::reportErrorTelemetry) }
|
||||
}
|
||||
|
||||
private fun reportErrorTelemetry() {
|
||||
var err = process.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
|
|
@ -44,11 +53,8 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
|
|||
err = err.substring(doneIndex + delimiter.length)
|
||||
}
|
||||
}
|
||||
|
||||
println("Core process exited with output: $err")
|
||||
|
||||
val telemetryService = service<TelemetryService>()
|
||||
telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
|
||||
service<ContinueErrorService>().reportMessage("Core process exited with output: $err")
|
||||
service<TelemetryService>().capture("jetbrains_core_exit", mapOf("error" to err))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
|
@ -67,6 +73,7 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
|
|||
elevatePermissions()
|
||||
}
|
||||
|
||||
// todo: consider setting permissions ahead-of-time during build/packaging, not at runtime
|
||||
private fun elevatePermissions() {
|
||||
val path = getContinueBinaryPath()
|
||||
val permissions = setOf(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.`continue`.process
|
|||
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import java.io.BufferedReader
|
||||
|
|
@ -19,6 +20,7 @@ class ContinueProcessHandler(
|
|||
private val pendingWrites = Channel<String>(Channel.UNLIMITED)
|
||||
private val writer = OutputStreamWriter(process.output)
|
||||
private val reader = BufferedReader(InputStreamReader(process.input))
|
||||
private val log = Logger.getInstance(ContinueProcessHandler::class.java)
|
||||
|
||||
init {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
|
|
@ -27,6 +29,7 @@ class ContinueProcessHandler(
|
|||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
try {
|
||||
log.debug("Handle: $line")
|
||||
handleMessage(line)
|
||||
} catch (e: Exception) {
|
||||
service<ContinueErrorService>().report(e, "Error handling message: $line")
|
||||
|
|
@ -40,6 +43,7 @@ class ContinueProcessHandler(
|
|||
}
|
||||
scope.launch(Dispatchers.IO) {
|
||||
for (message in pendingWrites) {
|
||||
log.debug("Write: $message")
|
||||
writer.write(message)
|
||||
writer.write("\r\n")
|
||||
writer.flush()
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import com.intellij.openapi.components.Service
|
|||
import com.intellij.openapi.diagnostic.Attachment
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.extensions.PluginId
|
||||
import com.intellij.openapi.util.SystemInfo
|
||||
import com.intellij.ui.jcef.JBCefApp
|
||||
import io.sentry.Hint
|
||||
import io.sentry.Sentry
|
||||
|
|
@ -26,6 +27,8 @@ class ContinueErrorService {
|
|||
config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
|
||||
config.setTag("jcef_supported", JBCefApp.isSupported().toString())
|
||||
config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version)
|
||||
config.setTag("system", SystemInfo.OS_NAME)
|
||||
config.setTag("system_version", SystemInfo.OS_VERSION)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -39,7 +42,14 @@ class ContinueErrorService {
|
|||
sentryEvent.message = Message().apply { this.message = message }
|
||||
val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) })
|
||||
Sentry.captureEvent(sentryEvent, hint)
|
||||
log.warn("Problem sent to Sentry: $message", throwable)
|
||||
log.warn("Exception sent to Sentry: $message", throwable)
|
||||
}
|
||||
|
||||
fun reportMessage(
|
||||
message: String,
|
||||
) {
|
||||
Sentry.captureMessage(message)
|
||||
log.warn("Message sent to Sentry: $message")
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
package com.github.continuedev.continueintellijextension.proxy
|
||||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.startup.StartupActivity
|
||||
import kotlinx.coroutines.*
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
class ProxyPoolingActivity : StartupActivity {
|
||||
private val scope = CoroutineScope(Dispatchers.Default)
|
||||
private var lastSettings = ProxySettings.getSettings()
|
||||
private val log = Logger.getInstance(ProxyPoolingActivity::class.java)
|
||||
|
||||
override fun runActivity(project: Project) {
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
val newSettings = ProxySettings.getSettings()
|
||||
if (newSettings != lastSettings) {
|
||||
onSettingsChanged(project)
|
||||
lastSettings = newSettings
|
||||
}
|
||||
delay(2.seconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onSettingsChanged(project: Project) {
|
||||
log.warn("Proxy settings changed, restarting")
|
||||
project.service<ContinuePluginService>().coreMessengerManager?.coreMessenger?.restart()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.github.continuedev.continueintellijextension.proxy
|
||||
|
||||
import com.intellij.util.net.HttpConfigurable
|
||||
|
||||
data class ProxySettings(
|
||||
val enabled: Boolean,
|
||||
val proxy: String,
|
||||
) {
|
||||
|
||||
companion object {
|
||||
fun getSettings(): ProxySettings {
|
||||
val settings = HttpConfigurable.getInstance()
|
||||
return ProxySettings(
|
||||
enabled = settings.USE_HTTP_PROXY,
|
||||
proxy = "${settings.PROXY_HOST}:${settings.PROXY_PORT}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -33,7 +33,7 @@ class ContinuePluginService : Disposable, DumbAware {
|
|||
coroutineScope.cancel()
|
||||
coreMessenger?.coroutineScope?.let {
|
||||
it.cancel()
|
||||
coreMessenger?.killSubProcess()
|
||||
coreMessenger?.close()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,62 +2,69 @@ package com.github.continuedev.continueintellijextension.toolWindow
|
|||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.intellij.openapi.actionSystem.ActionManager
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.wm.ToolWindow
|
||||
import com.intellij.openapi.wm.ToolWindowFactory
|
||||
import com.intellij.ui.content.ContentFactory
|
||||
import com.intellij.ui.dsl.builder.AlignX
|
||||
import com.intellij.ui.dsl.builder.panel
|
||||
import com.intellij.ui.jcef.JBCefApp
|
||||
import com.intellij.util.ui.JBUI.Borders.empty
|
||||
import javax.swing.JComponent
|
||||
import javax.swing.JPanel
|
||||
|
||||
const val JS_QUERY_POOL_SIZE = "200"
|
||||
|
||||
class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
||||
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
|
||||
val continueToolWindow = ContinuePluginWindow(project)
|
||||
val content =
|
||||
ContentFactory.getInstance().createContent(continueToolWindow.content, null, false)
|
||||
toolWindow.contentManager.addContent(content)
|
||||
val titleActions = mutableListOf<AnAction>()
|
||||
createTitleActions(titleActions)
|
||||
|
||||
// Add MaximizeToolWindow action
|
||||
val action = ActionManager.getInstance().getAction("MaximizeToolWindow")
|
||||
if (action != null) {
|
||||
titleActions.add(action)
|
||||
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
|
||||
val inner = if (JBCefApp.isSupported())
|
||||
ContinuePluginWindow(project).content
|
||||
else
|
||||
createNotSupportedPanel()
|
||||
val content = ContentFactory.getInstance().createContent(inner, null, false)
|
||||
toolWindow.contentManager.addContent(content)
|
||||
toolWindow.setTitleActions(
|
||||
listOf(
|
||||
ActionManager.getInstance().getAction("ContinueSidebarActionsGroup"),
|
||||
ActionManager.getInstance().getAction("MaximizeToolWindow")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
toolWindow.setTitleActions(titleActions)
|
||||
}
|
||||
override fun shouldBeAvailable(project: Project) = true
|
||||
|
||||
private fun createTitleActions(titleActions: MutableList<in AnAction>) {
|
||||
val action = ActionManager.getInstance().getAction("ContinueSidebarActionsGroup")
|
||||
if (action != null) {
|
||||
titleActions.add(action)
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldBeAvailable(project: Project) = true
|
||||
|
||||
class ContinuePluginWindow(project: Project) {
|
||||
private val defaultGUIUrl = "http://continue/index.html"
|
||||
|
||||
init {
|
||||
System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
|
||||
System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
|
||||
System.setProperty("ide.browser.jcef.out-of-process.enabled", "false")
|
||||
private fun createNotSupportedPanel(): JPanel {
|
||||
val html = ContinuePluginToolWindowFactory::class.java.classLoader
|
||||
.getResourceAsStream("jcef_error.html")
|
||||
.bufferedReader()
|
||||
.readText()
|
||||
return panel {
|
||||
row {
|
||||
text(html)
|
||||
}
|
||||
}.withBorder(empty(10))
|
||||
}
|
||||
|
||||
val browser: ContinueBrowser by lazy {
|
||||
val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl
|
||||
class ContinuePluginWindow(project: Project) {
|
||||
private val defaultGUIUrl = "http://continue/index.html"
|
||||
|
||||
val browser = ContinueBrowser(project, url)
|
||||
project.service<ContinuePluginService>().continuePluginWindow = this
|
||||
browser
|
||||
init {
|
||||
System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
|
||||
System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
|
||||
System.setProperty("ide.browser.jcef.out-of-process.enabled", "false")
|
||||
}
|
||||
|
||||
val browser: ContinueBrowser by lazy {
|
||||
val url = System.getenv("GUI_URL") ?: defaultGUIUrl
|
||||
|
||||
val browser = ContinueBrowser(project, url)
|
||||
project.service<ContinuePluginService>().continuePluginWindow = this
|
||||
browser
|
||||
}
|
||||
|
||||
val content: JComponent
|
||||
get() = browser.browser.component
|
||||
}
|
||||
|
||||
val content: JComponent
|
||||
get() = browser.browser.component
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -290,6 +290,7 @@ data class ApplyState(
|
|||
val numDiffs: Int? = null,
|
||||
val filepath: String? = null,
|
||||
val fileContent: String? = null,
|
||||
val originalFileContent: String? = null,
|
||||
val toolCallId: String? = null
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -14,9 +14,6 @@
|
|||
com.intellij.modules.json
|
||||
</depends>
|
||||
|
||||
<!-- com.intellij.openapi.module.ModuleManager.Companion is only available since this build -->
|
||||
<idea-version since-build="223.7571.182"/>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<editorFactoryListener
|
||||
implementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteEditorListener"/>
|
||||
|
|
@ -40,6 +37,7 @@
|
|||
<errorHandler implementation="com.github.continuedev.continueintellijextension.error.ContinueErrorSubmitter"/>
|
||||
<postStartupActivity
|
||||
implementation="com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity"/>
|
||||
<postStartupActivity implementation="com.github.continuedev.continueintellijextension.proxy.ProxyPoolingActivity"/>
|
||||
<applicationConfigurable
|
||||
parentId="tools"
|
||||
instance="com.github.continuedev.continueintellijextension.services.ContinueExtensionConfigurable"
|
||||
|
|
|
|||
22
extensions/intellij/src/main/resources/jcef_error.html
Normal file
22
extensions/intellij/src/main/resources/jcef_error.html
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<!--suppress ALL-->
|
||||
<html>
|
||||
<h2>
|
||||
<center>Continue Chat is Unable to Load</center>
|
||||
</h2>
|
||||
<p>Continue Chat requires a JRE that supports the Java Chromium Embedded Framework (JCEF) to render our webview. You can
|
||||
still use Autocomplete and Edit.</p>
|
||||
<h3>How to Fix It?</h3>
|
||||
<p>You can manually switch to a JRE that supports JCEF:</p>
|
||||
<ol>
|
||||
<li>In the main menu, go to <b>Help | Find Action</b> or press
|
||||
<b>Ctrl + Shift + A</b>.
|
||||
</li>
|
||||
<li>Find and select the <b>Choose Boot Java Runtime for the IDE</b> action.</li>
|
||||
<li>Select the runtime that comes with JCEF support and click <b>OK</b>.</li>
|
||||
<li>Restart with the new runtime.</li>
|
||||
</ol>
|
||||
<p>Runtimes that support JCEF are usually called <b>JetBrains Runtime</b> and have the <code>-jcef</code> suffix,
|
||||
for example <code>21.0.3+13-509.11-jcef</code>.</p>
|
||||
<br>
|
||||
<small>You can find more information in the <a href="https://www.jetbrains.com/help/idea/switching-boot-jdk.html">JetBrains documentation</a>.</small>
|
||||
</html>
|
||||
|
|
@ -12,13 +12,12 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
|
|||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import io.mockk.*
|
||||
import junit.framework.TestCase
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
@ExperimentalCoroutinesApi
|
||||
class ApplyToFileHandlerTest {
|
||||
class ApplyToFileHandlerTest : TestCase() {
|
||||
// Mock all dependencies
|
||||
private val mockProject = mockk<Project>(relaxed = true)
|
||||
private val mockContinuePluginService = mockk<ContinuePluginService>(relaxed = true)
|
||||
|
|
@ -39,8 +38,7 @@ class ApplyToFileHandlerTest {
|
|||
"tool-call-123"
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
override fun setUp() {
|
||||
// Common setup
|
||||
every { mockEditorUtils.editor } returns mockEditor
|
||||
every { mockContinuePluginService.coreMessenger } returns mockCoreMessenger
|
||||
|
|
@ -56,8 +54,7 @@ class ApplyToFileHandlerTest {
|
|||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should insert text directly when document is empty`() = runTest {
|
||||
fun `test should insert text directly when document is empty`() = runTest {
|
||||
// Given
|
||||
every { mockEditorUtils.isDocumentEmpty() } returns true
|
||||
|
||||
|
|
|
|||
|
|
@ -1,48 +1,39 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FimResult
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import com.github.continuedev.continueintellijextension.utils.checkFim
|
||||
import org.junit.jupiter.api.Disabled
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
import junit.framework.TestCase
|
||||
|
||||
class CheckFimTest {
|
||||
@Test
|
||||
fun testFim() {
|
||||
class CheckFimTest : TestCase() {
|
||||
fun `test FIM`() {
|
||||
val oldEditRange = "hello world"
|
||||
val newEditRange = "hello this world"
|
||||
val cursorPosition = Pair(0, 6)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("this "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMultilineFim() {
|
||||
fun `test multiline FIM`() {
|
||||
val oldEditRange = "hello {\n world\n}"
|
||||
val newEditRange = "hello {\n print()\n world\n}"
|
||||
val cursorPosition = Pair(1, 2)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("print()\n "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNotFim() {
|
||||
fun `test not FIM`() {
|
||||
val oldEditRange = "hello world"
|
||||
val newEditRange = "hello this world"
|
||||
val cursorPosition = Pair(0, 8)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMultilineNotFim() {
|
||||
fun `test multiline not FIM`() {
|
||||
val oldEditRange = "hello {\n world\n}"
|
||||
val newEditRange = "hello {\n world\n}\nprint()"
|
||||
val cursorPosition = Pair(1, 2)
|
||||
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFimEdge() {
|
||||
fun `test FIM edge`() {
|
||||
val oldEditRange = ""
|
||||
val newEditRange = ""
|
||||
val cursorPosition = Pair(0, 0)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,77 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.FileType
|
||||
import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
|
||||
import com.intellij.testFramework.UsefulTestCase
|
||||
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
|
||||
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
|
||||
|
||||
class FileUtilsTest : UsefulTestCase() {
|
||||
val fileUtils = FileUtils()
|
||||
val myFixture = setupRealFilesFixture()
|
||||
val tmpFixture get() = myFixture.tempDirFixture
|
||||
val tmpDir get() = myFixture.tempDirPath
|
||||
|
||||
override fun setUp() =
|
||||
myFixture.setUp()
|
||||
|
||||
override fun tearDown() =
|
||||
myFixture.tearDown()
|
||||
|
||||
fun `test fileExists`() {
|
||||
val file = tmpFixture.createFile("test.txt", "")
|
||||
val uri = "file://${file.path}"
|
||||
assertTrue(fileUtils.fileExists(uri))
|
||||
}
|
||||
|
||||
fun `test fileExists inside directory`() {
|
||||
val file = tmpFixture.createFile("dir/dir2/file.txt", "")
|
||||
val uri = "file://${file.path}"
|
||||
assertTrue(fileUtils.fileExists(uri))
|
||||
}
|
||||
|
||||
fun `test fileExists fails when file doesn't exists`() {
|
||||
val uri = "file:///tmp/aaaa.txt"
|
||||
assertFalse(fileUtils.fileExists(uri))
|
||||
}
|
||||
|
||||
fun `test readFile`() {
|
||||
val uri = "file://$tmpDir/bbbb.txt"
|
||||
tmpFixture.createFile("bbbb.txt", "contents")
|
||||
val text = fileUtils.readFile(uri)
|
||||
assertEquals("contents", text)
|
||||
}
|
||||
|
||||
fun `test listDir`() {
|
||||
tmpFixture.createFile("a.txt", "a")
|
||||
tmpFixture.createFile("b.txt", "b")
|
||||
tmpFixture.createFile("c.txt", "c")
|
||||
tmpFixture.createFile("dir/invisibleA.txt", "d")
|
||||
tmpFixture.createFile("dir/invisibleB.txt", "e")
|
||||
|
||||
val result = fileUtils.listDir("file://$tmpDir")
|
||||
|
||||
assertTrue(result.any { it[0] == "a.txt" && it[1] == FileType.FILE.value })
|
||||
assertTrue(result.any { it[0] == "b.txt" && it[1] == FileType.FILE.value })
|
||||
assertTrue(result.any { it[0] == "c.txt" && it[1] == FileType.FILE.value })
|
||||
assertTrue(result.any { it[0] == "dir" && it[1] == FileType.DIRECTORY.value })
|
||||
assertTrue(result.any { it[0] == "dir" && it[1] == FileType.DIRECTORY.value })
|
||||
assertFalse(result.any { it[0] == "invisibleA.txt" })
|
||||
assertFalse(result.any { it[0] == "invisibleB.txt" })
|
||||
assertEquals(4, result.size)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
// note: with this, files will actually exist inside /tmp/unitTest/ dir, otherwise it's virtual
|
||||
fun setupRealFilesFixture(): CodeInsightTestFixture {
|
||||
val factory = IdeaTestFixtureFactory.getFixtureFactory()
|
||||
return factory.createCodeInsightFixture(
|
||||
factory.createLightFixtureBuilder("my_continue_project").fixture,
|
||||
factory.createTempDirTestFixture()
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,64 +1,48 @@
|
|||
package com.github.continuedev.continueintellijextension.unit
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
|
||||
import org.junit.jupiter.api.Disabled
|
||||
import org.junit.jupiter.api.Test
|
||||
import junit.framework.TestCase
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class UriUtilsTest {
|
||||
@Test
|
||||
fun testUriToFile() {
|
||||
class UriUtilsTest : TestCase() {
|
||||
fun `test URI to File`() {
|
||||
val uri = "file:///path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Disabled("Not working")
|
||||
@Test
|
||||
fun testUriToFileWithWindowsPath() {
|
||||
val uri = "file:///C:/path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("C:/path/to/file"), file)
|
||||
}
|
||||
// fixme it's not working
|
||||
// fun `test Windows path`() {
|
||||
// val uri = "file:///C:/path/to/file"
|
||||
// val file = UriUtils.uriToFile(uri)
|
||||
// assertEquals(File("C:/path/to/file"), file)
|
||||
// }
|
||||
|
||||
@Test
|
||||
fun shouldHandleAuthorityComponent() {
|
||||
val uri = "file://C:/path/to/file"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/C:/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithSpaces() {
|
||||
fun `test spaces`() {
|
||||
val uri = "file:///path/to/file%20with%20spaces"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file with spaces"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithSpecialCharacters() {
|
||||
fun `test special characters`() {
|
||||
val uri = "file:///path/to/file%23with%25special%26chars"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file#with%special&chars"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithQueryParams() {
|
||||
fun `test query params`() {
|
||||
val uri = "file:///path/to/file?param=value"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/path/to/file"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithWSLPath() {
|
||||
fun `test WSL path`() {
|
||||
val uri = "file:///wsl$/Ubuntu/home/user/file.txt"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/wsl$/Ubuntu/home/user/file.txt"), file)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUriToFileWithWSLLocalhostPath() {
|
||||
fun `test WSL localhost path`() {
|
||||
val uri = "file:///wsl.localhost/Ubuntu/home/user/file.txt"
|
||||
val file = UriUtils.uriToFile(uri)
|
||||
assertEquals(File("/wsl.localhost/Ubuntu/home/user/file.txt"), file)
|
||||
|
|
|
|||
4
extensions/vscode/package-lock.json
generated
4
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.66",
|
||||
"version": "1.1.68",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.66",
|
||||
"version": "1.1.68",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.66",
|
||||
"version": "1.1.69",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
|
|
@ -1,83 +1,40 @@
|
|||
const { fork } = require("child_process");
|
||||
const fs = require("fs");
|
||||
const https = require("https");
|
||||
const path = require("path");
|
||||
|
||||
const { ProxyAgent } = require("undici");
|
||||
const { rimrafSync } = require("rimraf");
|
||||
|
||||
const { execCmdSync } = require("../../../scripts/util");
|
||||
|
||||
/**
|
||||
* download a file using nodejs http
|
||||
* download a file using fetch API
|
||||
* @param {string} url
|
||||
* @param {string} outputPath
|
||||
* @param {number} maxRedirects
|
||||
*/
|
||||
async function downloadFile(url, outputPath, maxRedirects = 5) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const downloadWithRedirects = (currentUrl, redirectCount = 0) => {
|
||||
if (redirectCount > maxRedirects) {
|
||||
return reject(new Error(`Too many redirects (${maxRedirects})`));
|
||||
}
|
||||
async function downloadFile(url, outputPath) {
|
||||
// Use proxy if set in environment variables
|
||||
const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
|
||||
const agent = proxy ? new ProxyAgent(proxy) : undefined;
|
||||
|
||||
const request = https.get(currentUrl, (response) => {
|
||||
if (
|
||||
response.statusCode >= 300 &&
|
||||
response.statusCode < 400 &&
|
||||
response.headers.location
|
||||
) {
|
||||
return downloadWithRedirects(
|
||||
response.headers.location,
|
||||
redirectCount + 1,
|
||||
);
|
||||
}
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
return reject(
|
||||
new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`),
|
||||
);
|
||||
}
|
||||
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
const writeStream = fs.createWriteStream(outputPath);
|
||||
|
||||
const totalSize = parseInt(response.headers["content-length"], 10);
|
||||
let downloadedSize = 0;
|
||||
|
||||
response.on("data", (chunk) => {
|
||||
downloadedSize += chunk.length;
|
||||
if (totalSize) {
|
||||
const percent = ((downloadedSize / totalSize) * 100).toFixed(1);
|
||||
process.stdout.write(
|
||||
`\rDownloading: ${percent}% (${downloadedSize}/${totalSize} bytes)`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
response.pipe(writeStream);
|
||||
|
||||
writeStream.on("finish", () => {
|
||||
console.log(`\nDownload completed: ${outputPath}`);
|
||||
resolve(outputPath);
|
||||
});
|
||||
|
||||
writeStream.on("error", reject);
|
||||
response.on("error", reject);
|
||||
});
|
||||
|
||||
request.on("error", reject);
|
||||
request.setTimeout(30000, () => {
|
||||
request.destroy();
|
||||
reject(new Error("Request timeout"));
|
||||
});
|
||||
};
|
||||
|
||||
downloadWithRedirects(url);
|
||||
const response = await fetch(url, {
|
||||
redirect: "follow", // Automatically follow redirects
|
||||
dispatcher: agent,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download file, status code: ${response.status}`);
|
||||
}
|
||||
|
||||
// Create output directory if it doesn't exist
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Get the response as an array buffer and write it to the file
|
||||
const buffer = await response.arrayBuffer();
|
||||
fs.writeFileSync(outputPath, Buffer.from(buffer));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -6,10 +6,6 @@ import * as vscode from "vscode";
|
|||
import { DiffChar, DiffLine } from "core";
|
||||
import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
|
||||
import { myersCharDiff } from "core/diff/myers";
|
||||
import {
|
||||
NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
} from "core/nextEdit/constants";
|
||||
import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
|
||||
import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
|
||||
import { getThemeString } from "../util/getTheme";
|
||||
|
|
@ -117,6 +113,9 @@ export class NextEditWindowManager {
|
|||
// Track for logging purposes.
|
||||
private loggingService: NextEditLoggingService;
|
||||
private mostRecentCompletionId: string | null = null;
|
||||
// Helps us skip redundant calculations. No need for cleanup because this always gets reassigned with new values at showNextEditWindow, and we don't reuse windows.
|
||||
private editableRegionStartLine: number = 0;
|
||||
private editableRegionEndLine: number = 0;
|
||||
|
||||
// Disposables
|
||||
private disposables: vscode.Disposable[] = [];
|
||||
|
|
@ -261,6 +260,7 @@ export class NextEditWindowManager {
|
|||
editor: vscode.TextEditor,
|
||||
currCursorPos: vscode.Position,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
oldEditRangeSlice: string,
|
||||
newEditRangeSlice: string,
|
||||
diffLines: DiffLine[],
|
||||
|
|
@ -272,11 +272,15 @@ export class NextEditWindowManager {
|
|||
// Clear any existing decorations first (very important to prevent overlapping).
|
||||
await this.hideAllNextEditWindows();
|
||||
|
||||
this.editableRegionStartLine = editableRegionStartLine;
|
||||
this.editableRegionEndLine = editableRegionEndLine;
|
||||
|
||||
// Store the current tooltip text for accepting later.
|
||||
this.currentTooltipText = newEditRangeSlice;
|
||||
|
||||
// How far away is the current line from the start of the editable region?
|
||||
const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine;
|
||||
const lineOffsetAtCursorPos =
|
||||
currCursorPos.line - this.editableRegionStartLine;
|
||||
|
||||
// How long is the line at the current cursor position?
|
||||
const lineContentAtCursorPos =
|
||||
|
|
@ -291,7 +295,7 @@ export class NextEditWindowManager {
|
|||
// Calculate the actual line number in the editor by adding the startPos offset
|
||||
// to the line number from the diff calculation.
|
||||
this.finalCursorPos = new vscode.Position(
|
||||
editableRegionStartLine + offset.line,
|
||||
this.editableRegionStartLine + offset.line,
|
||||
offset.character,
|
||||
);
|
||||
|
||||
|
|
@ -301,13 +305,13 @@ export class NextEditWindowManager {
|
|||
currCursorPos,
|
||||
oldEditRangeSlice,
|
||||
newEditRangeSlice,
|
||||
editableRegionStartLine,
|
||||
this.editableRegionStartLine,
|
||||
diffLines,
|
||||
);
|
||||
|
||||
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
|
||||
|
||||
this.renderDeletes(editor, editableRegionStartLine, diffChars);
|
||||
this.renderDeletions(editor, diffChars);
|
||||
|
||||
// Reserve tab and esc to either accept or reject the displayed next edit contents.
|
||||
await NextEditWindowManager.reserveTabAndEsc();
|
||||
|
|
@ -317,6 +321,8 @@ export class NextEditWindowManager {
|
|||
* Hide all tooltips in all editors.
|
||||
*/
|
||||
public async hideAllNextEditWindows() {
|
||||
await NextEditWindowManager.freeTabAndEsc();
|
||||
|
||||
if (this.currentDecoration) {
|
||||
vscode.window.visibleTextEditors.forEach((editor) => {
|
||||
editor.setDecorations(this.currentDecoration!, []);
|
||||
|
|
@ -339,12 +345,10 @@ export class NextEditWindowManager {
|
|||
// Clear the current tooltip text.
|
||||
this.currentTooltipText = null;
|
||||
}
|
||||
|
||||
await NextEditWindowManager.freeTabAndEsc();
|
||||
}
|
||||
|
||||
public async hideAllNextEditWindowsAndResetCompletionId() {
|
||||
this.hideAllNextEditWindows();
|
||||
await this.hideAllNextEditWindows();
|
||||
|
||||
// Log with accept = false.
|
||||
await vscode.commands.executeCommand(
|
||||
|
|
@ -352,6 +356,7 @@ export class NextEditWindowManager {
|
|||
this.mostRecentCompletionId,
|
||||
this.loggingService,
|
||||
);
|
||||
|
||||
this.mostRecentCompletionId = null;
|
||||
}
|
||||
|
||||
|
|
@ -369,6 +374,10 @@ export class NextEditWindowManager {
|
|||
const position = editor.selection.active;
|
||||
|
||||
let success = false;
|
||||
|
||||
// Hide windows first for a snappier feel.
|
||||
await this.hideAllNextEditWindows();
|
||||
|
||||
if (this.textApplier) {
|
||||
success = await this.textApplier.applyText(
|
||||
editor,
|
||||
|
|
@ -377,20 +386,15 @@ export class NextEditWindowManager {
|
|||
this.finalCursorPos,
|
||||
);
|
||||
} else {
|
||||
// Define the editable region.
|
||||
const editableRegionStartLine = Math.max(
|
||||
0,
|
||||
position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
|
||||
);
|
||||
const editableRegionEndLine = Math.min(
|
||||
editor.document.lineCount - 1,
|
||||
position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
);
|
||||
const startPos = new vscode.Position(editableRegionStartLine, 0);
|
||||
const endPosChar = editor.document.lineAt(editableRegionEndLine).text
|
||||
// Define the range to replace.
|
||||
const startPos = new vscode.Position(this.editableRegionStartLine, 0);
|
||||
const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text
|
||||
.length;
|
||||
|
||||
const endPos = new vscode.Position(editableRegionEndLine, endPosChar);
|
||||
const endPos = new vscode.Position(
|
||||
this.editableRegionEndLine,
|
||||
endPosChar,
|
||||
);
|
||||
const editRange = new vscode.Range(startPos, endPos);
|
||||
|
||||
success = await editor.edit((editBuilder) => {
|
||||
|
|
@ -405,23 +409,19 @@ export class NextEditWindowManager {
|
|||
.update("editor.inlineSuggest.enabled", false, true);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
if (success && this.finalCursorPos) {
|
||||
// Move cursor to the final position if available.
|
||||
if (this.finalCursorPos) {
|
||||
editor.selection = new vscode.Selection(
|
||||
this.finalCursorPos,
|
||||
this.finalCursorPos,
|
||||
);
|
||||
|
||||
// Reenable inline suggestions after we move the cursor.
|
||||
await vscode.workspace
|
||||
.getConfiguration()
|
||||
.update("editor.inlineSuggest.enabled", true, true);
|
||||
|
||||
await this.hideAllNextEditWindows();
|
||||
}
|
||||
editor.selection = new vscode.Selection(
|
||||
this.finalCursorPos,
|
||||
this.finalCursorPos,
|
||||
);
|
||||
}
|
||||
|
||||
// Reenable inline suggestions.
|
||||
await vscode.workspace
|
||||
.getConfiguration()
|
||||
.update("editor.inlineSuggest.enabled", true, true);
|
||||
|
||||
// Log with accept = true.
|
||||
await vscode.commands.executeCommand(
|
||||
"continue.logNextEditOutcomeAccept",
|
||||
|
|
@ -454,7 +454,7 @@ export class NextEditWindowManager {
|
|||
*/
|
||||
private setupListeners() {
|
||||
// Theme change listener.
|
||||
vscode.workspace.onDidChangeConfiguration((e) => {
|
||||
vscode.workspace.onDidChangeConfiguration(async (e) => {
|
||||
if (
|
||||
e.affectsConfiguration("workbench.colorTheme") ||
|
||||
e.affectsConfiguration("editor.fontSize") ||
|
||||
|
|
@ -467,7 +467,7 @@ export class NextEditWindowManager {
|
|||
e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
|
||||
) {
|
||||
this.theme = getThemeString();
|
||||
this.codeRenderer.setTheme(this.theme);
|
||||
await this.codeRenderer.setTheme(this.theme);
|
||||
console.log(
|
||||
"Theme updated:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
|
|
@ -479,9 +479,9 @@ export class NextEditWindowManager {
|
|||
});
|
||||
|
||||
// Listen for active color theme changes.
|
||||
vscode.window.onDidChangeActiveColorTheme(() => {
|
||||
vscode.window.onDidChangeActiveColorTheme(async () => {
|
||||
this.theme = getThemeString();
|
||||
this.codeRenderer.setTheme(this.theme);
|
||||
await this.codeRenderer.setTheme(this.theme);
|
||||
console.log(
|
||||
"Active theme changed:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
|
|
@ -495,10 +495,11 @@ export class NextEditWindowManager {
|
|||
this.activeEditor &&
|
||||
!vscode.window.visibleTextEditors.includes(this.activeEditor)
|
||||
) {
|
||||
if (this.mostRecentCompletionId)
|
||||
if (this.mostRecentCompletionId) {
|
||||
this.loggingService.cancelRejectionTimeout(
|
||||
this.mostRecentCompletionId,
|
||||
);
|
||||
}
|
||||
await this.hideAllNextEditWindows();
|
||||
}
|
||||
});
|
||||
|
|
@ -508,10 +509,11 @@ export class NextEditWindowManager {
|
|||
// If the selection changed in our active editor, hide the tooltip.
|
||||
if (this.activeEditor && e.textEditor === this.activeEditor) {
|
||||
// If the cursor moved because of something other than accepting next edit, stop logging it.
|
||||
if (!this.accepted && this.mostRecentCompletionId)
|
||||
if (!this.accepted && this.mostRecentCompletionId) {
|
||||
this.loggingService.cancelRejectionTimeout(
|
||||
this.mostRecentCompletionId,
|
||||
);
|
||||
}
|
||||
await this.hideAllNextEditWindows();
|
||||
}
|
||||
});
|
||||
|
|
@ -747,7 +749,6 @@ export class NextEditWindowManager {
|
|||
}
|
||||
|
||||
// Store the decoration and editor.
|
||||
await this.hideAllNextEditWindows();
|
||||
this.currentDecoration = decoration; // TODO: This might be redundant.
|
||||
this.disposables.push(decoration);
|
||||
this.activeEditor = editor;
|
||||
|
|
@ -786,13 +787,7 @@ export class NextEditWindowManager {
|
|||
);
|
||||
}
|
||||
|
||||
private renderDeletes(
|
||||
editor: vscode.TextEditor,
|
||||
editableRegionStartLine: number,
|
||||
// oldEditRangeSlice: string,
|
||||
// newEditRangeSlice: string,
|
||||
oldDiffChars: DiffChar[],
|
||||
) {
|
||||
private renderDeletions(editor: vscode.TextEditor, oldDiffChars: DiffChar[]) {
|
||||
const charsToDelete: vscode.DecorationOptions[] = [];
|
||||
|
||||
// const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
|
||||
|
|
@ -803,11 +798,11 @@ export class NextEditWindowManager {
|
|||
charsToDelete.push({
|
||||
range: new vscode.Range(
|
||||
new vscode.Position(
|
||||
editableRegionStartLine + diff.oldLineIndex!,
|
||||
this.editableRegionStartLine + diff.oldLineIndex!,
|
||||
diff.oldCharIndexInLine!,
|
||||
),
|
||||
new vscode.Position(
|
||||
editableRegionStartLine + diff.oldLineIndex!,
|
||||
this.editableRegionStartLine + diff.oldLineIndex!,
|
||||
diff.oldCharIndexInLine! + diff.char.length,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -29,13 +29,6 @@ export class ApplyManager {
|
|||
toolCallId,
|
||||
isSearchAndReplace,
|
||||
}: ApplyToFilePayload) {
|
||||
await this.webviewProtocol.request("updateApplyState", {
|
||||
streamId,
|
||||
status: "streaming",
|
||||
fileContent: text,
|
||||
toolCallId,
|
||||
});
|
||||
|
||||
if (filepath) {
|
||||
await this.ensureFileOpen(filepath);
|
||||
}
|
||||
|
|
@ -46,6 +39,17 @@ export class ApplyManager {
|
|||
return;
|
||||
}
|
||||
|
||||
// Capture the original file content before applying changes
|
||||
const originalFileContent = activeTextEditor.document.getText();
|
||||
|
||||
await this.webviewProtocol.request("updateApplyState", {
|
||||
streamId,
|
||||
status: "streaming",
|
||||
fileContent: text,
|
||||
originalFileContent,
|
||||
toolCallId,
|
||||
});
|
||||
|
||||
const hasExistingDocument = !!activeTextEditor.document.getText().trim();
|
||||
|
||||
if (hasExistingDocument) {
|
||||
|
|
|
|||
|
|
@ -420,6 +420,7 @@ export class ContinueCompletionProvider
|
|||
editor,
|
||||
currCursorPos,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
oldEditRangeSlice,
|
||||
newEditRangeSlice,
|
||||
diffLines,
|
||||
|
|
|
|||
|
|
@ -315,11 +315,12 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
// newline separated, because myersDiff() would consider
|
||||
// ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
|
||||
// "A\n" and "A\n\n" are unambiguous.
|
||||
const oldFileContent =
|
||||
diffLines
|
||||
.filter((line) => line.type === "same" || line.type === "old")
|
||||
.map((line) => line.line)
|
||||
.join("\n") + "\n";
|
||||
const oldContentWithoutTrailingNewline = diffLines
|
||||
.filter((line) => line.type === "same" || line.type === "old")
|
||||
.map((line) => line.line)
|
||||
.join("\n");
|
||||
|
||||
const oldFileContent = oldContentWithoutTrailingNewline + "\n";
|
||||
|
||||
const newFileContent =
|
||||
diffLines
|
||||
|
|
@ -329,9 +330,16 @@ export class VerticalDiffHandler implements vscode.Disposable {
|
|||
|
||||
const myersDiffs = myersDiff(oldFileContent, newFileContent);
|
||||
|
||||
const replaceContent = myersDiffs
|
||||
.map((diff) => (diff.type === "old" ? "" : diff.line))
|
||||
.join("\n");
|
||||
// Preserve the trailing newline behavior by checking the original document content
|
||||
const originalDocumentContent = this.editor.document.getText(this.range);
|
||||
const originalContentEndsWithNewline =
|
||||
originalDocumentContent.endsWith("\n");
|
||||
|
||||
// Add trailing newline only if the original file had one to prevent line count discrepancies
|
||||
const replaceContent =
|
||||
myersDiffs
|
||||
.map((diff) => (diff.type === "old" ? "" : diff.line))
|
||||
.join("\n") + (originalContentEndsWithNewline ? "\n" : "");
|
||||
|
||||
// Then, we insert our diff lines
|
||||
await this.editor.edit((editBuilder) => {
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ class EditOutcomeTracker {
|
|||
newCodeLines: pendingEdit.newCodeLines,
|
||||
lineChange: pendingEdit.lineChange,
|
||||
accepted,
|
||||
filepath: pendingEdit.filepath,
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -113,6 +113,10 @@ const StyledMarkdown = styled.div<{
|
|||
line-height: 1.5;
|
||||
}
|
||||
|
||||
* {
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
> *:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,67 +0,0 @@
|
|||
import { headerIsMarkdown } from "./headerIsMarkdown";
|
||||
|
||||
describe("headerIsMarkdown", () => {
|
||||
// Test exact match with common Markdown identifiers
|
||||
it("should identify exact matches with common Markdown identifiers", () => {
|
||||
expect(headerIsMarkdown("md")).toBe(true);
|
||||
expect(headerIsMarkdown("markdown")).toBe(true);
|
||||
expect(headerIsMarkdown("gfm")).toBe(true);
|
||||
expect(headerIsMarkdown("github-markdown")).toBe(true);
|
||||
});
|
||||
|
||||
// Test identifiers preceded by a space
|
||||
it("should identify identifiers preceded by a space", () => {
|
||||
expect(headerIsMarkdown("lang md")).toBe(true);
|
||||
expect(headerIsMarkdown("something markdown")).toBe(true);
|
||||
expect(headerIsMarkdown("language gfm")).toBe(true);
|
||||
expect(headerIsMarkdown("spec github-markdown")).toBe(true);
|
||||
});
|
||||
|
||||
// Test file extensions
|
||||
it("should identify file names with markdown extensions", () => {
|
||||
expect(headerIsMarkdown("example.md")).toBe(true);
|
||||
expect(headerIsMarkdown("document.markdown")).toBe(true);
|
||||
expect(headerIsMarkdown("readme.gfm")).toBe(true);
|
||||
});
|
||||
|
||||
// Test more complex cases with extensions
|
||||
it("should identify file names with markdown extensions followed by other text", () => {
|
||||
expect(headerIsMarkdown("example.md additional text")).toBe(true);
|
||||
expect(headerIsMarkdown("document.markdown with some description")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
|
||||
});
|
||||
|
||||
// Test non-markdown cases
|
||||
it("should not identify non-markdown headers", () => {
|
||||
expect(headerIsMarkdown("javascript")).toBe(false);
|
||||
expect(headerIsMarkdown("typescript")).toBe(false);
|
||||
expect(headerIsMarkdown("plain")).toBe(false);
|
||||
expect(headerIsMarkdown("python")).toBe(false);
|
||||
});
|
||||
|
||||
// Test edge cases
|
||||
it("should handle edge cases correctly", () => {
|
||||
expect(headerIsMarkdown("")).toBe(false);
|
||||
expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
|
||||
expect(headerIsMarkdown("readme md")).toBe(true);
|
||||
expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
|
||||
});
|
||||
|
||||
// Test case sensitivity
|
||||
it("should respect case sensitivity", () => {
|
||||
expect(headerIsMarkdown("MD")).toBe(false);
|
||||
expect(headerIsMarkdown("MARKDOWN")).toBe(false);
|
||||
expect(headerIsMarkdown("example.MD")).toBe(false);
|
||||
expect(headerIsMarkdown("lang MD")).toBe(false);
|
||||
});
|
||||
|
||||
// Test with special characters and spacing
|
||||
it("should handle special characters and spacing correctly", () => {
|
||||
expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
|
||||
expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
|
||||
expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
|
||||
expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
|
||||
});
|
||||
});
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
/**
|
||||
* Determines if a given header string represents Markdown content.
|
||||
*
|
||||
* The function checks various patterns to identify Markdown headers:
|
||||
* - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown)
|
||||
* - Contains these identifiers preceded by a space
|
||||
* - First word has a file extension of md, markdown, or gfm
|
||||
*
|
||||
* @param header - The string to check for Markdown indicators
|
||||
* @returns True if the header represents Markdown content, false otherwise
|
||||
*/
|
||||
export function headerIsMarkdown(header: string): boolean {
|
||||
return (
|
||||
header === "md" ||
|
||||
header === "markdown" ||
|
||||
header === "gfm" ||
|
||||
header === "github-markdown" ||
|
||||
header.includes(" md") ||
|
||||
header.includes(" markdown") ||
|
||||
header.includes(" gfm") ||
|
||||
header.includes(" github-markdown") ||
|
||||
header.split(" ")[0]?.split(".").pop() === "md" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "gfm"
|
||||
);
|
||||
}
|
||||
|
|
@ -6,6 +6,14 @@ describe("patchNestedMarkdown", () => {
|
|||
expect(patchNestedMarkdown(source)).toBe(source);
|
||||
});
|
||||
|
||||
it("should handle nested blocks without a type", () => {
|
||||
const source =
|
||||
"```markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n```";
|
||||
const expected =
|
||||
"~~~markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n~~~";
|
||||
expect(patchNestedMarkdown(source)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should replace backticks with tildes for markdown codeblocks", () => {
|
||||
const source = "```markdown\n# Header\nSome text\n```";
|
||||
const expected = "~~~markdown\n# Header\nSome text\n~~~";
|
||||
|
|
|
|||
|
|
@ -7,7 +7,10 @@
|
|||
|
||||
Note, this was benchmarked at sub-millisecond
|
||||
*/
|
||||
import { headerIsMarkdown } from "./headerIsMarkdown";
|
||||
import {
|
||||
headerIsMarkdown,
|
||||
MarkdownBlockStateTracker,
|
||||
} from "../../../../../core/utils/markdownUtils";
|
||||
|
||||
export const patchNestedMarkdown = (source: string): string => {
|
||||
// Early return if no markdown codeblock pattern is found (including GitHub variants)
|
||||
|
|
@ -16,21 +19,29 @@ export const patchNestedMarkdown = (source: string): string => {
|
|||
|
||||
let nestCount = 0;
|
||||
const lines = source.split("\n");
|
||||
const trimmedLines = lines.map((l) => l.trim());
|
||||
|
||||
// Use optimized state tracker for efficient bare backtick analysis
|
||||
const stateTracker = new MarkdownBlockStateTracker(lines);
|
||||
const trimmedLines = stateTracker.getTrimmedLines();
|
||||
|
||||
for (let i = 0; i < trimmedLines.length; i++) {
|
||||
const line = trimmedLines[i];
|
||||
|
||||
if (nestCount > 0) {
|
||||
// Inside a markdown block
|
||||
if (line.match(/^`+$/)) {
|
||||
// Ending a block with just backticks (```)
|
||||
nestCount--;
|
||||
if (nestCount === 0) {
|
||||
lines[i] = "~~~"; // End of markdown block
|
||||
if (stateTracker.isBareBacktickLine(i)) {
|
||||
// Found bare backticks - use optimized lookup for remaining count
|
||||
const remainingBareBackticks =
|
||||
stateTracker.getRemainingBareBackticksAfter(i);
|
||||
|
||||
// If this is the last bare backticks, it closes the markdown block
|
||||
if (remainingBareBackticks === 0) {
|
||||
nestCount = 0;
|
||||
lines[i] = "~~~"; // Convert final closing delimiter to tildes
|
||||
}
|
||||
// Otherwise, keep as backticks (inner nested block delimiter)
|
||||
} else if (line.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
// Going into a nested codeblock (with language identifier)
|
||||
nestCount++;
|
||||
}
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import {
|
|||
ExclamationCircleIcon,
|
||||
ExclamationTriangleIcon,
|
||||
InformationCircleIcon,
|
||||
} from "@heroicons/react/24/solid";
|
||||
} from "@heroicons/react/16/solid";
|
||||
import { ReactNode } from "react";
|
||||
import { vscBackground } from "..";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import {
|
||||
AtSymbolIcon,
|
||||
LightBulbIcon,
|
||||
LightBulbIcon as LightBulbIconOutline,
|
||||
PhotoIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { LightBulbIcon as LightBulbIconSolid } from "@heroicons/react/24/solid";
|
||||
import { InputModifiers } from "core";
|
||||
import { modelSupportsImages } from "core/llm/autodetect";
|
||||
import { useContext, useRef } from "react";
|
||||
|
|
@ -13,7 +14,6 @@ import { selectSelectedChatModel } from "../../redux/slices/configSlice";
|
|||
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
|
||||
import { exitEdit } from "../../redux/thunks/edit";
|
||||
import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
|
||||
import { cn } from "../../util/cn";
|
||||
import { ToolTip } from "../gui/Tooltip";
|
||||
import ModelSelect from "../modelSelection/ModelSelect";
|
||||
import { ModeSelect } from "../ModeSelect";
|
||||
|
|
@ -139,19 +139,23 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
</ToolTip>
|
||||
</HoverItem>
|
||||
)}
|
||||
{defaultModel?.provider === "anthropic" && (
|
||||
{defaultModel?.underlyingProviderName === "anthropic" && (
|
||||
<HoverItem
|
||||
onClick={() =>
|
||||
dispatch(setHasReasoningEnabled(!hasReasoningEnabled))
|
||||
}
|
||||
>
|
||||
<LightBulbIcon
|
||||
data-tooltip-id="model-reasoning-tooltip"
|
||||
className={cn(
|
||||
"h-3 w-3 hover:brightness-150",
|
||||
hasReasoningEnabled && "brightness-200",
|
||||
)}
|
||||
/>
|
||||
{hasReasoningEnabled ? (
|
||||
<LightBulbIconSolid
|
||||
data-tooltip-id="model-reasoning-tooltip"
|
||||
className="h-3 w-3 brightness-200 hover:brightness-150"
|
||||
/>
|
||||
) : (
|
||||
<LightBulbIconOutline
|
||||
data-tooltip-id="model-reasoning-tooltip"
|
||||
className="h-3 w-3 hover:brightness-150"
|
||||
/>
|
||||
)}
|
||||
|
||||
<ToolTip id="model-reasoning-tooltip" place="top">
|
||||
{hasReasoningEnabled
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ export function GeneratingIndicator({
|
|||
testId?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center" data-testid={testId}>
|
||||
<span className="text-description text-xs">{text}</span>
|
||||
<div className="text-description flex items-center" data-testid={testId}>
|
||||
<span className="text-xs">{text}</span>
|
||||
<AnimatedEllipsis />
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Tool } from "core";
|
||||
import { MessageModes, Tool } from "core";
|
||||
import { useMemo } from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
|
||||
import { toggleToolGroupSetting } from "../../../../../redux/slices/uiSlice";
|
||||
|
|
@ -43,20 +43,28 @@ export const ToolPoliciesSection = () => {
|
|||
|
||||
const allToolsOff = mode === "chat";
|
||||
|
||||
const message =
|
||||
mode === "chat"
|
||||
? "All tools disabled (Chat)"
|
||||
: mode === "plan"
|
||||
? "Read-only/MCP tools available (Plan)"
|
||||
: "All tools available (Agent)";
|
||||
const getMessage = (mode: MessageModes) => {
|
||||
switch (mode) {
|
||||
case "chat":
|
||||
return "All tools disabled in Chat, switch to Plan or Agent mode to use tools";
|
||||
case "plan":
|
||||
return "Read-only/MCP tools available in Plan mode";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const message = getMessage(mode);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="my-1 mb-3">
|
||||
<Alert type="info" size="sm">
|
||||
<span className="text-2xs italic">{message}</span>
|
||||
</Alert>
|
||||
</div>
|
||||
{(mode === "chat" || mode === "plan") && (
|
||||
<div className="my-1 mb-3">
|
||||
<Alert type="info" size="sm">
|
||||
<span className="text-2xs italic">{message}</span>
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
{toolsByGroup.map(([groupName, tools]) => {
|
||||
const isGroupEnabled =
|
||||
!allToolsOff && toolGroupSettings[groupName] !== "exclude";
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { screen } from "@testing-library/react";
|
||||
import { NodeViewProps } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { beforeEach, describe, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "../../../../../util/test/render";
|
||||
import { CodeBlockPreview } from "./CodeBlockPreview";
|
||||
|
||||
const postIde = vi.fn();
|
||||
|
||||
vi.mock("../../../../../context/MockIdeMessenger", async (importOriginal) => {
|
||||
const original = (await importOriginal()) as any;
|
||||
return {
|
||||
...original,
|
||||
MockIdeMessenger: class MockedMockIdeMessenger extends original.MockIdeMessenger {
|
||||
post(...args: any[]) {
|
||||
postIde(...args);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe("CodeBlockPreview", () => {
|
||||
const createMockContextItem = (
|
||||
overrides: Partial<ContextItemWithId> = {},
|
||||
): ContextItemWithId => ({
|
||||
content: "console.log('test');",
|
||||
name: "test.ts",
|
||||
description: "Test file",
|
||||
id: {
|
||||
providerTitle: "file",
|
||||
itemId: "test-item-id",
|
||||
},
|
||||
uri: {
|
||||
type: "file",
|
||||
value: "/test/test.ts",
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createMockNodeViewProps = (
|
||||
item: ContextItemWithId,
|
||||
selected = false,
|
||||
): NodeViewProps => ({
|
||||
node: {
|
||||
attrs: {
|
||||
item,
|
||||
},
|
||||
} as any,
|
||||
view: {} as any,
|
||||
getPos: vi.fn(() => 0),
|
||||
innerDecorations: {} as any,
|
||||
editor: {} as any,
|
||||
extension: {} as any,
|
||||
HTMLAttributes: {},
|
||||
decorations: [] as any,
|
||||
selected,
|
||||
updateAttributes: vi.fn(),
|
||||
deleteNode: vi.fn(),
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("opens file when title is clicked", async () => {
|
||||
const item = createMockContextItem({
|
||||
id: { providerTitle: "file", itemId: "test-id" },
|
||||
uri: { type: "file", value: "/test/file.ts" },
|
||||
name: "test.ts",
|
||||
});
|
||||
const props = createMockNodeViewProps(item);
|
||||
|
||||
await renderWithProviders(<CodeBlockPreview {...props} />);
|
||||
|
||||
const title = screen.getByText("test.ts");
|
||||
title.click();
|
||||
|
||||
expect(postIde).toHaveBeenCalled();
|
||||
expect(postIde).toHaveBeenCalledWith("showFile", {
|
||||
filepath: "/test/file.ts",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -42,7 +42,7 @@ export const CodeBlockPreview = ({
|
|||
});
|
||||
} else if (item.id.providerTitle === "code") {
|
||||
const rif = ctxItemToRifWithContents(item, true);
|
||||
ideMessenger.ide.showLines(
|
||||
void ideMessenger.ide.showLines(
|
||||
rif.filepath,
|
||||
rif.range.start.line,
|
||||
rif.range.end.line,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import { useAuth } from "../../context/Auth";
|
|||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { AddModelForm } from "../../forms/AddModelForm";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { EMPTY_CONFIG } from "../../redux/slices/configSlice";
|
||||
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
|
||||
import { updateSelectedModelByRole } from "../../redux/thunks/updateSelectedModelByRole";
|
||||
import {
|
||||
|
|
@ -94,6 +93,7 @@ function ModelSelect() {
|
|||
|
||||
const isInEdit = useAppSelector((store) => store.session.isInEdit);
|
||||
const config = useAppSelector((state) => state.config.config);
|
||||
const isConfigLoading = useAppSelector((state) => state.config.loading);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const [options, setOptions] = useState<Option[]>([]);
|
||||
|
|
@ -192,7 +192,6 @@ function ModelSelect() {
|
|||
);
|
||||
}
|
||||
|
||||
const isConfigLoading = config === EMPTY_CONFIG;
|
||||
const hasNoModels = allModels?.length === 0;
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import {
|
|||
setDocumentStylesFromTheme,
|
||||
} from "../styles/theme";
|
||||
import { isJetBrains } from "../util";
|
||||
import { logAgentModeEditOutcome } from "../util/editOutcomeLogger";
|
||||
import { setLocalStorage } from "../util/localStorage";
|
||||
import { migrateLocalStorage } from "../util/migrateLocalStorage";
|
||||
import { useWebviewListener } from "./useWebviewListener";
|
||||
|
|
@ -276,17 +277,40 @@ function ParallelListeners() {
|
|||
store.getState().session.history,
|
||||
state.toolCallId,
|
||||
);
|
||||
if (toolCallState && toolCallState.status !== "canceled") {
|
||||
dispatch(
|
||||
acceptToolCall({
|
||||
toolCallId: state.toolCallId,
|
||||
}),
|
||||
);
|
||||
void dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: state.toolCallId,
|
||||
}),
|
||||
);
|
||||
|
||||
if (toolCallState) {
|
||||
const accepted = toolCallState.status !== "canceled";
|
||||
|
||||
logToolUsage(toolCallState, accepted, true, ideMessenger);
|
||||
|
||||
// Log edit outcome for Agent Mode
|
||||
const applyState = store
|
||||
.getState()
|
||||
.session.codeBlockApplyStates.states.find(
|
||||
(s) => s.streamId === state.streamId,
|
||||
);
|
||||
|
||||
if (applyState) {
|
||||
void logAgentModeEditOutcome(
|
||||
toolCallState,
|
||||
applyState,
|
||||
accepted,
|
||||
ideMessenger,
|
||||
);
|
||||
}
|
||||
|
||||
if (accepted) {
|
||||
dispatch(
|
||||
acceptToolCall({
|
||||
toolCallId: state.toolCallId,
|
||||
}),
|
||||
);
|
||||
void dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: state.toolCallId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
// const output: ContextItem = {
|
||||
// name: "Edit tool output",
|
||||
|
|
|
|||
19
gui/src/pages/gui/ToolCallDiv/IndicatorBar.tsx
Normal file
19
gui/src/pages/gui/ToolCallDiv/IndicatorBar.tsx
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { ChevronDownIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
interface IndicatorBarProps {
|
||||
text: string;
|
||||
isExpanded: boolean;
|
||||
}
|
||||
|
||||
export function IndicatorBar({ text, isExpanded }: IndicatorBarProps) {
|
||||
return (
|
||||
<div className="absolute left-0 right-0 top-0 z-10 flex h-8 items-start justify-center pt-1">
|
||||
<div className="border-border bg-editor text-description flex items-center gap-2 rounded border px-2 py-1 text-[11px] shadow-sm">
|
||||
<span>{text}</span>
|
||||
<ChevronDownIcon
|
||||
className={`text-description h-3 w-3 ${isExpanded ? "" : "rotate-180"}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
import { ToolCallState } from "core";
|
||||
import styled from "styled-components";
|
||||
import { vscForeground } from "../../../components";
|
||||
import { useMemo } from "react";
|
||||
import Ansi from "../../../components/ansiTerminal/Ansi";
|
||||
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
|
||||
import { useAppDispatch } from "../../../redux/hooks";
|
||||
import { moveTerminalProcessToBackground } from "../../../redux/thunks/moveTerminalProcessToBackground";
|
||||
import { TerminalCollapsibleContainer } from "./TerminalCollapsibleContainer";
|
||||
|
||||
interface RunTerminalCommandToolCallProps {
|
||||
command: string;
|
||||
|
|
@ -12,64 +12,34 @@ interface RunTerminalCommandToolCallProps {
|
|||
toolCallId: string | undefined;
|
||||
}
|
||||
|
||||
const CommandStatus = styled.div`
|
||||
font-size: 12px;
|
||||
color: var(--vscode-descriptionForeground, ${vscForeground}88);
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 8px;
|
||||
padding-right: 8px;
|
||||
`;
|
||||
|
||||
const StatusIcon = styled.span<{
|
||||
interface StatusIconProps {
|
||||
status: "running" | "completed" | "failed" | "background";
|
||||
}>`
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
margin-right: 8px;
|
||||
background-color: ${(props) =>
|
||||
props.status === "running"
|
||||
? "var(--vscode-testing-runAction, #4caf50)"
|
||||
: props.status === "completed"
|
||||
? "var(--vscode-testing-iconPassed, #4caf50)"
|
||||
: props.status === "background"
|
||||
? "var(--vscode-statusBarItem-prominentBackground, #2196f3)"
|
||||
: "var(--vscode-testing-iconFailed, #f44336)"};
|
||||
${(props) =>
|
||||
props.status === "running" ? "animation: pulse 1.5s infinite;" : ""}
|
||||
`;
|
||||
}
|
||||
|
||||
// Waiting message styled for consistency
|
||||
const WaitingMessage = styled.div`
|
||||
padding: 8px;
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
margin-top: 8px;
|
||||
`;
|
||||
function StatusIcon({ status }: StatusIconProps) {
|
||||
const getStatusColor = () => {
|
||||
switch (status) {
|
||||
case "running":
|
||||
return "bg-success";
|
||||
case "completed":
|
||||
return "bg-success";
|
||||
case "background":
|
||||
return "bg-accent";
|
||||
case "failed":
|
||||
return "bg-error";
|
||||
default:
|
||||
return "bg-success";
|
||||
}
|
||||
};
|
||||
|
||||
// For consistency with the rest of the styled components
|
||||
const AnsiWrapper = styled.div`
|
||||
margin-top: 8px;
|
||||
`;
|
||||
|
||||
const BackgroundLink = styled.a`
|
||||
font-size: 12px;
|
||||
color: var(--vscode-textLink-foreground, #3794ff);
|
||||
margin-left: 12px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`;
|
||||
|
||||
// Just spacing between terminal components and the next toolcall
|
||||
const TerminalContainer = styled.div`
|
||||
margin-bottom: 16px;
|
||||
`;
|
||||
return (
|
||||
<span
|
||||
className={`mr-2 h-2 w-2 rounded-full ${getStatusColor()} ${
|
||||
status === "running" ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
||||
const dispatch = useAppDispatch();
|
||||
|
|
@ -84,6 +54,42 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
|||
const isRunning = props.toolCallState.status === "calling";
|
||||
const hasOutput = terminalContent.length > 0;
|
||||
|
||||
const displayLines = 15;
|
||||
|
||||
// Process terminal content for line limiting
|
||||
const processedTerminalContent = useMemo(() => {
|
||||
if (!terminalContent)
|
||||
return {
|
||||
fullContent: "",
|
||||
limitedContent: "",
|
||||
totalLines: 0,
|
||||
isLimited: false,
|
||||
hiddenLinesCount: 0,
|
||||
};
|
||||
|
||||
const lines = terminalContent.split("\n");
|
||||
const totalLines = lines.length;
|
||||
|
||||
if (totalLines > displayLines) {
|
||||
const lastTwentyLines = lines.slice(-displayLines);
|
||||
return {
|
||||
fullContent: terminalContent,
|
||||
limitedContent: lastTwentyLines.join("\n"),
|
||||
totalLines,
|
||||
isLimited: true,
|
||||
hiddenLinesCount: totalLines - displayLines,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
fullContent: terminalContent,
|
||||
limitedContent: terminalContent,
|
||||
totalLines,
|
||||
isLimited: false,
|
||||
hiddenLinesCount: 0,
|
||||
};
|
||||
}, [terminalContent]);
|
||||
|
||||
// Determine status type
|
||||
let statusType: "running" | "completed" | "failed" | "background" =
|
||||
"completed";
|
||||
|
|
@ -96,7 +102,7 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
|||
}
|
||||
|
||||
return (
|
||||
<TerminalContainer>
|
||||
<div className="mb-4">
|
||||
{/* Command */}
|
||||
<StyledMarkdownPreview
|
||||
isRenderingInStepContainer
|
||||
|
|
@ -105,21 +111,33 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
|||
|
||||
{/* Terminal output with ANSI support */}
|
||||
{isRunning && !hasOutput && (
|
||||
<WaitingMessage>Waiting for output...</WaitingMessage>
|
||||
<div className="mt-2 px-4 py-2">Waiting for output...</div>
|
||||
)}
|
||||
{hasOutput && (
|
||||
<AnsiWrapper>
|
||||
<Ansi>{terminalContent}</Ansi>
|
||||
</AnsiWrapper>
|
||||
<TerminalCollapsibleContainer
|
||||
collapsible={processedTerminalContent.isLimited}
|
||||
hiddenLinesCount={processedTerminalContent.hiddenLinesCount}
|
||||
className="mt-2"
|
||||
collapsedContent={
|
||||
<div className="mt-2">
|
||||
<Ansi>{processedTerminalContent.limitedContent}</Ansi>
|
||||
</div>
|
||||
}
|
||||
expandedContent={
|
||||
<div className="mt-2">
|
||||
<Ansi>{processedTerminalContent.fullContent}</Ansi>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Status information */}
|
||||
{(statusMessage || isRunning) && (
|
||||
<CommandStatus>
|
||||
<div className="text-description mt-2 flex items-center px-2 text-xs">
|
||||
<StatusIcon status={statusType} />
|
||||
{isRunning ? "Running" : statusMessage}
|
||||
{isRunning && props.toolCallId && (
|
||||
<BackgroundLink
|
||||
<span
|
||||
onClick={() => {
|
||||
// Dispatch the action to move the command to the background
|
||||
dispatch(
|
||||
|
|
@ -128,12 +146,13 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
|||
}),
|
||||
);
|
||||
}}
|
||||
className="text-link ml-3 cursor-pointer text-xs no-underline hover:underline"
|
||||
>
|
||||
Move to background
|
||||
</BackgroundLink>
|
||||
</span>
|
||||
)}
|
||||
</CommandStatus>
|
||||
</div>
|
||||
)}
|
||||
</TerminalContainer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,61 @@
|
|||
import { useState } from "react";
|
||||
import { IndicatorBar } from "./IndicatorBar";
|
||||
|
||||
interface TerminalCollapsibleContainerProps {
|
||||
collapsedContent: React.ReactNode;
|
||||
expandedContent: React.ReactNode;
|
||||
className?: string;
|
||||
collapsible?: boolean;
|
||||
hiddenLinesCount?: number;
|
||||
}
|
||||
|
||||
export function TerminalCollapsibleContainer({
|
||||
collapsedContent,
|
||||
expandedContent,
|
||||
className = "",
|
||||
collapsible = false,
|
||||
hiddenLinesCount = 0,
|
||||
}: TerminalCollapsibleContainerProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
|
||||
if (!collapsible) {
|
||||
return <div className={className}>{collapsedContent}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`relative ${className}`}>
|
||||
{/* Indicator bar - shows for both collapsed and expanded states */}
|
||||
{((!isExpanded && hiddenLinesCount > 0) ||
|
||||
(isExpanded && collapsible)) && (
|
||||
<IndicatorBar
|
||||
text={isExpanded ? "Collapse" : `+${hiddenLinesCount} more lines`}
|
||||
isExpanded={isExpanded}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Clickable overlay covering the entire content area */}
|
||||
{collapsible && (
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsExpanded(!isExpanded);
|
||||
}}
|
||||
className="absolute inset-0 z-20 cursor-pointer"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Content container with proper constraint for gradient */}
|
||||
<div
|
||||
className={`relative overflow-hidden rounded-lg ${collapsible ? "cursor-pointer" : ""}`}
|
||||
>
|
||||
{/* Gradient overlay on top of content - only when collapsed */}
|
||||
{!isExpanded && hiddenLinesCount > 0 && (
|
||||
<div className="from-editor pointer-events-none absolute left-[9px] right-[9px] top-4 z-[5] h-[100px] rounded-t-md bg-gradient-to-b to-transparent" />
|
||||
)}
|
||||
|
||||
{isExpanded ? expandedContent : collapsedContent}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -68,6 +68,7 @@ export const configSlice = createSlice({
|
|||
} else {
|
||||
state.config = config;
|
||||
}
|
||||
state.loading = false;
|
||||
},
|
||||
updateConfig: (
|
||||
state,
|
||||
|
|
|
|||
|
|
@ -784,6 +784,9 @@ export const sessionSlice = createSlice({
|
|||
applyState.status = payload.status ?? applyState.status;
|
||||
applyState.numDiffs = payload.numDiffs ?? applyState.numDiffs;
|
||||
applyState.filepath = payload.filepath ?? applyState.filepath;
|
||||
applyState.fileContent = payload.fileContent ?? applyState.fileContent;
|
||||
applyState.originalFileContent =
|
||||
payload.originalFileContent ?? applyState.originalFileContent;
|
||||
}
|
||||
|
||||
if (payload.status === "done") {
|
||||
|
|
|
|||
|
|
@ -157,7 +157,8 @@ export const streamNormalInput = createAsyncThunk<
|
|||
completionOptions = {
|
||||
...completionOptions,
|
||||
reasoning: true,
|
||||
reasoningBudgetTokens: completionOptions.reasoningBudgetTokens ?? 2048,
|
||||
reasoningBudgetTokens:
|
||||
selectedChatModel.completionOptions?.reasoningBudgetTokens ?? 2048,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
81
gui/src/util/editOutcomeLogger.test.ts
Normal file
81
gui/src/util/editOutcomeLogger.test.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { ApplyState, ToolCallState } from "core";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { assembleEditOutcomeData } from "./editOutcomeLogger";
|
||||
|
||||
vi.mock("../redux/store", () => ({
|
||||
store: {
|
||||
getState: vi.fn(() => ({
|
||||
session: { history: [] },
|
||||
config: {
|
||||
config: {
|
||||
selectedModelByRole: {
|
||||
chat: { provider: "test", model: "test-model" },
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("assembleEditOutcomeData", () => {
|
||||
it("should assemble complete edit outcome data correctly", () => {
|
||||
const toolCallState: ToolCallState = {
|
||||
status: "generating",
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: { name: "test", arguments: "{}" },
|
||||
},
|
||||
parsedArgs: {},
|
||||
};
|
||||
|
||||
const applyState: ApplyState = {
|
||||
streamId: "stream-123",
|
||||
filepath: "/test/file.ts",
|
||||
originalFileContent: "const old = 1;",
|
||||
fileContent: "const new = 2;\nconst another = 3;",
|
||||
};
|
||||
|
||||
const result = assembleEditOutcomeData(toolCallState, applyState, true);
|
||||
console.log(result);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
streamId: "stream-123",
|
||||
filepath: "/test/file.ts",
|
||||
previousCode: "const old = 1;",
|
||||
newCode: "const new = 2;\nconst another = 3;",
|
||||
previousCodeLines: 1,
|
||||
newCodeLines: 2,
|
||||
lineChange: 1,
|
||||
accepted: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle empty code content", () => {
|
||||
const toolCallState: ToolCallState = {
|
||||
status: "generating",
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: { name: "test", arguments: "{}" },
|
||||
},
|
||||
parsedArgs: {},
|
||||
};
|
||||
|
||||
const applyState: ApplyState = {
|
||||
streamId: "stream-123",
|
||||
filepath: "/test/empty.ts",
|
||||
originalFileContent: "",
|
||||
fileContent: "",
|
||||
};
|
||||
|
||||
const result = assembleEditOutcomeData(toolCallState, applyState, false);
|
||||
|
||||
expect(result.previousCodeLines).toBe(0);
|
||||
expect(result.newCodeLines).toBe(0);
|
||||
expect(result.lineChange).toBe(0);
|
||||
expect(result.accepted).toBe(false);
|
||||
});
|
||||
});
|
||||
190
gui/src/util/editOutcomeLogger.ts
Normal file
190
gui/src/util/editOutcomeLogger.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import { ApplyState, ToolCallState } from "core";
|
||||
import { IIdeMessenger } from "../context/IdeMessenger";
|
||||
import { store } from "../redux/store";
|
||||
|
||||
/**
|
||||
* Extract model information from tool call state
|
||||
*/
|
||||
function extractModelInfo(toolCallState: ToolCallState): {
|
||||
modelProvider: string;
|
||||
modelTitle: string;
|
||||
} {
|
||||
// Get the conversation history to find the model info
|
||||
const history = store.getState().session.history;
|
||||
|
||||
// Find the assistant message that contains this tool call
|
||||
const assistantMessage = history.find(
|
||||
(item) =>
|
||||
item.message.role === "assistant" &&
|
||||
item.message.toolCalls?.some((tc) => tc.id === toolCallState.toolCallId),
|
||||
);
|
||||
|
||||
if (
|
||||
assistantMessage?.message.role === "assistant" &&
|
||||
"model" in assistantMessage.message &&
|
||||
assistantMessage.message.model
|
||||
) {
|
||||
// Extract provider from model string (e.g., "anthropic::claude-3-5-sonnet" -> "anthropic")
|
||||
const modelParts = String(assistantMessage.message.model).split("::");
|
||||
return {
|
||||
modelProvider: modelParts[0] || "unknown",
|
||||
modelTitle: modelParts[1] || String(assistantMessage.message.model),
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback to config if not found in message
|
||||
const config = store.getState().config.config;
|
||||
const chatModel = config?.selectedModelByRole?.chat;
|
||||
|
||||
return {
|
||||
modelProvider: chatModel?.provider || "unknown",
|
||||
modelTitle: chatModel?.model || "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract prompt and completion from tool call state
|
||||
*/
|
||||
function extractPromptAndCompletion(toolCallState: ToolCallState): {
|
||||
prompt: string;
|
||||
completion: string;
|
||||
} {
|
||||
const history = store.getState().session.history;
|
||||
|
||||
// Find the assistant message with this tool call
|
||||
const assistantMessageIndex = history.findIndex(
|
||||
(item) =>
|
||||
item.message.role === "assistant" &&
|
||||
item.message.toolCalls?.some((tc) => tc.id === toolCallState.toolCallId),
|
||||
);
|
||||
|
||||
if (assistantMessageIndex >= 0) {
|
||||
const assistantMessage = history[assistantMessageIndex];
|
||||
|
||||
// Look for the most recent user message before this assistant message
|
||||
let userMessage = null;
|
||||
for (let i = assistantMessageIndex - 1; i >= 0; i--) {
|
||||
if (history[i].message.role === "user") {
|
||||
userMessage = history[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const promptContent = userMessage
|
||||
? Array.isArray(userMessage.message.content)
|
||||
? userMessage.message.content
|
||||
.map((part) =>
|
||||
typeof part === "string"
|
||||
? part
|
||||
: part.type === "text"
|
||||
? part.text || ""
|
||||
: "",
|
||||
)
|
||||
.join("")
|
||||
: userMessage.message.content || ""
|
||||
: "";
|
||||
|
||||
const completionContent = Array.isArray(assistantMessage.message.content)
|
||||
? assistantMessage.message.content
|
||||
.map((part) =>
|
||||
typeof part === "string"
|
||||
? part
|
||||
: part.type === "text"
|
||||
? part.text || ""
|
||||
: "",
|
||||
)
|
||||
.join("")
|
||||
: assistantMessage.message.content || "";
|
||||
|
||||
return {
|
||||
prompt: promptContent,
|
||||
completion: completionContent,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: "Unknown prompt",
|
||||
completion: "Unknown completion",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract code changes from apply state
|
||||
*/
|
||||
function extractCodeChanges(applyState: ApplyState): {
|
||||
previousCode: string;
|
||||
newCode: string;
|
||||
previousCodeLines: number;
|
||||
newCodeLines: number;
|
||||
lineChange: number;
|
||||
} {
|
||||
// Use the original file content if provided, otherwise empty string
|
||||
const previousCode = applyState.originalFileContent || "";
|
||||
const newCode = applyState.fileContent || "";
|
||||
|
||||
// Calculate line counts properly - empty string should be 0 lines, not 1
|
||||
const previousCodeLines =
|
||||
previousCode === "" ? 0 : previousCode.split("\n").length;
|
||||
const newCodeLines = newCode === "" ? 0 : newCode.split("\n").length;
|
||||
const lineChange = newCodeLines - previousCodeLines;
|
||||
|
||||
return {
|
||||
previousCode,
|
||||
newCode,
|
||||
previousCodeLines,
|
||||
newCodeLines,
|
||||
lineChange,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble complete edit outcome data from tool call and apply state
|
||||
*/
|
||||
export function assembleEditOutcomeData(
|
||||
toolCallState: ToolCallState,
|
||||
applyState: ApplyState,
|
||||
accepted: boolean,
|
||||
) {
|
||||
const modelInfo = extractModelInfo(toolCallState);
|
||||
const promptAndCompletion = extractPromptAndCompletion(toolCallState);
|
||||
const codeChanges = extractCodeChanges(applyState);
|
||||
|
||||
return {
|
||||
streamId: applyState.streamId,
|
||||
timestamp: new Date().toISOString(),
|
||||
modelProvider: modelInfo.modelProvider,
|
||||
modelTitle: modelInfo.modelTitle,
|
||||
prompt: promptAndCompletion.prompt,
|
||||
completion: promptAndCompletion.completion,
|
||||
previousCode: codeChanges.previousCode,
|
||||
newCode: codeChanges.newCode,
|
||||
filepath: applyState.filepath || "",
|
||||
previousCodeLines: codeChanges.previousCodeLines,
|
||||
newCodeLines: codeChanges.newCodeLines,
|
||||
lineChange: codeChanges.lineChange,
|
||||
accepted,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Log Agent Mode edit outcome to editOutcome.jsonl
|
||||
*/
|
||||
export async function logAgentModeEditOutcome(
|
||||
toolCallState: ToolCallState,
|
||||
applyState: ApplyState,
|
||||
accepted: boolean,
|
||||
ideMessenger: IIdeMessenger,
|
||||
): Promise<void> {
|
||||
// Use the original file content stored in applyState, captured before edits were applied
|
||||
|
||||
const editOutcomeData = assembleEditOutcomeData(
|
||||
toolCallState,
|
||||
applyState,
|
||||
accepted,
|
||||
);
|
||||
|
||||
ideMessenger.post("devdata/log", {
|
||||
name: "editOutcome",
|
||||
data: editOutcomeData,
|
||||
});
|
||||
}
|
||||
|
|
@ -12,4 +12,5 @@ export const editOutcomeEventAllSchema = baseDevDataAllSchema.extend({
|
|||
newCodeLines: z.number(),
|
||||
lineChange: z.number(),
|
||||
accepted: z.boolean(),
|
||||
filepath: z.string(),
|
||||
});
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue