Synchronize native text fixtures and compare ordinary tab migration

This commit is contained in:
zsviczian committed 2026-10-29 22:05:59 +01:00
1 parent 65f63a3049
commit e4a36a6b39
6 files changed
+144 -11

No files matched your search

+12
View File
@@ -3190,3 +3190,15 @@ remain strict pending maintainer classification; no production changes.
diagnostics tests and the unchanged production build pass. Focused prefix
reproduction, migration comparison and large-scene sequence diagnosis remain
in progress; production behavior and the PDF rollback remain untouched.
- 2026-10-29 (#3022): Prefix reproduction at 65f63a30 identifies raw/button/wikilink
second undo consuming an enabled, visible control's real history entry without
restoring text. The isolated legacy setup then proves every raw variant leaves
the view raw while its data model remains parsed. Corrected only test setup to
await the normal save/reload mode transition before clearing the next fixture;
two regressions enforce synchronization and ordering. Added bounded read-only
delta/model evidence and a focused ordinary-host-tab-drag migration control;
it is explicitly synthetic and outside full-profile coverage. Every original
text/history, migration and cleanup assertion remains. Production and PDF
rollback unchanged. Next risk checks: full predecessor text sequence, both
migration routes and all six large-scene cycles before complete repeats.
+44 -7
View File
@@ -3,15 +3,20 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { runInAppTask } from "./inAppTask.mjs";
export async function runLifecycleScenario({ cli, drawingPath }) {
export async function runLifecycleScenario({ cli, drawingPath }, { migrationRoute = "direct" } = {}) {
assert.ok(["direct", "host-drag"].includes(migrationRoute));
assert.ok(drawingPath.startsWith("__excalidraw_cli_smoke_"));
const prefix = drawingPath.replace(/\.(excalidraw\.md|excalidraw|md)$/, "") + "_lifecycle";
const fixture = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const result = await runInAppTask({ cli, execute: exerciseLifecycle, args: [prefix, fixture], timeoutMs: 180_000 });
return { id: "lifecycle", status: "passed", ...result };
const result = await runInAppTask({ cli, execute: exerciseLifecycle, args: [prefix, fixture, migrationRoute], timeoutMs: 180_000 });
return { id: migrationRoute === "direct" ? "lifecycle" : "lifecycle-host-drag-control", status: "passed", ...result };
}
async function exerciseLifecycle(c, prefix, fixture) {
async function exerciseLifecycle(c, prefix, fixture, migrationRoute) {
if (migrationRoute === "host-drag") {
const originalCase = c.case.bind(c);
c.case = (id, features, run) => originalCase(id.replace("native:", "diagnostic:host-drag:"), features, run);
}
let plugin = app.plugins.plugins["obsidian-excalidraw-plugin"];
const doc = app.workspace.containerEl.ownerDocument, previous = app.workspace.activeLeaf, owned = new Set();
const check = (condition, label) => { if (!condition) throw Error(label); };
@@ -79,13 +84,45 @@ async function exerciseLifecycle(c, prefix, fixture) {
// Reacquire a live destination instead of retaining that detached group.
const destination = survivor.parent;
check(destination.containerEl.isConnected && destination.containerEl.ownerDocument === doc && typeof main.parent.removeChild === "function" && typeof destination.insertChild === "function", "installed host cannot migrate an owned leaf back to main");
main.parent.removeChild(main); main.setDimension(null); destination.insertChild(-1, main);
destination.selectTabIndex(destination.children.indexOf(main)); app.workspace.requestResize();
let routeEvidence = { input: "direct host remove/insert operations" };
if (migrationRoute === "host-drag") {
// Enter Obsidian's registered tab dragstart/drop handlers instead of
// rearranging leaf parents in test code. This is a synthetic host-route
// control, not evidence of a real OS drag or trusted pointer interaction.
const source = main.tabHeaderEl, target = survivor.tabHeaderEl;
const sourceWindow = source.ownerDocument.defaultView, mainWindow = doc.defaultView;
const sr = source.getBoundingClientRect(), tr = target.getBoundingClientRect();
check(sr.width > 0 && tr.width > 0, "migration tab headers are not visible");
const point = { clientX: tr.x + tr.width / 2, clientY: tr.y + tr.height * 0.8 };
const start = new sourceWindow.DragEvent("dragstart", { bubbles: true, cancelable: true,
clientX: sr.x + sr.width / 2, clientY: sr.y + sr.height / 2, dataTransfer: new sourceWindow.DataTransfer() });
const end = new sourceWindow.DragEvent("dragend", { bubbles: true });
let dropDispatched = false;
source.dispatchEvent(start);
try {
const over = new mainWindow.DragEvent("dragover", { bubbles: true, cancelable: true,
...point, dataTransfer: new mainWindow.DataTransfer() });
target.dispatchEvent(over);
check(app.workspace.getDropLocation(over) === destination, "ordinary tab drag did not target the live main tab group");
const drop = new mainWindow.DragEvent("drop", { bubbles: true, cancelable: true,
...point, dataTransfer: new mainWindow.DataTransfer() });
dropDispatched = true;
target.dispatchEvent(drop); // Host drop handler removes its drag listeners before migrating.
check(main.getRoot() === app.workspace.rootSplit, "ordinary tab drop did not move the owned leaf");
routeEvidence = { input: "synthetic dragstart/dragover/drop through Obsidian's ordinary tab handlers",
trusted: false, sourceMain: sourceWindow === mainWindow, point };
} finally {
if (!dropDispatched) source.dispatchEvent(end);
}
} else {
main.parent.removeChild(main); main.setDimension(null); destination.insertChild(-1, main);
destination.selectTabIndex(destination.children.indexOf(main)); app.workspace.requestResize();
}
await c.waitFor(() => main.view !== retired && main.view.ownerDocument === doc && main.view.excalidrawAPI, "popout to main replacement");
await ready(main); check(!retired.excalidrawAPI && main.view.excalidrawAPI.getSceneElements()[0].x === 654, "popout source survived or lost edit");
await c.waitFor(() => !main.view.isDirty(), "replacement main-window persistence");
const saved = await plugin.ea.getSceneFromFile(first); check(saved.elements[0].x === 654, "main replacement did not write captured migration edit");
return { assertions: ["dirty edit survives popout-to-main", "retired popout API unmounted", "replacement main window physically saves captured edit"] };
return { routeEvidence, assertions: ["dirty edit survives popout-to-main", "retired popout API unmounted", "replacement main window physically saves captured edit"] };
});
await c.case("native:lifecycle-new-popout-survivor", ["P03"], async () => {
const popout = app.workspace.openPopoutLeaf(); owned.add(popout);
+29 -3
View File
@@ -4,6 +4,30 @@ import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { captureTextUndoState } from "./textUndoDiagnostics.mjs";
/** Use the real mode transition; reload=false changes only the view, not its model. */
export async function prepareTextUndoFixture(view, mode) {
if (view.compatibilityMode)
throw Error("text undo regression requires a Markdown drawing");
const modes = () => ({ view: view.textMode, model: view.excalidrawData.textMode });
const before = modes();
if (before.view !== mode || before.model !== mode)
await view.changeTextMode(mode);
const after = modes();
if (after.view !== mode || after.model !== mode)
throw Error("text fixture mode transition did not synchronize view and model");
// Mode switching saves/reloads the previous drawing. Clear the next fixture
// only afterwards, using the current API, so that reload cannot restore it.
const api = view.excalidrawAPI;
api.updateScene({ elements: [], appState: { viewModeEnabled: false, selectedElementIds: {} }, captureUpdate: "NEVER" });
api.history.clear();
api.setActiveTool({ type: "text" });
const canvas = view.containerEl.querySelector("canvas.interactive");
if (!canvas) throw Error("interactive canvas missing");
const r = canvas.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2,
modeSetup: { requested: mode, before, after } };
}
/**
* Verify scene source survives reopening and unchanged submission after undo/redo.
* Uses native CDP input in the main window and the toolbar's stable test IDs.
@@ -22,7 +46,7 @@ export async function runTextUndoScenario({ cli, drawingPath, reportDir }) {
const snapshotCode = `(()=>{const v=${viewCode};const a=v?.excalidrawAPI;return JSON.stringify({elements:a?.getSceneElements().filter(e=>e.type==="text").map(e=>({id:e.id,text:e.text,originalText:e.originalText,rawText:e.rawText,cache:v.excalidrawData.getParsedResult(e.id)})),selected:a?.getAppState().selectedElementIds,editor:v?.containerEl.querySelector("textarea.excalidraw-wysiwyg")?.value??null})})()`;
const snapshot = () => evaluate(snapshotCode);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const observations = { version: 1, actions: [], completedVariants: [] };
const observations = { version: 2, setups: [], actions: [], completedVariants: [] };
let variantLabel, actionLabel;
const inspect = () =>
evaluate(
@@ -173,9 +197,11 @@ export async function runTextUndoScenario({ cli, drawingPath, reportDir }) {
variantLabel = label;
actionLabel = "create/edit text";
const point = evaluate(
`(()=>{const v=${viewCode};if(v.compatibilityMode)throw Error("text undo regression requires a Markdown drawing");const a=v.excalidrawAPI;a.updateScene({elements:[],appState:{viewModeEnabled:false,selectedElementIds:{}},captureUpdate:"NEVER"});a.history.clear();v.changeTextMode(${JSON.stringify(mode)},false);a.setActiveTool({type:"text"});const canvas=v.containerEl.querySelector("canvas.interactive");if(!canvas)throw Error("interactive canvas missing");const r=canvas.getBoundingClientRect();return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2})})()`,
`(${prepareTextUndoFixture.toString()})(${viewCode},${JSON.stringify(mode)}).then(JSON.stringify)`,
);
click(point);
observations.setups.push({ variant: label, ...point.modeSetup });
persist();
click({ x: point.x, y: point.y });
await poll(
(value) => value.editor !== null,
`${label}: new text editor`,
+18 -1
View File
@@ -48,7 +48,7 @@ export function captureTextUndoState(view, workspace) {
);
let history = { source: "not exposed by public API" };
// Forensics only: walk the owning root's ancestors, bounded even for malformed
// test fibers. Read stack lengths, never retain the App/fiber or call its APIs.
// test fibers. Read bounded delta data, never retain the App/fiber or call its APIs.
const key =
root && Object.keys(root).find((k) => k.startsWith("__reactFiber$"));
let fiber = key && root[key];
@@ -68,6 +68,16 @@ export function captureTextUndoState(view, workspace) {
source: "read-only owning App fiber",
undoDepth: candidate.undoStack.length,
redoDepth: candidate.redoStack.length,
undoEntries: candidate.undoStack.slice(-8).map((entry) => ({
id: entry.id,
elements: entry.elements,
appState: entry.appState?.delta,
})),
redoEntries: candidate.redoStack.slice(-8).map((entry) => ({
id: entry.id,
elements: entry.elements,
appState: entry.appState?.delta,
})),
};
break;
}
@@ -108,6 +118,8 @@ export function captureTextUndoState(view, workspace) {
history,
viewState: {
textMode: view?.textMode,
modelTextMode: view?.excalidrawData?.textMode,
scenePrevTextMode: view?.excalidrawData?.scene?.prevTextMode,
compatibilityMode: view?.compatibilityMode,
dirty: view?.isDirty?.(),
closing: view?.isClosingOrMigrating?.(),
@@ -128,6 +140,11 @@ export function captureTextUndoState(view, workspace) {
text: e.text,
originalText: e.originalText,
rawText: e.rawText,
link: e.link,
x: e.x,
y: e.y,
width: e.width,
height: e.height,
cache:
e.type === "text"
? view.excalidrawData.getParsedResult(e.id)
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import { captureTextUndoState } from "./textUndoDiagnostics.mjs";
import { prepareTextUndoFixture } from "./textUndo.mjs";
function fixture() {
const history = { undoStack: [{}], redoStack: [{}, {}] };
@@ -93,6 +94,11 @@ test("text-history diagnostics preserve owning window, leaked active target, con
source: "read-only owning App fiber",
undoDepth: 1,
redoDepth: 2,
undoEntries: [{ id: undefined, elements: undefined, appState: undefined }],
redoEntries: [
{ id: undefined, elements: undefined, appState: undefined },
{ id: undefined, elements: undefined, appState: undefined },
],
});
assert.equal(snapshot.elements[0].cache.raw, "[[file|label]]");
assert.deepEqual(f.history, { undoStack: [{}], redoStack: [{}, {}] });
@@ -117,3 +123,30 @@ test("missing and hidden history controls remain unavailable evidence and cyclic
assert.equal(snapshot.history.source, "not exposed by public API");
assert.doesNotThrow(() => JSON.stringify(snapshot));
});
test("text fixture awaits the normal mode reload before clearing the replacement API", async () => {
const calls = [];
const api = {
updateScene: () => calls.push("clear scene"),
history: { clear: () => calls.push("clear history") },
setActiveTool: () => calls.push("text tool"),
};
const view = { textMode: "parsed", excalidrawData: { textMode: "parsed" },
excalidrawAPI: {}, containerEl: { querySelector: () => ({ getBoundingClientRect: () => ({ x: 0, y: 0, width: 100, height: 80 }) }) },
async changeTextMode(...args) {
assert.deepEqual(args, ["raw"], "reload=false would leave the model parsed");
calls.push("reload"); await Promise.resolve();
this.textMode = this.excalidrawData.textMode = "raw";
this.excalidrawAPI = api;
} };
const result = await prepareTextUndoFixture(view, "raw");
assert.deepEqual(calls, ["reload", "clear scene", "clear history", "text tool"]);
assert.deepEqual(result.modeSetup.after, { view: "raw", model: "raw" });
assert.deepEqual({ x: result.x, y: result.y }, { x: 50, y: 40 });
});
test("incoherent text modes fail before scene or history mutation", async () => {
const view = { textMode: "raw", excalidrawData: { textMode: "parsed" },
async changeTextMode() {} };
await assert.rejects(prepareTextUndoFixture(view, "raw"), /did not synchronize/);
});
+8
View File
@@ -62,6 +62,9 @@ if (
const fullProfile = profile === "full" || profile === "regression";
const coreOnly=process.argv.includes("--core"),coreScenarios=fullProfile||coreOnly;
const lifecycle = coreScenarios || process.argv.includes("--lifecycle");
const migrationComparison = process.argv.includes("--migration-comparison");
if (fullProfile && migrationComparison)
throw Error("Migration comparison is a focused diagnostic, not a full-profile replacement");
const extrasServices =
coreScenarios || process.argv.includes("--extras-services");
const devices =
@@ -121,6 +124,7 @@ const flags = [
"--prepare-only",
"--behavior-matrix",
"--lifecycle",
"--migration-comparison",
"--extras-services",
"--devices",
"--data-integrity",
@@ -267,6 +271,10 @@ try {
]
: []),
...(lifecycle ? [runLifecycleScenario] : []),
...(migrationComparison ? [
context => runLifecycleScenario(context),
context => runLifecycleScenario(context, { migrationRoute: "host-drag" }),
] : []),
...(extrasServices ? [runExtrasServicesScenario] : []),
...(dataIntegrity ? [runDataIntegrityScenario] : []),
...(workflowFixes ? [runWorkflowFixesScenario] : []),