Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Built-in AI picks a white-model scene from a typed sentence when no Agent is connected

Bowen Xue397101c7bbb5
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index 450dc54..28ff660 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -31,6 +31,7 @@ from .jobs import ACTIVE, DONE, JobError, Jobs, chain_error, library_view
PREFIX = '/freevideo/agent/v1'
from .whitebox import MAX_VIDEO_BYTES as MAX_WHITEBOX_VIDEO
+from . import whitebox_pick
from .whitebox_presets import PRESETS, preset as whitebox_preset
# What an empty wait tells the agent: the conversation is open for as long as the user keeps the page.
KEEP_WAITING = ('Nothing new yet. The user is still in FreeVideo and may speak at any moment: call this wait '
@@ -46,6 +47,8 @@ RESUMED = ('This conversation is already under way; its last lines are in "befor
'say nothing until the user speaks, then carry on from there.')
BEFORE_LINES, BEFORE_TEXT = 8, 600
# The user started a white-model scene and then spoke: the words may be about it, not a new request.
+# Seconds one question to the local prompt model may take, loading the model included.
+WHITEBOX_ASK_SECONDS = 120
WHITEBOX_PENDING = ('The user started a white-model scene in this conversation ("whitebox" lists it). If the words ask about '
'it or about progress, answer from its status in one sentence (waiting or rendering: still being made; '
'failed: say it was not made, and why) and start nothing. A question is never a prompt.')
@@ -2191,24 +2194,63 @@ def register():
async def whitebox_presets(request):
return reply(dict(presets=[{k: row[k] for k in ('id', 'name', 'shot', 'prompt')} for row in PRESETS]))
+ def whitebox_ask(question, system, answer_format, max_tokens):
+ """One question to the local prompt model; a refusal, a timeout or a lost job is an OSError for pick()."""
+ try:
+ key = port.vlm_start('ask', dict(questions=[dict(text=question, images=[])], format=answer_format,
+ max_tokens=max_tokens, system=system))
+ except JobError as error:
+ raise OSError(error.code) from None
+ deadline = time.monotonic() + WHITEBOX_ASK_SECONDS
+ while True:
+ try:
+ state = port.vlm_status(key)
+ except (ValueError, JobError):
+ raise OSError('lost') from None
+ phase = state.get('phase')
+ if phase == 'complete':
+ answers = state.get('answers') or []
+ if len(answers) != 1 or not isinstance(answers[0], dict):
+ raise OSError('invalid_output')
+ return answers[0]
+ if phase not in ('starting', 'loading', 'rewriting', 'answering', 'finishing', 'cancelling'):
+ raise OSError(str(state.get('error') or phase))
+ if time.monotonic() > deadline:
+ port.vlm_cancel(key)
+ raise TimeoutError('timeout')
+ time.sleep(.5)
+
@routes.post('/freevideo/agent/whitebox/try')
@guarded
async def whitebox_try(request):
if request.content_type != 'application/json':
return problem('unsupported_media_type', 'Send JSON', 415)
value = await body(request)
- row = whitebox_preset(value.get('preset') if isinstance(value, dict) else None)
- if row is None:
- raise JobError('not_found', 'No such ready-made scene')
+ if not isinstance(value, dict):
+ raise JobError('invalid_request', 'Send a JSON object')
sid = value.get('session')
- notice = None
if sid is not None:
store = work_sessions()
if store is None or not isinstance(sid, str) or not store.has(chat['client'], sid):
raise JobError('not_found', 'No such conversation')
- # The conversation gets the confirmation card once the page has rendered the scene.
- notice = dict(question=row['prompt'], summary=row['name'])
- scene = await asyncio.to_thread(jobs.whitebox.create, row['code'], row['shot'], sid, notice)
+ shot = value.get('shot')
+ if (shot is None) == (value.get('preset') is None):
+ raise JobError('invalid_request', 'Send either a preset or a shot')
+ if shot is not None:
+ # The built-in AI picks a ready-made scene for the shot; when none fits, the video is made as usual.
+ picked = await asyncio.to_thread(whitebox_pick.pick, shot, whitebox_ask)
+ if picked['code'] is None:
+ return reply(dict(scene=None, reason=picked['reason']))
+ row = whitebox_preset(picked['params']['template'])
+ code = picked['code']
+ else:
+ row = whitebox_preset(value.get('preset'))
+ if row is None:
+ raise JobError('not_found', 'No such ready-made scene')
+ shot, code = row['shot'], row['code']
+ # The conversation gets the confirmation card once the page has rendered the scene.
+ notice = dict(question=row['prompt'], summary=row['name']) if sid is not None else None
+ scene = await asyncio.to_thread(jobs.whitebox.create, code, shot, sid, notice)
return reply(dict(scene, preset=row['id'], name=row['name'], prompt=row['prompt']), 201)
@routes.post('/freevideo/agent/whitebox/{id}/video')
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index ad76ce1..a3ea6e8 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -491,8 +491,8 @@ def contracts(*, local=False):
for method, suffix, summary, extra in (
('GET', '/next', 'The page asks for a white-model scene to render', {}),
('GET', '/presets', 'The ready-made white-model scenes the page can try', {}),
- ('POST', '/try', 'The page renders one ready-made white-model scene (no model writes code)',
- dict(body=obj(dict(preset=string(32, pattern=r'^[a-z0-9-]{1,32}$'), session=SESSION), ('preset',)))),
+ ('POST', '/try', 'The page renders one ready-made white-model scene, named (preset) or picked by the built-in AI for a shot (shot); no model writes code',
+ dict(body=obj(dict(preset=string(32, pattern=r'^[a-z0-9-]{1,32}$'), shot=string(4000), session=SESSION)))),
('POST', '/{id}/video', 'The page sends the rendered white-model video (the raw mp4 body)',
dict(path=obj({'id': WHITEBOX}, ('id',)))),
('POST', '/{id}/failed', 'The page reports that a white-model scene could not be rendered',
diff --git a/freevideo_engine/agent/whitebox_pick.py b/freevideo_engine/agent/whitebox_pick.py
index d291ad1..098ca1f 100644
--- a/freevideo_engine/agent/whitebox_pick.py
+++ b/freevideo_engine/agent/whitebox_pick.py
@@ -57,7 +57,7 @@ APPLY = """function applyParameters(base, p) {
return {scene, camera, update(t) {
if (typeof t !== 'number' || !Number.isFinite(t)) throw new Error('invalid_time');
camera.position.y -= previousOffset;
- base.update(Math.min(5, Math.max(0, t * p.speed)));
+ base.update(Math.min(p.seconds, Math.max(0, t * p.speed)));
camera.position.y += p.camera_height;
previousOffset = p.camera_height;
}};
@@ -111,25 +111,34 @@ def compile_scene(value):
params = effective(value)
if params['template'] == 'none':
return None
- source = preset(params['template'])['code']
+ row = preset(params['template'])
+ if row is None:
+ raise ValueError('template_invalid')
+ source = row['code']
+ seconds = row['seconds']
+ if isinstance(seconds, bool) or not isinstance(seconds, (int, float)) or not 0 < seconds <= 12:
+ raise ValueError('template_invalid')
head = 'export function build(THREE)'
if source.count(head) != 1:
raise ValueError('template_invalid')
return (source.replace(head, 'function buildTemplate(THREE)') + '\n' + APPLY + '\nexport function build(THREE) {\n'
- ' return applyParameters(buildTemplate(THREE), ' + json.dumps(params) + ');\n}\n')
+ ' return applyParameters(buildTemplate(THREE), ' + json.dumps(dict(params, seconds=seconds)) + ');\n}\n')
def pick(shot, ask):
"""Choose a scene for the shot. `ask(question, system, answer_format, max_tokens)` returns the model's answer
row (`text`, and `json` for the JSON format). The result always has `params`; `code` is None, and `reason`
- says why, whenever no white model should be made."""
+ says why, whenever no white model should be made. A failure to ask at all (timeout, connection) is one of those."""
try:
if not gate_allows(ask(gate_question(shot), SYSTEM, 'text', GATE_TOKENS).get('text')):
return dict(params=dict(NONE), code=None, reason='gate_no')
row = ask(pick_question(shot), SYSTEM, 'json', PICK_TOKENS)
params = effective(row.get('json'))
code = compile_scene(params)
- except (ValueError, AttributeError, TypeError) as error:
+ except (OSError, TimeoutError):
+ # The model could not be asked (timeout, connection): the video is made without a white model.
+ return dict(params=dict(NONE), code=None, reason='ask_failed')
+ except (ValueError, AttributeError, TypeError, KeyError) as error:
reason = str(error)
return dict(params=dict(NONE), code=None, reason=reason if reason in ('gate_invalid', 'params_invalid') else 'params_invalid')
return dict(params=params, code=code, reason='none' if code is None else 'template')
diff --git a/freevideo_engine/agent/whitebox_presets.py b/freevideo_engine/agent/whitebox_presets.py
index 450d146..7f700d9 100644
--- a/freevideo_engine/agent/whitebox_presets.py
+++ b/freevideo_engine/agent/whitebox_presets.py
@@ -3,6 +3,7 @@
PRESETS = (
dict(id='cat', name='橘猫跳上书架', shot='一只橘猫在客厅地板上蹲下蓄力,沿着错落的书架层板一级一级跳上去,最后蹲在最高一层,镜头侧面平移并略微上摇跟随。',
prompt='A ginger cat crouches on a living room floor, gathers itself and leaps up a staggered wooden bookshelf, jumping from one shelf to the next between rows of books, and finally settles on the top shelf, while the camera pans sideways and tilts up slightly to follow. Warm indoor daylight, realistic fur and wood, soft shadows, smooth camera motion. Soft room tone and the light thud of paws on wood.',
+ seconds=5,
code='export function build(THREE) {\n const scene = new THREE.Scene();\n const camera = new THREE.PerspectiveCamera(65, 960 / 544, 0.1, 300);\n const std = c => new THREE.MeshStandardMaterial({ color: c, roughness: 1 });\n const add = (geo, mat, x, y, z, name, parent) => {\n const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.name = name || "";\n m.castShadow = true; m.receiveShadow = true; (parent || scene).add(m); return m;\n };\n const ss = x => x * x * (3 - 2 * x);\n const lerp = (a, b, u) => a + (b - a) * u;\n const clamp01 = x => Math.min(1, Math.max(0, x));\n const sun = new THREE.DirectionalLight(0xffffff, 1.8);\n sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048);\n sun.shadow.camera.left = -60; sun.shadow.camera.right = 60; sun.shadow.camera.top = 60; sun.shadow.camera.bottom = -60; sun.shadow.camera.far = 200;\n scene.add(sun);\n\n scene.background = new THREE.Color(0xe9e2d6);\n scene.add(new THREE.HemisphereLight(0xfff4e6, 0x8a7f72, 1.2)); sun.position.set(6, 10, 8);\n add(new THREE.PlaneGeometry(14, 10).rotateX(-Math.PI / 2), std(0xb88f65), 0, 0, 0, "floor");\n add(new THREE.BoxGeometry(14, 4, 0.2), std(0xe9e2d6), 0, 2, -1.2, "wall");\n // bookshelf: two side boards, staggered shelves\n add(new THREE.BoxGeometry(0.1, 2.6, 0.5), std(0x7a5232), -1.4, 1.3, -0.9, "side");\n add(new THREE.BoxGeometry(0.1, 2.6, 0.5), std(0x7a5232), 1.4, 1.3, -0.9, "side");\n const shelves = [[0.6, -0.9], [1.2, -0.4], [1.8, 0.2], [2.4, 0.6]];\n const stepsX = [-0.9, -0.2, 0.5, 1.0], ys = [0.55, 1.05, 1.55, 2.1];\n for (let i = 0; i < 4; i++) {\n add(new THREE.BoxGeometry(1.0, 0.06, 0.5), std(0x9a6b3f), stepsX[i], ys[i] - 0.03, -0.9, "shelf");\n for (let k = 0; k < 3; k++) add(new THREE.BoxGeometry(0.12, 0.28, 0.3), std([0x3c6ea8, 0xb04a4a, 0x4a8a5a][(i + k) % 3]), stepsX[i] - 0.3 + k * 0.2, ys[i] + 0.14, -1.0, "book");\n }\n add(new THREE.BoxGeometry(0.9, 0.5, 0.5), std(0x6b7b8c), -2.6, 0.25, 0.6, "sofa_block");\n const cat = new THREE.Group(); cat.name = "hero_cat"; scene.add(cat);\n const orange = std(0xe58a2e);\n const body = add(new THREE.BoxGeometry(0.42, 0.22, 0.2), orange, 0, 0.18, 0, "hero_cat_body", cat);\n add(new THREE.SphereGeometry(0.11, 10, 8), orange, 0.26, 0.28, 0, "hero_cat_head", cat);\n add(new THREE.ConeGeometry(0.035, 0.08, 4), orange, 0.28, 0.4, 0.06, "hero_cat_ear", cat);\n add(new THREE.ConeGeometry(0.035, 0.08, 4), orange, 0.28, 0.4, -0.06, "hero_cat_ear", cat);\n const tail = add(new THREE.CylinderGeometry(0.03, 0.03, 0.4, 6), orange, -0.34, 0.3, 0, "hero_cat_tail", cat);\n tail.rotation.z = 0.8;\n // waypoints: floor crouch, jump to each shelf\n const wp = [[-1.9, 0.0, 0.1], [-1.9, 0.0, 0.1], [stepsX[0], ys[0], -0.9], [stepsX[1], ys[1], -0.9], [stepsX[2], ys[2], -0.9], [stepsX[3], ys[3], -0.9], [stepsX[3], ys[3], -0.9]];\n const times = [0, 0.7, 1.4, 2.3, 3.2, 4.1, 5.0];\n const pos = t => { let i = 0; while (i < 5 && t > times[i + 1]) i++;\n const u = clamp01((t - times[i]) / (times[i + 1] - times[i])); const a = wp[i], b = wp[i + 1];\n const arc = (i >= 1 && i <= 4) ? Math.sin(Math.PI * u) * 0.45 : 0;\n const e = ss(u); return new THREE.Vector3(lerp(a[0], b[0], e), lerp(a[1], b[1], u) + arc, lerp(a[2], b[2], e)); };\n return { scene, camera, update(t) {\n const p = pos(t); cat.position.copy(p);\n cat.scale.y = (t < 0.7) ? 1 - 0.35 * Math.sin(Math.PI * clamp01(t / 0.7)) : 1;\n cat.rotation.z = (t > 0.7 && t < 4.1) ? 0.35 : 0;\n camera.position.set(p.x * 0.6, 0.9 + p.y * 0.5, 2.7);\n camera.lookAt(p.x * 0.85, 0.35 + p.y * 0.85, -0.9);\n } };\n}\n'),
)
diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js
index a1fdeca..43091dc 100644
--- a/web/autopilot_chat.js
+++ b/web/autopilot_chat.js
@@ -2,7 +2,7 @@
// cards at the place they happened. Reads and sends use the page session; the agent's token never enters the page.
import {agentGet, agentPost, retryAgentPost} from './agent_session.js';
import {ATTACH, attachmentURL, pickPictures, thumbnail, uploadPicture} from './chat_attachments.js';
-import {SCENE_TEXT, sceneList, startScene, watchScene} from './whitebox_scenes.js';
+import {SCENE_TEXT, pickScene, sceneList, startScene, watchScene} from './whitebox_scenes.js';
import {chatData, chatDelay, chatReadRequest, emptyChat, chatMerge, chatEntries, canSend, newId, SEND_ATTEMPTS, WAIT_FOR_AGENT, sendRefused, sendError} from './chat_data.js';
export {emptyChat, chatMerge, chatEntries, canSend} from './chat_data.js';
import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js';
@@ -279,6 +279,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
function setWhiteboxPreview(enabled) {
whiteboxPreview = enabled; whiteboxButton.setAttribute('aria-pressed', String(enabled));
try { localStorage.setItem(WHITEBOX_PREVIEW.storageKey, String(enabled)); } catch {}
+ queueMicrotask(() => { if (!stopped) render(); });
}
whiteboxButton.setAttribute('aria-pressed', String(whiteboxPreview));
if (initialWhiteboxPreview) setWhiteboxPreview(true);
@@ -304,11 +305,13 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}));
}).catch(() => { sceneRows = null; toggleScenes(false); say(t(...SCENE_TEXT.failed) + t('Connection lost. Try again.', '连接中断,请重试。')); });
}
- async function runScene(preset, session = state.session) {
- if (!session || stopped || sceneWaiting) return;
+ // `start` resolves with the scene's id; false means the video is made as usual (no ready-made scene fits).
+ async function runScene(preset, session = state.session, start = () => startScene(api, preset, session)) {
+ if (!session || stopped || sceneWaiting) return null;
say(t(...SCENE_TEXT.preparing)); sceneWaiting = true;
try {
- const id = await startScene(api, preset, session);
+ const id = await start();
+ if (id === false) { sceneWaiting = false; say(''); return false; }
const result = id ? await watchScene(api, id, {stopped: () => stopped, onState: value => { if (value.status === 'rendering') say(t(...SCENE_TEXT.rendering)); }}) : {status: 'ready'};
if (result.status === 'failed') {
sceneWaiting = false; const why = (result.error || '').replace(/[.。]+$/, '');
@@ -319,6 +322,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
say(t(...(result.last === 'rendering' ? SCENE_TEXT.timeout : result.page_open ? SCENE_TEXT.notStarted : SCENE_TEXT.noPage)));
}
} catch (failure) { sceneWaiting = false; say(t(...SCENE_TEXT.failed) + reason(failure)); }
+ return true;
}
// Pictures waiting to be sent, per conversation draft: {key, url, attachment|null}. A picture is uploaded the moment it is added.
const attachButton = press('fv-chat-attach', null, () => fileInput.click()), fileInput = el('input'), strip = el('ul', 'fv-chat-attached');
@@ -367,7 +371,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}
function addPictures(files) {
files = [...files || []];
- if (!files.length || !composeAllowed()) return;
+ if (!files.length || !composeAllowed() || builtinScene()) return;
const session = draftSession, list = stagedList(session), {accepted, problem} = pickPictures(files, ATTACH.count - list.length);
say(problem ? t(...ATTACH[problem]) : '');
for (const file of accepted) {
@@ -751,7 +755,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
// A hidden page keeps reading, slowly, so that its title can tell what happened.
const reading = () => !stopped && element.isConnected && shown();
const inSelectedChat = () => !creating && (!selectedSession || selectedSession === state.session);
- const composeAllowed = () => inSelectedChat() && state.agent.connected === true;
+ const builtinScene = () => whiteboxPreview && state.agent.connected !== true;
+ const composeAllowed = () => inSelectedChat() && (state.agent.connected === true || builtinScene() && !!state.session);
const sendingAllowed = () => inSelectedChat() && canSend(state);
const draftSending = () => pending.some(entry => entry.sending && entry.draft && entry.draft === drafts.get(draftSession));
@@ -1145,9 +1150,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
const MAKE = {hello, examples, dots, user: () => message('user'), agent: () => message('agent'), job: jobCard, confirm: confirmCard};
function render(follow = false) {
- const builtin = state.agent?.builtin === true;
- whiteboxButton.disabled = builtin;
- whiteboxButton.title = builtin ? t('Not available with the built-in AI', '内置 AI 不支持白模') : t(...WHITEBOX_PREVIEW.name);
+ whiteboxButton.title = t(...WHITEBOX_PREVIEW.name);
whiteboxButton.setAttribute('aria-label', whiteboxButton.title);
const entries = chatEntries(state), ids = new Set(entries.map(entry => entry.id).filter(Boolean));
for (const entry of pending) if (entry.session === state.session && ids.has(entry.id)) acknowledge(entry);
@@ -1193,8 +1196,9 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
if (log.children[index] !== node.element) log.insertBefore(node.element, log.children[index] || null);
});
const sendable = sendingAllowed();
- input.disabled = state.agent.connected !== true || creating || !!selectedSession && selectedSession !== state.session;
- input.placeholder = state.agent.connected === true && !sendable ? t('Ask your agent to continue', '请在 Agent 里让它继续') : t('Message the agent…', '对 Agent 说…');
+ input.disabled = !(state.agent.connected === true || builtinScene() && !!state.session) || creating || !!selectedSession && selectedSession !== state.session;
+ input.placeholder = builtinScene() ? t(...SCENE_TEXT.describe)
+ : state.agent.connected === true && !sendable ? t('Ask your agent to continue', '请在 Agent 里让它继续') : t('Message the agent…', '对 Agent 说…');
refreshSend();
if (focusSession === state.session && focusSession && !input.disabled && active()) { focusSession = null; input.focus(); }
if (stick) { pinned = true; scroller.scrollTop = scroller.scrollHeight; down.hidden = true; }
@@ -1251,7 +1255,16 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
say(creating ? t('Creating a new chat…', '正在新建对话…') : t('Loading this chat. Please send again shortly.', '正在读取对话,请稍后再发一次'));
return false;
}
- const entry = original || {id: newId(), text, attachments: attachments || [], session: state.session ?? null, draft, whiteboxPreview: whiteboxPreview && state.agent?.builtin !== true};
+ // With no Agent connected the white-model button is the way in: the sentence goes to the built-in AI, which
+ // picks a ready-made scene or says that none fits. It is never queued for an Agent.
+ if (builtinScene()) {
+ if (attachments?.length || original || !state.session) return false;
+ const made = await runScene(null, state.session, () => pickScene(api, text, state.session));
+ if (made === false) say(t(...SCENE_TEXT.failed) + t(...SCENE_TEXT.noFit));
+ else if (made === true) { input.value = ''; grow(); }
+ return made === true;
+ }
+ const entry = original || {id: newId(), text, attachments: attachments || [], session: state.session ?? null, draft, whiteboxPreview};
if (draft) entry.draft = draft;
if (!original) pending.push(entry);
if (!automatic) entry.attempts = 0;
diff --git a/web/whitebox_scenes.js b/web/whitebox_scenes.js
index 0a77075..5345819 100644
--- a/web/whitebox_scenes.js
+++ b/web/whitebox_scenes.js
@@ -7,6 +7,8 @@ export const SCENE_TEXT = Object.freeze({
label: ['Ready-made', '现成场景'], name: ['Start from a ready-made white-model scene', '用现成的白模场景开始'],
preparing: ['Preparing the white model…', '正在准备白模…'], failed: ['The white model could not be made: ', '白模没有做成:'],
rendering: ['Rendering the white model…', '正在渲染白模…'], retry: ['. Try again.', '。请重试。'],
+ noFit: ['no ready-made scene fits this sentence. Try again.', '没有适合这句话的现成场景。请重试。'],
+ describe: ['Describe the shot…', '描述一个镜头…'],
bare: ['The white model could not be made. Try again.', '白模没有做成。请重试。'],
noPage: ['The white model could not be made: the renderer is not running in this page. Reload the page and try again.', '白模没有做成:这个页面里的渲染没有运行。请刷新页面后重试。'],
notStarted: ['The white model could not be made: rendering did not start within 3 minutes. Try again.', '白模没有做成:三分钟内渲染没有开始。请重试。'],
@@ -27,6 +29,14 @@ export async function startScene(api, preset, session) {
return value?.id || null;
}
+// The built-in AI picks a scene for the shot: the scene's id, or false when no ready-made scene fits.
+export async function pickScene(api, shot, session) {
+ const response = await agentPost(api, '/freevideo/agent/whitebox/try', {shot, ...(session ? {session} : {})});
+ const value = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(value?.error?.message || value?.error?.code || `HTTP ${response.status}`);
+ return value?.id || false;
+}
+
// Resolves with the scene's last state: 'ready' (the card follows), 'failed' (with error), or 'timeout' (with the
// last state seen: 'waiting' nobody claimed it, 'rendering' it did not finish, page_open false no page was asking).
// onState hears every state seen, so the page can say what is happening.