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.

AI Autopilot: start a new conversation and return to earlier ones; the agent follows

Bowen Xue48ea8420bf94
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
index 3d683b8..3ac4ba2 100644
--- a/freevideo_engine/agent/guide.py
+++ b/freevideo_engine/agent/guide.py
@@ -351,7 +351,7 @@ def introduction(zh, offers):
return rows
-def connection_guide(root, base, lang=None, offers=None):
+def connection_guide(root, base, lang=None, offers=None, resumed=False):
"""Public bootstrap text contains locations and commands, never credential values."""
import json
from pathlib import Path
@@ -403,17 +403,27 @@ def connection_guide(root, base, lang=None, offers=None):
description=CAPABILITIES_ZH.get((method, suffix), row['summary']) if zh else row['summary'])
for (method, suffix), row in contracts().items()
if not suffix.startswith('/freevideo/') and not suffix.startswith('/connect')],
- first_reply='用中文回复用户;如果用户改用其他语言,就跟随用户。连接后先用通俗的话告诉用户你能做“先介绍这几样”里的事,'
- '只说这几样,并举两三个用户可以提出的要求。不要报版本号,不要念接口名。'
- '不要自行启动任务,等待用户提出要求。' if zh else
- 'Reply to the user in English; if the user switches languages, follow their language. '
- 'After connecting, first reply in plain words: tell the user you can do the things under '
- '"Introduce these", only those, and give two or three requests they can say. Do not quote version '
- 'numbers or endpoint names. Do not start any task yourself; wait for the user to ask.',
+ # An agent connecting again while the user's conversation is under way has greeted there once already.
+ first_reply=(('用中文回复用户;如果用户改用其他语言,就跟随用户。用户所在的对话已经开始了:连接后不要自我介绍,'
+ '也不要说“已连接”,先调一次等待接口,回应里的 before 是这段对话的最后几句;什么都不说,等用户开口再接着做。'
+ '不要自行启动任务。' if zh else
+ 'Reply to the user in English; if the user switches languages, follow their language. '
+ 'The user is in a conversation that has already begun: after connecting do not introduce yourself '
+ 'and do not say that you are connected. Call the wait once; "before" in its answer holds the last '
+ 'lines of that conversation. Say nothing until the user speaks, then carry on from there. '
+ 'Do not start any task yourself.') if resumed else (
+ '用中文回复用户;如果用户改用其他语言,就跟随用户。连接后先用通俗的话告诉用户你能做“先介绍这几样”里的事,'
+ '只说这几样,并举两三个用户可以提出的要求。不要报版本号,不要念接口名。'
+ '不要自行启动任务,等待用户提出要求。如果第一次等待的回应说这段对话已经在进行,就不再介绍,接着之前的做。' if zh else
+ 'Reply to the user in English; if the user switches languages, follow their language. '
+ 'After connecting, first reply in plain words: tell the user you can do the things under '
+ '"Introduce these", only those, and give two or three requests they can say. Do not quote version '
+ 'numbers or endpoint names. Do not start any task yourself; wait for the user to ask. If the first wait says '
+ 'the conversation is already under way, do not introduce yourself again; carry on from it.')),
introduce=introduction(zh, offers or {}),
conversation='用户会在 FreeVideo 的“AI 全自动”页里直接和你说话,你的话也显示在那里。'
'连接后先调一次等待接口 GET ' + base + PREFIX + '/inbox?wait=50(MCP 用不带 id 的 freevideo_wait),'
- '回应里的 session 就是这段对话;往 POST ' + base + PREFIX + '/sessions/{session}/events 发 '
+ '回应里的 session 就是用户现在所在的对话(用户新开或换到另一段对话时它会变,话总是发到最近一次等待给的那个 session);往 POST ' + base + PREFIX + '/sessions/{session}/events 发 '
'{"type":"message","text":"…"}(MCP 用 freevideo_session_post)。在这里先只说一句话,不超过 20 个字,'
'不列条目、不举例(页面上已经有例句),例如“连上了。告诉我想做什么视频。”'
'你自己窗口里的那段介绍照常说,但它不是这一轮的结尾:说完紧接着去调等待接口。'
@@ -430,7 +440,7 @@ def connection_guide(root, base, lang=None, offers=None):
'这段对话里不要新建会话。只有用户明确让你停,才停。' if zh else
'The user talks to you inside FreeVideo, in the Autopilot view, and your words are shown there. '
'After connecting, call the wait once: GET ' + base + PREFIX + '/inbox?wait=50 (MCP: freevideo_wait '
- 'without id). Its "session" is this conversation; POST ' + base + PREFIX + '/sessions/{session}/events '
+ 'without id). Its "session" is the conversation the user is in (it changes when the user opens or returns to another one; always post to the session the latest wait named); POST ' + base + PREFIX + '/sessions/{session}/events '
'with {"type":"message","text":"..."} (MCP: freevideo_session_post). Say only one short sentence '
'there first, at most 12 words, no list and no examples (the page already shows examples), for example '
'"Connected. Tell me what video you want.", in the language the user writes to you in. Give the introduction in your own window as usual, but it '
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index cb3ba8d..96400e7 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -32,6 +32,16 @@ PREFIX = '/freevideo/agent/v1'
# What an empty wait tells the agent: the conversation is open for as long as the user keeps the page.
KEEP_WAITING = ('Nothing new yet. The user is still in FreeVideo and may speak at any moment: call this wait '
'again now. An empty wait never ends the conversation; do not end your turn or write a summary.')
+# The user may open another conversation while the agent waits; its words go where the user now is.
+MOVED = ('The user is now in another conversation, session %s. Post your words to that session from now on; '
+ 'the user no longer sees the earlier one.')
+MOVED_NEW = ' It starts afresh: do not carry requests over from the earlier conversation unless the user refers to them.'
+MOVED_BACK = (' It is one the user was in before, and the user means what was said there, not the conversation you just '
+ 'left. Its last lines are in "before"; all of it: GET /sessions/%s/events.')
+# An agent that connects again finds the conversation where the user left it, and has greeted there once already.
+RESUMED = ('This conversation is already under way; its last lines are in "before". Do not introduce yourself again: '
+ 'say nothing until the user speaks, then carry on from there.')
+BEFORE_LINES, BEFORE_TEXT = 8, 600
def local_address(request):
@@ -391,7 +401,7 @@ def register():
page_sessions = {}
connection = dict(connected=False, client=None, via=None, last_seen_at=None)
# The conversation in the Autopilot view: the page and the connected agent talk in the agent's latest session.
- chat = dict(client=None, waiting=0, folds={})
+ chat = dict(client=None, waiting=0, folds={}, told={})
server._freevideo_agent_connection = connection
def problem(code, message=None, status=None, **details):
@@ -529,7 +539,11 @@ def register():
if sid:
store.get(sid) # not_found for an unknown session
else:
- sid = store.latest_for(client) or (store.create(client=client)['id'] if write else None)
+ # Work belongs to the conversation the agent last heard from; until its next wait it has
+ # not learned that the user opened another one.
+ told = chat['told'].get(client)
+ sid = told if told is not None and store.has(client, told) else (
+ store.current_for(client) or (store.create(client=client)['id'] if write else None))
if sid is None:
return None
request['agent_session'] = sid
@@ -787,18 +801,30 @@ def register():
key=lambda r: (r['status'] in ('running', 'cancelling'), r['created_at']))
return mine, active[-1] if active else None
- def chat_session(store):
- return store.latest_for(chat['client']) if store is not None and chat['client'] is not None else None
+ def chat_session(store, sid=None):
+ # The conversation the user is in, or an earlier one of the connected agent that the page names.
+ if store is None or chat['client'] is None:
+ return None
+ if sid is None:
+ return store.current_for(chat['client'])
+ if not store.has(chat['client'], sid):
+ raise JobError('not_found', 'No such conversation')
+ return sid
+
+ def chat_moved(store, before):
+ # The agent waits in the conversation the user was in; let that wait look again.
+ if store.current_for(chat['client']) != before:
+ store.wake(chat['client'])
@routes.get('/freevideo/agent/chat')
@guarded
async def chat_read(request):
- after = request[query_key].get('after')
+ after, wanted = request[query_key].get('after'), request[query_key].get('session')
def read():
store = work_sessions()
- sid = chat_session(store)
+ sid = chat_session(store, wanted)
rows = jobs.rows()
- value = dict(agent=agent_state(), session=sid, 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={}, confirms={}, current=None,
active=sum(1 for r in rows if r['status'] in ACTIVE))
if sid is None:
return value
@@ -854,7 +880,8 @@ def register():
store, client = work_sessions(), chat['client']
if store is None or client is None:
return None
- sid = store.latest_for(client) or store.create(client=client, by='user')['id']
+ before = store.current_for(client)
+ sid = chat_session(store, value.get('session')) or store.create(client=client, by='user')['id']
fold = chat_fold(store, sid)
if value['id'] in fold['sent']:
seq = fold['sent'][value['id']]
@@ -869,6 +896,7 @@ def register():
fold['ids'][row['seq']] = value['id']
while len(fold['sent']) > 500:
fold['ids'].pop(fold['sent'].pop(next(iter(fold['sent']))), None)
+ chat_moved(store, before)
return 201, dict(seq=row['seq'], id=value['id'], at=row['at'], session=sid, read=False, agent=agent_state())
done = await asyncio.to_thread(write)
if done is None:
@@ -884,14 +912,49 @@ def register():
value = await body(request)
def write():
store = work_sessions()
- sid = chat_session(store)
+ before = chat_session(store)
+ sid = chat_session(store, value.get('session'))
if sid is None:
raise JobError('not_found', 'No conversation')
row = store.append(sid, dict(type='confirm', id=value['id'],
state='approved' if value['approve'] else 'declined'), by='user')
+ chat_moved(store, before)
return dict(id=row['id'], state=row['state'])
return reply(await asyncio.to_thread(write))
+ @routes.get('/freevideo/agent/chat/list')
+ @guarded
+ async def chat_list(request):
+ def read():
+ store = work_sessions()
+ here = chat_session(store)
+ rows = store.history(chat['client']) if here else []
+ active = [r.get('session') for r in jobs.rows() if r['status'] in ACTIVE]
+ return dict(agent=agent_state(), here=here,
+ conversations=[dict(row, running=active.count(row['id'])) for row in rows])
+ return reply(await asyncio.to_thread(read))
+
+ @routes.post('/freevideo/agent/chat/new')
+ @guarded
+ async def chat_new(request):
+ def write():
+ store, client = work_sessions(), chat['client']
+ if store is None or client is None:
+ return None
+ before = store.current_for(client)
+ # A conversation the user has not spoken in yet is the new one already.
+ if before is not None and not store.spoken(before):
+ return 200, dict(session=before, agent=agent_state())
+ sid = store.create(client=client, by='user')['id']
+ chat_moved(store, before)
+ return 201, dict(session=sid, agent=agent_state())
+ done = await asyncio.to_thread(write)
+ if done is None:
+ return reply({'error': dict(code='not_connected', message='No agent is connected.', retryable=True,
+ details=[], next='Connect an agent in the Autopilot view, then try again.',
+ request_id=errors.request_id())}, 409)
+ return reply(done[1], done[0])
+
@routes.get('/freevideo/agent/chat/video')
@guarded
async def chat_video(request):
@@ -975,8 +1038,13 @@ def register():
root = installation_root()
prepare_token(root)
from .editor_runtime import available
+ store = work_sessions()
+ def begun():
+ here = store.current_for(chat['client']) if store is not None and chat['client'] else None
+ return bool(here and store.get(here)['last_seq'])
value = connection_guide(root, request.scheme + '://' + request.host, request[query_key].get('lang'),
- dict(continuation=await asyncio.to_thread(jobs.continuation_ready), editing=available()))
+ dict(continuation=await asyncio.to_thread(jobs.continuation_ready), editing=available()),
+ resumed=await asyncio.to_thread(begun))
if request[query_key].get('format') == 'json':
return reply(value)
return web.Response(text=connection_text(value), content_type='text/plain', headers={'Cache-Control': 'no-store'})
@@ -986,6 +1054,7 @@ def register():
async def hello(request):
value = await body(request)
connection.update(connected=True, client=value['client'], via=value['via'], last_seen_at=time.time())
+ chat['told'].pop(request['agent_client'], None) # a newly connected agent has heard from no conversation yet
unfinished = await asyncio.to_thread(jobs.productions.list, status='active', limit=5)
return reply(dict(connection, unfinished=unfinished))
@@ -1198,8 +1267,15 @@ def register():
return reply(await stop_session(sid), 201)
if by == 'agent' and value['type'] == 'message' and isinstance(value.get('text'), str):
value['text'] = chat_text(value['text'])
- return reply(await asyncio.to_thread(sessions.append, sid, value,
- by=by, client=session_client(request, by)), 201)
+ client = session_client(request, by)
+ def write():
+ row = sessions.append(sid, value, by=by, client=client)
+ here = sessions.current_for(client) if client and value['type'] == 'message' else None
+ if here not in (None, sid):
+ # Said where the user no longer looks: the answer itself tells the agent where to say it.
+ row['next'] = MOVED % here
+ return row
+ return reply(await asyncio.to_thread(write), 201)
@routes.get(PREFIX + '/confirmations')
@guarded
@@ -1485,12 +1561,29 @@ def register():
client = request['agent_client']
if store is not None and sid is None:
# An agent that only listens has no session yet: give it one, so the page can speak into it.
- sid = await asyncio.to_thread(lambda: store.latest_for(client) or store.create(client=client)['id'])
+ sid = await asyncio.to_thread(lambda: store.current_for(client) or store.create(client=client)['id'])
request['agent_session'] = sid
+ # Without a session of its own choosing, the agent listens wherever its user is.
+ follow = store is not None and not request.headers.get('X-FreeVideo-Session', '').strip()
+ def answer(value):
+ told, chat['told'][client] = chat['told'].get(client), value['session']
+ if follow and told != value['session']:
+ first = value['inbox'][0]['seq'] if value['inbox'] else store.get(value['session'])['last_seq'] + 1
+ if first > 1:
+ # What the user sees above these words. An agent that has to fetch it answers from the conversation it left.
+ value['before'] = [dict(e, text=e['text'][:BEFORE_TEXT]) if isinstance(e.get('text'), str) else e
+ for e in store.events(value['session'], after=max(0, first - 1 - BEFORE_LINES),
+ limit=BEFORE_LINES) if e['seq'] < first]
+ said = (RESUMED if first > 1 else '') if told is None else (
+ MOVED % value['session'] + (MOVED_BACK % value['session'] if first > 1 else MOVED_NEW))
+ value['next'] = (said + ' ' + value.get('next', '')).strip()
+ return reply(value)
deadline = time.monotonic() + min(50., float(request[query_key].get('wait', '0') or 0))
chat['waiting'] += 1
try:
while True:
+ if follow:
+ sid = request['agent_session'] = await asyncio.to_thread(store.current_for, client) or sid
if store is not None and sid is not None:
# Mark before reading so words arriving in between wake the wait below.
def read():
@@ -1498,16 +1591,17 @@ def register():
return mark, store.unread(sid, client)
mark, pending = await asyncio.to_thread(read)
if pending:
- return reply(dict(session=sid, inbox=pending[-20:]))
+ return answer(dict(session=sid, inbox=pending[-20:]))
left = deadline - time.monotonic()
if left <= 0:
# again: nothing new this time; the caller simply waits once more. An agent decides what to
# do next from the last answer it read, so the empty one says it in words as well.
- return reply(dict(session=sid, inbox=[], again=True, next=KEEP_WAITING))
+ return answer(dict(session=sid, inbox=[], again=True, next=KEEP_WAITING))
if store is None or sid is None:
await asyncio.sleep(min(left, 1.))
else:
- await store.wait(sid, after=mark, seconds=min(left, 25.), by='user')
+ await store.wait(sid, after=mark, seconds=min(left, 25.), by='user',
+ leave=(lambda here=sid: store.current_for(client) != here) if follow else None)
finally:
chat['waiting'] -= 1
# The agent was here for the whole wait, not only when it began.
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index f8d8fb4..2cdd74e 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -354,12 +354,12 @@ def contracts(*, local=False):
for suffix, method, body in (('', 'GET', None), ('/session', 'GET', None), ('/activity', 'GET', None),
('/activity/cancel', 'POST', obj({'id': JOB}, ('id',))), ('/connect', 'GET', None),
('/connect/reset', 'POST', EMPTY), ('/chat', 'GET', None), ('/chat/now', 'GET', None),
- ('/chat/video', 'GET', None),
- ('/chat', 'POST', obj({'text': string(8000), 'id': CHAT_ID}, ('text', 'id'))),
- ('/chat/confirm', 'POST', obj({'id': string(12, pattern=r'^cf[0-9a-f]{10}$'), 'approve': {'type': 'boolean'}},
- ('id', 'approve')))):
+ ('/chat/video', 'GET', None), ('/chat/list', 'GET', None), ('/chat/new', 'POST', EMPTY),
+ ('/chat', 'POST', obj({'text': string(8000), 'id': CHAT_ID, 'session': SESSION}, ('text', 'id'))),
+ ('/chat/confirm', 'POST', obj({'id': string(12, pattern=r'^cf[0-9a-f]{10}$'), 'approve': {'type': 'boolean'},
+ 'session': SESSION}, ('id', 'approve')))):
routes[(method, '/freevideo/agent' + suffix)] = route('Studio Agent controls', body=body, auth=False, local=True)
- routes['GET', '/freevideo/agent/chat']['query'] = obj({'after': number(0, integer=True)})
+ routes['GET', '/freevideo/agent/chat']['query'] = obj({'after': number(0, integer=True), 'session': SESSION})
routes['GET', '/freevideo/agent/chat/video']['query'] = obj({'id': string(43, pattern=r'^[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9a-f]{32}$')}, ('id',))
for suffix in ('', '/connect'):
routes['GET', '/freevideo/agent' + suffix]['query'] = obj({'lang': enum(('zh', 'en'))})
diff --git a/freevideo_engine/agent/sessions.py b/freevideo_engine/agent/sessions.py
index 5d48ab0..5fd002e 100644
--- a/freevideo_engine/agent/sessions.py
+++ b/freevideo_engine/agent/sessions.py
@@ -58,6 +58,11 @@ class Sessions:
self._initial_seq = {}
self._readers = {}
self._user_seq = {} # Last event the user wrote; unread() skips the file when nothing is newer.
+ # When each session began or its user last acted in it (spoke, answered), and the user's first words
+ # there: the conversation the user is in, and what the page calls each one in its history.
+ self._acted = {}
+ self._said = {}
+ self._chosen = set()
self._waiters = {}
self._partial = set()
self.root.mkdir(parents=True, exist_ok=True)
@@ -91,6 +96,9 @@ class Sessions:
updated_at=meta['created_at'], client=meta['client'], last_seq=0, stopped=False)
self._ids[sid] = {}
self._clients[sid] = {meta['client']} if meta['client'] else set()
+ self._acted[sid] = (meta['created_at'], 1)
+ if meta.get('by') == 'user':
+ self._chosen.add(sid)
for row in stream:
if not row.endswith(b'\n'):
self._partial.add(sid)
@@ -111,6 +119,12 @@ class Sessions:
meta.update(last_seq=event['seq'], updated_at=event['at'])
if event['by'] == 'user':
self._user_seq[sid] = event['seq']
+ # No counter here: the order must come out the same when the files are read again after a
+ # restart, so two things in one clock tick are ordered by what they are, then by session.
+ self._acted[sid] = max(self._acted[sid], (event['at'], 0))
+ self._chosen.add(sid)
+ if event['type'] == 'message' and sid not in self._said:
+ self._said[sid] = event['text'].strip()[:60]
if event.get('client'):
self._clients[sid].add(event['client'])
if event.get('id'):
@@ -149,6 +163,9 @@ class Sessions:
updated_at=meta['created_at'], client=client, last_seq=0, stopped=False)
self._ids[sid], self._clients[sid] = {}, {client} if client else set()
self._initial_seq[sid] = 0
+ self._acted[sid] = (meta['created_at'], 1)
+ if by == 'user':
+ self._chosen.add(sid)
return deepcopy(self._meta[sid])
def list(self, *, limit=50, before=None) -> dict:
@@ -244,7 +261,9 @@ class Sessions:
self._get(sid)
return self._events(sid, after, limit)
- async def wait(self, sid, *, after, seconds, types=None, by=None) -> list[dict]:
+ async def wait(self, sid, *, after, seconds, types=None, by=None, leave=None) -> list[dict]:
+ """Events after a cursor, waiting up to some seconds. leave, when given, ends an empty wait early
+ once it answers true: wake() asks for that look when the user moves to another conversation."""
_check(schema.session_schema('events'), dict(after=after, wait=seconds))
if types is not None:
_check(schema.array(schema.enum(('message', 'plan', 'step', 'confirm', 'control')), high=5), types)
@@ -294,6 +313,8 @@ class Sessions:
found, cursor = await offload(read)
if found:
return found
+ if leave is not None and await offload(leave):
+ return []
remaining = deadline - loop.time()
if remaining <= 0:
return []
@@ -316,6 +337,46 @@ class Sessions:
rows = [row for sid, row in self._meta.items() if client in self._clients[sid]]
return max(rows, key=lambda r: (r['updated_at'], r['id']))['id'] if rows else None
+ def current_for(self, client) -> str | None:
+ """The conversation this client's user is in: the newest one, or an older one the user spoke or
+ answered in after that; what the agent or the server writes never moves the user. Until the user
+ has opened a conversation or spoken on the page, it is wherever the latest work is, as before."""
+ with self.lock:
+ rows = [sid for sid in self._meta if client in self._clients[sid]]
+ if not rows:
+ return None
+ if not self._chosen.intersection(rows):
+ return max(rows, key=lambda sid: (self._meta[sid]['updated_at'], sid))
+ return max(rows, key=lambda sid: (self._acted[sid], sid))
+
+ def has(self, client, sid) -> bool:
+ with self.lock:
+ return sid in self._meta and client in self._clients[sid]
+
+ def spoken(self, sid) -> bool:
+ """Whether the user has said anything in this conversation."""
+ with self.lock:
+ return sid in self._said
+
+ def wake(self, client) -> None:
+ """Let this client's waits look again: its user moved to another conversation."""
+ with self.lock:
+ waiters = [w for sid, group in self._waiters.items() if client in self._clients[sid] for w in group]
+ for loop, signal in waiters:
+ try:
+ loop.call_soon_threadsafe(signal.set)
+ except RuntimeError:
+ pass # A closed client loop no longer needs notification.
+
+ def history(self, client, *, limit=50) -> list[dict]:
+ """This client's conversations the user has spoken in, for the page: latest change first."""
+ current = self.current_for(client)
+ with self.lock:
+ rows = sorted((row for sid, row in self._meta.items() if client in self._clients[sid] and sid in self._said),
+ key=lambda r: (r['updated_at'], r['id']), reverse=True)
+ return [dict(id=r['id'], title=self._said[r['id']], updated_at=r['updated_at'], current=r['id'] == current)
+ for r in rows[:limit]]
+
def read_until(self, sid, reader) -> int:
"""The last event this reader has been given; unread() moves it."""
with self.lock:
diff --git a/web/autopilot_chat.css b/web/autopilot_chat.css
index 934f04d..ea0c802 100644
--- a/web/autopilot_chat.css
+++ b/web/autopilot_chat.css
@@ -1,6 +1,19 @@
/* The conversation with an agent: one column, the box to type in fixed under it. */
-.fv-chat{box-sizing:border-box;position:relative;min-height:0;min-width:0;display:grid;grid-template-rows:minmax(0,1fr) auto;grid-template-columns:minmax(0,1fr);gap:16px;padding:0 40px 22px}
+.fv-chat{--fv-chats-width:232px;--fv-chats-pad:12px;--fv-chats-gap:6px;--fv-chats-row:40px;--fv-chats-radius:9px;--fv-chats-font:14px;--fv-chats-dot:6px;--fv-chats-toggle:34px;box-sizing:border-box;position:relative;min-height:0;min-width:0;display:grid;grid-template-columns:minmax(0,1fr)}
+.fv-chat-main{position:relative;min-height:0;min-width:0;display:grid;grid-template-rows:minmax(0,1fr) auto;grid-template-columns:minmax(0,1fr);gap:16px;padding:0 40px 22px}
.fv-chat[hidden],.fv-chat [hidden]{display:none}
+/* List dimensions are kept here for art review; the breakpoint below is shared with the drawer's keyboard behavior. */
+.fv-chat[data-conversations=true]{grid-template-columns:var(--fv-chats-width) minmax(0,1fr)}
+.fv-chat-conversations{box-sizing:border-box;min-height:0;min-width:0;display:flex;flex-direction:column;gap:var(--fv-chats-gap);padding:16px var(--fv-chats-pad);border-right:1px solid var(--fv-border);background:var(--fv-bg)}
+.fv-chat-conversation-list{min-height:0;overflow:auto;display:grid;align-content:start;gap:var(--fv-chats-gap)}
+.fv-studio .fv-chat-conversations button{box-sizing:border-box;flex:none;justify-content:flex-start;min-width:0;width:100%;min-height:var(--fv-chats-row);padding:8px var(--fv-chats-pad);border-radius:var(--fv-chats-radius);border:1px solid transparent;background:transparent;font-size:var(--fv-chats-font);font-weight:var(--fv-regular);color:var(--fv-ink);text-align:left;gap:10px}
+.fv-studio .fv-chat-conversations .fv-chat-new{border-color:var(--fv-border);margin-bottom:6px}
+.fv-studio .fv-chat-conversations button:hover:not(:disabled){background:var(--fv-raised)}
+.fv-studio .fv-chat-conversations button:focus-visible{outline-offset:-2px}
+.fv-studio .fv-chat-conversation[aria-current]{background:var(--fv-raised);border-color:var(--fv-accent-dim)}
+.fv-chat-conversation span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.fv-chat-running{flex:none;width:var(--fv-chats-dot);height:var(--fv-chats-dot);border-radius:50%;background:var(--fv-accent)}
+.fv-chat-tools{display:none}
.fv-chat-scroll{min-height:0;overflow:auto;margin:0 -40px;padding:24px 40px 2px;scrollbar-gutter:stable both-edges}
.fv-chat-log{list-style:none;margin:0 auto;padding:0;width:100%;max-width:720px;display:grid;grid-template-columns:minmax(0,1fr);align-content:start;gap:18px}
.fv-chat-log>li{min-width:0}.fv-chat-log p{margin:0;line-height:1.6}
@@ -69,6 +82,15 @@
.fv-studio .fv-chat-send:hover:not(:disabled){background:var(--fv-accent-hover)}
.fv-studio .fv-chat-send:disabled{opacity:1;background:#22344a;color:#9fb3c8}
.fv-studio .fv-chat-send:focus-visible{outline-offset:2px}
-@media(max-width:480px){.fv-chat{padding:0 14px 14px}.fv-chat-scroll{margin:0 -14px;padding:16px 14px 2px}.fv-chat-hello{padding-top:32px}.fv-chat-job{max-width:none;gap:12px}.fv-chat-confirm{max-width:none}
+@media(max-width:720px){
+ .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-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}
+ .fv-chat-conversations{display:none;position:absolute;inset:0 auto 0 0;z-index:3;width:var(--fv-chats-width);box-shadow:16px 0 32px #0005}
+ .fv-chat[data-chats-open=true] .fv-chat-conversations:not([hidden]){display:flex}
+}
+@media(max-width:480px){.fv-chat-main{padding:0 14px 14px}.fv-chat-scroll{margin:0 -14px;padding:16px 14px 2px}.fv-chat-hello{padding-top:32px}.fv-chat-job{max-width:none;gap:12px}.fv-chat-confirm{max-width:none}
.fv-chat-preview,.fv-chat-preview[data-shape=wide]{width:98px}.fv-chat-length{display:none}.fv-chat-percent{font-size:22px}.fv-studio.fv-autopilot .fv-chat-input textarea{font-size:16px}.fv-studio .fv-chat-down{right:14px;bottom:84px}}
@media(prefers-reduced-motion:reduce){.fv-chat-water,.fv-chat-percent,.fv-chat-parts>i::after{transition:none}.fv-chat-water::after,.fv-chat-dots>i,.fv-chat-preview>img{animation:none}}
diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js
index b70a3e2..533ac56 100644
--- a/web/autopilot_chat.js
+++ b/web/autopilot_chat.js
@@ -2,6 +2,7 @@
// 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 { estimatedFraction, remainingAbove, remainingShown } from './generation_progress.js';
+import {emptyConversations, hasConversations, mergeConversations, runningElsewhere, selectConversation} from './autopilot_conversations.js';
const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./autopilot_chat.css', import.meta.url).href; document.head.append(css);
@@ -13,6 +14,7 @@ function glyph(path, width = 2.2) {
return svg;
}
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'];
// What a job with no picture of its own is doing, in the reader's language.
@@ -136,16 +138,110 @@ function newId() {
// user can see the conversation; the page calls sync() whenever that may have changed. changed(view) follows every
// answer: {known, agent, current, active, any}.
export function agentChat(t, api, {open, edit, shown = () => true, changed = () => {}, interval = 1500} = {}) {
- const element = el('section', 'fv-chat'), scroller = el('div', 'fv-chat-scroll'), log = el('ol', 'fv-chat-log');
+ const element = el('section', 'fv-chat'), main = el('div', 'fv-chat-main'), scroller = el('div', 'fv-chat-scroll'), log = el('ol', 'fv-chat-log');
log.setAttribute('role', 'log'); log.setAttribute('aria-label', t('Conversation', '对话'));
const down = press('fv-chat-down', null, () => { scroller.scrollTo({top: scroller.scrollHeight, behavior: 'smooth'}); });
down.append(glyph('M12 5v14M5 12l7 7 7-7')); down.setAttribute('aria-label', t('Latest', '最新')); down.hidden = true;
const form = el('form', 'fv-chat-input'), input = el('textarea'), sendButton = el('button', 'fv-chat-send');
input.rows = 1; input.maxLength = 8000; input.setAttribute('aria-label', t('Message the agent', '对 Agent 说'));
sendButton.type = 'submit'; sendButton.setAttribute('aria-label', t('Send', '发送')); sendButton.append(glyph('M12 19V5M5 12l7-7 7 7'));
- form.append(input, sendButton); scroller.append(log); element.append(scroller, down, form);
+ form.append(input, sendButton); scroller.append(log); main.append(scroller, down, form); element.append(main);
let state = emptyChat(), pending = [], known = false, stopped = false, timer = null, busy = false, failures = 0;
+ let conversations = emptyConversations(), selectedSession, selection = 0, reread = false, focusSession = null, creating = false;
+ // Work under way in another conversation while this one has none: {session, job, ids}. The page's header keeps it in sight.
+ let away = null;
+ let listBusy = false, listAgain = false, listAt = -Infinity;
+ const listInterval = 10000;
+ const sidebar = el('nav', 'fv-chat-conversations'), list = el('div', 'fv-chat-conversation-list'), tools = el('div', 'fv-chat-tools');
+ sidebar.id = `fv-chat-conversations-${++chatNumber}`; sidebar.setAttribute('aria-label', t('Chats', '对话')); sidebar.hidden = true;
+ const newChat = press('fv-chat-new', t('New chat', '新对话'), () => void startChat());
+ newChat.prepend(glyph('M12 5v14M5 12h14')); newChat.title = t('New chat', '新对话');
+ const chats = press('fv-chat-chats', null, () => drawer(chats.getAttribute('aria-expanded') !== 'true'));
+ const chatsDot = el('i', 'fv-chat-running'); chatsDot.setAttribute('aria-hidden', 'true'); chatsDot.hidden = true;
+ chats.append(glyph('M4 5h16v12H9l-5 4V5M8 9h8M8 13h5'), chatsDot);
+ chats.title = t('Chats', '对话'); chats.setAttribute('aria-label', chats.title);
+ chats.setAttribute('aria-controls', sidebar.id); chats.setAttribute('aria-expanded', 'false');
+ tools.hidden = true; tools.append(chats); main.prepend(tools); sidebar.append(newChat, list); element.prepend(sidebar);
+ const listNodes = new Map(), narrow = () => window.matchMedia('(max-width: 720px)').matches;
+ function drawer(on, restore = false) {
+ element.dataset.chatsOpen = String(on); chats.setAttribute('aria-expanded', String(on));
+ // Only the overlay needs to keep keyboard focus in its list.
+ main.inert = on && narrow();
+ if (on) (list.querySelector('[aria-current]') || newChat).focus();
+ else if (restore) chats.focus();
+ }
+ function renderConversations() {
+ const visible = hasConversations(conversations);
+ element.dataset.conversations = String(visible); sidebar.hidden = tools.hidden = !visible;
+ if (!visible) drawer(false);
+ newChat.disabled = creating; chatsDot.hidden = !conversations.conversations.some(row => row.running > 0);
+ const keep = new Set(conversations.conversations.map(row => row.id));
+ for (const [id, node] of listNodes) if (!keep.has(id)) { node.button.remove(); listNodes.delete(id); }
+ conversations.conversations.forEach((row, index) => {
+ let node = listNodes.get(row.id);
+ if (!node) {
+ const button = press('fv-chat-conversation', null, () => chooseChat(row.id)), dot = el('i', 'fv-chat-running'), title = el('span');
+ button.dataset.session = row.id; dot.setAttribute('aria-hidden', 'true'); button.append(dot, title);
+ listNodes.set(row.id, node = {button, dot, title});
+ }
+ node.title.textContent = row.title; node.button.title = row.title; node.dot.hidden = row.running <= 0;
+ if (row.id === conversations.current) node.button.setAttribute('aria-current', 'true'); else node.button.removeAttribute('aria-current');
+ if (list.children[index] !== node.button) list.insertBefore(node.button, list.children[index] || null);
+ });
+ }
+ function chooseChat(session, focus = false) {
+ selectedSession = session; selection++; pinned = true; away = null;
+ conversations = selectConversation(conversations, session); renderConversations();
+ input.value = ''; grow(); drawer(false);
+ focusSession = focus ? session : null;
+ if (focus && session === state.session) input.focus(); else if (narrow()) chats.focus();
+ render(); void readConversations(true); void poll();
+ }
+ async function startChat() {
+ if (creating || !active() || conversations.supported !== true) return;
+ creating = true; renderConversations(); render();
+ try {
+ const response = await agentPost(api, '/freevideo/agent/chat/new', {});
+ if (stopped) return;
+ if (response.ok) {
+ const data = await response.json();
+ if (typeof data.session === 'string' && data.session) chooseChat(data.session, true);
+ } else if (response.status === 409) { state = {...state, agent: {connected: false, name: null}}; report(); }
+ } catch { /* Keep the current conversation available for another try. */ }
+ finally { creating = false; if (!stopped) { renderConversations(); render(); } }
+ }
+ async function readConversations(force = false) {
+ if (!active() || conversations.supported === false) return;
+ if (listBusy) { if (force) listAgain = true; return; }
+ if (!force && performance.now() - listAt < listInterval) return;
+ listBusy = true; listAt = performance.now();
+ try {
+ const response = await agentGet(api, '/freevideo/agent/chat/list', {signal: closed.signal});
+ if (stopped) return;
+ conversations = mergeConversations(conversations, response.ok ? await response.json() : null, response.status);
+ renderConversations();
+ if (conversations.supported === false && selectedSession !== undefined) { selectedSession = undefined; selection++; void poll(); }
+ } catch { /* List failures do not interrupt reading or sending. */ }
+ finally { listBusy = false; }
+ if (listAgain) { listAgain = false; void readConversations(true); }
+ }
+ const outside = event => {
+ if (chats.getAttribute('aria-expanded') === 'true' && !sidebar.contains(event.target) && !chats.contains(event.target)) drawer(false, true);
+ };
+ const keys = event => {
+ if (chats.getAttribute('aria-expanded') !== 'true') return;
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); drawer(false, true); }
+ else if (event.key === 'Tab' && narrow()) {
+ const buttons = [...sidebar.querySelectorAll('button')].filter(button => !button.disabled);
+ if (!buttons.length) return;
+ if (event.shiftKey && document.activeElement === buttons[0]) { event.preventDefault(); buttons.at(-1).focus(); }
+ else if (!event.shiftKey && document.activeElement === buttons.at(-1)) { event.preventDefault(); buttons[0].focus(); }
+ }
+ };
+ const resize = () => { if (!narrow()) drawer(false); };
+ document.addEventListener('pointerdown', outside, true); document.addEventListener('keydown', keys, true);
+ window.addEventListener('resize', resize);
// 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();
@@ -173,6 +269,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
return row ? row.seconds : null;
}
const active = () => !stopped && element.isConnected && !document.hidden && shown();
+ const sendingAllowed = () => !creating && (!selectedSession || selectedSession === state.session) && canSend(state);
// ---- one entry of the conversation each ----
function message(role) {
@@ -291,7 +388,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
} else { item.replaceChildren(); apply = null; }
}
apply?.(job, latest);
- const again = item.querySelector('.fv-chat-retry'); if (again) again.disabled = !canSend(state);
+ const again = item.querySelector('.fv-chat-retry'); if (again) again.disabled = !sendingAllowed();
}};
}
function confirmCard() {
@@ -329,7 +426,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
t('Make a 1-minute vertical short film: a day in a coffee shop', '做一条 1 分钟的竖屏短片:咖啡店的一天')];
list.append(...lines.map(line => press(null, line, () => send(line))));
item.append(el('p', 'fv-chat-meta', t('Try saying:', '可以这样说:')), list);
- return {element: item, update() { list.querySelectorAll('button').forEach(button => { button.disabled = !canSend(state); }); }};
+ return {element: item, update() { list.querySelectorAll('button').forEach(button => { button.disabled = !sendingAllowed(); }); }};
}
function dots() {
const item = el('li', 'fv-chat-thinking'), mark = el('span', 'fv-chat-dots'); mark.append(el('i'), el('i'), el('i'));
@@ -372,10 +469,11 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
node.update(value, extra || {});
if (log.children[index] !== node.element) log.insertBefore(node.element, log.children[index] || null);
});
- const sendable = canSend(state);
- input.disabled = state.agent.connected !== true;
+ 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 keep listening', '回到 Agent 那边让它继续') : t('Message the agent…', '对 Agent 说…');
sendButton.disabled = !sendable || !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;
}
@@ -385,18 +483,39 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
if (pinned) down.hidden = true;
}, {passive: true});
+ async function readAway() {
+ const row = state.current ? null : runningElsewhere(conversations, state.session);
+ if (!row) { away = null; return; }
+ try {
+ // Past the last message: only that conversation's jobs come back.
+ const query = new URLSearchParams({session: row.id, after: String(Number.MAX_SAFE_INTEGER)});
+ const response = await agentGet(api, `/freevideo/agent/chat?${query}`, {signal: closed.signal});
+ if (!response.ok) { away = null; return; }
+ const data = await response.json(), jobs = Object.values(data.jobs || {}).filter(job => WORKING.includes(job?.status));
+ const job = data.jobs?.[data.current] || jobs[0];
+ away = job ? {session: row.id, job, ids: jobs.map(job => job.id)} : null;
+ } catch { /* The last reading stays until the next one. */ }
+ }
function report() {
- const current = state.current ? state.jobs[state.current] || null : null;
+ const current = (state.current ? state.jobs[state.current] : away?.job) || null;
changed({known, agent: state.agent, current, fraction: current ? fractionOf(current) : 0, left: current ? leftOf(current) : null, active: state.active,
any: state.items.size > 0 || pending.length > 0});
}
async function send(text) {
text = String(text).trim();
- if (!text || !canSend(state)) return false;
+ if (!text || !sendingAllowed()) return false;
+ const sentSelection = selection;
const entry = {id: newId(), text}; pending.push(entry); render(true); report();
let response = null;
- try { response = await agentPost(api, '/freevideo/agent/chat', entry); } catch { /* Handled below as not sent. */ }
- if (response?.ok) { const value = await response.json().catch(() => ({})); if (value.agent) state.agent = value.agent; poll(); return true; }
+ const body = conversations.supported === true && state.session ? {...entry, session: state.session} : entry;
+ try { response = await agentPost(api, '/freevideo/agent/chat', body); } catch { /* Handled below as not sent. */ }
+ if (stopped) return false;
+ if (response?.ok) {
+ const value = await response.json().catch(() => ({}));
+ if (sentSelection === selection) { if (value.agent) state.agent = value.agent; void poll(); }
+ void readConversations(true); return true;
+ }
+ if (sentSelection !== selection) return false;
// Not sent: the sentence goes back to the box. An agent that was never connected leads back to the card.
pending = pending.filter(item => item !== entry);
if (!input.value) { input.value = text; grow(); }
@@ -409,7 +528,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
// At most five lines; the box scrolls after that.
const line = parseFloat(getComputedStyle(input).lineHeight) || 22;
input.style.height = `${Math.min(input.scrollHeight, Math.round(line * 5) + 14)}px`;
- sendButton.disabled = !canSend(state) || !input.value.trim();
+ sendButton.disabled = !sendingAllowed() || !input.value.trim();
}
input.addEventListener('input', grow);
// Enter sends, Shift+Enter starts a new line; Enter that confirms an input-method candidate does neither.
@@ -420,33 +539,53 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
form.addEventListener('submit', event => {
event.preventDefault();
const text = input.value;
- if (!text.trim() || !canSend(state)) return;
+ if (!text.trim() || !sendingAllowed()) return;
input.value = ''; grow(); void send(text);
});
+ // Both a server-side session change and a list selection reset the same reader. Job clocks stay keyed by job id.
+ function resetChat() {
+ state = emptyChat(); pending = []; answers.clear(); nodes.clear();
+ log.querySelectorAll('video').forEach(video => video.pause()); log.replaceChildren(); pinned = true;
+ }
async function poll() {
clearTimeout(timer); timer = null;
- if (stopped || busy) return;
+ if (stopped) return;
+ if (busy) { reread = true; return; }
if (!active()) return;
- busy = true;
+ busy = true; reread = false;
+ void readConversations();
+ const readSelection = selection, requested = selectedSession;
let again = false;
try {
- const after = state.session ? state.last : 0;
- const response = await agentGet(api, '/freevideo/agent/chat' + (after ? `?after=${after}` : ''), {signal: closed.signal});
+ const after = state.session && (!requested || requested === state.session) ? state.last : 0;
+ const query = new URLSearchParams();
+ if (requested) query.set('session', requested);
+ if (after) query.set('after', String(after));
+ const response = await agentGet(api, '/freevideo/agent/chat' + (query.size ? `?${query}` : ''), {signal: closed.signal});
if (stopped) return;
- if (response.ok) {
+ if (readSelection !== selection) again = true;
+ else if (response.ok) {
const data = await response.json();
+ if (stopped) return;
+ if (readSelection !== selection) { again = true; }
// Another conversation began: forget this one and read the new one whole.
- if (after && (data.session ?? null) !== state.session) { state = emptyChat(); again = true; }
+ else if (after && (data.session ?? null) !== state.session) { resetChat(); again = true; }
else {
- if ((data.session ?? null) !== state.session) state = emptyChat();
+ if ((data.session ?? null) !== state.session) resetChat();
state = chatMerge(state, data); failures = 0;
+ conversations = selectConversation(conversations, state.session); renderConversations();
+ await readAway();
+ if (stopped) return;
+ if (readSelection !== selection) { away = null; again = true; }
}
+ } else if (response.status === 404 && requested) {
+ selectedSession = undefined; selection++; resetChat(); again = true; void readConversations(true);
} else failures++;
} catch { failures++; }
finally { busy = false; }
if (stopped) return;
- if (again) return poll();
+ if (again || reread) return poll();
known = true;
// The next read is booked before the page hears of this one, so the page's sync() does not start another.
const idle = state.agent.connected !== true && !state.active;
@@ -455,7 +594,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}
// Between reads the estimate keeps moving, on the cards and in the page's header alike.
const moving = setInterval(() => {
- if (!active() || !Object.values(state.jobs).some(job => job.status === 'running')) return;
+ if (!active() || ![...Object.values(state.jobs), ...(away ? [away.job] : [])].some(job => job.status === 'running')) return;
for (const item of log.children) item.tick?.();
report();
}, 250);
@@ -467,12 +606,19 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
}
render();
return {element, input, sync, refresh: poll,
- scrollToJob(id) { log.querySelector(`[data-job="${CSS.escape(id)}"]`)?.scrollIntoView({block: 'center', behavior: 'smooth'}); },
+ scrollToJob(id) {
+ // A job of another conversation: go to that conversation, which opens at its end where the job is.
+ if (away?.job.id === id && !state.jobs[id]) chooseChat(away.session);
+ else log.querySelector(`[data-job="${CSS.escape(id)}"]`)?.scrollIntoView({block: 'center', behavior: 'smooth'});
+ },
async stopAll() {
- const ids = Object.values(state.jobs).filter(job => WORKING.includes(job.status)).map(job => job.id);
+ const ids = [...new Set([...Object.values(state.jobs).filter(job => WORKING.includes(job.status)).map(job => job.id), ...(away?.ids || [])])];
ids.forEach(id => stopping.add(id)); render();
await Promise.allSettled(ids.map(id => agentPost(api, '/freevideo/agent/activity/cancel', {id})));
poll();
},
- stop() { stopped = true; closed.abort(); clearInterval(moving); clearTimeout(timer); timer = null; document.removeEventListener('visibilitychange', visible); log.querySelectorAll('video').forEach(video => video.pause()); }};
+ stop() { stopped = true; closed.abort(); clearInterval(moving); clearTimeout(timer); timer = null;
+ document.removeEventListener('visibilitychange', visible); document.removeEventListener('pointerdown', outside, true);
+ document.removeEventListener('keydown', keys, true); window.removeEventListener('resize', resize);
+ log.querySelectorAll('video').forEach(video => video.pause()); }};
}
diff --git a/web/autopilot_conversations.js b/web/autopilot_conversations.js
new file mode 100644
index 0000000..ce2baca
--- /dev/null
+++ b/web/autopilot_conversations.js
@@ -0,0 +1,21 @@
+// The list is a server snapshot, in the server's order. An unsaid current conversation need not be in it.
+export const emptyConversations = () => ({supported: null, current: null, conversations: []});
+export const selectConversation = (state, session) => ({...state, current: session ?? null});
+export const hasConversations = state => state.supported === true && state.conversations.length > 0;
+// The first other conversation with work under way; null when there is none.
+export const runningElsewhere = (state, session) => state.conversations.find(row => row.running > 0 && row.id !== session) || null;
+
+export function mergeConversations(state, data, status = 200) {
+ // A legacy server is probed once per page; ordinary errors retain the last good snapshot.
+ if (status === 404) return {...state, supported: false, conversations: []};
+ if (state.supported === false || status !== 200 || !Array.isArray(data?.conversations)) return state;
+ const seen = new Set(), conversations = [];
+ for (const row of data.conversations) {
+ if (typeof row?.id !== 'string' || !row.id || typeof row.title !== 'string' || !row.title.trim() || seen.has(row.id)) continue;
+ seen.add(row.id);
+ conversations.push({id: row.id, title: row.title, updated_at: row.updated_at,
+ running: Math.max(0, Math.floor(Number(row.running) || 0))});
+ if (conversations.length === 50) break;
+ }
+ return {...state, supported: true, conversations};
+}
diff --git a/web/health.js b/web/health.js
index 0207a59..111fe4b 100644
--- a/web/health.js
+++ b/web/health.js
@@ -13,7 +13,7 @@ const t = (en, zh) => cn ? zh : en;
// launcher.js removes this flag during setup; read it before that.
const launchVisit = query.get('freevideo') === 'launch';
// Every script this folder ships; a test keeps the list in step with web/*.js.
-export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'browser_extension.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
+export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js',
'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'launcher.js', 'length_plan.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js', 'studio_recent.js',