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: the Agent's own view as the fourth tab
Bowen Xueb507b056021e
diff --git a/.gitignore b/.gitignoreindex c09426e..edad71a 100644--- a/.gitignore+++ b/.gitignore@@ -61,3 +61,4 @@ engine-gpu-*.lock# Optional local prompt models, runtime binaries and private rewrite caches./optional/*.gguf+/out/diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex aee2b25..d80bcd3 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -689,6 +689,9 @@ def register():video = (view.get('result') or {}).get('video') or {}if video.get('url'):value['video'] = video['url']+ if (view.get('result') or {}).get('library_id'):+ # The work this video became, for the page to show it in My works.+ value['work'] = view['result']['library_id']return valuereturn dict(active=sum(1 for r in rows if r['status'] in ACTIVE), jobs=[item(r) for r in shown])return reply(await asyncio.to_thread(read))diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjsindex 764e3b4..0b86732 100644--- a/scripts/test_freevideo_entry.mjs+++ b/scripts/test_freevideo_entry.mjs@@ -93,7 +93,8 @@ test('main browser entry registers both views and preserves node hooks', async t.replace("import { rememberPromptDraft, savePromptDraft } from './prompt_draft.js';", 'const {rememberPromptDraft,savePromptDraft} = globalThis.__freevideoEntryTest;').replace("import { regenerateResult, upscaleResult } from './studio_queue.js';", 'const {regenerateResult,upscaleResult} = globalThis.__freevideoEntryTest;').replace("import { openImageEditor, icon } from './image_editor.js';", 'const {openImageEditor,icon} = globalThis.__freevideoEntryTest;')- .replace("import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';", 'const {installNavigation,refreshNavigation,preferredView} = globalThis.__freevideoEntryTest;');+ .replace("import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';", 'const {installNavigation,refreshNavigation,preferredView} = globalThis.__freevideoEntryTest;')+ .replace("import { agentInterfaceEnabled } from './agent_connect.js';", 'const agentInterfaceEnabled = async () => false;');await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64'));const extension = extensions.find(row => row.name === 'FreeVideo.UnifiedMedia');assert.ok(extension, 'the main extension must register');diff --git a/web/agent_activity.css b/web/agent_activity.cssindex ee777e9..2222cef 100644--- a/web/agent_activity.css+++ b/web/agent_activity.css@@ -48,3 +48,9 @@@media(max-width:820px){.fv-studio .fv-header:has(>.fv-view-switch):has(.fv-agent-pill:not([hidden])){height:auto;min-height:98px;grid-template-columns:1fr auto;padding-block:10px}.fv-studio .fv-header:has(.fv-agent-pill:not([hidden]))>.fv-view-switch{grid-column:1/-1;grid-row:2;justify-self:center}.fv-studio .fv-header:has(.fv-agent-pill:not([hidden]))>.fv-header-actions{grid-column:2;grid-row:1}}@media(max-width:480px){.fv-agent-panel{top:104px;left:16px;right:16px;width:auto}}.fv-agent-panel:focus{outline:none}+/* The same rows as an always-open list inside a view. */+.fv-agent-list{display:grid;gap:10px;min-width:0}+.fv-agent-list[hidden],.fv-agent-list [hidden]{display:none}+.fv-agent-list h2{margin:0;font-size:var(--fv-strong);font-weight:var(--fv-semibold)}+.fv-agent-list ol{list-style:none;margin:0 -12px;padding:0;display:grid;gap:2px}+.fv-agent-empty{margin:0;font-size:var(--fv-body);line-height:1.5;color:var(--fv-muted)}diff --git a/web/agent_activity.js b/web/agent_activity.jsindex d495006..fbe8218 100644--- a/web/agent_activity.js+++ b/web/agent_activity.js@@ -1,4 +1,4 @@-import {agentPost} from './agent_session.js';+import {agentGet, agentPost} from './agent_session.js';// What agents connected to this FreeVideo are doing. Their requests share the// studio's queue, so people can see them, follow progress and stop them.const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./agent_activity.css', import.meta.url).href; document.head.append(css);@@ -6,10 +6,10 @@ const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = nconst KINDS = {generate: ['Generating', '生成中', 'M4 7h11a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2zm13 4 5-3v8l-5-3'],assemble: ['Assembling', '拼接中', 'M3 6h7v12H3zM14 6h7v12h-7zM10 12h4'],- vlm: ['Reviewing', '审看中', 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zm10 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'],+ vlm: ['Checking', '检查中', 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zm10 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'],enhance: ['Writing prompt', '润色提示词', 'M4 20l4-1 10-10-3-3L5 16zM14 7l3 3M18 3l1 2 2 1-2 1-1 2-1-2-2-1 2-1z'],};-const NAMES = {generate: ['Video', '视频'], assemble: ['Sequence', '成片'], vlm: ['Review', '审看'], enhance: ['Prompt', '提示词']};+const NAMES = {generate: ['Video', '视频'], assemble: ['Sequence', '成片'], vlm: ['Check', '检查'], enhance: ['Prompt', '提示词']};// Short reasons for the failures people can act on; the engine's own message stays in the tooltip.const REASONS = {@@ -27,19 +27,163 @@ function glyph(path) {const p = document.createElementNS('http://www.w3.org/2000/svg', 'path'); p.setAttribute('d', path); svg.append(p);return svg;}-const seconds = (s, t) => t(`${Math.max(1, Math.round(s))} s`, `${Math.max(1, Math.round(s))} 秒`);+// The same two wordings as the generation progress in the create view.+const left = (s, t) => s >= 60 ? t(`About ${Math.ceil(s / 60)}\u00a0min left`, `预计还需约 ${Math.ceil(s / 60)}\u00a0分钟`)+ : t('Less than a minute left', '预计还需不到 1\u00a0分钟');// The engine's phases in the reader's language.function phaseText(p, t) {const step = p.step;- if (p.phase === 'sampling' && step?.total) return t(`Sampling ${step.done} / ${step.total}`, `采样 ${step.done} / ${step.total}`);- return {encoding: t('Reading prompt and media', '编码提示词与素材'), load: t('Loading the model', '加载模型'),+ if (p.phase === 'sampling' && step?.total) return t(`Step ${step.done} / ${step.total}`, `生成 ${step.done} / ${step.total}`);+ return {encoding: t('Reading prompt and media', '读取提示词和素材'), load: t('Loading the model', '加载模型'),decode: t('Saving video and audio', '保存视频与音频'), starting: t('Starting', '启动中'),- loading: t('Loading the VLM', '加载视觉模型'), answering: t('Answering', '回答中'), rewriting: t('Writing', '改写中'),+ loading: t('Loading the model', '加载模型'), answering: t('Answering', '回答中'), rewriting: t('Writing', '改写中'),assembling: t('Joining clips', '拼接片段'), 'preparing images': t('Preparing images', '准备图片'),finishing: t('Finishing', '收尾中')}[p.phase] || '';}-export function createAgentActivity(t, api, host, {interval = [1500, 8000]} = {}) {+function status(job, t) {+ const [en, zh] = KINDS[job.kind] || KINDS.generate;+ if (job.status === 'running') return t(en, zh);+ if (job.status === 'queued') return job.progress?.queue_position+ ? t(`In queue · #${job.progress.queue_position}`, `排队 · 第 ${job.progress.queue_position} 位`) : t('Queued', '排队中');+ if (job.status === 'waiting') return job.waiting_for ? t('Waiting for earlier steps', '等待前序任务') : t('Waiting for the GPU', '等待显卡');+ return {succeeded: t('Done', '已完成'), failed: t('Failed', '失败'), cancelled: t('Cancelled', '已取消')}[job.status] || job.status;+}+function title(job, t) {+ const name = NAMES[job.kind] || NAMES.generate;+ return job.label || (t(name[0], name[1]) + (job.take ? ' · ' + t(`Take ${job.take}`, `第 ${job.take} 条`) : ''));+}+function row(job, t, api, refresh, open) {+ const item = el('li', 'fv-agent-job'); item.dataset.status = job.status; item.dataset.job = job.id;+ item.append(glyph((KINDS[job.kind] || KINDS.generate)[2]));+ const body = el('div', 'fv-agent-body');+ const head = el('div', 'fv-agent-head');+ head.append(el('strong', null, title(job, t)), el('span', 'fv-agent-state', status(job, t)));+ body.append(head);+ const p = job.progress || {};+ if (job.status === 'running' || job.status === 'queued') {+ const bar = el('div', 'fv-agent-bar'), fill = el('i');+ const fraction = Math.max(0, Math.min(1, Number(p.fraction) || 0));+ fill.style.transform = `scaleX(${job.status === 'queued' ? 0 : Math.max(.02, fraction)})`;+ bar.append(fill); bar.setAttribute('role', 'progressbar'); bar.setAttribute('aria-valuemin', '0');+ bar.setAttribute('aria-valuemax', '100'); bar.setAttribute('aria-valuenow', String(Math.round(fraction * 100)));+ body.append(bar);+ }+ const meta = [];+ if (job.status === 'running' && phaseText(p, t)) meta.push(phaseText(p, t));+ if (job.status === 'running' && p.remaining_seconds > 0) meta.push(left(p.remaining_seconds, t));+ const reason = job.status === 'failed' && REASONS[job.error?.code];+ if (reason) meta.push(t(...reason));+ else if (job.error?.message && job.status === 'failed') meta.push(job.error.message);+ if (job.project) meta.push(job.project);+ if (job.client) meta.push(job.client);+ const foot = el('div', 'fv-agent-foot');+ const details = el('p', 'fv-agent-meta', meta.join(' · '));+ if (reason && job.error?.message) details.title = job.error.message;+ foot.append(details);+ if (['waiting', 'queued', 'running'].includes(job.status)) {+ const stop = el('button', 'fv-agent-stop', t('Stop', '停止')); stop.type = 'button';+ stop.setAttribute('aria-label', t('Stop ', '停止 ') + title(job, t));+ stop.onclick = async () => {+ stop.disabled = true;+ try {+ await agentPost(api, '/freevideo/agent/activity/cancel', {id: job.id});+ } finally { refresh(); }+ };+ foot.append(stop);+ }+ if (job.work) {+ // The result is a work: show that one in Creations. (The file itself needs the Agent's token.)+ const show = el('button', 'fv-agent-open', t('Open', '打开')); show.type = 'button';+ show.setAttribute('aria-label', t('Open in Creations: ', '在作品中打开:') + title(job, t));+ show.onclick = () => open(job);+ foot.append(show);+ }+ body.append(foot);+ item.append(body);+ return item;+}+// Running first, then the rest in the order they will run; finished ones after, newest first.+function rows(jobs, t, api, refresh, open) {+ const rank = {running: 0, queued: 1, waiting: 2};+ const active = jobs.filter(j => j.status in rank)+ .sort((a, b) => rank[a.status] - rank[b.status] || String(a.created_at).localeCompare(String(b.created_at)));+ const done = jobs.filter(j => !(j.status in rank))+ .sort((a, b) => String(b.finished_at).localeCompare(String(a.finished_at)));+ const items = active.map(job => row(job, t, api, refresh, open));+ if (done.length) {+ const divider = el('li', 'fv-agent-divider', t('Last 30 minutes', '最近 30 分钟'));+ divider.setAttribute('role', 'presentation');+ items.push(divider, ...done.map(job => row(job, t, api, refresh, open)));+ }+ return items;+}+// A re-render keeps keyboard focus on the same control.+function refill(root, list, items) {+ const focused = root.contains(document.activeElement) ? document.activeElement : null;+ const key = focused && [focused.closest('[data-job]')?.dataset.job, focused.className];+ list.replaceChildren(...items);+ return key;+}++// "Open" on a finished video leads to that work in Creations.+async function showWork(t, job) {+ (await import('./library.js')).openLibrary(t, {selectedWork: job.work});+}++// The same jobs as a list that is always open, for a view of its own: what the agents are doing, how far+// along, where the result is, and a stop on each; open(job) can replace where a finished video opens. It shows+// once an agent is connected or has jobs, and asks nothing while it is out of sight.+export function agentActivityList(t, api, {interval = [1500, 8000], open = job => showWork(t, job)} = {}) {+ const element = el('section', 'fv-agent-list'); element.hidden = true;+ const heading = el('h2', null, t('Jobs', '任务')), list = el('ol');+ const empty = el('p', 'fv-agent-empty', t('Videos the agent makes will appear here.', 'Agent 生成的视频会显示在这里。'));+ element.append(heading, list, empty);+ let timer = null, stopped = false, on = null, failures = 0, active = 0;+ // Hidden itself, the list is in sight when the view that holds it is.+ const inSight = () => element.isConnected && (element.hidden ? element.parentElement : element)?.getClientRects().length > 0;+ async function connected() {+ try {+ const response = await agentGet(api, '/freevideo/agent/v1/connect/status');+ return response.ok && (await response.json()).connected === true;+ } catch { return false; }+ }+ async function poll() {+ clearTimeout(timer); timer = null;+ if (stopped) return;+ const shown = inSight();+ if (shown && on === null) {+ // Agent features can be off in this FreeVideo: ask once.+ try {+ const response = await api.fetchApi('/freevideo/agent', {cache: 'no-store'});+ on = response.ok && (await response.json()).enabled === true;+ } catch { on = false; }+ }+ if (stopped || on === false) return;+ if (shown && on) {+ try {+ const response = await api.fetchApi('/freevideo/agent/activity', {cache: 'no-store'});+ if (response.ok) {+ const data = await response.json(), jobs = data.jobs || [];+ const show = jobs.length > 0 || await connected();+ if (stopped) return;+ failures = 0; active = data.active || 0;+ const key = refill(element, list, rows(jobs, t, api, poll, open));+ list.hidden = !jobs.length; empty.hidden = !!jobs.length; element.hidden = !show;+ if (key) list.querySelector(`[data-job="${key[0]}"] .${key[1].split(' ')[0]}`)?.focus?.();+ } else failures++;+ } catch { failures++; }+ }+ if (stopped) return;+ // Fast while agents work; every 3 s while empty, like the connection card, so connecting shows at once.+ const wait = !shown ? 500 : active ? interval[0] : list.hidden ? Math.min(3000, interval[1]) : interval[1] * Math.min(4, 1 + failures);+ timer = setTimeout(poll, wait);+ }+ poll();+ return {element, refresh: poll, stop() { stopped = true; clearTimeout(timer); }};+}++export function createAgentActivity(t, api, host, {interval = [1500, 8000], open = job => showWork(t, job)} = {}) {const element = el('button', 'fv-agent-pill'); element.type = 'button'; element.hidden = true;element.setAttribute('aria-haspopup', 'dialog'); element.setAttribute('aria-expanded', 'false');const dot = el('span', 'fv-agent-dot'), label = el('span', 'fv-agent-label');@@ -49,90 +193,14 @@ export function createAgentActivity(t, api, host, {interval = [1500, 8000]} = {}host.append(panel);let data = {active: 0, jobs: []}, timer = null, disposed = false, failures = 0;- function status(job) {- const [en, zh] = KINDS[job.kind] || KINDS.generate;- if (job.status === 'running') return t(en, zh);- if (job.status === 'queued') return job.progress?.queue_position- ? t(`In queue · #${job.progress.queue_position}`, `排队 · 第 ${job.progress.queue_position} 位`) : t('Queued', '排队中');- if (job.status === 'waiting') return job.waiting_for ? t('Waiting for earlier steps', '等待前序任务') : t('Waiting for the GPU', '等待显卡');- return {succeeded: t('Done', '已完成'), failed: t('Failed', '失败'), cancelled: t('Cancelled', '已取消')}[job.status] || job.status;- }- function title(job) {- const name = NAMES[job.kind] || NAMES.generate;- return job.label || (t(name[0], name[1]) + (job.take ? ' · ' + t(`Take ${job.take}`, `第 ${job.take} 条`) : ''));- }- function row(job) {- const item = el('li', 'fv-agent-job'); item.dataset.status = job.status; item.dataset.job = job.id;- item.append(glyph((KINDS[job.kind] || KINDS.generate)[2]));- const body = el('div', 'fv-agent-body');- const head = el('div', 'fv-agent-head');- head.append(el('strong', null, title(job)), el('span', 'fv-agent-state', status(job)));- body.append(head);- const p = job.progress || {};- if (job.status === 'running' || job.status === 'queued') {- const bar = el('div', 'fv-agent-bar'), fill = el('i');- const fraction = Math.max(0, Math.min(1, Number(p.fraction) || 0));- fill.style.transform = `scaleX(${job.status === 'queued' ? 0 : Math.max(.02, fraction)})`;- bar.append(fill); bar.setAttribute('role', 'progressbar'); bar.setAttribute('aria-valuemin', '0');- bar.setAttribute('aria-valuemax', '100'); bar.setAttribute('aria-valuenow', String(Math.round(fraction * 100)));- body.append(bar);- }- const meta = [];- if (job.status === 'running' && phaseText(p, t)) meta.push(phaseText(p, t));- if (job.status === 'running' && p.remaining_seconds > 0) meta.push(t(`about ${seconds(p.remaining_seconds, t)} left`, `约剩 ${seconds(p.remaining_seconds, t)}`));- const reason = job.status === 'failed' && REASONS[job.error?.code];- if (reason) meta.push(t(...reason));- else if (job.error?.message && job.status === 'failed') meta.push(job.error.message);- if (job.project) meta.push(job.project);- if (job.client) meta.push(job.client);- const foot = el('div', 'fv-agent-foot');- const details = el('p', 'fv-agent-meta', meta.join(' · '));- if (reason && job.error?.message) details.title = job.error.message;- foot.append(details);- if (['waiting', 'queued', 'running'].includes(job.status)) {- const stop = el('button', 'fv-agent-stop', t('Stop', '停止')); stop.type = 'button';- stop.setAttribute('aria-label', t('Stop ', '停止 ') + title(job));- stop.onclick = async () => {- stop.disabled = true;- try {- await agentPost(api, '/freevideo/agent/activity/cancel', {id: job.id});- } finally { poll(); }- };- foot.append(stop);- }- if (job.video) {- const open = el('a', 'fv-agent-open', t('Open', '打开'));- open.href = api.apiURL ? api.apiURL(job.video) : job.video; open.target = '_blank'; open.rel = 'noopener';- open.setAttribute('aria-label', t('Open video of ', '打开视频:') + title(job));- foot.append(open);- }- body.append(foot);- item.append(body);- return item;- }function renderPanel() {- // Keep keyboard focus on the same control across a refresh.- const focused = panel.contains(document.activeElement) ? document.activeElement : null;- const key = focused && [focused.closest('[data-job]')?.dataset.job, focused.className];- panel.replaceChildren();const header = el('header');header.append(el('h2', null, t('Agent jobs', 'Agent 任务')),el('p', null, t('Requests from AI agents connected to FreeVideo. They share the queue with your videos.','已连接的 AI Agent 提交的任务,与您的生成共用同一个队列。')));- // Running first, then the rest in the order they will run; finished ones after, newest first.- const rank = {running: 0, queued: 1, waiting: 2};- const active = data.jobs.filter(j => j.status in rank)- .sort((a, b) => rank[a.status] - rank[b.status] || String(a.created_at).localeCompare(String(b.created_at)));- const done = data.jobs.filter(j => !(j.status in rank))- .sort((a, b) => String(b.finished_at).localeCompare(String(a.finished_at)));const list = el('ol');- for (const job of active) list.append(row(job));- if (done.length) {- const divider = el('li', 'fv-agent-divider', t('Last 30 minutes', '最近 30 分钟'));- divider.setAttribute('role', 'presentation');- list.append(divider);- for (const job of done) list.append(row(job));- }+ const key = refill(panel, list, rows(data.jobs, t, api, poll, job => { setOpen(false); open(job); }));+ panel.replaceChildren();panel.append(header, list);if (key) (panel.querySelector(`[data-job="${key[0]}"] .${key[1].split(' ')[0]}`) || panel).focus?.();}diff --git a/web/agent_connect.css b/web/agent_connect.cssindex e8c9632..45a3f45 100644--- a/web/agent_connect.css+++ b/web/agent_connect.css@@ -9,4 +9,11 @@.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)}-.fv-setup .fv-agent-connect[hidden]{display:none}+/* 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}}diff --git a/web/agent_connect.js b/web/agent_connect.jsindex 3df2af5..aa116f1 100644--- a/web/agent_connect.js+++ b/web/agent_connect.js@@ -113,34 +113,3 @@ export function agentConnectCard(t, api, shown = () => true) {const enabled = agentInterfaceEnabled(api);return {element: body, title: t('Connect an agent', '连接 Agent'), enabled, sync, stop};}--// Settings: the card as one collapsible section of the dialog.-export function agentConnect(t, api) {- let observer, dialog;- const section = el('details', 'fv-agent-connect');- section.hidden = true;- const card = agentConnectCard(t, api, () => !section.hidden && section.open && section.dataset.expanded !== 'false'- && (!dialog || dialog.open && dialog.dataset.closing !== 'true'));- section.append(el('summary', null, card.title), card.element);- function close() {- card.stop(); observer?.disconnect(); observer = null;- dialog?.removeEventListener('close', close); dialog = null;- }- section.addEventListener('toggle', () => {- if (!observer) {- dialog = section.closest('dialog');- observer = new MutationObserver(card.sync);- observer.observe(section, {attributes: true, attributeFilter: ['open', 'hidden', 'data-expanded']});- if (dialog) {- observer.observe(dialog, {attributes: true, attributeFilter: ['open', 'data-closing']});- dialog.addEventListener('close', close);- }- }- card.sync();- });- card.enabled.then(on => {- if (on) section.hidden = false;- else { close(); section.remove(); }- });- return section;-}diff --git a/web/autopilot.js b/web/autopilot.jsnew file mode 100644index 0000000..4bc1141--- /dev/null+++ b/web/autopilot.js@@ -0,0 +1,56 @@+// 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.+import { api } from '../../scripts/api.js';+import { agentActivityList } from './agent_activity.js';+import { agentConnectCard } from './agent_connect.js';+import { openEditorView } from './editor_loader.js';+import { closeDialog } from './motion.js';+import { openSetup } from './setup.js';+import { extendVideo, openStudio, showNodes } from './studio.js';+import { viewChanged, viewSwitch } from './view_navigation.js';+import { wordmark } from './wordmark.js';++const languageOverride = typeof location !== 'undefined'+ ? new URLSearchParams(location.search).get('freevideo_lang') : null;+const cn = languageOverride === 'zh' || (languageOverride !== 'en'+ && String(navigator.language || '').toLowerCase().startsWith('zh'));+const t = (en, zh) => cn ? zh : en;+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };++let current = null;+// Opens above the studio when one is open, as the editing view does, so going back finds it as it was.+export function openAutopilotView(node, {studio = null} = {}) {+ if (current?.open) { viewChanged('autopilot', node); return current; }+ studio?.querySelectorAll('video,audio').forEach(media => media.pause());+ const dialog = el('dialog', 'fv-studio fv-autopilot'); dialog.setAttribute('aria-label', t('Autopilot', 'AI 全自动'));+ 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 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; });+ dialog.append(header, body);+ dialog.addEventListener('cancel', event => { event.preventDefault(); closeDialog(dialog); });+ dialog.onclose = () => {+ card.stop(); jobs.stop(); dialog.remove();+ if (current === dialog) current = null;+ next();+ };+ current = dialog; document.body.append(dialog); dialog.showModal(); viewChanged('autopilot', node); card.sync();+ navigation.querySelector('[data-view=autopilot]').focus();+ return dialog;+}diff --git a/web/editor.js b/web/editor.jsindex 026a02f..c5d2f9f 100644--- a/web/editor.js+++ b/web/editor.js@@ -103,7 +103,7 @@ export function openEditor({api, app, from = null, panel = {}, components: giventransport = el('div', 'fv-ed-transport'), genHost = el('div', 'fv-ed-genbar'), tracksHost = el('div', 'fv-ed-tracks'), zoomHost = el('div', 'fv-ed-zoom');const adjustHost = el('aside', 'fv-ed-adjust-host');const button = (label, action, cls = '') => { const value = el('button', cls, label); value.type = 'button'; value.onclick = action; return value; };- const navigation = viewSwitch('editor', () => handle.switchView('studio'), () => handle.switchView('nodes'), () => {});+ const navigation = viewSwitch('editor', () => handle.switchView('studio'), () => handle.switchView('nodes'), () => {}, () => handle.switchView('autopilot'));for (const control of navigation.querySelectorAll('button')) control.removeAttribute('title');const brand = el('div', 'fv-brand');const headerActions = el('div', 'fv-header-actions');diff --git a/web/editor_entry.js b/web/editor_entry.jsindex d6ae04f..eb23605 100644--- a/web/editor_entry.js+++ b/web/editor_entry.js@@ -3,7 +3,7 @@ import {openEditor} from './editor.js';import {api} from '../../scripts/api.js';import {app} from '../../scripts/app.js';import {openStudio, showNodes} from './studio.js';-import {viewChanged} from './view_navigation.js';+import {openAutopilot, viewChanged} from './view_navigation.js';function editorPanel(node) {const values = Object.fromEntries((node.widgets || []).filter(widget => widget.name).map(widget => [widget.name, widget.value]));return {node: node.id, width: values.width, height: values.height, text: values.text || '', settings: Object.fromEntries(Object.entries({@@ -29,6 +29,7 @@ export function openEditorView(node, {studio} = {}) {}const handle = openEditor({api, app, panel, onView(view) {if (view === 'nodes') showNodes(node, studio);+ else if (view === 'autopilot') openAutopilot(node, {studio});else if (studio?.open) viewChanged('studio', node);else openStudio(node);}});diff --git a/web/first_run_guide.js b/web/first_run_guide.jsindex e195707..4efc7c7 100644--- a/web/first_run_guide.js+++ b/web/first_run_guide.js@@ -20,7 +20,7 @@ export const CHAPTERS = [{id: 'longer', anchor: '[data-fv-guide="longer"]', added: true,en: 'For a longer video, or to change part of one, choose "Edit".', zh: '要做更长的视频,或者修\u2060改\u2060其\u2060中\u2060一\u2060段,点“剪辑视图”。'},{id: 'agent', anchor: '[data-fv-guide="agent"]', added: true,- en: 'Connect Claude Code, Codex or another agent in Settings and let it make videos.', zh: '在设置里连接 Claude Code、Codex 等 Agent,让它生成视频。'},+ en: 'To have an AI agent such as Claude Code or Codex make videos for you, choose "Autopilot".', zh: '要让 Claude Code、Codex 等 Agent 替你生\u2060成\u2060视\u2060频,点“AI 全自动”。'},];export function guideSteps({record, available = [], returning = false, blockers = {}, all = false}) {diff --git a/web/freevideo.js b/web/freevideo.jsindex 7e39aa7..8a96260 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -8,6 +8,7 @@ import { createProgressConnection } from './progress_connection.js';import { notifyCompatibility } from './compatibility.js';import { startUpdateChecks } from './updates.js';import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';+import { agentInterfaceEnabled } from './agent_connect.js';import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs } from './prompt_references.js';import { outputDownloadURL } from './output_download.js';import { shareButton } from './share.js';@@ -564,7 +565,7 @@ app.registerExtension({beforeConfigureGraph() { configuringGraph = true; },async setup() {// One failing part must not take the others down; health.js shows what failed.- for (const [where, start] of [['progress', () => progressConnection.start()], ['navigation', () => installNavigation(showStudio)],+ for (const [where, start] of [['progress', () => progressConnection.start()], ['navigation', () => installNavigation(showStudio, agentInterfaceEnabled(api))],['updates', startUpdateChecks]]) {try { start(); } catch (error) { health({type: 'error', where, error}); }}diff --git a/web/health.js b/web/health.jsindex 3a808b4..d157df0 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', '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', '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/setup.js b/web/setup.jsindex bc3461e..dd48e8a 100644--- a/web/setup.js+++ b/web/setup.js@@ -2,7 +2,6 @@ import { api } from "../../scripts/api.js";import { wordmark } from './wordmark.js';import { openCompatibility } from './compatibility.js';import { animateDetails, closeDialog } from './motion.js';-import { agentConnect } from './agent_connect.js';import { createGuideReplayEntry } from './first_run_guide.js';const css = document.createElement('link');@@ -153,7 +152,7 @@ export async function openSetup() {const {openCreativeWorkspace} = await import('./view_navigation.js');return openCreativeWorkspace();}});- dialog.append(heading, installation, downloads, agentConnect(t, api), advanced, guideReplay);+ dialog.append(heading, installation, downloads, advanced, guideReplay);const motions = [...dialog.querySelectorAll('details')].map(animateDetails);dialog.addEventListener('cancel', e => { e.preventDefault(); closeDialog(dialog); });document.body.append(dialog); dialog.showModal();diff --git a/web/studio.js b/web/studio.jsindex c9dc348..a273126 100644--- a/web/studio.js+++ b/web/studio.js@@ -4,7 +4,8 @@ import { api } from '../../scripts/api.js';import { openSetup } from './setup.js';import { wordmark } from './wordmark.js';import { createGenerationProgress, referenceTrimText, thermalText, encoderFileText, encoderFilePath } from './generation_progress.js';-import { viewSwitch, viewChanged } from './view_navigation.js';+import { viewSwitch, viewChanged, agentTabReady, openAutopilot } from './view_navigation.js';+import { agentInterfaceEnabled } from './agent_connect.js';import { createUpdateNotice, createVersionInfo, productVersion } from './updates.js';import { createPortNotice } from './port_notice.js';import { reportIssue, reportTipClosed, showReportTip } from './report_issue.js';@@ -204,14 +205,13 @@ export function openStudio(node, {extendFrom = null} = {}) {const tools = el('div', null, 'fv-header-actions');const agents = createAgentActivity(t, api, dialog); tools.append(agents.element); cleanup.push(agents.dispose);const versionInfo = createVersionInfo(cn); tools.append(versionInfo.element); cleanup.push(versionInfo.dispose);- const settingsButton = button(t('Settings', '设置'), openSetup, 'fv-quiet');- // The Agent connection card lives in Settings, so the guide's last step circles this button when the card is there.- // The guide starts after this settles: it fixes its steps from the anchors present at that moment.- const agentDiscovery = api.fetchApi('/freevideo/agent', {cache: 'no-store'}).then(reply => reply.ok ? reply.json() : null)- .then(found => { if (found?.enabled === true) settingsButton.dataset.fvGuide = 'agent'; }).catch(() => {});- tools.append(settingsButton);+ tools.append(button(t('Settings', '设置'), openSetup, 'fv-quiet'));+ // The Agent's page is the fourth tab, shown where the Agent interface is on; the guide's last step circles it.+ agentTabReady(agentInterfaceEnabled(api));const navigation = viewSwitch('studio', () => {}, () => showNodes(node, dialog),- () => openEditorView(node, {studio: dialog}));+ () => openEditorView(node, {studio: dialog}), () => openAutopilot(node, {studio: dialog}));+ // The guide starts after the tab settles: it fixes its steps from the anchors present at that moment.+ const agentDiscovery = navigation.ready;header.append(brand, navigation, tools);const body = el('div', null, 'fv-body'), controls = el('div', null, 'fv-controls'), output = el('div', null, 'fv-preview-column');dialog.append(header, body); body.append(controls, output);diff --git a/web/view_navigation.css b/web/view_navigation.cssindex 4317746..30fd60f 100644--- a/web/view_navigation.css+++ b/web/view_navigation.css@@ -4,6 +4,7 @@.fv-view-switch button,.fv-view-navigation button{font:inherit;cursor:pointer;border:1px solid transparent;color:var(--fv-muted);background:transparent;border-radius:var(--fv-r-sm);padding:6px 14px;font-weight:var(--fv-medium);white-space:nowrap;transition:background .2s,color .2s,border-color .2s}.fv-view-switch button[aria-pressed=true],.fv-studio .fv-view-switch button[aria-pressed=true]{background:var(--fv-raised);color:var(--fv-ink);font-weight:var(--fv-semibold);box-shadow:0 1px 3px #0006}.fv-view-switch button:hover{color:var(--fv-ink)}.fv-view-switch button:focus-visible,.fv-view-navigation button:focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px}+.fv-view-switch button[hidden],.fv-studio .fv-view-switch button[hidden]{display:none}/* First-run tip: a tinted callout, not another line of grey text. */.fv-view-guide{display:flex;align-items:center;gap:10px;max-width:560px;margin-top:10px;padding:8px 8px 8px 12px;border-radius:var(--fv-r-sm);background:var(--fv-selected);font-size:12px;line-height:1.5;color:var(--fv-ink)}.fv-view-guide::before{content:'i';flex:none;display:grid;place-items:center;width:18px;height:18px;border-radius:50%;background:var(--fv-accent);color:var(--fv-bg);font:600 11px/1 Georgia,serif}diff --git a/web/view_navigation.js b/web/view_navigation.jsindex 8a2ec16..f9f375d 100644--- a/web/view_navigation.js+++ b/web/view_navigation.js@@ -11,7 +11,7 @@ const cn = languageOverride === 'zh' || (languageOverride !== 'en'&& String(navigator.language || '').toLowerCase().startsWith('zh'));const t = (en, zh) => cn ? zh : en;const preference = 'freevideo.view';-let toolbar, open, selected, currentView = 'nodes';+let toolbar, open, selected, currentView = 'nodes', agentTab = null;const style = document.createElement('link');style.rel = 'stylesheet'; style.href = new URL('./view_navigation.css', import.meta.url).href;document.head.append(style);@@ -27,15 +27,34 @@ export function viewChanged(view, node) {refreshNavigation();}-export function viewSwitch(view, onStudio, onNodes, onEditor) {+// Whether this FreeVideo has the Agent interface on. The surfaces that open first (the toolbar, the studio) ask+// and tell it here; a view switch shows its fourth tab only once the answer is yes.+export function agentTabReady(answer) {+ agentTab = Promise.resolve(answer).then(on => on === true, () => false);+ return agentTab;+}++// The Autopilot page loads on demand, as the editing view does; a failure leaves the current view as it is.+export async function openAutopilot(node, options) {+ try { return (await import('./autopilot.js')).openAutopilotView(node, options); }+ catch (error) { console.warn('FreeVideo autopilot view:', error); return null; }+}++export function viewSwitch(view, onStudio, onNodes, onEditor, onAutopilot) {const group = document.createElement('div'); group.className = 'fv-view-switch';group.setAttribute('role', 'group'); group.setAttribute('aria-label', t('FreeVideo view', 'FreeVideo 视图'));- for (const [id, label, action] of [['studio', t('Create', '创作面板'), onStudio], ['nodes', t('Nodes', '节点视图'), onNodes], ['editor', t('Edit', '剪辑视图'), onEditor]]) {+ for (const [id, label, action] of [['studio', t('Create', '创作面板'), onStudio], ['nodes', t('Nodes', '节点视图'), onNodes], ['editor', t('Edit', '剪辑视图'), onEditor],+ ['autopilot', t('Autopilot', 'AI 全自动'), onAutopilot]]) {const button = document.createElement('button'); button.type = 'button';const text = document.createElement('span'); text.textContent = label; button.append(text);button.dataset.label = label; button.dataset.view = id;if (id === 'editor') button.dataset.fvGuide = 'longer';button.setAttribute('aria-pressed', String(view === id)); button.onclick = action;+ if (id === 'autopilot') {+ button.hidden = view !== id;+ // Settled once the tab is shown or known to stay away; the first-run guide waits for it.+ group.ready = (agentTab || Promise.resolve(false)).then(on => { if (on) { button.hidden = false; button.dataset.fvGuide = 'agent'; } });+ }group.append(button);}return group;@@ -60,8 +79,9 @@ export function openCreativeWorkspace() {return true;}-export function installNavigation(openStudio) {+export function installNavigation(openStudio, agent = false) {open = openStudio;+ if (!toolbar) agentTabReady(agent);if (toolbar) { refreshNavigation(); return; }toolbar = document.createElement('aside'); toolbar.className = 'fv-view-navigation';toolbar.setAttribute('aria-label', t('FreeVideo workspace', 'FreeVideo 工作区'));@@ -76,7 +96,7 @@ export function installNavigation(openStudio) {const settings = document.createElement('button'); settings.type = 'button';settings.textContent = t('Settings', '设置'); settings.className = 'fv-view-settings'; settings.onclick = openSetup;row.append(grip, brand, viewSwitch('nodes', openCreativeWorkspace, () => {}, () => choose(node =>- openEditorView(node))), createVersionInfo(cn).element, settings); toolbar.append(row);+ openEditorView(node)), () => choose(node => openAutopilot(node))), createVersionInfo(cn).element, settings); toolbar.append(row);let shown = false;try { shown = localStorage.getItem('freevideo.view-guide') === '1'; } catch { /* Show once this session. */ }if (!shown) {