@celestia-island/hikari 0.55.398 → 0.55.399

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celestia-island/hikari",
3
- "version": "0.55.398",
3
+ "version": "0.55.399",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Hikari UI library, Vue 3 runtime — one design system for Vue 3 and Rust/WASM applications",
@@ -0,0 +1,46 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { createApp, defineComponent, h } from "vue";
3
+
4
+ // Mock the wasm module at the top level: the composable's lazy import()
5
+ // resolves to this factory, exactly like the real module landing after
6
+ // the first plaintext render.
7
+ vi.mock("../wasm/highlight/hikari_wasm_highlight.js", () => ({
8
+ highlight: (text: string, lang: string) => `<wasm>${lang}:${text}</wasm>`,
9
+ }));
10
+
11
+ import HkDiffViewer from "./HkDiffViewer";
12
+ import { useHighlight } from "../composables/useHighlight";
13
+
14
+ const DIFF = `--- a/rs
15
+ +++ b/rs
16
+ @@ -10,4 +10,5 @@
17
+ ctx-a
18
+ -removed
19
+ ctx-b
20
+ +added`;
21
+
22
+ describe("HkDiffViewer wasm-landing recolor (R2 S1-A)", () => {
23
+ it("memoized plaintext rows recolor once the wasm module lands and bumps the epoch", async () => {
24
+ // Advance the epoch first so this file starts with a clean memo
25
+ // (the Map is module-global and shared across files in a worker).
26
+ useHighlight().version.value += 1;
27
+ const container = document.createElement("div");
28
+ document.body.appendChild(container);
29
+ const Root = defineComponent({
30
+ setup() {
31
+ return () => h(HkDiffViewer, { diff: DIFF, language: "rust" } as never);
32
+ },
33
+ });
34
+ const app = createApp(Root);
35
+ app.mount(container);
36
+
37
+ // The composable bumps version itself when the (mocked) module lands;
38
+ // the memo must then drop its plaintext entries and serve wasm html.
39
+ await vi.waitFor(() => {
40
+ const html = container.querySelector(".hk-diff-viewer__code")?.innerHTML ?? "";
41
+ expect(html).toContain("<wasm>rust:");
42
+ });
43
+ app.unmount();
44
+ container.remove();
45
+ });
46
+ });
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
2
2
  import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
3
3
 
4
4
  import HkDiffViewer from "./HkDiffViewer";
5
+ import * as useHighlightModule from "../composables/useHighlight";
5
6
 
6
7
  /**
7
8
  * HkDiffViewer — the rendered half: hunk grouping, collapsed unchanged
@@ -350,3 +351,105 @@ describe("HkDiffViewer scroll map", () => {
350
351
  expect(hunkRows.length).toBeGreaterThan(4);
351
352
  });
352
353
  });
354
+
355
+
356
+ // ── Line-highlight memo (S2) ───────────────────────────────────────────
357
+ // A fold toggle re-renders the rows it kept; it must not re-run the wasm
358
+ // pest parser over them. The memo keys on (language, text) and is
359
+ // module-scoped (one page, one set of grammars), so each case below uses
360
+ // its own language id — that keeps the counts in this file independent
361
+ // while still exercising the shared cache.
362
+ describe("HkDiffViewer highlight memo", () => {
363
+ /** The wasm parser's per-line entry point (see useHighlight). */
364
+ const spyOnHighlight = () => vi.spyOn(useHighlightModule, "highlight");
365
+
366
+ it("re-expanding a fold re-renders rows without re-parsing them", async () => {
367
+ const spy = spyOnHighlight();
368
+ try {
369
+ const root = mount({ diff: DIFF, totalLines: 19, language: "memo-iron" });
370
+ await nextTick();
371
+ expect(root.querySelectorAll(".hk-diff-viewer__line")).toHaveLength(6);
372
+ // First paint: one parse per rendered row, no more.
373
+ expect(spy).toHaveBeenCalledTimes(6);
374
+
375
+ const head = root.querySelector(".hk-diff-viewer__hunk-head") as HTMLButtonElement;
376
+ head.click(); // collapse: the body leaves the tree, nothing to parse
377
+ await nextTick();
378
+ expect(root.querySelectorAll(".hk-diff-viewer__line")).toHaveLength(0);
379
+ expect(spy).toHaveBeenCalledTimes(6);
380
+
381
+ head.click(); // expand: same rows, served from the memo
382
+ await nextTick();
383
+ expect(root.querySelectorAll(".hk-diff-viewer__line")).toHaveLength(6);
384
+ // Three passes over the same rows used to mean 3 × 6 parses.
385
+ expect(spy).toHaveBeenCalledTimes(6);
386
+ } finally {
387
+ spy.mockRestore();
388
+ }
389
+ });
390
+
391
+ it("keeps one memo entry per (language, text) pair, not per pane", async () => {
392
+ const spy = spyOnHighlight();
393
+ try {
394
+ const root = mount({ diff: DIFF, totalLines: 19, language: "memo-silver" });
395
+ await nextTick();
396
+ expect(spy).toHaveBeenCalledTimes(6);
397
+ // A second viewer on the same content rides the shared memo: the rows
398
+ // are identical bytes, so a list of diffs pays once.
399
+ const second = mount({ diff: DIFF, totalLines: 19, language: "memo-silver" });
400
+ await nextTick();
401
+ expect(second.querySelectorAll(".hk-diff-viewer__line")).toHaveLength(6);
402
+ expect(spy).toHaveBeenCalledTimes(6);
403
+ // …while a different language is a different key.
404
+ const other = mount({ diff: DIFF, totalLines: 19, language: "memo-gold" });
405
+ await nextTick();
406
+ expect(other.querySelectorAll(".hk-diff-viewer__line")).toHaveLength(6);
407
+ expect(spy).toHaveBeenCalledTimes(12);
408
+ expect(root.querySelectorAll(".hk-diff-viewer__line")).toHaveLength(6);
409
+ } finally {
410
+ spy.mockRestore();
411
+ }
412
+ });
413
+
414
+ it("hovering a row is a CSS-only state change (no render, no parse)", async () => {
415
+ const spy = spyOnHighlight();
416
+ try {
417
+ const root = mount({ diff: DIFF, totalLines: 19, language: "memo-jade" });
418
+ await nextTick();
419
+ const row = root.querySelector(".hk-diff-viewer__line") as HTMLElement;
420
+ expect(spy).toHaveBeenCalledTimes(6);
421
+ // Hover carries no component state — the class/colour comes from the
422
+ // stylesheet — so the same node must survive the interaction.
423
+ row.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
424
+ row.dispatchEvent(new MouseEvent("mouseenter"));
425
+ await nextTick();
426
+ expect(root.querySelector(".hk-diff-viewer__line")).toBe(row);
427
+ expect(spy).toHaveBeenCalledTimes(6);
428
+ } finally {
429
+ spy.mockRestore();
430
+ }
431
+ });
432
+
433
+ it("parses only the newly revealed rows when a gap fetches context", async () => {
434
+ const spy = spyOnHighlight();
435
+ try {
436
+ const loadContext = vi.fn(async (start: number, count: number) =>
437
+ Array.from({ length: count }, (_, i) => `line-${start + i}`),
438
+ );
439
+ const root = mount({
440
+ diff: DIFF, totalLines: 19, loadContext, contextChunk: 2, language: "memo-onyx",
441
+ });
442
+ await nextTick();
443
+ expect(spy).toHaveBeenCalledTimes(6);
444
+ (root.querySelectorAll(".hk-diff-viewer__gap")[1] as HTMLButtonElement).click();
445
+ await tick();
446
+ await nextTick();
447
+ // The two revealed rows are new bytes (exactly two parses); the six
448
+ // rows the fold kept are memo hits.
449
+ expect(spy).toHaveBeenCalledTimes(8);
450
+ } finally {
451
+ spy.mockRestore();
452
+ }
453
+ });
454
+ });
455
+
@@ -2,7 +2,7 @@ import { computed, defineComponent, onMounted, ref, watch } from "vue";
2
2
  import { AlertTriangle, ChevronDown, ChevronRight, UnfoldVertical } from "lucide-vue-next";
3
3
  import HkSpinner from "./HkSpinner";
4
4
  import { useI18n } from "../i18n/context";
5
- import { highlight } from "../composables/useHighlight";
5
+ import { highlight, useHighlight } from "../composables/useHighlight";
6
6
  import { computeGaps, parseUnifiedDiff, type DiffLine, type UnchangedGap } from "./diffParse";
7
7
  import type { OverlayScrollMapSegment } from "../composables/useOverlayScrollbar";
8
8
  import "./HkDiffViewer.scss";
@@ -29,6 +29,45 @@ import "./HkDiffViewer.scss";
29
29
  * grammar lands, exactly like the markdown code blocks.
30
30
  */
31
31
 
32
+ /**
33
+ * Line-highlight memo.
34
+ *
35
+ * A diff pane re-renders on every fold toggle, every revealed context
36
+ * batch and every scroll-map emission, and each pass used to run the wasm
37
+ * pest parser once per VISIBLE row — so collapsing and re-expanding one
38
+ * hunk re-highlighted the same bytes three times, and a long file paid for
39
+ * its whole window on every interaction. A row's html is a pure function of
40
+ * (language, text) and rows come straight out of the immutable parsed diff,
41
+ * so the result is computed once per pair and reused for the lifetime of
42
+ * the page (bounded, and keyed by language so two panes on different
43
+ * languages never share an entry).
44
+ *
45
+ * Invalidation: `highlight()` falls back to escaped text until the wasm
46
+ * module lands, and the module bumps a reactive version when it does — the
47
+ * epoch below drops every pre-load entry so the colored html is recomputed
48
+ * exactly once instead of the plaintext being served forever.
49
+ */
50
+ const HIGHLIGHT_MEMO_LIMIT = 4000;
51
+ const highlightMemo = new Map<string, string>();
52
+ let highlightMemoEpoch = -1;
53
+
54
+ function memoHighlight(text: string, lang: string, epoch: number): string {
55
+ if (epoch !== highlightMemoEpoch) {
56
+ highlightMemoEpoch = epoch;
57
+ highlightMemo.clear();
58
+ }
59
+ const key = `${lang}\u0000${text}`;
60
+ const hit = highlightMemo.get(key);
61
+ if (hit !== undefined) return hit;
62
+ const html = highlight(text, lang);
63
+ // Drop the whole batch rather than track an LRU: the memo is shared
64
+ // module-level across panes, so an overflow clears every pane's entries
65
+ // (bounded, not locality-preserving) and the next pass refills it.
66
+ if (highlightMemo.size >= HIGHLIGHT_MEMO_LIMIT) highlightMemo.clear();
67
+ highlightMemo.set(key, html);
68
+ return html;
69
+ }
70
+
32
71
  interface GapState {
33
72
  /** Lines already revealed. */
34
73
  revealed: number;
@@ -75,6 +114,10 @@ export default defineComponent({
75
114
  setup(props, { emit }) {
76
115
  const host = ref<HTMLElement | null>(null);
77
116
  const { t } = useI18n();
117
+ // Reading this inside the render effect keeps the rows subscribed to the
118
+ // wasm load: when the module lands the epoch changes, the memo drops its
119
+ // plaintext entries and every row re-colors in the same pass.
120
+ const { version: highlightEpoch } = useHighlight();
78
121
 
79
122
  const parsed = computed(() => parseUnifiedDiff(props.diff));
80
123
  const gaps = computed(() => computeGaps(parsed.value, props.totalLines ?? null));
@@ -253,7 +296,10 @@ export default defineComponent({
253
296
 
254
297
  function renderLine(line: DiffLine, key: string) {
255
298
  const sign = line.kind === "add" ? "+" : line.kind === "del" ? "−" : "";
256
- const html = props.language ? highlight(line.text, props.language) : null;
299
+ // Memoized: a fold toggle re-renders the row, it does not re-parse it.
300
+ const html = props.language
301
+ ? memoHighlight(line.text, props.language, highlightEpoch.value)
302
+ : null;
257
303
  return (
258
304
  <div class="hk-diff-viewer__line" data-kind={line.kind} key={key}>
259
305
  <span class="hk-diff-viewer__no">{line.oldNo ?? ""}</span>
@@ -1,5 +1,6 @@
1
- import { afterEach, describe, expect, it } from "vitest";
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
2
  import { createApp, h, nextTick, ref } from "vue";
3
+ import { marked } from "marked";
3
4
 
4
5
  import HkMarkdownRenderer from "./HkMarkdownRenderer";
5
6
  import { setMermaidEngineForTests } from "../mermaid/engine";
@@ -146,3 +147,79 @@ describe("mermaid sub-app lifecycle pins", () => {
146
147
  expect(host.isConnected).toBe(false);
147
148
  });
148
149
  });
150
+
151
+ // ── Streaming reuse (S2) ───────────────────────────────────────────────
152
+ // A streamed reply re-emits every fence above the growing tail byte for
153
+ // byte on every chunk. The diagram under such a fence must survive the
154
+ // re-parse: unmounting a live board and mounting a byte-identical one is
155
+ // the expensive half of a mermaid block (engine layout), and it is the
156
+ // half the fence text itself can rule out.
157
+ describe("mermaid streaming reuse", () => {
158
+ /** Poll for a text token (the body is innerHTML, not vdom). */
159
+ async function settleForText(root: HTMLElement, text: string, tries = 160): Promise<void> {
160
+ for (let i = 0; i < tries; i += 1) {
161
+ if ((root.textContent ?? "").includes(text)) return;
162
+ await new Promise((r) => setTimeout(r, 5));
163
+ await nextTick();
164
+ }
165
+ }
166
+
167
+ it("reuses the mounted diagram when the fence source is unchanged", async () => {
168
+ setMermaidEngineForTests(mermaidParser);
169
+ const parseSpy = vi.spyOn(marked, "parse");
170
+ try {
171
+ const { container, set } = mount(DOC);
172
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
173
+ const host = container.querySelector(".hk-md-mermaid") as HTMLElement;
174
+ const board = host.querySelector(".hk-board");
175
+ expect(board).not.toBeNull();
176
+ expect(parseSpy).toHaveBeenCalledTimes(1);
177
+
178
+ // The stream appends prose BELOW the fence — the fence text is
179
+ // byte-identical, so the rendered board must ride along.
180
+ set(`${DOC}\n\nmore streamed prose`);
181
+ await settleForText(container, "more streamed prose");
182
+ await nextTick();
183
+ expect(parseSpy).toHaveBeenCalledTimes(2); // the BODY was re-parsed…
184
+
185
+ const after = container.querySelector(".hk-md-mermaid") as HTMLElement;
186
+ expect(after).toBe(host); // …and the diagram node was not rebuilt
187
+ expect(host.isConnected).toBe(true);
188
+ expect(host.querySelector(".hk-board")).toBe(board); // same live board
189
+ expect(container.querySelectorAll(".hk-md-mermaid")).toHaveLength(1);
190
+ } finally {
191
+ parseSpy.mockRestore();
192
+ }
193
+ });
194
+
195
+ it("still rebuilds the diagram when the fence source itself changes", async () => {
196
+ setMermaidEngineForTests(mermaidParser);
197
+ const { container, set } = mount(DOC);
198
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
199
+ const first = container.querySelector(".hk-md-mermaid") as HTMLElement;
200
+
201
+ // Streaming INTO the fence: the source grows, so the board must be new.
202
+ set(DOC.replace("A[Alpha] --> B[Beta]", "A[Alpha] --> B[Beta]\n B --> C[Gamma]"));
203
+ await settleForText(container, "Gamma");
204
+ await new Promise((r) => setTimeout(r, 60));
205
+ await nextTick();
206
+ const fresh = container.querySelector(".hk-md-mermaid") as HTMLElement;
207
+ expect(fresh).not.toBe(first);
208
+ expect(first.isConnected).toBe(false);
209
+ expect((first as unknown as Record<string, unknown>).__vue_app__).toBeUndefined();
210
+ });
211
+
212
+ it("retires the sub-app when the fence disappears from the body", async () => {
213
+ setMermaidEngineForTests(mermaidParser);
214
+ const { container, set } = mount(DOC);
215
+ await settleFor(container, ".hk-md-mermaid[data-mermaid='mounted']");
216
+ const host = container.querySelector(".hk-md-mermaid") as HTMLElement;
217
+
218
+ set("prose only now");
219
+ await settleForText(container, "prose only now");
220
+ await new Promise((r) => setTimeout(r, 60));
221
+ await nextTick();
222
+ expect(container.querySelector(".hk-md-mermaid")).toBeNull();
223
+ expect((host as unknown as Record<string, unknown>).__vue_app__).toBeUndefined();
224
+ });
225
+ });
@@ -0,0 +1,40 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { createApp, h, ref } from "vue";
3
+
4
+ // NO static `import { marked }` here: the delayed factory below must apply
5
+ // to the COMPONENT's lazy dynamic import, not to this file's load.
6
+ vi.mock("marked", async (importOriginal) => {
7
+ await new Promise((r) => setTimeout(r, 150));
8
+ return importOriginal<typeof import("marked")>();
9
+ });
10
+
11
+ describe("HkMarkdownRenderer stale-parse overlap (R2 S1-B)", () => {
12
+ it("a parse left behind by a newer body never overwrites it", async () => {
13
+ vi.resetModules();
14
+ const { default: Renderer } = await import("./HkMarkdownRenderer");
15
+
16
+ const holder = ref("A-markdown-body");
17
+ const plain = ref(false);
18
+ const container = document.createElement("div");
19
+ document.body.appendChild(container);
20
+ const app = createApp({
21
+ render: () => h(Renderer, { content: holder.value, plain: plain.value }),
22
+ });
23
+ app.mount(container);
24
+
25
+ // The A parse is in flight, hung on the delayed marked import; flip to
26
+ // plain with a new body — renderPlain is synchronous, so B lands at
27
+ // once. When the import resolves, A's parse is stale and must NOT own
28
+ // the body (the parseToken guard is what rejects it).
29
+ await new Promise((r) => setTimeout(r, 30));
30
+ plain.value = true;
31
+ holder.value = "B-plain-body";
32
+ await new Promise((r) => setTimeout(r, 350));
33
+
34
+ const text = container.textContent ?? "";
35
+ expect(text).toContain("B-plain-body");
36
+ expect(text).not.toContain("A-markdown-body");
37
+ app.unmount();
38
+ container.remove();
39
+ }, 15000);
40
+ });
@@ -0,0 +1,160 @@
1
+ // AI-generated: developed with the DeepSeek Harness agent (model DeepSeek V4.1 Flash); human-directed.
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { createApp, h, nextTick, ref } from "vue";
4
+ import { marked } from "marked";
5
+
6
+ import HkMarkdownRenderer from "./HkMarkdownRenderer";
7
+
8
+ /**
9
+ * Streaming (S2) contract for HkMarkdownRenderer.
10
+ *
11
+ * A streamed body (chat delta, agent trace, report being assembled) arrives
12
+ * one chunk per token batch. Every chunk used to run the whole pipeline —
13
+ * marked.parse over the entire body, DOMPurify, the DOMParser URL sweep and
14
+ * an innerHTML replacement — so n chunks over a body of length L cost
15
+ * O(n·L) parse work for O(L) of text: quadratic in the reply length. These
16
+ * cases pin the two fixes:
17
+ *
18
+ * - coalescing: a burst of chunks renders at most twice (leading edge +
19
+ * one trailing parse of the LATEST content), never once per chunk;
20
+ * - memo: a chrome flip (inlineChips) re-seats the markup the component
21
+ * already holds instead of paying a second full parse for the same body.
22
+ *
23
+ * `marked.parse` is the honest counter for "a full body render": it is the
24
+ * first and most expensive stage of the pipeline, and it runs exactly once
25
+ * per parse that actually happens.
26
+ */
27
+
28
+ const mounts: Array<{ app: ReturnType<typeof createApp>; container: HTMLElement }> = [];
29
+
30
+ function mountContent(initial: string) {
31
+ const holder = ref(initial);
32
+ const container = document.createElement("div");
33
+ document.body.appendChild(container);
34
+ const app = createApp({
35
+ render: () => h(HkMarkdownRenderer, { content: holder.value }),
36
+ });
37
+ app.mount(container);
38
+ mounts.push({ app, container });
39
+ return { container, set: (v: string) => { holder.value = v; } };
40
+ }
41
+
42
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
43
+
44
+ async function settleFor(root: HTMLElement, text: string, tries = 240): Promise<void> {
45
+ for (let i = 0; i < tries; i += 1) {
46
+ if ((root.textContent ?? "").includes(text)) return;
47
+ await sleep(5);
48
+ await nextTick();
49
+ }
50
+ }
51
+
52
+ let parseSpy: ReturnType<typeof vi.spyOn>;
53
+
54
+ beforeEach(() => {
55
+ // Same module instance the renderer lazily imports and parses through.
56
+ parseSpy = vi.spyOn(marked, "parse");
57
+ });
58
+
59
+ afterEach(() => {
60
+ parseSpy.mockRestore();
61
+ for (const { app, container } of mounts.splice(0)) {
62
+ app.unmount();
63
+ container.remove();
64
+ }
65
+ });
66
+
67
+ describe("HkMarkdownRenderer streaming", () => {
68
+ it("collapses a burst of content updates into at most two full parses", async () => {
69
+ const { container, set } = mountContent("stream start");
70
+ await settleFor(container, "stream start");
71
+ const initialParses = parseSpy.mock.calls.length;
72
+ expect(initialParses).toBe(1);
73
+
74
+ // Let the coalescing window close so the burst starts from an idle
75
+ // renderer — the leading edge is then immediate, as it is for the first
76
+ // paint of a settled body.
77
+ await sleep(80);
78
+ let text = "stream start";
79
+ for (let i = 1; i <= 10; i += 1) {
80
+ text = `${text} chunk-${i}`;
81
+ set(text);
82
+ // One Vue flush per chunk: the cadence a token stream really has
83
+ // (chunks land in successive ticks, far faster than a frame).
84
+ await nextTick();
85
+ }
86
+
87
+ // Trailing edge: the LAST chunk is always rendered, whatever the window.
88
+ await settleFor(container, "chunk-10");
89
+ const extra = parseSpy.mock.calls.length - initialParses;
90
+ // Ten chunks used to mean ten parses of the whole growing body.
91
+ expect(extra).toBeGreaterThanOrEqual(1);
92
+ expect(extra).toBeLessThanOrEqual(2);
93
+ expect(container.textContent).toContain("chunk-1 chunk-2 chunk-3");
94
+ });
95
+
96
+ it("renders every chunk that arrives after a quiet period (leading edge stays live)", async () => {
97
+ const { container, set } = mountContent("idle body");
98
+ await settleFor(container, "idle body");
99
+ const initialParses = parseSpy.mock.calls.length;
100
+ // Two chunks paced well beyond the window are two separate renders — a
101
+ // throttle that sat on them would delay a non-streaming update for no
102
+ // reason.
103
+ set("idle body plus one");
104
+ await settleFor(container, "plus one");
105
+ set("idle body plus one and two");
106
+ await settleFor(container, "and two");
107
+ expect(parseSpy.mock.calls.length - initialParses).toBe(2);
108
+ });
109
+
110
+ it("re-seats the held markup for an inlineChips flip instead of re-parsing", async () => {
111
+ const content = "Badge {{container_badge}} here";
112
+ const holder = ref(content);
113
+ const chips = ref(false);
114
+ const container = document.createElement("div");
115
+ document.body.appendChild(container);
116
+ const app = createApp({
117
+ render: () => h(HkMarkdownRenderer, { content: holder.value, inlineChips: chips.value }),
118
+ });
119
+ app.mount(container);
120
+ mounts.push({ app, container });
121
+
122
+ await settleFor(container, "here");
123
+ const parses = parseSpy.mock.calls.length;
124
+ expect(parses).toBe(1);
125
+ expect(container.querySelector(".hk-tpl-chip")).toBeNull();
126
+
127
+ chips.value = true;
128
+ await nextTick();
129
+ await sleep(30);
130
+ await nextTick();
131
+
132
+ // The chip pass ran on the SAME body: markup, not a second parse.
133
+ expect(container.querySelector(".hk-tpl-chip")).not.toBeNull();
134
+ expect(parseSpy.mock.calls.length).toBe(parses);
135
+
136
+ // …and flipping it back re-seats the un-chipped html again, still free.
137
+ chips.value = false;
138
+ await nextTick();
139
+ await sleep(30);
140
+ await nextTick();
141
+ expect(container.querySelector(".hk-tpl-chip")).toBeNull();
142
+ expect(container.textContent).toContain("Badge");
143
+ expect(parseSpy.mock.calls.length).toBe(parses);
144
+ });
145
+
146
+ it("a chunk landing mid-parse supersedes the older render (no stale body)", async () => {
147
+ const { container, set } = mountContent("first body");
148
+ await settleFor(container, "first body");
149
+ // Two updates: the second lands while the first parse is still resolving
150
+ // its imports/markup. The body must end on the newer text, never on the
151
+ // older one that finished last.
152
+ set("second body");
153
+ set("third body");
154
+ await settleFor(container, "third body");
155
+ await sleep(80);
156
+ await nextTick();
157
+ expect(container.textContent).toContain("third body");
158
+ expect(container.textContent).not.toContain("second body");
159
+ });
160
+ });
@@ -186,6 +186,28 @@ function sweepDangerousUrlAttributes(html: string): string {
186
186
  }
187
187
  }
188
188
 
189
+ /**
190
+ * Streaming coalescing window, in ms.
191
+ *
192
+ * A streamed reply (chat delta, agent trace, report being assembled) lands
193
+ * one chunk per token batch — many chunks per animation frame — and every
194
+ * chunk used to run the WHOLE pipeline: marked.parse over the entire body,
195
+ * DOMPurify, the DOMParser URL sweep, an innerHTML replacement of a node
196
+ * the browser then re-lays-out, plus a full mermaid re-mount. At n chunks
197
+ * over a body of length L that is O(n·L) parse work for O(L) of visible
198
+ * text, and the DOM writes land far faster than the eye (or the compositor)
199
+ * can use them.
200
+ *
201
+ * Chunks arriving inside one window collapse into a single parse against
202
+ * the LATEST props: the leading edge renders immediately when the renderer
203
+ * is idle (first paint, a settled body), and a change that lands inside the
204
+ * window defers to the window's end. The timer is armed once per window,
205
+ * never re-armed by later chunks — a debounce would starve the render
206
+ * entirely under a chunk every 40ms, and the trailing edge guarantees the
207
+ * final chunk is always rendered.
208
+ */
209
+ const STREAM_COALESCE_MS = 50;
210
+
189
211
  export default defineComponent({
190
212
  name: "HkMarkdownRenderer",
191
213
  props: {
@@ -220,30 +242,111 @@ export default defineComponent({
220
242
  // behind after `inlineChips` goes back to false.
221
243
  const parseSeq = ref(0);
222
244
 
245
+ let coalesceTimer: ReturnType<typeof setTimeout> | null = null;
246
+ let parsePending = false;
247
+ let lastParseStartedAt = Number.NEGATIVE_INFINITY;
248
+ // Monotonic token: a coalesced parse can still overlap the previous one
249
+ // (the marked/DOMPurify imports resolve on their own schedule), and the
250
+ // older one must never overwrite the newer body when it finishes last.
251
+ let parseToken = 0;
252
+ // Parse memo. `renderedHtml` is a pure function of (content, plain) — the
253
+ // sanitize configuration is module-fixed, so nothing else can change the
254
+ // markup. Remembers the source the CURRENT html came from, which lets an
255
+ // `inlineChips` flip (same body, different chrome) re-seat the existing
256
+ // markup instead of paying a second marked+sanitize pass for it.
257
+ let parsedSourceKey: string | null = null;
258
+
259
+ function nowMs(): number {
260
+ return typeof performance !== "undefined" && typeof performance.now === "function"
261
+ ? performance.now()
262
+ : Date.now();
263
+ }
264
+
265
+ function parseSourceKey(content: string, plain: boolean): string {
266
+ return plain ? `plain\u0000${content}` : `md\u0000${content}`;
267
+ }
268
+
223
269
  async function parse() {
224
- if (!props.content) {
270
+ const token = (parseToken += 1);
271
+ lastParseStartedAt = nowMs();
272
+ const content = props.content;
273
+ if (!content) {
225
274
  renderedHtml.value = "";
275
+ parseError.value = false;
276
+ parsedSourceKey = null;
277
+ // Re-seat the body even when empty: the DOM pass is what prunes the
278
+ // sub-apps and the overlay handles the now-gone content owned.
279
+ parseSeq.value += 1;
280
+ return;
281
+ }
282
+ const plain = props.plain;
283
+ const sourceKey = parseSourceKey(content, plain);
284
+ if (sourceKey === parsedSourceKey) {
285
+ // Same body, different chrome: the markup is already in hand. Bump
286
+ // the sequence so the chip pass re-runs from the pristine html.
287
+ parseSeq.value += 1;
226
288
  return;
227
289
  }
228
290
  parseError.value = false;
291
+ let html: string;
229
292
  try {
230
- if (props.plain) {
231
- renderedHtml.value = renderPlain(props.content);
232
- } else {
233
- renderedHtml.value = await renderMarkdown(props.content);
234
- }
293
+ html = plain ? renderPlain(content) : await renderMarkdown(content);
235
294
  } catch {
236
295
  parseError.value = true;
237
- renderedHtml.value = renderPlain(props.content);
238
- } finally {
239
- parseSeq.value += 1;
296
+ html = renderPlain(content);
240
297
  }
298
+ if (token !== parseToken) return; // a newer parse already owns the body
299
+ renderedHtml.value = html;
300
+ parsedSourceKey = sourceKey;
301
+ parseSeq.value += 1;
241
302
  }
242
303
 
304
+ /** @see STREAM_COALESCE_MS — coalesced entry for streaming content. */
305
+ function scheduleParse(): void {
306
+ parsePending = true;
307
+ if (coalesceTimer !== null) return;
308
+ const elapsed = nowMs() - lastParseStartedAt;
309
+ if (elapsed >= STREAM_COALESCE_MS) {
310
+ // Idle leading edge: start now, on the same tick the unfixed
311
+ // renderer always did (first paint, SSR/hydration, a settled body
312
+ // receiving one edit). The window exists only to collect a burst.
313
+ parsePending = false;
314
+ void parse();
315
+ return;
316
+ }
317
+ coalesceTimer = setTimeout(() => {
318
+ coalesceTimer = null;
319
+ if (!parsePending) return;
320
+ parsePending = false;
321
+ void parse();
322
+ }, STREAM_COALESCE_MS - elapsed);
323
+ }
324
+
325
+ /** Immediate entry for one-shot prop flips (drop a pending coalesce). */
326
+ function parseNow(): void {
327
+ if (coalesceTimer !== null) {
328
+ clearTimeout(coalesceTimer);
329
+ coalesceTimer = null;
330
+ }
331
+ parsePending = false;
332
+ void parse();
333
+ }
334
+
335
+ // Content is the streaming dimension: coalesced (see scheduleParse).
336
+ // `flush: "post"` keeps the parse behind any prop update that landed in
337
+ // the same tick, so it always reads the settled props.
338
+ watch(
339
+ () => props.content,
340
+ () => { scheduleParse(); },
341
+ { immediate: true, flush: "post" },
342
+ );
343
+
344
+ // Chrome flips are deliberate one-shot actions, not a stream: render at
345
+ // once (the memo turns an `inlineChips` flip into a DOM re-seat).
243
346
  watch(
244
- () => [props.content, props.plain, props.inlineChips],
245
- () => { void parse(); },
246
- { immediate: true },
347
+ () => [props.plain, props.inlineChips],
348
+ () => { parseNow(); },
349
+ { flush: "post" },
247
350
  );
248
351
 
249
352
  // Overlay scrollbars (shared chrome) on the markdown blocks that can
@@ -259,33 +362,57 @@ export default defineComponent({
259
362
  // the only way to mount a component inside it); they are tracked so
260
363
  // a re-parse (body replaced wholesale) and the final unmount never
261
364
  // leak an app on a detached node.
262
- const mermaidApps: Array<{ el: HTMLElement; app: App }> = [];
365
+ //
366
+ // `source` is kept alongside the node so a re-parse can RECOGNISE a
367
+ // diagram whose fence text did not change and hand the existing node
368
+ // (with its live sub-app, board and canvas) into the new slot: the
369
+ // mount is the expensive half of a mermaid block (engine layout), and
370
+ // while streaming every chunk that grows a LATER part of the body
371
+ // re-emits the fences above it byte-identically.
372
+ const mermaidApps: Array<{ el: HTMLElement; app: App; source: string }> = [];
263
373
 
264
- function pruneMermaidApps(): void {
265
- for (let i = mermaidApps.length - 1; i >= 0; i -= 1) {
266
- if (!mermaidApps[i].el.isConnected) {
267
- mermaidApps[i].app.unmount();
268
- mermaidApps.splice(i, 1);
374
+ function syncMermaidBlocks(body: HTMLElement): void {
375
+ const carriers = [...body.querySelectorAll<HTMLElement>('.hk-md-mermaid-src[data-mermaid="pending"]')];
376
+ // Reuse pool: mounted hosts grouped by fence source, in document
377
+ // order, so identical fences pair up one-to-one and predictably.
378
+ const spare = new Map<string, Array<{ el: HTMLElement; app: App; source: string }>>();
379
+ for (const mounted of mermaidApps) {
380
+ const list = spare.get(mounted.source);
381
+ if (list) list.push(mounted);
382
+ else spare.set(mounted.source, [mounted]);
383
+ }
384
+ const kept = new Set<{ el: HTMLElement; app: App; source: string }>();
385
+ if (getMermaidEngine()) {
386
+ for (const carrier of carriers) {
387
+ const source = carrier.querySelector("code")?.textContent ?? "";
388
+ const reuse = spare.get(source)?.shift();
389
+ if (reuse) {
390
+ // Same fence text → the same rendered diagram: splice the live
391
+ // node into the re-seated body instead of unmounting it here
392
+ // and mounting a byte-identical one a millisecond later.
393
+ carrier.replaceWith(reuse.el);
394
+ kept.add(reuse);
395
+ continue;
396
+ }
397
+ const host = document.createElement("div");
398
+ host.className = "hk-md-mermaid";
399
+ host.dataset.mermaid = "mounted";
400
+ carrier.replaceWith(host);
401
+ // Report contexts are narrow reading panes: the minimap is noise
402
+ // for a diagram-sized board, canvas dragging stays on (wide
403
+ // diagrams are exactly what pan was built for).
404
+ const app = createApp(HkMermaidDiagram, { source, minimap: false, interactive: true });
405
+ app.mount(host);
406
+ kept.add({ el: host, app, source });
269
407
  }
270
408
  }
271
- }
272
-
273
- function syncMermaidBlocks(body: HTMLElement): void {
274
- pruneMermaidApps();
275
- if (!getMermaidEngine()) return;
276
- for (const carrier of body.querySelectorAll<HTMLElement>('.hk-md-mermaid-src[data-mermaid="pending"]')) {
277
- const source = carrier.querySelector("code")?.textContent ?? "";
278
- const host = document.createElement("div");
279
- host.className = "hk-md-mermaid";
280
- host.dataset.mermaid = "mounted";
281
- carrier.replaceWith(host);
282
- // Report contexts are narrow reading panes: the minimap is noise
283
- // for a diagram-sized board, canvas dragging stays on (wide
284
- // diagrams are exactly what pan was built for).
285
- const app = createApp(HkMermaidDiagram, { source, minimap: false, interactive: true });
286
- app.mount(host);
287
- mermaidApps.push({ el: host, app });
409
+ // Everything not carried into this pass belongs to a fence that is
410
+ // gone from the body (or to a render with no engine): retire it.
411
+ for (const mounted of mermaidApps) {
412
+ if (!kept.has(mounted)) mounted.app.unmount();
288
413
  }
414
+ mermaidApps.length = 0;
415
+ mermaidApps.push(...kept);
289
416
  }
290
417
 
291
418
  function syncOverlayScrollbars() {
@@ -321,6 +448,14 @@ export default defineComponent({
321
448
  });
322
449
 
323
450
  onBeforeUnmount(() => {
451
+ // A stream can still be mid-flight at teardown: the pending coalesce
452
+ // must not fire a parse (and a body write) on an unmounted component.
453
+ if (coalesceTimer !== null) {
454
+ clearTimeout(coalesceTimer);
455
+ coalesceTimer = null;
456
+ }
457
+ parsePending = false;
458
+ parseToken += 1;
324
459
  for (const c of overlayScrollbars) c.handle.detach();
325
460
  overlayScrollbars.length = 0;
326
461
  for (const m of mermaidApps) m.app.unmount();
@@ -673,3 +673,99 @@ describe("HkTooltip closed-popup reachability (R2 S2)", () => {
673
673
  expect(document.querySelector(".hk-tooltip-popup")).toBeNull();
674
674
  });
675
675
  });
676
+
677
+ // ── Position tracking budget (S2) ──────────────────────────────────────
678
+ // The bubble used to hold a permanent per-frame loop while visible: two
679
+ // getBoundingClientRect reads plus the computed-style zoom lookup, 60 times
680
+ // a second, whether or not anything had moved. Geometry now rides explicit
681
+ // signals (ResizeObserver on trigger + popup, scroll / resize / wheel), and
682
+ // the frame sampler that catches un-evented motion retires on its own once
683
+ // the trigger holds still.
684
+ describe("HkTooltip position tracking budget", () => {
685
+ it("observes the trigger and the popup through a ResizeObserver", async () => {
686
+ const observe = vi.spyOn(ResizeObserver.prototype, "observe");
687
+ const disconnect = vi.spyOn(ResizeObserver.prototype, "disconnect");
688
+ try {
689
+ const { app, container } = mount({ text: "observed", delay: 0 });
690
+ enter(container);
691
+ await settle();
692
+ const trigger = wrapper(container);
693
+ expect(observe.mock.calls.some(([el]) => el === trigger)).toBe(true);
694
+ // The bubble's own box reflows when its text lands; that is a
695
+ // geometry change too.
696
+ expect(observe.mock.calls.some(([el]) => el === popup())).toBe(true);
697
+ // Observers outlive a hide (re-shows must not churn them) but never
698
+ // the component.
699
+ leave(container);
700
+ await nextTick();
701
+ expect(disconnect).not.toHaveBeenCalled();
702
+ app.unmount();
703
+ expect(disconnect).toHaveBeenCalled();
704
+ } finally {
705
+ observe.mockRestore();
706
+ disconnect.mockRestore();
707
+ }
708
+ });
709
+
710
+ it("retires the frame sampler at rest and re-arms on a signal", async () => {
711
+ const { container } = mount({ text: "resting", delay: 0, placement: "bottom" });
712
+ const anchor = wrapper(container);
713
+ let top = 100;
714
+ let rectReads = 0;
715
+ anchor.getBoundingClientRect = () => {
716
+ rectReads += 1;
717
+ return {
718
+ x: 200, y: top, left: 200, top, right: 280, bottom: top + 40,
719
+ width: 80, height: 40, toJSON: () => ({}),
720
+ } as DOMRect;
721
+ };
722
+ enter(container);
723
+ await settle();
724
+ expect(popup().style.top).toBe("148px");
725
+
726
+ // Past the quiet window the loop is gone: nothing measures the trigger,
727
+ // frame after frame, for a bubble that is simply sitting there.
728
+ await new Promise((r) => setTimeout(r, 240));
729
+ const parked = rectReads;
730
+ await new Promise((r) => setTimeout(r, 120));
731
+ expect(rectReads).toBe(parked);
732
+
733
+ // …and the signals bring it straight back, on the event's own turn (no
734
+ // waiting for the next frame): a scrolled container, then a wheel-pan.
735
+ top = 130;
736
+ document.dispatchEvent(new Event("scroll"));
737
+ expect(popup().style.top).toBe("178px"); // 130 + 40 + 8
738
+ top = 160;
739
+ window.dispatchEvent(new Event("wheel"));
740
+ expect(popup().style.top).toBe("208px");
741
+
742
+ leave(container);
743
+ await nextTick();
744
+ expect(popup().className).not.toContain("hk-tooltip-visible");
745
+ });
746
+
747
+ it("stops measuring the trigger once the bubble is hidden", async () => {
748
+ const { container } = mount({ text: "gone", delay: 0 });
749
+ const anchor = wrapper(container);
750
+ let rectReads = 0;
751
+ anchor.getBoundingClientRect = () => {
752
+ rectReads += 1;
753
+ return {
754
+ x: 0, y: 0, left: 0, top: 0, right: 10, bottom: 10,
755
+ width: 10, height: 10, toJSON: () => ({}),
756
+ } as DOMRect;
757
+ };
758
+ enter(container);
759
+ await settle();
760
+ leave(container);
761
+ await nextTick();
762
+ const parked = rectReads;
763
+ // A scroll with the bubble down must not measure (or place) anything.
764
+ document.dispatchEvent(new Event("scroll"));
765
+ await new Promise((r) => setTimeout(r, 60));
766
+ expect(rectReads).toBe(parked);
767
+ expect(document.querySelector(".hk-tooltip-popup")!.className).not.toContain(
768
+ "hk-tooltip-visible",
769
+ );
770
+ });
771
+ });
@@ -1,4 +1,4 @@
1
- import { computed, defineComponent, nextTick, onBeforeUnmount, ref, Teleport, type CSSProperties, type PropType, type SlotsType } from "vue";
1
+ import { computed, defineComponent, nextTick, onBeforeUnmount, ref, Teleport, watch, type CSSProperties, type PropType, type SlotsType } from "vue";
2
2
  import { usePopupManager, type PopupHandle } from "../runtime/usePopupManager";
3
3
  import { applyTooltipPosition, type TooltipPlacement } from "../runtime/tooltipPosition";
4
4
  import { armTouchHint } from "../runtime/touchHint";
@@ -34,6 +34,39 @@ export type TooltipTrigger = "hover" | "click";
34
34
 
35
35
  let popupSeq = 0;
36
36
 
37
+ /**
38
+ * Position tracking budget.
39
+ *
40
+ * The bubble used to own a permanent per-frame loop for as long as it was
41
+ * visible: two `getBoundingClientRect` reads plus the computed-style zoom
42
+ * lookup, re-placing the popup 60 times a second whether anything had moved
43
+ * or not (a hover annotation in a dense grid cost more than the app it
44
+ * annotated). Geometry now follows explicit signals — see `hookPositionSignals`
45
+ * — and the frame loop only survives to catch motion that fires no event at
46
+ * all; it retires on its own once the trigger has held still.
47
+ */
48
+ /** One geometry sample per display frame at most (16.7ms @ 60Hz). */
49
+ const POSITION_FRAME_MIN_MS = 16;
50
+ /** No rect change for this long ⇒ the trigger is at rest ⇒ retire. */
51
+ const POSITION_QUIET_MS = 180;
52
+
53
+ interface RectSnapshot {
54
+ left: number;
55
+ top: number;
56
+ width: number;
57
+ height: number;
58
+ }
59
+
60
+ function nowMs(): number {
61
+ return typeof performance !== "undefined" && typeof performance.now === "function"
62
+ ? performance.now()
63
+ : Date.now();
64
+ }
65
+
66
+ function rectSnapshot(rect: DOMRect): RectSnapshot {
67
+ return { left: rect.left, top: rect.top, width: rect.width, height: rect.height };
68
+ }
69
+
37
70
  export default defineComponent({
38
71
  name: "HkTooltip",
39
72
  props: {
@@ -82,6 +115,25 @@ export default defineComponent({
82
115
  const popupRef = ref<HTMLElement | null>(null);
83
116
  let showTimer: ReturnType<typeof setTimeout> | null = null;
84
117
  let positionFrame: number | null = null;
118
+ let resizeObserver: ResizeObserver | null = null;
119
+ let signalsHooked = false;
120
+ let lastSampleAt = Number.NEGATIVE_INFINITY;
121
+ let quietSince = 0;
122
+ let lastTriggerRect: RectSnapshot | null = null;
123
+
124
+ /** Did the trigger move since the last placement? One gBCR read is the
125
+ * entire cost of a static frame now. */
126
+ function rectMoved(next: RectSnapshot): boolean {
127
+ const prev = lastTriggerRect;
128
+ return (
129
+ !prev ||
130
+ prev.left !== next.left ||
131
+ prev.top !== next.top ||
132
+ prev.width !== next.width ||
133
+ prev.height !== next.height
134
+ );
135
+ }
136
+
85
137
  // Click mode owns its own dismissal wiring: listeners exist only while
86
138
  // the popup is open, and the trigger focus is remembered so a dismissal
87
139
  // decision can hand focus back.
@@ -112,8 +164,12 @@ export default defineComponent({
112
164
  }
113
165
 
114
166
  function updatePosition() {
115
- if (!wrapperRef.value || !popupRef.value) return;
116
- const rect = wrapperRef.value.getBoundingClientRect();
167
+ const trigger = wrapperRef.value;
168
+ const popup = popupRef.value;
169
+ if (!trigger || !popup) return;
170
+ const rect = trigger.getBoundingClientRect();
171
+ lastTriggerRect = rectSnapshot(rect);
172
+ quietSince = nowMs();
117
173
  // Placement geometry lives in the shared runtime helper (it also
118
174
  // serves the document-level tooltip bridge) — including the
119
175
  // ancestor-zoom division that keeps teleported popups pinned to
@@ -121,28 +177,139 @@ export default defineComponent({
121
177
  // that keeps the measured bubble inside the viewport gutter (flip,
122
178
  // cap, shift) instead of spilling off-screen or shrinking to the
123
179
  // containing block's leftover space.
124
- applyTooltipPosition(popupRef.value, rect, props.placement, props.maxWidth, {
180
+ applyTooltipPosition(popup, rect, props.placement, props.maxWidth, {
125
181
  allowBandOverlap: props.allowBandOverlap,
126
182
  });
183
+ observeGeometry();
127
184
  }
128
185
 
129
186
  function stopPositionTracking() {
130
187
  if (positionFrame !== null) cancelAnimationFrame(positionFrame);
131
188
  positionFrame = null;
189
+ // A fresh show always places once, whatever the trigger did while
190
+ // the bubble was down.
191
+ lastTriggerRect = null;
192
+ }
193
+
194
+ /** One cheap sample: the trigger rect, and nothing else. */
195
+ function samplePosition() {
196
+ positionFrame = null;
197
+ if (!visible.value) return;
198
+ const now = nowMs();
199
+ // One sample per display frame at most: `requestAnimationFrame` is a
200
+ // ~60Hz clock in a browser, but not in accelerated environments
201
+ // (happy-dom drives it off setImmediate), and the geometry pass must
202
+ // never run more often than a paint could use it.
203
+ if (now - lastSampleAt < POSITION_FRAME_MIN_MS) {
204
+ ensureSampler();
205
+ return;
206
+ }
207
+ lastSampleAt = now;
208
+ const trigger = wrapperRef.value;
209
+ // Both nodes must exist before a sample means anything: the popup is
210
+ // rendered by the next flush after a show, so a missing node is
211
+ // "not placed yet", never "at rest" — the loop waits for it instead
212
+ // of retiring before the first placement.
213
+ if (trigger && popupRef.value) {
214
+ if (rectMoved(rectSnapshot(trigger.getBoundingClientRect()))) {
215
+ updatePosition();
216
+ } else if (now - quietSince >= POSITION_QUIET_MS) {
217
+ // Nothing has moved for a while: retire the loop. The next signal
218
+ // (scroll / resize / wheel / ResizeObserver) revives it, and a
219
+ // resting tooltip then costs exactly zero frames.
220
+ return;
221
+ }
222
+ }
223
+ ensureSampler();
132
224
  }
133
225
 
134
- function trackPositionWhileVisible() {
226
+ function ensureSampler() {
135
227
  if (positionFrame !== null) return;
136
- const tick = () => {
137
- positionFrame = null;
138
- if (!visible.value) return;
139
- // A visible trigger can move without a pointer event (treemap wheel
140
- // zoom, minimap pan, layout animation). Re-read its rect per frame
141
- // until hide/unmount; each visible tooltip owns one such loop.
142
- updatePosition();
143
- positionFrame = requestAnimationFrame(tick);
144
- };
145
- positionFrame = requestAnimationFrame(tick);
228
+ positionFrame = requestAnimationFrame(samplePosition);
229
+ }
230
+
231
+ /**
232
+ * Event-driven re-placement: the signal itself is the measurement
233
+ * trigger, so the bubble lands on the event's own turn instead of
234
+ * waiting for the next frame — pan/zoom/drag then track the trigger
235
+ * exactly, and stay free while nothing happens.
236
+ */
237
+ function nudgePositionTracking() {
238
+ if (!visible.value) return;
239
+ lastSampleAt = Number.NEGATIVE_INFINITY;
240
+ lastTriggerRect = null;
241
+ updatePosition();
242
+ ensureSampler();
243
+ }
244
+
245
+ function beginPositionTracking() {
246
+ hookPositionSignals();
247
+ lastTriggerRect = null;
248
+ lastSampleAt = Number.NEGATIVE_INFINITY;
249
+ quietSince = nowMs();
250
+ ensureSampler();
251
+ observeGeometry();
252
+ }
253
+
254
+ // ── geometry signals ─────────────────────────────────────────────
255
+ // A visible bubble follows three kinds of motion: container movement
256
+ // (scroll, any scroller — capture phase), viewport changes (resize),
257
+ // and canvas/camera motion (wheel), all of which move the trigger
258
+ // without an enter/leave. Size changes come from a ResizeObserver on
259
+ // the trigger and on the bubble itself (its own box reflows when the
260
+ // text lands). Whatever still slips through — an un-evented transform
261
+ // animation — is caught by the short sampler above, which is the only
262
+ // reason a frame loop still exists at all.
263
+ const observedNodes = new Set<Element>();
264
+
265
+ function observeGeometry() {
266
+ if (typeof ResizeObserver === "undefined") return;
267
+ const observer = ensureResizeObserver();
268
+ for (const node of [wrapperRef.value, popupRef.value]) {
269
+ if (!node || observedNodes.has(node)) continue;
270
+ observedNodes.add(node);
271
+ observer.observe(node);
272
+ }
273
+ }
274
+
275
+ function ensureResizeObserver(): ResizeObserver {
276
+ if (!resizeObserver) {
277
+ resizeObserver = new ResizeObserver(() => nudgePositionTracking());
278
+ }
279
+ return resizeObserver;
280
+ }
281
+
282
+ function hookPositionSignals() {
283
+ if (signalsHooked) return;
284
+ signalsHooked = true;
285
+ window.addEventListener("resize", nudgePositionTracking, { passive: true });
286
+ // Capture phase on purpose: the scroller that moves the trigger is
287
+ // usually an inner card / list / diff body, and a bubble-phase
288
+ // document listener would never see it.
289
+ document.addEventListener("scroll", nudgePositionTracking, { capture: true, passive: true });
290
+ // Wheel is the pan/zoom signal of every canvas surface (treemap,
291
+ // minimap, board) — those move an element with no scroll and no
292
+ // resize at all.
293
+ window.addEventListener("wheel", nudgePositionTracking, { passive: true, capture: true });
294
+ // A DRAG pan emits neither scroll nor wheel: it starts at a
295
+ // pointerdown, which nudges once and re-arms the sampler while the
296
+ // trigger keeps moving (each moving sample restarts the quiet
297
+ // window). A pause longer than POSITION_QUIET_MS mid-gesture retires
298
+ // the sampler; the next pointerdown/scroll/wheel re-arms it.
299
+ document.addEventListener("pointerdown", nudgePositionTracking, { capture: true, passive: true });
300
+ }
301
+
302
+ function unhookPositionSignals() {
303
+ if (signalsHooked) {
304
+ signalsHooked = false;
305
+ window.removeEventListener("resize", nudgePositionTracking);
306
+ document.removeEventListener("scroll", nudgePositionTracking, true);
307
+ window.removeEventListener("wheel", nudgePositionTracking, true);
308
+ document.removeEventListener("pointerdown", nudgePositionTracking, true);
309
+ }
310
+ resizeObserver?.disconnect();
311
+ resizeObserver = null;
312
+ observedNodes.clear();
146
313
  }
147
314
 
148
315
  function show() {
@@ -158,7 +325,7 @@ export default defineComponent({
158
325
  ensureEngaged();
159
326
  showTimer = setTimeout(() => {
160
327
  visible.value = true;
161
- trackPositionWhileVisible();
328
+ beginPositionTracking();
162
329
  }, props.delay);
163
330
  }
164
331
 
@@ -233,7 +400,7 @@ export default defineComponent({
233
400
  clearShowTimer();
234
401
  ensureEngaged();
235
402
  visible.value = true;
236
- trackPositionWhileVisible();
403
+ beginPositionTracking();
237
404
  // A keyboard activation must land on the actions rather than staying
238
405
  // on the trigger; remember the origin for the focus hand-back.
239
406
  const active = document.activeElement;
@@ -298,9 +465,22 @@ export default defineComponent({
298
465
  });
299
466
  }
300
467
 
468
+ // Anything that changes the geometry INPUTS while the bubble is up
469
+ // (placement, the width cap, the band exemption, the caption text that
470
+ // sizes the box) re-places on the spot — the retired frame loop used to
471
+ // pick these up for free, so they must be an explicit signal.
472
+ watch(
473
+ () => [props.placement, props.maxWidth, props.allowBandOverlap, props.text],
474
+ () => { nudgePositionTracking(); },
475
+ { flush: "post" },
476
+ );
477
+
301
478
  onBeforeUnmount(() => {
302
479
  clearShowTimer();
303
480
  stopPositionTracking();
481
+ // Observers and listeners outlive the bubble by design (re-shows must
482
+ // not churn them) but never the component.
483
+ unhookPositionSignals();
304
484
  cancelTouchHint();
305
485
  detachDismissal();
306
486
  if (popupHandle) {