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.

Chat: a failed card runs its own request again, a stopped video goes on from its finished parts...

Bowen Xue13fe7cf9e4dc
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
index 28ff01d..97d362e 100644
--- a/freevideo_engine/agent/errors.py
+++ b/freevideo_engine/agent/errors.py
@@ -295,6 +295,7 @@ FAILURE_REASONS_ZH = {
'not_found': '找不到这次任务或素材',
'source_missing': '接续所需的上一段视频已经不在',
'chain_missing': '接续所需的生成记录已经不在',
+ 'not_resumable': '此任务无法继续生成',
'chain_unavailable': '分段生成服务还没有启动',
'continuation_unavailable': '当前生成方式不支持接续视频',
'join_failed': '片段已生成,但拼接成片时出错',
@@ -345,6 +346,7 @@ FAILURE_REASONS_EN = {
'not_found': 'This task or media file cannot be found',
'source_missing': 'The previous video needed to continue is no longer available',
'chain_missing': 'The generation record needed to continue is no longer available',
+ 'not_resumable': 'This task cannot be continued',
'chain_unavailable': 'The part-by-part generation service has not started yet',
'continuation_unavailable': 'The current generation mode cannot continue a video',
'join_failed': 'The parts were generated, but joining them into one video failed',
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
index c6706da..05e87a5 100644
--- a/freevideo_engine/agent/guide.py
+++ b/freevideo_engine/agent/guide.py
@@ -243,6 +243,10 @@ RULES = [
'edited. When the user tells you to stop, stop: cancel what you started and start nothing new. '
'When cancelled_by is "user", the user stopped this job on the page and the page already shows it as stopped: '
'send no message about it, and do not retry or resume it unless they ask.',
+ 'A user message with revises=N replaces message N and everything you wrote after it: understand it afresh '
+ 'from the new message. The jobs started for the old one are already stopped; do not continue them. '
+ 'A control event with action "retried" means the user ran job refs.job again on the page: do not start it '
+ 'again yourself; follow it like a job you started.',
'Cast before you shoot. Search the cast library first. Use the card the user named, or one that clearly '
'matches; ask if you are unsure. Create a card only when none fits: from the user\'s photos if they gave any, '
'otherwise make its reference pictures with POST /cast/{id}/generate. '
@@ -287,6 +291,8 @@ RULES_ZH = [
'只在 FreeVideo 内工作,不要改动本机的其他文件,不要撤销用户做的修改。'
'用户要求停止时,取消你启动的任务,不再启动新任务。'
'cancelled_by 为 "user" 时,表示用户在页面上停止了该任务,页面已显示已停止:不要为此发消息;除非用户要求,否则不要重试或恢复。',
+ '带 revises=N 的用户消息取代 seq N 那条及其之后你写的内容,按新消息重新理解;为旧消息开的任务已被停掉,不要续旧的。'
+ 'action 为 "retried" 的 control 事件表示用户在页面上重新运行了 refs.job 这个任务:不要自己再提交一次,像你自己提交的任务一样跟进。',
'先选角,再拍摄。先搜索角色库,使用用户指定的卡片或明确符合要求的卡片;拿不准时询问用户。'
'只有找不到合适卡片时才新建:用户提供了照片就用照片,否则通过 POST /cast/{id}/generate 生成参考图。'
'开拍前用一句话告诉用户选角结果。后续镜头使用卡片当前的图片。保留你创建的卡片,方便以后拍片复用。',
diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py
index 7513077..d5a70ce 100644
--- a/freevideo_engine/agent/jobs.py
+++ b/freevideo_engine/agent/jobs.py
@@ -1098,6 +1098,51 @@ class Jobs:
replace(original, row)
return (original, False) if replay_result else original
+ def again(self, row):
+ """How a conversation card offers a finished job again, or None for one that runs or succeeded.
+
+ 'continue' resumes a video and keeps its finished parts, 'retry' runs the same request from its start,
+ and 'resend' leaves it to the agent: the page says the user's words again. A video the user stopped only
+ goes on from its finished parts: nothing starts it over."""
+ if row['status'] not in ('failed', 'interrupted', 'cancelled'):
+ return None
+ stopped = row['kind'] in ('generate', 'assemble') and bool(user_stop_notice(row))
+ parent = row.get('parent') or {}
+ if parent.get('production') or parent.get('cast'):
+ return None if stopped else 'resend'
+ if row['kind'] == 'image':
+ return 'retry'
+ if row['kind'] != 'generate' or row['spec'].get('refine_from'):
+ return None if stopped else 'resend'
+ try:
+ blocks = self.chain(row['chain_id'])['blocks'] if row.get('chain_id') else ()
+ except (KeyError, JobError, OSError, ValueError):
+ blocks = ()
+ if any(block.get('state') == 'done' for block in blocks):
+ return 'continue'
+ return None if stopped else 'retry'
+
+ def run_again(self, identity):
+ """The user's Retry on a conversation card: the same job again, in the same card."""
+ row = self.get(identity)
+ way = self.again(row)
+ if way in ('continue', 'retry') and row['kind'] == 'generate':
+ return self.resume(identity)
+ if way != 'retry':
+ raise chain_error('not_resumable', 'Only failed, interrupted or cancelled videos and pictures run again.',
+ 'Say it to the agent again.')
+ with self.lock:
+ if row['status'] not in ('failed', 'interrupted', 'cancelled'):
+ raise chain_error('not_resumable', 'This picture is already running.', 'Wait for it to finish.')
+ # A picture has nothing finished to keep: its request, seed included, starts over.
+ dropped = ('error', 'result', '_cancel', 'cancelled_by', '_image', '_phase', 'waiting_for')
+ candidate = deepcopy({k: v for k, v in row.items() if k not in dropped})
+ candidate.update(status='waiting', started_at=None, finished_at=None, updated_at=self.clock(),
+ attempt=row.get('attempt', 1) + 1)
+ self.save(candidate)
+ replace(row, candidate)
+ return row
+
def queue_view(self):
"""Describe ownership/order without exposing studio workflows or prompts."""
runner = self.port.chain_runner()
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index 0616aab..3c6f021 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -6,6 +6,7 @@ to ComfyUI without a CORS preflight that ComfyUI does not grant.
"""
import asyncio
import base64
+from datetime import datetime
import binascii
import json
import hashlib
@@ -27,7 +28,7 @@ from . import private_file
from . import spec as specs
from .. import tiers as quality_tiers
from . import schema as contract, errors, access
-from .jobs import ACTIVE, DONE, JobError, Jobs, chain_error, library_view
+from .jobs import ACTIVE, DONE, JobError, Jobs, chain_error, library_view, user_stop_notice
PREFIX = '/freevideo/agent/v1'
from .whitebox import MAX_VIDEO_BYTES as MAX_WHITEBOX_VIDEO
@@ -880,6 +881,11 @@ def register():
estimate = jobs.estimate(row)
if estimate:
card['progress']['estimate'] = estimate
+ again = jobs.again(row)
+ if again:
+ card['again'] = again
+ # The user stopped it here: a video card says so, with no report to download.
+ card.update({k: v for k, v in user_stop_notice(row).items() if k == 'cancelled_by'})
return card
def chat_fold(store, sid):
@@ -899,7 +905,8 @@ def register():
base = dict(seq=row['seq'], at=row['at'], type=row['type'])
if row['type'] == 'message':
fold['items'].append(dict(base, role='user' if row['by'] == 'user' else 'agent', text=row['text'],
- **({'attachments': row['attachments']} if row.get('attachments') else {})))
+ **({'attachments': row['attachments']} if row.get('attachments') else {}),
+ **({'revises': row['revises']} if row.get('revises') else {})))
if row['by'] == 'user':
fold['said'] = row['text']
if row.get('mid'):
@@ -1097,6 +1104,30 @@ def register():
raise error from None
return result
+ def rewrite_from(store, sid, fold, said):
+ """The user rewrites their last message: stop what was started after it and decline what it still asks.
+
+ Jobs and films begun before it keep running. Raises when a job cannot be stopped; nothing is said then."""
+ since = datetime.fromisoformat(said['at'].replace('Z', '+00:00')).timestamp()
+ for row in jobs.active():
+ # Where the job shows in the conversation; one not shown yet goes by when it was made.
+ place = fold['jobs'].get(row['id'])
+ if not (place > said['seq'] if place is not None else row.get('session') == sid and row['created_at'] >= since):
+ continue
+ try:
+ jobs.cancel(row['id'], by='user')
+ except KeyError:
+ pass # Gone already.
+ for item in fold['items']:
+ if item['seq'] > said['seq'] and item.get('entity') and fold['entities'].get(item['entity']) == 'production':
+ try:
+ jobs.productions.pause(item['entity'], by='user')
+ except JobError:
+ pass # Finished, stopped or paused already.
+ for identity, item in list(fold['asked'].items()):
+ if item['seq'] > said['seq'] and item['state'] == 'asked':
+ store.append(sid, dict(type='confirm', id=identity, state='declined'), by='user')
+
@routes.post('/freevideo/agent/chat')
@guarded
async def chat_say(request):
@@ -1116,6 +1147,13 @@ def register():
pictures = chat_attachments(value.get('attachments', []))
sid = sid or store.create(client=client, by='user')['id']
fold = fold or chat_fold(store, sid)
+ revised = value.get('revises')
+ if revised is not None:
+ said = [i for i in fold['items'] if i['type'] == 'message' and i['role'] == 'user']
+ if not said or said[-1]['seq'] != revised:
+ raise specs.SpecError(contract.diagnostic('/revises', 'the seq of the last user message (%s)' % (
+ said[-1]['seq'] if said else 'none yet'), revised))
+ rewrite_from(store, sid, fold, said[-1])
if store.stopped(sid):
# Speaking again continues a conversation the user stopped earlier.
store.append(sid, dict(type='control', action='resumed'), by='user')
@@ -1124,6 +1162,8 @@ def register():
message['attachments'] = pictures
if value.get('whitebox'):
message['whitebox'] = True
+ if revised is not None:
+ message['revises'] = revised
row = store.append(sid, message, by='user')
fold['sent'][value['id']] = row['seq']
fold['ids'][row['seq']] = value['id']
@@ -1329,6 +1369,30 @@ def register():
return problem('not_found', 'No such job', 404)
return reply(dict(id=row['id'], status=row['status']))
+ @routes.post('/freevideo/agent/activity/resume')
+ @guarded
+ async def activity_resume(request):
+ # The page's Retry: the same job again, keeping a video's finished parts. Only the page may ask.
+ if request.content_type != 'application/json':
+ return problem('unsupported_media_type', 'Send JSON', 415)
+ value = await body(request)
+ def work():
+ row = jobs.run_again(value['id'])
+ store = work_sessions()
+ if store is not None and row.get('session'):
+ try:
+ # The agent hears it was the user, and does not plan that job again.
+ store.append(row['session'], dict(type='control', action='retried', refs=dict(job=row['id'])), by='user')
+ except JobError:
+ pass # A deleted or full conversation: the job runs again all the same.
+ return dict(id=row['id'], status=row['status'])
+ try:
+ answer = await asyncio.to_thread(work)
+ except KeyError:
+ return problem('not_found', 'No such job', 404)
+ await jobs.tick()
+ return reply(answer)
+
@routes.get('/freevideo/agent/connect')
@guarded
async def connect(request):
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index ca82a58..57fa1ab 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -82,7 +82,7 @@ def chat_request():
# Upload metadata supplied by the page is ignored; only the stored name is authoritative.
attachment = obj(dict(name=CHAT_ATTACHMENT_NAME, original_name={}, width={}, height={}, bytes={}), ('name',))
return obj(dict(text=dict(type='string', minLength=0, maxLength=8000), id=CHAT_ID,
- session=SESSION, whitebox={'type': 'boolean'},
+ session=SESSION, whitebox={'type': 'boolean'}, revises=number(1, integer=True),
attachments=array(attachment, 0, MAX_CHAT_ATTACHMENTS)), ('text', 'id'),
**{'if': {'required': ['attachments'], 'properties': {'attachments': {'minItems': 1}}},
'else': {'properties': {'text': string(8000)}}})
@@ -491,7 +491,8 @@ def contracts(*, local=False):
'Only the user may stop or continue a film (local Studio control)',
body=obj({'ref': REF}), path=obj({'id': PRODUCTION}, ('id',)), auth=False, local=True, idempotent=True)
for suffix, method, body in (('', 'GET', None), ('/session', 'GET', None), ('/activity', 'GET', None),
- ('/activity/cancel', 'POST', obj({'id': JOB}, ('id',))), ('/connect', 'GET', None),
+ ('/activity/cancel', 'POST', obj({'id': JOB}, ('id',))), ('/activity/resume', 'POST', obj({'id': JOB}, ('id',))),
+ ('/connect', 'GET', None),
('/connect/reset', 'POST', EMPTY), ('/chat', 'GET', None), ('/chat/now', 'GET', None),
('/chat/video', 'GET', None), ('/chat/list', 'GET', None), ('/chat/new', 'POST', EMPTY),
('/chat/delete', 'POST', obj({'session': SESSION, 'stop': {'type': 'boolean'}}, ('session',))),
@@ -502,7 +503,7 @@ def contracts(*, local=False):
'session': SESSION}, ('id', 'approve')))):
routes[(method, '/freevideo/agent' + suffix)] = route('Studio Agent controls', body=body, auth=False, local=True,
lan=suffix in ('/chat', '/chat/now', '/chat/confirm', '/chat/abandon', '/chat/list', '/chat/new', '/chat/video',
- '/activity', '/activity/cancel'))
+ '/activity', '/activity/cancel', '/activity/resume'))
# These existing ComfyUI handlers are registered outside the Agent dispatcher.
# /chain is a creation POST; monitoring reads /chains and /chain/{id}.
for suffix in ('/freevideo/progress', '/freevideo/chains', '/freevideo/chain/{id}'):
@@ -908,6 +909,9 @@ def session_event(*, stored=False, agent_only=False):
variants[0]['properties']['mid'] = CHAT_ID
variants[0]['properties']['attachments'] = array(CHAT_ATTACHMENT, 1, MAX_CHAT_ATTACHMENTS)
variants[0]['properties']['whitebox'] = {'type': 'boolean', 'description': 'The user chose a white-model preview for this request.'}
+ variants[0]['properties']['revises'] = dict(number(1, integer=True), description=(
+ 'The user rewrote their message with this seq: this one replaces it and what was written after it. '
+ 'The jobs started for it are stopped.'))
from .errors import ERRORS
variants += [obj(dict(type={'const': 'step'}, id=string(12, pattern=r'^st[0-9a-f]{10}$'),
tool=string(200), summary=text, state=enum(('started', 'done', 'failed')),
@@ -923,8 +927,10 @@ def session_event(*, stored=False, agent_only=False):
digest=string(64, pattern=r'^[0-9a-f]{64}$')),
('type', 'id', 'state'), **{'if': {'properties': {'state': {'const': 'asked'}}},
'then': {'required': ['question']}}),
- obj(dict(type={'const': 'control'}, action=enum(('stopped', 'resumed', 'renamed', 'abandoned')),
- title=dict(type='string', maxLength=120)), ('type', 'action'),
+ obj(dict(type={'const': 'control'}, action=enum(('stopped', 'resumed', 'renamed', 'abandoned', 'retried')),
+ title=dict(type='string', maxLength=120),
+ refs=obj(dict(job=JOB), ('job',), description='retried: the job the user ran again on the page.')),
+ ('type', 'action'),
**{'if': {'properties': {'action': {'const': 'renamed'}}},
'then': {'required': ['title']}, 'else': {'not': {'required': ['title']}}})]
if stored:
diff --git a/freevideo_engine/agent/sessions.py b/freevideo_engine/agent/sessions.py
index a48a481..ec5eca3 100644
--- a/freevideo_engine/agent/sessions.py
+++ b/freevideo_engine/agent/sessions.py
@@ -300,6 +300,8 @@ class Sessions:
raise SessionError('forbidden', 'Only the user may answer a confirmation')
if kind == 'control' and event['action'] != 'renamed' and by != 'user':
raise SessionError('forbidden', 'Only the user may stop or continue')
+ if kind == 'message' and 'revises' in event and by != 'user':
+ raise SessionError('forbidden', 'Only the user may rewrite a message')
result = dict(event, seq=meta['last_seq'] + 1, at=_stamp(self.clock()), by=by)
if client is not None:
result['client'] = client
@@ -516,7 +518,7 @@ class Sessions:
rows = self._events(sid, after, self.max_events)
return [row for row in rows if row['by'] == 'user' and (row['type'] == 'message'
or row['type'] == 'confirm' and row['state'] in ('approved', 'declined')
- or row['type'] == 'control' and row['action'] == 'abandoned')]
+ or row['type'] == 'control' and row['action'] in ('abandoned', 'retried'))]
class Confirmations:
diff --git a/web/autopilot_chat.css b/web/autopilot_chat.css
index 8170657..4b27c03 100644
--- a/web/autopilot_chat.css
+++ b/web/autopilot_chat.css
@@ -202,3 +202,18 @@
.fv-chat-refs{width:max-content;max-width:100%;display:flex;flex-wrap:wrap;gap:6px;justify-content:flex-end;margin:0 0 6px auto;padding:0;list-style:none}
.fv-chat-refs>li{width:96px;height:96px;border-radius:10px;overflow:hidden}
@media(max-width:560px){.fv-chat-refs>li{width:64px;height:64px}}
+
+/* The newest sentence can be rewritten in place. Its Edit row keeps its height, so showing it moves nothing. */
+.fv-chat-edit-row{display:flex;justify-content:flex-end;min-height:28px;margin-top:4px}
+.fv-chat-edit-row[hidden]{display:none}
+.fv-studio .fv-chat-log .fv-chat-edit{min-height:0;padding:4px 8px;border:0;border-radius:7px;background:none;color:var(--fv-muted);font-size:12.5px;font-weight:var(--fv-regular);opacity:0;transition:opacity var(--fv-quick)}
+.fv-studio .fv-chat-log .fv-chat-edit:hover:not(:disabled){background:var(--fv-raised);color:var(--fv-ink)}
+.fv-chat-me:is(:hover,:focus-within) .fv-chat-edit,.fv-studio .fv-chat-log .fv-chat-edit:focus-visible{opacity:1}
+@media(hover:none),(max-width:480px){.fv-studio .fv-chat-log .fv-chat-edit{opacity:1}}
+.fv-chat-me[data-editing=true]{width:min(500px,88%)}
+.fv-studio .fv-chat-log .fv-chat-edit-box{box-sizing:border-box;display:block;width:100%;min-height:44px;max-height:40vh;padding:10px 14px;border:1px solid var(--fv-accent-dim);border-radius:14px;background:#1d3550;color:var(--fv-ink);font:inherit;font-size:14.5px;line-height:22px;resize:none;outline:none;overflow-y:auto}
+.fv-chat-me>.fv-chat-edit-actions{margin-top:8px;justify-content:flex-end}
+.fv-chat-edit-actions>.fv-chat-error{text-align:right}
+.fv-studio .fv-chat-log .fv-chat-edit-send{border-color:transparent;background:var(--fv-accent);color:var(--fv-bg)}
+.fv-studio .fv-chat-log .fv-chat-edit-send:hover:not(:disabled){background:var(--fv-accent-hover)}
+@media(max-width:480px){.fv-studio .fv-chat-log .fv-chat-edit-box{font-size:16px}}
diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js
index 373d6d8..fc6e7fe 100644
--- a/web/autopilot_chat.js
+++ b/web/autopilot_chat.js
@@ -45,6 +45,8 @@ const WORKING = ['running', 'queued', 'waiting', 'cancelling'], VIDEOS = ['gener
const QUIET = {vlm: ['Checking', '检查中'], enhance: ['Enhancing prompt', '增强提示词']};
// Other jobs without a card keep their line while they run, and a finished one still marks the tab.
const BUSY = {music: ['Making music', '制作配乐']};
+// A failed card's one action: go on keeping the finished parts, run the same request again, or say the words again.
+const AGAIN = {continue: ['Continue generating', '继续生成'], retry: ['Retry', '重试'], resend: ['Send again', '再发一次']};
const WHITEBOX = {
generate: ['Generate video', '生成视频'], edit: ['Edit prompt', '改描述'], decline: ['Skip', '跳过'],
approved: ['Approved', '已确认'], superseded: ['Replaced', '已被替换'], declined: ['Skipped', '已跳过'],
@@ -825,13 +827,71 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
try { await send(text); }
finally { retrying.delete(key); if (!stopped) render(); }
}
+ // Why a card's job did not go on. A refusal turns the card to saying the words again; a lost connection keeps its button.
+ const fallbacks = new Map();
+ const againWay = (job, key) => fallbacks.get(key)?.resend ? 'resend' : job.again || 'resend';
+ async function resumeJob(key, job) {
+ if (retrying.has(key)) return;
+ retrying.add(key); fallbacks.delete(key); render();
+ const lost = {reason: t('Connection lost. Try again.', '连接中断,请重试。'), resend: false};
+ try {
+ const response = await dataLayer.resume(job.id);
+ if (!response?.ok) fallbacks.set(key, response ? {reason: failureReason({error: await sendError(response)}, t), resend: true} : lost);
+ } catch { fallbacks.set(key, lost); }
+ finally { retrying.delete(key); if (!stopped) { render(); report(); void poll(); } }
+ }
+ function againJob(key, job, text) {
+ if (againWay(job, key) === 'resend') { if (text) void retryJob(key, text); }
+ else void resumeJob(key, job);
+ }
// ---- one entry of the conversation each ----
function message(role) {
const item = el('li', role === 'user' ? 'fv-chat-me' : 'fv-chat-ai'), text = el('p'); item.append(text);
let status = null, error = null, retry = null, report = null, shown = '';
- return {element: item, update(entry) {
- text.textContent = entry.text; text.hidden = !entry.text && !!entry.attachments?.length;
+ let current = null, editRow = null, editButton = null, editor = null;
+ // The newest sentence opens in place; the box at the bottom keeps its draft.
+ function openEditor() {
+ if (editor || !current) return;
+ const box = el('textarea', 'fv-chat-edit-box'), note = el('span', 'fv-chat-error');
+ const actions = el('div', 'fv-chat-actions fv-chat-edit-actions');
+ const cancel = press('fv-chat-edit-cancel', t('Cancel', '取消'), () => closeEditor());
+ const go = press('fv-chat-edit-send', t('Send', '发送'), () => void submit());
+ note.setAttribute('role', 'alert'); note.hidden = true;
+ box.value = current.text; box.rows = 1; box.setAttribute('aria-label', t('Edit message', '编辑消息'));
+ actions.append(note, cancel, go);
+ editor = {box, actions, note, cancel, go, target: current, id: newId(), busy: false};
+ const fit = () => { box.style.height = 'auto'; box.style.height = `${box.scrollHeight + 2}px`; go.disabled = editor.busy || !box.value.trim(); };
+ box.addEventListener('input', fit);
+ listenDialogKey(box, 'keydown', event => {
+ if (event.key === 'Escape' && !editor.busy) { event.preventDefault(); event.stopPropagation(); closeEditor(); return; }
+ if (event.key !== 'Enter' || event.shiftKey || event.isComposing || event.keyCode === 229) return;
+ event.preventDefault(); void submit();
+ });
+ item.dataset.editing = 'true'; text.hidden = true; editRow.hidden = true;
+ text.after(box, actions);
+ fit(); box.focus(); box.setSelectionRange?.(box.value.length, box.value.length);
+ }
+ function closeEditor() {
+ if (!editor) return;
+ editor.box.remove(); editor.actions.remove(); editor = null;
+ delete item.dataset.editing; text.hidden = false; if (editRow) editRow.hidden = false;
+ if (current) text.textContent = current.text;
+ }
+ async function submit() {
+ const words = editor?.box.value.trim();
+ if (!words || editor.busy) return;
+ const open = editor;
+ open.busy = open.cancel.disabled = open.go.disabled = true; open.note.hidden = true;
+ const problem = await rewrite(open.target, words, open.id);
+ if (editor !== open) return;
+ open.busy = open.cancel.disabled = false; open.go.disabled = false;
+ if (problem) { open.note.textContent = problem; open.note.hidden = false; open.box.focus(); }
+ else { current = {...current, text: words}; closeEditor(); }
+ }
+ return {element: item, update(entry, {editable = false} = {}) {
+ current = entry;
+ if (!editor) { text.textContent = entry.text; text.hidden = !entry.text && !!entry.attachments?.length; }
const names = (entry.attachments || []).map(picture => picture.name).join('|');
if (names !== shown) {
shown = names; item.querySelector('.fv-chat-refs')?.remove();
@@ -842,6 +902,12 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}
}
if (role !== 'user') return;
+ if ((editable || editor) && !editRow) {
+ editRow = el('div', 'fv-chat-edit-row'); editButton = press('fv-chat-edit', t('Edit', '编辑'), openEditor);
+ editRow.append(editButton); item.append(editRow);
+ } else if (!editable && !editor && editRow) { editRow.remove(); editRow = editButton = null; }
+ // A rewrite the server has not shown yet has no number to rewrite.
+ if (editButton) editButton.disabled = !composeAllowed() || !Number.isFinite(entry.seq);
item.dataset.taken = String(entry.taken !== false);
item.dataset.failed = String(!!entry.error);
if (entry.error || entry.sending && entry.retried) {
@@ -1003,13 +1069,19 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}
function jobCard() {
const item = el('li', 'fv-chat-job');
- let mode = null, apply = null;
- return {element: item, update(job, {latest, retry, key}) {
+ let mode = null, apply = null, retry = null;
+ // The card's one button and, on its row, why the last press did not go on.
+ const again = () => [el('span', 'fv-chat-error fv-chat-again-note'), press('fv-chat-retry', null, () => retry?.())];
+ return {element: item, update(job, {latest, retry: action, key, text}) {
+ retry = action;
// 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') || (['image', 'production', 'cast'].includes(job.kind) && !WORKING.includes(job.status));
+ // What the user stopped says so; a video with finished parts can go on from there.
+ const byUser = jobMode(job) === 'stopped' && job.cancelled_by === 'user' && VIDEOS.includes(job.kind || 'generate');
const next = card ? jobMode(job) + (jobMode(job) === 'done' ? `:${job.play}:${job.thumbnail}:${job.work}`
- : jobMode(job) === 'failed' && job.kind === 'image' ? `:${job.error?.code}:${job.error?.report_id}:${job.error?.memory || ''}` : '')
+ : jobMode(job) === 'failed' && job.kind === 'image' ? `:${job.error?.code}:${job.error?.report_id}:${job.error?.memory || ''}`
+ : byUser ? `:user:${retry && job.again === 'continue' ? 'continue' : ''}` : '')
: 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';
@@ -1022,7 +1094,13 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
apply = next => { label.textContent = stopping.has(next.id) || next.status === 'cancelling'
? t('Stopping', '正在停止') : t(...(QUIET[next.kind] || BUSY[next.kind] || ['Working', '进行中'])); };
}
- else if (next === 'stopped' && (!job.error || job.kind === 'image')) { item.replaceChildren(el('span', null, t('Stopped', '已停止'))); apply = null; }
+ else if (next === 'stopped:user:continue') {
+ // The failed card's place and button, without a report: nothing went wrong.
+ const actions = el('div', 'fv-chat-actions fv-actions'), links = el('div', 'fv-result-links');
+ actions.append(...again()); links.append(actions);
+ item.replaceChildren(el('p', null, t('Stopped', '已停止')), links); apply = null;
+ }
+ else if (next === 'stopped:user:' || 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');
@@ -1030,7 +1108,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
memory: job.error?.memory}, t,
{productVersion, fetchApi: (path, options) => api.fetchApi(path, options)});
item.replaceChildren(host);
- if (retry) item.append(press('fv-chat-retry', t('Retry', '重试'), retry));
+ if (retry) { const row = el('div', 'fv-chat-actions'); row.append(...again()); item.append(row); }
apply = null;
}
else if (next === 'failed' || next === 'stopped') {
@@ -1041,14 +1119,23 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
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));
+ if (retry) actions.append(...again());
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);
- const again = item.querySelector('.fv-chat-retry'); if (again) again.disabled = !sendingAllowed() || retrying.has(key);
+ if (WORKING.includes(job.status)) fallbacks.delete(key);
+ const button = item.querySelector('.fv-chat-retry');
+ if (button) {
+ const way = againWay(job, key), note = item.querySelector('.fv-chat-again-note');
+ button.textContent = t(...AGAIN[way]);
+ button.hidden = way === 'resend' && !text;
+ // Going on needs no agent; saying the words again does.
+ button.disabled = retrying.has(key) || !inSelectedChat() || way === 'resend' && !sendingAllowed();
+ if (note) { note.textContent = fallbacks.get(key)?.reason || ''; note.hidden = !note.textContent; }
+ }
}};
}
function whiteboxState(entry) {
@@ -1205,6 +1292,43 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}
const MAKE = {hello, examples, dots, user: () => message('user'), agent: () => message('agent'), job: jobCard, confirm: confirmCard};
+ // A rewritten sentence takes the place of the one it rewrites. What was said, asked and left unfinished for the old
+ // words folds away; finished videos and pictures stay where they were. The session itself keeps every entry.
+ let rewriting = null;
+ function rewritten(entries) {
+ const list = [...entries];
+ if (rewriting && list.some(entry => entry.id === rewriting.id)) rewriting = null;
+ if (rewriting && rewriting.session === state.session)
+ list.push({type: 'message', role: 'user', id: rewriting.id, text: rewriting.text, revises: rewriting.revises, seq: Infinity, taken: false});
+ const home = new Map(), latest = new Map(), folded = [];
+ for (const entry of list) if (entry.type === 'message' && entry.role === 'user' && Number.isFinite(entry.revises)) {
+ // A rewrite of a rewrite still shows at the first sentence's place.
+ const origin = home.get(entry.revises) ?? entry.revises;
+ home.set(entry.seq, origin); latest.set(origin, entry); folded.push([entry.revises, entry.seq]);
+ }
+ if (!folded.length) return list;
+ const kept = entry => entry.type === 'job' && state.jobs[entry.job]?.status === 'succeeded';
+ return list.flatMap(entry => {
+ if (entry.type === 'message' && latest.has(entry.seq)) return [{...latest.get(entry.seq), slot: entry.id}];
+ return folded.some(([from, to]) => entry.seq > from && entry.seq <= to) && !kept(entry) ? [] : [entry];
+ });
+ }
+ // Rewrites the newest sentence: the server stops what began after it and declines what it still asked, then says the new words.
+ async function rewrite(entry, text, id) {
+ const response = await dataLayer.send({id, text, session: state.session, revises: entry.seq});
+ if (response?.ok) {
+ rewriting = {session: state.session, id, text, revises: entry.seq};
+ if (!stopped) { render(true); report(); void poll(); }
+ return null;
+ }
+ const error = await sendError(response);
+ if (!stopped) void poll();
+ // Another sentence came first: the page reads it, and this one stays in the box.
+ if (error?.code === 'invalid_request') return t('A newer message was sent first. This one was not sent.', '已有更新的消息,此⁠条⁠未⁠发⁠送⁠。');
+ if (WAIT_FOR_AGENT.includes(error?.code) || error?.code === 'session_full') return t('Not sent: ', '没发出去:') + failureReason({error}, t);
+ return t('Could not stop. Click again.', '未能停止,请再点一次。');
+ }
+
function render(follow = false) {
whiteboxButton.title = t(...WHITEBOX_PREVIEW.name);
whiteboxButton.setAttribute('aria-label', whiteboxButton.title);
@@ -1217,15 +1341,19 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
const wanted = [];
if (!entries.length && !localPending.length) wanted.push(['hello', 'hello', null]);
let lastUser = null;
- for (const entry of entries) {
+ const shownEntries = rewritten(entries);
+ // Only the newest sentence the agent already has can be rewritten, and not while another waits to go.
+ const editable = localPending.length ? null : shownEntries.findLast(entry => entry.type === 'message' && entry.role === 'user');
+ for (const entry of shownEntries) {
if (entry.type === 'message') {
if (entry.role === 'user') lastUser = entry;
- wanted.push([entry.role === 'user' && entry.id ? `m:${entry.id}` : `s:${entry.seq}`, entry.role === 'user' ? 'user' : 'agent', entry]);
+ wanted.push([entry.role === 'user' && entry.id ? `m:${entry.slot || entry.id}` : `s:${entry.seq}`, entry.role === 'user' ? 'user' : 'agent', entry,
+ {editable: entry === editable}]);
} else if (entry.type === 'job') {
const job = state.jobs[entry.job]; if (!job) continue;
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}]);
+ wanted.push([`s:${entry.seq}`, 'job', job, {latest: entry === finished, key, text, retry: () => againJob(key, job, text)}]);
const failure = state.failures[entry.entity];
if (failure) wanted.push([`e:${entry.seq}`, 'job', failure]);
} else if (entry.type === 'production' || entry.type === 'cast') {
diff --git a/web/chat_data.js b/web/chat_data.js
index 6066593..939f519 100644
--- a/web/chat_data.js
+++ b/web/chat_data.js
@@ -96,6 +96,8 @@ export function chatData(api) {
confirm: body => agentPost(api, '/freevideo/agent/chat/confirm', body),
abandon: session => agentPost(api, '/freevideo/agent/chat/abandon', session ? {session} : {}),
cancel: id => retryAgentPost(api, '/freevideo/agent/activity/cancel', {id}),
+ // Once: a second try after one that went through would only be refused as already running.
+ resume: id => agentPost(api, '/freevideo/agent/activity/resume', {id}),
activity: (cursor, options) => read('/freevideo/agent/activity' + (cursor ? '?cursor=' + encodeURIComponent(cursor) : ''), options),
sendMessage: (entry, options) => sendChatMessage(api, entry, options),
send: (body, options) => retryAgentPost(api, '/freevideo/agent/chat', body, options),