From b72fc0ea8f8dc0e1f88934e18b1b9ab5d34826ef Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 10 Jul 2025 18:47:06 +0200 Subject: [PATCH 01/26] fix: Send the process exit reason to Sentry + add OS info --- .../continue/IdeProtocolClient.kt | 1 - .../continue/IntelliJIde.kt | 1 - .../continue/process/ContinueBinaryProcess.kt | 9 ++++----- .../error/ContinueErrorService.kt | 12 +++++++++++- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 08a5e8d18..6b2da6179 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -13,7 +13,6 @@ import com.github.continuedev.continueintellijextension.utils.* import com.google.gson.Gson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileEditorManager diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 2dfc3e3e1..52161f2e3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -26,7 +26,6 @@ import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir -import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt index eb45cc4da..f10dd9d65 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.`continue`.process +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.services.TelemetryService import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath @@ -44,11 +45,8 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess { err = err.substring(doneIndex + delimiter.length) } } - - println("Core process exited with output: $err") - - val telemetryService = service() - telemetryService.capture("jetbrains_core_exit", mapOf("error" to err)) + service().reportMessage("Core process exited with output: $err") + service().capture("jetbrains_core_exit", mapOf("error" to err)) } private companion object { @@ -67,6 +65,7 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess { elevatePermissions() } + // todo: consider setting permissions ahead-of-time during build/packaging, not at runtime private fun elevatePermissions() { val path = getContinueBinaryPath() val permissions = setOf( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt index 21f920ef9..35e23d8a2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt @@ -6,6 +6,7 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId +import com.intellij.openapi.util.SystemInfo import com.intellij.ui.jcef.JBCefApp import io.sentry.Hint import io.sentry.Sentry @@ -26,6 +27,8 @@ class ContinueErrorService { config.setTag("ide_version", ApplicationInfo.getInstance().build.asString()) config.setTag("jcef_supported", JBCefApp.isSupported().toString()) config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version) + config.setTag("system", SystemInfo.OS_NAME) + config.setTag("system_version", SystemInfo.OS_VERSION) } } @@ -39,7 +42,14 @@ class ContinueErrorService { sentryEvent.message = Message().apply { this.message = message } val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) }) Sentry.captureEvent(sentryEvent, hint) - log.warn("Problem sent to Sentry: $message", throwable) + log.warn("Exception sent to Sentry: $message", throwable) + } + + fun reportMessage( + message: String, + ) { + Sentry.captureMessage(message) + log.warn("Message sent to Sentry: $message") } private companion object { From 00fc90badca92b6d03c40eb2e2e3462ba3213aaf Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 27 Jun 2025 16:00:29 -0700 Subject: [PATCH 02/26] fix: :bug: Project structure creation with bare codeblocks is breaking markdown display and creation --- .../utils/isOpeningNestedBlock.test.ts | 157 ++++++++++++++++++ .../utils/isOpeningNestedBlock.ts | 66 ++++++++ .../utils/patchNestedMarkdown.test.ts | 8 + .../utils/patchNestedMarkdown.ts | 15 +- 4 files changed, 242 insertions(+), 4 deletions(-) create mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts create mode 100644 gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts diff --git a/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts new file mode 100644 index 000000000..e5eb02f0c --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.test.ts @@ -0,0 +1,157 @@ +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 new file mode 100644 index 000000000..8327ed219 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/isOpeningNestedBlock.ts @@ -0,0 +1,66 @@ +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.test.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts index af94f118d..4e347a9e2 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts @@ -6,6 +6,14 @@ describe("patchNestedMarkdown", () => { expect(patchNestedMarkdown(source)).toBe(source); }); + it("should handle nested blocks without a type", () => { + const source = + "```markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n```"; + const expected = + "~~~markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n~~~"; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + it("should replace backticks with tildes for markdown codeblocks", () => { const source = "```markdown\n# Header\nSome text\n```"; const expected = "~~~markdown\n# Header\nSome text\n~~~"; diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 9be5bfbb2..30bd8fa1f 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -8,6 +8,7 @@ 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) @@ -24,10 +25,16 @@ export const patchNestedMarkdown = (source: string): string => { if (nestCount > 0) { // Inside a markdown block if (line.match(/^`+$/)) { - // Ending a block with just backticks (```) - nestCount--; - if (nestCount === 0) { - lines[i] = "~~~"; // End of markdown block + // 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 + } } } else if (line.startsWith("```")) { // Going into a nested codeblock From 9cd2f8b34b2ef814b2d1f386c024f993cc66274a Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 17:43:32 -0700 Subject: [PATCH 03/26] 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 { From 370b68ca1a12b777df43c7d5bf02207018f7e9d3 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 17:58:29 -0700 Subject: [PATCH 04/26] linting fixes --- .../filtering/streamTransforms/lineStream.ts | 185 +++++++++------ .../streamTransforms/lineStream.vitest.ts | 213 ++++++++++++++++++ 2 files changed, 335 insertions(+), 63 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index eabfca5a7..b603bc9ea 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -88,6 +88,118 @@ function isUselessLine(line: string): boolean { return hasUselessLine || trimmed.startsWith("// end"); } +/** + * Determines if a file is a markdown file based on its filepath. + */ +export function isMarkdownFile(filepath?: string): boolean { + if (!filepath) { + return false; + } + + return ["md", "markdown", "gfm"].includes( + filepath.split(".").pop()?.toLowerCase() || "", + ); +} + +/** + * Determines if the code block has nested markdown blocks. + */ +export function hasNestedMarkdownBlocks( + firstLine: string, + filepath?: string, +): boolean { + return ( + (firstLine.startsWith("```") && + headerIsMarkdown(firstLine.replace(/`/g, ""))) || + Boolean(filepath && headerIsMarkdown(filepath)) + ); +} + +/** + * Collects all lines from a LineStream into an array for analysis. + */ +export async function collectAllLines(rawLines: LineStream): Promise { + const allLines: string[] = []; + for await (const line of rawLines) { + allLines.push(line); + } + return allLines; +} + +/** + * Determines if we should stop at a markdown block based on nested markdown logic. + * This handles the complex case where markdown blocks contain other markdown blocks. + */ +export function shouldStopAtMarkdownBlock( + allLines: string[], + currentIndex: number, + hasNestedMarkdown: boolean, +): boolean { + if (!hasNestedMarkdown || allLines[currentIndex].trim() !== "```") { + return false; + } + + // 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 <= currentIndex; 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 currentIndex, stop + if (remainingBareBackticks === 0 && j === currentIndex) { + 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; + } + } + } + } + + return shouldStop; +} + +/** + * Processes block nesting logic and returns updated state. + */ +export function processBlockNesting( + line: string, + seenFirstFence: boolean, +): { newSeenFirstFence: boolean; shouldSkip: boolean } { + if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { + return { newSeenFirstFence: false, shouldSkip: true }; + } + + if (!seenFirstFence) { + return { newSeenFirstFence: true, shouldSkip: false }; + } + + return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; +} + export const USELESS_LINES = [""]; export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; export const CODE_STOP_BLOCK = "[/CODE]"; @@ -372,34 +484,22 @@ export async function* filterCodeBlockLines( // 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); - } + // Collect all lines for analysis + const allLines = await collectAllLines(rawLines); // Check if it has nested markdown blocks (like ```markdown or ```md) const firstLine = allLines[0] || ""; - const hasNestedMarkdown = - (firstLine.startsWith("```") && - headerIsMarkdown(firstLine.replace(/`/g, ""))) || - (filepath && headerIsMarkdown(filepath)); + const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); for (let i = 0; i < allLines.length; i++) { const line = allLines[i]; - if (!seenFirstFence) { - if (shouldRemoveLineBeforeStart(line)) { - // Filter out starting ``` or START block - continue; - } - // Regardless of a fence or START block start tracking the nesting level + // Process block nesting logic for the first fence + const nesting = processBlockNesting(line, seenFirstFence); + if (nesting.shouldSkip) { + continue; // Filter out starting ``` or START block + } + if (!seenFirstFence && nesting.newSeenFirstFence) { seenFirstFence = true; nestCount = 1; } @@ -412,48 +512,7 @@ export async function* filterCodeBlockLines( // 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) { + if (shouldStopAtMarkdownBlock(allLines, i, hasNestedMarkdown)) { return; // Stop without yielding the final closing ``` } else { // This is an inner block delimiter, yield it as content diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index f68447c39..c37e853b5 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -757,4 +757,217 @@ describe("lineStream", () => { expect(mockFullStop).toHaveBeenCalledTimes(1); }); }); + + // Tests for new helper functions + describe("isMarkdownFile", () => { + it("should return true for markdown file extensions", () => { + expect(lineStream.isMarkdownFile("README.md")).toBe(true); + expect(lineStream.isMarkdownFile("docs.markdown")).toBe(true); + expect(lineStream.isMarkdownFile("notes.gfm")).toBe(true); + expect(lineStream.isMarkdownFile("path/to/file.md")).toBe(true); + }); + + it("should return false for non-markdown file extensions", () => { + expect(lineStream.isMarkdownFile("script.js")).toBe(false); + expect(lineStream.isMarkdownFile("styles.css")).toBe(false); + expect(lineStream.isMarkdownFile("document.txt")).toBe(false); + expect(lineStream.isMarkdownFile("config.json")).toBe(false); + }); + + it("should return false for undefined or empty filepath", () => { + expect(lineStream.isMarkdownFile(undefined)).toBe(false); + expect(lineStream.isMarkdownFile("")).toBe(false); + }); + + it("should handle case insensitive extensions", () => { + expect(lineStream.isMarkdownFile("README.MD")).toBe(true); + expect(lineStream.isMarkdownFile("docs.MARKDOWN")).toBe(true); + expect(lineStream.isMarkdownFile("notes.GFM")).toBe(true); + }); + }); + + describe("hasNestedMarkdownBlocks", () => { + it("should detect nested markdown blocks from first line", () => { + expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe( + true, + ); + expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true); + expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe( + true, + ); + }); + + it("should detect nested markdown blocks from filepath", () => { + expect( + lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"), + ).toBe(true); + expect( + lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"), + ).toBe(true); + }); + + it("should return false for non-markdown scenarios", () => { + expect( + lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"), + ).toBe(false); + expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe( + false, + ); + expect( + lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined), + ).toBe(false); + }); + + it("should handle complex first line scenarios", () => { + expect( + lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined), + ).toBe(true); + expect( + lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined), + ).toBe(true); + }); + }); + + describe("collectAllLines", () => { + it("should collect all lines from a stream", async () => { + const linesGenerator = await getLineGenerator([ + "line1", + "line2", + "line3", + ]); + + const result = await lineStream.collectAllLines(linesGenerator); + + expect(result).toEqual(["line1", "line2", "line3"]); + }); + + it("should handle empty stream", async () => { + const linesGenerator = await getLineGenerator([]); + + const result = await lineStream.collectAllLines(linesGenerator); + + expect(result).toEqual([]); + }); + + it("should handle stream with empty lines", async () => { + const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]); + + const result = await lineStream.collectAllLines(linesGenerator); + + expect(result).toEqual(["", "line2", "", "line4"]); + }); + }); + + describe("shouldStopAtMarkdownBlock", () => { + it("should return false when hasNestedMarkdown is false", () => { + const allLines = ["```markdown", "content", "```"]; + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, false)).toBe( + false, + ); + }); + + it("should return false when current line is not closing backticks", () => { + const allLines = ["```markdown", "content", "more content"]; + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( + false, + ); + }); + + it("should handle simple nested markdown case", () => { + const allLines = ["```markdown", "# Title", "```"]; + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( + true, + ); + }); + + it("should handle complex nested markdown with inner code blocks", () => { + const allLines = [ + "```markdown", + "# Title", + "```javascript", + "console.log('hello');", + "```", + "```", + ]; + // At index 4 (first inner closing), should not stop + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( + false, + ); + // At index 5 (outer closing), should stop + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 5, true)).toBe( + true, + ); + }); + + it("should handle multiple bare backticks scenario", () => { + const allLines = [ + "```markdown", + "Content with ```inline code```", + "```", + "More content", + "```", + ]; + // At index 2, should not stop (not the last bare backticks) + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( + false, + ); + // At index 4, should stop (last bare backticks) + expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( + true, + ); + }); + }); + + describe("processBlockNesting", () => { + it("should skip lines that should be removed before start", () => { + const result = lineStream.processBlockNesting("```typescript", false); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + + it("should skip [CODE] blocks", () => { + const result = lineStream.processBlockNesting("[CODE]", false); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + + it("should set first fence when not seen yet", () => { + const result = lineStream.processBlockNesting("const x = 5;", false); + expect(result).toEqual({ + newSeenFirstFence: true, + shouldSkip: false, + }); + }); + + it("should not change state when first fence already seen", () => { + const result = lineStream.processBlockNesting("const x = 5;", true); + expect(result).toEqual({ + newSeenFirstFence: true, + shouldSkip: false, + }); + }); + + it("should handle prefix", () => { + const result = lineStream.processBlockNesting("", false); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + + it("should handle START EDITING HERE blocks", () => { + const result = lineStream.processBlockNesting( + "", + false, + ); + expect(result).toEqual({ + newSeenFirstFence: false, + shouldSkip: true, + }); + }); + }); }); From 49cf77997cfab9eccb0012a66f967f2684d762c4 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 22:02:36 -0700 Subject: [PATCH 05/26] performance enhancements --- .../filtering/streamTransforms/lineStream.ts | 131 ++++++---- .../streamTransforms/lineStream.vitest.ts | 228 ++++++++++++++++-- 2 files changed, 285 insertions(+), 74 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index b603bc9ea..b36d3e3a4 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -127,59 +127,82 @@ export async function collectAllLines(rawLines: LineStream): Promise { } /** - * Determines if we should stop at a markdown block based on nested markdown logic. - * This handles the complex case where markdown blocks contain other markdown blocks. + * State tracker for markdown block analysis to avoid recomputing on each call. */ -export function shouldStopAtMarkdownBlock( - allLines: string[], - currentIndex: number, - hasNestedMarkdown: boolean, -): boolean { - if (!hasNestedMarkdown || allLines[currentIndex].trim() !== "```") { - return false; - } +export class MarkdownBlockState { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + private markdownNestCount: number = 0; + private lastProcessedIndex: number = -1; - // 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 <= currentIndex; 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 currentIndex, stop - if (remainingBareBackticks === 0 && j === currentIndex) { - 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; - } + constructor(allLines: string[]) { + this.trimmedLines = allLines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); } } } - return shouldStop; + /** + * Determines if we should stop at the given markdown block position. + * Maintains state across calls to avoid redundant computation. + */ + shouldStopAtPosition(currentIndex: number): boolean { + if (this.trimmedLines[currentIndex] !== "```") { + return false; + } + + // Process any lines we haven't seen yet up to currentIndex + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { + const currentLine = this.trimmedLines[j]; + + if (this.markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - check if this is the last one + if (j === currentIndex) { + const remainingBareBackticks = this.bareBacktickPositions.filter( + (pos) => pos > j, + ).length; + if (remainingBareBackticks === 0) { + this.markdownNestCount = 0; + this.lastProcessedIndex = j; + return true; + } + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + this.markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + this.markdownNestCount = 1; + } + } + } + } + + this.lastProcessedIndex = currentIndex; + return false; + } +} + +/** + * Determines if we should stop at a markdown block based on nested markdown logic. + * This handles the complex case where markdown blocks contain other markdown blocks. + * Uses optimized state tracking to avoid redundant computation. + */ +export function shouldStopAtMarkdownBlock( + stateTracker: MarkdownBlockState, + currentIndex: number, +): boolean { + return stateTracker.shouldStopAtPosition(currentIndex); } /** @@ -491,6 +514,12 @@ export async function* filterCodeBlockLines( const firstLine = allLines[0] || ""; const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); + // Create optimized state tracker for markdown block analysis if needed + let markdownStateTracker: MarkdownBlockState | undefined; + if (hasNestedMarkdown) { + markdownStateTracker = new MarkdownBlockState(allLines); + } + for (let i = 0; i < allLines.length; i++) { const line = allLines[i]; @@ -511,8 +540,12 @@ export async function* filterCodeBlockLines( // Ending a block with just backticks (```) or STOP // For markdown files with nested markdown blocks, apply special logic - if (hasNestedMarkdown && line.trim() === "```") { - if (shouldStopAtMarkdownBlock(allLines, i, hasNestedMarkdown)) { + if ( + hasNestedMarkdown && + line.trim() === "```" && + markdownStateTracker + ) { + if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { return; // Stop without yielding the final closing ``` } else { // This is an inner block delimiter, yield it as content diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index c37e853b5..709b744d9 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -859,25 +859,16 @@ describe("lineStream", () => { }); describe("shouldStopAtMarkdownBlock", () => { - it("should return false when hasNestedMarkdown is false", () => { - const allLines = ["```markdown", "content", "```"]; - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, false)).toBe( - false, - ); - }); - it("should return false when current line is not closing backticks", () => { const allLines = ["```markdown", "content", "more content"]; - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( - false, - ); + const state = new lineStream.MarkdownBlockState(allLines); + expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); }); it("should handle simple nested markdown case", () => { const allLines = ["```markdown", "# Title", "```"]; - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( - true, - ); + const state = new lineStream.MarkdownBlockState(allLines); + expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(true); }); it("should handle complex nested markdown with inner code blocks", () => { @@ -889,14 +880,11 @@ describe("lineStream", () => { "```", "```", ]; + const state = new lineStream.MarkdownBlockState(allLines); // At index 4 (first inner closing), should not stop - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( - false, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(false); // At index 5 (outer closing), should stop - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 5, true)).toBe( - true, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 5)).toBe(true); }); it("should handle multiple bare backticks scenario", () => { @@ -907,14 +895,11 @@ describe("lineStream", () => { "More content", "```", ]; + const state = new lineStream.MarkdownBlockState(allLines); // At index 2, should not stop (not the last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 2, true)).toBe( - false, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); // At index 4, should stop (last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(allLines, 4, true)).toBe( - true, - ); + expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(true); }); }); @@ -970,4 +955,197 @@ describe("lineStream", () => { }); }); }); + + describe("MarkdownBlockState", () => { + it("should initialize with correct state", () => { + const allLines = ["```markdown", "content", "```", "more content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Test basic initialization - we can't directly test private properties, + // but we can test the behavior through shouldStopAtPosition + expect(state).toBeDefined(); + }); + + it("should correctly identify bare backticks positions", () => { + const allLines = ["```markdown", "```", "content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // At position 1 (first bare backticks), should not stop + expect(state.shouldStopAtPosition(1)).toBe(false); + // At position 3 (last bare backticks), should stop + expect(state.shouldStopAtPosition(3)).toBe(true); + }); + + it("should maintain state across multiple calls", () => { + const allLines = [ + "```markdown", + "# Title", + "```javascript", + "console.log('test');", + "```", + "More content", + "```", + ]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Process positions incrementally + expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block + expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block + expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block + }); + + it("should handle complex nesting scenarios efficiently", () => { + const allLines = [ + "```markdown", + "# Documentation", + "```typescript", + "interface Config {", + " name: string;", + "}", + "```", + "", + "```bash", + "npm install", + "```", + "", + "Final notes", + "```", + ]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Test multiple positions in sequence + expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block + expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block + expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block + }); + + it("should handle non-backtick lines correctly", () => { + const allLines = ["```markdown", "regular content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // Position 1 is not backticks, should return false + expect(state.shouldStopAtPosition(1)).toBe(false); + }); + + it("should handle empty lines and edge cases", () => { + const allLines = ["```markdown", "", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line + expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks + }); + + it("should reset nest count when reaching final bare backticks", () => { + const allLines = ["```markdown", "content", "```"]; + const state = new lineStream.MarkdownBlockState(allLines); + + // First call should stop and reset count + expect(state.shouldStopAtPosition(2)).toBe(true); + + // If we had more content, it should start fresh + // (This tests the internal state management) + }); + }); + + describe("shouldStopAtMarkdownBlock optimization", () => { + it("should maintain performance benefits with state reuse", () => { + const allLines = Array.from({ length: 100 }, (_, i) => { + if (i === 0) return "```markdown"; + if (i === 99) return "```"; + if (i % 10 === 0) return "```javascript"; + if (i % 10 === 5) return "```"; + return `line ${i}`; + }); + + const state = new lineStream.MarkdownBlockState(allLines); + + // Test that we can call multiple times without recomputing everything + const start = performance.now(); + + // Test several positions in sequence + for (let i = 10; i < 90; i += 10) { + if (allLines[i].trim() === "```") { + lineStream.shouldStopAtMarkdownBlock(state, i); + } + } + + const duration = performance.now() - start; + expect(duration).toBeLessThan(10); // Should be very fast due to state caching + }); + }); + + describe("filterCodeBlockLines with optimized MarkdownBlockState", () => { + it("should use optimized state tracker for markdown files", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown", + "# Documentation", + "```typescript", + "const config = { name: 'test' };", + "```", + "Final notes", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "README.md", + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "# Documentation", + "```typescript", + "const config = { name: 'test' };", + "```", + "Final notes", + ]); + }); + + it("should fall back to legacy behavior when no markdown nesting detected", async () => { + const linesGenerator = await getLineGenerator([ + "```typescript", + "const x = 5;", + "```", + ]); + + const result = lineStream.filterCodeBlockLines( + linesGenerator, + "script.ts", + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should handle mixed markdown and code scenarios with optimization", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "## API Reference", + "", + "```javascript", + "async function fetchData() {", + " return await fetch('/api/data');", + "}", + "```", + "", + "Usage notes and more documentation.", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "## API Reference", + "", + "```javascript", + "async function fetchData() {", + " return await fetch('/api/data');", + "}", + "```", + "", + "Usage notes and more documentation.", + ]); + }); + }); }); From 0a29810ee038d4494664e664563d9d3f5a3dc003 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 30 Jun 2025 22:19:51 -0700 Subject: [PATCH 06/26] add checks to avoid stopping prematurely on stop constants --- .../filtering/streamTransforms/lineStream.ts | 87 +++++++++++- .../streamTransforms/lineStream.vitest.ts | 134 ++++++++++++++++++ 2 files changed, 218 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index b36d3e3a4..a674c7d1b 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -67,13 +67,47 @@ function shouldRemoveLineBeforeStart(line: string): boolean { ); } -function shouldChangeLineAndStop(line: string): string | undefined { +export function shouldChangeLineAndStop(line: string): string | undefined { if (line.trimStart() === "```") { return line; } + // Check if [/CODE] appears in the line if (line.includes(CODE_STOP_BLOCK)) { - return line.split(CODE_STOP_BLOCK)[0].trimEnd(); + const stopBlockIndex = line.indexOf(CODE_STOP_BLOCK); + + // Check if [/CODE] is preceded by a non-whitespace character + // If so, it might be part of an identifier, so don't handle it + if (stopBlockIndex > 0) { + const charBefore = line[stopBlockIndex - 1]; + if (charBefore && !charBefore.match(/\s/)) { + return undefined; // Don't handle [/CODE] that's part of an identifier + } + } + + // Check if [/CODE] appears to be inside quotes + // Simple heuristic: count unmatched quotes before the stop block + const beforeStopBlock = line.substring(0, stopBlockIndex); + const singleQuotes = (beforeStopBlock.match(/'/g) || []).length; + const doubleQuotes = (beforeStopBlock.match(/"/g) || []).length; + + // If there's an odd number of quotes before [/CODE], we're likely inside quotes + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { + return undefined; // Don't handle [/CODE] inside quotes + } + + // Get the trimmed line to check if [/CODE] is at logical start + const trimmedLine = line.trimStart(); + + if (trimmedLine.startsWith(CODE_STOP_BLOCK)) { + // [/CODE] is at the logical start (after whitespace only) + if (trimmedLine === CODE_STOP_BLOCK) { + return line; // Return the whole line including leading whitespace + } + } + + // [/CODE] appears after some content (separated by whitespace) - return part before + return beforeStopBlock.trimEnd(); } return undefined; @@ -413,7 +447,54 @@ export async function* stopAtLines( linesToStopAt: string[] = LINES_TO_STOP_AT, ): LineStream { for await (const line of stream) { - if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) { + let shouldStop = false; + + // Check each stop phrase + for (const stopAt of linesToStopAt) { + if (line.includes(stopAt)) { + const stopAtIndex = line.indexOf(stopAt); + + // Check if stop phrase is preceded by a non-whitespace character + // If so, it might be part of an identifier, so don't handle it + if (stopAtIndex > 0) { + const charBefore = line[stopAtIndex - 1]; + if (charBefore && !charBefore.match(/\s/)) { + continue; // Don't handle stop phrase that's part of an identifier + } + } + + // Check if stop phrase appears to be inside quotes + // Simple heuristic: count unmatched quotes before the stop phrase + const beforeStopPhrase = line.substring(0, stopAtIndex); + const singleQuotes = (beforeStopPhrase.match(/'/g) || []).length; + const doubleQuotes = (beforeStopPhrase.match(/"/g) || []).length; + + // If there's an odd number of quotes before stop phrase, we're likely inside quotes + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { + continue; // Don't handle stop phrase inside quotes + } + + // Get the trimmed line to check if stop phrase is at logical start + const trimmedLine = line.trimStart(); + + if (trimmedLine.startsWith(stopAt)) { + // Stop phrase is at the logical start (after whitespace only) - should stop + shouldStop = true; + break; + } else { + // Stop phrase appears after some content - check if it's separated by whitespace + const contentBeforeStopPhrase = beforeStopPhrase.trimEnd(); + if (contentBeforeStopPhrase.length < beforeStopPhrase.length) { + // There's whitespace before the stop phrase, so it's properly separated + shouldStop = true; + break; + } + // If no whitespace separation, it's part of larger text, so continue + } + } + } + + if (shouldStop) { fullStop(); break; } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 709b744d9..ff137f442 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -174,6 +174,93 @@ describe("lineStream", () => { expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); expect(mockFullStop).toHaveBeenCalledTimes(1); }); + + it("should stop at lines with leading whitespace", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + ` ${lineStream.LINES_TO_STOP_AT[0]}`, + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should NOT stop when stop phrase is inside quotes", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + 'console.log("# End of file. not really");', + "let y = 10;", + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + // Should not stop, should yield all lines + expect(filteredLines).toEqual([ + "const x = 5;", + 'console.log("# End of file. not really");', + "let y = 10;", + "const z = 15;", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + + it("should NOT stop when stop phrase is inside single quotes", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "const message = '# End of file. not really';", + "let y = 10;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "const message = '# End of file. not really';", + "let y = 10;", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + + it("should NOT stop when stop phrase is part of larger text", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "// This function stopsafter processing", + "let y = 10;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "// This function stopsafter processing", + "let y = 10;", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + + it("should stop when stop phrase appears properly at start of content", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + "# End of file. Done here", + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); }); describe("skipPrefixes", () => { @@ -903,6 +990,53 @@ describe("lineStream", () => { }); }); + describe("shouldChangeLineAndStop", () => { + it("should handle [/CODE] at start of line", () => { + const result = lineStream.shouldChangeLineAndStop("[/CODE]"); + expect(result).toBe("[/CODE]"); + }); + + it("should handle [/CODE] with leading whitespace", () => { + const result = lineStream.shouldChangeLineAndStop(" [/CODE]"); + expect(result).toBe(" [/CODE]"); + }); + + it("should return partial line before [/CODE] when at start/after whitespace", () => { + const result = lineStream.shouldChangeLineAndStop( + "some code [/CODE] more text", + ); + expect(result).toBe("some code"); + }); + + it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => { + // This test demonstrates the current bug - it WILL fail initially + const result = lineStream.shouldChangeLineAndStop( + 'console.log("test [/CODE] end");', + ); + expect(result).toBeUndefined(); // Should not trigger stopping + }); + + it("should NOT trigger on [/CODE] in middle of identifier", () => { + // Another case that shows the bug + const result = lineStream.shouldChangeLineAndStop( + 'const var[/CODE]Name = "test";', + ); + expect(result).toBeUndefined(); // Should not trigger stopping + }); + + it("should handle ``` with trimStart correctly", () => { + const result = lineStream.shouldChangeLineAndStop(" ```"); + expect(result).toBe(" ```"); + }); + + it("should NOT handle ``` in middle of line", () => { + const result = lineStream.shouldChangeLineAndStop( + 'console.log("test ``` end");', + ); + expect(result).toBeUndefined(); + }); + }); + describe("processBlockNesting", () => { it("should skip lines that should be removed before start", () => { const result = lineStream.processBlockNesting("```typescript", false); From 938b7506cf73dfda8f794e9fab0a713e5c7a682a Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 2 Jul 2025 14:21:16 -0700 Subject: [PATCH 07/26] Optimize for more tests and nova --- .../streamTransforms/filterCodeBlock.ts | 139 ++++++ .../filterCodeBlock.vitest.ts | 452 ++++++++++++++++++ .../filtering/streamTransforms/lineStream.ts | 96 +--- core/edit/lazy/streamLazyApply.ts | 80 +++- core/llm/autodetect.ts | 3 +- .../utils/patchNestedMarkdown.ts | 50 +- 6 files changed, 707 insertions(+), 113 deletions(-) create mode 100644 core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts create mode 100644 core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts new file mode 100644 index 000000000..28af7d372 --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts @@ -0,0 +1,139 @@ +import { LineStream } from "../../../diff/util"; + +import { + collectAllLines, + hasNestedMarkdownBlocks, + MarkdownBlockState, + processBlockNesting, + shouldChangeLineAndStop, + shouldStopAtMarkdownBlock, +} from "./lineStream"; + +/** + * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. + * Now includes markdown-aware processing to handle nested markdown blocks properly. + * + * @param {LineStream} rawLines - The input stream of lines to filter. + * @param {string} filepath - Optional filepath to determine if this is a markdown file. + * @yields {string} Filtered and processed lines from the code block. + * + * @description + * This generator function performs the following tasks: + * 1. Removes initial lines that should be removed before the actual code starts. + * 2. For markdown files, applies nested markdown block logic to avoid premature termination. + * 3. For mixed content, uses simplified processing to avoid premature termination. + * 4. For traditional code blocks, uses original logic. + * 5. Yields processed lines that are part of the actual code block content. + */ +export async function* filterCodeBlockLines( + rawLines: LineStream, + filepath?: string, +): LineStream { + // Collect all lines for analysis + const allLines = await collectAllLines(rawLines); + + // Check if it has nested markdown blocks (like ```markdown or ```md) + const firstLine = allLines[0] || ""; + const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); + + // TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks) + // But exclude cases where we have nested markdown blocks + const hasMarkdownHeaders = allLines.some( + (line) => line.trim().startsWith("#") && !line.trim().startsWith("```"), + ); + + const hasCodeBlocks = allLines.some( + (line) => line.trim().startsWith("```") && line.trim().length >= 3, + ); + const isMixedContent = + hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown; + + // If this is mixed content, use simplified processing + if (isMixedContent) { + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]; + + // Skip initial wrapper lines if they exist + if (i === 0 && shouldRemoveLineBeforeStart(line)) { + continue; + } + + yield line; + } + return; + } + + // Original logic for non-mixed content + let seenFirstFence = false; + let nestCount = 0; + + // Create optimized state tracker for markdown block analysis if needed + let markdownStateTracker: MarkdownBlockState | undefined; + if (hasNestedMarkdown) { + markdownStateTracker = new MarkdownBlockState(allLines); + } + + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]; + + // Process block nesting logic for the first fence + const nesting = processBlockNesting(line, seenFirstFence); + if (nesting.shouldSkip) { + continue; // Filter out starting ``` or START block + } + if (!seenFirstFence && nesting.newSeenFirstFence) { + seenFirstFence = true; + nestCount = 1; + } + + if (nestCount > 0) { + // Inside a block including the outer block + const changedEndLine = shouldChangeLineAndStop(line); + if (typeof changedEndLine === "string") { + // Ending a block with just backticks (```) or STOP + + // For markdown files with nested markdown blocks, apply special logic + if ( + hasNestedMarkdown && + line.trim() === "```" && + markdownStateTracker + ) { + if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { + return; // Stop without yielding the final closing ``` + } else { + // This is an inner block delimiter, yield it as content + yield line; + continue; + } + } + + // Original logic for non-markdown files or simple cases + nestCount--; + if (nestCount === 0) { + // We've closed the outer wrapper - stop without yielding the closing ``` + return; + } else { + // This is a nested block closing, yield it as content + yield line; + } + } else if (line.startsWith("```")) { + // Going into a nested codeblock + nestCount++; + yield line; + } else { + // Otherwise just yield the line as content + yield line; + } + } + } +} + +function shouldRemoveLineBeforeStart(line: string): boolean { + return ( + line.trimStart().startsWith("```") || + line.trim() === "[CODE]" || + line.trim() === "" || + line.trim() === "" || + line.trim() === "{{FILL_HERE}}" + ); +} diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts new file mode 100644 index 000000000..78936a28c --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.vitest.ts @@ -0,0 +1,452 @@ +// eslint-disable-next-line max-lines-per-function +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; + +import * as lineStream from "./lineStream"; + +describe("filterCodeBlock", () => { + let mockFullStop: Mock; + + async function getLineGenerator(lines: any) { + return (async function* () { + for (const line of lines) { + yield line; + } + })(); + } + + async function getFilteredLines(results: any) { + const output = []; + + for await (const line of results) { + output.push(line); + } + + return output; + } + + beforeEach(() => { + mockFullStop = vi.fn(); + }); + + it("should handle unfenced code", async () => { + const linesGenerator = await getLineGenerator(["const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should handle unfenced code with a code block", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "```bash", + "ls -al", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + it("should handle unfenced code with a complex code block", async () => { + const linesGenerator = await getLineGenerator([ + "# Manual Testing Sandbox", + "", + "## Project Structure", + "", + "```", + "manual-testing-sandbox/", + "├── readme.md # Project documentation", + "├── package.json # Node.js dependencies and scripts", + "├── tsconfig.json # TypeScript configuration", + "├── jest.config.js # Jest testing configuration", + "├── requirements.txt # Python dependencies", + "├── Dockerfile # Docker container configuration", + "├── data.json # Sample JSON data", + "├── example.ipynb # Jupyter notebook example", + "│", + "├── src/ # Source code directory", + "│ ├── example.ts # TypeScript example", + "│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter", + "│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter", + "│ ├── MarkdownProcessor.ts # Markdown processing utility", + "│ └── MarkdownProcessor.test.ts # Tests for Markdown processor", + "│", + "├── react-calculator/ # React calculator application", + "├── calculator_test/ # Java calculator implementation", + "│ ├── Calculator.java # Calculator class", + "│ └── Main.java # Main application entry", + "│", + "├── nested-folder/ # Nested project example", + "│ ├── helloNested.py # Python script", + "│ ├── package.json # Nested package configuration", + "│ └── rules.md # Documentation", + "│", + "├── coverage/ # Test coverage reports", + "├── logs/ # Application logs", + "│", + "└── Test Files # Various language examples", + " ├── AdvancedPage.tsx # React TypeScript component", + " ├── Calculator.java # Java calculator", + " ├── program.cs # C# program", + " ├── query.sql # SQL query example", + " ├── test.css # CSS styles", + " ├── test.html # HTML page", + " ├── test.js # JavaScript code", + " ├── test.kt # Kotlin example", + " ├── test.php # PHP script", + " ├── test.py # Python script", + " ├── test.rb # Ruby script", + " ├── test.rs # Rust code", + " ├── test.sh # Shell script", + " └── test.ts # TypeScript code", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "# Manual Testing Sandbox", + "", + "## Project Structure", + "", + "```", + "manual-testing-sandbox/", + "├── readme.md # Project documentation", + "├── package.json # Node.js dependencies and scripts", + "├── tsconfig.json # TypeScript configuration", + "├── jest.config.js # Jest testing configuration", + "├── requirements.txt # Python dependencies", + "├── Dockerfile # Docker container configuration", + "├── data.json # Sample JSON data", + "├── example.ipynb # Jupyter notebook example", + "│", + "├── src/ # Source code directory", + "│ ├── example.ts # TypeScript example", + "│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter", + "│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter", + "│ ├── MarkdownProcessor.ts # Markdown processing utility", + "│ └── MarkdownProcessor.test.ts # Tests for Markdown processor", + "│", + "├── react-calculator/ # React calculator application", + "├── calculator_test/ # Java calculator implementation", + "│ ├── Calculator.java # Calculator class", + "│ └── Main.java # Main application entry", + "│", + "├── nested-folder/ # Nested project example", + "│ ├── helloNested.py # Python script", + "│ ├── package.json # Nested package configuration", + "│ └── rules.md # Documentation", + "│", + "├── coverage/ # Test coverage reports", + "├── logs/ # Application logs", + "│", + "└── Test Files # Various language examples", + " ├── AdvancedPage.tsx # React TypeScript component", + " ├── Calculator.java # Java calculator", + " ├── program.cs # C# program", + " ├── query.sql # SQL query example", + " ├── test.css # CSS styles", + " ├── test.html # HTML page", + " ├── test.js # JavaScript code", + " ├── test.kt # Kotlin example", + " ├── test.php # PHP script", + " ├── test.py # Python script", + " ├── test.rb # Ruby script", + " ├── test.rs # Rust code", + " ├── test.sh # Shell script", + " └── test.ts # TypeScript code", + "```", + ]); + }); + + it("should handle unfenced code with two code blocks", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "```bash", + "ls -al", + "```", + "```bash", + "ls -al", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "```bash", + "ls -al", + "```", + "```bash", + "ls -al", + "```", + ]); + }); + + it("should remove lines before the first valid line", async () => { + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should remove outer blocks", async () => { + const linesGenerator = await getLineGenerator([ + "```ts", + "const x = 5;", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should leave inner blocks intact", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "ls -al", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + it("should ignore ticks inside of code blocks such as tests", async () => { + const linesGenerator = await getLineGenerator([ + "```typescript", + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + 'it("should handle included inner ticks", async () => {', + " const linesGenerator = await getLineGenerator([`", + ' "```md"', + ' "const x = 5;"', + ' "```bash"', + ' "echo ```test```"', + ' "```"', + ' "```"', + "]);", + ]); + }); + + it("should handle included inner ticks", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "echo ```test```", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "```bash", + "echo ```test```", + "```", + ]); + }); + + it("should leave single inner blocks intact but not return trailing text", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "ls -al", + "```", + "```", + "trailing text", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + it("should leave double inner blocks intact but not return trailing text", async () => { + const linesGenerator = await getLineGenerator([ + "```md", + "const x = 5;", + "```bash", + "ls -al", + "```", + "const y = 10;", + "```sh", + "echo `hello world`", + "```", + "```", + "trailing text", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "```bash", + "ls -al", + "```", + "const y = 10;", + "```sh", + "echo `hello world`", + "```", + ]); + }); + + it("should leave inner blocks intact but not return trailing or leading text", async () => { + const linesGenerator = await getLineGenerator([ + "[CODE]", + "const x = 5;", + "```bash", + "ls -al", + "```", + "[/CODE]", + "trailing text", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]); + }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is included", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md"); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + // Markdown-aware tests + it("should handle markdown files with nested code blocks and a filename is excluded", async () => { + const linesGenerator = await getLineGenerator([ + "```markdown README.md", + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + // Should include all content up to the final closing ``` + expect(filteredLines).toEqual([ + "# Project Structure", + "", + "```", + "debug-test-folder/", + "├── AdvancedPage.tsx", + "├── Calculator.java", + "└── test.ts", + "```", + ]); + }); + + it("should handle non-markdown files normally with filepath parameter", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "function test() {", + " return 'hello';", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js"); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "function test() {", + " return 'hello';", + "}", + ]); + }); + + it("should handle simple markdown code blocks", async () => { + const linesGenerator = await getLineGenerator([ + "```", + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + + const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md"); + const filteredLines = await getFilteredLines(result); + + // Should remove the outer markdown wrapper, and return just the inner content. + // The lack of an end tag should cause it to return all remaining lines. + expect(filteredLines).toEqual([ + "Here's some code:", + "```", + "function example() {", + " console.log('test');", + "}", + "```", + ]); + }); +}); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index a674c7d1b..182990fef 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -3,6 +3,8 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +export { filterCodeBlockLines } from "./filterCodeBlock"; + export type LineFilter = (args: { lines: LineStream; fullStop: () => void; @@ -562,100 +564,6 @@ 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. 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, - 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 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; - - // Collect all lines for analysis - const allLines = await collectAllLines(rawLines); - - // Check if it has nested markdown blocks (like ```markdown or ```md) - const firstLine = allLines[0] || ""; - const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath); - - // Create optimized state tracker for markdown block analysis if needed - let markdownStateTracker: MarkdownBlockState | undefined; - if (hasNestedMarkdown) { - markdownStateTracker = new MarkdownBlockState(allLines); - } - - for (let i = 0; i < allLines.length; i++) { - const line = allLines[i]; - - // Process block nesting logic for the first fence - const nesting = processBlockNesting(line, seenFirstFence); - if (nesting.shouldSkip) { - continue; // Filter out starting ``` or START block - } - if (!seenFirstFence && nesting.newSeenFirstFence) { - seenFirstFence = true; - nestCount = 1; - } - - if (nestCount > 0) { - // Inside a block including the outer block - const changedEndLine = shouldChangeLineAndStop(line); - if (typeof changedEndLine === "string") { - // Ending a block with just backticks (```) or STOP - - // For markdown files with nested markdown blocks, apply special logic - if ( - hasNestedMarkdown && - line.trim() === "```" && - markdownStateTracker - ) { - if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) { - return; // Stop without yielding the final closing ``` - } else { - // This is an inner block delimiter, yield it as content - yield line; - continue; - } - } - - // Original logic for non-markdown files or simple cases - nestCount--; - if (nestCount === 0) { - // We've closed the outer wrapper - stop without yielding the closing ``` - return; - } else { - // This is a nested block closing, yield it as content - yield line; - } - } else if (line.startsWith("```")) { - // Going into a nested codeblock - nestCount++; - yield line; - } else { - // Otherwise just yield the line as content - yield line; - } - } - } -} - /** * Filters out English explanations at the start of a code block. * diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 1186ca6de..4aa746e79 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -31,6 +31,73 @@ function isMarkdownFile(filename: string): boolean { return ["md", "markdown", "gfm"].includes(ext || ""); } +/** + * Optimized state tracker for markdown block analysis to avoid recomputing on each call. + */ +class MarkdownBlockStateTracker { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + private markdownNestCount: number = 0; + private lastProcessedIndex: number = -1; + + constructor(allLines: string[]) { + this.trimmedLines = allLines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); + } + } + } + + /** + * Determines if we should stop at the given markdown block position. + * Maintains state across calls to avoid redundant computation. + */ + shouldStopAtPosition(currentIndex: number): boolean { + if (this.trimmedLines[currentIndex] !== "```") { + return false; + } + + // Process any lines we haven't seen yet up to currentIndex + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { + const currentLine = this.trimmedLines[j]; + + if (this.markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - check if this is the last one + if (j === currentIndex) { + const remainingBareBackticks = this.bareBacktickPositions.filter( + (pos) => pos > j, + ).length; + if (remainingBareBackticks === 0) { + this.markdownNestCount = 0; + this.lastProcessedIndex = j; + return true; + } + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + this.markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + this.markdownNestCount = 1; + } + } + } + } + + this.lastProcessedIndex = currentIndex; + return false; + } +} + async function* stopAtLinesWithMarkdownSupport( lines: LineStream, filename: string, @@ -64,6 +131,8 @@ async function* stopAtLinesWithMarkdownSupport( return; } + // Use optimized state tracker for markdown block analysis + const stateTracker = new MarkdownBlockStateTracker(allLines); let nestCount = 0; const trimmedLines = allLines.map((l) => l.trim()); @@ -72,15 +141,8 @@ async function* stopAtLinesWithMarkdownSupport( 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; + // Use optimized state tracker for markdown block logic + if (stateTracker.shouldStopAtPosition(i)) { for (let j = 0; j < i; j++) { yield allLines[j]; } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index a220b5dbd..df575bfed 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -400,5 +400,6 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools, + modelSupportsTools }; + diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 224ed18bf..562c70086 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -9,6 +9,40 @@ */ import { headerIsMarkdown } from "./headerIsMarkdown"; +/** + * Optimized state tracker for markdown patch operations to avoid recomputing on each call. + */ +class MarkdownPatchStateTracker { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + + constructor(lines: string[]) { + this.trimmedLines = lines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); + } + } + } + + /** + * Efficiently determines if there are remaining bare backticks after the given position. + */ + getRemainingBareBackticksAfter(currentIndex: number): number { + return this.bareBacktickPositions.filter((pos) => pos > currentIndex) + .length; + } + + /** + * Checks if the line at the given index is a bare backtick line. + */ + isBareBacktickLine(index: number): boolean { + return this.bareBacktickPositions.includes(index); + } +} + export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) @@ -18,20 +52,18 @@ export const patchNestedMarkdown = (source: string): string => { const lines = source.split("\n"); const trimmedLines = lines.map((l) => l.trim()); + // Use optimized state tracker for efficient bare backtick analysis + const stateTracker = new MarkdownPatchStateTracker(lines); + for (let i = 0; i < trimmedLines.length; i++) { const line = trimmedLines[i]; if (nestCount > 0) { // Inside a markdown block - if (line.match(/^`+$/)) { - // 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 (stateTracker.isBareBacktickLine(i)) { + // Found bare backticks - use optimized lookup for remaining count + const remainingBareBackticks = + stateTracker.getRemainingBareBackticksAfter(i); // If this is the last bare backticks, it closes the markdown block if (remainingBareBackticks === 0) { From f6d6c4fb81dd81eddd68691fb9fcc4c54539649e Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 4 Jul 2025 13:57:49 -0700 Subject: [PATCH 08/26] deduplicate code --- .../filtering/streamTransforms/lineStream.ts | 156 +++-------------- .../streamTransforms/lineStream.vitest.ts | 79 --------- core/edit/lazy/streamLazyApply.ts | 159 +----------------- core/utils/markdownUtils.ts | 113 +++++++++++++ core/utils/markdownUtils.vitest.ts | 80 +++++++++ core/utils/streamMarkdownUtils.ts | 122 ++++++++++++++ core/utils/streamMarkdownUtils.vitest.ts | 102 +++++++++++ 7 files changed, 441 insertions(+), 370 deletions(-) create mode 100644 core/utils/markdownUtils.ts create mode 100644 core/utils/markdownUtils.vitest.ts create mode 100644 core/utils/streamMarkdownUtils.ts create mode 100644 core/utils/streamMarkdownUtils.vitest.ts diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 182990fef..70ef1d20e 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -3,6 +3,17 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +import { + headerIsMarkdown, + isMarkdownFile, + MarkdownBlockStateTracker, + collectAllLines, +} from "../../../utils/markdownUtils"; +import { + shouldStopAtMarkdownBlock, + processBlockNesting as processBlockNestingUtil, +} from "../../../utils/streamMarkdownUtils"; + export { filterCodeBlockLines } from "./filterCodeBlock"; export type LineFilter = (args: { @@ -18,23 +29,6 @@ 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() @@ -124,19 +118,6 @@ function isUselessLine(line: string): boolean { return hasUselessLine || trimmed.startsWith("// end"); } -/** - * Determines if a file is a markdown file based on its filepath. - */ -export function isMarkdownFile(filepath?: string): boolean { - if (!filepath) { - return false; - } - - return ["md", "markdown", "gfm"].includes( - filepath.split(".").pop()?.toLowerCase() || "", - ); -} - /** * Determines if the code block has nested markdown blocks. */ @@ -147,116 +128,25 @@ export function hasNestedMarkdownBlocks( return ( (firstLine.startsWith("```") && headerIsMarkdown(firstLine.replace(/`/g, ""))) || - Boolean(filepath && headerIsMarkdown(filepath)) + Boolean(filepath && isMarkdownFile(filepath)) ); } -/** - * Collects all lines from a LineStream into an array for analysis. - */ -export async function collectAllLines(rawLines: LineStream): Promise { - const allLines: string[] = []; - for await (const line of rawLines) { - allLines.push(line); - } - return allLines; -} +// Re-export shared utilities +export { collectAllLines, isMarkdownFile }; +export { MarkdownBlockStateTracker as MarkdownBlockState }; +export { shouldStopAtMarkdownBlock }; -/** - * State tracker for markdown block analysis to avoid recomputing on each call. - */ -export class MarkdownBlockState { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; - private markdownNestCount: number = 0; - private lastProcessedIndex: number = -1; - - constructor(allLines: string[]) { - this.trimmedLines = allLines.map((l) => l.trim()); - // Pre-compute positions of all bare backtick lines for faster lookup - this.bareBacktickPositions = []; - for (let i = 0; i < this.trimmedLines.length; i++) { - if (this.trimmedLines[i].match(/^`+$/)) { - this.bareBacktickPositions.push(i); - } - } - } - - /** - * Determines if we should stop at the given markdown block position. - * Maintains state across calls to avoid redundant computation. - */ - shouldStopAtPosition(currentIndex: number): boolean { - if (this.trimmedLines[currentIndex] !== "```") { - return false; - } - - // Process any lines we haven't seen yet up to currentIndex - for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { - const currentLine = this.trimmedLines[j]; - - if (this.markdownNestCount > 0) { - // Inside a markdown block - if (currentLine.match(/^`+$/)) { - // Found bare backticks - check if this is the last one - if (j === currentIndex) { - const remainingBareBackticks = this.bareBacktickPositions.filter( - (pos) => pos > j, - ).length; - if (remainingBareBackticks === 0) { - this.markdownNestCount = 0; - this.lastProcessedIndex = j; - return true; - } - } - } else if (currentLine.startsWith("```")) { - // Going into a nested codeblock - this.markdownNestCount++; - } - } else { - // Not inside a markdown block yet - if (currentLine.startsWith("```")) { - const header = currentLine.replaceAll("`", ""); - if (headerIsMarkdown(header)) { - this.markdownNestCount = 1; - } - } - } - } - - this.lastProcessedIndex = currentIndex; - return false; - } -} - -/** - * Determines if we should stop at a markdown block based on nested markdown logic. - * This handles the complex case where markdown blocks contain other markdown blocks. - * Uses optimized state tracking to avoid redundant computation. - */ -export function shouldStopAtMarkdownBlock( - stateTracker: MarkdownBlockState, - currentIndex: number, -): boolean { - return stateTracker.shouldStopAtPosition(currentIndex); -} - -/** - * Processes block nesting logic and returns updated state. - */ +// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function export function processBlockNesting( line: string, seenFirstFence: boolean, ): { newSeenFirstFence: boolean; shouldSkip: boolean } { - if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { - return { newSeenFirstFence: false, shouldSkip: true }; - } - - if (!seenFirstFence) { - return { newSeenFirstFence: true, shouldSkip: false }; - } - - return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; + return processBlockNestingUtil( + line, + seenFirstFence, + shouldRemoveLineBeforeStart, + ); } export const USELESS_LINES = [""]; @@ -326,7 +216,7 @@ export async function* avoidPathLine( // Sometimes the model with copy this pattern, which is unwanted for await (const line of stream) { if (line.startsWith(`${comment} Path: `)) { - continue; + continue; // continue in the Continue codebase! How meta! } yield line; } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index ff137f442..1cd569ae4 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -846,32 +846,6 @@ describe("lineStream", () => { }); // Tests for new helper functions - describe("isMarkdownFile", () => { - it("should return true for markdown file extensions", () => { - expect(lineStream.isMarkdownFile("README.md")).toBe(true); - expect(lineStream.isMarkdownFile("docs.markdown")).toBe(true); - expect(lineStream.isMarkdownFile("notes.gfm")).toBe(true); - expect(lineStream.isMarkdownFile("path/to/file.md")).toBe(true); - }); - - it("should return false for non-markdown file extensions", () => { - expect(lineStream.isMarkdownFile("script.js")).toBe(false); - expect(lineStream.isMarkdownFile("styles.css")).toBe(false); - expect(lineStream.isMarkdownFile("document.txt")).toBe(false); - expect(lineStream.isMarkdownFile("config.json")).toBe(false); - }); - - it("should return false for undefined or empty filepath", () => { - expect(lineStream.isMarkdownFile(undefined)).toBe(false); - expect(lineStream.isMarkdownFile("")).toBe(false); - }); - - it("should handle case insensitive extensions", () => { - expect(lineStream.isMarkdownFile("README.MD")).toBe(true); - expect(lineStream.isMarkdownFile("docs.MARKDOWN")).toBe(true); - expect(lineStream.isMarkdownFile("notes.GFM")).toBe(true); - }); - }); describe("hasNestedMarkdownBlocks", () => { it("should detect nested markdown blocks from first line", () => { @@ -1037,59 +1011,6 @@ describe("lineStream", () => { }); }); - describe("processBlockNesting", () => { - it("should skip lines that should be removed before start", () => { - const result = lineStream.processBlockNesting("```typescript", false); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - - it("should skip [CODE] blocks", () => { - const result = lineStream.processBlockNesting("[CODE]", false); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - - it("should set first fence when not seen yet", () => { - const result = lineStream.processBlockNesting("const x = 5;", false); - expect(result).toEqual({ - newSeenFirstFence: true, - shouldSkip: false, - }); - }); - - it("should not change state when first fence already seen", () => { - const result = lineStream.processBlockNesting("const x = 5;", true); - expect(result).toEqual({ - newSeenFirstFence: true, - shouldSkip: false, - }); - }); - - it("should handle prefix", () => { - const result = lineStream.processBlockNesting("", false); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - - it("should handle START EDITING HERE blocks", () => { - const result = lineStream.processBlockNesting( - "", - false, - ); - expect(result).toEqual({ - newSeenFirstFence: false, - shouldSkip: true, - }); - }); - }); - describe("MarkdownBlockState", () => { it("should initialize with correct state", () => { const allLines = ["```markdown", "content", "```", "more content", "```"]; diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 4aa746e79..77d952e7b 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -6,168 +6,11 @@ import { import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; +import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js"; import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; -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 || ""); -} - -/** - * Optimized state tracker for markdown block analysis to avoid recomputing on each call. - */ -class MarkdownBlockStateTracker { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; - private markdownNestCount: number = 0; - private lastProcessedIndex: number = -1; - - constructor(allLines: string[]) { - this.trimmedLines = allLines.map((l) => l.trim()); - // Pre-compute positions of all bare backtick lines for faster lookup - this.bareBacktickPositions = []; - for (let i = 0; i < this.trimmedLines.length; i++) { - if (this.trimmedLines[i].match(/^`+$/)) { - this.bareBacktickPositions.push(i); - } - } - } - - /** - * Determines if we should stop at the given markdown block position. - * Maintains state across calls to avoid redundant computation. - */ - shouldStopAtPosition(currentIndex: number): boolean { - if (this.trimmedLines[currentIndex] !== "```") { - return false; - } - - // Process any lines we haven't seen yet up to currentIndex - for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { - const currentLine = this.trimmedLines[j]; - - if (this.markdownNestCount > 0) { - // Inside a markdown block - if (currentLine.match(/^`+$/)) { - // Found bare backticks - check if this is the last one - if (j === currentIndex) { - const remainingBareBackticks = this.bareBacktickPositions.filter( - (pos) => pos > j, - ).length; - if (remainingBareBackticks === 0) { - this.markdownNestCount = 0; - this.lastProcessedIndex = j; - return true; - } - } - } else if (currentLine.startsWith("```")) { - // Going into a nested codeblock - this.markdownNestCount++; - } - } else { - // Not inside a markdown block yet - if (currentLine.startsWith("```")) { - const header = currentLine.replaceAll("`", ""); - if (headerIsMarkdown(header)) { - this.markdownNestCount = 1; - } - } - } - } - - this.lastProcessedIndex = currentIndex; - return false; - } -} - -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; - } - - // Use optimized state tracker for markdown block analysis - const stateTracker = new MarkdownBlockStateTracker(allLines); - 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(/^`+$/)) { - // Use optimized state tracker for markdown block logic - if (stateTracker.shouldStopAtPosition(i)) { - 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, diff --git a/core/utils/markdownUtils.ts b/core/utils/markdownUtils.ts new file mode 100644 index 000000000..e292d8bf8 --- /dev/null +++ b/core/utils/markdownUtils.ts @@ -0,0 +1,113 @@ +/** + * Utility functions for working with markdown files and code blocks + */ + +/** + * Determines if a code block header indicates markdown content + */ +export function headerIsMarkdown(header: string): boolean { + return ( + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + header.split(" ")[0]?.split(".").pop() === "md" || + header.split(" ")[0]?.split(".").pop() === "markdown" || + header.split(" ")[0]?.split(".").pop() === "gfm" + ); +} + +/** + * Determines if a file is a markdown file based on its filepath. + */ +export function isMarkdownFile(filepath?: string): boolean { + if (!filepath) { + return false; + } + + const ext = filepath.split(".").pop()?.toLowerCase() || ""; + return ["md", "markdown", "gfm"].includes(ext); +} + +/** + * State tracker for markdown block analysis to avoid recomputing on each call. + * Optimized to handle nested markdown code blocks. + */ +export class MarkdownBlockStateTracker { + private trimmedLines: string[]; + private bareBacktickPositions: number[]; + private markdownNestCount: number = 0; + private lastProcessedIndex: number = -1; + + constructor(allLines: string[]) { + this.trimmedLines = allLines.map((l) => l.trim()); + // Pre-compute positions of all bare backtick lines for faster lookup + this.bareBacktickPositions = []; + for (let i = 0; i < this.trimmedLines.length; i++) { + if (this.trimmedLines[i].match(/^`+$/)) { + this.bareBacktickPositions.push(i); + } + } + } + + /** + * Determines if we should stop at the given markdown block position. + * Maintains state across calls to avoid redundant computation. + */ + shouldStopAtPosition(currentIndex: number): boolean { + if (this.trimmedLines[currentIndex] !== "```") { + return false; + } + + // Process any lines we haven't seen yet up to currentIndex + for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) { + const currentLine = this.trimmedLines[j]; + + if (this.markdownNestCount > 0) { + // Inside a markdown block + if (currentLine.match(/^`+$/)) { + // Found bare backticks - check if this is the last one + if (j === currentIndex) { + const remainingBareBackticks = this.bareBacktickPositions.filter( + (pos) => pos > j, + ).length; + if (remainingBareBackticks === 0) { + this.markdownNestCount = 0; + this.lastProcessedIndex = j; + return true; + } + } + } else if (currentLine.startsWith("```")) { + // Going into a nested codeblock + this.markdownNestCount++; + } + } else { + // Not inside a markdown block yet + if (currentLine.startsWith("```")) { + const header = currentLine.replaceAll("`", ""); + if (headerIsMarkdown(header)) { + this.markdownNestCount = 1; + } + } + } + } + + this.lastProcessedIndex = currentIndex; + return false; + } +} + +/** + * Collects all lines from a LineStream into an array for analysis. + */ +export async function collectAllLines(stream: AsyncGenerator): Promise { + const allLines: T[] = []; + for await (const line of stream) { + allLines.push(line); + } + return allLines; +} \ No newline at end of file diff --git a/core/utils/markdownUtils.vitest.ts b/core/utils/markdownUtils.vitest.ts new file mode 100644 index 000000000..e1380e08e --- /dev/null +++ b/core/utils/markdownUtils.vitest.ts @@ -0,0 +1,80 @@ +import { test, expect } from 'vitest'; +import { headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker } from './markdownUtils'; + +test('headerIsMarkdown correctly identifies markdown headers', () => { + // Should return true for markdown headers + expect(headerIsMarkdown('md')).toBe(true); + expect(headerIsMarkdown('markdown')).toBe(true); + expect(headerIsMarkdown('gfm')).toBe(true); + expect(headerIsMarkdown('github-markdown')).toBe(true); + expect(headerIsMarkdown('language md')).toBe(true); + expect(headerIsMarkdown('language markdown')).toBe(true); + expect(headerIsMarkdown('filename.md')).toBe(true); + expect(headerIsMarkdown('path/to/file.md language')).toBe(true); + + // Should return false for non-markdown headers + expect(headerIsMarkdown('javascript')).toBe(false); + expect(headerIsMarkdown('typescript')).toBe(false); + expect(headerIsMarkdown('python')).toBe(false); + expect(headerIsMarkdown('')).toBe(false); +}); + +test('isMarkdownFile correctly identifies markdown files', () => { + // Should return true for markdown files + expect(isMarkdownFile('test.md')).toBe(true); + expect(isMarkdownFile('path/to/file.markdown')).toBe(true); + expect(isMarkdownFile('README.md')).toBe(true); + + // Should return false for non-markdown files + expect(isMarkdownFile('test.js')).toBe(false); + expect(isMarkdownFile('script.ts')).toBe(false); + expect(isMarkdownFile('')).toBe(false); + expect(isMarkdownFile(undefined)).toBe(false); +}); + +test('MarkdownBlockStateTracker correctly tracks nested markdown blocks', () => { + const lines = [ + '# Header', + '', + 'Some text', + '', + '```md', + 'Nested markdown content', + '```javascript', + 'function test() {', + ' return true;', + '}', + '```', + 'More nested markdown', + '```', + '', + 'End of file' + ]; + + const stateTracker = new MarkdownBlockStateTracker(lines); + + // First backtick closure is within nested block (not markdown end) + expect(stateTracker.shouldStopAtPosition(10)).toBe(false); + + // This is the backtick that closes the outer markdown block + expect(stateTracker.shouldStopAtPosition(12)).toBe(true); +}); + +test('MarkdownBlockStateTracker handles simple code blocks correctly', () => { + const lines = [ + 'Some code:', + '', + '```javascript', + 'function test() {', + ' return true;', + '}', + '```', + '', + 'More text' + ]; + + const stateTracker = new MarkdownBlockStateTracker(lines); + + // This is just a simple code block, not nested markdown + expect(stateTracker.shouldStopAtPosition(6)).toBe(false); +}); \ No newline at end of file diff --git a/core/utils/streamMarkdownUtils.ts b/core/utils/streamMarkdownUtils.ts new file mode 100644 index 000000000..b1c8c7658 --- /dev/null +++ b/core/utils/streamMarkdownUtils.ts @@ -0,0 +1,122 @@ +import { LineStream } from "../diff/util"; +import { + isMarkdownFile, + MarkdownBlockStateTracker, + headerIsMarkdown, +} from "./markdownUtils"; + +/** + * Determines if we should stop at a markdown block based on nested markdown logic. + * This handles the complex case where markdown blocks contain other markdown blocks. + * Uses optimized state tracking to avoid redundant computation. + */ +export function shouldStopAtMarkdownBlock( + stateTracker: MarkdownBlockStateTracker, + currentIndex: number, +): boolean { + return stateTracker.shouldStopAtPosition(currentIndex); +} + +/** + * Processes block nesting logic and returns updated state. + */ +export function processBlockNesting( + line: string, + seenFirstFence: boolean, + shouldRemoveLineBeforeStart: (line: string) => boolean, +): { newSeenFirstFence: boolean; shouldSkip: boolean } { + if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) { + return { newSeenFirstFence: false, shouldSkip: true }; + } + + if (!seenFirstFence) { + return { newSeenFirstFence: true, shouldSkip: false }; + } + + return { newSeenFirstFence: seenFirstFence, shouldSkip: false }; +} + +/** + * Stream transformation that stops when encountering a markdown code block ending. + * Handles nested markdown blocks in markdown files. + */ +export async function* stopAtLinesWithMarkdownSupport( + lines: LineStream, + filename: string, +): LineStream { + if (!isMarkdownFile(filename)) { + for await (const line of lines) { + if (line.trim() === "```") { + return; + } + yield line; + } + return; + } + + const allLines: string[] = []; + for await (const line of lines) { + allLines.push(line); + } + + const source = allLines.join("\n"); + if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) { + // No nested markdown blocks detected, check for simple ``` stopping condition + let foundStandaloneBackticks = false; + for (let i = 0; i < allLines.length; i++) { + if (allLines[i].trim() === "```") { + // Found standalone backticks, yield lines up to this point + for (let j = 0; j < i; j++) { + yield allLines[j]; + } + foundStandaloneBackticks = true; + return; + } + } + + // No standalone backticks found, yield all lines + if (!foundStandaloneBackticks) { + for (const line of allLines) { + yield line; + } + } + return; + } + + // Use optimized state tracker for markdown block analysis + const stateTracker = new MarkdownBlockStateTracker(allLines); + 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(/^`+$/)) { + // Use optimized state tracker for markdown block logic + if (stateTracker.shouldStopAtPosition(i)) { + 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; + } + } + } + } + + // If we get here, yield all lines + for (const line of allLines) { + yield line; + } +} diff --git a/core/utils/streamMarkdownUtils.vitest.ts b/core/utils/streamMarkdownUtils.vitest.ts new file mode 100644 index 000000000..097b1fbd5 --- /dev/null +++ b/core/utils/streamMarkdownUtils.vitest.ts @@ -0,0 +1,102 @@ +import { expect, test } from "vitest"; +import { LineStream } from "../diff/util"; +import { + processBlockNesting, + stopAtLinesWithMarkdownSupport, +} from "./streamMarkdownUtils"; + +test("processBlockNesting correctly handles starting blocks", () => { + // Mock function to determine which lines should be removed + const shouldRemoveLineBeforeStart = (line: string) => + line === "[CODE]" || line === "```"; + + // Test not seeing first fence yet + const result1 = processBlockNesting( + "[CODE]", + false, + shouldRemoveLineBeforeStart, + ); + expect(result1.newSeenFirstFence).toBe(false); + expect(result1.shouldSkip).toBe(true); + + // Test not seeing first fence but line shouldn't be removed + const result2 = processBlockNesting( + "normal code", + false, + shouldRemoveLineBeforeStart, + ); + expect(result2.newSeenFirstFence).toBe(true); + expect(result2.shouldSkip).toBe(false); + + // Test already seen first fence + const result3 = processBlockNesting( + "more code", + true, + shouldRemoveLineBeforeStart, + ); + expect(result3.newSeenFirstFence).toBe(true); + expect(result3.shouldSkip).toBe(false); +}); + +test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => { + // Create a mock line stream + const mockLines = ["line 1", "line 2", "```", "line 4"]; + const lineStream: LineStream = (async function* () { + for (const line of mockLines) { + yield line; + } + })(); + + // Test with a non-markdown file + const filename = "test.js"; + const result = stopAtLinesWithMarkdownSupport(lineStream, filename); + + // Should only yield lines up to the backticks + const collected = []; + for await (const line of result) { + collected.push(line); + } + + expect(collected).toEqual(["line 1", "line 2"]); +}); + +test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => { + // Create a mock line stream with markdown content - but NOT nested markdown blocks + const mockLines = [ + "Some markdown text", + "", + "```javascript", + "function test() {", + " return true;", + "}", + "```", + "More text", + ]; + + const lineStream: LineStream = (async function* () { + for (const line of mockLines) { + yield line; + } + })(); + + // Test with a markdown file + const filename = "test.md"; + const result = stopAtLinesWithMarkdownSupport(lineStream, filename); + + // Should yield everything since there's no nested markdown blocks + const collected = []; + for await (const line of result) { + collected.push(line); + } + + // The function should stop at the standalone ``` line (not yield it or lines after) + // This is the correct behavior - it stops when it encounters standalone backticks + expect(collected).toEqual([ + "Some markdown text", + "", + "```javascript", + "function test() {", + " return true;", + "}", + ]); +}); From db25f4a89b6d0f035d21fe08e6c0e6f48bae9114 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 4 Jul 2025 14:03:37 -0700 Subject: [PATCH 09/26] prettier fixes --- core/utils/markdownUtils.ts | 6 +- core/utils/markdownUtils.vitest.ts | 108 +++++++++++++++-------------- 2 files changed, 60 insertions(+), 54 deletions(-) diff --git a/core/utils/markdownUtils.ts b/core/utils/markdownUtils.ts index e292d8bf8..edf827a08 100644 --- a/core/utils/markdownUtils.ts +++ b/core/utils/markdownUtils.ts @@ -104,10 +104,12 @@ export class MarkdownBlockStateTracker { /** * Collects all lines from a LineStream into an array for analysis. */ -export async function collectAllLines(stream: AsyncGenerator): Promise { +export async function collectAllLines( + stream: AsyncGenerator, +): Promise { const allLines: T[] = []; for await (const line of stream) { allLines.push(line); } return allLines; -} \ No newline at end of file +} diff --git a/core/utils/markdownUtils.vitest.ts b/core/utils/markdownUtils.vitest.ts index e1380e08e..211bcd8e1 100644 --- a/core/utils/markdownUtils.vitest.ts +++ b/core/utils/markdownUtils.vitest.ts @@ -1,80 +1,84 @@ -import { test, expect } from 'vitest'; -import { headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker } from './markdownUtils'; +import { test, expect } from "vitest"; +import { + headerIsMarkdown, + isMarkdownFile, + MarkdownBlockStateTracker, +} from "./markdownUtils"; -test('headerIsMarkdown correctly identifies markdown headers', () => { +test("headerIsMarkdown correctly identifies markdown headers", () => { // Should return true for markdown headers - expect(headerIsMarkdown('md')).toBe(true); - expect(headerIsMarkdown('markdown')).toBe(true); - expect(headerIsMarkdown('gfm')).toBe(true); - expect(headerIsMarkdown('github-markdown')).toBe(true); - expect(headerIsMarkdown('language md')).toBe(true); - expect(headerIsMarkdown('language markdown')).toBe(true); - expect(headerIsMarkdown('filename.md')).toBe(true); - expect(headerIsMarkdown('path/to/file.md language')).toBe(true); + expect(headerIsMarkdown("md")).toBe(true); + expect(headerIsMarkdown("markdown")).toBe(true); + expect(headerIsMarkdown("gfm")).toBe(true); + expect(headerIsMarkdown("github-markdown")).toBe(true); + expect(headerIsMarkdown("language md")).toBe(true); + expect(headerIsMarkdown("language markdown")).toBe(true); + expect(headerIsMarkdown("filename.md")).toBe(true); + expect(headerIsMarkdown("path/to/file.md language")).toBe(true); // Should return false for non-markdown headers - expect(headerIsMarkdown('javascript')).toBe(false); - expect(headerIsMarkdown('typescript')).toBe(false); - expect(headerIsMarkdown('python')).toBe(false); - expect(headerIsMarkdown('')).toBe(false); + expect(headerIsMarkdown("javascript")).toBe(false); + expect(headerIsMarkdown("typescript")).toBe(false); + expect(headerIsMarkdown("python")).toBe(false); + expect(headerIsMarkdown("")).toBe(false); }); -test('isMarkdownFile correctly identifies markdown files', () => { +test("isMarkdownFile correctly identifies markdown files", () => { // Should return true for markdown files - expect(isMarkdownFile('test.md')).toBe(true); - expect(isMarkdownFile('path/to/file.markdown')).toBe(true); - expect(isMarkdownFile('README.md')).toBe(true); + expect(isMarkdownFile("test.md")).toBe(true); + expect(isMarkdownFile("path/to/file.markdown")).toBe(true); + expect(isMarkdownFile("README.md")).toBe(true); // Should return false for non-markdown files - expect(isMarkdownFile('test.js')).toBe(false); - expect(isMarkdownFile('script.ts')).toBe(false); - expect(isMarkdownFile('')).toBe(false); + expect(isMarkdownFile("test.js")).toBe(false); + expect(isMarkdownFile("script.ts")).toBe(false); + expect(isMarkdownFile("")).toBe(false); expect(isMarkdownFile(undefined)).toBe(false); }); -test('MarkdownBlockStateTracker correctly tracks nested markdown blocks', () => { +test("MarkdownBlockStateTracker correctly tracks nested markdown blocks", () => { const lines = [ - '# Header', - '', - 'Some text', - '', - '```md', - 'Nested markdown content', - '```javascript', - 'function test() {', - ' return true;', - '}', - '```', - 'More nested markdown', - '```', - '', - 'End of file' + "# Header", + "", + "Some text", + "", + "```md", + "Nested markdown content", + "```javascript", + "function test() {", + " return true;", + "}", + "```", + "More nested markdown", + "```", + "", + "End of file", ]; const stateTracker = new MarkdownBlockStateTracker(lines); - + // First backtick closure is within nested block (not markdown end) expect(stateTracker.shouldStopAtPosition(10)).toBe(false); - + // This is the backtick that closes the outer markdown block expect(stateTracker.shouldStopAtPosition(12)).toBe(true); }); -test('MarkdownBlockStateTracker handles simple code blocks correctly', () => { +test("MarkdownBlockStateTracker handles simple code blocks correctly", () => { const lines = [ - 'Some code:', - '', - '```javascript', - 'function test() {', - ' return true;', - '}', - '```', - '', - 'More text' + "Some code:", + "", + "```javascript", + "function test() {", + " return true;", + "}", + "```", + "", + "More text", ]; const stateTracker = new MarkdownBlockStateTracker(lines); - + // This is just a simple code block, not nested markdown expect(stateTracker.shouldStopAtPosition(6)).toBe(false); -}); \ No newline at end of file +}); From 361685dc9da5b0a643b2ac038d76df61220f09f5 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 4 Jul 2025 21:38:22 -0700 Subject: [PATCH 10/26] remove nova change --- core/edit/streamDiffLines.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index c2cd32b0e..7cf1af2f7 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -55,11 +55,7 @@ export async function* addIndentation( } function modelIsInept(model: string): boolean { - return !( - model.includes("gpt") || - model.includes("claude") || - model.includes("nova") - ); + return !(model.includes("gpt") || model.includes("claude")); } export async function* streamDiffLines({ From 1bd49276c09d1e65a86fc91441e9244034e2752e Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 12:15:45 -0700 Subject: [PATCH 11/26] fix re-exports --- .../streamTransforms/filterCodeBlock.ts | 18 +++++--- .../filtering/streamTransforms/lineStream.ts | 12 +---- .../streamTransforms/lineStream.vitest.ts | 46 ++++++++++--------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts index 28af7d372..31e37b844 100644 --- a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts @@ -2,11 +2,17 @@ import { LineStream } from "../../../diff/util"; import { collectAllLines, - hasNestedMarkdownBlocks, - MarkdownBlockState, + MarkdownBlockStateTracker, +} from "../../../utils/markdownUtils"; + +import { processBlockNesting, - shouldChangeLineAndStop, shouldStopAtMarkdownBlock, +} from "../../../utils/streamMarkdownUtils"; + +import { + hasNestedMarkdownBlocks, + shouldChangeLineAndStop, } from "./lineStream"; /** @@ -68,16 +74,16 @@ export async function* filterCodeBlockLines( let nestCount = 0; // Create optimized state tracker for markdown block analysis if needed - let markdownStateTracker: MarkdownBlockState | undefined; + let markdownStateTracker: MarkdownBlockStateTracker | undefined; if (hasNestedMarkdown) { - markdownStateTracker = new MarkdownBlockState(allLines); + markdownStateTracker = new MarkdownBlockStateTracker(allLines); } for (let i = 0; i < allLines.length; i++) { const line = allLines[i]; // Process block nesting logic for the first fence - const nesting = processBlockNesting(line, seenFirstFence); + const nesting = processBlockNesting(line, seenFirstFence, shouldRemoveLineBeforeStart); if (nesting.shouldSkip) { continue; // Filter out starting ``` or START block } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 70ef1d20e..b355a2aa1 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -5,13 +5,10 @@ import { LineStream } from "../../../diff/util"; import { headerIsMarkdown, - isMarkdownFile, - MarkdownBlockStateTracker, - collectAllLines, + isMarkdownFile } from "../../../utils/markdownUtils"; import { - shouldStopAtMarkdownBlock, - processBlockNesting as processBlockNestingUtil, + processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils"; export { filterCodeBlockLines } from "./filterCodeBlock"; @@ -132,11 +129,6 @@ export function hasNestedMarkdownBlocks( ); } -// Re-export shared utilities -export { collectAllLines, isMarkdownFile }; -export { MarkdownBlockStateTracker as MarkdownBlockState }; -export { shouldStopAtMarkdownBlock }; - // Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function export function processBlockNesting( line: string, diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 1cd569ae4..994b47b1a 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; +import { collectAllLines, MarkdownBlockStateTracker } from "../../../utils/markdownUtils"; +import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils"; import * as lineStream from "./lineStream"; // eslint-disable-next-line max-lines-per-function @@ -897,7 +899,7 @@ describe("lineStream", () => { "line3", ]); - const result = await lineStream.collectAllLines(linesGenerator); + const result = await collectAllLines(linesGenerator); expect(result).toEqual(["line1", "line2", "line3"]); }); @@ -905,7 +907,7 @@ describe("lineStream", () => { it("should handle empty stream", async () => { const linesGenerator = await getLineGenerator([]); - const result = await lineStream.collectAllLines(linesGenerator); + const result = await collectAllLines(linesGenerator); expect(result).toEqual([]); }); @@ -913,7 +915,7 @@ describe("lineStream", () => { it("should handle stream with empty lines", async () => { const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]); - const result = await lineStream.collectAllLines(linesGenerator); + const result = await collectAllLines(linesGenerator); expect(result).toEqual(["", "line2", "", "line4"]); }); @@ -922,14 +924,14 @@ describe("lineStream", () => { describe("shouldStopAtMarkdownBlock", () => { it("should return false when current line is not closing backticks", () => { const allLines = ["```markdown", "content", "more content"]; - const state = new lineStream.MarkdownBlockState(allLines); - expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); + const state = new MarkdownBlockStateTracker(allLines); + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false); }); it("should handle simple nested markdown case", () => { const allLines = ["```markdown", "# Title", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); - expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(true); + const state = new MarkdownBlockStateTracker(allLines); + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true); }); it("should handle complex nested markdown with inner code blocks", () => { @@ -941,11 +943,11 @@ describe("lineStream", () => { "```", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // At index 4 (first inner closing), should not stop - expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(false); + expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false); // At index 5 (outer closing), should stop - expect(lineStream.shouldStopAtMarkdownBlock(state, 5)).toBe(true); + expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true); }); it("should handle multiple bare backticks scenario", () => { @@ -956,11 +958,11 @@ describe("lineStream", () => { "More content", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // At index 2, should not stop (not the last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(state, 2)).toBe(false); + expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false); // At index 4, should stop (last bare backticks) - expect(lineStream.shouldStopAtMarkdownBlock(state, 4)).toBe(true); + expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true); }); }); @@ -1014,7 +1016,7 @@ describe("lineStream", () => { describe("MarkdownBlockState", () => { it("should initialize with correct state", () => { const allLines = ["```markdown", "content", "```", "more content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Test basic initialization - we can't directly test private properties, // but we can test the behavior through shouldStopAtPosition @@ -1023,7 +1025,7 @@ describe("lineStream", () => { it("should correctly identify bare backticks positions", () => { const allLines = ["```markdown", "```", "content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // At position 1 (first bare backticks), should not stop expect(state.shouldStopAtPosition(1)).toBe(false); @@ -1041,7 +1043,7 @@ describe("lineStream", () => { "More content", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Process positions incrementally expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block @@ -1066,7 +1068,7 @@ describe("lineStream", () => { "Final notes", "```", ]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Test multiple positions in sequence expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block @@ -1076,7 +1078,7 @@ describe("lineStream", () => { it("should handle non-backtick lines correctly", () => { const allLines = ["```markdown", "regular content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Position 1 is not backticks, should return false expect(state.shouldStopAtPosition(1)).toBe(false); @@ -1084,7 +1086,7 @@ describe("lineStream", () => { it("should handle empty lines and edge cases", () => { const allLines = ["```markdown", "", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks @@ -1092,7 +1094,7 @@ describe("lineStream", () => { it("should reset nest count when reaching final bare backticks", () => { const allLines = ["```markdown", "content", "```"]; - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // First call should stop and reset count expect(state.shouldStopAtPosition(2)).toBe(true); @@ -1112,7 +1114,7 @@ describe("lineStream", () => { return `line ${i}`; }); - const state = new lineStream.MarkdownBlockState(allLines); + const state = new MarkdownBlockStateTracker(allLines); // Test that we can call multiple times without recomputing everything const start = performance.now(); @@ -1120,7 +1122,7 @@ describe("lineStream", () => { // Test several positions in sequence for (let i = 10; i < 90; i += 10) { if (allLines[i].trim() === "```") { - lineStream.shouldStopAtMarkdownBlock(state, i); + shouldStopAtMarkdownBlock(state, i); } } From 7cd725264ab35ed9b79816e844ffdec7a8700c43 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 12:47:28 -0700 Subject: [PATCH 12/26] fix duplicate logic --- core/utils/streamMarkdownUtils.ts | 33 ++++++------------------------- 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/core/utils/streamMarkdownUtils.ts b/core/utils/streamMarkdownUtils.ts index b1c8c7658..94505dfdf 100644 --- a/core/utils/streamMarkdownUtils.ts +++ b/core/utils/streamMarkdownUtils.ts @@ -1,8 +1,7 @@ import { LineStream } from "../diff/util"; import { isMarkdownFile, - MarkdownBlockStateTracker, - headerIsMarkdown, + MarkdownBlockStateTracker } from "./markdownUtils"; /** @@ -85,33 +84,13 @@ export async function* stopAtLinesWithMarkdownSupport( // Use optimized state tracker for markdown block analysis const stateTracker = new MarkdownBlockStateTracker(allLines); - 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(/^`+$/)) { - // Use optimized state tracker for markdown block logic - if (stateTracker.shouldStopAtPosition(i)) { - 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 (let i = 0; i < allLines.length; i++) { + if (stateTracker.shouldStopAtPosition(i)) { + for (let j = 0; j < i; j++) { + yield allLines[j]; } + return; } } From f604c17c27951119f33e1a5bc0f8c23850416c3d Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 13:07:08 -0700 Subject: [PATCH 13/26] fix rundundant trimming --- .../StyledMarkdownPreview/utils/patchNestedMarkdown.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 562c70086..b054f0bd9 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -41,6 +41,13 @@ class MarkdownPatchStateTracker { isBareBacktickLine(index: number): boolean { return this.bareBacktickPositions.includes(index); } + + /** + * Gets the trimmed lines array. + */ + getTrimmedLines(): string[] { + return this.trimmedLines; + } } export const patchNestedMarkdown = (source: string): string => { @@ -50,10 +57,10 @@ export const patchNestedMarkdown = (source: string): string => { let nestCount = 0; const lines = source.split("\n"); - const trimmedLines = lines.map((l) => l.trim()); // Use optimized state tracker for efficient bare backtick analysis const stateTracker = new MarkdownPatchStateTracker(lines); + const trimmedLines = stateTracker.getTrimmedLines(); for (let i = 0; i < trimmedLines.length; i++) { const line = trimmedLines[i]; From ad2bbc28c9256bf16c2918e6a81225d4860fbcb6 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 13:20:31 -0700 Subject: [PATCH 14/26] add back comments --- core/edit/lazy/streamLazyApply.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 77d952e7b..f806e956f 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -26,6 +26,7 @@ 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[], @@ -52,12 +53,14 @@ export async function* streamLazyApply( 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,11 +81,13 @@ 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) { @@ -90,6 +95,7 @@ async function* streamFillUnchangedCode( newLines.push(replacementLine); replacement += replacementLine + "\n"; } + // Yield the buffered lines for (const bufferedLine of buffer) { yield bufferedLine; newLines.push(bufferedLine); @@ -104,7 +110,9 @@ 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); @@ -112,11 +120,14 @@ 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); From 948246dc443815e6a722334179dcde6ab6f87102 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 13 Jul 2025 14:47:54 -0700 Subject: [PATCH 15/26] prettier and code cleanup --- .../streamTransforms/filterCodeBlock.ts | 11 +- .../filtering/streamTransforms/lineStream.ts | 102 ++--- .../streamTransforms/lineStream.vitest.ts | 95 ++++- core/llm/autodetect.ts | 3 +- core/utils/markdownUtils.ts | 31 +- core/utils/markdownUtils.vitest.ts | 350 ++++++++++++++---- core/utils/streamMarkdownUtils.ts | 5 +- .../utils/headerIsMarkdown.test.ts | 67 ---- .../utils/headerIsMarkdown.ts | 26 -- .../utils/patchNestedMarkdown.ts | 48 +-- 10 files changed, 473 insertions(+), 265 deletions(-) delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts delete mode 100644 gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts diff --git a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts index 31e37b844..d9cb8e8ac 100644 --- a/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts +++ b/core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts @@ -10,10 +10,7 @@ import { shouldStopAtMarkdownBlock, } from "../../../utils/streamMarkdownUtils"; -import { - hasNestedMarkdownBlocks, - shouldChangeLineAndStop, -} from "./lineStream"; +import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream"; /** * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. @@ -83,7 +80,11 @@ export async function* filterCodeBlockLines( const line = allLines[i]; // Process block nesting logic for the first fence - const nesting = processBlockNesting(line, seenFirstFence, shouldRemoveLineBeforeStart); + const nesting = processBlockNesting( + line, + seenFirstFence, + shouldRemoveLineBeforeStart, + ); if (nesting.shouldSkip) { continue; // Filter out starting ``` or START block } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index b355a2aa1..3cf1cec9f 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -3,13 +3,8 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; -import { - headerIsMarkdown, - isMarkdownFile -} from "../../../utils/markdownUtils"; -import { - processBlockNesting as processBlockNestingUtil -} from "../../../utils/streamMarkdownUtils"; +import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils"; +import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils"; export { filterCodeBlockLines } from "./filterCodeBlock"; @@ -60,6 +55,47 @@ function shouldRemoveLineBeforeStart(line: string): boolean { ); } +/** + * Shared utility for validating patterns in lines to avoid code duplication. + * Checks if a pattern appears in a valid context (not inside quotes or identifiers). + */ +export function validatePatternInLine( + line: string, + pattern: string, +): { + isValid: boolean; + patternIndex: number; + beforePattern: string; +} { + const patternIndex = line.indexOf(pattern); + + if (patternIndex === -1) { + return { isValid: false, patternIndex: -1, beforePattern: "" }; + } + + // Check if pattern is preceded by a non-whitespace character + // If so, it might be part of an identifier, so don't handle it + if (patternIndex > 0) { + const charBefore = line[patternIndex - 1]; + if (charBefore && !charBefore.match(/\s/)) { + return { isValid: false, patternIndex, beforePattern: "" }; + } + } + + // Check if pattern appears to be inside quotes + // Simple heuristic: count unmatched quotes before the pattern + const beforePattern = line.substring(0, patternIndex); + const singleQuotes = (beforePattern.match(/'/g) || []).length; + const doubleQuotes = (beforePattern.match(/"/g) || []).length; + + // If there's an odd number of quotes before pattern, we're likely inside quotes + if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { + return { isValid: false, patternIndex, beforePattern }; + } + + return { isValid: true, patternIndex, beforePattern }; +} + export function shouldChangeLineAndStop(line: string): string | undefined { if (line.trimStart() === "```") { return line; @@ -67,26 +103,10 @@ export function shouldChangeLineAndStop(line: string): string | undefined { // Check if [/CODE] appears in the line if (line.includes(CODE_STOP_BLOCK)) { - const stopBlockIndex = line.indexOf(CODE_STOP_BLOCK); + const validation = validatePatternInLine(line, CODE_STOP_BLOCK); - // Check if [/CODE] is preceded by a non-whitespace character - // If so, it might be part of an identifier, so don't handle it - if (stopBlockIndex > 0) { - const charBefore = line[stopBlockIndex - 1]; - if (charBefore && !charBefore.match(/\s/)) { - return undefined; // Don't handle [/CODE] that's part of an identifier - } - } - - // Check if [/CODE] appears to be inside quotes - // Simple heuristic: count unmatched quotes before the stop block - const beforeStopBlock = line.substring(0, stopBlockIndex); - const singleQuotes = (beforeStopBlock.match(/'/g) || []).length; - const doubleQuotes = (beforeStopBlock.match(/"/g) || []).length; - - // If there's an odd number of quotes before [/CODE], we're likely inside quotes - if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { - return undefined; // Don't handle [/CODE] inside quotes + if (!validation.isValid) { + return undefined; } // Get the trimmed line to check if [/CODE] is at logical start @@ -100,7 +120,7 @@ export function shouldChangeLineAndStop(line: string): string | undefined { } // [/CODE] appears after some content (separated by whitespace) - return part before - return beforeStopBlock.trimEnd(); + return validation.beforePattern.trimEnd(); } return undefined; @@ -336,26 +356,10 @@ export async function* stopAtLines( // Check each stop phrase for (const stopAt of linesToStopAt) { if (line.includes(stopAt)) { - const stopAtIndex = line.indexOf(stopAt); + const validation = validatePatternInLine(line, stopAt); - // Check if stop phrase is preceded by a non-whitespace character - // If so, it might be part of an identifier, so don't handle it - if (stopAtIndex > 0) { - const charBefore = line[stopAtIndex - 1]; - if (charBefore && !charBefore.match(/\s/)) { - continue; // Don't handle stop phrase that's part of an identifier - } - } - - // Check if stop phrase appears to be inside quotes - // Simple heuristic: count unmatched quotes before the stop phrase - const beforeStopPhrase = line.substring(0, stopAtIndex); - const singleQuotes = (beforeStopPhrase.match(/'/g) || []).length; - const doubleQuotes = (beforeStopPhrase.match(/"/g) || []).length; - - // If there's an odd number of quotes before stop phrase, we're likely inside quotes - if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) { - continue; // Don't handle stop phrase inside quotes + if (!validation.isValid) { + continue; } // Get the trimmed line to check if stop phrase is at logical start @@ -367,8 +371,10 @@ export async function* stopAtLines( break; } else { // Stop phrase appears after some content - check if it's separated by whitespace - const contentBeforeStopPhrase = beforeStopPhrase.trimEnd(); - if (contentBeforeStopPhrase.length < beforeStopPhrase.length) { + const contentBeforeStopPhrase = validation.beforePattern.trimEnd(); + if ( + contentBeforeStopPhrase.length < validation.beforePattern.length + ) { // There's whitespace before the stop phrase, so it's properly separated shouldStop = true; break; diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts index 994b47b1a..741c2b125 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; -import { collectAllLines, MarkdownBlockStateTracker } from "../../../utils/markdownUtils"; +import { + collectAllLines, + MarkdownBlockStateTracker, +} from "../../../utils/markdownUtils"; import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils"; import * as lineStream from "./lineStream"; @@ -1205,4 +1208,94 @@ describe("lineStream", () => { ]); }); }); + + describe("validatePatternInLine", () => { + it("should return false when pattern is not found", () => { + const result = lineStream.validatePatternInLine( + "const x = 5;", + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(-1); + expect(result.beforePattern).toBe(""); + }); + + it("should return false when pattern is preceded by non-whitespace", () => { + const result = lineStream.validatePatternInLine( + 'const var[/CODE]Name = "test";', + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(9); + }); + + it("should return false when pattern is inside double quotes", () => { + const result = lineStream.validatePatternInLine( + 'console.log("test [/CODE] end");', + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(18); + }); + + it("should return false when pattern is inside single quotes", () => { + const result = lineStream.validatePatternInLine( + "const message = 'test [/CODE] end';", + "[/CODE]", + ); + expect(result.isValid).toBe(false); + expect(result.patternIndex).toBe(22); + }); + + it("should return true when pattern is properly separated by whitespace", () => { + const result = lineStream.validatePatternInLine( + "some code [/CODE] more text", + "[/CODE]", + ); + expect(result.isValid).toBe(true); + expect(result.patternIndex).toBe(10); + expect(result.beforePattern).toBe("some code "); + }); + + it("should return true when pattern is at start of line", () => { + const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]"); + expect(result.isValid).toBe(true); + expect(result.patternIndex).toBe(0); + expect(result.beforePattern).toBe(""); + }); + + it("should return true when pattern has only whitespace before it", () => { + const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]"); + expect(result.isValid).toBe(true); + expect(result.patternIndex).toBe(4); + expect(result.beforePattern).toBe(" "); + }); + + it("should handle complex quote scenarios correctly", () => { + // Unmatched quote should make it invalid + const result1 = lineStream.validatePatternInLine( + 'const x = "unclosed quote [/CODE]', + "[/CODE]", + ); + expect(result1.isValid).toBe(false); + + // Matched quotes should make it valid + const result2 = lineStream.validatePatternInLine( + 'const x = "closed"; [/CODE]', + "[/CODE]", + ); + expect(result2.isValid).toBe(true); + }); + + it("should work with different patterns", () => { + const result1 = lineStream.validatePatternInLine( + "# End of file. Done", + "# End of file.", + ); + expect(result1.isValid).toBe(true); + + const result2 = lineStream.validatePatternInLine(" ```", "```"); + expect(result2.isValid).toBe(true); + }); + }); }); diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index df575bfed..a220b5dbd 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -400,6 +400,5 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools + modelSupportsTools, }; - diff --git a/core/utils/markdownUtils.ts b/core/utils/markdownUtils.ts index edf827a08..365f72811 100644 --- a/core/utils/markdownUtils.ts +++ b/core/utils/markdownUtils.ts @@ -38,8 +38,8 @@ export function isMarkdownFile(filepath?: string): boolean { * Optimized to handle nested markdown code blocks. */ export class MarkdownBlockStateTracker { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; + protected trimmedLines: string[]; + protected bareBacktickPositions: number[]; private markdownNestCount: number = 0; private lastProcessedIndex: number = -1; @@ -72,9 +72,8 @@ export class MarkdownBlockStateTracker { if (currentLine.match(/^`+$/)) { // Found bare backticks - check if this is the last one if (j === currentIndex) { - const remainingBareBackticks = this.bareBacktickPositions.filter( - (pos) => pos > j, - ).length; + const remainingBareBackticks = + this.getRemainingBareBackticksAfter(j); if (remainingBareBackticks === 0) { this.markdownNestCount = 0; this.lastProcessedIndex = j; @@ -99,6 +98,28 @@ export class MarkdownBlockStateTracker { this.lastProcessedIndex = currentIndex; return false; } + + /** + * Efficiently determines if there are remaining bare backticks after the given position. + */ + getRemainingBareBackticksAfter(currentIndex: number): number { + return this.bareBacktickPositions.filter((pos) => pos > currentIndex) + .length; + } + + /** + * Checks if the line at the given index is a bare backtick line. + */ + isBareBacktickLine(index: number): boolean { + return this.bareBacktickPositions.includes(index); + } + + /** + * Gets the trimmed lines array. + */ + getTrimmedLines(): string[] { + return this.trimmedLines; + } } /** diff --git a/core/utils/markdownUtils.vitest.ts b/core/utils/markdownUtils.vitest.ts index 211bcd8e1..c21c27587 100644 --- a/core/utils/markdownUtils.vitest.ts +++ b/core/utils/markdownUtils.vitest.ts @@ -1,84 +1,306 @@ -import { test, expect } from "vitest"; +import { describe, expect, it } from "vitest"; import { + collectAllLines, headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker, } from "./markdownUtils"; -test("headerIsMarkdown correctly identifies markdown headers", () => { - // Should return true for markdown headers - expect(headerIsMarkdown("md")).toBe(true); - expect(headerIsMarkdown("markdown")).toBe(true); - expect(headerIsMarkdown("gfm")).toBe(true); - expect(headerIsMarkdown("github-markdown")).toBe(true); - expect(headerIsMarkdown("language md")).toBe(true); - expect(headerIsMarkdown("language markdown")).toBe(true); - expect(headerIsMarkdown("filename.md")).toBe(true); - expect(headerIsMarkdown("path/to/file.md language")).toBe(true); +describe("headerIsMarkdown", () => { + // Test exact match with common Markdown identifiers + it("should identify exact matches with common Markdown identifiers", () => { + expect(headerIsMarkdown("md")).toBe(true); + expect(headerIsMarkdown("markdown")).toBe(true); + expect(headerIsMarkdown("gfm")).toBe(true); + expect(headerIsMarkdown("github-markdown")).toBe(true); + }); - // Should return false for non-markdown headers - expect(headerIsMarkdown("javascript")).toBe(false); - expect(headerIsMarkdown("typescript")).toBe(false); - expect(headerIsMarkdown("python")).toBe(false); - expect(headerIsMarkdown("")).toBe(false); + // Test identifiers preceded by a space + it("should identify identifiers preceded by a space", () => { + expect(headerIsMarkdown("lang md")).toBe(true); + expect(headerIsMarkdown("something markdown")).toBe(true); + expect(headerIsMarkdown("language gfm")).toBe(true); + expect(headerIsMarkdown("spec github-markdown")).toBe(true); + }); + + // Test file extensions + it("should identify file names with markdown extensions", () => { + expect(headerIsMarkdown("example.md")).toBe(true); + expect(headerIsMarkdown("document.markdown")).toBe(true); + expect(headerIsMarkdown("readme.gfm")).toBe(true); + }); + + // Test more complex cases with extensions + it("should identify file names with markdown extensions followed by other text", () => { + expect(headerIsMarkdown("example.md additional text")).toBe(true); + expect(headerIsMarkdown("document.markdown with some description")).toBe( + true, + ); + expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true); + }); + + // Test non-markdown cases + it("should not identify non-markdown headers", () => { + expect(headerIsMarkdown("javascript")).toBe(false); + expect(headerIsMarkdown("typescript")).toBe(false); + expect(headerIsMarkdown("plain")).toBe(false); + expect(headerIsMarkdown("python")).toBe(false); + }); + + // Test edge cases + it("should handle edge cases correctly", () => { + expect(headerIsMarkdown("")).toBe(false); + expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md" + expect(headerIsMarkdown("readme md")).toBe(true); + expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension + }); + + // Test case sensitivity + it("should respect case sensitivity", () => { + expect(headerIsMarkdown("MD")).toBe(false); + expect(headerIsMarkdown("MARKDOWN")).toBe(false); + expect(headerIsMarkdown("example.MD")).toBe(false); + expect(headerIsMarkdown("lang MD")).toBe(false); + }); + + // Test with special characters and spacing + it("should handle special characters and spacing correctly", () => { + expect(headerIsMarkdown(" md")).toBe(true); // Space before "md" + expect(headerIsMarkdown("md ")).toBe(true); // Space after "md" + expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix + expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix + }); }); -test("isMarkdownFile correctly identifies markdown files", () => { - // Should return true for markdown files - expect(isMarkdownFile("test.md")).toBe(true); - expect(isMarkdownFile("path/to/file.markdown")).toBe(true); - expect(isMarkdownFile("README.md")).toBe(true); +describe("isMarkdownFile", () => { + it("should identify markdown files by .md extension", () => { + expect(isMarkdownFile("README.md")).toBe(true); + expect(isMarkdownFile("docs/guide.md")).toBe(true); + expect(isMarkdownFile("/path/to/file.md")).toBe(true); + }); - // Should return false for non-markdown files - expect(isMarkdownFile("test.js")).toBe(false); - expect(isMarkdownFile("script.ts")).toBe(false); - expect(isMarkdownFile("")).toBe(false); - expect(isMarkdownFile(undefined)).toBe(false); + it("should identify markdown files by .markdown extension", () => { + expect(isMarkdownFile("README.markdown")).toBe(true); + expect(isMarkdownFile("docs/guide.markdown")).toBe(true); + expect(isMarkdownFile("/path/to/file.markdown")).toBe(true); + }); + + it("should identify markdown files by .gfm extension", () => { + expect(isMarkdownFile("README.gfm")).toBe(true); + expect(isMarkdownFile("docs/guide.gfm")).toBe(true); + expect(isMarkdownFile("/path/to/file.gfm")).toBe(true); + }); + + it("should handle case insensitive extensions", () => { + expect(isMarkdownFile("README.MD")).toBe(true); + expect(isMarkdownFile("guide.MARKDOWN")).toBe(true); + expect(isMarkdownFile("file.GFM")).toBe(true); + }); + + it("should return false for non-markdown files", () => { + expect(isMarkdownFile("script.js")).toBe(false); + expect(isMarkdownFile("style.css")).toBe(false); + expect(isMarkdownFile("data.json")).toBe(false); + expect(isMarkdownFile("document.txt")).toBe(false); + }); + + it("should return false for undefined or empty filepath", () => { + expect(isMarkdownFile(undefined)).toBe(false); + expect(isMarkdownFile("")).toBe(false); + }); + + it("should return false for files without extensions", () => { + expect(isMarkdownFile("README")).toBe(false); + expect(isMarkdownFile("Dockerfile")).toBe(false); + }); + + it("should handle files with multiple dots", () => { + expect(isMarkdownFile("file.backup.md")).toBe(true); + expect(isMarkdownFile("config.test.js")).toBe(false); + }); }); -test("MarkdownBlockStateTracker correctly tracks nested markdown blocks", () => { - const lines = [ - "# Header", - "", - "Some text", - "", - "```md", - "Nested markdown content", - "```javascript", - "function test() {", - " return true;", - "}", - "```", - "More nested markdown", - "```", - "", - "End of file", - ]; +describe("MarkdownBlockStateTracker", () => { + it("should initialize correctly with empty lines", () => { + const tracker = new MarkdownBlockStateTracker([]); + expect(tracker.shouldStopAtPosition(0)).toBe(false); + }); - const stateTracker = new MarkdownBlockStateTracker(lines); + it("should initialize correctly with non-markdown lines", () => { + const tracker = new MarkdownBlockStateTracker([ + "const x = 5;", + "console.log(x);", + ]); + expect(tracker.shouldStopAtPosition(0)).toBe(false); + expect(tracker.shouldStopAtPosition(1)).toBe(false); + }); - // First backtick closure is within nested block (not markdown end) - expect(stateTracker.shouldStopAtPosition(10)).toBe(false); + it("should detect simple markdown blocks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "# Title", + "```", + ]); + expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening + expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content + expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing + }); - // This is the backtick that closes the outer markdown block - expect(stateTracker.shouldStopAtPosition(12)).toBe(true); + it("should handle nested code blocks within markdown", () => { + const tracker = new MarkdownBlockStateTracker([ + "```md", + "Here's some code:", + "```javascript", + "console.log('hello');", + "```", + "More content", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening + expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing + expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing + }); + + it("should handle multiple bare backticks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "Content with ```inline``` code", + "```", + "More content", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks + expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks + }); + + it("should handle non-markdown code blocks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```javascript", + "console.log('hello');", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block + }); + + it("should handle mixed markdown types", () => { + const tracker = new MarkdownBlockStateTracker([ + "```gfm", + "# GitHub Flavored Markdown", + "```", + ]); + expect(tracker.shouldStopAtPosition(2)).toBe(true); + }); + + it("should handle state persistence across multiple calls", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "# Documentation", + "```typescript", + "interface Config {}", + "```", + "Final notes", + "```", + ]); + + // Process incrementally + expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening + expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing + expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing + }); + + it("should handle lines that are not closing backticks", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "Regular content line", + "```", + ]); + expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks + }); + + it("should provide access to trimmed lines", () => { + const tracker = new MarkdownBlockStateTracker([ + " ```markdown ", + " # Title ", + " ``` ", + ]); + const trimmedLines = tracker.getTrimmedLines(); + expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]); + }); + + it("should identify bare backtick lines correctly", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "```", + "content", + "```", + ]); + expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language + expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks + expect(tracker.isBareBacktickLine(2)).toBe(false); // Content + expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks + }); + + it("should count remaining bare backticks correctly", () => { + const tracker = new MarkdownBlockStateTracker([ + "```markdown", + "```", + "content", + "```", + "more content", + "```", + ]); + expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening + expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare + expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare + expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare + }); }); -test("MarkdownBlockStateTracker handles simple code blocks correctly", () => { - const lines = [ - "Some code:", - "", - "```javascript", - "function test() {", - " return true;", - "}", - "```", - "", - "More text", - ]; +describe("collectAllLines", () => { + async function* createAsyncGenerator(items: T[]): AsyncGenerator { + for (const item of items) { + yield item; + } + } - const stateTracker = new MarkdownBlockStateTracker(lines); + it("should collect all lines from a stream", async () => { + const stream = createAsyncGenerator(["line1", "line2", "line3"]); + const result = await collectAllLines(stream); + expect(result).toEqual(["line1", "line2", "line3"]); + }); - // This is just a simple code block, not nested markdown - expect(stateTracker.shouldStopAtPosition(6)).toBe(false); + it("should handle empty streams", async () => { + const stream = createAsyncGenerator([]); + const result = await collectAllLines(stream); + expect(result).toEqual([]); + }); + + it("should handle streams with mixed types", async () => { + const stream = createAsyncGenerator([1, "text", null, true]); + const result = await collectAllLines(stream); + expect(result).toEqual([1, "text", null, true]); + }); + + it("should handle streams with empty strings", async () => { + const stream = createAsyncGenerator(["", "line2", "", "line4"]); + const result = await collectAllLines(stream); + expect(result).toEqual(["", "line2", "", "line4"]); + }); + + it("should handle large streams", async () => { + const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`); + const stream = createAsyncGenerator(largeArray); + const result = await collectAllLines(stream); + expect(result).toEqual(largeArray); + }); + + it("should handle object streams", async () => { + const objects = [ + { type: "new", line: "const x = 5;" }, + { type: "old", line: "let y = 10;" }, + ]; + const stream = createAsyncGenerator(objects); + const result = await collectAllLines(stream); + expect(result).toEqual(objects); + }); }); diff --git a/core/utils/streamMarkdownUtils.ts b/core/utils/streamMarkdownUtils.ts index 94505dfdf..88e8eabec 100644 --- a/core/utils/streamMarkdownUtils.ts +++ b/core/utils/streamMarkdownUtils.ts @@ -1,8 +1,5 @@ import { LineStream } from "../diff/util"; -import { - isMarkdownFile, - MarkdownBlockStateTracker -} from "./markdownUtils"; +import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils"; /** * Determines if we should stop at a markdown block based on nested markdown logic. diff --git a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts b/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts deleted file mode 100644 index 51649c251..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { headerIsMarkdown } from "./headerIsMarkdown"; - -describe("headerIsMarkdown", () => { - // Test exact match with common Markdown identifiers - it("should identify exact matches with common Markdown identifiers", () => { - expect(headerIsMarkdown("md")).toBe(true); - expect(headerIsMarkdown("markdown")).toBe(true); - expect(headerIsMarkdown("gfm")).toBe(true); - expect(headerIsMarkdown("github-markdown")).toBe(true); - }); - - // Test identifiers preceded by a space - it("should identify identifiers preceded by a space", () => { - expect(headerIsMarkdown("lang md")).toBe(true); - expect(headerIsMarkdown("something markdown")).toBe(true); - expect(headerIsMarkdown("language gfm")).toBe(true); - expect(headerIsMarkdown("spec github-markdown")).toBe(true); - }); - - // Test file extensions - it("should identify file names with markdown extensions", () => { - expect(headerIsMarkdown("example.md")).toBe(true); - expect(headerIsMarkdown("document.markdown")).toBe(true); - expect(headerIsMarkdown("readme.gfm")).toBe(true); - }); - - // Test more complex cases with extensions - it("should identify file names with markdown extensions followed by other text", () => { - expect(headerIsMarkdown("example.md additional text")).toBe(true); - expect(headerIsMarkdown("document.markdown with some description")).toBe( - true, - ); - expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true); - }); - - // Test non-markdown cases - it("should not identify non-markdown headers", () => { - expect(headerIsMarkdown("javascript")).toBe(false); - expect(headerIsMarkdown("typescript")).toBe(false); - expect(headerIsMarkdown("plain")).toBe(false); - expect(headerIsMarkdown("python")).toBe(false); - }); - - // Test edge cases - it("should handle edge cases correctly", () => { - expect(headerIsMarkdown("")).toBe(false); - expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md" - expect(headerIsMarkdown("readme md")).toBe(true); - expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension - }); - - // Test case sensitivity - it("should respect case sensitivity", () => { - expect(headerIsMarkdown("MD")).toBe(false); - expect(headerIsMarkdown("MARKDOWN")).toBe(false); - expect(headerIsMarkdown("example.MD")).toBe(false); - expect(headerIsMarkdown("lang MD")).toBe(false); - }); - - // Test with special characters and spacing - it("should handle special characters and spacing correctly", () => { - expect(headerIsMarkdown(" md")).toBe(true); // Space before "md" - expect(headerIsMarkdown("md ")).toBe(true); // Space after "md" - expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix - expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix - }); -}); diff --git a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts deleted file mode 100644 index cfdba2fde..000000000 --- a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Determines if a given header string represents Markdown content. - * - * The function checks various patterns to identify Markdown headers: - * - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown) - * - Contains these identifiers preceded by a space - * - First word has a file extension of md, markdown, or gfm - * - * @param header - The string to check for Markdown indicators - * @returns True if the header represents Markdown content, false otherwise - */ -export function headerIsMarkdown(header: string): boolean { - return ( - header === "md" || - header === "markdown" || - header === "gfm" || - header === "github-markdown" || - header.includes(" md") || - header.includes(" markdown") || - header.includes(" gfm") || - header.includes(" github-markdown") || - header.split(" ")[0]?.split(".").pop() === "md" || - header.split(" ")[0]?.split(".").pop() === "markdown" || - header.split(" ")[0]?.split(".").pop() === "gfm" - ); -} diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index b054f0bd9..380c1a18a 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -7,48 +7,10 @@ Note, this was benchmarked at sub-millisecond */ -import { headerIsMarkdown } from "./headerIsMarkdown"; - -/** - * Optimized state tracker for markdown patch operations to avoid recomputing on each call. - */ -class MarkdownPatchStateTracker { - private trimmedLines: string[]; - private bareBacktickPositions: number[]; - - constructor(lines: string[]) { - this.trimmedLines = lines.map((l) => l.trim()); - // Pre-compute positions of all bare backtick lines for faster lookup - this.bareBacktickPositions = []; - for (let i = 0; i < this.trimmedLines.length; i++) { - if (this.trimmedLines[i].match(/^`+$/)) { - this.bareBacktickPositions.push(i); - } - } - } - - /** - * Efficiently determines if there are remaining bare backticks after the given position. - */ - getRemainingBareBackticksAfter(currentIndex: number): number { - return this.bareBacktickPositions.filter((pos) => pos > currentIndex) - .length; - } - - /** - * Checks if the line at the given index is a bare backtick line. - */ - isBareBacktickLine(index: number): boolean { - return this.bareBacktickPositions.includes(index); - } - - /** - * Gets the trimmed lines array. - */ - getTrimmedLines(): string[] { - return this.trimmedLines; - } -} +import { + headerIsMarkdown, + MarkdownBlockStateTracker, +} from "../../../../../core/utils/markdownUtils"; export const patchNestedMarkdown = (source: string): string => { // Early return if no markdown codeblock pattern is found (including GitHub variants) @@ -59,7 +21,7 @@ export const patchNestedMarkdown = (source: string): string => { const lines = source.split("\n"); // Use optimized state tracker for efficient bare backtick analysis - const stateTracker = new MarkdownPatchStateTracker(lines); + const stateTracker = new MarkdownBlockStateTracker(lines); const trimmedLines = stateTracker.getTrimmedLines(); for (let i = 0; i < trimmedLines.length; i++) { From 71fed98d36d14b21ea63cd054b0323aec6c871aa Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Wed, 23 Jul 2025 14:42:21 +0200 Subject: [PATCH 16/26] fix: Remove redundant jcef.out-of-process=false from run configs Related to #6611 --- extensions/intellij/.run/Run Extension.run.xml | 1 - extensions/intellij/.run/Run Qodana.run.xml | 1 - extensions/intellij/.run/Run Test IDE.run.xml | 1 - extensions/intellij/.run/Run Tests.run.xml | 1 - 4 files changed, 4 deletions(-) diff --git a/extensions/intellij/.run/Run Extension.run.xml b/extensions/intellij/.run/Run Extension.run.xml index 4bd794de1..30a38f6c4 100644 --- a/extensions/intellij/.run/Run Extension.run.xml +++ b/extensions/intellij/.run/Run Extension.run.xml @@ -20,7 +20,6 @@ - - -