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.
Editor: every Generate press answers at once
Bowen Xue5e1198b9b0a4
diff --git a/web/editor.css b/web/editor.cssindex 260cba8..1599393 100644--- a/web/editor.css+++ b/web/editor.css@@ -64,6 +64,10 @@.fv-ed-genbar .fv-ed-description{width:auto}.fv-ed-clip[data-state=running] .fv-block-progress.fv-ed-block-progress{display:grid}.fv-ed-gen-hint{font-size:13px;color:var(--fv-muted);flex:1;min-width:0}+.fv-ed-genbar[data-mode=selected] .fv-ed-gen-hint{flex:none}+.fv-ed-gen-note{font-size:13px;color:var(--fv-ink);flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.fv-ed-gen-note[hidden]{display:none}+.fv-ed-basic-progress[data-state=waiting] .fv-ed-basic-percent{font-weight:500;color:var(--fv-muted)}.fv-ed-description{flex:1;width:0}.fv-ed-first-frame{display:flex;align-items:center;gap:8px;flex:none;font-size:13px;white-space:nowrap}.fv-ed-first-frame[hidden]{display:none}@@ -143,6 +147,8 @@.fv-ed-description{width:100%;flex:1 1 100%}.fv-ed-genbar .fv-ed-description{order:-1}.fv-ed-refs{margin-right:auto}+ .fv-ed-gen-hint{flex:1 0 auto;white-space:nowrap}+ .fv-ed-gen-note{order:-1;flex:1 1 100%;white-space:normal}.fv-editor .fv-ed-genbar>button{margin-left:auto;max-width:100%;font-size:12px}.fv-ed-name-menu{position:fixed;top:120px;left:8px}.fv-ed-notice{top:60px;bottom:auto;pointer-events:none}diff --git a/web/editor.js b/web/editor.jsindex 1f023c7..a42382f 100644--- a/web/editor.js+++ b/web/editor.js@@ -46,7 +46,7 @@ function restoreGeneration(record, before, prepared) {return next;}const icon = path => { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true'); svg.classList.add('fv-ed-glyph'); const line = document.createElementNS(svg.namespaceURI, 'path'); line.setAttribute('d', path); svg.append(line); return svg; };-function basicBlockProgress(clipId, clipElement) {+function basicBlockProgress(clipId, clipElement, t = en => en) {const element = el('div', 'fv-ed-basic-progress'), water = el('div', 'fv-ed-basic-water'), percent = el('span', 'fv-ed-basic-percent');element.append(water, percent);let level = 0, run = null;@@ -54,7 +54,10 @@ function basicBlockProgress(clipId, clipElement) {if (value.run && value.run !== run) { level = 0; run = value.run; }element.dataset.state = value.state;const fraction = level = value.state === 'waiting' ? 0 : Math.max(level, Math.max(0, Math.min(1, value.fraction || 0))); water.style.height = `${fraction * 100}%`;- percent.textContent = `${Math.floor(fraction * 100 + 1e-8)}%`; percent.hidden = value.state !== 'generating' || clipElement.dataset.track !== 'v1' || clipElement.getBoundingClientRect().width < 44;+ const queued = value.state === 'waiting' && !!value.queued;+ element.dataset.queued = queued ? 'true' : 'false';+ percent.textContent = queued ? t('Queued', '排队中') : `${Math.floor(fraction * 100 + 1e-8)}%`;+ percent.hidden = (value.state !== 'generating' && !queued) || clipElement.dataset.track !== 'v1' || clipElement.getBoundingClientRect().width < 44;water.hidden = value.state !== 'generating';}, dispose() { element.remove(); }};}@@ -185,13 +188,18 @@ export function openEditor({api, app, from = null, panel = {}, components: givenconst code = value?.code || value?.message;if (['audio_prepare', 'speed_pending', 'speed_locked', 'speed'].includes(code)) return {ok: false, reason: code};if (code === 'unsupported') { genbar?.update(null); return; }- if (code === 'chain_too_long') {+ if (['chain_too_long', 'chain_part_too_short'].includes(code)) {const [en, zh] = (value.said || []).map(text => typeof text === 'string' && text ? text.slice(0, 200) : null);- notify(t(en || 'This video can have up to 5 parts. Make it shorter.', zh || '这条视频最多 5 段,请缩短一些。'));+ notify(code === 'chain_too_long' ? t(en || 'This video can have up to 5 parts. Make it shorter.', zh || '这条视频最多 5 段,请缩短一些。')+ : t(en || 'Each continued part must be at least 10 seconds. Make it longer.', zh || '接着生成的每一段至少 10 秒,请加长一些。'));return {ok: false, reason: code};}if (['busy', 'locked', 'text', 'audio_full', 'overlap', 'range'].includes(code)) {if (['locked', 'audio_full', 'overlap', 'range'].includes(code)) tracks?.flashBlocked?.(value.displayFrame);+ const said = {busy: t('This part is generating.', '这一段正在生成。'), locked: t('This track is locked.', '这条轨道已锁定。'),+ text: t('Write a description first.', '先写一句描述。'), overlap: t('That spot is taken. Use an empty spot.', '这里已经有片段了,请放到空白处。'),+ audio_full: t('Both audio tracks are full here. Move an audio clip first.', '这里两条声音轨都满了,请先挪开一段声音。')}[code];+ if (said) notify(said);return {ok: false, reason: code};}notify(t('Could not complete. Try again.', '没有完成,请重试'));@@ -199,15 +207,15 @@ export function openEditor({api, app, from = null, panel = {}, components: givenconst store = createEditorStore(api, {t, notify, standIn: given?.generationStandIn, onGenerationReady: ready => {if (disposed) return;generationAsked = true; genHost.hidden = !ready; element.dataset.generationReady = String(ready);- settleGenbar(); if (ready) { offerInitial?.(); extendEntry?.(); }+ settleGenbar(); if (ready) { offerInitial?.(); extendEntry?.(); void startHeld(); }tracks?.refresh?.(); genbar?.update(mostRecentJob ? barJob(jobStatuses.get(mostRecentJob)) : null);updateTransport(); adjustPanel?.update();}});// Until the server has answered, the bar keeps its place but cannot be used.let generationAsked = store.generationAvailable, loaded = false;const settleGenbar = () => {- const waiting = !loaded || !generationAsked;- genHost.inert = waiting || !store.generationAvailable; genHost.classList.toggle('fv-ed-pending', waiting);+ // While the engine is still answering, a press queues the part instead of doing nothing.+ genHost.inert = !loaded || generationAsked && !store.generationAvailable; genHost.classList.toggle('fv-ed-pending', !loaded);};store.generationReady();const queue = store.createSaveQueue({get record() { return state.record; },@@ -245,6 +253,85 @@ export function openEditor({api, app, from = null, panel = {}, components: given} catch (value) { if (value instanceof model.EditError) return false; throw value; }}const jobActive = () => generationBusy || [...jobStatuses.values()].some(job => ['queued', 'running', 'cancelling'].includes(job.state));+ // Parts pressed while they cannot be sent yet: the engine is still starting, or they continue a part+ // that is not finished. They are planned at once, shown queued, and sent in order when they can be.+ // Parts, and ranges not yet planned into parts, whose request is being sent.+ const held = [], sending = new Set(), sendingRanges = new Set();+ const overlaps = (a, b) => a.start < b.start + b.frames && a.start + a.frames > b.start;+ let startingHeld = false;+ const generating = clip => ['queued', 'running'].includes(clip?.pending);+ const isHeld = id => held.some(entry => entry.ids.includes(id));+ const partBefore = start => state.record.tracks[0].clips.find(clip => clip.frames > 0 && clip.start + clip.frames === start);+ function busySelection(selection) {+ const range = selectionRange(selection); if (!range) return false;+ if ([...sendingRanges].some(other => overlaps(other, range))) return true;+ return state.record.tracks[0].clips.some(clip => (generating(clip) || isHeld(clip.id) || sending.has(clip.id))+ && clip.start < range.start + range.frames && clip.start + clip.frames > range.start);+ }+ function waitingFor(selection) {+ if (!store.generationAvailable) return 'ready';+ const before = partBefore(selectionRange(selection).start);+ return generationBusy || generating(before) || before && isHeld(before.id) ? 'before' : null;+ }+ // The nearest spot at or after the chosen one where a part of the same length fits.+ function emptySpot(selection) {+ if (!['range', 'gap'].includes(selection?.kind)) return null;+ const range = selectionRange(selection), clips = state.record.tracks.filter(track => ['v1', 'a1', 'a2'].includes(track.id)).flatMap(track => track.clips);+ const starts = [range.start, ...clips.map(clip => clip.start + clip.frames).filter(at => at > range.start)].sort((a, b) => a - b);+ for (const start of starts) {+ if (clips.some(clip => clip.start < start + range.frames && clip.start + clip.frames > start)) continue;+ const moved = {kind: 'range', start, frames: range.frames, tracks: ['v1', 'a1']};+ if (actions.supportedSelection(moved)) return moved;+ }+ return null;+ }+ // A range left a sliver (under the shortest part) after a clip closes up to that clip's end.+ function flushSpot(selection) {+ if (selection?.kind !== 'range') return null;+ const range = selectionRange(selection), most = model.RULES.minSeconds * model.FPS;+ const clips = state.record.tracks.filter(track => ['v1', 'a1', 'a2'].includes(track.id)).flatMap(track => track.clips);+ const end = Math.max(-1, ...state.record.tracks[0].clips.map(clip => clip.start + clip.frames).filter(at => at < range.start));+ if (end < 0 || range.start - end >= most || clips.some(clip => clip.start < range.start && clip.start + clip.frames > end)) return null;+ const moved = {kind: 'range', start: end, frames: range.frames, tracks: ['v1', 'a1']};+ return actions.supportedSelection(moved) ? moved : null;+ }+ // A part with no description borrows the one before it, else the nearest earlier one, else any.+ function nearbyText(start) {+ const before = partBefore(start);+ if (before?.text?.trim()) return {text: before.text, before: true};+ const described = state.record.tracks[0].clips.filter(clip => clip.text?.trim()).sort((a, b) => a.start - b.start);+ const found = described.filter(clip => clip.start < start).at(-1) || described.at(-1);+ return found ? {text: found.text, before: false} : null;+ }+ const markHeld = (ids, queued) => { for (const id of ids) tracks?.setProgress(id, {state: 'waiting', fraction: 0, remainingSeconds: null, ...(queued ? {queued: true} : {})}); };+ function hold(selection, text) {+ const range = selectionRange(selection), selectedIds = selectionClips(selection).map(clip => clip.id), shown = selection === state.selection;+ let ids = [];+ state.apply(t('Generate', '生成'), record => {+ const selected = selectedIds.map(id => model.find(record, id)).filter(Boolean), planned = selected.length && selected.every(clip => !clip.source && clip.pending && !generating(clip));+ const next = planned ? model.startAttempt(record, selected.map(clip => clip.id), text) : model.planRange(record, {...range, target: 'both', text, maxSeconds: capability.maxSeconds, maxFollowSeconds: capability.maxFollowSeconds});+ ids = next.tracks[0].clips.filter(clip => clip.start >= range.start && clip.start < range.start + range.frames && clip.pending && !generating(clip)).map(clip => clip.id);+ return next;+ }, {checkpoint: true});+ held.push({ids, text}); markHeld(ids, true);+ if (shown) state.select({kind: 'clip', ids});+ }+ async function startHeld() {+ if (startingHeld || disposed || closing || generationBusy || !store.generationAvailable) return;+ startingHeld = true;+ try {+ while (held.length && !disposed) {+ const entry = held[0], clips = entry.ids.map(id => model.find(state.record, id)).filter(clip => clip && clip.pending && !generating(clip));+ if (!clips.length) { held.shift(); markHeld(entry.ids, false); continue; }+ const selection = {kind: 'clip', ids: clips.map(clip => clip.id)}, before = partBefore(Math.min(...clips.map(clip => clip.start)));+ if (generating(before)) break;+ held.shift(); markHeld(entry.ids, false);+ if (before && !before.source && before.pending) { genbar?.say(t('The part before did not finish, so this one did not start.', '上一段没有完成,这一段没有开始。')); continue; }+ try { await actions.generate({text: entry.text, selection}); }+ catch (value) { const reason = error(value); if (reason && !['chain_too_long', 'chain_part_too_short'].includes(reason.reason)) genbar?.say(t('This part did not start. Choose "Generate" again.', '这一段没有开始,请再点一次“生成”。')); }+ }+ } finally { startingHeld = false; }+ }function completeSources() {return store.getSources(model.references(state.record).map(sourceKey)).then(() => { player.refresh(); tracks?.refresh?.(); });}@@ -316,6 +403,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (completed.size || (!active && previous?.state !== job.state) || (job.output && job.output !== previous?.output))library?.refresh({outputs: job.output ? [job.output] : [...completed]});if (!active) jobWatchers.delete(job.id);+ void startHeld();return active;}function watchJob(id) {@@ -348,7 +436,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenlet remembered = editorViews.get(viewKey);if (!remembered) try { remembered = JSON.parse(localStorage.getItem(viewPrefix + viewKey)); } catch {}initialSelection = offerInitial = extendEntry = null;- projectEpoch++;+ projectEpoch++; held.length = 0;player.pause(); for (const stop of jobWatchers.values()) stop(); jobWatchers.clear(); jobStatuses.clear(); progress.clear(); runProgress.clear(); progressConnection?.reset();mostRecentJob = null; genbar?.update(null); queue.reset(record); stopExport?.(); stopExport = null; exportStatus = exportSnapshot = null; exportButton.textContent = t('Export', '导出');suppressSave = true; try { state.replace(record); savedContent = content(record); } finally { suppressSave = false; }@@ -460,13 +548,13 @@ export function openEditor({api, app, from = null, panel = {}, components: given}},reasonText: code => code === 'gpu_memory' ? t('Not enough graphics memory', '显存不够') : t('Could not generate', '没能生成'),- supportedSelection() {- if (state.selection?.kind === 'clip' && state.selection.ids.some(id => isText(model.find(state.record, id)))) return false;- const range = selectionRange(); if (!range) return false;- if (state.selection.kind === 'range' && !['v1', 'a1'].every(id => state.selection.tracks.includes(id))) return false;- if (state.selection.kind === 'gap' && state.selection.track !== 'v1') return false;+ supportedSelection(selection = state.selection) {+ if (selection?.kind === 'clip' && selection.ids.some(id => isText(model.find(state.record, id)))) return false;+ const range = selectionRange(selection); if (!range) return false;+ if (selection.kind === 'range' && !['v1', 'a1'].every(id => selection.tracks.includes(id))) return false;+ if (selection.kind === 'gap' && selection.track !== 'v1') return false;try {- const selected = selectionClips();+ const selected = selectionClips(selection);if (selected.length && selected.every(clip => clip.pending && !clip.source))model.prepare(state.record, selected.map(clip => clip.id));else model.planRange(state.record, {...range, target: 'both'});@@ -474,14 +562,17 @@ export function openEditor({api, app, from = null, panel = {}, components: given}catch (value) { if (value instanceof model.EditError) return value.code === 'busy'; throw value; }},- canGenerate(text) {- if (!store.generationAvailable || !actions.supportedSelection() || jobActive()) return false;- const range = selectionRange();+ // Another part generating is no reason: the server runs parts one after another.+ canGenerate(text, selection = state.selection) {+ return store.generationAvailable && actions.supportedSelection(selection) && (!!text.trim() || !actions.needsText(selection));+ },+ needsText(selection = state.selection) {+ const range = selectionRange(selection); if (!range) return true;// Only a part pulled out of a finished one needs no description: it continues that one.const head = state.record.tracks[0].clips.find(clip => clip.start === range.start);const before = !!head && model.continuesBefore(state.record, head.id) && state.record.tracks[0].clips.some(clip =>clip.start + clip.frames === range.start && clip.source && clip.extend && clip.in + clip.frames === clip.length);- return !!text.trim() || before;+ return !before;},// Only where earlier footage is continued: a part right after an extendable clip, or a range split into several parts.firstFrameVisible() {@@ -503,13 +594,15 @@ export function openEditor({api, app, from = null, panel = {}, components: givenfor (const count of model.rangeParts(state.record, {...range, ...capability})) { const value = capability.estimate(count); if (value == null) return null; seconds += value; }return seconds;},- async generate({target = 'both', text = '', label = t('Generate', '生成')} = {}) {- if (target !== 'both' || !actions.supportedSelection()) throw new model.EditError('unsupported');- if (!actions.canGenerate(text)) throw new model.EditError('text');+ async generate({target = 'both', text = '', label = t('Generate', '生成'), selection = state.selection} = {}) {+ if (target !== 'both' || !actions.supportedSelection(selection)) throw new model.EditError('unsupported');+ if (!actions.canGenerate(text, selection)) throw new model.EditError('text');+ const shown = selection === state.selection;generationBusy = true; updateTop(); updateTransport();generationDone = new Promise(resolve => { finishGeneration = resolve; });let ids = [], prepared = null, beforeAttempt = null, priorSelection = null, priorText = null, submittedSelection = null;- const epoch = projectEpoch, range = selectionRange(), selectedIds = selectionClips().map(clip => clip.id);+ const epoch = projectEpoch, range = selectionRange(selection), selectedIds = selectionClips(selection).map(clip => clip.id);+ sendingRanges.add(range);try {const frozen = await snapshot(); if (epoch !== projectEpoch || closing || disposed || !store.generationAvailable) return;beforeAttempt = state.record; priorSelection = state.selection; priorText = state.rangeText;@@ -520,8 +613,11 @@ export function openEditor({api, app, from = null, panel = {}, components: givenids = next.tracks[0].clips.filter(clip => clip.start >= range.start && clip.start < range.start + range.frames && clip.pending && !['queued', 'running'].includes(clip.pending)).map(clip => clip.id);return model.prepare(next, ids);}, {checkpoint: true});+ for (const id of ids) sending.add(id);prepared = state.record;- submittedSelection = state.select({kind: 'clip', ids}); await completeSources();+ // Only a press on what is still chosen moves the choice; a part started in the background+ // leaves whatever the user has moved on to, and what they typed there.+ submittedSelection = shown && state.selection === selection ? state.select({kind: 'clip', ids}) : state.selection; await completeSources();const paths = Object.fromEntries([...store.sources].map(([key, value]) => [key, value.path]));const request = model.generationRequest(prepared, ids, {text, paths});// Pictures guide parts that start fresh; a request whose parts all continue footage carries none.@@ -543,7 +639,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenconst job = await store.startChain({...frozen, blocks});if (!job && !store.generationAvailable) {if (epoch === projectEpoch) {- const restoreSelection = state.selection === submittedSelection;+ const restoreSelection = submittedSelection !== priorSelection && state.selection === submittedSelection;// Reverse only this submission's changes. Keep save receipts,// reserved IDs and unrelated edits made while POST was pending.state.settle(record => restoreGeneration(record, beforeAttempt, prepared));@@ -559,9 +655,56 @@ export function openEditor({api, app, from = null, panel = {}, components: given} catch (value) {if (ids.length && epoch === projectEpoch) state.settle(record => model.settle(record, ids, 'draft'));throw value;- } finally { if (disposed && ids.length) queue.enqueue(state.record); generationBusy = false; finishGeneration?.(); generationDone = null; finishGeneration = null; updateTop(); updateTransport(); }+ } finally { sendingRanges.delete(range); for (const id of ids) sending.delete(id); if (disposed && ids.length) queue.enqueue(state.record); generationBusy = false; finishGeneration?.(); generationDone = null; finishGeneration = null; updateTop(); updateTransport(); startHeld(); }+ },+ // A press on Generate always answers: what can be done for the user is done, then said in one line.+ async press(text) {+ if (disposed || closing || initializing) return {say: t('Opening the edit…', '正在打开…')};+ let selection = state.selection, said = null;+ if (!selectionRange(selection)) return {say: t('Drag on the timeline to choose a part first.', '先在时间线上拖出一段。')};+ if (actions.selectionHeld()) return {say: t('Queued', '排队中')};+ if (busySelection(selection)) return {say: t('This part is generating.', '这一段正在生成。')};+ const flush = flushSpot(selection);+ if (flush) { selection = state.select(flush); said = t('Moved to right after the part before.', '已接在上一段后面。'); genbar?.say(said); }+ else if (!actions.supportedSelection(selection)) {+ const moved = emptySpot(selection);+ if (!moved) return {say: t('Choose an empty spot on the timeline.', '请在时间线上选一段空白。')};+ selection = state.select(moved); said = t('Moved to the next empty spot.', '已挪到后面的空位。'); genbar?.say(said);+ }+ let used = null;+ if (!text.trim() && actions.needsText(selection)) {+ const found = nearbyText(selectionRange(selection).start);+ if (!found) return {say: [said, t('Write a description first.', '先写一句描述。')].filter(Boolean).join(' '), focus: true};+ text = found.text; used = found.before ? t('Used the description of the part before.', '沿用了上一段的描述。')+ : t('Used the latest description.', '沿用了最近一次的描述。');+ state.setRangeText(text); genbar?.setText(text);+ }+ const waiting = waitingFor(selection);+ if (waiting) {+ hold(selection, text);+ return {text, say: [said, used, waiting === 'ready' ? t('Queued. It starts once generation is ready.', '已排队,准备好后自动开始。')+ : t('Queued. It starts after the part before it.', '已排队,上一段完成后自动开始。')].filter(Boolean).join(' '), queued: true};+ }+ const busyBefore = jobActive();+ await actions.generate({text, selection});+ return {text, say: [said, used, busyBefore ? t('Queued. It starts after the part now generating.', '已排队,正在生成的那段完成后自动开始。') : null].filter(Boolean).join(' ') || null, queued: busyBefore};+ },+ selectionRunning: () => busySelection(state.selection),+ selectionSending() { const range = selectionRange(state.selection); return !!range && ([...sendingRanges].some(other => overlaps(other, range)) || [...sending].some(id => { const clip = model.find(state.record, id); return clip && overlaps(clip, range); })); },+ selectionHeld() { const ids = selectionClips(state.selection).map(clip => clip.id); return ids.length > 0 && ids.every(isHeld); },+ // Takes the selected parts out of the line; they stay as drafts.+ unhold() {+ const ids = selectionClips(state.selection).map(clip => clip.id);+ for (let i = held.length - 1; i >= 0; i--) if (held[i].ids.some(id => ids.includes(id))) { markHeld(held[i].ids, false); held.splice(i, 1); }+ },+ async cancel() {+ const range = selectionRange(state.selection);+ const own = range && state.record.tracks[0].clips.find(clip => clip.job && generating(clip)+ && clip.start < range.start + range.frames && clip.start + clip.frames > range.start)?.job;+ // A part still being sent has no job yet; never stop another one in its place.+ if (!own && actions.selectionSending()) return;+ const id = own || mostRecentJob; if (id) await deliverChain(await store.chainAction(id, 'cancel'));},- async cancel() { const id = mostRecentJob; if (id) await deliverChain(await store.chainAction(id, 'cancel')); },async resume() {if (!store.generationAvailable) return;const epoch = projectEpoch;@@ -912,7 +1055,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (trackResult.status === 'rejected') throw trackResult.reason;const module = trackResult.value, components = componentResult.status === 'fulfilled' ? componentResult.value : {};blockStates = components.blocks?.blockStates || null;- let blockProgress = basicBlockProgress;+ let blockProgress = (id, clipElement) => basicBlockProgress(id, clipElement, t);if (components.blocks?.createBlockProgress) blockProgress = (id, clipElement) => {const component = components.blocks.createBlockProgress({t, showPercent: clipElement.dataset.track === 'v1'});let run = null;diff --git a/web/editor_genbar.js b/web/editor_genbar.jsindex 81c86bd..f5efba2 100644--- a/web/editor_genbar.js+++ b/web/editor_genbar.js@@ -5,33 +5,59 @@ const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls)export const timeEstimate = (seconds, t) => seconds == null ? '' : seconds < 60? t(`about ${Math.max(1, Math.ceil(seconds))} s`, `约 ${Math.max(1, Math.ceil(seconds))} 秒`): t(`about ${Math.ceil(seconds / 60)} minutes`, `约 ${Math.ceil(seconds / 60)} 分钟`);+// After the next frame is on screen; a page nobody sees has no frame to wait for.+const painted = () => typeof document === 'undefined' || document.visibilityState !== 'visible' || typeof requestAnimationFrame !== 'function' ? Promise.resolve()+ : new Promise(resolve => requestAnimationFrame(() => { const {port1, port2} = new MessageChannel(); port1.onmessage = () => { port1.close(); resolve(); }; port2.postMessage(null); }));export function createEditorGenbar(host, {state, t, actions, text = ''}) {- const hint = el('span', 'fv-ed-gen-hint');+ const hint = el('span', 'fv-ed-gen-hint'), note = el('span', 'fv-ed-gen-note');+ note.setAttribute('role', 'status'); note.hidden = true;const input = el('input', 'fv-ed-description'); input.type = 'text'; input.value = text;const generate = el('button', 'fv-ed-generate'), cancel = el('button', null, t('Cancel', '取消')), resume = el('button', null, t('Continue', '继续'));for (const button of [generate, cancel, resume]) button.type = 'button';- host.append(hint, input, generate, cancel, resume);+ host.append(hint, note, input, generate, cancel, resume);const firstFrame = createFirstFrameSwitch(host, {state, t, actions});input.after(firstFrame.element);// Reference pictures for a part that starts fresh: thumbnails and a small "+" before the description.const references = actions.references ? createEditorReferences({t, source: actions.references.source, size: actions.references.size, error: actions.error, notify: actions.references.notify}) : null;if (references) input.before(references.element);- let status = null, serial = 0, disposed = false, submitting = false, previewSelection = null, estimateCache = null;+ let status = null, serial = 0, disposed = false, pressing = new Set(), previewSelection = null, estimateCache = null, noteTimer = null, queuedAt = null;+ // Which parts are generating, or how the job ended: a "Queued" line goes once this moves on.+ const progressKey = () => ['done', 'failed', 'cancelled', 'interrupted'].includes(status?.state) ? status.state+ : (status?.blocks || []).filter(block => block.state === 'running').map(block => block.id).join(',');+ function say(text, queued = false) {+ if (disposed) return;+ queuedAt = text && queued ? progressKey() : null;+ clearTimeout(noteTimer); note.textContent = text || ''; note.hidden = !text;+ if (text) noteTimer = setTimeout(() => { note.hidden = true; }, 6000);+ }async function render() {if (disposed) return;+ if (queuedAt != null && progressKey() !== queuedAt) say('');const current = ++serial, selection = previewSelection || state.selection;- const busy = submitting || ['queued', 'running', 'cancelling'].includes(status?.state);- const stopped = ['failed', 'cancelled', 'interrupted'].includes(status?.state);+ const running = ['queued', 'running', 'cancelling'].includes(status?.state);const selected = !!selection && (!!previewSelection || (actions.supportedSelection?.() ?? true));+ // While a part generates, choosing another place offers Generate again; it is queued behind.+ // A press is being sent for the parts in `pressing`; only that same selection waits for it.+ const sending = pressing.has(JSON.stringify(state.selection ?? null)), starting = pressing.size > 0 && !running;+ const other = (running || starting) && !sending && selected && !previewSelection && actions.selectionRunning?.() === false;+ // A part pressed while it could not start yet waits in line; its Cancel takes it out of the line.+ const held = !previewSelection && !!actions.selectionHeld?.();+ const busy = sending || held || (running || starting) && !other;+ // The selected part is still being sent: it can only be stopped once it has started.+ const opening = (starting || !!actions.selectionSending?.()) && !held;+ const stopped = ['failed', 'cancelled', 'interrupted'].includes(status?.state);host.dataset.mode = busy ? 'running' : selected ? 'selected' : 'idle';- hint.hidden = !busy; input.hidden = generate.hidden = busy;+ hint.hidden = !busy && !other; input.hidden = generate.hidden = busy;input.disabled = !selected || busy;input.placeholder = selected ? t('Describe this part', '描述这一段'): '';input.setAttribute('aria-label', t('Description', '描述'));generate.classList.toggle('fv-primary', selected && !busy);- cancel.hidden = !busy; resume.hidden = !stopped;- if (busy) {+ cancel.hidden = !busy || opening; resume.hidden = !stopped;+ const waiting = status?.state === 'queued' && !(status.blocks || []).some(block => ['queued', 'running'].includes(block.state) && block.prompt_id);+ if (opening) hint.textContent = t('Starting…', '正在开始…');+ else if (held || waiting) hint.textContent = t('Queued', '排队中');+ else if (running) {const blocks = status?.blocks || [], done = blocks.filter(block => block.state === 'done').length;const number = Math.min(blocks.length || 1, Math.max(done, status?.chainProgress?.index || 0) + 1), count = blocks.length || 1;const remaining = status?.chainProgress?.overall?.remaining_seconds ?? (blocks.every(block => Number.isFinite(block.remaining_seconds)) ? blocks.reduce((sum, block) => sum + block.remaining_seconds, 0) : null);@@ -41,7 +67,8 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {firstFrame.update(busy);references?.update(busy, busy ? undefined : !!actions.references.visible());generate.textContent = t('Generate', '生成');- generate.disabled = busy || !!previewSelection || !selected || !actions.canGenerate?.(input.value);+ // Never disabled for a reason the press itself can explain or fix.+ generate.disabled = busy || !!previewSelection;generate.title = '';if (selected && !busy) {const key = JSON.stringify(selection);@@ -55,12 +82,24 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {}input.oninput = () => { state.setRangeText(input.value); render(); };generate.onclick = async () => {- submitting = true; render();- try { await actions.generate({target: 'both', text: input.value}); }- catch (error) { actions.error(error); }- finally { submitting = false; render(); }+ const key = JSON.stringify(state.selection ?? null);+ if (pressing.has(key)) return;+ pressing.add(key); say(''); render();+ const typed = input.value;+ try {+ // The press shows before any planning, however long that takes.+ await painted();+ const result = actions.press ? await actions.press(input.value) : await actions.generate({target: 'both', text: input.value});+ // Never over what the user typed meanwhile, for another part.+ if (result?.text != null && result.text !== input.value && input.value === typed) input.value = result.text;+ if (result?.say) say(result.say, !!result.queued);+ if (result?.focus) { pressing.delete(key); render(); input.disabled = false; input.focus(); }+ }+ // A specific reason has already been said; a general one is added only when there was none.+ catch (error) { if (!actions.error(error) && !note.textContent) say(t('Could not start. Try again.', '没能开始,请重试。')); }+ finally { pressing.delete(key); render(); }};- cancel.onclick = () => actions.cancel().catch(actions.error);+ cancel.onclick = () => (!previewSelection && actions.selectionHeld?.() ? Promise.resolve(actions.unhold()).then(render) : actions.cancel()).catch(actions.error);resume.onclick = () => actions.resume().catch(actions.error);const unsubscribe = state.subscribe(event => {if (event.type === 'selection' && state.selection?.kind === 'range') {@@ -75,8 +114,8 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {if (event.type === 'selection' || event.type === 'record') render();});render();- return {element: host, getText() { return input.value; }, update(value) { status = value; render(); }, preview(selection) { previewSelection = selection; render(); }, setText(value) { input.value = value || ''; state.setRangeText(input.value); render(); },- dispose() { disposed = true; ++serial; unsubscribe(); references?.dispose(); }};+ return {element: host, say, getText() { return input.value; }, update(value) { status = value; render(); }, preview(selection) { previewSelection = selection; render(); }, setText(value) { input.value = value || ''; state.setRangeText(input.value); render(); },+ dispose() { disposed = true; ++serial; clearTimeout(noteTimer); unsubscribe(); references?.dispose(); }};}// A missing optional module leaves the editor's existing progress in place.@@ -105,6 +144,7 @@ export function editorBlockStates(job, messages = [], resolve = null) {? Number.isFinite(live.percent) ? live.percent / 100 : live.bar ?? live.overall?.fraction ?? block.fraction: block.fraction;return [block.id, {state: running && live ? 'generating' : states[block.state] || 'waiting',+ ...(['pending', 'queued'].includes(block.state) && !live ? {queued: true} : {}),fraction: Math.max(0, Math.min(1, fraction || 0)),remainingSeconds: running && live ? live.remaining_seconds ?? live.overall?.remaining_seconds ?? block.remaining_seconds ?? null: block.remaining_seconds ?? null}];diff --git a/web/editor_store.js b/web/editor_store.jsindex eae650d..c665da0 100644--- a/web/editor_store.js+++ b/web/editor_store.js@@ -209,14 +209,17 @@ export function createEditorStore(api, {t = en => en, notify = () => {}, onGenerpollers.add(retry);}// Optional adapter (or factory): startChain, owns, chain, chainAction, and- // optional restoreSources. Production callers provide none.+ // optional restoreSources and generationAvailable/generationReady readiness+ // hooks for a delayed test generator. Production callers provide none.const standIn = typeof injected === 'function'? injected({clock, sources, request: json, mediaURL: value => mediaURL(api, value)}) : injected;const store = {sources, cache,- get generationAvailable() { return !!standIn || generationAvailable; },+ get generationAvailable() { return standIn ? standIn.generationAvailable ?? true : generationAvailable; },generationReady() {- if (standIn) return Promise.resolve(true);+ if (standIn) return standIn.generationReady+ ? Promise.resolve(standIn.generationReady(ready => { if (!disposed) onGenerationReady(ready); }))+ : Promise.resolve(true);if (generationAvailable || generationGone || disposed) return Promise.resolve(generationAvailable);// Generating stays off until the list of long videos answers in its// expected shape. One bounded request at a time, shared by concurrent@@ -413,9 +416,9 @@ export function createEditorStore(api, {t = en => en, notify = () => {}, onGenerreturn null;}if (response.status === 400) {- // The server's own sentence for a video with too many parts is shown as it is.+ // The server's own sentence for a video with too many parts, or a continued part too short, is shown as it is.const body = await response.json().catch(() => null);- if (body?.code === 'chain_too_long') throw Object.assign(new Error(body.code), {code: body.code, said: [body.error, body.error_zh]});+ if (['chain_too_long', 'chain_part_too_short'].includes(body?.code)) throw Object.assign(new Error(body.code), {code: body.code, said: [body.error, body.error_zh]});}if (!response.ok) throw errorFor(response);return (await response.json())?.chain || null;diff --git a/web/editor_tracks.css b/web/editor_tracks.cssindex efd73dd..bbd6ece 100644--- a/web/editor_tracks.css+++ b/web/editor_tracks.css@@ -35,7 +35,7 @@.fv-ed-progress-fill{display:none;right:auto;width:calc(var(--fv-ed-progress) * 100%);background:color-mix(in srgb,var(--fv-accent) 55%,transparent)}.fv-ed-clip[data-state=running] .fv-ed-progress-fill:not([hidden]){display:block}.fv-ed-block-progress{display:none}-.fv-ed-clip[data-state=running] .fv-ed-block-progress{display:block}+.fv-ed-clip[data-state=running] .fv-ed-block-progress,.fv-ed-block-progress[data-queued=true]{display:block}.fv-ed-clip[data-state=failed]{border:1px solid color-mix(in srgb,var(--fv-warning) 60%,transparent);background:color-mix(in srgb,var(--fv-warning) 12%,transparent);cursor:grab}.fv-ed-clip-status{position:absolute;left:10px;right:4px;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap;overflow:hidden;color:var(--fv-warning);pointer-events:none}.fv-ed-clip-status svg{width:12px;height:12px;flex:none;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round}diff --git a/web/editor_tracks.js b/web/editor_tracks.jsindex c0a821c..f6865ea 100644--- a/web/editor_tracks.js+++ b/web/editor_tracks.js@@ -437,7 +437,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =const value = progresses.get(item.clip.id) || {state: item.clip.pending === 'queued' ? 'waiting': busy(item.clip) ? 'generating' : model.clipState(item.clip) === 'done' ? 'done': item.clip.pending === 'stopped' ? 'stopped' : model.clipState(item.clip) === 'failed' ? 'failed' : 'waiting',- fraction: 0, remainingSeconds: null};+ fraction: 0, remainingSeconds: null, ...(item.clip.pending === 'queued' ? {queued: true} : {})};item.element.style.setProperty('--fv-ed-progress', String(clamp(Number(value.fraction) || 0, 0, 1)));item.component?.update(value);}@@ -655,6 +655,9 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =for (const value of [frame, frame + length]) points.push(Math.round(value / grid) * grid);return transportSnapPoints(state, points, pointerEvent);}+ // A clip's end can be dragged longer only over hidden source, by generating more, or as a planned part.+ const canGrow = clip => (clip.pending && !clip.source) || isText(clip) || speedEdited(clip) || clip.in + clip.frames < clip.length+ || (clip.extend && actions.generationAvailable?.() !== false);// Only a part that continues another is held to the length of a continued part; a range being drawn never is.function boundaryLimits(clip = null) {const limits = actions.generationLimits?.() || {}, maxSeconds = limits.maxSeconds ?? model.RULES.maxSeconds;@@ -714,7 +717,11 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =if (gesture.type === 'rangeMove' && gesture.rangeBlocked) tooltip.hidden = true;} else if (gesture.type === 'range') {const aligned = snap(frame, points, state.zoom);- gesture.selection = capRange(rangeParameters(gesture.anchor, aligned.frame), aligned.frame < gesture.anchor);+ const drawn = rangeParameters(gesture.anchor, aligned.frame);+ // Drawn from a clip's end, the range starts exactly there.+ if (gesture.flush != null && aligned.frame > gesture.flush) Object.assign(drawn, {start: gesture.flush,+ frames: Math.max(2 * model.FPS, Math.round((aligned.frame - gesture.flush) / model.FPS) * model.FPS)});+ gesture.selection = capRange(drawn, aligned.frame < gesture.anchor);previewSelection = gesture.selection; showGuide(aligned.guide);renderSelection(); hint(gesture.selection, event);} else if (gesture.type === 'move') {@@ -749,6 +756,13 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =selectionBox.classList.toggle('fv-ed-cannot-drop', !!error);if (error) tooltip.hidden = true;} else if (gesture.type === 'edge') {+ // Past the end of a clip that cannot grow there, the drag draws the next part from that end.+ const clipEnd = gesture.clip.start + gesture.clip.frames;+ if (gesture.edge === 'end' && frame > clipEnd && !canGrow(gesture.clip)) {+ for (const id of [...gesture.ids, ...(gesture.rightPreviewIds || [])]) { const item = locate(id); if (item) position(item.element, item.clip.start, item.clip.frames); }+ Object.assign(gesture, {type: 'range', anchor: clipEnd, flush: clipEnd, id: undefined, ids: [], clip: null, edge: null, rightPreviewIds: []});+ cachedPoints = allPoints([]); tooltip.hidden = true; updatePointer(event); return;+ }let result = edgeParameters(gesture.clip, gesture.edge, frame, points, state.zoom, {canExtend: actions.generationAvailable?.() !== false});if (result.kind === 'extend') result.frames = capRange({start: result.frame, frames: result.frames}, false, true).frames;if (result.kind === 'planned') {