Skip to content

Hyperlink: cut autolink cost on big pastes and select-all formatting #773

Closed

Description

@HMarzban

Part of #769. Depends on #770: rebase onto it, and measure against it.

Summary

Autolink is the only real runtime cost in the extension. Its appendTransaction calls Tiptap's combineTransactionSteps and getChangedRanges, which cost O(steps²). A plain-text paste of 2,000 paragraphs, or select-all Bold on a long pad, creates thousands of steps, and the user sees a pause. This issue replaces that call with a linear pass that gives the same ranges. It also skips the linkify scan of a whole clipboard when the text holds whitespace. Output stays identical.

Review numbers (2026-11-12, prototype against main without #770; this issue takes its own before and after)

Workload jsdom, n = 9 In-app Chromium 156, n = 9 (background page: ratios only)
Paste 2,000 paragraphs of plain text (4,000 URLs) 371 → 203 ms (−45 %) −52 %
Select all on a 2,000-paragraph pad, then Bold 339 → 219 ms (−35 %) −34 %
Paste 250 KB of words over a selection 33.9 → 18.3 ms (−46 %) −42 %
Type 1,000 keys at the end of a 2,000-paragraph pad −5 % (inside noise) −5 %

The control copy of main moved at most ±5 % in the same runs. A StarterKit app pays +1,054 B min / +386 B gzip. Output (document JSON) equals main on every workload. These numbers come from the review prototype, before #770. The real before and after for this issue are taken on top of #770.

Cause (read from code)

  • extensions/extension-hyperlink/src/interactions/autolink.ts:37-39 calls combineTransactionSteps(oldState.doc, transactions), which applies every step again, then getChangedRanges, which maps each step range through all later maps: O(steps²).
  • A mark step (Bold) has an empty step map, but it still walks every map.
  • src/interactions/pasteHandler.ts and src/paste-title/pasteTitle.ts (oneUrl) run linkify.find over the whole clipboard. A clipboard that holds whitespace can never be one URL, because a link match never holds whitespace.

Fix

Three parts. Ship (a) and (b) together. Keep (c) out.

(a) Linear changed-ranges pass, in autolink.ts, replacing combineTransactionSteps + getChangedRanges:

  1. Collect every step and its own map from each transaction's mapping.maps. Do not apply any step again.
  2. Keep the indexes of the maps that hold ranges (map.ranges.length > 0). Mark steps have none, so they cost nothing to map through.
  3. For each step k: its ranges are map.forEach(from, to), or, for an empty map, the step's own from / to. Map each range forward through the live maps after k (assoc −1 for from, +1 for to). Map it back through the inverted live maps for the old range.
  4. Simplify like Tiptap's simplifyChangedRanges: drop duplicates, then drop a range that lies inside another one.
  5. The position map for old marks is the same forward walk from step 0.

The review prototype is in the collapsed block below. It matched getChangedRanges(combineTransactionSteps(...)) on 18,505 generated cases with 0 mismatches. It is linear in mark steps only: the simplify filter stays O(changes²). Say so in the code comment.

Prototype (review, 2026-11-12)
type Change = { oldRange: { from: number; to: number }; newRange: { from: number; to: number } }

// Same result as Tiptap's combineTransactionSteps + getChangedRanges, in linear time for mark steps.
function changedRanges(transactions: readonly Transaction[]): { changes: Change[]; map: (pos: number) => number } {
  const steps: any[] = []
  const maps: StepMap[] = []
  for (const t of transactions) t.steps.forEach((s, i) => { steps.push(s); maps.push(t.mapping.maps[i]) })
  const live: number[] = []
  maps.forEach((m, i) => { if ((m as any).ranges.length) live.push(i) })
  const inverted = live.map((i) => maps[i].invert()).reverse()
  const forward = (pos: number, k: number, assoc: number) => { for (const i of live) if (i >= k) pos = maps[i].map(pos, assoc); return pos }
  const back = (pos: number, assoc: number) => { for (const m of inverted) pos = m.map(pos, assoc); return pos }
  const raw: Change[] = []
  maps.forEach((m, k) => {
    const ranges: [number, number][] = []
    if (!(m as any).ranges.length) {
      const { from, to } = steps[k]
      if (from === undefined || to === undefined) return
      ranges.push([from, to])
    } else m.forEach((from, to) => { ranges.push([from, to]) })
    for (const [from, to] of ranges) {
      const nf = forward(from, k, -1), nt = forward(to, k, 1)
      raw.push({ oldRange: { from: back(nf, -1), to: back(nt, 1) }, newRange: { from: nf, to: nt } })
    }
  })
  const seen = new Set<string>()
  const unique = raw.filter((c) => { const key = `${c.oldRange.from},${c.oldRange.to},${c.newRange.from},${c.newRange.to}`; return seen.has(key) ? false : (seen.add(key), true) })
  const changes = unique.length === 1 ? unique : unique.filter((c, i) => {
    for (let j = 0; j < unique.length; j++) {
      if (j === i) continue
      const o = unique[j]
      if (c.oldRange.from >= o.oldRange.from && c.oldRange.to <= o.oldRange.to && c.newRange.from >= o.newRange.from && c.newRange.to <= o.newRange.to) return false
    }
    return true
  })
  return { changes, map: (pos) => forward(pos, 0, 1) }
}

Bring it to the package lint rules: no any, one statement per line.

(b) Paste whitespace guard, +11 B gzip:

  • src/interactions/pasteHandler.ts, before find(textContent): if (/\s/.test(textContent)) return false.
  • src/paste-title/pasteTitle.ts, oneUrl: if (!text || /\s/.test(text)) return null before find(text). Its caller already trims the clipboard (pasteTitle.ts:64), so a URL copied with a trailing newline still works.
  • The review checked 200,225 inputs (NBSP, tabs, URLs wrapped in newlines, emails, %20): 0 different answers.
  • It helps the paste handler only when the user pastes over a selection, and pasteTitle only with an empty selection.

(c) Keystroke fast path: do not ship. It returns early for a plain insert or delete away from a link. In a real browser one key costs about 95 µs, and the fast path saves about 16 µs of it, for +199 B gzip. It also skips work right next to links, where the remove-on-edit logic runs.

Benchmark

Field Value
Metric Package bench speed rows: pasteText2000, boldAll2000, pasteOverSelection250k, typeEnd2000 (median, 9 rotated rounds, with a control copy). Bytes a StarterKit app pays. Behaviour cases.
Before Take it on main with #770 merged, before the first commit of this issue. Post it as a Measured comment.
After not measured yet
Confounds #770, #772. Measure with none landing in between. Record each commit hash.
Condition jsdom on Bun 1.4.4, one laptop, nothing else running. Real browser: scripts/bench/browser.ts in a foreground Chrome window; it reports background: true when throttled, and then only ratios count.
How to run From extensions/extension-hyperlink: NODE_ENV=production bun scripts/bench/run.ts --ref <commit before this issue>, then NODE_ENV=production bun scripts/bench/browser.ts --ref <same>.
Pass rule Paste and select-all Bold at least 30 % faster in jsdom and in the browser; typeEnd2000 not slower beyond the control band; output identical on every workload (output differs must not appear); behaviour count unchanged; bytes at most +450 B gzip for a StarterKit app.
Guard The UX contract below.
Owner Agent in the repo: code, tests, jsdom and browser bench. Maintainer: the foreground browser run if the agent's runs report background, and the long-pad typing check.
Claim "Pasting 2,000 paragraphs runs about 45 % faster, and select-all formatting about 35 % faster (jsdom and Chrome, one laptop)." Quote only after a foreground browser run.

UX contract

  • Output identical to the base on every bench workload.
  • A differential unit test compares the new pass with getChangedRanges(combineTransactionSteps(...)), including map for every old position. Seed it with ReplaceAround steps (lift, wrap, setBlockType), AttrStep, add and remove node marks, 1-4 transactions, and rebased prosemirror-collab steps.
  • Prove it by sabotage: change i >= k to i > k, or drop the dedupe. The test must fail.
  • Two browsers on one long local pad: type, paste and select-all Bold in one. The other shows the same links. The pad sends y-tiptap steps, which the unit test does not cover.
  • Real browser: type fast for 30 s at the end of a 2,000-paragraph pad. No long task from autolink in the Performance panel, and no dropped keys.
  • Paste a URL copied from the address bar (with a trailing newline). It still becomes a link, and pasteTitle still names it on the pad.
  • All Hyperlink: keep the whole link when part of it is formatted #770 and Hyperlink: keep a custom href when autolink runs over an existing link #772 tests pass.

Acceptance checks

  • bun run test:unit, typecheck, lint and the full package Cypress suite pass.
  • Before and after bench tables posted here, from jsdom and from the browser.
  • CHANGELOG line under [Unreleased] with the measured gain and its condition.

Out of scope

  • The per-range scans that start at the doc root (about 70 ms left on Bold over 2,000 paragraphs). No prototype yet; file it after this lands if it still shows in a profile.
  • The keystroke fast path (part c).

Activity

  1. added this to the v2.3.8 milestone on Nov 12, 2026
  2. self-assigned this
    on Nov 12, 2026
  3. added
    Editor
    Performance
    on Nov 12, 2026
  4. HMarzban commented on Nov 12, 2026

    @HMarzban
    CollaboratorAuthor

    Measured (2026-11-12, working tree, not committed yet)

    Change:

    • src/interactions/changedRanges.ts (new): the linear changed-ranges pass. autolink.ts uses it instead of combineTransactionSteps + getChangedRanges.
    • src/interactions/pasteHandler.ts and src/paste-title/pasteTitle.ts (oneUrl): skip the linkify scan when the clipboard holds whitespace.
    • The keystroke fast path is not included (part c).
    • The same-text skip from the review prototype is not added again: Hyperlink: keep the whole link when part of it is formatted #770 already skips a change that keeps the link text.

    jsdom (package bench)

    Base = a copy of src/ with #770, #772 and #776; head = that plus this change.

    Metric base head Change
    Bytes: npm dist/index.js (min / gz) 56,040 / 20,484 57,013 / 20,861 +973 / +377
    Bytes: a StarterKit app pays (min / gz) 69,746 / 25,177 70,776 / 25,582 +1,030 / +405
    Bytes: normalizeHref-only import (min / gz) 366,922 / 121,319 367,952 / 121,722 +1,030 / +403
    Behaviour: all cases 18/18 18/18 0
    Behaviour: strip 10/10 10/10
    Behaviour: undo 2/2 2/2
    Behaviour: keep 4/4 4/4
    Behaviour: href 2/2 2/2
    Speed: pasteText2000 (ms) 473.016 229.973 -51% · control +6%
    Speed: boldAll2000 (ms) 371.16 248.047 -33% · control +2%
    Speed: typeEnd2000 (µs/key) 161.608 158.684 -2% · control +1%
    Speed: pasteOverSelection250k (ms) 26.76 13.68 -49% · control -5%
    Speed: boldPartOfLink (ms) 0.16 0.123 -23% · control -8%
    Speed: mount1000Links (ms) 29.665 30.911 +4% · control +2%

    jsdom on Bun 1.4.4, darwin arm64, 9 rotated rounds. No row shows output differs: the final document equals the base on every workload.

    Real browser (ratios only)

    Claude app browser pane, Chrome 156, 9 rounds, same base and head. The pane was a background page (max timer lag 1,193 ms; times about 7× the earlier foreground-like runs), so only ratios count:

    Workload Change control
    pasteText2000 −49 % +3 %
    boldAll2000 −27 % +3 %
    typeEnd2000 −1 % −1 %
    pasteOverSelection250k −33 % +4 %
    mount1000Links +3 % +4 %

    Checks run

    • src/interactions/__tests__/changedRanges.test.ts: the new pass equals getChangedRanges(combineTransactionSteps(...)) (ranges and the position map) on about 1,450 seeded cases of 1-4 transactions. The cases reach every step type: ReplaceStep, ReplaceAroundStep (lift, wrap, lists), AddMarkStep, RemoveMarkStep, AttrStep, AddNodeMarkStep, plus rebased concurrent steps. The test asserts that coverage.
    • Sabotage, each caught: map from the next step (i > k), drop the duplicate filter, invert the maps in the wrong order.
    • src/paste-title/__tests__/oneUrl.test.ts: the guarded oneUrl equals the unguarded rule on 15 inputs (NBSP, tab, a URL wrapped in newlines, emails, %20). A guard that also rejects dots fails 6.
    • bun run test:unit 474 / 474; typecheck, ESLint, Prettier clean; full package Cypress 289 / 289.
    • Bytes: +405 B gzip for a StarterKit app (pass rule: at most +450).

    Still owed

    • A foreground browser run (NODE_ENV=production bun scripts/bench/browser.ts --ref <commit before this issue> with the window in front).
    • Two browsers on one long local pad, and 30 s of fast typing on a 2,000-paragraph pad with the Performance panel.
    • The commit.
  5. HMarzban commented on Nov 12, 2026

    @HMarzban
    CollaboratorAuthor

    Pad check (local dev-local, 2026-11-12) and one finding

    Setup: a scratch pad with 2,025 blocks and 4,000 links, open in two tabs (live Hocuspocus). All four fixes (#770, #772, #776, this one) built in. Claude app browser pane, which runs as a background page, so the times below are inflated; compare them only with each other.

    Correctness:

    • Tab A: real Cmd+A, Cmd+B. Tab B then showed the same 4,000 links (same fingerprint hash of every href and text) and the same 10,001 bold text nodes.
    • One Cmd+Z in tab A gave back the unbolded pad with the same 4,000 links.
    • Real key typing at the end of the pad: no long task; autolink still links on a space (docs.plus → https://docs.plus).

    Finding: on the real pad, autolink is a small part of the select-all Bold pause. With the autolink plugin timed inside the pad, the select-all Bold made one long task of 5,203 ms, and autolink took 78 ms of it (2 calls, about 1.5 %). The pad runs 162 plugins, plus rendering and sync. So this issue removes autolink's quadratic cost, but most of the pause on a long pad sits elsewhere. That needs its own profile in a foreground window before anyone files or fixes it.

    Also seen, not a regression: text inserted in one chunk (as the browser tool types, and possibly some dictation or text-expansion tools) autolinks only the last word before the trailing space. main before this change does the same (checked in jsdom on both builds).

  6. HMarzban commented on Nov 12, 2026

    @HMarzban
    CollaboratorAuthor

    Committed

    c9cd2c98a on main, 2026-11-12, not pushed yet. One commit holds #770, #772, #773 and #776 together, by the maintainer's choice, so it cites each with Refs, and none closes on push. It is the same code the measured comments above describe.

    Open before this issue closes:

    • A browser run with the window in front: NODE_ENV=production bun scripts/bench/browser.ts --ref c9cd2c98a~1.
    • 30 s of fast typing on a 2,000-paragraph pad with the Performance panel open.
    • Production pad check after deploy.
  7. HMarzban commented on Nov 12, 2026

    @HMarzban
    CollaboratorAuthor

    Browser before/after and pad profile (2026-11-12): base c9cd2c98a~1, head c9cd2c98a

    Condition: Apple M5 Max, Bun 1.4.4, headless Chrome for Testing 158.0.8127.18, Playwright 1.64.1. That is build 1254, because Playwright's build 1248 is not installed. CPU rate 1.

    The bench is the package bench page (scripts/bench/browser.ts), not a pad:

    • pasteText2000 pastes 2,000 lines with 2 URLs each.
    • boldAll2000 bolds 2,000 paragraphs with 2 links each.
    • pasteOverSelection250k pastes 250,000 characters over a selection.

    Each session ran 9 rounds in rotated order. control is a second copy of base, with the same dist/index.js sha256. Base has the same package source as release 2.3.0. There were two runs:

    • wf3: 6 sessions with the HEAD timer probe, on a busy machine.
    • wf4: 4 sessions with the idle-lag probe. The 1-minute load at start and end points was 1.73–3.61.
    Workload wf3: head vs base wf4: per-session head/base Control (noise)
    pasteText2000 −48.8 %; re-run −48.18 %; per session −43.58 to −48.79 % median −45.2 %, range −45.9 to −44.5 % wf3 up to ±5.4 %; wf4 −0.1 to +3.7 %
    boldAll2000 −19.9 %; re-run −19.26 %; per session −17.1 to −24.0 % −22.1 to −19.2 % (3-session median −20.2 %) wf3 −0.5 to +2.1 %; wf4 +0.5 to +2.6 %
    pasteOverSelection250k −29.3 %; re-run −28.86 % −31.3 to −26.4 % (3-session median −29.2 %) wf3 −0.87 to +1.98 %; wf4 −0.3 to +1.8 %
    typeEnd2000 −2.9 %; re-run +1.70 %: no change −0.6 to +1.4 %: no change wf3 −3.7 / −0.20 %; wf4 −0.4 to +0.7 %
    mount1000Links +3.2 % median over 9 sessions; head-only jumps of +10.34 % and +12.8 % −6.4 to +8.7 % wf4 control alone −5.8 to +10.0 %; timer step 0.1 ms on about 10–12 ms; unresolved

    Quote ratios only. Absolute times move with machine load. The wf4 base medians were 12.1–21.2 % below wf3. Lower load is a likely cause, but it is not shown. boldPartOfLink sits at the 0.1 ms timer step.

    The background flag. The HEAD bench probes timer lag right after each workload, so it catches the editor's own queued work. In wf3, every rate-1 session set the flag, with lag 113.9–152.6 ms. The working tree now probes after an idle second. This change is not committed. With it, lag was 0.1–0.2 ms, and the flag was false in 4 of 4 sessions. The old probe ran the same day at similar load. It still gave 114.7 and 108.2 ms, with the flag true. So the probe change cleared the flag, not the lower load. This is an A/B with n = 2 per arm, not an A/A. Not tested: the 50 ms threshold, and a really backgrounded page.

    Queued work. Each run leaves queued work after the timed window. With the editor alive, it is 179.4 ms after a paste and 82.4 ms after a Bold (base, 1 session). It is equal in base, control and head. With the queued work counted, paste is −33.39 % (447.2 → 297.9 ms). Bold is −16.31 % (269.1 → 225.2 ms). That is 1 session only.

    jsdom overstates Bold. jsdom gives −34.5 % for Bold, while the browser gives −17.1 to −24.0 %.

    Rate-4 CPU throttle (1 session, not re-run). Paste −44.5 %, Bold −20.9 %, paste over a selection −27.7 %. Typing was +8.4 % against a +5.8 % control, so it is inconclusive.

    Pad profile (local webapp :3001, next dev --turbopack, dev build). Setup: a 2,025-block anonymous scratch pad (2,000 paragraphs plus 25 seed blocks) with 4,000 links, headless, 1440x900. Select-all Bold was timed from keydown to the second animation frame:

    • First run, padA, 6 cycles: median 4949.8 ms (4071.7–5035.8).
    • Verifier, 3 cycles per pad: padA 4797.5 ms (4192.3–4869.3), padB 5062.7 ms (4203.2–5222.4). The A/A gap is −265.2 ms (−5.2 %).

    Autolink's appendTransaction was timed by a wrapper inside that Bold. It took 73.05 ms (72.1–74.6) over 6 cycles. The verifier got 72.4 ms on padA and 75.6 ms on padB. So autolink is about 1.5 % of the pause.

    This is HEAD only, because no base build ran on a pad. Cycle 2 ran 600–900 ms faster than cycles 1 and 3 on both pads, so a median of 3 is fragile. These figures replace the earlier 5,203 ms and 78 ms, which came from a background browser pane.

    A 300-paragraph smoke profile (one profile, n = 1, no noise floor) gave 221.0 ms busy time. Most self time went to (program) 67.3 ms, y-tiptap 47.7 ms and prosemirror-transform 28.2 ms. The hyperlink extension had 0.2 ms self time and 1.7 ms inclusive.

    The CPU profiles at 2,000 paragraphs, typing Event Timing and the typing A/A are now done: see "Full pad profile" below.

    Rulings needed on the bench.

    1. The flag: keep the idle-lag probe in browser.ts. It is in the working tree, not committed. The data supports it.
    2. Which figure to quote: use the timed window as the headline, with the queued-work figure beside it.
    3. Browser build: Playwright 1.64.1 expects chromium 1248, which is not installed. Install it, or name build 1254 in the bench README.

    Raw data:

    • Bench, wf3: wf3/m1-browser-bench/run-{1,2,3}.json, run-cpu4x.json, jsdom.json, and the verifier's wf3/m1-browser-bench-verify/.
    • Bench, wf4: wf4/p6-browser-bench/run-{1,2,3}.json, run-oldprobe.json, and wf4/v-p6-browser-bench/{v-new,v-old}.json.
    • Pad: wf4/p1-pad-profile/full.log and wf4/p1-verify/out-2026-11-12T19-34-07-461Z/summary.json.

    Re-run commands:

    • Bench: cd wf4/p6-browser-bench && bun drive.ts run-<k> 1 9 30, one session at a time.
    • Pad: cd wf4/p1-pad-profile && bun pad-profile.ts --blocks 2000 --cycles 7 --profiled 2 --typing-runs 3, alone on the machine.

    Upstream follow-up. Tiptap's getChangedRanges(combineTransactionSteps(...)) calls StepMap.map exactly 3N²+N times for N mark steps. At N = 4,000 that is 48,004,000 calls. Our changedRanges calls it 0 times, with identical output. Without the counter patch, our pass is about 5.7× faster at N = 4,000 (ratio 0.174–0.176). An upstream draft is ready. File it after the push, with the counts first.

    Full pad profile (2026-11-13, finished after the workflow). Local webapp :3001 (next dev --turbopack, c9cd2c98a), headless Chrome for Testing 158.0.8127.18, Apple M5 Max, load average 1.33 → 1.77. Two fresh anonymous scratch pads, each 2,025 blocks with 4,000 links.

    Measure Pad A Pad B (A/A)
    Select-all Bold, keydown to the frame after (ms), n = 7 4,624.5 (3,895.8–4,705.7) 4,677.4 (3,863.5–4,816.1)
    Autolink inside that Bold (ms) 69.3 (68.3–71.6) 70.2 (68.6–70.6)
    Autolink share of the Bold 1.50 % (1.46–1.84) 1.50 % (1.46–1.78)
    Typing 300 keys at the end, per-key processing (ms), 3 runs median 8.95–9.45, p95 17.1–17.8 median 8.75–9.5, p95 17.1–17.3
    Autolink per key (µs), 3 runs 25–33.7 30.7–35

    A/A gap on the Bold: −1.13 %. CPU profile of 2 Bold cycles (5,429 and 5,233 ms busy): y-prosemirror / y-tiptap / Yjs 32–35 %, prosemirror-transform 30–34 %, V8 garbage collection and program 25–26 %, prosemirror-model 6 %, @docs.plus/extension-hyperlink 0.38 %, prosemirror-view 0.2 %, React 0.2–0.3 %, webapp code 0.02 %.

    So the long-pad Bold pause is collaborative sync and transform mapping, not the hyperlink extension. Dev build, one laptop, HEAD only (no parent build on a pad): Internal, not for a release note. Re-run: bun pad-profile.ts --blocks 2000 --cycles 7 --profiled 2 --typing-runs 3 in the local wf4/p1-pad-profile harness.

  8. HMarzban commented on Nov 16, 2026

    @HMarzban
    CollaboratorAuthor

    Production check, 2026-11-16. docs.plus at b7888dce1 (deployed 2026-11-15). Chrome on macOS, signed in. One scratch pad, never /demo. Each result was read from the editor DOM after the action. n = 1.

    Check Result
    Paste two lines with docs.plus/demo, github.com/docs-plus/docs.plus and [email protected] in tab A, then read tab B Both tabs hold the same three links: https://docs.plus/demo, https://github.com/docs-plus/docs.plus, mailto:[email protected]
    Paste https://example.com/ plus a newline on an empty selection A link to https://example.com/, titled Example Domain by paste title

    Ruling (maintainer, 2026-11-16): the browser Bold result meets this issue. The quadratic cost is gone: StepMap.map calls drop from 48,004,000 to 0 at N = 4,000, with identical output. Quote only the measured browser numbers (headless Chrome 158, one laptop, ledger on #769): paste of 2,000 lines −43.6 to −48.8 %, select-all Bold −17.1 to −24.0 %. Do not quote the body's earlier "about 35 %", which came from jsdom.

    The fix is c9cd2c98a, live since 3d90636a9 and still in b7888dce1. Release credit v2.3.8. Closing as done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

EditorExtensionPerformancetiptap

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions