You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "dedsec-terminal (via GitHub)" <gi...@apache.org> on 2026/09/14 19:23:12 UTC

[PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

dedsec-terminal opened a new pull request, #5311:
URL: https://github.com/apache/maka/pull/5311

   ## Summary
   
   `prepareMarkdownMath()` tokenizes `\[...\]` as display math before Markdown parsing, so escaped brackets inside link labels became block-level KaTeX inside the `<a>` instead of literal text. The math scanner now recognizes inline links/images, re-scans labels with display math disabled (inline math still renders inside labels), and rewrites escaped brackets in real link labels as literal transport tokens so bracket matching still forms the link.
   
   Fixes #5310
   
   ## Verification
   
   - New regression tests in `packages/ui/src/__tests__/markdown-body.test.ts` (escaped-bracket label, inline math in label, `$$` in label stays literal, display math after a link). Checked the two display-math tests fail on unpatched `markdown-math.tsx` and all pass with the fix: `markdown-body` 39/39, han/rhythm suites 4/4.
   - `biome check` and `tsc` build clean on the changed files.
   - Full `@maka/ui` dist suite: only failures are 6 pre-existing `mermaid-render-cache` environment failures, identical on the pristine tree.
   - Did not run Desktop/E2E lanes.
   
   ## AI use
   
   Select exactly one:
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: OpenCode (Muse Spark) - root-cause analysis, the link-aware preprocessing fix and regression tests, plus the local verification above.
   
   ## Checklist
   
   - [x] Tests cover the change and fail without it
   - [x] Lint, format, typecheck and the affected suites pass locally
   
   Does this PR entail a change in behavior?
   
   - [x] Yes — described under Summary above
   - [ ] No


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4008996656


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +338,165 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a Markdown inline link or image starting at `index` so its label
+ * can be re-scanned without display math. Bare `[text]` without a `(...)` or
+ * `[ref]` tail is left alone: without the tail there is no link whose inline
+ * layout display math could break.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  let isImage = false;
+  if (source[index] === '!') {
+    if (index + 1 >= source.length) return { kind: 'pending', end: index + 1 };
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+    isImage = true;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const labelEnd = findLabelEnd(source, openerEnd);
+  if (labelEnd === 'pending') return { kind: 'pending', end: openerEnd };
+  if (labelEnd === 'invalid') return undefined;
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);

Review Comment:
   [P2] Bound or linearize the pending link-tail scan. For every `[x](` opener without a closing `)`, `findInlineTailEnd()` walks the entire remaining suffix and this branch resumes from only `openerEnd`, so repeated openers are quadratic; the pending state also leaves `safeSourceEnd=0`, forcing every streaming append to repeat the whole scan. On this exact head, a 128,000-character input took 6.68 s in `prepareMarkdownMath` versus 24.7 ms on the exact base; streaming 16 chunks to 64,000 characters took 18.6 s cumulatively versus 17 ms. This runs synchronously before Markdown rendering, so one malformed model or user message can freeze the Desktop. Please use a single-pass or bounded parser, or advance/fence pending tails, and add an adversarial linear-time regression.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +338,165 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a Markdown inline link or image starting at `index` so its label
+ * can be re-scanned without display math. Bare `[text]` without a `(...)` or

Review Comment:
   [P2] Cover the standard collapsed and shortcut reference-link forms before rewriting label identity. Astryx already resolves both. On the exact base, `[\\[DISCUSS\\] label][]` plus its matching definition renders an anchor (with the old unwanted display math); on this head the use-site label becomes literal transport tokens while the definition becomes a display-math token, so the reference IDs no longer match and the UI shows literal `[[DISCUSS] label][]`. A shortcut reference still forms an anchor but keeps the original block KaTeX inside it because this scanner deliberately ignores a label without an explicit tail. The escaped-bracket fix needs to preserve identity across full, collapsed, and shortcut reference definitions, with regressions for both forms.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4009724930


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +338,165 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a Markdown inline link or image starting at `index` so its label
+ * can be re-scanned without display math. Bare `[text]` without a `(...)` or
+ * `[ref]` tail is left alone: without the tail there is no link whose inline
+ * layout display math could break.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  let isImage = false;
+  if (source[index] === '!') {
+    if (index + 1 >= source.length) return { kind: 'pending', end: index + 1 };
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+    isImage = true;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const labelEnd = findLabelEnd(source, openerEnd);
+  if (labelEnd === 'pending') return { kind: 'pending', end: openerEnd };
+  if (labelEnd === 'invalid') return undefined;
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);

Review Comment:
   Addressed in e65c4676c. Link-tail parsing is now bounded and pending tails consume the suffix once; valid link tails remain opaque. Added full/streaming adversarial regressions for repeated malformed [x]( input; focused runs stayed under 1 ms locally.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +338,165 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a Markdown inline link or image starting at `index` so its label
+ * can be re-scanned without display math. Bare `[text]` without a `(...)` or

Review Comment:
   Addressed in e65c4676c. Closed labels now use escaped-bracket transport consistently across full, collapsed, and shortcut reference uses and definitions; valid link tails stay opaque so reference IDs and hrefs remain unchanged. Added regressions for all three forms.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6162178402

   Addressed the review feedback:
   
   - Fixed pending inline tail handling in \	ranslateMarkdownMath\ (\packages/ui/src/markdown-math.tsx\) so an incomplete inline tail (\](\...\) does not bypass normal prose and math processing, while continuing to defer settlement across streaming chunks.
   - Added \character !== ']'\ to the final-character settlement guard to prevent trailing \]\ at chunk boundaries from settling prematurely.
   - Added completed-message and incremental streaming regression tests covering both cases in \packages/ui/src/__tests__/markdown-body.test.ts\: \prefix ](literal \\$ text\ (preserves literal \\\$\ without KaTeX) and \prefix ](literal \\(x+1\\) text\ (renders inline KaTeX math).
   - Regenerated \docs/astryx-surface-file-inventory.md\ (335 files) to resolve the stale inventory CI check.
   
   Local verification:
   - \
   pm run astryx:surface-inventory\: PASS (335 files, 2 exclusions)
   - \
   pm --workspace @maka/ui run build\: PASS
   - Focused \markdown-body\ suite: 67/67 PASS
   - Full \@maka/ui\ dist suite (\
   pm --workspace @maka/ui run test:dist\): 801/801 PASS (45 suites)
   - Biome & \git diff --check\: clean


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4274103227


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -154,16 +370,103 @@ function translateMarkdownMath(
       continue;
     }
 
+    const link = readMarkdownLink(source, index, leadingBackslashes);
+    if (link?.kind === 'pending') {
+      if (link.pendingInfo !== undefined && safeSourceEnd === index) {
+        onLinkPending?.(link.pendingInfo);
+      }
+      if (!isFinalSegment) {
+        canMarkSafe = false;
+      }
+      if (link.pendingInfo !== undefined) {

Review Comment:
   [P2] Limit display-math suppression to actual link context
   
   Any unfinished first label or destination sets this flag for the rest of the source. Completed Markdown containing `[unfinished\n\[x^2\]` or `[label](unfinished\n$$x^2$$` (each `\n` denotes an actual newline) therefore loses a valid display equation despite never forming a link. The resumed scan at line 123 also disables display math unconditionally: rendering `](\[x^2\]` in one update produces a formula, but appending the identical text character by character leaves no formula after streaming finishes. Both production Chromium reproductions fail here and pass with the immediately preceding math module. Keep display-math suppression bounded to the relevant link-label/reference context and preserve pending-kind context on the resumed path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4014466382


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +406,184 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+// NOTE: label scans deliberately have no length cap (tails keep theirs).

Review Comment:
   [P2] Keep unfinished label scans incremental
   
   Removing the cap fixes complete long labels, but an unclosed `[` now has no progress boundary. `findLabelEnd()` scans to EOF, `readMarkdownLink()` returns pending, and `protectMarkdownMath()` leaves `safeSourceEnd=0`; the next `MarkdownBody` update repeats the entire scan. On this exact head, a 256,000-character assistant stream appended in 10-character updates took 29.8 seconds of cumulative synchronous preprocessing versus 21.8 seconds on the immediate parent `616a4e3c`; a 128,000-character stream in 16-character updates took 4.2-5.1 seconds versus 1.7-2.5 seconds on the exact base. The added test exercises only a completed one-shot label, so it cannot catch this pending-stream path. Preserve unlimited completed labels, but retain incremental parser state or a bound that applies only while the label is unfinished, and add a streaming malformed-label regression.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4267125108


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -154,16 +265,104 @@ function translateMarkdownMath(
       continue;
     }
 
+    const link = readMarkdownLink(source, index, leadingBackslashes);
+    if (link?.kind === 'pending') {
+      // Remember the scan only when everything before its opener already
+      // settled: an earlier unresolved backtick or math opener must be
+      // reparsed together with later chunks, and resuming just the label
+      // would skip it forever.
+      if (link.labelState !== undefined && safeSourceEnd === index) {
+        onLabelPending?.(link.labelState);
+      }
+      text += source.slice(index, link.end);
+      index = link.end;
+      atLineStart = false;
+      if (isFinalSegment) {
+        markSafe();
+      } else {
+        canMarkSafe = false;
+      }
+      continue;
+    }
+    if (link?.kind === 'match') {
+      // A bare closed label with nothing after it can still grow an inline
+      // or reference tail, so it must not settle: resuming after it would
+      // scan that tail without the label context. Once any byte follows the
+      // label the link question is decided and settling is safe again.
+      const mayGrowTail = link.end === link.labelEnd + 1 && link.end >= source.length;
+      // Display math renders as a block, which cannot live inside an inline
+      // link label, and Markdown reads `\[` / `\]` there as literal escaped
+      // brackets. Re-run every closed label with display math disabled so
+      // escaped brackets survive for Markdown to unescape; inline math still
+      // renders inside. Astryx decides later whether the label is an inline
+      // link, reference use, shortcut, image, or definition, so all forms
+      // must share this representation. Image alt text included:
+      // Astryx keeps alt as a raw string, and the image component restores
+      // literal tokens, so no private-use characters reach the DOM.
+      const translatedLabel = translateMarkdownMath(source.slice(link.labelStart, link.labelEnd), {
+        startsAtLineStart: false,
+        priorTextChar: source[link.labelStart - 1],
+        allowDisplayMath: false,
+        protectEscapedBrackets: true,
+        isFinalSegment: true,
+      });
+      // The explicit identifier of a full reference must go through the same
+      // transform, or use-site and definition IDs diverge and the link breaks.
+      let translatedRefText = '';
+      let refSafe = true;
+      if (link.refLabelStart !== undefined && link.refLabelEnd !== undefined) {
+        const translatedRef = translateMarkdownMath(
+          source.slice(link.refLabelStart, link.refLabelEnd),
+          {
+            startsAtLineStart: false,
+            priorTextChar: source[link.refLabelStart - 1],
+            allowDisplayMath: false,
+            protectEscapedBrackets: true,
+            isFinalSegment: true,
+          },
+        );
+        translatedRefText = translatedRef.text;
+        refSafe = translatedRef.safeSourceEnd >= link.refLabelEnd - link.refLabelStart;
+      }
+      const refStart = link.refLabelStart ?? link.end;
+      const refEnd = link.refLabelEnd ?? link.end;
+      text += source.slice(index, link.labelStart)
+        + translatedLabel.text
+        + source.slice(link.labelEnd, refStart)
+        + translatedRefText
+        + source.slice(refEnd, link.end);
+      index = link.end;
+      atLineStart = source[index - 1] === '\n';
+      const labelSafe = translatedLabel.safeSourceEnd >= link.labelEnd - link.labelStart;
+      if (labelSafe && refSafe && !mayGrowTail) {
+        markSafe();
+      } else {
+        canMarkSafe = false;
+      }
+      continue;
+    }
+
     // Destinations take `$` verbatim: escaping there would reach the href,
     // where `\$` does not round-trip back to `$`.
     const destination = readLinkDestination(source, index);
-    if (destination !== undefined) {
-      text += source.slice(index, destination);
-      index = destination;
+    if (destination.kind === 'matched') {
+      text += source.slice(index, destination.end);
+      index = destination.end;
       atLineStart = false;
       markSafe();
       continue;
     }
+    if (destination.kind === 'pending') {
+      text += source.slice(index);

Review Comment:
   [P2] Preserve prose math behavior in an incomplete inline tail
   
   This raw-suffix branch also runs for a stray `](` with no closing `)`, even in a completed message. Through production MarkdownBody, `prefix ](literal $x$ text` now renders x as KaTeX rather than retaining literal dollars, while `prefix ](literal \(x+1\) text` loses the explicit formula and renders plain (x+1). Both additional assertions fail here and pass with the exact e81c1fa4 math module on current dependencies. Keep the boundary unsettled for a future chunk without skipping normal prose translation until a destination actually resolves; cover both completed-message cases while retaining the chunk-boundary fix.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4012969665


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +406,180 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+const MAX_LINK_LABEL_LENGTH = 4096;

Review Comment:
   [P3] Preserve escaped-bracket links and images at the scanner limit. Once a label reaches this 4,096-code-unit cap, `findLabelEnd()` returns the invalid boundary and line 450 converts it to a pending span, so the label is copied without the normalization this PR requires. Through `MarkdownBody` on this exact head, `[\\[DISCUSS\\] ${"a".repeat(4096)}](https://example.com)` produces no `<a>` and displays the Markdown source literally; the exact base produces an anchor (with the old unwanted display math), and an equally long plain label still produces an anchor on this head. The image form likewise loses `<img>`. This creates an undocumented, syntax-dependent length limit for otherwise valid content. Please preserve link/image parsing when the defensive scan cap is reached, and add a boundary regression.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6351393562

   Addressed the remaining review items in `b0a515b1d`:
   
   - Completed renders are now treated as final, so an unterminated reference identifier no longer suppresses display math for the rest of the message. Both `para [a][unfinished\n\[x^2\]` and `para [l][r\n\[x^2\]\n\nnext` render KaTeX again.
   - An explicit reference identifier invalidated by a line break now settles only the first label; its tail is rescanned as ordinary prose, preserving display math there.
   - Corrected the resumed blank-line comparison to use an actual newline and added newline-split regression coverage alongside the completed-render tests.
   
   Verification: `@maka/ui` build passed; full UI suite 815/815 passed; Biome clean on the changed files.
   
   CI on this head is still awaiting workflow approval. Could a maintainer approve the run?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6173610276

   @Astro-Han Rebased against latest upstream `main` (epoch 221) and resolved both P2 edge-case regressions in commit `c8b72edfe`:
   
   1. **Orphan `](` Tails with Line Breaks**:
      - `readLinkDestination` and `scanInlineTail` now explicitly reject raw and escaped line breaks (`\n`, `\r`, `\\\n`) in incomplete link tails and reference destinations. They are preserved as prose so inline math (`\(x+1\)` and `$x$`) and literal dollars render consistently without unintended destination opacity.
   2. **Streaming Reference Identifier Context**:
      - Suppressed display math during speculative incremental translation inside pending link/reference slices. This prevents reference identifiers and labels containing escaped brackets (`prefix [label][\[display\]`) from leaking into block-level `$$` display math during character-by-character streaming, maintaining exact parity with one-shot rendering.
   3. **Upstream Rebase & Surface Inventory**:
      - Rebased cleanly onto latest upstream `main` (epoch 221) and updated surface inventory (`docs/astryx-surface-file-inventory.md`) to 340 files matching upstream main.
   
   ### Verification
   - `npm run astryx:surface-inventory`: PASS (340 files, 2 exclusions)
   - `packages/ui` tests (`markdown-body.test.ts`): 73/73 PASS
   - Full `@maka/ui` dist suite: PASS
   - `npx biome check`: 0 issues
   - DCO sign-off: present on all commits
   - GitHub PR status: `MERGEABLE`
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5772742785

   Addressed the latest review in f8fa56df1:
   
   - preserved backslash escape parity when incremental scanning resumes inside a backslash run;
   - added a regression test comparing incremental and one-shot results;
   - replaced the positional scanner arguments with an options object; and
   - fixed the pending-label formatting issue.
   
   Local verification: Biome is clean for both changed files, and the focused markdown-body suite passes 56/56 tests. The package-wide typecheck still reports existing errors in unrelated UI files; neither changed file reports a type error.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5675528837

   All three P2s from the latest review are addressed on this head: image reference identifiers go through the same normalization while alt text stays verbatim, a trailing lone ! stays unsettled across chunks, and bounded label substrings settle instead of pinning the cache. New regressions for each; markdown-body 47/47 and full UI suite green locally apart from the known mermaid environment failures. Let me know if this works now.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4015191273


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +436,274 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+// NOTE: label scans deliberately have no length cap (tails keep theirs).
+// Finding a close is linear, settling is permanent, and per-chunk rescan cost
+// while a label is still open matches the base behaviour for unclosed math.
+// Capping labels instead degrades complete long labels to literal text,
+// which both breaks the link and pushes a giant literal run downstream that
+// renders far slower than the structured link would have.
+const MAX_LINK_TAIL_DEPTH = 32;
+const MAX_LINK_TAIL_LENGTH = 65536;
+
+type MarkdownLinkScan =
+  | {
+      kind: 'match';
+      labelStart: number;
+      labelEnd: number;
+      end: number;
+      refLabelStart?: number;
+      refLabelEnd?: number;
+    }
+  | { kind: 'pending'; end: number; labelState?: LabelScanState }
+  | undefined;
+
+// Resume state for an unfinished first-label scan, keyed by the owning cache.
+// Only the top-level scan stores here: nested scans re-derive on the next
+// full pass, and any closure funnels through a full reprocess anyway.
+const pendingLabelScans = new WeakMap<MarkdownMathCache, LabelScanState>();
+
+/**
+ * Recognize a bounded Markdown label starting at `index` so its contents can
+ * be re-scanned without display math. Astryx resolves whether a closed label
+ * is an inline link, reference use, shortcut, or definition after this pass;
+ * treating all of them alike keeps reference identities stable.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  if (source[index] === '!') {
+    // A trailing `!` may yet become an image opener once `[` arrives; caching
+    // it as safe would lose the `!` context and mistype the label as a link.
+    if (index + 1 >= source.length) return { kind: 'pending', end: index + 1 };
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const firstScan = scanLabel(source, initialLabelScanState(openerEnd));
+  if (firstScan.kind === 'pending') {
+    return { kind: 'pending', end: source.length, labelState: firstScan.state };
+  }
+  if (firstScan.kind === 'invalid') return { kind: 'pending', end: firstScan.end };
+  const labelEnd = firstScan.end;
+
+  const match = (end: number) => ({
+    kind: 'match' as const,
+    labelStart: openerEnd,
+    labelEnd,
+    end,
+  });
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);
+    if (tailEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof tailEnd !== 'number') return match(tailEnd.end);
+    return match(tailEnd);
+  }
+  if (tail === '[') {
+    const refEnd = findLabelEnd(source, labelEnd + 2);

Review Comment:
   [P2] Resume pending reference identifiers as well
   
   The new continuation state is returned only for `firstScan`. Once the visible label has closed, an unfinished full-reference identifier still comes through `findLabelEnd()` here, which discards its scan state; every streamed update restarts at the reference opener. On this exact head, 128,000 characters appended in 16-character updates took about 3.70 s for `[visible][...` and 5.46 s for `![visible][...`, versus 2.07/2.32 s on exact base; the newly covered first-label case took 0.86 s. Desktop accepts 128,000-character messages, so this remains reachable. The added test uses 1,024-character chunks and only the first label, and therefore does not exercise this branch. Please preserve/resume the second-label state too.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6353226742

   The UI suite and the other checks on this head are green, but the Desktop e2e job hit a cold-start flake: three tests never got past the splash screen and timed out waiting for the composer, while the other 34 passed. The failing specs do not touch Markdown rendering, and it looks like the same class of CI flake noted earlier. I cannot re-run workflows from a fork - could someone re-run the failed job? I have also refreshed the PR description with the current test counts. Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4015561585


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -155,32 +215,125 @@ function protectMarkdownMath(source: string, startsAtLineStart = true): {
       continue;
     }
 
-    const delimited =
-      readDelimitedMath(source, index, '\\(', '\\)', false, false)
-      ?? readDelimitedMath(source, index, '\\[', '\\]', true, true)
-      ?? readDelimitedMath(source, index, '$$', '$$', true, true);
-    if (delimited?.kind === 'pending') {
-      text += source.slice(index, delimited.end);
-      index = delimited.end;
+    const link = readMarkdownLink(source, index);
+    if (link?.kind === 'pending') {
+      if (link.labelState !== undefined) onLabelPending?.(link.labelState);      text += source.slice(index, link.end);

Review Comment:
   [P2] Only cache this label continuation when no earlier syntax is still unresolved. `protectMarkdownMath()` keeps scanning after an unmatched backtick or math opener by setting `canMarkSafe = false`, but this callback still records a later pending `[` unconditionally. On the next append, lines 56-65 assume that label is the only unsettled state and return after scanning it, so a delimiter that closes before the label never gets reparsed. For example, streaming the valid final text `` `[` $$x$$ `` with the first update ending after `` `[ `` leaves the formula literal on this head, while a fresh render produces KaTeX; `\([x\) $$y$$` and `$$[$$ $$y$$` fail similarly. Across eight focused final strings, the current head differed from one-shot output at these split boundaries, while exact base had zero differences. Guard the stored continuation with the same safe-prefix state (or retain all earlier parser state), and add a same-mount regression that closes the preceding code/math delim
 iter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4012634185


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -155,32 +185,154 @@ function protectMarkdownMath(source: string, startsAtLineStart = true): {
       continue;
     }
 
-    const delimited =
-      readDelimitedMath(source, index, '\\(', '\\)', false, false)
-      ?? readDelimitedMath(source, index, '\\[', '\\]', true, true)
-      ?? readDelimitedMath(source, index, '$$', '$$', true, true);
-    if (delimited?.kind === 'pending') {
-      text += source.slice(index, delimited.end);
-      index = delimited.end;
+    const link = readMarkdownLink(source, index);
+    if (link?.kind === 'pending') {
+      text += source.slice(index, link.end);
+      index = link.end;
+      atLineStart = false;
+      if (isFinalSegment) {
+        markSafe();
+      } else {
+        canMarkSafe = false;
+      }
+      continue;
+    }
+    if (link?.kind === 'match') {
+      // A bare closed label with nothing after it can still grow an inline
+      // or reference tail, so it must not settle: resuming after it would
+      // scan that tail without the label context. Once any byte follows the
+      // label the link question is decided and settling is safe again.
+      const mayGrowTail = link.end === link.labelEnd + 1 && link.end >= source.length;
+      if (link.isImage) {
+        // Image alt text is rendered as a raw attribute, not as Markdown
+        // inline content, so it stays verbatim: rewriting its escapes would
+        // leak transport tokens into the attribute. The explicit identifier
+        // of a full image reference still needs the same normalization as
+        // link identifiers, or use and definition diverge.
+        let middle = source.slice(link.labelEnd, link.end);
+        let tailSafe = true;
+        if (link.refLabelStart !== undefined && link.refLabelEnd !== undefined) {
+          const protectedImageRef = protectMarkdownMath(
+            source.slice(link.refLabelStart, link.refLabelEnd),
+            false,
+            false,
+            true,
+            true,
+          );
+          middle = source.slice(link.labelEnd, link.refLabelStart)
+            + protectedImageRef.text
+            + source.slice(link.refLabelEnd, link.end);
+          tailSafe = protectedImageRef.safeSourceEnd >= link.refLabelEnd - link.refLabelStart;
+        }
+        text += source.slice(index, link.labelEnd) + middle;

Review Comment:
   [P2] Preserve image parsing when the alt contains escaped brackets
   
   Leaving the image label source untouched prevents Astryx from recognizing valid images whose alt contains `\\[` / `\\]`. Through the production `MarkdownBody` path, each of these now renders as literal Markdown instead of an `<img>`: `![\\[alt\\] preview](...)`, `![\\[alt\\] preview][pic]`, `![\\[topic\\]][]`, and `![\\[topic\\]]`. Exact base renders an image for all four. The new test at `markdown-body.test.ts:362` only asserts that no math/token appears, so the literal fallback passes unnoticed. Please preserve parser-safe escaped brackets for the alt while restoring the literal alt value, and assert both `<img>` presence and its final `alt` for inline/full/collapsed/shortcut forms.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5679208454

   That one was my bug, sorry - the resumed scan was using positions relative to the sliced tail on the full source, so any settled prefix before the label threw it off and the close was never found. The stored state is now absolutized at store time. Also added the two streamed-label regressions from the follow-up shape (unclosed stream stays unsettled and fast, close-append converges to one-shot). Markdown-body 53/53 locally.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6169841281

   @me2seeks Addressed the P2 performance review in commit `5ed975c91`:
   
   - **Preserved resumable label and tail scan progress**: Threaded LabelScanState and TailScanState through onLinkPending callback in 	ranslateMarkdownMath, retaining scan progress across chunk appends rather than restarting from initialLabelScanState(openerEnd) on every update.
   - **Speculative safe checkpoints**: Maintained speculative safe bounds so incomplete labels and reference identifiers do not disable safe checkpoints, allowing streaming chunks to advance in O(N) without re-scanning and re-translating the entire prefix.
   - **Clean reparsing on closure**: Preserved re-parsing of the original source once the label or destination closes.
   - **Small-chunk regression coverage**: Added small-chunk streaming regression test covering unfinished labels, reference identifiers, and inline tails (streams unfinished labels, identifiers, and tails in small chunks without quadratic slowdown), asserting synchronous execution time remains within the linear streaming budget.
   
   Local verification:
   - 
   pm --workspace @maka/ui run build: PASS
   - Focused markdown-body suite: 68/68 PASS
   - git diff --check: clean
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4013422970


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +406,185 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+// Bounds incomplete label scans the same way tails are bounded: a close found
+// anywhere inside still resolves and settles, so only genuinely unfinished
+// input pays per-chunk rescan cost. Complete labels beyond this fall back to
+// literal text, matching the tail behaviour.
+const MAX_LINK_LABEL_LENGTH = 65536;

Review Comment:
   [P2] The regression is moved to 65,536 characters rather than removed. Desktop accepts send text up to 128,000 characters (`apps/desktop/src/main/permission-response-guard.ts:44,382`), so this limit is reachable with valid input. On this exact head, rendering `[\\[DISCUSS\\] ${"a".repeat(65524)}](https://example.com/long)` through the production `MarkdownBody` takes about 4.0 seconds synchronously and produces no `<a>`; the exact base renders the same 65,564-character input as a link in about 20–28 ms. The new regression only exercises 4,096 filler characters, so it stays below this new cutoff and cannot catch the failure. Please either cover the full accepted message bound or preserve valid closed labels without sending the over-limit form through the pathological fallback, and add a boundary test above the actual cutoff.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5675974225

   This one is addressed too: images now go through the same label normalization, and the image component restores literal tokens back to plain text for alt, so all four forms render <img> with the literal alt and nothing leaks into the DOM. Regressions cover inline, full, collapsed, and shortcut forms with exact alt assertions. Markdown-body 48/48 and full UI green locally apart from the known mermaid environment failures. Let me know if this works now.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5703758038

   @hqhq1025 anything else u need from my side.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5703763234

   <!-- maka-lifecycle:reopened -->


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6354057955

   > **Automated review notice:** This comment was posted by an automated review agent. It is not an independent human review and does not replace one.
   
   CI follow-up for `b0a515b1d9f38b28d8fe58b9ac4dafd278e6fc79`: [run 39855097867, attempt 1](https://github.com/apache/maka/actions/runs/39855097867/attempts/1) failed with 34/37 Desktop E2E tests passing. The three failures are `composer-directory-reference`, `composer-session-reference`, and the WorkHub attachment-rejection test in `expected-failure-feedback`. All time out in the fixture waiting for the editable composer; the captured window remains on the startup screen.
   
   The three specs and their launcher fixture are identical to current main. This does not prove a main failure or establish that this PR caused the timeout. I have not classified it as a new P2 or a confirmed flake. I requested one rerun of the failed job; a successful exact-head CI result is still outstanding. The earlier local validation and repaired math findings remain as documented in [the code review](https://github.com/apache/maka/pull/5311#pullrequestreview-5621444074).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5676376088

   Confirmed real on this head, fixed: the label scan bound is now aligned with the tail bound, so complete long labels still resolve and settle instead of falling back to literal text. Boundary regressions for the link and image forms included. Markdown-body 50/50 and full UI green locally apart from the known mermaid environment failures.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4010584316


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -155,25 +174,115 @@ function protectMarkdownMath(source: string, startsAtLineStart = true): {
       continue;
     }
 
-    const delimited =
-      readDelimitedMath(source, index, '\\(', '\\)', false, false)
-      ?? readDelimitedMath(source, index, '\\[', '\\]', true, true)
-      ?? readDelimitedMath(source, index, '$$', '$$', true, true);
-    if (delimited?.kind === 'pending') {
-      text += source.slice(index, delimited.end);
-      index = delimited.end;
+    const link = readMarkdownLink(source, index);
+    if (link?.kind === 'pending') {
+      text += source.slice(index, link.end);
+      index = link.end;
       atLineStart = false;
       canMarkSafe = false;
       continue;
     }
-    if (delimited?.kind === 'match') {
-      text += mathToken(delimited.formula, delimited.displayMode);
-      index = delimited.end;
+    if (link?.kind === 'match') {
+      // A bare closed label with nothing after it can still grow an inline
+      // or reference tail, so it must not settle: resuming after it would
+      // scan that tail without the label context. Once any byte follows the
+      // label the link question is decided and settling is safe again.
+      const mayGrowTail = link.end === link.labelEnd + 1 && link.end >= source.length;

Review Comment:
   [P2] This cache hold starts only after the scanner has already seen `![`, so a stream whose first chunk ends at the lone `!` still caches that byte as safe. On the next update scanning resumes at `[` and treats the image label as an ordinary link label. In a production `MarkdownBody` rerender, `!` followed by `![alt \\[x\\]](https://example.com/a.png)` produced an image whose alt contains private-use `MAKA_MATH` tokens, while a fresh mount of the identical final source rendered literal Markdown. Keep an unescaped trailing `!` unsafe (or preserve enough lookbehind) and add an image split-boundary regression.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -155,25 +174,115 @@ function protectMarkdownMath(source: string, startsAtLineStart = true): {
       continue;
     }
 
-    const delimited =
-      readDelimitedMath(source, index, '\\(', '\\)', false, false)
-      ?? readDelimitedMath(source, index, '\\[', '\\]', true, true)
-      ?? readDelimitedMath(source, index, '$$', '$$', true, true);
-    if (delimited?.kind === 'pending') {
-      text += source.slice(index, delimited.end);
-      index = delimited.end;
+    const link = readMarkdownLink(source, index);
+    if (link?.kind === 'pending') {
+      text += source.slice(index, link.end);
+      index = link.end;
       atLineStart = false;
       canMarkSafe = false;
       continue;
     }
-    if (delimited?.kind === 'match') {
-      text += mathToken(delimited.formula, delimited.displayMode);
-      index = delimited.end;
+    if (link?.kind === 'match') {
+      // A bare closed label with nothing after it can still grow an inline
+      // or reference tail, so it must not settle: resuming after it would
+      // scan that tail without the label context. Once any byte follows the
+      // label the link question is decided and settling is safe again.
+      const mayGrowTail = link.end === link.labelEnd + 1 && link.end >= source.length;
+      if (link.isImage) {
+        // Image alt text is rendered as a raw attribute, not as Markdown
+        // inline content. Leave its source untouched and continue scanning
+        // the destination normally.
+        text += source.slice(index, link.end);

Review Comment:
   [P2] Apply the escaped-bracket/reference-ID normalization to images too. This branch copies the entire image use unchanged, while the matching definition label is normalized later. On this head, valid `![visible][\\[topic\\]]` with `[\\[topic\\]]: https://example.com/image.png` renders as literal Markdown; the exact base renders `<img src="https://example.com/image.png" alt="visible">`. Inline, collapsed, and shortcut image forms with escaped brackets fail similarly, and the new tests cover only links. Preserve image identity while keeping alt text non-math, and add image regressions.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -155,25 +174,115 @@ function protectMarkdownMath(source: string, startsAtLineStart = true): {
       continue;
     }
 
-    const delimited =
-      readDelimitedMath(source, index, '\\(', '\\)', false, false)
-      ?? readDelimitedMath(source, index, '\\[', '\\]', true, true)
-      ?? readDelimitedMath(source, index, '$$', '$$', true, true);
-    if (delimited?.kind === 'pending') {
-      text += source.slice(index, delimited.end);
-      index = delimited.end;
+    const link = readMarkdownLink(source, index);
+    if (link?.kind === 'pending') {
+      text += source.slice(index, link.end);
+      index = link.end;
       atLineStart = false;
       canMarkSafe = false;
       continue;
     }
-    if (delimited?.kind === 'match') {
-      text += mathToken(delimited.formula, delimited.displayMode);
-      index = delimited.end;
+    if (link?.kind === 'match') {
+      // A bare closed label with nothing after it can still grow an inline
+      // or reference tail, so it must not settle: resuming after it would
+      // scan that tail without the label context. Once any byte follows the
+      // label the link question is decided and settling is safe again.
+      const mayGrowTail = link.end === link.labelEnd + 1 && link.end >= source.length;
+      if (link.isImage) {
+        // Image alt text is rendered as a raw attribute, not as Markdown
+        // inline content. Leave its source untouched and continue scanning
+        // the destination normally.
+        text += source.slice(index, link.end);
+        index = link.end;
+        atLineStart = false;
+        if (mayGrowTail) {
+          canMarkSafe = false;
+        } else {
+          markSafe();
+        }
+        continue;
+      }
+      // Display math renders as a block, which cannot live inside an inline
+      // link label, and Markdown reads `\[` / `\]` there as literal escaped
+      // brackets. Re-run every closed label with display math disabled so
+      // escaped brackets survive for Markdown to unescape; inline math still
+      // renders inside. Astryx decides later whether the label is an inline
+      // link, reference use, shortcut, or definition, so all forms must share
+      // this transport representation.
+      const protectedLabel = protectMarkdownMath(
+        source.slice(link.labelStart, link.labelEnd),
+        false,
+        false,
+        true,
+      );
+      // The explicit identifier of a full reference must go through the same
+      // transform, or use-site and definition IDs diverge and the link breaks.
+      let protectedRefText = '';
+      let refSafe = true;
+      if (link.refLabelStart !== undefined && link.refLabelEnd !== undefined) {
+        const protectedRef = protectMarkdownMath(
+          source.slice(link.refLabelStart, link.refLabelEnd),
+          false,
+          false,
+          true,
+        );
+        protectedRefText = protectedRef.text;
+        refSafe = protectedRef.safeSourceEnd >= link.refLabelEnd - link.refLabelStart;
+      }
+      const refStart = link.refLabelStart ?? link.end;
+      const refEnd = link.refLabelEnd ?? link.end;
+      text += source.slice(index, link.labelStart)
+        + protectedLabel.text
+        + source.slice(link.labelEnd, refStart)
+        + protectedRefText
+        + source.slice(refEnd, link.end);
+      index = link.end;
+      atLineStart = source[index - 1] === '\n';
+      const labelSafe = protectedLabel.safeSourceEnd >= link.labelEnd - link.labelStart;

Review Comment:
   [P2] A closed label should not inherit end-of-input uncertainty from the recursive scanner. For the valid link `[price$](https://example.com)`, the nested label scan treats the terminal `$` as a possible future `$$`, so `labelSafe` is false and permanently disables every later cache checkpoint. A 512 KiB response appended in 64 updates took 1.58 s here with `safeSourceEnd=0`, versus 66 ms on the exact base (and 93 ms for a normal label on this head); 1 MiB/128 updates took 7.28 s. Treat an already bounded label/reference substring as final, or use a non-streaming nested mode, and add a label-ending-`$` streaming performance regression.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4010088918


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +364,170 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+const MAX_LINK_LABEL_LENGTH = 4096;
+const MAX_LINK_TAIL_DEPTH = 32;
+const MAX_LINK_TAIL_LENGTH = 65536;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a bounded Markdown label starting at `index` so its contents can
+ * be re-scanned without display math. Astryx resolves whether a closed label
+ * is an inline link, reference use, shortcut, or definition after this pass;
+ * treating all of them alike keeps reference identities stable.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  let isImage = false;
+  if (source[index] === '!') {
+    if (index + 1 >= source.length) return undefined;
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+    isImage = true;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const labelEnd = findLabelEnd(source, openerEnd);
+  if (labelEnd === 'pending') return { kind: 'pending', end: source.length };
+  if (typeof labelEnd !== 'number') return { kind: 'pending', end: labelEnd.end };
+
+  const match = (end: number) => ({
+    kind: 'match' as const,
+    labelStart: openerEnd,
+    labelEnd,
+    end,
+    isImage,
+  });
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);
+    if (tailEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof tailEnd !== 'number') return match(tailEnd.end);
+    return match(tailEnd);
+  }
+  if (tail === '[') {
+    const refEnd = findLabelEnd(source, labelEnd + 2);
+    if (refEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof refEnd !== 'number') return match(refEnd.end);
+    return match(refEnd + 1);

Review Comment:
   [P2] Normalize the explicit reference identifier as well as the visible label. A valid full reference such as `[visible][\\[topic\\]]` with definition `[\\[topic\\]]: https://example.com/ref` renders an anchor on the exact base, but on this head the second label is copied verbatim here while the definition label is rewritten to literal transport tokens. The IDs no longer match, so the UI displays literal `[visible][[topic]]`. The new full-reference test uses a plain `topic` identifier and misses this path. Re-scan the reference label with the same identity-preserving transform and add an escaped-identifier regression.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +364,170 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+const MAX_LINK_LABEL_LENGTH = 4096;
+const MAX_LINK_TAIL_DEPTH = 32;
+const MAX_LINK_TAIL_LENGTH = 65536;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a bounded Markdown label starting at `index` so its contents can
+ * be re-scanned without display math. Astryx resolves whether a closed label
+ * is an inline link, reference use, shortcut, or definition after this pass;
+ * treating all of them alike keeps reference identities stable.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  let isImage = false;
+  if (source[index] === '!') {
+    if (index + 1 >= source.length) return undefined;
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+    isImage = true;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const labelEnd = findLabelEnd(source, openerEnd);
+  if (labelEnd === 'pending') return { kind: 'pending', end: source.length };
+  if (typeof labelEnd !== 'number') return { kind: 'pending', end: labelEnd.end };
+
+  const match = (end: number) => ({
+    kind: 'match' as const,
+    labelStart: openerEnd,
+    labelEnd,
+    end,
+    isImage,
+  });
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);
+    if (tailEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof tailEnd !== 'number') return match(tailEnd.end);
+    return match(tailEnd);
+  }
+  if (tail === '[') {
+    const refEnd = findLabelEnd(source, labelEnd + 2);
+    if (refEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof refEnd !== 'number') return match(refEnd.end);
+    return match(refEnd + 1);
+  }
+  return match(labelEnd + 1);

Review Comment:
   [P2] Do not mark a bare closed label safe while an appended byte can still turn it into a link. The incremental cache resumes after this label, so a later `(...)` tail bypasses the opaque-tail scan. In a production `MarkdownBody` rerender, rendering `[label]` and then appending `(https://example.com/$$value$$)` produced an href containing a raw private-use `MAKA_MATH` token; a fresh mount of the identical final text preserved the correct `https://example.com/$$value$$` href. Thus link targets depend on stream chunking and can change after remount. Keep enough lookbehind or unsafe suffix to reclassify the label when `(` or `[` arrives, and add a one-shot-versus-incremental equivalence regression.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4010309873


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +364,170 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+const MAX_LINK_LABEL_LENGTH = 4096;
+const MAX_LINK_TAIL_DEPTH = 32;
+const MAX_LINK_TAIL_LENGTH = 65536;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a bounded Markdown label starting at `index` so its contents can
+ * be re-scanned without display math. Astryx resolves whether a closed label
+ * is an inline link, reference use, shortcut, or definition after this pass;
+ * treating all of them alike keeps reference identities stable.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  let isImage = false;
+  if (source[index] === '!') {
+    if (index + 1 >= source.length) return undefined;
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+    isImage = true;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const labelEnd = findLabelEnd(source, openerEnd);
+  if (labelEnd === 'pending') return { kind: 'pending', end: source.length };
+  if (typeof labelEnd !== 'number') return { kind: 'pending', end: labelEnd.end };
+
+  const match = (end: number) => ({
+    kind: 'match' as const,
+    labelStart: openerEnd,
+    labelEnd,
+    end,
+    isImage,
+  });
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);
+    if (tailEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof tailEnd !== 'number') return match(tailEnd.end);
+    return match(tailEnd);
+  }
+  if (tail === '[') {
+    const refEnd = findLabelEnd(source, labelEnd + 2);
+    if (refEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof refEnd !== 'number') return match(refEnd.end);
+    return match(refEnd + 1);

Review Comment:
   You are right, sorry about that - I rewrote the visible label but left the identifier verbatim, so of course the IDs diverged. Fixed now: the explicit reference label goes through the same transform, with an escaped-identifier regression using your exact case. Is this looking better?



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +364,170 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+const MAX_LINK_LABEL_LENGTH = 4096;
+const MAX_LINK_TAIL_DEPTH = 32;
+const MAX_LINK_TAIL_LENGTH = 65536;
+
+type MarkdownLinkScan =
+  | { kind: 'match'; labelStart: number; labelEnd: number; end: number; isImage: boolean }
+  | { kind: 'pending'; end: number }
+  | undefined;
+
+/**
+ * Recognize a bounded Markdown label starting at `index` so its contents can
+ * be re-scanned without display math. Astryx resolves whether a closed label
+ * is an inline link, reference use, shortcut, or definition after this pass;
+ * treating all of them alike keeps reference identities stable.
+ */
+function readMarkdownLink(source: string, index: number): MarkdownLinkScan {
+  let openerEnd: number;
+  let isImage = false;
+  if (source[index] === '!') {
+    if (index + 1 >= source.length) return undefined;
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 2;
+    isImage = true;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const labelEnd = findLabelEnd(source, openerEnd);
+  if (labelEnd === 'pending') return { kind: 'pending', end: source.length };
+  if (typeof labelEnd !== 'number') return { kind: 'pending', end: labelEnd.end };
+
+  const match = (end: number) => ({
+    kind: 'match' as const,
+    labelStart: openerEnd,
+    labelEnd,
+    end,
+    isImage,
+  });
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailEnd = findInlineTailEnd(source, labelEnd + 1);
+    if (tailEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof tailEnd !== 'number') return match(tailEnd.end);
+    return match(tailEnd);
+  }
+  if (tail === '[') {
+    const refEnd = findLabelEnd(source, labelEnd + 2);
+    if (refEnd === 'pending') return { kind: 'pending', end: source.length };
+    if (typeof refEnd !== 'number') return match(refEnd.end);
+    return match(refEnd + 1);
+  }
+  return match(labelEnd + 1);

Review Comment:
   Good catch, that was my mistake - I was settling a bare closed label even though a later ( or [ can still turn it into a link. Bare labels at end of input now stay unsettled so the tail gets scanned with the label context, and I added a one-shot-vs-incremental equivalence test with your href case. Does that cover it?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5676189415

   Added the two gaps: collapsed form with escaped alt is now covered, plus an incremental-vs-one-shot guard for escaped image alts. Markdown-body 49/49 and full UI green locally apart from the known mermaid environment failures.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-6424168789

   Merged latest main to resolve the conflict. The new CI run is waiting for approval (fork PR): https://github.com/apache/maka/actions/runs/40377194312. Could a maintainer approve it?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5679820295

   Done: the reference identifier scan now forwards its pending state the same way the first label does, so streamed updates continue it instead of restarting at the reference opener. Invalid identifiers keep the old match-and-settle path. The 128K probe shape now measures in line with base, with the remainder being the shared prefix-check floor. New streaming regression included; markdown-body 54/54 locally.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5677989631

   Confirmed real, fixed differently than it reads: the 4s was not scan cost (preprocessing measured 6ms) but the render shape — a 65K literal text run renders in ~5.8s while the same input as a structured link renders in ~60ms, which I verified with plain 65K text versus a plain 65K link. So instead of moving the bound again, labels no longer have a length cap at all: a close found anywhere resolves and settles, and only genuinely unfinished input pays per-chunk rescan, same as unclosed math on base. The 65K case now renders in ~80ms with the anchor, and a 100K regression pins that there is no cliff left. Depth cap, blank-line rule, and tail bounds are untouched.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5680266820

   Right, that was still wrong - the continuation was stored even when earlier syntax was unsettled, so the stranded backtick/math never got reparsed. Now a pending label scan is only remembered when everything before its opener already settled; otherwise the next update does the normal full reparse. Same-mount regression for all three shapes included, red pre-fix and green post-fix. Full UI 485/485 locally.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal closed pull request #5311: fix(ui): keep escaped brackets in link labels out of display math
URL: https://github.com/apache/maka/pull/5311


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4069340846


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -283,6 +406,180 @@ function readDelimitedMath(
   return { kind: 'match', formula, displayMode, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+const MAX_LINK_LABEL_LENGTH = 4096;

Review Comment:
   The fixed label-length cutoff is no longer present; the incremental scanner now carries pending state until the label resolves, with coverage for labels beyond the former bound. Reverified in f8fa56df1 with all 56 markdown-body tests passing.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "dedsec-terminal (via GitHub)" <gi...@apache.org>.
dedsec-terminal commented on PR #5311:
URL: https://github.com/apache/maka/pull/5311#issuecomment-5775552461

   Resolved merge conflicts with latest `upstream/main` (adopting Astryx 0.6.2 math pipeline).
   
   ### Summary of Updates
   1. **Astryx 0.6.2 Integration & Merge Resolution**:
      - Reconciled `translateMarkdownMath` with the link label & reference identifier scanning logic.
      - Retained literal bracket token protection (`TOKEN_PATTERN`, `MARKDOWN_MATH_PLUGINS`, and `restoreTransportTokens`) so escaped brackets `\[` / `\]` inside link labels and image alts are protected from Astryx's naive `indexOf(']')` bracket matcher, while math formulas leverage Astryx's native `components.math` pipeline.
   2. **Boundary Escape Parity**:
      - Threaded `leadingBackslashes` via `countPrecedingBackslashes(source, sourceStart)` across incremental scan boundaries so multi-backslash runs (`\\\\\\\\[\\\\] x]`) preserve parity regardless of streaming chunk split points.
      - Regression test passes: `preserves escape parity when an incremental scan resumes inside a backslash run`.
   3. **Refactored Options**:
      - Replaced positional booleans with the `TranslateMarkdownMathOptions` object.
      - Fixed formatting in the link scanner loop.
   
   ### Verification
   - `npm --workspace @maka/ui run build`: PASS
   - `packages/ui/dist/__tests__/markdown-body.test.js`: 63/63 PASS
   - Full `@maka/ui` dist test suite: 637/637 PASS (41 suites)
   - `npx biome check`: 0 issues
   - `git diff --check`: clean
   - GitHub PR status: `MERGEABLE`
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4078933476


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -219,29 +411,30 @@ function translateMarkdownMath(
       // the span stays uncommitted: the next chunk rescans from the opener
       // and decides the closing guard with the neighbor in hand.
       const next = source[delimited.end];
-      if (next === undefined) markSafe();
+      if (isFinalSegment || next === undefined) markSafe();
       text += inlineMathSource(
         delimited.formula,
         text.length > 0 ? text[text.length - 1] : priorTextChar,
         next !== undefined && nextBreaksInlineClose(source, delimited.end),
       );
       index = delimited.end;
       atLineStart = source[index - 1] === '\n';
-      if (next !== undefined) markSafe();
+      if (isFinalSegment || next !== undefined) markSafe();
       continue;
     }
 
     const character = source[index] ?? '';
-    if (character === '$' && !isEscaped(source, index)) {
+    if (character === '$' && !isEscaped(source, index, leadingBackslashes)) {
       text += '\\$';
     } else {
       text += character;
     }
     index++;
     atLineStart = character === '\n';
     if (
-      index < source.length ||
-      (character !== '\\' && character !== '$' && character !== '`')
+      isFinalSegment
+      || index < source.length
+      || (character !== '\\' && character !== '$' && character !== '`')

Review Comment:
   **P2 — trigger class ① (normal path): any streamed markdown where a `]` not belonging to a `[`-label lands at a chunk boundary or just before a `[`/`(` that arrives later.**
   
   This settle rule guards the characters whose interpretation depends on the next byte (`\`, `$`, `` ` ``), but `]` has the same lookahead dependency and isn't excluded. Concretely, `readLinkDestination` only fires when `source[index + 1]` is `(` or `[` at scan time; if the `]` settles first, the pairing can never form — and worse, the following `[` opens a pending label scan that raw-appends everything until it closes.
   
   Repro (single-character streaming vs one-shot on this head):
   
   ```text
   in:       -!>|aa][`a]$|a>]\xa\>
   streamed: -!>|aa][`a]$|a>]\xa\>
   fresh:    -!>|aa][`a]\$|a>]\xa\>
   ```
   
   The `]` settles at the chunk end; the `[` then opens a label scan that stays pending (unclosed backtick code span), so the `$` and everything after streams verbatim — the settled output permanently differs from the one-shot result. A fuzz run over 20k random math-heavy docs found 28 divergences in this class that do not exist on `main` (which had no label machinery at all).
   
   Minimal fix, verified locally against the compiled output (divergences in this class drop to zero; 67/67 markdown tests still pass): `]` must not settle (a) at end-of-input — add it to the exclusion list here — and (b) when the next byte is `[`/`(` but the tail is not yet resolvable; emit it optimistically like the pending-label path does and let the next chunk rescan it.
   
   <details>
   <summary>中文</summary>
   
   同一发现的(a)半边:`]` 在输入末尾不能直接结算——下一字节可能是 `(`/`[`,构成 `](`/`][` 尾部。把它加进这里的排除列表即可;配套改动见下方另一条评论(已验证:本 PR 新增的 28 例发散全部收敛,67 个测试仍全过)。
   
   </details>



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -154,6 +265,83 @@ function translateMarkdownMath(
       continue;
     }
 
+    const link = readMarkdownLink(source, index, leadingBackslashes);
+    if (link?.kind === 'pending') {
+      // Remember the scan only when everything before its opener already
+      // settled: an earlier unresolved backtick or math opener must be
+      // reparsed together with later chunks, and resuming just the label
+      // would skip it forever.
+      if (link.labelState !== undefined && safeSourceEnd === index) {
+        onLabelPending?.(link.labelState);
+      }
+      text += source.slice(index, link.end);
+      index = link.end;
+      atLineStart = false;
+      if (isFinalSegment) {
+        markSafe();
+      } else {
+        canMarkSafe = false;
+      }
+      continue;
+    }
+    if (link?.kind === 'match') {
+      // A bare closed label with nothing after it can still grow an inline
+      // or reference tail, so it must not settle: resuming after it would
+      // scan that tail without the label context. Once any byte follows the
+      // label the link question is decided and settling is safe again.
+      const mayGrowTail = link.end === link.labelEnd + 1 && link.end >= source.length;
+      // Display math renders as a block, which cannot live inside an inline
+      // link label, and Markdown reads `\[` / `\]` there as literal escaped
+      // brackets. Re-run every closed label with display math disabled so
+      // escaped brackets survive for Markdown to unescape; inline math still
+      // renders inside. Astryx decides later whether the label is an inline
+      // link, reference use, shortcut, image, or definition, so all forms
+      // must share this representation. Image alt text included:
+      // Astryx keeps alt as a raw string, and the image component restores
+      // literal tokens, so no private-use characters reach the DOM.
+      const translatedLabel = translateMarkdownMath(source.slice(link.labelStart, link.labelEnd), {
+        startsAtLineStart: false,
+        priorTextChar: source[link.labelStart - 1],
+        allowDisplayMath: false,
+        protectEscapedBrackets: true,
+        isFinalSegment: true,
+      });
+      // The explicit identifier of a full reference must go through the same
+      // transform, or use-site and definition IDs diverge and the link breaks.
+      let translatedRefText = '';
+      let refSafe = true;
+      if (link.refLabelStart !== undefined && link.refLabelEnd !== undefined) {
+        const translatedRef = translateMarkdownMath(
+          source.slice(link.refLabelStart, link.refLabelEnd),
+          {
+            startsAtLineStart: false,
+            priorTextChar: source[link.refLabelStart - 1],
+            allowDisplayMath: false,
+            protectEscapedBrackets: true,
+            isFinalSegment: true,
+          },
+        );
+        translatedRefText = translatedRef.text;
+        refSafe = translatedRef.safeSourceEnd >= link.refLabelEnd - link.refLabelStart;
+      }
+      const refStart = link.refLabelStart ?? link.end;
+      const refEnd = link.refLabelEnd ?? link.end;
+      text += source.slice(index, link.labelStart)
+        + translatedLabel.text
+        + source.slice(link.labelEnd, refStart)
+        + translatedRefText
+        + source.slice(refEnd, link.end);
+      index = link.end;
+      atLineStart = source[index - 1] === '\n';
+      const labelSafe = translatedLabel.safeSourceEnd >= link.labelEnd - link.labelStart;
+      if (labelSafe && refSafe && !mayGrowTail) {
+        markSafe();
+      } else {
+        canMarkSafe = false;
+      }
+      continue;
+    }
+
     // Destinations take `$` verbatim: escaping there would reach the href,
     // where `\$` does not round-trip back to `$`.
     const destination = readLinkDestination(source, index);

Review Comment:
   Same finding, second half: when `readLinkDestination` sees `][` or `](` but the closing `]`/`)` hasn't arrived yet, it returns `undefined` and the `]` falls through to settle as a plain character — the tail pairing is lost at that moment. A three-way outcome here (matched / invalid / pending) would let the caller defer settlement only while the tail is still open, so a permanently invalid `](` (e.g. newline at depth 1) still settles as literal text instead of rescanning forever; a prose `][` at stream end settles on the final segment either way, matching one-shot.
   
   <details>
   <summary>中文</summary>
   
   同一发现的(b)半边:`]` 后面已见到 `[`/`(` 但尾部还没扫描完时也不能结算——`readLinkDestination` 此时返回 `undefined`,`]` 落进普通字符分支被 markSafe。建议给这里加 matched / invalid / pending 三态,仅 pending 时延迟结算,避免永久 invalid 的尾部反复重扫。
   
   </details>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4308771477


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -154,16 +372,109 @@ function translateMarkdownMath(
       continue;
     }
 
+    const link = readMarkdownLink(source, index, leadingBackslashes);
+    if (link?.kind === 'pending') {
+      if (link.pendingInfo !== undefined && safeSourceEnd === index) {
+        onLinkPending?.(link.pendingInfo);
+      }
+      if (!isFinalSegment) {
+        canMarkSafe = false;
+      }
+      if (link.pendingInfo !== undefined) {
+        // Only unclosed labels/identifiers keep display math suppressed while
+        // they remain pending; an unclosed inline tail does not, because its
+        // destination is copied verbatim and following prose must keep normal
+        // display-math handling.
+        if (link.pendingInfo.kind === 'label' && link.pendingInfo.ref) {

Review Comment:
   P2: A pending reference identifier still disables display math for the rest of the source. `para [a][unfinished\n\[x^2\]\n` and `para [l][r\n\[x^2\]\n\nnext` render no KaTeX in a completed `MarkdownBody` at this head but render `katex-display` with main's math module. Neither forms a link. The resumed path at line 124 has the same effect.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -457,19 +821,403 @@ function readDelimitedMath(
   return { kind: 'match', formula, display, end: close + closing.length };
 }
 
+const MAX_LINK_LABEL_DEPTH = 32;
+// NOTE: label scans deliberately have no length cap (tails keep theirs).
+// Finding a close is linear, settling is permanent, and per-chunk rescan cost
+// while a label is still open matches the base behaviour for unclosed math.
+// Capping labels instead degrades complete long labels to literal text,
+// which both breaks the link and pushes a giant literal run downstream that
+// renders far slower than the structured link would have.
+const MAX_LINK_TAIL_DEPTH = 32;
+const MAX_LINK_TAIL_LENGTH = 65536;
+
+type PendingLinkInfo =
+  | {
+      kind: 'label';
+      labelState: LabelScanState;
+      ref: boolean;
+    }
+  | {
+      kind: 'tail';
+      tailState: TailScanState;
+    };
+
+type MarkdownLinkScan =
+  | {
+      kind: 'match';
+      labelStart: number;
+      labelEnd: number;
+      end: number;
+      refLabelStart?: number;
+      refLabelEnd?: number;
+    }
+  | { kind: 'pending'; end: number; pendingInfo?: PendingLinkInfo }
+  | undefined;
+
+/**
+ * Recognize a bounded Markdown label starting at `index` so its contents can
+ * be re-scanned without display math. Astryx resolves whether a closed label
+ * is an inline link, reference use, shortcut, or definition after this pass;
+ * treating all of them alike keeps reference identities stable.
+ */
+function readMarkdownLink(
+  source: string,
+  index: number,
+  leadingBackslashes: number,
+): MarkdownLinkScan {
+  let openerEnd: number;
+  if (source[index] === '!') {
+    // A trailing `!` may yet become an image opener once `[` arrives; caching
+    // it as safe would lose the `!` context and mistype the label as a link.
+    if (index + 1 >= source.length) return { kind: 'pending', end: index + 1 };
+    if (source[index + 1] !== '[') return undefined;
+    if (isEscaped(source, index, leadingBackslashes)) return undefined;
+    openerEnd = index + 2;
+  } else if (source[index] === '[') {
+    if (isEscaped(source, index, leadingBackslashes)) return undefined;
+    openerEnd = index + 1;
+  } else {
+    return undefined;
+  }
+
+  const firstScan = scanLabel(source, initialLabelScanState(openerEnd));
+  if (firstScan.kind === 'pending') {
+    return {
+      kind: 'pending',
+      end: source.length,
+      pendingInfo: { kind: 'label', labelState: firstScan.state, ref: false },
+    };
+  }
+  if (firstScan.kind === 'invalid') return { kind: 'pending', end: firstScan.end };
+  const labelEnd = firstScan.end;
+
+  const match = (end: number) => ({
+    kind: 'match' as const,
+    labelStart: openerEnd,
+    labelEnd,
+    end,
+  });
+
+  const tail = source[labelEnd + 1] ?? '';
+  if (tail === '(') {
+    const tailScan = scanInlineTail(source, initialTailScanState(labelEnd + 1));
+    if (tailScan.kind === 'pending') {
+      return {
+        kind: 'pending',
+        end: source.length,
+        pendingInfo: { kind: 'tail', tailState: tailScan.state },
+      };
+    }
+    if (tailScan.kind === 'invalid') return match(tailScan.end);
+    return match(tailScan.end);
+  }
+  if (tail === '[') {
+    const refScan = scanLabel(source, initialLabelScanState(labelEnd + 2));
+    if (refScan.kind === 'pending') {
+      return {
+        kind: 'pending',
+        end: source.length,
+        pendingInfo: { kind: 'label', labelState: refScan.state, ref: true },
+      };
+    }
+    if (refScan.kind === 'invalid') return match(refScan.end);
+    return {
+      ...match(refScan.end + 1),
+      refLabelStart: labelEnd + 2,
+      refLabelEnd: refScan.end,
+    };
+  }
+  return match(labelEnd + 1);
+}
+
+function countPrecedingBackslashes(source: string, pos: number): number {
+  let count = 0;
+  let i = pos - 1;
+  while (i >= 0 && source[i] === '\\') {
+    count++;
+    i--;
+  }
+  return count;
+}
+
+/** Whether the character at `pos` is backslash-escaped (odd run before it). */
+function isEscaped(
+  source: string,
+  pos: number,
+  leadingBackslashes = 0,
+): boolean {
+  let count = countPrecedingBackslashes(source, pos);
+  if (pos - count === 0) count += leadingBackslashes;
+  return count % 2 === 1;
+}
+
+/**
+ * Resumable scan for the `]` closing a link label, skipping escapes, code
+ * spans, and nested labels. Absolute positions stay valid across streaming
+ * appends, so an unfinished scan can continue over new bytes instead of
+ * re-walking from the opener on every update.
+ */
+type LabelScanState = {
+  index: number;
+  depth: number;
+  escapeNext: boolean;
+  checkBlank: boolean;
+  runStart: number | null;
+  codeDelimLen: number;
+  codeSearchFrom: number;
+};
+
+function initialLabelScanState(from: number): LabelScanState {
+  return {
+    index: from,
+    depth: 0,
+    escapeNext: false,
+    checkBlank: false,
+    runStart: null,
+    codeDelimLen: 0,
+    codeSearchFrom: 0,
+  };
+}
+
+type LabelScanResult =
+  | { kind: 'pending'; state: LabelScanState }
+  | { kind: 'closed'; end: number }
+  | { kind: 'invalid'; end: number };
+
+/**
+ * Find the `]` closing a link label opened before `from`, skipping escapes,
+ * code spans, and nested labels. Blank lines and excessive nesting can never
+ * form a label here; running out of input means more text may still complete
+ * it. There is deliberately no length bound: a close found anywhere resolves
+ * and settles, so incomplete input is the only case that rescans per chunk.
+ * Both the first label and reference identifiers scan through here, so a
+ * pending second label resumes the same way the first one does.
+ */
+function scanLabel(source: string, st: LabelScanState): LabelScanResult {
+  const pending = (): LabelScanResult => ({ kind: 'pending', state: st });
+  while (st.index < source.length) {
+    if (st.escapeNext) {
+      // A trailing backslash left this pending; the pair only exists once the
+      // escaped character has arrived. Skip both together, exactly as a fresh
+      // scan would.
+      if (st.index + 1 >= source.length) return pending();
+      st.escapeNext = false;
+      st.index += 2;
+      continue;
+    }
+    if (st.checkBlank) {
+      st.checkBlank = false;
+      // The newline at st.index was already seen; only a second newline
+      // makes it a blank line. Otherwise consume it as an ordinary char and
+      // process the new character normally below.
+      if (st.index + 1 >= source.length) {
+        st.checkBlank = true;
+        return pending();
+      }
+      if (source[st.index + 1] === '\n') return { kind: 'invalid', end: st.index };
+      st.index++;
+    }
+    if (st.runStart !== null || source[st.index] === '`') {
+      if (st.runStart === null) st.runStart = st.index;
+      while (source[st.index] === '`') st.index++;
+      if (st.index >= source.length) return pending();
+      st.codeDelimLen = st.index - st.runStart;
+      st.runStart = null;
+      st.codeSearchFrom = st.index;
+    }
+    if (st.codeDelimLen > 0) {
+      const close = source.indexOf('`'.repeat(st.codeDelimLen), st.codeSearchFrom);
+      if (close < 0) {
+        st.codeSearchFrom = Math.max(st.codeSearchFrom, source.length - (st.codeDelimLen - 1));
+        return pending();
+      }
+      st.index = close + st.codeDelimLen;
+      st.codeDelimLen = 0;
+      st.codeSearchFrom = 0;
+      continue;
+    }
+    const ch = source[st.index] ?? '';
+    if (ch === '\n') {
+      if (st.index + 1 >= source.length) {
+        st.checkBlank = true;
+        return pending();
+      }
+      if (source[st.index + 1] === '\n') return { kind: 'invalid', end: st.index };
+      st.index++;
+      continue;
+    }
+    if (ch === '\\') {
+      if (st.index + 1 >= source.length) {
+        st.escapeNext = true;
+        return pending();
+      }
+      st.index += 2;
+      continue;
+    }
+    if (ch === '[') {
+      st.depth++;
+      if (st.depth > MAX_LINK_LABEL_DEPTH) {
+        return { kind: 'invalid', end: findInvalidLinkBoundary(source, st.index) };
+      }
+      st.index++;
+      continue;
+    }
+    if (ch === ']') {
+      if (st.depth === 0) return { kind: 'closed', end: st.index };
+      st.depth--;
+      st.index++;
+      continue;
+    }
+    st.index++;
+  }
+  return pending();
+}
+
+type TailScanState = {
+  from: number;
+  index: number;
+  depth: number;
+  escapeNext: boolean;
+  allowNewlines: boolean;
+  checkBlank: boolean;
+};
+
+function initialTailScanState(from: number, allowNewlines = true): TailScanState {
+  return {
+    from,
+    index: from + 1,
+    depth: 1,
+    escapeNext: false,
+    allowNewlines,
+    checkBlank: false,
+  };
+}
+
+type TailScanResult =
+  | { kind: 'pending'; state: TailScanState }
+  | { kind: 'closed'; end: number }
+  | { kind: 'invalid'; end: number };
+
+function scanInlineTail(source: string, st: TailScanState): TailScanResult {
+  while (st.index < source.length) {
+    if (st.checkBlank) {
+      st.checkBlank = false;
+      if (st.index + 1 >= source.length) {
+        st.checkBlank = true;
+        return { kind: 'pending', state: st };
+      }
+      if (source[st.index + 1] === '\\n') {

Review Comment:
   P3: `'\\n'` is a two-character string, so this comparison is never true. It should be `'\n'`, as in the equivalent label-scanner branch. I found no output difference in fuzzing because closing or invalidating a tail triggers a fresh rescan, but please fix it and add a test that splits the stream immediately after a newline.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] fix(ui): keep escaped brackets in link labels out of display math [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5311:
URL: https://github.com/apache/maka/pull/5311#discussion_r4269046083


##########
packages/ui/src/markdown-math.tsx:
##########
@@ -319,51 +631,57 @@ function displayMathSource(
   formula: string,
   source: string,
   index: number,
+  linePrefix = '',
 ): string {
   const lineStart = source.lastIndexOf('\n', index - 1) + 1;
-  const quotePrefix = /^ {0,3}(?:> ?)*/.exec(source.slice(lineStart, index))?.[0] ?? '';
-  const margin = quotePrefix + ' '.repeat(index - lineStart - quotePrefix.length);
+  const prefix = lineStart === 0 ? linePrefix : '';
+  const lineSoFar = prefix + source.slice(lineStart, index);
+  const quotePrefix = /^ {0,3}(?:> ?)*/.exec(lineSoFar)?.[0] ?? '';
+  const margin = quotePrefix + ' '.repeat(lineSoFar.length - quotePrefix.length);
   const body = formula.replaceAll('\n', `\n${margin}`);
   return `\n${margin}$$\n${margin}${body}\n${margin}$$\n${margin}`;
 }
 
+type LinkDestinationScan =
+  | { kind: 'matched'; end: number }
+  | { kind: 'invalid' }
+  | { kind: 'pending'; tailState?: TailScanState };
+
 /**
  * Span of `](destination …)`/`![…](destination …)` and `][label]` reference
  * links. A destination ends at the `)` that returns paren depth to zero; an
  * unclosed one is prose and gets the ordinary `$` treatment.
  */
-function readLinkDestination(source: string, index: number): number | undefined {
-  if (source[index] !== ']') return undefined;
+function readLinkDestination(source: string, index: number): LinkDestinationScan {
+  if (source[index] !== ']') return { kind: 'invalid' };
+  if (index + 1 >= source.length) return { kind: 'pending' };
+
   if (source[index + 1] === '[') {
     const close = source.indexOf(']', index + 2);
-    return close >= 0 && !source.slice(index + 2, close).includes('\n')
-      ? close + 1
-      : undefined;
-  }
-  if (source[index + 1] !== '(') return undefined;
-  let depth = 0;
-  for (let i = index + 1; i < source.length; i++) {
-    const char = source[i];
-    if (char === '\\') {
-      i++;
-    } else if (char === '(') {
-      depth++;
-    } else if (char === ')') {
-      depth--;
-      if (depth === 0) return i + 1;
-    } else if (char === '\n' && depth === 1) {
-      return undefined;
+    if (close < 0) {
+      if (source.slice(index + 2).includes('\n')) return { kind: 'invalid' };
+      return { kind: 'pending' };
     }
+    return !source.slice(index + 2, close).includes('\n')
+      ? { kind: 'matched', end: close + 1 }
+      : { kind: 'invalid' };
   }
-  return undefined;
+
+  if (source[index + 1] !== '(') return { kind: 'invalid' };
+
+  const scan = scanInlineTail(source, initialTailScanState(index + 1));

Review Comment:
   [P2] Preserve the single-newline rejection for orphan inline tails
   
   This now uses a scanner that permits a single newline, whereas the previous orphan-tail reader rejected it. With no opening link label, completed MarkdownBody rendering of `prefix ](literal
   $x$)` unexpectedly produces math, and `prefix ](literal
   \(x+1\))` loses its explicit inline formula. Both real-render regressions fail at this head and pass with the previous exact math module. Preserve the orphan-tail newline boundary instead of bypassing ordinary prose/math processing through this opaque tail.



##########
packages/ui/src/markdown-math.tsx:
##########
@@ -68,24 +90,150 @@ export function prepareMarkdownMath(
   // keeps the scanner on the changing tail; it does not make the full-string
   // identity check itself incremental.
   const extendsPrevious = source.startsWith(cache.source);
+  if (!extendsPrevious) {
+    pendingLinkScans.delete(cache);
+  } else {
+    const pending = pendingLinkScans.get(cache);
+    if (pending !== undefined) {
+      let isStillPending = false;
+      if (pending.kind === 'label') {
+        const continued = scanLabel(source, pending.labelState);
+        if (continued.kind === 'pending') {
+          pending.labelState = continued.state;
+          isStillPending = true;
+        }
+      } else {
+        const continued = scanInlineTail(source, pending.tailState);
+        if (continued.kind === 'pending') {
+          pending.tailState = continued.state;
+          isStillPending = true;
+        }
+      }
+
+      if (isStillPending) {
+        const specSourceStart = pending.speculativeSafeSourceEnd;
+        const specTextStart = pending.speculativeSafeTextEnd;
+        const lastNewline = specSourceStart > 0 ? source.lastIndexOf('\n', specSourceStart - 1) : -1;
+        const linePrefix = specSourceStart > 0 && lastNewline < specSourceStart - 1
+          ? source.slice(lastNewline + 1, specSourceStart)
+          : '';
+        const translated = translateMarkdownMath(source.slice(specSourceStart), {
+          startsAtLineStart: specSourceStart === 0 || source[specSourceStart - 1] === '\n',
+          priorTextChar: cache.text[specTextStart - 1],
+          leadingBackslashes: countPrecedingBackslashes(source, specSourceStart),
+          linePrefix,
+        });
+        cache.source = source;
+        cache.text = specTextStart === cache.text.length
+          ? cache.text + translated.text
+          : `${cache.text.slice(0, specTextStart)}${translated.text}`;
+        pending.speculativeSafeSourceEnd = specSourceStart + translated.speculativeSafeSourceEnd;

Review Comment:
   [P2] Keep reference-label context when advancing speculative progress
   
   Updating `prefix [label][\[display\]` character by character in the mounted MarkdownBody renders a displayed formula, while supplying the identical text in one update produces no formula. A final completed render still retains the incorrect formula. Both backslash-escaped brackets are part of the unfinished reference identifier, but the next speculative translation starts inside it without that context. This mounted regression passes with the previous exact math module. Keep the reference context attached to speculative progress, and add fresh-versus-incremental completed-render coverage.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org