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.
Autopilot is a conversation with the connected agent
Bowen Xue5d386d10adb4
diff --git a/web/agent_connect.css b/web/agent_connect.cssindex 45a3f45..3a62b07 100644--- a/web/agent_connect.css+++ b/web/agent_connect.css@@ -1,19 +1,38 @@-/* Connect an agent: one sentence, one action, one status. The card carries its own layout wherever it is placed. */-.fv-agent-connect-body{display:grid;gap:12px;min-width:0}-.fv-agent-connect-body>p{margin:0}-.fv-agent-connect-body .fv-agent-sentence{padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-bg);color:var(--fv-ink);font-size:var(--fv-body);overflow-wrap:anywhere;user-select:all}-.fv-agent-connect-body .fv-agent-sentence:empty{display:none}-.fv-agent-connect-body .fv-agent-note{font-size:var(--fv-micro);line-height:1.5;color:var(--fv-muted)}-.fv-agent-connect-body .fv-agent-note[hidden]{display:none}-.fv-agent-connect-body .fv-agent-connect-actions{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}-.fv-agent-connect-body .fv-agent-connect-status{display:flex;align-items:center;gap:8px;min-width:0;font-size:var(--fv-body);color:var(--fv-muted)}-.fv-agent-connect-body .fv-agent-connect-dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--fv-disabled)}-.fv-agent-connect-body .fv-agent-connect-dot[data-color=green]{background:var(--fv-success)}-/* The Autopilot page: one centred column under the top bar. */-.fv-studio.fv-autopilot{display:grid;grid-template-rows:auto minmax(0,1fr)}-.fv-studio.fv-autopilot .fv-autopilot-body{box-sizing:border-box;overflow:auto;display:grid;align-content:start;justify-items:center;gap:24px;padding:48px 16px 24px}-.fv-autopilot-card{box-sizing:border-box;width:min(640px,100%);display:grid;gap:14px;padding:26px;border:1px solid var(--fv-border);border-radius:var(--fv-r-lg);background:var(--fv-card)}-.fv-autopilot-card>h2{margin:0;font-size:var(--fv-strong);line-height:1.3;font-weight:var(--fv-semibold);color:var(--fv-ink)}-.fv-autopilot-card[hidden]{display:none}-.fv-autopilot-body>.fv-agent-list{box-sizing:border-box;width:min(640px,100%);padding:0 26px}-@media(max-width:480px){.fv-autopilot-card{padding:18px}.fv-autopilot-body>.fv-agent-list{padding:0 18px}}+/* Connect an agent: one card, one action. The card carries its own layout wherever it is placed. */+.fv-agent-connect-body{box-sizing:border-box;width:min(440px,100%);display:grid;justify-items:start;gap:16px;padding:28px;border:1px solid var(--fv-accent-dim);border-radius:14px;background:var(--fv-card);box-shadow:0 0 0 1px color-mix(in srgb,var(--fv-accent-dim) 35%,transparent),0 18px 40px -20px color-mix(in srgb,var(--fv-accent) 40%,transparent)}+.fv-agent-connect-body[hidden],.fv-agent-connect-body [hidden]{display:none}+.fv-agent-connect-body>*{margin:0;min-width:0}+.fv-agent-connect-icon{width:44px;height:44px;border-radius:11px;display:grid;place-items:center;background:var(--fv-selected);color:var(--fv-accent-hover)}+.fv-agent-connect-body svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-linecap:round;stroke-linejoin:round}+.fv-agent-connect-body>h2{font-size:19px;line-height:1.3;font-weight:700;color:var(--fv-ink)}+.fv-agent-connect-body>.fv-muted{margin-top:-10px;font-size:13.5px;color:var(--fv-muted)}+.fv-agent-connect-actions{display:flex;align-items:center;gap:12px;margin-top:10px;flex-wrap:wrap}+.fv-studio .fv-agent-connect-actions button{padding:9px 20px;font-size:14px}.fv-agent-connect-actions button svg{width:16px;height:16px}+.fv-agent-connect-arrow{color:var(--fv-disabled)}.fv-agent-connect-hint{color:var(--fv-muted);font-size:13.5px}+.fv-agent-connect-body .fv-agent-sentence{justify-self:stretch;padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-bg);color:var(--fv-ink);font-size:var(--fv-body);overflow-wrap:anywhere;user-select:all}+/* The Autopilot page: the card in the very middle, or one conversation column under the top bar. */+.fv-studio.fv-autopilot{display:grid;grid-template-rows:auto minmax(0,1fr);overflow:hidden}+.fv-studio.fv-autopilot .fv-header{position:relative}+.fv-autopilot .fv-autopilot-body{box-sizing:border-box;min-height:0;min-width:0;display:grid;grid-template-columns:minmax(0,1fr)}+.fv-autopilot .fv-autopilot-body[data-view=connect]{place-items:center;padding:16px;overflow:auto}+.fv-studio .fv-autopilot-lamp{min-height:0;gap:8px;padding:6px 13px;border:1px solid var(--fv-border);border-radius:99px;background:transparent;color:var(--fv-muted);font-size:13.5px;font-weight:var(--fv-regular);white-space:nowrap;flex:none}+.fv-studio .fv-autopilot-lamp:disabled{opacity:1}.fv-autopilot-lamp[hidden]{display:none}+.fv-autopilot-lamp>i{width:8px;height:8px;border-radius:50%;background:var(--fv-disabled)}+.fv-studio .fv-autopilot-lamp[data-color=green]{color:var(--fv-ink);border-color:#245a45;background:#0f2019}+.fv-autopilot-lamp[data-color=green]>i{background:var(--fv-success);box-shadow:0 0 0 3px color-mix(in srgb,var(--fv-success) 20%,transparent)}+.fv-autopilot-now{display:flex;align-items:center;min-width:0;border:1px solid var(--fv-accent-dim);background:color-mix(in srgb,var(--fv-selected) 55%,var(--fv-bg));border-radius:99px;font-size:13.5px;font-variant-numeric:tabular-nums}+.fv-autopilot-now[hidden]{display:none}+.fv-studio .fv-autopilot-now button{min-height:0;border:0;background:transparent;border-radius:99px}+.fv-studio .fv-autopilot-now-go{gap:9px;padding:6px 4px 6px 13px;min-width:0;color:var(--fv-ink);font-weight:var(--fv-regular);white-space:nowrap}+.fv-autopilot-now-go>i{flex:none;width:16px;height:16px;border-radius:50%;background:conic-gradient(var(--fv-accent) calc(var(--p,0)*1%),#24364a 0);-webkit-mask:radial-gradient(circle,transparent 5px,#000 5.5px);mask:radial-gradient(circle,transparent 5px,#000 5.5px)}+.fv-autopilot-now-name{overflow:hidden;text-overflow:ellipsis;max-width:220px}.fv-autopilot-now-go>:empty:not(i){display:none}+.fv-autopilot-now-go>span:not(.fv-autopilot-now-name),.fv-autopilot-now-go>em{font-style:normal;color:var(--fv-muted)}.fv-autopilot-now-go>b{font-weight:var(--fv-semibold)}+.fv-studio .fv-autopilot-now-stop{flex:none;width:30px;height:30px;padding:0}+.fv-autopilot-now-stop::after{content:"";width:18px;height:18px;border-radius:5px;background:#1b2a3a radial-gradient(circle,var(--fv-danger) 0 0) center/7px 7px no-repeat}+.fv-studio .fv-autopilot-now-stop:hover::after{background-color:var(--fv-danger-subtle)}+.fv-autopilot-line{position:absolute;left:0;bottom:-1px;height:2px;border-radius:0 2px 2px 0;background:linear-gradient(90deg,var(--fv-accent),var(--fv-accent-hover));transition:width .6s var(--fv-ease),opacity .4s;pointer-events:none}+.fv-autopilot-line[data-on=false]{opacity:0}+@media(max-width:1050px){.fv-autopilot-now-go>em{display:none}.fv-autopilot-now-name{max-width:120px}}+@media(max-width:820px){.fv-studio.fv-autopilot .fv-header:has(.fv-autopilot-now:not([hidden])){height:auto;min-height:98px;grid-template-columns:auto minmax(0,1fr);padding-block:10px}.fv-autopilot .fv-header:has(.fv-autopilot-now:not([hidden]))>.fv-view-switch{grid-column:1/-1;grid-row:2;justify-self:center}.fv-autopilot .fv-header:has(.fv-autopilot-now:not([hidden]))>.fv-header-actions{grid-column:2;grid-row:1}}+@media(max-width:480px){.fv-studio.fv-autopilot .fv-header{grid-template-columns:auto minmax(0,1fr)}.fv-autopilot .fv-header-actions>.fv-quiet{display:none}.fv-autopilot-now{font-size:12.5px}.fv-autopilot-now-name{max-width:92px}.fv-studio .fv-autopilot-now-go{padding:5px 2px 5px 10px}.fv-studio .fv-autopilot-lamp{padding:4px 10px;font-size:12.5px}.fv-autopilot-now:not([hidden])+.fv-autopilot-lamp[data-color=green]>span{display:none}.fv-agent-connect-body{padding:22px}}+@media(prefers-reduced-motion:reduce){.fv-autopilot-line{transition:none}}diff --git a/web/agent_connect.js b/web/agent_connect.jsindex b5d850e..b8f8e9f 100644--- a/web/agent_connect.js+++ b/web/agent_connect.js@@ -1,18 +1,9 @@-import {agentGet} from './agent_session.js';-function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }-// null means no connection has been seen; '' remembers a connection without a name.-export function connectionState(copied, status, previousName, t) {- if (status?.connected === true) {- const name = status.client?.trim();- return {color: 'green', text: name ? t(`Connected to ${name}`, `已连接 ${name}`) : t('Connected', '已连接'), buttonText: t('Copy', '复制')};- }- if (previousName != null) {- const name = previousName || 'Agent';- return {color: 'gray', text: t(`${name} disconnected`, `${name} 已断开`), buttonText: t('Reconnect', '重新连接')};- }- return {color: 'gray', text: copied ? t('Waiting for connection…', '等待连接…') : t('Not connected', '未连接'), buttonText: t('Copy', '复制')};+// The one place a page says whether an agent is connected: its name while it is, never a client id.+export function connectionLabel(agent, t) {+ if (agent?.connected !== true) return {color: 'gray', text: t('Not connected', '未连接')};+ return {color: 'green', text: String(agent.name || '').trim() || t('Connected', '已连接')};}export function connectionSentence(address, t) {@@ -20,11 +11,6 @@ export function connectionSentence(address, t) {return t(`Connect to FreeVideo: open ${url} and follow the instructions.`, `请连接 FreeVideo:打开 ${url} 并按说明操作。`);}-// Shown under the status line, only when the service says editing cannot run here; connecting still works.-export function editingNote(status, t) {- return status?.editing === false ? t('The agent cannot edit videos or images for now.', 'Agent 暂时不能剪辑和修图。') : '';-}-// Whether this FreeVideo has the Agent interface on. Any failure counts as off: the surface shows nothing.export async function agentInterfaceEnabled(api) {try {@@ -33,42 +19,46 @@ export async function agentInterfaceEnabled(api) {} catch { return false; }}-// The card alone: who can connect, the sentence, one light and one button. It belongs to whichever surface-// shows it. shown() says whether the user can see it now; the surface calls sync() whenever that may have changed.+const ICONS = {plug: ['M9 7V3M15 7V3M7 7h10v4a5 5 0 0 1-10 0V7zM12 16v5', 1.8], copy: ['M11 9h7a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM5 15V5a2 2 0 0 1 2-2h8', 2]};+function icon(name) {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', ICONS[name][0]);+ svg.setAttribute('stroke-width', String(ICONS[name][1])); svg.append(path);+ return svg;+}++// The card alone: who can connect and one button that copies the sentence to paste to the agent. The sentence+// stays out of sight; it shows, selected, only when the browser refuses the clipboard. shown() says whether the+// user can see the card now; the surface calls sync() whenever that may have changed.export function agentConnectCard(t, api, shown = () => true) {const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./agent_connect.css', import.meta.url).href; document.head.append(css);- const body = el('div', 'fv-agent-connect-body');+ const body = el('section', 'fv-agent-connect-body');+ const mark = el('span', 'fv-agent-connect-icon'); mark.append(icon('plug'));+ const title = el('h2', null, t('Connect an agent', '连接 Agent'));const subtitle = el('p', 'fv-muted', t('Claude Code, Codex, FreeToken and others', 'Claude Code、Codex、FreeToken 等'));- const sentence = el('p', 'fv-agent-sentence');- const note = el('p', 'fv-agent-note'); note.hidden = true;const actions = el('div', 'fv-agent-connect-actions');- const status = el('div', 'fv-agent-connect-status'); status.setAttribute('role', 'status');- const dot = el('span', 'fv-agent-connect-dot'); dot.setAttribute('aria-hidden', 'true');- const label = el('span'); status.append(dot, label);const button = el('button', 'fv-primary'); button.type = 'button'; button.disabled = true;- actions.append(status, button); body.append(subtitle, sentence, actions, note);+ const label = el('span'); button.append(icon('copy'), label);+ const arrow = el('span', 'fv-agent-connect-arrow', '→'); arrow.setAttribute('aria-hidden', 'true');+ actions.append(button, arrow, el('span', 'fv-agent-connect-hint', t('Paste to your agent', '粘贴给 Agent')));+ const sentence = el('p', 'fv-agent-sentence'); sentence.hidden = true;+ body.append(mark, title, subtitle, actions, sentence);- let copied = false, feedback = false, previousName = null, value = null;+ let feedback = false, text = '';let timer, feedbackTimer, controller, generation = 0;const active = () => body.isConnected && shown();- function render() {- const state = connectionState(copied, value, previousName, t);- dot.dataset.color = state.color; label.textContent = state.text;- button.textContent = feedback ? t('Copied', '已复制') : state.buttonText;- note.textContent = editingNote(value, t); note.hidden = !note.textContent;- }+ const render = () => { label.textContent = feedback ? t('Copied', '已复制') : t('Copy', '复制'); };render();button.onclick = async () => {- const text = sentence.textContent;- try { await navigator.clipboard.writeText(text); }+ try { await navigator.clipboard.writeText(text); sentence.hidden = true; }catch {+ sentence.textContent = text; sentence.hidden = false;const range = document.createRange(); range.selectNodeContents(sentence);const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);}if (!active()) return;- copied = true;- if (value?.connected !== true) previousName = null;feedback = true; render();clearTimeout(feedbackTimer);feedbackTimer = setTimeout(() => { feedback = false; render(); }, 2000);@@ -79,40 +69,30 @@ export function agentConnectCard(t, api, shown = () => true) {controller?.abort(); controller = null;clearTimeout(feedbackTimer); feedback = false; render();}- async function poll() {+ // Only the sentence is read here, until it is known; who is connected comes from the surface that holds the card.+ async function load() {const current = generation;const request = new AbortController(); controller = request;try {- if (!sentence.textContent) {- // The sentence carries no parameter: the server gives the agent the language this card showed.- const response = await api.fetchApi('/freevideo/agent/connect?lang=' + t('en', 'zh'), {cache: 'no-store', signal: request.signal});- if (!response.ok) return;- const connect = await response.json();- if (current !== generation || !active()) return;- if (!connect.address) return;- sentence.textContent = connectionSentence(connect.address, t);- button.disabled = false;- }- const response = await agentGet(api, '/freevideo/agent/v1/connect/status', {signal: request.signal});- if (!response.ok) return;- const next = await response.json();- if (current !== generation || !active()) return;- value = next;- if (value.connected === true) previousName = value.client?.trim() || previousName || '';- render();- } catch { /* Keep the last observed state and retry while expanded. */ }+ // The sentence carries no parameter: the server gives the agent the language this card showed.+ const response = await api.fetchApi('/freevideo/agent/connect?lang=' + t('en', 'zh'), {cache: 'no-store', signal: request.signal});+ const connect = response.ok ? await response.json() : null;+ if (current !== generation || !connect?.address) return;+ text = connectionSentence(connect.address, t);+ button.disabled = false;+ } catch { /* Try again while the card is in sight. */ }finally {if (current === generation) {controller = null;- if (active()) timer = setTimeout(poll, 3000);+ if (!text && active()) timer = setTimeout(load, 3000);}}}function sync() {if (!active()) { stop(); return; }- if (!controller && !timer) poll();+ if (!text && !controller && !timer) load();}// Resolves to whether this FreeVideo has the Agent interface on; a surface shows nothing when it is off.const enabled = agentInterfaceEnabled(api);- return {element: body, title: t('Connect an agent', '连接 Agent'), enabled, sync, stop};+ return {element: body, enabled, sync, stop};}diff --git a/web/autopilot.js b/web/autopilot.jsindex 4bc1141..3b333f5 100644--- a/web/autopilot.js+++ b/web/autopilot.js@@ -1,7 +1,7 @@-// The Agent's own page, beside the studio and the editing view: the card that connects one, and under it what the agent is doing.+// The Agent's own page, beside the studio and the editing view: the card that connects one, then the conversation with it.import { api } from '../../scripts/api.js';-import { agentActivityList } from './agent_activity.js';-import { agentConnectCard } from './agent_connect.js';+import { agentConnectCard, connectionLabel } from './agent_connect.js';+import { about, agentChat, jobFraction, jobName } from './autopilot_chat.js';import { openEditorView } from './editor_loader.js';import { closeDialog } from './motion.js';import { openSetup } from './setup.js';@@ -25,32 +25,69 @@ export function openAutopilotView(node, {studio = null} = {}) {const header = el('header', 'fv-header'), brand = el('div', 'fv-brand'), tools = el('div', 'fv-header-actions');brand.append(wordmark());const settings = el('button', 'fv-quiet', t('Settings', '设置')); settings.type = 'button'; settings.onclick = openSetup;- tools.append(settings);+ // The one place this page says who is connected, and beside it what that agent is making now.+ const lamp = el('button', 'fv-autopilot-lamp'), lampText = el('span'); lamp.type = 'button'; lamp.append(el('i'), lampText);+ const now = el('div', 'fv-autopilot-now'), go = el('button', 'fv-autopilot-now-go'), halt = el('button', 'fv-autopilot-now-stop'); now.hidden = true;+ const ring = el('i'), name = el('span', 'fv-autopilot-now-name'), more = el('span'), percent = el('b'), eta = el('em');+ go.type = halt.type = 'button'; go.append(ring, name, more, percent, eta); now.append(go, halt);+ halt.title = t('Stop all', '全部停止'); halt.setAttribute('aria-label', halt.title);+ const line = el('i', 'fv-autopilot-line');+ tools.append(now, lamp, settings);// The view chosen next takes over once this page has closed; Escape goes back to what is underneath.let next = () => studio?.open ? viewChanged('studio', node) : viewChanged('nodes', node);const leave = action => { next = action; closeDialog(dialog); };const navigation = viewSwitch('autopilot', () => leave(() => studio?.open ? viewChanged('studio', node) : openStudio(node)),() => leave(() => showNodes(node, studio)), () => leave(() => openEditorView(node, {studio: studio?.open ? studio : undefined})), () => {});- header.append(brand, navigation, tools);- const card = agentConnectCard(t, api, () => dialog.open && dialog.dataset.closing !== 'true');- const body = el('div', 'fv-autopilot-body'), panel = el('section', 'fv-autopilot-card');- // The list shows itself once an agent is connected or has jobs, and asks nothing while this page is out of sight.- // A finished job opens its work in Creations. Continuing it there belongs to the studio, so this page gives way first.- const jobs = agentActivityList(t, api, {open: async job => (await import('./library.js')).openLibrary(t, {selectedWork: job.work,- extend: async record => {- if (dialog.open) await new Promise(done => { dialog.addEventListener('close', done, {once: true}); closeDialog(dialog); });- return extendVideo(record, node);- }})});- panel.append(el('h2', null, card.title), card.element); body.append(panel, jobs.element);- card.enabled.then(on => { if (!on) panel.hidden = true; });+ header.append(brand, navigation, tools, line);+ const inSight = () => dialog.open && dialog.dataset.closing !== 'true';+ const body = el('div', 'fv-autopilot-body');+ const card = agentConnectCard(t, api, () => inSight() && !card.element.hidden);+ // Leaving for another view waits until this page has closed, so the view underneath is never covered twice.+ const closed = () => dialog.open ? new Promise(done => { dialog.addEventListener('close', done, {once: true}); closeDialog(dialog); }) : null;+ const chat = agentChat(t, api, {shown: inSight,+ // A finished video opens as its work in Creations. Continuing it there belongs to the studio, so this page gives way first.+ open: async job => (await import('./library.js')).openLibrary(t, {selectedWork: job.work, back: t('Back to Autopilot', '返回 AI 全自动'),+ extend: async record => { await closed(); return extendVideo(record, node); }}),+ edit: job => leave(() => openEditorView(node, {studio: studio?.open ? studio : undefined, work: {id: job.work, video: `FreeVideo/${job.work}/video.mp4`, geometry: {width: job.width, height: job.height, seconds: job.seconds}}})),+ changed: view => { last = view; show(); }});+ // With no agent the card stands alone in the middle. Once one has connected the conversation stays, also after+ // it disconnects; the light then leads back to the card.+ let last = {known: false, agent: {}, current: null, active: 0, any: false}, on = null, wantCard = false, currentId = null;+ function show() {+ const connected = last.agent.connected === true, label = connectionLabel(last.agent, t);+ if (connected) wantCard = false;+ const ready = on === true && last.known, talking = ready && (connected || (last.any && !wantCard));+ // The card gives way to the conversation: typing can start at once.+ const arrived = talking && chat.element.hidden && (card.element.contains(document.activeElement) || document.activeElement === lamp);+ card.element.hidden = !ready || talking; chat.element.hidden = !talking;+ if (arrived) chat.input.focus();+ body.dataset.view = talking ? 'chat' : 'connect';+ lamp.hidden = !ready; lamp.dataset.color = label.color; lampText.textContent = label.text; lamp.disabled = connected || !last.any;+ const job = talking ? last.current : null;+ now.hidden = !job; line.dataset.on = String(!!job);+ if (job) {+ const fraction = jobFraction(job), running = job.status === 'running';+ currentId = job.id; name.textContent = jobName(job, t); more.textContent = last.active > 1 ? `+${last.active - 1}` : '';+ percent.textContent = running ? `${Math.round(fraction * 100)}%` : '';+ eta.textContent = running && job.progress?.remaining_seconds > 0 ? about(job.progress.remaining_seconds, t) : '';+ ring.style.setProperty('--p', String(fraction * 100)); line.style.width = `${fraction * 100}%`;+ }+ card.sync();+ }+ lamp.onclick = () => { wantCard = !wantCard; show(); };+ go.onclick = () => chat.scrollToJob(currentId);+ halt.onclick = () => chat.stopAll();+ body.append(card.element, chat.element);+ card.enabled.then(value => { on = value; show(); if (value) chat.sync(); });+ show();dialog.append(header, body);dialog.addEventListener('cancel', event => { event.preventDefault(); closeDialog(dialog); });dialog.onclose = () => {- card.stop(); jobs.stop(); dialog.remove();+ card.stop(); chat.stop(); dialog.remove();if (current === dialog) current = null;next();};- current = dialog; document.body.append(dialog); dialog.showModal(); viewChanged('autopilot', node); card.sync();+ current = dialog; document.body.append(dialog); dialog.showModal(); viewChanged('autopilot', node); show();navigation.querySelector('[data-view=autopilot]').focus();return dialog;}diff --git a/web/autopilot_chat.css b/web/autopilot_chat.cssnew file mode 100644index 0000000..a8035b8--- /dev/null+++ b/web/autopilot_chat.css@@ -0,0 +1,73 @@+/* The conversation with an agent: one column, the box to type in fixed under it. */+.fv-chat{box-sizing:border-box;position:relative;min-height:0;min-width:0;display:grid;grid-template-rows:minmax(0,1fr) auto;grid-template-columns:minmax(0,1fr);gap:16px;padding:0 40px 22px}+.fv-chat[hidden],.fv-chat [hidden]{display:none}+.fv-chat-scroll{min-height:0;overflow:auto;margin:0 -40px;padding:24px 40px 2px;scrollbar-gutter:stable both-edges}+.fv-chat-log{list-style:none;margin:0 auto;padding:0;width:100%;max-width:720px;display:grid;grid-template-columns:minmax(0,1fr);align-content:start;gap:18px}+.fv-chat-log>li{min-width:0}.fv-chat-log p{margin:0}+.fv-chat-me{justify-self:end;max-width:min(500px,88%)}+.fv-chat-me>p{background:#1d3550;border-radius:14px 14px 4px 14px;padding:10px 14px;white-space:pre-wrap;overflow-wrap:anywhere;transition:opacity var(--fv-base) var(--fv-ease)}+.fv-chat-me[data-taken=false]>p{opacity:.7}+.fv-chat-ai>p{max-width:600px;white-space:pre-wrap;overflow-wrap:anywhere}+.fv-chat-hello{padding-top:72px}.fv-chat-hello>p{font-size:24px;line-height:1.5;font-weight:var(--fv-semibold);letter-spacing:.2px}+.fv-chat-hello+.fv-chat-examples{margin-top:-2px}+.fv-chat-examples>div{display:grid;gap:10px;margin-top:12px}.fv-chat-meta{color:var(--fv-muted);font-size:12.5px;font-variant-numeric:tabular-nums}+.fv-chat-examples>.fv-chat-meta{font-size:14px}+.fv-studio .fv-chat-examples button{justify-content:flex-start;text-align:left;min-height:0;padding:12px 16px;border:1px solid var(--fv-border);background:#121b26;border-radius:11px;font-size:15px;font-weight:var(--fv-regular);color:var(--fv-ink)}+.fv-studio .fv-chat-examples button:hover:not(:disabled){border-color:var(--fv-accent-dim);background:#14243a}+/* A job the agent started: the frame fills like water while it is made, then holds the video. */+.fv-chat-job{box-sizing:border-box;justify-self:start;width:100%;max-width:560px;display:grid;grid-template-columns:auto minmax(0,1fr);gap:14px;padding:12px;border:1px solid var(--fv-border);border-radius:14px;background:var(--fv-card)}+.fv-chat-job:is([data-mode=stopped],[data-mode=failed],[data-mode=quiet]){width:auto;display:flex;align-items:center;gap:10px;padding:0;border:0;background:none;color:var(--fv-muted);font-size:13.5px}+.fv-chat-preview{position:relative;align-self:start;width:124px;aspect-ratio:16/9;border-radius:9px;overflow:hidden;background:#0c121a}+.fv-chat-preview[data-shape=wide]{width:196px}+.fv-chat-preview>:is(img,video){position:absolute;inset:0;width:100%;height:100%;object-fit:contain;display:block}+.fv-chat-preview>img{animation:fv-chat-in .3s var(--fv-ease)}.fv-chat-preview[data-video]>img{display:none}+@keyframes fv-chat-in{from{opacity:0}}+.fv-chat-water{position:absolute;left:0;right:0;bottom:0;background:linear-gradient(180deg,#4f9dff66,#2a6fc955 60%,#1d4f9566);transition:height .6s var(--fv-ease)}+.fv-chat-water::before{content:"";position:absolute;left:0;right:0;top:-18px;height:18px;background:linear-gradient(180deg,transparent,#4f9dff2e)}+.fv-chat-water::after{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:linear-gradient(90deg,#9fd2ff,#e3f2ff 45%,#9fd2ff) 0 0/200% 100%;box-shadow:0 0 10px #7cc4ff;animation:fv-chat-shine 5s linear infinite}+@keyframes fv-chat-shine{to{background-position:-200% 0}}+.fv-chat-percent{position:absolute;left:0;right:0;top:50%;transform:translateY(-50%);text-align:center;font-size:26px;line-height:1;font-weight:700;font-variant-numeric:tabular-nums;text-shadow:0 2px 10px #000a}+.fv-chat-length{position:absolute;right:7px;bottom:6px;font-size:11.5px;line-height:1.5;color:#fff;background:#0009;border-radius:4px;padding:0 5px;font-variant-numeric:tabular-nums;pointer-events:none}+.fv-chat-preview[data-video] .fv-chat-length{bottom:16px}+.fv-studio .fv-chat-play{position:absolute;inset:0;width:100%;height:100%;min-height:0;padding:0;border:0;border-radius:0;background:transparent}+.fv-studio .fv-chat-play:hover{background:transparent}+.fv-chat-play::before{content:"";width:46px;height:46px;border-radius:50%;background:#0b1118b8;border:1px solid #ffffff3d;transition:opacity var(--fv-quick)}+.fv-chat-play::after{content:"";position:absolute;left:50%;top:50%;margin:-8px 0 0 -4px;border-left:13px solid #fff;border-top:8px solid transparent;border-bottom:8px solid transparent;transition:opacity var(--fv-quick)}+.fv-chat-preview[data-playing=true] .fv-chat-play::before,.fv-chat-preview[data-playing=true] .fv-chat-play::after{opacity:0}+.fv-chat-seek{position:absolute;left:8px;right:8px;bottom:5px;width:auto;height:10px;min-height:0;margin:0;padding:0;border:0;background:none;appearance:none;-webkit-appearance:none;cursor:pointer}+.fv-studio .fv-chat-seek{min-height:0;border-radius:9px}+.fv-chat-seek::-webkit-slider-runnable-track{height:3px;border-radius:9px;background:#ffffff40}+.fv-chat-seek::-webkit-slider-thumb{-webkit-appearance:none;width:9px;height:9px;margin-top:-3px;border-radius:50%;background:#fff}+.fv-chat-seek::-moz-range-track{height:3px;border-radius:9px;background:#ffffff40}.fv-chat-seek::-moz-range-thumb{width:9px;height:9px;border:0;border-radius:50%;background:#fff}+.fv-chat-info{display:grid;align-content:space-between;gap:12px;min-width:0;padding:4px 4px 2px 0}+.fv-chat-info h3{margin:0;font-size:15px;line-height:1.4;font-weight:var(--fv-semibold);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.fv-chat-info .fv-chat-meta{margin-top:3px}+.fv-chat-parts{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:4px;margin-bottom:7px}+.fv-chat-parts>i{position:relative;height:6px;border-radius:9px;background:#1f2c3b;overflow:hidden}+.fv-chat-parts>i::after{content:"";position:absolute;left:0;top:0;bottom:0;width:var(--w,0%);background:var(--fv-accent);transition:width .6s var(--fv-ease)}+.fv-chat-line{display:flex;justify-content:space-between;gap:10px;color:var(--fv-muted);font-size:12.5px;font-variant-numeric:tabular-nums}+.fv-chat-actions{display:flex;align-items:center;gap:8px;min-width:0}.fv-chat-left{flex:1;min-width:0;color:var(--fv-muted);font-size:12.5px;font-variant-numeric:tabular-nums}+.fv-studio .fv-chat-log :is(.fv-chat-actions,.fv-chat-job)>button{flex:none;min-height:0;padding:5px 14px;border-radius:7px;font-size:13px;white-space:nowrap}+.fv-studio .fv-chat-stop::before{content:"";width:8px;height:8px;border-radius:2px;background:var(--fv-danger)}+.fv-studio .fv-chat-stop:disabled{opacity:1;border-color:transparent;background:none;color:var(--fv-muted)}.fv-studio .fv-chat-stop:disabled::before{display:none}+.fv-chat-confirm{box-sizing:border-box;justify-self:start;width:100%;max-width:440px;display:grid;gap:12px;padding:14px 14px 12px;border:1px solid var(--fv-border);border-radius:14px;background:var(--fv-card)}+.fv-chat-confirm>p:first-child{font-size:14.5px;line-height:1.55;overflow-wrap:anywhere}.fv-chat-confirm>.fv-chat-meta{margin-top:-6px}+.fv-chat-confirm[data-state=answered]{width:auto;padding:0;border:0;background:none;color:var(--fv-muted);font-size:13.5px}+/* The agent has the sentence and has not answered yet. */+.fv-chat-dots{display:inline-flex;gap:5px;align-items:center;height:22px}+.fv-chat-dots>i,.fv-chat-dots:empty::before{content:"";width:6px;height:6px;border-radius:50%;background:var(--fv-muted);animation:fv-chat-breathe 1.4s var(--fv-ease) infinite}+.fv-chat-dots>i:nth-child(2){animation-delay:.2s}.fv-chat-dots>i:nth-child(3){animation-delay:.4s}+@keyframes fv-chat-breathe{0%,100%{opacity:.25}40%{opacity:1}}+.fv-studio .fv-chat-down{position:absolute;right:max(40px,calc(50% - 360px));bottom:96px;width:34px;height:34px;min-height:0;padding:0;border-radius:50%;background:var(--fv-raised);box-shadow:0 6px 18px #0008}+.fv-chat svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-linecap:round;stroke-linejoin:round}+.fv-chat-input{box-sizing:border-box;justify-self:center;width:100%;max-width:720px;min-height:54px;display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:end;border:1px solid var(--fv-border);background:#0e151e;border-radius:14px;padding:8px 8px 8px 16px;transition:border-color var(--fv-quick),box-shadow var(--fv-quick)}+.fv-chat-input:focus-within{border-color:var(--fv-accent-dim);box-shadow:0 0 0 3px color-mix(in srgb,var(--fv-accent) 13%,transparent)}+.fv-studio.fv-autopilot .fv-chat-input textarea,.fv-chat-input textarea{box-sizing:border-box;width:100%;height:36px;min-height:36px;max-height:none;padding:7px 0;border:0;border-radius:0;background:none;color:var(--fv-ink);font-size:14.5px;line-height:22px;resize:none;outline:none;overflow-y:auto}+.fv-chat-input textarea::placeholder{color:var(--fv-disabled)}+.fv-studio .fv-chat-send{width:36px;height:36px;min-height:0;padding:0;border:0;border-radius:9px;background:var(--fv-accent);color:var(--fv-bg)}+.fv-studio .fv-chat-send:hover:not(:disabled){background:var(--fv-accent-hover)}+.fv-studio .fv-chat-send:disabled{opacity:1;background:#22344a;color:#9fb3c8}+.fv-studio .fv-chat-send:focus-visible{outline-offset:2px}+@media(max-width:480px){.fv-chat{padding:0 14px 14px}.fv-chat-scroll{margin:0 -14px;padding:16px 14px 2px}.fv-chat-hello{padding-top:32px}.fv-chat-job{max-width:none;gap:12px}.fv-chat-confirm{max-width:none}+ .fv-chat-preview,.fv-chat-preview[data-shape=wide]{width:98px}.fv-chat-percent{font-size:22px}.fv-studio.fv-autopilot .fv-chat-input textarea{font-size:16px}.fv-studio .fv-chat-down{right:14px;bottom:84px}}+@media(prefers-reduced-motion:reduce){.fv-chat-water,.fv-chat-parts>i::after{transition:none}.fv-chat-water::after,.fv-chat-dots>i,.fv-chat-preview>img{animation:none}}diff --git a/web/autopilot_chat.js b/web/autopilot_chat.jsnew file mode 100644index 0000000..a39ed7a--- /dev/null+++ b/web/autopilot_chat.js@@ -0,0 +1,365 @@+// The conversation with the connected agent: what the user says, what the agent answers, and the agent's jobs as+// cards at the place they happened. Reads and sends use the page session; the agent's token never enters the page.+import {agentGet, agentPost} from './agent_session.js';++const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./autopilot_chat.css', import.meta.url).href; document.head.append(css);++function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }+function glyph(path, width = 2.2) {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('stroke-width', String(width));+ const p = document.createElementNS('http://www.w3.org/2000/svg', 'path'); p.setAttribute('d', path); svg.append(p);+ return svg;+}+const press = (cls, text, action) => { const b = el('button', cls, text); b.type = 'button'; b.onclick = action; return b; };++const WORKING = ['running', 'queued', 'waiting'], VIDEOS = ['generate', 'assemble'];+// What a job with no picture of its own is doing, in the reader's language.+const QUIET = {vlm: ['Checking', '检查中'], enhance: ['Writing the prompt', '润色提示词']};++export const about = (seconds, t) => seconds >= 60 ? t(`About ${Math.ceil(seconds / 60)} min`, `约 ${Math.ceil(seconds / 60)} 分钟`) : t('Under 1 min', '不到 1 分钟');+export function clock(seconds) { const s = Math.max(0, Math.round(seconds)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; }+export const jobName = (job, t) => job.label || t('Video', '视频');+export const jobFraction = job => Math.max(0, Math.min(1, Number(job.progress?.fraction) || 0));+// working, done, stopped or failed: which card a job shows.+export const jobMode = job => WORKING.includes(job.status) ? 'working' : job.status === 'succeeded' ? 'done' : job.status === 'cancelled' ? 'stopped' : 'failed';+// The one line that says where a job is. No step count is written unless the engine gave one.+export function jobLine(job, t) {+ const p = job.progress || {};+ if (job.status !== 'running') return t('Queued', '排队中');+ if (p.phase === 'sampling' && p.step?.total) return t(`Step ${p.step.done} / ${p.step.total}`, `生成 ${p.step.done} / ${p.step.total}`);+ if (['decode', 'finishing', 'assembling'].includes(p.phase)) return t('Saving', '保存中');+ return t('Preparing', '准备中');+}+export function jobMeta(job, t) {+ const parts = [];+ if (job.width > 0 && job.height > 0) parts.push(`${job.width} × ${job.height}`);+ if (job.seconds > 0) parts.push(t(`${job.seconds} s`, `${job.seconds} 秒`));+ return parts.join(' · ');+}+// One number per part of a long video: 1 when made, how far along for the one being made, 0 for the rest.+export function jobParts(job) {+ const block = job.progress?.block, step = job.progress?.step;+ if (!(block?.total > 1)) return [];+ const inside = job.progress.phase === 'sampling' && step?.total ? Math.min(1, step.done / step.total) : 0;+ return Array.from({length: block.total}, (_, i) => i < (block.done || 0) ? 1 : i === block.index - 1 ? inside : 0);+}++export const emptyChat = () => ({session: undefined, items: new Map(), jobs: {}, confirms: {}, last: 0, read: 0, agent: {}, current: null, active: 0});+// One answer from the server folded into what the page already has: entries add up by their number, jobs are+// replaced by id (a card keeps its last state after the server stops listing its job), and so are the answers to its questions.+export function chatMerge(state, data) {+ const items = new Map(state.items);+ for (const item of data.items || []) if (['message', 'job', 'confirm'].includes(item.type) && Number.isFinite(item.seq)) items.set(item.seq, item);+ const read = Math.max(state.read, Number(data.read_seq) || 0, ...(data.items || []).filter(item => item.read === true).map(item => item.seq));+ return {session: data.session ?? null, items, jobs: {...state.jobs, ...(data.jobs || {})}, confirms: {...state.confirms, ...(data.confirms || {})}, read,+ last: Math.max(state.last, Number(data.last_seq) || 0, ...items.keys()), agent: data.agent || {},+ current: data.current || null, active: Number(data.active) || 0};+}+// The entries in order. A user's sentence counts as taken once the agent has read it or has said or done anything after it.+export function chatEntries(state) {+ const list = [...state.items.values()].sort((a, b) => a.seq - b.seq);+ let answered = 0;+ for (const item of list) if (item.type !== 'message' || item.role !== 'user') answered = item.seq;+ return list.map(item => item.type === 'message' && item.role === 'user'+ ? {...item, taken: item.read === true || item.seq <= state.read || item.seq < answered} : item);+}+// Whether a sentence sent now reaches anyone: the agent is waiting for one, or is at work and will come back for it.+export const canSend = state => state.agent?.connected === true && (state.agent.listening !== false || state.active > 0);++function newId() {+ const bytes = crypto.getRandomValues(new Uint8Array(12));+ return 'm-' + [...bytes].map(b => b.toString(36).padStart(2, '0')).join('').slice(0, 20);+}++// open(job) shows a finished video in Creations, edit(job) takes it to the editing view. shown() says whether the+// user can see the conversation; the page calls sync() whenever that may have changed. changed(view) follows every+// answer: {known, agent, current, active, any}.+export function agentChat(t, api, {open, edit, shown = () => true, changed = () => {}, interval = 1500} = {}) {+ const element = el('section', 'fv-chat'), scroller = el('div', 'fv-chat-scroll'), log = el('ol', 'fv-chat-log');+ log.setAttribute('role', 'log'); log.setAttribute('aria-label', t('Conversation', '对话'));+ const down = press('fv-chat-down', null, () => { scroller.scrollTo({top: scroller.scrollHeight, behavior: 'smooth'}); });+ down.append(glyph('M12 5v14M5 12l7 7 7-7')); down.setAttribute('aria-label', t('Latest', '最新')); down.hidden = true;+ const form = el('form', 'fv-chat-input'), input = el('textarea'), sendButton = el('button', 'fv-chat-send');+ input.rows = 1; input.maxLength = 8000; input.setAttribute('aria-label', t('Message the agent', '对 Agent 说'));+ sendButton.type = 'submit'; sendButton.setAttribute('aria-label', t('Send', '发送')); sendButton.append(glyph('M12 19V5M5 12l7-7 7 7'));+ form.append(input, sendButton); scroller.append(log); element.append(scroller, down, form);++ let state = emptyChat(), pending = [], known = false, stopped = false, timer = null, busy = false, failures = 0;+ const nodes = new Map(), answers = new Map(), stopping = new Set();+ const active = () => !stopped && element.isConnected && !document.hidden && shown();++ // ---- one entry of the conversation each ----+ function message(role) {+ const item = el('li', role === 'user' ? 'fv-chat-me' : 'fv-chat-ai'), text = el('p'); item.append(text);+ return {element: item, update(entry) { text.textContent = entry.text; if (role === 'user') item.dataset.taken = String(entry.taken !== false); }};+ }+ function preview(job) {+ const box = el('div', 'fv-chat-preview');+ const shape = (w, h) => { if (w > 0 && h > 0) { box.style.aspectRatio = `${w} / ${h}`; box.dataset.shape = w > h * 1.1 ? 'wide' : 'tall'; } };+ shape(job.width, job.height);+ return {box, shape};+ }+ function working(item, job) {+ const {box} = preview(job), water = el('i', 'fv-chat-water'), percent = el('b', 'fv-chat-percent'); box.append(water, percent);+ const info = el('div', 'fv-chat-info'), head = el('div'), name = el('h3'), meta = el('p', 'fv-chat-meta'); head.append(name, meta);+ const middle = el('div', 'fv-chat-where'), parts = el('div', 'fv-chat-parts'), line = el('p', 'fv-chat-line'), part = el('span'), step = el('span'); line.append(part, step);+ middle.append(parts, line);+ const foot = el('div', 'fv-chat-actions'), left = el('span', 'fv-chat-left');+ const stop = press('fv-chat-stop', null, async () => {+ stopping.add(job.id); render();+ try { await agentPost(api, '/freevideo/agent/activity/cancel', {id: job.id}); } catch { stopping.delete(job.id); }+ poll();+ });+ foot.append(left, stop); info.append(head, middle, foot); item.replaceChildren(box, info);+ return next => {+ const fraction = jobFraction(next), cells = jobParts(next), queued = next.status !== 'running';+ water.style.height = `${fraction * 100}%`; percent.textContent = queued ? '' : `${Math.round(fraction * 100)}%`;+ name.textContent = jobName(next, t); meta.textContent = jobMeta(next, t); meta.hidden = !meta.textContent;+ while (parts.children.length > cells.length) parts.lastChild.remove();+ while (parts.children.length < cells.length) parts.append(el('i'));+ cells.forEach((value, index) => parts.children[index].style.setProperty('--w', `${value * 100}%`));+ parts.hidden = !cells.length;+ const block = next.progress?.block;+ part.textContent = cells.length ? t(`Part ${block.index} / ${block.total}`, `第 ${block.index} / ${block.total} 段`) : jobLine(next, t);+ step.textContent = cells.length ? jobLine(next, t) : '';+ left.textContent = !queued && next.progress?.remaining_seconds > 0 ? about(next.progress.remaining_seconds, t) : '';+ const going = stopping.has(next.id);+ stop.disabled = going; stop.textContent = going ? t('Stopping', '正在停止') : t('Stop', '停止');+ stop.setAttribute('aria-label', t('Stop ', '停止 ') + jobName(next, t));+ };+ }+ function done(item, job) {+ const info = el('div', 'fv-chat-info'), head = el('div'), name = el('h3'), meta = el('p', 'fv-chat-meta'); head.append(name, meta);+ const foot = el('div', 'fv-chat-actions');+ const show = press('fv-chat-open', t('Open', '打开'), () => open(job));+ const cut = press('fv-chat-edit', t('Edit', '剪辑'), () => edit(job));+ if (job.work) foot.append(show, cut);+ info.append(head, foot);+ const children = [info];+ if (job.thumbnail || job.play) {+ const {box, shape} = preview(job), length = el('span', 'fv-chat-length', job.seconds > 0 ? clock(job.seconds) : '');+ if (job.thumbnail) {+ const image = el('img'); image.alt = ''; image.src = api.apiURL(job.thumbnail);+ image.onload = () => { if (!box.style.aspectRatio) shape(image.naturalWidth, image.naturalHeight); };+ box.append(image);+ }+ if (job.play) {+ // The video plays inside its frame, with its sound; the line under it follows and can be dragged.+ let video = null;+ const toggle = press('fv-chat-play', null, () => {+ if (!video) {+ video = el('video'); video.playsInline = true; video.src = api.apiURL(job.play);+ const seek = el('input', 'fv-chat-seek'); seek.type = 'range'; seek.min = '0'; seek.max = '1000'; seek.value = '0';+ seek.setAttribute('aria-label', t('Position', '播放位置'));+ video.onloadedmetadata = () => shape(video.videoWidth, video.videoHeight);+ video.ontimeupdate = () => { if (video.duration) seek.value = String(Math.round(video.currentTime / video.duration * 1000)); };+ video.onplay = video.onpause = video.onended = () => { box.dataset.playing = String(!video.paused && !video.ended); label(); };+ seek.oninput = () => { if (video.duration) video.currentTime = seek.value / 1000 * video.duration; };+ box.prepend(video); box.append(seek); box.dataset.video = 'true';+ }+ if (video.paused || video.ended) void video.play().catch(() => {}); else video.pause();+ });+ const label = () => toggle.setAttribute('aria-label', (box.dataset.playing === 'true' ? t('Pause ', '暂停 ') : t('Play ', '播放 ')) + jobName(job, t));+ label(); box.append(toggle);+ }+ if (length.textContent) box.append(length);+ children.unshift(box);+ }+ item.replaceChildren(...children);+ return (next, latest) => {+ name.textContent = jobName(next, t); meta.textContent = jobMeta(next, t); meta.hidden = !meta.textContent;+ show.classList.toggle('fv-primary', latest);+ };+ }+ function jobCard() {+ const item = el('li', 'fv-chat-job');+ let mode = null, apply = null;+ return {element: item, update(job, {latest, retry}) {+ // Jobs without a picture (a check, a prompt) are one quiet line while they run, and nothing after.+ const next = VIDEOS.includes(job.kind || 'generate') ? jobMode(job) + (jobMode(job) === 'done' ? `:${job.play}:${job.thumbnail}:${job.work}` : '')+ : WORKING.includes(job.status) ? 'quiet' : 'none';+ if (next !== mode) {+ mode = next; item.dataset.job = job.id; item.dataset.mode = next.split(':')[0]; item.hidden = next === 'none';+ if (next !== 'working') stopping.delete(job.id);+ if (next === 'working') apply = working(item, job);+ else if (next.startsWith('done')) apply = done(item, job);+ else if (next === 'quiet') { item.replaceChildren(el('span', 'fv-chat-dots'), el('span', null, t(...(QUIET[job.kind] || ['Working', '进行中'])))); apply = null; }+ else if (next === 'stopped') { item.replaceChildren(el('span', null, t('Stopped', '已停止'))); apply = null; }+ else if (next === 'failed') {+ item.replaceChildren(el('span', null, t('Could not generate', '没有生成出来')));+ // Trying again says the same sentence to the agent once more; why it failed is the agent's to say.+ if (retry) item.append(press('fv-chat-retry', t('Retry', '重试'), retry));+ apply = null;+ } else { item.replaceChildren(); apply = null; }+ }+ apply?.(job, latest);+ const again = item.querySelector('.fv-chat-retry'); if (again) again.disabled = !canSend(state);+ }};+ }+ function confirmCard() {+ const item = el('li', 'fv-chat-confirm');+ let shownState = null;+ return {element: item, update(entry) {+ const value = answers.get(entry.id) || state.confirms[entry.id] || entry.state || 'asked';+ if (value === shownState) return;+ shownState = value; item.dataset.state = value === 'asked' ? 'asked' : 'answered';+ if (value !== 'asked') { item.replaceChildren(el('span', null, value === 'approved' ? t('Started', '已开始') : t('Not now', '先不拍'))); return; }+ const answer = approve => async () => {+ item.querySelectorAll('button').forEach(button => { button.disabled = true; });+ try {+ const response = await agentPost(api, '/freevideo/agent/chat/confirm', {id: entry.id, approve});+ if (response.ok) answers.set(entry.id, (await response.json()).state || (approve ? 'approved' : 'declined'));+ } catch { /* The card stays as asked. */ }+ shownState = null; render(); poll();+ };+ const buttons = el('div', 'fv-chat-actions');+ buttons.append(press('fv-chat-yes fv-primary', t('Start', '开始'), answer(true)), press('fv-chat-no', t('Not now', '先不'), answer(false)));+ const question = el('p', null, entry.question);+ const estimate = el('p', 'fv-chat-meta', entry.estimate_seconds > 0 ? about(entry.estimate_seconds, t) : ''); estimate.hidden = !estimate.textContent;+ item.replaceChildren(question, estimate, buttons);+ }};+ }+ // Before anything is said: what the agent can do, and sentences that send themselves when clicked.+ function hello() {+ const item = el('li', 'fv-chat-hello');+ item.append(el('p', null, t('I can make videos for you,', '我可以替你生成视频,')), el('p', null, t('or turn a story into a short film.', '也可以把一个故事拍成短片。')));+ return {element: item, update() {}};+ }+ function examples() {+ const item = el('li', 'fv-chat-examples'), list = el('div');+ const lines = [t('Make a 10-second video: a rainy night, a girl squeezes onto the last bus', '生成一段 10 秒的视频:雨夜,女孩挤上末班车'),+ t('Make a 1-minute vertical short film: a day in a coffee shop', '做一条 1 分钟的竖屏短片:咖啡店的一天')];+ list.append(...lines.map(line => press(null, line, () => send(line))));+ item.append(el('p', 'fv-chat-meta', t('Try saying:', '可以这样说:')), list);+ return {element: item, update() { list.querySelectorAll('button').forEach(button => { button.disabled = !canSend(state); }); }};+ }+ function dots() {+ const item = el('li', 'fv-chat-thinking'), mark = el('span', 'fv-chat-dots'); mark.append(el('i'), el('i'), el('i'));+ item.setAttribute('role', 'status'); item.setAttribute('aria-label', t('Thinking', '正在思考')); item.append(mark);+ return {element: item, update() {}};+ }+ const MAKE = {hello, examples, dots, user: () => message('user'), agent: () => message('agent'), job: jobCard, confirm: confirmCard};++ function render(follow = false) {+ const entries = chatEntries(state), ids = new Set(entries.map(entry => entry.id).filter(Boolean));+ pending = pending.filter(entry => !ids.has(entry.id));+ const said = entries.some(entry => entry.type !== 'message' || entry.role === 'user') || pending.length > 0;+ const finished = entries.filter(entry => entry.type === 'job' && state.jobs[entry.job]?.status === 'succeeded' && state.jobs[entry.job].work).at(-1);+ const wanted = [];+ if (!entries.length && !pending.length) wanted.push(['hello', 'hello', null]);+ let lastUser = null;+ for (const entry of entries) {+ if (entry.type === 'message') {+ if (entry.role === 'user') lastUser = entry;+ wanted.push([entry.role === 'user' && entry.id ? `m:${entry.id}` : `s:${entry.seq}`, entry.role === 'user' ? 'user' : 'agent', entry]);+ } else if (entry.type === 'job') {+ const job = state.jobs[entry.job]; if (!job) continue;+ const text = lastUser?.text;+ wanted.push([`s:${entry.seq}`, 'job', job, {latest: entry === finished, retry: text ? () => send(text) : null}]);+ } else wanted.push([`s:${entry.seq}`, 'confirm', entry]);+ }+ for (const entry of pending) wanted.push([`m:${entry.id}`, 'user', {...entry, taken: false}]);+ if (!said) wanted.push(['examples', 'examples', null]);+ // The agent has the sentence, or is waiting for one, and has not answered yet.+ const tail = pending.at(-1) || entries.at(-1);+ if (tail?.type !== 'job' && tail?.type !== 'confirm' && (pending.length || tail?.role === 'user') && state.agent.connected === true+ && (state.agent.listening !== false || tail.taken === true)) wanted.push(['dots', 'dots', null]);++ const stick = follow || scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48;+ const before = log.children.length, keep = new Set(wanted.map(([key]) => key));+ for (const [key, node] of nodes) if (!keep.has(key)) { node.element.remove(); nodes.delete(key); }+ wanted.forEach(([key, kind, value, extra], index) => {+ let node = nodes.get(key);+ if (!node) { node = MAKE[kind](); nodes.set(key, node); }+ node.update(value, extra || {});+ if (log.children[index] !== node.element) log.insertBefore(node.element, log.children[index] || null);+ });+ const sendable = canSend(state);+ input.disabled = state.agent.connected !== true;+ input.placeholder = state.agent.connected === true && !sendable ? t('Ask your agent to keep listening', '回到 Agent 那边让它继续') : t('Message the agent…', '对 Agent 说…');+ sendButton.disabled = !sendable || !input.value.trim();+ if (stick) { scroller.scrollTop = scroller.scrollHeight; down.hidden = true; }+ else if (log.children.length > before) down.hidden = false;+ }+ scroller.addEventListener('scroll', () => { if (scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 48) down.hidden = true; }, {passive: true});++ function report() {+ changed({known, agent: state.agent, current: state.current ? state.jobs[state.current] || null : null, active: state.active,+ any: state.items.size > 0 || pending.length > 0});+ }+ async function send(text) {+ text = String(text).trim();+ if (!text || !canSend(state)) return false;+ const entry = {id: newId(), text}; pending.push(entry); render(true); report();+ let response = null;+ try { response = await agentPost(api, '/freevideo/agent/chat', entry); } catch { /* Handled below as not sent. */ }+ if (response?.ok) { const value = await response.json().catch(() => ({})); if (value.agent) state.agent = value.agent; poll(); return true; }+ // Not sent: the sentence goes back to the box. An agent that was never connected leads back to the card.+ pending = pending.filter(item => item !== entry);+ if (!input.value) { input.value = text; grow(); }+ if (response?.status === 409) state = {...state, agent: {connected: false, name: null}};+ render(); report();+ return false;+ }+ function grow() {+ input.style.height = 'auto';+ // At most five lines; the box scrolls after that.+ const line = parseFloat(getComputedStyle(input).lineHeight) || 22;+ input.style.height = `${Math.min(input.scrollHeight, Math.round(line * 5) + 14)}px`;+ sendButton.disabled = !canSend(state) || !input.value.trim();+ }+ input.addEventListener('input', grow);+ // Enter sends, Shift+Enter starts a new line; Enter that confirms an input-method candidate does neither.+ input.addEventListener('keydown', event => {+ if (event.key !== 'Enter' || event.shiftKey || event.isComposing || event.keyCode === 229) return;+ event.preventDefault(); form.requestSubmit();+ });+ form.addEventListener('submit', event => {+ event.preventDefault();+ const text = input.value;+ if (!text.trim() || !canSend(state)) return;+ input.value = ''; grow(); void send(text);+ });++ async function poll() {+ clearTimeout(timer); timer = null;+ if (stopped || busy) return;+ if (!active()) return;+ busy = true;+ let again = false;+ try {+ const after = state.session ? state.last : 0;+ const response = await agentGet(api, '/freevideo/agent/chat' + (after ? `?after=${after}` : ''));+ if (stopped) return;+ if (response.ok) {+ const data = await response.json();+ // Another conversation began: forget this one and read the new one whole.+ if (after && (data.session ?? null) !== state.session) { state = emptyChat(); again = true; }+ else {+ if ((data.session ?? null) !== state.session) state = emptyChat();+ state = chatMerge(state, data); failures = 0;+ }+ } else failures++;+ } catch { failures++; }+ finally { busy = false; }+ if (stopped) return;+ if (again) return poll();+ known = true; render(); report();+ const idle = state.agent.connected !== true && !state.active;+ timer = setTimeout(poll, (idle ? Math.max(interval, 3000) : interval) * Math.min(4, 1 + failures));+ }+ const visible = () => { if (!document.hidden) sync(); };+ document.addEventListener('visibilitychange', visible);+ function sync() { if (active() && !timer && !busy) poll(); }+ render();+ return {element, input, sync, refresh: poll,+ scrollToJob(id) { log.querySelector(`[data-job="${CSS.escape(id)}"]`)?.scrollIntoView({block: 'center', behavior: 'smooth'}); },+ async stopAll() {+ const ids = Object.values(state.jobs).filter(job => WORKING.includes(job.status)).map(job => job.id);+ ids.forEach(id => stopping.add(id)); render();+ await Promise.allSettled(ids.map(id => agentPost(api, '/freevideo/agent/activity/cancel', {id})));+ poll();+ },+ stop() { stopped = true; clearTimeout(timer); timer = null; document.removeEventListener('visibilitychange', visible); log.querySelectorAll('video').forEach(video => video.pause()); }};+}diff --git a/web/editor_entry.js b/web/editor_entry.jsindex eb23605..8208177 100644--- a/web/editor_entry.js+++ b/web/editor_entry.js@@ -15,7 +15,7 @@ function editorPanel(node) {return {node: String(node.id), prompt: value.output, extra_data: {extra_pnginfo: {workflow: value.workflow || {}}}};}};}-export function openEditorView(node, {studio} = {}) {+export function openEditorView(node, {studio, work = null} = {}) {studio?.querySelectorAll('video,audio').forEach(media => media.pause());const panel = editorPanel(node);const progressElement = studio?.querySelector('.fv-generation-progress');@@ -27,7 +27,7 @@ export function openEditorView(node, {studio} = {}) {return number ? {percent: Number(number[1])} : {percent: 0};};}- const handle = openEditor({api, app, panel, onView(view) {+ const handle = openEditor({api, app, panel, from: work ? {work} : null, onView(view) {if (view === 'nodes') showNodes(node, studio);else if (view === 'autopilot') openAutopilot(node, {studio});else if (studio?.open) viewChanged('studio', node);diff --git a/web/health.js b/web/health.jsindex d157df0..39870fe 100644--- a/web/health.js+++ b/web/health.js@@ -13,7 +13,7 @@ const t = (en, zh) => cn ? zh : en;// launcher.js removes this flag during setup; read it before that.const launchVisit = query.get('freevideo') === 'launch';// Every script this folder ships; a test keeps the list in step with web/*.js.-export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'browser_extension.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',+export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'browser_extension.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js','editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js','editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'length_plan.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js','progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js', 'studio_recent.js',diff --git a/web/library.js b/web/library.jsindex a57faad..adf7d66 100644--- a/web/library.js+++ b/web/library.js@@ -86,12 +86,13 @@ async function workflowBackfill(collection, t) {}// ``upscale`` queues the second pass of a first-pass preview (the studio's node).-export function openLibrary(t, {upscale = null, selectedWork = null, extend = null} = {}) {+export function openLibrary(t, {upscale = null, selectedWork = null, extend = null, back: backLabel = null} = {}) {if (opened?.open) { if (selectedWork) opened.close(); else { opened.focus(); return; } }const dialog = el('dialog', null, 'fv-studio fv-library'); opened = dialog;dialog.setAttribute('aria-label', t('Your creations', '我的作品'));const header = el('header', null, 'fv-library-header');- const back = button(t('Back to create', '返回创作'), () => closeDialog(dialog), 'fv-quiet');+ // Closing returns to the view this was opened from; that view names itself on the button.+ const back = button(backLabel || t('Back to create', '返回创作'), () => closeDialog(dialog), 'fv-quiet');const title = el('h2', t('Your creations', '我的作品'));const refresh = button(t('Refresh', '刷新'), () => load(false), 'fv-quiet');header.append(back, title, refresh);