Merge branch 'continuedev:main' into init-tool-policy-in-tools-definitions
This commit is contained in:
commit
50f7331122
30 changed files with 2744 additions and 267 deletions
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
|
||||
|
|
|
|||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
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>
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.30
|
||||
pluginVersion=1.0.31
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`.process
|
||||
|
||||
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
|
||||
|
|
@ -44,11 +45,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 +65,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(
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.66",
|
||||
"version": "1.1.67",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
|
|
|
|||
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>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue