diff --git a/AGENTS.md b/AGENTS.md index 285f69ca..80bc59d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -519,6 +519,19 @@ If a task touches any of the above, read adjacent code first and validate more c Use the layered test commands and explicit acceptance limits documented below. Fast/source tests, built artifacts, native integration and physical devices establish different evidence. +### Required regression coverage and execution + +- Every behavior-changing feature, fix or refactor must add or extend executable tests for its intended behavior and the existing workflows it can affect. For a bug fix, preserve evidence that the regression fails before the fix and passes afterward. Assert observable outcomes; do not substitute registration, inventory, screenshots alone or an implementation-mirroring mock for behavioral evidence. +- Source tests under `scripts/testing/` and `tests/` named `*.test.mjs` are discovered by `test:fast`. Native helpers are not auto-discovered: wire new scenarios into the coordinator/profile and declared required-case/feature mappings. An unreferenced test file provides no executed coverage. +- During implementation, run the affected focused tests and required build after each independently testable checkpoint. Keep `tests/features.json` and `tests/inventory.json` current when coverage or discovery changes. Preserve existing assertions; report unexpected behavior instead of weakening tests or accepting new snapshots automatically. +- Settings/persistence changes need non-default configurations and unknown-key sentinels across actual plugin unload/reload and startup, with both on-disk data and loaded preferences asserted. Calling `loadSettings()` on an existing instance alone does not establish reload preservation. Include pending saves and externally changed data when those lifecycles are affected; preserve backup evidence if an unexpected replacement occurs. +- Before declaring a code PR ready, run `npm run test:regression:portable`. Also run the affected native scenarios for editor input/history, rendering/embeds, settings/persistence, window ownership/lifecycle, CLI/EA integration or real Extras services. Run the complete `npm run test:native` profile before readiness when those native workflows are affected. A focused pass is not a complete native pass. +- Run the complete portable and native profiles for coordinated release acceptance, after integrating upstream fork changes, and when validating a newly installed Obsidian version, including alphas. Record the actual host version; do not skip a case solely because the host is newer. Repeat complete matching-build runs when the acceptance plan requires them (including #3022); do not impose a new repeat count implicitly on unrelated changes. +- Portable CI runs on pull requests and pushes to `master`. Native CI is an explicitly dispatched, exact-commit workflow on the isolated desktop runner; local native testing is invoked through the documented commands. Neither suite runs inside the shipped plugin during ordinary use. Review the pinned companion revisions in workflows for coordinated changes: a pinned CI combination does not automatically test another repository's latest branch. +- Documentation-only or demonstrably mechanical changes do not require invented behavioral tests. Run their relevant documentation/inventory checks and state why runtime validation is unnecessary. Record the commands, results, source/artifact identities and genuine limitations for every code handoff. + +Use [the testing guide](docs/TESTING.md) for the full command matrix and [runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md) for targeted native flags and the prepared-vault contract. Native tests use the repository-local vault, never a personal vault. An explicitly requested personal-vault deployment is separate from test execution: back up existing artifacts/settings, verify preservation, and stop to recover/report any unexpected settings replacement. + ### Obsidian CLI runtime lane Start with the layered [testing guide](docs/TESTING.md) and [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md). Use `npm run test:native` to prepare and test `.test-work/vaults/excalidraw-auto-test/`. Every native sequence builds selected workspace revisions, freezes and hash-verifies the plugin and available Extras artifacts, installs and enables them, applies the immutable seed's settings, verifies the running CLI vault/config identity and restores the declared baseline. Use the matching local fork when available. Never reuse stale installed builds. Missing Extras is explicit and cannot satisfy Extras-dependent coverage. Serialize preparation, deployment, scenarios and cleanup under the shared application-user-data lock. Specific maintained scripts remain tested in ea-scripts; focus here on core Excalidraw and ExcalidrawAutomate. Inventory and screenshots do not establish behavior; missing important matrix cases remain unfinished. diff --git a/RefactorPlan.md b/RefactorPlan.md index 0d4373d4..3654db6f 100644 --- a/RefactorPlan.md +++ b/RefactorPlan.md @@ -1,11 +1,12 @@ # Incremental refactor assessment and plan -Testing follow-up, 2026-10-30: maintainer installed Obsidian 1.14.5; runtime -inspection confirms Electron 43.8.3. Current product branches remain unchanged. -Host versions remain evidence, never exact-version gates; the existing runner -success control now uses a future alpha label, and automatic runtime metadata -also records installer identity. Exclusive foreground access is confirmed for -focused blocker reruns and the two still-required complete native repeats. +Testing follow-up, 2026-10-30: two complete matching-build native repeats pass +357/357 each at the recorded acceptance checkpoint (F32). The subsequently +reported parsed-link undo truncation predates the testing PR. Its approved +plugin-only fix passes eight new full drawing-history sequences and all 16 +existing text-edit variants (F33). This focused follow-up is separate from the +earlier full-pair evidence. Host versions remain metadata, never exact-version +gates; the native runner also verifies a future alpha label. Status: the `ExcalidrawView`/`main.ts` plan is parked as of 2026-08-13 (see "Parked: next steps if resumed" near the end). The active refactor is the @@ -34,7 +35,8 @@ 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) | Acceptance blocked; PRs remain draft | At plugin 9cb6c5eb / fork 053a3b9 / Extras 1cdcb7c, 662 portable cases pass (64 new / 598 reused), with source/package gates. Proven text-mode and asynchronous image-editor test setup/cleanup defects are corrected. All 16 text variants and six large-scene cycles pass after full core predecessors. Latest full attempt has 345 required passes, 11 failures and one missing identity; no full repeat passes. Strict storms, intermittent migration exceptions and a host getZoomFactor teardown exception remain blockers. Raw payloads, capture limitations, hashes and recovery are public. Installer comparison requires approval; production unchanged. See docs/TESTING.md | +| Automated test coverage (#3022) | Acceptance complete at the frozen checkpoint; PRs ready for review | Plugin fd32ac68 / fork 053a3b9 / Extras 1cdcb7c pass two complete 357/357 native repeats and 666 portable cases, with matching artifacts, cleanup, baseline restoration and strict negative controls. Historical failures remain public; the original observer-storm cause remains unidentified. See F32 and the immutable acceptance report. The later approved link-history fix has separate focused evidence in F33. | +| Parsed-link drawing history | Implemented; focused source/native regression passes | Preserve earlier shape actions when submitting parsed links. Four new source cases cover plain/wiki/aliased/Markdown links; eight trusted-input sequences undo all seven drawing actions to empty and redo identity, geometry, source, links and bindings. Verify the optional selection-only editor step explicitly; retain all 16 previous text-edit variants. No fork or Extras production change. | | 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 | @@ -3391,3 +3393,41 @@ remain strict pending maintainer classification; no production changes. complete; highest remaining risk is intermittent observer recurrence, retained under the strict gate. Physical mobile, native macOS/Linux, real OS drag and isolated whole-app cold start remain separate validation environments. + +- 2026-10-30 (approved parsed-link history fix): Reproduced the maintainer's + shape/label/B sequence with real input: after undoing B and the text, five + rectangles remain with zero undo depth. Removed only the ordinary parsed-link + submission history reset; the fork already records raw/display/link values + together. Four source regressions and all eight new plus 16 existing native + text sequences pass, with strict errors, cleanup and baseline restoration. + Retained the initial failed expectation about the editor's selection-only + entry; explicitly verify that entry without skipping drawing edits. Updated + the feature map, reviewed the new test inventory entry and scoped the exact + production audit to this authorized patch. Touched production files introduce + no lint diagnostics. Risk checks: replay the maintainer's sequence in the main + window; separately exercise popout and physical mobile label editing. The + earlier complete 357-case pair remains evidence for its frozen checkpoint, + not for this later patch. Repeat portable/build checks before deployment. + +- 2026-10-30 (link-history verification follow-up): The normal standalone fork + browser suite exposed an independent setup error: pointer-clicking its already + active Selection tool deliberately switches to Lasso. Passive state capture + confirms the cause. Guard the redundant click in the fork-owned fixture; + retain every grouping/deletion/history assertion. All 18 browser cases pass. + The new history fix is deployed and ready; an unexpected deployment settings + rewrite was recovered from the exact pre-reload backup and remains unassigned. + No settings production fix, fork runtime change or printing change is included. + +- 2026-10-30 (test-maintenance policy and settings incident assessment): Made + test authoring and focused/PR-ready/release/upstream/Obsidian-alpha execution + requirements explicit in all three agent guides; clarified automatic portable + CI versus manually invoked native profiles. Read-only saved-evidence analysis + identifies a defaults-like settings replacement. Isolated actual-manager code + reproduces a save after destruction with null settings persisting an empty + object. The original callback is not captured, so incident attribution remains + a leading hypothesis. Recorded the combined custom-settings/unload/reload + coverage gap in F34. No settings production changes or personal-vault reload + experiments. Documentation/inventory checks apply to this checkpoint; the + code-validation evidence remains the prior 670-case portable and focused + native run. Highest next risk is a delayed settings save after plugin teardown; + reproduce it in the repository-local vault before a separately approved fix. diff --git a/docs/OBSIDIAN_RUNTIME_TESTING.md b/docs/OBSIDIAN_RUNTIME_TESTING.md index 011f4077..be3029a0 100644 --- a/docs/OBSIDIAN_RUNTIME_TESTING.md +++ b/docs/OBSIDIAN_RUNTIME_TESTING.md @@ -357,6 +357,17 @@ and legacy/empty source handling. The matrix includes plain text, `[[link]]`, and JavaScript error checks. The scenario uses the toolbar's stable test IDs, so labels may be localized. Physical mobile and popout checks remain separate. +It also draws four earlier shapes, A, a `[[link]]` label and B using trusted +pointer/keyboard input. Eight additional sequences cover bound/standalone text, +raw/parsed mode and keyboard/toolbar history. They undo B, the text, A and every +earlier shape to an empty scene, then redo the full sequence and compare element +identity, geometry, Markdown source, link metadata and bindings. Evidence is +written to `text-creation-history.json`; these sequences extend the existing +`text-undo-2976` identity rather than adding new canonical native case IDs. +An optional selection-only editor entry is verified separately: it must have +no element delta, consume exactly one history entry and leave the scene unchanged. +Every drawing-action entry must still undo in the specified order. + For the native Excalidraw authoring protocol, run: ```sh diff --git a/docs/TESTING_FINDINGS_3022.md b/docs/TESTING_FINDINGS_3022.md index 7b8d4bb4..5c478023 100644 --- a/docs/TESTING_FINDINGS_3022.md +++ b/docs/TESTING_FINDINGS_3022.md @@ -1,6 +1,6 @@ # Test findings for maintainer review -**Current evidence: F32 and the [2026-10-30 acceptance report](testing-evidence/3022/README.md).** +**Acceptance checkpoint: F32 and the [2026-10-30 acceptance report](testing-evidence/3022/README.md). Later approved link-history fix: F33.** Earlier findings retain their original hosts and failed attempts as history. The required native pair passes 357/357 in both complete matching-build repeats. Earlier failures remain historical evidence; no production observer fix is claimed. @@ -735,3 +735,93 @@ and the strict gate is unchanged. Physical touch/WebView/stylus, real OS drag/clipboard, native macOS/Linux and isolated whole-app cold start remain separate environments. [Both complete case matrices and manifests](testing-evidence/3022/native-acceptance-pair-2026-10-30.json) support review readiness without claiming those additional environments. + +## F33 - Parsed-link submission discarded earlier drawing history + +The maintainer reproduced drawing earlier shapes, A, a bound `[[link]]` label +and B, then undoing B and the label but being unable to undo A or earlier shapes. +Source execution confirms this predates the testing PR and the October 11 text +restoration fix. The parser submission branch explicitly cleared the entire +history whenever raw Markdown differed from parsed display text. The initial +focused native reproduction confirms the same failure: after two undos, five +rectangles remain with undo depth zero. Original evidence is retained under +`.test-work/reports/2026-10-30-link-history-before/`. + +The maintainer authorized fixing this on October 30. Remove only that ordinary +parsed-link submission reset: the matching fork already captures raw Markdown, +parsed display and link metadata in the text transaction. Leave the independent +mode-switch, asynchronous-transclusion and invalid-clipboard reset paths intact. +No fork or Extras production code, observer or printing changes. + +Four new source cases use the actual submission hook and parser for raw/parsed +and bound/standalone text, each checking plain text, wiki links, aliases and +Markdown links plus cache refresh after undo. Eight native sequences use real +CDP drawing/text input and keyboard/toolbar history. They undo B, the link text, +A and all four earlier rectangles to an empty scene, then redo the entire scene +and compare identities, geometry, source, links and bindings. The first fixed +probe exposed a test assumption: entering a label may capture a selection-only +entry. That failed evidence remains in `2026-10-30-link-history-after/`. The +corrected test explicitly verifies at most one such entry, no element delta, +unchanged scene and one consumed history entry; no drawing-action assertion is +removed. The final focused run passes all eight sequences and all 16 existing +text-edit variants, error controls, cleanup and baseline restoration: +`.test-work/reports/2026-10-30-link-history-verified/`. + +Repeat with `node --test scripts/testing/textSubmissionHistory.test.mjs` and +`npm.cmd run verify:obsidian -- --text-undo --diagnostics`. Broader portable and +build verification uses `npm.cmd run test:regression:portable`; the exact +production audit now includes this specifically authorized patch. Native case +identity remains `text-undo-2976`; no earlier complete-run evidence is relabeled +as testing this later fix. Main-window trusted input is covered; popout and +physical mobile remain separate risk checks for this follow-up. + +Broader verification also exposed an independent fork-owned browser setup +error. After the preceding tool workflow already selects Selection, clicking +that active toolbar button intentionally activates Lasso. Passive failure +capture confirms `activeTool.type === "lasso"`; the existing readiness assertion +correctly fails. Guard only that redundant setup click. All 18 normal browser +cases then pass with the original group/delete/history assertions unchanged. +The fork inventory records this test-only correction. Use the documented +`PLAYWRIGHT_BROWSERS_PATH` when running portable checks; no browser upgrade is +needed. Initial failed reports remain in the ignored local evidence directories. + +Local deployment verification caught a settings-file rewrite during reload. +The original backup was restored while the plugin was unloaded, then loaded +again and verified byte-identical after settling. The fixed runtime and drawing +editors are ready. The rewrite's original cause is unassigned; no settings +production change is included, and private settings/backups remain untracked. + +## F34 - Settings replacement during reload: unsafe late-save path reproduced + +The preserved deployment evidence shows a substantive replacement, not merely +canonical JSON ordering: 212 persisted keys became 187. Canonical comparison +against source literals matches 178 of 179 comparable default properties; the +exception is the normal once-off compression-reset flag. Eight computed defaults +are outside that static comparison. The replacement differs from the native +vault's configured fixture, and the two vaults have distinct recovery namespaces. +This supports default initialization/persistence as the failure mechanism; it +does not prove which load or save initiated the incident. + +There is a concrete unsafe lifecycle path. `onunload()` destroys the settings +manager and sets `settings = null`. The manager's `destroy()` closes the recovery +store but does not reject later `saveSettings()` calls. The API-key persistence +helper spreads its input (`{ ...settings }`), so a null input becomes an empty +object. The still-active writer can then save `{}`. The loader accepts an empty +object as a valid record and fills defaults on the next load. + +An isolated reproduction executes the actual manager, serialization writer and +key-obfuscation modules with fake storage: destroy the manager, clear host +settings, invoke a late save. It performs one write after destruction and loses +the non-default sentinel. This is evidence of the unsafe path, not a native +capture of the original callback. The private diagnostic is +`tmp/reproduce-late-settings-save.mjs`, with results under the ignored deployment +evidence directory; no real settings are used in that reproduction. + +Existing native coverage saves/loads settings on a live plugin instance. The +separate plugin-reload case asserts drawing/runtime/command survival, without +asserting custom settings across that boundary. A combined regression must use +non-default values and unknown keys, cover delayed saves during teardown, reload +the plugin, and check both persisted data and loaded preferences. Keep any +production fix separate until approved. Original settings were restored from +the exact backup and their loaded preferences verified. No additional reload +experiment was performed in the personal vault for this diagnosis. diff --git a/scripts/testing/host/textCreationHistory.mjs b/scripts/testing/host/textCreationHistory.mjs new file mode 100644 index 00000000..cb0af350 --- /dev/null +++ b/scripts/testing/host/textCreationHistory.mjs @@ -0,0 +1,102 @@ +/** Trusted input: earlier shapes survive link submission in the undo/redo chain. */ +import assert from "node:assert/strict"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { captureTextUndoState } from "./textUndoDiagnostics.mjs"; + +export async function runTextCreationHistory({ cli, drawingPath, reportDir, prepareFixture }) { + const view = `app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(drawingPath)})?.view`; + const evaluate = (code) => JSON.parse(cli("eval", "code=" + code).trim().replace(/^=>\s*/, "")); + const cdp = (method, params) => cli("dev:cdp", "method=" + method, "params=" + JSON.stringify(params)); + const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + const snapshots = [], completed = []; + const persist = () => writeFileSync(join(reportDir, "text-creation-history.json"), JSON.stringify({ completed, snapshots }, null, 2)); + const state = () => evaluate(`JSON.stringify((${captureTextUndoState.toString()})(${view},app.workspace))`); + const scene = () => evaluate(`JSON.stringify(${view}.excalidrawAPI.getSceneElements().map(e=>({id:e.id,type:e.type,x:e.x,y:e.y,width:e.width,height:e.height,angle:e.angle,rawText:e.rawText,text:e.text,originalText:e.originalText,link:e.link,containerId:e.containerId,boundElements:e.boundElements})))`); + async function poll(predicate, label, read = scene) { + const end = Date.now() + 10000; + for (;;) { const value = read(); if (predicate(value)) return value; + if (Date.now() >= end) throw Error(label + ": " + JSON.stringify(value)); await wait(50); } + } + const key = (key, code, keyCode, modifiers = 0) => { + for (const type of ["keyDown", "keyUp"]) cdp("Input.dispatchKeyEvent", { type, key, code, windowsVirtualKeyCode: keyCode, modifiers }); + }; + const mouse = (type, point, extra = {}) => cdp("Input.dispatchMouseEvent", { type, ...point, button: "left", clickCount: 1, ...extra }); + const click = (point, count = 1) => { mouse("mousePressed", point, { clickCount: count }); mouse("mouseReleased", point, { clickCount: count }); }; + const focus = () => evaluate(`(()=>{${view}.containerEl.querySelector('.excalidraw').focus();return JSON.stringify(true)})()`); + async function draw(point, width, count) { + focus(); key("r", "KeyR", 82); + mouse("mouseMoved", point); mouse("mousePressed", point, { buttons: 1 }); + mouse("mouseMoved", { x: point.x + width / 2, y: point.y + 35 }, { buttons: 1 }); + mouse("mouseMoved", { x: point.x + width, y: point.y + 70 }, { buttons: 1 }); + mouse("mouseReleased", { x: point.x + width, y: point.y + 70 }); + const elements = await poll((elements) => elements.length === count, "rectangle creation"); + return elements.findLast((e) => e.type === "rectangle").id; + } + for (const mode of ["parsed", "raw"]) for (const bound of [true, false]) for (const input of ["keyboard", "button"]) { + const label = `${mode}/${bound ? "bound" : "standalone"}/${input}`; + try { + evaluate(`(${prepareFixture.toString()})(${view},${JSON.stringify(mode)}).then(JSON.stringify)`); + const r = evaluate(`(()=>{const r=${view}.containerEl.querySelector('canvas.interactive').getBoundingClientRect();return JSON.stringify({x:r.x,y:r.y,width:r.width,height:r.height})})()`); + assert.ok(r.width > 500 && r.height > 350, "usable drawing geometry"); + const width = Math.min(70, r.width * .09), y = r.y + r.height * .35; + const points = Array.from({ length: 6 }, (_, i) => ({ x: r.x + r.width * (.06 + i * .15), y })); + const ids = []; + for (let i = 0; i < 5; i++) ids.push(await draw(points[i], width, i + 1)); + const a = ids.at(-1); + if (bound) { + const center = { x: points[4].x + width / 2, y: y + 35 }; + click(center); click(center, 2); + } else { + key("t", "KeyT", 84); click({ x: points[4].x, y: y + 150 }); + } + await poll((s) => s.editor !== null, "open text editor", state); + cdp("Input.insertText", { text: "[[link]]" }); key("Escape", "Escape", 27); + await poll((s) => s.editor === null, "submit text", state); + const withText = await poll((elements) => elements.length === 6 && elements.some((e) => e.rawText === "[[link]]"), "submitted Markdown source"); + const text = withText.find((e) => e.type === "text"); + assert.equal(text.containerId, bound ? a : null, label + " text ownership"); + ids.push(text.id); + ids.push(await draw(points[5], width, 7)); + const final = scene(); + const act = async (action, expected, selectionOnly = false) => { + const ready = await poll((s) => s.controls[action].present && s.controls[action].visible && !s.controls[action].disabled, + `${label}: ${action} control unavailable`, state); + snapshots.push({ label, action, expected, selectionOnly, state: ready }); persist(); + if (input === "keyboard") { + focus(); key("z", "KeyZ", 90, (process.platform === "darwin" ? 4 : 2) | (action === "redo" ? 8 : 0)); + } else { + const b = ready.controls[action].bounds; click({ x: b.x + b.width / 2, y: b.y + b.height / 2 }); + } + const expectedIds = ids.slice(0, expected).sort(); + const result = await poll((elements) => JSON.stringify(elements.map((e) => e.id).sort()) === JSON.stringify(expectedIds), `${label}: ${action} to ${expected} elements`); + await poll((s) => s.history[action + "Depth"] === ready.history[action + "Depth"] - 1, + `${label}: ${action} consumes exactly one history entry`, state); + return result; + }; + const counts = [7]; + let selectionSteps = 0; + for (let n = 6; n >= 0; n--) { + const top = state().history.undoEntries?.at(-1); + if (top && ["added", "removed", "updated"].every((key) => Object.keys(top.elements?.[key] || {}).length === 0)) { + // Entering a label may capture deselection before the text transaction. + // Verify this exact entry; never skip unavailable controls or element edits. + assert.ok(top.appState && Object.keys(top.appState).every((side) => + Object.keys(top.appState[side]).every((key) => key === "selectedElementIds")), "selection-only history delta"); + assert.equal(++selectionSteps, 1, "at most one editor-selection entry"); + const beforeSelection = scene(); + await act("undo", n + 1, true); + assert.deepEqual(scene(), beforeSelection, "selection undo does not alter the drawing"); + counts.push(n + 1); + } + await act("undo", n); counts.push(n); + } + for (const n of counts.slice(0, -1).reverse()) await act("redo", n); + assert.deepEqual(scene(), final, label + " full redo restores geometry/link/binding/source state"); + completed.push(label); persist(); + } catch (error) { + snapshots.push({ label, failure: error.message, state: state(), scene: scene() }); persist(); throw error; + } + } + return { variants: completed, assertions: ["undo B, link text, A and all four earlier shapes to empty", "verify at most one selection-only editor entry", "redo complete scene", "bound/standalone source and links", "raw/parsed and keyboard/toolbar"] }; +} diff --git a/scripts/testing/host/textUndo.mjs b/scripts/testing/host/textUndo.mjs index 6718f323..f6e531f3 100644 --- a/scripts/testing/host/textUndo.mjs +++ b/scripts/testing/host/textUndo.mjs @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { captureTextUndoState } from "./textUndoDiagnostics.mjs"; +import { runTextCreationHistory } from "./textCreationHistory.mjs"; /** Use the real mode transition; reload=false changes only the view, not its model. */ export async function prepareTextUndoFixture(view, mode) { @@ -190,6 +191,9 @@ export async function runTextUndoScenario({ cli, drawingPath, reportDir }) { }, ]; try { + observations.creationHistory = await runTextCreationHistory({ + cli, drawingPath, reportDir, prepareFixture: prepareTextUndoFixture, + }); for (const mode of ["parsed", "raw"]) { for (const input of ["keyboard", "button"]) { for (const variant of variants) { @@ -306,6 +310,7 @@ export async function runTextUndoScenario({ cli, drawingPath, reportDir }) { cases, observations, assertions: [ + "undo past bound/standalone link creation to an empty drawing and redo the complete scene", "reopened source after undo/redo", "unchanged submission refreshes cache", "editing after undo", diff --git a/scripts/testing/review3022ProductionDiff.mjs b/scripts/testing/review3022ProductionDiff.mjs index 446a8d05..73cfbe7b 100644 --- a/scripts/testing/review3022ProductionDiff.mjs +++ b/scripts/testing/review3022ProductionDiff.mjs @@ -18,7 +18,7 @@ export function reviewProductionDiff({ const roots = { plugin: pluginRoot, fork: forkRoot, extras: extrasRoot }, report = { scope: - "PDF timeout/concurrency rollback, plus the maintainer-authorized plain-PDF, local-font and internal Canvas-node focus fixes of 2026-10-29 and their release notes; no other production changes.", + "PDF timeout/concurrency rollback, plus the maintainer-authorized plain-PDF, local-font and internal Canvas-node focus fixes of 2026-10-29, parsed-link undo-history preservation authorized on 2026-10-30, and their release notes; no other production changes.", baselines, repositories: {}, }; @@ -67,6 +67,7 @@ export function reviewProductionDiff({ ? [ "src/shared/Dialogs/Messages.ts", "src/shared/EmbeddedFileLoader.ts", + "src/view/ExcalidrawView.ts", "src/view/managers/CanvasNodeFactory.ts", ] : ["packages/excalidraw/obsidianUtils.ts"], @@ -88,6 +89,20 @@ export function reviewProductionDiff({ ); }; if (kind === "plugin") { + expectedFile("src/view/ExcalidrawView.ts", (source) => + source.replace( + [ + " // Updating only the cache after undo must not discard the redo stack.", + " if (textChanged) {", + " api.history.clear();", + " }", + ].join("\n"), + [ + " // The fork records raw Markdown and parsed display text in the same edit.", + " // Preserve earlier drawing actions as well as redo on cache-only updates.", + ].join("\n"), + ), + ); expectedFile("src/view/managers/CanvasNodeFactory.ts", (source) => source .replace( @@ -110,6 +125,7 @@ export function reviewProductionDiff({ "## Fixed\n- Autosave", [ "## Fixed", + "- Adding a link to a text element or shape label no longer discards undo history for earlier drawing actions.", "- Embedded Markdown previews no longer take editor focus when they load, avoiding a mobile toolbar error. [#3022](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/3022)", "- Importing a PDF file through ExcalidrawAutomate loads page 1 when no page reference is supplied. [#3022](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/3022)", "- Markdown images using Helvetica no longer try to fetch a nonexistent font file. [#3022](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/3022)", @@ -219,7 +235,7 @@ if ( JSON.stringify(report, null, 2) + "\n", ); process.stdout.write( - "Production diff audit passed: exact plain-PDF/local-font/internal-node-focus fixes and release notes; Extras PDF rollback only. " + + "Production diff audit passed: exact plain-PDF/local-font/internal-node-focus/parsed-link-history fixes and release notes; Extras PDF rollback only. " + output + "\n", ); diff --git a/scripts/testing/textSubmissionHistory.test.mjs b/scripts/testing/textSubmissionHistory.test.mjs new file mode 100644 index 00000000..9b26a091 --- /dev/null +++ b/scripts/testing/textSubmissionHistory.test.mjs @@ -0,0 +1,57 @@ +/** Execute the production submission hook and parser; no original-source coverage credit. */ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import vm from "node:vm"; +import ts from "typescript"; + +const compile = (source) => ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, +}).outputText; +const source = readFileSync(new URL("../../src/view/ExcalidrawView.ts", import.meta.url), "utf8"); +const ast = ts.createSourceFile("ExcalidrawView.ts", source, ts.ScriptTarget.Latest, true); +const viewClass = ast.statements.find((n) => ts.isClassDeclaration(n) && n.name?.text === "ExcalidrawView"); +const method = viewClass.members.find((n) => n.name?.getText(ast) === "onBeforeTextSubmit"); +const Submit = vm.runInNewContext(compile(`class Submit { ${method.getText(ast)} }\nSubmit;`), { + window: { setTimeout: () => 1, clearTimeout() {} }, t: (key) => key, + isTextImageTransclusion: () => false, TextMode: { raw: "raw", parsed: "parsed" }, +}); +const exports = {}; +vm.runInNewContext(compile(readFileSync(new URL("../../src/shared/ExcalidrawData.ts", import.meta.url), "utf8")), { + exports, require: () => ({}), window: { setTimeout: () => 1, clearTimeout() {} }, +}); + +for (const mode of ["parsed", "raw"]) { + for (const bound of [false, true]) { + test(`${mode} ${bound ? "bound" : "standalone"} text submission preserves earlier drawing history and Markdown source`, () => { + for (const raw of ["plain", "[[link]]", "[[link|label]]", "[label](https://example.com)"]) { + const model = Object.create(exports.ExcalidrawData.prototype); + Object.assign(model, { plugin: { settings: { parseTODO: false } }, textElements: new Map(), + linkPrefix: "", urlPrefix: "", showLinkBrackets: false }); + const undo = ["x", "y", "z", "w", "A"], redo = [], sizes = []; + const view = Object.assign(Object.create(Submit.prototype), { + excalidrawAPI: { history: { clear() { undo.length = 0; redo.length = 0; } } }, + semaphores: {}, textMode: mode, excalidrawData: model, setDirty() {}, + updateContainerSize: (...args) => sizes.push(args), + plugin: { settings: { syncElementLinkWithText: true } }, + }); + const element = { id: "label", type: "text", originalText: "", rawText: "", link: null, + containerId: bound ? "A" : null }; + const [parsed, link] = model.quickParse(raw); + const result = view.onBeforeTextSubmit(element, raw, raw, false); + assert.deepEqual(undo, ["x", "y", "z", "w", "A"], raw); + assert.equal(model.getRawText(element.id), raw); + assert.equal(result.updatedNextOriginalText ?? raw, mode === "raw" ? raw : parsed); + assert.equal(result.nextLink, link); + assert.equal(sizes.length, bound ? 1 : 0); + + // A cache refresh on unchanged submission after undo must preserve redo too. + redo.push("text edit", "B"); + model.textElements.delete(element.id); + view.onBeforeTextSubmit({ ...element, originalText: raw, rawText: raw }, raw, raw, false); + assert.deepEqual(undo, ["x", "y", "z", "w", "A"], raw); + assert.deepEqual(redo, ["text edit", "B"], raw); + } + }); + } +} diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index f7ec2f69..83a23209 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -30,6 +30,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it? - Added opt-in image inventory, bounded image labels/tags, mixed-fidelity SVG/PNG previews and output limits. Originals remain untouched and full fidelity stays the default. [#3004](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3004) ## Fixed +- Adding a link to a text element or shape label no longer discards undo history for earlier drawing actions. - Embedded Markdown previews no longer take editor focus when they load, avoiding a mobile toolbar error. [#3022](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/3022) - Importing a PDF file through ExcalidrawAutomate loads page 1 when no page reference is supplied. [#3022](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/3022) - Markdown images using Helvetica no longer try to fetch a nonexistent font file. [#3022](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/3022) diff --git a/src/view/ExcalidrawView.ts b/src/view/ExcalidrawView.ts index 44a1ccee..1c90f0e9 100644 --- a/src/view/ExcalidrawView.ts +++ b/src/view/ExcalidrawView.ts @@ -6727,10 +6727,8 @@ export default class ExcalidrawView } return { updatedNextOriginalText: null, nextLink: textElement.link }; } //There were no links to parse, raw text and parsed text are equivalent - // Updating only the cache after undo must not discard the redo stack. - if (textChanged) { - api.history.clear(); - } + // The fork records raw Markdown and parsed display text in the same edit. + // Preserve earlier drawing actions as well as redo on cache-only updates. return { updatedNextOriginalText: parseResultOriginal, nextLink: link }; } return { updatedNextOriginalText: null, nextLink: textElement.link }; diff --git a/tests/features.json b/tests/features.json index eae0dec5..ab80a84e 100644 --- a/tests/features.json +++ b/tests/features.json @@ -207,6 +207,16 @@ "text-undo-2976" ] }, + { + "layer": "source", + "path": "scripts/testing/textSubmissionHistory.test.mjs", + "cases": [ + "parsed standalone text submission preserves earlier drawing history and Markdown source", + "parsed bound text submission preserves earlier drawing history and Markdown source", + "raw standalone text submission preserves earlier drawing history and Markdown source", + "raw bound text submission preserves earlier drawing history and Markdown source" + ] + }, { "layer": "native", "path": "scripts/testing/host/groupedLinkClick.mjs", diff --git a/tests/inventory.json b/tests/inventory.json index ef5ff440..3318cc6f 100644 --- a/tests/inventory.json +++ b/tests/inventory.json @@ -2601,6 +2601,10 @@ "path": "scripts/testing/textElementParsing.test.mjs", "mode": "isolated-or-extracted" }, + { + "path": "scripts/testing/textSubmissionHistory.test.mjs", + "mode": "isolated-or-extracted" + }, { "path": "tests/markdownImageCache.test.mjs", "mode": "direct-module-or-tooling"