diff --git a/.github/workflows/mermaid-feasibility.yml b/.github/workflows/mermaid-feasibility.yml index 0aff8a92..e9344dba 100644 --- a/.github/workflows/mermaid-feasibility.yml +++ b/.github/workflows/mermaid-feasibility.yml @@ -44,18 +44,27 @@ jobs: git diff --exit-code -- pnpm-lock.yaml - name: Install browser run: pnpm exec playwright install --with-deps "$THROUGHLINE_QA_BROWSER" + - name: Verify process-memory measurement helper + run: node --test scripts/mermaid-process-memory.test.mjs - name: Build and inventory proof dependency boundary run: | + git status --porcelain --untracked-files=all + test -z "$(git status --porcelain --untracked-files=all)" mkdir -p "$RUNNER_TEMP/mermaid-proof" pnpm build node scripts/audit-mermaid-proof.mjs "$RUNNER_TEMP/mermaid-proof/dependencies.json" - name: Measure independent packed feasibility host - run: node scripts/audit-mermaid-packed.mjs "$RUNNER_TEMP/mermaid-proof/packed.json" + run: | + git status --porcelain --untracked-files=all + test -z "$(git status --porcelain --untracked-files=all)" + node scripts/audit-mermaid-packed.mjs "$RUNNER_TEMP/mermaid-proof/packed.json" - name: Measure source workload and capture actual rendered screenshots if: ${{ !cancelled() }} shell: bash run: | set -euo pipefail + git status --porcelain --untracked-files=all + test -z "$(git status --porcelain --untracked-files=all)" mkdir -p "$RUNNER_TEMP/mermaid-proof" pnpm exec vite --host 127.0.0.1 --port 5174 > "$RUNNER_TEMP/mermaid-proof/vite.log" 2>&1 & server=$! @@ -66,11 +75,18 @@ jobs: done curl --fail --silent http://127.0.0.1:5174/scripts/mermaid-proof.html > /dev/null node scripts/measure-mermaid-proof.mjs "$THROUGHLINE_QA_BROWSER" "$RUNNER_TEMP/mermaid-proof" + # Vitest writes failure screenshots into the checkout. Run these tests + # after measurements so failed regressions cannot contaminate source evidence. + - name: Verify focused Mermaid browser feasibility + if: ${{ !cancelled() }} + run: pnpm test:browser:run src/react/__tests__/mermaid-proof src/react/__tests__/mermaid-player.browser.test.tsx - name: Retain actual evidence, including failures where available if: ${{ always() }} uses: actions/upload-artifact@v7 with: name: mermaid-feasibility-${{ matrix.browser }}-${{ github.run_id }} - path: ${{ runner.temp }}/mermaid-proof/ + path: | + ${{ runner.temp }}/mermaid-proof/ + src/react/__tests__/__screenshots__/ if-no-files-found: warn retention-days: 30 diff --git a/docs/mermaid-feasibility.md b/docs/mermaid-feasibility.md index 8d3fe59e..f2385f1f 100644 --- a/docs/mermaid-feasibility.md +++ b/docs/mermaid-feasibility.md @@ -136,3 +136,56 @@ Per-area recommendation (maintainer decision still required): The read-only Mermaid feasibility workflow captures browser-specific packed proof, workload measurements/screenshots and the dependency inventory as retained artifacts. Its browser suite is separate from final release acceptance. Browser heap snapshots are explicitly method-labeled (or unavailable); they do not establish peak process memory. Record subsequent exact commit, engine versions, actual timings, asset hashes/bytes and failure outcomes; never replace missing measurements with estimates. No human AT or native zoom was performed for this candidate. The display-reference and Graph state-strip design choices require explicit review. Graph/Sequence/collapse/source selection/performance/browser safety each remain unaccepted until reviewed against the evidence. Do not start production cutover or publication on this report alone. + +## Follow-up feasibility candidate — review and measurement required + +This branch adds a fixed host-owned Graph value slot per mapped node, painted from the same bounded value summary as the native player, without putting frame values into Mermaid syntax or triggering layout on writes. The state strip remains a textual equivalent. Graph/Sequence source controls are ordinary host-owned buttons derived directly from the descriptor and remain available during loading or failure; event-caption pointer/keyboard selection now binds directly to globally unique host-authored tokens on ordinary SVG text elements, not private CSS classes, route positions or generated IDs. Visual arrow paths and phase boxes are no longer semantic selection targets; their guarded pinned association is used only for optional presentation and motion. Participant visual binding remains version-specific, with independent host controls available. Global row-token uniqueness includes participant captions and rejects duplicated rendered references. Review the explicit interaction tradeoff (select a caption/reference or host control, not the bare arrow path or phase box), actual browser behavior and optional visual geometry before declaring MR-04/MR-10 accepted. The cache is trace-scoped; retries and stale request cancellation retain the existing abort boundary. + +The independent packed proof now includes the shared primitive/shape summary helper. Source and packed measurement scripts record Linux process-tree RSS samples (100 ms requested interval), baseline and sampled maximum. The measure includes the dedicated Node measurement runner and descendants, may double-count shared pages, and is not exact peak or browser-only unique memory. Do not compare across differing process trees or interpret unavailable measurements as zero. CI runs the focused browser suite on all three engines and retains reports. The package is still native; this is copied-adapter feasibility, not U29 production proof. + +| Requirement | Candidate change / required fresh evidence | Disposition | +| --- | --- | --- | +| MR-01–03 | Repeat pure/packed boundary, hierarchy and topology checks | Pending exact-head results | +| MR-04–06 | Global row references, independent source controls, repeated/orphan phases, windows and perturbations | Pending caption/host source-selection and optional geometry review | +| MR-07–08 | Native State unchanged; inline state slot and current focus/write cues, unchanged-topology seek, motion lifecycle | Pending three-engine parity and legibility review | +| MR-09–10 | Host-owned selection/fallback, hostile content, trace-scoped cache, retry and SSR | NO-GO pending exact results, participant visual binding/optional geometry review and required human evidence | +| MR-11 | Sampled process-tree RSS, asset/lock/inventory and workload reports | Pending actual measured results and notice review | +| MR-12 | Review all four references and failures with exact SHA | NO-GO until reviewed evidence | + +A synthetic SVG regression exercises token selection with deliberately unknown classes and reversed text-element order; real renderer perturbation, participant lookalike and missing graph-slot regressions remain required alongside the four canonical cases. Memory availability requires multiple observations and an observed descendant process. No measurements, screenshots, human AT or native zoom results are claimed for this candidate before its workflows execute. No production integration, package export change, release or ticket closure is authorized. A failure of the reserved state slot must fall back rather than silently omit modeled values. If the caption-based selection interaction, participant binding or optional geometry fails parity, retain native rendering and seek a reviewed disposition; do not equate independent source buttons with approved visual parity. + + +## Evidence review — 2026-11-26, tested source `5bfeebd1237efaa5a46fcb5ad2c87ede6a2f7720` + +The [full CI](https://github.com/0xbuffdev/throughline/actions/runs/45893817204), [Firefox/WebKit QA](https://github.com/0xbuffdev/throughline/actions/runs/45893817211) and [three-engine feasibility workflow](https://github.com/0xbuffdev/throughline/actions/runs/45893817198) passed. Full suites: 454 unit/compiler tests; 201 browser tests per engine; 55 focused feasibility tests per engine; two process-memory helper tests per engine. Native public package consumer/security/quality checks and proposed merge result passed. This is evidence for the named SHA, not for subsequent changes or the production Mermaid renderer. + +All three downloaded artifact archives were examined, including measurements, packed reports, lock and inventory JSON, and rendered Graph/Sequence/mobile screenshots. Source, packed and dependency reports identify the same clean, unchanged SHA and input fingerprint `7ff61a7509b2b9dbe79e262870cc23d41f9ce2b2da08cf314e52ee339527cadb`. Independent consumer lock SHA-256 `c2f8c1d170db51c4b0ccf342ed49352084e61cdacd5eb81ee591688d5c4f24d9` and per-engine inventory hashes were independently recomputed from the retained JSON. All three archives report identical native tarball SHA-256 `6f7a96a2cf72c7e40f8ce282fb7eb7e674e63858b5a5d4329f68b010b083770a`; the tarball itself is not in those ZIPs and its hash was not independently recomputed. No nonlocal requests or page errors. Packed tests selected all four reference entities by pointer, keyboard and independent list, compared exact source IDs/cells/inline summaries to the installed native core, and selected Sequence event captions by pointer and keyboard. Packed host document widths matched viewport at 260/320/375/720 px; graph scroll surface was 575 px wide in the narrow checkout measurement with 12 px node font. + +| Browser / artifact | 8/12 native geometry / candidate render ms | 64/160 native / candidate ms | 200/1000 native / candidate ms | 10k phases projection / 40-phase render ms | Source / packed sampled max RSS (MiB) | +| --- | --- | --- | --- | --- | --- | +| [Chromium](https://github.com/0xbuffdev/throughline/actions/runs/45893817198/artifacts/15152143619) | 0.4 / 57.7, 53.6, 52.4 | 2.9 / 455.1, 427.0, 405.4 | 17.8 / 6088.6 | 60 / 55.1 | 980.2 / 1346.7 | +| [Firefox](https://github.com/0xbuffdev/throughline/actions/runs/45893817198/artifacts/15152024100) | 0 / 83, 67, 67 | 8 / 587, 540, 531 | 45 / 9120 | 90 / 115 | 1486.2 / 1769.1 | +| [WebKit](https://github.com/0xbuffdev/throughline/actions/runs/45893817198/artifacts/15153300770) | 1 / 100, 70, 71 | 4 / 545, 473, 474 | 32 / 5708 | 82 / 103 | 1178.2 / 1448.2 | + +Native geometry timings and Mermaid render timings measure different operations; zero denotes timer resolution. All graph nodes/edges mapped; the large graph bypasses the preview cap and produces a 2.64–2.72 MB SVG with width about 31,275–31,287 units. Even the 64/160 graph is about 9,990–9,994 units wide. Do not claim interactive parity at these extremes. Source measurements sampled 101/148/105 times, packed 51/73/121 (Chromium/Firefox/WebKit). The aggregate RSS includes the Node runner, browser descendants and potentially shared pages counted repeatedly. Packed baseline includes the prior build and is not directly comparable with the source runner. No unique or instantaneous peak-memory claim. All engines reported 89 built assets totaling 5,825,337 bytes (1,696,561 gzip bytes); initial Graph host requests 2,933,913 bytes (878,957 gzip bytes); additional Sequence requests 117,959 bytes (31,282 gzip bytes). These are full copied-adapter host costs, not Mermaid-only or production release costs. + +The source audit found 115 reachable packages and no missing license texts; the independent npm host resolved 202 installed packages with the same lock across engines. The latter includes DOMPurify 3.5.0 (MPL-2.0 OR Apache-2.0), elkjs 0.12.2 (EPL-2.0 OR GPL-3.0-or-later), and Khroma 2.1.0 (manifest UNDECLARED, license file present). The source inventory differs from independently resolved consumer versions. Production notice and source-availability review remains necessary; native runtime MIT-only audit is not approval of this tree. + +**Negative visual finding from actual screenshots:** while the one-shot Sequence cue is moving, its duplicate text caption overlaps the fixed source-reference caption on desktop and mobile in all three engines. Source identity is technically correct but legibility and access to the authoritative caption during motion are not assured. The follow-up removes the duplicate moving Sequence text, retains the one-shot directional cue and keeps the exact fixed selectable caption visible. Graph motion retains its label. The regression now asserts that the only moving Sequence element is the directional cue, tied to the same source as the stationary visible caption, and no receipt-only cue is generated. Fresh three-engine tests/screenshots are required after this correction; this section records the previous exact-head evidence, not their result. + +| Requirement | Review disposition for feasibility | +| --- | --- | +| MR-01 | GO for isolated proof: pure/public native package boundary intact; no production adoption | +| MR-02 | GO for tested syntax and mapped Graph sources across four references and negative cases | +| MR-03 | GO for current-presence/collapse projection; union reuse rejected; native group/camera integration still U27 | +| MR-04 | GO for exact host controls and explicit event-caption tokens; NO-GO for claiming private-independent bare-mark/participant geometry parity; approve caption-selection interaction explicitly | +| MR-05 | GO for recorded phases and honest arrows/notes, including repeats/orphans; caption legibility correction needs fresh evidence | +| MR-06 | GO for bounded 40-phase diagram and complete evidence navigation | +| MR-07 | GO for native State and bounded inline Graph summary/focus/write implementation at tested frames | +| MR-08 | Automated clock/seek/reduced-motion behavior passed; visual overlap found, corrected subsequently, new evidence pending | +| MR-09 | GO for tested hostile/offline trust boundary, not arbitrary untrusted SVG | +| MR-10 | Automated browser/SSR/packed proof passed; human AT/zoom, participant mapping review and production integration still outstanding | +| MR-11 | GO for collected measurements; NO-GO for unbounded Graph or production performance/notice approval. Review bounded fallback and default display budget, not merely finite geometry. | +| MR-12 | Overall NO-GO for production cutover pending visual correction verification, review of interaction/limits/notices and applicable human evidence. | + +**Per-area decision:** Graph/collapse: GO for bounded feasibility experiments, not production. Sequence: conditional on the corrected caption and explicit interaction approval. Exact source ID/selection: GO for host controls and event captions on tested inputs; remaining private participant/geometry association is presentation-specific and must not become essential. Performance: NO-GO for unbounded rendering, review the 64/160 preview limit before integration. Browser safety: GO for tested automated/offline proof; human AT/native zoom not performed. No package publication, public exports, U27 start, or U29 acceptance is implied. Maintainer must approve the explicit go/no-go and tradeoffs; final exact-candidate TL-U18 AT/zoom remains separate. diff --git a/scripts/audit-mermaid-packed.mjs b/scripts/audit-mermaid-packed.mjs index a544cb8a..3eb36c32 100644 --- a/scripts/audit-mermaid-packed.mjs +++ b/scripts/audit-mermaid-packed.mjs @@ -9,6 +9,7 @@ import { createHash } from "node:crypto"; import { chromium, firefox, webkit } from "@playwright/test"; import { build, preview } from "vite"; import { captureSource, sameSource } from "./mermaid-source-identity.mjs"; +import { sampleProcessMemory } from "./mermaid-process-memory.mjs"; const root = dirname(dirname(fileURLToPath(import.meta.url))); const before = captureSource(root); @@ -17,7 +18,7 @@ const browserType = { chromium, firefox, webkit }[engine]; assert(browserType, "Unsupported packed proof browser"); const scratch = mkdtempSync(join(tmpdir(), "throughline-mermaid-packed-")); const output = resolve(process.argv[2] ?? join(tmpdir(), "throughline-mermaid-packed-report.json")); -let browser, server; +let browser, server, memory; const sha256 = bytes => createHash("sha256").update(bytes).digest("hex"); function run(command, args, cwd) { const result = spawnSync(command, args, { cwd, encoding: "utf8", maxBuffer: 8 * 1024 * 1024 }); @@ -86,14 +87,15 @@ try { mkdirSync(join(consumer, "proof")); // Copy the actual test host/adapter, changing import boundaries only. Runtime // model, query, examples and player imports resolve to the installed tarball. - for (const name of ["adapter.ts", "diagram.tsx", "render.ts", "motion.ts", "evidence.tsx", "sequence-layout.ts"]) { - const directory = name === "sequence-layout.ts" ? "src/v2" + for (const name of ["adapter.ts", "diagram.tsx", "render.ts", "motion.ts", "evidence.tsx", "sequence-layout.ts", "value-summary.ts"]) { + const directory = ["sequence-layout.ts", "value-summary.ts"].includes(name) ? "src/v2" : name.endsWith(".tsx") ? "src/react/__tests__/mermaid-proof" : "src/react/mermaid"; const original = readFileSync(join(root, directory, name), "utf8"); const copied = original.replace(/"\.\.\/(?:\.\.\/)+v2\/model\.js"/g, '"@0xbuff/throughline"') .replaceAll('"../../mermaid/', '"./'); writeFileSync(join(consumer, "proof", name), copied .replace('"../../v2/sequence-layout.js"', '"./sequence-layout.js"') + .replace('"../../v2/value-summary.js"', '"./value-summary.js"') .replace('"./model.js"', '"@0xbuff/throughline"')); } let host = readFileSync(join(root, "scripts/mermaid-proof.tsx"), "utf8"); @@ -121,6 +123,7 @@ try { build: { outDir: "dist" }, preview: { host: "127.0.0.1", port: 0, strictPort: false } }); const base = "http://127.0.0.1:" + server.httpServer.address().port; const executablePath = engine === "webkit" ? process.env.THROUGHLINE_QA_WEBKIT_EXECUTABLE : undefined; + memory = sampleProcessMemory(); browser = await browserType.launch(executablePath ? { executablePath } : {}); const page = await browser.newPage({ viewport: { width: 375, height: 812 }, reducedMotion: "reduce" }); const errors = [], nonLocal = [], requested = new Set(); @@ -151,6 +154,18 @@ try { assert.equal(await diagram.locator("[data-thl-motion-item]").count(), 1); assert.notEqual(await diagram.locator("[data-thl-motion-item]").evaluate(node => getComputedStyle(node).stroke), "none", "Packed sequence arrow has no painted stroke"); + const caption = diagram.locator("[data-thl-source-reference][role=button]"); + assert.equal(await caption.count(), 1, "Packed sequence has no unique source reference"); + await caption.click(); + const selectedSource = page.getByRole("region", { name: "Selected exact source" }); + await selectedSource.waitFor(); + assert.deepEqual(JSON.parse(await selectedSource.locator("[data-proof-source]").textContent()).eventIds, ["requestSent"]); + await selectedSource.getByRole("button", { name: "Clear selection" }).click(); + await caption.focus(); + await page.keyboard.press("Enter"); + await selectedSource.waitFor(); + assert.deepEqual(JSON.parse(await selectedSource.locator("[data-proof-source]").textContent()).eventIds, ["requestSent"]); + await selectedSource.getByRole("button", { name: "Clear selection" }).click(); await page.getByText("Complete evidence at selected frame", { exact: true }).click(); await page.getByRole("button", { name: "requestSent", exact: true }).click(); assert((await page.getByRole("region", { name: "Selected exact source" }).textContent()).includes("requestSent")); @@ -219,6 +234,25 @@ try { }; const mark = diagram.locator('[data-thl-item-id="' + expected.itemId + '"][role="button"]'); assert.equal(await mark.count(), 1, "Missing or duplicate rendered entity"); + // Compare the inline slot against the installed core's independently + // queried cell, using the native summary contract rather than SVG text. + const cell = expected.cells[0].cell; + let expectedSummary; + if (cell.status === "unknown") expectedSummary = "Unknown"; + else if (cell.status === "absent") expectedSummary = "Absent"; + else { + const value = cell.value; + if (Array.isArray(value)) expectedSummary = value.length + (value.length === 1 ? " item" : " items"); + else if (value !== null && typeof value === "object") { + const count = Object.keys(value).length; + expectedSummary = count + (count === 1 ? " field" : " fields"); + } else { + const bounded = typeof value === "string" && value.length > 46 ? value.slice(0, 45).replace(/[\uD800-\uDBFF]$/, "") + "…" : value; + const text = JSON.stringify(bounded); + expectedSummary = text.length > 48 ? text.slice(0, 47) + "…" : text; + } + } + assert.equal(await mark.locator("[data-thl-state-label]").textContent(), expectedSummary, "Inline Graph value differs from installed core"); await clear(); await mark.click(); await verify(); await clear(); await mark.focus(); assert(await mark.evaluate(node => document.activeElement === node), "SVG mark did not receive keyboard focus"); @@ -246,20 +280,22 @@ try { noMessageFallback = { diagnostic: expected.diagnostics, eventCount: expected.eventSources.length }; } referenceResults.push({ exampleIndex: Number(value), id: expected.id, title, initialNodes, - expectedSource: expected.source, expectedCells: expected.cells, svgPointer: true, svgKeyboard: true, list: true, noMessageFallback }); + expectedSource: expected.source, expectedCells: expected.cells, inlineState: expectedSummary, svgPointer: true, svgKeyboard: true, list: true, noMessageFallback }); } assert.deepEqual(errors, []); assert.deepEqual(nonLocal, []); const after = captureSource(root); const report = { sourceSha: before.sourceSha, dirty: Boolean(before.status), sourceStable: sameSource(before, after), inputFingerprint: before.fingerprint, mermaid: "12.3.0", engine, browser: browser.version(), - referenceResults, responsive, dependencyEvidence, + referenceResults, sequenceCaptionPointer: true, sequenceCaptionKeyboard: true, responsive, dependencyEvidence, archiveSha256: createHash("sha256").update(readFileSync(tarball)).digest("hex"), initialAssets, sequenceAssets, - assets, errors, nonLocal, packedCore: true, proofHostBuild: true, candidateBrowser: true, productionMermaid: false }; + processMemory: memory.stop(), assets, errors, nonLocal, packedCore: true, proofHostBuild: true, candidateBrowser: true, productionMermaid: false }; writeFileSync(output, JSON.stringify(report, null, 2) + "\n"); assert(report.sourceStable, "Source changed during packed-candidate verification"); console.log("Packed native package + copied Mermaid feasibility adapter passed; NOT a production Mermaid cutover: " + output); + console.log("TL_U26_PACKED_PROCESS_MEMORY " + JSON.stringify(report.processMemory)); } finally { + memory?.stop(); await browser?.close(); if (server) await new Promise(resolve => server.httpServer.close(resolve)); rmSync(scratch, { recursive: true, force: true }); diff --git a/scripts/measure-mermaid-proof.mjs b/scripts/measure-mermaid-proof.mjs index c2ebd266..14c6562b 100644 --- a/scripts/measure-mermaid-proof.mjs +++ b/scripts/measure-mermaid-proof.mjs @@ -3,6 +3,7 @@ import { mkdirSync, writeFileSync } from "node:fs"; import { resolve, join } from "node:path"; import { cpus, platform, release } from "node:os"; import { captureSource, sameSource } from "./mermaid-source-identity.mjs"; +import { sampleProcessMemory } from "./mermaid-process-memory.mjs"; const before = captureSource(); @@ -13,6 +14,7 @@ const base = process.env.THROUGHLINE_PROOF_URL ?? "http://127.0.0.1:5174"; const output = resolve(process.argv[3] ?? "/tmp/throughline-mermaid-proof-" + engine); mkdirSync(output, { recursive: true }); const customLauncher = engine === "webkit" ? process.env.THROUGHLINE_QA_WEBKIT_EXECUTABLE : undefined; +const memory = sampleProcessMemory(); const browser = await type.launch({ headless: true, ...(customLauncher ? { executablePath: customLauncher } : {}) }); try { const page = await browser.newPage({ viewport: { width: 960, height: 900 } }); @@ -112,9 +114,9 @@ try { const report = { sourceSha: before.sourceSha, dirty: Boolean(before.status), sourceStable, inputFingerprint: before.fingerprint, after, mermaid: "12.3.0", engine, browserVersion: browser.version(), customLauncher: Boolean(customLauncher), platform: platform(), release: release(), - cpu: cpus()[0]?.model, network, errors, ...findings }; + cpu: cpus()[0]?.model, network, errors, processMemory: memory.stop(), ...findings }; writeFileSync(join(output, "measurements.json"), JSON.stringify(report, null, 2) + "\n"); console.log(JSON.stringify({ output, sourceSha: report.sourceSha, dirty: report.dirty, - graphs: report.graphs, sequence: report.sequence, network, errors }, null, 2)); + graphs: report.graphs, sequence: report.sequence, processMemory: report.processMemory, network, errors }, null, 2)); if (errors.length || network.length || !sourceStable) process.exitCode = 1; -} finally { await browser.close(); } +} finally { memory.stop(); await browser.close(); } diff --git a/scripts/mermaid-process-memory.mjs b/scripts/mermaid-process-memory.mjs new file mode 100644 index 00000000..03e6e39a --- /dev/null +++ b/scripts/mermaid-process-memory.mjs @@ -0,0 +1,45 @@ +import { execFileSync } from "node:child_process"; +import { platform } from "node:os"; + +/** Sum RSS of this dedicated measurement process and its descendants. + * Shared pages can be counted more than once. Sampled maximum is a lower + * bound on peak sampled RSS, not unique memory or instantaneous peak. + */ +export function processTreeRss(snapshot, root) { + const rows = snapshot.trim().split(/\n/).map(line => line.trim().split(/\s+/)) + .filter(parts => parts.length >= 4).map(([pid, ppid, rss, comm]) => ({ pid: Number(pid), ppid: Number(ppid), rss: Number(rss), comm })); + const visited = new Set([root]); + let changed = true; + while (changed) { + changed = false; + for (const row of rows) if (visited.has(row.ppid) && !visited.has(row.pid)) { visited.add(row.pid); changed = true; } + } + const selected = rows.filter(row => visited.has(row.pid) && row.comm !== "ps" && Number.isFinite(row.rss)); + if (!selected.some(row => row.pid === root)) throw new Error("Measurement root not present"); + return { rssBytes: selected.reduce((sum, row) => sum + row.rss * 1024, 0), processes: selected.length }; +} + +export function sampleProcessMemory() { + const intervalMs = 100; + const method = "Linux ps RSS sum of dedicated Node measurement process and descendants; shared pages may be counted twice; sampled max, not exact peak or unique memory"; + let samples = 0, baseline, max, failure, finished, timer, largestTree = 0; + function sample() { + try { + const value = processTreeRss(execFileSync("ps", ["-eo", "pid=,ppid=,rss=,comm="], { encoding: "utf8" }), process.pid); + baseline ??= value; + largestTree = Math.max(largestTree, value.processes); + if (!max || value.rssBytes > max.rssBytes) max = value; + samples++; + } catch (error) { failure = String(error); } + } + if (platform() === "linux") { sample(); timer = setInterval(sample, intervalMs); timer.unref(); } + return { stop() { + if (finished) return finished; + clearInterval(timer); + if (platform() === "linux") sample(); + finished = { method, intervalMs, samples, baseline: baseline ?? null, max: max ?? null, + largestTree, available: samples >= 2 && largestTree > 1 && !failure, ...(failure ? { failure } : {}), + ...(platform() !== "linux" ? { reason: "NOT PERFORMED — Linux ps sampler only" } : {}) }; + return finished; + } }; +} diff --git a/scripts/mermaid-process-memory.test.mjs b/scripts/mermaid-process-memory.test.mjs new file mode 100644 index 00000000..fa898882 --- /dev/null +++ b/scripts/mermaid-process-memory.test.mjs @@ -0,0 +1,12 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { processTreeRss, sampleProcessMemory } from "./mermaid-process-memory.mjs"; +test("sums only the measurement process tree and excludes the sampler", () => { + assert.deepEqual(processTreeRss("1 0 10 init\n10 1 20 node\n11 10 30 browser\n12 11 40 renderer\n13 10 5 ps\n20 1 1000 unrelated", 10), { rssBytes: 90 * 1024, processes: 3 }); + assert.throws(() => processTreeRss("1 0 10 init", 10), /root not present/); +}); +test("stopping twice returns the same report", () => { + const monitor = sampleProcessMemory(), report = monitor.stop(); + assert.equal(monitor.stop(), report); + assert.equal(typeof report.available, "boolean"); +}); diff --git a/src/react/__tests__/mermaid-player.browser.test.tsx b/src/react/__tests__/mermaid-player.browser.test.tsx index b15cbf98..57724630 100644 --- a/src/react/__tests__/mermaid-player.browser.test.tsx +++ b/src/react/__tests__/mermaid-player.browser.test.tsx @@ -39,13 +39,21 @@ it("keeps three Sequence lanes fixed through a send, receipt and explicit reply" const cues = new Set(); const observer = new MutationObserver(records => { for (const record of records) for (const node of record.addedNodes) { - if (node instanceof Element && node.matches("[data-thl-transfer]")) - cues.add(node.querySelector("text")?.textContent ?? ""); + if (node instanceof Element && node.matches("[data-thl-transfer]")) { + const id = node.getAttribute("data-thl-transfer"); + const caption = diagram.element().querySelector('[data-thl-source-reference][data-thl-item-id="' + id + '"]'); + const labels = [...diagram.element().querySelectorAll('[data-thl-motion-label="' + id + '"]')]; + if (caption && labels.includes(caption) && labels.every(label => + !label.hasAttribute("data-thl-label-in-motion") && getComputedStyle(label).visibility === "visible") && + !node.querySelector("text") && node.querySelectorAll("animateMotion").length === 1 && + caption.getAttribute("role") === "button") + cues.add(labels.map(label => label.textContent).join("").replace(/\s/g, "")); + } } }); observer.observe(screen.getByRole("tabpanel").element(), { childList: true, subtree: true }); await screen.getByRole("button", { name: "Step forward" }).click(); - await expect.poll(() => cues.has("Checkout request")).toBe(true); + await expect.poll(() => [...cues].some(caption => caption.includes("Checkoutrequest"))).toBe(true); expect(lanes()).toEqual(initial); const route = diagram.element().querySelector(".messageLine0"); expect(route?.getAttribute("data-from")).toBe("thl_node_0"); @@ -71,7 +79,7 @@ it("keeps three Sequence lanes fixed through a send, receipt and explicit reply" await next.click(); await expect.poll(() => diagram.element().querySelector("[data-thl-source], [data-thl-destination]")).toBeNull(); await next.click(); - await expect.poll(() => cues.has("Checkout reply")).toBe(true); + await expect.poll(() => [...cues].some(caption => caption.includes("Checkoutreply"))).toBe(true); observer.disconnect(); const reply = diagram.element().querySelector(".messageLine0[data-thl-active]")!; expect(reply.getAttribute("data-from")).toBe("thl_node_1"); @@ -125,12 +133,13 @@ it("updates Graph transfer paint without relayout and opens the exact source in expect(screen.container.querySelector(".thl-v2-inspect")).toBeNull(); }, 60_000); -it("inspects the exact message when selecting a drawn sequence arrow, including when seeking backwards", async () => { +it("inspects the exact message from its explicit sequence row reference, including when seeking backwards", async () => { const trace = compileArtifact(retryCheckout()); const screen = await render(); await screen.getByRole("button", { name: "Step forward" }).click(); const arrow = screen.getByRole("button", { name: /^Inspect transfer / }); await expect.element(arrow).toBeVisible(); + expect(arrow.element().hasAttribute("data-thl-source-reference")).toBe(true); (arrow.element() as SVGElement).focus(); await userEvent.keyboard("{Enter}"); const panel = screen.getByRole("complementary", { name: "Workflow inspector" }); @@ -326,7 +335,7 @@ it("follows the latest recorded Sequence event vertically and resets on rewind", await userEvent.keyboard("{End}"); await expect.poll(() => { const header = scroller.querySelector("[data-thl-sequence-header]")?.getBoundingClientRect(); - const current = scroller.querySelector('[aria-label="Inspect received · noticeReceived"][data-thl-active]'); + const current = scroller.querySelector('[data-thl-phase-item][data-thl-active]'); const mark = current?.getBoundingClientRect(); const viewport = scroller.getBoundingClientRect(); return Boolean(scroller.scrollTop > 0 && header && mark && @@ -413,10 +422,13 @@ it.each(EXAMPLES.map(example => example.id))("exposes frame-linked graph state f const source = EXAMPLES.find(example => example.id === id)!.artifact; source.steps[0].focusEntityIds = [source.entities[0].id]; const trace = compileArtifact(source); - const screen = await render(); + let renders = 0; + const Renderer = createMermaidPlayerDiagram((proof, signal) => { renders++; return renderProof(proof, signal); }); + const screen = await render(); const strip = screen.getByRole("region", { name: "Graph modeled state" }); await expect.element(strip).toBeVisible(); expect(strip.element().querySelectorAll("[data-graph-state-item]").length).toBeGreaterThan(0); + const initialRenderCount = renders; await screen.getByRole("button", { name: "Step forward" }).click(); const diagram = screen.getByRole("group", { name: "Source-linked graph at current frame" }); await expect.element(diagram).toBeVisible(); @@ -424,11 +436,15 @@ it.each(EXAMPLES.map(example => example.id))("exposes frame-linked graph state f const view = (await import("../../v2/views.js")).projectView(inspector, { kind: "graph", frameIndex: 1 }); const { property } = await import("../mermaid/adapter.js"); const { summarizeCell } = await import("../value-display.js"); + const before = (await import("../mermaid/adapter.js")).graphProof(trace, (await import("../../v2/views.js")).projectView(inspector, { kind: "graph", frameIndex: 0 })); + const after = (await import("../mermaid/adapter.js")).graphProof(trace, view); + if (before.source === after.source) expect(renders).toBe(initialRenderCount); for (const item of view.items.filter(item => item.role === "entity")) { const card = strip.element().querySelector('[data-graph-state-item="' + item.id + '"]'); expect(card?.textContent).toContain(summarizeCell(property(item, "cell") as import("../../v2/model.js").Cell)); expect(card?.textContent).toContain("Present"); const node = diagram.element().querySelector('[data-thl-item-id="' + item.id + '"]'); + expect(node?.querySelector("[data-thl-state-label]")?.textContent).toBe(summarizeCell(property(item, "cell") as import("../../v2/model.js").ReadonlyCell)); expect(node?.hasAttribute("data-thl-written")).toBe(property(item, "changed") === true); expect(node?.hasAttribute("data-thl-focused")).toBe(property(item, "focused") === true); } @@ -449,3 +465,26 @@ it("offers independent exact sequence source controls for identical sends", asyn await expect.element(inspector).toBeVisible(); expect(inspector.element().querySelector(".inspect-summary")?.getAttribute("data-source-event-ids")).toBe("secondSent"); }, 60_000); + + +it.each([260, 375, 720])("keeps independent exact source selection available when sequence rendering rejects at %ipx", async width => { + const trace = compileArtifact(stateEvidenceFixture()); + const Renderer = createMermaidPlayerDiagram(async () => { throw new Error("simulated failure"); }); + const screen = await render(
); + await screen.getByRole("button", { name: "Step forward" }).click(); + await expect.element(screen.getByRole("button", { name: "Retry diagram" })).toBeVisible(); + const disclosure = screen.getByText("Sequence source references", { exact: true }); + const table = screen.getByRole("region", { name: "State and event table" }); + await expect.element(table).toBeVisible(); + expect(disclosure.element().getBoundingClientRect().bottom).toBeLessThanOrEqual(table.element().getBoundingClientRect().top + 1); + await disclosure.click(); + const list = screen.getByRole("list", { name: "Visible sequence source references" }); + const details = disclosure.element().parentElement!; + expect(details.getBoundingClientRect().bottom).toBeLessThanOrEqual(table.element().getBoundingClientRect().top + 1); + const source = list.element().querySelector('[data-source-event-ids="secondSent"]'); + expect(source).not.toBeNull(); + await userEvent.click(source!); + const inspector = screen.getByRole("complementary", { name: "Workflow inspector" }); + await expect.element(inspector).toBeVisible(); + expect(inspector.element().querySelector(".inspect-summary")?.getAttribute("data-source-event-ids")).toBe("secondSent"); +}, 60_000); diff --git a/src/react/__tests__/mermaid-proof/adapter.test.ts b/src/react/__tests__/mermaid-proof/adapter.test.ts index 38f1fc17..bc58c5c4 100644 --- a/src/react/__tests__/mermaid-proof/adapter.test.ts +++ b/src/react/__tests__/mermaid-proof/adapter.test.ts @@ -91,3 +91,14 @@ describe("TL-U26 pure source-to-Mermaid proof", () => { expect(escaped).toContain("#60;"); }); }); + + +it("reserves stable graph state slots without embedding dynamic values in syntax", () => { + const trace = compileArtifact(EXAMPLES.find(example => example.id === "factorial")!.artifact); + const inspector = inspectTrace(trace); + const first = graphProof(trace, projectView(inspector, { kind: "graph", frameIndex: 0 })); + const next = graphProof(trace, projectView(inspector, { kind: "graph", frameIndex: 1 })); + expect(first.source).toBe(next.source); + expect(first.elements.filter(entry => entry.role === "entity").every(entry => entry.stateSlot && entry.stateText !== undefined)).toBe(true); + expect(next.elements.filter(entry => entry.role === "entity").some(entry => entry.written)).toBe(true); +}); diff --git a/src/react/__tests__/mermaid-proof/diagram.tsx b/src/react/__tests__/mermaid-proof/diagram.tsx index 517a2412..9c23df57 100644 --- a/src/react/__tests__/mermaid-proof/diagram.tsx +++ b/src/react/__tests__/mermaid-proof/diagram.tsx @@ -1,7 +1,7 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useLayoutEffect, useRef, useState } from "react"; import type { DiagramProof, ProofElement } from "../../mermaid/adapter.js"; import { renderProof } from "../../mermaid/render.js"; -import { animateTransfers } from "../../mermaid/motion.js"; +import { animateTransfers, paintGraphState } from "../../mermaid/motion.js"; /** Test-only lifecycle proof. The host retains frame and semantic selection. */ export function ProofDiagram({ proof, onSelect, renderer = renderProof, motion }: { @@ -38,6 +38,7 @@ export function ProofDiagram({ proof, onSelect, renderer = renderProof, motion } return () => { active = false; controller.abort(); }; }, [proof.source, renderer, oversized]); const current = output?.source === proof.source ? output : undefined; + useLayoutEffect(() => { if (diagram.current && current?.svg) paintGraphState(diagram.current, proof); }, [current?.svg, proof]); useEffect(() => { if (!motion) return; if (!instruction.current || instruction.current.revision !== motion.revision) diff --git a/src/react/__tests__/mermaid-proof/motion.browser.test.tsx b/src/react/__tests__/mermaid-proof/motion.browser.test.tsx index 2467aba1..f4c4b6f2 100644 --- a/src/react/__tests__/mermaid-proof/motion.browser.test.tsx +++ b/src/react/__tests__/mermaid-proof/motion.browser.test.tsx @@ -41,14 +41,36 @@ it("moves a directional graph arrow and its label along the modeled route, then cancel(); expect(host.querySelectorAll("[data-thl-transfer], animateMotion")).toHaveLength(0); }, 60_000); -it("animates explicit Sequence sends with labels, and never turns receipt-only evidence into motion", async () => { +it("animates only explicit Sequence sends while keeping the exact selectable caption stationary", async () => { const trace = compileArtifact(retryCheckout()), inspector = inspectTrace(trace); for (const frameIndex of [1, 2]) { const proof = sequenceProof(trace, projectView(inspector, { kind: "sequence", frameIndex })); const host = mount((await renderProof(proof)).svg); const cancel = animateTransfers(host, proof, 600, true, false); expect(host.querySelectorAll("[data-thl-transfer]")).toHaveLength(frameIndex === 1 ? 1 : 0); - if (frameIndex === 1) expect(host.querySelector("[data-thl-transfer] text")?.textContent).toBe("Checkout request"); + if (frameIndex === 1) { + const entry = proof.elements.find(item => item.role === "event" && item.sent && item.current)!; + const caption = host.querySelector('[data-thl-source-reference="' + entry.rowToken + '"]')!; + const cue = host.querySelector("[data-thl-transfer]")!; + expect(cue.getAttribute("data-thl-transfer")).toBe(entry.itemId); + expect(cue.querySelectorAll("animateMotion")).toHaveLength(1); + expect(cue.querySelector("text")).toBeNull(); + // Mermaid wraps a caption into sibling text nodes; the allocated token + // alone is the independent selection anchor, not the whole caption. + const labels = [...host.querySelectorAll('[data-thl-motion-label="' + entry.itemId + '"]')]; + expect(labels).toContain(caption); + expect(labels.map(label => label.textContent).join("").replace(/\s/g, "")).toContain("Checkoutrequest"); + expect(caption.textContent?.trimEnd()).toMatch(new RegExp(entry.rowToken + "$")); + expect(caption.getAttribute("aria-label")).toBe("Inspect transfer Checkout request"); + for (const label of labels) { + expect(label.hasAttribute("data-thl-label-in-motion")).toBe(false); + expect(getComputedStyle(label).visibility).toBe("visible"); + } + expect(caption.getAttribute("data-thl-item-id")).toBe(entry.itemId); + expect(caption.hasAttribute("data-thl-label-in-motion")).toBe(false); + expect(caption.getAttribute("role")).toBe("button"); + expect(getComputedStyle(caption).visibility).toBe("visible"); + } cancel(); } }, 60_000); diff --git a/src/react/__tests__/mermaid-proof/render.browser.test.tsx b/src/react/__tests__/mermaid-proof/render.browser.test.tsx index 7a472660..fcea108d 100644 --- a/src/react/__tests__/mermaid-proof/render.browser.test.tsx +++ b/src/react/__tests__/mermaid-proof/render.browser.test.tsx @@ -6,7 +6,7 @@ import { EXAMPLES } from "../../../examples.js"; import { distributedGraph } from "../../../__tests__/v2-graph-fixture.js"; import { retryCheckout } from "../../../__tests__/v2-sequence-fixture.js"; import { graphProof, sequenceProof, type DiagramProof } from "../../mermaid/adapter.js"; -import { renderProof, retryableLoader } from "../../mermaid/render.js"; +import { bindSequenceSourceReferences, renderProof, retryableLoader } from "../../mermaid/render.js"; const hosts: HTMLDivElement[] = []; afterEach(() => { for (const host of hosts.splice(0)) host.remove(); }); @@ -229,3 +229,52 @@ it("keeps authored reference-shaped labels and message IDs distinct from trusted await expect(renderProof(proof, undefined, svg => svg.replaceAll(tokens[0], tokens[0] + " " + tokens[0]))).rejects.toThrow(); } }, 60_000); + + +it("binds row selection by host tokens without generated classes, IDs, positions or order", () => { + const artifact = retryCheckout(); + const trace = compileArtifact(artifact); + const proof = sequenceProof(trace, projectView(inspectTrace(trace), { kind: "sequence", frameIndex: 2 })); + const events = proof.elements.filter(entry => entry.role === "event"); + expect(events.length).toBeGreaterThan(1); + const root = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + for (const entry of [...events].reverse()) { + const text = document.createElementNS(root.namespaceURI!, "text"); + text.setAttribute("class", "unknown-renderer-class"); + text.textContent = "arbitrary caption " + entry.rowToken; + root.append(text); + } + bindSequenceSourceReferences(root, proof); + for (const entry of events) { + const caption = root.querySelector('[data-thl-source-reference="' + entry.rowToken + '"]'); + expect(caption?.getAttribute("data-thl-item-id")).toBe(entry.itemId); + expect(caption?.getAttribute("role")).toBe("button"); + expect(caption?.getAttribute("tabindex")).toBe("0"); + } + const duplicate = root.firstElementChild!.cloneNode(true); + root.append(duplicate); + expect(() => bindSequenceSourceReferences(root, proof)).toThrow("duplicated"); +}); + +it("reserves participant caption lookalikes before allocating sequence row references", async () => { + const artifact = retryCheckout(); + artifact.entities[0].label = "TL000000"; + const trace = compileArtifact(artifact); + const proof = sequenceProof(trace, projectView(inspectTrace(trace), { kind: "sequence", frameIndex: 2 })); + const events = proof.elements.filter(entry => entry.role === "event"); + expect(events.map(entry => entry.rowToken)).not.toContain("TL000000"); + const host = await mount(proof); + expect(host.querySelectorAll("[data-thl-source-reference]")).toHaveLength(events.length); + for (const entry of events) { + const caption = host.querySelector('[data-thl-source-reference="' + entry.rowToken + '"]'); + expect(caption?.getAttribute("data-thl-item-id")).toBe(entry.itemId); + } +}); + +it("fails closed rather than omitting graph state when a reserved line is missing", async () => { + const trace = compileArtifact(distributedGraph()); + const proof = graphProof(trace, projectView(inspectTrace(trace), { kind: "graph", frameIndex: 1 })); + const entry = proof.elements.find(item => item.stateSlot)!; + expect(entry.stateSlot).toBeDefined(); + await expect(renderProof(proof, undefined, svg => svg.replaceAll(entry.stateSlot!, "missing"))).rejects.toThrow("graph state slot"); +}); diff --git a/src/react/mermaid/adapter.ts b/src/react/mermaid/adapter.ts index acf70b87..76c60412 100644 --- a/src/react/mermaid/adapter.ts +++ b/src/react/mermaid/adapter.ts @@ -1,5 +1,7 @@ import type { CompiledTrace, SourceIds, ViewDescriptor, ViewItem } from "../../v2/model.js"; import { sequenceActors, type SequenceActor } from "../../v2/sequence-layout.js"; +import { summarizeCell } from "../../v2/value-summary.js"; +import type { ReadonlyCell } from "../../v2/model.js"; /** Internal Mermaid input and the source identities it presents. */ export type ProofElement = Readonly<{ @@ -13,6 +15,11 @@ export type ProofElement = Readonly<{ context?: boolean; visited?: boolean; strokeToken?: string; + /** Fixed geometry slot; dynamic state never enters Mermaid syntax. */ + stateSlot?: string; + stateText?: string; + focused?: boolean; + written?: boolean; /** Host-authored sequence row reference, not a semantic event ID. */ rowToken?: string; sent?: boolean; @@ -114,7 +121,21 @@ export function graphProof(trace: CompiledTrace, view: ViewDescriptor, if (view.kind !== "graph") throw new Error("Graph descriptor required"); const visible = view.items.filter(item => ["entity", "group", "relation"].includes(item.role)); if (visible.length > 1_400) throw new Error("Graph proof work limit exceeded"); - const elements = visible.map(element); + const elements = visible.map((item, index) => { + const entry = element(item, index); + if (item.role !== "entity" && !entry.collapsed) return entry; + // A fixed-size host-owned line reserves space in every topology render. + // Avoid collisions with authored labels (including joined wrapped lines). + let serial = index; + let stateSlot: string; + const caption = wrappedLabel(item.label, 20, 4).replaceAll("
", "").replace(/\s/g, ""); + do { stateSlot = "THLSTATE" + String(serial++).padStart(6, "0"); } + while (caption.includes(stateSlot)); + return Object.freeze({ ...entry, stateSlot, + stateText: entry.collapsed ? String(property(item, "count")) + " present" : + summarizeCell((property(item, "cell") ?? null) as ReadonlyCell | null), + focused: property(item, "focused") === true, written: property(item, "changed") === true }); + }); const byItem = new Map(elements.map(item => [item.itemId, item])); const groups = visible.filter(item => item.role === "group"); const groupBySource = new Map(groups.map(item => [item.source.groupIds![0], item])); @@ -142,7 +163,7 @@ export function graphProof(trace: CompiledTrace, view: ViewDescriptor, emit(item.id); lines.push("end"); } else { - lines.push(entry.id + '("' + wrappedLabel(item.label, 20, 4) + '")'); + lines.push(entry.id + '("' + wrappedLabel(item.label, 20, 4) + '
' + entry.stateSlot + '")'); // A host-owned class is an explicit map key, not Mermaid's private ID. lines.push("class " + entry.id + " " + entry.id + "_source"); } @@ -215,7 +236,7 @@ export function sequenceProof(trace: CompiledTrace, view: ViewDescriptor, // adjacent lines. Numeric escapes cannot emit ASCII letters/digits (those // are emitted literally); decode them once to cover punctuation too. const reserved = new Set(); - for (const { caption } of rows) { + for (const caption of [...rows.map(row => row.caption), ...actors.map(actor => wrappedLabel(actor.label, 15, 3))]) { const text = caption.replaceAll("
", "").replace(/#(\d+);/g, (_, n: string) => String.fromCodePoint(Number(n))); for (const token of text.replace(/\s/g, "").match(/TL\d{6}/g) ?? []) reserved.add(token); } diff --git a/src/react/mermaid/motion.ts b/src/react/mermaid/motion.ts index 1dd6c0aa..3a0355a9 100644 --- a/src/react/mermaid/motion.ts +++ b/src/react/mermaid/motion.ts @@ -35,7 +35,25 @@ function placeGraphCaption(route: SVGGeometryElement, caption: SVGTextElement, o } } +/** Paint bounded state in the reserved node line without rebuilding geometry. */ +export function paintGraphState(host: HTMLElement, proof: DiagramProof): void { + if (proof.kind !== "graph") return; + const elements = new Map(proof.elements.map(entry => [entry.itemId, entry])); + for (const label of host.querySelectorAll("[data-thl-state-label]")) { + const entry = elements.get(label.getAttribute("data-thl-state-label")!); + if (!entry) continue; + const text = entry.stateText ?? "Unavailable"; + if (label.textContent !== text) label.textContent = text; + label.setAttribute("aria-label", text); + label.setAttribute("title", text); + const node = label.closest("[data-thl-item-id]"); + node?.toggleAttribute("data-thl-focused", entry.focused === true); + node?.toggleAttribute("data-thl-written", entry.written === true); + } +} + export function paintRoutes(host: HTMLElement, proof: DiagramProof, selectedId: string | null): () => void { + paintGraphState(host, proof); const elements = new Map(proof.elements.map(entry => [entry.itemId, entry])); const sources = new Set(), destinations = new Set(); const visitedNodes = new Set(); @@ -131,7 +149,9 @@ export function animateTransfers(host: HTMLElement, proof: DiagramProof, duratio text.setAttribute("y", "-13"); caption.append(text); for (const [element, rotate] of [[head, "auto"], [caption, "0"]] as const) { - if (element === caption && !text.textContent) continue; + // Sequence captions carry the authoritative selectable row reference. + // Keep them stationary and visible; a moving duplicate obscures them. + if (element === caption && (proof.kind === "sequence" || !text.textContent)) continue; const animation = document.createElementNS(ns, "animateMotion"); animation.setAttribute("dur", duration / 1000 + "s"); animation.setAttribute("repeatCount", "1"); animation.setAttribute("rotate", rotate); animation.setAttribute("fill", "freeze"); @@ -151,7 +171,7 @@ export function animateTransfers(host: HTMLElement, proof: DiagramProof, duratio destination.setAttribute("data-thl-cue-running", ""); destinations.add(destination); } - for (const label of host.querySelectorAll('[data-thl-motion-label="' + entry.itemId + '"]')) { + if (proof.kind === "graph") for (const label of host.querySelectorAll('[data-thl-motion-label="' + entry.itemId + '"]')) { label.setAttribute("data-thl-label-in-motion", ""); labels.push(label); } diff --git a/src/react/mermaid/player-diagram.tsx b/src/react/mermaid/player-diagram.tsx index bb60a209..2d1b0574 100644 --- a/src/react/mermaid/player-diagram.tsx +++ b/src/react/mermaid/player-diagram.tsx @@ -21,14 +21,16 @@ function useDiagram(proof: DiagramProof | undefined, trace: DiagramRendererProps renderDiagram: typeof renderProof) { const source = proof?.source; const [attempt, setAttempt] = useState(0); - const cache = useRef(new Map()); + const cache = useRef<{ trace: typeof trace; entries: Map }>({ trace, entries: new Map() }); const [result, setResult] = useState<{ trace: typeof trace; source: string; kind: DiagramProof["kind"]; diagram: RenderedDiagram | null; frame: number; attempt: number; }>(); useEffect(() => { if (!proof || !source) return; const rendered = { trace, source, kind: proof.kind, frame: frameIndex, attempt }; - const cached = cache.current.get(source); + if (cache.current.trace !== trace) cache.current = { trace, entries: new Map() }; + const entries = cache.current.entries; + const cached = entries.get(source); if (cached) { setResult({ ...rendered, diagram: cached }); return; @@ -36,9 +38,9 @@ function useDiagram(proof: DiagramProof | undefined, trace: DiagramRendererProps const request = new AbortController(); void renderDiagram(proof, request.signal).then(diagram => { if (request.signal.aborted) return; - cache.current.set(source, diagram); - if (cache.current.size > CACHE_LIMIT) - cache.current.delete(cache.current.keys().next().value!); + entries.set(source, diagram); + if (entries.size > CACHE_LIMIT) + entries.delete(entries.keys().next().value!); setResult({ ...rendered, diagram }); }, () => { if (!request.signal.aborted) setResult({ ...rendered, diagram: null }); @@ -369,16 +371,36 @@ function MermaidPlayerDiagramImpl({ if (event.key === "Enter" || event.key === " ") select(event); }, }; + // Essential source selection uses ordinary host-owned buttons, independent + // of generated SVG class names, route geometry or renderer availability. + const sourceControls = proof &&
+ {proof.kind === "sequence" ? "Sequence source references" : "Graph source references"} +
    + {proof.elements.map(entry =>
  • + +
  • )} +
+
; if (!proof || diagram === null) return

{proof ? "The diagram couldn’t be rendered." : "This diagram exceeds the preview display limit."}

{proof && }
+ {sourceControls} {fallback()}
; if (!visible) return

Preparing {proof.kind === "graph" ? "graph" : "sequence"}…

+ {sourceControls}
; const markup = { __html: visible.svg }; if (proof.kind === "sequence") return
@@ -399,21 +421,12 @@ function MermaidPlayerDiagramImpl({ }
- {diagram &&
- Sequence source references -
    - {proof.elements.filter(entry => entry.role === "event").map(entry =>
  • - -
  • )} -
-
} + {sourceControls} ; return
+ stateEvidence={<>
{view.items.filter(item => item.role === "entity" || (item.role === "group" && property(item, "collapsed") === true)).map(item => { const group = item.role === "group"; const focused = property(item, "focused") === true, changed = property(item, "changed") === true; @@ -427,7 +440,7 @@ function MermaidPlayerDiagramImpl({ {focused && · Focus}{changed && · Write} ; })} -
} + {sourceControls}} follow={unfollowedTrace !== trace} onFollowChange={enabled => setUnfollowedTrace(enabled ? null : trace)}>
diff --git a/src/react/mermaid/render.ts b/src/react/mermaid/render.ts index 1908caf3..9209073e 100644 --- a/src/react/mermaid/render.ts +++ b/src/react/mermaid/render.ts @@ -66,8 +66,9 @@ function bindDirection(root: SVGSVGElement, route: SVGElement): void { } /** Bind host-authored paint/row tokens to the current descriptor. Graph - * tokens do not rely on generated SVG IDs; Sequence still has a pinned local - * caption/mark bridge. Source controls provide an independent text path. + * tokens do not rely on generated SVG IDs. Sequence event selection uses + * explicit text references; its optional geometry bridge remains pinned. + * Host source controls provide an independent text path. * Missing/duplicated/ambiguous routes fail closed rather than guessing. */ export function bindSources(svg: string, proof: DiagramProof): Pick { @@ -88,6 +89,7 @@ export function bindSources(svg: string, proof: DiagramProof): Pick [entry.rowToken, entry])); if (byToken.size !== events.length || byToken.has(undefined)) throw new Error("Sequence proof lacks unique source references"); + bindSequenceSourceReferences(root, proof); const bound = new Set(); const resolve = (labels: readonly Element[], sent: boolean) => { // The adapter reserves all reference-shaped authored caption strings @@ -125,12 +127,9 @@ export function bindSources(svg: string, proof: DiagramProof): Pick !entry.sent); @@ -143,7 +142,8 @@ export function bindSources(svg: string, proof: DiagramProof): Pick item.role === "group" && !item.collapsed)) { // Region geometry is optional. Group selection uses the host's source control. @@ -208,6 +209,60 @@ export function bindSources(svg: string, proof: DiagramProof): Pick entry.role === "event"); + const byToken = new Map(events.map(entry => [entry.rowToken, entry])); + if (byToken.size !== events.length || byToken.has(undefined)) + throw new Error("Sequence proof lacks unique source references"); + const found = new Map(); + for (const text of root.querySelectorAll("text")) { + const tokens = (text.textContent?.match(/TL\d{6}/g) ?? []).filter(token => byToken.has(token)); + if (!tokens.length) continue; + const token = tokens[0]; + if (tokens.length !== 1 || found.has(token) || !text.textContent?.trimEnd().endsWith(token)) + throw new Error("Missing or duplicated sequence source reference"); + found.set(token, text); + } + if (found.size !== events.length) throw new Error("Missing or duplicated sequence source reference"); + for (const [token, text] of found) { + const entry = byToken.get(token)!; + bindItem(text, entry.itemId, entry.sent ? "Inspect transfer " + (entry.flowLabel ?? entry.label) : "Inspect " + entry.label); + text.setAttribute("data-thl-source-reference", token); + } +} + +/** Replace only the trusted reserved text line; never parse authored values as markup. + * Fail closed if this pinned renderer does not preserve the reserved line. + */ +function bindGraphState(node: Element, entry: DiagramProof["elements"][number]): void { + if (!entry.stateSlot) return; + const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); + const slots: Text[] = []; + while (walker.nextNode()) { + const text = walker.currentNode as Text; + if (text.data.trim() === entry.stateSlot) slots.push(text); + } + if (slots.length !== 1) throw new Error("Rendered graph state slot unavailable"); + const text = slots[0], parent = text.parentElement; + if (!parent) throw new Error("Rendered graph state slot has no parent"); + if (parent.namespaceURI === "http://www.w3.org/1999/xhtml") { + const span = document.createElementNS(parent.namespaceURI, "span"); + span.setAttribute("data-thl-state-label", entry.itemId); + span.setAttribute("style", "display:inline-block;max-width:100px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;vertical-align:bottom"); + span.textContent = entry.stateText ?? "Unavailable"; + text.replaceWith(span); + } else { + // SVG text fallback must have a dedicated line, not the entity caption. + if (parent.textContent?.trim() !== entry.stateSlot) throw new Error("Ambiguous SVG graph state slot"); + parent.setAttribute("data-thl-state-label", entry.itemId); + parent.textContent = entry.stateText ?? "Unavailable"; + } +} + function normalizedSize(root: SVGSVGElement): Pick { const { width, height } = root.viewBox.baseVal; if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) diff --git a/src/styles/throughline.css b/src/styles/throughline.css index b17b35dd..292874b3 100644 --- a/src/styles/throughline.css +++ b/src/styles/throughline.css @@ -1616,8 +1616,18 @@ padding: 16px; color: var(--thl-muted); text-align: center; } .thl.player-shell .mermaid-loading p { margin: 0; } -.thl.player-shell .mermaid-fallback .mermaid-status { padding-inline: 12px; } -.thl.player-shell .mermaid-fallback .state-view { inset-block-start: 76px; } +.thl.player-shell .mermaid-fallback { + position: absolute; inset: 40px 12px 12px; display: flex; flex-direction: column; + min-width: 0; min-height: 0; gap: 6px; +} +.thl.player-shell .mermaid-fallback .mermaid-status { flex: 0 0 auto; } +.thl.player-shell .mermaid-fallback .mermaid-source-references { min-width: 0; overflow-wrap: anywhere; } +/* Native State uses an absolute inset when rendered directly in the canvas. + In the Mermaid fallback it must share space with diagnostics and source + controls; a fixed top offset overlaps wrapped controls and disclosures. */ +.thl.player-shell .mermaid-fallback .state-view { + position: relative; inset: auto; flex: 1 1 0; min-height: 0; min-width: 0; overflow: auto; +} .thl.player-shell:fullscreen { height: 100dvh; width: 100%; overflow: auto; } .thl.player-shell:fullscreen .player-content { flex: 1 1 0; min-height: 180px; } diff --git a/src/v2/value-summary.ts b/src/v2/value-summary.ts index 9952988e..b6e0e0e1 100644 --- a/src/v2/value-summary.ts +++ b/src/v2/value-summary.ts @@ -1,5 +1,4 @@ import type { ReadonlyCell, ReadonlyJsonValue, QueryCell } from "./model.js"; -import { encodeJson } from "./validator.js"; /** Bounded summaries describe shape, never synthesize domain meaning. */ export function summarizeValue(value: ReadonlyJsonValue): string { @@ -9,7 +8,7 @@ export function summarizeValue(value: ReadonlyJsonValue): string { return count + (count === 1 ? " field" : " fields"); } const bounded = typeof value === "string" && value.length > 46 ? value.slice(0, 45).replace(/[\uD800-\uDBFF]$/, "") + "…" : value; - const text = encodeJson(bounded); + const text = JSON.stringify(bounded); return text.length > 48 ? text.slice(0, 47) + "…" : text; }