Repository navigation
Description
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-39callscombineTransactionSteps(oldState.doc, transactions), which applies every step again, thengetChangedRanges, 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.tsandsrc/paste-title/pasteTitle.ts(oneUrl) runlinkify.findover 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:
- Collect every step and its own map from each transaction's
mapping.maps. Do not apply any step again. - Keep the indexes of the maps that hold ranges (
map.ranges.length > 0). Mark steps have none, so they cost nothing to map through. - For each step
k: its ranges aremap.forEach(from, to), or, for an empty map, the step's ownfrom/to. Map each range forward through the live maps afterk(assoc −1 forfrom, +1 forto). Map it back through the inverted live maps for the old range. - Simplify like Tiptap's
simplifyChangedRanges: drop duplicates, then drop a range that lies inside another one. - 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, beforefind(textContent):if (/\s/.test(textContent)) return false.src/paste-title/pasteTitle.ts,oneUrl:if (!text || /\s/.test(text)) return nullbeforefind(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(...)), includingmapfor every old position. Seed it with ReplaceAround steps (lift, wrap,setBlockType),AttrStep, add and remove node marks, 1-4 transactions, and rebasedprosemirror-collabsteps. - Prove it by sabotage: change
i >= ktoi > 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
HMarzban commentedon Nov 12, 2026
Measured (2026-11-12, working tree, not committed yet)
Change:
src/interactions/changedRanges.ts(new): the linear changed-ranges pass.autolink.tsuses it instead ofcombineTransactionSteps+getChangedRanges.src/interactions/pasteHandler.tsandsrc/paste-title/pasteTitle.ts(oneUrl): skip the linkify scan when the clipboard holds whitespace.jsdom (package bench)
Base = a copy of
src/with #770, #772 and #776; head = that plus this change.dist/index.js(min / gz)normalizeHref-only import (min / gz)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:
controlChecks run
src/interactions/__tests__/changedRanges.test.ts: the new pass equalsgetChangedRanges(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.i > k), drop the duplicate filter, invert the maps in the wrong order.src/paste-title/__tests__/oneUrl.test.ts: the guardedoneUrlequals 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:unit474 / 474; typecheck, ESLint, Prettier clean; full package Cypress 289 / 289.Still owed
NODE_ENV=production bun scripts/bench/browser.ts --ref <commit before this issue>with the window in front).HMarzban commentedon Nov 12, 2026
Pad check (local
dev-local, 2026-11-12) and one findingSetup: 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:
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.Cmd+Zin tab A gave back the unbolded pad with the same 4,000 links.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.
mainbefore this change does the same (checked in jsdom on both builds).HMarzban commentedon Nov 12, 2026
Committed
c9cd2c98aonmain, 2026-11-12, not pushed yet. One commit holds #770, #772, #773 and #776 together, by the maintainer's choice, so it cites each withRefs, and none closes on push. It is the same code the measured comments above describe.Open before this issue closes:
NODE_ENV=production bun scripts/bench/browser.ts --ref c9cd2c98a~1.HMarzban commentedon Nov 12, 2026
Browser before/after and pad profile (2026-11-12): base
c9cd2c98a~1, headc9cd2c98aCondition: 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:Each session ran 9 rounds in rotated order.
controlis a second copy of base, with the samedist/index.jssha256. Base has the same package source as release 2.3.0. There were two runs: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
backgroundflag. 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:Autolink's
appendTransactionwas 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.
browser.ts. It is in the working tree, not committed. The data supports it.Raw data:
wf3/m1-browser-bench/run-{1,2,3}.json,run-cpu4x.json,jsdom.json, and the verifier'swf3/m1-browser-bench-verify/.wf4/p6-browser-bench/run-{1,2,3}.json,run-oldprobe.json, andwf4/v-p6-browser-bench/{v-new,v-old}.json.wf4/p1-pad-profile/full.logandwf4/p1-verify/out-2026-11-12T19-34-07-461Z/summary.json.Re-run commands:
cd wf4/p6-browser-bench && bun drive.ts run-<k> 1 9 30, one session at a time.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(...))callsStepMap.mapexactly 3N²+N times for N mark steps. At N = 4,000 that is 48,004,000 calls. OurchangedRangescalls 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.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-hyperlink0.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 3in the localwf4/p1-pad-profileharness.fix(extension-hyperlink): keep links intact when autolink runs
perf(webapp): load HyperlinkBase in the pad and composer
HMarzban commentedon Nov 16, 2026
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.docs.plus/demo,github.com/docs-plus/docs.plusand[email protected]in tab A, then read tab Bhttps://docs.plus/demo,https://github.com/docs-plus/docs.plus,mailto:[email protected]https://example.com/plus a newline on an empty selectionhttps://example.com/, titledExample Domainby paste titleRuling (maintainer, 2026-11-16): the browser Bold result meets this issue. The quadratic cost is gone:
StepMap.mapcalls 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 since3d90636a9and still inb7888dce1. Release credit v2.3.8. Closing as done.