Skip to content

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

Agent connection: simpler Settings card, connection guide and evaluation updates

Bowen Xue0a202d7357ef
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
index 05ca04f..68d5ac9 100644
--- a/freevideo_engine/agent/errors.py
+++ b/freevideo_engine/agent/errors.py
@@ -105,6 +105,9 @@ ERRORS.update({
'image_changed': (409, False, 'The image changed since you read it.', 'Apply your operations to error.image and send its revision.'),
'layer_locked': (409, False, 'An operation changes a layer the user locked.', 'Leave the locked layer unchanged; ask the user to unlock it if it must change.'),
'export_failed': (409, True, 'The export did not finish.', 'Read the project, then submit the export again with a new ref.'),
+ 'clip_source_unusable': (409, False, 'A clip\'s source is missing, or cannot be read as far as the clip uses it.',
+ 'Read the project and check each clip\'s source: it must exist and play, and in + frames must stay '
+ 'within its real length. Correct the project, then export the new revision.'),
})
diff --git a/freevideo_engine/agent/forecast.py b/freevideo_engine/agent/forecast.py
index 0e65098..44ba77a 100644
--- a/freevideo_engine/agent/forecast.py
+++ b/freevideo_engine/agent/forecast.py
@@ -9,7 +9,7 @@ def generation_estimate(port, spec, chain=None):
reasons here so a film never invents a time for unsupported conditioning.
"""
from ..chain_plan import plan as chain_plan
- chain = chain if chain is not None else chain_plan(spec['seconds'])
+ chain = chain if chain is not None else chain_plan(spec['seconds'], continued=bool(spec.get('continue_from')))
table = port.capability_snapshot(dict(width=str(spec['width']), height=str(spec['height']),
task=spec['task'], adapters='1' if spec['loras'] else '0'))
seconds = None
diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py
index 5d1d3a9..b5aad65 100644
--- a/freevideo_engine/agent/jobs.py
+++ b/freevideo_engine/agent/jobs.py
@@ -1030,13 +1030,9 @@ class Jobs:
payload.pop('seconds')
payload['blocks'] = deepcopy(row['editor']['blocks'])
elif spec.get('continue_from'):
- from ..chain_plan import plan
- source = self.port.output_relative(self.source_video(spec['continue_from']))
- payload.pop('seconds')
- payload['join'] = True
- payload['blocks'] = [dict(id='b%d' % (i + 1), frames=block['frames'], text=prompt,
- seed=spec['seed'] + i, after='b%d' % i if i else dict(work=source))
- for i, block in enumerate(plan(spec['seconds'])['blocks'])]
+ # Planned as a continuation, so the new video is as long as the request says.
+ payload.update(after=dict(work=self.port.output_relative(self.source_video(spec['continue_from']))),
+ text=prompt, seed=spec['seed'])
self.start_chain(row, payload=payload)
work = asyncio.create_task(asyncio.to_thread(prepare))
try:
diff --git a/freevideo_engine/agent/projects.py b/freevideo_engine/agent/projects.py
index be4b590..4554335 100644
--- a/freevideo_engine/agent/projects.py
+++ b/freevideo_engine/agent/projects.py
@@ -92,6 +92,24 @@ def changed_clip_ids(before, after):
return changed + [identity for identity in old if identity not in new]
+def _claims(project):
+ """(path, source key, length) wherever a project says how long a source is: every clip and every version of it."""
+ tracks = project.get('tracks') if isinstance(project, dict) else None
+ for t, track in enumerate(tracks if isinstance(tracks, list) else ()):
+ clips = track.get('clips') if isinstance(track, dict) else None
+ for c, clip in enumerate(clips if isinstance(clips, list) else ()):
+ if not isinstance(clip, dict):
+ continue
+ path, versions = '/project/tracks/%d/clips/%d' % (t, c), clip.get('versions')
+ rows = [(path, clip.get('source'), clip.get('length'))]
+ rows += [('%s/versions/%d' % (path, v), row, row.get('length'))
+ for v, row in enumerate(versions if isinstance(versions, list) else ()) if isinstance(row, dict)]
+ for where, source, length in rows:
+ if (isinstance(source, dict) and isinstance(source.get('kind'), str) and isinstance(source.get('id'), str)
+ and type(length) is int):
+ yield where + '/length', source['kind'] + ':' + source['id'], length
+
+
class Projects:
def __init__(self, root, *, directory=None):
self.root = root # The ComfyUI output folder, where the page keeps FreeVideo/.editor
@@ -153,6 +171,24 @@ class Projects:
return self._load(identity)
# Whole-project writes ------------------------------------------------------------------------------
+ def _lengths(self, project, stored=None):
+ """A written project cannot say a source is longer than it is.
+
+ The page takes every length from the file; a whole-project write states it. A clip that asks for
+ frames its source does not have would only be found by the export, which stops there.
+ """
+ known = {row[1:] for row in _claims(stored)} if stored else set()
+ for path, key, length in _claims(project):
+ if (key, length) in known:
+ continue
+ try:
+ info = comfy_editor.sources(self.root, [key])[key]
+ except ValueError:
+ continue # not a source at all: the editor's own check refuses it and names the part
+ known.add((key, length))
+ if not info['missing'] and info['frames'] and length > info['frames']:
+ raise _invalid(path, 'at most %d, the number of frames this source has' % info['frames'], length)
+
def create(self, value, *, ref=None, client=None):
schema.validate(schema.project_schema('create'), value)
digest, replay = self._receipt('projects:create', value, ref, client)
@@ -163,6 +199,7 @@ class Projects:
raise _invalid('/project', 'a new project with id null and revision 0')
# The page's receipt makes a repeated create return the first project.
create = _operation_key(ref, client) if ref is not None else None
+ self._lengths(project)
result = dict(project=self._save(deepcopy(project), create=create))
self._remember(ref, digest, result, client)
return result
@@ -176,6 +213,7 @@ class Projects:
if not isinstance(project, dict) or project.get('id') != identity:
raise _invalid('/project/id', 'the project id in the path', project.get('id') if isinstance(project, dict) else None)
before = self._load(identity)['project']
+ self._lengths(project, before)
saved = self._save(deepcopy(project), ref=ref, client=client)
result = dict(project=saved, changed_clip_ids=changed_clip_ids(before, saved))
self._remember(ref, digest, result, client)
@@ -368,7 +406,8 @@ class Projects:
# Export ----------------------------------------------------------------------------------------------
-EXPORT_REASONS = {'source_missing': 'source_missing', 'unreadable': 'source_missing', 'disk_full': 'storage_unavailable'}
+# Both are about a clip in the project, so the answer says to look there, not to resume a generation.
+EXPORT_REASONS = {'source_missing': 'clip_source_unusable', 'unreadable': 'clip_source_unusable', 'disk_full': 'storage_unavailable'}
def run_export(port, row, *, poll=.25):
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index 8dec0f3..6949f3e 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -30,6 +30,16 @@ from .jobs import ACTIVE, DONE, JobError, Jobs, chain_error, library_view
PREFIX = '/freevideo/agent/v1'
+def local_address(request):
+ """The backend's bound port, independent of page origins and forwarding headers."""
+ socket = request.transport.get_extra_info('sockname') if request.transport else None
+ if not socket:
+ raise JobError('not_ready', 'Listening address unavailable')
+ host = '[::1]' if ':' in socket[0] else '127.0.0.1'
+ scheme = 'https' if request.transport.get_extra_info('sslcontext') is not None else 'http'
+ return f'{scheme}://{host}:{socket[1]}'
+
+
def token_path(root):
return Path(root) / 'agent' / 'token'
@@ -190,7 +200,7 @@ def plan(port, value, jobs=None):
if spec['width'] * spec['height'] > 2 * 1024 ** 2:
result['warnings'].append('Above 2 MP takes much longer and needs more memory')
from ..chain_plan import plan as chain_plan
- result['chain_plan'] = chain_plan(spec['seconds'])
+ result['chain_plan'] = chain_plan(spec['seconds'], continued=bool(spec.get('continue_from')))
from .forecast import generation_estimate
result['estimate'], result['capabilities_revision'] = generation_estimate(port, spec, result['chain_plan'])
return result
@@ -556,8 +566,10 @@ def register():
@guarded
async def discover(request):
# Unauthenticated: tells a client where to look, reveals nothing else.
+ connect = request.scheme + '://' + request.host + PREFIX + '/connect'
return reply(dict(enabled=True, api_versions=[API_VERSION], base=PREFIX, auth='bearer',
- token='agent/token in the FreeVideo installation folder'))
+ token='agent/token in the FreeVideo installation folder', connect=connect,
+ instructions='GET ' + connect + ' for plain-text connection instructions and follow them.'))
@routes.get('/freevideo/agent/session')
@guarded
@@ -635,7 +647,7 @@ def register():
for row in jobs.rows():
if row.get('client'):
seen[row['client']] = max(seen.get(row['client'], 0), row['created_at'])
- return reply(dict(api=PREFIX, token_file=str(token_path(root)), claude_code=config['claude_code'],
+ return reply(dict(address=local_address(request), api=PREFIX, token_file=str(token_path(root)), claude_code=config['claude_code'],
mcp_json=config['mcp_json'], cli=('"%s"' % script if ' ' in str(script) else str(script))
+ ' agent status' if script else None,
token_from_environment=False,
diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.py
index ae49600..352982f 100644
--- a/freevideo_engine/agent/spec.py
+++ b/freevideo_engine/agent/spec.py
@@ -149,15 +149,15 @@ def task(media):
return 'i2va' if 'first' in media else 'l2va' if 'last' in media else 't2va'
-def saved_length(canvas, seconds):
+def saved_length(canvas, seconds, continued=False):
"""Frames and seconds of the saved video. One generation keeps its aligned canvas; a longer video is
- made in blocks and joined to exactly the planned whole seconds."""
+ made in blocks and joined to exactly the planned whole seconds. A continuation saves only what it adds."""
from ..chain_plan import PlanError, plan
try:
- planned = plan(seconds)
+ planned = plan(seconds, continued=continued)
except PlanError:
return canvas['frames'], canvas['seconds']
- if planned['single']:
+ if planned['single'] and not continued:
return canvas['frames'], canvas['seconds']
return planned['frames'], planned['frames'] / canvas['fps']
@@ -180,8 +180,7 @@ def normalize(value):
from ..geometry import geometry
width, height = canvas_size(original)
canvas = geometry(width, height, seconds=value['seconds'])
- frames, output_seconds = (canvas['frames'], canvas['seconds']) if value.get('continue_from') else \
- saved_length(canvas, value['seconds'])
+ frames, output_seconds = saved_length(canvas, value['seconds'], bool(value.get('continue_from')))
result.update(prompt=value['prompt'], width=width, height=height, seconds=float(value['seconds']),
frames=frames, output_seconds=output_seconds, seed_random=value['seed'] is None,
seed=secrets.randbelow(MAX_SEED + 1) if value['seed'] is None else value['seed'],
diff --git a/freevideo_engine/chain_plan.py b/freevideo_engine/chain_plan.py
index 99976cb..49d7668 100644
--- a/freevideo_engine/chain_plan.py
+++ b/freevideo_engine/chain_plan.py
@@ -30,8 +30,12 @@ def _first_frames(seconds):
return geometry(seconds=seconds)['frames']
-def plan(seconds, single=False, max_frames=None, single_limit_seconds=None, block_seconds=None):
- """`max_frames`: the most frames this device generates at once for the current settings (unknown: 15 s)."""
+def plan(seconds, single=False, max_frames=None, single_limit_seconds=None, block_seconds=None, continued=False):
+ """`max_frames`: the most frames this device generates at once for the current settings (unknown: 15 s).
+
+ `continued`: the video goes on from a saved one, so its first block too spends OVERLAP frames on what
+ came before and adds only the rest.
+ """
_number(seconds, 'Length')
if type(single) is not bool:
raise PlanError('invalid', 'Single must be true or false')
@@ -53,6 +57,10 @@ def plan(seconds, single=False, max_frames=None, single_limit_seconds=None, bloc
# The longest whole-second block this device can start a video with, and continue one with.
first = (limit - (limit - 5) % UNIT) // FPS if limit >= 39 else 0
following = (limit - OVERLAP) // UNIT * UNIT // FPS if limit >= OVERLAP + UNIT else 0
+ new = frames
+ if continued:
+ new = max(1, math.ceil(round(FPS * seconds, 6) / UNIT)) * UNIT
+ frames = new + OVERLAP
block = BLOCK_SECONDS
if block_seconds is not None:
block = math.floor(_number(block_seconds, 'The block length') + .5)
@@ -62,10 +70,10 @@ def plan(seconds, single=False, max_frames=None, single_limit_seconds=None, bloc
raise PlanError('block_too_long', 'This device cannot generate a block of this length')
fits = frames <= limit
# The block length only matters once a video is split: up to 30 s stays one generation.
- if fits and (single or seconds <= SINGLE_SECONDS or seconds <= min(block, first)):
- return dict(seconds=seconds, frames=frames, single=True, hide_frames=0,
- blocks=[dict(seconds=seconds, frames=frames, new_frames=frames)])
- first, following = min(block, first), min(block, following)
+ if fits and (single or seconds <= SINGLE_SECONDS or seconds <= min(block, following if continued else first)):
+ return dict(seconds=seconds, frames=new, single=True, hide_frames=0,
+ blocks=[dict(seconds=seconds, frames=frames, new_frames=new)])
+ first, following = min(block, following if continued else first), min(block, following)
if first < SHORTEST_BLOCK or following < SHORTEST_BLOCK:
raise PlanError('device_limit', 'This device cannot generate this length at this size')
total = seconds = math.floor(seconds + .5)
@@ -81,7 +89,7 @@ def plan(seconds, single=False, max_frames=None, single_limit_seconds=None, bloc
blocks, shown = [], 0
for index, length in enumerate(lengths):
target = FPS * sum(lengths[:index + 1])
- if index == 0:
+ if index == 0 and not continued:
new = requested = _first_frames(length)
else:
# Each block takes the shortest step that reaches its whole second; nothing is cut in between.
diff --git a/freevideo_engine/chain_store.py b/freevideo_engine/chain_store.py
index 6231a4c..2597b70 100644
--- a/freevideo_engine/chain_store.py
+++ b/freevideo_engine/chain_store.py
@@ -66,15 +66,20 @@ def validate(payload):
if type(join) is not bool:
raise ValueError('Join must be a bool')
if 'seconds' in payload:
+ # 'after' continues a saved video: the plan then counts the first block as a continuation too.
+ source = payload.get('after')
+ if source is not None and not isinstance(source, dict):
+ raise ValueError('A planned video can only continue a saved work')
planned = chain_plan.plan(payload['seconds'], payload.get('single', False), payload.get('max_frames'),
- payload.get('single_limit_seconds'), payload.get('block_seconds'))
+ payload.get('single_limit_seconds'), payload.get('block_seconds'),
+ continued=source is not None)
inputs = prompt[node]['inputs']
text, seed = payload.get('text', inputs.get('text')), payload.get('seed', inputs.get('seed'))
if not isinstance(text, str):
raise ValueError('Text must be a string')
if type(seed) is not int or seed < 0:
raise ValueError('A nonnegative integer seed is required')
- rows = [dict(id='b%s' % (index + 1), after='b%s' % index if index else None,
+ rows = [dict(id='b%s' % (index + 1), after='b%s' % index if index else source,
frames=row['frames'], text=text, seed=seed + index)
for index, row in enumerate(planned['blocks'])]
else:
diff --git a/web/agent_connect.css b/web/agent_connect.css
index ea8c04d..d63b4e8 100644
--- a/web/agent_connect.css
+++ b/web/agent_connect.css
@@ -1,19 +1,10 @@
-/* Settings · AI agents: copyable commands, a few facts, and a guarded token reset. */
-.fv-setup .fv-agent-connect-body,.fv-setup .fv-agent-connect-content{display:grid;gap:12px}
-.fv-setup .fv-agent-connect-body{padding-top:10px}
-.fv-setup .fv-agent-connect-body>p{margin:0;text-wrap:balance}
-.fv-setup .fv-agent-connect-content>p:empty{display:none}
-.fv-setup .fv-agent-copy{display:grid;gap:6px;min-width:0}
-.fv-setup .fv-agent-copy-head{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:var(--fv-micro);color:var(--fv-muted)}
-.fv-setup .fv-agent-copy-head button{min-height:26px;padding:0 10px;font-size:var(--fv-micro)}
-.fv-setup .fv-agent-copy :is(code,pre){display:block;margin:0;padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-bg);color:var(--fv-ink);font:12px/1.55 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;user-select:all}
-.fv-setup .fv-agent-copy-block pre{max-height:220px;overflow:auto;user-select:text}
-.fv-setup .fv-agent-facts{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:6px 16px;margin:0;font-size:var(--fv-micro)}
-.fv-setup .fv-agent-facts dt{color:var(--fv-muted)}
-.fv-setup .fv-agent-facts dd{margin:0;overflow-wrap:anywhere}
-.fv-setup .fv-agent-actions{align-items:center}
-.fv-setup .fv-agent-actions a{color:var(--fv-accent);font-size:var(--fv-body)}
-.fv-setup .fv-agent-confirm{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-raised);font-size:var(--fv-micro)}
-.fv-setup .fv-agent-confirm span{flex:1 1 220px;color:var(--fv-muted)}
-.fv-setup .fv-agent-confirm .fv-danger{border-color:var(--fv-danger);color:var(--fv-danger)}
+/* 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-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)}
.fv-setup .fv-agent-connect[hidden]{display:none}
diff --git a/web/agent_connect.js b/web/agent_connect.js
index eedd94e..cd9c955 100644
--- a/web/agent_connect.js
+++ b/web/agent_connect.js
@@ -1,116 +1,131 @@
-import {agentPost} from './agent_session.js';
-// Settings section: connect an AI agent (Claude Code, Cursor, scripts) to this FreeVideo.
-const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./agent_connect.css', import.meta.url).href; document.head.append(css);
-
-const DOCS = 'https://github.com/FlashML-org/FreeVideo/blob/main/docs/AGENTS.md';
-const DOCS_ZH = 'https://github.com/FlashML-org/FreeVideo/blob/main/docs/zh-CN/AGENTS.md';
+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; }
-function ago(iso, t) {
- const seconds = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
- if (!Number.isFinite(seconds)) return '';
- if (seconds < 90) return t('just now', '刚刚');
- if (seconds < 5400) return t(`${Math.round(seconds / 60)} min ago`, `${Math.round(seconds / 60)} 分钟前`);
- if (seconds < 129600) return t(`${Math.round(seconds / 3600)} h ago`, `${Math.round(seconds / 3600)} 小时前`);
- return t(`${Math.round(seconds / 86400)} days ago`, `${Math.round(seconds / 86400)} 天前`);
+// null means no connection has been seen; '' remembers a connection without a name.
+export function connectionState(copied, status, previousName, t) {
+ if (status?.connected === true) return {color: 'green', text: status.client?.trim() || 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', '复制')};
}
-// A command or snippet with a Copy button; falls back to selecting the text.
-function copyable(t, label, text, {block = false} = {}) {
- const wrap = el('div', 'fv-agent-copy' + (block ? ' fv-agent-copy-block' : ''));
- const head = el('div', 'fv-agent-copy-head');
- const code = el(block ? 'pre' : 'code', null, text);
- const button = el('button', null, t('Copy', '复制')); button.type = 'button';
- button.setAttribute('aria-label', t('Copy ', '复制') + label);
+// 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.
+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 subtitle = el('p', 'fv-muted', t('Claude Code, Codex, FreeToken and others', 'Claude Code、Codex、FreeToken 等'));
+ const sentence = el('p', 'fv-agent-sentence');
+ 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);
+
+ let copied = false, feedback = false, previousName = null, value = null;
+ 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;
+ }
+ render();
+
button.onclick = async () => {
- try { await navigator.clipboard.writeText(text); button.textContent = t('Copied', '已复制'); }
+ const text = sentence.textContent;
+ try { await navigator.clipboard.writeText(text); }
catch {
- const range = document.createRange(); range.selectNodeContents(code);
+ const range = document.createRange(); range.selectNodeContents(sentence);
const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
- button.textContent = t('Selected', '已选中');
}
- setTimeout(() => { button.textContent = t('Copy', '复制'); }, 1600);
+ if (!active()) return;
+ copied = true;
+ if (value?.connected !== true) previousName = null;
+ feedback = true; render();
+ clearTimeout(feedbackTimer);
+ feedbackTimer = setTimeout(() => { feedback = false; render(); }, 2000);
};
- head.append(el('span', null, label), button);
- wrap.append(head, code);
- return wrap;
-}
-export function agentConnect(t, api) {
- const section = el('details', 'fv-agent-connect');
- // Agent features can be off in this FreeVideo: the section appears only when they are on.
- section.hidden = true;
- (async () => {
- let on = false;
+ function stop() {
+ generation++; clearTimeout(timer); timer = null;
+ controller?.abort(); controller = null;
+ clearTimeout(feedbackTimer); feedback = false; render();
+ }
+ async function poll() {
+ const current = generation;
+ const request = new AbortController(); controller = request;
+ try {
+ if (!sentence.textContent) {
+ const response = await api.fetchApi('/freevideo/agent/connect', {cache: 'no-store', signal: request.signal});
+ if (!response.ok) return;
+ const connect = await response.json();
+ if (current !== generation || !active()) return;
+ if (!connect.address) return;
+ const url = connect.address + '/freevideo/agent';
+ sentence.textContent = t(`Connect to FreeVideo: open ${url} and follow the instructions.`, `请连接 FreeVideo:打开 ${url} 并按说明操作。`);
+ 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. */ }
+ finally {
+ if (current === generation) {
+ controller = null;
+ if (active()) timer = setTimeout(poll, 3000);
+ }
+ }
+ }
+ function sync() {
+ if (!active()) { stop(); return; }
+ if (!controller && !timer) poll();
+ }
+ // Resolves to whether this FreeVideo has the Agent interface on; a surface shows nothing when it is off.
+ const enabled = (async () => {
try {
const response = await api.fetchApi('/freevideo/agent', {cache: 'no-store'});
- on = response.ok && (await response.json()).enabled === true;
- } catch { on = false; }
- if (on) section.hidden = false;
- else section.remove();
+ return response.ok && (await response.json()).enabled === true;
+ } catch { return false; /* Discovery unavailable: the card stays absent. */ }
})();
- section.append(el('summary', null, t('AI agents', 'AI Agent 接入')));
- const body = el('div', 'fv-agent-connect-body');
- body.append(el('p', 'fv-muted', t('Let Claude Code, Cursor and other AI agents generate, review and edit with FreeVideo on this computer. Their jobs share the queue with yours and appear at the top of the creative workspace.',
- '让 Claude Code、Cursor 等 AI Agent 在这台电脑上用 FreeVideo 生成、审片和剪辑。它们的任务与您的生成共用队列,并显示在创作面板顶部。')));
- const content = el('div', 'fv-agent-connect-content'); content.setAttribute('aria-live', 'polite');
- content.append(el('p', 'fv-muted', t('Loading…', '正在读取…')));
- body.append(content);
- section.append(body);
- let loaded = false;
+ return {element: body, title: t('Connect an agent', '连接 Agent'), enabled, sync, stop};
+}
- async function load() {
- let value;
- try {
- const response = await api.fetchApi('/freevideo/agent/connect', {cache: 'no-store'});
- value = await response.json();
- if (!response.ok) throw new Error(value?.error?.message || response.statusText);
- } catch (error) {
- content.replaceChildren(el('p', 'fv-failure', t('Agent connection is unavailable: ', '无法读取 Agent 接入信息:') + error.message));
- return;
- }
- loaded = true;
- content.replaceChildren();
- content.append(copyable(t, 'Claude Code', value.claude_code),
- copyable(t, t('Claude Desktop, Cursor (mcpServers)', 'Claude Desktop、Cursor(mcpServers)'), JSON.stringify(value.mcp_json, null, 2), {block: true}));
- if (value.cli) content.append(copyable(t, t('Command line', '命令行'), value.cli));
- const facts = el('dl', 'fv-agent-facts');
- const fact = (name, text) => { facts.append(el('dt', null, name), el('dd', null, text)); };
- fact(t('HTTP API', 'HTTP 接口'), value.api);
- fact(t('Token', '令牌'), value.token_from_environment
- ? t('Set by FREEVIDEO_AGENT_TOKEN', '由环境变量 FREEVIDEO_AGENT_TOKEN 指定')
- : value.token_file);
- fact(t('Recent agents', '最近连接的 Agent'), value.agents?.length
- ? value.agents.map(a => `${a.client} · ${ago(a.last_seen, t)}`).join(',')
- : t('None yet', '暂无'));
- content.append(facts);
- const actions = el('div', 'fv-actions fv-agent-actions');
- const docs = el('a', null, t('Agent guide ↗', 'Agent 使用说明 ↗'));
- docs.href = t(DOCS, DOCS_ZH); docs.target = '_blank'; docs.rel = 'noopener noreferrer';
- const reset = el('button', null, t('Reset token', '重置令牌')); reset.type = 'button';
- reset.hidden = !!value.token_from_environment;
- const confirm = el('div', 'fv-agent-confirm'); confirm.hidden = true; confirm.setAttribute('role', 'group');
- const yes = el('button', 'fv-danger', t('Reset', '重置')); yes.type = 'button';
- const no = el('button', null, t('Keep', '保留')); no.type = 'button';
- confirm.append(el('span', null, t('Connected agents will need the new token; MCP servers read it again when they restart.',
- '已连接的 Agent 需要改用新令牌;MCP 服务重启后会自动读取。')), yes, no);
- const status = el('p', 'fv-muted'); status.setAttribute('role', 'status');
- reset.onclick = () => { confirm.hidden = false; reset.hidden = true; no.focus(); };
- no.onclick = () => { confirm.hidden = true; reset.hidden = false; reset.focus(); };
- yes.onclick = async () => {
- yes.disabled = true;
- try {
- const response = await agentPost(api, '/freevideo/agent/connect/reset', {});
- if (!response.ok) throw new Error(response.statusText);
- status.textContent = t('A new token was created. The old one no longer works.', '已生成新令牌,旧令牌已失效。');
- } catch (error) {
- status.className = 'fv-failure'; status.textContent = error.message;
- } finally { yes.disabled = false; confirm.hidden = true; reset.hidden = false; }
- };
- actions.append(docs, reset);
- content.append(actions, confirm, status);
+// 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 (section.open && !loaded) load(); });
+ 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/agent_session.js b/web/agent_session.js
index 97e2cb2..c4a6979 100644
--- a/web/agent_session.js
+++ b/web/agent_session.js
@@ -15,6 +15,17 @@ export async function agentHeaders(api) {
return pending;
}
+// Status reads use the same page session, acquired only when the card opens.
+export async function agentGet(api, path, options = {}) {
+ for (let attempt = 0; ; attempt++) {
+ const headers = await agentHeaders(api);
+ options.signal?.throwIfAborted();
+ const response = await api.fetchApi(path, {...options, cache: 'no-store', credentials: 'same-origin', headers});
+ if (response.status !== 401 || attempt) return response;
+ sessions.delete(api);
+ }
+}
+
// A restarted FreeVideo forgets page sessions: fetch a new one once and repeat.
export async function agentPost(api, path, body) {
for (let attempt = 0; ; attempt++) {