From 9cd2f8b34b2ef814b2d1f386c024f993cc66274a Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 17:43:32 -0700 Subject: [PATCH] enhancing the solution --- .../filtering/streamTransforms/lineStream.ts | 116 ++++- .../streamTransforms/lineStream.vitest.ts | 144 ++++++ core/edit/lazy/replace.ts | 14 +- core/edit/lazy/streamLazyApply.test.ts | 459 ++++++++++++++++++ core/edit/lazy/streamLazyApply.ts | 118 ++++- core/edit/recursiveStream.ts | 3 +- .../utils/isOpeningNestedBlock.test.ts | 157 ------ .../utils/isOpeningNestedBlock.ts | 66 --- .../utils/patchNestedMarkdown.ts | 25 +- 9 files changed, 836 insertions(+), 266 deletions(-) create mode 100644 core/edit/lazy/streamLazyApply.test.ts delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index bc193cb12..eabfca5a7 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -16,6 +16,23 @@ export type CharacterFilter = (args: { multiline: boolean; }) => AsyncGenerator; +// Duplicated from gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +function headerIsMarkdown(header: string): boolean { + return ( + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + header.split(" ")[0]?.split(".").pop() === "md" || + header.split(" ")[0]?.split(".").pop() === "markdown" || + header.split(" ")[0]?.split(".").pop() === "gfm" + ); +} + function isBracketEnding(line: string): boolean { return line .trim() @@ -331,25 +348,52 @@ export async function* removeTrailingWhitespace( /** * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. + * Now includes markdown-aware processing to handle nested markdown blocks properly. * * @param {LineStream} rawLines - The input stream of lines to filter. + * @param {string} filepath - Optional filepath to determine if this is a markdown file. * @yields {string} Filtered and processed lines from the code block. * * @description * This generator function performs the following tasks: * 1. Removes initial lines that should be removed before the actual code starts. - * 2. Filters out ending code block markers (```) unless they are the last line. - * 3. Handles special cases where lines should be changed and the stream should stop. - * 4. Yields processed lines that are part of the actual code block content. + * 2. For markdown files, applies nested markdown block logic to avoid premature termination. + * 3. For non-markdown files, uses original stopping behavior. + * 4. Handles special cases where lines should be changed and the stream should stop. + * 5. Yields processed lines that are part of the actual code block content. */ -export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { +export async function* filterCodeBlockLines( + rawLines: LineStream, + filepath?: string, +): LineStream { let seenFirstFence = false; // nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented - // when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early + // when an inner code block is discovered to avoid exiting the function prematurely. The function will exit early // when all blocks are matched. When no outer fence is discovered the function will always continue to the end. let nestCount = 0; + // Check if this is a markdown file and collect lines for analysis + const isMarkdownFile = + filepath && + ["md", "markdown", "gfm"].includes( + filepath.split(".").pop()?.toLowerCase() || "", + ); + + const allLines: string[] = []; for await (const line of rawLines) { + allLines.push(line); + } + + // Check if it has nested markdown blocks (like ```markdown or ```md) + const firstLine = allLines[0] || ""; + const hasNestedMarkdown = + (firstLine.startsWith("```") && + headerIsMarkdown(firstLine.replace(/`/g, ""))) || + (filepath && headerIsMarkdown(filepath)); + + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]; + if (!seenFirstFence) { if (shouldRemoveLineBeforeStart(line)) { // Filter out starting ``` or START block @@ -365,14 +409,66 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { const changedEndLine = shouldChangeLineAndStop(line); if (typeof changedEndLine === "string") { // Ending a block with just backticks (```) or STOP + + // For markdown files with nested markdown blocks, apply special logic + if (hasNestedMarkdown && line.trim() === "```") { + // Apply the same nested markdown logic as patchNestedMarkdown + const trimmedLines = allLines.map((l) => l.trim()); + + let markdownNestCount = 0; + let shouldStop = false; + + for (let j = 0; j <= i; j++) { + const currentLine = trimmedLines[j]; + + if (markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - count remaining ones + let remainingBareBackticks = 0; + for (let k = j + 1; k < trimmedLines.length; k++) { + if (trimmedLines[k].match(/^`+$/)) { + remainingBareBackticks++; + } + } + + // If this is the last bare backticks and we're at position i, stop + if (remainingBareBackticks === 0 && j === i) { + markdownNestCount = 0; + shouldStop = true; + break; + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + markdownNestCount = 1; + } + } + } + } + + if (shouldStop) { + return; // Stop without yielding the final closing ``` + } else { + // This is an inner block delimiter, yield it as content + yield line; + continue; + } + } + + // Original logic for non-markdown files or simple cases nestCount--; if (nestCount === 0) { - // if we are closing the outer block then exit early - // only exit early if the outer block was started with a block - // it it was text, we will never exit early + // We've closed the outer wrapper - stop without yielding the closing ``` return; } else { - // otherwise just yield the line + // This is a nested block closing, yield it as content yield line; } } else if (line.startsWith("```")) { @@ -380,7 +476,7 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { nestCount++; yield line; } else { - // otherwise just yield the line + // Otherwise just yield the line as content yield line; } } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 8861b968c..f68447c39 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -301,6 +301,37 @@ describe("lineStream", () => { ]); }); + it("should ignore ticks inside of code blocks such as tests", async () => { + const linesGenerator = await getLineGenerator([ + "```typescript", + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + ]); + }); + it("should handle included inner ticks", async () => { const linesGenerator = await getLineGenerator([ "```md", @@ -395,6 +426,119 @@ describe("lineStream", () => { "```", ]); }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is included", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "README.md", + ); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is excluded", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + it("should handle non-markdown files normally with filepath parameter", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "function test() {", + " return 'hello';", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js"); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "function test() {", + " return 'hello';", + "}", + ]); + }); + + it("should handle simple markdown code blocks", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "README.md", + ); + const filteredLines = await getFilteredLines(result); + + // Should remove the outer markdown wrapper, and return just the inner content. + // The lack of an end tag should cause it to return all remaining lines. + expect(filteredLines).toEqual([ + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + }); }); describe("filterEnglishLinesAtStart", () => { diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index 1a5ba704d..e7ec47dc9 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -1,8 +1,5 @@ import { ILLM } from "../.."; -import { - filterLeadingNewline, - stopAtLines, -} from "../../autocomplete/filtering/streamTransforms/lineStream"; +import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { dedent } from "../../util"; @@ -90,11 +87,18 @@ export async function* getReplacementWithLlm( { role: "assistant", content: assistantPrompt }, ], abortController.signal, + { + raw: true, + prediction: undefined, + reasoning: false, + }, ); let lines = streamLines(completion); lines = filterLeadingNewline(lines); - lines = stopAtLines(lines, () => {}, ["```"]); + // We want to retrive everything from the llm + // then let the filterCodeBlocks function clean up for any trailing text. + // if we stop here early, we run the risk of loosing inner markdown content. for await (const line of lines) { yield line; diff --git a/core/edit/lazy/streamLazyApply.test.ts b/core/edit/lazy/streamLazyApply.test.ts new file mode 100644 index 000000000..3a829b5f4 --- /dev/null +++ b/core/edit/lazy/streamLazyApply.test.ts @@ -0,0 +1,459 @@ +import { streamLazyApply } from "./streamLazyApply"; + +// Mock LLM for testing +class MockLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response for markdown file with nested blocks + const lines = [ + "# Project Structure", + "", + "```markdown README.md", + "# Project Structure", + "", + "```", + ".", + "├── src/", + "│ └── main.js", + "└── package.json", + "```", + "```", + ]; + + // Yield each line separately (more realistic streaming) + for (const line of lines) { + yield line; + } + } +} + +class MockJavaScriptLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response for JavaScript file + const lines = [ + "function calculateSum(a, b) {", + " return a + b;", + "}", + "", + "function calculateProduct(a, b) {", + " return a * b;", + "}", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockPythonLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response for Python file + const lines = [ + "def calculate_sum(a, b):", + " return a + b", + "", + "def calculate_product(a, b):", + " return a * b", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockWithUnchangedCodeLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate LLM response with UNCHANGED_CODE markers + const lines = [ + "function newFunction() {", + " return 'new';", + "}", + "", + "// ... unchanged code ...", + "", + "function anotherFunction() {", + " return 'updated';", + "}", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockTypeScriptLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + const lines = [ + "interface User {", + " id: number;", + " name: string;", + "}", + "", + "function getUser(id: number): User {", + " return { id, name: 'Test User' };", + "}", + ]; + + for (const line of lines) { + yield line; + } + } +} + +class MockEmptyLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Empty response + return; + } +} + +class MockSimpleLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + const lines = ["function test() {", " return true;", "}"]; + for (const line of lines) { + yield line; + } + } +} + +class MockRegularMarkdownLLM { + model = "claude-3-5-sonnet-20241022"; + providerName = "anthropic"; + + async *streamChat(messages: any[], signal?: AbortSignal) { + // Simulate regular markdown with simple code block + const lines = [ + "# Debug Test Folder", + "The sole purpose of this folder is to open it when debugging.", + "", + "## File Structure", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "├── Dockerfile", + "└── test.ts", + "```", + ]; + + for (const line of lines) { + yield line; + } + } +} + +describe("streamLazyApply", () => { + test("should handle markdown files with nested blocks without stopping early", async () => { + const oldCode = "# Project\n\nBasic readme content."; + const newCode = `# Project Structure + +\`\`\`markdown README.md +# Project Structure + +\`\`\` +. +├── src/ +│ └── main.js +└── package.json +\`\`\` +\`\`\``; + const filename = "README.md"; + const llm = new MockLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines (not empty) + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the nested markdown content + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("```markdown README.md"); + expect(allContent).toContain("└── package.json"); + + // Should not have been truncated at the first ``` + expect(allContent).toContain("src/"); + }); + + test("should handle JavaScript files correctly", async () => { + const oldCode = "function calculateSum(a, b) {\n return a + b;\n}"; + const newCode = `function calculateSum(a, b) { + return a + b; +} + +function calculateProduct(a, b) { + return a * b; +}`; + const filename = "calculator.js"; + const llm = new MockJavaScriptLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the JavaScript functions + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("calculateSum"); + expect(allContent).toContain("calculateProduct"); + }); + + test("should handle Python files correctly", async () => { + const oldCode = "def calculate_sum(a, b):\n return a + b"; + const newCode = `def calculate_sum(a, b): + return a + b + +def calculate_product(a, b): + return a * b`; + const filename = "calculator.py"; + const llm = new MockPythonLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the Python functions + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("calculate_sum"); + expect(allContent).toContain("calculate_product"); + }); + + test("should handle UNCHANGED_CODE markers in responses", async () => { + const oldCode = `function oldFunction() { + return 'old'; +} + +function existingFunction() { + return 'existing'; +}`; + const newCode = `function newFunction() { + return 'new'; +} + +function existingFunction() { + return 'existing'; +} + +function anotherFunction() { + return 'updated'; +}`; + const filename = "example.js"; + const llm = new MockWithUnchangedCodeLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain new and updated functions + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("newFunction"); + expect(allContent).toContain("anotherFunction"); + }); + + test("should handle TypeScript files correctly", async () => { + const oldCode = "interface User {\n id: number;\n}"; + const newCode = `interface User { + id: number; + name: string; +} + +function getUser(id: number): User { + return { id, name: 'Test User' }; +}`; + const filename = "user.ts"; + const llm = new MockTypeScriptLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain TypeScript interface and function + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("interface User"); + expect(allContent).toContain("getUser"); + expect(allContent).toContain("name: string"); + }); + + test("should work with empty LLM responses", async () => { + const oldCode = "function test() { return 1; }"; + const newCode = "function test() { return 2; }"; + const filename = "test.js"; + const llm = new MockEmptyLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should handle empty response gracefully + expect(diffLines).toBeDefined(); + }); + + test("should correctly identify markdown vs non-markdown files", async () => { + // Test that our isMarkdownFile logic works + const markdownFiles = ["README.md", "docs.markdown", "example.gfm"]; + const nonMarkdownFiles = [ + "script.js", + "code.py", + "style.css", + "component.tsx", + ]; + + // This is more of a unit test, but verifies our file detection logic + // We can test this indirectly by checking that different file types + // are processed through different code paths + + const oldCode = "function test() { return false; }"; + const newCode = "function test() { return true; }"; + const llm = new MockSimpleLLM() as any; + + // Test each file type + for (const filename of [...markdownFiles, ...nonMarkdownFiles]) { + const abortController = new AbortController(); + const diffLines = []; + + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should work for all file types + expect(diffLines.length).toBeGreaterThan(0); + + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("test"); + } + }); + + test("should handle regular markdown files with simple code blocks", async () => { + const oldCode = "# Old Content"; + const newCode = `# Debug Test Folder +The sole purpose of this folder is to open it when debugging. + +## File Structure +\`\`\` +debug-test-folder/ +├── AdvancedPage.tsx +├── Calculator.java +├── Dockerfile +└── test.ts +\`\`\``; + + const filename = "README.md"; + const llm = new MockRegularMarkdownLLM() as any; + const abortController = new AbortController(); + + const diffLines = []; + for await (const diffLine of streamLazyApply( + oldCode, + filename, + newCode, + llm, + abortController, + )) { + diffLines.push(diffLine); + } + + // Should have received diff lines (not empty) + expect(diffLines.length).toBeGreaterThan(0); + + // Should contain the full file structure + const allContent = diffLines.map((d) => d.line).join("\n"); + expect(allContent).toContain("Debug Test Folder"); + expect(allContent).toContain("File Structure"); + expect(allContent).toContain("debug-test-folder/"); + expect(allContent).toContain("├── AdvancedPage.tsx"); + expect(allContent).toContain("└── test.ts"); + + // Should not have been truncated at the opening ``` + expect(allContent).toContain("Calculator.java"); + expect(allContent).toContain("Dockerfile"); + }); +}); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index f8ec0905c..1186ca6de 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -2,7 +2,6 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, removeTrailingWhitespace, - stopAtLines, } from "../../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; @@ -11,6 +10,102 @@ import { DiffLine, ILLM } from "../../index.js"; import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; +function headerIsMarkdown(header: string): boolean { + return ( + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + header.split(" ")[0]?.split(".").pop() === "md" || + header.split(" ")[0]?.split(".").pop() === "markdown" || + header.split(" ")[0]?.split(".").pop() === "gfm" + ); +} + +function isMarkdownFile(filename: string): boolean { + const ext = filename.split(".").pop()?.toLowerCase(); + return ["md", "markdown", "gfm"].includes(ext || ""); +} + +async function* stopAtLinesWithMarkdownSupport( + lines: LineStream, + filename: string, +): LineStream { + if (!isMarkdownFile(filename)) { + for await (const line of lines) { + if (line.trim() === "```") { + return; + } + yield line; + } + return; + } + + const allLines: string[] = []; + for await (const line of lines) { + allLines.push(line); + } + + const source = allLines.join("\n"); + if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) { + for (let i = 0; i < allLines.length; i++) { + if (allLines[i].trim() === "```") { + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + return; + } + yield allLines[i]; + } + return; + } + + let nestCount = 0; + const trimmedLines = allLines.map((l) => l.trim()); + + for (let i = 0; i < trimmedLines.length; i++) { + const line = trimmedLines[i]; + + if (nestCount > 0) { + if (line.match(/^`+$/)) { + let remainingBareBackticks = 0; + for (let j = i + 1; j < trimmedLines.length; j++) { + if (trimmedLines[j].match(/^`+$/)) { + remainingBareBackticks++; + } + } + + if (remainingBareBackticks === 0) { + nestCount = 0; + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + return; + } + } else if (line.startsWith("```")) { + nestCount++; + } + } else { + if (line.startsWith("```")) { + const header = line.replaceAll("`", ""); + const isMarkdown = headerIsMarkdown(header); + + if (isMarkdown) { + nestCount = 1; + } + } + } + } + + for (const line of allLines) { + yield line; + } +} + export async function* streamLazyApply( oldCode: string, filename: string, @@ -26,7 +121,6 @@ export async function* streamLazyApply( const promptMessages = promptFactory(oldCode, filename, newCode); const lazyCompletion = llm.streamChat(promptMessages, abortController.signal); - // Do find and replace over the lazy edit response async function* replacementFunction( oldCode: string, linesBefore: string[], @@ -44,20 +138,21 @@ export async function* streamLazyApply( } let lazyCompletionLines = streamLines(lazyCompletion, true); - // Process line output - // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); - lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); + + lazyCompletionLines = stopAtLinesWithMarkdownSupport( + lazyCompletionLines, + filename, + ); + lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines); - // Fill in unchanged code let lines = streamFillUnchangedCode( lazyCompletionLines, oldCode, replacementFunction, ); - // Convert output to diff const oldLines = oldCode.split(/\r?\n/); let diffLines = streamDiff(oldLines, lines); diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines); @@ -78,13 +173,11 @@ async function* streamFillUnchangedCode( const newLines = []; let buffer = []; let waitingForBuffer = false; - for await (const line of lines) { if (waitingForBuffer) { buffer.push(line); if (buffer.length >= BUFFER_LINES_BELOW) { - // Find the replacement and continue streaming once we have it const replacementLines = replacementFunction(oldCode, newLines, buffer); let replacement = ""; for await (const replacementLine of replacementLines) { @@ -92,8 +185,6 @@ async function* streamFillUnchangedCode( newLines.push(replacementLine); replacement += replacementLine + "\n"; } - - // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); @@ -108,9 +199,7 @@ async function* streamFillUnchangedCode( } if (line.includes(UNCHANGED_CODE)) { - // Buffer so we can give the context of BUFFER_LINES_BELOW lines below waitingForBuffer = true; - // TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently } else { yield line; newLines.push(line); @@ -118,14 +207,11 @@ async function* streamFillUnchangedCode( } if (waitingForBuffer) { - // If we're still waiting for a buffer, we've reached the end of the stream - // and we should just look for the replacement with what we have const replacementLines = replacementFunction(oldCode, newLines, buffer); for await (const replacementLine of replacementLines) { yield replacementLine; newLines.push(replacementLine); } - // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts index 004563cdb..d249755f4 100644 --- a/core/edit/recursiveStream.ts +++ b/core/edit/recursiveStream.ts @@ -63,7 +63,8 @@ export async function* recursiveStream( } } else { const generator = llm.streamChat(prompt, abortController.signal, { - prediction, + raw: true, + prediction: undefined, reasoning: false, }); diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts deleted file mode 100644 index e5eb02f0c..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { expect, test } from "vitest"; -import { isOpeningNestedBlock } from "./isOpeningNestedBlock"; - -test("isOpeningNestedBlock should return true when odd number of bare backticks ahead", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be opening (1 ``` ahead = odd) - "content", - - "```", // <- index 4: closing (0 ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(true); - expect(isOpeningNestedBlock(trimmedLines, 4, 2)).toBe(false); -}); - -test("isOpeningNestedBlock should return false when even number (zero) of bare backticks ahead", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing (0 ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle multiple nested pairs", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: opening (3 ``` ahead = odd) - "```", // <- index 3: opening (2 ``` ahead = even) -> should be false - "content", - - "```", // <- index 5: closing (1 ``` ahead = odd) -> should be true - "```", // <- index 6: closing (0 ``` ahead = even) -> should be false - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(true); // 3 ahead = odd - expect(isOpeningNestedBlock(trimmedLines, 3, 2)).toBe(false); // 2 ahead = even - expect(isOpeningNestedBlock(trimmedLines, 5, 2)).toBe(true); // 1 ahead = odd - expect(isOpeningNestedBlock(trimmedLines, 6, 1)).toBe(false); // 0 ahead = even -}); - -test("isOpeningNestedBlock should return false when reaching end of markdown block via ~~~", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing since ~~~ terminates the block - "content", - - "~~~", // <- terminator stops counting - "```", // <- this one is after the markdown block ends - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should return false when reaching new markdown block", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing since new markdown block starts - "content", - - "```md", // <- new markdown block terminates counting - "```", // <- this one belongs to the new block - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle empty content between backticks", () => { - const trimmedLines = [ - "```markdown", - - "```", // <- index 1: opening (1 ``` ahead = odd) - "", - - "```", // <- index 3: closing (0 ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 1, 1)).toBe(true); - expect(isOpeningNestedBlock(trimmedLines, 3, 2)).toBe(false); -}); - -test("isOpeningNestedBlock should handle case where currentIndex is last line", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: last line, should be closing (0 ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should not be confused by backticks in content", () => { - const trimmedLines = [ - "```markdown", - "Some `code` with backticks", - - "```", // <- index 2: should be closing (0 bare ``` ahead = even) - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle GitHub markdown variants as terminators", () => { - const trimmedLines = [ - "```markdown", - "# Header", - - "```", // <- index 2: should be closing (terminator stops counting) - "content", - - "```gfm", // <- GitHub markdown variant starts new block - "```", - ]; - - expect(isOpeningNestedBlock(trimmedLines, 2, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should only check terminators at nest level 1", () => { - const trimmedLines = [ - "```markdown", - - "```", // <- index 1: at nest level 1, ~~~ should terminate counting - "~~~", // <- terminator found, stops counting - "```", // <- this doesn't count towards the logic - ]; - - expect(isOpeningNestedBlock(trimmedLines, 1, 1)).toBe(false); -}); - -test("isOpeningNestedBlock should handle complex realistic markdown structure", () => { - const trimmedLines = [ - "```markdown README.md", - "# Project Structure", - "", - "```", // <- index 3: has 2 ``` ahead (even), so should be closing - ".", - "│ └── file.ts", - "```", // <- index 7: has 1 ``` ahead (odd), so should be opening - "```", // <- index 8: has 0 ``` ahead (even), so should be closing - ]; - - expect(isOpeningNestedBlock(trimmedLines, 3, 1)).toBe(false); // 2 ahead = even - expect(isOpeningNestedBlock(trimmedLines, 7, 2)).toBe(true); // 1 ahead = odd - expect(isOpeningNestedBlock(trimmedLines, 8, 1)).toBe(false); // 0 ahead = even -}); diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts deleted file mode 100644 index 8327ed219..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { headerIsMarkdown } from "./headerIsMarkdown"; - -/** - * Determines if a line with bare backticks (```) should be treated as opening - * a nested code block rather than closing the current block. - * - * Uses look-ahead to check if there are more bare backtick lines ahead, - * which would indicate this is opening a nested block. - * - * @param trimmedLines - Array of trimmed lines from the source - * @param currentIndex - Index of the current line with bare backticks - * @param nestCount - Current nesting level - * @returns true if this should open a nested block, false if it should close - */ -export function isOpeningNestedBlock( - trimmedLines: string[], - currentIndex: number, - nestCount: number, -): boolean { - // Simulate what would happen if we continue processing from this point - // Count how many blocks would need to be closed vs opened - - let simulatedNestCount = nestCount; - let bareBackticksAhead = 0; - - for (let j = currentIndex + 1; j < trimmedLines.length; j++) { - const line = trimmedLines[j]; - - // Count bare backticks lines - if (line.match(/^`+$/)) { - bareBackticksAhead++; - } else if (line.startsWith("```")) { - // Non-bare backticks (with language/type) always open - simulatedNestCount++; - } - - // Stop looking if we hit what appears to be the end of current markdown block - if (nestCount === 1) { - // At top level of markdown block - check for block terminators - if ( - line.startsWith("~~~") || - (line.startsWith("```") && headerIsMarkdown(line.replaceAll("`", ""))) - ) { - break; - } - } - } - - // The key insight: if we need the current backticks to close to get back to nestCount=1, - // and there are more bare backticks ahead than what we'd need to close everything, - // then this should open - - if (nestCount > 1) { - // We're deeply nested, usually should close - return bareBackticksAhead > nestCount - 1; - } - - // At top level (nestCount === 1), if there are exactly 2 ahead and we're at top level, - // this suggests: current=open, first_ahead=close, second_ahead=close_markdown - if (nestCount === 1 && bareBackticksAhead === 2) { - return true; - } - - // Default to the original logic - return bareBackticksAhead % 2 === 1; -} diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 30bd8fa1f..224ed18bf 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -8,7 +8,6 @@ Note, this was benchmarked at sub-millisecond */ import { headerIsMarkdown } from "./headerIsMarkdown"; -import { isOpeningNestedBlock } from "./isOpeningNestedBlock"; export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) @@ -25,19 +24,23 @@ export const patchNestedMarkdown = (source: string): string => { if (nestCount > 0) { // Inside a markdown block if (line.match(/^`+$/)) { - // Found bare backticks - determine if opening or closing - if (isOpeningNestedBlock(trimmedLines, i, nestCount)) { - // Opening a nested codeblock - nestCount++; - } else { - // Closing a block - nestCount--; - if (nestCount === 0) { - lines[i] = "~~~"; // End of markdown block + // Found bare backticks + // Count how many bare backticks are remaining after this one + let remainingBareBackticks = 0; + for (let j = i + 1; j < trimmedLines.length; j++) { + if (trimmedLines[j].match(/^`+$/)) { + remainingBareBackticks++; } } + + // If this is the last bare backticks, it closes the markdown block + if (remainingBareBackticks === 0) { + nestCount = 0; + lines[i] = "~~~"; // Convert final closing delimiter to tildes + } + // Otherwise, keep as backticks (inner nested block delimiter) } else if (line.startsWith("```")) { - // Going into a nested codeblock + // Going into a nested codeblock (with language identifier) nestCount++; } } else {