diff --git a/docs/testing-evidence/embed-controls-2026-11-06.md b/docs/testing-evidence/embed-controls-2026-11-06.md index 4c4f07fc..ab9e3702 100644 --- a/docs/testing-evidence/embed-controls-2026-11-06.md +++ b/docs/testing-evidence/embed-controls-2026-11-06.md @@ -110,18 +110,45 @@ that rule. All ten phone/tablet embed cases, including resize/history/reset, tables, fullscreen pinch and pan, passed against the fresh frozen build: `.test-work/reports/pr3037-phone-probe-3/report.json`. -A repeated popout run exposed the native table cell editor activating underneath -a toolbar mouse press and retaining an extra rendered copy. Toolbar compatibility -mouse/touch events are now isolated from the table; button default activation is -preserved. Source tests and the focused popout roundtrip passed after the fix: -`.test-work/reports/pr3037-table-input-smoke/popout-probe.json`. +Toolbar compatibility mouse/touch events are isolated from the surrounding native +table, preserving button default activation. Editing table syntax intentionally +opens Obsidian's inner cell editor; the host retains its hidden display preview. +The native test exits through a trusted footer click instead of moving only the +outer editor's caret. It verifies that this roundtrip preserves every source byte. -Latest source suite before the event-isolation checkpoint: 716 tests in 87 files -passed. Modified embed modules have zero targeted lint or TypeScript diagnostics. -The production bundle is 5,088,586 bytes before that final small checkpoint. -Complete native and portable acceptance, minimum Obsidian 1.8.7, macOS, physical -Android/iOS and hosted CodeScanner remain explicit gates until actual evidence -is recorded. +Complete portable regression at `76ffd8ed4dbb347e0c1a7ef01d5778f9537a41d3` +passed 934 canonical cases, with successful cleanup and no missing cases. It +includes 717 plugin tests and 199 source-coverage tests. GitHub Plugin tests and +CodeQL passed at that revision. The first complete native attempt remains failed: +399 passed, five failed, cleanup passed. Evidence is retained under +`.test-work/reports/pr3037-native-76ffd8ed/`. + +The November 7 checkpoint addresses the observed native readiness failures: + +- Focus the table handle through trusted hover/scroll/click input before keyboard + resizing, while retaining inactive-pane ownership and exact transaction checks. +- Wait for saved fixture frontmatter before each stability reopen; disk persistence + completes before Obsidian republishes the cache used by its default-view router. +- Flush live Markdown saves before retiring views and deleting owned fixtures. +- Restore Electron zoom and require bounded geometry/notification idle before + closing the owning popout; keep the strict host exception gate unchanged. +- Coalesce the controller's ResizeObserver-driven layout writes into an owned + animation frame and cancel it on unload. This does not attribute or suppress the + host's historically recorded observer notifications. + +All six stability cycles and the restored-zoom workflow passed focused validation +without unexpected host errors. Full phone/tablet workflows passed 108 cases with +clean error gates, cleanup and restoration. The corrected desktop input sequence +then passed all 15 embed cases with baseline restoration. Evidence: +`.test-work/reports/pr3037-native-readiness-focused-1/`, including +`devices/report.json` and `controls-input-probe.json`. Failed predecessor attempts +remain separate; the focused parent report's hidden-handle input failure is not +acceptance evidence. + +Latest source suite: 717 tests in 87 files passed. Modified embed modules have zero +targeted lint or TypeScript diagnostics. Fresh complete portable/native acceptance +is still required at this checkpoint. Minimum Obsidian 1.8.7, macOS, physical +Android/iOS and hosted CodeScanner remain separate unverified gates. `npm run code` reports 118 existing errors outside the modified production modules; targeted lint and targeted TypeScript diagnostics pass. Production diff --git a/scripts/testing/embedControls.source.test.mjs b/scripts/testing/embedControls.source.test.mjs index 4c120b70..c56ab986 100644 --- a/scripts/testing/embedControls.source.test.mjs +++ b/scripts/testing/embedControls.source.test.mjs @@ -122,8 +122,12 @@ test("late image sizing leaves the toolbar inside paint containment and remeasur f.frame.fire("load"); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), true); f.image.bounds = { ...f.image.bounds, bottom: 130, height: 130 }; const observer = f.observers.find(observer => observer.resize); assert.equal(observer.target, f.image); - observer.fire(); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), false); + observer.fire(); observer.fire(); + assert.equal(f.pendingFrames(), 1); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), true); + f.flushFrames(); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), false); assert.equal(f.frame.style["--excalidraw-embed-control-top"], "0px"); assert.equal(f.frame.style["--excalidraw-embed-control-bottom"], "-8px"); + observer.fire(); assert.equal(f.pendingFrames(), 1); } finally { f.close(); } + assert.equal(f.pendingFrames(), 0); f.flushFrames(); }); diff --git a/scripts/testing/embedTestDOM.mjs b/scripts/testing/embedTestDOM.mjs index 7c1fef5a..38f9e820 100644 --- a/scripts/testing/embedTestDOM.mjs +++ b/scripts/testing/embedTestDOM.mjs @@ -1,12 +1,14 @@ /** Small lifecycle/DOM boundary for production embed-controller tests; no rendering claim. */ export function embedTestDOM() { - const observers = []; let listeners = 0; + const observers = [], frames = new Map(); let listeners = 0, nextFrame = 0; const window = { events: new Map(), closed: false, innerWidth: 800, MutationObserver: class { constructor(callback) { this.callback = callback; observers.push(this); } observe() { this.connected = true; } disconnect() { this.connected = false; } fire() { if (this.connected) this.callback(); } } }; + window.requestAnimationFrame = callback => { const id = ++nextFrame; frames.set(id, callback); return id; }; + window.cancelAnimationFrame = id => frames.delete(id); window.ResizeObserver = class extends window.MutationObserver { constructor(callback) { super(callback); this.resize = true; } observe(target) { super.observe(); this.target = target; } @@ -53,5 +55,6 @@ export function embedTestDOM() { unload() { for (const cleanup of this.cleanups.splice(0)) cleanup(); this.onunload?.(); } } class MarkdownRenderChild extends Component { constructor(containerEl) { super(); this.containerEl = containerEl; } } - return { Element, Component, MarkdownRenderChild, window, document, fire, observers, listenerCount: () => listeners }; + return { Element, Component, MarkdownRenderChild, window, document, fire, observers, listenerCount: () => listeners, + pendingFrames: () => frames.size, flushFrames: () => { const callbacks = [...frames.values()]; frames.clear(); for (const callback of callbacks) callback(); } }; } diff --git a/scripts/testing/host/behaviorEnvironment.mjs b/scripts/testing/host/behaviorEnvironment.mjs index 6ff08457..19d85901 100644 --- a/scripts/testing/host/behaviorEnvironment.mjs +++ b/scripts/testing/host/behaviorEnvironment.mjs @@ -69,6 +69,10 @@ export async function behaviorEnvironment( windows.get(owner).push({ leaf, view }); } for (const [owner, entries] of windows) { + // Native Markdown autosave/reload can outlive setViewState(empty). + // Flush while the note exists, then let its update/render work settle. + for (const { view } of entries) + if (view.containerEl.isConnected && view.getViewType?.() === "markdown" && view.file) await view.save(); browserIdle.push(await settleBrowserDiagnostics(owner,windowErrors,'behavior:'+context.id)); for (const { view } of entries) view.exitFullscreen?.(); for (const { view } of entries) diff --git a/scripts/testing/host/embedControls.mjs b/scripts/testing/host/embedControls.mjs index 82f58853..47b4a3f9 100644 --- a/scripts/testing/host/embedControls.mjs +++ b/scripts/testing/host/embedControls.mjs @@ -259,7 +259,7 @@ async function exerciseEmbedControls(c, env, template, modifier) { const cm = leaf.view.editor.cm; const ready = () => { const current = frames(); - c.observations = { ...c.observations, table: { selection: cm.state.selection.main.toJSON(), frames: current.map(frame => ({ connected: frame.isConnected, width: frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") })), html: cm.contentDOM.querySelector(".cm-table-widget")?.outerHTML.slice(0, 10000) } }; + c.observations = { ...c.observations, table: { selection: cm.state.selection.main.toJSON(), frames: current.map(frame => ({ connected: frame.isConnected, bounds: frame.getBoundingClientRect().toJSON(), width: frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") })), html: cm.contentDOM.querySelector(".cm-table-widget")?.outerHTML.replace(//g, "").slice(0, 10000) } }; return current.length === 3 && current.every((frame, i) => frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") === (i === 2 ? "120" : "100")); }; await c.waitFor(ready, "three authoritative table cells and escaped display dimensions"); @@ -270,7 +270,10 @@ async function exerciseEmbedControls(c, env, template, modifier) { other.view.editor.setCursor({ line: other.view.editor.lastLine(), ch: 0 }); app.workspace.setActiveLeaf(other, { focus: true }); } - frames()[1].querySelector('[data-excalidraw-embed-action="resize"]').focus(); + // A second pane's asynchronous activation can reclaim programmatic focus. + // Use the same trusted click that a keyboard user uses to focus the handle. + await action(1, "resize"); + await c.waitFor(() => doc.activeElement === frames()[1]?.querySelector('[data-excalidraw-embed-action="resize"]'), "owned table resize keyboard focus"); await key("ArrowRight", "ArrowRight", 39); const changed = source.replace(token + " | second", token.replace("100", "108") + " | second"); await c.waitFor(() => cm.state.doc.toString() === changed, "only the second identical physical table cell resized"); @@ -280,7 +283,12 @@ async function exerciseEmbedControls(c, env, template, modifier) { await action(2, "edit"); check(cm.state.sliceDoc(cm.state.selection.main.from, cm.state.selection.main.to) === markdown, "table source edit selected the wrong syntax or cell"); leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 }); + // The table intentionally owns an inner cell editor while syntax is being + // edited. Moving the outer caret by API does not blur that editor. Exit it + // through trusted note input before counting/restoring its normal previews. + await click(() => [...cm.contentDOM.querySelectorAll(".cm-line")].find(line => line.closest(".cm-content") === cm.contentDOM && line.textContent.trim() === "Footer")); await c.waitFor(ready, "table syntax edit roundtrip"); + check(cm.state.doc.toString() === source, "table source editing roundtrip rewrote surrounding syntax"); await action(1, "reset"); const reset = source.replace(token + " | second", token.replace("\\|100", "") + " | second"); await c.waitFor(() => cm.state.doc.toString() === reset, "table reset preserves escaped aliases, style, title and other cells"); diff --git a/scripts/testing/host/stability.mjs b/scripts/testing/host/stability.mjs index 2cd06451..11c7661f 100644 --- a/scripts/testing/host/stability.mjs +++ b/scripts/testing/host/stability.mjs @@ -44,6 +44,9 @@ async function exerciseStability(c,path,fixture,cycles){ const observation={cycle};c.observations.push(observation); let anchor;app.workspace.iterateAllLeaves(l=>{if(!anchor&&l.getRoot()===app.workspace.rootSplit)anchor=l;}); check(anchor,'No main-window anchor');app.workspace.setActiveLeaf(anchor,{focus:true}); + // Vault persistence completes before Obsidian republishes frontmatter. + // The default-view router requires that metadata on every fresh open. + await c.waitFor(()=>!!app.metadataCache.getCache(path)?.frontmatter?.['excalidraw-plugin'],'large saved fixture frontmatter before open'); leaf=app.workspace.getLeaf('tab');await leaf.openFile(file); observation.opened=loadState(); try{await c.waitFor(()=>leaf.view.excalidrawAPI&&leaf.view.isLoaded&&!leaf.view.semaphores.justLoaded&&!leaf.view.isClosingOrMigrating(),'large scene first commit',60000);}catch(error){observation.failed=loadState();throw error;} diff --git a/scripts/testing/host/stability.test.mjs b/scripts/testing/host/stability.test.mjs index 8d861cbb..0a0e51d4 100644 --- a/scripts/testing/host/stability.test.mjs +++ b/scripts/testing/host/stability.test.mjs @@ -24,7 +24,7 @@ test("failed stability loading retires the owned leaf before deleting its file", operations = []; let detached = false, closed = false, - removed = false; + removed = false, frontmatter; const file = { path: "__excalidraw_cli_smoke_owned_stability.excalidraw.md" }; const doc = { querySelectorAll: () => [{}] }; const originalView = { @@ -40,7 +40,7 @@ test("failed stability loading retires the owned leaf before deleting its file", const leaf = { id: "owned", view: originalView, - async openFile() {}, + async openFile() { assert.ok(frontmatter?.["excalidraw-plugin"], "Opening before metadata is ready can select Markdown mode"); }, async setViewState(state) { assert.equal(state.type, "empty"); closed = true; @@ -63,6 +63,7 @@ test("failed stability loading retires the owned leaf before deleting its file", }, root = {}; const app = { + metadataCache: { getCache: () => ({ frontmatter }) }, plugins: { plugins: { "obsidian-excalidraw-plugin": { isExcalidrawFile: () => true }, @@ -110,6 +111,12 @@ test("failed stability loading retires the owned leaf before deleting its file", assert.ok(predicate()); return; } + if (label === "large saved fixture frontmatter before open") { + assert.equal(!!predicate(), false); + frontmatter = { "excalidraw-plugin": "parsed" }; + assert.equal(predicate(), true); + return; + } assert.equal(label, "large scene first commit"); throw Error("owned first commit failure"); }, diff --git a/scripts/testing/host/workflowBundle.mjs b/scripts/testing/host/workflowBundle.mjs index 476bb3a2..9c2755ac 100644 --- a/scripts/testing/host/workflowBundle.mjs +++ b/scripts/testing/host/workflowBundle.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { runInAppTask } from "./inAppTask.mjs"; +import { settleBrowserDiagnostics } from "./browserDiagnostics.mjs"; export const workflowBundleCaseIds = ["native:workflow-markdown-extraction-3009", "native:workflow-zen-controls-3000"]; @@ -9,15 +10,24 @@ export async function runWorkflowBundleScenario({ cli, drawingPath }) { assert.ok(drawingPath.startsWith("__excalidraw_cli_smoke_")); const prefix = drawingPath.replace(/\.(excalidraw\.md|excalidraw|md)$/, "") + "_bundle"; const fixture = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8"); - const result = await runInAppTask({ cli, execute: exerciseWorkflows, args: [prefix, fixture], timeoutMs: 180000, cleanupMs: 60000 }); + const execute = new Function(`return async function(c,prefix,fixture){return (${exerciseWorkflows.toString()})(c,prefix,fixture,${settleBrowserDiagnostics.toString()});}`)(); + const result = await runInAppTask({ cli, execute, args: [prefix, fixture], timeoutMs: 180000, cleanupMs: 60000 }); return { id: "workflow-bundle-3030", status: "passed", ...result }; } -async function exerciseWorkflows(c, prefix, fixture) { +async function exerciseWorkflows(c, prefix, fixture, settleBrowserDiagnostics) { const plugin = app.plugins.plugins["obsidian-excalidraw-plugin"]; const mainDocument = app.workspace.containerEl.ownerDocument; const previous = app.workspace.activeLeaf, leaves = new Set(), tabs = new Set(), rootFiles = new Set(); const attachmentFolderPath = app.vault.getConfig("attachmentFolderPath"); + const windowEvents = [], observedWindows = new Map(); + const observeWindow = win => { + if (observedWindows.has(win)) return; + const listener = event => windowEvents.push({ message: event.message, at: Date.now() }); + win.addEventListener("error", listener); observedWindows.set(win, listener); + }; + observeWindow(mainDocument.defaultView); + c.defer(() => { for (const [win, listener] of observedWindows) if (!win.closed) win.removeEventListener("error", listener); }); c.observations = {}; const check = (condition, message) => { if (!condition) throw Error(message); }; const closeTab = async (tab, view) => { @@ -64,6 +74,7 @@ async function exerciseWorkflows(c, prefix, fixture) { const leaf = popout ? app.workspace.openPopoutLeaf() : app.workspace.getLeaf("tab"); leaves.add(leaf); if (popout) await c.waitFor(() => leaf.view.containerEl.ownerDocument !== mainDocument, "empty workflow popout migration"); await leaf.openFile(file); await ready(leaf); + observeWindow(leaf.view.ownerWindow); app.workspace.setActiveLeaf(leaf, { focus: true }); leaf.view.ownerWindow.focus(); return leaf; }; @@ -149,7 +160,7 @@ async function exerciseWorkflows(c, prefix, fixture) { return { assertions: ["root/nested/Unicode owning folder defaults", "two simultaneous drawings retain the selected image's owner", "explicit selection and cancellation", "unique names and original content preserved", "external source links persist through save/reopen", "main/popout extraction"], variants }; }); await c.case("native:workflow-zen-controls-3000", ["P03", "P08"], async () => { - const variants = []; + const variants = [], zoomIdle = []; for (const popout of [false, true]) { const leaf = await open(prefix + "/Zen-" + popout + ".excalidraw.md", popout), view = leaf.view, api = view.excalidrawAPI; const doc = view.ownerDocument, win = view.ownerWindow; @@ -196,9 +207,13 @@ async function exerciseWorkflows(c, prefix, fixture) { view.contentEl.setCssProps({ width: originalWidth, "max-width": originalMaxWidth }); api.updateScene({ appState: { zenModeEnabled: false }, captureUpdate: "NEVER" }); } + // Restoring Electron zoom schedules native status/resize work. Keep its + // owning popout alive until that work is quiet before destroying it. + const idle = await settleBrowserDiagnostics(win, windowEvents, "workflow restored zoom"); + zoomIdle.push(idle); check(idle.status === "passed", "Restored workflow zoom did not settle"); await closeLeaf(leaf); } - return { assertions: ["Zen exit and zoom indicator do not intersect", "both controls remain inside the editor and uncovered", "zoom and exit actions activate repeatedly", "LTR/RTL wide/narrow panes and UI scale", "main/popout document ownership"], variants }; + return { assertions: ["Zen exit and zoom indicator do not intersect", "both controls remain inside the editor and uncovered", "zoom and exit actions activate repeatedly", "LTR/RTL wide/narrow panes and UI scale", "main/popout document ownership", "restored native zoom settles before popout teardown"], variants, zoomIdle }; }); return { tests: c.tests }; } diff --git a/src/core/managers/DrawingEmbedControls.ts b/src/core/managers/DrawingEmbedControls.ts index 27708539..e33f913f 100644 --- a/src/core/managers/DrawingEmbedControls.ts +++ b/src/core/managers/DrawingEmbedControls.ts @@ -77,8 +77,18 @@ export class DrawingEmbedControls extends MarkdownRenderChild { observer.observe(frame, { childList: true, subtree: true }); this.register(() => observer.disconnect()); if (typeof win.ResizeObserver === "function") { - this.resizeObserver = new win.ResizeObserver(() => this.placeToolbar()); - this.register(() => { this.resizeObserver?.disconnect(); this.resizeObserver = null; }); + let frameId: number | null = null; + this.resizeObserver = new win.ResizeObserver(() => { + // Placement can change flow. Write outside observer delivery, and + // coalesce notifications into disposable owning-window UI work. + if (frameId === null) frameId = win.requestAnimationFrame(() => { + frameId = null; this.placeToolbar(); + }); + }); + this.register(() => { + this.resizeObserver?.disconnect(); this.resizeObserver = null; + if (frameId !== null) win.cancelAnimationFrame(frameId); + }); } this.registerDomEvent(frame, "load", () => this.placeToolbar(), true); this.registerDomEvent(frame, "pointerenter", () => this.placeToolbar());