Skip to content

fix(ui): make file-link label disambiguation near-linear - #124258

Merged
vyctorbrzezowski merged 2 commits into
mainfrom
brzezowski/file-label-cardinality
Aug 15, 2026
Merged

vyctorbrzezowski merged 2 commits into
mainfrom
brzezowski/file-label-cardinality

Conversation

@vyctorbrzezowski

@vyctorbrzezowski vyctorbrzezowski commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

shortestFileLabels in ui/src/components/file-kind.ts computes the shortest unambiguous label for each file link rendered in a Markdown message. For every path, it repeatedly scans the entire path list at each suffix depth to check for collisions. A message with a dense list of distinct file references drives this into roughly quadratic time and can visibly stall the chat renderer.

Fixes #124230

Why This Change Was Made

The label routine is the sole owner of this computation (called once per render from ui/src/components/markdown-parser.ts:463, reached by default from ui/src/components/chat-message-bubble.ts:296 and ui/src/pages/chat/components/chat-sidebar.ts:521), so the fix stays inside it rather than adding a parser-level guard or a cross-render cache that would just relocate the cost or introduce a new caching boundary. The rewrite replaces the repeated full-list scan with one reversed-segment suffix trie built once per render: each path's minimal unique suffix depth is then found with one child lookup per depth instead of a comparison against every other path. Output is unchanged — same shortest-suffix selection, same separator preservation, same full-path fallback — only the algorithmic complexity changes.

User Impact

Chat and file-preview surfaces that render Markdown with file links (default-on chat message bubbles, and the detail panel) no longer risk a renderer stall when a message references a large number of distinct files. Existing labels are byte-for-byte identical; this is a scaling fix, not a behavior change.

Evidence

Reachable cardinality (revised from the earlier benchmark)

Both surfaces that call shortestFileLabels (chat-message-bubble.ts:296, chat-sidebar.ts:521) render with mode defaulting to "message" (markdown-render-options.ts:22). For that mode, renderSanitizedMarkdown never reaches the file-link parse path at all above MARKDOWN_PARSE_LIMIT (40,000 characters, ui/src/components/markdown.ts:90,510-515) — text past that length is escaped and rendered as plain text, no markdown parsing, no file-link decoration, no call into shortestFileLabels. So the true producer-side ceiling on n is not an independent "path count" — it's however many distinct file references fit inside a single 40,000-character message.

The original benchmark's 16,000-path row (using the ~27-char-average synthetic paths from the fixture) needs roughly 432,000 characters of message text — over 10x the parse cap. That workload can never reach this function in the shipped product; the earlier "~1500x" framing was measured past the point the code path can be entered. Real repository paths make the reachable ceiling tighter still: git ls-files '*.ts' '*.tsx' | head -900 averages 48.8 characters/path, so 900 of those already total ~43,900 characters, at the cap.

Benchmark, re-run at reachable scale

Same methodology as before (shortestFileLabels called directly, all-unique-basename paths, the shape that defeats the pre-fix algorithm's early exit), now bounded to what a single 40,000-character message can actually carry:

Path count Total message chars (this shape) Pre-fix Post-fix
500 13,180 74–82 ms 0.6–1.1 ms
1,000 26,580 (well inside the 40k cap) 74–107 ms 0.6–1.1 ms
1,400 38,100 (at the practical edge of the 40k cap) 137–181 ms 0.7–1.6 ms

(3 local runs per size; ranges cover the observed spread.) Corroborating run against 900 real repository .ts/.tsx paths (43,877 chars, i.e. already past the cap on their own): pre-fix 105.76 ms, post-fix 1.04 ms.

Reframed claim: within the range this code path can actually be entered, the pre-fix implementation costs roughly 75–180 ms — not the 20+ second, 16,000-path figure from the original benchmark, which described a workload the UI cannot produce. That range is still a real, user-visible stall (blocking the render of a single chat message for 100+ ms is noticeable jank), and the quadratic shape means it gets worse the closer a message gets to the 40k cap — so the fix is still warranted, just not for the reason originally stated. The post-fix implementation stays under ~2 ms across the same range: a ~70–170x improvement at reachable cardinality, not the previously claimed ~1500x at an unreachable one.

Performance contract: deterministic, not timing-based

The previous version of this PR only asserted output correctness at high cardinality, so the pre-fix quadratic implementation also passed it. Per review, ui/src/components/markdown-links.test.ts now has a dedicated test, keeps per-path lookup cost linear as path count grows (performance contract), that asserts the actual complexity contract instead of wall-clock time:

  • It counts every Map#get call made while shortestFileLabels runs (vi.spyOn(Map.prototype, "get"), restored via mockRestore()), at 500 and 4,000 paths (8x).
  • The current trie makes a fixed number of child lookups per path segment — one per segment on insert, one per resolved suffix depth on lookup — so total lookups scale with path count: empirically exactly 6x per path for this fixture, so 8x the paths costs ~8x the lookups.
  • The pre-fix full-list rescan re-read every other path's segments inside unique.some(...) at every depth, which is O(n²) lookups for this same shape: verified locally at exactly n² (e.g. 4,000,000 lookups at n=2,000), so 8x the paths there costs ~64x the lookups.
  • The test asserts the lookup count stays inside a generous band (> small * 4 and < small * 16) — comfortably containing the true ~8x linear growth while excluding the ~64x quadratic signature. Verified by temporarily reverting shortestFileLabels to the pre-fix implementation locally: the test fails deterministically (expected 16000000 to be less than 4000000), then reverted the file back and reran clean.
  • No timers, no CI-load-dependent thresholds — the count is exact and reproducible every run.

Focused test run against the fix:

$ node scripts/run-vitest.mjs ui/src/components/markdown-links.test.ts
 Test Files  1 passed (1)
      Tests  74 passed (74)

node scripts/check-changed.mjs -- ui/src/components/file-kind.ts ui/src/components/markdown-links.test.ts passed after fixing an oxlint(no-extend-native)/unbound-method finding in the new test (switched from directly reassigning Map.prototype.get to vi.spyOn): format, lint, typecheck (core + UI), dead-export scan, dependency/patch guards, and the delegated Testbox lint run all green.

CI

checks-ui-e2e (6/12) failed on the prior head (c985d533b4c) in ui/src/e2e/agent-file-lifecycle.e2e.test.ts ("reads and saves the selected agent workspace through an isolated Gateway") — a stale/duplicated file-content assertion ('# Real main instructions\n# Saved thr…' vs '# Saved through real Gateway\n') in a test unrelated to this PR's Control UI markdown/file-label code. That test file is not touched by this diff.

This looks like a pre-existing, sitewide E2E flake, not caused by this PR: sibling open PRs from the same day each hit exactly one failing checks-ui-e2e shard, each a different, unrelated test — #124285 failed shard 11/12 in new-session-page.prompt-attachments.e2e.test.ts (textarea line-count assertion), #124264 failed shard 2/12 in session-management.sidebar.e2e.test.ts (missing "Selected session recovered" text), and this PR failed shard 6/12 in agent-file-lifecycle.e2e.test.ts. Different tests, different shards, no shared code path with this diff — consistent with CI-load-driven flake in the isolated-Gateway E2E lane rather than a regression from this change. Pushing the new commit reruns this lane fresh on the new head.

shortestFileLabels rescanned every path list at each suffix depth to
find the shortest unambiguous label, which is quadratic in path
count. A Markdown message with thousands of distinct file references
could stall the chat renderer. Replace the repeated scan with one
reversed-segment suffix trie built per render, so each path's label
depth is found with one child lookup per depth instead of a
comparison against every other path. Output is unchanged.

Fixes #124230
@clawsweeper

clawsweeper Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui size: S maintainer Maintainer-authored PR labels Aug 15, 2026
@vyctorbrzezowski
vyctorbrzezowski marked this pull request as ready for review August 15, 2026 19:32
@vyctorbrzezowski vyctorbrzezowski self-assigned this Aug 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 15, 2026
@clawsweeper

clawsweeper Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 15, 2026, 5:52 PM ET / 21:52 UTC.

ClawSweeper review

What this changes

The branch replaces repeated file-path suffix scans in Control UI Markdown with a per-render suffix trie and adds a structural test that guards near-linear lookup growth.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open: current main still uses the repeated all-path scan, and the updated head addresses the prior performance-contract finding with a deterministic owner-level growth guard. The patch is correct; wait for refreshed exact-head checks and normal maintainer handling.

Priority: P2
Reviewed head: b5301521fa874f5a5679d3c7d48c3246fee4cdb1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused owner-boundary repair and deterministic regression guard are good merge-quality evidence; remaining work is routine exact-head CI and maintainer review.
Proof confidence 🌊 off-meta tidepool Not applicable: This member-authored, behavior-preserving Control UI performance repair has focused source and regression evidence; the external-contributor real-behavior-proof gate does not apply.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This member-authored, behavior-preserving Control UI performance repair has focused source and regression evidence; the external-contributor real-behavior-proof gate does not apply.
Evidence reviewed 5 items Current-main defect: Current main still derives each label by repeatedly scanning every unique path through unique.some, which makes the reported high-cardinality shape quadratic.
Owner boundary and callers: The parser collects all file-link decorations, calls the helper once per render, and preserves line suffixes separately; chat message and detail-sidebar consumers opt into file links.
Updated performance guard: The PR builds one reversed suffix trie and its second commit adds a 500-to-4,000 path Map#get growth guard; it would fail on the prior repeated-scan implementation while avoiding timing thresholds.
Findings None None.
Security None None.

How this fits together

Control UI Markdown parsing collects file-link targets from a chat message, computes short distinct labels, then renders those labels in message and detail views. The helper affects label derivation only; link parsing, line suffixes, and rendered destinations remain downstream contracts.

flowchart LR
  A[Chat Markdown] --> B[File link parsing]
  B --> C[Collected file paths]
  C --> D[Suffix trie label derivation]
  D --> E[Distinct short labels]
  E --> F[Chat and detail rendering]
Loading

Before merge

  • Resolve merge risk (P1) - The bug fix adds 28 net production lines; the trie is the justified owner-level structure needed to avoid rescanning all paths, but it should not grow further through parser caches or consumer guards.
  • Resolve merge risk (P1) - GitHub reports the PR clean but behind current main, while the supplied exact-head check rollup is incomplete; merge only after the refreshed merge result and required checks cover the current head.
Agent review details

Security

None.

PR surface

Source +28, Tests +58. Total +86 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 41 13 +28
Tests 1 59 1 +58
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 100 14 +86

Review metrics

Metric Value Why it matters
Production versus test delta production +41/-13 (net +28); tests +59/-1 (net +58) The production growth is a focused suffix-index structure replacing the repeated scan; the added test coverage protects both label output and cost growth.
Structural performance scale 500 to 4,000 paths (8x input) The new owner-level guard requires lookup growth below 16x, excluding the previous quadratic signature without using CI-sensitive timing.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #124230
Summary: This PR is the concrete candidate repair for the linked file-link label performance bug.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the suffix index local to label derivation, retain the deterministic scaling guard, and merge only after the current head has a clean refreshed merge result and required checks.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the suffix index local to label derivation, retain the deterministic scaling guard, and merge only after the current head has a clean refreshed merge result and required checks.

Do we have a high-confidence way to reproduce the issue?

Yes, at source level: current main's nested unique.some scan at ui/src/components/file-kind.ts:125-140 has a clear quadratic high-cardinality path, though this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. A render-local suffix index repairs the computation at its owning helper while preserving parser-owned line suffixes; a parser cache or consumer guard would relocate rather than remove the repeated work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ac6940641ce0.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored, behavior-preserving Control UI performance repair has focused source and regression evidence; the external-contributor real-behavior-proof gate does not apply.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Dense model-authored file-link messages can cause visible Control UI rendering jank, but the blast radius is limited to this optional rendering path.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored, behavior-preserving Control UI performance repair has focused source and regression evidence; the external-contributor real-behavior-proof gate does not apply.

Evidence

What I checked:

Likely related people:

  • vyctorbrzezowski: Authored the original file-link feature commit, the recent adjacent Markdown-label change on main, and this repair. (role: feature owner and recent area contributor; confidence: high; commits: 619f3c9ab10f, ac6940641ce0; files: ui/src/components/file-kind.ts, ui/src/components/markdown-parser.ts, ui/src/components/markdown-links.test.ts)
  • Peter Steinberger: Current-history and blame signals connect this contributor to the present file shape and adjacent Control UI chat work; shallow history makes the exact ownership trail incomplete. (role: recent Control UI contributor; confidence: medium; commits: cc9883a3d33b; files: ui/src/components/file-kind.ts, ui/src/components/markdown-parser.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Wait for required checks and the refreshed clean merge result on b530152.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-15T20:07:17.021Z sha c985d53 :: found issues before merge. :: [P2] Assert the large-input performance contract

Add a deterministic performance-contract regression for
shortestFileLabels: count Map#get calls via vi.spyOn while the trie
runs at two path-count scales and assert the growth stays linear
(generous band) rather than the pre-fix O(n^2) full-list rescan's
quadratic signature. No wall-clock timing, so it can't flake under CI
load; verified locally that it fails deterministically against the
pre-fix implementation and passes clean against the fix.
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 15, 2026
@vyctorbrzezowski
vyctorbrzezowski merged commit 5374c11 into main Aug 15, 2026
178 of 180 checks passed
@vyctorbrzezowski
vyctorbrzezowski deleted the brzezowski/file-label-cardinality branch August 15, 2026 22:41
@vyctorbrzezowski

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 16, 2026
…4258)

* fix(ui): make file-link label disambiguation near-linear

shortestFileLabels rescanned every path list at each suffix depth to
find the shortest unambiguous label, which is quadratic in path
count. A Markdown message with thousands of distinct file references
could stall the chat renderer. Replace the repeated scan with one
reversed-segment suffix trie built per render, so each path's label
depth is found with one child lookup per depth instead of a
comparison against every other path. Output is unchanged.

Fixes openclaw#124230

* test(ui): assert file-label lookup cost stays linear

Add a deterministic performance-contract regression for
shortestFileLabels: count Map#get calls via vi.spyOn while the trie
runs at two path-count scales and assert the growth stays linear
(generous band) rather than the pre-fix O(n^2) full-list rescan's
quadratic signature. No wall-clock timing, so it can't flake under CI
load; verified locally that it fails deterministically against the
pre-fix implementation and passes clean against the fix.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make Markdown file-link label disambiguation linear

1 participant