Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: compact input, round two — text fits itself, markdown accepted, a load reports what it dropped (#490)

nyblnetd083baa07fb8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 76a5c05a..d7e89823 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1360,6 +1360,24 @@ jobs:
# the loader gates the expanded doc, the file on disk stays full.
run: node scripts/test-slides-compact.ts
+ - name: Agent-deck corpus rig
+ # scripts/fixtures/agent-decks/*.json — compact decks written the way
+ # agents write them (md, omitted h, nested arrays) — load through the
+ # real loader with zero dropped keys and zero validate() errors; a
+ # deliberately wrong deck reports every drop at its path with a reason.
+ run: |
+ slides/node_modules/.bin/esbuild scripts/test-slides-agent-decks.ts --bundle --platform=node --format=esm --outfile="$RUNNER_TEMP/test-slides-agent-decks.mjs"
+ node "$RUNNER_TEMP/test-slides-agent-decks.mjs"
+
+ - name: Gate parity rig (the load-report collector changes no decision)
+ # main's untrusted.ts frozen from git at rig time and bundled beside
+ # the branch's; every checked-in deck plus a hostile corpus goes
+ # through both with the collector OFF and the outputs must be
+ # byte-identical. Security-reviewed hunk (#486).
+ run: |
+ git fetch --no-tags --depth=1 origin main
+ node scripts/test-gate-parity.ts
+
- name: Layers panel rig
# editor/layerrows.ts, DOM-free: rows top-first, labels per type,
# group indent, moveInPaintOrder == the Order buttons (front/back/±1,
diff --git a/AGENTS.md b/AGENTS.md
index 07d3489e..f9429294 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -111,13 +111,37 @@ re-run yields the same ids.
{ "type": "text", "x": 120, "y": 240, "w": 452, "h": 60, "html": "Revenue" } ] ] } ] }
```
+Two more things a compact text element may do. Leave `h` out (or write
+`"h": "auto"`) and the box is sized to its text on load, measured on the
+deck's real fonts — the same number *Fit height to text* would set; you
+cannot know how tall three lines of 24 pt are, the runtime can. Write `md`
+instead of `html` and it converts exactly as pasted markdown does: `**bold**`,
+`*italic*`, `` `code` ``, `~~strike~~`, `- bullets` (indent two spaces for a
+sub-bullet), `[caption](https://…)`; when both are present `html` wins.
+
Load it with `window.bento.loadDoc(json)` or *Save ▾ Replace from JSON…*;
`window.bento.compact()` (or *Save ▾ Copy compact JSON*) gives a deck back in
-this shape. A compact document passes the untrusted shape gate on the way in
-(unknown keys are dropped). The FILE is always saved full — the on-disk
-format is unchanged and every shipped shell reads it as before.
-`slides/src/compact.ts` is the whole mechanism; `scripts/test-slides-compact.ts`
-proves the round-trip on the starter deck and the gallery decks.
+this shape. A compact document passes the untrusted shape gate on the way in,
+and `loadDoc` RETURNS what happened:
+
+```js
+const r = window.bento.loadDoc(json)
+// r === false → not a document at all (nothing changed)
+// r.dropped → [{ path: '/slides/0/elements/2/fontSze', reason: 'unknown key for a text element' }, …]
+// r.expanded → fields filled from the editor's defaults
+// r.fitted → text boxes sized to their text
+// r.findings → window.bento.validate() on the loaded deck (overflow, off-canvas, dead links …)
+```
+
+The loop is: load → read `dropped` and `findings` → fix the JSON → load
+again. A dropped key is one the format does not have (a typo, or a field that
+does not exist for that element type); an invalid value is the right key with
+the wrong type or range. The FILE is always saved full — the on-disk format is
+unchanged and every shipped shell reads it as before. `slides/src/compact.ts`
+and `compactload.ts` are the whole mechanism; `scripts/test-slides-compact.ts`
+proves the round-trip on the starter deck and the gallery decks, and
+`scripts/fixtures/agent-decks/` holds decks written this way that must load
+clean in CI — add yours there if you find a shape that does not.
## Commands
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a4af889..d6a94777 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,19 @@ pre-1.0.
the compact way. Asked for, with a working proof of concept, by
benedictjohannes (#411, #422); the nested arrays and the flattening come
from that proof.
+- **The short way, round two: text sizes itself, markdown is accepted, and
+ a load says what it dropped.** In a compact document a text element may
+ leave `h` out (or say `"auto"`): the box is sized to its text on load,
+ with the deck's real fonts — the same measurement as *Fit height to text*.
+ A text element may carry `md` instead of `html` and it converts exactly as
+ pasted markdown does (bold, italic, code, strike, bullets and sub-bullets,
+ links). And `window.bento.loadDoc` now returns a report: every key the
+ safety check discarded, with its path and the reason (`/slides/0/elements/2/fontSze:
+ unknown key`), how many fields were filled in, and `validate()`'s findings
+ — so an agent's loop is load, read, fix, load again, instead of guessing
+ why a field vanished. *Replace from JSON…* summarises the same report in a
+ toast and logs it. Three agent-written decks are checked in and load clean
+ in CI.
- **A Layers list.** The Slide panel now opens with *Layers*: every element
on the slide, top of the stack first, with a glyph and a short label (the
text's first words, or the kind). Click a row to select, shift-click to add,
diff --git a/scripts/fixtures/agent-decks/markdown-auto-height.json b/scripts/fixtures/agent-decks/markdown-auto-height.json
new file mode 100644
index 00000000..92204e8f
--- /dev/null
+++ b/scripts/fixtures/agent-decks/markdown-auto-height.json
@@ -0,0 +1,65 @@
+{
+ "compact": true,
+ "title": "Agent-written notes",
+ "slides": [
+ {
+ "elements": [
+ {
+ "type": "text",
+ "x": 96,
+ "y": 60,
+ "w": 1088,
+ "md": "Release notes",
+ "fontSize": 56,
+ "fontWeight": 800,
+ "align": "left"
+ },
+ [
+ {
+ "type": "text",
+ "x": 96,
+ "y": 180,
+ "w": 520,
+ "md": "**Broadcast.** Audience copies follow the presenter.\n\n- locked or free\n- per-show key\n - nothing after the show",
+ "fontSize": 24,
+ "align": "left",
+ "valign": "top"
+ },
+ {
+ "type": "text",
+ "x": 664,
+ "y": 180,
+ "w": 520,
+ "md": "**Reveal.** Elements appear on the arrow key.\n\n- in reading order\n- together\n- `fx.step` in the file",
+ "fontSize": 24,
+ "align": "left",
+ "valign": "top"
+ }
+ ],
+ {
+ "type": "text",
+ "x": 96,
+ "y": 600,
+ "w": 1088,
+ "h": "auto",
+ "md": "Read more at [bento.page](https://bento.page)",
+ "fontSize": 20,
+ "opacity": 0.7
+ }
+ ]
+ },
+ {
+ "elements": [
+ {
+ "type": "text",
+ "x": 96,
+ "y": 60,
+ "w": 1088,
+ "md": "Thanks",
+ "fontSize": 72,
+ "fontWeight": 800
+ }
+ ]
+ }
+ ]
+}
diff --git a/scripts/fixtures/agent-decks/three-cards.json b/scripts/fixtures/agent-decks/three-cards.json
new file mode 100644
index 00000000..effa874e
--- /dev/null
+++ b/scripts/fixtures/agent-decks/three-cards.json
@@ -0,0 +1,140 @@
+{
+ "compact": true,
+ "title": "Three options",
+ "theme": {
+ "background": "#0F1720",
+ "color": "#F5F7FA"
+ },
+ "slides": [
+ {
+ "id": "options",
+ "elements": [
+ {
+ "id": "heading",
+ "type": "text",
+ "x": 96,
+ "y": 80,
+ "w": 1088,
+ "h": 80,
+ "html": "Three ways forward",
+ "fontSize": 48,
+ "fontWeight": 700
+ },
+ [
+ {
+ "type": "shape",
+ "shape": "rect",
+ "x": 96,
+ "y": 220,
+ "w": 340,
+ "h": 360,
+ "fill": "#1B2735",
+ "radius": 16
+ },
+ {
+ "type": "text",
+ "x": 120,
+ "y": 248,
+ "w": 292,
+ "h": 56,
+ "html": "Build",
+ "fontSize": 30,
+ "fontWeight": 700,
+ "align": "left"
+ },
+ {
+ "type": "text",
+ "x": 120,
+ "y": 320,
+ "w": 292,
+ "h": 220,
+ "html": "Own the engine; 8 KB; every construct we measured.",
+ "fontSize": 20,
+ "align": "left",
+ "valign": "top",
+ "opacity": 0.8
+ }
+ ],
+ [
+ {
+ "type": "shape",
+ "shape": "rect",
+ "x": 470,
+ "y": 220,
+ "w": 340,
+ "h": 360,
+ "fill": "#1B2735",
+ "radius": 16
+ },
+ {
+ "type": "text",
+ "x": 494,
+ "y": 248,
+ "w": 292,
+ "h": 56,
+ "html": "Buy",
+ "fontSize": 30,
+ "fontWeight": 700,
+ "align": "left"
+ },
+ {
+ "type": "text",
+ "x": 494,
+ "y": 320,
+ "w": 292,
+ "h": 220,
+ "html": "Keep the dependency; 64 KB; nothing to maintain.",
+ "fontSize": 20,
+ "align": "left",
+ "valign": "top",
+ "opacity": 0.8
+ }
+ ],
+ [
+ {
+ "type": "shape",
+ "shape": "rect",
+ "x": 844,
+ "y": 220,
+ "w": 340,
+ "h": 360,
+ "fill": "#1B2735",
+ "radius": 16
+ },
+ {
+ "type": "text",
+ "x": 868,
+ "y": 248,
+ "w": 292,
+ "h": 56,
+ "html": "Wait",
+ "fontSize": 30,
+ "fontWeight": 700,
+ "align": "left"
+ },
+ {
+ "type": "text",
+ "x": 868,
+ "y": 320,
+ "w": 292,
+ "h": 220,
+ "html": "Do nothing this cycle; revisit with real demand.",
+ "fontSize": 20,
+ "align": "left",
+ "valign": "top",
+ "opacity": 0.8
+ }
+ ],
+ {
+ "type": "shape",
+ "shape": "line",
+ "x": 96,
+ "y": 620,
+ "w": 1088,
+ "h": 2,
+ "fill": "#F7A600"
+ }
+ ]
+ }
+ ]
+}
diff --git a/scripts/fixtures/agent-decks/title-and-bullets.json b/scripts/fixtures/agent-decks/title-and-bullets.json
new file mode 100644
index 00000000..803bc256
--- /dev/null
+++ b/scripts/fixtures/agent-decks/title-and-bullets.json
@@ -0,0 +1,85 @@
+{
+ "compact": true,
+ "title": "Quarterly review",
+ "theme": {
+ "background": "#0F1720",
+ "color": "#F5F7FA",
+ "accent": "#F7A600"
+ },
+ "slides": [
+ {
+ "elements": [
+ {
+ "type": "text",
+ "x": 96,
+ "y": 220,
+ "w": 1088,
+ "h": 120,
+ "html": "Quarterly review",
+ "fontSize": 72,
+ "fontWeight": 800
+ },
+ {
+ "type": "text",
+ "x": 96,
+ "y": 360,
+ "w": 1088,
+ "h": 60,
+ "html": "Q3 2026 · Platform team",
+ "fontSize": 28,
+ "opacity": 0.7
+ }
+ ]
+ },
+ {
+ "elements": [
+ {
+ "type": "text",
+ "x": 96,
+ "y": 80,
+ "w": 1088,
+ "h": 80,
+ "html": "What shipped",
+ "fontSize": 48,
+ "fontWeight": 700
+ },
+ {
+ "type": "text",
+ "x": 96,
+ "y": 200,
+ "w": 1088,
+ "h": 360,
+ "md": "- Live broadcast for presentations\n- Reveal steps within a slide\n- Files 86 KB smaller\n- A security fix worth updating for",
+ "fontSize": 30,
+ "align": "left",
+ "valign": "top"
+ }
+ ]
+ },
+ {
+ "elements": [
+ {
+ "type": "text",
+ "x": 96,
+ "y": 80,
+ "w": 1088,
+ "h": 80,
+ "html": "Next",
+ "fontSize": 48,
+ "fontWeight": 700
+ },
+ {
+ "type": "text",
+ "x": 96,
+ "y": 200,
+ "w": 1088,
+ "h": 300,
+ "md": "1. Image export\n2. Layer panel\n3. Maths engine",
+ "fontSize": 30,
+ "align": "left",
+ "valign": "top"
+ }
+ ]
+ }
+ ]
+}
diff --git a/scripts/test-gate-parity.ts b/scripts/test-gate-parity.ts
new file mode 100644
index 00000000..0560c63d
--- /dev/null
+++ b/scripts/test-gate-parity.ts
@@ -0,0 +1,186 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Gate parity: with the load-report collector OFF, the untrusted gate on this
+// branch must make byte-identical accept/drop decisions to the gate on main
+// for every fixture. The collector (withDropReport) is an observation hook;
+// this is the proof it observes and never changes.
+//
+// node scripts/test-gate-parity.ts (needs origin/main fetched)
+//
+// HOW. main's slides/src/untrusted.ts is taken from git at rig time
+// (`git show origin/main:…`), written beside the branch's copy so its
+// relative imports resolve to the same model/palette/modelkeys/tips, and the
+// two are esbuild-bundled as separate entries; each fixture goes through
+// both sanitizeSlide (and, element by element, sanitizeElement) and the JSON
+// outputs are compared. The temporary file is removed afterwards.
+//
+// FIXTURES. Every checked-in deck (starter, the two gallery fixtures, the
+// three agent decks — expanded with the pure compact.ts first), plus a
+// hostile/edge corpus in the shapes the gate rigs already cover
+// (test-clipboard, test-embed, test-slides-crop): unknown keys, wrong types,
+// missing required keys, half-objects, url() backgrounds, javascript: and
+// http: sources, oversized lists, __proto__, unknown element types and
+// tip/shape enum values, every element type at its minimum.
+
+import { readFileSync, writeFileSync, unlinkSync, readdirSync, existsSync, mkdirSync } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { dirname, join } from 'node:path'
+import { tmpdir } from 'node:os'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const mainCopy = join(root, 'slides/src/untrusted.__main__.ts')
+const esbuild = join(root, 'slides/node_modules/.bin/esbuild')
+const out = join(tmpdir(), `bento-gate-parity-${process.pid}`)
+
+// ---- main's gate, frozen at rig time --------------------------------------
+// GIT= lets a machine whose `git` on PATH is a shim point at a real binary
+const GIT = process.env.GIT ?? 'git'
+const mainSrc = execFileSync(GIT, ['show', 'origin/main:slides/src/untrusted.ts'], { cwd: root, encoding: 'utf8' })
+const mainSha = execFileSync(GIT, ['rev-parse', '--short', 'origin/main'], { cwd: root, encoding: 'utf8' }).trim()
+writeFileSync(mainCopy, mainSrc)
+const bundle = (entry: string, name: string) => {
+ const file = join(out, name)
+ execFileSync(esbuild, [entry, '--bundle', '--platform=node', '--format=esm', `--outfile=${file}`, '--log-level=error'], { cwd: root })
+ return file
+}
+let branchGate: { sanitizeSlide: (v: unknown) => unknown; sanitizeElement: (v: unknown) => unknown }
+let mainGate: typeof branchGate
+let compact: { expandDoc: (v: unknown) => { slides: Array<{ elements: unknown[] }> } }
+try {
+ mkdirSync(out, { recursive: true })
+ const b = bundle(join(root, 'slides/src/untrusted.ts'), 'branch.mjs')
+ const m = bundle(mainCopy, 'main.mjs')
+ const c = bundle(join(root, 'slides/src/compact.ts'), 'compact.mjs')
+ branchGate = await import(pathToFileURL(b).href)
+ mainGate = await import(pathToFileURL(m).href)
+ compact = await import(pathToFileURL(c).href)
+} finally {
+ if (existsSync(mainCopy)) unlinkSync(mainCopy)
+}
+console.log(`main's gate frozen from origin/main ${mainSha}\n`)
+
+// ---- fixtures ---------------------------------------------------------------
+const box = { x: 10, y: 10, w: 100, h: 50 }
+const slides: Array<[string, unknown]> = []
+const add = (name: string, slide: unknown) => slides.push([name, slide])
+
+// real decks
+const { starterDoc } = await import(pathToFileURL(bundle(join(root, 'slides/src/starterdeck.ts'), 'starter.mjs')).href)
+starterDoc().slides.forEach((s: unknown, i: number) => add(`starter/${i}`, s))
+for (const f of readdirSync(join(root, 'scripts/fixtures/compact-decks')).filter((f) => f.endsWith('.json'))) {
+ JSON.parse(readFileSync(join(root, 'scripts/fixtures/compact-decks', f), 'utf8')).slides.forEach((s: unknown, i: number) => add(`${f}/${i}`, s))
+}
+for (const f of readdirSync(join(root, 'scripts/fixtures/agent-decks')).filter((f) => f.endsWith('.json'))) {
+ compact.expandDoc(JSON.parse(readFileSync(join(root, 'scripts/fixtures/agent-decks', f), 'utf8'))).slides.forEach((s, i) => add(`${f}/${i}`, s))
+}
+
+// hostile / edge, in the gate rigs' shapes
+const el = (p: Record<string, unknown>) => ({ id: 'e', ...box, ...p })
+const hostile: Record<string, unknown>[] = [
+ el({ type: 'text', html: 'h', bogus: 1, onclick: 'alert(1)' }),
+ el({ type: 'text', html: 'h', fontSize: 'big', opacity: 2, rotation: 'x' }),
+ el({ type: 'text', html: 'h', colorGradient: { angle: 90 } }),
+ el({ type: 'text', html: 'h', shadow: { x: 1, y: 1 } }),
+ el({ type: 'text', html: 'h', fx: { enter: 'fade', step: -1, loop: { kind: 'nope' } } }),
+ el({ type: 'text', html: 'h', link: 'javascript:alert(1)' }),
+ el({ type: 'text', html: 'h', link: 'https://example.com', themeRefs: { color: 'accent2' } }),
+ el({ type: 'text', html: 'h', themeRefs: { color: 'not-a-slot' } }),
+ el({ type: 'text' }),
+ el({ type: 'shape', shape: 'rect', fill: 'url(https://evil/x.png)', stroke: 'red; }' }),
+ el({ type: 'shape', shape: 'arrow', heads: 2 }),
+ el({ type: 'shape', shape: 'arrow2' }),
+ el({ type: 'shape', shape: 'line', lineEnd: 'diamond-open', lineStart: 'nope' }),
+ el({ type: 'shape', shape: 'path', d: 'M0 0 L10 10 <script>' }),
+ el({ type: 'shape', shape: 'line', from: { el: 'a', side: 'top' }, to: { el: 'b', side: 'sideways' } }),
+ el({ type: 'image', src: 'javascript:alert(1)' }),
+ el({ type: 'image', src: 'http://example.com/a.png', crop: { x: 2, y: 0, scale: 0.5 } }),
+ el({ type: 'image', src: 'data:image/png;base64,AAAA', crop: { x: 0.5, y: 0.5, scale: 2 }, keepAspectRatio: false }),
+ el({ type: 'image', src: 'asset:k', fit: 'stretch' }),
+ el({ type: 'media', kind: 'video', src: 'https://example.com/v.mp4', autoplay: 'yes' }),
+ el({ type: 'media', kind: 'radio', src: 'asset:m' }),
+ el({ type: 'table', columns: [{ w: 1 }], rows: [{ cells: [{ html: 'a', bg: 'url(x)' }] }] }),
+ el({ type: 'table', columns: [{ w: 1 }], rows: [{ cells: [{ html: 'a' }] }, { cells: 'nope' }] }),
+ el({ type: 'table', columns: [], rows: [] }),
+ el({ type: 'chart', option: { series: [{ type: 'bar', data: [1, 2] }], tooltip: { formatter: 'function(){}' } } }),
+ el({ type: 'chart', option: 'not an object' }),
+ el({ type: 'code', content: 'x', grammarName: 'javascript', themeAssetId: '../x' }),
+ el({ type: 'svg', asset: 'k', markup: '<svg onload=alert(1)>' }),
+ el({ type: 'embed', doc: { format: 'bento/dash', slides: [] } }),
+ el({ type: 'embed', doc: 'https://example.com' }),
+ el({ type: 'sparkle' }),
+ el({ type: 5 }),
+ { type: 'text', ...box, html: 'no id' },
+ { type: 'text', id: '', ...box, html: 'empty id' },
+ { ['__proto__']: { polluted: true }, type: 'text', id: 'p', ...box, html: 'x' },
+ 'not an object',
+ null,
+]
+const slideCases: Array<[string, unknown]> = [
+ ['plain', { id: 's', elements: hostile }],
+ ['gradient background', { id: 'sl', background: 'linear-gradient(180deg, rgba(15,20,27,1) 0%, rgba(30,42,58,1) 100%)', elements: [] }],
+ ['url background', { id: 'sl', background: 'url(https://evil.example/beacon.png)', elements: [] }],
+ ['unknown slide keys', { id: 'sl', elements: [], bogus: 1, transition: 'spin', hover: { type: 'reveal' }, hidden: 'yes', unnumbered: true }],
+ ['comments', { id: 'sl', elements: [], comments: [{ id: 'c', author: 'a', text: 't', at: 'now', replies: [{ id: 'r', author: 'b', text: 'u', at: 'now' }] }, { id: 'bad' }] }],
+ ['half hover', { id: 'sl', elements: [], hover: { dim: 0.5 } }],
+ ['no id', { elements: [] }],
+ ['elements not a list', { id: 'sl', elements: 'nope' }],
+ ['too many elements', { id: 'sl', elements: Array.from({ length: 5000 }, (_, i) => el({ id: `e${i}`, type: 'text', html: 'x' })) }],
+ ['not an object', 42],
+]
+for (const [n, s] of slideCases) add(`hostile/${n}`, s)
+
+// ---- compare -----------------------------------------------------------------
+const j = (v: unknown) => JSON.stringify(v === undefined ? null : v)
+let same = 0, elementsCompared = 0
+for (const [name, slide] of slides) {
+ const a = j(branchGate.sanitizeSlide(slide))
+ const b = j(mainGate.sanitizeSlide(slide))
+ if (a === b) same++
+ else ok(false, `slide ${name}: branch and main disagree\n branch: ${a.slice(0, 300)}\n main: ${b.slice(0, 300)}`)
+ const els = (slide as { elements?: unknown }).elements
+ if (Array.isArray(els)) for (const e of els) {
+ elementsCompared++
+ const ea = j(branchGate.sanitizeElement(e)), eb = j(mainGate.sanitizeElement(e))
+ if (ea !== eb) ok(false, `element in ${name}: branch and main disagree\n branch: ${ea.slice(0, 300)}\n main: ${eb.slice(0, 300)}`)
+ }
+}
+ok(same === slides.length, `${same}/${slides.length} slide fixtures byte-identical through both gates (${elementsCompared} elements compared individually)`)
+ok(slides.length >= 45 && elementsCompared >= 250, `fixture count: ${slides.length} slides, ${elementsCompared} elements`)
+// ---- and with the collector ON: the report may differ, the DOCUMENT must not
+const { withDropReport } = branchGate as unknown as { withDropReport: <T>(fn: () => T) => { result: T; dropped: Array<{ path: string }> } }
+let sameOn = 0, elementsOn = 0, drops = 0
+for (const [name, slide] of slides) {
+ const { result, dropped } = withDropReport(() => branchGate.sanitizeSlide(slide))
+ drops += dropped.length
+ if (j(result) === j(mainGate.sanitizeSlide(slide))) sameOn++
+ else ok(false, `slide ${name}: with the collector ON the branch's document differs from main's`)
+ const els = (slide as { elements?: unknown }).elements
+ if (Array.isArray(els)) for (const e of els) {
+ elementsOn++
+ const on = withDropReport(() => branchGate.sanitizeElement(e)).result
+ if (j(on) !== j(mainGate.sanitizeElement(e))) ok(false, `element in ${name}: with the collector ON the branch's element differs from main's`)
+ }
+}
+ok(sameOn === slides.length, `collector ON: ${sameOn}/${slides.length} slide fixtures still byte-identical to main (${elementsOn} elements individually); ${drops} drops reported along the way`)
+ok(drops > 50, 'the report is not empty — the hook observed; it did not decide')
+// nesting: an inner report must not truncate the outer one's paths
+const nested = withDropReport(() => {
+ branchGate.sanitizeSlide({ id: 'outer', elements: [{ type: 'text', id: 'a', ...box, html: 'x', bogus: 1 }] })
+ const inner = withDropReport(() => branchGate.sanitizeSlide({ id: 'inner', elements: [{ type: 'text', id: 'b', ...box, html: 'x', bogus2: 1 }] }))
+ branchGate.sanitizeSlide({ id: 'outer2', elements: [{ type: 'text', id: 'c', ...box, html: 'x', bogus3: 1 }] })
+ return inner
+})
+ok(nested.result.dropped.length === 1 && nested.result.dropped[0].path === '/elements/0/bogus2', 'a nested report sees only its own drops with a fresh trail')
+ok(nested.dropped.length === 2 && nested.dropped.every((d) => /^\/elements\/0\/bogus3?$/.test(d.path)), `the outer report keeps its own two drops with intact paths after the inner one (${nested.dropped.map((d) => d.path).join(', ')})`)
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-slides-agent-decks.ts b/scripts/test-slides-agent-decks.ts
new file mode 100644
index 00000000..dce04c91
--- /dev/null
+++ b/scripts/test-slides-agent-decks.ts
@@ -0,0 +1,78 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Agent-deck corpus: compact decks written the way agents write them
+// (scripts/fixtures/agent-decks/*.json) must load clean — through the real
+// loader (compactload.ts: expand → gate → parseDoc → validate) — with zero
+// dropped keys and zero validate() errors. A change to a default, the gate or
+// the expansion that breaks the agent path fails here, not in someone's
+// harness. esbuild-bundled in CI (the loader pulls the gate and validate).
+//
+// slides/node_modules/.bin/esbuild scripts/test-slides-agent-decks.ts --bundle --platform=node --format=esm --outfile=/tmp/x.mjs && node /tmp/x.mjs
+//
+// No DOM here: fit-to-text is skipped (fit=false) and validate() runs its
+// unmeasured checks; the browser half (heights) is measured in Chrome and
+// stated in the PR that lands each change to compactload.ts.
+
+import { readFileSync, readdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { parseDocInputReport } from '../slides/src/compactload.ts'
+import { isCompact, provisionalHeight } from '../slides/src/compact.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+// bundled: the bundle lives elsewhere, so the repo root is the cwd (CI runs from it)
+const root = process.cwd()
+const dir = join(root, 'scripts/fixtures/agent-decks')
+const files = readdirSync(dir).filter((f) => f.endsWith('.json')).sort()
+ok(files.length >= 3, `${files.length} agent decks in the corpus`)
+
+for (const f of files) {
+ console.log(`\n${f}\n`)
+ const json = readFileSync(join(dir, f), 'utf8')
+ const raw = JSON.parse(json)
+ ok(isCompact(raw), 'is a compact document')
+ const parsed = parseDocInputReport(json, false)
+ ok(!!parsed, 'loads')
+ if (!parsed) continue
+ const { doc, report } = parsed
+ ok(report.compact && report.dropped.length === 0, `zero dropped keys${report.dropped.length ? ': ' + report.dropped.map((d) => `${d.path} (${d.reason})`).join('; ') : ''}`)
+ ok(report.expanded > 0, `${report.expanded} fields expanded`)
+ const errors = report.findings.findings.filter((x) => x.severity === 'error')
+ ok(errors.length === 0, `validate(): zero errors${errors.length ? ': ' + errors.map((e) => e.message).join('; ') : ''}`)
+ const warnings = report.findings.findings.filter((x) => x.severity === 'warning')
+ if (warnings.length) console.log(` (${warnings.length} warning(s): ${warnings.map((w) => w.code ?? w.message).join(', ')})`)
+ const els = doc.slides.flatMap((s) => s.elements)
+ ok(els.every((e) => typeof e.id === 'string' && e.id), 'every element has an id')
+ ok(new Set(els.map((e) => e.id)).size === els.length || doc.slides.every((s) => new Set(s.elements.map((e) => e.id)).size === s.elements.length), 'ids are unique within each slide')
+ ok(els.every((e) => e.type !== 'text' || typeof (e as { html?: unknown }).html === 'string'), 'every text element has html (md converted)')
+ ok(els.every((e) => !('md' in e)), 'no md reaches the document')
+ // provisional heights are present where h was omitted (the browser fits them)
+ const auto = raw.slides.flatMap((s: { elements?: unknown[] }) => (s.elements ?? []).flat(Infinity)).filter((e: { type?: string; h?: unknown }) => e.type === 'text' && (e.h === undefined || e.h === 'auto')).length
+ ok(report.fitted === 0 && report.refit.length === 0, 'without a DOM nothing is fitted (fit=false) and nothing is queued')
+ if (auto) ok(els.some((e) => e.type === 'text' && e.h === provisionalHeight(Number((e as { fontSize?: number }).fontSize) || 24, Number((e as { lineHeight?: number }).lineHeight) || 1.2)), `${auto} text element(s) carry a provisional one-line height`)
+}
+
+console.log('\nthe report on a deliberately wrong deck\n')
+{
+ const bad = JSON.stringify({ compact: true, slides: [{ elements: [
+ { type: 'text', x: 0, y: 0, w: 100, h: 20, html: 'x', bogus: 1, onclick: 'alert(1)', fontSize: 'big' },
+ { type: 'sparkle', x: 0, y: 0, w: 1, h: 1 },
+ ] }] })
+ const parsed = parseDocInputReport(bad, false)
+ ok(!!parsed, 'a deck with mistakes still loads (the gate drops, it does not refuse)')
+ const paths = parsed?.report.dropped.map((d) => d.path) ?? []
+ ok(paths.includes('/slides/0/elements/0/bogus'), `bogus key reported at its path (${paths.join(', ')})`)
+ ok(paths.includes('/slides/0/elements/0/onclick'), 'onclick reported at its path')
+ ok(parsed?.report.dropped.some((d) => d.path === '/slides/0/elements/0/fontSize' && d.reason === 'invalid value'), 'an invalid value is reported as such')
+ ok(parsed?.report.dropped.some((d) => d.path === '/slides/0/elements/1/type' && /unknown element type/.test(d.reason)), 'an unknown element type is reported and the element dropped')
+ ok(parsed?.doc.slides[0].elements.length === 1, 'the good element survives, the unknown one is gone')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-slides-compact.ts b/scripts/test-slides-compact.ts
index de6211f4..82b30ba8 100644
--- a/scripts/test-slides-compact.ts
+++ b/scripts/test-slides-compact.ts
@@ -22,7 +22,8 @@
import { readFileSync, readdirSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
-import { compactDoc, expandDoc, isCompact, compactJson, COMPACT_FLAG } from '../slides/src/compact.ts'
+import { compactDoc, expandDoc, expandDocWithStats, provisionalHeight, isCompact, compactJson, COMPACT_FLAG } from '../slides/src/compact.ts'
+import { markdownToHtml } from '../slides/src/editor/markdown.ts'
import { starterDoc } from '../slides/src/starterdeck.ts'
import { defaultText, defaultShape, defaultTable, defaultCode, readableInk, FONT_STACK, newDoc, isLightBg, type BentoDoc, type TextElement, type ShapeElement, type TableElement } from '../slides/src/model.ts'
@@ -153,18 +154,54 @@ ok(((mc.slides as Obj[])[0].elements as Obj[]).every((e) => e.type !== 'text' ||
console.log('\nthe gated loader and the surfaces\n')
const loader = read('slides/src/compactload.ts')
-ok(/import \{ sanitizeSlide \} from '\.\/untrusted'/.test(loader) && /map\(sanitizeSlide\)/.test(loader) && /return parseDoc\(JSON\.stringify\(expanded\)\)/.test(loader), 'compactload.ts expands, runs sanitizeSlide on every slide, then parseDoc — the gate is the single point of validation')
-ok(/if \(!isCompact\(raw\)\) return parseDoc\(json\)/.test(loader), 'a full document takes the plain parseDoc path, as today')
+ok(/import \{ sanitizeSlide, withDropReport, withPathSegment[^}]*\} from '\.\/untrusted'/.test(loader) && /=> sanitizeSlide\(s\)/.test(loader) && /const doc = parseDoc\(JSON\.stringify\(ex\)\)/.test(loader), 'compactload.ts expands, runs sanitizeSlide on every slide (collecting drops), then parseDoc — the gate is the single point of validation')
+ok(/if \(!isCompact\(raw\)\) \{\s*const doc = parseDoc\(json\)/.test(loader), 'a full document takes the plain parseDoc path, as today')
const main = read('slides/src/main.ts')
-ok(/const next = parseDocInput\(json\)/.test(main) && /compact: \(\) => compactJson\(store\.doc\)/.test(main), 'window.bento.loadDoc accepts compact input and window.bento.compact() emits it')
+ok(/const parsed = parseDocInputReport\(json\)/.test(main) && /return parsed\.report/.test(main) && /compact: \(\) => compactJson\(store\.doc\)/.test(main), 'window.bento.loadDoc accepts compact input and returns the load report; window.bento.compact() emits compact JSON')
ok(/return serializeFile\(store\.doc\)/.test(main), 'window.bento.serialize() is unchanged — the file is full')
const editor = read('slides/src/editor/editor.ts')
-ok(/const next = parseDocInput\(ta\.value\)/.test(editor), 'Replace from JSON… accepts compact input')
+ok(/const parsed = parseDocInputReport\(ta\.value\)/.test(editor) && /Loaded: \{dropped\} fields dropped, \{warnings\} warnings — see console/.test(editor), 'Replace from JSON… accepts compact input and summarises the report in a toast')
ok(/t\('Copy compact JSON \(for agents\)'\)/.test(editor) && /this\.copyDocJson\(true\)/.test(editor) && /compact \? compactJson\(clone\)/.test(editor), 'the Save menu has Copy compact JSON, wired to compactJson')
ok(!/compact/i.test(read('slides/src/save.ts')) && !/compactDoc|compactJson/.test(read('slides/src/model.ts')), 'save.ts and model.ts know nothing of compaction — the on-disk file cannot be compact')
ok(!/compact/.test(read('slides/src/modelkeys.generated.ts')), 'no model key named compact — the flag is input, never stored')
ok(/compact/.test(read('AGENTS.md')), 'AGENTS.md tells agents about the compact form')
+console.log('\nround two: md, auto height, the report\n')
+{
+ const mk = (el: Obj) => ({ compact: true, slides: [{ id: 's1', elements: [el] }] })
+ const one = (d: unknown) => (expandDoc(d).slides[0].elements[0] as unknown as Obj)
+ // md → the editor's paste conversion, byte for byte
+ const md = '**Bold** and *it*\n- one\n - two'
+ ok(one(mk({ type: 'text', x: 0, y: 0, w: 400, h: 100, md })).html === markdownToHtml(md), 'md converts through markdownToHtml — the same html a paste produces')
+ ok(!('md' in one(mk({ type: 'text', x: 0, y: 0, w: 400, h: 100, md }))), 'md never reaches the document')
+ const both = one(mk({ type: 'text', x: 0, y: 0, w: 400, h: 100, md, html: '<b>kept</b>' }))
+ ok(both.html === '<b>kept</b>' && !('md' in both), 'html wins when both are present; md is dropped')
+ ok(one(mk({ type: 'shape', shape: 'rect', x: 0, y: 0, w: 10, h: 10, md })).md === md, 'md on a non-text element is left to the gate (which drops it as unknown)')
+ // h omitted / "auto" → a provisional one-line height, listed for the browser
+ const r1 = expandDocWithStats(mk({ type: 'text', x: 0, y: 0, w: 400, html: 'hi', fontSize: 30, lineHeight: 1.5 }))
+ const e1 = r1.doc.slides[0].elements[0] as unknown as Obj
+ ok(e1.h === provisionalHeight(30, 1.5) && e1.h === 45, `omitted h → provisional one line (${e1.h} = 30 × 1.5)`)
+ ok(r1.stats.autoHeight.length === 1 && r1.stats.autoHeight[0].id === e1.id && r1.stats.autoHeight[0].slide === 's1', 'the element is listed for fitting, by slide and id')
+ const r2 = expandDocWithStats(mk({ type: 'text', x: 0, y: 0, w: 400, h: 'auto', html: 'hi' }))
+ const e2 = r2.doc.slides[0].elements[0] as unknown as Obj
+ ok(typeof e2.h === 'number' && r2.stats.autoHeight.length === 1, 'h: "auto" is the same request as omitting h')
+ const r3 = expandDocWithStats(mk({ type: 'text', x: 0, y: 0, w: 400, h: 120, html: 'hi' }))
+ ok((r3.doc.slides[0].elements[0] as unknown as Obj).h === 120 && r3.stats.autoHeight.length === 0, 'a given h is kept and not listed')
+ const r4 = expandDocWithStats(mk({ type: 'table', x: 0, y: 0, w: 400, columns: [{ w: 1 }], rows: [{ cells: [{ html: 'a' }] }] }))
+ ok(r4.stats.autoHeight.length === 0, 'tables are never auto-fitted (their height follows their rows)')
+ // the stats
+ const r5 = expandDocWithStats({ compact: true, slides: [{ elements: [[{ type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'a' }, { type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'b' }]] }] })
+ ok(r5.stats.minted === 2 && r5.stats.expanded > 20 && r5.stats.fromMarkdown === 0, `stats: 2 ids minted, ${r5.stats.expanded} fields expanded, 0 from markdown`)
+ ok(expandDocWithStats({ format: 'x', slides: [] }).stats.expanded === 0, 'a full document reports nothing expanded')
+ // the report shape on the browser side, by source
+ ok(/export interface LoadReport/.test(loader) && /dropped: Dropped\[\]/.test(loader) && /expanded: number/.test(loader) && /findings: ValidateResult/.test(loader) && /refit: ExpandStats\['autoHeight'\]/.test(loader), 'LoadReport carries dropped, expanded, fitted, findings and refit')
+ ok(/fitAutoHeights\(doc, stats\)/.test(loader) && /measureElement\(tx, doc\)/.test(loader), 'compactload fits every provisional height with measureElement — the panel button\'s measurement')
+ ok(/document\.fonts\.ready\.then/.test(main) && /fitAutoHeights\(store\.doc, \{ autoHeight: parsed\.report\.refit \}\)/.test(main), 'loadDoc re-fits after document.fonts.ready when fonts were still loading')
+ const gate = read('slides/src/untrusted.ts')
+ ok(/export function withDropReport/.test(gate) && /if \(!collector\) return$/m.test(gate), 'the gate collects drops only under withDropReport — one null check otherwise')
+ ok(/note\(key, 'unknown key'\)/.test(gate) && /note\(key, `unknown key for a \$\{type\} element`\)/.test(gate) && /note\(key, 'invalid value'\)/.test(gate), 'unknown keys and invalid values are reported with a reason')
+}
+
console.log('\nwhat the editor dereferences on first render\n')
{
// parseDoc checks only format and a non-empty slides array; render.ts reads
diff --git a/slides/src/compact.ts b/slides/src/compact.ts
index d9a0ffa8..60d6336c 100644
--- a/slides/src/compact.ts
+++ b/slides/src/compact.ts
@@ -27,6 +27,21 @@
* slides still works when the author repeats an id on purpose, and a
* round-trip through the editor never changes an id it did not mint.
*
+ * Round two, still compact-input only (the saved file is unchanged):
+ *
+ * - A text element may OMIT `h`, or say `h: "auto"`: the box is sized to
+ * its text — the same measurement the panel's "Fit height to text" makes,
+ * on the deck's real fonts. An agent cannot know how tall three lines of
+ * 24 pt Inter at 800 px are; the runtime can. Measuring needs the DOM, so
+ * this module (pure, node-importable) writes a PROVISIONAL one-line h and
+ * lists the element in `autoHeight`; compactload.ts (browser) measures and
+ * writes the real number before the document reaches the store.
+ * - A text element may carry `md` instead of `html`: markdown, converted by
+ * the SAME function the editor uses for pasted plain text
+ * (editor/markdown.ts markdownToHtml — bold, italic, code, strike, bullets
+ * and indented sub-bullets, [caption](url)). When both are present `html`
+ * wins and `md` is dropped; `md` never reaches the document.
+ *
* Defaults come from the SAME functions model.ts's editor paths use
* (defaultText, defaultShape, …), never a second table — a second table is
* what drifts. Where the editor derives a value from the deck (text colour
@@ -40,6 +55,7 @@
* touches save, so no shipped shell ever meets a compact document.
*/
+import { markdownToHtml } from './editor/markdown.ts'
import {
FORMAT, FORMAT_VERSION, FONT_STACK,
defaultText, defaultShape, defaultImage, defaultChart, defaultCode, defaultTable, defaultMedia,
@@ -171,6 +187,19 @@ const usableDocField = (k: string, v: unknown, dd: Obj): boolean =>
/** Is this JSON a compact document? The flag decides; nothing is inferred. */
export const isCompact = (doc: unknown): boolean => isObj(doc) && doc[COMPACT_FLAG] === true
+/** What expansion did, for the load report. `autoHeight` names the text
+ * elements (slide id + element id) whose `h` is provisional. */
+export interface ExpandStats {
+ /** fields filled in from defaults (doc, slide and element level) */
+ expanded: number
+ /** ids minted for elements that had none */
+ minted: number
+ /** text elements converted from `md` */
+ fromMarkdown: number
+ /** text elements whose h is provisional — the browser measures these */
+ autoHeight: Array<{ slide: string; id: string }>
+}
+
/**
* Fill every omitted field, flatten nested element arrays, mint missing ids.
* Pure; returns a new object. A document without the flag is returned as is
@@ -178,7 +207,18 @@ export const isCompact = (doc: unknown): boolean => isObj(doc) && doc[COMPACT_FL
* `s${n}` (1-based); elements without one get `${slideId}-${type}-${index}`.
*/
export function expandDoc(input: unknown): BentoDoc {
- if (!isCompact(input)) return input as BentoDoc
+ return expandDocWithStats(input).doc
+}
+
+/** One line of the text at its font size — the provisional `h` for a text
+ * element that asked to be fitted (compactload.ts replaces it). */
+export const provisionalHeight = (fontSize: number, lineHeight: number): number =>
+ Math.ceil(fontSize * lineHeight)
+
+/** expandDoc, and what it did. */
+export function expandDocWithStats(input: unknown): { doc: BentoDoc; stats: ExpandStats } {
+ const stats: ExpandStats = { expanded: 0, minted: 0, fromMarkdown: 0, autoHeight: [] }
+ if (!isCompact(input)) return { doc: input as BentoDoc, stats }
const src = input as Obj
const dd = docDefaults()
const doc: Obj = { ...dd, ...src }
@@ -191,14 +231,16 @@ export function expandDoc(input: unknown): BentoDoc {
// missing one is the default; so is one of the wrong shape (`size: null`,
// `title: 3`): an author who wrote that meant "I don't care", not "break".
for (const k of Object.keys(dd)) {
- if (!(k in src) || !usableDocField(k, src[k], dd)) doc[k] = dd[k]
+ if (!(k in src) || !usableDocField(k, src[k], dd)) { doc[k] = dd[k]; stats.expanded++ }
}
doc.theme = { ...(dd.theme as Obj), ...(isObj(src.theme) ? src.theme : {}) }
- for (const k of Object.keys(dd.theme as Obj)) if (typeof (doc.theme as Obj)[k] !== 'string') (doc.theme as Obj)[k] = (dd.theme as Obj)[k]
+ for (const k of Object.keys(dd.theme as Obj)) if (typeof (doc.theme as Obj)[k] !== 'string') { (doc.theme as Obj)[k] = (dd.theme as Obj)[k]; stats.expanded++ }
const slidesIn = Array.isArray(src.slides) ? (src.slides as unknown[]) : []
doc.slides = slidesIn.map((raw, si) => {
const s0 = isObj(raw) ? raw : {}
- const slide: Obj = { ...slideDefaults(doc), ...s0 }
+ const sd = slideDefaults(doc)
+ const slide: Obj = { ...sd, ...s0 }
+ stats.expanded += Object.keys(sd).filter((k) => !(k in s0)).length
if (typeof slide.id !== 'string' || !slide.id) slide.id = `s${si + 1}`
const flat: Obj[] = []
const walk = (v: unknown) => { if (Array.isArray(v)) v.forEach(walk); else if (isObj(v)) flat.push(v) }
@@ -206,12 +248,25 @@ export function expandDoc(input: unknown): BentoDoc {
slide.elements = flat.map((el, i) => {
const defaults = elementDefaults(el, slide, doc) ?? {}
const out: Obj = { ...defaults, ...el }
- if (typeof out.id !== 'string' || !out.id) out.id = mintId(slide, el, i)
+ stats.expanded += Object.keys(defaults).filter((k) => !(k in el)).length
+ if (typeof out.id !== 'string' || !out.id) { out.id = mintId(slide, el, i); stats.minted++ }
+ if (el.type === 'text') {
+ // md → html by the editor's own paste conversion; html wins when both
+ if (typeof el.md === 'string') {
+ if (typeof el.html !== 'string') { out.html = markdownToHtml(el.md); stats.fromMarkdown++ }
+ delete out.md
+ }
+ // h omitted or "auto": provisional one line; the browser fits it
+ if (el.h === undefined || el.h === 'auto') {
+ out.h = provisionalHeight(Number(out.fontSize) || 24, Number(out.lineHeight) || 1.2)
+ stats.autoHeight.push({ slide: slide.id as string, id: out.id as string })
+ }
+ }
return out as unknown as SlideElement
})
return slide as unknown as Slide
})
- return doc as unknown as BentoDoc
+ return { doc: doc as unknown as BentoDoc, stats }
}
/** The font stack expansion assumes for text — exported so the rig can state
diff --git a/slides/src/compactload.ts b/slides/src/compactload.ts
index 2c7f658d..213ff183 100644
--- a/slides/src/compactload.ts
+++ b/slides/src/compactload.ts
@@ -2,7 +2,8 @@
// Copyright (c) 2026 The Bento authors
// The agent entry point for a document that may be compact (src/compact.ts).
// Kept apart from compact.ts so that module stays node-importable for the rig
-// and the measure script: this one needs the untrusted gate, which is bundled.
+// and the measure script: this one needs the untrusted gate (bundled) and the
+// DOM (text measurement).
//
// parseDoc (model.ts) stays what it is — the file on disk is always full. A
// COMPACT document is authored by a tool, so it gets the untrusted shape gate
@@ -10,10 +11,38 @@
// meet): an unknown key or a malformed value is dropped rather than reaching
// the renderer. A full document is not gated here — that is today's
// behaviour and today's promise (your own file is yours).
+//
+// Round two adds the LOAD REPORT: what the gate dropped (path + reason), what
+// expansion filled, and validate()'s findings on the result — so an agent's
+// loop is load → read the report → fix → reload, instead of guessing why a
+// field vanished. And fit-to-text: a text element that omitted `h` arrives
+// from expandDoc with a provisional one-line height; here it is measured the
+// way the panel's "Fit height to text" measures (measureElement, the deck's
+// real fonts) and given its true height BEFORE the document reaches the store,
+// so undo never sees the provisional frame.
+
+import { parseDoc, type BentoDoc, type Slide, type TextElement } from './model'
+import { sanitizeSlide, withDropReport, withPathSegment, type Dropped } from './untrusted'
+import { expandDocWithStats, isCompact, type ExpandStats } from './compact'
+import { measureElement } from './measure'
+import { validateDoc, type ValidateResult } from './validate'
-import { parseDoc, type BentoDoc, type Slide } from './model'
-import { sanitizeSlide } from './untrusted'
-import { expandDoc, isCompact } from './compact'
+export interface LoadReport {
+ ok: true
+ /** was the input compact (expanded here) or full (taken as is)? */
+ compact: boolean
+ /** every key/value the gate discarded, with a JSON-pointer-ish path */
+ dropped: Dropped[]
+ /** fields expansion filled from the editor's defaults */
+ expanded: number
+ /** text elements whose h was fitted to their text */
+ fitted: number
+ /** validate() on the loaded document */
+ findings: ValidateResult
+ /** the elements still to re-fit once document.fonts settles (heights were
+ * measured against fallback fonts); empty when fonts were ready */
+ refit: ExpandStats['autoHeight']
+}
/**
* Parse document JSON that may be compact. Returns null on anything parseDoc
@@ -21,10 +50,53 @@ import { expandDoc, isCompact } from './compact'
* docId minting see a full document.
*/
export function parseDocInput(json: string): BentoDoc | null {
+ return parseDocInputReport(json)?.doc ?? null
+}
+
+/** parseDocInput, plus the report. `fit` runs the text measurement (browser
+ * only); it is skipped where there is no DOM. */
+export function parseDocInputReport(json: string, fit = typeof document !== 'undefined'): { doc: BentoDoc; report: LoadReport } | null {
let raw: unknown
try { raw = JSON.parse(json) } catch { return null }
- if (!isCompact(raw)) return parseDoc(json)
- const expanded = expandDoc(raw) as unknown as Record<string, unknown>
- expanded.slides = ((expanded.slides ?? []) as unknown[]).map(sanitizeSlide).filter((s): s is Slide => s !== null)
- return parseDoc(JSON.stringify(expanded))
+ if (!isCompact(raw)) {
+ const doc = parseDoc(json)
+ if (!doc) return null
+ return { doc, report: { ok: true, compact: false, dropped: [], expanded: 0, fitted: 0, findings: validateDoc(doc), refit: [] } }
+ }
+ const { doc: expanded, stats } = expandDocWithStats(raw)
+ const ex = expanded as unknown as Record<string, unknown>
+ // paths read /slides/3/elements/2/fontSize — the slide index is ours to add
+ const { result: slides, dropped } = withDropReport(() =>
+ ((ex.slides ?? []) as unknown[])
+ .map((s, i) => withPathSegment('slides', () => withPathSegment(String(i), () => sanitizeSlide(s))))
+ .filter((s): s is Slide => s !== null))
+ ex.slides = slides
+ const doc = parseDoc(JSON.stringify(ex))
+ if (!doc) return null
+ let fitted = 0
+ let refit: ExpandStats['autoHeight'] = []
+ if (fit && stats.autoHeight.length) {
+ fitted = fitAutoHeights(doc, stats)
+ if (document.fonts?.status === 'loading') refit = stats.autoHeight
+ }
+ return { doc, report: { ok: true, compact: true, dropped, expanded: stats.expanded, fitted, findings: validateDoc(doc), refit } }
+}
+
+/**
+ * Give every provisional text height its measured value. Returns how many
+ * were written. Exported so the fonts-ready re-fit (main.ts) and the rig can
+ * call it on a loaded document.
+ */
+export function fitAutoHeights(doc: BentoDoc, stats: Pick<ExpandStats, 'autoHeight'>): number {
+ let n = 0
+ for (const { slide: sid, id } of stats.autoHeight) {
+ const slide = doc.slides.find((s) => s.id === sid)
+ const el = slide?.elements.find((e) => e.id === id)
+ if (!el || el.type !== 'text') continue
+ const tx = el as TextElement
+ if (!tx.html?.trim()) continue
+ const m = measureElement(tx, doc)
+ if (m.height > 0 && m.height !== tx.h) { tx.h = m.height; n++ }
+ }
+ return n
}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 366372cb..07880448 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -41,7 +41,7 @@ import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, mintRoomKey, onl
import { projectDoc, projectOp, type AudienceTicket } from '../audience'
import { stripEmbeddedEnvelopes } from '../envelope'
import { compactJson } from '../compact'
-import { parseDocInput } from '../compactload'
+import { parseDocInputReport } from '../compactload'
import { lsGet, lsJson, lsSet } from '../../../kernel/src/storage.ts'
import { shrinkImageFile, shrinkEnabled, setShrinkEnabled, shrinkNote, type ShrinkResult } from './shrink'
@@ -1139,13 +1139,21 @@ export class Editor {
// either wipe the user's room credentials (paste of our own JSON) or
// silently move the deck into a room that came from somewhere else.
// Content is imported; identity and capability are not.
- const next = parseDocInput(ta.value) // full or compact (src/compact.ts)
- if (next) {
+ const parsed = parseDocInputReport(ta.value) // full or compact (src/compact.ts)
+ if (parsed) {
+ const next = parsed.doc
const keep = this.store.doc.collab
if (keep) next.collab = keep
else delete next.collab
this.store.replaceDoc(next)
- this.toast(t('Document replaced — ⌘Z undoes'))
+ // the load report, summarised; the whole thing goes to the console
+ // where an agent driving the page (or a person) can read the paths
+ const r = parsed.report
+ const warnings = r.findings.counts.warning + r.findings.counts.error
+ if (r.dropped.length || warnings) {
+ console.info('[bento] load report', r)
+ this.toast(t('Loaded: {dropped} fields dropped, {warnings} warnings — see console', { dropped: String(r.dropped.length), warnings: String(warnings) }))
+ } else this.toast(t('Document replaced — ⌘Z undoes'))
overlay.remove()
} else {
ta.style.borderColor = '#C0392B'
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 153e589b..07de8e01 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -922,4 +922,5 @@ export const de: Catalog = {
"Copy compact JSON (for agents)": "Kompaktes JSON kopieren (für Agenten)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Dasselbe Deck ohne alle Standardwerte — die Form, die ein KI-Agent schreiben sollte. „Aus JSON ersetzen“ nimmt es zurück; die gespeicherte Datei ist immer vollständig.",
"Compact JSON copied": "Kompaktes JSON kopiert",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Geladen: {dropped} Felder verworfen, {warnings} Warnungen — siehe Konsole",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index adfc84b5..27dd6624 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -922,4 +922,5 @@ export const es: Catalog = {
"Copy compact JSON (for agents)": "Copiar JSON compacto (para agentes)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "La misma presentación sin ningún valor predeterminado: la forma que debería escribir un agente de IA. «Reemplazar desde JSON» lo acepta; el archivo guardado siempre es completo.",
"Compact JSON copied": "JSON compacto copiado",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Cargado: {dropped} campos descartados, {warnings} avisos; consulta la consola",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index 3db35bce..54a5ea61 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -922,4 +922,5 @@ export const fr: Catalog = {
"Copy compact JSON (for agents)": "Copier le JSON compact (pour les agents)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "La même présentation sans aucune valeur par défaut : la forme qu’un agent IA devrait écrire. « Remplacer depuis JSON » la reprend ; le fichier enregistré est toujours complet.",
"Compact JSON copied": "JSON compact copié",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Chargé : {dropped} champs ignorés, {warnings} avertissements — voir la console",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index 69a357dc..38c32af7 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -922,4 +922,5 @@ export const it: Catalog = {
"Copy compact JSON (for agents)": "Copia JSON compatto (per gli agenti)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "La stessa presentazione senza alcun valore predefinito: la forma che un agente IA dovrebbe scrivere. «Sostituisci da JSON» la riprende; il file salvato è sempre completo.",
"Compact JSON copied": "JSON compatto copiato",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Caricato: {dropped} campi scartati, {warnings} avvisi — vedi la console",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index 74495752..ad618e9f 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -922,4 +922,5 @@ export const ja: Catalog = {
"Copy compact JSON (for agents)": "コンパクトな JSON をコピー(エージェント向け)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "既定値をすべて省いた同じデッキ。AI エージェントが書くべき形です。「JSON から置き換え」で戻せます。保存されるファイルは常に完全な形です。",
"Compact JSON copied": "コンパクトな JSON をコピーしました",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "読み込み完了: {dropped} 個のフィールドを破棄、警告 {warnings} 件 — コンソールを確認",
}
diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.ts
index eb07bde7..af1af331 100644
--- a/slides/src/i18n/packed.ts
+++ b/slides/src/i18n/packed.ts
@@ -928,4 +928,5 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Copy compact JSON (for agents)": ["コンパクトな JSON をコピー(エージェント向け)","复制精简 JSON(供智能体使用)","複製精簡 JSON(供代理程式使用)","Copiar JSON compacto (para agentes)","Copier le JSON compact (pour les agents)","Kompaktes JSON kopieren (für Agenten)","Copia JSON compatto (per gli agenti)","Copiar JSON compacto (para agentes)"],
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": ["既定値をすべて省いた同じデッキ。AI エージェントが書くべき形です。「JSON から置き換え」で戻せます。保存されるファイルは常に完全な形です。","同一份文稿,省去所有默认值——AI 智能体应当书写的形式。“从 JSON 替换”可读回它;保存的文件始终是完整的。","同一份文稿,省去所有預設值——AI 代理程式應當書寫的形式。「從 JSON 取代」可讀回它;儲存的檔案始終是完整的。","La misma presentación sin ningún valor predeterminado: la forma que debería escribir un agente de IA. «Reemplazar desde JSON» lo acepta; el archivo guardado siempre es completo.","La même présentation sans aucune valeur par défaut : la forme qu’un agent IA devrait écrire. « Remplacer depuis JSON » la reprend ; le fichier enregistré est toujours complet.","Dasselbe Deck ohne alle Standardwerte — die Form, die ein KI-Agent schreiben sollte. „Aus JSON ersetzen“ nimmt es zurück; die gespeicherte Datei ist immer vollständig.","La stessa presentazione senza alcun valore predefinito: la forma che un agente IA dovrebbe scrivere. «Sostituisci da JSON» la riprende; il file salvato è sempre completo.","A mesma apresentação sem nenhum valor predefinido: a forma que um agente de IA deve escrever. «Substituir a partir de JSON» aceita-a; o ficheiro guardado é sempre completo."],
"Compact JSON copied": ["コンパクトな JSON をコピーしました","已复制精简 JSON","已複製精簡 JSON","JSON compacto copiado","JSON compact copié","Kompaktes JSON kopiert","JSON compatto copiato","JSON compacto copiado"],
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": ["読み込み完了: {dropped} 個のフィールドを破棄、警告 {warnings} 件 — コンソールを確認","已加载:丢弃 {dropped} 个字段,{warnings} 条警告 — 见控制台","已載入:捨棄 {dropped} 個欄位,{warnings} 則警告 — 見主控台","Cargado: {dropped} campos descartados, {warnings} avisos; consulta la consola","Chargé : {dropped} champs ignorés, {warnings} avertissements — voir la console","Geladen: {dropped} Felder verworfen, {warnings} Warnungen — siehe Konsole","Caricato: {dropped} campi scartati, {warnings} avvisi — vedi la console","Carregado: {dropped} campos descartados, {warnings} avisos — ver a consola"],
}
diff --git a/slides/src/i18n/packs/ar.ts b/slides/src/i18n/packs/ar.ts
index 53d3204f..b8fb5cda 100644
--- a/slides/src/i18n/packs/ar.ts
+++ b/slides/src/i18n/packs/ar.ts
@@ -942,4 +942,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "نسخ JSON مضغوط (للوكلاء)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "العرض نفسه بدون أي قيمة افتراضية: الشكل الذي ينبغي لوكيل الذكاء الاصطناعي كتابته. «استبدال من JSON» يقبله؛ الملف المحفوظ كامل دائمًا.",
"Compact JSON copied": "تم نسخ JSON المضغوط",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "تم التحميل: {dropped} حقول مهملة، {warnings} تحذيرات — راجع وحدة التحكم",
}
diff --git a/slides/src/i18n/packs/bn.ts b/slides/src/i18n/packs/bn.ts
index 254dfaa2..5765690f 100644
--- a/slides/src/i18n/packs/bn.ts
+++ b/slides/src/i18n/packs/bn.ts
@@ -945,4 +945,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "সংক্ষিপ্ত JSON কপি করুন (এজেন্টের জন্য)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "সব ডিফল্ট বাদ দেওয়া একই ডেক — একটি AI এজেন্টের যেভাবে লেখা উচিত। “JSON থেকে প্রতিস্থাপন” এটি ফিরিয়ে নেয়; সংরক্ষিত ফাইল সবসময় পূর্ণ।",
"Compact JSON copied": "সংক্ষিপ্ত JSON কপি হয়েছে",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "লোড হয়েছে: {dropped}টি ফিল্ড বাদ, {warnings}টি সতর্কতা — কনসোল দেখুন",
}
diff --git a/slides/src/i18n/packs/da.ts b/slides/src/i18n/packs/da.ts
index e3c6f812..4e339abb 100644
--- a/slides/src/i18n/packs/da.ts
+++ b/slides/src/i18n/packs/da.ts
@@ -934,4 +934,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kopiér kompakt JSON (til agenter)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Samme dæk uden alle standardværdier — den form en AI-agent bør skrive. »Erstat fra JSON« tager den tilbage; den gemte fil er altid fuldstændig.",
"Compact JSON copied": "Kompakt JSON kopieret",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Indlæst: {dropped} felter udeladt, {warnings} advarsler — se konsollen",
}
diff --git a/slides/src/i18n/packs/fa.ts b/slides/src/i18n/packs/fa.ts
index f4bad922..9fceb6d1 100644
--- a/slides/src/i18n/packs/fa.ts
+++ b/slides/src/i18n/packs/fa.ts
@@ -938,4 +938,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "کپی JSON فشرده (برای عامل‌ها)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "همان دک بدون هیچ مقدار پیش‌فرض؛ شکلی که یک عامل هوش مصنوعی باید بنویسد. «جایگزینی از JSON» آن را می‌پذیرد؛ پروندهٔ ذخیره‌شده همیشه کامل است.",
"Compact JSON copied": "JSON فشرده کپی شد",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "بارگذاری شد: {dropped} فیلد حذف شد، {warnings} هشدار — کنسول را ببینید",
}
diff --git a/slides/src/i18n/packs/fi.ts b/slides/src/i18n/packs/fi.ts
index a4a985c5..638c6453 100644
--- a/slides/src/i18n/packs/fi.ts
+++ b/slides/src/i18n/packs/fi.ts
@@ -939,4 +939,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kopioi tiivis JSON (agenteille)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Sama pakka ilman oletusarvoja — muoto, jonka tekoälyagentin tulisi kirjoittaa. ”Korvaa JSON:sta” ottaa sen vastaan; tallennettu tiedosto on aina täydellinen.",
"Compact JSON copied": "Tiivis JSON kopioitu",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Ladattu: {dropped} kenttää hylätty, {warnings} varoitusta — katso konsoli",
}
diff --git a/slides/src/i18n/packs/fil.ts b/slides/src/i18n/packs/fil.ts
index 5485b6d0..f746d125 100644
--- a/slides/src/i18n/packs/fil.ts
+++ b/slides/src/i18n/packs/fil.ts
@@ -951,4 +951,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kopyahin ang compact na JSON (para sa mga agent)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Ang parehong deck na wala ang lahat ng default — ang anyong dapat isulat ng isang AI agent. Tinatanggap ito ng “Palitan mula sa JSON”; ang na-save na file ay laging buo.",
"Compact JSON copied": "Nakopya ang compact na JSON",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Na-load: {dropped} field ang inalis, {warnings} babala — tingnan ang console",
}
diff --git a/slides/src/i18n/packs/he.ts b/slides/src/i18n/packs/he.ts
index bda9f593..5931f2b4 100644
--- a/slides/src/i18n/packs/he.ts
+++ b/slides/src/i18n/packs/he.ts
@@ -935,4 +935,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "העתקת JSON קומפקטי (לסוכנים)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "אותה מצגת בלי ברירות המחדל — הצורה שסוכן AI צריך לכתוב. «החלפה מ-JSON» מקבלת אותה; הקובץ השמור תמיד מלא.",
"Compact JSON copied": "JSON קומפקטי הועתק",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "נטען: {dropped} שדות הושמטו, {warnings} אזהרות — ראו את הקונסולה",
}
diff --git a/slides/src/i18n/packs/hi.ts b/slides/src/i18n/packs/hi.ts
index 1ff28667..d7350990 100644
--- a/slides/src/i18n/packs/hi.ts
+++ b/slides/src/i18n/packs/hi.ts
@@ -942,4 +942,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "संक्षिप्त JSON कॉपी करें (एजेंट के लिए)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "वही डेक, हर डिफ़ॉल्ट हटाकर — वह रूप जो एक AI एजेंट को लिखना चाहिए। “JSON से बदलें” इसे वापस लेता है; सहेजी गई फ़ाइल हमेशा पूरी होती है।",
"Compact JSON copied": "संक्षिप्त JSON कॉपी हो गया",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "लोड हुआ: {dropped} फ़ील्ड हटाए गए, {warnings} चेतावनियाँ — कंसोल देखें",
}
diff --git a/slides/src/i18n/packs/id.ts b/slides/src/i18n/packs/id.ts
index 7f3f7b26..6aeec9ba 100644
--- a/slides/src/i18n/packs/id.ts
+++ b/slides/src/i18n/packs/id.ts
@@ -932,4 +932,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Salin JSON ringkas (untuk agen)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Dek yang sama tanpa semua nilai bawaan — bentuk yang seharusnya ditulis agen AI. “Ganti dari JSON” menerimanya kembali; berkas yang disimpan selalu lengkap.",
"Compact JSON copied": "JSON ringkas disalin",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Dimuat: {dropped} bidang dibuang, {warnings} peringatan — lihat konsol",
}
diff --git a/slides/src/i18n/packs/ko.ts b/slides/src/i18n/packs/ko.ts
index ec0546df..57d9452b 100644
--- a/slides/src/i18n/packs/ko.ts
+++ b/slides/src/i18n/packs/ko.ts
@@ -926,4 +926,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "간결한 JSON 복사 (에이전트용)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "모든 기본값을 뺀 같은 덱 — AI 에이전트가 작성해야 할 형태입니다. “JSON에서 바꾸기”로 되돌릴 수 있으며, 저장되는 파일은 항상 완전한 형태입니다.",
"Compact JSON copied": "간결한 JSON을 복사했습니다",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "불러옴: 필드 {dropped}개 삭제됨, 경고 {warnings}건 — 콘솔 참조",
}
diff --git a/slides/src/i18n/packs/ms.ts b/slides/src/i18n/packs/ms.ts
index 061f364a..2bcf0e7e 100644
--- a/slides/src/i18n/packs/ms.ts
+++ b/slides/src/i18n/packs/ms.ts
@@ -935,4 +935,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Salin JSON padat (untuk ejen)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Dek yang sama tanpa semua nilai lalai — bentuk yang patut ditulis oleh ejen AI. “Ganti daripada JSON” menerimanya semula; fail yang disimpan sentiasa lengkap.",
"Compact JSON copied": "JSON padat disalin",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Dimuatkan: {dropped} medan digugurkan, {warnings} amaran — lihat konsol",
}
diff --git a/slides/src/i18n/packs/nb.ts b/slides/src/i18n/packs/nb.ts
index 456385e9..ef3f4a7e 100644
--- a/slides/src/i18n/packs/nb.ts
+++ b/slides/src/i18n/packs/nb.ts
@@ -936,4 +936,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kopier kompakt JSON (for agenter)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Samme kortstokk uten alle standardverdier — formen en KI-agent bør skrive. «Erstatt fra JSON» tar den tilbake; den lagrede filen er alltid fullstendig.",
"Compact JSON copied": "Kompakt JSON kopiert",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Lastet: {dropped} felt forkastet, {warnings} advarsler — se konsollen",
}
diff --git a/slides/src/i18n/packs/nl.ts b/slides/src/i18n/packs/nl.ts
index bc07a7e4..c03f8a23 100644
--- a/slides/src/i18n/packs/nl.ts
+++ b/slides/src/i18n/packs/nl.ts
@@ -930,4 +930,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Compacte JSON kopiëren (voor agents)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Hetzelfde deck zonder alle standaardwaarden — de vorm die een AI-agent zou moeten schrijven. ‘Vervangen uit JSON’ neemt het terug; het opgeslagen bestand is altijd volledig.",
"Compact JSON copied": "Compacte JSON gekopieerd",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Geladen: {dropped} velden weggelaten, {warnings} waarschuwingen — zie de console",
}
diff --git a/slides/src/i18n/packs/pl.ts b/slides/src/i18n/packs/pl.ts
index 371a4399..1d29acf2 100644
--- a/slides/src/i18n/packs/pl.ts
+++ b/slides/src/i18n/packs/pl.ts
@@ -933,4 +933,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kopiuj zwięzły JSON (dla agentów)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Ta sama prezentacja bez wartości domyślnych — postać, którą powinien pisać agent AI. „Zastąp z JSON” przyjmuje ją z powrotem; zapisany plik jest zawsze pełny.",
"Compact JSON copied": "Skopiowano zwięzły JSON",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Wczytano: odrzucono {dropped} pól, {warnings} ostrzeżeń — zobacz konsolę",
}
diff --git a/slides/src/i18n/packs/ru.ts b/slides/src/i18n/packs/ru.ts
index 8dc8ec66..7c9dd8d7 100644
--- a/slides/src/i18n/packs/ru.ts
+++ b/slides/src/i18n/packs/ru.ts
@@ -934,4 +934,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Копировать компактный JSON (для агентов)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Та же презентация без значений по умолчанию — форма, которую должен писать ИИ-агент. «Заменить из JSON» принимает её обратно; сохранённый файл всегда полный.",
"Compact JSON copied": "Компактный JSON скопирован",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Загружено: отброшено полей: {dropped}, предупреждений: {warnings} — см. консоль",
}
diff --git a/slides/src/i18n/packs/sv.ts b/slides/src/i18n/packs/sv.ts
index 5bd438d5..e2a3d202 100644
--- a/slides/src/i18n/packs/sv.ts
+++ b/slides/src/i18n/packs/sv.ts
@@ -931,4 +931,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kopiera kompakt JSON (för agenter)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Samma presentation utan alla standardvärden — formen en AI-agent bör skriva. ”Ersätt från JSON” tar tillbaka den; den sparade filen är alltid fullständig.",
"Compact JSON copied": "Kompakt JSON kopierad",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Inläst: {dropped} fält bortfiltrerade, {warnings} varningar — se konsolen",
}
diff --git a/slides/src/i18n/packs/th.ts b/slides/src/i18n/packs/th.ts
index 32b69e63..b4ddcf16 100644
--- a/slides/src/i18n/packs/th.ts
+++ b/slides/src/i18n/packs/th.ts
@@ -936,4 +936,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "คัดลอก JSON แบบกระชับ (สำหรับเอเจนต์)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "เด็คเดียวกันโดยตัดค่าเริ่มต้นทั้งหมดออก คือรูปแบบที่เอเจนต์ AI ควรเขียน “แทนที่จาก JSON” รับกลับได้ ไฟล์ที่บันทึกจะสมบูรณ์เสมอ",
"Compact JSON copied": "คัดลอก JSON แบบกระชับแล้ว",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "โหลดแล้ว: ตัดฟิลด์ออก {dropped} รายการ, คำเตือน {warnings} รายการ — ดูคอนโซล",
}
diff --git a/slides/src/i18n/packs/tk.ts b/slides/src/i18n/packs/tk.ts
index 384908ff..ce7fa809 100644
--- a/slides/src/i18n/packs/tk.ts
+++ b/slides/src/i18n/packs/tk.ts
@@ -959,4 +959,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Ykjam JSON-y göçür (agentler üçin)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Ähli deslapky bahalary aýrylan şol bir toplum — AI agentiň ýazmaly görnüşi. «JSON-dan çalyş» ony yzyna alýar; ýatda saklanan faýl elmydama doly.",
"Compact JSON copied": "Ykjam JSON göçürildi",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Ýüklendi: {dropped} meýdan taşlandy, {warnings} duýduryş — konsola serediň",
}
diff --git a/slides/src/i18n/packs/tr.ts b/slides/src/i18n/packs/tr.ts
index e9e0a7ed..922c77b9 100644
--- a/slides/src/i18n/packs/tr.ts
+++ b/slides/src/i18n/packs/tr.ts
@@ -933,4 +933,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Kompakt JSON'u kopyala (ajanlar için)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Tüm varsayılanlar çıkarılmış aynı deste — bir yapay zekâ ajanının yazması gereken biçim. “JSON'dan değiştir” geri alır; kaydedilen dosya her zaman tamdır.",
"Compact JSON copied": "Kompakt JSON kopyalandı",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Yüklendi: {dropped} alan atıldı, {warnings} uyarı — konsola bakın",
}
diff --git a/slides/src/i18n/packs/uk.ts b/slides/src/i18n/packs/uk.ts
index 611e3326..6174ae4f 100644
--- a/slides/src/i18n/packs/uk.ts
+++ b/slides/src/i18n/packs/uk.ts
@@ -942,4 +942,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Копіювати компактний JSON (для агентів)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Та сама презентація без значень за замовчуванням — форма, яку має писати ШІ-агент. «Замінити з JSON» приймає її назад; збережений файл завжди повний.",
"Compact JSON copied": "Компактний JSON скопійовано",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Завантажено: відкинуто полів: {dropped}, попереджень: {warnings} — див. консоль",
}
diff --git a/slides/src/i18n/packs/ur.ts b/slides/src/i18n/packs/ur.ts
index 4a81725a..e0da7132 100644
--- a/slides/src/i18n/packs/ur.ts
+++ b/slides/src/i18n/packs/ur.ts
@@ -952,4 +952,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "کمپیکٹ JSON کاپی کریں (ایجنٹس کے لیے)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "وہی ڈیک، ہر ڈیفالٹ ہٹا کر — وہ شکل جو ایک AI ایجنٹ کو لکھنی چاہیے۔ “JSON سے بدلیں” اسے واپس لیتا ہے؛ محفوظ شدہ فائل ہمیشہ مکمل ہوتی ہے۔",
"Compact JSON copied": "کمپیکٹ JSON کاپی ہو گیا",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "لوڈ ہو گیا: {dropped} فیلڈز ہٹائے گئے، {warnings} انتباہات — کنسول دیکھیں",
}
diff --git a/slides/src/i18n/packs/vi.ts b/slides/src/i18n/packs/vi.ts
index 3381af6b..69849d16 100644
--- a/slides/src/i18n/packs/vi.ts
+++ b/slides/src/i18n/packs/vi.ts
@@ -932,4 +932,5 @@ export const strings: Catalog = {
"Copy compact JSON (for agents)": "Sao chép JSON gọn (cho tác tử)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Cùng bộ trang chiếu nhưng bỏ mọi giá trị mặc định: dạng mà một tác tử AI nên viết. “Thay thế từ JSON” nhận lại nó; tệp đã lưu luôn đầy đủ.",
"Compact JSON copied": "Đã sao chép JSON gọn",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Đã tải: bỏ {dropped} trường, {warnings} cảnh báo — xem console",
}
diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.ts
index 37ee06e6..37301e30 100644
--- a/slides/src/i18n/pt.ts
+++ b/slides/src/i18n/pt.ts
@@ -920,4 +920,5 @@ export const pt: Catalog = {
"Copy compact JSON (for agents)": "Copiar JSON compacto (para agentes)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "A mesma apresentação sem nenhum valor predefinido: a forma que um agente de IA deve escrever. «Substituir a partir de JSON» aceita-a; o ficheiro guardado é sempre completo.",
"Compact JSON copied": "JSON compacto copiado",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Carregado: {dropped} campos descartados, {warnings} avisos — ver a consola",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index c0c837a3..8aa898b4 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -922,4 +922,5 @@ export const zhHans: Catalog = {
"Copy compact JSON (for agents)": "复制精简 JSON(供智能体使用)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "同一份文稿,省去所有默认值——AI 智能体应当书写的形式。“从 JSON 替换”可读回它;保存的文件始终是完整的。",
"Compact JSON copied": "已复制精简 JSON",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "已加载:丢弃 {dropped} 个字段,{warnings} 条警告 — 见控制台",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index ee6d79fb..afa407d3 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -922,4 +922,5 @@ export const zhHant: Catalog = {
"Copy compact JSON (for agents)": "複製精簡 JSON(供代理程式使用)",
"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "同一份文稿,省去所有預設值——AI 代理程式應當書寫的形式。「從 JSON 取代」可讀回它;儲存的檔案始終是完整的。",
"Compact JSON copied": "已複製精簡 JSON",
+ "Loaded: {dropped} fields dropped, {warnings} warnings — see console": "已載入:捨棄 {dropped} 個欄位,{warnings} 則警告 — 見主控台",
}
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 4f576916..8a8bc586 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -19,7 +19,7 @@ import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './u
import { i18nApi, t, applyDirection } from './i18n'
import { parseDoc, type BentoDoc, type TextElement } from './model'
import { compactJson } from './compact'
-import { parseDocInput } from './compactload'
+import { parseDocInputReport, fitAutoHeights, type LoadReport } from './compactload'
import { validateDoc, type ValidateOpts } from './validate'
import { resolveThemeRefs } from './palette'
import { measureText, measureElement, type TextMeasureSpec } from './measure'
@@ -321,12 +321,29 @@ if (location.hash === '#present') {
* with defaults omitted, nested element arrays and missing ids allowed; see
* src/compact.ts). Validates via parseDoc; returns false and changes
* nothing on invalid input. Undoable in the editor.
+ *
+ * On success returns the LOAD REPORT (truthy, so `if (loadDoc(j))` still
+ * reads as before): `{ ok: true, compact, dropped: [{path, reason}],
+ * expanded, fitted, findings, refit }` — what the gate discarded and why,
+ * how many fields the compact expansion filled, how many text boxes were
+ * fitted to their text, and validate()'s findings on the loaded document.
+ * An agent's loop: load → read dropped/findings → fix → load again.
*/
- loadDoc(json: string): boolean {
- const next = parseDocInput(json)
- if (!next) return false
- store.replaceDoc(next)
- return true
+ loadDoc(json: string): LoadReport | false {
+ const parsed = parseDocInputReport(json)
+ if (!parsed) return false
+ store.replaceDoc(parsed.doc)
+ // Heights measured while a deck font was still downloading are measured
+ // against the fallback face. Once the fonts settle, fit those boxes
+ // again as one undoable step — the report says which they were.
+ if (parsed.report.refit.length) {
+ void document.fonts.ready.then(() => {
+ if (store.doc !== parsed.doc) return // the deck moved on
+ const n = fitAutoHeights(store.doc, { autoHeight: parsed.report.refit })
+ if (n) store.commit(() => {})
+ })
+ }
+ return parsed.report
},
/**
* The document as compact JSON: every field equal to what the editor would
diff --git a/slides/src/untrusted.ts b/slides/src/untrusted.ts
index 91b6ce0a..9ef14701 100644
--- a/slides/src/untrusted.ts
+++ b/slides/src/untrusted.ts
@@ -50,6 +50,42 @@ import { TIP_KINDS } from './tips'
const DROP = undefined
type Check = (v: unknown) => unknown
+/**
+ * The load report (compact input, round two). The gate drops silently by
+ * design — that is right for a hostile file and wrong for an agent that
+ * misspelled `fontSize`. `withDropReport` runs a gate call with a collector
+ * attached; every drop names a JSON-pointer-ish path and a one-line reason.
+ * Off by default: with no collector, `note()` is one null check and the path
+ * stack is never touched, so a paste or a remote op costs what it did.
+ */
+export interface Dropped { path: string; reason: string }
+let collector: Dropped[] | null = null
+const trail: string[] = []
+const note = (key: string | null, reason: string) => {
+ if (!collector) return
+ collector.push({ path: '/' + (key === null ? trail : [...trail, key]).join('/'), reason })
+}
+const within = <T>(key: string, fn: () => T): T => {
+ if (!collector) return fn()
+ trail.push(key)
+ try { return fn() } finally { trail.pop() }
+}
+/** Add a segment to the report path around `fn` — for a caller that walks a
+ * list itself (compactload.ts adds /slides/<i>). No-op with no collector. */
+export const withPathSegment = <T>(key: string, fn: () => T): T => within(key, fn)
+/** Run `fn` collecting every drop the gate makes; returns the list. */
+export function withDropReport<T>(fn: () => T): { result: T; dropped: Dropped[] } {
+ // Nesting: an inner report gets its own list and a fresh trail, and the
+ // outer one gets both of its back afterwards — so a gate call that itself
+ // asks for a report (none does today) cannot truncate the caller's paths.
+ const prevCollector = collector
+ const prevTrail = trail.splice(0)
+ const dropped: Dropped[] = []
+ collector = dropped
+ try { return { result: fn(), dropped } }
+ finally { collector = prevCollector; trail.splice(0, trail.length, ...prevTrail) }
+}
+
/**
* Assigning `out['__proto__'] = x` on a plain object walks the setter and
* changes the prototype — so this key is skipped everywhere a foreign object
@@ -211,11 +247,14 @@ function shape(
if (!isPlainObject(v)) return DROP
const out: Record<string, unknown> = {}
for (const key of Object.keys(v)) {
- if (key === PROTO || !keys.includes(key)) continue
- const val = checks[key]?.(v[key])
+ if (key === PROTO || !keys.includes(key)) { note(key, 'unknown key'); continue }
+ const val = within(key, () => checks[key]?.(v[key]))
if (val !== DROP) out[key] = val
+ else note(key, 'invalid value')
}
- return required.every((key) => out[key] !== DROP) ? out : DROP
+ const missing = required.filter((key) => out[key] === DROP)
+ if (missing.length) { note(null, `missing required ${missing.join(', ')} — object dropped`); return DROP }
+ return out
}
}
@@ -225,11 +264,11 @@ function shape(
* data with its labels — and silently closing a hole would misalign the rest.
*/
const list = (max: number, item: Check): Check => (v) => {
- if (!Array.isArray(v) || v.length > max) return DROP
+ if (!Array.isArray(v) || v.length > max) { note(null, Array.isArray(v) ? `more than ${max} entries` : 'not a list'); return DROP }
const out: unknown[] = []
- for (const entry of v) {
- const val = item(entry)
- if (val === DROP) return DROP
+ for (let i = 0; i < v.length; i++) {
+ const val = within(String(i), () => item(v[i]))
+ if (val === DROP) { note(String(i), 'invalid entry — the whole list is dropped'); return DROP }
out.push(val)
}
return out
@@ -490,25 +529,28 @@ export function checkElementProp(
/** Rebuild a foreign element, or null if it is not one. */
export function sanitizeElement(value: unknown): SlideElement | null {
- if (!isPlainObject(value)) return null
+ if (!isPlainObject(value)) { note(null, 'not an object — element dropped'); return null }
const type = value.type
- if (typeof type !== 'string') return null
+ if (typeof type !== 'string') { note('type', 'missing — element dropped'); return null }
const known = (MODEL_KEYS.element as Record<string, readonly string[]>)[type]
- if (!known) return null
+ if (!known) { note('type', `unknown element type "${type}" — element dropped`); return null }
// Identity is not optional: ids anchor selection, morph, comments and the
// CRDT node key, and a slide paste keeps them (only slide ids are reminted).
const id = ELEMENT_CHECKS.id(value.id)
- if (typeof id !== 'string' || !id) return null
+ if (typeof id !== 'string' || !id) { note('id', 'missing or invalid — element dropped'); return null }
const out: Record<string, unknown> = { type, id }
for (const key of Object.keys(value)) {
- if (key === 'type' || key === 'id' || key === PROTO || !known.includes(key)) continue
- const val = ELEMENT_CHECKS[key]?.(value[key])
+ if (key === 'type' || key === 'id') continue
+ if (key === PROTO || !known.includes(key)) { note(key, `unknown key for a ${type} element`); continue }
+ const val = within(key, () => ELEMENT_CHECKS[key]?.(value[key]))
if (val !== DROP) out[key] = val
+ else note(key, 'invalid value')
}
// An element missing what its type needs is not a degraded element, it is one
// the format cannot express — and the renderer throws on it (see above), which
// takes the whole slide down, not just the paste.
- if (!(REQUIRED_ELEMENT_KEYS[type] ?? []).every((key) => out[key] !== DROP)) return null
+ const missing = (REQUIRED_ELEMENT_KEYS[type] ?? []).filter((key) => out[key] === DROP)
+ if (missing.length) { note(null, `missing required ${missing.join(', ')} — element dropped`); return null }
return out as unknown as SlideElement
}
@@ -534,7 +576,7 @@ const SLIDE_CHECKS: Record<string, Check> = {
// elements are dropped INDIVIDUALLY: one hostile element must not cost the
// author the rest of a legitimately copied slide
elements: (v) => (Array.isArray(v) && v.length <= LIMITS.elements
- ? v.map(sanitizeElement).filter((el): el is SlideElement => el !== null)
+ ? v.map((el, i) => within(String(i), () => sanitizeElement(el))).filter((el): el is SlideElement => el !== null)
: DROP),
}
@@ -551,9 +593,9 @@ export const CHECKED_KEYS = {
/** Rebuild a foreign slide, or null if it is not one. */
export function sanitizeSlide(value: unknown): Slide | null {
- if (!isPlainObject(value)) return null
+ if (!isPlainObject(value)) { note(null, 'not an object — slide dropped'); return null }
const id = SLIDE_CHECKS.id(value.id)
- if (typeof id !== 'string' || !id) return null
+ if (typeof id !== 'string' || !id) { note('id', 'missing or invalid — slide dropped'); return null }
const out = shape(MODEL_KEYS.slide, SLIDE_CHECKS)(value) as Record<string, unknown>
if (!Array.isArray(out.elements)) out.elements = []
return out as unknown as Slide