diff --git a/.github/workflows/native-tests.yml b/.github/workflows/native-tests.yml new file mode 100644 index 00000000..646aed69 --- /dev/null +++ b/.github/workflows/native-tests.yml @@ -0,0 +1,71 @@ +name: Trusted isolated native tests +# Manual exact-SHA approval only. Never use pull_request_target or an untrusted +# PR trigger on a persistent desktop. Configure the protected environment and +# an isolated runner with no personal vaults/secrets before enabling this lane. +on: + workflow_dispatch: + inputs: + tested_sha: + description: Exact 40-character plugin commit approved for this run + required: true + profile: + type: choice + options: [smoke, full, devices, soak] + default: smoke +permissions: + contents: read +jobs: + native: + environment: native-test-approval + runs-on: [self-hosted, Windows, excalidraw-isolated] + timeout-minutes: 90 + env: + EXCALIDRAW_TEST_VAULT_NAME: ${{ vars.EXCALIDRAW_TEST_VAULT_NAME }} + EXCALIDRAW_TEST_VAULT_PATH: ${{ vars.EXCALIDRAW_TEST_VAULT_PATH }} + EXCALIDRAW_TEST_CONFIG_DIR: ${{ vars.EXCALIDRAW_TEST_CONFIG_DIR }} + EXCALIDRAW_TEST_AUTOMATION_ROOT: ${{ vars.EXCALIDRAW_TEST_AUTOMATION_ROOT }} + EXCALIDRAW_TEST_USER_DATA_PATH: ${{ vars.EXCALIDRAW_TEST_USER_DATA_PATH }} + EXCALIDRAW_TEST_REPORT_DIR: ${{ github.workspace }}/.test-work/reports/native-ci + EXCALIDRAW_FORK_ROOT: ${{ github.workspace }}/.test-work/checkouts/fork + EXCALIDRAW_TEST_FORK_TYPES_ROOT: ${{ github.workspace }}/.test-work/checkouts/fork + EXCALIDRAW_EXTRAS_ROOT: ${{ github.workspace }}/.test-work/checkouts/extras + steps: + - name: Require an exact approved commit + env: + TESTED_SHA: ${{ inputs.tested_sha }} + run: if ($env:TESTED_SHA -notmatch '^[a-f0-9]{40}$') { throw 'Supply an exact approved commit SHA' } + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tested_sha }} + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: zsviczian/excalidraw + ref: d04bc1a6211a15394a1cc7036e7a7532608bf421 + path: .test-work/checkouts/fork + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: zsviczian/obsidian-excalidraw-extras + ref: e37c06feff9fef48877f565328762433a676afcc + path: .test-work/checkouts/extras + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '22.22.3' + - name: Prove session ownership before any native mutation + run: node scripts/testing/host/requireIsolatedSession.mjs + - run: npm ci + - run: corepack enable + - run: yarn --cwd .test-work/checkouts/fork install --frozen-lockfile + - run: npm ci --prefix .test-work/checkouts/extras + - name: Run approved native profile + env: + TEST_PROFILE: ${{ inputs.profile }} + run: node scripts/testing/host/verify.mjs "--profile=$env:TEST_PROFILE" + - uses: actions/upload-artifact@v4 + if: always() + with: + name: native-${{ inputs.profile }}-${{ inputs.tested_sha }} + path: .test-work/reports + if-no-files-found: error diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..4ce4b803 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,56 @@ +name: Plugin tests +on: + pull_request: + push: + branches: [master] + workflow_dispatch: +permissions: + contents: read +jobs: + portable: + runs-on: ubuntu-latest + timeout-minutes: 35 + env: + EXCALIDRAW_FORK_ROOT: ${{ github.workspace }}/.test-work/checkouts/fork + EXCALIDRAW_TEST_FORK_TYPES_ROOT: ${{ github.workspace }}/.test-work/checkouts/fork + EXCALIDRAW_EXTRAS_ROOT: ${{ github.workspace }}/.test-work/checkouts/extras + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: zsviczian/excalidraw + ref: d04bc1a6211a15394a1cc7036e7a7532608bf421 + path: .test-work/checkouts/fork + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: zsviczian/obsidian-excalidraw-extras + ref: e37c06feff9fef48877f565328762433a676afcc + path: .test-work/checkouts/extras + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '22.22.3' + cache: npm + - run: npm ci + - run: corepack enable + - run: yarn --cwd .test-work/checkouts/fork install --frozen-lockfile + - run: npm ci --prefix .test-work/checkouts/extras + - name: Build and freeze the reviewed workspace combination + run: npm run test:build-workspace + - run: npm run lib + - run: npm run test:fixtures + - run: npm run test:inventory + - run: npm run test:features + - run: npm run test:fast + - run: npm run test:source-coverage + - run: node --check dist/main.js + - uses: actions/upload-artifact@v4 + if: always() + with: + name: plugin-portable-evidence + path: | + .test-work/reports + .test-work/frozen/**/combination.json + .test-work/frozen/**/artifacts.json + if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index ffc82427..261dcff7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -517,11 +517,11 @@ If a task touches any of the above, read adjacent code first and validate more c ## Validation Expectations -There is no comprehensive runtime unit-test suite. The CLI harness has focused tests wired into `package.json`. +Use the layered test commands and explicit acceptance limits documented below. Fast/source tests, built artifacts, native integration and physical devices establish different evidence. ### Obsidian CLI runtime lane -Follow [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md) for macOS and Windows setup, and its linked fork guide for feature gates. `npm run test:obsidian:runner` tests the vault guards and platform launchers without Obsidian. `npm run verify:obsidian:plugin` builds this plugin with the installed component package. `npm run verify:obsidian` first builds and copies the sibling fork's four Obsidian artifacts. Both native lanes require the explicitly configured `excalidraw-test` vault, check the CLI-selected vault and config paths before deployment, stage the exact `main.js`/CSS/manifest, and assert a live drawing and clean JavaScript error buffer. Review the report's build mode, source identity, hashes, and cleanup result. A previous local artifact copy into `node_modules` remains in effect for the plugin-only lane until `npm install` restores the published package. +Start with the layered [testing guide](docs/TESTING.md) and [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md). Use the discovered fast suite, source ratchets, immutable fixture/inventory/feature guards and workspace smoke/full/device/soak profiles. Specific maintained scripts are tested in ea-scripts; focus this repository on core Excalidraw and ExcalidrawAutomate. Preserve explicit remaining feature obligations and inherited failures. Native lanes require an explicitly configured `excalidraw-test` or marker-verified owned automation vault, validate CLI-selected vault/config paths before deployment and serialize all native work under the application-user-data lock. Review frozen source identities, installed hashes, actual geometry/input, errors and cleanup. The plugin-only lane retains any earlier ignored runtime copy until `npm install` restores the published package; it is not published-package verification. Look for an existing `excalidraw-test` vault in Obsidian's vault registry and confirm its path and enabled plugin. If absent, ask the user to create it and install/enable Excalidraw from Community plugins before deployment. Do not create or download a replacement vault without consent. Complete any first-open trust prompt and reopen the vault before CLI probes. Never choose a personal/default vault when the test vault is unavailable. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3d30ac9d..0d312ae2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,7 +68,7 @@ conflict handling, and the one-time adoption procedure for older workspaces. ## 🧪 Testing -At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly. +Use the layered [test lanes and maintenance guide](docs/TESTING.md): discovered fast tests, actual source-mapped coverage, production artifact checks and guarded native smoke/full/device/soak profiles. Build before running the fast suite because it inspects the shipped bundle. Keep the source-linked feature registry and public-surface inventory current; neither inventory nor a passing smoke establishes complete coverage. Native, inherited-suite and physical-device limitations remain explicit in the checkpoint record. Focus this suite on core Excalidraw and ExcalidrawAutomate; maintained scripts have their own tests in ea-scripts. The native CLI lane supports macOS and Windows. Run `npm run test:obsidian:runner` for the offline harness tests, then `npm run verify:obsidian:plugin` to build and diff --git a/RefactorPlan.md b/RefactorPlan.md index b8899e95..68be0bfb 100644 --- a/RefactorPlan.md +++ b/RefactorPlan.md @@ -27,7 +27,7 @@ validated, and what remains uncertain. | Phase | Status | Current outcome | | --- | --- | --- | | Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented | -| Automated test coverage (#3022) | In progress; source, data and lifecycle checkpoint | 403 fast tests and 59 source-mapped tests pass; native data, dirty migrations/reload and real Extras/PDF checks pass. Fork-owned/browser and Extras source/browser checks pass. Inherited failures and incomplete feature/device/package/CI gates remain explicit; see docs/TESTING_BASELINE_3022.md | +| Automated test coverage (#3022) | In progress; core feature, device and frozen-workspace checkpoint | 414 fast tests and 59 source-mapped tests pass. Native core EA, trusted toolbar/history/custom-highlighter/laser, six large-scene cycles and 40 device cases pass. Fork/Extras owned source, browser and package gates pass; CI and source-linked P01–P12 obligations are added. Full native error acceptance, isolated cold restart and remaining core cases are explicit; see docs/TESTING_BASELINE_3022.md | | Template selection and cancellation (#2649, PR #3020) | Implemented; source and native selection/cancellation checks pass | A dedicated chooser returns template/blank/cancel, displays paths relative to the configured root, and initially selects explicit blank. Interactive callers resolve before folder/file/editor/leaf side effects. Public getBlankDrawing/createDrawing and EA/CLI contracts retain string/file returns and deterministic initData behavior | | Nested-split fullscreen (#2743, PR #3020) | Implemented; seven source tests and native lower-right split pass | Keep the complete ancestor path visible; hide surrounding siblings and restore only owned classes. Native 958x641 drawing expands to 2560x1438 and returns to identical bounds. Existing inline styles remain untouched; controls are optional and cleanup retains the entry document across migration | | Canvas preview scaling investigation (#2729, PR #3020) | Original SVG-only behavior not reproduced on Windows Obsidian 1.14.5; unresolved | Two nodes sharing a drawing scale independently in SVG, SVG-as-image and PNG with immersive mode on/off. Doubling one node width scales its preview by 2.0063; the other remains unchanged. Tall previews clip in all modes. No speculative rendering/cache change; retain measurements and keep the issue open | @@ -2940,3 +2940,13 @@ Highest-risk follow-up: cancellation while a popout is destroyed, workspace restoration across actual mobile-mode reloads, and delayed deletion callbacks. Validate main/new/restored popouts, phone/tablet orientation and theme changes; macOS/Linux, minimum hosts and physical Android/iOS remain separate gates. + +### 2026-10-28 - Core features, frozen producers and device boundaries (#3022) + +Added immutable three-repository production/declaration staging, companion byte/path negative controls, per-scenario owned drawings and settle-before-cleanup adapters for legacy probes. Fork checkpoint d04bc1a6 and Extras e37c06fe are pushed independently. Plugin fast discovery passes 414 tests in 42 files; source ratchets pass 59 whole-module tests. Forty native device/breakpoint cases pass. Direct EA shapes/bindings/groups/frames/bound text, isolated edits, image data, SVG import, decoded exports and disposal pass; trusted toolbar/history/custom highlighter/laser cases and six 1000-element reopen cycles also pass cleanly. + +All twelve broader native functional scenarios passed on frozen bytes, but that overall diagnostic failed with illegal-access teardown exceptions and two post-delete ENOENT errors. Native Vault-delete retirement fixes the cleanup sequence; a subsequent stability/text/link run has zero errors. Full repeat is pending. Electron 43.3.0 matches a known teardown defect fixed in 43.5.0; this is a host-cause hypothesis until confirmed on a fixed host. No broad error filtering or production teardown workaround was added. Fault-injection notices now dismiss only the exact UUID-owned failed-write notification. + +Maintainer direction narrows this PR to core Excalidraw and ExcalidrawAutomate. Removed the exploratory maintained-script scenario from the suite; ea-scripts remains the owner of script-specific tests. Added a source/fixture/test-linked P01-P12 registry with remaining obligations, hosted portable CI and manual exact-SHA isolated-native CI. Neither inventory nor CI configuration is represented as executed behavioral evidence. + +Highest-risk follow-up: repeat native main/popout teardown and deletion with the clean-error gate, verify pen state after switching tools and after reload, and run the bounded soak. Main-window and fresh/moved popout workflows need separate checks; macOS/Linux and physical Android/iOS remain separate platform gates. Do not restart the shared application to substitute for an isolated cold-start test. diff --git a/docs/OBSIDIAN_RUNTIME_TESTING.md b/docs/OBSIDIAN_RUNTIME_TESTING.md index 792a53d5..da1947eb 100644 --- a/docs/OBSIDIAN_RUNTIME_TESTING.md +++ b/docs/OBSIDIAN_RUNTIME_TESTING.md @@ -495,7 +495,9 @@ force-close the application while other vaults are open. After interrupted clean review the report/controller's exact drawing path before removing leftovers; never delete notes by prefix alone. -The default smoke covers one newly created main-window drawing. It does not validate +The historical default smoke covers one newly created main-window drawing. For the +current reproducible workspace smoke/full/device/soak profiles, source and fixture +guards, see [the maintained testing guide](TESTING.md). A smoke alone does not validate saved scenes, clipboard, text editing, fonts/images, export, custom pens, popout migration, offline assets, or physical mobile touch. For affected features, follow the fork's [native validation procedure](https://github.com/zsviczian/excalidraw/blob/master/dev-docs/Obsidian/OBSIDIAN_RUNTIME_TESTING.md) diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 00000000..75d47c98 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,100 @@ +# Maintaining the test lanes + +Use Node 22.22.3, npm here and in Extras, and Yarn in the fork. Source-mapped +tests use Node's synchronous registration hooks and require Node 22.15 or newer. +The plugin still supports its declared Obsidian minimum; the native CLI has a +separate installer floor (1.12.7) and desktop-only transport. + +## Portable checks + +Install each checkout's declared dependencies. Set `EXCALIDRAW_FORK_ROOT`, +`EXCALIDRAW_TEST_FORK_TYPES_ROOT` and `EXCALIDRAW_EXTRAS_ROOT` to explicit sibling +checkouts when they are elsewhere. Then run: + +```sh +npm run test:build-workspace +npm run lib +npm run test:fixtures +npm run test:inventory +npm run test:features +npm run test:fast +npm run test:source-coverage +``` + +Build first: the fast command includes production-bundle assertions. Every +repository-owned `.test.mjs` is discovered; zero discovery, missing files, +duplicate IDs, failed/todo/skipped cases and ratchet regressions fail. Regenerate +`tests/inventory.json` with `node scripts/testing/inventory.mjs` after intentional +surface/test changes, then review the diff. Fixture changes require the same +deliberate regeneration/review through `scripts/testing/fixtures.mjs`. + +`tests/features.json` maps P01–P12 source anchors, fixture IDs, executable cases, +success/failure/cleanup expectations and remaining obligations. It is an +obligation list. A mapping or AST inventory is not execution coverage of every +command, setting, EA method or hook. Keep unresolved cases in the denominator. +Source coverage measures actual compiled production modules with source maps; +historical extraction/VM tests receive no original-source coverage credit. + +## Native workspace profiles + +Set all of these explicitly; never fall back to an active vault: + +```sh +EXCALIDRAW_TEST_VAULT_NAME=excalidraw-test +EXCALIDRAW_TEST_VAULT_PATH=/absolute/path/excalidraw-test +EXCALIDRAW_TEST_CONFIG_DIR=/absolute/path/excalidraw-test/.obsidian +EXCALIDRAW_TEST_REPORT_DIR=/absolute/path/to/new-report-directory +``` + +Use environment assignment appropriate to the shell. Other vault names require +the provisioner's ownership marker and `EXCALIDRAW_TEST_AUTOMATION_ROOT`. +Provisioning copies the immutable CC0 synthetic seed; it does not register a +vault or alter Obsidian's global registry. Initial installer, CLI registration, +vault opening, community-plugin trust and install/discovery are explicit setup +prerequisites. See [the runner contract](testing-contracts.md) and +[runtime transport guidance](OBSIDIAN_RUNTIME_TESTING.md). + +| Command | Required work | +| --- | --- | +| `npm run verify:obsidian:smoke` | Build/freeze/stage all three repositories; load commands, protocol and one main-window drawing | +| `npm run verify:obsidian:full` | Smoke plus data/lifecycle, real Extras services/PDF, workflow/pickers, Lucide, text/history, images/embeds, wheel, CLI, links, LaTeX input, core EA authoring, stability and device matrix | +| `npm run verify:obsidian:devices` | Smoke then 40 measured desktop/mobile-emulation/theme/layout/breakpoint cases | +| `npm run verify:obsidian:soak` | Smoke then 25 bounded 1,000-element open/edit/save/export/close cycles | + +Each producer freezes bytes and generated declaration evidence before staging. +Only the four runtime fork artifacts are copied to the installed exact npm +package; dependency pins and published declarations remain unchanged. This is +workspace verification, not a published-package release claim. Reports record +producer commits, dirty-diff/lockfile hashes and installed artifact hashes. +The maintainer has deferred fork publication and the plugin pin update. + +Native calls run serially under the shared application-user-data lock. Never +steal DevTools/debugger ownership. Async host operations settle before cleanup; +unsettled work preserves its exact owned fixtures/controller for guarded +recovery. Each scenario gets a separate UUID-owned drawing. Dirty cleanup saves +first, then uses the Vault delete event to retire the view before detaching. +Do not globally clear IndexedDB or delete notes by prefix. A nonpassing required +scenario, unexpected error or failed cleanup fails the suite. + +Desktop emulation uses actual Obsidian mobile mode and trusted input, but does +not establish physical Android/iOS WebView, stylus, native keyboard or safe-area +behavior. Whole-application restart is allowed only in an isolated automation +session. Plugin reload is separate evidence and must never be called cold restart. + +## Current acceptance evidence + +[The baseline/checkpoint record](TESTING_BASELINE_3022.md) preserves first +attempts, inherited failures and unavailable lanes. Raw machine-specific reports +are ignored under `.test-work/reports` and `tmp/pr3022-baseline`. + +On the current Windows host (Obsidian 1.14.5, installer 1.14.0, Electron 43.3.0), +the full functional scenarios pass but popout teardown emits `illegal access` +exceptions, so the overall run fails. Electron documents this class of teardown +failure and its fix in 43.5.0; that is a likely explanation requiring confirmation +on a fixed host. Keep the errors visible, without wildcard suppression. +See [Electron's fix/release record](https://releases.electronjs.org/pr/53041). + +The fork's additive owned gate and inherited compatibility diagnostic are +independent. The latter currently fails; it must not become a skipped or +`continue-on-error` green gate. The three repositories' workflows upload reports +even on failure. Ordinary hosted CI never launches Obsidian or accesses vaults. diff --git a/docs/TESTING_BASELINE_3022.md b/docs/TESTING_BASELINE_3022.md index 8b2d3a9c..b17f3593 100644 --- a/docs/TESTING_BASELINE_3022.md +++ b/docs/TESTING_BASELINE_3022.md @@ -71,3 +71,15 @@ Portable JSON schemas and executable byte/path/report validation are under `scripts/testing/`; the shared contract is [documented here](testing-contracts.md). Future checkpoints must retain first-attempt failures, required blocked lanes, inherited-suite results and physical/legacy/platform gaps explicitly. + +## Core/device/frozen-workspace checkpoint + +- Plugin: 414 fast tests in 42 files; 59 measured whole-module tests with ratchets pass. Direct native EA authoring, image/decoded export, SVG import and disposal pass. Trusted toolbar/history, custom highlighter and transient-laser semantics pass. +- Devices: 40 measured desktop/mobile-emulation/theme/layout/breakpoint cases pass, including exact boundaries and trusted input. Physical mobile remains untested. +- Stability: six 1000-element edit/save/reopen cycles pass with fresh APIs, retired roots and actual decoded PNG pixels; the subsequent 16 text/history variants and grouped-link checks pass with zero captured errors. +- Fork d04bc1a6: 93 owned tests, 12 built-browser cases, full/owned typechecks and clean packed consumer pass. Selected source coverage is 43.2% lines, 61.08% branches, 40.52% functions. Eighteen runtime modules remain unexecuted. The inherited lane stays failed: 2264 pass, 380 fail, 47 pending, one todo (2692 total). The required root update diagnostic also failed; all 16 generated golden changes were restored. +- Extras e37c06fe: 30 source tests/ratchets, four production-bundle browser cases, production/API builds and clean packed API consumer pass. Native real MathJax, editable Mermaid and PDF checks pass; PDF is one 288x216pt page with text and 3330 red SVG pixels. + +The full frozen diagnostic has 12 passing functional scenarios and passing owned cleanup, but its overall error gate fails: three primitive illegal-access exceptions and two ENOENT errors after fixture deletion. A revised save-then-Vault-delete retirement sequence passes a later multi-scenario clean run; full repeat remains required. Electron documents the matching child-window teardown defect as fixed in 43.5.0 (https://releases.electronjs.org/pr/53041), newer than this host's 43.3.0. Treat the match as a hypothesis requiring a fixed-host run, not an approved suppression. + +Earlier exploratory maintained-script evidence is retained only in ignored diagnostics. Script-specific coverage is outside this PR following maintainer direction; core EA has its own direct native cases. Current remaining obligations are tracked in tests/features.json. Hosted and exact-SHA trusted-native workflows are implemented but have not yet run remotely. Native cold restart/fresh session registration, legacy/minimum hosts, macOS/Linux and physical Android/iOS are explicit unavailable gates in this shared session. diff --git a/package.json b/package.json index b4be5243..d6a4a500 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,12 @@ "test:source-coverage": "node scripts/testing/runFast.mjs --coverage", "test:fixtures": "node scripts/testing/fixtures.mjs --check", "test:inventory": "node scripts/testing/inventory.mjs --check", + "test:features": "node scripts/testing/features.mjs", + "test:build-workspace": "node scripts/testing/buildWorkspace.mjs", + "verify:obsidian:smoke": "node scripts/testing/host/verify.mjs --profile=smoke", + "verify:obsidian:full": "node scripts/testing/host/verify.mjs --profile=full", + "verify:obsidian:devices": "node scripts/testing/host/verify.mjs --profile=devices", + "verify:obsidian:soak": "node scripts/testing/host/verify.mjs --profile=soak", "test:provision": "node scripts/testing/provision.mjs", "test:bundle": "node --test scripts/testing/bundle.test.mjs", "test:drawing-load-error": "node --test scripts/testing/drawingLoadError.test.mjs", diff --git a/scripts/testing/buildWorkspace.mjs b/scripts/testing/buildWorkspace.mjs new file mode 100644 index 00000000..3f391bbe --- /dev/null +++ b/scripts/testing/buildWorkspace.mjs @@ -0,0 +1,11 @@ +/** Hosted/native producers share the same immutable three-repository handoff. */ +import {randomUUID} from 'node:crypto'; +import {dirname,join,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {produceCombination} from './host/combination.mjs'; +const pluginRoot=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +const combination=produceCombination({pluginRoot, + forkRoot:resolve(process.env.EXCALIDRAW_FORK_ROOT||join(pluginRoot,'../excalidraw')), + extrasRoot:resolve(process.env.EXCALIDRAW_EXTRAS_ROOT||join(pluginRoot,'../obsidian-excalidraw-extras')), + output:resolve(process.env.EXCALIDRAW_TEST_COMBINATION_OUTPUT||join(pluginRoot,'.test-work/frozen/combination-'+randomUUID()))}); +process.stdout.write(`Frozen three-repository workspace: ${combination.output}\n`); diff --git a/scripts/testing/contracts.mjs b/scripts/testing/contracts.mjs index e4839764..3ed2dd5f 100644 --- a/scripts/testing/contracts.mjs +++ b/scripts/testing/contracts.mjs @@ -129,7 +129,7 @@ export function aggregateReports(reports, requiredTestIds) { const unsuccessful = tests.filter(t => t.status !== "passed" && (t.status !== "notApplicable" || requiredTestIds.includes(t.testId))); const failedCleanup = reports.some(r => r.cleanup !== "passed" || r.status !== "passed"); return { schemaVersion: SCHEMA_VERSION, suiteId: "aggregate", status: missing.length || unsuccessful.length || failedCleanup ? "failed" : "passed", - cleanup: reports.every(r => r.cleanup === "passed") ? "passed" : "failed", missing, tests }; + cleanup: reports.every(r => r.cleanup === "passed") ? "passed" : "failed", requiredTestIds, missing, tests }; } /** Stable discovery used by the fixture/discovery gate; never follows links. */ diff --git a/scripts/testing/features.mjs b/scripts/testing/features.mjs new file mode 100644 index 00000000..78d55448 --- /dev/null +++ b/scripts/testing/features.mjs @@ -0,0 +1,29 @@ +/** Source-linked obligations are a denominator, never a substitute for execution. */ +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {dirname,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {ownedPath} from './contracts.mjs'; +export const projectRoot=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +export function validateFeatures(registry,root=projectRoot){ + assert.equal(registry.schemaVersion,2,'Unsupported feature schema'); + const fixtures=new Set(JSON.parse(readFileSync(ownedPath(root,'tests/fixtures/manifest.json'))).fixtures.map(f=>f.id)); + assert.deepEqual(registry.features.map(f=>f.id),Array.from({length:12},(_,i)=>'P'+String(i+1).padStart(2,'0')),'P01–P12 denominator changed'); + for(const feature of registry.features){ + assert.ok(['P0','P1'].includes(feature.priority)&&feature.name&&feature.success&&feature.failure&&feature.cleanup,'Feature obligations missing: '+feature.id); + assert.ok(feature.platforms.length&&feature.anchors.length&&feature.tests.length,'Feature mapping empty: '+feature.id); + for(const anchor of feature.anchors){const text=readFileSync(ownedPath(root,anchor.path),'utf8');assert.ok(anchor.symbol&&text.includes(anchor.symbol),'Stale feature anchor: '+anchor.path+' '+anchor.symbol);} + for(const id of feature.fixtures)assert.ok(fixtures.has(id),'Unknown fixture: '+id); + for(const test of feature.tests){assert.ok(['source','native','browser','artifact'].includes(test.layer),'Unknown test layer');ownedPath(root,test.path);assert.ok(test.cases?.length,'Missing executable case IDs');} + assert.ok(Array.isArray(feature.remaining),'Remaining obligations must be explicit'); + } + // Public entries stay enumerated individually. Mapping a family does not claim + // that all 187 settings, 161 EA entries or commands were behaviorally tested. + const inventory=JSON.parse(readFileSync(ownedPath(root,'tests/inventory.json'))); + return {features:registry.features.length,remaining:registry.features.flatMap(f=>f.remaining.map(reason=>({featureId:f.id,reason}))), + publicSurface:Object.fromEntries(['commands','publicEA','settings','cliCommands','hooks'].map(key=>[key,{discovered:inventory[key].length,entries:inventory[key].map(entry=>({...entry,behavioralCoverage:'not inferred from inventory'}))}]))}; +} +if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){ + const evidence=validateFeatures(JSON.parse(readFileSync(ownedPath(projectRoot,'tests/features.json')))); + process.stdout.write(`${evidence.features} feature groups mapped; ${evidence.remaining.length} explicit remaining obligations. Inventory is discovery, not coverage.\n`); +} diff --git a/scripts/testing/features.test.mjs b/scripts/testing/features.test.mjs new file mode 100644 index 00000000..e806d3b2 --- /dev/null +++ b/scripts/testing/features.test.mjs @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {readFileSync} from 'node:fs'; +import {validateFeatures} from './features.mjs'; +const registry=()=>JSON.parse(readFileSync(new URL('../../tests/features.json',import.meta.url))); +test('feature map retains the full denominator and public surfaces without inferred execution',()=>{ + const result=validateFeatures(registry());assert.equal(result.features,12);assert.equal(result.publicSurface.publicEA.discovered,161); + assert.ok(result.remaining.length>0);assert.equal(result.publicSurface.settings.entries[0].behavioralCoverage,'not inferred from inventory'); +}); +test('feature drift, missing test files, stale anchors and unowned fixture references fail closed',()=>{ + let r=registry();r.features.pop();assert.throws(()=>validateFeatures(r),/denominator/); + r=registry();r.features[0].anchors[0].symbol='missing-owned-source-anchor';assert.throws(()=>validateFeatures(r),/Stale/); + r=registry();r.features[0].tests[0].path='../private.test.mjs';assert.throws(()=>validateFeatures(r),/traversal/); + r=registry();r.features[0].fixtures=['not-a-fixture'];assert.throws(()=>validateFeatures(r),/Unknown fixture/); +}); diff --git a/scripts/testing/host/automate.mjs b/scripts/testing/host/automate.mjs new file mode 100644 index 00000000..a0a778aa --- /dev/null +++ b/scripts/testing/host/automate.mjs @@ -0,0 +1,74 @@ +/** Direct public EA workflows on an owned editor, independent of user scripts. */ +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {runInAppTask} from './inAppTask.mjs'; +export async function runAutomateScenario({cli,drawingPath}){ + assert.ok(drawingPath.startsWith('__excalidraw_cli_smoke_')); + const png=readFileSync(new URL('../../../tests/vault/Assets/Transparency.png',import.meta.url)).toString('base64'); + const svg=readFileSync(new URL('../../../tests/vault/Assets/Layers.svg',import.meta.url),'utf8'); + const result=await runInAppTask({cli,execute:exerciseAutomate,args:[drawingPath,png,svg],timeoutMs:150000}); + return {id:'core-excalidraw-automate',status:'passed',...result}; +} +async function exerciseAutomate(c,drawingPath,png,svgSource){ + const p=app.plugins.plugins['obsidian-excalidraw-plugin'],view=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===drawingPath)?.view; + const check=(value,label)=>{if(!value)throw Error(label);}; + check(view?.excalidrawAPI,'Owned EA target missing'); + const ea=p.ea.getAPI(view),other=p.ea.getAPI(view);let cleanups=0; + c.defer(()=>{ea.destroy();other.destroy();check(ea.targetView===null&&Object.keys(ea.elementsDict).length===0&&Object.keys(ea.imagesDict).length===0,'EA retained target/scene resources');check(cleanups===1,'EA cleanup did not run exactly once');}); + ea.registerCleanup(()=>cleanups++); + let left,right,arrow,frame,label,group; + await c.case('native:ea-shapes-bindings-and-isolation',['P07','P10'],async()=>{ + ea.setStyle({backgroundColor:'#ff0000',fillStyle:'solid',strokeColor:'#1e1e1e',roughness:0}); + left=ea.addRect(0,0,160,90);right=ea.addDiamond(300,0,180,100); + label=ea.addText(20,150,'Owned EA label',{box:'box',boxPadding:12}); + arrow=ea.connectObjects(left,'right',right,'left',{endArrowHead:'arrow'}); + check(arrow&&ea.getElement(arrow).startBinding?.elementId===left&&ea.getElement(arrow).endBinding?.elementId===right,'EA arrow bindings differ'); + group=ea.addToGroup([left,right]);check(ea.getElement(left).groupIds.includes(group)&&ea.getElement(right).groupIds.includes(group),'EA grouping missing'); + frame=ea.addFrame(-40,-40,600,350,'Owned frame'); + for(const element of ea.getElements())if(element.id!==frame)element.frameId=frame; + ea.getElement(left).customData={ownedEA:{retained:'metadata'}}; + check(other.getElements().length===0&&other.style.backgroundColor!==ea.style.backgroundColor,'EA instances share staged state'); + const count=ea.getElements().length; + check(ea.connectObjects('missing-owned-id','right',right,'left')===undefined&&ea.getElements().length===count,'Invalid connection partially staged an arrow'); + check(await ea.addElementsToView(false,true,true),'EA publish failed'); + await c.waitFor(()=>view.excalidrawAPI.getSceneElements().some(e=>e.id===frame),'EA scene publication'); + check((await view.saveWithOutcome()).status==='persisted','EA publication did not receive physical save acknowledgement'); + const scene=await p.ea.getSceneFromFile(view.file); + check(scene.elements.some(e=>e.id===left&&e.customData?.ownedEA?.retained==='metadata'),'EA metadata did not reach disk'); + // addText with a box returns its container ID, as the public EA API defines. + const box=scene.elements.find(e=>e.id===label),text=scene.elements.find(e=>e.type==='text'&&e.containerId===label); + check(text?.text==='Owned EA label'&&box?.boundElements.some(e=>e.id===text.id),'Bound text/container relation missing'); + return {assertions:['independent EA styles and staged scenes','shape/arrow bindings, group, frame and bound text','invalid connection has no partial mutation','published custom metadata reaches physical drawing']}; + }); + await c.case('native:ea-edit-image-and-decoded-export',['P05','P09','P10'],async()=>{ + ea.clear();const original=view.excalidrawAPI.getSceneElements().find(e=>e.id===left),x=original.x; + ea.copyViewElementsToEAforEditing([original]);ea.getElement(left).x=42; + check(original.x===x,'EA edit mutated live source before publication'); + const image=await ea.addImage(10,400,'data:image/png;base64,'+png,false,false); + check(ea.getElement(image).width===4&&ea.getElement(image).height===2,'EA image geometry differs'); + check(await ea.addElementsToView(false,true,true),'EA image/edit publication failed'); + const updated=view.excalidrawAPI.getSceneElements();check(updated.filter(e=>e.id===left).length===1&&updated.find(e=>e.id===left).x===42,'EA edit duplicated or lost an element'); + ea.clear();ea.copyViewElementsToEAforEditing(updated,true); + check(Object.keys(ea.imagesDict).length>0,'EA copy lost image data'); + const svg=await ea.createSVG(undefined,false,undefined,undefined,'light',10); + check(svg.tagName.toLowerCase()==='svg'&&svg.querySelector('image')&&svg.querySelector('path,rect'),'EA SVG omitted content'); + const blob=await ea.createPNG(undefined,1,undefined,undefined,'light',10); + check(blob.type==='image/png'&&blob.size>100,'EA PNG missing'); + const url=URL.createObjectURL(blob),decoded=new Image(); + try{decoded.src=url;await decoded.decode();check(decoded.naturalWidth>300&&decoded.naturalHeight>200,'EA PNG dimensions missing'); + const canvas=createFragment().createEl('canvas');canvas.width=96;canvas.height=64;const context=canvas.getContext('2d');context.drawImage(decoded,0,0,96,64);const pixels=context.getImageData(0,0,96,64).data; + let red=0;for(let i=0;i160&&pixels[i+1]<120&&pixels[i+2]<120&&pixels[i+3]>0)red++; + check(red>10,'EA PNG lacks the red shape'); + }finally{URL.revokeObjectURL(url);} + return {assertions:['copy-for-editing isolates live elements until publication','image data and natural dimensions preserved','existing ID updated once','actual SVG content and decoded PNG pixels']}; + }); + await c.case('native:ea-svg-import-and-disposal',['P09','P10','P11'],async()=>{ + other.clear();check(other.importSVG(svgSource),'EA portable SVG conversion failed'); + const elements=other.getElements();check(elements.length>=3&&elements.some(e=>e.opacity===50),'EA SVG layers/opacity missing'); + check(elements.some(e=>e.type==='line'||e.type==='freedraw'),'EA SVG open stroke missing'); + ea.destroy();ea.destroy();check(cleanups===1,'Repeated destroy reran cleanup'); + check(view.excalidrawAPI&&view.isLoaded,'EA disposal retired its editor'); + return {assertions:['public EA imports the portable SVG fixture','opacity and open strokes retained','idempotent cleanup leaves editor usable']}; + }); + return {tests:c.tests}; +} diff --git a/scripts/testing/host/combination.mjs b/scripts/testing/host/combination.mjs new file mode 100644 index 00000000..893966e6 --- /dev/null +++ b/scripts/testing/host/combination.mjs @@ -0,0 +1,41 @@ +/** Freeze all producers before native deployment; never read a sibling's live dist during staging. */ +import assert from 'node:assert/strict'; +import {copyFileSync,existsSync,mkdirSync,readFileSync,writeFileSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {spawnSync} from 'node:child_process'; +import {produceArtifacts} from '../produceArtifacts.mjs'; +import {sourceIdentity,validateArtifactManifest,ownedPath,fileHash} from '../contracts.mjs'; +import {packageManagerInvocation} from './processTools.mjs'; +import {parseCLIJSON} from './inAppTask.mjs'; +export function produceCombination({pluginRoot,forkRoot,extrasRoot,output}){ + output=resolve(output);assert.ok(!existsSync(output),'Combination output already exists');mkdirSync(output,{recursive:true}); + const roots={plugin:resolve(pluginRoot),fork:resolve(forkRoot),extras:resolve(extrasRoot)},manifests={}; + const run=({manager,args,cwd})=>{const invocation=packageManagerInvocation(manager,args);const r=spawnSync(invocation.file,invocation.args,{cwd,env:{...process.env,EXCALIDRAW_TEST_FORK_TYPES_ROOT:roots.fork},stdio:'inherit',windowsHide:true,timeout:600000});if(r.error||r.status)throw Error('Producer '+manager+' '+args.join(' ')+' failed: '+(r.error?.message||r.status));}; + for(const kind of ['fork','extras'])manifests[kind]=produceArtifacts({root:roots[kind],kind,snapshotRoot:join(output,kind),run}); + const installed=JSON.parse(readFileSync(join(roots.plugin,'node_modules/@zsviczian/excalidraw/package.json'),'utf8')); + const declared=JSON.parse(readFileSync(join(roots.plugin,'package.json'),'utf8')).dependencies['@zsviczian/excalidraw'];assert.equal(installed.version,declared,'Install the exact declared fork package before local artifact handoff'); + for(const entry of manifests.fork.artifacts.filter(entry=>['production-js','production-css','development-js','development-css'].includes(entry.role))){ + const name=entry.relativePath.split('/').at(-1);const target=ownedPath(roots.plugin,'node_modules/@zsviczian/excalidraw/dist/obsidian/'+name,{existing:false});mkdirSync(join(target,'..'),{recursive:true});copyFileSync(ownedPath(join(output,'fork'),entry.relativePath),target); + } + manifests.plugin=produceArtifacts({root:roots.plugin,kind:'plugin',snapshotRoot:join(output,'plugin'),run}); + for(const kind of ['fork','extras','plugin']){ + validateArtifactManifest(manifests[kind],join(output,kind)); + const {commit,dirty,diffHash,lockfileHash}=manifests[kind];assert.deepEqual(sourceIdentity(roots[kind]),{commit,dirty,diffHash,lockfileHash},kind+' changed during combination build'); + } + const combination={schemaVersion:2,mode:'workspace',roots,manifests};writeFileSync(join(output,'combination.json'),JSON.stringify(combination,null,2)+'\n');return {...combination,output}; +} +export async function stageExtras({combination,target,cli}){ + const root=join(combination.output,'extras'),manifest=validateArtifactManifest(combination.manifests.extras,root),id='excalidraw-extras'; + const metadata=JSON.parse(readFileSync(ownedPath(root,manifest.artifacts.find(entry=>entry.role==='manifest').relativePath),'utf8'));assert.equal(metadata.id,id,'Wrong Extras plugin manifest'); + const entries=manifest.artifacts.filter(entry=>['main','manifest','styles'].includes(entry.role)).map(entry=>{ + const name={main:'main.js',manifest:'manifest.json',styles:'styles.css'}[entry.role]; + return {...entry,destination:ownedPath(target.config,'plugins/'+id+'/'+name,{existing:false})}; + }); + const before=parseCLIJSON(cli('eval',"code=JSON.stringify({loaded:!!app.plugins.plugins['excalidraw-extras']})")); + if(before.loaded)cli('plugin:disable','id='+id); + const installedHashes={}; + for(const entry of entries){mkdirSync(join(entry.destination,'..'),{recursive:true});copyFileSync(ownedPath(root,entry.relativePath),entry.destination);installedHashes[entry.role]=fileHash(entry.destination);assert.equal(installedHashes[entry.role],entry.sha256,'Installed Extras byte mismatch');} + cli('plugin:enable','id='+id); + const end=Date.now()+20000;for(;;){const ready=parseCLIJSON(cli('eval',"code=JSON.stringify(!!app.plugins.plugins['excalidraw-extras']?.api)"));if(ready)break;if(Date.now()>end)throw Error('Paired Extras API did not become ready');await new Promise(resolve=>setTimeout(resolve,50));} + return {evidence:{installedHashes,id,source:manifest.commit,sha256:manifest.artifacts.find(entry=>entry.role==='main').sha256,previouslyLoaded:before.loaded},cleanup:()=>{if(!before.loaded)cli('plugin:disable','id='+id);}}; +} diff --git a/scripts/testing/host/combination.test.mjs b/scripts/testing/host/combination.test.mjs new file mode 100644 index 00000000..584b6cae --- /dev/null +++ b/scripts/testing/host/combination.test.mjs @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,symlinkSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {createArtifactManifest,fileHash} from '../contracts.mjs'; +import {stageExtras} from './combination.mjs'; +function fixture(){ + const output=mkdtempSync(join(tmpdir(),'excalidraw-combination-')),root=join(output,'extras');mkdirSync(join(root,'dist'),{recursive:true}); + const entries=['main.js','manifest.json','styles.css','index.d.ts']; + entries.forEach(name=>writeFileSync(join(root,'dist',name),name==='manifest.json'?JSON.stringify({id:'excalidraw-extras'}):'owned '+name)); + const manifest=createArtifactManifest({root,kind:'extras',repository:'zsviczian/obsidian-excalidraw-extras',buildCommand:'synthetic producer fixture',identity:{commit:'a'.repeat(40),dirty:false,diffHash:'b'.repeat(64),lockfileHash:'c'.repeat(64)},artifacts:entries.map((name,i)=>({role:['main','manifest','styles','declarations'][i],relativePath:'dist/'+name}))}); + const config=join(output,'vault/.obsidian');mkdirSync(config,{recursive:true});return{combination:{output,manifests:{extras:manifest}},target:{config},root}; +} +test('corrupt frozen Extras bytes fail before the first native call',async()=>{ + const input=fixture();writeFileSync(join(input.root,'dist/main.js'),'corrupted');let calls=0; + await assert.rejects(stageExtras({...input,cli:()=>{calls++;}}),/mismatch/);assert.equal(calls,0); +}); +test('redirected companion destination fails before disable or deployment',async()=>{ + const input=fixture(),outside=join(input.combination.output,'outside');mkdirSync(outside);mkdirSync(join(input.target.config,'plugins')); + symlinkSync(outside,join(input.target.config,'plugins/excalidraw-extras'),process.platform==='win32'?'junction':'dir');let calls=0; + await assert.rejects(stageExtras({...input,cli:()=>{calls++;}}),/Redirected/);assert.equal(calls,0); +}); +test('companion staging proves installed bytes and restores prior disabled state',async()=>{ + const input=fixture(),calls=[]; + const result=await stageExtras({...input,cli:(command,...args)=>{calls.push([command,...args]);if(command==='eval')return args[0].includes('loaded:')?'{"loaded":false}':'true';return'';}}); + assert.equal(result.evidence.installedHashes.main,fileHash(join(input.target.config,'plugins/excalidraw-extras/main.js'))); + assert.equal(JSON.parse(readFileSync(join(input.target.config,'plugins/excalidraw-extras/manifest.json'))).id,'excalidraw-extras'); + assert.equal(calls.filter(call=>call[0]==='plugin:disable').length,0);result.cleanup(); + assert.equal(calls.filter(call=>call[0]==='plugin:disable').length,1); +}); diff --git a/scripts/testing/host/coreInteraction.mjs b/scripts/testing/host/coreInteraction.mjs new file mode 100644 index 00000000..e1e7f54e --- /dev/null +++ b/scripts/testing/host/coreInteraction.mjs @@ -0,0 +1,70 @@ +/** Trusted mouse/keyboard exercise the real toolbar, custom pen and laser. */ +import assert from 'node:assert/strict'; +import {runInAppTask} from './inAppTask.mjs'; +export async function runCoreInteractionScenario({cli,drawingPath}){ + assert.ok(drawingPath.startsWith('__excalidraw_cli_smoke_')); + const result=await runInAppTask({cli,execute:exerciseCore,args:[drawingPath,process.platform==='darwin'?4:2],timeoutMs:120000, + onRequest:request=>{assert.equal(request.method,'cdp');assert.ok(['Input.dispatchMouseEvent','Input.dispatchKeyEvent'].includes(request.params.method));cli('dev:cdp','method='+request.params.method,'params='+JSON.stringify(request.params.params));return{dispatched:true};}}); + return{id:'core-trusted-interaction',status:'passed',...result}; +} +async function exerciseCore(c,drawingPath,modifier){ + const p=app.plugins.plugins['obsidian-excalidraw-plugin'],view=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===drawingPath)?.view,api=view?.excalidrawAPI; + const check=(value,label)=>{if(!value)throw Error(label);};check(api,'Owned core editor missing'); + const doc=view.ownerDocument,oldPens=p.settings.customPens,oldCount=p.settings.numberOfCustomPens; + const wasFullscreen=view.isFullscreen(),events=[]; + c.defer(()=>{p.settings.customPens=oldPens;p.settings.numberOfCustomPens=oldCount;if(view.excalidrawAPI)api.updateScene({appState:{customPens:oldPens.slice(0,oldCount),currentStrokeOptions:null,resetCustomPen:null},captureUpdate:'NEVER'});if(!wasFullscreen)view.exitFullscreen();}); + if(!wasFullscreen)view.gotoFullscreen(); + const canvas=view.containerEl.querySelector('canvas.interactive');check(canvas,'Interactive canvas missing'); + const listener=event=>{if(event.target===canvas)events.push({trusted:event.isTrusted,type:event.pointerType});}; + doc.addEventListener('pointerdown',listener,true);c.defer(()=>doc.removeEventListener('pointerdown',listener,true)); + const input=(type,x,y)=>c.requestHost('cdp',{method:'Input.dispatchMouseEvent',params:{type,x,y,button:'left',buttons:type==='mouseReleased'?0:1,clickCount:1}}); + const key=async(key,code,keyCode,modifiers=0)=>{for(const type of ['keyDown','keyUp'])await c.requestHost('cdp',{method:'Input.dispatchKeyEvent',params:{type,key,code,windowsVirtualKeyCode:keyCode,modifiers}});}; + const click=async element=>{ + element.scrollIntoView({block:'nearest',inline:'nearest'});let x,y; + try{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));},'uncovered core control');} + catch(error){throw Error(error.message+': '+JSON.stringify({rect:element.getBoundingClientRect().toJSON(),hit:doc.elementFromPoint(x,y)?.outerHTML.slice(0,250),viewport:[innerWidth,innerHeight]}));} + await input('mousePressed',x,y);await input('mouseReleased',x,y); + }; + const toolbar=async id=>{let button;await c.waitFor(()=>{button=[...view.containerEl.querySelectorAll('[data-testid="'+id+'"]')].find(el=>el.getBoundingClientRect().width>0&&!el.closest('.tool-popover-content'));return button;},id);await click(button);}; + const stroke=async()=>{ + let start,end;await c.waitFor(()=>{const r=canvas.getBoundingClientRect();for(const [x,y]of[[0.65,0.55],[0.55,0.65],[0.7,0.4]]){const a={x:r.x+r.width*x,y:r.y+r.height*y},b={x:a.x+70,y:a.y+45};if(doc.elementFromPoint(a.x,a.y)===canvas&&doc.elementFromPoint(b.x,b.y)===canvas){start=a;end=b;return true;}}},'uncovered core drawing area'); + await input('mouseMoved',start.x,start.y);await input('mousePressed',start.x,start.y); + for(let step=1;step<=4;step++)await input('mouseMoved',start.x+(end.x-start.x)*step/4,start.y+(end.y-start.y)*step/4); + await input('mouseReleased',end.x,end.y); + }; + await c.case('native:core-toolbar-draw-history',['P04','P07'],async()=>{ + const count=api.getSceneElements().length;await toolbar('toolbar-rectangle');await c.waitFor(()=>api.getAppState().activeTool.type==='rectangle','rectangle selection');await stroke(); + await c.waitFor(()=>api.getSceneElements().length===count+1,'trusted rectangle'); + check(events.some(e=>e.trusted&&e.type==='mouse'),'Drawing input was not trusted'); + view.containerEl.querySelector('.excalidraw').focus();await key('z','KeyZ',90,modifier);await c.waitFor(()=>api.getSceneElements().length===count,'trusted undo'); + await key('z','KeyZ',90,modifier|8);await c.waitFor(()=>api.getSceneElements().length===count+1,'trusted redo'); + return{assertions:['visible uncovered toolbar control','trusted pointer produces a rectangle','actual keyboard undo and redo preserve scene count']}; + }); + await c.case('native:core-custom-highlighter',['P05','P07'],async()=>{ + const baseColor=api.getAppState().currentItemStrokeColor; + const pen={type:'highlighter',freedrawOnly:true,strokeColor:'#FFC47C',backgroundColor:'#FFC47C',fillStyle:'solid',strokeWidth:2,roughness:0, + penOptions:{highlighter:true,constantPressure:true,hasOutline:true,outlineWidth:4,options:{thinning:1,smoothing:0.5,streamline:0.5,easing:'linear',start:{cap:true,taper:0,easing:'linear'},end:{cap:true,taper:0,easing:'linear'}}}}; + p.settings.customPens=[pen];p.settings.numberOfCustomPens=1; + api.updateScene({appState:{customPens:[pen],selectedElementIds:{}},captureUpdate:'NEVER'}); + let label;await c.waitFor(()=>{label=[...view.containerEl.querySelectorAll('.ToolIcon__icon[aria-label="highlighter"]')].map(el=>el.closest('label')).find(el=>el?.getBoundingClientRect().width>0);return label;},'custom highlighter control');await click(label); + await c.waitFor(()=>api.getAppState().activeTool.type==='freedraw'&&api.getAppState().currentStrokeOptions?.highlighter,'highlighter activation'); + const before=api.getSceneElements().length;await stroke();await c.waitFor(()=>api.getSceneElements().length===before+1,'highlighter stroke'); + const line=api.getSceneElements().find(el=>el.type==='freedraw');check(line?.customData?.strokeOptions?.highlighter&&line.points.length>=2,'Custom pen options did not reach the drawn stroke'); + check(api.getSceneElements().indexOf(line)===0,'Highlighter was not placed below existing shapes'); + await toolbar('toolbar-rectangle');await c.waitFor(()=>api.getAppState().activeTool.type==='rectangle'&&api.getAppState().resetCustomPen===null&&api.getAppState().currentItemStrokeColor===baseColor,'freedraw-only pen restores base stroke outside freehand'); + await toolbar('toolbar-freedraw');await c.waitFor(()=>api.getAppState().resetCustomPen&&api.getAppState().currentStrokeOptions?.highlighter,'custom pen reapplies on return to freehand'); + await click(label);await c.waitFor(()=>!api.getAppState().currentStrokeOptions,'custom pen deselects'); + check((await view.saveWithOutcome()).status==='persisted','Highlighter did not save'); + check((await p.ea.getSceneFromFile(view.file)).elements.some(el=>el.id===line.id&&el.customData?.strokeOptions?.highlighter),'Highlighter metadata lost on disk'); + return{assertions:['trusted custom pen toolbar activation','freehand pressure/highlighter metadata','highlighter beneath ordinary shapes','freedraw-only pen restores base options','custom stroke reaches physical save']}; + }); + await c.case('native:core-laser-transient',['P07'],async()=>{ + api.setActiveTool({type:'laser'});await c.waitFor(()=>api.getAppState().activeTool.type==='laser','laser tool'); + const ids=api.getSceneElements().map(el=>el.id),eventCount=events.length;await stroke(); + check(events.length>eventCount&&events.at(-1).trusted,'Laser did not receive trusted input'); + check(JSON.stringify(api.getSceneElements().map(el=>el.id))===JSON.stringify(ids),'Laser created a persistent drawing element'); + api.setActiveTool({type:'selection'}); + return{assertions:['active laser receives trusted pointer input','laser stroke adds no persistent scene element','selection remains usable'],limitations:'Trail animation pixels have a separate renderer/browser oracle; this checks native interaction and persistence semantics.'}; + }); + return{tests:c.tests}; +} diff --git a/scripts/testing/host/dataIntegrity.mjs b/scripts/testing/host/dataIntegrity.mjs index b5fa881b..c98f99d7 100644 --- a/scripts/testing/host/dataIntegrity.mjs +++ b/scripts/testing/host/dataIntegrity.mjs @@ -21,6 +21,11 @@ async function exerciseDataIntegrity(c, prefix, fixtures) { const check = (condition, message) => { if (!condition) throw Error(message); }; const close = async leaf => { if (leaf.view?.getViewType() !== "empty") await leaf.setViewState({ type: "empty", state: {} }); leaf.detach(); ownedLeaves.delete(leaf); }; c.defer(async () => { + // The intentional failed-write case creates persistent host notices. They + // belong to this exact fixture and otherwise cover later toolbar checks. + const notices=[...app.workspace.containerEl.ownerDocument.querySelectorAll('.notice')].filter(notice=>notice.textContent.includes(prefix+'/')&¬ice.textContent.includes('EXCALIDRAW_OWNED_WRITE_FAILURE')); + for(const notice of notices)notice.click(); + await c.waitForCleanup(()=>notices.every(notice=>!notice.isConnected),'owned fault-injection notices'); for (const leaf of ownedLeaves) await close(leaf); if (originalLeaf) app.workspace.setActiveLeaf(originalLeaf, { focus: true }); const folder = app.vault.getFolderByPath(prefix); diff --git a/scripts/testing/host/debuggerSession.mjs b/scripts/testing/host/debuggerSession.mjs index 31428dd7..1cef1500 100644 --- a/scripts/testing/host/debuggerSession.mjs +++ b/scripts/testing/host/debuggerSession.mjs @@ -10,21 +10,24 @@ export function acquireDebuggerSession(cli) { let attachedByUs = false, installed = false, disposed = false; try { 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:[]};c.debugger=require('@electron/remote').getCurrentWebContents().debugger;c.listener=(_event,method,params)=>{if(method==='Runtime.consoleAPICalled'&¶ms.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',messages:[String(params.exceptionDetails.exception?.description??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'&¶ms.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});})()`); installed = true; cli("dev:cdp", "method=Runtime.enable", "params={}"); } catch (error) { - if (installed) evaluate(`(()=>{const c=globalThis[${JSON.stringify(key)}];c.debugger.removeListener('message',c.listener);delete globalThis[${JSON.stringify(key)}];return JSON.stringify(true);})()`); - if (attachedByUs) cli("dev:debug", "off"); + 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"); } throw error; } return { read: () => evaluate(`JSON.stringify(globalThis[${JSON.stringify(key)}].errors)`), dispose() { if (disposed) return; - 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);})()`); - cli("dev:debug", "off"); disposed = true; + 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; } }, }; } diff --git a/scripts/testing/host/debuggerSession.test.mjs b/scripts/testing/host/debuggerSession.test.mjs index d26b1570..44893de3 100644 --- a/scripts/testing/host/debuggerSession.test.mjs +++ b/scripts/testing/host/debuggerSession.test.mjs @@ -23,8 +23,12 @@ 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.exceptionThrown", { exceptionDetails: { text: "exception" } }); + 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"))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); @@ -38,3 +42,10 @@ test("expected fault injection cannot hide another error or an incorrect count", assert.equal(unexpectedConsoleErrors([], 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); +}); diff --git a/scripts/testing/host/deviceProfiles.mjs b/scripts/testing/host/deviceProfiles.mjs index 30331ee5..65763d95 100644 --- a/scripts/testing/host/deviceProfiles.mjs +++ b/scripts/testing/host/deviceProfiles.mjs @@ -15,3 +15,14 @@ export function deviceProfiles() { // migration behavior has its separate native lifecycle obligations. return profiles.map(profile => ({ ...profile, pane: "fullscreen" })); } + +/** Canonical common/editorInterface.ts boundaries; actual editor bounds are recorded. */ +export function breakpointProfiles() { + const cases = [ + ...[598, 599, 600].map(width => ({ id: `mobile-width-${width}`, width, height: 900, formFactor: width <= 599 ? "phone" : "tablet" })), + ...[799, 800, 801].map(width => ({ id: `sidebar-width-${width}`, width, height: 900, formFactor: "tablet", canFitSidebar: width > 800 })), + ...[999, 1000, 1001].map(width => ({ id: `landscape-width-${width}`, width, height: 499, formFactor: width < 1000 ? "phone" : "desktop" })), + ...[499, 500, 501].map(height => ({ id: `landscape-height-${height}`, width: 999, height, formFactor: height < 500 ? "phone" : "desktop" })), + ]; + return cases.map(profile => ({ ...profile, editorWidth: profile.width, boundary: true, id: "breakpoint-" + profile.id, mobile: true, mode: profile.formFactor === "phone" ? "mobile" : "compact", theme: "light", input: "touch", pane: "fullscreen" })); +} diff --git a/scripts/testing/host/deviceProfiles.test.mjs b/scripts/testing/host/deviceProfiles.test.mjs new file mode 100644 index 00000000..e3cdecc2 --- /dev/null +++ b/scripts/testing/host/deviceProfiles.test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { deviceProfiles, breakpointProfiles } from "./deviceProfiles.mjs"; +test("device obligations retain desktop, both mobile orientations, both themes and all supported layouts", () => { + const profiles = deviceProfiles(); assert.equal(profiles.length, 28); + assert.equal(new Set(profiles.map(profile => profile.id)).size, profiles.length); + for (const theme of ["light", "dark"]) for (const mode of ["full", "tray", "compact"]) { + assert.ok(profiles.some(profile => profile.formFactor === "desktop" && profile.theme === theme && profile.mode === mode)); + assert.ok(profiles.some(profile => profile.formFactor === "tablet" && profile.theme === theme && profile.mode === mode)); + } + assert.ok(profiles.filter(profile => profile.mobile).every(profile => profile.input === "touch")); + assert.equal(breakpointProfiles().length, 12); + assert.equal(new Set([...profiles, ...breakpointProfiles()].map(profile => profile.id)).size, 40); +}); diff --git a/scripts/testing/host/deviceRecovery.mjs b/scripts/testing/host/deviceRecovery.mjs index a4e5090d..82af5114 100644 --- a/scripts/testing/host/deviceRecovery.mjs +++ b/scripts/testing/host/deviceRecovery.mjs @@ -22,10 +22,10 @@ export async function restoreDeviceState({ cli, original, path, created }) { await app.workspace.changeLayout(layout); return { removed: !app.vault.getFileByPath(path) }; } })); - await attempt("theme, preference and geometry", () => evaluate(`(()=>{const w=${mainWindowExpression};if(w.id!==${original.id})throw Error('Main owner changed');app.changeTheme(${JSON.stringify(original.theme)});${original.desktopMode === null ? "localStorage.removeItem('excalidraw.desktopUIMode');" : `localStorage.setItem('excalidraw.desktopUIMode',${JSON.stringify(original.desktopMode)});`}w.setBounds(${JSON.stringify(original.bounds)});w.setMinimumSize(...${JSON.stringify(original.minimum)});${original.maximized ? "w.maximize();" : ""}${original.fullscreen ? "w.setFullScreen(true);" : ""}return JSON.stringify(true);})()`)); + await attempt("theme, preference and geometry", () => evaluate(`(()=>{const w=${mainWindowExpression};if(w.id!==${original.id})throw Error('Main owner changed');app.changeTheme(${JSON.stringify(original.theme)});${original.desktopMode === null ? "localStorage.removeItem('excalidraw.desktopUIMode');" : `localStorage.setItem('excalidraw.desktopUIMode',${JSON.stringify(original.desktopMode)});`}w.webContents.setZoomFactor(${original.zoom ?? 1});w.setBounds(${JSON.stringify(original.bounds)});w.setMinimumSize(...${JSON.stringify(original.minimum)});${original.maximized ? "w.maximize();" : ""}${original.fullscreen ? "w.setFullScreen(true);" : ""}return JSON.stringify(true);})()`)); await attempt("restoration verification", async () => { - const state = evaluate(`JSON.stringify((()=>{const w=${mainWindowExpression};return{mobile:app.isMobile===true,theme:app.vault.getConfig('theme'),desktopMode:localStorage.getItem('excalidraw.desktopUIMode'),id:w.id,minimum:w.getMinimumSize(),maximized:w.isMaximized(),fullscreen:w.isFullScreen()};})())`); - for (const key of ["mobile", "theme", "desktopMode", "id", "minimum", "maximized", "fullscreen"]) assert.deepEqual(state[key], original[key], `Restoration differs: ${key}`); + const state = evaluate(`JSON.stringify((()=>{const w=${mainWindowExpression};return{mobile:app.isMobile===true,theme:app.vault.getConfig('theme'),desktopMode:localStorage.getItem('excalidraw.desktopUIMode'),id:w.id,minimum:w.getMinimumSize(),maximized:w.isMaximized(),fullscreen:w.isFullScreen(),zoom:w.webContents.getZoomFactor(),touch:{maxTouchPoints:navigator.maxTouchPoints,coarse:matchMedia('(pointer: coarse)').matches,hover:matchMedia('(hover: hover)').matches}};})())`); + for (const key of ["mobile", "theme", "desktopMode", "id", "minimum", "maximized", "fullscreen", ...(original.zoom === undefined ? [] : ["zoom"]), ...(original.touch ? ["touch"] : [])]) assert.deepEqual(state[key], original[key], `Restoration differs: ${key}`); }); if (errors.length) throw new AggregateError(errors.map(error => Error(error)), "Device restoration failed: " + errors.join("; ")); return { restored: true }; diff --git a/scripts/testing/host/devices.mjs b/scripts/testing/host/devices.mjs index 4408f59a..143cdd51 100644 --- a/scripts/testing/host/devices.mjs +++ b/scripts/testing/host/devices.mjs @@ -18,7 +18,7 @@ export async function runDeviceMatrix({ cli, reportDir, vaultName, vaultPath, co assert.equal(realpathSync(cli("vault", "info=path").trim()), target.vault, "Device CLI selected another vault"); const evaluate = code => parseCLIJSON(cli("eval", "code=" + code)); const owner = mainWindowExpression; - const original = evaluate(`JSON.stringify((()=>{const w=${owner};if(w.webContents.debugger.isAttached())throw Error('Existing debugger owner');return{mobile:app.isMobile===true,theme:app.vault.getConfig('theme'),layout:app.workspace.getLayout(),desktopMode:localStorage.getItem('excalidraw.desktopUIMode'),id:w.id,bounds:w.getBounds(),minimum:w.getMinimumSize(),maximized:w.isMaximized(),fullscreen:w.isFullScreen()};})())`); + const original = evaluate(`JSON.stringify((()=>{const w=${owner};if(w.webContents.debugger.isAttached())throw Error('Existing debugger owner');return{mobile:app.isMobile===true,theme:app.vault.getConfig('theme'),layout:app.workspace.getLayout(),desktopMode:localStorage.getItem('excalidraw.desktopUIMode'),id:w.id,bounds:w.getBounds(),minimum:w.getMinimumSize(),maximized:w.isMaximized(),fullscreen:w.isFullScreen(),zoom:w.webContents.getZoomFactor(),touch:{maxTouchPoints:navigator.maxTouchPoints,coarse:matchMedia('(pointer: coarse)').matches,hover:matchMedia('(hover: hover)').matches}};})())`); const path = `__excalidraw_cli_smoke_devices_${randomUUID()}.excalidraw.md`; const fixture = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8"); const report = { schemaVersion: 2, suiteId: "native-devices", status: "failed", cleanup: "not-started", tests: [], @@ -29,7 +29,7 @@ export async function runDeviceMatrix({ cli, reportDir, vaultName, vaultPath, co report.reloadDiagnostics = []; const ready = () => waitForNativeReady(cli, { diagnostics: report.reloadDiagnostics }); try { - evaluate(`(()=>{const w=${owner};if(w.id!==${original.id})throw Error('Main owner changed');w.setFullScreen(false);w.unmaximize();w.setMinimumSize(200,200);return JSON.stringify(true);})()`); + evaluate(`(()=>{const w=${owner};if(w.id!==${original.id})throw Error('Main owner changed');w.setFullScreen(false);w.unmaximize();w.setMinimumSize(200,200);w.webContents.setZoomFactor(1);return JSON.stringify(true);})()`); await runInAppTask({ cli, args: [path, fixture], execute: async (_c, path, fixture) => { if (app.vault.getFileByPath(path)) throw Error("Device fixture collision"); await app.vault.create(path, fixture); return { created: true }; } }); created = true; @@ -44,6 +44,9 @@ export async function runDeviceMatrix({ cli, reportDir, vaultName, vaultPath, co cli("dev:cdp", "method=Emulation.setTouchEmulationEnabled", `params=${JSON.stringify({ enabled: profile.input === "touch", maxTouchPoints: profile.input === "touch" ? 5 : 1 })}`); const result = await runInAppTask({ cli, execute: exerciseDevice, args: [path, fixture, profile], timeoutMs: 60_000, onRequest: request => { + if (request.method === "resize-editor" && Number.isSafeInteger(request.params.delta) && Math.abs(request.params.delta) <= 32) { + evaluate(`(()=>{const w=${owner};if(w.id!==${original.id})throw Error('Main owner changed');const [width,height]=w.getContentSize();w.setContentSize(width+${request.params.delta},height);return JSON.stringify(true);})()`); return { resized: true }; + } if (request.method === "screenshot" && request.params.id === profile.id) { cli("dev:screenshot", "path=" + join(reportDir, profile.id + ".png")); return { captured: true }; } if (request.method !== "cdp" || !["Input.dispatchMouseEvent", "Input.dispatchTouchEvent"].includes(request.params.method)) throw Error("Unexpected device input request"); cli("dev:cdp", "method=" + request.params.method, "params=" + JSON.stringify(request.params.params)); return { dispatched: true }; @@ -59,8 +62,10 @@ export async function runDeviceMatrix({ cli, reportDir, vaultName, vaultPath, co if (error.cleanupFailed) report.unsettledTask = true; } finally { try { - if (debuggerSession) { debuggerSession.dispose(); debuggerSession = null; } + let debuggerError; + if (debuggerSession) { try { debuggerSession.dispose(); } catch (error) { debuggerError=error; } finally { debuggerSession=null; } } report.restoration = await restoreDeviceState({ cli, original, path, created }); + if (debuggerError) throw debuggerError; report.cleanup = report.unsettledTask ? "failed" : "passed"; } catch (error) { report.cleanup = "failed"; report.cleanupError = String(error.stack || error); } if (report.cleanup !== "passed") report.status = "failed"; @@ -71,6 +76,7 @@ export async function runDeviceMatrix({ cli, reportDir, vaultName, vaultPath, co async function exerciseDevice(c, path, fixture, profile) { const p = app.plugins.plugins["obsidian-excalidraw-plugin"], doc = app.workspace.containerEl.ownerDocument; + await c.waitFor(() => innerWidth === profile.width && innerHeight === profile.height, "actual requested viewport"); const check = (condition, message) => { if (!condition) throw Error(message); }; const settings = Object.fromEntries(["desktopUIMode", "tabletUIMode", "phoneUIMode", "penModeSingleFingerPanning"].map(key => [key, p.settings[key]])); const desktopMode = localStorage.getItem("excalidraw.desktopUIMode"); @@ -89,7 +95,7 @@ async function exerciseDevice(c, path, fixture, profile) { const file = app.vault.getFileByPath(path); check(file, "Owned device fixture missing"); await app.vault.modify(file, fixture); p.settings.desktopUIMode = profile.mode === "mobile" ? "tray" : profile.mode; p.settings.tabletUIMode = profile.mode === "mobile" ? "compact" : profile.mode; - p.settings.phoneUIMode = "mobile"; p.settings.penModeSingleFingerPanning = false; + p.settings.phoneUIMode = profile.boundary ? "mobile" : profile.mode; p.settings.penModeSingleFingerPanning = false; const leaf = app.workspace.getLeaf("tab"); c.defer(async () => { await leaf.setViewState({ type: "empty", state: {} }); leaf.detach(); }); await leaf.openFile(file); @@ -102,11 +108,17 @@ async function exerciseDevice(c, path, fixture, profile) { view.gotoFullscreen(); c.defer(() => { view.exitFullscreen(); check(!view.isFullscreen(), "Owned fullscreen did not restore"); }); await c.waitFor(() => view.isFullscreen() && view.containerEl.querySelector("canvas.interactive").getBoundingClientRect().width >= innerWidth - 100, "owned fullscreen viewport"); } + if (profile.editorWidth !== undefined) { + const width = view.containerEl.querySelector(".excalidraw").getBoundingClientRect().width; + if (width !== profile.editorWidth) await c.requestHost("resize-editor", { delta: Math.round(profile.editorWidth - width) }); + await c.waitFor(() => view.containerEl.querySelector(".excalidraw").getBoundingClientRect().width === profile.editorWidth, "exact editor breakpoint width"); + } view.setUIMode(profile.mode === "mobile" ? "tray" : profile.mode); view.setTheme(profile.theme); api.updateScene({ appState: { penMode: false, viewModeEnabled: false }, captureUpdate: "NEVER" }); await c.waitFor(() => doc.body.hasClass(profile.theme === "dark" ? "theme-dark" : "theme-light") && api.getAppState().theme === profile.theme, "actual host and drawing themes"); try { await c.waitFor(() => api.getEditorInterface().formFactor === profile.formFactor, "measured device classification"); } catch (error) { throw Error(error.message + ": " + JSON.stringify({ viewport: { width: innerWidth, height: innerHeight }, editor: api.getEditorInterface(), device: p.getObsidianDevice() })); } + if (profile.canFitSidebar !== undefined) check(api.getEditorInterface().canFitSidebar === profile.canFitSidebar, "Sidebar breakpoint differs"); const rect = element => { const r = element.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height, right: r.right, bottom: r.bottom }; }; const button = [...view.containerEl.querySelectorAll('[data-testid="toolbar-rectangle"]')].find(element => !element.closest(".tool-popover-content") && element.getBoundingClientRect().width > 0); check(button, "Rectangle tool is not reachable"); @@ -119,6 +131,13 @@ async function exerciseDevice(c, path, fixture, profile) { }; await input(profile.input === "touch" ? "touchStart" : "mousePressed", x, y); await input(profile.input === "touch" ? "touchEnd" : "mouseReleased", x, y); await c.waitFor(() => api.getAppState().activeTool.type === "rectangle", "trusted toolbar selection"); + if (!profile.boundary) await c.waitFor(() => { + const root = view.containerEl.querySelector(".excalidraw"), compact = view.containerEl.querySelector(".compact-shape-actions"); + if (profile.mode === "mobile") return root.classList.contains("excalidraw--mobile"); + if (profile.mode === "tray") return root.classList.contains("excalidraw--tray") && !!view.containerEl.querySelector(".App-top-bar"); + if (profile.mode === "compact") return !!compact && compact.getBoundingClientRect().width > 0; + return !compact && !root.classList.contains("excalidraw--tray") && !!view.containerEl.querySelector(".selected-shape-actions"); + }, "actual requested layout"); const canvas = view.containerEl.querySelector("canvas.interactive"), canvasBounds = rect(canvas), events = []; await c.requestHost("screenshot", { id: profile.id }); const listener = event => { if (event.target === canvas) events.push({ trusted: event.isTrusted, pointerType: event.pointerType }); }; @@ -146,6 +165,6 @@ async function exerciseDevice(c, path, fixture, profile) { check((app.isMobile === true) === profile.mobile, "Narrow desktop/mobile mode confused"); await c.requestHost("screenshot", { id: profile.id }); return { assertions: ["actual Obsidian mobile/desktop mode", "measured editor classification", "actual host and drawing theme", "visible uncovered tool", "trusted pointer selects and draws", "device edit saves to disk"], - requested: profile, actual: { viewport: { width: innerWidth, height: innerHeight }, retiredRestoredOwnedEditors: restoredOwned.length, paneBefore, fullscreen: view.isFullscreen(), canvas: canvasBounds, tool: bounds, editorInterface: api.getEditorInterface(), hostDevice: p.getObsidianDevice(), mobile: app.isMobile === true, + requested: profile, actual: { viewport: { width: innerWidth, height: innerHeight }, retiredRestoredOwnedEditors: restoredOwned.length, paneBefore, fullscreen: view.isFullscreen(), editorBounds: rect(view.containerEl.querySelector(".excalidraw")), canvas: canvasBounds, tool: bounds, editorInterface: api.getEditorInterface(), hostDevice: p.getObsidianDevice(), mobile: app.isMobile === true, maxTouchPoints: navigator.maxTouchPoints, coarsePointer: matchMedia("(pointer: coarse)").matches, events } }; } diff --git a/scripts/testing/host/embedRecovery.mjs b/scripts/testing/host/embedRecovery.mjs index 70d63b1f..aed6acc2 100644 --- a/scripts/testing/host/embedRecovery.mjs +++ b/scripts/testing/host/embedRecovery.mjs @@ -1,3 +1,4 @@ +import {runHostFunction} from './legacyTask.mjs'; /** Issue #2953: real Markdown embeds and deliberate detachment in a disposable vault. */ import assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; @@ -161,10 +162,8 @@ export async function runEmbedRecoveryScenario({ cli, drawingPath }) { await wait(100); } } - async function act(fn, ...args) { - evaluate(`(()=>{const c=globalThis.${CONTROL};c.state="pending";c.error=null;Promise.resolve((${fn.toString()})(${[CONTROL, ...args].map(value => JSON.stringify(value)).join(",")})).then(()=>c.state="done").catch(e=>{c.error=String(e);c.state="failed"});return JSON.stringify({started:true})})()`); - await poll(value => value.state === "done", fn.name); - } + let unsettled=false; + async function act(fn,...args){try{return await runHostFunction({cli,execute:fn,args:[CONTROL,...args]});}catch(error){if(error.cleanupFailed)unsettled=true;throw error;}} const checks = []; invoke(setup, drawingPath, paths); try { @@ -227,6 +226,7 @@ export async function runEmbedRecoveryScenario({ cli, drawingPath }) { } } } finally { + if(unsettled)throw Object.assign(Error("Unsettled embed task; preserve owned fixtures"),{cleanupFailed:true}); await act(cleanup, paths); evaluate(`(()=>{delete globalThis.${CONTROL};return JSON.stringify({clean:true})})()`); } diff --git a/scripts/testing/host/groupedLinkClick.mjs b/scripts/testing/host/groupedLinkClick.mjs index aba1e331..8dbf5cef 100644 --- a/scripts/testing/host/groupedLinkClick.mjs +++ b/scripts/testing/host/groupedLinkClick.mjs @@ -1,3 +1,4 @@ +import {runHostFunction} from './legacyTask.mjs'; /** Run only against the guarded runner's disposable drawing. */ async function exerciseGroupedLinkClicks(view, link, modifier) { const api = view.excalidrawAPI; @@ -128,23 +129,10 @@ async function exerciseGroupedLinkClicks(view, link, modifier) { /** Synthetic input through the mounted editor; the parent owns deployment and cleanup. */ export async function runGroupedLinkClickScenario({ cli, drawingPath }) { - const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, '')); - const controller = '__excalidrawGroupedLinkClick'; - const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(drawingPath)})?.view`; - const modifier = process.platform === 'darwin' ? { metaKey: true } : { ctrlKey: true }; - evaluate(`(()=>{if(globalThis.${controller})throw Error('Controller already present');const c={state:'pending'};globalThis.${controller}=c;(${exerciseGroupedLinkClicks.toString()})(${viewCode},${JSON.stringify(`[[${drawingPath}]]`)},${JSON.stringify(modifier)}).then(assertions=>{c.assertions=assertions;c.state='passed'},error=>{c.error=String(error.stack||error);c.state='failed'});return JSON.stringify({started:true})})()`); - try { - for (let i = 0; i < 120; i++) { - await new Promise(resolve => setTimeout(resolve, 250)); - const state = evaluate(`JSON.stringify(globalThis.${controller})`); - if (state.state === 'failed') throw Error(state.error); - if (state.state === 'passed') return { - id: 'grouped-link-click', status: 'passed', - input: 'owner-window synthetic pointer events', assertions: state.assertions, - }; - } - throw Error('Grouped link click scenario timed out'); - } finally { - evaluate(`(()=>{delete globalThis.${controller};return JSON.stringify({clean:true})})()`); - } + const modifier=process.platform==='darwin'?{metaKey:true}:{ctrlKey:true}; + const assertions=await runHostFunction({cli,helpers:[exerciseGroupedLinkClicks],args:[drawingPath,modifier],execute:async(path,modifier)=>{ + const view=app.workspace.getLeavesOfType('excalidraw').find(leaf=>leaf.view.file?.path===path)?.view; + if(!view)throw Error('Owned grouped-link editor missing');return exerciseGroupedLinkClicks(view,'[['+path+']]',modifier); + }}); + return {id:'grouped-link-click',status:'passed',input:'owner-window synthetic pointer events',assertions}; } diff --git a/scripts/testing/host/imageGeometry.mjs b/scripts/testing/host/imageGeometry.mjs index 4f0bff0e..dfd77e7f 100644 --- a/scripts/testing/host/imageGeometry.mjs +++ b/scripts/testing/host/imageGeometry.mjs @@ -1,5 +1,5 @@ /** #3014/#2947: real formula bounds and resized Markdown sidepanel edits. */ -import assert from "node:assert/strict"; +import { runLegacyTask } from "./legacyTask.mjs"; import { exerciseMarkdownCrop } from "./markdownImageCrop.mjs"; const CONTROL = "__excalidrawImageGeometry"; @@ -165,31 +165,21 @@ async function cleanup(control) { else delete c.gateway.getMathJax; } c.tab?.close(); - if (c.pop) { await c.pop.setViewState({ type: "empty", state: {} }); c.pop.detach(); } - if (c.previous && c.previous !== c.pop) app.workspace.setActiveLeaf(c.previous, { focus: true }); + if (c.pop) { + const win=c.pop.view.containerEl.ownerDocument.defaultView; + if(win===app.workspace.containerEl.ownerDocument.defaultView){await c.pop.setViewState({type:'empty',state:{}});c.pop.detach();} + else {if(c.pop.view.isDirty?.())await c.pop.view.saveWithOutcome();win.close();const end=Date.now()+10000;while(!win.closed){if(Date.now()>end)throw Error('Geometry popout did not close');await new Promise(resolve=>setTimeout(resolve,25));}} + } + if (c.previous?.view.containerEl.isConnected && c.previous !== c.pop) app.workspace.setActiveLeaf(c.previous, { focus: true }); delete globalThis[control]; } /** Uses only the parent runner's disposable drawing and restores its gateway. */ export async function runImageGeometryScenario({ cli, drawingPath, realRenderer = false }) { - const evaluate = code => JSON.parse(cli("eval", `code=${code}`).trim().replace(/^=>\s*/, "")); - const cases = []; - for (const [popout, scenario] of [[false, exercise], [true, exercise], [false, exerciseMarkdown], [false, exerciseMarkdownCrop]]) { - let result; - try { - evaluate(`(()=>{if(globalThis.${CONTROL})throw Error("geometry controller exists");const c=globalThis.${CONTROL}={state:"pending"};(${scenario.toString()})(${JSON.stringify(CONTROL)},${JSON.stringify(drawingPath)},${popout},${realRenderer}).then(()=>c.state="done").catch(e=>{c.error=e.stack;c.state="failed"});return JSON.stringify({started:true})})()`); - for (let i = 0; i < 600; i++) { - result = evaluate(`JSON.stringify({state:globalThis.${CONTROL}.state,error:globalThis.${CONTROL}.error,results:globalThis.${CONTROL}.results,reopen:globalThis.${CONTROL}.reopen})`); - if (result.state !== "pending") break; - await new Promise(resolve => setTimeout(resolve, 100)); - } - assert.equal(result.state, "done", result.error ?? "geometry scenario timed out"); - cases.push({ window: popout ? "popout" : "main", ...result }); - } catch (error) { - throw new Error(`${error.message}; scenario: ${scenario.name}; completed: ${cases.length}; last state: ${JSON.stringify(result)}`, { cause: error }); - } finally { - cli("eval", `code=(${cleanup.toString()})(${JSON.stringify(CONTROL)})`); - } + const cases=[]; + for(const [popout,scenario] of [[false,exercise],[true,exercise],[false,exerciseMarkdown],[false,exerciseMarkdownCrop]]){ + const result=await runLegacyTask({cli,control:CONTROL,execute:scenario,cleanup,args:[drawingPath,popout,realRenderer],timeoutMs:90000,cleanupMs:120000}); + cases.push({window:popout?'popout':'main',...result}); } - return { id: realRenderer ? "image-geometry-real-3014" : "image-geometry-3014", renderer: realRenderer ? "extras-mathjax" : "deterministic-svg", status: "passed", cases }; + return {id:realRenderer?'image-geometry-real-3014':'image-geometry-3014',renderer:realRenderer?'extras-mathjax':'deterministic-svg',status:'passed',cases}; } diff --git a/scripts/testing/host/inAppTask.mjs b/scripts/testing/host/inAppTask.mjs index ec2ec069..c675f649 100644 --- a/scripts/testing/host/inAppTask.mjs +++ b/scripts/testing/host/inAppTask.mjs @@ -79,6 +79,7 @@ function installTask(key, execute, args) { c.defer = callback => c.disposers.push(callback); c.case = async (testId, featureIds, executeCase) => { c.checkpoint(); + c.activeCase=testId; try { const evidence = await executeCase(); if (!evidence?.assertions?.length) throw Error('Native case has no assertion evidence'); @@ -86,7 +87,7 @@ function installTask(key, execute, args) { } catch (error) { c.tests.push({ testId, featureIds, status: 'failed', reason: String(error.stack || error) }); throw error; - } + } finally { delete c.activeCase; } }; c.task = (async () => { try { c.result = await execute(c, ...args); } catch (error) { c.error = String(error.stack || error); } diff --git a/scripts/testing/host/latexInput.mjs b/scripts/testing/host/latexInput.mjs index 8aa27ef5..6f16add6 100644 --- a/scripts/testing/host/latexInput.mjs +++ b/scripts/testing/host/latexInput.mjs @@ -1,3 +1,4 @@ +import {runHostFunction} from './legacyTask.mjs'; /** #2970: real CodeMirror input in a main window and an owned Electron popout. */ import assert from "node:assert/strict"; @@ -105,8 +106,8 @@ async function cleanup(control) { else delete gateway.getMathJax; } cancel(control); - if (c.pop) { await c.pop.setViewState({ type: "empty", state: {} }); c.pop.detach(); } - if (c.previous && c.previous !== c.pop) app.workspace.setActiveLeaf(c.previous, { focus: true }); + if (c.pop) {const win=c.pop.view.containerEl.ownerDocument.defaultView;if(win===app.workspace.containerEl.ownerDocument.defaultView)throw Error('LaTeX popout owner changed');if(c.pop.view.isDirty?.())await c.pop.view.saveWithOutcome();win.close();const end=Date.now()+10000;while(!win.closed){if(Date.now()>end)throw Error('LaTeX popout did not close');await new Promise(resolve=>setTimeout(resolve,25));}} + if (c.previous?.view.containerEl.isConnected && c.previous !== c.pop) app.workspace.setActiveLeaf(c.previous, { focus: true }); delete globalThis[control]; } @@ -131,12 +132,9 @@ export async function runLatexInputScenario({ cli, drawingPath, realRenderer = f } throw Error(`${label}: ${JSON.stringify(current())}`); } - async function act(fn, ...args) { - evaluate(`(()=>{${definitions}const c=globalThis.${CONTROL};c.state="pending";c.error=null;Promise.resolve((${fn.toString()})(${[CONTROL, ...args].map(v => JSON.stringify(v)).join(",")})).then(()=>c.state="done").catch(e=>{c.error=e.stack||String(e);c.state="failed"});return JSON.stringify({started:true})})()`); - await poll(v => v.state === "done", fn.name); - } + async function act(fn,...args){return runHostFunction({cli,execute:fn,helpers:[editor,cancel],args:[CONTROL,...args]});} const cdp = (method, params = {}) => JSON.parse(cli("dev:cdp", `method=${method}`, `params=${JSON.stringify(params)}`)); - let session, request = 0; + let session, request = 0, unsettled=false; const input = (method, params) => session ? cdp("Target.sendMessageToTarget", { sessionId: session, message: JSON.stringify({ id: ++request, method, params }), }) : cdp(method, params); @@ -151,9 +149,7 @@ export async function runLatexInputScenario({ cli, drawingPath, realRenderer = f return { ready: true }; }); try { - // setup must install its controller before starting async fixture work. - evaluate(`(()=>{Promise.resolve((${setup.toString()})(${JSON.stringify(CONTROL)},${JSON.stringify(drawingPath)},${JSON.stringify(realRenderer)})).then(()=>globalThis.${CONTROL}.state="done").catch(e=>{const c=globalThis.${CONTROL};if(c){c.error=e.stack;c.state="failed"}else throw e});return JSON.stringify({started:true})})()`); - await poll(v => v.state === "done", "setup"); + await runHostFunction({cli,execute:setup,args:[CONTROL,drawingPath,realRenderer]}); for (const mode of ["main", "direct-popout", "moved-popout"]) { if (mode !== "main") { const before = new Set(cdp("Target.getTargets").targetInfos.map(t => t.targetId)); @@ -218,25 +214,18 @@ export async function runLatexInputScenario({ cli, drawingPath, realRenderer = f cases.push(mode); if (session) { cdp("Target.detachFromTarget", { sessionId: session }); session = undefined; - await act(async control => { const c = globalThis[control]; await c.pop.setViewState({ type: "empty", state: {} }); c.pop.detach(); c.pop = null; c.current = c.leaf; }); + await act(async control => { const c = globalThis[control]; const win=c.pop.view.containerEl.ownerDocument.defaultView;if(win===app.workspace.containerEl.ownerDocument.defaultView)throw Error('LaTeX popout owner changed');if(c.pop.view.isDirty?.())await c.pop.view.saveWithOutcome();win.close();const end=Date.now()+10000;while(!win.closed){if(Date.now()>end)throw Error('LaTeX popout did not close');await new Promise(resolve=>setTimeout(resolve,25));} c.pop = null; c.current = c.leaf; }); } } return { id: realRenderer ? "latex-preview-2970" : "latex-input-2970", status: "passed", cases, renderer: realRenderer ? "real Extras MathJax and Latex Suite preview" : "local SVG stub; MathJax/Extras not tested", assertions: ["mounted CodeMirror root", "native clicks/arrows/backspace", "selection replacement/undo", "Mod-Enter/save/reopen", "cancel/destroy", ...(realRenderer ? ["visible Latex Suite preview", "preview contains rendered math without errors"] : [])] }; - } finally { + } catch(error) {unsettled=error.cleanupFailed===true;throw error;} finally { let detachError; try { if (session) cdp("Target.detachFromTarget", { sessionId: session }); } catch (error) { detachError = error; } - evaluate(`(()=>{${definitions}Promise.resolve((${cleanup.toString()})(${JSON.stringify(CONTROL)})).catch(e=>{globalThis.${CONTROL}.cleanupError=e.stack});return JSON.stringify({started:true})})()`); - for (let i = 0; i < 100; i++) { - const value = evaluate(`JSON.stringify({exists:!!globalThis.${CONTROL},error:globalThis.${CONTROL}?.cleanupError})`); - if (!value.exists) break; - if (value.error) throw Error(value.error); - if (i === 99) throw Error("LaTeX cleanup timed out"); - await wait(100); - } + if(!unsettled)await runHostFunction({cli,execute:cleanup,helpers:[editor,cancel],args:[CONTROL]}); if (detachError) throw detachError; } } diff --git a/scripts/testing/host/legacyTask.mjs b/scripts/testing/host/legacyTask.mjs new file mode 100644 index 00000000..b3929864 --- /dev/null +++ b/scripts/testing/host/legacyTask.mjs @@ -0,0 +1,23 @@ +/** Retire polling-only native probes through the shared settle-before-cleanup contract. */ +import assert from 'node:assert/strict'; +import {runInAppTask} from './inAppTask.mjs'; +export async function runLegacyTask({cli,control,execute,cleanup=async()=>{},args=[],timeoutMs=120000,cleanupMs=180000}){ + assert.match(control,/^__[a-zA-Z0-9_]+$/,'Legacy controller must be a named owned test global'); + // Both functions are local repository helpers, serialized exactly as existing + // native probes are. No remote code, production instrumentation or source-coverage credit. + const adapter=new Function(`return async function(c,control,args){ + if(globalThis[control])throw Error('Existing native controller: '+control); + const legacy={state:'pending'};globalThis[control]=legacy; + c.defer(async()=>{await (${cleanup.toString()})(control);if(globalThis[control]===legacy)delete globalThis[control];}); + c.checkpoint();const result=await (${execute.toString()})(control,...args); + return {result,results:legacy.results,reopen:legacy.reopen}; + }`)(); + try{return await runInAppTask({cli,execute:adapter,args:[control,args],timeoutMs,cleanupMs});} + catch(error){error.message+='; legacy controller: '+control;throw error;} +} + +/** Await an entire existing host operation before its caller may restore or delete resources. */ +export function runHostFunction({cli,execute,args=[],helpers=[],timeoutMs=60000,cleanupMs=120000}){ + const adapter=new Function(`return async function(c,...args){${helpers.map(helper=>helper.toString()).join(';')} c.checkpoint();return await (${execute.toString()})(...args);}`)(); + return runInAppTask({cli,execute:adapter,args,timeoutMs,cleanupMs}); +} diff --git a/scripts/testing/host/legacyTask.test.mjs b/scripts/testing/host/legacyTask.test.mjs new file mode 100644 index 00000000..5dff05c9 --- /dev/null +++ b/scripts/testing/host/legacyTask.test.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import vm from 'node:vm'; +import {runLegacyTask} from './legacyTask.mjs'; +function host(){const state={setTimeout,clearTimeout,events:[]};vm.createContext(state);return {state,cli(command,code){assert.equal(command,'eval');return String(vm.runInContext(code.slice(5),state));}};} +test('timed-out legacy work settles before cleanup and controller removal',async()=>{ + const {state,cli}=host(); + await assert.rejects(runLegacyTask({cli,control:'__legacy_owned',timeoutMs:10,cleanupMs:1000,execute:async()=>{events.push('started');await new Promise(resolve=>setTimeout(resolve,150));events.push('finished');},cleanup:async()=>{events.push('cleanup');}}),/deadline/); + assert.deepEqual(state.events,['started','finished','cleanup']); + assert.equal(vm.runInContext('Object.keys(globalThis).some(key=>key.startsWith("__"))',state),false); +}); +test('failed legacy cleanup retains both controllers for guarded recovery',async()=>{ + const {state,cli}=host(); + await assert.rejects(runLegacyTask({cli,control:'__legacy_failed',execute:async()=>{},cleanup:async()=>{throw Error('owned resource leaked');}}),error=>error.cleanupFailed&&/resource leaked/.test(error.message)); + assert.equal(vm.runInContext('!!globalThis.__legacy_failed',state),true); + assert.equal(Object.keys(state).filter(key=>key.startsWith('__excalidrawTestTask_')).length,1); +}); diff --git a/scripts/testing/host/lifecycle.mjs b/scripts/testing/host/lifecycle.mjs index 9dd29374..8d45da55 100644 --- a/scripts/testing/host/lifecycle.mjs +++ b/scripts/testing/host/lifecycle.mjs @@ -89,6 +89,9 @@ async function exerciseLifecycle(c, prefix, fixture) { }); await c.case("native:lifecycle-new-popout-survivor", ["P03"], async () => { const popout = app.workspace.openPopoutLeaf(); owned.add(popout); + // Obsidian moves the initially empty leaf asynchronously; begin file loading + // only after it reaches its destination document, as in the Lucide probe. + await c.waitFor(() => popout.view.containerEl.ownerDocument !== doc, "empty popout migration before drawing load"); await popout.setViewState({ type: "excalidraw", state: { file: first.path } }); app.workspace.setActiveLeaf(popout, { focus: true }); await ready(popout); check(popout.view.ownerDocument !== doc && popout.view.excalidrawAPI.getSceneElements()[0].x === 654, "fresh popout did not load persisted data"); diff --git a/scripts/testing/host/lucideIcons.mjs b/scripts/testing/host/lucideIcons.mjs index 7f0c356a..eff99a96 100644 --- a/scripts/testing/host/lucideIcons.mjs +++ b/scripts/testing/host/lucideIcons.mjs @@ -1,3 +1,4 @@ +import { runLegacyTask } from './legacyTask.mjs'; /** #3019 live checks, restricted to fixtures owned by the guarded parent runner. */ import assert from 'node:assert/strict'; import { join } from 'node:path'; @@ -11,6 +12,7 @@ export async function runLucideScenario({cli,drawingPath,reportDir}) { const evaluate=code=>JSON.parse(cli('eval','code='+code).trim().replace(/^=>\s*/,'')); const action=(command,values={})=>JSON.parse(cli('obsidian-excalidraw-plugin:'+command,'json='+JSON.stringify({apiVersion:1,...values}))); const ok=r=>{assert.equal(r.ok,true,JSON.stringify(r));return r;}; + let unsettled=false; let n=0; const id=()=>prefix.slice(-40)+'-'+(++n); const read=source=>ok(action('read',{path:paths.drawing,source,detail:'elements',limit:200})).data; @@ -53,21 +55,14 @@ export async function runLucideScenario({cli,drawingPath,reportDir}) { const vault=evaluate('JSON.stringify(app.vault.adapter.basePath)'); copyFileSync(join(vault,paths.png),join(reportDir,'lucide-presets.png')); ok(action('create',{requestId:id(),path:paths.popout,elements:[]})); - evaluate(`(()=>{if(globalThis.${key})throw Error('Lucide test already active');globalThis.${key}={state:'pending'};(${probeLucide.toString()})(${JSON.stringify(key)},${JSON.stringify(paths.drawing)},${JSON.stringify(drawingPath)},${JSON.stringify(catalog.map(e=>e.icon))},${JSON.stringify(paths.popout)}).then(result=>Object.assign(globalThis.${key},{state:'done',result})).catch(error=>Object.assign(globalThis.${key},{state:'failed',error:String(error.stack)}));return JSON.stringify({started:true})})()`); - let probe; - for(let i=0;i<1000;i++) { - probe=evaluate(`JSON.stringify(globalThis.${key})`); - if(probe.state!=='pending')break; - await new Promise(resolve=>setTimeout(resolve,100)); - } - assert.equal(probe.state,'done',probe.error??'Lucide probe timed out'); + const probe=await runLegacyTask({cli,control:key,execute:probeLucide,args:[paths.drawing,drawingPath,catalog.map(e=>e.icon),paths.popout],timeoutMs:120000,cleanupMs:120000}); const saved=read('disk');assert.equal(saved.assetIds.length,0); assert.ok(saved.elements.every(e=>e.type!=='image')); evaluate(`(async()=>{const p=app.plugins.plugins['obsidian-excalidraw-plugin'];const view=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(paths.drawing)}).view;await p.lucidePicker.open(view);return JSON.stringify({open:true})})()`); cli('dev:screenshot','path='+join(reportDir,'lucide-picker.png')); return {id:'lucide-3019',status:'passed',catalog:catalog.length,artifacts,...probe.result}; - } finally { - evaluate(`(async()=>{const p=app.plugins.plugins['obsidian-excalidraw-plugin'];p?.lucidePicker?.tab?.close();delete globalThis.${key};for(const path of ${JSON.stringify(Object.values(paths))}){if(!path.startsWith('__excalidraw_cli_smoke_'))throw Error('Not an owned fixture');for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}const file=app.vault.getFileByPath(path);if(file)await app.vault.delete(file)}return JSON.stringify({clean:true})})()`); + } catch(error) {unsettled=error.cleanupFailed===true;throw error;} finally { + if(!unsettled)evaluate(`(async()=>{const p=app.plugins.plugins['obsidian-excalidraw-plugin'];p?.lucidePicker?.tab?.close();delete globalThis.${key};for(const path of ${JSON.stringify(Object.values(paths))}){if(!path.startsWith('__excalidraw_cli_smoke_'))throw Error('Not an owned fixture');for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}const file=app.vault.getFileByPath(path);if(file)await app.vault.delete(file)}return JSON.stringify({clean:true})})()`); } } @@ -186,7 +181,7 @@ async function probeLucide(key,path,otherPath,catalog,popoutPath) { return {catalogPresetConversions:conversions,rejectedCatalogInputs:rejected,totalElements:total,totalPoints:points,maxConversionMs:maxMs,imageMenu:true,uiPresets:true,gridPagination:true,nestedThumbnailClicks:true,undoRedo:true,keyboardNavigation:true,singleton:true,twoDrawings:true,popout:true,staleTarget:true,sessionReuse:true}; } finally { picker.tab?.close(); - if(popout){await popout.setViewState({type:'empty',state:{}});popout.detach();} + if(popout){const win=popout.view.containerEl.ownerDocument.defaultView;if(win===app.workspace.containerEl.ownerDocument.defaultView)throw Error('Lucide popout migrated unexpectedly');if(popout.view.isDirty?.())await popout.view.saveWithOutcome();win.close();const end=Date.now()+10000;while(!win.closed){if(Date.now()>end)throw Error('Lucide popout did not close');await new Promise(resolve=>setTimeout(resolve,25));}} if(view.excalidrawAPI===api)api.updateScene({appState:{currentItemStrokeColor:originalStyle.currentItemStrokeColor,currentItemRoughness:originalStyle.currentItemRoughness,currentItemOpacity:originalStyle.currentItemOpacity},captureUpdate:'NEVER'}); } } diff --git a/scripts/testing/host/requireIsolatedSession.mjs b/scripts/testing/host/requireIsolatedSession.mjs new file mode 100644 index 00000000..f79257b4 --- /dev/null +++ b/scripts/testing/host/requireIsolatedSession.mjs @@ -0,0 +1,29 @@ +/** Native CI preflight only: prove the explicitly provisioned session is isolated. */ +import assert from 'node:assert/strict'; +import {readFileSync,realpathSync} from 'node:fs'; +import {join,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {ownedPath} from '../contracts.mjs'; +import {validateOwnedVault} from '../provision.mjs'; +import {parseCLIJSON} from './inAppTask.mjs'; +import {obsidianCliExecutable,spawnNativeSync} from './processTools.mjs'; +export function requireIsolatedSession({workRoot,vaultPath,vaultName,userDataPath,readHostUserData}){ + assert.ok(workRoot&&vaultPath&&vaultName&&userDataPath,'Set explicit owned automation vault and user-data paths'); + const owned=validateOwnedVault({workRoot:resolve(workRoot),vaultPath:resolve(vaultPath)}); + assert.equal(owned.marker.vaultName,vaultName,'Wrong owned native vault'); + const marker=JSON.parse(readFileSync(ownedPath(userDataPath,'.excalidraw-native-session.json'))); + assert.equal(marker.schemaVersion,2);assert.equal(marker.owner,'obsidian-excalidraw-tests'); + assert.equal(marker.vaultId,owned.marker.vaultId,'Native session marker belongs to another vault'); + const registry=JSON.parse(readFileSync(ownedPath(userDataPath,'obsidian.json'))); + const registered=Object.values(registry.vaults||{}); + assert.equal(registered.length,1,'Native CI session must register exactly one owned vault'); + assert.equal(realpathSync(registered[0].path),owned.vault,'Native CI session includes a different vault'); + assert.equal(realpathSync(readHostUserData()),realpathSync(userDataPath),'CLI reached another application session'); + return {vaultId:owned.marker.vaultId,isolated:true}; +} +if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){ + const vaultName=process.env.EXCALIDRAW_TEST_VAULT_NAME; + requireIsolatedSession({workRoot:process.env.EXCALIDRAW_TEST_AUTOMATION_ROOT,vaultPath:process.env.EXCALIDRAW_TEST_VAULT_PATH,vaultName,userDataPath:process.env.EXCALIDRAW_TEST_USER_DATA_PATH, + readHostUserData:()=>{const r=spawnNativeSync(obsidianCliExecutable(),['vault='+vaultName,'eval',"code=JSON.stringify(require('@electron/remote').app.getPath('userData'))"],{encoding:'utf8',timeout:15000});if(r.error||r.status)throw Error('Native CI cannot reach its isolated host');return parseCLIJSON(r.stdout);}}); + process.stdout.write('Verified one registered owned automation vault in the actual CLI session\n'); +} diff --git a/scripts/testing/host/requireIsolatedSession.test.mjs b/scripts/testing/host/requireIsolatedSession.test.mjs new file mode 100644 index 00000000..d0e2b3a3 --- /dev/null +++ b/scripts/testing/host/requireIsolatedSession.test.mjs @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {mkdtempSync,mkdirSync,writeFileSync,rmSync,realpathSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join,dirname,basename} from 'node:path'; +import {provisionVault} from '../provision.mjs'; +import {requireIsolatedSession} from './requireIsolatedSession.mjs'; +test('native CI rejects another CLI session, extra registered vaults and mismatched ownership',t=>{ + const parent=mkdtempSync(join(tmpdir(),'excalidraw-native-isolation-')); + t.after(()=>{assert.equal(dirname(realpathSync(parent)),realpathSync(tmpdir()));assert.ok(basename(parent).startsWith('excalidraw-native-isolation-'));rmSync(parent,{recursive:true,force:true});}); + const workRoot=join(parent,'owned'),vault=provisionVault({workRoot,name:'excalidraw-auto-native-ci'}),userDataPath=join(parent,'user-data');mkdirSync(userDataPath); + const marker={schemaVersion:2,owner:'obsidian-excalidraw-tests',vaultId:vault.ownership.vaultId}; + const registry={vaults:{owned:{path:vault.vaultPath}}}; + const write=()=>{writeFileSync(join(userDataPath,'.excalidraw-native-session.json'),JSON.stringify(marker));writeFileSync(join(userDataPath,'obsidian.json'),JSON.stringify(registry));};write(); + const options={workRoot,vaultPath:vault.vaultPath,vaultName:'excalidraw-auto-native-ci',userDataPath,readHostUserData:()=>userDataPath}; + assert.equal(requireIsolatedSession(options).isolated,true); + assert.throws(()=>requireIsolatedSession({...options,readHostUserData:()=>parent}),/another application/); + registry.vaults.other={path:parent};write();assert.throws(()=>requireIsolatedSession(options),/exactly one/);delete registry.vaults.other; + marker.vaultId='another-vault';write();assert.throws(()=>requireIsolatedSession(options),/another vault/); +}); diff --git a/scripts/testing/host/runner.mjs b/scripts/testing/host/runner.mjs index cb8ec37c..3b663635 100644 --- a/scripts/testing/host/runner.mjs +++ b/scripts/testing/host/runner.mjs @@ -1,7 +1,7 @@ /** Native Obsidian smoke lane for the exact locally built Excalidraw plugin. */ import { createHash, randomUUID } from "node:crypto"; import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; -import { basename, isAbsolute, join, relative, sep } from "node:path"; +import { basename, isAbsolute, join, relative, resolve, sep } from "node:path"; import { validateOwnedVault } from "../provision.mjs"; import { adaptSmokeReport, ownedPath } from "../contracts.mjs"; import { acquireDebuggerSession, unexpectedConsoleErrors } from "./debuggerSession.mjs"; @@ -84,9 +84,9 @@ function artifacts(projectRoot) { return { paths, hashes: Object.fromEntries(ARTIFACTS.map((name) => [name, hash(paths[name])])), version: manifest.version }; } -const startCode = (name) => `(()=>{const p=app.plugins.plugins[${JSON.stringify(PLUGIN_ID)}];if(!p)return JSON.stringify({state:"failed",error:"plugin not loaded"});if(globalThis.${CONTROL})return JSON.stringify({state:"failed",error:"smoke controller already exists"});const c={state:"pending",name:${JSON.stringify(name)},path:null,error:null,cancel:false};globalThis.${CONTROL}=c;const extension=p.settings.compatibilityMode?".excalidraw":p.settings.useExcalidrawExtension?".excalidraw.md":".md";Promise.resolve(p.createAndOpenDrawing(c.name+extension,"new-tab","/")).then(async path=>{c.path=path;c.state="created";if(c.cancel){const file=app.vault.getFileByPath(path);if(file&&file.name.startsWith(${JSON.stringify(PREFIX)})){const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);if(leaf){await leaf.setViewState({type:"empty",state:{}});leaf.detach()}await app.vault.delete(file)}c.state="clean"}}).catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"started"})})()`; -const statusCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"missing"});const leaf=c.path&&app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===c.path);const view=leaf?.view;return JSON.stringify({state:c.state,path:c.path,error:c.error,ready:!!view?.excalidrawAPI,wrapper:!!view?.containerEl?.querySelector(".excalidraw-wrapper"),ownerMatches:!!view&&view.ownerDocument===view.containerEl.ownerDocument,mainWindow:!!view&&view.ownerDocument===app.workspace.containerEl?.ownerDocument})})()`; -const cleanupCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"clean"});if(c.state==="pending"){c.cancel=true;return JSON.stringify({state:"pending"})}if(c.state==="cleaning")return JSON.stringify({state:"cleaning"});const path=c.path;const file=path&&app.vault.getFileByPath(path);if(!file){delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})}if(!file.name.startsWith(${JSON.stringify(PREFIX)}))return JSON.stringify({state:"failed",error:"refusing to delete a non-smoke drawing"});const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);c.state="cleaning";(async()=>{if(leaf){await leaf.setViewState({type:"empty",state:{}});leaf.detach()}await app.vault.delete(file);c.state="clean"})().catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"cleaning"})})()`; +const startCode = (name) => `(()=>{const p=app.plugins.plugins[${JSON.stringify(PLUGIN_ID)}];let anchor;app.workspace.iterateAllLeaves(leaf=>{if(!anchor&&leaf.getRoot()===app.workspace.rootSplit)anchor=leaf});if(anchor){app.workspace.setActiveLeaf(anchor,{focus:true});app.workspace.containerEl.ownerDocument.defaultView.focus()}if(!p)return JSON.stringify({state:"failed",error:"plugin not loaded"});if(globalThis.${CONTROL})return JSON.stringify({state:"failed",error:"smoke controller already exists"});const c={state:"pending",name:${JSON.stringify(name)},path:null,error:null,cancel:false};globalThis.${CONTROL}=c;const extension=p.settings.compatibilityMode?".excalidraw":p.settings.useExcalidrawExtension?".excalidraw.md":".md";Promise.resolve(p.createAndOpenDrawing(c.name+extension,"new-tab","/")).then(async path=>{c.path=path;c.state="created";if(c.cancel){const file=app.vault.getFileByPath(path);if(file&&file.name.startsWith(${JSON.stringify(PREFIX)})){const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);if(leaf){await leaf.setViewState({type:"empty",state:{}});leaf.detach()}await app.vault.delete(file)}c.state="clean"}}).catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"started"})})()`; +const statusCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"missing"});const leaf=c.path&&app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===c.path);const view=leaf?.view;return JSON.stringify({state:c.state,path:c.path,error:c.error,ready:!!view?.excalidrawAPI&&view.isLoaded&&!view.excalidrawAPI.getAppState().isLoading&&!view.semaphores.justLoaded&&!view.isClosingOrMigrating(),wrapper:!!view?.containerEl?.querySelector(".excalidraw-wrapper"),ownerMatches:!!view&&view.ownerDocument===view.containerEl.ownerDocument,mainWindow:!!view&&view.ownerDocument===app.workspace.containerEl?.ownerDocument})})()`; +const cleanupCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"clean"});if(c.state==="pending"){c.cancel=true;return JSON.stringify({state:"pending"})}if(c.state==="cleaning")return JSON.stringify({state:"cleaning"});const path=c.path;const file=path&&app.vault.getFileByPath(path);if(!file){delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})}if(!file.name.startsWith(${JSON.stringify(PREFIX)}))return JSON.stringify({state:"failed",error:"refusing to delete a non-smoke drawing"});const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);c.state="cleaning";(async()=>{if(leaf){const view=leaf.view;if(view.excalidrawAPI&&view.isDirty()){const saved=await view.saveWithOutcome();if(saved.status!=="persisted")throw Error("Owned drawing cleanup could not save")}}await app.vault.delete(file);if(leaf){const end=Date.now()+15000;while(leaf.view.getViewType()==="excalidraw"&&leaf.view.containerEl.isConnected){if(Date.now()>end)throw Error("Deleted owned drawing did not retire");await new Promise(resolve=>setTimeout(resolve,25))}if(leaf.view.containerEl.isConnected)leaf.detach()}c.state="clean"})().catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"cleaning"})})()`; async function poll(read, acceptable, wait, now, timeoutMs = 20_000) { const deadline = now() + timeoutMs; @@ -101,15 +101,23 @@ async function poll(read, acceptable, wait, now, timeoutMs = 20_000) { /** Preflight, build, stage and exercise one disposable drawing; always write a report. */ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, configDir, automationRoot, reportDir, runCli, runBuild, - wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(), source = {}, unique = () => randomUUID(), scenarios = [], ownedDebugger = false }) { + wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(), source = {}, unique = () => randomUUID(), scenarios = [], ownedDebugger = false, deployCompanions }) { + reportDir = resolve(reportDir); const report = { schemaVersion: 1, status: "failed", startedAt: new Date(now()).toISOString(), source, target: { vaultName, vaultPath, configDir }, capabilities: {}, artifacts: {}, scenarios: [], cleanup: "not-started" }; mkdirSync(reportDir, { recursive: true }); let phase = "preflight"; let created = false; let preserveOwnedFixtures = false; - let debuggerSession, ownedCli; + let debuggerSession, ownedCli, companionCleanup; const expectedConsoleErrors = []; + const cleanupDrawing = async () => { + if(!created)return; + const cli = code => parseEval(runCli(vaultName,'eval','code='+code)); + const response=cli(cleanupCode);if(response.state==='failed')throw Error(response.error); + await poll(()=>cli(`(()=>JSON.stringify({state:globalThis.${CONTROL}?.state||"clean",error:globalThis.${CONTROL}?.error}))()`),value=>value.state==='clean',wait,now); + cli(`(()=>{delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})})()`);created=false; + }; try { const target = validateTarget({ vaultName, vaultPath, configDir, automationRoot }); const cli = (command, ...args) => { @@ -120,7 +128,8 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf ownedCli = cli; report.capabilities.version = cli("version").trim(); const help = cli("help"); - const missing = REQUIRED_CLI.filter((command) => !help.includes(command)); + const required=ownedDebugger?[...REQUIRED_CLI,"dev:debug","dev:cdp"]:REQUIRED_CLI; + const missing = required.filter((command) => !help.includes(command)); if (missing.length) throw new Error(`Obsidian CLI lacks: ${missing.join(", ")}`); const selected = cliPath(cli("vault", "info=path")); if (!existsSync(selected) || realpathSync(selected) !== target.vault) { @@ -135,15 +144,19 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf throw new Error(`CLI config directory differs from ${target.config}`); } if (ownedDebugger) debuggerSession = acquireDebuggerSession(cli); + if (ownedDebugger) report.capabilities.runtime = parseEval(cli("eval", "code=JSON.stringify({versions:require('process').versions,platform:require('process').platform,userAgent:navigator.userAgent})")); phase = "build"; - const forkArtifacts = await runBuild(); - const built = artifacts(projectRoot); + const buildResult = await runBuild(); + const forkArtifacts = buildResult?.forkArtifacts || buildResult; + const built = artifacts(buildResult?.pluginArtifactRoot || projectRoot); + if (buildResult?.combination) report.combination = buildResult.combination; report.artifacts = { forkArtifacts, version: built.version, sourceHashes: built.hashes, mainBytes: readFileSync(built.paths["main.js"]).length }; phase = "deploy"; if (existsSync(target.pluginDir)) cli("plugin:disable", `id=${PLUGIN_ID}`); + if (deployCompanions) { const deployed = await deployCompanions({ cli, target }); report.artifacts.companions = deployed.evidence; companionCleanup = deployed.cleanup; } mkdirSync(target.pluginDir, { recursive: true }); for (const name of ARTIFACTS) copyFileSync(built.paths[name], join(target.pluginDir, name)); report.artifacts.installedHashes = Object.fromEntries(ARTIFACTS.map((name) => [name, hash(join(target.pluginDir, name))])); @@ -166,16 +179,27 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf const started = parseEval(cli("eval", `code=${startCode(name)}`)); if (started.state !== "started") throw new Error(started.error || "Could not start drawing smoke"); created = true; - const drawing = await poll(() => parseEval(cli("eval", `code=${statusCode}`)), + let drawing = await poll(() => parseEval(cli("eval", `code=${statusCode}`)), (value) => value.state === "created" && value.ready && value.wrapper && value.ownerMatches && value.mainWindow, wait, now); if (!drawing.path || !basename(drawing.path).startsWith(PREFIX)) throw new Error("Unexpected smoke drawing path"); report.target.drawingPath = drawing.path; + report.target.fixturePaths = [drawing.path]; report.scenarios.push({ id: "drawing-main-window", status: "passed", assertions: ["Excalidraw API ready", "wrapper mounted", "owner document matches", "main application document"] }); phase = "feature-scenarios"; - for (const scenario of scenarios) { + for (const [index,scenario] of scenarios.entries()) { + if(index>0){ + await cleanupDrawing(); + const next=parseEval(cli('eval','code='+startCode(name+'_case'+index))); + if(next.state!=='started')throw Error(next.error||'Next scenario fixture did not start');created=true; + drawing=await poll(()=>parseEval(cli('eval','code='+statusCode)),value=>value.state==='created'&&value.ready&&value.wrapper&&value.ownerMatches&&value.mainWindow,wait,now); + if(!drawing.path||!basename(drawing.path).startsWith(PREFIX))throw Error('Unexpected scenario drawing path'); + report.target.fixturePaths.push(drawing.path); + } + report.target.drawingPath=drawing.path; const result = await scenario({ cli, drawingPath: drawing.path, reportDir }); report.scenarios.push(result); expectedConsoleErrors.push(...(result.expectedConsoleErrors || [])); + if (result.status !== "passed") throw Error(`Required native scenario ${result.id} is ${result.status}: ${result.reason || "no reason supplied"}`); } const errors = cli("dev:errors").trim(); if (errors && !/^No errors captured\.?$/i.test(errors)) throw new Error(`Captured JavaScript errors: ${errors.slice(0, 1000)}`); @@ -185,19 +209,14 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf preserveOwnedFixtures = error?.cleanupFailed === true; report.error = error instanceof Error ? error.message : String(error); if (error?.evidence) report.failedTaskEvidence = error.evidence; - report.scenarios.push({ id: phase, status: "failed", reason: report.error }); + report.scenarios.push({ id: phase, status: "failed", reason: report.error, ...(error?.evidence?.length ? {tests:error.evidence} : {}) }); } finally { if (created && preserveOwnedFixtures) { report.cleanup = "failed"; report.cleanupError = "Unsettled or leaked native task; fixtures preserved for guarded recovery"; } else if (created) { try { - const cli = (code) => parseEval(runCli(vaultName, "eval", `code=${code}`)); - const response = cli(cleanupCode); - if (response.state === "failed") throw new Error(response.error); - await poll(() => cli(`(()=>JSON.stringify({state:globalThis.${CONTROL}?.state||"clean",error:globalThis.${CONTROL}?.error}))()`), - (value) => value.state === "clean", wait, now); - cli(`(()=>{delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})})()`); + await cleanupDrawing(); report.cleanup = "passed"; } catch (error) { report.cleanup = "failed"; @@ -205,6 +224,7 @@ export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, conf report.status = "failed"; } } + if (companionCleanup) { try { await companionCleanup(); } catch(error) { report.status="failed"; report.cleanup="failed"; report.cleanupError=String(error); } } if (debuggerSession) { try { report.consoleErrors = debuggerSession.read(); diff --git a/scripts/testing/host/runner.test.mjs b/scripts/testing/host/runner.test.mjs index d423df9e..df40b327 100644 --- a/scripts/testing/host/runner.test.mjs +++ b/scripts/testing/host/runner.test.mjs @@ -68,7 +68,7 @@ test("stages exact artifacts, asserts an editor and cleans its test drawing", as const input = fixture(); const commands = []; let cleanupStarted = false; - let commandReads = 0; + let commandReads = 0, activeDrawing="__excalidraw_cli_smoke_1.excalidraw.md"; const runCli = (_vault, command, ...args) => { commands.push(command); if (command === "version") return "1.13.0"; @@ -84,18 +84,20 @@ test("stages exact artifacts, asserts an editor and cleans its test drawing", as if (code.includes("getCLIRuntime")) return '{"valid":true,"protocol":3}'; if (code.includes("app.vault.configDir")) return '{"configDir":".obsidian"}'; if (code.includes("createAndOpenDrawing")) { + activeDrawing=code.includes("_case1")?"__excalidraw_cli_smoke_1_case1.excalidraw.md":"__excalidraw_cli_smoke_1.excalidraw.md"; assert.ok(code.includes("useExcalidrawExtension")); assert.ok(code.includes('"new-tab","/"')); return '=> {"state":"started"}'; } if (code.includes("app.vault.delete")) { - assert.ok(code.indexOf('await leaf.setViewState({type:"empty",state:{}})') < code.indexOf("await app.vault.delete(file)")); + assert.ok(code.indexOf("await view.saveWithOutcome()") {}, unique: () => "1", wait: () => {} }; - const report = await runObsidianSmoke({ ...options, scenarios: [featureScenario] }); + let companionCleaned = 0; + const options = { ...input, runCli, runBuild: () => ({pluginArtifactRoot:input.projectRoot,forkArtifacts:{verified:true}}), unique: () => "1", wait: () => {}, + deployCompanions: ({target}) => { assert.equal(target.config,input.configDir); return {evidence:{paired:true},cleanup:()=>{assert.equal(cleanupStarted,true);companionCleaned++;}}; } }; + const report = await runObsidianSmoke({ ...options, scenarios: [featureScenario,({drawingPath})=>{assert.equal(cleanupStarted,true,'Previous feature fixture must be retired first');assert.equal(drawingPath,'__excalidraw_cli_smoke_1_case1.excalidraw.md');return {id:'independent-feature',status:'passed'};}] }); assert.equal(report.status, "passed", report.error); assert.equal(report.cleanup, "passed"); - assert.equal(report.target.drawingPath, "__excalidraw_cli_smoke_1.excalidraw.md"); + assert.equal(report.target.drawingPath, "__excalidraw_cli_smoke_1_case1.excalidraw.md"); assert.deepEqual(report.artifacts.sourceHashes, report.artifacts.installedHashes); assert.ok(commands.includes("plugin:enable")); assert.equal(commandReads, 2); @@ -121,6 +125,12 @@ test("stages exact artifacts, asserts an editor and cleans its test drawing", as assert.equal(failed.cleanup, "passed"); assert.equal(cleanupStarted, true); assert.match(failed.error, /feature regression/); + assert.equal(companionCleaned,2,'Companion state restores after both success and scenario failure'); + assert.equal(report.artifacts.companions.paired,true); + const blocked = await runObsidianSmoke({...options,scenarios:[()=>({id:'required-feature',status:'blocked',reason:'Missing host capability'})]}); + assert.equal(blocked.status,'failed');assert.match(blocked.error,/required-feature is blocked/);assert.equal(blocked.cleanup,'passed'); + const cleanupFailure=await runObsidianSmoke({...options,deployCompanions:()=>({evidence:{},cleanup:()=>{throw Error('owned companion cleanup failure');}})}); + assert.equal(cleanupFailure.status,'failed');assert.equal(cleanupFailure.cleanup,'failed');assert.match(cleanupFailure.cleanupError,/companion cleanup failure/); }); test("an eval Error payload fails even when the CLI process reports success", async () => { diff --git a/scripts/testing/host/stability.mjs b/scripts/testing/host/stability.mjs new file mode 100644 index 00000000..9c449630 --- /dev/null +++ b/scripts/testing/host/stability.mjs @@ -0,0 +1,71 @@ +/** Bounded large-scene round trips in the real host; timings are diagnostics. */ +import assert from 'node:assert/strict'; +import {scene,drawingMarkdown} from '../fixtures.mjs'; +import {sha256} from '../contracts.mjs'; +import {runInAppTask} from './inAppTask.mjs'; + +export function stabilityFixture(count=1000){ + assert.ok(Number.isInteger(count)&&count>=2&&count<=2000,'Bounded stability fixture'); + const value=scene(count); + value.elements.forEach((element,index)=>{element.x=(index%40)*120;element.y=Math.floor(index/40)*80;}); + return drawingMarkdown(value); +} +export async function runStabilityScenario({cli,drawingPath,cycles=6}){ + assert.ok(drawingPath.startsWith('__excalidraw_cli_smoke_')); + assert.ok(Number.isInteger(cycles)&&cycles>=2&&cycles<=25,'Bounded stability cycles'); + const fixture=stabilityFixture(),path=drawingPath.replace(/\.(excalidraw\.md|excalidraw|md)$/,'')+'_stability.excalidraw.md'; + const result=await runInAppTask({cli,execute:exerciseStability,args:[path,fixture,cycles],timeoutMs:cycles*30000+90000,cleanupMs:60000}); + return {id:'stability',status:'passed',fixtureHash:sha256(fixture),...result}; +} +async function exerciseStability(c,path,fixture,cycles){ + const p=app.plugins.plugins['obsidian-excalidraw-plugin'],doc=app.workspace.containerEl.ownerDocument; + const check=(value,label)=>{if(!value)throw Error(label);}; + const beforeRoots=doc.querySelectorAll('.excalidraw-wrapper').length,previous=app.workspace.activeLeaf; + let leaf; + c.defer(async()=>{ + const file=app.vault.getFileByPath(path); + if(leaf?.view?.excalidrawAPI&&leaf.view.isDirty())check((await leaf.view.saveWithOutcome()).status==='persisted','Stability cleanup save failed'); + if(file){check(path.startsWith('__excalidraw_cli_smoke_')&&file.path===path,'Unowned stability cleanup');await app.vault.delete(file);} + if(leaf){await c.waitForCleanup(()=>leaf.view.getViewType()!=='excalidraw'||!leaf.view.containerEl.isConnected,'stability view retirement');if(leaf.view.containerEl.isConnected)leaf.detach();} + if(previous?.view.containerEl.isConnected)app.workspace.setActiveLeaf(previous,{focus:true}); + check(doc.querySelectorAll('.excalidraw-wrapper').length===beforeRoots,'Stability left an editor root'); + }); + const file=await app.vault.create(path,fixture); + await c.waitFor(()=>p.isExcalidrawFile(file),'large fixture metadata'); + const timings=[],retired=[]; + for(let cycle=0;cycle{ + const start=performance.now(); + let anchor;app.workspace.iterateAllLeaves(l=>{if(!anchor&&l.getRoot()===app.workspace.rootSplit)anchor=l;}); + check(anchor,'No main-window anchor');app.workspace.setActiveLeaf(anchor,{focus:true}); + leaf=app.workspace.getLeaf('tab');await leaf.openFile(file); + await c.waitFor(()=>leaf.view.excalidrawAPI&&leaf.view.isLoaded&&!leaf.view.semaphores.justLoaded&&!leaf.view.isClosingOrMigrating(),'large scene first commit',60000); + const view=leaf.view,api=view.excalidrawAPI,elements=api.getSceneElements(); + check(elements.length===1000,'Large scene lost elements'); + check(elements.every((element,i)=>element.customData?.retainedUnknown?.value===i),'Large scene lost custom data'); + check(!retired.includes(api),'Reopen reused a retired API'); + api.updateScene({elements:elements.map((element,i)=>i?element:{...element,x:cycle+1,version:element.version+1,versionNonce:element.versionNonce+1}),captureUpdate:'IMMEDIATELY',forceFlushSync:true}); + await c.waitFor(()=>view.isDirty(),'large scene dirty revision'); + check((await view.saveWithOutcome()).status==='persisted','Large scene save not acknowledged'); + const disk=await app.vault.read(file),saved=await p.ea.getSceneFromFile(file); + check(disk.includes('User Markdown retained.')&&saved.elements.length===1000&&saved.elements[0].x===cycle+1,'Large scene disk round trip differs'); + if(cycle===0){ + const runtime=p.getCLIRuntime(),exportStart=performance.now(); + const blob=await runtime.exportToBlob({elements:api.getSceneElements(),appState:{...api.getAppState(),exportBackground:true,exportScale:1},files:api.getFiles(),getDimensions:(width,height)=>({width:Math.ceil(width/4),height:Math.ceil(height/4),scale:0.25})}); + check(blob?.type==='image/png'&&blob.size>100,'Large scene PNG missing'); + const url=URL.createObjectURL(blob),image=new Image(); + try{image.src=url;await image.decode();check(image.naturalWidth>200&&image.naturalHeight>100,'Large scene PNG geometry missing'); + const canvas=createFragment().createEl('canvas');canvas.width=128;canvas.height=64;const context=canvas.getContext('2d');context.drawImage(image,0,0,128,64); + const pixels=context.getImageData(0,0,128,64).data;let red=0;for(let i=0;i180&&pixels[i+1]<200&&pixels[i+2]<200&&pixels[i+3]>0)red++; + check(red>100,'Large scene PNG is blank');check(performance.now()-exportStart<60000,'Large scene export exceeded generous budget'); + }finally{URL.revokeObjectURL(url);} + } + retired.push(api);await leaf.setViewState({type:'empty',state:{}});leaf.detach();leaf=null; + await c.waitFor(()=>!view.excalidrawAPI&&!view.containerEl.querySelector('.excalidraw-wrapper'),'old editor unmount'); + check(doc.querySelectorAll('.excalidraw-wrapper').length===beforeRoots,'Editor roots accumulate across reopen'); + const elapsed=performance.now()-start;check(elapsed<60000,'Large scene cycle exceeded generous budget');timings.push(elapsed); + return {assertions:['1000 elements and unknown custom data retained','physical save and Markdown preserved','fresh API and retired root','bounded scene/export duration'],durationMs:elapsed}; + }); + } + return {tests:c.tests,cycles,elements:1000,timingsMs:timings,limitations:'No forced-GC heap or physical-device performance claim; popout stress has its separate lifecycle lane.'}; +} diff --git a/scripts/testing/host/stability.test.mjs b/scripts/testing/host/stability.test.mjs new file mode 100644 index 00000000..051d1ea8 --- /dev/null +++ b/scripts/testing/host/stability.test.mjs @@ -0,0 +1,12 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {stabilityFixture} from './stability.mjs'; +test('large-scene stress stays bounded and deterministic with preserved prose and custom data',()=>{ + const value=stabilityFixture();assert.equal(value,stabilityFixture()); + const scene=JSON.parse(value.match(/```json\n([\s\S]*?)\n```/)[1]); + assert.equal(scene.elements.length,1000);assert.ok(value.includes('User Markdown retained.')); + assert.ok(Math.max(...scene.elements.map(e=>e.x+e.width))<5000); + assert.ok(Math.max(...scene.elements.map(e=>e.y+e.height))<2100); + assert.equal(scene.elements[999].customData.retainedUnknown.value,999); + assert.throws(()=>stabilityFixture(10000),/Bounded/); +}); diff --git a/scripts/testing/host/verify.mjs b/scripts/testing/host/verify.mjs index 488e4374..f9ef2bda 100644 --- a/scripts/testing/host/verify.mjs +++ b/scripts/testing/host/verify.mjs @@ -1,5 +1,5 @@ /** Build the plugin (optionally with the sibling fork), then run the guarded native smoke. */ -import { createHash } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; @@ -22,28 +22,48 @@ import { runLucideScenario } from "./lucideIcons.mjs"; import { runWorkflowFixesScenario } from "./workflowFixes.mjs"; import { acquireHostLock } from "./hostLock.mjs"; import { runDataIntegrityScenario } from "./dataIntegrity.mjs"; +import { runLifecycleScenario } from './lifecycle.mjs'; +import { runExtrasServicesScenario } from './extrasServices.mjs'; +import { runStabilityScenario } from './stability.mjs'; +import { runAutomateScenario } from './automate.mjs'; +import { runCoreInteractionScenario } from './coreInteraction.mjs'; +import { runDeviceMatrix } from './devices.mjs'; +import { deviceProfiles, breakpointProfiles } from './deviceProfiles.mjs'; +import { produceCombination, stageExtras } from './combination.mjs'; +import { aggregateReports, adaptSmokeReport } from '../contracts.mjs'; +import { writeReportFiles } from '../reportFiles.mjs'; +import { writeFileSync } from 'node:fs'; const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); +const profileArg = process.argv.slice(2).find(arg=>arg.startsWith('--profile=')); +const profile = profileArg?.slice('--profile='.length); +if(profileArg !== undefined && !['smoke','full','devices','soak'].includes(profile))throw Error('Use --profile=smoke|full|devices|soak'); +const fullProfile=profile==='full'; +const lifecycle=fullProfile||process.argv.includes('--lifecycle'); +const extrasServices=fullProfile||process.argv.includes('--extras-services'); +const devices=fullProfile||profile==='devices'||process.argv.includes('--devices'); const pluginOnly = process.argv.includes("--plugin-only"); -const textUndo = process.argv.includes("--text-undo"); -const nativeCLI = process.argv.includes("--native-cli"); -const embedRecovery = process.argv.includes("--embed-recovery"); -const groupedLinkClick = process.argv.includes("--grouped-link-click"); -const latexInput = process.argv.includes("--latex-input"); +const textUndo = fullProfile || process.argv.includes("--text-undo"); +const nativeCLI = fullProfile || process.argv.includes("--native-cli"); +const embedRecovery = fullProfile || process.argv.includes("--embed-recovery"); +const groupedLinkClick = fullProfile || process.argv.includes("--grouped-link-click"); +const latexInput = fullProfile || process.argv.includes("--latex-input"); const latexPreview = process.argv.includes("--latex-preview"); -const imageGeometryReal = process.argv.includes("--image-geometry-real"); +const imageGeometryReal = fullProfile || process.argv.includes("--image-geometry-real"); const imageGeometry = process.argv.includes("--image-geometry") || imageGeometryReal; -const wheelZoom = process.argv.includes("--wheel-zoom"); +const wheelZoom = fullProfile || process.argv.includes("--wheel-zoom"); const webDrop = process.argv.includes("--web-drop"); const internalDrop = process.argv.includes("--internal-drop"); const youtubeDrop = process.argv.includes("--youtube-drop"); const svgImport = process.argv.includes("--svg-import"); -const lucide = process.argv.includes("--lucide"); -const workflowFixes = process.argv.includes("--workflow-fixes"); -const dataIntegrity = process.argv.includes("--data-integrity"); -if (process.argv.slice(2).some(arg => !["--data-integrity", "--workflow-fixes", "--plugin-only", "--lucide", "--text-undo", "--native-cli", "--embed-recovery", "--grouped-link-click", "--latex-input", "--latex-preview", "--image-geometry", "--image-geometry-real", "--wheel-zoom", "--web-drop", "--internal-drop", "--youtube-drop", "--svg-import"].includes(arg))) { +const lucide = fullProfile || process.argv.includes("--lucide"); +const workflowFixes = fullProfile || process.argv.includes("--workflow-fixes"); +const dataIntegrity = fullProfile || process.argv.includes("--data-integrity"); +if (process.argv.slice(2).some(arg => arg !== profileArg && !["--lifecycle", "--extras-services", "--devices", "--data-integrity", "--workflow-fixes", "--plugin-only", "--lucide", "--text-undo", "--native-cli", "--embed-recovery", "--grouped-link-click", "--latex-input", "--latex-preview", "--image-geometry", "--image-geometry-real", "--wheel-zoom", "--web-drop", "--internal-drop", "--youtube-drop", "--svg-import"].includes(arg))) { throw new Error("Supported options: --data-integrity, --workflow-fixes, --plugin-only, --lucide, --text-undo, --native-cli, --embed-recovery, --grouped-link-click, --latex-input, --latex-preview, --image-geometry, --image-geometry-real, --wheel-zoom, --web-drop, --internal-drop, --youtube-drop, --svg-import"); } +if(profile && pluginOnly)throw Error("A frozen workspace profile cannot use --plugin-only"); +const extrasRoot=resolve(process.env.EXCALIDRAW_EXTRAS_ROOT||join(pluginRoot,"../obsidian-excalidraw-extras")); const forkRoot = resolve(process.env.EXCALIDRAW_FORK_ROOT || join(pluginRoot, "../excalidraw")); const reportDir = process.env.EXCALIDRAW_TEST_REPORT_DIR || mkdtempSync(join(tmpdir(), "excalidraw-obsidian-")); const FORK_ARTIFACTS = ["excalidraw.production.min.js", "excalidraw.production.min.css", @@ -65,7 +85,7 @@ const source = { forkRevision: git(forkRoot, ["rev-parse", "HEAD"]), forkDirty: Boolean(git(forkRoot, ["status", "--porcelain"])), }), - buildMode: pluginOnly ? "installed-package" : "local-fork", + buildMode: profile ? "workspace-frozen" : pluginOnly ? "installed-package" : "local-fork", node: process.version, platform: process.platform, }; @@ -76,7 +96,7 @@ const userDataPath = process.env.EXCALIDRAW_TEST_USER_DATA_PATH || (process.plat : process.platform === "darwin" ? join(homedir(), "Library/Application Support/obsidian") : join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "obsidian")); const hostLock = acquireHostLock({ userDataPath }); -let report; +let report, combination; try { report = await runObsidianSmoke({ projectRoot: pluginRoot, @@ -86,7 +106,11 @@ report = await runObsidianSmoke({ automationRoot: process.env.EXCALIDRAW_TEST_AUTOMATION_ROOT, reportDir, source, + ownedDebugger:true, + deployCompanions:profile?context=>stageExtras({combination,...context}):undefined, scenarios: [ + ...(lifecycle ? [runLifecycleScenario] : []), + ...(extrasServices ? [runExtrasServicesScenario] : []), ...(dataIntegrity ? [runDataIntegrityScenario] : []), ...(workflowFixes ? [runWorkflowFixesScenario] : []), ...(lucide ? [runLucideScenario] : []), @@ -102,10 +126,17 @@ report = await runObsidianSmoke({ ...(groupedLinkClick ? [runGroupedLinkClickScenario] : []), ...(latexInput ? [runLatexInputScenario] : []), ...(latexPreview ? [context => runLatexInputScenario({ ...context, realRenderer: true })] : []), + ...(fullProfile ? [runAutomateScenario] : []), + ...(fullProfile ? [runCoreInteractionScenario] : []), + ...(fullProfile || profile==='soak' ? [context=>runStabilityScenario({...context,cycles:profile==='soak'?25:6})] : []), ], runCli: (vault, commandName, ...args) => command(obsidianCliExecutable(), [`vault=${vault}`, commandName, ...args], pluginRoot), runBuild: () => { + if(profile){ + combination=produceCombination({pluginRoot,forkRoot,extrasRoot,output:join(pluginRoot,'.test-work/frozen/combination-'+randomUUID())}); + return {pluginArtifactRoot:join(combination.output,'plugin'),forkArtifacts:Object.fromEntries(combination.manifests.fork.artifacts.filter(entry=>['production-js','production-css','development-js','development-css'].includes(entry.role)).map(entry=>[entry.role,entry.sha256])),combination}; + } if (Number(process.versions.node.split(".")[0]) < 22) throw new Error("Node.js 22 or newer is required"); const sourceDir = join(forkRoot, "packages/excalidraw/dist/obsidian"); const installedDir = join(pluginRoot, "node_modules/@zsviczian/excalidraw/dist/obsidian"); @@ -147,6 +178,12 @@ report = await runObsidianSmoke({ return hashes; }, }); + if(devices && report.status==='passed'){ + const cli=(name,...args)=>command(obsidianCliExecutable(),[`vault=${process.env.EXCALIDRAW_TEST_VAULT_NAME}`,name,...args],pluginRoot); + const deviceReport=await runDeviceMatrix({cli,reportDir:join(reportDir,'devices'),vaultName:process.env.EXCALIDRAW_TEST_VAULT_NAME,vaultPath:process.env.EXCALIDRAW_TEST_VAULT_PATH,configDir:process.env.EXCALIDRAW_TEST_CONFIG_DIR,automationRoot:process.env.EXCALIDRAW_TEST_AUTOMATION_ROOT,profiles:[...deviceProfiles(),...breakpointProfiles()]}); + const aggregate=aggregateReports([adaptSmokeReport(report),deviceReport],[]);aggregate.source=source;aggregate.combination=combination; + writeFileSync(join(reportDir,'aggregate.json'),JSON.stringify(aggregate,null,2)+'\n');writeReportFiles(aggregate,reportDir);if(aggregate.status!=='passed')report.status='failed'; + } } finally { hostLock.release(); } diff --git a/scripts/testing/host/wheelZoom.mjs b/scripts/testing/host/wheelZoom.mjs index 31caee6e..0e75094d 100644 --- a/scripts/testing/host/wheelZoom.mjs +++ b/scripts/testing/host/wheelZoom.mjs @@ -1,5 +1,6 @@ /** #3008: real wheel events must use live plugin zoom limits in each document. */ import assert from "node:assert/strict"; +import { runLegacyTask } from './legacyTask.mjs'; async function exercise(control, drawingPath) { const c = globalThis[control]; @@ -57,17 +58,8 @@ async function exercise(control, drawingPath) { /** Restores the live settings without persisting test values. */ export async function runWheelZoomScenario({ cli, drawingPath }) { + assert.ok(drawingPath.startsWith('__excalidraw_cli_smoke_')); const control = "__excalidrawWheelZoom"; - const evaluate = code => JSON.parse(cli("eval", `code=${code}`).trim().replace(/^=>\s*/, "")); - try { - evaluate(`(()=>{if(globalThis.${control})throw Error("wheel controller exists");const c=globalThis.${control}={state:"pending"};(${exercise.toString()})(${JSON.stringify(control)},${JSON.stringify(drawingPath)}).then(()=>c.state="done").catch(e=>{c.state="failed";c.error=e.stack});return JSON.stringify({started:true})})()`); - let result; - for (let i = 0; i < 200; i++) { - result = evaluate(`JSON.stringify({state:globalThis.${control}.state,error:globalThis.${control}.error,results:globalThis.${control}.results})`); - if (result.state !== "pending") break; - await new Promise(resolve => setTimeout(resolve, 100)); - } - assert.equal(result.state, "done", result.error ?? "wheel scenario timed out"); - return { id: "wheel-zoom-3008", status: "passed", cases: result.results }; - } finally { cli("eval", `code=delete globalThis.${control}`); } + const result=await runLegacyTask({cli,control,execute:exercise,args:[drawingPath]}); + return { id: "wheel-zoom-3008", status: "passed", cases: result.results }; } diff --git a/scripts/testing/host/workflowFixes.mjs b/scripts/testing/host/workflowFixes.mjs index 71e7caff..95ba791b 100644 --- a/scripts/testing/host/workflowFixes.mjs +++ b/scripts/testing/host/workflowFixes.mjs @@ -1,36 +1,39 @@ /** Native #3020 checks, confined to the guarded parent's UUID-owned fixtures. */ import assert from 'node:assert/strict'; import {join} from 'node:path'; +import {runInAppTask} from './inAppTask.mjs'; export async function runWorkflowFixesScenario({cli,drawingPath,reportDir}) { const prefix=drawingPath.replace(/\.excalidraw\.md$/,'')+'_workflows'; assert.ok(prefix.startsWith('__excalidraw_cli_smoke_')); - const baseline=process.env.EXCALIDRAW_WORKFLOW_BASELINE==='1',key='__workflow3020'; - const evaluate=code=>JSON.parse(cli('eval','code='+code).trim().replace(/^=>\s*/,'')); - evaluate(`(()=>{if(globalThis.${key})throw Error('Workflow probe active');globalThis.${key}={state:'pending'};(${probeWorkflows.toString()})(${JSON.stringify(key)},${JSON.stringify(prefix)},${JSON.stringify(drawingPath)},${baseline}).then(result=>Object.assign(globalThis.${key},{state:'done',result})).catch(error=>Object.assign(globalThis.${key},{state:'failed',error:String(error.stack)}));return JSON.stringify({started:true})})()`); - let state; - for(let i=0;i<1400;i++) { - state=evaluate(`JSON.stringify(globalThis.${key})`); - if(state.capture){cli('dev:screenshot','path='+join(reportDir,(baseline?'before-':'after-')+state.capture+'.png'));evaluate(`(()=>{delete globalThis.${key}.capture;return JSON.stringify({ok:true})})()`);} - if(state.state!=='pending')break; - await new Promise(resolve=>setTimeout(resolve,100)); - } - evaluate(`(()=>{delete globalThis.${key};return JSON.stringify({clean:true})})()`); - assert.equal(state.state,'done',(state.error??'Workflow timeout')+' '+JSON.stringify(state.observations??{})); - return {id:'workflow-fixes-3020',status:'passed',baseline,...state.result}; + const baseline=process.env.EXCALIDRAW_WORKFLOW_BASELINE==='1'; + const result=await runInAppTask({cli,execute:probeWorkflows,args:[prefix,drawingPath,baseline],timeoutMs:180000,cleanupMs:60000,onRequest:request=>{ + if(request.method!=='screenshot'||!/^[a-zA-Z0-9-]+$/.test(request.params.name))throw Error('Unexpected workflow screenshot request'); + cli('dev:screenshot','path='+join(reportDir,(baseline?'before-':'after-')+request.params.name+'.png'));return {captured:true}; + }}); + return {id:'workflow-fixes-3020',status:'passed',baseline,...result}; } -async function probeWorkflows(key,prefix,drawingPath,baseline) { - const c=globalThis[key],p=app.plugins.plugins['obsidian-excalidraw-plugin']; +async function probeWorkflows(c,prefix,drawingPath,baseline) { + const p=app.plugins.plugins['obsidian-excalidraw-plugin']; const originalLayout=app.workspace.getLayout(),leaves=[],doc=app.workspace.containerEl.ownerDocument; const settings=Object.fromEntries(['templateFilePath','previewImageType','canvasImmersiveEmbed','folder','embedUseExcalidrawFolder','compatibilityMode'].map(key=>[key,p.settings[key]])); const check=(condition,message)=>{if(!condition)throw Error(message);}; - const wait=async(predicate,message)=>{const end=Date.now()+25000;while(!predicate()){if(Date.now()>end)throw Error('Workflow timeout: '+message);await new Promise(r=>setTimeout(r,40));}}; + const ownedPrompts=new Set(); + const wait=async(predicate,message)=>{await c.waitFor(predicate,message,25000);if(message.includes('chooser')){const prompt=doc.querySelector('.prompt');if(prompt)ownedPrompts.add(prompt);}}; const settle=()=>new Promise(r=>setTimeout(r,250)); - const capture=async name=>{c.capture=name;await wait(()=>!c.capture,'screenshot '+name);}; + const capture=name=>c.requestHost('screenshot',{name}); const rect=el=>{const r=el.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height};}; + check(!doc.querySelector('.prompt'),'Close existing prompts before the workflow scenario'); let fullscreenView; - try { + c.defer(async()=>{const folder=app.vault.getFolderByPath(prefix);if(folder){check(folder.path===prefix&&prefix.startsWith('__excalidraw_cli_smoke_'),'unowned cleanup');await app.vault.delete(folder,true);}}); + c.defer(()=>Object.assign(p.settings,settings)); + c.defer(async()=>{await app.workspace.changeLayout(originalLayout);await c.waitForCleanup(()=>app.workspace.getLeavesOfType('excalidraw').some(l=>l.view.file?.path===drawingPath&&l.view.isLoaded&&l.view.excalidrawAPI&&!l.view.semaphores.justLoaded),'restored parent drawing first commit');}); + c.defer(async()=>{const errors=[];for(const leaf of leaves){try{if(leaf.view.containerEl.isConnected){await leaf.setViewState({type:'empty',state:{}});leaf.detach();}}catch(error){errors.push(error);}}if(errors.length)throw new AggregateError(errors,'Workflow leaf cleanup failed');}); + c.defer(()=>fullscreenView?.exitFullscreen()); + c.defer(async()=>{for(const prompt of ownedPrompts){if(prompt.isConnected){doc.dispatchEvent(new doc.defaultView.KeyboardEvent('keydown',{key:'Escape',code:'Escape',bubbles:true,cancelable:true}));await c.waitForCleanup(()=>!prompt.isConnected,'owned chooser cancellation');}}}); + + await app.vault.createFolder(prefix); const note=await app.vault.create(prefix+'/Note.md','Workflow fixture.'),draw=app.vault.getFileByPath(drawingPath); const uid=()=>crypto.randomUUID().replace(/-/g,'').slice(0,16),drawingId=uid(); @@ -134,9 +137,10 @@ async function probeWorkflows(key,prefix,drawingPath,baseline) { await wait(()=>app.workspace.getLeavesOfType('excalidraw').some(l=>l.view.file?.path===path&&l.view.isLoaded&&l.view.excalidrawAPI&&!l.view.isClosingOrMigrating()&&!l.view.semaphores.justLoaded),'new drawing first commit'); }; const choose=async (operation,choice)=>{ - let done=false,result,failure; + let done=false,result,failure,prompt; + c.defer(async()=>{if(!done){if(prompt?.isConnected)doc.dispatchEvent(new doc.defaultView.KeyboardEvent('keydown',{key:'Escape',code:'Escape',bubbles:true,cancelable:true}));await c.waitForCleanup(()=>done,'pending owned drawing creation');}}); Promise.resolve(operation()).then(value=>{done=true;result=value;}).catch(error=>{done=true;failure=String(error);}); - await wait(()=>doc.querySelector('.prompt'),'chooser '+choice); + await wait(()=>doc.querySelector('.prompt'),'chooser '+choice);prompt=doc.querySelector('.prompt'); const input=doc.querySelector('.prompt input'),items=()=>[...doc.querySelectorAll('.prompt .suggestion-item')]; if(choice==='blank') { check(items()[0].textContent===p.getLabel('PROMPT_BLANK_DRAWING'),'blank is not first'); @@ -194,12 +198,5 @@ async function probeWorkflows(key,prefix,drawingPath,baseline) { Object.assign(extra,{blank:true,filteredDuplicateSelection:true,outsideDismissal:true,embedCancelNoChanges:true,conversionCancelNoChanges:true,fileExplorerCancelNoChanges:true,singleTemplateAutomatic:true,zeroTemplateAutomatic:true,legacy:true,explicitDataNoPrompt:true}); } return {fullscreen:{original,fullscreen,restored,hiddenAncestors,variants:fullscreenVariants},canvas:canvasResults,templates:{labels,created,folderCreated,output:output??null,error:error??null,...extra}}; - } finally { - fullscreenView?.exitFullscreen();Object.assign(p.settings,settings); - for(const leaf of leaves){await leaf.setViewState({type:'empty',state:{}});leaf.detach();} - await app.workspace.changeLayout(originalLayout); - await wait(()=>app.workspace.getLeavesOfType('excalidraw').some(l=>l.view.file?.path===drawingPath&&l.view.isLoaded&&l.view.excalidrawAPI&&!l.view.semaphores.justLoaded),'restored parent drawing first commit'); - const folder=app.vault.getFolderByPath(prefix); - if(folder){check(folder.path===prefix&&prefix.startsWith('__excalidraw_cli_smoke_'),'unowned cleanup');await app.vault.delete(folder,true);} - } + } diff --git a/scripts/testing/produceArtifacts.mjs b/scripts/testing/produceArtifacts.mjs index 28ee09e7..ce126459 100644 --- a/scripts/testing/produceArtifacts.mjs +++ b/scripts/testing/produceArtifacts.mjs @@ -1,7 +1,7 @@ /** Build a producer, fingerprint source before/after, then freeze verified outputs. */ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { existsSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { createArtifactManifest, freezeArtifacts, sourceIdentity, walkFiles } from "./contracts.mjs"; @@ -28,7 +28,7 @@ export function produceArtifacts({ root, kind, snapshotRoot, run = runBuild }) { assert.ok(["plugin", "fork", "extras"].includes(kind), "Unknown producer kind"); assert.ok(!existsSync(snapshotRoot), "Snapshot already exists"); const before = sourceIdentity(root); - const steps = kind === "fork" ? [{ manager: "yarn", args: ["build:obsidian"], cwd: join(root, "packages/excalidraw") }] + const steps = kind === "fork" ? ["build:esm", "build:obsidian"].map(script => ({ manager: "yarn", args: [script], cwd: join(root, "packages/excalidraw") })) : [{ manager: "npm", args: ["run", "build"], cwd: root }, ...(kind === "extras" ? [{ manager: "npm", args: ["run", "build:api"], cwd: root }] : [])]; for (const step of steps) run(step); assert.deepEqual(sourceIdentity(root), before, "Producer source changed while building; discard output and rebuild"); diff --git a/scripts/testing/reportFiles.mjs b/scripts/testing/reportFiles.mjs index b81d8334..511472cf 100644 --- a/scripts/testing/reportFiles.mjs +++ b/scripts/testing/reportFiles.mjs @@ -3,8 +3,9 @@ import { writeFileSync } from "node:fs"; import { join } from "node:path"; const xml = value => String(value).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "").replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'"); export function renderJUnit(report) { - const unsuccessful = report.tests.filter(test => test.status !== "passed"); - const cases = report.tests.map(test => `${test.status === "passed" ? "" : `${xml(test.reason || test.status)}`}`); + const optionalNA=test=>test.status==='notApplicable'&&!(report.requiredTestIds||[]).includes(test.testId); + const unsuccessful = report.tests.filter(test => test.status !== "passed"&&!optionalNA(test)); + const cases = report.tests.map(test => `${test.status === "passed" ? "" : optionalNA(test)?``:`${xml(test.reason || test.status)}`}`); // A required blocked case is deliberately a failure, never a skipped green job. if (report.status !== "passed" && !unsuccessful.length) cases.push(`${xml(report.error || report.cleanupError || "Suite, discovery or cleanup gate failed")}`); return `\n${cases.join("\n")}\n`; diff --git a/scripts/testing/reportFiles.test.mjs b/scripts/testing/reportFiles.test.mjs index 7b266e1e..59bf8e86 100644 --- a/scripts/testing/reportFiles.test.mjs +++ b/scripts/testing/reportFiles.test.mjs @@ -7,6 +7,9 @@ test("JUnit escapes evidence and represents blocked or cleanup-only failures as const xml = renderJUnit(report); assert.ok(xml.includes('failures="1"')); assert.ok(xml.includes("<host> & "permission"")); assert.ok(!xml.includes(" { const baseline = [{ path: "src/critical.ts", lines: 90, branches: 80, functions: 75 }]; diff --git a/scripts/testing/sourceHarness.mjs b/scripts/testing/sourceHarness.mjs index 18566d4b..8c13c670 100644 --- a/scripts/testing/sourceHarness.mjs +++ b/scripts/testing/sourceHarness.mjs @@ -1,13 +1,14 @@ /** Test-only ESM compilation graph: import whole production modules with explicit boundary substitutes. */ import { randomUUID } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { registerHooks } from "node:module"; +import * as nodeModule from "node:module"; import { dirname, relative, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import ts from "typescript"; const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); export function sourceHarness(mocks = {}) { + if (typeof nodeModule.registerHooks !== "function") throw Error("Whole-module source tests require Node 22.15+; use the documented Node 22.22.3 toolchain"); const token = "__sourceHarness_" + randomUUID().replaceAll("-", ""), query = `?${token}`; const compiledRoot = resolve(root, ".test-work/source-graphs", token), sourcePaths = new Map(); const moduleURL = path => { @@ -16,7 +17,7 @@ export function sourceHarness(mocks = {}) { sourcePaths.set(url, path); return url; }; globalThis[token] = mocks; - const hooks = registerHooks({ + const hooks = nodeModule.registerHooks({ resolve(specifier, context, next) { if (sourcePaths.has(specifier)) return { shortCircuit: true, url: specifier }; if (Object.hasOwn(mocks, specifier)) { diff --git a/tests/features.json b/tests/features.json new file mode 100644 index 00000000..340575b9 --- /dev/null +++ b/tests/features.json @@ -0,0 +1,584 @@ +{ + "schemaVersion": 2, + "inventory": "tests/inventory.json", + "policy": "Obligations and source/test mapping only. Execution, inherited failures and platform limits are reported independently; mapping a group does not cover every public entry. Specific maintained scripts are outside this PR scope per maintainer direction; they are tested in ea-scripts.", + "features": [ + { + "id": "P01", + "priority": "P0", + "name": "Packaging and lifecycle", + "anchors": [ + { + "path": "src/core/managers/PackageManager.ts", + "symbol": "export class PackageManager" + } + ], + "tests": [ + { + "layer": "source", + "path": "scripts/testing/package.source.test.mjs", + "cases": [ + "node:scripts/testing/package.source.test.mjs::one private runtime serves main and two popout leases; only final release removes the alias", + "node:scripts/testing/package.source.test.mjs::destroy clears owned aliases and registrations without clobbering a replacement alias" + ] + }, + { + "layer": "artifact", + "path": "scripts/testing/bundle.test.mjs", + "cases": [ + "node:scripts/testing/bundle.test.mjs::production bootstrap supplies matching private React and JSX runtimes", + "node:scripts/testing/bundle.test.mjs::compressed Excalidraw retains every published offline font asset" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/lifecycle.mjs", + "cases": [ + "native:lifecycle-plugin-reload" + ] + } + ], + "fixtures": [], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Exact private runtime and protocol load; runtime identity and commands are ready", + "failure": "Reject absent/incompatible adapters; roll back partial registration", + "cleanup": "Dispose owned adapters, aliases and leases", + "remaining": [ + "Isolated native cold restart and restored-popout session require a prepared isolated application" + ] + }, + { + "id": "P02", + "priority": "P0", + "name": "Drawing durability", + "anchors": [ + { + "path": "src/view/managers/ViewSaveCoordinator.ts", + "symbol": "export class ViewSaveCoordinator" + } + ], + "tests": [ + { + "layer": "source", + "path": "scripts/testing/persistence.source.test.mjs", + "cases": [ + "node:scripts/testing/persistence.source.test.mjs::same-path snapshots remain ordered and uncoalesced while another drawing proceeds independently", + "node:scripts/testing/persistence.source.test.mjs::failed writes preserve the failure receipt, never schedule a backup and release the path for retry" + ] + }, + { + "layer": "source", + "path": "scripts/testing/saveCoordinator.source.test.mjs", + "cases": [ + "node:scripts/testing/saveCoordinator.source.test.mjs::failed saves keep dirty state and successful retry acknowledges only captured bytes", + "node:scripts/testing/saveCoordinator.source.test.mjs::an edit during a save queues its own later snapshot instead of clearing the newer dirty revision" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/dataIntegrity.mjs", + "cases": [ + "native:data-write-failure", + "native:data-rename-delete", + "native:data-backup" + ] + } + ], + "fixtures": [ + "Drawings/Uncompressed.excalidraw.md", + "Drawings/Compressed.excalidraw.md", + "Drawings/Legacy.excalidraw" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Save/reopen preserves prose, scene metadata and physical receipts", + "failure": "Failed writes retain dirty edits; stale API and own-write echoes cannot overwrite", + "cleanup": "Close owned views and delete exact owned files and backup keys", + "remaining": [] + }, + { + "id": "P03", + "priority": "P0", + "name": "Multiwindow and async work", + "anchors": [ + { + "path": "src/view/ExcalidrawView.ts", + "symbol": "onWindowMigrated" + } + ], + "tests": [ + { + "layer": "source", + "path": "scripts/testing/sceneFiles.source.test.mjs", + "cases": [ + "node:scripts/testing/sceneFiles.source.test.mjs::late file callbacks reject replacement API for the same path and release PDF resources", + "node:scripts/testing/sceneFiles.source.test.mjs::late file callbacks reject another file and release PDF resources" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/lifecycle.mjs", + "cases": [ + "native:lifecycle-dirty-main-to-popout", + "native:lifecycle-dirty-popout-to-main", + "native:lifecycle-new-popout-survivor" + ] + } + ], + "fixtures": [ + "Drawings/Uncompressed.excalidraw.md" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Dirty migrations persist through replacement views; survivor remains usable", + "failure": "Refuse stale loaders and cancellation completion; unmount before async persistence", + "cleanup": "Await actual owned popout closure and settle all test tasks", + "remaining": [ + "Current Electron 43.3.0 emits illegal-access teardown exceptions; confirm on a fixed Electron host without filtering" + ] + }, + { + "id": "P04", + "priority": "P0", + "name": "Text, links and history", + "anchors": [ + { + "path": "src/view/ExcalidrawView.ts", + "symbol": "ExcalidrawView" + } + ], + "tests": [ + { + "layer": "native", + "path": "scripts/testing/host/textUndo.mjs", + "cases": [ + "text-undo-2976" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/groupedLinkClick.mjs", + "cases": [ + "grouped-link-click" + ] + } + ], + "fixtures": [ + "Links/Árvíztűrő 测试.md" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Parsed/raw and keyboard/button variants retain edit/history behavior", + "failure": "Unchanged edit preserves redo; stale targets and rejected edits do not mutate", + "cleanup": "Close owned editors and restore focus", + "remaining": [ + "Trusted OS clipboard/paste formats and navigation need independent native coverage" + ] + }, + { + "id": "P05", + "priority": "P0", + "name": "Images and embedded content", + "anchors": [ + { + "path": "src/utils/ExcalidrawExtrasGateway.ts", + "symbol": "export class ExcalidrawExtrasGateway" + } + ], + "tests": [ + { + "layer": "native", + "path": "scripts/testing/host/imageGeometry.mjs", + "cases": [ + "image-geometry-real-3014" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/embedRecovery.mjs", + "cases": [ + "markdown-embed-recovery-2953" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/extrasServices.mjs", + "cases": [ + "native:extras-pdf-output" + ] + } + ], + "fixtures": [ + "Assets/Transparency.png", + "Assets/Small.pdf", + "Notes/Embeds.md" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Decoded output, crop geometry, shared files and embed recovery are correct", + "failure": "Stale/cancelled loaders cannot publish into a replacement context", + "cleanup": "Dispose image/PDF resources and remove exact owned assets", + "remaining": [ + "PDF import and URL-image network failure require additional portable native cases" + ] + }, + { + "id": "P06", + "priority": "P0", + "name": "Settings and recovery", + "anchors": [ + { + "path": "src/core/settingsDefaults.ts", + "symbol": "DEFAULT_SETTINGS" + } + ], + "tests": [ + { + "layer": "source", + "path": "scripts/testing/settings/settings.source.test.mjs", + "cases": [ + "node:scripts/testing/settings/settings.source.test.mjs::missing first-install settings are distinct from corruption and synchronized records", + "node:scripts/testing/settings/settings.source.test.mjs::settings queue coalesces writes, waits for in-flight revisions and applies actions after success" + ] + }, + { + "layer": "source", + "path": "scripts/testing/settings/settingsWriter.test.mjs", + "cases": [ + "node:scripts/testing/settings/settingsWriter.test.mjs::key order does not change canonical serialization", + "node:scripts/testing/settings/settingsWriter.test.mjs::array order is semantically significant and preserved" + ] + } + ], + "fixtures": [ + ".obsidian/app.json" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Defaults, unknown keys and serialized revisions remain intact", + "failure": "Missing first install differs from corruption; queue failure remains recoverable", + "cleanup": "Restore changed preferences and await writes", + "remaining": [ + "Native corrupt-settings recovery and legacy/new settings UI require an isolated owned session" + ] + }, + { + "id": "P07", + "priority": "P1", + "name": "Authoring and interaction", + "anchors": [ + { + "path": "src/shared/ExcalidrawAutomate.ts", + "symbol": "export class ExcalidrawAutomate" + } + ], + "tests": [ + { + "layer": "native", + "path": "scripts/testing/host/nativeCLI.mjs", + "cases": [ + "native-cli-authoring" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/wheelZoom.mjs", + "cases": [ + "wheel-zoom-3008" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/automate.mjs", + "cases": [ + "native:ea-shapes-bindings-and-isolation", + "native:ea-edit-image-and-decoded-export", + "native:ea-svg-import-and-disposal" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/coreInteraction.mjs", + "cases": [ + "native:core-toolbar-draw-history", + "native:core-custom-highlighter", + "native:core-laser-transient" + ] + } + ], + "fixtures": [], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Frames, bindings, groups and authoring survive disk/export round trips", + "failure": "Invalid relationships and stale revisions cannot partially mutate", + "cleanup": "Restore focus and retire all owned editor roots", + "remaining": [ + "Layer ordering and drag selection have native cases pending; physical pressure/stylus is a separate device gate" + ] + }, + { + "id": "P08", + "priority": "P1", + "name": "Layouts, navigation and devices", + "anchors": [ + { + "path": "src/view/sidepanel/Sidepanel.ts", + "symbol": "export class ExcalidrawSidepanelView" + } + ], + "tests": [ + { + "layer": "native", + "path": "scripts/testing/host/workflowFixes.mjs", + "cases": [ + "workflow-fixes-3020" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/devices.mjs", + "cases": [ + "native:device:desktop-wide-full-light" + ] + } + ], + "fixtures": [], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Measured layout, reachable controls, trusted input and fullscreen restoration", + "failure": "Cancel pickers without creating files; fail clipped or missing controls", + "cleanup": "Restore theme, mobile mode, preferences, geometry and workspace", + "remaining": [ + "Physical keyboard/stylus/safe-area behavior remains a physical-device release gate" + ] + }, + { + "id": "P09", + "priority": "P1", + "name": "Import, export and libraries", + "anchors": [ + { + "path": "src/shared/svgToExcalidraw/walker.ts", + "symbol": "walk" + } + ], + "tests": [ + { + "layer": "source", + "path": "scripts/testing/svg.source.test.mjs", + "cases": [ + "node:scripts/testing/svg.source.test.mjs::whole-module SVG conversion preserves opacity, transforms and open strokes", + "node:scripts/testing/svg.source.test.mjs::whole-module SVG fixture imports without mutating source bytes" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/lucideIcons.mjs", + "cases": [ + "lucide-3019" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/extrasServices.mjs", + "cases": [ + "native:extras-mermaid-gateway", + "native:extras-pdf-output" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/automate.mjs", + "cases": [ + "native:ea-shapes-bindings-and-isolation", + "native:ea-edit-image-and-decoded-export", + "native:ea-svg-import-and-disposal" + ] + } + ], + "fixtures": [ + "Assets/Layers.svg", + "Sources/Diagrams.json" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Layer/opacity conversion, editable diagrams and actual decoded export output", + "failure": "Invalid assets and unavailable services fail without hidden fallback", + "cleanup": "Remove temporary render DOM, print listeners and owned output", + "remaining": [ + "Portable native SVG drop/library import and OS clipboard import need additional cases; public EA SVG import is exercised" + ] + }, + { + "id": "P10", + "priority": "P1", + "name": "ExcalidrawAutomate, CLI and core scripting boundary", + "anchors": [ + { + "path": "src/shared/Scripts.ts", + "symbol": "export class ScriptEngine" + } + ], + "tests": [ + { + "layer": "source", + "path": "scripts/testing/cli.test.mjs", + "cases": [ + "node:scripts/testing/cli.test.mjs::registration validates minimum API, optional method and desktop without bumping the baseline", + "node:scripts/testing/cli.test.mjs::icon discovery is read-only, bounded and snapshot-paginated" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/nativeCLI.mjs", + "cases": [ + "native-cli-authoring" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/automate.mjs", + "cases": [ + "native:ea-shapes-bindings-and-isolation", + "native:ea-edit-image-and-decoded-export", + "native:ea-svg-import-and-disposal" + ] + } + ], + "fixtures": [], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Direct EA authoring, grouping, binding, image and export APIs; idempotent CLI and typed discovery work", + "failure": "Interaction refusal, invalid relationships, BUSY and stale revisions retain scene", + "cleanup": "Destroy the owned EA instance and settle its resources before deleting the owned scene", + "remaining": [] + }, + { + "id": "P11", + "priority": "P1", + "name": "Offline and failure boundaries", + "anchors": [ + { + "path": "src/utils/ExcalidrawExtrasGateway.ts", + "symbol": "getMathJax" + } + ], + "tests": [ + { + "layer": "artifact", + "path": "scripts/testing/bundle.test.mjs", + "cases": [ + "node:scripts/testing/bundle.test.mjs::production bootstrap supplies matching private React and JSX runtimes", + "node:scripts/testing/bundle.test.mjs::compressed Excalidraw retains every published offline font asset" + ] + }, + { + "layer": "source", + "path": "scripts/testing/package.source.test.mjs", + "cases": [ + "node:scripts/testing/package.source.test.mjs::one private runtime serves main and two popout leases; only final release removes the alias", + "node:scripts/testing/package.source.test.mjs::destroy clears owned aliases and registrations without clobbering a replacement alias" + ] + }, + { + "layer": "native", + "path": "scripts/testing/host/extrasServices.mjs", + "cases": [ + "native:extras-mathjax-gateway" + ] + } + ], + "fixtures": [ + "Sources/Equations.json", + "Invalid/Corrupt.excalidraw.md" + ], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Required payload/font bytes are embedded and services resolve through the gateway", + "failure": "Invalid protocol, failed activation and malformed input fail closed", + "cleanup": "Own and remove debugger/listeners; unrelated errors always fail", + "remaining": [ + "Native real unhandled-error negative control is separate from ordinary clean-error acceptance" + ] + }, + { + "id": "P12", + "priority": "P1", + "name": "Long-lived stability", + "anchors": [ + { + "path": "src/view/ExcalidrawView.ts", + "symbol": "ExcalidrawView" + } + ], + "tests": [ + { + "layer": "native", + "path": "scripts/testing/host/stability.mjs", + "cases": [ + "native:stability-roundtrip:0", + "native:stability-roundtrip:5" + ] + } + ], + "fixtures": [], + "platforms": [ + "Windows desktop", + "desktop mobile emulation", + "macOS/Linux follow-up", + "physical Android/iOS follow-up" + ], + "success": "Bounded 1000-element save/reopen and decoded export; roots/APIs retire each cycle", + "failure": "Timeout or failed save fails the run without deleting unsettled resources", + "cleanup": "Return root count to baseline; delete exact owned scene", + "remaining": [ + "25-cycle soak and repeated reload need the final profile run; forced-GC heap and physical-device performance are not inferred" + ] + } + ] +} diff --git a/tests/inventory.json b/tests/inventory.json index 418e3806..86368479 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -2295,14 +2295,26 @@ "path": "scripts/testing/extrasMermaid.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/features.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/fullscreen.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/host/combination.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/host/debuggerSession.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/host/deviceProfiles.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/host/hostReadiness.test.mjs", "mode": "direct-module-or-tooling" @@ -2311,14 +2323,26 @@ "path": "scripts/testing/host/inAppTask.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/host/legacyTask.test.mjs", + "mode": "isolated-or-extracted" + }, { "path": "scripts/testing/host/processTools.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/host/requireIsolatedSession.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/host/runner.test.mjs", "mode": "direct-module-or-tooling" }, + { + "path": "scripts/testing/host/stability.test.mjs", + "mode": "direct-module-or-tooling" + }, { "path": "scripts/testing/hostContracts.test.mjs", "mode": "isolated-or-extracted"