Capture exact text-history action, control readiness and owning scene state

This commit is contained in:
zsviczian committed 2026-10-29 21:44:27 +01:00
1 parent f240fb86db
commit 65f63a3049
5 files changed
+523 -60

No files matched your search

+10
View File
@@ -3180,3 +3180,13 @@ remain strict pending maintainer classification; no production changes.
work and left all PRs draft. Highest-risk next checks are exact text-action DOM
readiness and migration on an approved host containing the related Electron
fix; physical touch and other native desktop OSes remain separate validation.
- 2026-10-29 (#3022): Verified clean reviewed heads f240fb86 / 053a3b9 / 1cdcb7c
and exclusive foreground access. Added read-only text-history snapshots for
exact variant/action, owning window, active target/layout, control state and
actual owning-App stack lengths. The immediate control check and every text/
history assertion remain unchanged. Failure-only passive samples observe late
readiness without retrying input or turning failure into success. Two offline
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.
+250 -60
View File
@@ -1,55 +1,116 @@
/** Issue #2976: exercise actual text input and history on the runner's owned drawing. */
import assert from "node:assert/strict";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { captureTextUndoState } from "./textUndoDiagnostics.mjs";
/**
* 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.
* The parent runner owns target guards, deployment, drawing cleanup and error checks.
*/
export async function runTextUndoScenario({ cli, drawingPath }) {
export async function runTextUndoScenario({ cli, drawingPath, reportDir }) {
const viewCode = `app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===${JSON.stringify(drawingPath)})?.view`;
const evaluate = code => JSON.parse(cli("eval", `code=${code}`).trim().replace(/^=>\s*/, ""));
const cdp = (method, params) => cli("dev:cdp", `method=${method}`, `params=${JSON.stringify(params)}`);
const evaluate = (code) =>
JSON.parse(
cli("eval", `code=${code}`)
.trim()
.replace(/^=>\s*/, ""),
);
const cdp = (method, params) =>
cli("dev:cdp", `method=${method}`, `params=${JSON.stringify(params)}`);
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 wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const observations = { version: 1, actions: [], completedVariants: [] };
let variantLabel, actionLabel;
const inspect = () =>
evaluate(
`JSON.stringify((${captureTextUndoState.toString()})(${viewCode},app.workspace))`,
);
const persist = () => {
if (reportDir)
writeFileSync(
join(reportDir, "text-history-evidence.json"),
JSON.stringify(observations, null, 2) + "\n",
);
};
async function poll(predicate, label) {
const deadline = Date.now() + 10_000;
for (;;) {
const value = snapshot();
if (predicate(value)) return value;
if (Date.now() >= deadline) throw new Error(`${label}: ${JSON.stringify(value)}`);
if (Date.now() >= deadline)
throw new Error(`${label}: ${JSON.stringify(value)}`);
await wait(100);
}
}
function key(key, code, keyCode, modifiers = 0) {
for (const type of ["keyDown", "keyUp"]) {
cdp("Input.dispatchKeyEvent", { type, key, code, windowsVirtualKeyCode: keyCode, modifiers });
cdp("Input.dispatchKeyEvent", {
type,
key,
code,
windowsVirtualKeyCode: keyCode,
modifiers,
});
}
}
const modifier = process.platform === "darwin" ? 4 : 2;
const enter = async () => {
// Toolbar history can leave focus on a button or restore an unselected scene.
// Select the fixture's text before testing a new editing session.
evaluate(`(()=>{const v=${viewCode};const a=v.excalidrawAPI;const e=a.getSceneElements().find(e=>e.type==="text");if(!e)throw Error("fixture text missing");a.updateScene({appState:{selectedElementIds:{[e.id]:true}},captureUpdate:"NEVER"});v.containerEl.querySelector(".excalidraw")?.focus();return JSON.stringify({selected:true})})()`);
await poll(value => value.selected?.[value.elements[0]?.id], "fixture selection did not settle");
evaluate(
`(()=>{const v=${viewCode};const a=v.excalidrawAPI;const e=a.getSceneElements().find(e=>e.type==="text");if(!e)throw Error("fixture text missing");a.updateScene({appState:{selectedElementIds:{[e.id]:true}},captureUpdate:"NEVER"});v.containerEl.querySelector(".excalidraw")?.focus();return JSON.stringify({selected:true})})()`,
);
await poll(
(value) => value.selected?.[value.elements[0]?.id],
"fixture selection did not settle",
);
key("Enter", "Enter", 13);
};
const escape = () => key("Escape", "Escape", 27);
function click(point) {
for (const type of ["mousePressed", "mouseReleased"]) {
cdp("Input.dispatchMouseEvent", { type, ...point, button: "left", clickCount: 1 });
cdp("Input.dispatchMouseEvent", {
type,
...point,
button: "left",
clickCount: 1,
});
}
}
function history(action, input) {
function history(action, input, stage) {
actionLabel = stage;
const state = inspect();
observations.actions.push({
variant: variantLabel,
action,
input,
stage,
state,
});
persist();
if (input === "keyboard") {
key("z", "KeyZ", 90, modifier | (action === "redo" ? 8 : 0));
} else {
const point = evaluate(`(()=>{const v=${viewCode};const b=v.containerEl.querySelector(${JSON.stringify(`button[data-testid="button-${action}"]`)});if(!b||b.disabled)throw Error("history button unavailable");const r=b.getBoundingClientRect();return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2})})()`);
const button = state.controls[action];
if (!button.present || button.disabled)
throw Error(`${variantLabel}: ${stage}: history button unavailable`);
const point = {
x: button.bounds.x + button.bounds.width / 2,
y: button.bounds.y + button.bounds.height / 2,
};
click(point);
}
}
function assertSource(value, expected, label, cache = false, display = expected) {
function assertSource(
value,
expected,
label,
cache = false,
display = expected,
) {
assert.equal(value.elements.length, 1, label);
const element = value.elements[0];
assert.equal(element.text, display, `${label}: rendered text`);
@@ -57,67 +118,196 @@ export async function runTextUndoScenario({ cli, drawingPath }) {
assert.equal(element.rawText, expected, `${label}: raw source`);
if (cache) {
assert.equal(element.cache.raw, expected, `${label}: cached source`);
if (display !== expected) assert.equal(element.cache.parsed, display, `${label}: cached display`);
if (display !== expected)
assert.equal(element.cache.parsed, display, `${label}: cached display`);
}
}
async function reopenAndSubmit(expected, label, display = expected) {
await enter();
const opened = await poll(value => value.editor !== null, `${label}: editor did not open`);
const opened = await poll(
(value) => value.editor !== null,
`${label}: editor did not open`,
);
assert.equal(opened.editor, expected, `${label}: editor source`);
assertSource(opened, expected, label);
escape();
const submitted = await poll(value => value.editor === null, `${label}: editor did not close`);
assertSource(submitted, expected, `${label}: unchanged submission`, true, display);
const submitted = await poll(
(value) => value.editor === null,
`${label}: editor did not close`,
);
assertSource(
submitted,
expected,
`${label}: unchanged submission`,
true,
display,
);
}
const cases = [];
const variants = [
{ name: "plain", first: "one", second: "two", third: "three" },
{ name: "wikilink", first: "[[link]]", second: "[[other]]", third: "[[changed]]" },
{ name: "extra-bracket", first: "[[link]]]", second: "[[other]]]", third: "[[changed]]]" },
{ name: "alias", first: "[[link|one]]", second: "[[other|two]]", third: "[[changed|three]]" },
{
name: "wikilink",
first: "[[link]]",
second: "[[other]]",
third: "[[changed]]",
},
{
name: "extra-bracket",
first: "[[link]]]",
second: "[[other]]]",
third: "[[changed]]]",
},
{
name: "alias",
first: "[[link|one]]",
second: "[[other|two]]",
third: "[[changed|three]]",
},
];
for (const mode of ["parsed", "raw"]) {
for (const input of ["keyboard", "button"]) {
for (const variant of variants) {
const label = `${mode}/${input}/${variant.name}`;
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})})()`);
click(point);
await poll(value => value.editor !== null, `${label}: new text editor`);
cdp("Input.insertText", { text: variant.first });
escape();
const first = await poll(value => value.editor === null, `${label}: first submission`);
const firstDisplay = mode === "parsed" ? first.elements[0].cache.parsed : variant.first;
assertSource(first, variant.first, label, true, firstDisplay);
await enter();
await poll(value => value.editor === variant.first, `${label}: edit first text`);
cdp("Input.insertText", { text: variant.second });
escape();
const second = await poll(value => value.editor === null, `${label}: second submission`);
const secondDisplay = mode === "parsed" ? second.elements[0].cache.parsed : variant.second;
assertSource(second, variant.second, label, true, secondDisplay);
history("undo", input);
assertSource(await poll(value => value.elements[0]?.rawText === variant.first, `${label}: undo`), variant.first, label, false, firstDisplay);
await reopenAndSubmit(variant.first, `${label}: after undo`, firstDisplay);
history("redo", input);
assertSource(await poll(value => value.elements[0]?.rawText === variant.second, `${label}: redo`), variant.second, label, false, secondDisplay);
await reopenAndSubmit(variant.second, `${label}: after redo`, secondDisplay);
history("undo", input);
await poll(value => value.elements[0]?.rawText === variant.first, `${label}: second undo`);
await enter();
await poll(value => value.editor === variant.first, `${label}: edit after undo`);
cdp("Input.insertText", { text: variant.third });
escape();
const third = await poll(value => value.editor === null, `${label}: edited submission`);
const thirdDisplay = mode === "parsed" ? third.elements[0].cache.parsed : variant.third;
assertSource(third, variant.third, label, true, thirdDisplay);
cases.push(label);
try {
for (const mode of ["parsed", "raw"]) {
for (const input of ["keyboard", "button"]) {
for (const variant of variants) {
const label = `${mode}/${input}/${variant.name}`;
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})})()`,
);
click(point);
await poll(
(value) => value.editor !== null,
`${label}: new text editor`,
);
cdp("Input.insertText", { text: variant.first });
escape();
const first = await poll(
(value) => value.editor === null,
`${label}: first submission`,
);
const firstDisplay =
mode === "parsed" ? first.elements[0].cache.parsed : variant.first;
assertSource(first, variant.first, label, true, firstDisplay);
await enter();
await poll(
(value) => value.editor === variant.first,
`${label}: edit first text`,
);
cdp("Input.insertText", { text: variant.second });
escape();
const second = await poll(
(value) => value.editor === null,
`${label}: second submission`,
);
const secondDisplay =
mode === "parsed"
? second.elements[0].cache.parsed
: variant.second;
assertSource(second, variant.second, label, true, secondDisplay);
history("undo", input, "first undo");
assertSource(
await poll(
(value) => value.elements[0]?.rawText === variant.first,
`${label}: undo`,
),
variant.first,
label,
false,
firstDisplay,
);
await reopenAndSubmit(
variant.first,
`${label}: after undo`,
firstDisplay,
);
history("redo", input, "redo after unchanged undo submission");
assertSource(
await poll(
(value) => value.elements[0]?.rawText === variant.second,
`${label}: redo`,
),
variant.second,
label,
false,
secondDisplay,
);
await reopenAndSubmit(
variant.second,
`${label}: after redo`,
secondDisplay,
);
history("undo", input, "second undo after unchanged redo submission");
await poll(
(value) => value.elements[0]?.rawText === variant.first,
`${label}: second undo`,
);
await enter();
await poll(
(value) => value.editor === variant.first,
`${label}: edit after undo`,
);
cdp("Input.insertText", { text: variant.third });
escape();
const third = await poll(
(value) => value.editor === null,
`${label}: edited submission`,
);
const thirdDisplay =
mode === "parsed" ? third.elements[0].cache.parsed : variant.third;
assertSource(third, variant.third, label, true, thirdDisplay);
cases.push(label);
observations.completedVariants.push(label);
persist();
}
}
}
const source = snapshot().elements[0].rawText;
const fallback = evaluate(
`(()=>{const v=${viewCode};const e=v.excalidrawAPI.getSceneElements().find(e=>e.type==="text");return JSON.stringify({legacy:v.onBeforeTextEdit({...e,rawText:undefined},true),empty:v.onBeforeTextEdit({...e,rawText:""},true)})})()`,
);
assert.equal(fallback.legacy, source, "legacy cache fallback");
assert.equal(
fallback.empty,
"",
"empty scene source remains authoritative",
);
observations.status = "passed";
persist();
return {
id: "text-undo-2976",
status: "passed",
cases,
observations,
assertions: [
"reopened source after undo/redo",
"unchanged submission refreshes cache",
"editing after undo",
"parsed Markdown source",
"legacy and empty source",
],
};
} catch (error) {
observations.status = "failed";
observations.failure = {
variant: variantLabel,
stage: actionLabel,
message: error.message,
};
// Observe eventual readiness without issuing input or converting the failed
// immediate check into a pass. This establishes evidence for a later wait.
try {
observations.terminal = inspect();
observations.passiveAfterFailure = [];
for (const delay of [50, 200, 750]) {
await wait(delay);
observations.passiveAfterFailure.push(inspect());
}
} catch (captureError) {
observations.captureError = String(captureError);
}
error.observations = observations;
persist();
throw error;
}
const source = snapshot().elements[0].rawText;
const fallback = evaluate(`(()=>{const v=${viewCode};const e=v.excalidrawAPI.getSceneElements().find(e=>e.type==="text");return JSON.stringify({legacy:v.onBeforeTextEdit({...e,rawText:undefined},true),empty:v.onBeforeTextEdit({...e,rawText:""},true)})})()`);
assert.equal(fallback.legacy, source, "legacy cache fallback");
assert.equal(fallback.empty, "", "empty scene source remains authoritative");
return { id: "text-undo-2976", status: "passed", cases,
assertions: ["reopened source after undo/redo", "unchanged submission refreshes cache", "editing after undo", "parsed Markdown source", "legacy and empty source"] };
}
@@ -0,0 +1,140 @@
/** Read-only native text-history evidence. Serialized into the owned vault only. */
export function captureTextUndoState(view, workspace) {
const doc = view?.containerEl?.ownerDocument;
const win = doc?.defaultView;
const api = view?.excalidrawAPI;
const root = view?.containerEl?.querySelector(".excalidraw");
const rect = (element) => {
if (!element) return null;
const r = element.getBoundingClientRect();
return { x: r.x, y: r.y, width: r.width, height: r.height };
};
const controls = Object.fromEntries(
["undo", "redo"].map((action) => {
const button = view?.containerEl?.querySelector(
`button[data-testid="button-${action}"]`,
);
// Read presence/enabled state before layout measurements. No rendering,
// focus, event, history or store method is invoked by this diagnostic.
const present = !!button,
disabled = button?.disabled ?? null;
const bounds = rect(button);
const style = button && win?.getComputedStyle(button);
const visible =
!!bounds &&
bounds.width > 0 &&
bounds.height > 0 &&
style?.display !== "none" &&
style?.visibility !== "hidden";
const hit =
bounds &&
doc.elementFromPoint(
bounds.x + bounds.width / 2,
bounds.y + bounds.height / 2,
);
return [
action,
{
present,
disabled,
visible,
display: style?.display,
visibility: style?.visibility,
bounds,
covered: !!button && hit?.closest?.("button") !== button,
},
];
}),
);
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.
const key =
root && Object.keys(root).find((k) => k.startsWith("__reactFiber$"));
let fiber = key && root[key];
const visited = new Set();
for (
let i = 0;
fiber && i < 128 && !visited.has(fiber);
i++, fiber = fiber.return
) {
visited.add(fiber);
const candidate = fiber.stateNode?.history;
if (
Array.isArray(candidate?.undoStack) &&
Array.isArray(candidate?.redoStack)
) {
history = {
source: "read-only owning App fiber",
undoDepth: candidate.undoStack.length,
redoDepth: candidate.redoStack.length,
};
break;
}
}
let ownerContentsId;
try {
ownerContentsId = win
?.require?.("@electron/remote")
.getCurrentWebContents().id;
} catch {
/* Ownership still has document/main-window evidence below. */
}
const state = api?.getAppState();
return {
at: Date.now(),
targetDrawing: view?.file?.path,
owner: {
contentsId: ownerContentsId,
main: doc === workspace.containerEl.ownerDocument,
closed: win?.closed,
focused: doc?.hasFocus(),
viewport: { width: win?.innerWidth, height: win?.innerHeight },
},
activeLeaf: {
id: workspace.activeLeaf?.id,
type: workspace.activeLeaf?.view?.getViewType?.(),
file: workspace.activeLeaf?.view?.file?.path,
},
activeEditor: {
type: workspace.activeEditor?.getViewType?.(),
file: workspace.activeEditor?.file?.path,
editor: !!workspace.activeEditor?.editor,
},
layout: workspace.getLayout(),
root: { classes: root?.className, bounds: rect(root) },
editorInterface: api?.getEditorInterface?.(),
controls,
history,
viewState: {
textMode: view?.textMode,
compatibilityMode: view?.compatibilityMode,
dirty: view?.isDirty?.(),
closing: view?.isClosingOrMigrating?.(),
},
state: {
viewModeEnabled: state?.viewModeEnabled,
activeTool: state?.activeTool,
editingTextId: state?.editingTextElement?.id,
selectedElementIds: state?.selectedElementIds,
},
elements: api
?.getSceneElementsIncludingDeleted()
.map((e) => ({
id: e.id,
type: e.type,
isDeleted: e.isDeleted,
version: e.version,
text: e.text,
originalText: e.originalText,
rawText: e.rawText,
cache:
e.type === "text"
? view.excalidrawData.getParsedResult(e.id)
: undefined,
})),
editor:
view?.containerEl?.querySelector("textarea.excalidraw-wysiwyg")?.value ??
null,
};
}
@@ -0,0 +1,119 @@
import assert from "node:assert/strict";
import test from "node:test";
import { captureTextUndoState } from "./textUndoDiagnostics.mjs";
function fixture() {
const history = { undoStack: [{}], redoStack: [{}, {}] };
const button = (x, disabled) => ({
disabled,
bounds: { x, y: 10, width: 30, height: 20 },
getBoundingClientRect() {
return this.bounds;
},
closest() {
return this;
},
});
const undo = button(10, false),
redo = button(50, true);
const root = {
className: "excalidraw",
getBoundingClientRect: () => ({ x: 0, y: 0, width: 800, height: 600 }),
__reactFiber$owned: { return: { stateNode: { history } } },
};
const win = {
closed: false,
innerWidth: 800,
innerHeight: 600,
getComputedStyle: () => ({ display: "block", visibility: "visible" }),
require: () => ({ getCurrentWebContents: () => ({ id: 42 }) }),
};
const doc = {
defaultView: win,
hasFocus: () => true,
elementFromPoint: (x) => (x < 50 ? undo : redo),
};
const element = {
id: "owned",
type: "text",
text: "label",
originalText: "label",
rawText: "[[file|label]]",
version: 2,
};
const query = (selector) =>
selector === ".excalidraw"
? root
: selector.includes("button-undo")
? undo
: selector.includes("button-redo")
? redo
: null;
const view = {
file: { path: "__excalidraw_cli_smoke_owned.md" },
textMode: "parsed",
compatibilityMode: false,
isDirty: () => true,
isClosingOrMigrating: () => false,
containerEl: { ownerDocument: doc, querySelector: query },
excalidrawData: {
getParsedResult: () => ({ raw: element.rawText, parsed: element.text }),
},
excalidrawAPI: {
getAppState: () => ({
viewModeEnabled: false,
selectedElementIds: { owned: true },
}),
getSceneElementsIncludingDeleted: () => [element],
getEditorInterface: () => ({ formFactor: "desktop" }),
},
};
const workspace = {
containerEl: { ownerDocument: doc },
activeLeaf: {
id: "other",
view: { file: { path: "Notes/Other.md" }, getViewType: () => "markdown" },
},
getLayout: () => ({ active: "other", main: { id: "split" } }),
};
return { history, undo, redo, root, win, doc, view, workspace };
}
test("text-history diagnostics preserve owning window, leaked active target, controls and actual stack depths without mutation", () => {
const f = fixture(),
snapshot = captureTextUndoState(f.view, f.workspace);
assert.equal(snapshot.owner.contentsId, 42);
assert.equal(snapshot.owner.main, true);
assert.equal(snapshot.activeLeaf.file, "Notes/Other.md");
assert.equal(snapshot.targetDrawing, f.view.file.path);
assert.equal(snapshot.controls.undo.disabled, false);
assert.equal(snapshot.controls.redo.disabled, true);
assert.equal(snapshot.controls.undo.visible, true);
assert.deepEqual(snapshot.history, {
source: "read-only owning App fiber",
undoDepth: 1,
redoDepth: 2,
});
assert.equal(snapshot.elements[0].cache.raw, "[[file|label]]");
assert.deepEqual(f.history, { undoStack: [{}], redoStack: [{}, {}] });
assert.doesNotThrow(() => JSON.stringify(snapshot));
});
test("missing and hidden history controls remain unavailable evidence and cyclic private fibers stay bounded", () => {
const f = fixture(),
original = f.view.containerEl.querySelector;
f.view.containerEl.querySelector = (selector) =>
selector.includes("button-redo") ? null : original(selector);
f.undo.bounds.width = 0;
f.win.getComputedStyle = () => ({ display: "none", visibility: "hidden" });
const cyclic = {};
cyclic.return = cyclic;
f.root["__reactFiber$owned"] = cyclic;
const snapshot = captureTextUndoState(f.view, f.workspace);
assert.equal(snapshot.controls.redo.present, false);
assert.equal(snapshot.controls.redo.disabled, null);
assert.equal(snapshot.controls.redo.visible, false);
assert.equal(snapshot.controls.undo.visible, false);
assert.equal(snapshot.history.source, "not exposed by public API");
assert.doesNotThrow(() => JSON.stringify(snapshot));
});
+4
View File
@@ -2497,6 +2497,10 @@
"path": "scripts/testing/host/stability.test.mjs",
"mode": "isolated-or-extracted"
},
{
"path": "scripts/testing/host/textUndoDiagnostics.test.mjs",
"mode": "direct-module-or-tooling"
},
{
"path": "scripts/testing/hostContracts.test.mjs",
"mode": "isolated-or-extracted"