@joplo-app/core 0.6.2 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/guide.js CHANGED
@@ -29,9 +29,12 @@ export function pluginSkillIndex(plugins) {
29
29
  ]), ...(!plugins.length ? [' None. Install an author package, add it to config.plugins, then read npx joplo skill <plugin-id>.'] : []), ''].join('\n');
30
30
  }
31
31
  export function findPluginTopic(topic, plugins) {
32
- const [id] = topic.replace(/^plugin:/, '').split('/');
32
+ const [id] = topic.replace(/^(?:plugin:|joplo-plugin-)/, '').split('/');
33
33
  if (!topic.startsWith('plugin:') && SKILL_TOPICS.some(t => t.name === topic))
34
34
  return null;
35
+ const direct = !topic.startsWith('plugin:') && plugins.find(p => p.id === topic.split('/')[0]);
36
+ if (direct)
37
+ return direct;
35
38
  return plugins.find(p => p.id === id) ?? null;
36
39
  }
37
40
  export function pluginSkillTopic(p, topic) {
@@ -152,11 +155,16 @@ Success: check reports 0 errors; outline --work explainer shows the intended sli
152
155
 
153
156
  ## Binary assets
154
157
  - asset('./file.glb') embeds a self-contained GLB; MP3/WAV/OGG/M4A/FLAC are supported too. Paths are relative to the calling source file. Images retain a 2 MB limit; binary files have a 50 MB limit. Dev serves binary bytes by content hash; npx joplo build writes every asset as its own file (assets/<hash>.<ext>), so the built site must be opened over HTTP: npx joplo preview, a share, or any static server. Double-clicking index.html (file://) is not supported.
158
+ - Before reviewing a material folder, run npx joplo assets . --usage --scan photos --format json (repeat --scan for explicit project-relative folders; optional --work <exact work id> or --scenario <id> includes continuing predecessors). This is read-only: it loads author modules, observes actual asset() evaluations and declared plugin resources, and hashes explicitly scanned files; it does not build, render, generate resources, spend, upload or delete. As with check/build, trusted author modules execute while loading.
159
+ - Read asset reports as evidence, not cleanup advice. scope.authorReferences is whole-loaded-project, including drafts; contextual references have workId/scenarioId/layer/elementId/source and inSelectedScope. A scene-level reference is not proof of a particular step. Declared binaries are matched across dev/publish compiles by plugin/compiler/input identity, never by coincidental sequential IDs or ordinary prose strings; a draft-only selection has no packaged assets. publication=included-in-selected-ir means the selected publish IR contains its bytes/resource id, not that a completed build has packed it. Draft-only or excluded content can still have author references. sampledVisibility is always unknown: no frames are sampled and conditions/camera/plugin internals are not resolved.
160
+ - not-found-in-loaded-model only means no observed reference in that evaluation; never rename it unused. Dynamic paths, imported helpers, unexecuted branches, cached modules or unevaluated plugin compilers remain unknown. Identical-byte files share content matches, so contentMatch marks ambiguous provenance rather than choosing one file. No author/source/year/license metadata is inferred, and a report is not a copyright decision. Symlinks are skipped and scans cannot escape the project; only scan folders the user intended. If loading/compilation fails, fix check errors and rerun; never generate missing paid resources merely to fill a report.
161
+
155
162
  - Prefer existing CC0 assets and public-domain reference images, then use a generation plugin to fill gaps in an original style. Read the enabled plugin's skill before generation. Commit persistent artifacts and metadata; never put API keys in project source.
156
- - npx joplo resources --dry-run lists missing persistent resources and estimated credits. Interactive resources confirms each item; unattended generation requires --allow-spend. check/build/render remain offline for these artifacts. Missing or corrupt output gives diagnostics, not an implicit paid retry. Keep large GLB files below 5 MB where possible and inspect MODEL_SIZE warnings before sharing.
163
+ - npx joplo resources --work <work-key-or-qualified-option-id> --dry-run limits loading and generation to one work; unrelated work modules are not evaluated. Shared config, layouts and routes still must load successfully. Cross-work from references outside the selection fail explicitly: generate/check the complete dependency context rather than assuming the command includes it. Omit --work to process the full project. npx joplo resources --dry-run lists missing persistent resources and estimated credits. Interactive resources confirms each item; unattended generation requires --allow-spend. check/build/render remain offline for these artifacts. Missing or corrupt output gives diagnostics, not an implicit paid retry. Keep large GLB files below 5 MB where possible and inspect MODEL_SIZE warnings before sharing.
157
164
 
158
165
  ## Structure and files
159
- - joplo.config.ts exports config({ name, plugins, layout?, home?, theme?, autoFocus?, voice?, locales? }). plugins is explicit; installation alone does not enable a plugin.
166
+ - joplo.config.ts exports config({ name, plugins, layout?, home?, theme?, autoFocus?, voice?, locales?, watch? }). plugins is explicit; installation alone does not enable a plugin.
167
+ - Dev watch exclusions: config({ watch: { ignore: ['exports/frames', '.coord'] } }) excludes project-relative output files/directories and their descendants from recompilation and review invalidation. Paths are literal, not globs; do not exclude real source or referenced assets. Existing .joplo/dist/node_modules/.git exclusions remain. Restart the dev board after changing this configuration; each project has its own exclusions. Ordinary image assets still trigger updates.
160
168
  - layouts/<id>.tsx exports layout(tree). Outlet places the current page; Slot declares a named insertion point. Those are engine composition primitives.
161
169
  - routes/**/page.tsx exports page({ title, layout?, viewport? }, tree). The directory determines its route. Set layout: false to opt out of the shared layout.
162
170
  - works/<key>.tsx (or .ts) exports work({ title, summary, scenarios, stage? | layers?, viewport?, on?, routes?, audience?, roles?, state?, free?, draft?, order? }). The filename is the entry key and must not collide with a feature folder.
@@ -200,7 +208,24 @@ Declare both success and recovery cases in the feature. View code belongs to the
200
208
  - set(path, value) replaces; push(path, value) appends; patch(path, object) expands to sets (nested objects replace, not deep-merge). go(route) navigates in this work; back returns to the prior route.
201
209
  - stream(path, text, { pace? }) writes like set, but during playback the bound text appears character by character (a model answering, speech being transcribed); jumps, screenshots and deep links show the full text. When the new value starts with the old one, only the added characters stream, so write each step's full value (previous text + the new words) rather than juggling separate fragments. pace: 'voice' spreads the new characters over this step's narrate()/say() line, so the words land as they are spoken; the default pace is model-output speed. Only a plain text child bound to the path streams ({$.ui.reply}); stream values are translated like other on-screen text, so keep every language's successive values prefix-consistent.
202
210
  - toast(text), toast.success/error/info(text) show an engine message. done(result, outcome?) ends a scenario; outcomes success/failure/cancelled must agree with flow's badge. uses(ruleKey, ...) links rules; it is an effect, not a flow method.
203
- - free.click/type/select/toggle/drag/hover/scroll/act in work.free declare local reactions. free is a named object, not an array: free: { open: free.click('open', set($.ui.open, true)) }. Only set, push and toast are local effects; navigation, completion and media remain scripted. Play/jump/scenario/reset discard the local layer.
211
+ - free.click/type/select/toggle/drag/hover/scroll/act in work.free declare local reactions for gestures an element cannot carry itself. free is a named object, not an array: free: { pick: free.select('year', '1984', set($.ui.era, 'mac')) }. Only set, push and toast are local effects; navigation, completion and media remain scripted. Play/jump/scenario/reset discard the local layer. For a click, write onClick on the element instead (next section).
212
+
213
+ ## Element events (onClick)
214
+ Give a button, link, menu item or other interactive element its behavior where it is drawn, so the script and a viewer who takes over run the same effects:
215
+ \`\`\`tsx
216
+ // props on interactive elements from an installed plugin (read its skill for the component names)
217
+ id="btn_invite" disabled={not($.ui.isAdmin)} onClick={[set($.ui.inviteOpen, true), uses('admin_only')]}
218
+ id="btn_cancel" onClick={set($.ui.inviteOpen, false)}
219
+ id="nav_settings" onClick={go('/settings')}
220
+ // the step only says what the viewer does and why
221
+ flow('Invite a teammate').click('btn_invite', 'The admin opens the invite dialog')
222
+ \`\`\`
223
+ - onClick takes one effect or an array: set, push, toast, go and uses. A scripted .click(id) runs the element's onClick first, then the step's own effects. Keep captions, narrate(), say(), camera and focus cues, done(), and the .system() response in the steps.
224
+ - Do not repeat the element's writes in the step (STEP_REPEATS_EVENT). Step effects stay available for what only this moment of the story does.
225
+ - After the viewer pauses, every element with onClick works as a local reaction: go() changes page locally, uses() only links rules. Play, jump, scenario change and reset discard the local layer. A page reached only locally never advances the script; the next step still belongs to the timeline's page.
226
+ - One id has one behavior per work: an id that appears on several pages (a layout nav link) needs the same onClick everywhere (EVENT_CONFLICT). Do not also declare work.free for that click (FREE_EVENT_CONFLICT).
227
+ - Only onClick takes effects for now (EVENT_UNSUPPORTED). Inputs keep value={$.ui.name} and the typed value; put follow-up reactions in the step.
228
+ - Give the controls a viewer will try (cancel, close, back, navigation) an onClick instead of marking them unmodeled; keep unmodeled for what this work deliberately leaves out.
204
229
 
205
230
  ## Reusable effect factories
206
231
  Step arguments and card effects accept nested arrays, flattened in order. Compose helpers that return patch() plus other effects instead of copying transition state. Only done() completes a scenario; unknown effect objects report EFFECT_INVALID.
@@ -294,7 +319,7 @@ Joplo already has the parts of a user story; fill them in that spirit.
294
319
  - Rhythm: every short step waits 3 s, so a run of trivial steps feels like a metronome. Merge trivial steps (type, then click) and give key results an explain.
295
320
 
296
321
  ## 6. Narration: narrate() is a presenter talking, not the caption read aloud
297
- When the board or the published site reads a demo aloud, each step reads, in order of preference: narrate() in the narrator's voice; else say(), the character's own line in that role's voice; else the caption in the narrator's voice (cards read title and sub). A caption read aloud sounds like a screen reader, so give the steps that will be heard a narrate() line, written the way a person walks a colleague through a feature. It may later be recorded by a real voice, so write how people speak.
322
+ When the board or the published site reads a demo aloud, each step reads, in order of preference: narrate() in the narrator's voice; else say(), the character's own line in that role's voice; else the caption in the narrator's voice (cards read title and sub). Use narrate(false) on a deliberately silent step: it suppresses narration, say(), caption/card fallback and the spoken subtitle; the step title stays visible and voice-paced streams use their normal text speed. narrate('') remains an error, not a silence marker. Without narrate(false), the existing fallback is unchanged. A caption read aloud sounds like a screen reader, so give the steps that will be heard a narrate() line, written the way a person walks a colleague through a feature. It may later be recorded by a real voice, so write how people speak.
298
323
  - Short first: one sentence, two at most, mostly 3–8 seconds. Cut every word the screen already shows; the viewer is watching.
299
324
  - Each line does one job: orient (who, where, what we are about to see), point (what to look at now and why it matters), connect (carry the viewer from the last step: 'Now over to Ajie'), or conclude (what this proved).
300
325
  - Say what the caption cannot: the intent, the reason, the consequence. Never repeat the caption word for word; name an on-screen label only when the viewer must find it.
@@ -307,6 +332,8 @@ When the board or the published site reads a demo aloud, each step reads, in ord
307
332
  - An on-screen headline and narration play together: narrate the point in spoken words (the why, the consequence) rather than reading the headline back, since the subtitle would show the same sentence twice.
308
333
  - say() is first person, what the character would really say; narration about the characters goes in narrate().
309
334
  - Who says it: a user action's say() uses the role of the layer it lands on. A system step has no acting person, so it reads in the narrator's voice unless you name the speaker: say('Book it for Friday', { role: 'me' }). Use that for a person talking to the product (voice input, a call, a voice assistant) while the screen reacts in system steps.
335
+ - These audio options require matching CLI, Kit and Core versions. An older Kit/Core can ignore unknown narrate/say options and use the normal provider path, so never promise zero provider calls for mixed old packages. Upgrade the toolchain together and run joplo voice --dry-run: supplied lines must show audio: provided and zero estimatedBillableChars before generation. Old strict Cloud readers also need the matching contract upgrade before accepting these new Step fields; build locally until that deployment gate is satisfied.
336
+ - Reuse prepared audio with narrate('Presenter words', { audio: asset('./presenter.wav') }) or say('Actor words', { role: 'actor', audio: localResource('voices', 'line', 'existing take') }). The text still drives subtitles and role labels; the selected clip uses the existing narration track and recording/ducking path. Read the resource plugin's skill to prepare its artifact first. A supplied clip never calls a TTS provider and contributes zero generation characters, even if it is missing or invalid; fix the resource diagnostic instead of retrying voice generation. Remote URL strings and file paths are not implicit downloads: use asset() or a localResource() reference. narrate wins over say; narrate(false) suppresses both. With an explicit clip, use one selected narrate/say effect per step; do not concatenate multiple lines around one clip. Audio is literal: translating subtitles does not translate a supplied recording; prepare the matching recording and script for each content language.
310
337
  - Voice input / dictation: one system step per spoken phrase, say(phrase, { role }) plus stream($.ui.text, fullTextSoFar, { pace: 'voice' }), so the subtitle shows the phrase, the speaker's voice reads it and the transcript grows in step with the voice. Put the presenter's explanation in narrate() on separate steps (pauses, results); one step reads only one line, and narrate() wins over say().
311
338
  - Open with the person and their goal; close with the one to three points, as speech, not a list read aloud. Write in the demo's language.
312
339
  Wrong, it reads the interface: .click('share', 'Xiaoyu shares the itinerary', narrate('Click Share to share the itinerary.'))
@@ -345,13 +372,13 @@ The engine renders scripted state at step k, plus disposable local exploration.
345
372
  ## Playback and free exploration
346
373
  - The first picture-changing input while playing pauses and applies the same input. Matching the next script action advances once and stays stopped, including before a following system step. It behaves like manual pause followed by that input.
347
374
  - Declared work.free reactions remain available in build/share and review publications after scope filtering. Verify a non-scripted action in the actual published site, then reset; local effects must disappear without changing timeline state.
348
- - Arbitration: exact next action → reachable other scenario on the same stage (confirm first) → declared free reaction/native local behavior → existing hint. Type, value, target and plugin payload all matter; a bare click cannot complete a typing action.
375
+ - Arbitration: exact next action → reachable other scenario on the same stage (confirm first) → element onClick, declared free reaction or native local behavior → existing hint. Type, value, target and plugin payload all matter; a bare click cannot complete a typing action.
349
376
  - Blank/noninteractive clicks only pause, with no local-change notice. Covers/transition cards remain inert. Hover never pauses; while paused it matches normally. Touch tap completing hover follows the click rule.
350
377
  - Pointerdown pauses immediately and the same drag continues. A declared element drag owns its pointer before stage pan or plugin orbit: the source follows the pointer (also inside scaled pictures) and is transparent to hit tests while dragged. On release the engine picks the destination under the pointer, else the one the dragged element overlaps most, else the nearest within about 48 stage px; with none it snaps back and changes nothing. Esc, a cancelled pointer, a window blur or a hidden page also snap back; a second finger or pointer never takes over a drag in progress. Known limit (0.3.0): that 48 px is measured in the outer stage scale, not the scale of a picture plugin inside it, so the "nearby" tolerance is larger in a shrunk picture and smaller in a magnified one — make endpoints big enough and keep unrelated endpoints apart. The first wheel event pauses and scrolls; keep the burst/inertia in its scroll container before stage zoom.
351
378
  - Playback controls stay outside stage input. Editing keys stay with a focused editable control. Plugin actions enter the same arbiter; never independently advance the timeline.
352
379
  - Sequential playback is the default everywhere (board, published site, embed, render --chain): when a scenario finishes during playback, the next scenario starts at once — no countdown, no end card. The order follows from chains first (a chapter that continues another plays right after it, wherever it is declared), then declaration order. A from chapter continues in the same shot; a scenario marked flow('Slice title', { autoplay: false }) is skipped together with the chapters that continue it, and playing such a branch stops at its end. Pausing, exploring, a pending scenario switch or stepping manually never jumps ahead; the replay / next-case controls appear only when the whole sequence has finished. Declare scenarios in viewing order.
353
380
  - Play, jump, scenario change and reset discard local effects. Screenshots, video, deep links and __JOPLO_STATE__ always read the timeline. Frozen in-flight previews must not paint over accepted local edits; preserve their original anchor for reset/resume.
354
- - Use native controls from installed plugins and read their skills for supported edits. Use work.free for declared secondary reactions; keep lasting results in scripted effects. Test actual inputs, not only autoplay.
381
+ - Use native controls from installed plugins and read their skills for supported edits. Give clickable elements onClick so they work after takeover; use work.free for other declared secondary reactions; keep lasting results in scripted effects. Test actual inputs, not only autoplay.
355
382
 
356
383
  ## Actions and the shared clock
357
384
  - Scripted scroll is a timeline projection: returning to an earlier step, resetting, or switching scenarios on the same stage restores the initial scroll baseline and applies only the selected prefix. Test 0 → scrolled step → 0 and a scenario without scrolling. Pausing an in-flight scroll keeps its intermediate position; ordinary render frames must not reset it.
@@ -377,16 +404,22 @@ Start playback before testing stage gestures: covers and transition cards intent
377
404
  - A step's hold controls dwell; narration may extend waiting. The engine estimates spoken time and sequences chapters. Keep a long story in smaller scenarios with from, retaining the previous final state.
378
405
  - Transition cards mark a real opening/ending/time shift. Most information should change on the view, not arrive as a text deck. Read story and the installed visual plugins' recipes.
379
406
  - Media is provided by an explicitly configured plugin. A viewer gesture unlocks sound; pause/resume/speed share the clock and narration ducks background audio. Static frames stay silent. Read the plugin skill for resources and production limits.
380
- - Media continuity is engine behavior for every media plugin: a track keeps playing across steps on the engine clock (it only re-seeks on a jump, reset or non-relay chapter change); playing the same resource again continues it; playing a different one with fadeMs crossfades (old out, new in, no silence); a continuing chapter starts with the music its previous chapter ended with. Explicit marker seeks reposition that track (even at 0ms) and start its fade from the marker, while ordinary steps/relay chapters preserve its driver. Overlapping outgoing/incoming audio both count toward the decoded-memory budget; the host applies fade/volume/narration ducking once. Video chain export records that same mix; film strips skip audio.
407
+ - Build validates explicit narration audio after selecting the publication scope and resolving prepared resources. AUDIO_ASSET_MISSING / AUDIO_ASSET_INVALID blocks publication before writing output when a selected speech clip has no prepared audio asset; prepare or repair it and rebuild. It never falls back to a voice provider or grants spending permission. An excluded work’s missing clip does not block the selected scope, and timing-only hold('audio', ref) may still use an estimate without a prepared clip.
408
+ - Audio resource failures are exposed by the playback host; video recording fails instead of silently delivering missing audio. MEDIA_DECODE_BUDGET warns when simultaneous resources exceed the shared PCM budget at 48 kHz; MEDIA_DECODE_HEADROOM warns about 96 kHz devices. Check can estimate from inspected durations, while build uses decoded metadata when available; unknown resources and other device rates still need playback verification. MEDIA_ENCODE_BUDGET separately checks the 4 MiB encoded-byte cache for prepared audio, including simultaneous retained resources. This is independent of the 32 MiB Float32 PCM cache and the local compiler artifact limit. A large PCM WAV can fail encoded admission even when decoded mono PCM fits; transcode to lossless FLAC or a smaller supported encoding. Check reads cached prepared byte/channel/region metadata without generating or spending; absent artifacts only permit duration/stereo estimates, so prepare local resources and check again. Runtime errors name the cache, requested/retained bytes and limit. Read the media plugin guide for concrete authoring remedies.
409
+ - Media continuity is engine behavior for every media plugin: a track keeps playing across steps on the engine clock (it only re-seeks on a jump, reset or non-relay chapter change); playing the same resource again continues it; playing a different one with fadeMs crossfades (old out, new in, no silence); a continuing chapter starts with the music its previous chapter ended with. Explicit marker seeks reposition that track (even at 0ms) and start its fade from the marker, while ordinary steps/relay chapters preserve its driver. Overlapping outgoing/incoming audio both count toward the decoded-memory budget until the actual engine-clock fade ends. The host then destroys the faded driver and releases its leases even during the same long step, while retaining a lightweight retirement marker so stale snapshots cannot resurrect it; explicit play or seek can rebuild it. Static warnings describe planned snapshot overlap, not observed audible state: real narration duration can move fade timing. They must not be suppressed merely because a later real-time render may finish the fade, and they are not a promise that long tracks fit; the host applies fade/volume/narration ducking once. Video chain export records that same mix; film strips skip audio.
381
410
 
382
411
  ## Make it play like a film, not slides (Required for video-like pieces)
383
412
  Viewers call a piece "a slide deck" when pictures swap in one frame and then sit still. The static storyboard cannot show either problem, so it never proves the piece moves well.
384
413
  - No hard cuts. Every chapter/era/scene seam needs a transition the viewer can follow: carry one object across (a match cut through the subject: push in until it fills the frame, swap the world behind it, pull back), morph a shared object, crossfade layers, or move the camera over the swap. One deliberate cut is a signature move; more than that is a deck. A scene change must not reset all visual context.
385
414
  - No dead frames. Nothing on screen may be completely still for more than about 1.5 s; a still composition lasts at most about 3.5 s, and something changes at element level every 2–2.5 s. During reading holds keep a slow, eased camera drift with an end point (constant-speed motion reads as a screensaver). Use the installed visual plugin's drift and enter/exit transitions; read its recipes.
386
- - One main motion per beat; most beats 2–3 s. hold(seconds) is the author's pacing: a step with hold no longer gets the 3 s reading floor (caption reading time per character and narration still extend it). System steps show their event for about 0.9 s before committing; narration waits keep the engine clock (and therefore drift and transitions) running.
415
+ - Verify real layout after fonts and transforms, not only check: npx joplo render . --scenario-id film.open --out still.png --audit-layout --audit-content '[data-jid="frame"]' --audit-important '[data-jid="quote"]' --audit-safe-area '0,920,1920,160' --audit-exclude '[data-jid="stamp"]'. Areas use actual page CSS pixels relative to the export root, or a selector inside it; importance and intentional decoration are explicit, never guessed from text meaning. The sibling .layout.json reports Range text-line bounds, clipping/safe-area warnings, source/element/work/scenario/step and evidence. A static result is final-state only (atMs:null), not animation proof.
416
+ - For motion use --film --audit-layout (fresh run; --sample-ms at most 50). The audit consumes the same export clock and JPEG frames: post-commit, entry finish and plugin-declared camera/drift/waypoint deadlines are sampled within the report's sampleToleranceMs; intervening intervals are sampled with --audit-every-ms (20–1000, default 250). A later step may interrupt a motion phase. Inspect evidence before editing: overlap is a geometry heuristic warning, masks/rotation/nonrectangular clipping or hidden importance remain unknown, and unmeasured intervals can contain issues. --audit-layout supports static or film, not sheet/video/frames/resume. It never changes layout or generates paid narration/resources.
417
+ - One main motion per beat; most beats 2–3 s. hold(seconds) is the author's pacing: a step with hold no longer gets the 3 s reading floor (caption reading time per character and narration still extend it). A step takes its pre-commit lead plus its post-commit dwell (the larger of visual dwell and narration). hold(seconds) only sets post-commit dwell, so summing holds alone underestimates runtime. System steps default to a 0.9 s pre-commit lead; use work({ pace: { systemLead: 0 }, ... }) for narration-led films or a finite 0–30 seconds to choose it. The work setting applies to every system step, including continuing chapters, and preserves explicit timing in reduced-motion mode. Cards still commit directly; narration waits keep the engine clock (and therefore drift and transitions) running.
418
+ - Calibrated resource audio keeps its AudioRegion: playback, progress and measured duration use contentStartFrame/contentFrames, excluding probes, encoder delay and guards; native decoder trim mismatches fail explicitly. Recorded/offline narration retains the original file plus numeric AudioRegion so downstream mixing can select the same content. Live and recorded supplied narration share the media host's existing 4 MiB encoded and 32 MiB decoded-PCM budgets. Recording preparation retains only validated content/region facts, releases its measurement lease and reacquires a bounded lease for playback; abort, failure, cancellation and unmount release consumer leases immediately, and late results cannot play. On a budget error, shorten the simultaneous content or prepare a smaller supported encoding (preserving region metadata), rather than raising limits or synthesizing replacement TTS.
419
+ - Audio-led dwell: narrate('Words', { audio: asset('./take.wav') }), hold('voice', { pad: 0.4 }) waits for this step's selected narration/dialogue duration plus 0.4 seconds. hold('audio', asset('./cue.wav'), { pad: 0 }) uses another existing audio resource's duration without playing it. pad defaults to 0.45 seconds and accepts finite 0–30; it replaces the normal breath rather than adding a second breath. Explicit audio-led hold removes caption/explain reading floors; dwell is still the maximum of the audio duration plus pad, numeric hold, required camera/stream work and plugin effectHold. Pre-commit actions/systemLead remain separate. Numeric hold keeps its old meaning. Playback already waits for actual narration completion; this API reuses that wait, so a shorter clip is not extended by the narration's character estimate. Without a prepared matching clip, planning uses an estimate and check/outline label it estimated; it does not synthesize audio. Measured cached voice timing is bound to the selected clip/voice/content-language identity; changed text, voice or language must not reuse an old measured duration. Check again after preparing audio, then inspect outline and render --film --voice real before lining up other tracks.
387
420
  - Anti-deck gate: before building, write one line per beat — the main moving object, its start → end state, and the verb (push, morph, rise, swap…). If most beats are only fades or panels appearing, redesign them. A contact sheet that reads like slide thumbnails fails.
388
421
  - Chapters: use chapter() default continuation; sequential playback of a continuing chapter continues in the same shot (no countdown, no reset, music keeps playing). Bring the next chapter's music in on the beat before the visual swap (play the next score with fadeMs; the old track fades out under it — a J-cut). Play the same score again to keep it going. Stop music only at the real ending.
389
- - Film sampling freezes the browser clock before loading, advances on a fixed 16 ms loading grid and waits for DOM commits to settle before each sample. Loading time does not become playback time. Repeat the same command when checking timing; compare scenario/position timelines separately from pixel differences (fonts, browser and platform can still affect rasterization).
422
+ - Film sampling has a 50 ms default observation tolerance: identical source can cross a step/chapter boundary one sample apart; pixel equality across browsers is not guaranteed. It freezes the browser clock before loading, advances on a fixed 16 ms loading grid and waits for DOM commits to settle before each sample. Loading time does not become playback time. Repeat the same command when checking timing; compare scenario/position timelines separately from pixel differences (fonts, browser and platform can still affect rasterization).
390
423
  - Required review: run npx joplo render <dir> --scenario-id <first chapter> --film --chain --out film.png and read every page (one per chapter; red = one-frame full-screen change, grey = nothing visible changed for ≥ 1.5 s). The CLI prints every CUT and STILL with time and step; film.json beside it has the largest adjacent-frame change around every step. Fix every CUT that is not a deliberate signature and every STILL, then film again. Also record --video (real time) and watch it once start to end. Cells are samples on the engine clock; check a suspicious moment with --frames <dir> at full size before changing code — fine textures (1-px checkers, hairlines) shimmer as moiré under zoom or drift and show up as cuts. The opposite also happens: in a product-recording piece the real change is a few characters, a caret or a timer, below the STILL threshold, so a typing sequence can be reported as one long STILL. Crop the changing area across consecutive --frames before adding motion only to satisfy the detector.
391
424
  - Review as a picky viewer, not the author: list issues with time code, evidence (frame/metric), impact, severity (blocker / major / minor / note) and verdict (APPROVE / APPROVE_WITH_NOTES / REVISE). Check mechanics first (cuts, stills, overlaps, cropped text), then meaning, then taste; "not cinematic enough" without evidence is not a finding. Do at least two rounds of film → issues → fix, and finish one chapter seam to delivery quality before copying the technique to the others.
392
425
  - Static frames (render, --sheet, thumbnails, deep links) show settled pictures: no drift, no half-finished transitions. That is deliberate and is why the film strip is the motion check.
@@ -406,8 +439,14 @@ The host can draw an input/keyboard record after a type/press step, and toasts c
406
439
  - outline lists scenario and step ids. Use those ids in render/export; a deep link chooses where viewing starts and is not an access boundary. render takes qualified ids: --scenario-id <feature>.<option>.<scenario> and --step-id '<feature>.<option>.<scenario>#<n>' (the NOT_FOUND message lists the available scenario ids).
407
440
  - joplo render --scenario-id <id> --step-id <id> --out frame.png renders timeline state. --sheet --columns 3 renders every step with captions/narration (settled frames only). --film [--chain] [--every 250] samples real playback on the engine clock for motion review; --video records a webm. Both need the export component (npx joplo setup).
408
441
  - Exporting a video to publish elsewhere: render --video [--chain] starts at the cover fading out (loading and audio preparation are not recorded). --width 1920 --height 1080 (or --width 1080 --height 1920) sets the video resolution: the stage keeps its own aspect, is scaled sharply and centered on the theme background, so portrait output suits phone pages. The audio track is the media plugins' music plus generated narration: --voice real (default) mixes the clips npx joplo voice made for the current voice and holds each step for the real audio; lines without a clip use estimated timing silently and the CLI lists them, so generate voice first and record again (browser speech is never captured). --clean (or --hide cover,cursor,title,subtitles) leaves out player chrome; --srt <file> writes the subtitles timed to the video for the platform's own captions. Watch the result once; trust the listed missing lines, not the absence of an error.
442
+ - Direct composition geometry: --viewport 720x1280 sets the logical stage used by layout, camera, screen overlays and hit areas; --width 1080 --height 1920 sets output pixels. --no-frame removes the device bezel. Without --viewport, existing page geometry and desktop/mobile defaults remain unchanged. Use the same geometry for screenshots, --sheet, --film and --video before comparing them. --crop '[data-jid="picture"]' or --crop 0,0,450,800 crops screenshots, sheets, film analysis and frame files; numeric coordinates are CSS pixels relative to the export canvas, and selectors must resolve to one visible rectangle entirely inside it. A selector crop captures that rectangle of the composited page, including overlapping host chrome; it does not render the selected element in isolation. For source-component pixel checks, explicitly --hide cover,cursor,title,subtitles (or --clean), then inspect the clean crop. Keep the overlays for a separate final-output review. CUT/STILL fractions use the cropped image. A sampled crop must keep a fixed CSS width and height: changing dimensions raises a timestamped error rather than mixing incomparable pixel arrays; crop a stable outer frame when the subject moves. Video cropping uses logical geometry instead; --crop with --video is rejected.
443
+ - Sampled film/frame capture explicitly sets frame.sampling. The host waits for current-frame async presentation tasks and React commits before reading pixels; it uses wall-clock deadlines without moving the frozen engine clock. Decode/task failures stop the export with the sample timestamp. Real-time --video uses normal playback, not this per-frame handshake; inspect that recording separately.
444
+ - Public offline frames: npx joplo render <dir> --scenario-id <first> --chain --frames-out output/frames --fps 30 --viewport 720x1280 --no-frame exports JPEG files named by engine milliseconds and timeline.json. The supported library entry is renderFrames from @joplo-app/server; do not import dist/dev.js, private routes or __JOPLO_RECORD__. Targets use round(frameIndex * 1000 / fps), not repeated fractional runFor calls. Frames use cached clip durations silently and never call paid TTS; absent clips use estimated timing. Clean frames omit cover/cursor/title/subtitles by default. This is sampled replay with a 50 ms observation tolerance, not a promise of byte-identical scheduling or font rasterization.
445
+ - --timeline output/timeline.json accompanies --film and --video too. Schema version 1 includes actual observed step commits/ends, chapter boundaries, generic media snapshots and committed play/seek/stop/volume changes, camera cues and narration events (text, cached clip id/file/duration when present). engineMs is engine time; outputMs is recording/frame time. Narration endAt is observed relative to playback start and outputEndMs is already aligned to the output; do not infer a clip's start from stepPlan. Film defaults to estimated narration, while frames and video default to cached real duration; choose the matching path when aligning alternate audio or subtitles. Continuing chapters retain the whole-chain clock; completion explicitly names the final scenario and actual engine/output end time. Referenced cached narration and media bytes are copied beside the timeline into <name>.assets/; file paths are relative to the JSON and remain usable after the temporary server closes. Media assets include audioInfo when the compiler measured an AudioRegion: sourceSampleRate, contentStartFrame, contentFrames and cycleFrames describe decoded samples, not encoded bytes. Rescale those frame counts to the decoder sample rate, trim to the content start and loop only cycleFrames; starting an encoded file at byte/sample zero can expose encoder delay, calibration audio or guard padding. Asset failures are explicit errors; no TTS is generated.
446
+ - WebM needs only the export component. An output ending in .mp4 additionally uses local ffmpeg with H.264/AAC; missing ffmpeg or encoding failure is an explicit error. Encoding writes a private temporary file and commits only a complete result; failure preserves an existing output. Audio assets are content-validated and atomically written; use --overwrite to repair a corrupt cached export asset. --voice estimate is silent estimated narration and --voice off skips narration; background media remains independent. --silent omits every audio track while keeping cached narration timing. Video results expose measured calibration offset and audio/video end points. Review a decoded audio signal against early and late narration events before accepting a long alternate mix; calibration offsets are not proof every external encoder preserves sync.
447
+ - Film cost: --every changes saved cells only; --sample-ms changes image-analysis frequency (20–250 ms, default 50). Use 100–250 ms for a fast exploratory pass, then 50 ms for final CUT/STILL review: brief transitions can fall between coarse samples. The JSON includes wall time, baseline/end RSS, a 5-second RSS trace and process-lifetime peak RSS (Node only, not Chromium). Compare speed at the same sample interval, geometry and quality; coarse-mode wall times do not establish an equivalent-quality speedup, and concurrent load affects measurements. --checkpoint output/checkpoint.json commits progress at chapter boundaries; --resume replays the engine to restore state while reusing verified pixel analysis. Content hashes include project source/CSS/assets, voice cache bytes plus prepared clip duration/voice identity, host and enabled plugin runtime/build identities, browser/platform and every rendering option. Changes invalidate the checkpoint. Resume validates identical step identities and commit offsets within 50 ms, requires the same stable scenario/step/active state and recomputes the short chapter seam; larger divergence asks for a fresh render; never substitute an initial chapter state. --chapter-timeout 180000 limits wall processing per chapter and preserves the last committed checkpoint on failure. Keep output paths separate when running concurrent exports.
409
448
  - A full-size render can pass while a shorter board clips the input area. Check the actual visible hitbox with real pointer input in the board and the built site; DOM text existing is not proof it can be used.
410
- - Fixed render dimensions are a capture size; viewport belongs to page/layer. In a browser wait for fonts and [data-jcamera][data-camera-settled="1"] plus two animation frames. Do not mistake DOM progress for painted pixels.
449
+ - Fixed --width/--height dimensions are a capture size; --viewport explicitly overrides the logical page/layer geometry for export. In a browser wait for fonts and [data-jcamera][data-camera-settled="1"] plus two animation frames. Do not mistake DOM progress for painted pixels.
411
450
  - Test first input, drag, wheel, hover, keyboard, confirmation cancel/confirm, reset and resumed playback. Compare restored frames and direct jumps with pristine script frames. Explain unverified devices or audio behavior.
412
451
  - For layout, visual motion, shapes, charts and component APIs use the installed plugin skills. The engine has no built-in component vocabulary.
413
452
 
@@ -444,6 +483,7 @@ Read the relevant installed plugin skill for the visual component, its props and
444
483
  - "Notice this changed / this matters": highlight('id'). No zoom; a ring that pulses once.
445
484
  - One short reason next to an element: callout('id', 'Share after generation', { side? }). A note with a leader line; side is top / right / bottom / left, or omitted to pick the free side.
446
485
  - What a screen is made of, or an order of parts: numbered('input', 'preview', 'send'). Badges 1, 2, 3 (keep it to 5 or fewer).
486
+ - Use an existing clip to determine dwell: hold('voice', { pad: 0.4 }) for this step's narration or hold('audio', asset('./cue.wav'), { pad: 0 }) for a separate clip. This replaces caption reading floors, never required action/plugin-effect time; measured versus estimated is visible in check/outline. See demo for the max rule, preparation and timing sources.
447
487
  - Give viewers time to look (a chart, a comparison, a long result): hold(5). Autoplay stays at least 5 seconds (0.5–30, scaled by speed).
448
488
  Read the relevant installed plugin skill for the visual component, its props and recovery rules.
449
489
  - Hand-drawn circle / underline / box / arrow: mark('id', { kind }) (see demo).
@@ -591,7 +631,13 @@ Example: features/invite/works/a.tsx:12:5 warning UNBOUND_INTERACTIVE Interac
591
631
  - FROM_UNKNOWN (error): copy an existing slice key from the diagnostic's available-slices list; omit from for normal chapter continuation, or use from: null to restart.
592
632
  - WORK_EMPTY (info): add the first entry under scenarios, for example opening: chapter('Opening').system('Begin', narrate('Hello')). An empty work remains visible locally but is skipped in publish/review; explicit build --work selection fails.
593
633
  - WORK_DRAFT_SKIPPED (info): a draft was excluded from publish/review; remove draft: true only when it is ready. Explicit --work selection of a draft fails instead of publishing empty content.
594
- - FREE_ACTION_INVALID / FREE_TARGET_MISSING / FREE_EFFECT_INVALID: give each free reaction a valid targeted action in this work and only set, append or toast with valid leaf state paths. Move navigation, completion, media and plugin effects into flow steps; do not add event callbacks.
634
+ - FREE_ACTION_INVALID / FREE_TARGET_MISSING / FREE_EFFECT_INVALID: give each free reaction a valid targeted action in this work and only set, append or toast with valid leaf state paths. Move navigation, completion, media and plugin effects into flow steps; for a click, use the element's onClick instead.
635
+ - EVENT_EFFECT_INVALID: onClick takes effect helpers only (set, push, toast, go, uses; one or an array) with valid state paths. Move done(), camera, focus cues, narration and plugin effects into the step that clicks it.
636
+ - EVENT_NOT_INTERACTIVE: the element cannot be clicked, so onClick would never run; put it on a button, link, menu item or other interactive component.
637
+ - EVENT_UNSUPPORTED: only onClick takes effects for now; bind inputs with value={$.ui.x} and put other reactions in steps or work.free.
638
+ - EVENT_CONFLICT: the same id has different onClick on two stages of one work; give the elements different ids, or make the behavior identical (shared layout links).
639
+ - FREE_EVENT_CONFLICT: a work.free click reaction duplicates an element's onClick; move its effects into onClick and delete the free entry.
640
+ - STEP_REPEATS_EVENT (warning): the step writes a path its target's onClick already writes; delete the write from the step.
595
641
  - ACTION_INVALID / ACTION_UNKNOWN / ACTION_DATA_INVALID / ACTION_TARGET_INVALID / ACTION_DESTINATION_MISSING / ACTION_DESTINATION_INVALID / PLUGIN_ACTION_INVALID: check the action shape, enabled plugin declaration, exact payload fields/ranges, allowed target type, and drag/scroll endpoint. Read the plugin skill; keep endpoints in the current stage, then rerun check.
596
642
  - UNKNOWN_COMPONENT: Choose a supported name from components; do not invent components.
597
643
  - UNKNOWN_PLUGIN / PLUGIN_PARENT / PLUGIN_INVALID / PLUGIN_DUPLICATE / PLUGIN_RUNTIME_MISSING: plugin components need their package in config({ plugins: [...] }) once, written inside the parent named in the message; a missing runtime means reinstall the package (npx joplo skill plugins).
@@ -599,7 +645,7 @@ Example: features/invite/works/a.tsx:12:5 warning UNBOUND_INTERACTIVE Interac
599
645
  - PLUGIN_DATA_INVALID: plugin output failed its JSON/schema contract, or the complete published IR exceeds depth 100 after shared references are expanded (root depth 0, including primitive leaves). For depth errors, flatten the cache or replace nested objects with string ids, then rebuild and verify that the published output can be compared with itself. See npx joplo skill plugins for the output contract.
600
646
  - MISSING_ID / DUPLICATE_ID: Give interactive elements stable ids unique within the stage; update step references.
601
647
  - EFFECT_INVALID: Use documented helpers, with arrays for composition. Arbitrary or misspelled effect objects are rejected, never interpreted as done().
602
- - FUNCTION_PROP: Replace onClick and other callbacks with flow steps and state effects.
648
+ - FUNCTION_PROP: callbacks never run. Write onClick={set(...)} / onClick={[...]} with effects, or put the behavior in flow steps.
603
649
  - UNKNOWN_CASE / UNKNOWN_RULE / INVALID_REFERENCE: Check case, rule, and reference keys and their owning work.
604
650
  - UNKNOWN_SLOT / UNKNOWN_ROUTE / UNKNOWN_LAYOUT: Check routes, layouts, and Slot declarations; add elements only to existing locations.
605
651
  - FEATURE_ORDER_INVALID: feature({ order }) must be a finite number; omit it for natural folder-name order. NaN, Infinity and strings are invalid.
@@ -613,6 +659,10 @@ Example: features/invite/works/a.tsx:12:5 warning UNBOUND_INTERACTIVE Interac
613
659
  - SAY_TOO_LONG / NARRATE_TOO_LONG (warning): a say() or narrate() line over about 80 units (about 10 seconds aloud). Autoplay waits until it is read; say less or split the step.
614
660
  - SAY_EMPTY / NARRATE_EMPTY: say() needs the character's words, narrate() the narrator's. Remove it to fall back to the caption.
615
661
  - SAY_ROLE_CONFLICT: one step has say(…, { role }) lines from two different roles. A step reads one speaker; split the lines into consecutive steps.
662
+ - AUDIO_SOURCE_INVALID / AUDIO_INVALID: supply asset() audio bytes or an enabled localResource() reference, prepare a valid decodable audio artifact and check again. No remote URL fetching or provider fallback occurs for explicit audio.
663
+ - SPEECH_AUDIO_CONFLICT / HOLD_AUDIO_CONFLICT / HOLD_AUDIO_INVALID: one selected speech effect/clip and one audio-derived hold per step; pad is finite 0–30 seconds. Keep say(text, { role, audio }), not say(role, text).
664
+ - AUDIO_TIMING_MEASURED / AUDIO_TIMING_ESTIMATED (info): measured duration is from matching prepared audio; estimated means no matching measurement is available. Neither check nor outline creates TTS audio. voice reports a missing supplied resource in failed/total.failed even when every ordinary TTS clip is already cached; zero billable missing/chars does not mean all supplied audio is ready. Prepared content measurements take priority over conflicting plugin inspect hints. Changing the line, voice or content language invalidates the old cached timing. A measured duration plus pad still cannot truncate required actions or plugin effectHold.
665
+ - PACE_INVALID: work({ pace: { systemLead } }) accepts a finite 0–30 seconds (0 removes system pre-commit lead); omit it to preserve the default 0.9 seconds. hold() only controls post-commit dwell.
616
666
  - STREAM_PACE_INVALID: stream()'s pace is only 'voice' (follow this step's spoken line); omit it for model-output speed.
617
667
  - VOICE_CONFIG_INVALID: config({ voice }) takes { profile?, narrator?, roles?: { roleKey: 'voice' }, locales?: { ja: { narrator?, roles? } } } with non-empty strings. API keys never go in the config.
618
668
  - LOCALES_INVALID / LOCALES_UNDECLARED: config({ locales }) lists supported languages once each, source language first; every locales/<lang>.json must be listed there and must not be the source language. LOCALE_FILE_INVALID: the file must be one JSON object of "source text": "translation" strings.
@@ -705,6 +755,8 @@ Required after every round of development: start the follower before handing the
705
755
  npx joplo dev ./demo
706
756
  npx joplo feedback watch ./demo --local --follow --json
707
757
 
758
+ A successful initial compilation registers local review rounds before dev returns its ready link, including when joining another board; opening a browser is not required. If compilation fails, fix the diagnostics and wait for a successful compile before starting the watcher. Review rounds have no idle timeout. Source edits and compilation failures close a round; use feedback list --local --all --json to inspect its closing reason rather than treating it as expiration. The joined-project terminal notice identifies a dependency, not a replacement host: a joined project still depends on the original board process, so keep that terminal running. If it stops, restart dev and the watcher.
759
+
708
760
  --follow covers every option of the project and attaches by itself to the new round that each source edit opens, so no session id is needed. Give the reviewer the URL dev printed only after the follower is ready; a running board may use a different port or serve several projects. If they want to operate the UI themselves, hand over the link without navigating or submitting on their behalf.
709
761
 
710
762
  ## Local review: feedback without leaving the board
@@ -877,6 +929,8 @@ Deploy only dist output, not author source files. MCP, comments, and collaborati
877
929
  - The review version is a separate share (review: { shareId, url } in .joplo/cloud.json); it never replaces the main link. If the cloud rejects the review manifest, plain share retries once without it and still publishes.
878
930
 
879
931
  ## Narration (Joplo Cloud and your own keys)
932
+ - Limit narration generation before spending characters: npx joplo voice . --work short --dry-run --format json (standalone entry key or qualified feature work id). --scenario <exact scenario id> (alias --scenario-id) selects one chapter and follows its from predecessors; combining it with --work requires the chapter to belong to that work. Inspect data.locales[].details: workId, scenarioId, stepId, text, chars, missing and estimatedBillableChars. These are upper-bound estimates from the local cache, not a promise of actual charges: a remote Cloud cache hit is free. Shared text/voice is estimated once; silent steps show zero and valid cached clips show no billable characters. Then run the same command without --dry-run. Generation uses the existing cache and voice pins and never deletes clips outside this scope. Unknown/draft scopes fail before speech requests; omitted scope keeps all non-draft standalone works and picked feature works. Generate each required scope before build/share; scoping generation does not change what the later build selects.
933
+ - Declare the source language even for a single-language project: config({ locales: ['zh-CN'], ... }). The interface language is not the content language. Without config locales the clip metadata uses und (undetermined), and speech follows the text naturally; the tool does not infer a language from Chinese characters or label it English. Declared languages use their content locale in metadata and speech requests; existing clip keys remain text/voice based and do not require regeneration just to correct metadata.
880
934
  - Voice sources are only: browser voice (free, local), Joplo Cloud narration (signed in, no key, billed in characters), and official OpenAI / ElevenLabs (the user's own key; the API address is fixed). AiHubMix, OpenAI-compatible gateways with a custom Base URL and custom HTTP providers were removed: an old one shows "No longer supported" in the board. Audio it already generated still plays and is still bundled by build and share; it cannot make new audio. Ask the user to switch sources; do not edit ~/.joplo/voice/profiles.json yourself. An old OpenAI / ElevenLabs entry pointed at another address (a proxy), headers or response format is also "No longer supported": its key was for that proxy and is never sent to the official API; deleting it in Manage keys restores the official provider.
881
935
  - Default: a project that never chose a source and has no config voice.profile uses Joplo Cloud narration when the user is signed in, otherwise the browser voice. Choosing Browser voice in the board sticks. Re-sharing a project that never chose a source prefers valid audio already generated for the current default, then reuses matching text from the previous share. Different voices can coexist per language, role and text; the published playback index preserves their real fingerprints, including on a later update from another machine. Do not regenerate everything or explicitly change sources just to make an update include new clips; an explicit source change deliberately stops inheriting the old source.
882
936
  - After changing an automatic caption's label, input/selected value or keys, rebuild before sharing: audio is eligible only if its text matches the current caption in that clip's language. Valid local audio takes priority over reusable published audio only after this check. Stale text, unknown languages or mismatched cache keys are excluded from the site files and playback index; a step with no valid clip counts as missing and uses the browser voice. Do not treat matching step IDs or a previous successful generation as proof that a clip is current; preserve valid clips in the other interface languages instead of deleting the whole cache.
@@ -886,7 +940,7 @@ Deploy only dist output, not author source files. MCP, comments, and collaborati
886
940
  - Per-language voices are pinned: the first successful clip in a non-default content language records the Joplo Cloud voice picked for it (the cloud's recommended voice for that language: the current voice stays if it is recommended, otherwise the first recommended one of the same gender) in .joplo/voice/index.json (pins). Later builds, shares and machines use the pinned voice, so recommendation changes never invalidate audio or charge again; config({ voice: { locales } }) still overrides. Invalid pin languages, maps or voice IDs are ignored individually and valid entries remain; a missing/invalid entry uses the normal recommendation rule and is saved after successful generation. Do not delete the whole voice index or edit it by hand to recover pins, because it also indexes the audio cache.
887
941
  - Cloud unreachable, or an older cloud without narration: audio already generated still plays and ships, generation is unavailable (the board says so; npx joplo voice exits with NETWORK and sends nothing); --dry-run still estimates.
888
942
  - Characters: each clip costs Array.from(text).length characters, charged only when generation succeeds. Regenerating the same text and voice is served from cache for free, and audio already in .joplo/voice/ is never requested again. Previewing voices in the board (▶ Preview) plays prepared samples and costs nothing. Free accounts get a one-time trial; Pro gets a monthly allowance; top-up packs add more (bought in the console, <server>/usage).
889
- - Generating spends the user's characters. Before a large batch run npx joplo voice --dry-run (prints the steps and characters it would use and what would be left) and tell the user; generate when they asked for narration or agree. npx joplo voice --format json generates the missing clips for every picked option and content language; data.quota.totalRemainingChars is the cloud's own count after the last clip (never compute it yourself).
943
+ - Generating spends the user's characters. Before a large batch run npx joplo voice --work short --dry-run (omit --work for the whole project; prints the steps and characters it would use and what would be left) and tell the user; generate when they asked for narration or agree. npx joplo voice --format json generates the missing clips for every picked option and content language; data.quota.totalRemainingChars is the cloud's own count after the last clip (never compute it yourself).
890
944
  - npx joplo whoami (text and --format json data.voice) shows what is left: totalRemainingChars, period trial or month, resetsAt.
891
945
  - TTS_QUOTA_EXCEEDED exits 7: generation stopped; clips already made are kept and the remaining steps use the browser voice (the demo still plays; the board marks those steps "Browser voice"). Pass on error.details (neededChars, remainingChars, usageUrl for a top-up pack). Do not retry in a loop, switch providers, or buy anything on the user's behalf.
892
946
  - VOICE_NO_SOURCE: nothing can generate (signed out and nothing chosen, a missing OpenAI / ElevenLabs key, or config names a profile this machine lacks); ask the user to run npx joplo login in their own terminal or add a key in the board. VOICE_UNSUPPORTED: the chosen source is an old, removed one; ask the user to switch. EMAIL_UNVERIFIED: the user must verify their email (or sign in with GitHub) first. AUTH_REQUIRED / AUTH_EXPIRED exit 3 as for share.
@@ -928,7 +982,7 @@ Deploy only dist output, not author source files. MCP, comments, and collaborati
928
982
  - A sentence assembled from several state values (the words before the cursor + new words + the words after it, a label + a value) is joined with no separator. Chinese and Japanese need none; in languages that separate words with spaces, put the space inside the translations at the seams (a 'before' ending in a space, an 'after' starting with one). Successive stream() values must stay prefix-consistent in every language (each step's value = the previous one + the new words). Check both with a small script over locales/<lang>.json, then render --content <lang> the steps where pieces meet.
929
983
  - Longer languages overflow layouts written for the source: let headlines wrap instead of white-space: nowrap, and break long words with overflow-wrap: anywhere rather than word-break: break-all.
930
984
  - One link serves everyone: viewers get their browser language, ?lang=<lang> picks one, and languages the project lacks fall back to the source language. The board's content-language menu previews each language; npx joplo render --content <lang> screenshots one.
931
- - Narration: generate audio per language in the board, or npx joplo voice (every content language; --locale <lang> for one). Joplo Cloud narration sends the content language with each clip and picks the cloud's recommended voice for that language (a voice already in the recommendation stays); other providers pick a native preset voice when they have one. config({ voice: { locales: { ja: { narrator } } } }) overrides both. Languages without audio use the viewer's browser voice. Re-sharing reuses the audio already in the previous share (same text and voice). On another computer (no .joplo/cloud.json) run npx joplo share --private --no-review --update <share link>: it updates that share (free and Pro alike) and reuses its audio instead of regenerating it.
985
+ - Narration: generate audio per language in the board, or npx joplo voice (every content language; --locale <lang> for one). Joplo Cloud narration sends the content language with each clip and picks the cloud's recommended voice for that language (a voice already in the recommendation stays); other providers pick a native preset voice when they have one. config({ voice: { locales: { ja: { narrator } } } }) overrides both. Languages without audio use the viewer's browser voice. Re-sharing reuses the audio already in the previous share (same text and voice), including older project schema versions. The previous share is fetched explicitly as HTML; failure to read it stops publication instead of silently replacing generated audio with browser speech. If an update unexpectedly reports missing narration, stop and recover the previous audio before publishing; a change of worktree or project schema is not a reason to regenerate or spend characters. On another computer (no .joplo/cloud.json) run npx joplo share --private --no-review --update <share link>: it updates that share (free and Pro alike) and reuses its audio instead of regenerating it.
932
986
 
933
987
  ## Common publishing pitfalls
934
988
  - Do not patch CHOICE_REQUIRED by silently adding --private --no-review: ask both questions first; an agent choosing flags would violate the user decision even if no prompt appears.
@@ -969,13 +1023,13 @@ The engine supplies authoring, compilation, state, scheduling and host services.
969
1023
  ## Discover and use
970
1024
  1. Read package.json and config.plugins. npx joplo skill lists engine topics plus enabled plugin entries/topics; .claude/skills/joplo-plugins/SKILL.md indexes installed files.
971
1025
  2. Install a trusted author package, import its default manifest/factory and explicitly add it to config.plugins. Use the package's exact version when version-coupled to this CLI. A default export is either a manifest (list it as-is) or a factory that takes options (list its call, as its plugin guide shows); do not copy one package's form to another. A forgotten call is reported as config.plugins[i] is a function by check (PLUGIN_INVALID) and skill install, which then changes no skills; that message is a config fix, not missing dependencies.
972
- 3. Run npx joplo skill <plugin-id> or <plugin-id>/<topic>, then import components and effects directly from that package. For ids colliding with engine topics use plugin:<id>/<topic>. Do not invent component names or copy another plugin's conventions.
1026
+ 3. Run npx joplo skill <plugin-id> or <plugin-id>/<topic>, then import components and effects directly from that package. Installed skill names also work: joplo-plugin-<id> and joplo-plugin-<id>/<topic> resolve only enabled plugins. For ids colliding with engine topics use plugin:<id>/<topic> or the installed skill name. If a plugin guide is unavailable, check config.plugins and run npx joplo skill to list enabled guides. Do not invent component names or copy another plugin's conventions.
973
1027
  4. Run npx joplo skill install after adding/removing plugins. It synchronizes per-plugin files and removes unchanged generated files for removed plugins; edited files are protected (inspect --diff before --force). Outside a project it installs only engine skills.
974
1028
  5. A template may carry manually maintained plugin guides for reading before dependency installation; their absence does not prevent init. After install, rerun skill install to verify the live config; unresolved imports never mean a plugin was enabled successfully.
975
1029
  6. joplo components inspects only the enabled manifests; a named query gives that component's declarations and example. For full recipes/behavior read its plugin skill.
976
1030
 
977
1031
  ## Optional 3D
978
- The starter does not include 3D or its large browser dependency. To add it: npm install @joplo-app/plugin-3d@0.6.2; default-import scene3d from that package in joplo.config.ts, add scene3d to config.plugins, then run npx joplo skill install. Read npx joplo skill scene3d, scene3d/models and scene3d/generation for rendering, existing assets and optional local generation. A key is unnecessary for existing assets; dry-run before approving any generation.
1032
+ The starter does not include 3D or its large browser dependency. To add it: npm install @joplo-app/plugin-3d@0.7.2; default-import scene3d from that package in joplo.config.ts, add scene3d to config.plugins, then run npx joplo skill install. Read npx joplo skill scene3d, scene3d/models and scene3d/generation for rendering, existing assets and optional local generation. A key is unnecessary for existing assets; dry-run before approving any generation.
979
1033
 
980
1034
  ## Errors and trust
981
1035
  - UNKNOWN_PLUGIN: the element's author package is not enabled. Use its package provenance in the diagnostic to install/import it and add it to config.plugins. UNKNOWN_COMPONENT: no enabled manifest declares that element or intrinsic tag; read the installed catalogs.
@@ -989,6 +1043,7 @@ The starter does not include 3D or its large browser dependency. To add it: npm
989
1043
  - Runtime CSS imports and emitted local assets are bundled with the plugin: CSS is installed as a per-plugin style sheet, and local URLs become typed data URLs, including CSS images/fonts and imports above the normal inline threshold. Exercise source dev, npm prebuilt dev and the built site served by npx joplo preview (no other network) with real asset loading checks; a successful JS import alone does not prove styles or textures were delivered. Generated asset references that cannot be resolved fail explicitly.
990
1044
  - Verify both source development and the installed production package in a real browser. A prebuilt host must share its own React instance with dynamic plugin modules; serving a raw CommonJS dependency URL is not sufficient. Production dev and offline publish use the same bundling/shared-module contract.
991
1045
  - skill is the entry guide: when to use, how to enable/import, the smallest correct example, success checks, pitfalls and recovery. skillTopics maps topic keys to { description, body }; installed references and CLI topics come from this exact version. Do not put private project data or credentials in guides.
1046
+ - Compile frame hooks can query isVisible(sceneId, nodeId) for the current snapshot's declared visibility, including ancestor conditions and responsive gates. Use it to diagnose references to hidden elements without importing Core's condition evaluator into a plugin. It returns false for missing elements or scenes outside the current work; it does not measure CSS or DOM layout.
992
1047
  - Node hooks normalize/derive/frame/effect/validate trusted author data. Outputs must be finite JSON within supported depth/size, immutable across calls, identity-safe, and serializable. Functions/prototypes/cycles are rejected. Hooks and source instructions are never shipped as runtime IR.
993
1048
  - derive runs once for every node of your plugin and sees only that node's subtree. Validate references between elements (an arrow's from/to, a mark's target) from the container that holds them all, and return early for other nodes; validating at the referring node reports every target as unknown.
994
1049
  - Effect compilers return declarative writes, references, optional directorTarget, media commands, derived data and optional holdMs. Preserve source ordering.
@@ -1004,6 +1059,7 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1004
1059
  - frame contains resolved state, drawing snapshot, animate, clock/gesture, local playground and reset epoch. animate=false renders final layout; use ctx.hold while required assets load. Stop handled gesture propagation where ownership requires it.
1005
1060
  - Author-side helper functions can import isNode, isBind and bindPath from @joplo-app/kit. Use isNode(value) before traversing a JNode; use isBind(value) before bindPath(value) to distinguish bindings from plain objects. These are authoring values, not compiled IR or rendered DOM nodes; never infer a binding by coercing the proxy to a string.
1006
1061
  - The engine clock has one frame driver, owned by the player: it samples once per display frame while playing and stops when paused or idle. A plugin only reads the clock (frame.clock, useEngineFrame()); it never advances it, and never runs its own requestAnimationFrame or timer loop to move timeline animation, which would drift from pause, speed, video export and film strips.
1062
+ - Async sampled presentation: only when ctx.frame.sampling is true, register ctx.frameReady(signal => presentCurrentFrame(signal)) in a layout effect and return its cancellation function. Subscribe with useEngineFrame so each current engine frame gets its own task. Resolve only after pixels are committed; reject decode/presentation errors. Abort must remove listeners and prevent late drawing. The host cancels replaced clock/seek/scenario generations and unmounted owners, ignores their late failures, and waits until the current registry is quiet before capture (10 wall-clock seconds maximum). Never wait for a future engine tick or create a second animation clock. Legacy ctx.hold() gates initial loading and may wait for future RAF measurement/animation; it must not gate a frozen sample. Use frameReady for current-frame async pixels. This is presentation lifecycle, not IR or a timer/animation API; ordinary real-time playback does not set sampling.
1007
1063
  - frame.clock (and useCtx().clock) is a coarse frame: its object changes only when running, paused or speed changes, while timeMs/elapsedMs/rawMs read the live engine time whenever you read them. The stage does not re-render every frame, so a large scene stays smooth during playback. A React presenter that must redraw every frame (a camera, a dot moving along a path, typed text) calls useEngineFrame() from @joplo-app/kit/renderer, and should memoize the children it renders so its subtree does not re-render with it. Imperative mount/update components already get update() every frame. Reading clock.timeMs in render or as an effect dependency without useEngineFrame() freezes the animation.
1008
1064
  - Testing an engine or plugin change from your own checkout: npx joplo dev joins any board already running under the same JOPLO_HOME, and that board serves its own build, so your change will not appear. Start a separate board with JOPLO_HOME=<empty dir> npx joplo dev <dir> --port <free port>, and run feedback watch with the same JOPLO_HOME.
1009
1065
  - Use @joplo-app/kit/renderer and renderer-style services instead of internal source imports. kit/renderer is the stable layer (useCtx, useEngineFrame, useI18n, useRoot, useRootAttrs, RenderNode, rectOf, resolveProps, isSelfVisible, walkNodes, nodeLabel, motion). @joplo-app/kit/renderer-internal (rough strokes, responsive values, choices and layout regions, look) belongs to the in-repo standard library and may change in any release; do not import it from an optional or third-party plugin. Share React through the published bridge; clean up observers/listeners and animation on destroy.
@@ -1012,6 +1068,8 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1012
1068
  - data declares text and scope projections for node/step slots. Missing projection stops scoped publication; never leave cut content merely hidden in DOM. Translation changes only declared display paths, not ids, colors or structural values.
1013
1069
 
1014
1070
  ## Local resources and media
1071
+ - Read-only local compiler inspect(input, { directory, projectDir }) receives the project root to resolve relative source files and a temporary job directory. It receives no keys or allowSpend, and its process environment excludes account credential variables. This is a capability convention, not a filesystem sandbox: plugins remain trusted local code. Do not generate paid artifacts during inspection.
1072
+ - Resource references are objects, not URLs. Pass localResource(...) directly to a prop supported by its plugin; interpolating it into CSS url() produces JavaScript’s default object-string representation and LOCAL_RESOURCE_STRINGIFIED. This diagnostic recognizes that broken form in style and direct src/href/poster fields, not arbitrary prose or every possible string conversion. Use asset() for embedded CSS image URLs.
1015
1073
  - Node props can use localResource(plugin, compiler, input) from kit/plugin. The compiler extracts author-only input into ResourceRequest and leaves an opaque reference in IR; the renderer resolves it from the scoped asset table. No description or credentials belong in public IR.
1016
1074
  - Optional Node local entry exposes text-to-resource compilers. The host caches by compiler version/code and exact input, coalesces requests and records warnings for local failures. Requests/source text are not public IR.
1017
1075
  - A compiler may declare persistent:true and estimate(input):{credits}; its compile context receives projectDir, keys and allowSpend. Persistent output must be checked before credentials/network, and remains authoritative across compiler code updates. Only the explicit resources command grants allowSpend after displaying each estimate; ordinary host calls pass false. Do not infer permission from a configured key.
@@ -1019,6 +1077,7 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1019
1077
  - Local credential clients must serialize requests with JSON.stringify and never log request bodies. Malformed JSON returns a fixed 400 USAGE message without request excerpts; correct serialization locally without copying the secret into diagnostics. A 404 means the plugin/key pair is not declared by the current project: reload its enabled declarations and use an existing card instead of guessing identities.
1020
1078
  - Release ctx.hold on success, error, superseded requests and unmount, after drawing the ready frame. Recheck scope before inlining assets; unused resources must not ship.
1021
1079
  - Step effects can emit play/stop commands for named tracks. Each step's media snapshot is taken at the moment the step commits; between two commits the anchor advances by the planned time (the previous step's stay or estimated narration, whichever is longer, plus the next step's action demonstration: cursor travel, press, typing). Continuous playback follows the one engine clock; jumping/replaying resets to the same snapshot, which now lands close to where continuous playback would be. Pause, speed, fade and narration ducking are host behavior, synthesis belongs to the plugin.
1080
+ - Optional media startDelayMs waits 0–60000 engine ms after commit; source offset and one-shot lifetime advance only after remaining wait reaches zero. Snapshots retain original startDelayMs, delayRemainingMs and deterministic startEventId for explicit delayed plays; inheritance preserves identity and seek restores the snapshot. Fade-in starts with source playback. duck defaults true (narration gain multiplier .25), while false exempts only that track. maxRetiring (integer 0–32, default absent/unbounded) limits exiting slots per named track, excludes current, and preserves the newest retirement. These policies add no automatic hold and do not create streaming or a nested audio timeline. Recorded timeline media snapshots retain the fields; observed play commits are not an acoustic-onset measurement.
1022
1081
  - Free reactions are playback data: public payloads retain work.free after scope filtering, while authoring notes and source positions are stripped. Validate the actual built site (npx joplo preview) with arbitrary input and a secondary reaction; replay-only tests cannot detect a dropped free map.
1023
1082
  - Scope before writing media. Build writes validated resources as separate asset files (assets/<hash>.<ext>, uploaded once per content by share) and inlines plugin runtimes; the site needs HTTP but no other network. In runtimes, accept asset URLs with embeddedAsset(src, kind) from @joplo-app/kit/plugin instead of testing for data: URLs. Video mixing capability is separate from playback support—state its actual limit.
1024
1083
 
package/dist/load.d.ts CHANGED
@@ -14,7 +14,9 @@ export declare function loadLocales(root: string): {
14
14
  files: Record<string, string>;
15
15
  diagnostics: Diagnostic[];
16
16
  };
17
- export declare function loadAuthoring(root: string, importer: Importer): Promise<{
17
+ export declare function loadAuthoring(root: string, importer: Importer, options?: {
18
+ work?: string;
19
+ }): Promise<{
18
20
  authoring: AuthoringProject | null;
19
21
  diagnostics: Diagnostic[];
20
22
  }>;
package/dist/load.js CHANGED
@@ -112,7 +112,7 @@ export function loadLocales(root) {
112
112
  }
113
113
  return { locales, files, diagnostics };
114
114
  }
115
- export async function loadAuthoring(root, importer) {
115
+ export async function loadAuthoring(root, importer, options = {}) {
116
116
  // 步骤和规则的源位置来自调用栈;开启原生 source map,保证行号指向 TSX 源码而不是转译产物。
117
117
  process.setSourceMapsEnabled?.(true);
118
118
  const r = resolve(root);
@@ -183,8 +183,14 @@ export async function loadAuthoring(root, importer) {
183
183
  }
184
184
  };
185
185
  await walk(join(r, 'routes'), '');
186
+ // Resource commands can load one work without evaluating unrelated author modules.
187
+ const selected = options.work;
188
+ const standaloneSelected = !!selected && list(join(r, 'works')).some(f => /\.(tsx|ts)$/.test(f) && !isDir(join(r, 'works', f)) && stem(f) === selected);
189
+ let foundWork = false;
186
190
  const features = {};
187
191
  for (const fid of list(join(r, 'features'))) {
192
+ if (selected && (standaloneSelected || !list(join(r, 'features', fid, 'works')).some(f => /\.(tsx|ts)$/.test(f) && `${fid}.${stem(f)}` === selected)))
193
+ continue;
188
194
  const fd = join(r, 'features', fid);
189
195
  if (!isDir(fd))
190
196
  continue;
@@ -200,22 +206,26 @@ export async function loadAuthoring(root, importer) {
200
206
  continue;
201
207
  const works = {};
202
208
  for (const o of list(join(fd, 'works'))) {
203
- if (!/\.(tsx|ts)$/.test(o))
209
+ if (!/\.(tsx|ts)$/.test(o) || selected && `${fid}.${stem(o)}` !== selected)
204
210
  continue;
211
+ foundWork = true;
205
212
  const v = await load(join(fd, 'works', o), 'work');
206
213
  if (v)
207
214
  works[stem(o)] = v;
208
215
  }
209
- features[fid] = { def, works };
216
+ features[fid] = { def: selected ? { ...def, pick: Object.keys(works)[0] } : def, works };
210
217
  }
211
218
  const works = {};
212
219
  for (const f of list(join(r, 'works'))) {
213
- if (!/\.(tsx|ts)$/.test(f) || isDir(join(r, 'works', f)))
220
+ if (!/\.(tsx|ts)$/.test(f) || isDir(join(r, 'works', f)) || selected && (!standaloneSelected || stem(f) !== selected))
214
221
  continue;
222
+ foundWork = true;
215
223
  const v = await load(join(r, 'works', f), 'work');
216
224
  if (v)
217
225
  works[stem(f)] = v;
218
226
  }
227
+ if (selected && !foundWork)
228
+ fail(cfgFile, `Work does not exist: ${selected}`, 'WORK_NOT_FOUND');
219
229
  if (!config)
220
230
  return { authoring: null, diagnostics: diags };
221
231
  const loc = loadLocales(r);
package/dist/media.js CHANGED
@@ -1,7 +1,15 @@
1
1
  /** Pure clock projection. Neither resource compilation nor plugin semantics run here. */
2
2
  export function advanceMedia(snapshot, elapsedMs) {
3
3
  const elapsed = Math.max(0, elapsedMs);
4
- return Object.fromEntries(Object.entries(snapshot).flatMap(([id, t]) => t.stopAfterMs !== undefined && elapsed >= t.stopAfterMs ? [] : [[id, { ...t, offsetMs: t.offsetMs + elapsed, ...(t.stopAfterMs !== undefined ? { stopAfterMs: t.stopAfterMs - elapsed, volume: t.volume * (1 - elapsed / t.stopAfterMs) } : {}) }]]));
4
+ return Object.fromEntries(Object.entries(snapshot).flatMap(([id, t]) => {
5
+ const activeMs = Math.max(0, elapsed - (t.delayRemainingMs ?? t.startDelayMs ?? 0));
6
+ if (t.stopAfterMs !== undefined && elapsed >= t.stopAfterMs || t.endAfterMs !== undefined && activeMs >= t.endAfterMs)
7
+ return [];
8
+ return [[id, { ...t, offsetMs: t.offsetMs + activeMs,
9
+ ...(t.startDelayMs !== undefined || t.delayRemainingMs !== undefined ? { delayRemainingMs: Math.max(0, (t.delayRemainingMs ?? t.startDelayMs ?? 0) - elapsed) } : {}),
10
+ ...(t.endAfterMs !== undefined ? { endAfterMs: t.endAfterMs - activeMs } : {}),
11
+ ...(t.stopAfterMs !== undefined ? { stopAfterMs: t.stopAfterMs - elapsed, volume: t.volume * (1 - elapsed / t.stopAfterMs) } : {}) }]];
12
+ }));
5
13
  }
6
14
  export function mediaAt(project, scenarioId, position, elapsedMs = 0) {
7
15
  const sc = project.scenarios[scenarioId];
package/dist/outline.d.ts CHANGED
@@ -26,6 +26,11 @@ export type OutlineScenario = {
26
26
  /** 估算播放时长(毫秒,1×)。 */
27
27
  ms: number;
28
28
  cards: number;
29
+ /** Explicit audio timing facts; unavailable clips remain visibly estimated. */
30
+ audioTiming?: {
31
+ measured: number;
32
+ estimated: number;
33
+ };
29
34
  /** 第一步 / 最后一步是过渡卡。 */
30
35
  opening: boolean;
31
36
  ending: boolean;
package/dist/outline.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * 估算按 1× 速度、用 IR 里的英文字幕兜底,不含鼠标移动与逐字输入,所以只是“约”。
6
6
  */
7
7
  import { entriesOf, scenariosOf, sliceKey } from "./entries.js";
8
- import { scenarioPlanMs } from "./step-plan.js";
8
+ import { stepPlan, scenarioPlanMs } from "./step-plan.js";
9
9
  import { JoploError } from "./result.js";
10
10
  /** 一个场景按 1× 自动播放大约多久(毫秒):每一步的时间计划(stepPlan:操作演示 + 停留与朗读估算中较长者)之和。 */
11
11
  export function scenarioEstimateMs(project, scenario) {
@@ -43,6 +43,7 @@ export function outline(project, opts = {}) {
43
43
  description: s.description,
44
44
  steps: s.steps.length,
45
45
  ms: scenarioEstimateMs(project, s),
46
+ ...(s.steps.some(st => st.holdFor) ? { audioTiming: { measured: s.steps.filter(st => st.holdFor && stepPlan(project, st).timingSource === 'measured').length, estimated: s.steps.filter(st => st.holdFor && stepPlan(project, st).timingSource === 'estimated').length } } : {}),
46
47
  cards: s.steps.filter((st) => st.action.type === 'card').length,
47
48
  opening: s.steps[0]?.action.type === 'card',
48
49
  ending: s.steps.length > 0 && s.steps.at(-1).action.type === 'card',
@@ -1,7 +1,7 @@
1
1
  import type { Action, Effect, Project } from './schema.js';
2
2
  import { explainClick, type PlayState } from './player.js';
3
3
  export type LocalEffect = Extract<Effect, {
4
- type: 'set' | 'append' | 'toast';
4
+ type: 'set' | 'append' | 'toast' | 'navigate';
5
5
  }>;
6
6
  /** Only local deltas. Dropping this object restores the exact scripted state. Never serialized in IR or URLs. */
7
7
  export type Playground = {
@@ -36,3 +36,8 @@ export declare function arbitrateAction(project: Project, timeline: PlayState, a
36
36
  }): ActionVerdict;
37
37
  export declare function applyPlayground(layer: Playground | null, effects: readonly LocalEffect[]): Playground;
38
38
  export declare function playgroundState(timeline: PlayState, layer: Playground | null): PlayState;
39
+ /**
40
+ * The stage the viewer is looking at. A reported stage other than the timeline's page (a layer) stays authoritative;
41
+ * otherwise local navigation in the playground decides. Dropping the layer returns to the timeline's page.
42
+ */
43
+ export declare function shownSceneOf(timeline: PlayState, layer: Playground | null, shown: string | null): string;
@@ -69,7 +69,8 @@ export function arbitrateAction(project, timeline, action, opts = {}) {
69
69
  const available = (input) => !('target' in input) || !!findNode(scene, input.target) && isNodeVisible(scene, input.target, view) && !isNodeDisabled(findNode(scene, input.target).node, view);
70
70
  const matches = (expected) => inputs.some(input => available(input) && actionMatches(canonicalAction(expected, scene, view), canonicalAction(input, scene, view), expected.type === 'plugin' ? pluginActionSpec(project, expected.name) : undefined));
71
71
  const next = scenario.steps[timeline.position];
72
- if (next && !timeline.completed && matches(next.action) && !checkStep(project, scenario, timeline, next))
72
+ // A page reached only in the local layer never advances the timeline: the scripted step belongs to the timeline's page.
73
+ if (next && !timeline.completed && view.sceneId === timeline.sceneId && matches(next.action) && !checkStep(project, scenario, timeline, next))
73
74
  return { kind: 'advance' };
74
75
  const candidates = (opts.index ?? actionIndex(project, scenario.workId)).filter(entry => entry.scenarioId !== scenario.id && entry.sceneId === scene.id && matches(entry.action));
75
76
  if (candidates.length)
@@ -77,8 +78,11 @@ export function arbitrateAction(project, timeline, action, opts = {}) {
77
78
  const reaction = Object.values(project.works[scenario.workId]?.free ?? {}).find(r => matches(r.action));
78
79
  const native = nativeEffects(scene, view, opts.native ?? action);
79
80
  const nativeFocus = action.type === 'click' && available(action) && !!findNode(scene, action.target)?.node.traits?.native;
81
+ // Local navigation (element onClick go()) only reaches stages of this work; publication keeps the shared public stages.
82
+ const localStage = (sceneId) => { const target = project.scenes[sceneId]; return !!target && (target.workId === scenario.workId || project.mode === 'publish' && target.workId === null); };
83
+ const local = (e) => e.type === 'set' || e.type === 'append' || e.type === 'toast' || e.type === 'navigate' && localStage(e.sceneId);
80
84
  if (reaction || native.length || nativeFocus)
81
- return { kind: 'free', effects: [...native, ...(reaction?.effects.filter((e) => e.type === 'set' || e.type === 'append' || e.type === 'toast') ?? [])] };
85
+ return { kind: 'free', effects: [...native, ...(reaction?.effects.filter(local) ?? [])] };
82
86
  const hint = 'target' in action ? explainClick(project, timeline, action.target, scene.id) : { kind: 'static' };
83
87
  // Legacy explainClick intentionally accepts a target alone; never let it bypass action matching.
84
88
  return { kind: 'hint', verdict: hint.kind === 'advance' ? { kind: 'out_of_order', label: '', expectedCaption: next?.caption ?? null } : hint };
@@ -95,6 +99,14 @@ export function playgroundState(timeline, layer) {
95
99
  view.toasts = [{ id: `free-${i}`, text: effect.text, tone: effect.tone }];
96
100
  continue;
97
101
  }
102
+ if (effect.type === 'navigate') {
103
+ if (effect.sceneId !== view.sceneId) {
104
+ view.sceneStack.push(view.sceneId);
105
+ view.sceneId = effect.sceneId;
106
+ view.toasts = [];
107
+ }
108
+ continue;
109
+ }
98
110
  const [root, ...keys] = effect.path.split('.');
99
111
  if (!['ui', 'data', 'inputs'].includes(root) || !keys.length || keys.some(k => ['__proto__', 'constructor', 'prototype'].includes(k)))
100
112
  continue;
@@ -109,3 +121,12 @@ export function playgroundState(timeline, layer) {
109
121
  }
110
122
  return view;
111
123
  }
124
+ /**
125
+ * The stage the viewer is looking at. A reported stage other than the timeline's page (a layer) stays authoritative;
126
+ * otherwise local navigation in the playground decides. Dropping the layer returns to the timeline's page.
127
+ */
128
+ export function shownSceneOf(timeline, layer, shown) {
129
+ if (shown && shown !== timeline.sceneId)
130
+ return shown;
131
+ return playgroundState(timeline, layer).sceneId;
132
+ }
@@ -14,6 +14,12 @@ export type CompileOptions = {
14
14
  compiler: string;
15
15
  input: string;
16
16
  }) => LocalResourceInfo | undefined;
17
+ /** Host-only measured durations; callbacks and local cache paths never enter IR. */
18
+ audioDurationFor?: (source: string) => number | undefined;
19
+ voiceDurationFor?: (stepId: string) => {
20
+ durationMs: number;
21
+ key: string;
22
+ } | undefined;
17
23
  pluginOptions?: Record<string, Record<string, unknown>>;
18
24
  };
19
25
  export declare function enabledPlugins(configured: unknown): unknown[];
@@ -44,6 +50,13 @@ export declare class PluginCompiler {
44
50
  private frozenRoot;
45
51
  private frozenScenes;
46
52
  private infoOf;
53
+ readonly embeddedAudio: Record<string, string>;
54
+ voiceDuration(stepId: string): {
55
+ durationMs: number;
56
+ key: string;
57
+ } | undefined;
58
+ audioSource(value: unknown, source?: string): string;
59
+ audioDuration(source: string): number | undefined;
47
60
  readonly defs: Map<string, PluginDef>;
48
61
  readonly info: Record<string, PluginInfo>;
49
62
  constructor(configured: unknown, report: PluginReport, source?: string, options?: CompileOptions);
@@ -62,7 +75,12 @@ export declare class PluginCompiler {
62
75
  track: string;
63
76
  action: "play";
64
77
  resource: string;
78
+ oneShot?: boolean;
79
+ durationMs?: number;
65
80
  offsetMs?: number;
81
+ startDelayMs?: number;
82
+ duck?: boolean;
83
+ maxRetiring?: number;
66
84
  volume?: number;
67
85
  loop?: boolean;
68
86
  fadeMs?: number;