Changesets · Branches · Tags · Compare
| Changeset | fa7d9685012ea5e151ad16ad42b7cc8e15248f062ce10f579bda9a6866ef2942 |
|---|---|
| Author | Dallin Romney <dallinromney@gmail.com> · 2025-07-24 14:33 +02:00 |
| Committer | GitHub <noreply@github.com> · 2025-07-24 14:33 +02:00 |
| Parents | 44b20f765bd5, 8c937313cfcd |
17 files changed
added core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts +146 −0
| @@ -0,0 +1,146 @@ | ||
| 1 | +import { LineStream } from "../../../diff/util"; | |
| 2 | + | |
| 3 | +import { | |
| 4 | + collectAllLines, | |
| 5 | + MarkdownBlockStateTracker, | |
| 6 | +} from "../../../utils/markdownUtils"; | |
| 7 | + | |
| 8 | +import { | |
| 9 | + processBlockNesting, | |
| 10 | + shouldStopAtMarkdownBlock, | |
| 11 | +} from "../../../utils/streamMarkdownUtils"; | |
| 12 | + | |
| 13 | +import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream"; | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. | |
| 17 | + * Now includes markdown-aware processing to handle nested markdown blocks properly. | |
| 18 | + * | |
| 19 | + * @param {LineStream} rawLines - The input stream of lines to filter. | |
| 20 | + * @param {string} filepath - Optional filepath to determine if this is a markdown file. | |
| 21 | + * @yields {string} Filtered and processed lines from the code block. | |
| 22 | + * | |
| 23 | + * @description | |
| 24 | + * This generator function performs the following tasks: | |
| 25 | + * 1. Removes initial lines that should be removed before the actual code starts. | |
| 26 | + * 2. For markdown files, applies nested markdown block logic to avoid premature termination. | |
| 27 | + * 3. For mixed content, uses simplified processing to avoid premature termination. | |
| 28 | + * 4. For traditional code blocks, uses original logic. | |
| 29 | + * 5. Yields processed lines that are part of the actual code block content. | |
| 30 | + */ | |
| 31 | +export async function* filterCodeBlockLines( | |
| 32 | + rawLines: LineStream, | |
| 33 | + filepath?: string, | |
| 34 | +): LineStream { | |
| 35 | + // Collect all lines for analysis | |
| 36 | + const allLines = await collectAllLines(rawLines); | |
| 37 | + | |
| 38 | + // Check if it has nested markdown blocks (like ```markdown or ```md) | |
| 39 | + const firstLine = allLines[0] || ""; | |
| 40 | + const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); | |
| 41 | + | |
| 42 | + // TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks) | |
| 43 | + // But exclude cases where we have nested markdown blocks | |
| 44 | + const hasMarkdownHeaders = allLines.some( | |
| 45 | + (line) => line.trim().startsWith("#") && !line.trim().startsWith("```"), | |
| 46 | + ); | |
| 47 | + | |
| 48 | + const hasCodeBlocks = allLines.some( | |
| 49 | + (line) => line.trim().startsWith("```") && line.trim().length >= 3, | |
| 50 | + ); | |
| 51 | + const isMixedContent = | |
| 52 | + hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown; | |
| 53 | + | |
| 54 | + // If this is mixed content, use simplified processing | |
| 55 | + if (isMixedContent) { | |
| 56 | + for (let i = 0; i < allLines.length; i++) { | |
| 57 | + const line = allLines[i]; | |
| 58 | + | |
| 59 | + // Skip initial wrapper lines if they exist | |
| 60 | + if (i === 0 && shouldRemoveLineBeforeStart(line)) { | |
| 61 | + continue; | |
| 62 | + } | |
| 63 | + | |
| 64 | + yield line; | |
| 65 | + } | |
| 66 | + return; | |
| 67 | + } | |
| 68 | + | |
| 69 | + // Original logic for non-mixed content | |
| 70 | + let seenFirstFence = false; | |
| 71 | + let nestCount = 0; | |
| 72 | + | |
| 73 | + // Create optimized state tracker for markdown block analysis if needed | |
| 74 | + let markdownStateTracker: MarkdownBlockStateTracker | undefined; | |
| 75 | + if (hasNestedMarkdown) { | |
| 76 | + markdownStateTracker = new MarkdownBlockStateTracker(allLines); | |
| 77 | + } | |
| 78 | + | |
| 79 | + for (let i = 0; i < allLines.length; i++) { | |
| 80 | + const line = allLines[i]; | |
| 81 | + | |
| 82 | + // Process block nesting logic for the first fence | |
| 83 | + const nesting = processBlockNesting( | |
| 84 | + line, | |
| 85 | + seenFirstFence, | |
| 86 | + shouldRemoveLineBeforeStart, | |
| 87 | + ); | |
| 88 | + if (nesting.shouldSkip) { | |
| 89 | + continue; // Filter out starting ``` or START block | |
| 90 | + } | |
| 91 | + if (!seenFirstFence && nesting.newSeenFirstFence) { | |
| 92 | + seenFirstFence = true; | |
| 93 | + nestCount = 1; | |
| 94 | + } | |
| 95 | + | |
| 96 | + if (nestCount > 0) { | |
| 97 | + // Inside a block including the outer block | |
| 98 | + const changedEndLine = shouldChangeLineAndStop(line); | |
| 99 | + if (typeof changedEndLine === "string") { | |
| 100 | + // Ending a block with just backticks (```) or STOP | |
| 101 | + | |
| 102 | + // For markdown files with nested markdown blocks, apply special logic | |
| 103 | + if ( | |
| 104 | + hasNestedMarkdown && | |
| 105 | + line.trim() === "```" && | |
| 106 | + markdownStateTracker | |
| 107 | + ) { | |
| 108 | + if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { | |
| 109 | + return; // Stop without yielding the final closing ``` | |
| 110 | + } else { | |
| 111 | + // This is an inner block delimiter, yield it as content | |
| 112 | + yield line; | |
| 113 | + continue; | |
| 114 | + } | |
| 115 | + } | |
| 116 | + | |
| 117 | + // Original logic for non-markdown files or simple cases | |
| 118 | + nestCount--; | |
| 119 | + if (nestCount === 0) { | |
| 120 | + // We've closed the outer wrapper - stop without yielding the closing ``` | |
| 121 | + return; | |
| 122 | + } else { | |
| 123 | + // This is a nested block closing, yield it as content | |
| 124 | + yield line; | |
| 125 | + } | |
| 126 | + } else if (line.startsWith("```")) { | |
| 127 | + // Going into a nested codeblock | |
| 128 | + nestCount++; | |
| 129 | + yield line; | |
| 130 | + } else { | |
| 131 | + // Otherwise just yield the line as content | |
| 132 | + yield line; | |
| 133 | + } | |
| 134 | + } | |
| 135 | + } | |
| 136 | +} | |
| 137 | + | |
| 138 | +function shouldRemoveLineBeforeStart(line: string): boolean { | |
| 139 | + return ( | |
| 140 | + line.trimStart().startsWith("```") || | |
| 141 | + line.trim() === "[CODE]" || | |
| 142 | + line.trim() === "<COMPLETION>" || | |
| 143 | + line.trim() === "<START EDITING HERE>" || | |
| 144 | + line.trim() === "{{FILL_HERE}}" | |
| 145 | + ); | |
| 146 | +} |
added core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts +452 −0
| @@ -0,0 +1,452 @@ | ||
| 1 | +// eslint-disable-next-line max-lines-per-function | |
| 2 | +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; | |
| 3 | + | |
| 4 | +import * as lineStream from "./lineStream"; | |
| 5 | + | |
| 6 | +describe("filterCodeBlock", () => { | |
| 7 | + let mockFullStop: Mock; | |
| 8 | + | |
| 9 | + async function getLineGenerator(lines: any) { | |
| 10 | + return (async function* () { | |
| 11 | + for (const line of lines) { | |
| 12 | + yield line; | |
| 13 | + } | |
| 14 | + })(); | |
| 15 | + } | |
| 16 | + | |
| 17 | + async function getFilteredLines(results: any) { | |
| 18 | + const output = []; | |
| 19 | + | |
| 20 | + for await (const line of results) { | |
| 21 | + output.push(line); | |
| 22 | + } | |
| 23 | + | |
| 24 | + return output; | |
| 25 | + } | |
| 26 | + | |
| 27 | + beforeEach(() => { | |
| 28 | + mockFullStop = vi.fn(); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + it("should handle unfenced code", async () => { | |
| 32 | + const linesGenerator = await getLineGenerator(["const x = 5;"]); | |
| 33 | + | |
| 34 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 35 | + const filteredLines = await getFilteredLines(result); | |
| 36 | + | |
| 37 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should handle unfenced code with a code block", async () => { | |
| 41 | + const linesGenerator = await getLineGenerator([ | |
| 42 | + "const x = 5;", | |
| 43 | + "```bash", | |
| 44 | + "ls -al", | |
| 45 | + "```", | |
| 46 | + ]); | |
| 47 | + | |
| 48 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 49 | + const filteredLines = await getFilteredLines(result); | |
| 50 | + | |
| 51 | + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); | |
| 52 | + }); | |
| 53 | + | |
| 54 | + it("should handle unfenced code with a complex code block", async () => { | |
| 55 | + const linesGenerator = await getLineGenerator([ | |
| 56 | + "# Manual Testing Sandbox", | |
| 57 | + "", | |
| 58 | + "## Project Structure", | |
| 59 | + "", | |
| 60 | + "```", | |
| 61 | + "manual-testing-sandbox/", | |
| 62 | + "├── readme.md # Project documentation", | |
| 63 | + "├── package.json # Node.js dependencies and scripts", | |
| 64 | + "├── tsconfig.json # TypeScript configuration", | |
| 65 | + "├── jest.config.js # Jest testing configuration", | |
| 66 | + "├── requirements.txt # Python dependencies", | |
| 67 | + "├── Dockerfile # Docker container configuration", | |
| 68 | + "├── data.json # Sample JSON data", | |
| 69 | + "├── example.ipynb # Jupyter notebook example", | |
| 70 | + "│", | |
| 71 | + "├── src/ # Source code directory", | |
| 72 | + "│ ├── example.ts # TypeScript example", | |
| 73 | + "│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter", | |
| 74 | + "│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter", | |
| 75 | + "│ ├── MarkdownProcessor.ts # Markdown processing utility", | |
| 76 | + "│ └── MarkdownProcessor.test.ts # Tests for Markdown processor", | |
| 77 | + "│", | |
| 78 | + "├── react-calculator/ # React calculator application", | |
| 79 | + "├── calculator_test/ # Java calculator implementation", | |
| 80 | + "│ ├── Calculator.java # Calculator class", | |
| 81 | + "│ └── Main.java # Main application entry", | |
| 82 | + "│", | |
| 83 | + "├── nested-folder/ # Nested project example", | |
| 84 | + "│ ├── helloNested.py # Python script", | |
| 85 | + "│ ├── package.json # Nested package configuration", | |
| 86 | + "│ └── rules.md # Documentation", | |
| 87 | + "│", | |
| 88 | + "├── coverage/ # Test coverage reports", | |
| 89 | + "├── logs/ # Application logs", | |
| 90 | + "│", | |
| 91 | + "└── Test Files # Various language examples", | |
| 92 | + " ├── AdvancedPage.tsx # React TypeScript component", | |
| 93 | + " ├── Calculator.java # Java calculator", | |
| 94 | + " ├── program.cs # C# program", | |
| 95 | + " ├── query.sql # SQL query example", | |
| 96 | + " ├── test.css # CSS styles", | |
| 97 | + " ├── test.html # HTML page", | |
| 98 | + " ├── test.js # JavaScript code", | |
| 99 | + " ├── test.kt # Kotlin example", | |
| 100 | + " ├── test.php # PHP script", | |
| 101 | + " ├── test.py # Python script", | |
| 102 | + " ├── test.rb # Ruby script", | |
| 103 | + " ├── test.rs # Rust code", | |
| 104 | + " ├── test.sh # Shell script", | |
| 105 | + " └── test.ts # TypeScript code", | |
| 106 | + "```", | |
| 107 | + ]); | |
| 108 | + | |
| 109 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 110 | + const filteredLines = await getFilteredLines(result); | |
| 111 | + | |
| 112 | + expect(filteredLines).toEqual([ | |
| 113 | + "# Manual Testing Sandbox", | |
| 114 | + "", | |
| 115 | + "## Project Structure", | |
| 116 | + "", | |
| 117 | + "```", | |
| 118 | + "manual-testing-sandbox/", | |
| 119 | + "├── readme.md # Project documentation", | |
| 120 | + "├── package.json # Node.js dependencies and scripts", | |
| 121 | + "├── tsconfig.json # TypeScript configuration", | |
| 122 | + "├── jest.config.js # Jest testing configuration", | |
| 123 | + "├── requirements.txt # Python dependencies", | |
| 124 | + "├── Dockerfile # Docker container configuration", | |
| 125 | + "├── data.json # Sample JSON data", | |
| 126 | + "├── example.ipynb # Jupyter notebook example", | |
| 127 | + "│", | |
| 128 | + "├── src/ # Source code directory", | |
| 129 | + "│ ├── example.ts # TypeScript example", | |
| 130 | + "│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter", | |
| 131 | + "│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter", | |
| 132 | + "│ ├── MarkdownProcessor.ts # Markdown processing utility", | |
| 133 | + "│ └── MarkdownProcessor.test.ts # Tests for Markdown processor", | |
| 134 | + "│", | |
| 135 | + "├── react-calculator/ # React calculator application", | |
| 136 | + "├── calculator_test/ # Java calculator implementation", | |
| 137 | + "│ ├── Calculator.java # Calculator class", | |
| 138 | + "│ └── Main.java # Main application entry", | |
| 139 | + "│", | |
| 140 | + "├── nested-folder/ # Nested project example", | |
| 141 | + "│ ├── helloNested.py # Python script", | |
| 142 | + "│ ├── package.json # Nested package configuration", | |
| 143 | + "│ └── rules.md # Documentation", | |
| 144 | + "│", | |
| 145 | + "├── coverage/ # Test coverage reports", | |
| 146 | + "├── logs/ # Application logs", | |
| 147 | + "│", | |
| 148 | + "└── Test Files # Various language examples", | |
| 149 | + " ├── AdvancedPage.tsx # React TypeScript component", | |
| 150 | + " ├── Calculator.java # Java calculator", | |
| 151 | + " ├── program.cs # C# program", | |
| 152 | + " ├── query.sql # SQL query example", | |
| 153 | + " ├── test.css # CSS styles", | |
| 154 | + " ├── test.html # HTML page", | |
| 155 | + " ├── test.js # JavaScript code", | |
| 156 | + " ├── test.kt # Kotlin example", | |
| 157 | + " ├── test.php # PHP script", | |
| 158 | + " ├── test.py # Python script", | |
| 159 | + " ├── test.rb # Ruby script", | |
| 160 | + " ├── test.rs # Rust code", | |
| 161 | + " ├── test.sh # Shell script", | |
| 162 | + " └── test.ts # TypeScript code", | |
| 163 | + "```", | |
| 164 | + ]); | |
| 165 | + }); | |
| 166 | + | |
| 167 | + it("should handle unfenced code with two code blocks", async () => { | |
| 168 | + const linesGenerator = await getLineGenerator([ | |
| 169 | + "const x = 5;", | |
| 170 | + "```bash", | |
| 171 | + "ls -al", | |
| 172 | + "```", | |
| 173 | + "```bash", | |
| 174 | + "ls -al", | |
| 175 | + "```", | |
| 176 | + ]); | |
| 177 | + | |
| 178 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 179 | + const filteredLines = await getFilteredLines(result); | |
| 180 | + | |
| 181 | + expect(filteredLines).toEqual([ | |
| 182 | + "const x = 5;", | |
| 183 | + "```bash", | |
| 184 | + "ls -al", | |
| 185 | + "```", | |
| 186 | + "```bash", | |
| 187 | + "ls -al", | |
| 188 | + "```", | |
| 189 | + ]); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + it("should remove lines before the first valid line", async () => { | |
| 193 | + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); | |
| 194 | + | |
| 195 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 196 | + const filteredLines = await getFilteredLines(result); | |
| 197 | + | |
| 198 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 199 | + }); | |
| 200 | + | |
| 201 | + it("should remove outer blocks", async () => { | |
| 202 | + const linesGenerator = await getLineGenerator([ | |
| 203 | + "```ts", | |
| 204 | + "const x = 5;", | |
| 205 | + "```", | |
| 206 | + ]); | |
| 207 | + | |
| 208 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 209 | + const filteredLines = await getFilteredLines(result); | |
| 210 | + | |
| 211 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 212 | + }); | |
| 213 | + | |
| 214 | + it("should leave inner blocks intact", async () => { | |
| 215 | + const linesGenerator = await getLineGenerator([ | |
| 216 | + "```md", | |
| 217 | + "const x = 5;", | |
| 218 | + "```bash", | |
| 219 | + "ls -al", | |
| 220 | + "```", | |
| 221 | + "```", | |
| 222 | + ]); | |
| 223 | + | |
| 224 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 225 | + const filteredLines = await getFilteredLines(result); | |
| 226 | + | |
| 227 | + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); | |
| 228 | + }); | |
| 229 | + | |
| 230 | + it("should ignore ticks inside of code blocks such as tests", async () => { | |
| 231 | + const linesGenerator = await getLineGenerator([ | |
| 232 | + "```typescript", | |
| 233 | + 'it("should handle included inner ticks", async () => {', | |
| 234 | + " const linesGenerator = await getLineGenerator([`", | |
| 235 | + ' "```md"', | |
| 236 | + ' "const x = 5;"', | |
| 237 | + ' "```bash"', | |
| 238 | + ' "echo ```test```"', | |
| 239 | + ' "```"', | |
| 240 | + ' "```"', | |
| 241 | + "]);", | |
| 242 | + "```", | |
| 243 | + ]); | |
| 244 | + | |
| 245 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 246 | + const filteredLines = await getFilteredLines(result); | |
| 247 | + | |
| 248 | + expect(filteredLines).toEqual([ | |
| 249 | + 'it("should handle included inner ticks", async () => {', | |
| 250 | + " const linesGenerator = await getLineGenerator([`", | |
| 251 | + ' "```md"', | |
| 252 | + ' "const x = 5;"', | |
| 253 | + ' "```bash"', | |
| 254 | + ' "echo ```test```"', | |
| 255 | + ' "```"', | |
| 256 | + ' "```"', | |
| 257 | + "]);", | |
| 258 | + ]); | |
| 259 | + }); | |
| 260 | + | |
| 261 | + it("should handle included inner ticks", async () => { | |
| 262 | + const linesGenerator = await getLineGenerator([ | |
| 263 | + "```md", | |
| 264 | + "const x = 5;", | |
| 265 | + "```bash", | |
| 266 | + "echo ```test```", | |
| 267 | + "```", | |
| 268 | + "```", | |
| 269 | + ]); | |
| 270 | + | |
| 271 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 272 | + const filteredLines = await getFilteredLines(result); | |
| 273 | + | |
| 274 | + expect(filteredLines).toEqual([ | |
| 275 | + "const x = 5;", | |
| 276 | + "```bash", | |
| 277 | + "echo ```test```", | |
| 278 | + "```", | |
| 279 | + ]); | |
| 280 | + }); | |
| 281 | + | |
| 282 | + it("should leave single inner blocks intact but not return trailing text", async () => { | |
| 283 | + const linesGenerator = await getLineGenerator([ | |
| 284 | + "```md", | |
| 285 | + "const x = 5;", | |
| 286 | + "```bash", | |
| 287 | + "ls -al", | |
| 288 | + "```", | |
| 289 | + "```", | |
| 290 | + "trailing text", | |
| 291 | + ]); | |
| 292 | + | |
| 293 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 294 | + const filteredLines = await getFilteredLines(result); | |
| 295 | + | |
| 296 | + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); | |
| 297 | + }); | |
| 298 | + | |
| 299 | + it("should leave double inner blocks intact but not return trailing text", async () => { | |
| 300 | + const linesGenerator = await getLineGenerator([ | |
| 301 | + "```md", | |
| 302 | + "const x = 5;", | |
| 303 | + "```bash", | |
| 304 | + "ls -al", | |
| 305 | + "```", | |
| 306 | + "const y = 10;", | |
| 307 | + "```sh", | |
| 308 | + "echo `hello world`", | |
| 309 | + "```", | |
| 310 | + "```", | |
| 311 | + "trailing text", | |
| 312 | + ]); | |
| 313 | + | |
| 314 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 315 | + const filteredLines = await getFilteredLines(result); | |
| 316 | + | |
| 317 | + expect(filteredLines).toEqual([ | |
| 318 | + "const x = 5;", | |
| 319 | + "```bash", | |
| 320 | + "ls -al", | |
| 321 | + "```", | |
| 322 | + "const y = 10;", | |
| 323 | + "```sh", | |
| 324 | + "echo `hello world`", | |
| 325 | + "```", | |
| 326 | + ]); | |
| 327 | + }); | |
| 328 | + | |
| 329 | + it("should leave inner blocks intact but not return trailing or leading text", async () => { | |
| 330 | + const linesGenerator = await getLineGenerator([ | |
| 331 | + "[CODE]", | |
| 332 | + "const x = 5;", | |
| 333 | + "```bash", | |
| 334 | + "ls -al", | |
| 335 | + "```", | |
| 336 | + "[/CODE]", | |
| 337 | + "trailing text", | |
| 338 | + ]); | |
| 339 | + | |
| 340 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 341 | + const filteredLines = await getFilteredLines(result); | |
| 342 | + | |
| 343 | + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); | |
| 344 | + }); | |
| 345 | + | |
| 346 | + // Markdown-aware tests | |
| 347 | + it("should handle markdown files with nested code blocks and a filename is included", async () => { | |
| 348 | + const linesGenerator = await getLineGenerator([ | |
| 349 | + "```markdown README.md", | |
| 350 | + "# Project Structure", | |
| 351 | + "", | |
| 352 | + "```", | |
| 353 | + "debug-test-folder/", | |
| 354 | + "├── AdvancedPage.tsx", | |
| 355 | + "├── Calculator.java", | |
| 356 | + "└── test.ts", | |
| 357 | + "```", | |
| 358 | + "```", | |
| 359 | + ]); | |
| 360 | + | |
| 361 | + const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md"); | |
| 362 | + const filteredLines = await getFilteredLines(result); | |
| 363 | + | |
| 364 | + // Should include all content up to the final closing ``` | |
| 365 | + expect(filteredLines).toEqual([ | |
| 366 | + "# Project Structure", | |
| 367 | + "", | |
| 368 | + "```", | |
| 369 | + "debug-test-folder/", | |
| 370 | + "├── AdvancedPage.tsx", | |
| 371 | + "├── Calculator.java", | |
| 372 | + "└── test.ts", | |
| 373 | + "```", | |
| 374 | + ]); | |
| 375 | + }); | |
| 376 | + | |
| 377 | + // Markdown-aware tests | |
| 378 | + it("should handle markdown files with nested code blocks and a filename is excluded", async () => { | |
| 379 | + const linesGenerator = await getLineGenerator([ | |
| 380 | + "```markdown README.md", | |
| 381 | + "# Project Structure", | |
| 382 | + "", | |
| 383 | + "```", | |
| 384 | + "debug-test-folder/", | |
| 385 | + "├── AdvancedPage.tsx", | |
| 386 | + "├── Calculator.java", | |
| 387 | + "└── test.ts", | |
| 388 | + "```", | |
| 389 | + "```", | |
| 390 | + ]); | |
| 391 | + | |
| 392 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 393 | + const filteredLines = await getFilteredLines(result); | |
| 394 | + | |
| 395 | + // Should include all content up to the final closing ``` | |
| 396 | + expect(filteredLines).toEqual([ | |
| 397 | + "# Project Structure", | |
| 398 | + "", | |
| 399 | + "```", | |
| 400 | + "debug-test-folder/", | |
| 401 | + "├── AdvancedPage.tsx", | |
| 402 | + "├── Calculator.java", | |
| 403 | + "└── test.ts", | |
| 404 | + "```", | |
| 405 | + ]); | |
| 406 | + }); | |
| 407 | + | |
| 408 | + it("should handle non-markdown files normally with filepath parameter", async () => { | |
| 409 | + const linesGenerator = await getLineGenerator([ | |
| 410 | + "```", | |
| 411 | + "function test() {", | |
| 412 | + " return 'hello';", | |
| 413 | + "}", | |
| 414 | + "```", | |
| 415 | + ]); | |
| 416 | + | |
| 417 | + const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js"); | |
| 418 | + const filteredLines = await getFilteredLines(result); | |
| 419 | + | |
| 420 | + expect(filteredLines).toEqual([ | |
| 421 | + "function test() {", | |
| 422 | + " return 'hello';", | |
| 423 | + "}", | |
| 424 | + ]); | |
| 425 | + }); | |
| 426 | + | |
| 427 | + it("should handle simple markdown code blocks", async () => { | |
| 428 | + const linesGenerator = await getLineGenerator([ | |
| 429 | + "```", | |
| 430 | + "Here's some code:", | |
| 431 | + "```", | |
| 432 | + "function example() {", | |
| 433 | + " console.log('test');", | |
| 434 | + "}", | |
| 435 | + "```", | |
| 436 | + ]); | |
| 437 | + | |
| 438 | + const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md"); | |
| 439 | + const filteredLines = await getFilteredLines(result); | |
| 440 | + | |
| 441 | + // Should remove the outer markdown wrapper, and return just the inner content. | |
| 442 | + // The lack of an end tag should cause it to return all remaining lines. | |
| 443 | + expect(filteredLines).toEqual([ | |
| 444 | + "Here's some code:", | |
| 445 | + "```", | |
| 446 | + "function example() {", | |
| 447 | + " console.log('test');", | |
| 448 | + "}", | |
| 449 | + "```", | |
| 450 | + ]); | |
| 451 | + }); | |
| 452 | +}); |
modified core/autocomplete/filtering/streamTransforms/lineStream.ts +127 −62
| @@ -3,6 +3,11 @@ | ||
| 3 | 3 | import { DiffLine } from "../../.."; |
| 4 | 4 | import { LineStream } from "../../../diff/util"; |
| 5 | 5 | |
| 6 | +import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils"; | |
| 7 | +import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils"; | |
| 8 | + | |
| 9 | +export { filterCodeBlockLines } from "./filterCodeBlock"; | |
| 10 | + | |
| 6 | 11 | export type LineFilter = (args: { |
| 7 | 12 | lines: LineStream; |
| 8 | 13 | fullStop: () => void; |
| @@ -50,13 +55,72 @@ | ||
| 50 | 55 | ); |
| 51 | 56 | } |
| 52 | 57 | |
| 53 | -function shouldChangeLineAndStop(line: string): string | undefined { | |
| 58 | +/** | |
| 59 | + * Shared utility for validating patterns in lines to avoid code duplication. | |
| 60 | + * Checks if a pattern appears in a valid context (not inside quotes or identifiers). | |
| 61 | + */ | |
| 62 | +export function validatePatternInLine( | |
| 63 | + line: string, | |
| 64 | + pattern: string, | |
| 65 | +): { | |
| 66 | + isValid: boolean; | |
| 67 | + patternIndex: number; | |
| 68 | + beforePattern: string; | |
| 69 | +} { | |
| 70 | + const patternIndex = line.indexOf(pattern); | |
| 71 | + | |
| 72 | + if (patternIndex === -1) { | |
| 73 | + return { isValid: false, patternIndex: -1, beforePattern: "" }; | |
| 74 | + } | |
| 75 | + | |
| 76 | + // Check if pattern is preceded by a non-whitespace character | |
| 77 | + // If so, it might be part of an identifier, so don't handle it | |
| 78 | + if (patternIndex > 0) { | |
| 79 | + const charBefore = line[patternIndex - 1]; | |
| 80 | + if (charBefore && !charBefore.match(/\s/)) { | |
| 81 | + return { isValid: false, patternIndex, beforePattern: "" }; | |
| 82 | + } | |
| 83 | + } | |
| 84 | + | |
| 85 | + // Check if pattern appears to be inside quotes | |
| 86 | + // Simple heuristic: count unmatched quotes before the pattern | |
| 87 | + const beforePattern = line.substring(0, patternIndex); | |
| 88 | + const singleQuotes = (beforePattern.match(/'/g) || []).length; | |
| 89 | + const doubleQuotes = (beforePattern.match(/"/g) || []).length; | |
| 90 | + | |
| 91 | + // If there's an odd number of quotes before pattern, we're likely inside quotes | |
| 92 | + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { | |
| 93 | + return { isValid: false, patternIndex, beforePattern }; | |
| 94 | + } | |
| 95 | + | |
| 96 | + return { isValid: true, patternIndex, beforePattern }; | |
| 97 | +} | |
| 98 | + | |
| 99 | +export function shouldChangeLineAndStop(line: string): string | undefined { | |
| 54 | 100 | if (line.trimStart() === "```") { |
| 55 | 101 | return line; |
| 56 | 102 | } |
| 57 | 103 | |
| 104 | + // Check if [/CODE] appears in the line | |
| 58 | 105 | if (line.includes(CODE_STOP_BLOCK)) { |
| 59 | - return line.split(CODE_STOP_BLOCK)[0].trimEnd(); | |
| 106 | + const validation = validatePatternInLine(line, CODE_STOP_BLOCK); | |
| 107 | + | |
| 108 | + if (!validation.isValid) { | |
| 109 | + return undefined; | |
| 110 | + } | |
| 111 | + | |
| 112 | + // Get the trimmed line to check if [/CODE] is at logical start | |
| 113 | + const trimmedLine = line.trimStart(); | |
| 114 | + | |
| 115 | + if (trimmedLine.startsWith(CODE_STOP_BLOCK)) { | |
| 116 | + // [/CODE] is at the logical start (after whitespace only) | |
| 117 | + if (trimmedLine === CODE_STOP_BLOCK) { | |
| 118 | + return line; // Return the whole line including leading whitespace | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + // [/CODE] appears after some content (separated by whitespace) - return part before | |
| 123 | + return validation.beforePattern.trimEnd(); | |
| 60 | 124 | } |
| 61 | 125 | |
| 62 | 126 | return undefined; |
| @@ -71,6 +135,32 @@ | ||
| 71 | 135 | return hasUselessLine || trimmed.startsWith("// end"); |
| 72 | 136 | } |
| 73 | 137 | |
| 138 | +/** | |
| 139 | + * Determines if the code block has nested markdown blocks. | |
| 140 | + */ | |
| 141 | +export function hasNestedMarkdownBlocks( | |
| 142 | + firstLine: string, | |
| 143 | + filepath?: string, | |
| 144 | +): boolean { | |
| 145 | + return ( | |
| 146 | + (firstLine.startsWith("```") && | |
| 147 | + headerIsMarkdown(firstLine.replace(/`/g, ""))) || | |
| 148 | + Boolean(filepath && isMarkdownFile(filepath)) | |
| 149 | + ); | |
| 150 | +} | |
| 151 | + | |
| 152 | +// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function | |
| 153 | +export function processBlockNesting( | |
| 154 | + line: string, | |
| 155 | + seenFirstFence: boolean, | |
| 156 | +): { newSeenFirstFence: boolean; shouldSkip: boolean } { | |
| 157 | + return processBlockNestingUtil( | |
| 158 | + line, | |
| 159 | + seenFirstFence, | |
| 160 | + shouldRemoveLineBeforeStart, | |
| 161 | + ); | |
| 162 | +} | |
| 163 | + | |
| 74 | 164 | export const USELESS_LINES = [""]; |
| 75 | 165 | export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; |
| 76 | 166 | export const CODE_STOP_BLOCK = "[/CODE]"; |
| @@ -138,7 +228,7 @@ | ||
| 138 | 228 | // Sometimes the model with copy this pattern, which is unwanted |
| 139 | 229 | for await (const line of stream) { |
| 140 | 230 | if (line.startsWith(`${comment} Path: `)) { |
| 141 | - continue; | |
| 231 | + continue; // continue in the Continue codebase! How meta! | |
| 142 | 232 | } |
| 143 | 233 | yield line; |
| 144 | 234 | } |
| @@ -261,7 +351,40 @@ | ||
| 261 | 351 | linesToStopAt: string[] = LINES_TO_STOP_AT, |
| 262 | 352 | ): LineStream { |
| 263 | 353 | for await (const line of stream) { |
| 264 | - if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) { | |
| 354 | + let shouldStop = false; | |
| 355 | + | |
| 356 | + // Check each stop phrase | |
| 357 | + for (const stopAt of linesToStopAt) { | |
| 358 | + if (line.includes(stopAt)) { | |
| 359 | + const validation = validatePatternInLine(line, stopAt); | |
| 360 | + | |
| 361 | + if (!validation.isValid) { | |
| 362 | + continue; | |
| 363 | + } | |
| 364 | + | |
| 365 | + // Get the trimmed line to check if stop phrase is at logical start | |
| 366 | + const trimmedLine = line.trimStart(); | |
| 367 | + | |
| 368 | + if (trimmedLine.startsWith(stopAt)) { | |
| 369 | + // Stop phrase is at the logical start (after whitespace only) - should stop | |
| 370 | + shouldStop = true; | |
| 371 | + break; | |
| 372 | + } else { | |
| 373 | + // Stop phrase appears after some content - check if it's separated by whitespace | |
| 374 | + const contentBeforeStopPhrase = validation.beforePattern.trimEnd(); | |
| 375 | + if ( | |
| 376 | + contentBeforeStopPhrase.length < validation.beforePattern.length | |
| 377 | + ) { | |
| 378 | + // There's whitespace before the stop phrase, so it's properly separated | |
| 379 | + shouldStop = true; | |
| 380 | + break; | |
| 381 | + } | |
| 382 | + // If no whitespace separation, it's part of larger text, so continue | |
| 383 | + } | |
| 384 | + } | |
| 385 | + } | |
| 386 | + | |
| 387 | + if (shouldStop) { | |
| 265 | 388 | fullStop(); |
| 266 | 389 | break; |
| 267 | 390 | } |
| @@ -329,64 +452,6 @@ | ||
| 329 | 452 | } |
| 330 | 453 | } |
| 331 | 454 | |
| 332 | -/** | |
| 333 | - * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. | |
| 334 | - * | |
| 335 | - * @param {LineStream} rawLines - The input stream of lines to filter. | |
| 336 | - * @yields {string} Filtered and processed lines from the code block. | |
| 337 | - * | |
| 338 | - * @description | |
| 339 | - * This generator function performs the following tasks: | |
| 340 | - * 1. Removes initial lines that should be removed before the actual code starts. | |
| 341 | - * 2. Filters out ending code block markers (```) unless they are the last line. | |
| 342 | - * 3. Handles special cases where lines should be changed and the stream should stop. | |
| 343 | - * 4. Yields processed lines that are part of the actual code block content. | |
| 344 | - */ | |
| 345 | -export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { | |
| 346 | - let seenFirstFence = false; | |
| 347 | - // nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented | |
| 348 | - // when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early | |
| 349 | - // when all blocks are matched. When no outer fence is discovered the function will always continue to the end. | |
| 350 | - let nestCount = 0; | |
| 351 | - | |
| 352 | - for await (const line of rawLines) { | |
| 353 | - if (!seenFirstFence) { | |
| 354 | - if (shouldRemoveLineBeforeStart(line)) { | |
| 355 | - // Filter out starting ``` or START block | |
| 356 | - continue; | |
| 357 | - } | |
| 358 | - // Regardless of a fence or START block start tracking the nesting level | |
| 359 | - seenFirstFence = true; | |
| 360 | - nestCount = 1; | |
| 361 | - } | |
| 362 | - | |
| 363 | - if (nestCount > 0) { | |
| 364 | - // Inside a block including the outer block | |
| 365 | - const changedEndLine = shouldChangeLineAndStop(line); | |
| 366 | - if (typeof changedEndLine === "string") { | |
| 367 | - // Ending a block with just backticks (```) or STOP | |
| 368 | - nestCount--; | |
| 369 | - if (nestCount === 0) { | |
| 370 | - // if we are closing the outer block then exit early | |
| 371 | - // only exit early if the outer block was started with a block | |
| 372 | - // it it was text, we will never exit early | |
| 373 | - return; | |
| 374 | - } else { | |
| 375 | - // otherwise just yield the line | |
| 376 | - yield line; | |
| 377 | - } | |
| 378 | - } else if (line.startsWith("```")) { | |
| 379 | - // Going into a nested codeblock | |
| 380 | - nestCount++; | |
| 381 | - yield line; | |
| 382 | - } else { | |
| 383 | - // otherwise just yield the line | |
| 384 | - yield line; | |
| 385 | - } | |
| 386 | - } | |
| 387 | - } | |
| 388 | -} | |
| 389 | - | |
| 390 | 455 | /** |
| 391 | 456 | * Filters out English explanations at the start of a code block. |
| 392 | 457 | * |
modified core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +685 −0
| @@ -1,5 +1,10 @@ | ||
| 1 | 1 | import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; |
| 2 | 2 | |
| 3 | +import { | |
| 4 | + collectAllLines, | |
| 5 | + MarkdownBlockStateTracker, | |
| 6 | +} from "../../../utils/markdownUtils"; | |
| 7 | +import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils"; | |
| 3 | 8 | import * as lineStream from "./lineStream"; |
| 4 | 9 | |
| 5 | 10 | // eslint-disable-next-line max-lines-per-function |
| @@ -174,6 +179,93 @@ | ||
| 174 | 179 | expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); |
| 175 | 180 | expect(mockFullStop).toHaveBeenCalledTimes(1); |
| 176 | 181 | }); |
| 182 | + | |
| 183 | + it("should stop at lines with leading whitespace", async () => { | |
| 184 | + const linesGenerator = await getLineGenerator([ | |
| 185 | + "const x = 5;", | |
| 186 | + "let y = 10;", | |
| 187 | + ` ${lineStream.LINES_TO_STOP_AT[0]}`, | |
| 188 | + "const z = 15;", | |
| 189 | + ]); | |
| 190 | + | |
| 191 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 192 | + const filteredLines = await getFilteredLines(result); | |
| 193 | + | |
| 194 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 195 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + it("should NOT stop when stop phrase is inside quotes", async () => { | |
| 199 | + const linesGenerator = await getLineGenerator([ | |
| 200 | + "const x = 5;", | |
| 201 | + 'console.log("# End of file. not really");', | |
| 202 | + "let y = 10;", | |
| 203 | + "const z = 15;", | |
| 204 | + ]); | |
| 205 | + | |
| 206 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 207 | + const filteredLines = await getFilteredLines(result); | |
| 208 | + | |
| 209 | + // Should not stop, should yield all lines | |
| 210 | + expect(filteredLines).toEqual([ | |
| 211 | + "const x = 5;", | |
| 212 | + 'console.log("# End of file. not really");', | |
| 213 | + "let y = 10;", | |
| 214 | + "const z = 15;", | |
| 215 | + ]); | |
| 216 | + expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 217 | + }); | |
| 218 | + | |
| 219 | + it("should NOT stop when stop phrase is inside single quotes", async () => { | |
| 220 | + const linesGenerator = await getLineGenerator([ | |
| 221 | + "const x = 5;", | |
| 222 | + "const message = '# End of file. not really';", | |
| 223 | + "let y = 10;", | |
| 224 | + ]); | |
| 225 | + | |
| 226 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 227 | + const filteredLines = await getFilteredLines(result); | |
| 228 | + | |
| 229 | + expect(filteredLines).toEqual([ | |
| 230 | + "const x = 5;", | |
| 231 | + "const message = '# End of file. not really';", | |
| 232 | + "let y = 10;", | |
| 233 | + ]); | |
| 234 | + expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 235 | + }); | |
| 236 | + | |
| 237 | + it("should NOT stop when stop phrase is part of larger text", async () => { | |
| 238 | + const linesGenerator = await getLineGenerator([ | |
| 239 | + "const x = 5;", | |
| 240 | + "// This function stops<STOP EDITING HERE>after processing", | |
| 241 | + "let y = 10;", | |
| 242 | + ]); | |
| 243 | + | |
| 244 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 245 | + const filteredLines = await getFilteredLines(result); | |
| 246 | + | |
| 247 | + expect(filteredLines).toEqual([ | |
| 248 | + "const x = 5;", | |
| 249 | + "// This function stops<STOP EDITING HERE>after processing", | |
| 250 | + "let y = 10;", | |
| 251 | + ]); | |
| 252 | + expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + it("should stop when stop phrase appears properly at start of content", async () => { | |
| 256 | + const linesGenerator = await getLineGenerator([ | |
| 257 | + "const x = 5;", | |
| 258 | + "let y = 10;", | |
| 259 | + "# End of file. Done here", | |
| 260 | + "const z = 15;", | |
| 261 | + ]); | |
| 262 | + | |
| 263 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 264 | + const filteredLines = await getFilteredLines(result); | |
| 265 | + | |
| 266 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 267 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 268 | + }); | |
| 177 | 269 | }); |
| 178 | 270 | |
| 179 | 271 | describe("skipPrefixes", () => { |
| @@ -301,6 +393,37 @@ | ||
| 301 | 393 | ]); |
| 302 | 394 | }); |
| 303 | 395 | |
| 396 | + it("should ignore ticks inside of code blocks such as tests", async () => { | |
| 397 | + const linesGenerator = await getLineGenerator([ | |
| 398 | + "```typescript", | |
| 399 | + 'it("should handle included inner ticks", async () => {', | |
| 400 | + " const linesGenerator = await getLineGenerator([`", | |
| 401 | + ' "```md"', | |
| 402 | + ' "const x = 5;"', | |
| 403 | + ' "```bash"', | |
| 404 | + ' "echo ```test```"', | |
| 405 | + ' "```"', | |
| 406 | + ' "```"', | |
| 407 | + "]);", | |
| 408 | + "```", | |
| 409 | + ]); | |
| 410 | + | |
| 411 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 412 | + const filteredLines = await getFilteredLines(result); | |
| 413 | + | |
| 414 | + expect(filteredLines).toEqual([ | |
| 415 | + 'it("should handle included inner ticks", async () => {', | |
| 416 | + " const linesGenerator = await getLineGenerator([`", | |
| 417 | + ' "```md"', | |
| 418 | + ' "const x = 5;"', | |
| 419 | + ' "```bash"', | |
| 420 | + ' "echo ```test```"', | |
| 421 | + ' "```"', | |
| 422 | + ' "```"', | |
| 423 | + "]);", | |
| 424 | + ]); | |
| 425 | + }); | |
| 426 | + | |
| 304 | 427 | it("should handle included inner ticks", async () => { |
| 305 | 428 | const linesGenerator = await getLineGenerator([ |
| 306 | 429 | "```md", |
| @@ -395,6 +518,119 @@ | ||
| 395 | 518 | "```", |
| 396 | 519 | ]); |
| 397 | 520 | }); |
| 521 | + | |
| 522 | + // Markdown-aware tests | |
| 523 | + it("should handle markdown files with nested code blocks and a filename is included", async () => { | |
| 524 | + const linesGenerator = await getLineGenerator([ | |
| 525 | + "```markdown README.md", | |
| 526 | + "# Project Structure", | |
| 527 | + "", | |
| 528 | + "```", | |
| 529 | + "debug-test-folder/", | |
| 530 | + "├── AdvancedPage.tsx", | |
| 531 | + "├── Calculator.java", | |
| 532 | + "└── test.ts", | |
| 533 | + "```", | |
| 534 | + "```", | |
| 535 | + ]); | |
| 536 | + | |
| 537 | + const result = lineStream.filterCodeBlockLines( | |
| 538 | + linesGenerator, | |
| 539 | + "README.md", | |
| 540 | + ); | |
| 541 | + const filteredLines = await getFilteredLines(result); | |
| 542 | + | |
| 543 | + // Should include all content up to the final closing ``` | |
| 544 | + expect(filteredLines).toEqual([ | |
| 545 | + "# Project Structure", | |
| 546 | + "", | |
| 547 | + "```", | |
| 548 | + "debug-test-folder/", | |
| 549 | + "├── AdvancedPage.tsx", | |
| 550 | + "├── Calculator.java", | |
| 551 | + "└── test.ts", | |
| 552 | + "```", | |
| 553 | + ]); | |
| 554 | + }); | |
| 555 | + | |
| 556 | + // Markdown-aware tests | |
| 557 | + it("should handle markdown files with nested code blocks and a filename is excluded", async () => { | |
| 558 | + const linesGenerator = await getLineGenerator([ | |
| 559 | + "```markdown README.md", | |
| 560 | + "# Project Structure", | |
| 561 | + "", | |
| 562 | + "```", | |
| 563 | + "debug-test-folder/", | |
| 564 | + "├── AdvancedPage.tsx", | |
| 565 | + "├── Calculator.java", | |
| 566 | + "└── test.ts", | |
| 567 | + "```", | |
| 568 | + "```", | |
| 569 | + ]); | |
| 570 | + | |
| 571 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 572 | + const filteredLines = await getFilteredLines(result); | |
| 573 | + | |
| 574 | + // Should include all content up to the final closing ``` | |
| 575 | + expect(filteredLines).toEqual([ | |
| 576 | + "# Project Structure", | |
| 577 | + "", | |
| 578 | + "```", | |
| 579 | + "debug-test-folder/", | |
| 580 | + "├── AdvancedPage.tsx", | |
| 581 | + "├── Calculator.java", | |
| 582 | + "└── test.ts", | |
| 583 | + "```", | |
| 584 | + ]); | |
| 585 | + }); | |
| 586 | + | |
| 587 | + it("should handle non-markdown files normally with filepath parameter", async () => { | |
| 588 | + const linesGenerator = await getLineGenerator([ | |
| 589 | + "```", | |
| 590 | + "function test() {", | |
| 591 | + " return 'hello';", | |
| 592 | + "}", | |
| 593 | + "```", | |
| 594 | + ]); | |
| 595 | + | |
| 596 | + const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js"); | |
| 597 | + const filteredLines = await getFilteredLines(result); | |
| 598 | + | |
| 599 | + expect(filteredLines).toEqual([ | |
| 600 | + "function test() {", | |
| 601 | + " return 'hello';", | |
| 602 | + "}", | |
| 603 | + ]); | |
| 604 | + }); | |
| 605 | + | |
| 606 | + it("should handle simple markdown code blocks", async () => { | |
| 607 | + const linesGenerator = await getLineGenerator([ | |
| 608 | + "```", | |
| 609 | + "Here's some code:", | |
| 610 | + "```", | |
| 611 | + "function example() {", | |
| 612 | + " console.log('test');", | |
| 613 | + "}", | |
| 614 | + "```", | |
| 615 | + ]); | |
| 616 | + | |
| 617 | + const result = lineStream.filterCodeBlockLines( | |
| 618 | + linesGenerator, | |
| 619 | + "README.md", | |
| 620 | + ); | |
| 621 | + const filteredLines = await getFilteredLines(result); | |
| 622 | + | |
| 623 | + // Should remove the outer markdown wrapper, and return just the inner content. | |
| 624 | + // The lack of an end tag should cause it to return all remaining lines. | |
| 625 | + expect(filteredLines).toEqual([ | |
| 626 | + "Here's some code:", | |
| 627 | + "```", | |
| 628 | + "function example() {", | |
| 629 | + " console.log('test');", | |
| 630 | + "}", | |
| 631 | + "```", | |
| 632 | + ]); | |
| 633 | + }); | |
| 398 | 634 | }); |
| 399 | 635 | |
| 400 | 636 | describe("filterEnglishLinesAtStart", () => { |
| @@ -613,4 +849,453 @@ | ||
| 613 | 849 | expect(mockFullStop).toHaveBeenCalledTimes(1); |
| 614 | 850 | }); |
| 615 | 851 | }); |
| 852 | + | |
| 853 | + // Tests for new helper functions | |
| 854 | + | |
| 855 | + describe("hasNestedMarkdownBlocks", () => { | |
| 856 | + it("should detect nested markdown blocks from first line", () => { | |
| 857 | + expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe( | |
| 858 | + true, | |
| 859 | + ); | |
| 860 | + expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true); | |
| 861 | + expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe( | |
| 862 | + true, | |
| 863 | + ); | |
| 864 | + }); | |
| 865 | + | |
| 866 | + it("should detect nested markdown blocks from filepath", () => { | |
| 867 | + expect( | |
| 868 | + lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"), | |
| 869 | + ).toBe(true); | |
| 870 | + expect( | |
| 871 | + lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"), | |
| 872 | + ).toBe(true); | |
| 873 | + }); | |
| 874 | + | |
| 875 | + it("should return false for non-markdown scenarios", () => { | |
| 876 | + expect( | |
| 877 | + lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"), | |
| 878 | + ).toBe(false); | |
| 879 | + expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe( | |
| 880 | + false, | |
| 881 | + ); | |
| 882 | + expect( | |
| 883 | + lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined), | |
| 884 | + ).toBe(false); | |
| 885 | + }); | |
| 886 | + | |
| 887 | + it("should handle complex first line scenarios", () => { | |
| 888 | + expect( | |
| 889 | + lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined), | |
| 890 | + ).toBe(true); | |
| 891 | + expect( | |
| 892 | + lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined), | |
| 893 | + ).toBe(true); | |
| 894 | + }); | |
| 895 | + }); | |
| 896 | + | |
| 897 | + describe("collectAllLines", () => { | |
| 898 | + it("should collect all lines from a stream", async () => { | |
| 899 | + const linesGenerator = await getLineGenerator([ | |
| 900 | + "line1", | |
| 901 | + "line2", | |
| 902 | + "line3", | |
| 903 | + ]); | |
| 904 | + | |
| 905 | + const result = await collectAllLines(linesGenerator); | |
| 906 | + | |
| 907 | + expect(result).toEqual(["line1", "line2", "line3"]); | |
| 908 | + }); | |
| 909 | + | |
| 910 | + it("should handle empty stream", async () => { | |
| 911 | + const linesGenerator = await getLineGenerator([]); | |
| 912 | + | |
| 913 | + const result = await collectAllLines(linesGenerator); | |
| 914 | + | |
| 915 | + expect(result).toEqual([]); | |
| 916 | + }); | |
| 917 | + | |
| 918 | + it("should handle stream with empty lines", async () => { | |
| 919 | + const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]); | |
| 920 | + | |
| 921 | + const result = await collectAllLines(linesGenerator); | |
| 922 | + | |
| 923 | + expect(result).toEqual(["", "line2", "", "line4"]); | |
| 924 | + }); | |
| 925 | + }); | |
| 926 | + | |
| 927 | + describe("shouldStopAtMarkdownBlock", () => { | |
| 928 | + it("should return false when current line is not closing backticks", () => { | |
| 929 | + const allLines = ["```markdown", "content", "more content"]; | |
| 930 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 931 | + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false); | |
| 932 | + }); | |
| 933 | + | |
| 934 | + it("should handle simple nested markdown case", () => { | |
| 935 | + const allLines = ["```markdown", "# Title", "```"]; | |
| 936 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 937 | + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true); | |
| 938 | + }); | |
| 939 | + | |
| 940 | + it("should handle complex nested markdown with inner code blocks", () => { | |
| 941 | + const allLines = [ | |
| 942 | + "```markdown", | |
| 943 | + "# Title", | |
| 944 | + "```javascript", | |
| 945 | + "console.log('hello');", | |
| 946 | + "```", | |
| 947 | + "```", | |
| 948 | + ]; | |
| 949 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 950 | + // At index 4 (first inner closing), should not stop | |
| 951 | + expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false); | |
| 952 | + // At index 5 (outer closing), should stop | |
| 953 | + expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true); | |
| 954 | + }); | |
| 955 | + | |
| 956 | + it("should handle multiple bare backticks scenario", () => { | |
| 957 | + const allLines = [ | |
| 958 | + "```markdown", | |
| 959 | + "Content with ```inline code```", | |
| 960 | + "```", | |
| 961 | + "More content", | |
| 962 | + "```", | |
| 963 | + ]; | |
| 964 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 965 | + // At index 2, should not stop (not the last bare backticks) | |
| 966 | + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false); | |
| 967 | + // At index 4, should stop (last bare backticks) | |
| 968 | + expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true); | |
| 969 | + }); | |
| 970 | + }); | |
| 971 | + | |
| 972 | + describe("shouldChangeLineAndStop", () => { | |
| 973 | + it("should handle [/CODE] at start of line", () => { | |
| 974 | + const result = lineStream.shouldChangeLineAndStop("[/CODE]"); | |
| 975 | + expect(result).toBe("[/CODE]"); | |
| 976 | + }); | |
| 977 | + | |
| 978 | + it("should handle [/CODE] with leading whitespace", () => { | |
| 979 | + const result = lineStream.shouldChangeLineAndStop(" [/CODE]"); | |
| 980 | + expect(result).toBe(" [/CODE]"); | |
| 981 | + }); | |
| 982 | + | |
| 983 | + it("should return partial line before [/CODE] when at start/after whitespace", () => { | |
| 984 | + const result = lineStream.shouldChangeLineAndStop( | |
| 985 | + "some code [/CODE] more text", | |
| 986 | + ); | |
| 987 | + expect(result).toBe("some code"); | |
| 988 | + }); | |
| 989 | + | |
| 990 | + it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => { | |
| 991 | + // This test demonstrates the current bug - it WILL fail initially | |
| 992 | + const result = lineStream.shouldChangeLineAndStop( | |
| 993 | + 'console.log("test [/CODE] end");', | |
| 994 | + ); | |
| 995 | + expect(result).toBeUndefined(); // Should not trigger stopping | |
| 996 | + }); | |
| 997 | + | |
| 998 | + it("should NOT trigger on [/CODE] in middle of identifier", () => { | |
| 999 | + // Another case that shows the bug | |
| 1000 | + const result = lineStream.shouldChangeLineAndStop( | |
| 1001 | + 'const var[/CODE]Name = "test";', | |
| 1002 | + ); | |
| 1003 | + expect(result).toBeUndefined(); // Should not trigger stopping | |
| 1004 | + }); | |
| 1005 | + | |
| 1006 | + it("should handle ``` with trimStart correctly", () => { | |
| 1007 | + const result = lineStream.shouldChangeLineAndStop(" ```"); | |
| 1008 | + expect(result).toBe(" ```"); | |
| 1009 | + }); | |
| 1010 | + | |
| 1011 | + it("should NOT handle ``` in middle of line", () => { | |
| 1012 | + const result = lineStream.shouldChangeLineAndStop( | |
| 1013 | + 'console.log("test ``` end");', | |
| 1014 | + ); | |
| 1015 | + expect(result).toBeUndefined(); | |
| 1016 | + }); | |
| 1017 | + }); | |
| 1018 | + | |
| 1019 | + describe("MarkdownBlockState", () => { | |
| 1020 | + it("should initialize with correct state", () => { | |
| 1021 | + const allLines = ["```markdown", "content", "```", "more content", "```"]; | |
| 1022 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1023 | + | |
| 1024 | + // Test basic initialization - we can't directly test private properties, | |
| 1025 | + // but we can test the behavior through shouldStopAtPosition | |
| 1026 | + expect(state).toBeDefined(); | |
| 1027 | + }); | |
| 1028 | + | |
| 1029 | + it("should correctly identify bare backticks positions", () => { | |
| 1030 | + const allLines = ["```markdown", "```", "content", "```"]; | |
| 1031 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1032 | + | |
| 1033 | + // At position 1 (first bare backticks), should not stop | |
| 1034 | + expect(state.shouldStopAtPosition(1)).toBe(false); | |
| 1035 | + // At position 3 (last bare backticks), should stop | |
| 1036 | + expect(state.shouldStopAtPosition(3)).toBe(true); | |
| 1037 | + }); | |
| 1038 | + | |
| 1039 | + it("should maintain state across multiple calls", () => { | |
| 1040 | + const allLines = [ | |
| 1041 | + "```markdown", | |
| 1042 | + "# Title", | |
| 1043 | + "```javascript", | |
| 1044 | + "console.log('test');", | |
| 1045 | + "```", | |
| 1046 | + "More content", | |
| 1047 | + "```", | |
| 1048 | + ]; | |
| 1049 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1050 | + | |
| 1051 | + // Process positions incrementally | |
| 1052 | + expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block | |
| 1053 | + expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block | |
| 1054 | + expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block | |
| 1055 | + }); | |
| 1056 | + | |
| 1057 | + it("should handle complex nesting scenarios efficiently", () => { | |
| 1058 | + const allLines = [ | |
| 1059 | + "```markdown", | |
| 1060 | + "# Documentation", | |
| 1061 | + "```typescript", | |
| 1062 | + "interface Config {", | |
| 1063 | + " name: string;", | |
| 1064 | + "}", | |
| 1065 | + "```", | |
| 1066 | + "", | |
| 1067 | + "```bash", | |
| 1068 | + "npm install", | |
| 1069 | + "```", | |
| 1070 | + "", | |
| 1071 | + "Final notes", | |
| 1072 | + "```", | |
| 1073 | + ]; | |
| 1074 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1075 | + | |
| 1076 | + // Test multiple positions in sequence | |
| 1077 | + expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block | |
| 1078 | + expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block | |
| 1079 | + expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block | |
| 1080 | + }); | |
| 1081 | + | |
| 1082 | + it("should handle non-backtick lines correctly", () => { | |
| 1083 | + const allLines = ["```markdown", "regular content", "```"]; | |
| 1084 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1085 | + | |
| 1086 | + // Position 1 is not backticks, should return false | |
| 1087 | + expect(state.shouldStopAtPosition(1)).toBe(false); | |
| 1088 | + }); | |
| 1089 | + | |
| 1090 | + it("should handle empty lines and edge cases", () => { | |
| 1091 | + const allLines = ["```markdown", "", "```"]; | |
| 1092 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1093 | + | |
| 1094 | + expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line | |
| 1095 | + expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks | |
| 1096 | + }); | |
| 1097 | + | |
| 1098 | + it("should reset nest count when reaching final bare backticks", () => { | |
| 1099 | + const allLines = ["```markdown", "content", "```"]; | |
| 1100 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1101 | + | |
| 1102 | + // First call should stop and reset count | |
| 1103 | + expect(state.shouldStopAtPosition(2)).toBe(true); | |
| 1104 | + | |
| 1105 | + // If we had more content, it should start fresh | |
| 1106 | + // (This tests the internal state management) | |
| 1107 | + }); | |
| 1108 | + }); | |
| 1109 | + | |
| 1110 | + describe("shouldStopAtMarkdownBlock optimization", () => { | |
| 1111 | + it("should maintain performance benefits with state reuse", () => { | |
| 1112 | + const allLines = Array.from({ length: 100 }, (_, i) => { | |
| 1113 | + if (i === 0) return "```markdown"; | |
| 1114 | + if (i === 99) return "```"; | |
| 1115 | + if (i % 10 === 0) return "```javascript"; | |
| 1116 | + if (i % 10 === 5) return "```"; | |
| 1117 | + return `line ${i}`; | |
| 1118 | + }); | |
| 1119 | + | |
| 1120 | + const state = new MarkdownBlockStateTracker(allLines); | |
| 1121 | + | |
| 1122 | + // Test that we can call multiple times without recomputing everything | |
| 1123 | + const start = performance.now(); | |
| 1124 | + | |
| 1125 | + // Test several positions in sequence | |
| 1126 | + for (let i = 10; i < 90; i += 10) { | |
| 1127 | + if (allLines[i].trim() === "```") { | |
| 1128 | + shouldStopAtMarkdownBlock(state, i); | |
| 1129 | + } | |
| 1130 | + } | |
| 1131 | + | |
| 1132 | + const duration = performance.now() - start; | |
| 1133 | + expect(duration).toBeLessThan(10); // Should be very fast due to state caching | |
| 1134 | + }); | |
| 1135 | + }); | |
| 1136 | + | |
| 1137 | + describe("filterCodeBlockLines with optimized MarkdownBlockState", () => { | |
| 1138 | + it("should use optimized state tracker for markdown files", async () => { | |
| 1139 | + const linesGenerator = await getLineGenerator([ | |
| 1140 | + "```markdown", | |
| 1141 | + "# Documentation", | |
| 1142 | + "```typescript", | |
| 1143 | + "const config = { name: 'test' };", | |
| 1144 | + "```", | |
| 1145 | + "Final notes", | |
| 1146 | + "```", | |
| 1147 | + ]); | |
| 1148 | + | |
| 1149 | + const result = lineStream.filterCodeBlockLines( | |
| 1150 | + linesGenerator, | |
| 1151 | + "README.md", | |
| 1152 | + ); | |
| 1153 | + const filteredLines = await getFilteredLines(result); | |
| 1154 | + | |
| 1155 | + expect(filteredLines).toEqual([ | |
| 1156 | + "# Documentation", | |
| 1157 | + "```typescript", | |
| 1158 | + "const config = { name: 'test' };", | |
| 1159 | + "```", | |
| 1160 | + "Final notes", | |
| 1161 | + ]); | |
| 1162 | + }); | |
| 1163 | + | |
| 1164 | + it("should fall back to legacy behavior when no markdown nesting detected", async () => { | |
| 1165 | + const linesGenerator = await getLineGenerator([ | |
| 1166 | + "```typescript", | |
| 1167 | + "const x = 5;", | |
| 1168 | + "```", | |
| 1169 | + ]); | |
| 1170 | + | |
| 1171 | + const result = lineStream.filterCodeBlockLines( | |
| 1172 | + linesGenerator, | |
| 1173 | + "script.ts", | |
| 1174 | + ); | |
| 1175 | + const filteredLines = await getFilteredLines(result); | |
| 1176 | + | |
| 1177 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 1178 | + }); | |
| 1179 | + | |
| 1180 | + it("should handle mixed markdown and code scenarios with optimization", async () => { | |
| 1181 | + const linesGenerator = await getLineGenerator([ | |
| 1182 | + "```md", | |
| 1183 | + "## API Reference", | |
| 1184 | + "", | |
| 1185 | + "```javascript", | |
| 1186 | + "async function fetchData() {", | |
| 1187 | + " return await fetch('/api/data');", | |
| 1188 | + "}", | |
| 1189 | + "```", | |
| 1190 | + "", | |
| 1191 | + "Usage notes and more documentation.", | |
| 1192 | + "```", | |
| 1193 | + ]); | |
| 1194 | + | |
| 1195 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 1196 | + const filteredLines = await getFilteredLines(result); | |
| 1197 | + | |
| 1198 | + expect(filteredLines).toEqual([ | |
| 1199 | + "## API Reference", | |
| 1200 | + "", | |
| 1201 | + "```javascript", | |
| 1202 | + "async function fetchData() {", | |
| 1203 | + " return await fetch('/api/data');", | |
| 1204 | + "}", | |
| 1205 | + "```", | |
| 1206 | + "", | |
| 1207 | + "Usage notes and more documentation.", | |
| 1208 | + ]); | |
| 1209 | + }); | |
| 1210 | + }); | |
| 1211 | + | |
| 1212 | + describe("validatePatternInLine", () => { | |
| 1213 | + it("should return false when pattern is not found", () => { | |
| 1214 | + const result = lineStream.validatePatternInLine( | |
| 1215 | + "const x = 5;", | |
| 1216 | + "[/CODE]", | |
| 1217 | + ); | |
| 1218 | + expect(result.isValid).toBe(false); | |
| 1219 | + expect(result.patternIndex).toBe(-1); | |
| 1220 | + expect(result.beforePattern).toBe(""); | |
| 1221 | + }); | |
| 1222 | + | |
| 1223 | + it("should return false when pattern is preceded by non-whitespace", () => { | |
| 1224 | + const result = lineStream.validatePatternInLine( | |
| 1225 | + 'const var[/CODE]Name = "test";', | |
| 1226 | + "[/CODE]", | |
| 1227 | + ); | |
| 1228 | + expect(result.isValid).toBe(false); | |
| 1229 | + expect(result.patternIndex).toBe(9); | |
| 1230 | + }); | |
| 1231 | + | |
| 1232 | + it("should return false when pattern is inside double quotes", () => { | |
| 1233 | + const result = lineStream.validatePatternInLine( | |
| 1234 | + 'console.log("test [/CODE] end");', | |
| 1235 | + "[/CODE]", | |
| 1236 | + ); | |
| 1237 | + expect(result.isValid).toBe(false); | |
| 1238 | + expect(result.patternIndex).toBe(18); | |
| 1239 | + }); | |
| 1240 | + | |
| 1241 | + it("should return false when pattern is inside single quotes", () => { | |
| 1242 | + const result = lineStream.validatePatternInLine( | |
| 1243 | + "const message = 'test [/CODE] end';", | |
| 1244 | + "[/CODE]", | |
| 1245 | + ); | |
| 1246 | + expect(result.isValid).toBe(false); | |
| 1247 | + expect(result.patternIndex).toBe(22); | |
| 1248 | + }); | |
| 1249 | + | |
| 1250 | + it("should return true when pattern is properly separated by whitespace", () => { | |
| 1251 | + const result = lineStream.validatePatternInLine( | |
| 1252 | + "some code [/CODE] more text", | |
| 1253 | + "[/CODE]", | |
| 1254 | + ); | |
| 1255 | + expect(result.isValid).toBe(true); | |
| 1256 | + expect(result.patternIndex).toBe(10); | |
| 1257 | + expect(result.beforePattern).toBe("some code "); | |
| 1258 | + }); | |
| 1259 | + | |
| 1260 | + it("should return true when pattern is at start of line", () => { | |
| 1261 | + const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]"); | |
| 1262 | + expect(result.isValid).toBe(true); | |
| 1263 | + expect(result.patternIndex).toBe(0); | |
| 1264 | + expect(result.beforePattern).toBe(""); | |
| 1265 | + }); | |
| 1266 | + | |
| 1267 | + it("should return true when pattern has only whitespace before it", () => { | |
| 1268 | + const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]"); | |
| 1269 | + expect(result.isValid).toBe(true); | |
| 1270 | + expect(result.patternIndex).toBe(4); | |
| 1271 | + expect(result.beforePattern).toBe(" "); | |
| 1272 | + }); | |
| 1273 | + | |
| 1274 | + it("should handle complex quote scenarios correctly", () => { | |
| 1275 | + // Unmatched quote should make it invalid | |
| 1276 | + const result1 = lineStream.validatePatternInLine( | |
| 1277 | + 'const x = "unclosed quote [/CODE]', | |
| 1278 | + "[/CODE]", | |
| 1279 | + ); | |
| 1280 | + expect(result1.isValid).toBe(false); | |
| 1281 | + | |
| 1282 | + // Matched quotes should make it valid | |
| 1283 | + const result2 = lineStream.validatePatternInLine( | |
| 1284 | + 'const x = "closed"; [/CODE]', | |
| 1285 | + "[/CODE]", | |
| 1286 | + ); | |
| 1287 | + expect(result2.isValid).toBe(true); | |
| 1288 | + }); | |
| 1289 | + | |
| 1290 | + it("should work with different patterns", () => { | |
| 1291 | + const result1 = lineStream.validatePatternInLine( | |
| 1292 | + "# End of file. Done", | |
| 1293 | + "# End of file.", | |
| 1294 | + ); | |
| 1295 | + expect(result1.isValid).toBe(true); | |
| 1296 | + | |
| 1297 | + const result2 = lineStream.validatePatternInLine(" ```", "```"); | |
| 1298 | + expect(result2.isValid).toBe(true); | |
| 1299 | + }); | |
| 1300 | + }); | |
| 616 | 1301 | }); |
modified core/edit/lazy/replace.ts +9 −5
| @@ -1,8 +1,5 @@ | ||
| 1 | 1 | import { ILLM } from "../.."; |
| 2 | -import { | |
| 3 | - filterLeadingNewline, | |
| 4 | - stopAtLines, | |
| 5 | -} from "../../autocomplete/filtering/streamTransforms/lineStream"; | |
| 2 | +import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream"; | |
| 6 | 3 | import { streamLines } from "../../diff/util"; |
| 7 | 4 | import { dedent } from "../../util"; |
| 8 | 5 | |
| @@ -90,11 +87,18 @@ | ||
| 90 | 87 | { role: "assistant", content: assistantPrompt }, |
| 91 | 88 | ], |
| 92 | 89 | abortController.signal, |
| 90 | + { | |
| 91 | + raw: true, | |
| 92 | + prediction: undefined, | |
| 93 | + reasoning: false, | |
| 94 | + }, | |
| 93 | 95 | ); |
| 94 | 96 | |
| 95 | 97 | let lines = streamLines(completion); |
| 96 | 98 | lines = filterLeadingNewline(lines); |
| 97 | - lines = stopAtLines(lines, () => {}, ["```"]); | |
| 99 | + // We want to retrive everything from the llm | |
| 100 | + // then let the filterCodeBlocks function clean up for any trailing text. | |
| 101 | + // if we stop here early, we run the risk of loosing inner markdown content. | |
| 98 | 102 | |
| 99 | 103 | for await (const line of lines) { |
| 100 | 104 | yield line; |
added core/edit/lazy/streamLazyApply.test.ts +459 −0
| @@ -0,0 +1,459 @@ | ||
| 1 | +import { streamLazyApply } from "./streamLazyApply"; | |
| 2 | + | |
| 3 | +// Mock LLM for testing | |
| 4 | +class MockLLM { | |
| 5 | + model = "claude-3-5-sonnet-20241022"; | |
| 6 | + providerName = "anthropic"; | |
| 7 | + | |
| 8 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 9 | + // Simulate LLM response for markdown file with nested blocks | |
| 10 | + const lines = [ | |
| 11 | + "# Project Structure", | |
| 12 | + "", | |
| 13 | + "```markdown README.md", | |
| 14 | + "# Project Structure", | |
| 15 | + "", | |
| 16 | + "```", | |
| 17 | + ".", | |
| 18 | + "├── src/", | |
| 19 | + "│ └── main.js", | |
| 20 | + "└── package.json", | |
| 21 | + "```", | |
| 22 | + "```", | |
| 23 | + ]; | |
| 24 | + | |
| 25 | + // Yield each line separately (more realistic streaming) | |
| 26 | + for (const line of lines) { | |
| 27 | + yield line; | |
| 28 | + } | |
| 29 | + } | |
| 30 | +} | |
| 31 | + | |
| 32 | +class MockJavaScriptLLM { | |
| 33 | + model = "claude-3-5-sonnet-20241022"; | |
| 34 | + providerName = "anthropic"; | |
| 35 | + | |
| 36 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 37 | + // Simulate LLM response for JavaScript file | |
| 38 | + const lines = [ | |
| 39 | + "function calculateSum(a, b) {", | |
| 40 | + " return a + b;", | |
| 41 | + "}", | |
| 42 | + "", | |
| 43 | + "function calculateProduct(a, b) {", | |
| 44 | + " return a * b;", | |
| 45 | + "}", | |
| 46 | + ]; | |
| 47 | + | |
| 48 | + for (const line of lines) { | |
| 49 | + yield line; | |
| 50 | + } | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +class MockPythonLLM { | |
| 55 | + model = "claude-3-5-sonnet-20241022"; | |
| 56 | + providerName = "anthropic"; | |
| 57 | + | |
| 58 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 59 | + // Simulate LLM response for Python file | |
| 60 | + const lines = [ | |
| 61 | + "def calculate_sum(a, b):", | |
| 62 | + " return a + b", | |
| 63 | + "", | |
| 64 | + "def calculate_product(a, b):", | |
| 65 | + " return a * b", | |
| 66 | + ]; | |
| 67 | + | |
| 68 | + for (const line of lines) { | |
| 69 | + yield line; | |
| 70 | + } | |
| 71 | + } | |
| 72 | +} | |
| 73 | + | |
| 74 | +class MockWithUnchangedCodeLLM { | |
| 75 | + model = "claude-3-5-sonnet-20241022"; | |
| 76 | + providerName = "anthropic"; | |
| 77 | + | |
| 78 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 79 | + // Simulate LLM response with UNCHANGED_CODE markers | |
| 80 | + const lines = [ | |
| 81 | + "function newFunction() {", | |
| 82 | + " return 'new';", | |
| 83 | + "}", | |
| 84 | + "", | |
| 85 | + "// ... unchanged code ...", | |
| 86 | + "", | |
| 87 | + "function anotherFunction() {", | |
| 88 | + " return 'updated';", | |
| 89 | + "}", | |
| 90 | + ]; | |
| 91 | + | |
| 92 | + for (const line of lines) { | |
| 93 | + yield line; | |
| 94 | + } | |
| 95 | + } | |
| 96 | +} | |
| 97 | + | |
| 98 | +class MockTypeScriptLLM { | |
| 99 | + model = "claude-3-5-sonnet-20241022"; | |
| 100 | + providerName = "anthropic"; | |
| 101 | + | |
| 102 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 103 | + const lines = [ | |
| 104 | + "interface User {", | |
| 105 | + " id: number;", | |
| 106 | + " name: string;", | |
| 107 | + "}", | |
| 108 | + "", | |
| 109 | + "function getUser(id: number): User {", | |
| 110 | + " return { id, name: 'Test User' };", | |
| 111 | + "}", | |
| 112 | + ]; | |
| 113 | + | |
| 114 | + for (const line of lines) { | |
| 115 | + yield line; | |
| 116 | + } | |
| 117 | + } | |
| 118 | +} | |
| 119 | + | |
| 120 | +class MockEmptyLLM { | |
| 121 | + model = "claude-3-5-sonnet-20241022"; | |
| 122 | + providerName = "anthropic"; | |
| 123 | + | |
| 124 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 125 | + // Empty response | |
| 126 | + return; | |
| 127 | + } | |
| 128 | +} | |
| 129 | + | |
| 130 | +class MockSimpleLLM { | |
| 131 | + model = "claude-3-5-sonnet-20241022"; | |
| 132 | + providerName = "anthropic"; | |
| 133 | + | |
| 134 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 135 | + const lines = ["function test() {", " return true;", "}"]; | |
| 136 | + for (const line of lines) { | |
| 137 | + yield line; | |
| 138 | + } | |
| 139 | + } | |
| 140 | +} | |
| 141 | + | |
| 142 | +class MockRegularMarkdownLLM { | |
| 143 | + model = "claude-3-5-sonnet-20241022"; | |
| 144 | + providerName = "anthropic"; | |
| 145 | + | |
| 146 | + async *streamChat(messages: any[], signal?: AbortSignal) { | |
| 147 | + // Simulate regular markdown with simple code block | |
| 148 | + const lines = [ | |
| 149 | + "# Debug Test Folder", | |
| 150 | + "The sole purpose of this folder is to open it when debugging.", | |
| 151 | + "", | |
| 152 | + "## File Structure", | |
| 153 | + "```", | |
| 154 | + "debug-test-folder/", | |
| 155 | + "├── AdvancedPage.tsx", | |
| 156 | + "├── Calculator.java", | |
| 157 | + "├── Dockerfile", | |
| 158 | + "└── test.ts", | |
| 159 | + "```", | |
| 160 | + ]; | |
| 161 | + | |
| 162 | + for (const line of lines) { | |
| 163 | + yield line; | |
| 164 | + } | |
| 165 | + } | |
| 166 | +} | |
| 167 | + | |
| 168 | +describe("streamLazyApply", () => { | |
| 169 | + test("should handle markdown files with nested blocks without stopping early", async () => { | |
| 170 | + const oldCode = "# Project\n\nBasic readme content."; | |
| 171 | + const newCode = `# Project Structure | |
| 172 | + | |
| 173 | +\`\`\`markdown README.md | |
| 174 | +# Project Structure | |
| 175 | + | |
| 176 | +\`\`\` | |
| 177 | +. | |
| 178 | +├── src/ | |
| 179 | +│ └── main.js | |
| 180 | +└── package.json | |
| 181 | +\`\`\` | |
| 182 | +\`\`\``; | |
| 183 | + const filename = "README.md"; | |
| 184 | + const llm = new MockLLM() as any; | |
| 185 | + const abortController = new AbortController(); | |
| 186 | + | |
| 187 | + const diffLines = []; | |
| 188 | + for await (const diffLine of streamLazyApply( | |
| 189 | + oldCode, | |
| 190 | + filename, | |
| 191 | + newCode, | |
| 192 | + llm, | |
| 193 | + abortController, | |
| 194 | + )) { | |
| 195 | + diffLines.push(diffLine); | |
| 196 | + } | |
| 197 | + | |
| 198 | + // Should have received diff lines (not empty) | |
| 199 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 200 | + | |
| 201 | + // Should contain the nested markdown content | |
| 202 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 203 | + expect(allContent).toContain("```markdown README.md"); | |
| 204 | + expect(allContent).toContain("└── package.json"); | |
| 205 | + | |
| 206 | + // Should not have been truncated at the first ``` | |
| 207 | + expect(allContent).toContain("src/"); | |
| 208 | + }); | |
| 209 | + | |
| 210 | + test("should handle JavaScript files correctly", async () => { | |
| 211 | + const oldCode = "function calculateSum(a, b) {\n return a + b;\n}"; | |
| 212 | + const newCode = `function calculateSum(a, b) { | |
| 213 | + return a + b; | |
| 214 | +} | |
| 215 | + | |
| 216 | +function calculateProduct(a, b) { | |
| 217 | + return a * b; | |
| 218 | +}`; | |
| 219 | + const filename = "calculator.js"; | |
| 220 | + const llm = new MockJavaScriptLLM() as any; | |
| 221 | + const abortController = new AbortController(); | |
| 222 | + | |
| 223 | + const diffLines = []; | |
| 224 | + for await (const diffLine of streamLazyApply( | |
| 225 | + oldCode, | |
| 226 | + filename, | |
| 227 | + newCode, | |
| 228 | + llm, | |
| 229 | + abortController, | |
| 230 | + )) { | |
| 231 | + diffLines.push(diffLine); | |
| 232 | + } | |
| 233 | + | |
| 234 | + // Should have received diff lines | |
| 235 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 236 | + | |
| 237 | + // Should contain the JavaScript functions | |
| 238 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 239 | + expect(allContent).toContain("calculateSum"); | |
| 240 | + expect(allContent).toContain("calculateProduct"); | |
| 241 | + }); | |
| 242 | + | |
| 243 | + test("should handle Python files correctly", async () => { | |
| 244 | + const oldCode = "def calculate_sum(a, b):\n return a + b"; | |
| 245 | + const newCode = `def calculate_sum(a, b): | |
| 246 | + return a + b | |
| 247 | + | |
| 248 | +def calculate_product(a, b): | |
| 249 | + return a * b`; | |
| 250 | + const filename = "calculator.py"; | |
| 251 | + const llm = new MockPythonLLM() as any; | |
| 252 | + const abortController = new AbortController(); | |
| 253 | + | |
| 254 | + const diffLines = []; | |
| 255 | + for await (const diffLine of streamLazyApply( | |
| 256 | + oldCode, | |
| 257 | + filename, | |
| 258 | + newCode, | |
| 259 | + llm, | |
| 260 | + abortController, | |
| 261 | + )) { | |
| 262 | + diffLines.push(diffLine); | |
| 263 | + } | |
| 264 | + | |
| 265 | + // Should have received diff lines | |
| 266 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 267 | + | |
| 268 | + // Should contain the Python functions | |
| 269 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 270 | + expect(allContent).toContain("calculate_sum"); | |
| 271 | + expect(allContent).toContain("calculate_product"); | |
| 272 | + }); | |
| 273 | + | |
| 274 | + test("should handle UNCHANGED_CODE markers in responses", async () => { | |
| 275 | + const oldCode = `function oldFunction() { | |
| 276 | + return 'old'; | |
| 277 | +} | |
| 278 | + | |
| 279 | +function existingFunction() { | |
| 280 | + return 'existing'; | |
| 281 | +}`; | |
| 282 | + const newCode = `function newFunction() { | |
| 283 | + return 'new'; | |
| 284 | +} | |
| 285 | + | |
| 286 | +function existingFunction() { | |
| 287 | + return 'existing'; | |
| 288 | +} | |
| 289 | + | |
| 290 | +function anotherFunction() { | |
| 291 | + return 'updated'; | |
| 292 | +}`; | |
| 293 | + const filename = "example.js"; | |
| 294 | + const llm = new MockWithUnchangedCodeLLM() as any; | |
| 295 | + const abortController = new AbortController(); | |
| 296 | + | |
| 297 | + const diffLines = []; | |
| 298 | + for await (const diffLine of streamLazyApply( | |
| 299 | + oldCode, | |
| 300 | + filename, | |
| 301 | + newCode, | |
| 302 | + llm, | |
| 303 | + abortController, | |
| 304 | + )) { | |
| 305 | + diffLines.push(diffLine); | |
| 306 | + } | |
| 307 | + | |
| 308 | + // Should have received diff lines | |
| 309 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 310 | + | |
| 311 | + // Should contain new and updated functions | |
| 312 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 313 | + expect(allContent).toContain("newFunction"); | |
| 314 | + expect(allContent).toContain("anotherFunction"); | |
| 315 | + }); | |
| 316 | + | |
| 317 | + test("should handle TypeScript files correctly", async () => { | |
| 318 | + const oldCode = "interface User {\n id: number;\n}"; | |
| 319 | + const newCode = `interface User { | |
| 320 | + id: number; | |
| 321 | + name: string; | |
| 322 | +} | |
| 323 | + | |
| 324 | +function getUser(id: number): User { | |
| 325 | + return { id, name: 'Test User' }; | |
| 326 | +}`; | |
| 327 | + const filename = "user.ts"; | |
| 328 | + const llm = new MockTypeScriptLLM() as any; | |
| 329 | + const abortController = new AbortController(); | |
| 330 | + | |
| 331 | + const diffLines = []; | |
| 332 | + for await (const diffLine of streamLazyApply( | |
| 333 | + oldCode, | |
| 334 | + filename, | |
| 335 | + newCode, | |
| 336 | + llm, | |
| 337 | + abortController, | |
| 338 | + )) { | |
| 339 | + diffLines.push(diffLine); | |
| 340 | + } | |
| 341 | + | |
| 342 | + // Should have received diff lines | |
| 343 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 344 | + | |
| 345 | + // Should contain TypeScript interface and function | |
| 346 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 347 | + expect(allContent).toContain("interface User"); | |
| 348 | + expect(allContent).toContain("getUser"); | |
| 349 | + expect(allContent).toContain("name: string"); | |
| 350 | + }); | |
| 351 | + | |
| 352 | + test("should work with empty LLM responses", async () => { | |
| 353 | + const oldCode = "function test() { return 1; }"; | |
| 354 | + const newCode = "function test() { return 2; }"; | |
| 355 | + const filename = "test.js"; | |
| 356 | + const llm = new MockEmptyLLM() as any; | |
| 357 | + const abortController = new AbortController(); | |
| 358 | + | |
| 359 | + const diffLines = []; | |
| 360 | + for await (const diffLine of streamLazyApply( | |
| 361 | + oldCode, | |
| 362 | + filename, | |
| 363 | + newCode, | |
| 364 | + llm, | |
| 365 | + abortController, | |
| 366 | + )) { | |
| 367 | + diffLines.push(diffLine); | |
| 368 | + } | |
| 369 | + | |
| 370 | + // Should handle empty response gracefully | |
| 371 | + expect(diffLines).toBeDefined(); | |
| 372 | + }); | |
| 373 | + | |
| 374 | + test("should correctly identify markdown vs non-markdown files", async () => { | |
| 375 | + // Test that our isMarkdownFile logic works | |
| 376 | + const markdownFiles = ["README.md", "docs.markdown", "example.gfm"]; | |
| 377 | + const nonMarkdownFiles = [ | |
| 378 | + "script.js", | |
| 379 | + "code.py", | |
| 380 | + "style.css", | |
| 381 | + "component.tsx", | |
| 382 | + ]; | |
| 383 | + | |
| 384 | + // This is more of a unit test, but verifies our file detection logic | |
| 385 | + // We can test this indirectly by checking that different file types | |
| 386 | + // are processed through different code paths | |
| 387 | + | |
| 388 | + const oldCode = "function test() { return false; }"; | |
| 389 | + const newCode = "function test() { return true; }"; | |
| 390 | + const llm = new MockSimpleLLM() as any; | |
| 391 | + | |
| 392 | + // Test each file type | |
| 393 | + for (const filename of [...markdownFiles, ...nonMarkdownFiles]) { | |
| 394 | + const abortController = new AbortController(); | |
| 395 | + const diffLines = []; | |
| 396 | + | |
| 397 | + for await (const diffLine of streamLazyApply( | |
| 398 | + oldCode, | |
| 399 | + filename, | |
| 400 | + newCode, | |
| 401 | + llm, | |
| 402 | + abortController, | |
| 403 | + )) { | |
| 404 | + diffLines.push(diffLine); | |
| 405 | + } | |
| 406 | + | |
| 407 | + // Should work for all file types | |
| 408 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 409 | + | |
| 410 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 411 | + expect(allContent).toContain("test"); | |
| 412 | + } | |
| 413 | + }); | |
| 414 | + | |
| 415 | + test("should handle regular markdown files with simple code blocks", async () => { | |
| 416 | + const oldCode = "# Old Content"; | |
| 417 | + const newCode = `# Debug Test Folder | |
| 418 | +The sole purpose of this folder is to open it when debugging. | |
| 419 | + | |
| 420 | +## File Structure | |
| 421 | +\`\`\` | |
| 422 | +debug-test-folder/ | |
| 423 | +├── AdvancedPage.tsx | |
| 424 | +├── Calculator.java | |
| 425 | +├── Dockerfile | |
| 426 | +└── test.ts | |
| 427 | +\`\`\``; | |
| 428 | + | |
| 429 | + const filename = "README.md"; | |
| 430 | + const llm = new MockRegularMarkdownLLM() as any; | |
| 431 | + const abortController = new AbortController(); | |
| 432 | + | |
| 433 | + const diffLines = []; | |
| 434 | + for await (const diffLine of streamLazyApply( | |
| 435 | + oldCode, | |
| 436 | + filename, | |
| 437 | + newCode, | |
| 438 | + llm, | |
| 439 | + abortController, | |
| 440 | + )) { | |
| 441 | + diffLines.push(diffLine); | |
| 442 | + } | |
| 443 | + | |
| 444 | + // Should have received diff lines (not empty) | |
| 445 | + expect(diffLines.length).toBeGreaterThan(0); | |
| 446 | + | |
| 447 | + // Should contain the full file structure | |
| 448 | + const allContent = diffLines.map((d) => d.line).join("\n"); | |
| 449 | + expect(allContent).toContain("Debug Test Folder"); | |
| 450 | + expect(allContent).toContain("File Structure"); | |
| 451 | + expect(allContent).toContain("debug-test-folder/"); | |
| 452 | + expect(allContent).toContain("├── AdvancedPage.tsx"); | |
| 453 | + expect(allContent).toContain("└── test.ts"); | |
| 454 | + | |
| 455 | + // Should not have been truncated at the opening ``` | |
| 456 | + expect(allContent).toContain("Calculator.java"); | |
| 457 | + expect(allContent).toContain("Dockerfile"); | |
| 458 | + }); | |
| 459 | +}); |
modified core/edit/lazy/streamLazyApply.ts +7 −5
| @@ -2,11 +2,11 @@ | ||
| 2 | 2 | filterLeadingAndTrailingNewLineInsertion, |
| 3 | 3 | filterLeadingNewline, |
| 4 | 4 | removeTrailingWhitespace, |
| 5 | - stopAtLines, | |
| 6 | 5 | } from "../../autocomplete/filtering/streamTransforms/lineStream.js"; |
| 7 | 6 | import { streamDiff } from "../../diff/streamDiff.js"; |
| 8 | 7 | import { LineStream, streamLines } from "../../diff/util.js"; |
| 9 | 8 | import { DiffLine, ILLM } from "../../index.js"; |
| 9 | +import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js"; | |
| 10 | 10 | |
| 11 | 11 | import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; |
| 12 | 12 | import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; |
| @@ -44,9 +44,12 @@ | ||
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 46 | let lazyCompletionLines = streamLines(lazyCompletion, true); |
| 47 | - // Process line output | |
| 48 | - // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); | |
| 49 | - lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); | |
| 47 | + | |
| 48 | + lazyCompletionLines = stopAtLinesWithMarkdownSupport( | |
| 49 | + lazyCompletionLines, | |
| 50 | + filename, | |
| 51 | + ); | |
| 52 | + | |
| 50 | 53 | lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); |
| 51 | 54 | lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines); |
| 52 | 55 | |
| @@ -92,7 +95,6 @@ | ||
| 92 | 95 | newLines.push(replacementLine); |
| 93 | 96 | replacement += replacementLine + "\n"; |
| 94 | 97 | } |
| 95 | - | |
| 96 | 98 | // Yield the buffered lines |
| 97 | 99 | for (const bufferedLine of buffer) { |
| 98 | 100 | yield bufferedLine; |
modified core/edit/recursiveStream.ts +2 −1
| @@ -63,7 +63,8 @@ | ||
| 63 | 63 | } |
| 64 | 64 | } else { |
| 65 | 65 | const generator = llm.streamChat(prompt, abortController.signal, { |
| 66 | - prediction, | |
| 66 | + raw: true, | |
| 67 | + prediction: undefined, | |
| 67 | 68 | reasoning: false, |
| 68 | 69 | }); |
| 69 | 70 |
modified core/edit/streamDiffLines.ts +1 −5
| @@ -55,11 +55,7 @@ | ||
| 55 | 55 | } |
| 56 | 56 | |
| 57 | 57 | function modelIsInept(model: string): boolean { |
| 58 | - return !( | |
| 59 | - model.includes("gpt") || | |
| 60 | - model.includes("claude") || | |
| 61 | - model.includes("nova") | |
| 62 | - ); | |
| 58 | + return !(model.includes("gpt") || model.includes("claude")); | |
| 63 | 59 | } |
| 64 | 60 | |
| 65 | 61 | export async function* streamDiffLines({ |
added core/utils/markdownUtils.ts +136 −0
| @@ -0,0 +1,136 @@ | ||
| 1 | +/** | |
| 2 | + * Utility functions for working with markdown files and code blocks | |
| 3 | + */ | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Determines if a code block header indicates markdown content | |
| 7 | + */ | |
| 8 | +export function headerIsMarkdown(header: string): boolean { | |
| 9 | + return ( | |
| 10 | + header === "md" || | |
| 11 | + header === "markdown" || | |
| 12 | + header === "gfm" || | |
| 13 | + header === "github-markdown" || | |
| 14 | + header.includes(" md") || | |
| 15 | + header.includes(" markdown") || | |
| 16 | + header.includes(" gfm") || | |
| 17 | + header.includes(" github-markdown") || | |
| 18 | + header.split(" ")[0]?.split(".").pop() === "md" || | |
| 19 | + header.split(" ")[0]?.split(".").pop() === "markdown" || | |
| 20 | + header.split(" ")[0]?.split(".").pop() === "gfm" | |
| 21 | + ); | |
| 22 | +} | |
| 23 | + | |
| 24 | +/** | |
| 25 | + * Determines if a file is a markdown file based on its filepath. | |
| 26 | + */ | |
| 27 | +export function isMarkdownFile(filepath?: string): boolean { | |
| 28 | + if (!filepath) { | |
| 29 | + return false; | |
| 30 | + } | |
| 31 | + | |
| 32 | + const ext = filepath.split(".").pop()?.toLowerCase() || ""; | |
| 33 | + return ["md", "markdown", "gfm"].includes(ext); | |
| 34 | +} | |
| 35 | + | |
| 36 | +/** | |
| 37 | + * State tracker for markdown block analysis to avoid recomputing on each call. | |
| 38 | + * Optimized to handle nested markdown code blocks. | |
| 39 | + */ | |
| 40 | +export class MarkdownBlockStateTracker { | |
| 41 | + protected trimmedLines: string[]; | |
| 42 | + protected bareBacktickPositions: number[]; | |
| 43 | + private markdownNestCount: number = 0; | |
| 44 | + private lastProcessedIndex: number = -1; | |
| 45 | + | |
| 46 | + constructor(allLines: string[]) { | |
| 47 | + this.trimmedLines = allLines.map((l) => l.trim()); | |
| 48 | + // Pre-compute positions of all bare backtick lines for faster lookup | |
| 49 | + this.bareBacktickPositions = []; | |
| 50 | + for (let i = 0; i < this.trimmedLines.length; i++) { | |
| 51 | + if (this.trimmedLines[i].match(/^`+$/)) { | |
| 52 | + this.bareBacktickPositions.push(i); | |
| 53 | + } | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * Determines if we should stop at the given markdown block position. | |
| 59 | + * Maintains state across calls to avoid redundant computation. | |
| 60 | + */ | |
| 61 | + shouldStopAtPosition(currentIndex: number): boolean { | |
| 62 | + if (this.trimmedLines[currentIndex] !== "```") { | |
| 63 | + return false; | |
| 64 | + } | |
| 65 | + | |
| 66 | + // Process any lines we haven't seen yet up to currentIndex | |
| 67 | + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { | |
| 68 | + const currentLine = this.trimmedLines[j]; | |
| 69 | + | |
| 70 | + if (this.markdownNestCount > 0) { | |
| 71 | + // Inside a markdown block | |
| 72 | + if (currentLine.match(/^`+$/)) { | |
| 73 | + // Found bare backticks - check if this is the last one | |
| 74 | + if (j === currentIndex) { | |
| 75 | + const remainingBareBackticks = | |
| 76 | + this.getRemainingBareBackticksAfter(j); | |
| 77 | + if (remainingBareBackticks === 0) { | |
| 78 | + this.markdownNestCount = 0; | |
| 79 | + this.lastProcessedIndex = j; | |
| 80 | + return true; | |
| 81 | + } | |
| 82 | + } | |
| 83 | + } else if (currentLine.startsWith("```")) { | |
| 84 | + // Going into a nested codeblock | |
| 85 | + this.markdownNestCount++; | |
| 86 | + } | |
| 87 | + } else { | |
| 88 | + // Not inside a markdown block yet | |
| 89 | + if (currentLine.startsWith("```")) { | |
| 90 | + const header = currentLine.replaceAll("`", ""); | |
| 91 | + if (headerIsMarkdown(header)) { | |
| 92 | + this.markdownNestCount = 1; | |
| 93 | + } | |
| 94 | + } | |
| 95 | + } | |
| 96 | + } | |
| 97 | + | |
| 98 | + this.lastProcessedIndex = currentIndex; | |
| 99 | + return false; | |
| 100 | + } | |
| 101 | + | |
| 102 | + /** | |
| 103 | + * Efficiently determines if there are remaining bare backticks after the given position. | |
| 104 | + */ | |
| 105 | + getRemainingBareBackticksAfter(currentIndex: number): number { | |
| 106 | + return this.bareBacktickPositions.filter((pos) => pos > currentIndex) | |
| 107 | + .length; | |
| 108 | + } | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * Checks if the line at the given index is a bare backtick line. | |
| 112 | + */ | |
| 113 | + isBareBacktickLine(index: number): boolean { | |
| 114 | + return this.bareBacktickPositions.includes(index); | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * Gets the trimmed lines array. | |
| 119 | + */ | |
| 120 | + getTrimmedLines(): string[] { | |
| 121 | + return this.trimmedLines; | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +/** | |
| 126 | + * Collects all lines from a LineStream into an array for analysis. | |
| 127 | + */ | |
| 128 | +export async function collectAllLines<T>( | |
| 129 | + stream: AsyncGenerator<T>, | |
| 130 | +): Promise<T[]> { | |
| 131 | + const allLines: T[] = []; | |
| 132 | + for await (const line of stream) { | |
| 133 | + allLines.push(line); | |
| 134 | + } | |
| 135 | + return allLines; | |
| 136 | +} |
added core/utils/markdownUtils.vitest.ts +306 −0
| @@ -0,0 +1,306 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + collectAllLines, | |
| 4 | + headerIsMarkdown, | |
| 5 | + isMarkdownFile, | |
| 6 | + MarkdownBlockStateTracker, | |
| 7 | +} from "./markdownUtils"; | |
| 8 | + | |
| 9 | +describe("headerIsMarkdown", () => { | |
| 10 | + // Test exact match with common Markdown identifiers | |
| 11 | + it("should identify exact matches with common Markdown identifiers", () => { | |
| 12 | + expect(headerIsMarkdown("md")).toBe(true); | |
| 13 | + expect(headerIsMarkdown("markdown")).toBe(true); | |
| 14 | + expect(headerIsMarkdown("gfm")).toBe(true); | |
| 15 | + expect(headerIsMarkdown("github-markdown")).toBe(true); | |
| 16 | + }); | |
| 17 | + | |
| 18 | + // Test identifiers preceded by a space | |
| 19 | + it("should identify identifiers preceded by a space", () => { | |
| 20 | + expect(headerIsMarkdown("lang md")).toBe(true); | |
| 21 | + expect(headerIsMarkdown("something markdown")).toBe(true); | |
| 22 | + expect(headerIsMarkdown("language gfm")).toBe(true); | |
| 23 | + expect(headerIsMarkdown("spec github-markdown")).toBe(true); | |
| 24 | + }); | |
| 25 | + | |
| 26 | + // Test file extensions | |
| 27 | + it("should identify file names with markdown extensions", () => { | |
| 28 | + expect(headerIsMarkdown("example.md")).toBe(true); | |
| 29 | + expect(headerIsMarkdown("document.markdown")).toBe(true); | |
| 30 | + expect(headerIsMarkdown("readme.gfm")).toBe(true); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + // Test more complex cases with extensions | |
| 34 | + it("should identify file names with markdown extensions followed by other text", () => { | |
| 35 | + expect(headerIsMarkdown("example.md additional text")).toBe(true); | |
| 36 | + expect(headerIsMarkdown("document.markdown with some description")).toBe( | |
| 37 | + true, | |
| 38 | + ); | |
| 39 | + expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true); | |
| 40 | + }); | |
| 41 | + | |
| 42 | + // Test non-markdown cases | |
| 43 | + it("should not identify non-markdown headers", () => { | |
| 44 | + expect(headerIsMarkdown("javascript")).toBe(false); | |
| 45 | + expect(headerIsMarkdown("typescript")).toBe(false); | |
| 46 | + expect(headerIsMarkdown("plain")).toBe(false); | |
| 47 | + expect(headerIsMarkdown("python")).toBe(false); | |
| 48 | + }); | |
| 49 | + | |
| 50 | + // Test edge cases | |
| 51 | + it("should handle edge cases correctly", () => { | |
| 52 | + expect(headerIsMarkdown("")).toBe(false); | |
| 53 | + expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md" | |
| 54 | + expect(headerIsMarkdown("readme md")).toBe(true); | |
| 55 | + expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension | |
| 56 | + }); | |
| 57 | + | |
| 58 | + // Test case sensitivity | |
| 59 | + it("should respect case sensitivity", () => { | |
| 60 | + expect(headerIsMarkdown("MD")).toBe(false); | |
| 61 | + expect(headerIsMarkdown("MARKDOWN")).toBe(false); | |
| 62 | + expect(headerIsMarkdown("example.MD")).toBe(false); | |
| 63 | + expect(headerIsMarkdown("lang MD")).toBe(false); | |
| 64 | + }); | |
| 65 | + | |
| 66 | + // Test with special characters and spacing | |
| 67 | + it("should handle special characters and spacing correctly", () => { | |
| 68 | + expect(headerIsMarkdown(" md")).toBe(true); // Space before "md" | |
| 69 | + expect(headerIsMarkdown("md ")).toBe(true); // Space after "md" | |
| 70 | + expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix | |
| 71 | + expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix | |
| 72 | + }); | |
| 73 | +}); | |
| 74 | + | |
| 75 | +describe("isMarkdownFile", () => { | |
| 76 | + it("should identify markdown files by .md extension", () => { | |
| 77 | + expect(isMarkdownFile("README.md")).toBe(true); | |
| 78 | + expect(isMarkdownFile("docs/guide.md")).toBe(true); | |
| 79 | + expect(isMarkdownFile("/path/to/file.md")).toBe(true); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + it("should identify markdown files by .markdown extension", () => { | |
| 83 | + expect(isMarkdownFile("README.markdown")).toBe(true); | |
| 84 | + expect(isMarkdownFile("docs/guide.markdown")).toBe(true); | |
| 85 | + expect(isMarkdownFile("/path/to/file.markdown")).toBe(true); | |
| 86 | + }); | |
| 87 | + | |
| 88 | + it("should identify markdown files by .gfm extension", () => { | |
| 89 | + expect(isMarkdownFile("README.gfm")).toBe(true); | |
| 90 | + expect(isMarkdownFile("docs/guide.gfm")).toBe(true); | |
| 91 | + expect(isMarkdownFile("/path/to/file.gfm")).toBe(true); | |
| 92 | + }); | |
| 93 | + | |
| 94 | + it("should handle case insensitive extensions", () => { | |
| 95 | + expect(isMarkdownFile("README.MD")).toBe(true); | |
| 96 | + expect(isMarkdownFile("guide.MARKDOWN")).toBe(true); | |
| 97 | + expect(isMarkdownFile("file.GFM")).toBe(true); | |
| 98 | + }); | |
| 99 | + | |
| 100 | + it("should return false for non-markdown files", () => { | |
| 101 | + expect(isMarkdownFile("script.js")).toBe(false); | |
| 102 | + expect(isMarkdownFile("style.css")).toBe(false); | |
| 103 | + expect(isMarkdownFile("data.json")).toBe(false); | |
| 104 | + expect(isMarkdownFile("document.txt")).toBe(false); | |
| 105 | + }); | |
| 106 | + | |
| 107 | + it("should return false for undefined or empty filepath", () => { | |
| 108 | + expect(isMarkdownFile(undefined)).toBe(false); | |
| 109 | + expect(isMarkdownFile("")).toBe(false); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + it("should return false for files without extensions", () => { | |
| 113 | + expect(isMarkdownFile("README")).toBe(false); | |
| 114 | + expect(isMarkdownFile("Dockerfile")).toBe(false); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + it("should handle files with multiple dots", () => { | |
| 118 | + expect(isMarkdownFile("file.backup.md")).toBe(true); | |
| 119 | + expect(isMarkdownFile("config.test.js")).toBe(false); | |
| 120 | + }); | |
| 121 | +}); | |
| 122 | + | |
| 123 | +describe("MarkdownBlockStateTracker", () => { | |
| 124 | + it("should initialize correctly with empty lines", () => { | |
| 125 | + const tracker = new MarkdownBlockStateTracker([]); | |
| 126 | + expect(tracker.shouldStopAtPosition(0)).toBe(false); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + it("should initialize correctly with non-markdown lines", () => { | |
| 130 | + const tracker = new MarkdownBlockStateTracker([ | |
| 131 | + "const x = 5;", | |
| 132 | + "console.log(x);", | |
| 133 | + ]); | |
| 134 | + expect(tracker.shouldStopAtPosition(0)).toBe(false); | |
| 135 | + expect(tracker.shouldStopAtPosition(1)).toBe(false); | |
| 136 | + }); | |
| 137 | + | |
| 138 | + it("should detect simple markdown blocks", () => { | |
| 139 | + const tracker = new MarkdownBlockStateTracker([ | |
| 140 | + "```markdown", | |
| 141 | + "# Title", | |
| 142 | + "```", | |
| 143 | + ]); | |
| 144 | + expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening | |
| 145 | + expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content | |
| 146 | + expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing | |
| 147 | + }); | |
| 148 | + | |
| 149 | + it("should handle nested code blocks within markdown", () => { | |
| 150 | + const tracker = new MarkdownBlockStateTracker([ | |
| 151 | + "```md", | |
| 152 | + "Here's some code:", | |
| 153 | + "```javascript", | |
| 154 | + "console.log('hello');", | |
| 155 | + "```", | |
| 156 | + "More content", | |
| 157 | + "```", | |
| 158 | + ]); | |
| 159 | + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening | |
| 160 | + expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing | |
| 161 | + expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing | |
| 162 | + }); | |
| 163 | + | |
| 164 | + it("should handle multiple bare backticks", () => { | |
| 165 | + const tracker = new MarkdownBlockStateTracker([ | |
| 166 | + "```markdown", | |
| 167 | + "Content with ```inline``` code", | |
| 168 | + "```", | |
| 169 | + "More content", | |
| 170 | + "```", | |
| 171 | + ]); | |
| 172 | + expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks | |
| 173 | + expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks | |
| 174 | + }); | |
| 175 | + | |
| 176 | + it("should handle non-markdown code blocks", () => { | |
| 177 | + const tracker = new MarkdownBlockStateTracker([ | |
| 178 | + "```javascript", | |
| 179 | + "console.log('hello');", | |
| 180 | + "```", | |
| 181 | + ]); | |
| 182 | + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block | |
| 183 | + }); | |
| 184 | + | |
| 185 | + it("should handle mixed markdown types", () => { | |
| 186 | + const tracker = new MarkdownBlockStateTracker([ | |
| 187 | + "```gfm", | |
| 188 | + "# GitHub Flavored Markdown", | |
| 189 | + "```", | |
| 190 | + ]); | |
| 191 | + expect(tracker.shouldStopAtPosition(2)).toBe(true); | |
| 192 | + }); | |
| 193 | + | |
| 194 | + it("should handle state persistence across multiple calls", () => { | |
| 195 | + const tracker = new MarkdownBlockStateTracker([ | |
| 196 | + "```markdown", | |
| 197 | + "# Documentation", | |
| 198 | + "```typescript", | |
| 199 | + "interface Config {}", | |
| 200 | + "```", | |
| 201 | + "Final notes", | |
| 202 | + "```", | |
| 203 | + ]); | |
| 204 | + | |
| 205 | + // Process incrementally | |
| 206 | + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening | |
| 207 | + expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing | |
| 208 | + expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing | |
| 209 | + }); | |
| 210 | + | |
| 211 | + it("should handle lines that are not closing backticks", () => { | |
| 212 | + const tracker = new MarkdownBlockStateTracker([ | |
| 213 | + "```markdown", | |
| 214 | + "Regular content line", | |
| 215 | + "```", | |
| 216 | + ]); | |
| 217 | + expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks | |
| 218 | + }); | |
| 219 | + | |
| 220 | + it("should provide access to trimmed lines", () => { | |
| 221 | + const tracker = new MarkdownBlockStateTracker([ | |
| 222 | + " ```markdown ", | |
| 223 | + " # Title ", | |
| 224 | + " ``` ", | |
| 225 | + ]); | |
| 226 | + const trimmedLines = tracker.getTrimmedLines(); | |
| 227 | + expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]); | |
| 228 | + }); | |
| 229 | + | |
| 230 | + it("should identify bare backtick lines correctly", () => { | |
| 231 | + const tracker = new MarkdownBlockStateTracker([ | |
| 232 | + "```markdown", | |
| 233 | + "```", | |
| 234 | + "content", | |
| 235 | + "```", | |
| 236 | + ]); | |
| 237 | + expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language | |
| 238 | + expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks | |
| 239 | + expect(tracker.isBareBacktickLine(2)).toBe(false); // Content | |
| 240 | + expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks | |
| 241 | + }); | |
| 242 | + | |
| 243 | + it("should count remaining bare backticks correctly", () => { | |
| 244 | + const tracker = new MarkdownBlockStateTracker([ | |
| 245 | + "```markdown", | |
| 246 | + "```", | |
| 247 | + "content", | |
| 248 | + "```", | |
| 249 | + "more content", | |
| 250 | + "```", | |
| 251 | + ]); | |
| 252 | + expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening | |
| 253 | + expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare | |
| 254 | + expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare | |
| 255 | + expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare | |
| 256 | + }); | |
| 257 | +}); | |
| 258 | + | |
| 259 | +describe("collectAllLines", () => { | |
| 260 | + async function* createAsyncGenerator<T>(items: T[]): AsyncGenerator<T> { | |
| 261 | + for (const item of items) { | |
| 262 | + yield item; | |
| 263 | + } | |
| 264 | + } | |
| 265 | + | |
| 266 | + it("should collect all lines from a stream", async () => { | |
| 267 | + const stream = createAsyncGenerator(["line1", "line2", "line3"]); | |
| 268 | + const result = await collectAllLines(stream); | |
| 269 | + expect(result).toEqual(["line1", "line2", "line3"]); | |
| 270 | + }); | |
| 271 | + | |
| 272 | + it("should handle empty streams", async () => { | |
| 273 | + const stream = createAsyncGenerator([]); | |
| 274 | + const result = await collectAllLines(stream); | |
| 275 | + expect(result).toEqual([]); | |
| 276 | + }); | |
| 277 | + | |
| 278 | + it("should handle streams with mixed types", async () => { | |
| 279 | + const stream = createAsyncGenerator([1, "text", null, true]); | |
| 280 | + const result = await collectAllLines(stream); | |
| 281 | + expect(result).toEqual([1, "text", null, true]); | |
| 282 | + }); | |
| 283 | + | |
| 284 | + it("should handle streams with empty strings", async () => { | |
| 285 | + const stream = createAsyncGenerator(["", "line2", "", "line4"]); | |
| 286 | + const result = await collectAllLines(stream); | |
| 287 | + expect(result).toEqual(["", "line2", "", "line4"]); | |
| 288 | + }); | |
| 289 | + | |
| 290 | + it("should handle large streams", async () => { | |
| 291 | + const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`); | |
| 292 | + const stream = createAsyncGenerator(largeArray); | |
| 293 | + const result = await collectAllLines(stream); | |
| 294 | + expect(result).toEqual(largeArray); | |
| 295 | + }); | |
| 296 | + | |
| 297 | + it("should handle object streams", async () => { | |
| 298 | + const objects = [ | |
| 299 | + { type: "new", line: "const x = 5;" }, | |
| 300 | + { type: "old", line: "let y = 10;" }, | |
| 301 | + ]; | |
| 302 | + const stream = createAsyncGenerator(objects); | |
| 303 | + const result = await collectAllLines(stream); | |
| 304 | + expect(result).toEqual(objects); | |
| 305 | + }); | |
| 306 | +}); |
added core/utils/streamMarkdownUtils.ts +98 −0
| @@ -0,0 +1,98 @@ | ||
| 1 | +import { LineStream } from "../diff/util"; | |
| 2 | +import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils"; | |
| 3 | + | |
| 4 | +/** | |
| 5 | + * Determines if we should stop at a markdown block based on nested markdown logic. | |
| 6 | + * This handles the complex case where markdown blocks contain other markdown blocks. | |
| 7 | + * Uses optimized state tracking to avoid redundant computation. | |
| 8 | + */ | |
| 9 | +export function shouldStopAtMarkdownBlock( | |
| 10 | + stateTracker: MarkdownBlockStateTracker, | |
| 11 | + currentIndex: number, | |
| 12 | +): boolean { | |
| 13 | + return stateTracker.shouldStopAtPosition(currentIndex); | |
| 14 | +} | |
| 15 | + | |
| 16 | +/** | |
| 17 | + * Processes block nesting logic and returns updated state. | |
| 18 | + */ | |
| 19 | +export function processBlockNesting( | |
| 20 | + line: string, | |
| 21 | + seenFirstFence: boolean, | |
| 22 | + shouldRemoveLineBeforeStart: (line: string) => boolean, | |
| 23 | +): { newSeenFirstFence: boolean; shouldSkip: boolean } { | |
| 24 | + if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { | |
| 25 | + return { newSeenFirstFence: false, shouldSkip: true }; | |
| 26 | + } | |
| 27 | + | |
| 28 | + if (!seenFirstFence) { | |
| 29 | + return { newSeenFirstFence: true, shouldSkip: false }; | |
| 30 | + } | |
| 31 | + | |
| 32 | + return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; | |
| 33 | +} | |
| 34 | + | |
| 35 | +/** | |
| 36 | + * Stream transformation that stops when encountering a markdown code block ending. | |
| 37 | + * Handles nested markdown blocks in markdown files. | |
| 38 | + */ | |
| 39 | +export async function* stopAtLinesWithMarkdownSupport( | |
| 40 | + lines: LineStream, | |
| 41 | + filename: string, | |
| 42 | +): LineStream { | |
| 43 | + if (!isMarkdownFile(filename)) { | |
| 44 | + for await (const line of lines) { | |
| 45 | + if (line.trim() === "```") { | |
| 46 | + return; | |
| 47 | + } | |
| 48 | + yield line; | |
| 49 | + } | |
| 50 | + return; | |
| 51 | + } | |
| 52 | + | |
| 53 | + const allLines: string[] = []; | |
| 54 | + for await (const line of lines) { | |
| 55 | + allLines.push(line); | |
| 56 | + } | |
| 57 | + | |
| 58 | + const source = allLines.join("\n"); | |
| 59 | + if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) { | |
| 60 | + // No nested markdown blocks detected, check for simple ``` stopping condition | |
| 61 | + let foundStandaloneBackticks = false; | |
| 62 | + for (let i = 0; i < allLines.length; i++) { | |
| 63 | + if (allLines[i].trim() === "```") { | |
| 64 | + // Found standalone backticks, yield lines up to this point | |
| 65 | + for (let j = 0; j < i; j++) { | |
| 66 | + yield allLines[j]; | |
| 67 | + } | |
| 68 | + foundStandaloneBackticks = true; | |
| 69 | + return; | |
| 70 | + } | |
| 71 | + } | |
| 72 | + | |
| 73 | + // No standalone backticks found, yield all lines | |
| 74 | + if (!foundStandaloneBackticks) { | |
| 75 | + for (const line of allLines) { | |
| 76 | + yield line; | |
| 77 | + } | |
| 78 | + } | |
| 79 | + return; | |
| 80 | + } | |
| 81 | + | |
| 82 | + // Use optimized state tracker for markdown block analysis | |
| 83 | + const stateTracker = new MarkdownBlockStateTracker(allLines); | |
| 84 | + | |
| 85 | + for (let i = 0; i < allLines.length; i++) { | |
| 86 | + if (stateTracker.shouldStopAtPosition(i)) { | |
| 87 | + for (let j = 0; j < i; j++) { | |
| 88 | + yield allLines[j]; | |
| 89 | + } | |
| 90 | + return; | |
| 91 | + } | |
| 92 | + } | |
| 93 | + | |
| 94 | + // If we get here, yield all lines | |
| 95 | + for (const line of allLines) { | |
| 96 | + yield line; | |
| 97 | + } | |
| 98 | +} |
added core/utils/streamMarkdownUtils.vitest.ts +102 −0
| @@ -0,0 +1,102 @@ | ||
| 1 | +import { expect, test } from "vitest"; | |
| 2 | +import { LineStream } from "../diff/util"; | |
| 3 | +import { | |
| 4 | + processBlockNesting, | |
| 5 | + stopAtLinesWithMarkdownSupport, | |
| 6 | +} from "./streamMarkdownUtils"; | |
| 7 | + | |
| 8 | +test("processBlockNesting correctly handles starting blocks", () => { | |
| 9 | + // Mock function to determine which lines should be removed | |
| 10 | + const shouldRemoveLineBeforeStart = (line: string) => | |
| 11 | + line === "[CODE]" || line === "```"; | |
| 12 | + | |
| 13 | + // Test not seeing first fence yet | |
| 14 | + const result1 = processBlockNesting( | |
| 15 | + "[CODE]", | |
| 16 | + false, | |
| 17 | + shouldRemoveLineBeforeStart, | |
| 18 | + ); | |
| 19 | + expect(result1.newSeenFirstFence).toBe(false); | |
| 20 | + expect(result1.shouldSkip).toBe(true); | |
| 21 | + | |
| 22 | + // Test not seeing first fence but line shouldn't be removed | |
| 23 | + const result2 = processBlockNesting( | |
| 24 | + "normal code", | |
| 25 | + false, | |
| 26 | + shouldRemoveLineBeforeStart, | |
| 27 | + ); | |
| 28 | + expect(result2.newSeenFirstFence).toBe(true); | |
| 29 | + expect(result2.shouldSkip).toBe(false); | |
| 30 | + | |
| 31 | + // Test already seen first fence | |
| 32 | + const result3 = processBlockNesting( | |
| 33 | + "more code", | |
| 34 | + true, | |
| 35 | + shouldRemoveLineBeforeStart, | |
| 36 | + ); | |
| 37 | + expect(result3.newSeenFirstFence).toBe(true); | |
| 38 | + expect(result3.shouldSkip).toBe(false); | |
| 39 | +}); | |
| 40 | + | |
| 41 | +test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => { | |
| 42 | + // Create a mock line stream | |
| 43 | + const mockLines = ["line 1", "line 2", "```", "line 4"]; | |
| 44 | + const lineStream: LineStream = (async function* () { | |
| 45 | + for (const line of mockLines) { | |
| 46 | + yield line; | |
| 47 | + } | |
| 48 | + })(); | |
| 49 | + | |
| 50 | + // Test with a non-markdown file | |
| 51 | + const filename = "test.js"; | |
| 52 | + const result = stopAtLinesWithMarkdownSupport(lineStream, filename); | |
| 53 | + | |
| 54 | + // Should only yield lines up to the backticks | |
| 55 | + const collected = []; | |
| 56 | + for await (const line of result) { | |
| 57 | + collected.push(line); | |
| 58 | + } | |
| 59 | + | |
| 60 | + expect(collected).toEqual(["line 1", "line 2"]); | |
| 61 | +}); | |
| 62 | + | |
| 63 | +test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => { | |
| 64 | + // Create a mock line stream with markdown content - but NOT nested markdown blocks | |
| 65 | + const mockLines = [ | |
| 66 | + "Some markdown text", | |
| 67 | + "", | |
| 68 | + "```javascript", | |
| 69 | + "function test() {", | |
| 70 | + " return true;", | |
| 71 | + "}", | |
| 72 | + "```", | |
| 73 | + "More text", | |
| 74 | + ]; | |
| 75 | + | |
| 76 | + const lineStream: LineStream = (async function* () { | |
| 77 | + for (const line of mockLines) { | |
| 78 | + yield line; | |
| 79 | + } | |
| 80 | + })(); | |
| 81 | + | |
| 82 | + // Test with a markdown file | |
| 83 | + const filename = "test.md"; | |
| 84 | + const result = stopAtLinesWithMarkdownSupport(lineStream, filename); | |
| 85 | + | |
| 86 | + // Should yield everything since there's no nested markdown blocks | |
| 87 | + const collected = []; | |
| 88 | + for await (const line of result) { | |
| 89 | + collected.push(line); | |
| 90 | + } | |
| 91 | + | |
| 92 | + // The function should stop at the standalone ``` line (not yield it or lines after) | |
| 93 | + // This is the correct behavior - it stops when it encounters standalone backticks | |
| 94 | + expect(collected).toEqual([ | |
| 95 | + "Some markdown text", | |
| 96 | + "", | |
| 97 | + "```javascript", | |
| 98 | + "function test() {", | |
| 99 | + " return true;", | |
| 100 | + "}", | |
| 101 | + ]); | |
| 102 | +}); |
deleted gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts +0 −67
| @@ -1,67 +0,0 @@ | ||
| 1 | -import { headerIsMarkdown } from "./headerIsMarkdown"; | |
| 2 | - | |
| 3 | -describe("headerIsMarkdown", () => { | |
| 4 | - // Test exact match with common Markdown identifiers | |
| 5 | - it("should identify exact matches with common Markdown identifiers", () => { | |
| 6 | - expect(headerIsMarkdown("md")).toBe(true); | |
| 7 | - expect(headerIsMarkdown("markdown")).toBe(true); | |
| 8 | - expect(headerIsMarkdown("gfm")).toBe(true); | |
| 9 | - expect(headerIsMarkdown("github-markdown")).toBe(true); | |
| 10 | - }); | |
| 11 | - | |
| 12 | - // Test identifiers preceded by a space | |
| 13 | - it("should identify identifiers preceded by a space", () => { | |
| 14 | - expect(headerIsMarkdown("lang md")).toBe(true); | |
| 15 | - expect(headerIsMarkdown("something markdown")).toBe(true); | |
| 16 | - expect(headerIsMarkdown("language gfm")).toBe(true); | |
| 17 | - expect(headerIsMarkdown("spec github-markdown")).toBe(true); | |
| 18 | - }); | |
| 19 | - | |
| 20 | - // Test file extensions | |
| 21 | - it("should identify file names with markdown extensions", () => { | |
| 22 | - expect(headerIsMarkdown("example.md")).toBe(true); | |
| 23 | - expect(headerIsMarkdown("document.markdown")).toBe(true); | |
| 24 | - expect(headerIsMarkdown("readme.gfm")).toBe(true); | |
| 25 | - }); | |
| 26 | - | |
| 27 | - // Test more complex cases with extensions | |
| 28 | - it("should identify file names with markdown extensions followed by other text", () => { | |
| 29 | - expect(headerIsMarkdown("example.md additional text")).toBe(true); | |
| 30 | - expect(headerIsMarkdown("document.markdown with some description")).toBe( | |
| 31 | - true, | |
| 32 | - ); | |
| 33 | - expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true); | |
| 34 | - }); | |
| 35 | - | |
| 36 | - // Test non-markdown cases | |
| 37 | - it("should not identify non-markdown headers", () => { | |
| 38 | - expect(headerIsMarkdown("javascript")).toBe(false); | |
| 39 | - expect(headerIsMarkdown("typescript")).toBe(false); | |
| 40 | - expect(headerIsMarkdown("plain")).toBe(false); | |
| 41 | - expect(headerIsMarkdown("python")).toBe(false); | |
| 42 | - }); | |
| 43 | - | |
| 44 | - // Test edge cases | |
| 45 | - it("should handle edge cases correctly", () => { | |
| 46 | - expect(headerIsMarkdown("")).toBe(false); | |
| 47 | - expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md" | |
| 48 | - expect(headerIsMarkdown("readme md")).toBe(true); | |
| 49 | - expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension | |
| 50 | - }); | |
| 51 | - | |
| 52 | - // Test case sensitivity | |
| 53 | - it("should respect case sensitivity", () => { | |
| 54 | - expect(headerIsMarkdown("MD")).toBe(false); | |
| 55 | - expect(headerIsMarkdown("MARKDOWN")).toBe(false); | |
| 56 | - expect(headerIsMarkdown("example.MD")).toBe(false); | |
| 57 | - expect(headerIsMarkdown("lang MD")).toBe(false); | |
| 58 | - }); | |
| 59 | - | |
| 60 | - // Test with special characters and spacing | |
| 61 | - it("should handle special characters and spacing correctly", () => { | |
| 62 | - expect(headerIsMarkdown(" md")).toBe(true); // Space before "md" | |
| 63 | - expect(headerIsMarkdown("md ")).toBe(true); // Space after "md" | |
| 64 | - expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix | |
| 65 | - expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix | |
| 66 | - }); | |
| 67 | -}); |
deleted gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +0 −26
| @@ -1,26 +0,0 @@ | ||
| 1 | -/** | |
| 2 | - * Determines if a given header string represents Markdown content. | |
| 3 | - * | |
| 4 | - * The function checks various patterns to identify Markdown headers: | |
| 5 | - * - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown) | |
| 6 | - * - Contains these identifiers preceded by a space | |
| 7 | - * - First word has a file extension of md, markdown, or gfm | |
| 8 | - * | |
| 9 | - * @param header - The string to check for Markdown indicators | |
| 10 | - * @returns True if the header represents Markdown content, false otherwise | |
| 11 | - */ | |
| 12 | -export function headerIsMarkdown(header: string): boolean { | |
| 13 | - return ( | |
| 14 | - header === "md" || | |
| 15 | - header === "markdown" || | |
| 16 | - header === "gfm" || | |
| 17 | - header === "github-markdown" || | |
| 18 | - header.includes(" md") || | |
| 19 | - header.includes(" markdown") || | |
| 20 | - header.includes(" gfm") || | |
| 21 | - header.includes(" github-markdown") || | |
| 22 | - header.split(" ")[0]?.split(".").pop() === "md" || | |
| 23 | - header.split(" ")[0]?.split(".").pop() === "markdown" || | |
| 24 | - header.split(" ")[0]?.split(".").pop() === "gfm" | |
| 25 | - ); | |
| 26 | -} |
modified gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts +8 −0
| @@ -6,6 +6,14 @@ | ||
| 6 | 6 | expect(patchNestedMarkdown(source)).toBe(source); |
| 7 | 7 | }); |
| 8 | 8 | |
| 9 | + it("should handle nested blocks without a type", () => { | |
| 10 | + const source = | |
| 11 | + "```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```"; | |
| 12 | + const expected = | |
| 13 | + "~~~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~~~"; | |
| 14 | + expect(patchNestedMarkdown(source)).toBe(expected); | |
| 15 | + }); | |
| 16 | + | |
| 9 | 17 | it("should replace backticks with tildes for markdown codeblocks", () => { |
| 10 | 18 | const source = "```markdown\n# Header\nSome text\n```"; |
| 11 | 19 | const expected = "~~~markdown\n# Header\nSome text\n~~~"; |
modified gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +19 −8
| @@ -7,7 +7,10 @@ | ||
| 7 | 7 | |
| 8 | 8 | Note, this was benchmarked at sub-millisecond |
| 9 | 9 | */ |
| 10 | -import { headerIsMarkdown } from "./headerIsMarkdown"; | |
| 10 | +import { | |
| 11 | + headerIsMarkdown, | |
| 12 | + MarkdownBlockStateTracker, | |
| 13 | +} from "../../../../../core/utils/markdownUtils"; | |
| 11 | 14 | |
| 12 | 15 | export const patchNestedMarkdown = (source: string): string => { |
| 13 | 16 | // Early return if no markdown codeblock pattern is found (including GitHub variants) |
| @@ -16,21 +19,29 @@ | ||
| 16 | 19 | |
| 17 | 20 | let nestCount = 0; |
| 18 | 21 | const lines = source.split("\n"); |
| 19 | - const trimmedLines = lines.map((l) => l.trim()); | |
| 22 | + | |
| 23 | + // Use optimized state tracker for efficient bare backtick analysis | |
| 24 | + const stateTracker = new MarkdownBlockStateTracker(lines); | |
| 25 | + const trimmedLines = stateTracker.getTrimmedLines(); | |
| 20 | 26 | |
| 21 | 27 | for (let i = 0; i < trimmedLines.length; i++) { |
| 22 | 28 | const line = trimmedLines[i]; |
| 23 | 29 | |
| 24 | 30 | if (nestCount > 0) { |
| 25 | 31 | // Inside a markdown block |
| 26 | - if (line.match(/^`+$/)) { | |
| 27 | - // Ending a block with just backticks (```) | |
| 28 | - nestCount--; | |
| 29 | - if (nestCount === 0) { | |
| 30 | - lines[i] = "~~~"; // End of markdown block | |
| 32 | + if (stateTracker.isBareBacktickLine(i)) { | |
| 33 | + // Found bare backticks - use optimized lookup for remaining count | |
| 34 | + const remainingBareBackticks = | |
| 35 | + stateTracker.getRemainingBareBackticksAfter(i); | |
| 36 | + | |
| 37 | + // If this is the last bare backticks, it closes the markdown block | |
| 38 | + if (remainingBareBackticks === 0) { | |
| 39 | + nestCount = 0; | |
| 40 | + lines[i] = "~~~"; // Convert final closing delimiter to tildes | |
| 31 | 41 | } |
| 42 | + // Otherwise, keep as backticks (inner nested block delimiter) | |
| 32 | 43 | } else if (line.startsWith("```")) { |
| 33 | - // Going into a nested codeblock | |
| 44 | + // Going into a nested codeblock (with language identifier) | |
| 34 | 45 | nestCount++; |
| 35 | 46 | } |
| 36 | 47 | } else { |