Implementation Plan: ANU-14 - Embed the Bento editor, AI Assistant, and shared preview
Status: Approved by the user on 2026-07-27. Approved plan SHA-256:
05713A34E3B442E7C87234E3DFFC8B57F58D047AA5DD7F9440685CAFE2E5487F.
Scope
Launch the exact-version Anuva Bento editor from Step 3 Scene Editor with the complete saved PresentationConfig v2 aggregate and the selected scene/surface in focus. Add authenticated load, manual save, debounced autosave, durable unsaved-draft recovery, explicit immutable-revision conflict resolution, workspace-scoped media access, template-family application, validated surface-aware AI Assistant operations, composite undo/redo, and a coordinated three-surface Web preview driven by the exact player version packaged for Unity.
The saved immutable aggregate revision is authoritative for editor load, Web preview, and render handoff. The editor must never persist directly, invent an accepted revision, carry credentials, or bypass CMS workspace checks.
Product Main inputs and dependencies
- Product Main change:
2026-07-24-anuva-bento-integration - Product Main source:
docs/changes/2026-07-24-anuva-bento-integration/index.md - Linear parent:
ANU-8 - Linear implementation child:
ANU-14 - Repository label:
anuvax-cms - Required dependencies:
ANU-12andANU-13, both Done - ANU-12 delivery: Anuva Bento PR 4, merged as
c72925ef513012cb5ef56d6fdea2f5e930ef4fe9 - ANU-13 delivery: CMS PR 39, merged as
5c25b32c53d9d2203fb86aa2645d84fb6379d7dc - Contract, player, editor, and protocol versions:
1.0.0 - Renderer version:
1.0.8-anuva-renderer.1 - ANU-12 editor manifest SHA-256:
d6a6458bd475a0f5e90f107b030c8edd389e761ad30069566789544fafa1bba5 - ANU-11 player manifest-file SHA-256:
df806b6541cf5bffa1803917a0628d9079bef75109cac979e4275f7630c50042
Product Main owns product invariants and cross-repository decisions.
anuva-bento owns executable schemas, editor/player behavior, template
families, and release artifacts. CMS owns authenticated hosting, persistence,
revision recovery, AI orchestration, media delivery, and product Web UX.
Downstream artifact readiness gate
Planning inspection of the merged ANU-12 source and local handoff found three
gaps in the current anuva/bento-editor 1.0.0 host protocol:
- The host can receive
dirty-changedandsave-request, but it cannot request a validated save. The only save triggers are controls and keyboard handling inside the iframe. CMS therefore cannot implement compliant debounced autosave over the closed protocol. - The protocol has no command that focuses a stable scene/slide and surface after loading the complete presentation. CMS therefore cannot guarantee the required Scene Editor launch focus.
loadrequires a non-empty template-family catalog, but the packaged editor artifact does not include a host-readable Signal/Paper catalog file or a protocol operation that returns the catalog. Reaching into the same-origin iframe's privatewindow.anuvaEditorobject would bypass the reviewed message contract.
Before changing CMS implementation code, obtain a reviewed Bento-owned artifact
that preserves protocol 1.0.0 compatibility or deliberately versions it and
adds:
- a host
request-savecommand that emits the same validatedsave-requestevent as the editor's Save control; - a stable focus/navigation command using surface plus stable slide/scene identity, with structured unsupported-target errors; and
- deterministic, checksummed template-family JSON artifacts, or a validated protocol command that supplies the exact loaded catalog to the host.
Rebuild the editor and server-safe contract from the reviewed Bento commit, verify manifests, schemas, licenses, notices, renderer parity, and hard-offline behavior, and record the new commit and hashes in CMS provenance. Do not patch Bento-owned runtime behavior inside CMS, scrape iframe DOM, synthesize editor keyboard events, duplicate hand-written template definitions, or use the private same-origin debug adapter as a production API.
This dependency correction is cross-repository scope. If Product Main does not provide the reviewed artifact within the current ANU-14 contract, stop before CMS implementation and return the gap for a Product Main decision. Any artifact or protocol change that materially changes this plan requires a fresh plan preview and user approval.
Artifact hosting and provenance
- Reproduce the reviewed editor package and refreshed contract package from the exact Bento commit. Verify file counts, per-file SHA-256 values, manifest identity, schemas, exact versions, license, and third-party notices.
- Vendor the immutable editor artifact beside the existing contract/player consumer boundary without changing or rebuilding its files in the Next.js application. Update the narrow provenance record and focused artifact tests.
- Serve editor and player files through path-safe, authenticated same-origin route handlers. Include the vendored files in production output tracing and reject traversal, unknown files, manifest mismatches, unsupported versions, and requests without an authenticated workspace.
- Apply narrow editor/player headers: exact content types,
nosniff, a production content-security policy,frame-ancestors 'self', no public Bento update/collaboration endpoints, and cache behavior that never confuses mutable session state with immutable artifact files. - Keep editor/player version checks explicit. A manifest, ready event, contract, protocol, renderer, or saved-aggregate mismatch blocks load or preview with a recoverable typed state; it never falls back to another runtime.
Expected tracked surfaces include the immutable Bento vendor boundary, provenance tests, authenticated artifact route handlers, and any required Next.js output-tracing or security-header configuration.
Editor session and Scene Editor integration
- Add a dedicated editor-host service rather than extending the already large presentation action file with bridge mechanics. The server boundary loads the presentation, latest accepted compilation, template catalog, recoverable user draft, and referenced assets only after auth, workspace, relationship, schema, and exact-version validation.
- Add a client
BentoEditorHostcomponent that owns the iframe lifecycle, exactevent.originandevent.sourcechecks, schema validation, request ID correlation, timeouts, superseded-request handling, ready/dirty/save/error state, and disposal. Only allowlisted contract messages may reach product state. - Launch the editor from the selected Step 3 scene with full-presentation
context. Pass stable scene-to-slide identity and the selected Main,
Companion, or Emphasis surface through the reviewed focus command after
load; retain scene navigation context when the editor closes. - Present the editor as a responsive full-height dialog/sheet that supports desktop and mobile layouts, returns focus to the launch control, labels loading/saving/conflict/error states, exposes keyboard help, and announces status through accessible live regions.
- Keep the existing simple voiceover, caption, pause, and visual controls. When an editor-authored aggregate is current, any operation that recompiles surface documents from scene plans must warn that it will replace later Bento edits and require explicit confirmation. Never silently overwrite an editor-authored revision with a generated compilation.
Expected tracked surfaces include focused presentation editor host/service modules, the Step 3 presentation page, shared dialog/status primitives where needed, and focused bridge and UI tests.
Save, autosave, immutable revisions, and recovery
- Treat the editor's validated complete envelope and
baseRevisionas an untrusted save proposal. Revalidate the aggregate, asset identities, exact compatibility pins, presentation identity, workspace ownership, and base revision/checksum on the server. - Extend the immutable revision service with idempotent editor save request IDs, database-enforced per-presentation revision uniqueness, explicit authoring source, authenticated author, operation attribution, and compare-and-swap conflict results. Preserve the last accepted pointer on validation, compatibility, asset, or conflict failure.
- Add a workspace/user/presentation-scoped editor-draft collection for recoverable unsaved state. It stores only a validated credential-free envelope, base revision/checksum, content checksum, status, and safe diagnostics. It is not a second accepted presentation format and never becomes the render pointer until an explicit successful save.
- Manual save and debounced autosave use the same single-flight queue. A newer dirty state supersedes an unsent save; in-flight saves are serialized; repeat request IDs are idempotent; transient failures retain the draft and retry with bounded backoff after reconnect.
- On success, append one immutable compilation revision, move
presentations.latestCompilation, acknowledge the exact accepted revision to the editor, mark the matching draft resolved, and refresh product readiness from the saved aggregate. - On conflict, persist the unsaved proposal as a conflicted draft while leaving the latest accepted revision unchanged. Show both revision identities and offer explicit actions:
- load the persisted revision after confirming abandonment of the draft; or
- keep the draft and save it as the next revision only after reviewing the current persisted revision and confirming replacement.
- Preserve dirty/conflicted state across iframe reconnect and page refresh through the authenticated draft. A stale runtime, unsupported document, or unavailable asset must remain recoverable without clearing the draft.
Expected tracked surfaces include the presentation compilation schema and revision service, a focused editor-draft collection/service, regenerated Payload types, fake-Payload support, and conflict/idempotency/workspace tests.
Templates, media, and asset access
- Load only checksummed template-family artifacts from the reviewed Bento package. Validate family schema, contract, renderer, family version, surface dimensions, transparency, safe areas, and semantic slots before exposing a family to the editor.
- Let the editor apply layouts and whole families through its validated atomic operation executor. Surface mapping warnings and blocking issues before persistence; keep template changes in the editor's composite undo history.
- Resolve PresentationConfig
/assets/<stable-id>.<extension>locators through an authenticated same-origin asset route. Map the stable ID to a workspace-ownedmedia_assetsorvoiceover_audio_assetsrecord, verify media type and lowercase SHA-256, stream bytes without redirects, and never place access tokens, signed URLs, cookies, or secrets in the document. - Reuse existing upload and media-selection flows. New/replacement media must
be persisted and checksummed before the editor receives a
bind-assetoperation. Reject undeclared, cross-workspace, unsupported, checksum-mismatched, executable SVG/HTML, credential-bearing, or traversal input. - Preserve the same package-relative asset identity in saved aggregates and render packages. Web transport authorization remains separate from immutable document/package identity.
Expected tracked surfaces include authenticated asset delivery, media lookup helpers, template catalog loading, existing upload/select integrations, and asset security tests.
AI Assistant operations and attribution
- Add a Bento authoring prompt/tool boundary that receives the user's instruction, selected presentation/scene/surface, stable editable targets, current accepted revision, and allowlisted media references. It must never provide secrets, raw binaries, arbitrary selectors, or an unrestricted document mutation surface to a model.
- Use the installed Mastra APIs and repository model configuration only after
verifying their exact local documentation. Produce a structured
AnuvaEditorOperation[]result from the closed ANU-12 catalog rather than HTML, JavaScript, JSON Patch, callbacks, expressions, or arbitrary property paths. - Validate model output with the server-safe Bento contract, enforce requested
presentation/surface/scene scope and expected revision, then send the batch
through the editor's
apply-operationscommand. The editor performs final preflight, atomic execution, and composite undo. - Show the proposed operation summary and target scope before application. Failed validation or operation execution leaves the editor and persisted aggregate unchanged and returns safe structured issues.
- Meter the provider call through the existing
ai_interactionslifecycle. Add a dedicated task/action identity and record user, presentation, optional scene, model, revision, operation IDs/types/scopes, correlation ID, success, and cost attribution. Operation audit metadata must not contain secrets, binary content, full prompts, or raw model response bodies. - Manual, template, host, and AI operation attribution is copied into the accepted compilation revision without making mutable audit records part of PresentationConfig or its checksum.
Expected tracked surfaces include a dedicated Bento authoring prompt/schema, Mastra agent or tool registration as justified by installed APIs, server action or service orchestration, metering task metadata, AI Assistant UI, and validation/metering/failure tests. No provider or model string change is planned.
Saved-revision Web preview
- Replace the Step 3 placeholder visual preview with a coordinated PresentationConfig preview that loads the latest accepted revision only. Dirty editor state is visibly newer than preview until autosave/manual save succeeds.
- Host three exact-player iframes for Main, Companion, and Emphasis. Validate origin, source, protocol, player/runtime versions, request correlation, readiness, asset readiness, lifecycle, and structured errors for every surface.
- Drive all three players from one Web preview clock using absolute
reset/seek/tickand the persisted authoritative timeline. Keep play/pause/seek/scene navigation deterministic, including backwards seeks, Main/Companion persistence, Emphasis clearing, and fragments. - Block playback until all required players and assets are ready. A failure, superseded load, unsupported document, stale runtime, or missing asset clears stale visual output and offers retry after the underlying state is corrected.
- Compare the player manifest/version and aggregate asset identities against the render-package snapshot path so Web preview proves the same saved document and exact player artifact intended for Unity.
Expected tracked surfaces include a focused player-host component, Step 3 preview controls/state, authenticated player artifact routes, and player parity tests.
Data model changes
Planned Payload changes are limited to authoring durability and auditability:
presentation_compilations- database-unique revision key and idempotent client save request identity;
- authoring source and authenticated author;
- operation-attribution JSON with IDs/types/scopes but no executable content;
- editor manual-save and autosave trigger values.
presentation_editor_drafts- workspace, presentation, and user relationships;
- base revision/checksum and draft content checksum;
- validated credential-free aggregate;
- active, conflicted, resolved, or discarded state;
- safe conflict/recovery diagnostics.
ai_interactions- a dedicated Bento authoring task type, reusing current presentation/scene, workflow/action metadata, metering, status, and cost fields.
Regenerate src/payload-types.ts. No Payload admin component is planned, so an
import-map regeneration is required only if implementation introduces one.
Delivery sequence
- Resolve the Bento-owned artifact readiness gate and re-preview this plan if the resulting protocol or package boundary changes materially.
- Reproduce, verify, vendor, trace, and securely serve the exact editor, contract, template, and player artifacts with provenance and network-denial tests.
- Add editor draft/revision/idempotency/attribution persistence and workspace-scoped load/save/conflict-resolution services; regenerate Payload types and extend fake-Payload tests.
- Add authenticated asset delivery plus template/media catalog integration and security tests.
- Build the validated editor bridge and responsive Scene Editor launch flow, including focus, manual save, autosave, reconnect, durable draft recovery, explicit conflict resolution, and recompilation replacement warnings.
- Add structured Mastra-backed AI operation generation, metering, pre-application review, editor execution, attribution, and atomic failure coverage.
- Add the three-surface saved-revision player host and deterministic preview controls with runtime/package parity and asset readiness checks.
- Update durable/state docs, maintain the ImplementationLog and
CompletionReport, run the full verification matrix, preview all changed docs,
and create the linked draft PR through
anuva pr create ANU-14 --draft --confirm.
Each step must leave the repository typecheckable and keep the last accepted revision renderable. Any material change to protocol, persistence, conflict resolution, source-of-truth behavior, or scope requires a plan update, fresh preview, and new user approval before implementation continues.
Documentation impact
- Add a durable editor/preview document covering artifact provenance, iframe host/auth protocol, session lifecycle, autosave, conflicts, drafts, templates, AI operations, media, preview clock, accessibility, security, and recovery.
- Update
docs/core/PresentationVideoWorkflow.mdfor Scene Editor launch, editor-authoritative saved revisions, recompilation warnings, and shared preview. - Update
docs/core/PresentationConfig.mdfor editor-authored revisions, attribution, drafts, and Web asset transport. - Update
docs/core/MastraAgentsAndTools.mdfor the structured Bento operation boundary and metering. - Update
docs/core/PayloadDataModel.md,docs/core/AuthAndWorkspace.md, anddocs/core/TestingAndVerification.mdfor new persistence, authenticated routes, tenant boundaries, and verification. - Update
docs/state/CurrentImplementationMap.md,docs/state/RouteMap.md,docs/state/ServerActionsMap.md,docs/state/CollectionMap.md,docs/state/WorkflowMap.md, anddocs/state/KnownGaps.mdwhere implementation paths and resolved gaps change. - Maintain this change-folder plan, post-approval ImplementationLog and CompletionReport, recursive indexes, and MkDocs navigation. Product Main owns canonical publication.
Verification and acceptance checks
| Acceptance area | Planned evidence |
|---|---|
| Dependency artifact | Exact Bento commit and manifests; schemas, licenses, notices, renderer parity, host autosave/focus/catalog capability, deterministic rebuild |
| Authenticated hosting | Unauthenticated, cross-workspace, traversal, unknown-file, wrong-content-type, and stale-manifest rejection; production output contains exact artifact files |
| Editor load and focus | Full aggregate loads once; every stable scene/surface focus works; one session preserves all three documents and presentation context |
| Save and autosave | Manual and debounced saves use one validated queue; accepted revision acknowledgement, idempotent retry, reconnect, and supersession pass |
| Conflict and recovery | Concurrent revision tests preserve current accepted aggregate plus user draft; explicit reload/replace paths, refresh recovery, and last-good pointer pass |
| Templates and undo | Signal/Paper schema/version checks, all-surface family and per-layout targeting, safe/unsafe mapping, user extras, atomic undo/redo |
| AI operations | Structured-output validation, expected-revision and target-scope enforcement, atomic editor execution, undo, metering, attribution, and malicious-output rejection |
| Media and security | Workspace ownership, checksum/media type, asset route, SVG/HTML sanitization, no token/secret/query locator, redirect/traversal/undeclared asset failures |
| Shared preview | Three surfaces use the saved revision and exact packaged player; readiness, timeline, play/pause/seek/backseek, fragments, persistence, transient Emphasis, and parity checks |
| Failure and accessibility | Load/save/offline/reconnect/stale-runtime/unsupported-document states, retry behavior, keyboard navigation, focus return, dialog semantics, and live status announcements |
| Network denial | Editor/player production flows make no Bento update/collaboration/public-service requests and documents contain no credentials or executable AI output |
| Repository quality | pnpm generate:types, optional pnpm generate:importmap, pnpm lint, pnpm typecheck, pnpm test:int, relevant Playwright projects, git diff --check, recursive docs indexes, and strict MkDocs |
Integration tests will assert returned action results and persisted fake database state. Browser tests will exercise the real vendored editor/player artifacts where possible, with deterministic fixtures and captured network/page errors. Any unavailable external provider test will use the repository's controlled Mastra/provider mocks and will be identified separately from artifact/browser evidence.
Non-goals and rollback
Non-goals:
- changing Bento editor/player internals or maintaining a CMS-private protocol fork;
- Unity/Vuplex lifecycle, performance, virtual-surface mapping, or capture;
- Python package staging, retry orchestration, or render failure propagation;
- public Bento package publication, update services, or collaboration;
- embedding access tokens, signed URLs, provider secrets, or executable AI output in documents, drafts, artifacts, or render packages;
- migrating legacy Reveal data or reintroducing a Reveal preview path;
- silently regenerating scene plans over accepted editor-authored documents; or
- expanding templates beyond the reviewed Bento-owned family catalog.
Before an editor revision becomes accepted, rollback is removal of the new host, draft, and route surfaces while retaining ANU-13 revisions and preview behavior. After editor revisions exist, rollback means disabling editor entry and selecting the last accepted compatible immutable revision; it never rewrites or deletes accepted revisions or translates Bento documents back to Reveal. Failed saves and conflicts retain the last accepted pointer and the recoverable user draft.