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.
AI autopilot: every click answers, sends are bounded, and failures name the step with a report
Bowen Xue957d251fbb39
diff --git a/freevideo_engine/agent/cast.py b/freevideo_engine/agent/cast.pyindex 7ed1f99..1b32163 100644--- a/freevideo_engine/agent/cast.py+++ b/freevideo_engine/agent/cast.py@@ -98,6 +98,7 @@ def view(card):if card.get('voice'):value['voice'] = dict(deepcopy(card['voice']), media=media_view(card['voice']['media']),clip=assets.view(card['voice']['clip']['file']))+ value['generate_error'] = errors.with_reason(value.get('generate_error'))return value@@ -112,7 +113,8 @@ def row_view(card):return dict(id=card['id'], kind=card['kind'], name=card['name'], description=card['description'],origin=card['origin'], revision=card['revision'], updated_at=card['updated_at'],images=len(card['images']), voice=card['voice'] is not None,- generating=card.get('generating') is not None, thumbnail=thumbnail(card))+ generating=card.get('generating') is not None, thumbnail=thumbnail(card),+ generate_error=errors.with_reason(card.get('generate_error')))def _plain(item):@@ -729,7 +731,7 @@ class Cast:code = (row.get('error') or {}).get('code') if row else 'not_found'code = code or (row['status'] if row else 'not_found')detail = errors.image_failure(code, (row.get('error') or {}).get('report_id') if row else None)- failure = failure or dict(code=code or row['status'], job=job, message=(+ failure = failure or dict(code=code, job=job, error_zh=detail['reason']['zh'], message=('The generation was cancelled.' if row and row['status'] == 'cancelled'else detail['reason']['en']), **detail)continue@@ -764,7 +766,8 @@ class Cast:face = job == generating.get('face_job')if row is None or row['status'] != 'succeeded':code = (row.get('error') or {}).get('code') if row else 'not_found'- failure = failure or dict(code=code or row['status'], job=job, message=(+ failure = failure or dict(code=code or row['status'], job=job,+ error_zh=errors.failure_reason((row.get('error') or dict(code=code or row['status'])) if row else dict(code=code)), message=('The generation was cancelled.' if row and row['status'] == 'cancelled'else 'The reference clip did not finish.'))continuediff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.pyindex f79540a..8ec96ea 100644--- a/freevideo_engine/agent/errors.py+++ b/freevideo_engine/agent/errors.py@@ -248,6 +248,82 @@ def safe_details(value):return '[redacted]'+# One public sentence shared by conversation cards, HTTP and MCP. Backend text+# is classified, never echoed: it can contain prompts, filenames or credentials.+FAILURE_REASONS_ZH = {+ 'out_of_memory': '生成时显存或内存不足',+ 'insufficient_memory': '可用显存或内存不够生成这段内容',+ 'no_memory': '可用显存或内存不够生成这张图片',+ 'ram_space': '加载模型时系统内存不足',+ 'model_missing': '需要的模型还没有安装好',+ 'pack_missing': '图片模型还没有安装好',+ 'not_ready': '生成所需的环境还没有安装好',+ 'cancelled': '生成已被停止',+ 'stopped_by_user': '生成已被停止',+ 'interrupted': '生成服务中途重启,任务被打断',+ 'worker_exit': '图片生成进程中途退出',+ 'closed': '图片生成服务已经关闭',+ 'image_unavailable': '图片生成服务还没有启动',+ 'vlm_unavailable': '读取画面的模型服务还没有启动',+ 'vlm_failed': '读取画面的模型没有完成请求',+ 'vlm_invalid_json': '模型返回的结果格式无法读取',+ 'context_length': '描述和参考图超过了模型可读取的长度',+ 'dependency_failed': '前面依赖的任务没有完成',+ 'lost': '生成服务没有保留这次任务的结果',+ 'unknown_job': '图片生成服务找不到这次任务',+ 'not_found': '找不到这次任务或素材',+ 'source_missing': '接续所需的上一段视频已经不在',+ 'chain_missing': '接续所需的生成记录已经不在',+ 'chain_unavailable': '分段生成服务还没有启动',+ 'continuation_unavailable': '当前生成方式不支持接续视频',+ 'join_failed': '片段已生成,但拼接成片时出错',+ 'invalid_output': '生成的结果无法读取或保存',+ 'storage_unavailable': '任务记录或素材无法写入磁盘',+ 'submit_interrupted': '提交生成时服务中断,尚未确认任务是否开始',+ 'timeout': '生成等待超时',+ 'invalid_media': '参考素材无法读取',+ 'clip_unreadable': '生成的角色参考视频无法读取',+ 'invalid_request': '生成参数不符合支持的范围',+ 'invalid_drama': '短剧计划中有无法使用的参数',+ 'reshoot_limit': '这个镜头已达到可生成的次数上限',+ 'production_limit': '这部短剧已达到可生成的任务数量上限',+ 'export_failed': '导出成片时出错',+ 'invalid_prompt': '图片描述为空或超过了支持的长度',+ 'invalid_dimensions': '图片尺寸超出了支持的范围',+ 'too_many_images': '参考图片数量超过了支持的范围',+ 'chain_too_long': '接续后的视频超过了支持的段数',+ 'chain_rejected': '生成服务无法使用这组参数',+ 'generation_failed': '生成过程中出错,未能完成结果',+ 'internal_error': '处理任务时出错,未能完成结果',+}+FAILURE_MESSAGES_ZH = {+ 'The previous video is too short to continue; it needs to be at least 2 s long.': '接续的上一段视频太短,至少需要 2 秒',+ 'The previous video has no usable continuation data. Generate it again with this version of FreeVideo.': '上一段视频缺少可用的接续数据',+ 'The previous video cannot be read.': '接续的上一段视频无法读取',+ 'Use the same width and height as the previous video.': '接续的画面大小与上一段视频不一致',+ 'The reference video is too short; it needs to be at least about 1 s long.': '参考视频太短,至少需要约 1 秒',+}+++def failure_reason(error):+ if isinstance(error.get('error_zh'), str) and error['error_zh'].strip():+ return error['error_zh']+ lines = str(error.get('message') or '').strip().splitlines()+ line = lines[0] if lines else ''+ if line.startswith('FreeVideo generation failed') and len(lines) > 1:+ line = lines[1].strip()+ line = re.sub(r'^(?:[\w.]*Error|[\w.]*Exception):\s*', '', line)+ if line in FAILURE_MESSAGES_ZH:+ return FAILURE_MESSAGES_ZH[line]+ if line.startswith(('CUDA out of memory', 'MPS backend out of memory')):+ return FAILURE_REASONS_ZH['out_of_memory']+ return FAILURE_REASONS_ZH.get(error.get('code'), '处理任务时出错,未能完成结果')+++def with_reason(error):+ return dict(error, error_zh=failure_reason(error)) if error else error++def build(code, *, details=None, request=None, validation=False, message=None, next_action=None,action_required=True, retry_after_seconds=None, owner=None, kind=None, stage='request', resumable=True,report_id=None):@@ -270,7 +346,7 @@ def build(code, *, details=None, request=None, validation=False, message=None, nresult['retry_after_seconds'] = retry_after_seconds or 1result['details'].append(dict(owner=owner if owner in ('agent', 'ui') else 'ui'))result['message'] += ' An Agent job is ahead.' if owner == 'agent' else ' A job in the user interface is ahead.'- return result+ return with_reason(result)def validation(errors, code='invalid_request'):diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.pyindex 2e12cdb..0f517fb 100644--- a/freevideo_engine/agent/jobs.py+++ b/freevideo_engine/agent/jobs.py@@ -14,6 +14,7 @@ import jsonimport loggingimport mathimport os+import reimport secretsimport shutilimport stat@@ -592,15 +593,21 @@ class Jobs:def finish(self, row, status, *, result=None, error=None, save=True):if error is not None:code = error.get('code', 'internal_error')+ report_id = error.get('report_id')if code == 'invalid_json' and row['kind'] in ('vlm', 'enhance'):code = 'vlm_invalid_json'+ reason_zh = errors.failure_reason(dict(error, code=code))if code != error.get('code') or not error.get('request_id') or row['kind'] == 'image':error = errors.build(code, details=error.get('details'),request=row.get('request_id'), action_required=code != 'cancelled',kind=row['kind'], stage='terminal', resumable=not row['spec'].get('refine_from'),report_id=error.get('report_id'))+ if row['kind'] == 'image':+ reason_zh = error['error_zh']if error is not None:- error = dict(error, request_id=row.get('request_id') or error['request_id'])+ error = dict(error, request_id=row.get('request_id') or error['request_id'], error_zh=reason_zh)+ if row['kind'] != 'image' and isinstance(report_id, str) and re.fullmatch(r'[a-f0-9]{32}', report_id):+ error['report_id'] = report_idif error.get('next'):error['next'] = errors.recovery(error['code'], kind=row['kind'], stage='terminal',resumable=not row['spec'].get('refine_from')).replace('{id}', row['id'])@@ -1068,6 +1075,11 @@ class Jobs:result['error'] = errors.build(result['error']['code'], kind='image', stage='terminal',details=result['error'].get('details'), request=row.get('request_id'),action_required=result['error']['code'] != 'cancelled', report_id=row['error'].get('report_id'))+ else:+ result['error'] = dict(result['error'], error_zh=errors.failure_reason(row['error']))+ report_id = row['error'].get('report_id')+ if isinstance(report_id, str) and re.fullmatch(r'[a-f0-9]{32}', report_id):+ result['error']['report_id'] = report_idif result['error'].get('next'):result['error'] = dict(result['error'], next=errors.recovery(result['error']['code'], kind=row['kind'],stage='terminal', resumable=not row['spec'].get('refine_from')).replace('{id}', row['id']))@@ -1696,6 +1708,10 @@ class Jobs:reason = self.port.generation_error(history, chain['node'])except Exception as error:self.log_poll_failure(row, error)+ try:+ report_id = (self.port.progress(chain['node']) or {}).get('report_id')+ except Exception:+ report_id = Nonecode = reason.get('code', 'generation_failed')if code not in ('insufficient_memory', 'out_of_memory', 'generation_failed'):code = 'generation_failed'@@ -1718,8 +1734,12 @@ class Jobs:'POST /freevideo/agent/v1/jobs/%s/resume to retry unfinished work.' % row['id'])if code == 'insufficient_memory' and reason.get('alternatives'):next_action = 'Use the alternatives in details to lower size or duration, then POST /freevideo/agent/v1/jobs.'- return chain_error(code, errors.ERRORS[code][2], next_action, details=[detail],- retryable=code != 'insufficient_memory').view()+ failure = dict(chain_error(code, errors.ERRORS[code][2], next_action, details=[detail],+ retryable=code != 'insufficient_memory').view(),+ error_zh=errors.failure_reason(dict(code=code, message=message)))+ if isinstance(report_id, str) and re.fullmatch(r'[a-f0-9]{32}', report_id):+ failure['report_id'] = report_id+ return failure# Local image generation ----------------------------------------------------------------------------def wait_image(self, row, code, *, waiting_for=None):@@ -1781,7 +1801,9 @@ class Jobs:elif phase == 'cancelled':self.finish(row, 'cancelled', error=dict(code='cancelled'))else:- code = state.get('error') or 'generation_failed'+ failure = state.get('error')+ code = failure.get('code') if isinstance(failure, dict) else failure+ code = code or 'generation_failed'if not self.wait_image(row, code):self.finish(row, 'failed', error=dict(code=code, report_id=state.get('report_id')))diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.pyindex 54c794f..fab1b08 100644--- a/freevideo_engine/agent/productions.py+++ b/freevideo_engine/agent/productions.py@@ -140,7 +140,22 @@ def _safe_error(error):rows = [_safe_row(row) for row in details] if isinstance(details, list) and details else []if rows and all(rows):result.update(details=rows, message='; '.join(row['message'] for row in rows))- return result+ return dict(result, error_zh=errors.failure_reason(error))+++def failure(view):+ """The current failure, excluding old takes superseded by a usable take."""+ if view.get('stalled'):+ return view['stalled'], None+ join = view.get('join') or {}+ if join.get('state') in ('failed', 'interrupted') and join.get('error'):+ return join['error'], join.get('task')+ for shot in view.get('shots', []):+ if shot['state'] == 'failed':+ take = next((t for t in reversed(shot['takes']) if t.get('error') and not t['stale']), {})+ if take:+ return take['error'], take.get('task')+ return None, Noneclass Productions:@@ -194,7 +209,7 @@ class Productions:def _stalled(self, error):code = error.code if isinstance(getattr(error, 'code', None), str) and error.code in errors.ERRORS else 'internal_error'- return dict(code=code, message=errors.ERRORS[code][2], at=iso(self.jobs.clock()))+ return errors.with_reason(dict(code=code, message=errors.ERRORS[code][2], at=iso(self.jobs.clock())))def _save(self, record):self.directory.mkdir(parents=True, exist_ok=True)@@ -588,7 +603,7 @@ class Productions:value = production.view(record['state'])tasks = record.get('tasks', {})def contextual(error, join=False):- error = deepcopy(error)+ error = errors.with_reason(deepcopy(error))if error and 'next' in error:action = self._context_next(record, join)if action:@@ -604,9 +619,11 @@ class Productions:ref = record['state']['current_join']join = next(j for j in record['state']['joins'] if j['ref'] == ref)value['join'].update(ref=ref, task=tasks.get(ref), error=contextual(join['error'], True))- value['stalled'] = deepcopy(record.get('stalled'))+ value['stalled'] = errors.with_reason(deepcopy(record.get('stalled')))value['progress'] = self._progress(record)value['over_budget'] = self._elapsed_budget(value['progress'])+ error, _ = failure(value)+ value['error_zh'] = errors.failure_reason(error) if error else Nonereturn valuedef get(self, identity, *, since=None, wait=0, compact=True):@@ -625,9 +642,15 @@ class Productions:changed = record['state']['revision'] != sinceif not changed and compact:progress = self._progress(record)- return dict(id=identity, revision=since, changed=False, status=record['state']['status'],+ value = dict(id=identity, revision=since, changed=False, status=record['state']['status'],paused=deepcopy(record['state'].get('paused')), fraction=progress['fraction'],elapsed_seconds=progress['elapsed_seconds'])+ state = record['state']+ join = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)+ error, _ = failure(dict(stalled=record.get('stalled'), join=join, shots=state['shots']))+ if error:+ value['error_zh'] = errors.failure_reason(error)+ return valuereturn dict(self._view(record), changed=changed)async def get_async(self, identity, *, since=None, wait=0, compact=True):@@ -676,7 +699,7 @@ class Productions:shot = next((s for s in view['shots'] if s['chosen'] is None), view['shots'][-1])result.append(dict(id=view['id'], title=view['title'], status=view['status'], revision=view['revision'],shot=shot['index'], shots=len(view['shots']), next=view['todo'][0] if view['todo'] else None,- paused=view['paused'], stalled=view['stalled'], session=record.get('session')))+ paused=view['paused'], stalled=view['stalled'], session=record.get('session'), error_zh=view['error_zh']))return resultdef _mutate(self, action, identity, *, by, ref=None, client=None, **values):diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex e47d59b..ef1e926 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -586,6 +586,12 @@ def register():for key in ('drama', 'project', 'image'):if isinstance(value.get(key), str):refs[key] = value[key]+ identity = value.get('id')+ if isinstance(identity, str):+ if identity.startswith('d') and 'shots' in value:+ refs['drama'] = identity+ elif identity.startswith('c') and value.get('kind') in ('character', 'setting'):+ refs['cast'] = identityreturn refsasync def session_after(request, response):@@ -726,6 +732,9 @@ def register():value['waiting_for'] = len(view['waiting_for'])if view.get('error'):value['error'] = view['error']+ report_id = (view.get('error') or {}).get('report_id') or (view.get('result') or {}).get('report_id')+ if isinstance(report_id, str) and re.fullmatch(r'[a-f0-9]{32}', report_id):+ value['report_id'] = report_idvideo = (view.get('result') or {}).get('video') or {}if video.get('url'):value['video'] = video['url']@@ -792,7 +801,8 @@ def register():if fold is None:while len(chat['folds']) >= 8:chat['folds'].pop(next(iter(chat['folds'])))- fold = chat['folds'][sid] = dict(seq=0, items=[], jobs={}, asked={}, sent={}, ids={}, names={}, said=None)+ # Message IDs persist in session events and rebuild deduplication when a fold is evicted.+ fold = chat['folds'][sid] = dict(seq=0, items=[], jobs={}, entities={}, asked={}, sent={}, ids={}, names={}, said=None)while store.get(sid)['last_seq'] > fold['seq']:rows = store.events(sid, after=fold['seq'], limit=500)if not rows:@@ -810,11 +820,18 @@ def register():while len(fold['sent']) > 500:fold['ids'].pop(fold['sent'].pop(next(iter(fold['sent']))), None)elif row['type'] == 'step' and row['state'] == 'done':- job = (row.get('refs') or {}).get('job')+ refs = row.get('refs') or {}+ job = refs.get('job')+ entity = next(((refs[key], kind) for key, kind in (('drama', 'production'), ('cast', 'cast')) if refs.get(key)), None)+ new_entity = entity and entity[0] not in fold['entities']+ if new_entity:+ fold['entities'][entity[0]] = entity[1]if job and job not in fold['jobs']:fold['jobs'][job] = row['seq']fold['names'][job] = chat_name(fold['said'])- fold['items'].append(dict(base, type='job', job=job))+ fold['items'].append(dict(base, type='job', job=job, **({'entity': entity[0]} if new_entity else {})))+ elif new_entity:+ fold['items'].append(dict(base, type=entity[1], entity=entity[0]))elif row['type'] == 'confirm':if row['state'] == 'asked':item = dict(base, id=row['id'], question=row.get('question'),@@ -854,7 +871,7 @@ def register():store = work_sessions()sid = chat_session(store, wanted)rows = jobs.rows()- value = dict(agent=agent_state(), session=sid, here=chat_session(store), last_seq=0, read_seq=0, items=[], jobs={}, confirms={}, current=None,+ value = dict(agent=agent_state(), session=sid, here=chat_session(store), last_seq=0, read_seq=0, items=[], jobs={}, failures={}, confirms={}, current=None,active=sum(1 for r in rows if r['status'] in ACTIVE))if sid is None:return value@@ -883,6 +900,24 @@ def register():shown = {r['id']: r for r in mine if r['status'] in ACTIVE or (r.get('finished_at') or 0) > now - 1800}shown.update((i['job'], known[i['job']]) for i in items if i['type'] == 'job')value['jobs'] = {identity: chat_card(row, fold) for identity, row in shown.items()}+ for identity, kind in fold['entities'].items():+ try:+ entity = jobs.productions.get(identity, compact=False) if kind == 'production' else jobs.cast.get(identity)+ except JobError:+ continue # A deleted card is no longer part of this conversation.+ error, task = None, None+ if kind == 'cast':+ error = entity.get('generate_error')+ task = (error or {}).get('job')+ else:+ from .productions import failure+ error, task = failure(entity)+ if error:+ task_view = jobs.view(known[task], detail=False) if task in known else {}+ report_id = ((task_view.get('error') or {}).get('report_id')+ or (task_view.get('result') or {}).get('report_id'))+ value['failures'][identity] = dict(id=identity, kind=kind, status='failed',+ label=entity.get('title') or entity.get('name'), error=errors.with_reason(error), report_id=report_id)value['current'] = current['id'] if current else Noneif current and current['id'] not in value['jobs']:value['jobs'][current['id']] = chat_card(current, fold)diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.pyindex 11ef962..1e3d01c 100644--- a/freevideo_engine/agent/schema.py+++ b/freevideo_engine/agent/schema.py@@ -510,7 +510,7 @@ def cast_view():description=nullable(string(1000)), revision=number(1, integer=True),images=array(picture, 0, 6), candidates=array(picture, 0, 6),generating=nullable(generating), generated=nullable(generated),- generate_error=nullable(obj(dict(code=string(), job=JOB, message=string()), ('code', 'job', 'message')))),+ generate_error=nullable(obj(dict(code=string(), job=JOB, message=string(), error_zh=string()), ('code', 'job', 'message')))),('id', 'kind', 'name', 'revision', 'images', 'candidates', 'generating')), additionalProperties=True)@@ -1332,7 +1332,8 @@ def openapi():report_id={'type': ['string', 'null'], 'pattern': '^[0-9a-f]{32}$','description': 'Image diagnostic report ID, or null when no report exists.'},request_id=string(), docs=string(), retry_after_seconds=number(0), card={'type': 'object'}, job=JOB,- project={'type': 'object'}, current_revision=number(1, integer=True)),+ project={'type': 'object'}, current_revision=number(1, integer=True),+ error_zh=string()),('code', 'message', 'details', 'retryable', 'request_id', 'docs'))}))diff --git a/web/agent_activity.js b/web/agent_activity.jsindex 5785391..224ca57 100644--- a/web/agent_activity.js+++ b/web/agent_activity.js@@ -1,4 +1,4 @@-import {agentPost} from './agent_session.js';+import {retryAgentPost} 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);@@ -45,6 +45,7 @@ function phaseText(p, t) {function status(job, t) {const [en, zh] = KINDS[job.kind] || KINDS.generate;if (job.status === 'running') return t(en, zh);+ if (job.status === 'cancelling') return t('Stopping', '正在停止');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', '等待显卡');@@ -54,7 +55,7 @@ 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) {+function row(job, t, api, refresh, open, cancellationErrors) {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');@@ -75,7 +76,7 @@ function row(job, t, api, refresh, open) {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);+ else if (job.status === 'failed') meta.push(t(job.error?.message || 'The task failed.', job.error?.error_zh || '处理任务时出错,未能完成结果'));if (job.project) meta.push(job.project);const foot = el('div', 'fv-agent-foot');const details = el('p', 'fv-agent-meta', meta.join(' · '));@@ -85,10 +86,16 @@ function row(job, t, api, refresh, open) {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;+ stop.disabled = true; stop.textContent = t('Stopping', '正在停止');try {- await agentPost(api, '/freevideo/agent/activity/cancel', {id: job.id});+ const response = await retryAgentPost(api, '/freevideo/agent/activity/cancel', {id: job.id});+ if (!response?.ok) {+ const message = t('Stopping failed after a retry. If still running, click again.', '停止没成功,已重试;仍在运行请再点一次');+ details.textContent = message;+ cancellationErrors.set(job.id, message);+ } else cancellationErrors.delete(job.id);} finally { refresh(); }+ stop.disabled = false; stop.textContent = t('Stop', '停止');};foot.append(stop);}@@ -100,21 +107,22 @@ function row(job, t, api, refresh, open) {foot.append(show);}body.append(foot);+ if (cancellationErrors.has(job.id)) details.textContent = cancellationErrors.get(job.id);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};+function rows(jobs, t, api, refresh, open, cancellationErrors) {+ const rank = {running: 0, cancelling: 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));+ const items = active.map(job => row(job, t, api, refresh, open, cancellationErrors));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)));+ items.push(divider, ...done.map(job => row(job, t, api, refresh, open, cancellationErrors)));}return items;}@@ -140,18 +148,20 @@ export function createAgentActivity(t, api, host, {interval = [1500, 8000], openpanel.setAttribute('aria-label', t('Agent jobs', 'Agent 任务'));host.append(panel);let data = {active: 0, jobs: []}, timer = null, disposed = false, failures = 0;+ const cancellationErrors = new Map();function renderPanel() {const header = el('header');header.append(el('h2', null, t('Agent jobs', 'Agent 任务')));const list = el('ol');- const key = refill(panel, list, rows(data.jobs, t, api, poll, job => { setOpen(false); open(job); }));+ const key = refill(panel, list, rows(data.jobs, t, api, poll, job => { setOpen(false); open(job); }, cancellationErrors));panel.replaceChildren();panel.append(header, list);if (key) (panel.querySelector(`[data-job="${key[0]}"] .${key[1].split(' ')[0]}`) || panel).focus?.();}function render() {const jobs = data.jobs || [];+ for (const job of jobs) if (!['waiting', 'queued', 'running', 'cancelling'].includes(job.status)) cancellationErrors.delete(job.id);element.hidden = !jobs.length;if (!jobs.length) { setOpen(false); return; }const running = jobs.find(j => j.status === 'running'), active = data.active || 0;diff --git a/web/agent_connect.css b/web/agent_connect.cssindex 2d0c8ca..f6f5d75 100644--- a/web/agent_connect.css+++ b/web/agent_connect.css@@ -30,6 +30,8 @@.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-studio .fv-autopilot-now-stop[aria-busy=true]{width:auto;padding:0 8px;font-size:12px;color:var(--fv-muted);opacity:1}+.fv-autopilot-now-stop[aria-busy=true]::after{display:none}.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}}diff --git a/web/agent_connect.js b/web/agent_connect.jsindex b8f8e9f..65bf2cd 100644--- a/web/agent_connect.js+++ b/web/agent_connect.js@@ -43,15 +43,22 @@ export function agentConnectCard(t, api, shown = () => true) {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);+ const status = el('p', 'fv-agent-connect-status', t('Getting the connection address…', '正在获取连接地址…')); status.setAttribute('role', 'status');+ body.append(mark, title, subtitle, actions, sentence, status);- let feedback = false, text = '';+ let feedback = false, text = '', failures = 0;let timer, feedbackTimer, controller, generation = 0;const active = () => body.isConnected && shown();- const render = () => { label.textContent = feedback ? t('Copied', '已复制') : t('Copy', '复制'); };+ const render = () => {+ label.textContent = !text && failures >= 3 ? t('Could not get address. Retry', '获取失败,重试') : feedback ? t('Copied', '已复制') : t('Copy', '复制');+ button.disabled = !text && failures < 3;+ button.title = !text && failures < 3 ? t('Getting the connection address…', '正在获取连接地址…') : '';+ status.hidden = !!text; status.textContent = !text && failures < 3 ? t('Getting the connection address…', '正在获取连接地址…') : '';+ };render();button.onclick = async () => {+ if (!text) { failures = 0; render(); await load(); return; }try { await navigator.clipboard.writeText(text); sentence.hidden = true; }catch {sentence.textContent = text; sentence.hidden = false;@@ -77,20 +84,21 @@ export function agentConnectCard(t, api, shown = () => true) {// 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;+ if (current !== generation) return;+ if (!connect?.address) throw new Error('Missing address');text = connectionSentence(connect.address, t);- button.disabled = false;- } catch { /* Try again while the card is in sight. */ }+ failures = 0; render();+ } catch { if (current === generation) { failures++; render(); } }finally {if (current === generation) {controller = null;- if (!text && active()) timer = setTimeout(load, 3000);+ if (!text && active() && failures < 3) timer = setTimeout(() => { timer = null; void load(); }, 3000);}}}function sync() {if (!active()) { stop(); return; }- if (!text && !controller && !timer) load();+ if (!text && failures < 3 && !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);diff --git a/web/agent_session.js b/web/agent_session.jsindex c4a6979..b233004 100644--- a/web/agent_session.js+++ b/web/agent_session.js@@ -37,3 +37,18 @@ export async function agentPost(api, path, body) {sessions.delete(api);}}++// UI actions retry once, including HTTP refusals. Callers keep the same+// idempotency id/body and show the result where the user clicked.+export async function retryAgentPost(api, path, body, {retry = async () => body, accept = () => true} = {}) {+ for (let attempt = 0; attempt < 2; attempt++) {+ let response = null;+ try {+ response = await agentPost(api, path, body);+ if (response?.ok && await accept(response)) return response;+ } catch { /* Retry below, including an unreadable response body. */ }+ if (attempt) return response?.ok ? null : response;+ body = await retry(response);+ if (!body) return response;+ }+}diff --git a/web/autopilot.js b/web/autopilot.jsindex fe348b6..9453dd5 100644--- a/web/autopilot.js+++ b/web/autopilot.js@@ -68,7 +68,9 @@ export function openAutopilotView(node, {studio = null} = {}) {const job = talking ? last.current : null;now.hidden = !job; line.dataset.on = String(!!job);halt.disabled = !!last.stopping;- halt.title = last.stopping ? t('Stopping', '正在停止') : t('Stop all', '全部停止'); halt.setAttribute('aria-label', halt.title);+ halt.setAttribute('aria-busy', String(!!last.stopping));+ halt.textContent = last.stopping ? t('Stopping…', '正在停止…') : '';+ halt.title = last.stopping ? t('Stopping…', '正在停止…') : t('Stop all', '全部停止'); halt.setAttribute('aria-label', halt.title);if (job) {const fraction = last.fraction || 0, running = job.status === 'running';currentId = job.id; name.textContent = jobName(job, t); more.textContent = last.active > 1 ? `+${last.active - 1}` : '';diff --git a/web/autopilot_chat.css b/web/autopilot_chat.cssindex db8f83b..7f2fa37 100644--- a/web/autopilot_chat.css+++ b/web/autopilot_chat.css@@ -109,6 +109,13 @@.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-notice{justify-self:center;width:100%;max-width:720px;margin:6px 0;font-size:14px;color:var(--fv-ink)}+.fv-chat-preview[data-loading=true] .fv-chat-play::before{border-color:var(--fv-accent);animation:fv-chat-breathe 1s infinite}+.fv-chat-job:is([data-mode=failed],[data-mode=stopped]){display:block;width:100%}.fv-chat-job:is([data-mode=failed],[data-mode=stopped]) .fv-chat-actions{margin-top:10px;flex-wrap:wrap}+.fv-studio .fv-chat-job:is([data-mode=failed],[data-mode=stopped]) .fv-result-links{justify-content:flex-start}+.fv-chat-job .fv-report-tip{max-width:100%}+.fv-chat-main{grid-template-rows:auto minmax(0,1fr) auto auto}+.fv-chat-tools{grid-row:1}.fv-chat-scroll{grid-row:2}.fv-chat-notice{grid-row:3}.fv-chat-input{grid-row:4}.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)}@@ -120,7 +127,7 @@.fv-studio .fv-chat-conversations .fv-chat-conversation-row:has(> .fv-chat-more:not([hidden])) .fv-chat-conversation{padding-right:calc(var(--fv-chats-pad) + 36px)}.fv-studio .fv-chat-conversations .fv-chat-more,.fv-studio .fv-chat-conversation-row:is(:hover,:focus-within,[data-menu-open=true]) .fv-chat-more{width:36px;height:36px;min-height:36px;opacity:1;pointer-events:auto}.fv-chat[data-conversations=true]{grid-template-columns:minmax(0,1fr)}- .fv-chat[data-conversations=true] .fv-chat-main{grid-template-rows:auto minmax(0,1fr) auto}+ .fv-chat[data-conversations=true] .fv-chat-main{grid-template-rows:auto minmax(0,1fr) auto auto}.fv-chat-tools:not([hidden]){display:flex;padding-top:12px;margin-bottom:-12px}.fv-studio .fv-chat-chats{position:relative;width:var(--fv-chats-toggle);height:var(--fv-chats-toggle);min-height:0;padding:0;border-radius:var(--fv-chats-radius);background:var(--fv-card)}.fv-chat-chats .fv-chat-running{position:absolute;top:5px;right:5px}diff --git a/web/autopilot_chat.js b/web/autopilot_chat.jsindex 39cccda..6be090b 100644--- a/web/autopilot_chat.js+++ b/web/autopilot_chat.js@@ -1,9 +1,10 @@// 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';+import {agentGet, agentPost, retryAgentPost} from './agent_session.js';import {isolateDialogKeys, routeDialogKey} from './dialog_keys.js';import {closeDialog} from './motion.js';-import { estimatedFraction, remainingAbove, remainingShown } from './generation_progress.js';+import { estimatedFraction, remainingAbove, remainingShown, createDiagnosticReportControl } from './generation_progress.js';+import {createErrorReport} from './error_panel.js';import {canDeleteConversation, conversationMenu, emptyConversations, hasConversations, mergeConversations, removeConversation, runningElsewhere, selectConversation} from './autopilot_conversations.js';import {renderImageFailure} from './image_generation.js';@@ -19,9 +20,26 @@ function glyph(path, width = 2.2) {const press = (cls, text, action) => { const b = el('button', cls, text); b.type = 'button'; b.onclick = action; return b; };let chatNumber = 0;-const WORKING = ['running', 'queued', 'waiting'], VIDEOS = ['generate', 'assemble'];+const WORKING = ['running', 'queued', 'waiting', 'cancelling'], VIDEOS = ['generate', 'assemble'];// What a job with no picture of its own is doing, in the reader's language.const QUIET = {vlm: ['Checking', '检查中'], enhance: ['Polishing', '润色中']};+const SEND_ATTEMPTS = 3, WAIT_FOR_AGENT = ['not_connected', 'not_listening'];+const GENERIC_FAILURE_ZH = '处理任务时出错,未能完成结果';+// A listening/connection race is queued; other 4xx refusals never repeat automatically.+const sendRefused = (error, response) => error?.code === 'session_full' || error?.retryable === false+ || response?.status >= 400 && response.status < 500 && !WAIT_FOR_AGENT.includes(error?.code);+async function sendError(response) {+ if (!response) return null;+ try { return (await (response.clone?.() || response).json())?.error || null; }+ catch { return null; }+}+// Sends and failure cards use the same public reason, including the engine's Chinese mapping.+function failureReason(value, t) {+ const error = value.error, reason = error?.error_zh || value.error_zh;+ if (error?.code === 'session_full' && (!reason || reason === GENERIC_FAILURE_ZH))+ return t('This conversation is full. Start a new chat.', '这个对话已达到消息数量上限,请新建对话');+ return t(error?.message || 'The task failed.', reason || GENERIC_FAILURE_ZH);+}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')}`; }@@ -78,6 +96,7 @@ const SAVING = ['decode', 'finishing', 'assembling'], stepped = p => p.phase ===// 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 === 'cancelling') return t('Stopping', '正在停止');if (job.status !== 'running') return t('Queued', '排队中');if (stepped(p)) return t(`Step ${p.step.done} / ${p.step.total}`, `生成 ${p.step.done} / ${p.step.total}`);if (SAVING.includes(p.phase)) return t('Saving', '保存中');@@ -110,14 +129,14 @@ export function jobParts(job) {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});+export const emptyChat = () => ({session: undefined, items: new Map(), jobs: {}, failures: {}, 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);+ for (const item of data.items || []) if (['message', 'job', 'confirm', 'production', 'cast'].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,+ return {session: data.session ?? null, items, jobs: {...state.jobs, ...(data.jobs || {})}, failures: data.failures || {}, 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};}@@ -222,6 +241,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()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); main.append(scroller, down, form); element.append(main);+ const notice = el('p', 'fv-chat-notice'); notice.hidden = true; notice.setAttribute('role', 'status'); main.insertBefore(notice, form);+ function say(text) { notice.textContent = text; notice.hidden = !text; }let dismissImage = null;let state = emptyChat(), pending = [], known = false, stopped = false, timer = null, busy = false, failures = 0;@@ -433,7 +454,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()}}function chooseChat(session, focus = false) {- closeMenu();+ closeMenu(); say('');showDraft(session); rememberSelection(session);selectedSession = session; selection++; pinned = true; away = null;conversations = selectConversation(conversations, session); renderConversations();@@ -512,7 +533,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()// Whether the reader is at the newest entry. It holds while the conversation is out of sight, which forgets where it was scrolled.let pinned = true;const closed = new AbortController();- const nodes = new Map(), answers = new Map(), stopping = new Set(), stopErrors = new Map(), retrying = new Set(), confirming = new Set(), confirmErrors = new Map();+ const nodes = new Map(), answers = new Map(), stopping = new Set(), retrying = new Set(), confirming = new Set(), confirmErrors = new Map();let bulkStopping = false;const cardKey = (session, id) => JSON.stringify([session, id]);// The fraction each job shows: the estimate, never backwards, short of 100% until the video is saved.@@ -539,19 +560,20 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()}const active = () => !stopped && element.isConnected && !document.hidden && shown();const inSelectedChat = () => !creating && (!selectedSession || selectedSession === state.session);+ const composeAllowed = () => inSelectedChat() && state.agent.connected === true;const sendingAllowed = () => inSelectedChat() && canSend(state);const draftSending = () => pending.some(entry => entry.sending && entry.draft && entry.draft === drafts.get(draftSession));- async function cancelJob(job, session) {- if (stopping.has(job.id)) return;- stopping.add(job.id); stopErrors.delete(job.id); render(); report();- try {- const response = await agentPost(api, '/freevideo/agent/activity/cancel', {id: job.id});- if (!response.ok) throw await requestError(response);- } catch (error) {- stopping.delete(job.id);- stopErrors.set(job.id, {session, text: t('Could not stop "' + jobName(job, t) + '": ', '没有停止“' + jobName(job, t) + '”:') + reason(error)});- }+ async function cancelJobs(ids) {+ if (!ids.length) { say(t('No tasks are running.', '当前没有在运行的任务')); return; }+ ids = ids.filter(id => !stopping.has(id));+ if (!ids.length) return;+ say(t('Stopping…', '正在停止…'));+ ids.forEach(id => stopping.add(id)); render(); report();+ const results = await Promise.all(ids.map(id => retryAgentPost(api, '/freevideo/agent/activity/cancel', {id})));+ results.forEach((response, index) => { if (!response?.ok) stopping.delete(ids[index]); });+ if (results.some(response => !response?.ok)) say(t('Stopping failed after a retry. If still running, click again.', '停止没成功,已重试;仍在运行请再点一次'));+ else say('');if (!stopped) { render(); report(); void poll(); }}async function retryJob(key, text) {@@ -601,10 +623,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()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 session = state.session;- const stop = press('fv-chat-stop', null, () => void cancelJob(job, session));- const error = el('p', 'fv-chat-error'); error.setAttribute('role', 'alert');- foot.append(left, stop); info.append(head, middle, foot, error); item.replaceChildren(box, info);+ const stop = press('fv-chat-stop', null, () => void cancelJobs([job.id]));+ foot.append(left, stop); info.append(head, middle, foot); item.replaceChildren(box, info);const said = {};// The number rides on the water, and goes under the line once there is no room left above it.const level = next => {@@ -629,9 +649,9 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()const where = cardLine(said, next, t);part.textContent = cells.length ? t(`Part ${block.index} / ${block.total}`, `第 ${block.index} / ${block.total} 段`) : where;step.textContent = cells.length ? where : '';- error.textContent = stopErrors.get(next.id)?.text || ''; error.hidden = !error.textContent;- const going = stopping.has(next.id);- stop.disabled = going; stop.textContent = going ? t('Stopping', '正在停止') : t('Stop', '停止');+ const going = stopping.has(next.id) || next.status === 'cancelling';+ stop.disabled = going; stop.textContent = going ? t('Stopping…', '正在停止…') : t('Stop', '停止');+ stop.setAttribute('aria-busy', String(going));stop.setAttribute('aria-label', t('Stop ', '停止 ') + jobName(next, t));};}@@ -661,6 +681,24 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()if (job.play) {// The video plays inside its frame, with its sound; the line under it follows and can be dragged.let video = null;+ let playing = false, loadRetried = false;+ const playbackFailure = () => {+ if (item.dataset.mode !== 'done') return;+ playback.textContent = t('Cannot play right now. Open it in Creations.', '暂时播放不了,可在作品库中打开'); playback.hidden = false;+ show.textContent = t('Open in Creations', '在作品库打开'); if (!show.parentNode) foot.append(show);+ if (!foot.parentNode) info.append(foot);+ };+ const playback = el('p', 'fv-chat-playback'); playback.hidden = true; info.append(playback);+ const play = async () => {+ if (playing) return;+ playing = true; box.dataset.loading = 'true';+ try { await video.play(); playback.hidden = true; }+ catch {+ if (loadRetried) playbackFailure();+ else try { loadRetried = true; video.load(); await video.play(); playback.hidden = true; } catch { playbackFailure(); }+ }+ finally { playing = false; delete box.dataset.loading; }+ };const toggle = press('fv-chat-play', null, () => {if (!video) {video = el('video'); video.playsInline = true; video.src = api.apiURL(job.play);@@ -669,10 +707,15 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()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(); };+ video.onerror = () => {+ if (playing) return;+ if (loadRetried) { playbackFailure(); return; }+ loadRetried = true; video.load(); void play();+ };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();+ if (video.paused || video.ended) { loadRetried = false; void play(); } else video.pause();});const label = () => toggle.setAttribute('aria-label', (box.dataset.playing === 'true' ? t('Pause ', '暂停 ') : t('Play ', '播放 ')) + jobName(job, t));label(); box.append(toggle);@@ -693,27 +736,43 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()return {element: item, update(job, {latest, retry, key}) {// Jobs without a picture (a check, a prompt) are one quiet line while they run, and nothing after.// A picture takes seconds: the same quiet line while it is made, then the picture.- const card = VIDEOS.includes(job.kind || 'generate') || (job.kind === 'image' && !WORKING.includes(job.status));+ const card = VIDEOS.includes(job.kind || 'generate') || (['image', 'production', 'cast'].includes(job.kind) && !WORKING.includes(job.status));const next = card ? jobMode(job) + (jobMode(job) === 'done' ? `:${job.play}:${job.thumbnail}:${job.work}`- : jobMode(job) === 'failed' ? `:${job.error?.code}:${job.error?.report_id}` : '')+ : jobMode(job) === 'failed' && job.kind === 'image' ? `:${job.error?.code}:${job.error?.report_id}` : ''): 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 (job.kind === 'image') item.dataset.kind = 'image'; else delete item.dataset.kind;- if (next !== 'working') { stopping.delete(job.id); stopErrors.delete(job.id); }+ if (!WORKING.includes(job.status)) 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.startsWith('failed')) {- if (job.kind === 'image') {- const host = el('div');- renderImageFailure(host, {error: job.error?.code || 'generation_failed', report_id: job.error?.report_id}, t,- {productVersion, fetchApi: (path, options) => api.fetchApi(path, options)});- item.replaceChildren(host);- } else item.replaceChildren(el('span', null, t('Could not generate', '没有生成出来')));+ else if (next === 'quiet') {+ const label = el('span'); item.replaceChildren(el('span', 'fv-chat-dots'), label);+ apply = next => { label.textContent = stopping.has(next.id) || next.status === 'cancelling'+ ? t('Stopping', '正在停止') : t(...(QUIET[next.kind] || ['Working', '进行中'])); };+ }+ else if (next === 'stopped' && (!job.error || job.kind === 'image')) { item.replaceChildren(el('span', null, t('Stopped', '已停止'))); apply = null; }+ else if (next.startsWith('failed') && job.kind === 'image') {+ // Picture failures name their step with the picture's own report card.+ const host = el('div');+ renderImageFailure(host, {error: job.error?.code || 'generation_failed', report_id: job.error?.report_id}, t,+ {productVersion, fetchApi: (path, options) => api.fetchApi(path, options)});+ item.replaceChildren(host);if (retry) item.append(press('fv-chat-retry', t('Retry', '重试'), retry));apply = null;+ }+ else if (next === 'failed' || next === 'stopped') {+ const reason = el('p'), actions = el('div', 'fv-chat-actions fv-actions'), links = el('div', 'fv-result-links');+ let current = job;+ const diagnostic = createDiagnosticReportControl(t, {api, tip: true, version: productVersion,+ label: () => t('Download diagnostic report', '下载诊断报告'),+ fallback: () => new Blob([JSON.stringify(createErrorReport({error: current.error, exception_type: current.error?.code,+ details: current.error?.request_id}, {stage: 'execution'}), null, 2)], {type: 'application/json'})});+ actions.append(diagnostic.report);+ if (retry) actions.append(press('fv-chat-retry', t('Retry', '重试'), retry));+ links.append(actions); item.replaceChildren(reason, links);+ apply = next => { current = next; reason.textContent = failureReason(next, t);+ diagnostic.updateReport({report_id: next.report_id}); };} else { item.replaceChildren(); apply = null; }}apply?.(job, latest);@@ -771,7 +830,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()item.setAttribute('role', 'status'); item.setAttribute('aria-label', t('Thinking', '正在思考')); item.append(mark);return {element: item, update() {}};}- const MAKE = {error: () => { const element = el('li', 'fv-chat-error'); element.setAttribute('role', 'alert'); return {element, update(text) { element.textContent = text; }}; }, hello, examples, dots, user: () => message('user'), agent: () => message('agent'), job: jobCard, confirm: confirmCard};+ 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));@@ -792,12 +851,16 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()const text = lastUser?.text;const key = cardKey(state.session, job.id);wanted.push([`s:${entry.seq}`, 'job', job, {latest: entry === finished, key, retry: text ? () => retryJob(key, text) : null}]);+ const failure = state.failures[entry.entity];+ if (failure) wanted.push([`e:${entry.seq}`, 'job', failure]);+ } else if (entry.type === 'production' || entry.type === 'cast') {+ const failure = state.failures[entry.entity];+ if (failure) wanted.push([`s:${entry.seq}`, 'job', failure]);} else wanted.push([`s:${entry.seq}`, 'confirm', entry]);}for (const entry of localPending) 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.- for (const [id, error] of stopErrors) if (error.session !== state.session) wanted.push([`stop:${id}`, 'error', error.text]);const tail = localPending.at(-1) || entries.at(-1);if (tail?.type !== 'job' && tail?.type !== 'confirm' && (localPending.some(entry => !entry.error) || !tail?.error && tail?.role === 'user') && state.agent.connected === true&& (state.agent.listening !== false || tail.taken === true)) wanted.push(['dots', 'dots', null]);@@ -814,7 +877,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()const sendable = sendingAllowed();input.disabled = state.agent.connected !== true || creating || !!selectedSession && selectedSession !== state.session;input.placeholder = state.agent.connected === true && !sendable ? t('Ask your agent to continue', '请在 Agent 里让它继续') : t('Message the agent…', '对 Agent 说…');- sendButton.disabled = !sendable || draftSending() || !input.value.trim();+ sendButton.disabled = !composeAllowed() || draftSending() || !input.value.trim();if (focusSession === state.session && focusSession && !input.disabled && active()) { focusSession = null; input.focus(); }if (stick) { pinned = true; scroller.scrollTop = scroller.scrollHeight; down.hidden = true; }else if (log.children.length > before) down.hidden = false;@@ -847,34 +910,63 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()stopping: bulkStopping, any: state.items.size > 0 || pending.some(entry => entry.session === state.session)});}function acknowledge(entry) {- entry.acknowledged = true; entry.error = null;+ entry.acknowledged = true; entry.error = null; entry.automatic = false;+ if (entry.session === state.session) say('');unsaidSessions.delete(entry.session);if (entry.draft && drafts.get(entry.session) === entry.draft) {drafts.delete(entry.session);if (draftSession === entry.session) { input.value = ''; grow(); }}}- async function send(text, original = null, draft = null) {+ const waitingNotice = code => (code ? code === 'not_listening' : state.agent.connected === true)+ ? t('Not sent: Agent is not listening yet. It will send automatically once listening resumes.', '没发出去:Agent 还没在听,继续监听后会自动发送')+ : t('Not sent: Agent is not connected. It will send automatically once connected.', '没发出去:Agent 还没连接,连接后会自动发送');+ async function send(text, original = null, draft = null, automatic = false) {text = String(text).trim();- original ||= pending.find(entry => entry.session === (state.session ?? null) && entry.text === text && (entry.error || entry.sending));- if (!text || !sendingAllowed() || original?.sending || original && original.session !== state.session) return false;+ original ||= pending.find(entry => entry.session === (state.session ?? null) && entry.text === text && (entry.error || entry.sending || entry.automatic));+ if (!text || original?.sending || original && original.session !== state.session) return false;+ if (!inSelectedChat()) {+ say(creating ? t('Creating a new chat…', '正在新建对话…') : t('Loading this chat. Please send again shortly.', '正在读取对话,请稍后再发一次'));+ return false;+ }const entry = original || {id: newId(), text, session: state.session ?? null, draft};if (draft) entry.draft = draft;if (!original) pending.push(entry);- entry.sending = true; entry.retried = !!original; entry.error = null; render(true); report();+ if (!automatic) entry.attempts = 0;+ if (!sendingAllowed()) {+ entry.automatic = true; entry.error = waitingNotice();+ say(entry.error); render(); report(); return false;+ }+ entry.sending = true; entry.retried = !!original; entry.error = null; entry.automatic = false; render(true); report();try {const body = {id: entry.id, text: entry.text};if (conversations.supported === true && entry.session) body.session = entry.session;- const response = await agentPost(api, '/freevideo/agent/chat', body);- if (!response.ok) throw await requestError(response);- const value = await response.json().catch(() => ({}));- acknowledge(entry);- if (!entry.session && value.session) entry.session = value.session;- if (!stopped) { void poll(); void readConversations(true); }- return true;- } catch (error) {+ entry.attempts++;+ const response = await retryAgentPost(api, '/freevideo/agent/chat', body, {retry: async response => {+ if (stopped || entry.acknowledged || sendRefused(await sendError(response), response) || entry.attempts >= SEND_ATTEMPTS) return null;+ entry.attempts++; return body;+ }});if (entry.acknowledged) return true;- entry.error = t('Could not send: ', '没有发送成功:') + reason(error);+ if (response?.ok) {+ const value = await response.json().catch(() => ({}));+ acknowledge(entry);+ if (!entry.session && value.session) entry.session = value.session;+ if (!stopped) { void poll(); void readConversations(true); }+ return true;+ }+ const error = await sendError(response), refused = sendRefused(error, response);+ const waiting = !refused && (WAIT_FOR_AGENT.includes(error?.code) || !error && state.agent.connected !== true);+ const exhausted = entry.attempts >= SEND_ATTEMPTS;+ entry.automatic = waiting && !exhausted;+ const explanation = refused || error && !waiting ? t('Not sent: ', '没发出去:') + failureReason({error}, t)+ : exhausted ? t('Not sent: tried 3 times. Automatic sending stopped; please send again.', '没发出去:已尝试 3 次,已停止自动发送,请再发一次')+ : waiting ? waitingNotice(error?.code) : t('The network is unstable. Retried; please send again.', '网络不稳,已重试,请再发一次');+ entry.error = waiting ? explanation : t('Could not send: ', '没有发送成功:') + (error?.message || explanation);+ if (entry.session === state.session) {+ if (waiting && error?.code === 'not_connected') state = {...state, agent: {connected: false, name: null}};+ if (waiting && error?.code === 'not_listening') state = {...state, agent: {...state.agent, listening: false}};+ say(explanation);+ }return false;} finally {entry.sending = false;@@ -886,9 +978,19 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()// At most five lines; the box scrolls after that.const line = (typeof getComputedStyle === 'function' && parseFloat(getComputedStyle(input).lineHeight)) || 22;input.style.height = `${Math.min(input.scrollHeight, Math.round(line * 5) + 14)}px`;- sendButton.disabled = !sendingAllowed() || draftSending() || !input.value.trim();+ sendButton.disabled = !composeAllowed() || draftSending() || !input.value.trim();}- input.addEventListener('input', () => { saveDraft(); grow(); if (unsaidSessions.has(draftSession)) renderConversations(); });+ input.addEventListener('input', () => {+ saveDraft();+ // Editing a queued draft cancels its automatic delivery. Its original message remains available for manual retry.+ for (const entry of pending) if (entry.automatic && entry.session === draftSession && entry.draft !== drafts.get(draftSession)) {+ entry.automatic = false;+ entry.error = t('Not sent: the queued draft changed. Retry to send the original.', '没发出去:排队草稿已修改,原消息需手动重试');+ say('');+ }+ if (!input.value.trim()) say('');+ grow(); if (unsaidSessions.has(draftSession)) renderConversations();+ });// 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;@@ -898,7 +1000,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()event.preventDefault();const text = input.value;const draft = saveDraft();- if (!text.trim() || !sendingAllowed() || draftSending()) return;+ if (!text.trim() || !composeAllowed() || draftSending()) return;const failed = pending.find(entry => entry.session === state.session && entry.draft === draft && entry.error);void send(text, failed, draft);});@@ -968,6 +1070,11 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()const idle = state.agent.connected !== true && !state.active;timer = setTimeout(poll, (idle ? Math.max(interval, 3000) : interval) * Math.min(4, 1 + failures));render(); report();+ if (sendingAllowed()) for (const entry of [...pending]) {+ if (entry.session !== state.session || !entry.automatic || entry.sending || entry.acknowledged) continue;+ await send(entry.text, entry, entry.draft, true);+ if (!sendingAllowed() || stopped) break;+ }}// Between reads the estimate keeps moving, on the cards and in the page's header alike.const moving = setInterval(() => {@@ -990,10 +1097,9 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()},async stopAll() {if (bulkStopping) return;- const jobs = new Map(Object.values(state.jobs).filter(job => WORKING.includes(job.status)).map(job => [job.id, {job, session: state.session}]));- for (const id of away?.ids || []) if (!jobs.has(id)) jobs.set(id, {job: away.jobs[id], session: away.session});+ const ids = [...new Set([...Object.values(state.jobs).filter(job => WORKING.includes(job.status)).map(job => job.id), ...(away?.ids || [])])];bulkStopping = true; report();- try { await Promise.all([...jobs.values()].map(({job, session}) => cancelJob(job, session))); }+ try { await cancelJobs(ids); }finally { bulkStopping = false; if (!stopped) { report(); void poll(); } }},stop() { closeMenu(); stopped = true; dismissImage?.(); closed.abort(); clearInterval(moving); clearTimeout(timer); timer = null;diff --git a/web/generation_progress.js b/web/generation_progress.jsindex e6314f0..e398d2a 100644--- a/web/generation_progress.js+++ b/web/generation_progress.js@@ -1,5 +1,5 @@// One whole-video estimate and the same five rows in Studio and the node view.-import { saveReport } from './report_issue.js';+import { saveReport, reportIssue, showReportTip } from './report_issue.js';const css = document.createElement('link');css.rel = 'stylesheet'; css.href = new URL('./generation_progress.css', import.meta.url).href;document.head.append(css);@@ -349,6 +349,59 @@ export function estimatedFraction(state, overall, stateAge, overallAge) {return candidate;}+// The video's report download, also used by Agent failure cards. A task that+// failed before creating an engine report supplies the shared redacted summary.+export function createDiagnosticReportControl(t, {api = null, fallback = null, tip = false, version = null,+ label = () => t('Download report', '下载报告')} = {}) {+ if (tip) {+ const href = new URL('./result_actions.css', import.meta.url).href;+ if (![...document.head.querySelectorAll('link')].some(link => link.href === href)) {+ const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = href; document.head.append(style);+ }+ }+ const report = el('button', 'fv-report-download fv-quiet'); report.type = 'button'; report.hidden = true;+ let reportId = null, revision = 0;+ report.textContent = label();+ function updateReport(message) {+ if (message.new_request === true || message.overall?.reset === true || message.reset === true && !message.phase) {+ reportId = null; revision++; report.hidden = true;+ }+ if (typeof message.report_id === 'string' && /^[a-f0-9]{32}$/.test(message.report_id)) {+ if (reportId !== message.report_id) { revision++; report.disabled = false; report.textContent = label(); }+ reportId = message.report_id;+ }+ report.hidden = !reportId && !fallback;+ return reportId;+ }+ async function fetchReport() {+ if (reportId) {+ const path = `/freevideo/report/${reportId}`;+ const response = await (api ? api.fetchApi(path) : fetch(path));+ if (!response.ok) throw new Error('Report unavailable');+ return response.blob();+ }+ if (fallback) return fallback();+ throw new Error('Report unavailable');+ }+ async function downloadReport() { saveReport(await fetchReport()); }+ report.onclick = async () => {+ if (report.disabled || report.hidden) return;+ const current = revision;+ report.disabled = true; report.textContent = t('Preparing report…', '正在整理报告…');+ try {+ await downloadReport();+ if (current === revision) {+ report.textContent = label();+ if (tip && report.isConnected) showReportTip(report.parentElement, report, t, {mode: 'downloaded',+ submit: () => reportIssue(fetchReport, typeof version === 'function' ? version() : version, {save: false})});+ }+ } catch {+ if (current === revision) report.textContent = t('Report unavailable · retry', '报告暂不可用 · 重试');+ } finally { if (current === revision) report.disabled = false; }+ };+ return {report, updateReport, fetchReport, downloadReport, hasReport: () => reportId !== null};+}+export function createGenerationProgress(t, now = () => Date.now(), {compact = false, api = null, onLayout = null} = {}) {const element = el('section', 'fv-generation-progress'); element.hidden = true;if (compact) element.classList.add('fv-generation-compact');@@ -422,42 +475,8 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = fconst fraction = value => Math.min(1, Math.max(0, value));const newRequest = message => message.new_request === true || message.overall?.reset === true|| (message.reset === true && !message.phase);- const report = el('button', 'fv-report-download fv-quiet'); report.type = 'button'; report.hidden = true;- let reportId = null;- const reportLabel = () => t('Download report', '下载报告');- report.textContent = reportLabel();- function updateReport(message) {- if (newRequest(message)) { reportId = null; report.hidden = true; }- if (typeof message.report_id === 'string' && /^[a-f0-9]{32}$/.test(message.report_id)) {- if (reportId !== message.report_id) { report.disabled = false; report.textContent = reportLabel(); }- reportId = message.report_id; report.hidden = false;- }- // The saved video's request record is different from the redacted- // diagnostic download. Keep this token available after completion;- // only a new request clears it.- return reportId;- }- // The redacted diagnostic export; throws when it is unavailable.- async function fetchReport() {- const id = reportId;- if (!id) throw new Error('Report unavailable');- const path = `/freevideo/report/${id}`;- const response = await (api ? api.fetchApi(path) : fetch(path));- if (!response.ok) throw new Error('Report unavailable');- return response.blob();- }- async function downloadReport() { saveReport(await fetchReport()); }- report.onclick = async () => {- if (!reportId || report.disabled) return;- const id = reportId;- report.disabled = true; report.textContent = t('Preparing report…', '正在整理报告…');- try {- await downloadReport();- if (id === reportId) report.textContent = reportLabel();- } catch {- if (id === reportId) report.textContent = t('Report unavailable · retry', '报告暂不可用 · 重试');- } finally { if (id === reportId) report.disabled = false; }- };+ const diagnostic = createDiagnosticReportControl(t, {api});+ const {report, updateReport, fetchReport, downloadReport} = diagnostic;const hasCount = value => Number.isInteger(value.total) && value.total > 0 && Number.isInteger(value.done)&& value.done >= 0 && value.done <= value.total;@@ -513,7 +532,7 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = fconst threshold = Math.max(floor, valid(typical) ? 2 * typical : 0);const shown = !ended && age >= threshold;const wasShown = !stall.hidden;- const hasReport = reportId !== null;+ const hasReport = diagnostic.hasReport();// The separate notice never adds another clock or blocks the run.if (shown && (stall.hidden || hasReport !== stallHasReport)) {const first = t('No progress for a while. Generation is still running, so you can keep waiting.',@@ -987,6 +1006,6 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = fmini_fraction: visible && !mini.hidden && miniMode === 'determinate' ? miniShown : null,mini_shimmer: visible && !mini.hidden && miniShimmer};}- return {element, stall, report, updateReport, fetchReport, downloadReport, hasReport: () => reportId !== null, update, hide, dispose: hide,+ return {element, stall, report, updateReport, fetchReport, downloadReport, hasReport: diagnostic.hasReport, update, hide, dispose: hide,noticeCount: () => trims.size, stallShown: () => !stall.hidden, percentShown: () => !heading.hidden, snapshot};}