Refine local-vault native behavior evidence and host cleanup

This commit is contained in:
zsviczian committed 2026-10-29 07:00:54 +01:00
1 parent de5f791c80
commit b8b2273930
20 files changed
+1197 -147

No files matched your search

+27
View File
@@ -3016,3 +3016,30 @@ Pushed the existing branches: plugin `d7d9a355efdf07fe1f47ded0f7e32f5c6b1225bf`,
A subsequent native-only assertion review removes a substituted PNG padding: every export row now uses its actual requested padding, compares SVG dimension changes against an independent padding control, and checks decoded PNG dimensions within integer pixel rounding. These strengthened assertions are syntax-checked but remain unexecuted. The required native denominator is 351 IDs, including seven actual plugin-command cases; all require fresh evidence.
The installed repository-local vault still awaits one-time Obsidian opening/trust/CLI registration. No native workflow, real PDF inspection or complete repeated native run is claimed. All three PRs remain draft and their bodies explain this unfinished state. Highest-risk checks remain active Live Preview, zero/false precedence, asynchronous source/crop updates and trusted command/EA targeting in popouts and phone/tablet emulation. Physical devices and other desktop operating systems remain separate environments.
### 2026-10-29 � Local-vault native execution and test-tooling corrections (#3022)
The maintainer completed local-vault registration/trust. A fresh real plugin?Extras
PDF passed completion, cleanup, PDF.js text/page/pixel checks and independent
visual inspection (10,610 bytes, one 288 � 216 pt page). The initial occluded-display
render deadline remains failed evidence; test PDF decoding now uses print intent.
The plugin fast suite passes 462 cases. The current denominator is 258 behavioral
cases and 357 native cases overall, including the accepted frame-padding policy.
Corrected test-only metadata readiness, supported EA zoom use, opacity-aware
pixel assertions, visible Markdown-root selection, individual wheel completion,
command labels/shortcut badges, wrapped-link hit targets and native console-object
inspection. Renderer scheduling and focus emulation are scoped and recorded.
Desktop execution exposed the already-known destroyed-popout promise hazard;
recovery and failed evidence are retained. Behavior cleanup now uses the existing
lifecycle close-window pattern. A focused eight-case split/popout run passes
business assertions and cleanup but fails the ResizeObserver error gate. No
errors were filtered. Plain PDF TFile input and Helvetica Markdown-image diagnostics
are reported for maintainer classification. Production-diff audit still permits
only the Extras PDF timeout/lock rollback; plugin/fork runtime is unchanged.
Remaining: complete mobile/core workflows, fresh full portable verification, two
complete matching-build native passes, final evidence/counts and PR updates. The
highest-risk checks are trusted palette/shortcuts and actual embed/settings flows
in narrow/mobile panes, plus popout teardown and error-free surviving-editor saves.
Physical devices and macOS/Linux remain separate environments.
+38 -5
View File
@@ -67,7 +67,7 @@ directories. `npm.cmd` / `yarn.cmd` avoid blocked PowerShell `.ps1` shims.
`tests/features.json.behaviorMatrix` defines all factor domains, reviewed
expected results/assertions, case templates and required context-specific IDs.
There are currently **252 additional required behavioral cases** across main,
There are currently **258 additional required behavioral cases** across main,
ordinary split, nested split, popout, emulated phone and emulated tablet contexts.
Six of these use actual plugin CLI `read`/`apply` transport; the other host cases
use native EA/renderers and trusted CDP input as applicable. Fifteen popout
@@ -114,7 +114,7 @@ live-configuration tooling case). Later follow-ups strengthen only native export
geometry assertions and update documentation; these native assertions remain
unexecuted until the local-vault prerequisite is completed.
The required native denominator is **351 cases**: 311 core/behavior/drop cases
The required native denominator is **357 cases**: 317 core/behavior/drop cases
and 40 device/layout cases. Seven of these IDs exercise actual plugin CLI
commands; host/EA/input cases and emulated contexts are counted separately in
reports. The 84 historical native IDs are recorded as omitted by the portable
@@ -125,10 +125,10 @@ follow-up; neither count nor implementation substitutes for execution.
| --- | --- |
| PDF timeout/lock rollback | Source regression passes; completion remains event-driven |
| Delay beyond two minutes | Controlled clock passes at 120001 ms and a further 15 minutes; resources remain owned until completion |
| Real plugin?Extras PDF and decoded-page inspection | **Pending** in the local vault |
| Real plugin?Extras PDF and decoded-page inspection | **Passed**, `opened-single-pdf-repeat/`: one page, 288 � 216 pt, preserved text and 3330 red pixels |
| Actual installed plugin and Extras files | Present and hash-verified; latest preparation/provenance must be refreshed after changes |
| One-time local vault registration/trust | **Pending**; no fallback permitted |
| 252 cross-context behavioral cases | Implemented, **unexecuted** |
| One-time local vault registration/trust | **Completed** by maintainer; native canonical-path verification passes |
| 258 cross-context behavioral cases | Desktop execution/debugging in progress; phone/tablet and complete acceptance pending |
| 15 additional popout drop variants | Required, **unexecuted** |
| Two complete matching-build native runs | **Pending** |
| Follow-up production diff | Pass: plugin/fork runtime unchanged; Extras PDF rollback only |
@@ -294,3 +294,36 @@ The optional inherited diagnostic preserves its own failures and is available
through manual workflow dispatch. It is not a required PR job. Workflows upload
their reports even on failure. Ordinary hosted CI never launches Obsidian or
accesses vaults.
## Native execution checkpoint, 2026-10-29
Reports under the ignored working tree retain source/diff identities, artifact
hashes, all failures and cleanup evidence. The plugin artifact remains 5,029,887
bytes with SHA-256 `676808bf603c5169886a25a7b4d5b193e32e1c580276bc078b832516aab048fd`;
Extras remains `28f3c966b44bb35881b98d05f3fc327163b170b51bcdb3af13821c427015c8bb`.
- `opened-single-pdf-repeat/`: real gateway/export, decoded output and cleanup
pass. Retained `native-single-export.pdf` is 10,610 bytes; SHA-256
`7e93eafebb3710df05efce6697ae39287b4c9348038c1255e53dd7a7a6ef1bc8`.
Its decoded page was also visually inspected. An earlier tooling display-render
deadline remains recorded as failed; PDF.js print intent avoids waiting for a
display animation frame in an occluded renderer. This changes test tooling only.
- `follow-up-fast/`: 462 tests in 51 files pass, including four additional
tooling regressions since the 458-case portable checkpoint. A fresh full
portable aggregate is still required before reporting a new aggregate count.
- `behavior-desktop-contexts/`: broad desktop execution; the failed popout
cleanup awaited a promise whose realm Obsidian destroyed. Failed evidence and
guarded recovery are retained. Only the verified local-vault renderer was
reloaded after proving no native print resources remained. The task was not
reported as settled or passed.
- `behavior-split-popout-targeted/`: eight real behavior cases pass; cleanup
passes; acceptance fails on ResizeObserver notifications. No error filtering.
The padding oracle follows the maintainer decision: frame-enabled exports retain
their existing no-padding policy; explicit padding cases disable frame rendering.
A separate policy case runs in every context. Behavior input scopes background
throttling and CDP focus emulation to its owned renderer, records actual mode and
geometry, then restores scheduling. This is trusted CDP input with emulated page
focus, not physical OS-focus, touch or drag evidence. Lifecycle tests keep their
own focus semantics. Popout error capture uses the same strict combined oracle;
expected missing-asset ENOENT diagnostics require the exact owned path and count.
+48
View File
@@ -88,3 +88,51 @@ tests exercise real production/development artifacts. Native tests exercise real
Obsidian CLI, EA, file persistence and decoded exports. Reports keep those forms
of evidence distinct. Physical mobile and other operating systems require their
own validation; desktop emulation does not establish those environments.
## F10 � Plain PDF TFile input: classification pending
In `behavior-main-scheduled/report.json`, `EA.addImage(x,y,pdfTFile)`
reproduces a loader error followed by a null-size exception. The API documents
`TFile | string`, and the loader defaults the page to 1, but its crop parsing
reads `linkParts.ref.split(...)` when ref is null. An explicit
`pdfTFile.path + '#page=1'` works and is used in the valid-reference workflow.
The maintainer has been asked whether plain PDF TFile input should load page 1
or whether an explicit page reference is the accepted requirement. Production
code is unchanged; this finding is not a passing invalid-input contract.
## F11 � System-font Markdown image: classification pending
The same native report records `Failed to fetch font "Helvetica" from urls "" []`
for Markdown-image frontmatter `excalidraw-font: Helvetica`. The plugin comment
expects an empty CSS definition for that system font; the fork font-content
helper instead reports the empty source list. Bundled Excalifont is the valid
font used by the rendering workflow. The maintainer has been asked whether the
system-font diagnostic is intended fallback behavior or a defect. No production
change or exception allowlist has been introduced for it.
## F12 � Native tooling teardown and layout diagnostics
The broad desktop run `behavior-desktop-contexts/` closed the final popout via
`await leaf.setViewState({type:'empty'})`. Obsidian destroyed that renderer while
the promise remained pending, the same host limitation already documented in the
lifecycle helper. It also produced repeated primitive illegal-access exceptions.
The failed run was retained. Guarded recovery verified renderer 252 was destroyed,
that no print DOM remained, then reloaded only the canonical local-vault renderer
250 and removed the exact two owned scenario paths. No native print was cancelled;
the orphaned promise was not represented as settled.
The behavior cleanup now follows the existing lifecycle pattern: physically save
if dirty, close the owning popout window, and wait from the main realm for actual
host teardown. A focused split/popout repeat completed all eight business cases
and cleanup without that stranded promise, but failed the strict error gate on
ResizeObserver notifications. This remains a failed run, not a waived host error.
Test input was also unnecessarily scrolling already-visible fixed controls; the
next run checks targeted input without those extra layout changes. Reproduce and
classify any residual before proposing a production change.
## Maintainer decision � Export padding and frames
Frame-enabled SVG/PNG exports suppress padding even without frame elements. The
maintainer confirmed this is intended. Padding combinations explicitly disable
frame rendering, and a separate default/enabled policy case protects the existing
behavior in each context. No production modification is needed.
+10
View File
@@ -99,6 +99,16 @@ export const exportCases = pairwise(exportFactors, [
}));
export const workflowCases = [
{
id: "export-frame-padding-policy",
features: ["P06", "P09"],
assertions: [
"default frame rendering suppresses padding, including scenes without frames",
"disabling frame rendering enables the requested padding",
"actual SVG and decoded PNG dimensions agree",
"saved scene survives reopen",
],
},
{
id: "cli-atomic-targeted-edit",
features: ["P03", "P07", "P10"],
+182 -22
View File
@@ -1,5 +1,11 @@
/** Serialized only into the owned native vault; shared setup never substitutes for behavioral assertions. */
export async function behaviorEnvironment(c, parentPath, context, template) {
export async function behaviorEnvironment(
c,
parentPath,
context,
template,
completeConsoleErrors,
) {
const p = app.plugins.plugins["obsidian-excalidraw-plugin"],
mainDoc = app.workspace.containerEl.ownerDocument;
const check = (condition, label) => {
@@ -9,10 +15,12 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
parentPath.startsWith("__excalidraw_cli_smoke_"),
"Unowned behavior fixture",
);
const runId = parentPath.match(
/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,
)?.[0];
check(runId, "Owned behavior parent has no run identity");
const prefix =
parentPath.replace(/\.(excalidraw\.md|excalidraw|md)$/, "") +
"_behavior_" +
context.id;
"__excalidraw_cli_smoke_" + runId.slice(0, 8) + "_behavior_" + context.id;
check(!app.vault.getFolderByPath(prefix), "Behavior fixture collision");
await app.vault.createFolder(prefix);
const owned = new Set(),
@@ -25,8 +33,19 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
"Behavior cleanup save failed",
);
if (leaf.view?.containerEl.isConnected) {
await leaf.setViewState({ type: "empty", state: {} });
leaf.detach();
const owner = leaf.view.containerEl.ownerDocument.defaultView;
if (owner !== mainDoc.defaultView && !owner.closed) {
// Match the lifecycle suite: the final tab can destroy the realm
// owning setViewState's promise. Observe actual host teardown instead.
owner.close();
await c.waitForCleanup(
() => owner.closed,
"owned behavior popout teardown",
);
} else {
await leaf.setViewState({ type: "empty", state: {} });
leaf.detach();
}
}
}
const folder = app.vault.getFolderByPath(prefix);
@@ -114,27 +133,54 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
.require("@electron/remote")
.getCurrentWebContents();
const errors = [];
c.externalConsoleErrors = errors;
if (ownerContents.id !== mainContents.id) {
check(
!ownerContents.debugger.isAttached(),
"Behavior popout already has a debugger owner",
);
const background = ownerContents.getBackgroundThrottling();
ownerContents.setBackgroundThrottling(false);
c.defer(() => {
if (!ownerContents.isDestroyed())
ownerContents.setBackgroundThrottling(background);
});
ownerContents.debugger.attach("1.3");
const listener = (_event, method, params) => {
if (method === "Runtime.exceptionThrown")
errors.push(params.exceptionDetails);
errors.push({
kind: "exception",
details: params.exceptionDetails,
messages: [
String(
params.exceptionDetails.exception?.description ??
params.exceptionDetails.text,
),
],
});
if (method === "Runtime.consoleAPICalled" && params.type === "error")
errors.push(params.args);
errors.push({
kind: "console",
overflowArgs: params.args.some((arg) => arg.preview?.overflow)
? params.args
: undefined,
messages: params.args.map(
(arg) =>
String(arg.description ?? arg.value ?? arg.type) +
(arg.preview?.properties
? " " + JSON.stringify(arg.preview.properties)
: ""),
),
});
};
ownerContents.debugger.on("message", listener);
await ownerContents.debugger.sendCommand("Runtime.enable");
c.defer(() => {
c.defer(async () => {
await completeConsoleErrors({ errors, debugger: ownerContents.debugger });
ownerContents.debugger.removeListener("message", listener);
ownerContents.debugger.detach();
check(
errors.length === 0,
"Unexpected popout behavior error: " + JSON.stringify(errors),
);
// The coordinator applies the same strict error/count oracle across
// main and popout captures after owned cleanup has settled.
});
}
const input = (method, params) =>
@@ -143,6 +189,19 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
method,
params,
});
// CLI can address an occluded vault. Make this owned behavioral page active
// for hit testing and layout; lifecycle scenarios keep real focus semantics.
await ownerContents.debugger.sendCommand(
"Emulation.setFocusEmulationEnabled",
{ enabled: true },
);
c.defer(async () => {
if (!ownerContents.isDestroyed())
await ownerContents.debugger.sendCommand(
"Emulation.setFocusEmulationEnabled",
{ enabled: false },
);
});
const key = async (key, code, keyCode, modifiers = 0) => {
for (const type of ["keyDown", "keyUp"])
await input("Input.dispatchKeyEvent", {
@@ -155,17 +214,44 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
};
const click = async (element, button = "left") => {
check(element, "Missing interaction target");
element.scrollIntoView({ block: "nearest", inline: "nearest" });
// Leave already-visible controls in place. Scrolling a fixed toolbar or
// modal input can disturb the surrounding Obsidian workspace layout.
const uncovered = () =>
[...element.getClientRects()].some(
(r) =>
r.width > 0 &&
r.height > 0 &&
element.contains(
doc.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2),
),
);
if (!uncovered())
element.scrollIntoView({
block: element.tagName === "A" ? "center" : "nearest",
inline: "nearest",
});
let x, y;
await c.waitFor(() => {
const r = element.getBoundingClientRect();
x = r.x + r.width / 2;
y = r.y + r.height / 2;
return (
r.width > 0 &&
r.height > 0 &&
element.contains(doc.elementFromPoint(x, y))
);
// Wrapped inline links have a bounding-box center outside their text.
for (const r of element.getClientRects()) {
x = r.x + r.width / 2;
y = r.y + r.height / 2;
if (
r.width > 0 &&
r.height > 0 &&
element.contains(doc.elementFromPoint(x, y))
)
return true;
}
c.caseTrace = {
...c.caseTrace,
clickTarget: {
html: element.outerHTML.slice(0, 700),
bounds: element.getBoundingClientRect().toJSON(),
hit: doc.elementFromPoint(x, y)?.outerHTML.slice(0, 400),
},
};
return false;
}, "visible uncovered behavior control");
if (context.input === "touch" && button === "left") {
await input("Input.dispatchTouchEvent", {
@@ -274,9 +360,30 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
ctx.drawImage(image, 0, 0);
const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
let red = 0,
green = 0,
blue = 0,
transparent = 0;
let redDominant = 0,
halfAlphaRed = 0,
redOverWhite = 0;
const opaqueColors = new Map();
for (let i = 0; i < pixels.length; i += 4) {
const [r, g, b, a] = pixels.subarray(i, i + 4);
if (a && r > g + 30 && r > b + 30) {
redDominant++;
if (a >= 120 && a <= 136) halfAlphaRed++;
}
if (
r === 255 &&
Math.abs(g - 127.5) < 1.6 &&
Math.abs(b - 127.5) < 1.6 &&
a === 255
)
redOverWhite++;
if (a === 255) {
const key = r + "," + g + "," + b;
opaqueColors.set(key, (opaqueColors.get(key) || 0) + 1);
}
if (
pixels[i] > 180 &&
pixels[i + 1] < 90 &&
@@ -285,15 +392,24 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
)
red++;
if (pixels[i + 2] > 180 && pixels[i] < 90 && pixels[i + 3]) blue++;
if (g > 180 && r < 90 && b < 90 && a) green++;
if (!pixels[i + 3]) transparent++;
}
return {
width: canvas.width,
height: canvas.height,
red,
green,
blue,
transparent,
cornerAlpha: pixels[3],
redDominant,
halfAlphaRed,
redOverWhite,
dominantOpaque: [...opaqueColors.entries()]
.sort((a, b) => b[1] - a[1])[0]?.[0]
.split(",")
.map(Number),
};
} finally {
if (typeof source !== "string") win.URL.revokeObjectURL(url);
@@ -310,7 +426,50 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
leafId: leaf.id,
ownerContentsId: ownerContents.id,
mainContentsId: mainContents.id,
visibility: doc.visibilityState,
scopedBackgroundThrottling: ownerContents.getBackgroundThrottling(),
focusEmulation: true,
});
const diagnostics = () => {
const view = leaf.view,
state = view.excalidrawAPI?.getAppState();
return {
file: view.file?.path,
viewType: view.getViewType(),
mode: view.getMode?.(),
actual: geometry(),
camera: state
? {
zoom: state.zoom,
allowWheelZoom: state.allowWheelZoom,
inputDevice: state.inputDevice,
width: state.width,
height: state.height,
viewModeEnabled: state.viewModeEnabled,
}
: null,
canvas: [...view.containerEl.querySelectorAll("canvas")].map((el) => ({
classes: el.className,
bounds: el.getBoundingClientRect().toJSON(),
})),
preview: [
...view.contentEl.querySelectorAll(
".markdown-preview-view,.markdown-preview-sizer",
),
]
.slice(0, 3)
.map((el) => ({
classes: el.className,
bounds: el.getBoundingClientRect().toJSON(),
text: el.textContent.slice(0, 800),
html: el.outerHTML.slice(0, 1800),
})),
palette: [...doc.querySelectorAll(".prompt .suggestion-item")].map(
(el) => el.textContent,
),
trace: c.caseTrace,
};
};
check(
(app.isMobile === true) === ["phone", "tablet"].includes(context.id),
"Behavior context does not match actual Obsidian mobile mode",
@@ -332,5 +491,6 @@ export async function behaviorEnvironment(c, parentPath, context, template) {
key,
click,
geometry,
diagnostics,
};
}
+63 -5
View File
@@ -1,6 +1,7 @@
/** Required core workflows across actual workspace contexts; no screenshots count as behavioral passes. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { behavioralCases } from "../behaviorPlan.mjs";
import { runInAppTask, parseCLIJSON } from "./inAppTask.mjs";
import { behaviorEnvironment } from "./behaviorEnvironment.mjs";
@@ -16,6 +17,7 @@ import { exerciseMarkdownBehavior } from "./markdownBehavior.mjs";
import { exerciseImageBehavior } from "./imageBehavior.mjs";
import { exerciseInteractionBehavior } from "./interactionBehavior.mjs";
import { exerciseCLIBehavior } from "./cliBehavior.mjs";
import { completeConsoleErrors } from "./debuggerSession.mjs";
const methods = new Set([
"Input.dispatchMouseEvent",
@@ -24,6 +26,36 @@ const methods = new Set([
"Input.insertText",
"Emulation.setTouchEmulationEnabled",
]);
/** Continue independent cases while retaining failures; cancellation still stops work. */
export function collectBehaviorCases(c) {
const runCase = c.case.bind(c);
c.case = async (...args) => {
c.phase = args[0];
c.caseTrace = {};
try {
return await runCase(...args);
} catch (error) {
const record = c.tests.find(
(test) => test.testId === args[0] && test.status === "failed",
);
if (record && c.diagnostics) {
try {
record.diagnostics = c.diagnostics();
} catch (diagnosticError) {
record.diagnosticError = String(diagnosticError);
}
}
if (
c.cancelled ||
!c.tests.some(
(test) => test.testId === args[0] && test.status === "failed",
)
)
throw error;
}
};
}
export function behaviorInputDriver(cli) {
return (request) => {
if (request.method === "behavior-plugin-cli") {
@@ -61,6 +93,7 @@ export async function runBehaviorMatrix({
contexts = ["main", "split", "nested-split", "popout"],
input = "mouse",
caseIds,
reportDir,
}) {
const template = readFileSync(
new URL(
@@ -69,7 +102,8 @@ export async function runBehaviorMatrix({
),
"utf8",
);
const tests = [];
const tests = [],
consoleErrors = [];
for (const id of contexts) {
const rows = behavioralCases([id]).filter(
(row) => !caseIds || caseIds.includes(row.id),
@@ -82,7 +116,9 @@ export async function runBehaviorMatrix({
);
const execute =
new Function(`return async function(c,path,context,template,rows,modifier){
const env=await (${behaviorEnvironment.toString()})(c,path,context,template);
(${collectBehaviorCases.toString()})(c);
const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()});
c.diagnostics=env.diagnostics;
await (${exerciseSettingsBehavior.toString()})(c,env,rows.filter(r=>r.id.startsWith('settings-')&&r.values));
await (${exerciseExportBehavior.toString()})(c,env,rows.filter(r=>r.id.startsWith('export-')));
await (${exerciseSettingsLifecycle.toString()})(c,env,rows.filter(r=>['settings-live-persistence','frontmatter-prefixes-theme-scale'].includes(r.id)));
@@ -91,7 +127,7 @@ export async function runBehaviorMatrix({
await (${exerciseImageBehavior.toString()})(c,env,rows.filter(r=>r.id.startsWith('images-')||r.id==='drawing-and-markdown-embeds'));
await (${exerciseEABehavior.toString()})(c,env,rows.filter(r=>r.id.startsWith('ea-')));
await (${exerciseInteractionBehavior.toString()})(c,env,rows.filter(r=>r.id.startsWith('command-')||r.id==='toolbar-context-shortcuts'),modifier);
return {tests:c.tests};
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[]};
}`)();
const result = await runInAppTask({
cli,
@@ -106,6 +142,21 @@ export async function runBehaviorMatrix({
timeoutMs: 600000,
cleanupMs: 60000,
onRequest: behaviorInputDriver(cli),
onProgress: (phase, state) => {
if (reportDir)
writeFileSync(
join(reportDir, "behavior-" + id + "-progress.json"),
JSON.stringify({
phase,
tests: state.tests,
at: new Date().toISOString(),
}) + "\n",
);
},
}).catch((error) => {
// Keep completed contexts when a later context cannot finish cleanup.
error.evidence = [...tests, ...(error.evidence || [])];
throw error;
});
assert.deepEqual(
result.tests.map((t) => t.testId).sort(),
@@ -113,11 +164,18 @@ export async function runBehaviorMatrix({
"Behavioral obligations missing from " + id,
);
tests.push(...result.tests);
consoleErrors.push(...result.consoleErrors);
}
return {
id: "behavior-matrix",
status: "passed",
status: tests.every((test) => test.status === "passed")
? "passed"
: "failed",
tests,
consoleErrors,
expectedConsoleErrors: tests.flatMap(
(test) => test.expectedConsoleErrors || [],
),
scope: { contexts, caseIds: caseIds || "all" },
};
}
+8
View File
@@ -28,6 +28,14 @@ export async function exerciseCLIBehavior(c, env, rows) {
);
const otherLeaf = app.workspace.getLeaf("tab");
env.owned.add(otherLeaf);
await c.waitFor(
() =>
p.isExcalidrawFile(other) &&
app.metadataCache.getFileCache(other)?.frontmatter?.[
"excalidraw-plugin"
],
"other CLI target metadata",
);
await otherLeaf.openFile(other);
await env.ready(otherLeaf);
app.workspace.setActiveLeaf(otherLeaf, { focus: true });
+152 -15
View File
@@ -3,42 +3,179 @@ import { randomUUID } from "node:crypto";
import { parseCLIJSON } from "./inAppTask.mjs";
export function acquireDebuggerSession(cli) {
const evaluate = code => parseCLIJSON(cli("eval", "code=" + code));
const attached = evaluate('JSON.stringify(require("@electron/remote").getCurrentWebContents().debugger.isAttached())');
if (attached !== false) throw Error("Native debugger is already attached; close the existing DevTools/debugger before this owned run");
const evaluate = (code) => parseCLIJSON(cli("eval", "code=" + code));
const attached = evaluate(
'JSON.stringify(require("@electron/remote").getCurrentWebContents().debugger.isAttached())',
);
if (attached !== false)
throw Error(
"Native debugger is already attached; close the existing DevTools/debugger before this owned run",
);
const originalBackgroundThrottling = evaluate(
'JSON.stringify(require("@electron/remote").getCurrentWebContents().getBackgroundThrottling())',
);
if (typeof originalBackgroundThrottling !== "boolean")
throw Error("Native scheduling identity unavailable");
let schedulingOwned = false;
const restoreScheduling = () => {
if (schedulingOwned) {
evaluate(
`(()=>{require('@electron/remote').getCurrentWebContents().setBackgroundThrottling(${originalBackgroundThrottling});return JSON.stringify(true);})()`,
);
schedulingOwned = false;
}
};
const key = "__excalidrawTestConsole_" + randomUUID().replaceAll("-", "");
let attachedByUs = false, installed = false, disposed = false;
let attachedByUs = false,
installed = false,
disposed = false;
try {
cli("dev:debug", "on"); attachedByUs = true;
// The real renderer can be occluded even while CLI reports a focused window.
// Keep test input/render scheduling active, then restore the exact prior value.
schedulingOwned = true;
evaluate(
"(()=>{require('@electron/remote').getCurrentWebContents().setBackgroundThrottling(false);return JSON.stringify(true);})()",
);
cli("dev:debug", "on");
attachedByUs = true;
cli("dev:cdp", "method=Runtime.disable", "params={}");
cli("dev:cdp", "method=Runtime.discardConsoleEntries", "params={}");
evaluate(`(()=>{if(globalThis[${JSON.stringify(key)}])throw Error('Console controller collision');const c={errors:[],contexts:{}};c.debugger=require('@electron/remote').getCurrentWebContents().debugger;c.listener=(_event,method,params)=>{if(method==='Runtime.executionContextCreated')c.contexts[params.context.id]=params.context;if(method==='Runtime.consoleAPICalled'&&params.type==='error')c.errors.push({kind:'console',messages:params.args.map(arg=>String(arg.description??arg.value??arg.type)+(arg.preview?.properties?' '+JSON.stringify(arg.preview.properties):''))});if(method==='Runtime.exceptionThrown')c.errors.push({kind:'exception',timestamp:params.timestamp,context:c.contexts[params.exceptionDetails.executionContextId],tasks:Object.keys(globalThis).filter(key=>key.startsWith('__excalidrawTestTask_')).map(key=>({key,phase:globalThis[key].phase,activeCase:globalThis[key].activeCase,lastCase:globalThis[key].tests.at(-1)?.testId})),details:params.exceptionDetails,messages:[String(params.exceptionDetails.exception?.description??params.exceptionDetails.exception?.value??params.exceptionDetails.text)]});};c.debugger.on('message',c.listener);globalThis[${JSON.stringify(key)}]=c;return JSON.stringify({installed:true});})()`);
evaluate(
`(()=>{if(globalThis[${JSON.stringify(key)}])throw Error('Console controller collision');const c={errors:[],contexts:{}};c.debugger=require('@electron/remote').getCurrentWebContents().debugger;c.listener=(_event,method,params)=>{if(method==='Runtime.executionContextCreated')c.contexts[params.context.id]=params.context;if(method==='Runtime.consoleAPICalled'&&params.type==='error')c.errors.push({kind:'console',overflowArgs:params.args.some(arg=>arg.preview?.overflow)?params.args:undefined,messages:params.args.map(arg=>String(arg.description??arg.value??arg.type)+(arg.preview?.properties?' '+JSON.stringify(arg.preview.properties):'')+(arg.preview?.overflow?' [preview truncated]':''))});if(method==='Runtime.exceptionThrown')c.errors.push({kind:'exception',timestamp:params.timestamp,context:c.contexts[params.exceptionDetails.executionContextId],tasks:Object.keys(globalThis).filter(key=>key.startsWith('__excalidrawTestTask_')).map(key=>({key,phase:globalThis[key].phase,activeCase:globalThis[key].activeCase,lastCase:globalThis[key].tests.at(-1)?.testId})),details:params.exceptionDetails,messages:[String(params.exceptionDetails.exception?.description??params.exceptionDetails.exception?.value??params.exceptionDetails.text)]});};c.debugger.on('message',c.listener);globalThis[${JSON.stringify(key)}]=c;return JSON.stringify({installed:true});})()`,
);
installed = true;
cli("dev:cdp", "method=Runtime.enable", "params={}");
} catch (error) {
try {
if (installed) evaluate(`(()=>{const c=globalThis[${JSON.stringify(key)}];c.debugger.removeListener('message',c.listener);delete globalThis[${JSON.stringify(key)}];return JSON.stringify(true);})()`);
} finally { if (attachedByUs) cli("dev:debug", "off"); }
if (installed)
evaluate(
`(()=>{const c=globalThis[${JSON.stringify(key)}];c.debugger.removeListener('message',c.listener);delete globalThis[${JSON.stringify(key)}];return JSON.stringify(true);})()`,
);
} finally {
try {
restoreScheduling();
} finally {
if (attachedByUs) cli("dev:debug", "off");
}
}
throw error;
}
return {
read: () => evaluate(`JSON.stringify(globalThis[${JSON.stringify(key)}].errors)`),
scheduling: {
originalBackgroundThrottling,
scopedBackgroundThrottling: false,
},
read: () => {
const errors = evaluate(
`JSON.stringify(globalThis[${JSON.stringify(key)}].errors)`,
);
if (!errors.some((error) => error.overflowArgs)) return errors;
// A CDP preview contains only a few fields. Read all own properties before
// deciding that a missing-file diagnostic contains no additional error.
return evaluate(
`(${completeConsoleErrors.toString()})(globalThis[${JSON.stringify(key)}]).then(JSON.stringify)`,
);
},
dispose() {
if (disposed) return;
try {
evaluate(`(()=>{const c=globalThis[${JSON.stringify(key)}];if(!c)throw Error('Owned console controller disappeared');c.debugger.removeListener('message',c.listener);delete globalThis[${JSON.stringify(key)}];return JSON.stringify(true);})()`);
} finally { cli("dev:debug", "off"); disposed = true; }
evaluate(
`(()=>{const c=globalThis[${JSON.stringify(key)}];if(!c)throw Error('Owned console controller disappeared');c.debugger.removeListener('message',c.listener);delete globalThis[${JSON.stringify(key)}];return JSON.stringify(true);})()`,
);
} finally {
try {
restoreScheduling();
} finally {
cli("dev:debug", "off");
disposed = true;
}
}
},
};
}
export function unexpectedConsoleErrors(errors, expected = []) {
const counts = expected.map(() => 0), unexpected = [];
const counts = expected.map(() => 0),
unexpected = [];
for (const error of errors) {
const message = error.messages.join("\n");
const index = expected.findIndex(item => error.kind === (item.kind || "console") && message.includes(item.contains));
if (index < 0) unexpected.push(error); else counts[index]++;
const index = expected.findIndex(
(item) =>
error.kind === (item.kind || "console") &&
(item.contains
? message.includes(item.contains)
: item.containsAll?.length > 0) &&
(!item.containsAll ||
item.containsAll.every((fragment) => message.includes(fragment))) &&
(!item.excludes ||
item.excludes.every((fragment) => !message.includes(fragment))),
);
if (index < 0) unexpected.push(error);
else counts[index]++;
}
expected.forEach((item, index) => { if (counts[index] < item.min || counts[index] > item.max) unexpected.push({ kind: "expected-error-count", messages: [`${item.contains}: observed ${counts[index]}, expected ${item.min}–${item.max}`] }); });
expected.forEach((item, index) => {
if (counts[index] < item.min || counts[index] > item.max)
unexpected.push({
kind: "expected-error-count",
messages: [
`${item.contains}: observed ${counts[index]}, expected ${item.min}–${item.max}`,
],
});
});
return unexpected;
}
/** Resolve truncated CDP objects without invoking accessors or trusting a preview. */
export async function completeConsoleErrors(controller) {
const readObject = async (objectId, depth) => {
const full = await controller.debugger.sendCommand(
"Runtime.getProperties",
{ objectId, ownProperties: true },
);
let incomplete = !!full.exceptionDetails;
const properties = [];
for (const property of full.result || []) {
const value = property.value;
const item = {
name: property.name,
type: value?.type ?? "accessor",
value: String(
value?.value ?? value?.description ?? value?.type ?? "accessor",
),
};
if (!value || value.type === "function") incomplete = true;
if (value?.objectId) {
if (value.subtype === "error" && depth < 1) {
const nested = await readObject(value.objectId, depth + 1);
item.properties = nested.properties;
incomplete ||= nested.incomplete;
} else incomplete = true;
}
properties.push(item);
}
return { properties, incomplete };
};
for (const error of controller.errors) {
if (!error.overflowArgs) continue;
error.messages = await Promise.all(
error.overflowArgs.map(async (arg) => {
if (!arg.preview?.overflow)
return (
String(arg.description ?? arg.value ?? arg.type) +
(arg.preview?.properties
? " " + JSON.stringify(arg.preview.properties)
: "")
);
const full = await readObject(arg.objectId, 0);
return (
String(arg.description ?? arg.type) +
" " +
JSON.stringify(full.properties) +
(full.incomplete ? " [preview truncated]" : "")
);
}),
);
delete error.overflowArgs;
}
return controller.errors;
}
+195 -24
View File
@@ -2,50 +2,221 @@ import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { EventEmitter } from "node:events";
import { acquireDebuggerSession, unexpectedConsoleErrors } from "./debuggerSession.mjs";
function host(attached = false) {
const debuggerInstance = new EventEmitter(); debuggerInstance.isAttached = () => attached;
const commands = [], context = vm.createContext({ require: () => ({ getCurrentWebContents: () => ({ debugger: debuggerInstance }) }) });
import {
acquireDebuggerSession,
unexpectedConsoleErrors,
completeConsoleErrors,
} from "./debuggerSession.mjs";
function host(attached = false, initialBackground = true) {
let background = initialBackground;
const debuggerInstance = new EventEmitter();
debuggerInstance.isAttached = () => attached;
const contents = {
debugger: debuggerInstance,
getBackgroundThrottling: () => background,
setBackgroundThrottling: (value) => {
background = value;
},
};
const commands = [],
context = vm.createContext({
require: () => ({ getCurrentWebContents: () => contents }),
});
const cli = (command, ...args) => {
commands.push([command, ...args]);
if (command === "eval") return String(vm.runInContext(args[0].slice(5), context));
if (command === "eval")
return String(vm.runInContext(args[0].slice(5), context));
if (command === "dev:debug") attached = args[0] === "on";
return "";
};
return { cli, commands, debuggerInstance, context };
return {
cli,
commands,
debuggerInstance,
context,
background: () => background,
};
}
test("an existing debugger is never stolen or detached", () => {
const { cli, commands } = host(true);
assert.throws(() => acquireDebuggerSession(cli), /already attached/);
assert.equal(commands.some(command => command[0] === "dev:debug"), false);
assert.equal(
commands.some((command) => command[0] === "dev:debug"),
false,
);
});
test("owned console and exception capture is removed with its exact attachment", () => {
const { cli, commands, debuggerInstance, context } = host();
const session = acquireDebuggerSession(cli);
debuggerInstance.emit("message", null, "Runtime.consoleAPICalled", { type: "error", args: [{ description: "actual failure" }] });
debuggerInstance.emit("message", null, "Runtime.executionContextCreated", {context:{id:4,name:'owned test context'}});
debuggerInstance.emit("message", null, "Runtime.exceptionThrown", { exceptionDetails: {executionContextId:4,text:"Uncaught",exception:{type:'string',value:'actual primitive exception'}} });
debuggerInstance.emit("message", null, "Runtime.consoleAPICalled", {
type: "error",
args: [{ description: "actual failure" }],
});
debuggerInstance.emit("message", null, "Runtime.executionContextCreated", {
context: { id: 4, name: "owned test context" },
});
debuggerInstance.emit("message", null, "Runtime.exceptionThrown", {
exceptionDetails: {
executionContextId: 4,
text: "Uncaught",
exception: { type: "string", value: "actual primitive exception" },
},
});
assert.equal(session.read().length, 2);
assert.equal(session.read()[1].messages[0],"actual primitive exception");
assert.equal(session.read()[1].context.name,"owned test context");
assert.ok(commands.findIndex(command=>command.includes("method=Runtime.disable"))<commands.findIndex(command=>command.includes("method=Runtime.enable")));
session.dispose(); session.dispose();
assert.equal(session.read()[1].messages[0], "actual primitive exception");
assert.equal(session.read()[1].context.name, "owned test context");
assert.ok(
commands.findIndex((command) =>
command.includes("method=Runtime.disable"),
) <
commands.findIndex((command) =>
command.includes("method=Runtime.enable"),
),
);
session.dispose();
session.dispose();
assert.equal(debuggerInstance.listenerCount("message"), 0);
assert.equal(Object.keys(context).some(key => key.startsWith("__excalidrawTestConsole_")), false);
assert.equal(commands.filter(command => command[0] === "dev:debug" && command[1] === "off").length, 1);
assert.equal(
Object.keys(context).some((key) =>
key.startsWith("__excalidrawTestConsole_"),
),
false,
);
assert.equal(
commands.filter(
(command) => command[0] === "dev:debug" && command[1] === "off",
).length,
1,
);
});
test("expected fault injection cannot hide another error or an incorrect count", () => {
const expected = [{ contains: "OWNED_WRITE_FAILURE", min: 1, max: 1 }], error = { kind: "console", messages: ["OWNED_WRITE_FAILURE"] };
const expected = [{ contains: "OWNED_WRITE_FAILURE", min: 1, max: 1 }],
error = { kind: "console", messages: ["OWNED_WRITE_FAILURE"] };
assert.deepEqual(unexpectedConsoleErrors([error], expected), []);
assert.equal(unexpectedConsoleErrors([error, error], expected).length, 1);
assert.equal(unexpectedConsoleErrors([error, { messages: ["unrelated failure"] }], expected).length, 1);
assert.equal(
unexpectedConsoleErrors(
[error, { messages: ["unrelated failure"] }],
expected,
).length,
1,
);
assert.equal(unexpectedConsoleErrors([], expected).length, 1);
assert.equal(unexpectedConsoleErrors([error, { ...error, kind: "exception" }], expected).length, 1);
assert.equal(
unexpectedConsoleErrors([error, { ...error, kind: "exception" }], expected)
.length,
1,
);
});
test('lost console controller fails cleanup but still releases our debugger attachment', () => {
const {cli,commands,context}=host();const session=acquireDebuggerSession(cli);
const key=Object.keys(context).find(key=>key.startsWith('__excalidrawTestConsole_'));assert.ok(key);vm.runInContext('delete globalThis['+JSON.stringify(key)+']',context);
assert.throws(()=>session.dispose(),/controller disappeared/);
assert.equal(commands.filter(command=>command[0]==='dev:debug'&&command[1]==='off').length,1);
test("lost console controller fails cleanup but still releases our debugger attachment", () => {
const { cli, commands, context } = host();
const session = acquireDebuggerSession(cli);
const key = Object.keys(context).find((key) =>
key.startsWith("__excalidrawTestConsole_"),
);
assert.ok(key);
vm.runInContext("delete globalThis[" + JSON.stringify(key) + "]", context);
assert.throws(() => session.dispose(), /controller disappeared/);
assert.equal(
commands.filter(
(command) => command[0] === "dev:debug" && command[1] === "off",
).length,
1,
);
});
test("renderer scheduling is scoped and restores both original background-throttling values", () => {
for (const original of [true, false]) {
const h = host(false, original),
session = acquireDebuggerSession(h.cli);
assert.equal(h.background(), false);
assert.equal(session.scheduling.originalBackgroundThrottling, original);
session.dispose();
session.dispose();
assert.equal(h.background(), original);
}
});
test("expected missing-asset diagnostics cannot hide exceptions, extra fields, another source or repeated errors", () => {
const rule = {
containsAll: [
"EmbeddedFileLoader._getObsidianImage",
"owned-source.svg",
"depth=0",
],
excludes: ["name=error", "[preview truncated]"],
min: 1,
max: 1,
};
const good = {
kind: "console",
messages: ["EmbeddedFileLoader._getObsidianImage owned-source.svg depth=0"],
};
assert.deepEqual(unexpectedConsoleErrors([good], [rule]), []);
for (const other of [
{ ...good, kind: "exception" },
{
kind: "console",
messages: [
"EmbeddedFileLoader._getObsidianImage other-source.svg depth=0",
],
},
{ kind: "console", messages: [good.messages[0] + " name=error"] },
{ kind: "console", messages: [good.messages[0] + " [preview truncated]"] },
])
assert.ok(unexpectedConsoleErrors([other], [rule]).length);
assert.ok(unexpectedConsoleErrors([good, good], [rule]).length);
});
test("truncated console objects expose the actual native error and complete own properties", async () => {
const error = {
kind: "console",
overflowArgs: [
{ objectId: "outer", description: "Object", preview: { overflow: true } },
],
messages: [],
};
const objects = {
outer: [
{ name: "file", value: { type: "string", value: "owned-source.svg" } },
{
name: "error",
value: {
type: "object",
subtype: "error",
objectId: "native-error",
description: "Error: ENOENT",
},
},
],
"native-error": [
{ name: "code", value: { type: "string", value: "ENOENT" } },
{ name: "path", value: { type: "string", value: "owned-source.svg" } },
],
};
const c = {
errors: [error],
debugger: {
sendCommand: async (method, params) => {
assert.equal(method, "Runtime.getProperties");
assert.equal(params.ownProperties, true);
return { result: objects[params.objectId] };
},
},
};
assert.equal((await completeConsoleErrors(c))[0], error);
assert.match(
error.messages[0],
/"name":"code","type":"string","value":"ENOENT"/,
);
assert.equal(error.messages[0].includes("[preview truncated]"), false);
assert.equal(error.overflowArgs, undefined);
objects["native-error"].push({
name: "cause",
value: { type: "object", objectId: "uninspected" },
});
error.overflowArgs = [{ objectId: "outer", preview: { overflow: true } }];
await completeConsoleErrors(c);
assert.match(error.messages[0], /\[preview truncated\]/);
});
+13 -4
View File
@@ -114,6 +114,7 @@ export async function runDeviceMatrix({
`(()=>{app.changeTheme(${JSON.stringify(profile.theme === "dark" ? "obsidian" : "moonstone")});return JSON.stringify(true);})()`,
);
debuggerSession = acquireDebuggerSession(cli);
const expectedConsoleErrors = [];
cli(
"dev:cdp",
"method=Emulation.setTouchEmulationEnabled",
@@ -160,23 +161,29 @@ export async function runDeviceMatrix({
return { dispatched: true };
},
});
let workflows;
if (
featureWorkflows &&
["phone-portrait-light", "tablet-portrait-full-light"].includes(
profile.id,
)
) {
const workflows = await runBehaviorMatrix({
workflows = await runBehaviorMatrix({
cli,
drawingPath: path,
contexts: [profile.id.startsWith("phone-") ? "phone" : "tablet"],
input: "touch",
reportDir,
});
report.tests.push(...workflows.tests);
expectedConsoleErrors.push(...(workflows.expectedConsoleErrors || []));
}
const errors = debuggerSession.read();
const errors = [
...debuggerSession.read(),
...(workflows?.consoleErrors || []),
];
assert.deepEqual(
unexpectedConsoleErrors(errors),
unexpectedConsoleErrors(errors, expectedConsoleErrors),
[],
"Unexpected device console/JavaScript error",
);
@@ -189,7 +196,9 @@ export async function runDeviceMatrix({
...result,
});
}
report.status = "passed";
report.status = report.tests.every((test) => test.status === "passed")
? "passed"
: "failed";
} catch (error) {
report.error = String(error.stack || error);
report.tests.push(...(error.evidence || []));
+31 -1
View File
@@ -87,6 +87,14 @@ export async function exerciseEABehavior(c, env, rows) {
);
const otherLeaf = app.workspace.getLeaf("tab");
env.owned.add(otherLeaf);
await c.waitFor(
() =>
p.isExcalidrawFile(otherFile) &&
app.metadataCache.getFileCache(otherFile)?.frontmatter?.[
"excalidraw-plugin"
],
"other EA target metadata",
);
await otherLeaf.openFile(otherFile);
await env.ready(otherLeaf);
app.workspace.setActiveLeaf(otherLeaf, { focus: true });
@@ -242,6 +250,19 @@ export async function exerciseSettingsLifecycle(c, env, rows) {
const api = view.excalidrawAPI,
canvas = view.containerEl.querySelector("canvas.interactive"),
bounds = canvas.getBoundingClientRect();
const wheelEvents = [];
c.caseTrace = { wheelEvents };
const observeWheel = (event) =>
wheelEvents.push({
trusted: event.isTrusted,
deltaY: event.deltaY,
ctrl: event.ctrlKey,
meta: event.metaKey,
target: event.target?.className,
});
canvas.addEventListener("wheel", observeWheel, { passive: true });
c.defer(() => canvas.removeEventListener("wheel", observeWheel));
p.settings.allowWheelZoom = true;
let point;
for (const [x, y] of [
[0.7, 0.55],
@@ -273,13 +294,21 @@ export async function exerciseSettingsLifecycle(c, env, rows) {
() => api.getAppState().allowWheelZoom === true,
"wheel-ready app state",
);
for (let i = 0; i < 8; i++)
for (let i = 0; i < 12 && api.getAppState().zoom.value > 0.5; i++) {
const before = api.getAppState().zoom.value;
await env.input("Input.dispatchMouseEvent", {
type: "mouseWheel",
...point,
modifiers: 0,
deltaX: 0,
deltaY: 300,
});
// Wait for each wheel update; Chromium may coalesce a burst of ticks.
await c.waitFor(
() => api.getAppState().zoom.value < before,
"individual trusted wheel update",
);
}
await c.waitFor(
() => Math.abs(api.getAppState().zoom.value - 0.5) < 1e-8,
"trusted wheel uses first live minimum",
@@ -288,6 +317,7 @@ export async function exerciseSettingsLifecycle(c, env, rows) {
await env.input("Input.dispatchMouseEvent", {
type: "mouseWheel",
...point,
modifiers: 0,
deltaX: 0,
deltaY: 300,
});
+17 -1
View File
@@ -19,6 +19,11 @@ export async function runExtrasServicesScenario({
args: [prefix],
timeoutMs: 180_000,
cleanupMs: 135_000,
onProgress: (phase) =>
writeFileSync(
join(reportDir, "native-single-export-progress.json"),
JSON.stringify({ phase, at: new Date().toISOString() }) + "\n",
),
onRequest: (request) => {
assert.equal(request.method, "pdf-evidence");
assert.equal(request.params.path, prefix + "/Output.pdf");
@@ -36,6 +41,7 @@ export async function runExtrasServicesScenario({
}
async function exerciseExtras(c, prefix) {
c.phase = "extras-services";
const plugin = app.plugins.plugins["obsidian-excalidraw-plugin"],
extras = app.plugins.plugins["excalidraw-extras"];
const check = (value, label) => {
@@ -139,6 +145,7 @@ async function exerciseExtras(c, prefix) {
beforePrints = doc.querySelectorAll("body > .print").length;
const path = prefix + "/Output.pdf",
absolutePath = app.vault.adapter.getFullPath(path);
c.phase = "pdf-native-print";
await service.exportToPDF(
content,
absolutePath,
@@ -155,6 +162,7 @@ async function exerciseExtras(c, prefix) {
beforeStyles.every((sheet, i) => doc.adoptedStyleSheets[i] === sheet),
"PDF temporary DOM or stylesheet leaked",
);
c.phase = "pdf-read-completed-output";
await c.waitFor(
() => app.vault.getFileByPath(path),
"native PDF file event",
@@ -171,12 +179,14 @@ async function exerciseExtras(c, prefix) {
const pdf = await loading.promise;
c.defer(() => pdf.destroy());
check(pdf.numPages === 1, `unexpected PDF page count: ${pdf.numPages}`);
c.phase = "pdf-page";
const first = await pdf.getPage(1),
viewport = first.getViewport({ scale: 1 });
check(
Math.abs(viewport.width - 288) < 1 && Math.abs(viewport.height - 216) < 1,
"PDF media box differs from 4in × 3in",
);
c.phase = "pdf-text";
const text = (await first.getTextContent()).items
.map((item) => item.str || "")
.join(" ");
@@ -185,12 +195,18 @@ async function exerciseExtras(c, prefix) {
canvas.width = Math.ceil(viewport.width);
canvas.height = Math.ceil(viewport.height);
const context = canvas.getContext("2d");
await first.render({ canvasContext: context, viewport }).promise;
c.phase = "pdf-decode-pixels";
// Batch verification must not depend on display animation frames: Electron
// can occlude the vault while its CLI remains available. PDF.js print intent
// renders the same page without requestAnimationFrame scheduling.
await first.render({ canvasContext: context, viewport, intent: "print" })
.promise;
const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data;
let red = 0;
for (let i = 0; i < pixels.length; i += 4)
if (pixels[i] > 180 && pixels[i + 1] < 80 && pixels[i + 2] < 80) red++;
check(red > 100, "PDF lost SVG content");
c.phase = "pdf-retain-evidence";
const evidence = await c.requestHost("pdf-evidence", {
path,
pngBase64: canvas.toDataURL("image/png").split(",")[1],
+46 -5
View File
@@ -111,7 +111,17 @@ export async function exerciseImageBehavior(c, env, rows) {
first.red > 100 && first.blue === 0,
"Initial SVG source is not red",
);
const editNote = await env.create(
"Source-edit-anchor.md",
"Owned external-edit anchor.",
);
const editLeaf = app.workspace.getLeaf("tab");
env.owned.add(editLeaf);
await editLeaf.openFile(editNote);
app.workspace.setActiveLeaf(editLeaf, { focus: true });
await app.vault.modify(source, svgText("#0000ff"));
app.workspace.setActiveLeaf(env.leaf, { focus: true });
env.win.focus();
await c.waitFor(
() => {
const data =
@@ -181,11 +191,33 @@ export async function exerciseImageBehavior(c, env, rows) {
edited,
restored,
missing: { imageIdRetained: true, referenceRetained: true },
expectedConsoleErrors: [
{
containsAll: [
'"value":"EmbeddedFileLoader._getObsidianImage"',
'"value":"' + reference + '"',
'"name":"depth","type":"number","value":"0"',
'"name":"code","type":"string","value":"ENOENT"',
'"name":"syscall","type":"string","value":"open"',
JSON.stringify({
name: "path",
type: "string",
value: require("node:path").join(
app.vault.adapter.getBasePath(),
reference,
),
}),
],
excludes: ["[preview truncated]"],
min: 1,
max: 1,
},
],
};
}
const markdown = await env.create(
"Embedded-note.md",
'---\nexcalidraw-font: Helvetica\nexcalidraw-font-color: "#ff0000"\nexcalidraw-border-color: "#0000ff"\nexcalidraw-css: "h1 { color: #ff0000; }"\n---\n# EMBEDDED_MARKDOWN_RENDER_TOKEN\n\n| Name | Value |\n| --- | --- |\n| Owned | 42 |\n\n$E=mc^2$\n',
'---\nexcalidraw-font: Excalifont\nexcalidraw-font-color: "#ff0000"\nexcalidraw-border-color: "#0000ff"\nexcalidraw-css: "h1 { background-color: #00ff00; }"\n---\n# EMBEDDED_MARKDOWN_RENDER_TOKEN\n\n| Name | Value |\n| --- | --- |\n| Owned | 42 |\n\n$E=mc^2$\n',
);
const drawing = await env.create(
"Embedded-source.excalidraw.md",
@@ -205,7 +237,13 @@ export async function exerciseImageBehavior(c, env, rows) {
drawing,
app.vault.getFileByPath("Assets/Small.pdf"),
].entries()) {
const id = await ea.addImage(i * 450, 300, file, false, false);
const id = await ea.addImage(
i * 450,
300,
file.extension === "pdf" ? file.path + "#page=1" : file,
false,
false,
);
check(id, "Embedded source conversion failed: " + file.path);
ids.push(id);
}
@@ -229,9 +267,10 @@ export async function exerciseImageBehavior(c, env, rows) {
}),
"asynchronous embedded image data",
);
view.excalidrawAPI.scrollToContent(
ea.viewZoomToElements(
false,
view.getViewElements().filter((e) => e.id === embeddable),
{ fitToContent: true },
0.05,
);
await c.waitFor(() => {
const ref = view.getEmbeddableLeafElementById(embeddable);
@@ -264,7 +303,9 @@ export async function exerciseImageBehavior(c, env, rows) {
}),
);
check(
markdownPixels.red > 10 && markdownPixels.blue > 10,
markdownPixels.red > 10 &&
markdownPixels.blue > 10 &&
markdownPixels.green > 20,
"Markdown font/CSS and border frontmatter did not reach actual exported pixels",
);
view = await saveReopen(view);
+127 -34
View File
@@ -3,56 +3,113 @@ import { randomUUID } from "node:crypto";
export function parseCLIJSON(output) {
const value = output.trim().replace(/^=>\s*/, "");
if (/^Error:/m.test(value)) throw Error(`Obsidian CLI: ${value.slice(0, 1000)}`);
try { return JSON.parse(value); } catch { throw Error(`Expected JSON from Obsidian CLI: ${value.slice(0, 500)}`); }
if (/^Error:/m.test(value))
throw Error(`Obsidian CLI: ${value.slice(0, 1000)}`);
try {
return JSON.parse(value);
} catch {
throw Error(`Expected JSON from Obsidian CLI: ${value.slice(0, 500)}`);
}
}
export async function runInAppTask({ cli, execute, args = [], timeoutMs = 60_000, cleanupMs = 30_000,
onRequest, onProgress, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), now = () => Date.now(), token = randomUUID().replaceAll("-", "") }) {
export async function runInAppTask({
cli,
execute,
args = [],
timeoutMs = 60_000,
cleanupMs = 30_000,
onRequest,
onProgress,
wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
now = () => Date.now(),
token = randomUUID().replaceAll("-", ""),
}) {
const key = `__excalidrawTestTask_${token}`;
const evaluate = code => parseCLIJSON(cli("eval", "code=" + code));
evaluate(`(${installTask.toString()})(${JSON.stringify(key)},${execute.toString()},${JSON.stringify(args)})`);
const read = () => evaluate(`JSON.stringify((()=>{const c=globalThis[${JSON.stringify(key)}];return c?{state:c.state,result:c.result,error:c.error,tests:c.tests,cleanup:c.cleanup,cleanupErrors:c.cleanupErrors,cleanupPending:c.cleanupPending,phase:c.phase,request:c.request}:{state:'missing'}})())`);
const evaluate = (code) => parseCLIJSON(cli("eval", "code=" + code));
evaluate(
`(${installTask.toString()})(${JSON.stringify(key)},${execute.toString()},${JSON.stringify(args)})`,
);
const read = () =>
evaluate(
`JSON.stringify((()=>{const c=globalThis[${JSON.stringify(key)}];return c?{state:c.state,result:c.result,error:c.error,tests:c.tests,cleanup:c.cleanup,cleanupErrors:c.cleanupErrors,cleanupPending:c.cleanupPending,phase:c.phase,request:c.request}:{state:'missing'}})())`,
);
let state, originalError, previousPhase;
try {
const end = now() + timeoutMs;
for (;;) {
state = read();
if(onProgress&&state.phase!==previousPhase){previousPhase=state.phase;onProgress(state.phase);}
if (
onProgress &&
(state.phase !== previousPhase || state.state === "done")
) {
previousPhase = state.phase;
onProgress(state.phase, state);
}
if (state.state === "done") {
if (state.error) { const error = Error(state.error); error.evidence = state.tests; throw error; }
if (state.cleanup !== "passed") throw Error("Native task cleanup failed: " + state.cleanupErrors.join("; "));
if (state.error) {
const error = Error(state.error);
error.evidence = state.tests;
throw error;
}
if (state.cleanup !== "passed")
throw Error(
"Native task cleanup failed: " + state.cleanupErrors.join("; "),
);
return state.result;
}
if (state.state === "cleaning" && state.error) { const error = Error(state.error); error.evidence = state.tests; throw error; }
if (state.state === "missing") throw Error("Native task controller disappeared");
if (state.state === "cleaning" && state.error) {
const error = Error(state.error);
error.evidence = state.tests;
throw error;
}
if (state.state === "missing")
throw Error("Native task controller disappeared");
if (now() >= end) throw Error("Native task deadline exceeded");
if (state.request) {
if (!onRequest) throw Error("No trusted-input/screenshot driver available");
if (!onRequest)
throw Error("No trusted-input/screenshot driver available");
const response = await onRequest(state.request);
evaluate(`(()=>{const c=globalThis[${JSON.stringify(key)}];if(c?.request?.id!==${JSON.stringify(state.request.id)})throw Error('Task request ownership changed');c.response=${JSON.stringify(response ?? null)};delete c.request;return JSON.stringify({acknowledged:true})})()`);
evaluate(
`(()=>{const c=globalThis[${JSON.stringify(key)}];if(c?.request?.id!==${JSON.stringify(state.request.id)})throw Error('Task request ownership changed');c.response=${JSON.stringify(response ?? null)};delete c.request;return JSON.stringify({acknowledged:true})})()`,
);
}
await wait(50);
}
} catch (error) {
originalError = error;
error.evidence ||= state?.tests;
throw error;
} finally {
const end = now() + cleanupMs;
try {
evaluate(`(()=>{const c=globalThis[${JSON.stringify(key)}];if(c)c.cancelled=true;return JSON.stringify({cancelled:!!c})})()`);
evaluate(
`(()=>{const c=globalThis[${JSON.stringify(key)}];if(c)c.cancelled=true;return JSON.stringify({cancelled:!!c})})()`,
);
for (;;) {
state = read();
if (state.state === "done") break;
if (state.state === "missing" || now() >= end) throw Error("Native task did not settle; preserve owned fixtures for recovery");
if (state.state === "missing" || now() >= end)
throw Error(
"Native task did not settle; preserve owned fixtures for recovery",
);
await wait(50);
}
if (state.cleanup !== "passed") throw Error("Native task cleanup failed: " + state.cleanupErrors.join("; "));
evaluate(`(()=>{delete globalThis[${JSON.stringify(key)}];return JSON.stringify({removed:true})})()`);
if (state.cleanup !== "passed")
throw Error(
"Native task cleanup failed: " + state.cleanupErrors.join("; "),
);
if (originalError) originalError.evidence = state.tests;
evaluate(
`(()=>{delete globalThis[${JSON.stringify(key)}];return JSON.stringify({removed:true})})()`,
);
} catch (cleanupError) {
const error = new Error(`${originalError?.message || "Native task"}; ${cleanupError.message}`, { cause: originalError || cleanupError });
const error = new Error(
`${originalError?.message || "Native task"}; ${cleanupError.message}`,
{ cause: originalError || cleanupError },
);
error.evidence = state?.tests || originalError?.evidence;
error.cleanupFailed = true; throw error;
error.cleanupFailed = true;
throw error;
}
}
}
@@ -60,43 +117,79 @@ export async function runInAppTask({ cli, execute, args = [], timeoutMs = 60_000
/** Entire implementation is serialized into the real host, never shipped in main.js. */
function installTask(key, execute, args) {
if (globalThis[key]) throw Error("Native task ownership collision");
const c = { state: "running", cancelled: false, cleanup: "not-started", cleanupErrors: [], disposers: [], requestId: 0, tests: [] };
const c = {
state: "running",
cancelled: false,
cleanup: "not-started",
cleanupErrors: [],
disposers: [],
requestId: 0,
tests: [],
};
globalThis[key] = c;
c.checkpoint = () => { if (c.cancelled) throw Error("Native task cancelled"); };
c.checkpoint = () => {
if (c.cancelled) throw Error("Native task cancelled");
};
c.waitFor = async (predicate, label, timeoutMs = 20000) => {
const end = Date.now() + timeoutMs;
for (;;) { c.checkpoint(); const ready = await predicate(); c.checkpoint(); if (ready) return; if (Date.now() >= end) throw Error(`Timed out: ${label}`); await new Promise(resolve => setTimeout(resolve, 25)); }
for (;;) {
c.checkpoint();
const ready = await predicate();
c.checkpoint();
if (ready) return;
if (Date.now() >= end) throw Error(`Timed out: ${label}`);
await new Promise((resolve) => setTimeout(resolve, 25));
}
};
c.waitForCleanup = async (predicate, label, timeoutMs = 20000) => {
const end = Date.now() + timeoutMs;
while (!(await predicate())) { if (Date.now() >= end) throw Error(`Cleanup timed out: ${label}`); await new Promise(resolve => setTimeout(resolve, 25)); }
while (!(await predicate())) {
if (Date.now() >= end) throw Error(`Cleanup timed out: ${label}`);
await new Promise((resolve) => setTimeout(resolve, 25));
}
};
c.requestHost = async (method, params) => {
c.checkpoint(); if (c.request) throw Error("Concurrent host requests are not supported");
c.checkpoint();
if (c.request) throw Error("Concurrent host requests are not supported");
c.request = { id: ++c.requestId, method, params };
await c.waitFor(() => !c.request, `host ${method}`);
return c.response;
};
c.defer = callback => c.disposers.push(callback);
c.defer = (callback) => c.disposers.push(callback);
c.case = async (testId, featureIds, executeCase) => {
c.checkpoint();
c.activeCase=testId;
c.activeCase = testId;
try {
const evidence = await executeCase();
if (!evidence?.assertions?.length) throw Error('Native case has no assertion evidence');
c.tests.push({ testId, featureIds, status: 'passed', ...evidence });
if (!evidence?.assertions?.length)
throw Error("Native case has no assertion evidence");
c.tests.push({ testId, featureIds, status: "passed", ...evidence });
} catch (error) {
c.tests.push({ testId, featureIds, status: 'failed', reason: String(error.stack || error) });
c.tests.push({
testId,
featureIds,
status: "failed",
reason: String(error.stack || error),
});
throw error;
} finally { delete c.activeCase; }
} finally {
delete c.activeCase;
}
};
c.task = (async () => {
try { c.result = await execute(c, ...args); } catch (error) { c.error = String(error.stack || error); }
finally {
try {
c.result = await execute(c, ...args);
} catch (error) {
c.error = String(error.stack || error);
} finally {
c.state = "cleaning";
for (const [index, dispose] of c.disposers.reverse().entries()) {
c.cleanupPending = index;
try { await dispose(); } catch (error) { c.cleanupErrors.push(String(error)); }
try {
await dispose();
} catch (error) {
c.cleanupErrors.push(String(error));
}
}
delete c.cleanupPending;
c.cleanup = c.cleanupErrors.length ? "failed" : "passed";
+37 -1
View File
@@ -2,6 +2,8 @@ import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { parseCLIJSON, runInAppTask } from "./inAppTask.mjs";
import { collectBehaviorCases } from "./behaviorMatrix.mjs";
import { aggregateReports } from "../contracts.mjs";
function host() {
const state = { setTimeout, clearTimeout, events: [] };
vm.createContext(state);
@@ -40,10 +42,19 @@ test("timeout cancels condition waits, awaits cleanup, then propagates failure",
timeoutMs: 20,
execute: async (c) => {
c.defer(() => events.push("cancel cleanup"));
await c.case("completed-before-deadline", [], async () => ({
assertions: ["completed before the stall"],
}));
await c.waitFor(() => false, "never ready");
},
}),
/deadline/,
(error) =>
/deadline/.test(error.message) &&
error.evidence.some(
(test) =>
test.testId === "completed-before-deadline" &&
test.status === "passed",
),
);
assert.deepEqual(state.events, ["cancel cleanup"]);
assert.equal(
@@ -51,6 +62,31 @@ test("timeout cancels condition waits, awaits cleanup, then propagates failure",
false,
);
});
test("collecting independent behavioral failures retains strict failed acceptance", async () => {
const { cli } = host();
const execute = new Function(
`return async function(c){(${collectBehaviorCases.toString()})(c);await c.case('failed-case',[],async()=>{throw Error('assertion failed')});await c.case('later-case',[],async()=>({assertions:['ran after failed case']}));return {tests:c.tests};}`,
)();
const result = await runInAppTask({ cli, execute });
assert.deepEqual(
result.tests.map((test) => test.status),
["failed", "passed"],
);
const aggregate = aggregateReports(
[
{
schemaVersion: 2,
suiteId: "native-obsidian",
status: "passed",
cleanup: "passed",
tests: result.tests,
},
],
["failed-case", "later-case"],
);
assert.equal(aggregate.status, "failed");
});
test("failed cleanup retains the controller and cannot become a pass", async () => {
const { cli, state } = host();
await assert.rejects(
+63 -14
View File
@@ -32,11 +32,28 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
() => doc.querySelector(".prompt input.prompt-input"),
"trusted command-palette opening",
);
const input = doc.querySelector(".prompt input.prompt-input");
await click(input);
await c.waitFor(
() => doc.activeElement === input,
"palette input focus",
);
await env.input("Input.insertText", { text: selected.name });
let item;
await c.waitFor(() => {
c.caseTrace = {
command: selected.name,
query: input.value,
items: [
...doc.querySelectorAll(".prompt .suggestion-item"),
].map((el) => el.textContent),
};
item = [...doc.querySelectorAll(".prompt .suggestion-item")].find(
(el) => el.textContent.includes(selected.name),
// Obsidian renders the command's namespace and label in separate
// spans, without the colon/space in the registered command name.
(el) =>
el.querySelector(".suggestion-content")?.textContent ===
selected.name.replace(": ", ""),
);
return item;
}, "command-palette search result");
@@ -65,18 +82,16 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
const first = api.getSceneElements()[0],
expectedX = first.x + 19;
api.updateScene({
elements: api
.getSceneElements()
.map((el) =>
el.id === first.id
? {
...el,
x: expectedX,
version: el.version + 1,
versionNonce: el.versionNonce + 1,
}
: el,
),
elements: api.getSceneElements().map((el) =>
el.id === first.id
? {
...el,
x: expectedX,
version: el.version + 1,
versionNonce: el.versionNonce + 1,
}
: el,
),
captureUpdate: "IMMEDIATELY",
});
await c.waitFor(() => view.isDirty(), "palette-save dirty edit");
@@ -178,16 +193,50 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
() => api.getAppState().activeTool.type === "selection",
"selection shortcut",
);
let menuPoint;
const scene = api.getSceneElements(),
state = api.getAppState();
for (const [x, y] of [
[0.15, 0.85],
[0.85, 0.85],
[0.15, 0.35],
]) {
const point = { x: r.x + r.width * x, y: r.y + r.height * y };
const sx = (point.x - r.x) / state.zoom.value - state.scrollX,
sy = (point.y - r.y) / state.zoom.value - state.scrollY;
if (
doc.elementFromPoint(point.x, point.y) === canvas &&
!scene.some(
(el) =>
sx >= el.x - 5 &&
sx <= el.x + el.width + 5 &&
sy >= el.y - 5 &&
sy <= el.y + el.height + 5,
)
) {
menuPoint = point;
break;
}
}
check(menuPoint, "No empty canvas point for the canvas context menu");
for (const type of ["mousePressed", "mouseReleased"])
await env.input("Input.dispatchMouseEvent", {
type,
...a,
...menuPoint,
button: "right",
buttons: type === "mousePressed" ? 2 : 0,
clickCount: 1,
});
let selectAll;
await c.waitFor(() => {
c.caseTrace = {
menuPoint,
contextMenu: api.getAppState().contextMenu,
menuHTML: doc
.querySelector(".context-menu")
?.outerHTML.slice(0, 3000),
events,
};
selectAll = doc.querySelector(
'.context-menu [data-testid="selectAll"] button',
);
+21 -7
View File
@@ -32,13 +32,23 @@ export async function exerciseMarkdownBehavior(c, env, rows) {
"Markdown heading/block and drawing metadata",
);
const activeRoot = (mode) => {
const root = leaf.view.contentEl.querySelector(
mode === "preview"
? ".markdown-preview-view"
: ".markdown-source-view.is-live-preview",
);
const bounds = root?.getBoundingClientRect();
return bounds?.width > 0 && bounds.height > 0 ? root : null;
// Nested embeds retain hidden preview renderers, including in Live Preview.
// Inspect this view's visible renderer rather than the first nested preview.
const root = [
...leaf.view.contentEl.querySelectorAll(
mode === "preview"
? ".markdown-preview-view"
: ".markdown-source-view.is-live-preview",
),
].find((element) => {
const bounds = element.getBoundingClientRect();
return (
bounds.width > 0 &&
bounds.height > 0 &&
!element.closest(".internal-embed")
);
});
return root || null;
};
const open = async (mode) => {
await leaf.setViewState({
@@ -103,6 +113,10 @@ export async function exerciseMarkdownBehavior(c, env, rows) {
view.getViewElements().find((el) => el.id === id).rawText === raw,
"Parsed mode lost the original link source",
);
check(
(await view.saveWithOutcome()).status === "persisted",
"Raw-mode source was not physically saved",
);
await view.changeTextMode("raw");
await c.waitFor(
() =>
+2 -2
View File
@@ -149,7 +149,7 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf
if(typeof actual!=='string'||!existsSync(actual)||realpathSync(actual)!==realpathSync(expectedUserDataPath))throw Error('CLI application user-data identity differs from the held host lock');
report.capabilities.applicationIdentity=realpathSync(actual);
}
if (ownedDebugger) debuggerSession = acquireDebuggerSession(cli);
if (ownedDebugger) { debuggerSession = acquireDebuggerSession(cli); report.capabilities.scheduling = debuggerSession.scheduling; }
if (ownedDebugger) report.capabilities.runtime = parseEval(cli("eval", "code=JSON.stringify({versions:require('process').versions,platform:require('process').platform,userAgent:navigator.userAgent})"));
phase = "build";
@@ -236,7 +236,7 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf
if (companionCleanup && !preserveOwnedFixtures) { try { await companionCleanup(); } catch(error) { report.status="failed"; report.cleanup="failed"; report.cleanupError=String(error); } }
if (debuggerSession) {
try {
report.consoleErrors = debuggerSession.read();
report.consoleErrors = [...debuggerSession.read(), ...report.scenarios.flatMap(s=>s.consoleErrors||[])];
report.unexpectedConsoleErrors = unexpectedConsoleErrors(report.consoleErrors, expectedConsoleErrors);
if (report.unexpectedConsoleErrors.length) { report.status = "failed"; report.error ||= "Unexpected console/JavaScript errors after native cleanup"; }
const errors = ownedCli("dev:errors").trim();
+86 -7
View File
@@ -95,8 +95,68 @@ export async function exerciseSettingsBehavior(c, env, rows) {
export async function exerciseExportBehavior(c, env, rows) {
const { p, check, openDrawing, saveReopen, decode } = env;
const noFrames = { enabled: false, name: false, outline: false, clip: false };
const dimensions = (node) =>
["width", "height"].map((key) => Number.parseFloat(node.getAttribute(key)));
for (const row of rows)
await c.case(row.testId, row.featureIds, async () => {
if (row.id === "export-frame-padding-policy") {
p.settings.defaultMode = "normal";
let view = await openDrawing(row.id);
const ea = p.ea.getAPI(view);
try {
const options = { withBackground: false, theme: "light" },
padding = 7;
const zero = await ea.createViewSVG({ ...options, padding: 0 });
const framed = await ea.createViewSVG({ ...options, padding });
const unframed = await ea.createViewSVG({
...options,
padding,
frameRendering: noFrames,
});
const a = dimensions(zero),
b = dimensions(framed),
d = dimensions(unframed);
check(
a.every((n, i) => Math.abs(n - b[i]) < 1e-8),
"Default frame rendering no longer suppresses padding",
);
check(
d.every((n, i) => Math.abs(n - a[i] - padding * 2) < 1e-8),
"Disabled frame rendering does not restore padding",
);
const defaultPixels = await decode(
await ea.createViewPNG({ ...options, padding, scale: 1 }),
);
const paddedPixels = await decode(
await ea.createViewPNG({
...options,
padding,
scale: 1,
frameRendering: noFrames,
}),
);
check(
Math.abs(defaultPixels.width - b[0]) <= 1 &&
Math.abs(defaultPixels.height - b[1]) <= 1 &&
Math.abs(paddedPixels.width - d[0]) <= 1 &&
Math.abs(paddedPixels.height - d[1]) <= 1,
"Frame policy differs between SVG and decoded PNG",
);
view = await saveReopen(view);
return {
assertions: row.assertions,
defaultDimensions: b,
paddedDimensions: d,
defaultPixels,
paddedPixels,
actual: env.geometry(),
reopened: true,
};
} finally {
ea.destroy();
}
}
const v = row.values;
Object.assign(p.settings, {
defaultMode: "normal",
@@ -130,6 +190,7 @@ export async function exerciseExportBehavior(c, env, rows) {
withBackground: row.expected.background,
padding: row.expected.padding,
theme: row.expected.theme,
frameRendering: noFrames,
});
check(
svg.tagName.toLowerCase() === "svg" && svg.querySelector("path,rect"),
@@ -140,25 +201,31 @@ export async function exerciseExportBehavior(c, env, rows) {
padding: row.expected.padding,
theme: row.expected.theme,
scale: 1,
frameRendering: noFrames,
});
const decoded = await decode(png);
const dimensions = (node) =>
["width", "height"].map((key) =>
Number.parseFloat(node.getAttribute(key)),
);
const [width, height] = dimensions(svg);
const controlPadding = row.expected.padding === 0 ? 3 : 0;
const control = await ea.createViewSVG({
withBackground: row.expected.background,
padding: controlPadding,
theme: row.expected.theme,
frameRendering: noFrames,
});
const [controlWidth, controlHeight] = dimensions(control);
const delta = 2 * (row.expected.padding - controlPadding);
check(
Math.abs(width - controlWidth - delta) < 1e-8 &&
Math.abs(height - controlHeight - delta) < 1e-8,
"Actual SVG geometry does not honor the requested padding, including zero",
"Actual SVG geometry does not honor padding: " +
JSON.stringify({
width,
height,
controlWidth,
controlHeight,
delta,
row,
}),
);
check(
Math.abs(decoded.width - width) <= 1 &&
@@ -166,8 +233,20 @@ export async function exerciseExportBehavior(c, env, rows) {
"Decoded PNG geometry differs from matching SVG options beyond pixel rounding",
);
check(
decoded.width > 100 && decoded.height > 60 && decoded.red > 20,
"Export lost fixture geometry or red content",
decoded.width > 100 &&
decoded.height > 60 &&
decoded.redDominant > 20,
"Export lost fixture geometry or red content: " +
JSON.stringify({ decoded, row }),
);
check(
row.expected.background
? row.expected.theme === "light"
? decoded.redOverWhite > 20
: decoded.dominantOpaque?.every((channel) => channel < 100)
: decoded.halfAlphaRed > 20,
"Decoded fixture opacity/background composition differs: " +
JSON.stringify({ decoded, row }),
);
check(
row.expected.background
+31
View File
@@ -452,6 +452,7 @@
"native:behavior:main:export-10",
"native:behavior:main:export-11",
"native:behavior:main:export-12",
"native:behavior:main:export-frame-padding-policy",
"native:behavior:main:settings-live-persistence",
"native:behavior:main:frontmatter-prefixes-theme-scale",
"native:behavior:split:settings-01",
@@ -482,6 +483,7 @@
"native:behavior:split:export-10",
"native:behavior:split:export-11",
"native:behavior:split:export-12",
"native:behavior:split:export-frame-padding-policy",
"native:behavior:split:settings-live-persistence",
"native:behavior:split:frontmatter-prefixes-theme-scale",
"native:behavior:nested-split:settings-01",
@@ -512,6 +514,7 @@
"native:behavior:nested-split:export-10",
"native:behavior:nested-split:export-11",
"native:behavior:nested-split:export-12",
"native:behavior:nested-split:export-frame-padding-policy",
"native:behavior:nested-split:settings-live-persistence",
"native:behavior:nested-split:frontmatter-prefixes-theme-scale",
"native:behavior:popout:settings-01",
@@ -542,6 +545,7 @@
"native:behavior:popout:export-10",
"native:behavior:popout:export-11",
"native:behavior:popout:export-12",
"native:behavior:popout:export-frame-padding-policy",
"native:behavior:popout:settings-live-persistence",
"native:behavior:popout:frontmatter-prefixes-theme-scale",
"native:behavior:phone:settings-01",
@@ -572,6 +576,7 @@
"native:behavior:phone:export-10",
"native:behavior:phone:export-11",
"native:behavior:phone:export-12",
"native:behavior:phone:export-frame-padding-policy",
"native:behavior:phone:settings-live-persistence",
"native:behavior:phone:frontmatter-prefixes-theme-scale",
"native:behavior:tablet:settings-01",
@@ -602,6 +607,7 @@
"native:behavior:tablet:export-10",
"native:behavior:tablet:export-11",
"native:behavior:tablet:export-12",
"native:behavior:tablet:export-frame-padding-policy",
"native:behavior:tablet:settings-live-persistence",
"native:behavior:tablet:frontmatter-prefixes-theme-scale"
]
@@ -894,6 +900,7 @@
"native:behavior:main:export-10",
"native:behavior:main:export-11",
"native:behavior:main:export-12",
"native:behavior:main:export-frame-padding-policy",
"native:behavior:main:frontmatter-prefixes-theme-scale",
"native:behavior:main:images-shared-crops",
"native:behavior:main:drawing-and-markdown-embeds",
@@ -909,6 +916,7 @@
"native:behavior:split:export-10",
"native:behavior:split:export-11",
"native:behavior:split:export-12",
"native:behavior:split:export-frame-padding-policy",
"native:behavior:split:frontmatter-prefixes-theme-scale",
"native:behavior:split:images-shared-crops",
"native:behavior:split:drawing-and-markdown-embeds",
@@ -924,6 +932,7 @@
"native:behavior:nested-split:export-10",
"native:behavior:nested-split:export-11",
"native:behavior:nested-split:export-12",
"native:behavior:nested-split:export-frame-padding-policy",
"native:behavior:nested-split:frontmatter-prefixes-theme-scale",
"native:behavior:nested-split:images-shared-crops",
"native:behavior:nested-split:drawing-and-markdown-embeds",
@@ -939,6 +948,7 @@
"native:behavior:popout:export-10",
"native:behavior:popout:export-11",
"native:behavior:popout:export-12",
"native:behavior:popout:export-frame-padding-policy",
"native:behavior:popout:frontmatter-prefixes-theme-scale",
"native:behavior:popout:images-shared-crops",
"native:behavior:popout:drawing-and-markdown-embeds",
@@ -954,6 +964,7 @@
"native:behavior:phone:export-10",
"native:behavior:phone:export-11",
"native:behavior:phone:export-12",
"native:behavior:phone:export-frame-padding-policy",
"native:behavior:phone:frontmatter-prefixes-theme-scale",
"native:behavior:phone:images-shared-crops",
"native:behavior:phone:drawing-and-markdown-embeds",
@@ -969,6 +980,7 @@
"native:behavior:tablet:export-10",
"native:behavior:tablet:export-11",
"native:behavior:tablet:export-12",
"native:behavior:tablet:export-frame-padding-policy",
"native:behavior:tablet:frontmatter-prefixes-theme-scale",
"native:behavior:tablet:images-shared-crops",
"native:behavior:tablet:drawing-and-markdown-embeds"
@@ -1858,6 +1870,19 @@
}
],
"workflows": [
{
"id": "export-frame-padding-policy",
"features": [
"P06",
"P09"
],
"assertions": [
"default frame rendering suppresses padding, including scenes without frames",
"disabling frame rendering enables the requested padding",
"actual SVG and decoded PNG dimensions agree",
"saved scene survives reopen"
]
},
{
"id": "cli-atomic-targeted-edit",
"features": [
@@ -2067,6 +2092,7 @@
"native:behavior:main:export-10",
"native:behavior:main:export-11",
"native:behavior:main:export-12",
"native:behavior:main:export-frame-padding-policy",
"native:behavior:main:cli-atomic-targeted-edit",
"native:behavior:main:settings-live-persistence",
"native:behavior:main:frontmatter-prefixes-theme-scale",
@@ -2109,6 +2135,7 @@
"native:behavior:split:export-10",
"native:behavior:split:export-11",
"native:behavior:split:export-12",
"native:behavior:split:export-frame-padding-policy",
"native:behavior:split:cli-atomic-targeted-edit",
"native:behavior:split:settings-live-persistence",
"native:behavior:split:frontmatter-prefixes-theme-scale",
@@ -2151,6 +2178,7 @@
"native:behavior:nested-split:export-10",
"native:behavior:nested-split:export-11",
"native:behavior:nested-split:export-12",
"native:behavior:nested-split:export-frame-padding-policy",
"native:behavior:nested-split:cli-atomic-targeted-edit",
"native:behavior:nested-split:settings-live-persistence",
"native:behavior:nested-split:frontmatter-prefixes-theme-scale",
@@ -2193,6 +2221,7 @@
"native:behavior:popout:export-10",
"native:behavior:popout:export-11",
"native:behavior:popout:export-12",
"native:behavior:popout:export-frame-padding-policy",
"native:behavior:popout:cli-atomic-targeted-edit",
"native:behavior:popout:settings-live-persistence",
"native:behavior:popout:frontmatter-prefixes-theme-scale",
@@ -2235,6 +2264,7 @@
"native:behavior:phone:export-10",
"native:behavior:phone:export-11",
"native:behavior:phone:export-12",
"native:behavior:phone:export-frame-padding-policy",
"native:behavior:phone:cli-atomic-targeted-edit",
"native:behavior:phone:settings-live-persistence",
"native:behavior:phone:frontmatter-prefixes-theme-scale",
@@ -2277,6 +2307,7 @@
"native:behavior:tablet:export-10",
"native:behavior:tablet:export-11",
"native:behavior:tablet:export-12",
"native:behavior:tablet:export-frame-padding-policy",
"native:behavior:tablet:cli-atomic-targeted-edit",
"native:behavior:tablet:settings-live-persistence",
"native:behavior:tablet:frontmatter-prefixes-theme-scale",