@joplo-app/core 0.7.1 → 0.7.3

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) {
@@ -157,7 +160,7 @@ Success: check reports 0 errors; outline --work explainer shows the intended sli
157
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.
158
161
 
159
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.
160
- - 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.
161
164
 
162
165
  ## Structure and files
163
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.
@@ -175,21 +178,25 @@ Success: check reports 0 errors; outline --work explainer shows the intended sli
175
178
  For tools reading IR from @joplo-app/core, use entriesOf/entryOf for entries, featuresOf for real features in entryIds order, rolesOf(project, workId) for shared or standalone roles, sliceKey(scenario) for its author key, and visibleRoutes(project) for paths without the internal blank page. Follow scenario.workId and the projection; never split ids to infer ownership.
176
179
 
177
180
  ## Engine-only example
178
- In features/<f>/works/<key>.tsx, buildScreen is project code using the installed plugins' components. It must return enabled elements with ids email, send and result; read those plugin skills for the actual view code.
181
+ In features/<f>/works/<key>.tsx, buildScreen is project code using the installed plugins' components. It must return enabled elements with ids email, send and result, and put the onClick it receives on send; read those plugin skills for the actual view code.
179
182
  \`\`\`ts
180
- import { $, work, flow, page, set, done } from '@joplo-app/kit';
183
+ import { $, work, flow, page, set, done, mock, response } from '@joplo-app/kit';
181
184
  import { buildScreen } from './screen';
185
+ // The request and its possible results, written once
186
+ const sendLink = mock('sendLink', {
187
+ accepted: response('Accepted', set($.ui.sending, false), set($.ui.sent, true), done('Link sent')),
188
+ unknown: response('No account', set($.ui.sending, false), set($.ui.error, 'Check the address')),
189
+ });
182
190
  export default work({
183
191
  title: 'A · Recover access', summary: 'A retry keeps the entered address',
184
- routes: { '/reset': page({ title: 'Reset password' }, buildScreen()) },
192
+ routes: { '/reset': page({ title: 'Reset password' }, buildScreen({ onSend: [set($.ui.sending, true), sendLink] })) },
185
193
  state: { ui: { sending: false, error: '', sent: false } },
186
194
  scenarios: {
187
- retry: flow('Correct an address and retry', { cases: ['unknown_email'], start: '/reset' })
188
- .type('email', 'ana@example.invalid').click('send', set($.ui.sending, true))
189
- .system('No account', set($.ui.sending, false), set($.ui.error, 'Check the address'))
195
+ // The first send finds no account, the retry is accepted
196
+ retry: flow('Correct an address and retry', { cases: ['unknown_email'], start: '/reset', api: { sendLink: ['unknown', 'accepted'] } })
197
+ .type('email', 'ana@example.invalid').click('send', 'Send the link')
190
198
  .type('email', 'ana@example.com', set($.ui.error, ''))
191
- .click('send', set($.ui.sending, true))
192
- .system('Accepted', set($.ui.sending, false), set($.ui.sent, true), done('Link sent')),
199
+ .click('send', 'Send again'),
193
200
  },
194
201
  });
195
202
  \`\`\`
@@ -197,15 +204,49 @@ Declare both success and recovery cases in the feature. View code belongs to the
197
204
 
198
205
  ## Steps and effects
199
206
  - chapter(name, options) uses the same slice options as flow(); its default predecessor is the previous chapter, with from: null to restart. Use all chapter() or all flow() in one work.
200
- - flow(name, { cases?, start?, state?, from?, autoplay?, layer?, description?, expected?, mock?, outcome?, actionEntry? }). state overrides work state. description is the cover sentence; expected describes what the viewer should observe.
207
+ - flow(name, { cases?, start?, state?, from?, autoplay?, layer?, description?, expected?, mock?, outcome?, actionEntry?, api? }). The mock option is only the badge label (for example 'Mocked failure'); api picks mock() outcomes (System responses below). state overrides work state. description is the cover sentence; expected describes what the viewer should observe.
201
208
  - autoplay: false keeps an optional scenario selectable through a fork, chapter list or deep link, but skips it in sequential published-site playback. Playing that scenario manually stops at its end. Default/true preserves declaration order.
202
209
  - from: 'previousKey' continues that scenario's final route, ui/data/inputs and director layer. Validate steps and automatic captions against that ending page; dependency order does not change chapter order. Do not combine from with start. layer overrides the initial director layer.
203
210
  - .click(id), .type(id, value), .select(id, value), .toggle(id, boolean), .press(keys), .back(), .drag(id, destination), .hover(id, ms), .scroll(id, destination), .act(pluginAction, id, data). Read demo and the action-owning plugin skill for recognition requirements.
204
- - .system('event', ...effects) models a response, not a real request. .card() creates a transition. Strings are captions; other arguments are effects. Step arguments and card accept effect arrays.
211
+ - .system('event', ...effects) models a response, not a real request. For the response to something the viewer triggers (send, save, load), write a mock() instead so the viewer gets it after taking over; keep .system() for story events (time passes, another person acts). .card() creates a transition. Strings are captions; other arguments are effects. Step arguments and card accept effect arrays.
205
212
  - 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.
206
213
  - 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.
207
214
  - 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.
208
- - 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.
215
+ - 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).
216
+
217
+ ## Element events (onClick)
218
+ 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:
219
+ \`\`\`tsx
220
+ // props on interactive elements from an installed plugin (read its skill for the component names)
221
+ id="btn_invite" disabled={not($.ui.isAdmin)} onClick={[set($.ui.inviteOpen, true), uses('admin_only')]}
222
+ id="btn_cancel" onClick={set($.ui.inviteOpen, false)}
223
+ id="nav_settings" onClick={go('/settings')}
224
+ // the step only says what the viewer does and why
225
+ flow('Invite a teammate').click('btn_invite', 'The admin opens the invite dialog')
226
+ \`\`\`
227
+ - onClick takes one effect or an array: set, push, toast, go, uses and a mock() request. A scripted .click(id) runs the element's onClick first, then the step's own effects. Keep captions, narrate(), say(), camera and focus cues and done() in the steps; the request's result goes in mock().
228
+ - 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.
229
+ - 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.
230
+ - 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).
231
+ - Only onClick takes effects for now (EVENT_UNSUPPORTED). Inputs keep value={$.ui.name} and the typed value; put follow-up reactions in the step.
232
+ - 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.
233
+
234
+ ## System responses (mock / response)
235
+ Write each request and its possible results once, then let each slice pick the result it shows:
236
+ \`\`\`tsx
237
+ const sendInvite = mock('sendInvite', {
238
+ ok: response('Request succeeded (mock)', 'Sent', set($.ui.sending, false), set($.ui.open, false), done('Invite sent')),
239
+ timeout: response('Request timed out (mock)', 'Input kept', set($.ui.sending, false), set($.ui.error, 'Timeout')),
240
+ });
241
+ // on the element: onClick={[set($.ui.sending, true), sendInvite]}
242
+ success: flow('Send').click('send', 'Send the invite'), // first outcome (ok)
243
+ retry: flow('Retry', { api: { sendInvite: ['timeout', 'ok'] } }).click('send').click('send', 'Retry'),
244
+ \`\`\`
245
+ - response(name, ...args) takes the same arguments as .system(name, ...args): the first string is its caption, the rest are effects, including done(), narrate() and camera.
246
+ - In the script, every call to a mock (in an element's onClick or a step's effects) adds one system step right after that step. flow({ api: { name: [outcomes] } }) uses one outcome per call, in order; a mock the slice does not list uses its first outcome.
247
+ - After the viewer takes over, clicking the element applies the first outcome's local effects (set, push, toast, go) at once; done(), narration and camera stay in the script.
248
+ - The mock name is unique within a work; outcomes are the cases the design must show. Every outcome should appear in some slice (MOCK_OUTCOME_UNUSED).
249
+ - A response cannot call another mock. Use .system() for an event nobody triggers on stage.
209
250
 
210
251
  ## Reusable effect factories
211
252
  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.
@@ -312,6 +353,8 @@ When the board or the published site reads a demo aloud, each step reads, in ord
312
353
  - 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.
313
354
  - say() is first person, what the character would really say; narration about the characters goes in narrate().
314
355
  - 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.
356
+ - 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.
357
+ - 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.
315
358
  - 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().
316
359
  - 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.
317
360
  Wrong, it reads the interface: .click('share', 'Xiaoyu shares the itinerary', narrate('Click Share to share the itinerary.'))
@@ -350,13 +393,13 @@ The engine renders scripted state at step k, plus disposable local exploration.
350
393
  ## Playback and free exploration
351
394
  - 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.
352
395
  - 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.
353
- - 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.
396
+ - 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.
354
397
  - 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.
355
398
  - 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.
356
399
  - 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.
357
400
  - 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.
358
401
  - 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.
359
- - 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.
402
+ - 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.
360
403
 
361
404
  ## Actions and the shared clock
362
405
  - 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.
@@ -382,8 +425,9 @@ Start playback before testing stage gestures: covers and transition cards intent
382
425
  - 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.
383
426
  - 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.
384
427
  - 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.
385
- - 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. Read the media plugin guide for concrete authoring remedies.
386
- - 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.
428
+ - 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.
429
+ - 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.
430
+ - 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.
387
431
 
388
432
  ## Make it play like a film, not slides (Required for video-like pieces)
389
433
  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.
@@ -392,6 +436,8 @@ Viewers call a piece "a slide deck" when pictures swap in one frame and then sit
392
436
  - 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.
393
437
  - 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.
394
438
  - 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.
439
+ - 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.
440
+ - 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.
395
441
  - 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.
396
442
  - 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.
397
443
  - 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).
@@ -414,7 +460,8 @@ The host can draw an input/keyboard record after a type/press step, and toasts c
414
460
  - 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).
415
461
  - 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).
416
462
  - 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.
417
- - 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. 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.
463
+ - 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.
464
+ - 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.
418
465
  - 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.
419
466
  - --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.
420
467
  - 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.
@@ -457,6 +504,7 @@ Read the relevant installed plugin skill for the visual component, its props and
457
504
  - "Notice this changed / this matters": highlight('id'). No zoom; a ring that pulses once.
458
505
  - 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.
459
506
  - 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).
507
+ - 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.
460
508
  - 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).
461
509
  Read the relevant installed plugin skill for the visual component, its props and recovery rules.
462
510
  - Hand-drawn circle / underline / box / arrow: mark('id', { kind }) (see demo).
@@ -604,7 +652,20 @@ Example: features/invite/works/a.tsx:12:5 warning UNBOUND_INTERACTIVE Interac
604
652
  - 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.
605
653
  - 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.
606
654
  - 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.
607
- - 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.
655
+ - 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.
656
+ - 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.
657
+ - 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.
658
+ - EVENT_UNSUPPORTED: only onClick takes effects for now; bind inputs with value={$.ui.x} and put other reactions in steps or work.free.
659
+ - 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).
660
+ - FREE_EVENT_CONFLICT: a work.free click reaction duplicates an element's onClick; move its effects into onClick and delete the free entry.
661
+ - STEP_REPEATS_EVENT (warning): the step writes a path its target's onClick already writes; delete the write from the step.
662
+ - MOCK_INVALID: mock(name, outcomes) needs an id-like name and at least one response('Event name', ...effects); a response cannot call another mock.
663
+ - MOCK_CONFLICT: two different mocks share one name in a work; give each request its own name, or reuse the same mock object.
664
+ - MOCK_OUTCOME_UNKNOWN: flow({ api }) names an outcome the mock does not have; copy one from the outcomes listed in the message.
665
+ - MOCK_OUTCOMES_EXHAUSTED: the slice calls the mock more times than flow({ api }) lists outcomes; list one outcome per call, in order.
666
+ - MOCK_OUTCOMES_LEFTOVER: flow({ api }) lists more outcomes than the slice calls that mock (or names a mock the slice never calls); remove the extra entries.
667
+ - MOCK_OUTCOME_UNUSED (warning): no slice of the work shows this outcome; add a slice that picks it with flow({ api }), or delete the outcome.
668
+ - FLOW_API_INVALID: flow({ api }) maps mock names to arrays of outcome names, for example api: { sendInvite: ['timeout', 'ok'] }.
608
669
  - 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.
609
670
  - UNKNOWN_COMPONENT: Choose a supported name from components; do not invent components.
610
671
  - 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).
@@ -612,7 +673,7 @@ Example: features/invite/works/a.tsx:12:5 warning UNBOUND_INTERACTIVE Interac
612
673
  - 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.
613
674
  - MISSING_ID / DUPLICATE_ID: Give interactive elements stable ids unique within the stage; update step references.
614
675
  - EFFECT_INVALID: Use documented helpers, with arrays for composition. Arbitrary or misspelled effect objects are rejected, never interpreted as done().
615
- - FUNCTION_PROP: Replace onClick and other callbacks with flow steps and state effects.
676
+ - FUNCTION_PROP: callbacks never run. Write onClick={set(...)} / onClick={[...]} with effects, or put the behavior in flow steps.
616
677
  - UNKNOWN_CASE / UNKNOWN_RULE / INVALID_REFERENCE: Check case, rule, and reference keys and their owning work.
617
678
  - UNKNOWN_SLOT / UNKNOWN_ROUTE / UNKNOWN_LAYOUT: Check routes, layouts, and Slot declarations; add elements only to existing locations.
618
679
  - FEATURE_ORDER_INVALID: feature({ order }) must be a finite number; omit it for natural folder-name order. NaN, Infinity and strings are invalid.
@@ -626,6 +687,9 @@ Example: features/invite/works/a.tsx:12:5 warning UNBOUND_INTERACTIVE Interac
626
687
  - 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.
627
688
  - SAY_EMPTY / NARRATE_EMPTY: say() needs the character's words, narrate() the narrator's. Remove it to fall back to the caption.
628
689
  - SAY_ROLE_CONFLICT: one step has say(…, { role }) lines from two different roles. A step reads one speaker; split the lines into consecutive steps.
690
+ - 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.
691
+ - 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).
692
+ - 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.
629
693
  - 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.
630
694
  - STREAM_PACE_INVALID: stream()'s pace is only 'voice' (follow this step's spoken line); omit it for model-output speed.
631
695
  - 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.
@@ -719,6 +783,8 @@ Required after every round of development: start the follower before handing the
719
783
  npx joplo dev ./demo
720
784
  npx joplo feedback watch ./demo --local --follow --json
721
785
 
786
+ 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.
787
+
722
788
  --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.
723
789
 
724
790
  ## Local review: feedback without leaving the board
@@ -985,13 +1051,13 @@ The engine supplies authoring, compilation, state, scheduling and host services.
985
1051
  ## Discover and use
986
1052
  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.
987
1053
  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.
988
- 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.
1054
+ 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.
989
1055
  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.
990
1056
  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.
991
1057
  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.
992
1058
 
993
1059
  ## Optional 3D
994
- The starter does not include 3D or its large browser dependency. To add it: npm install @joplo-app/plugin-3d@0.7.1; 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.
1060
+ The starter does not include 3D or its large browser dependency. To add it: npm install @joplo-app/plugin-3d@0.7.3; 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.
995
1061
 
996
1062
  ## Errors and trust
997
1063
  - 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.
@@ -1005,6 +1071,7 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1005
1071
  - 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.
1006
1072
  - 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.
1007
1073
  - 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.
1074
+ - 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.
1008
1075
  - 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.
1009
1076
  - 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.
1010
1077
  - Effect compilers return declarative writes, references, optional directorTarget, media commands, derived data and optional holdMs. Preserve source ordering.
@@ -1020,6 +1087,7 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1020
1087
  - 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.
1021
1088
  - 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.
1022
1089
  - 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.
1090
+ - 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.
1023
1091
  - 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.
1024
1092
  - 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.
1025
1093
  - 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.
@@ -1028,6 +1096,8 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1028
1096
  - 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.
1029
1097
 
1030
1098
  ## Local resources and media
1099
+ - 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.
1100
+ - 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.
1031
1101
  - 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.
1032
1102
  - 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.
1033
1103
  - 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.
@@ -1035,6 +1105,7 @@ The starter does not include 3D or its large browser dependency. To add it: npm
1035
1105
  - 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.
1036
1106
  - 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.
1037
1107
  - 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.
1108
+ - 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.
1038
1109
  - 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.
1039
1110
  - 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.
1040
1111
 
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 || t.endAfterMs !== undefined && elapsed >= t.endAfterMs) ? [] : [[id, { ...t, offsetMs: t.offsetMs + elapsed, ...(t.endAfterMs !== undefined ? { endAfterMs: t.endAfterMs - 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);
@@ -65,6 +78,9 @@ export declare class PluginCompiler {
65
78
  oneShot?: boolean;
66
79
  durationMs?: number;
67
80
  offsetMs?: number;
81
+ startDelayMs?: number;
82
+ duck?: boolean;
83
+ maxRetiring?: number;
68
84
  volume?: number;
69
85
  loop?: boolean;
70
86
  fadeMs?: number;