From 572cb9c3814f457350859a97a7aae3565bcb9ec5 Mon Sep 17 00:00:00 2001 From: zsviczian Date: Wed, 14 Oct 2026 06:45:42 +0200 Subject: [PATCH 1/2] docs: add draft implementation handoff for CLI image efficiency (#3004) --- docs/agent-handoffs/issue-3004.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/agent-handoffs/issue-3004.md diff --git a/docs/agent-handoffs/issue-3004.md b/docs/agent-handoffs/issue-3004.md new file mode 100644 index 00000000..e6d6ee07 --- /dev/null +++ b/docs/agent-handoffs/issue-3004.md @@ -0,0 +1,14 @@ +# Issue #3004 — CLI image safety and efficient previews + +Status: planning-only handoff; no runtime fix is included. + +- Issue: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3004 +- Branch: `2026-10-14-issue-3004-cli-image-efficiency` +- Starting baseline: `master@b022db60b690e648e04b62774f745ae6a6e47cdb`. +- Read the draft PR for this branch for the source-based assessment, proposed request contract, implementation order, and acceptance tests. It is the implementation handoff, not a claim of completed work. + +Keep full-fidelity revision checks independent from opt-in preview reduction. Address both `getFiles()` payloads and cached image strings in prepared-file metadata. Add bounded-resolution and selective labelled-placeholder previews without editing source drawings or weakening stale-image checks. Prefer plugin-side export preparation using the existing component APIs. + +Implement on this same branch after rereading `AGENTS.md`, `CONTRIBUTING.md`, the issue, and PR discussion. Preserve the original-image export default, request receipts, source/output ownership, and existing public APIs. No fork/package/version changes are approved by this planning checkpoint. + +Remove this temporary file once the implementation and repeatable tests replace it. Update the PR with actual validation and remaining risks; do not merge automatically. From abf35c06de48bc5bcb0e1c93a6dec7f3eaf1c9fc Mon Sep 17 00:00:00 2001 From: zsviczian Date: Thu, 15 Oct 2026 06:17:18 +0200 Subject: [PATCH 2/2] Fix image-heavy CLI revisions and add bounded image previews --- docs/AITrainingData/excalidraw-cli/SKILL.md | 9 +- docs/CLI.md | 33 ++- docs/OBSIDIAN_RUNTIME_TESTING.md | 19 ++ docs/agent-handoffs/issue-3004.md | 14 -- scripts/testing/cli.test.mjs | 218 +++++++++++++++++- scripts/testing/host/cliImagePreview.mjs | 127 ++++++++++ scripts/testing/host/cliLargeIdentity.mjs | 32 +++ scripts/testing/host/nativeCLI.mjs | 11 +- scripts/testing/host/runner.mjs | 2 +- src/core/cli/CLIWriteCommands.ts | 2 +- src/core/cli/cliApply.ts | 16 +- src/core/cli/cliCommands.ts | 15 +- src/core/cli/cliDependencies.ts | 65 ++++++ src/core/cli/cliExport.ts | 178 ++++++++++---- src/core/cli/cliExportGeometry.ts | 27 +++ src/core/cli/cliIdentity.ts | 54 +++++ src/core/cli/cliImageDimensions.ts | 56 +++++ src/core/cli/cliImages.ts | 179 ++++++++++++++ src/core/cli/cliProtocol.ts | 3 +- src/core/cli/cliSchema.ts | 26 ++- src/core/cli/cliScripts.ts | 3 +- src/core/cli/cliTarget.ts | 32 ++- src/core/managers/ExcalidrawCLI.ts | 55 +++-- src/shared/Dialogs/Messages.ts | 4 + src/shared/EmbeddedFileLoader.ts | 15 +- src/utils/elementCustomDataUtils.ts | 40 ++++ src/utils/excalidrawAutomateUtils.ts | 7 + test-data/cli-preview-3004/README.md | 30 +++ .../cli-preview-3004/dark-placeholder.png | Bin 0 -> 32523 bytes test-data/cli-preview-3004/light-mixed.png | Bin 0 -> 27453 bytes test-data/cli-preview-3004/light-original.png | Bin 0 -> 18901 bytes .../cli-preview-3004/light-placeholder.svg | 2 + .../cli-preview-3004/live-thumbnails.png | Bin 0 -> 21198 bytes 33 files changed, 1167 insertions(+), 107 deletions(-) delete mode 100644 docs/agent-handoffs/issue-3004.md create mode 100644 scripts/testing/host/cliImagePreview.mjs create mode 100644 scripts/testing/host/cliLargeIdentity.mjs create mode 100644 src/core/cli/cliDependencies.ts create mode 100644 src/core/cli/cliExportGeometry.ts create mode 100644 src/core/cli/cliIdentity.ts create mode 100644 src/core/cli/cliImageDimensions.ts create mode 100644 src/core/cli/cliImages.ts create mode 100644 test-data/cli-preview-3004/README.md create mode 100644 test-data/cli-preview-3004/dark-placeholder.png create mode 100644 test-data/cli-preview-3004/light-mixed.png create mode 100644 test-data/cli-preview-3004/light-original.png create mode 100644 test-data/cli-preview-3004/light-placeholder.svg create mode 100644 test-data/cli-preview-3004/live-thumbnails.png diff --git a/docs/AITrainingData/excalidraw-cli/SKILL.md b/docs/AITrainingData/excalidraw-cli/SKILL.md index 82668c8c..b6fea9d5 100644 --- a/docs/AITrainingData/excalidraw-cli/SKILL.md +++ b/docs/AITrainingData/excalidraw-cli/SKILL.md @@ -10,13 +10,16 @@ All results use apiVersion 1. Check ok, mutation and persistence; process exit z Put large requests in a visible vault-relative JSON file and pass input="". Inline json is for small requests. Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command. Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts. -Loop: :read source=live detail=elements → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file. -For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY only after read-back. +Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file. +For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back. New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals. Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails. :result requestId= recovers a receipt after lost stdout. Receipts expire after 15 minutes/reload; unknown outcome requires read-back before another write. :api surface=ea name= gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts. :script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing. One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction. -Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Remote assets follow existing permissions. +Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets. +For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview. +imageMetadata apply operations set bounded descriptive label/tags, with null clearing; request-only imagePolicy.labels does not persist. Thumbnail mode uses thumbnailMaxDimension=512 by default; only PNG/JPEG/WebP with safe preflight dimensions are decoded (24 MiB / 16 million pixels maximum). +maxWidth/maxHeight/maxPixels bound output dimensions; maxArtifactBytes caps final bytes. Source revision covers originals; representationId identifies the preview. SVG width controls display size, not embedded raster payload size; use imagePolicy for that. Use :schema for exact fields, operation limits, and runnable examples. Do not edit compressed drawing Markdown directly or install another Excalidraw CLI. diff --git a/docs/CLI.md b/docs/CLI.md index c10262ba..2053eb43 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -105,6 +105,7 @@ not every later human edit. A handoff is not reported as durable. | `connect` | `from`, `to`; optional local `id`, `fromSide`, `toSide` (top/bottom/left/right) | | `group` | `ids`; returns a new group ID | | `ungroup` | `ids`, `groupId`; preserves other groups | +| `imageMetadata` | `id`, `label` (1–80 characters or `null` to clear), `tags` (up to 12 unique short strings or `null`) | | `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG; optional `id`, `x`, `y`, `scale` (boolean) | | `latex` | `text`; optional `id`, `x`, `y`, `scaleX`, `scaleY`; requires compatible enabled Extras MathJax | @@ -119,7 +120,7 @@ tombstones and binding cleanup and does not delete attachment files. ## Read, render, and recover `list` returns exact paths. `read` defaults to a summary without asset bodies; -`detail=elements` returns at most 50 elements per page (maximum 200). Use +`detail=elements` returns at most 50 elements per page (maximum 200); `detail=images` inventories placements, media types, loaded sizes (or unknown), existing labels/tags, and load state without base64. The inventory separates `loadedRenditionBytes` (decoded data-URL bytes) from `originalBytes` (known Vault attachment size); unknown values are `null`. It reports natural dimensions only when known from crop metadata. Use `nextOffset` and the same `revision` for later pages. A changed snapshot returns `STALE_REVISION`. `ids` filters explicit IDs and `selectedOnly` needs a live view. @@ -141,8 +142,32 @@ asset. Source/revision, theme, byte count, and dimensions are returned. Live exp does not save the drawing. Optional `theme` is light/dark, `padding` is 0–200 (default 10), `scale` is 0.1–4 for PNG (default 1), and `area` is an exact `{x,y,width,height}` scene rectangle. Inspect the image before another revision. -Missing/undecoded assets fail explicitly. Existing remote assets use normal -plugin permissions and may require network access. Core shape/text and SVG/PNG +Missing originals fail explicitly. A request-only `imagePolicy` opts into per-image preview reduction before image loading and SVG construction; no policy means original fidelity. For example: + +```json +{ + "apiVersion": 1, "command": "export", "requestId": "overview-1", + "path": "Drawings/Flow.excalidraw.md", "source": "live", "out": "Previews/Flow.svg", + "imagePolicy": { + "default": "placeholder", + "rules": [ + { "ids": ["chosen-element-id"], "mode": "original" }, + { "tags": ["context"], "mode": "thumbnail" }, + { "mimeTypes": ["image/svg+xml"], "maxBytes": 65536, "mode": "original" } + ], + "labels": { "another-element-id": "Context screenshot" }, + "thumbnailMaxDimension": 512 + }, + "maxWidth": 1200, "maxHeight": 900, "maxPixels": 1000000, + "maxArtifactBytes": 4194304 +} +``` + +Rules use AND across conditions and OR within each ID/tag/MIME list, first match wins. Unknown asset size does not match `maxBytes`; one rule must contain a matching condition. `default` is `original`, `thumbnail`, or `placeholder`. Placeholder labels come from request-only `labels`, then persisted namespaced metadata, then a short element ID. Set persisted `label`/`tags` with the guarded `apply` `imageMetadata` operation. The tool preserves unrelated `customData`, image placement, stacking and rotation, and never edits the source drawing during export. + +Thumbnail resolution is distinct from PNG pixel output bounds: thumbnail generation preflights PNG/JPEG/WebP headers before decoding and refuses sources over 24 MiB, images over 16 million pixels, and formats with unknown dimensions. SVG, GIF, animated WebP, and unsupported headers require `original` or `placeholder`. Disk thumbnails require direct PNG/JPEG/WebP sources; use loaded live renditions for composite drawing/PDF/Markdown assets. Conversions run sequentially and release temporary images and canvases. Cropped thumbnails preserve the original crop; placeholder labels rotate and mirror with the image, within its visible footprint. Original images can still exceed the final 32 MiB SVG cap. `maxWidth`, `maxHeight`, and `maxPixels` bound output dimensions (including the intermediate PNG canvas); PNG can derive a scale below 0.1 to fit a requested bound. SVG dimensions change display size but do not reduce embedded image bytes. `maxArtifactBytes` (1 KiB–32 MiB) bounds final bytes, with an early embedded-payload preflight. The export receipt returns `effectiveScale`, representation counts, the first 50 per-element decisions with a total count, output bounds, a scene-to-preview mapping (including frame titles and padding), and a separate `representationId` describing the preview. The source `revision` always describes the full original content. Image annotations are descriptive metadata, not a trust signal. + +Missing/undecoded assets fail explicitly when required by the chosen representation. Live previews use currently loaded content. Disk exports re-read consumed Vault attachments and compare content digests before publication, bypass cached drawing/PDF renditions, and refuse intervening Vault edits (including unrelated edits, conservatively). Disk exports refuse required remote or machine-local assets because those cannot participate in a Vault snapshot; use a loaded live source or placeholders. Live remote assets use normal plugin permissions and may require network access. Core shape/text and SVG/PNG rendering work without Extras; optional features are never activated automatically. Every write requires a unique 1–80 character `requestId` (letters, digits, `_`, @@ -151,7 +176,7 @@ content with the same ID is rejected. Script source is part of that identity. `result` can recover lost stdout or report `status: pending, ok: null`. Completed receipts expire after 15 minutes; there are at most 128 in one plugin session. Reload/expiry/unknown outcomes require read-back before issuing another write. -Competing CLI operations on the same target return `BUSY`; human editing remains +Competing CLI operations on the same target return `BUSY`; a refusal known to occur before lock acquisition can be retried with the *identical* requestId. An unexpected internal error is reported as `INTERNAL_ERROR` without leaking payloads or stack traces, and any possibly started write has an unknown outcome; read back before retrying. human editing remains possible, so always refresh after `STALE_REVISION`. Input is limited to 2 MiB and nesting to 30 levels; output to 512 KiB. Use either diff --git a/docs/OBSIDIAN_RUNTIME_TESTING.md b/docs/OBSIDIAN_RUNTIME_TESTING.md index 6230b5c9..99769c70 100644 --- a/docs/OBSIDIAN_RUNTIME_TESTING.md +++ b/docs/OBSIDIAN_RUNTIME_TESTING.md @@ -238,6 +238,25 @@ and bytes. The separate text-undo scenario still requires the component fix described above. Run one driver at a time; UI/CDP input also needs the intended vault window to retain focus. +The native CLI lane also saves a light/dark SVG/PNG image-policy matrix in the +report's `image-previews/` directory before cleaning its Vault fixtures. It covers +shared-image originals, thumbnails and placeholders, crop/mirroring/rotation, +transparency, frame title bounds, source/dirty-state preservation, metadata clear +semantics, and an actual same-size/same-mtime +attachment replacement after disk asset preparation. No raced output may publish. Set `EXCALIDRAW_CLI_POPOUT=1` to add +popout inventory/export/teardown. This host currently reports ResizeObserver +notifications when closing even a blank drawing popout; the runner preserves +those errors and fails its clean-error gate rather than hiding them. + +Set `EXCALIDRAW_CLI_LARGE_IDENTITY=1` for the explicit native identity stress: +387 synthetic file records hold more aggregate payload characters than V8's +maximum single-string length, including prepared descriptor payloads. It checks +stable read/pagination revisions, last-byte replacement, stale-apply refusal and +placeholder export, recording read timings and sampled JS heap usage. Its strings +share immutable backing storage; this is not a benchmark of 570 MB of independently +decoded real images, regenerated-equal payloads, peak memory or UI responsiveness. +Those measurements still require an image-heavy drawing copy in the test vault. + For LaTeX dialog input and window ownership (#2970), run: ```bash diff --git a/docs/agent-handoffs/issue-3004.md b/docs/agent-handoffs/issue-3004.md deleted file mode 100644 index e6d6ee07..00000000 --- a/docs/agent-handoffs/issue-3004.md +++ /dev/null @@ -1,14 +0,0 @@ -# Issue #3004 — CLI image safety and efficient previews - -Status: planning-only handoff; no runtime fix is included. - -- Issue: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3004 -- Branch: `2026-10-14-issue-3004-cli-image-efficiency` -- Starting baseline: `master@b022db60b690e648e04b62774f745ae6a6e47cdb`. -- Read the draft PR for this branch for the source-based assessment, proposed request contract, implementation order, and acceptance tests. It is the implementation handoff, not a claim of completed work. - -Keep full-fidelity revision checks independent from opt-in preview reduction. Address both `getFiles()` payloads and cached image strings in prepared-file metadata. Add bounded-resolution and selective labelled-placeholder previews without editing source drawings or weakening stale-image checks. Prefer plugin-side export preparation using the existing component APIs. - -Implement on this same branch after rereading `AGENTS.md`, `CONTRIBUTING.md`, the issue, and PR discussion. Preserve the original-image export default, request receipts, source/output ownership, and existing public APIs. No fork/package/version changes are approved by this planning checkpoint. - -Remove this temporary file once the implementation and repeatable tests replace it. Update the PR with actual validation and remaining risks; do not merge automatically. diff --git a/scripts/testing/cli.test.mjs b/scripts/testing/cli.test.mjs index abaeb2c8..5d6c5d2c 100644 --- a/scripts/testing/cli.test.mjs +++ b/scripts/testing/cli.test.mjs @@ -36,7 +36,7 @@ function harness({ supported = true, desktop = true, native = true } = {}) { } const protocol = load('src/core/cli/cliProtocol'); const { ExcalidrawCLI } = load('src/core/managers/ExcalidrawCLI'); - return { manager: new ExcalidrawCLI(plugin), protocol, elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), plugin, registrations, versionChecks, files, View }; + return { manager: new ExcalidrawCLI(plugin), protocol, elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), images: load('src/core/cli/cliImages'), dimensions: load('src/core/cli/cliImageDimensions'), dependencies: load('src/core/cli/cliDependencies'), customData: load('src/utils/elementCustomDataUtils'), plugin, registrations, versionChecks, files, View, mocks }; } const request = (command, values = {}) => ({ apiVersion: 1, command, ...values }); @@ -92,7 +92,7 @@ test('portable skill stays aligned with native output and schema describes finit assert.equal((await h.manager.execute(request('api', { name: 'addRect' }))).data.entries[0].description, ''); const schema = (await h.manager.execute(request('schema', { action: 'apply' }))).data.jsonSchema; assert.ok(schema.required.includes('expectedRevision')); - assert.deepEqual(schema.$defs.operation.oneOf.map(option => option.properties.op.const), ['add', 'update', 'delete', 'connect', 'group', 'ungroup', 'image', 'latex']); + assert.deepEqual(schema.$defs.operation.oneOf.map(option => option.properties.op.const), ['add', 'update', 'delete', 'connect', 'group', 'ungroup', 'image', 'imageMetadata', 'latex']); }); test('multiple views require explicit identity; disk ignores ambiguity and refuses view selection', async () => { @@ -236,3 +236,217 @@ test('CLI compilation checks exact source even when file stat matches a cached m file.content = 'new source'; assert.equal(await (await getCompiled.call(engine, file, 'new source'))(), 'new source'); await assert.rejects(getCompiled.call(engine, file, 'different'), /source changed/); }); + +test('segmented live revisions retain immutable payloads and catch last-byte or descriptor changes', () => { + const h = harness(); + const dataURL = 'data:image/png;base64,' + 'a'.repeat(2 * 1024 * 1024); + const file = { id: 'asset', mimeType: 'image/png', dataURL, created: 1 }; + const element = { id: 'img', type: 'image', fileId: 'asset', version: 1, isDeleted: false }; + const embedded = { img: dataURL, imgInverted: dataURL, mtime: 2 }; + const model = { textElements: new Map(), markdownImages: new Map(), equations: new Map(), mermaids: new Map(), + exportPreparedSaveData: () => ({ files: new Map([['asset', embedded]]) }) }; + const files = { asset: file }; + const view = new h.View(); + Object.assign(view, { id: 'view-1', file: h.files[0], excalidrawData: model, + excalidrawAPI: { getSceneElementsIncludingDeleted: () => [element], getFiles: () => files }, + getScene: () => ({ appState: { theme: 'light' } }), data: 'markdown', textMode: 'raw', plugin: { settings: { use: true } }, + isLoaded: true, isClosingOrMigrating: () => false }); + const targets = h.manager.targets; + const original = targets.revision(view); + assert.equal(targets.revision(view), original); + file.dataURL = dataURL.slice(0, -1) + 'b'; + const replaced = targets.revision(view); + assert.notEqual(replaced, original); + assert.equal(targets.revision(view), replaced); + embedded.imgInverted = dataURL.slice(0, -1) + 'c'; + assert.notEqual(targets.revision(view), replaced); + const beforeSettings = targets.revision(view); + view.plugin.settings.use = false; + assert.notEqual(targets.revision(view), beforeSettings); + const beforeApi = targets.revision(view); + view.excalidrawAPI = { ...view.excalidrawAPI }; + assert.notEqual(targets.revision(view), beforeApi); + h.manager.destroy(); +}); + +test('CLI image inventory and policy avoid data URLs, separate shared-symbol representations and reject malformed rules', async () => { + const h = harness(); + const { parseImagePolicy, decideImage, imageInventory, prepareImagePreview } = h.images; + const file = { id: 'shared', dataURL: 'data:image/png;base64,QUJDRA==', mimeType: 'image/png', created: 0 }; + const original = { id: 'original', type: 'image', fileId: 'shared', status: 'saved', x: 10, y: 12, width: 200, height: 100, angle: 0.5, opacity: 80, scale: [-1, 1], crop: null, customData: { excalidrawCLI: { version: 1, tags: ['context'] } } }; + const copy = { ...original, id: 'placeholder', customData: { excalidrawCLI: { version: 1, label: '<& 安全>' } } }; + const policy = parseImagePolicy({ default: 'placeholder', rules: [{ ids: ['original'], mode: 'original' }], thumbnailMaxDimension: 512 }); + const a = decideImage(original, file, policy), b = decideImage(copy, file, policy); + assert.equal(a.mode, 'original'); assert.equal(b.mode, 'placeholder'); + assert.equal(imageInventory(original, file).loadedRenditionBytes, 4); + assert.equal(imageInventory(original, file).tags[0], 'context'); + assert.equal(imageInventory({ ...original, status: undefined }, file).status, null); + const preview = await prepareImagePreview([original, copy], { shared: file }, policy, new Map([[a.elementId, a], [b.elementId, b]])); + assert.equal(preview.elements[0].fileId, 'shared'); + assert.notEqual(preview.elements[1].fileId, 'shared'); + assert.equal(preview.elements[1].crop, null); + assert.equal(preview.elements[1].x, copy.x); assert.equal(preview.elements[1].angle, copy.angle); + assert.deepEqual(preview.elements[1].scale, copy.scale); + const previewPayload = preview.files[preview.elements[1].fileId].dataURL; + const xml = atob(previewPayload.split(',')[1]); + assert.match(xml, /<&/); assert.doesNotMatch(xml, /