Skip to content

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

Agent conversations: delete from the row menu; a deleting one takes no new work

Bowen Xue1e43b6a4abb0
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
index a0b4492..027f35f 100644
--- a/freevideo_engine/agent/errors.py
+++ b/freevideo_engine/agent/errors.py
@@ -164,7 +164,16 @@ REPAIR = {
}
+# A conversation that is not there: the user may delete one while the agent still works or waits in it.
+SESSION_GONE = ('This conversation does not exist; the user may have deleted it.',
+ 'Do not repeat elsewhere what you were saying or doing for it. Call the wait again without a session '
+ '(GET /freevideo/agent/v1/inbox?wait=50; MCP: freevideo_wait without id) and carry on in the session '
+ 'it names.')
+
+
def recovery(code, *, kind=None, stage='request', resumable=True):
+ if kind == 'session' and code == 'not_found':
+ return SESSION_GONE[1]
if kind == 'image' and code == 'pack_missing':
return ERRORS[code][3]
if kind == 'image' and code == 'no_memory':
@@ -210,6 +219,8 @@ def build(code, *, details=None, request=None, validation=False, message=None, n
action = recovery(code, kind=kind, stage=stage, resumable=resumable)
if kind == 'image':
default_message = IMAGE_ERRORS.get(code, default_message)
+ if kind == 'session' and code == 'not_found':
+ default_message = SESSION_GONE[0]
result = dict(code=code, message=message if validation and message else default_message,
details=(details or []) if validation else safe_details(details or []),
retryable=retryable, request_id=request or request_id(),
diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py
index 4384f12..c5623e0 100644
--- a/freevideo_engine/agent/jobs.py
+++ b/freevideo_engine/agent/jobs.py
@@ -455,6 +455,8 @@ class Jobs:
# Optional executor hook: called as parent_allowed(row['parent']) before a
# child with a parent may start. A False answer records the job as cancelled.
self.parent_allowed = None
+ # Optional: called as session_open(sid) while work for a conversation is committed; raises if it is gone.
+ self.session_open = None
from .projects import Projects
# The page keeps its projects under ComfyUI's output folder; loading may already poll project jobs.
self.projects = Projects(port.output_root)
@@ -765,6 +767,8 @@ class Jobs:
if receipt:
receipt['jobs'] = [r['id'] for r in rows]
rows[0]['receipts'] = [receipt]
+ if self.session_open is not None and rows and rows[0].get('session'):
+ self.session_open(rows[0]['session']) # Deleting a conversation checks for work under this same lock.
self.save_batch(rows)
self.jobs.update({r['id']: r for r in rows})
return rows, False
diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.py
index f752ab5..8d21f09 100644
--- a/freevideo_engine/agent/productions.py
+++ b/freevideo_engine/agent/productions.py
@@ -560,6 +560,8 @@ class Productions:
if ref:
record['receipts'].append(dict(key=ref, digest=digest, result=result,
**({'client': client} if client else {})))
+ if self.jobs.session_open is not None and record.get('session'):
+ self.jobs.session_open(record['session']) # Deleting a conversation checks for films under this same lock.
self._save(record)
if cards:
self.jobs.cast.used(sorted(cards), identity)
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index 0034678..f973670 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -360,6 +360,7 @@ def register():
# Operations an agent runs only after the user approves them; the page changes the policy.
confirmations = Confirmations(port.output_root / 'FreeVideo' / '.agent' / 'confirm.json', sessions)
jobs.productions.gate = confirmations.gate
+ jobs.session_open = sessions.require_open
except Exception as error:
# Optional agent state must never prevent the studio or other routes from loading.
logging.getLogger(__name__).warning('[FreeVideo] Agent startup unavailable: %s', error)
@@ -979,6 +980,34 @@ def register():
request_id=errors.request_id())}, 409)
return reply(done[1], done[0])
+ @routes.post('/freevideo/agent/chat/delete')
+ @guarded
+ async def chat_delete(request):
+ value = await body(request)
+ def write():
+ store = work_sessions()
+ before = chat_session(store)
+ sid = chat_session(store, value['session'])
+ if sid is None:
+ raise JobError('not_found', 'No conversation')
+ # Work in progress still writes into its conversation; finished videos stay in the library.
+ # New work is refused first, so what is counted below cannot grow before the file goes.
+ store.begin_delete(sid)
+ try:
+ with jobs.lock: # Productions share it.
+ if (any(r.get('session') == sid and r['status'] in ACTIVE for r in jobs.rows())
+ or any(f['session'] == sid and not f['paused']
+ for f in jobs.productions.list(status='active', limit=None))):
+ raise JobError('conflict', 'Work is in progress in this conversation')
+ store.delete(sid)
+ except BaseException:
+ store.end_delete(sid)
+ raise
+ chat['folds'].pop(sid, None) # The page cache held its whole text.
+ chat_moved(store, before)
+ return dict(deleted=sid, here=chat_session(store), agent=agent_state())
+ return reply(await asyncio.to_thread(write))
+
@routes.get('/freevideo/agent/chat/video')
@guarded
async def chat_video(request):
@@ -1261,6 +1290,9 @@ def register():
after = row['seq']
except (ConnectionError, asyncio.CancelledError):
pass
+ except JobError as error:
+ if error.code != 'not_found':
+ raise # A deleted conversation ends its stream; the next request for it says it is gone.
finally:
tasks = [task for task in (disconnect, pending) if task is not None]
for task in tasks:
@@ -1607,7 +1639,9 @@ def register():
try:
while True:
if follow:
- sid = request['agent_session'] = await asyncio.to_thread(store.current_for, client) or sid
+ # The user may delete the conversation the agent waits in; with none left, it listens in a new one.
+ sid = request['agent_session'] = await asyncio.to_thread(
+ lambda: store.current_for(client) or (sid if store.has(client, sid) else store.create(client=client)['id']))
if store is not None and sid is not None:
# Mark before reading so words arriving in between wake the wait below.
def read():
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index 62f22f7..767fe18 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -386,6 +386,7 @@ def contracts(*, local=False):
('/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/list', 'GET', None), ('/chat/new', 'POST', EMPTY),
+ ('/chat/delete', 'POST', obj({'session': SESSION}, ('session',))),
('/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')))):
diff --git a/freevideo_engine/agent/sessions.py b/freevideo_engine/agent/sessions.py
index 5fd002e..adf4946 100644
--- a/freevideo_engine/agent/sessions.py
+++ b/freevideo_engine/agent/sessions.py
@@ -22,6 +22,8 @@ class SessionError(JobError):
def view(self):
if self.code == 'invalid_request':
return errors.validation(self.details['details'])
+ if self.code == 'not_found':
+ return errors.build(self.code, kind='session')
return super().view()
@@ -65,6 +67,7 @@ class Sessions:
self._chosen = set()
self._waiters = {}
self._partial = set()
+ self._closing = set() # Being deleted: no new work may start in them.
self.root.mkdir(parents=True, exist_ok=True)
self._load()
@@ -168,6 +171,42 @@ class Sessions:
self._chosen.add(sid)
return deepcopy(self._meta[sid])
+ def require_open(self, sid) -> None:
+ """not_found unless the conversation exists and is not being deleted; work calls this as it is committed."""
+ with self.lock:
+ self._get(sid)
+ if sid in self._closing:
+ raise SessionError('not_found', 'Session does not exist')
+
+ def begin_delete(self, sid) -> None:
+ """Refuse new work in the conversation until delete() or end_delete(); the caller then checks for work in it."""
+ with self.lock:
+ self._get(sid)
+ self._closing.add(sid)
+
+ def end_delete(self, sid) -> None:
+ with self.lock:
+ self._closing.discard(sid)
+
+ def delete(self, sid) -> None:
+ """Forget a conversation and remove its file. A wait in it ends empty; anything later says not_found."""
+ with self.lock:
+ self._get(sid)
+ self._path(sid).unlink(missing_ok=True)
+ self._closing.discard(sid)
+ waiters = self._waiters.pop(sid, ())
+ for kept in (self._meta, self._ids, self._clients, self._initial_seq, self._user_seq, self._acted, self._said):
+ kept.pop(sid, None)
+ self._chosen.discard(sid)
+ self._partial.discard(sid)
+ for key in [key for key in self._readers if key[0] == sid]:
+ del self._readers[key]
+ for loop, signal in waiters:
+ try:
+ loop.call_soon_threadsafe(signal.set)
+ except RuntimeError:
+ pass # A closed client loop no longer needs notification.
+
def list(self, *, limit=50, before=None) -> dict:
_check(schema.session_schema('list'), dict(limit=limit, **({'before': before} if before is not None else {})))
with self.lock:
@@ -281,6 +320,8 @@ class Sessions:
def read():
with self.lock:
+ if sid not in self._meta:
+ return [], None # Deleted while waiting.
rows = self._events(sid, cursor, self.max_events)
found = [row for row in rows if (types is None or row['type'] in types)
and (by is None or row['by'] == by)]
@@ -311,7 +352,7 @@ class Sessions:
# after the scan schedule set() on the loop and cannot lose a wakeup.
signal.clear()
found, cursor = await offload(read)
- if found:
+ if found or cursor is None:
return found
if leave is not None and await offload(leave):
return []
diff --git a/web/autopilot_chat.css b/web/autopilot_chat.css
index ea0c802..10d32eb 100644
--- a/web/autopilot_chat.css
+++ b/web/autopilot_chat.css
@@ -4,7 +4,7 @@
.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-conversations{position:relative;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}
@@ -12,6 +12,25 @@
.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}
+/* The row button keeps its full frame; the inset action only takes space from the title. */
+.fv-chat-conversation-row{position:relative;min-width:0;display:flex;align-items:center;border-radius:var(--fv-chats-radius)}
+.fv-chat-conversation-row:is(:hover,:focus-within,[data-menu-open=true]){background:var(--fv-raised)}
+.fv-studio .fv-chat-conversations .fv-chat-conversation{flex:1;width:100%}
+.fv-studio .fv-chat-conversation-row:has(> .fv-chat-more:not([hidden])):is(:hover,:focus-within,[data-menu-open=true]) .fv-chat-conversation{padding-right:calc(var(--fv-chats-pad) + 28px)}
+.fv-studio .fv-chat-conversations .fv-chat-more{position:absolute;right:1px;top:50%;transform:translateY(-50%);width:0;height:28px;min-height:28px;padding:0;border:0;overflow:hidden;justify-content:center;color:var(--fv-muted);opacity:0;pointer-events:none}
+.fv-studio .fv-chat-conversation-row:is(:hover,:focus-within,[data-menu-open=true]) .fv-chat-more{width:28px;opacity:1;pointer-events:auto}
+.fv-studio .fv-chat-conversations .fv-chat-more:hover:not(:disabled){background:transparent;color:var(--fv-ink)}
+.fv-chat-more svg{flex:none}
+/* Menu values match .fv-menu / .fv-menu-item in result_actions.css (lines 16–18). */
+.fv-chat-menu{box-sizing:border-box;position:absolute;z-index:5;display:grid;width:max-content;max-width:calc(100% - 2px);max-height:100%;overflow:auto;padding:6px;border:1px solid var(--fv-border);border-radius:13px;background:var(--fv-raised);box-shadow:0 14px 36px #00000073;animation:fv-chat-menu-enter .16s ease}
+.fv-chat-menu-layer{grid-area:1/1;display:flex;min-width:0}
+.fv-chat-menu-layer[data-active=false]{visibility:hidden;pointer-events:none}
+.fv-studio .fv-chat-menu .fv-chat-menu-item{flex:1;width:auto;min-height:0;padding:9px 11px;border:0;border-radius:9px;background:none;color:var(--fv-ink);font-size:13px;white-space:nowrap}
+.fv-studio .fv-chat-menu .fv-chat-menu-item:is(:hover,:focus-visible){background:var(--fv-hover);outline:none}
+.fv-studio .fv-chat-menu .fv-chat-menu-delete{color:var(--fv-danger)}
+.fv-studio .fv-chat-menu .fv-chat-menu-delete:is(:hover,:focus-visible){background:var(--fv-danger-subtle)}
+@keyframes fv-chat-menu-enter{from{opacity:0}}
+@media(hover:none){.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-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}
@@ -83,6 +102,8 @@
.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:720px){
+ .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-tools:not([hidden]){display:flex;padding-top:12px;margin-bottom:-12px}
@@ -93,4 +114,4 @@
}
@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}}
+@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,.fv-chat-menu{animation:none}}
diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js
index 4184f84..db97647 100644
--- a/web/autopilot_chat.js
+++ b/web/autopilot_chat.js
@@ -2,7 +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';
+import {canDeleteConversation, conversationMenu, emptyConversations, hasConversations, mergeConversations, removeConversation, 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);
@@ -164,33 +164,145 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
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;
+ let menuState = null, changingMenu = false;
+ const deleting = new Set(), deleted = new Set();
+ // One overlay outside the scrolling list, positioned in the sidebar's own coordinates.
+ const menu = el('div', 'fv-chat-menu'), first = el('div', 'fv-chat-menu-layer'), confirmation = el('div', 'fv-chat-menu-layer fv-chat-menu-confirm');
+ menu.id = `${sidebar.id}-menu`; menu.setAttribute('role', 'menu'); menu.hidden = true;
+ const remove = press('fv-chat-menu-item', t('Delete', '删除'), () => {
+ menuState = conversationMenu(conversations, menuState, 'confirm');
+ updateMenu(true);
+ });
+ const yes = press('fv-chat-menu-item fv-chat-menu-delete', t('Delete', '删除'), () => void deleteChat(menuState?.session));
+ const cancel = press('fv-chat-menu-item', t('Cancel', '取消'), () => closeMenu(true));
+ for (const button of [remove, yes, cancel]) button.setAttribute('role', 'menuitem');
+ first.append(remove); confirmation.append(yes, cancel); menu.append(first, confirmation); sidebar.append(menu);
+ const menuOrigin = () => listNodes.get(menuState?.session)?.more;
+ const inMenu = target => menu.contains(target) || menuOrigin()?.contains(target);
+ const leaveMenu = event => { if (menuState && !changingMenu && !inMenu(event.relatedTarget)) closeMenu(); };
+ menu.addEventListener('focusout', leaveMenu);
function drawer(on, restore = false) {
+ if (!on) closeMenu();
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 positionMenu() {
+ const node = listNodes.get(menuState?.session);
+ if (!node) return;
+ const bounds = sidebar.getBoundingClientRect(), anchor = node.more.getBoundingClientRect(), row = node.row.getBoundingClientRect();
+ // Local dimensions also handle the enclosing dialog's entry scale without fixed-position offsets.
+ const sx = bounds.width / (sidebar.offsetWidth || bounds.width) || 1, sy = bounds.height / (sidebar.offsetHeight || bounds.height) || 1;
+ const left = bounds.left + (sidebar.clientLeft || 0) * sx, top = bounds.top + (sidebar.clientTop || 0) * sy;
+ const width = sidebar.clientWidth, height = sidebar.clientHeight || bounds.height / sy;
+ const mw = menu.offsetWidth || menu.getBoundingClientRect().width / sx, mh = menu.offsetHeight || menu.getBoundingClientRect().height / sy;
+ const x0 = Math.max(0, -left / sx), x1 = Math.min(width, ((window.innerWidth || bounds.right) - left) / sx);
+ const y0 = Math.max(0, -top / sy), y1 = Math.min(height, ((window.innerHeight || bounds.bottom) - top) / sy);
+ const below = (row.bottom - top) / sy, above = (row.top - top) / sy - mh;
+ menu.style.left = `${Math.max(x0, Math.min((anchor.right - left) / sx - mw, x1 - mw))}px`;
+ menu.style.top = `${Math.max(y0, Math.min(below + mh <= y1 ? below : above, y1 - mh))}px`;
+ }
+ function updateMenu(focus = false) {
+ changingMenu = true;
+ try {
+ menu.hidden = !menuState;
+ const confirming = menuState?.stage === 'confirm';
+ first.dataset.active = String(!confirming); confirmation.dataset.active = String(confirming);
+ first.inert = !!confirming; confirmation.inert = !confirming;
+ remove.tabIndex = confirming ? -1 : 0; yes.tabIndex = cancel.tabIndex = confirming ? 0 : -1;
+ yes.disabled = cancel.disabled = deleting.has(menuState?.session);
+ for (const [id, node] of listNodes) {
+ const opened = menuState?.session === id;
+ node.row.dataset.menuOpen = String(opened); node.more.setAttribute('aria-expanded', String(opened));
+ }
+ if (menuState) {
+ positionMenu();
+ if (focus) (confirming ? cancel : remove).focus({preventScroll: true});
+ }
+ } finally { changingMenu = false; }
+ }
+ function closeMenu(restore = false) {
+ const origin = menuOrigin();
+ menuState = conversationMenu(conversations, menuState, 'close'); updateMenu();
+ if (restore && origin && !origin.hidden) origin.focus({preventScroll: true});
+ }
+ function openMenu(session) {
+ if (menuState?.session === session) { closeMenu(); return; }
+ if (deleting.has(session)) return;
+ menuState = conversationMenu(conversations, menuState, 'open', session); updateMenu(true);
+ }
function renderConversations() {
- const visible = hasConversations(conversations);
+ const previous = menuState;
+ const lostFocus = previous && inMenu(document.activeElement);
+ menuState = conversationMenu(conversations, menuState);
+ // After the final deletion, keep New chat reachable as the keyboard destination.
+ const visible = hasConversations(conversations) || conversations.supported === true && deleted.size > 0;
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); }
+ for (const [id, node] of listNodes) if (!keep.has(id)) { node.row.remove(); listNodes.delete(id); }
conversations.conversations.forEach((row, index) => {
let node = listNodes.get(row.id);
if (!node) {
+ const container = el('div', 'fv-chat-conversation-row');
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});
+ const more = press('fv-chat-more', null, () => openMenu(row.id));
+ more.title = t('More', '更多'); more.setAttribute('aria-haspopup', 'menu'); more.setAttribute('aria-controls', menu.id);
+ more.append(glyph('M5 12h.01M12 12h.01M19 12h.01', 3.5));
+ more.addEventListener('focusout', leaveMenu); container.append(button, more);
+ listNodes.set(row.id, node = {row: container, button, dot, title, more});
}
node.title.textContent = row.title; node.button.title = row.title; node.dot.hidden = row.running <= 0;
+ node.more.setAttribute('aria-label', t(`More: ${row.title}`, `更多:${row.title}`));
+ node.more.hidden = !canDeleteConversation(row);
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);
+ if (list.children[index] !== node.row) list.insertBefore(node.row, list.children[index] || null);
});
+ updateMenu();
+ if (lostFocus && !menuState) (listNodes.get(previous.session)?.button || (visible ? newChat : input)).focus({preventScroll: true});
+ }
+ async function deleteChat(session) {
+ if (!menuState || deleting.has(session) || menuState.session !== session || menuState.stage !== 'confirm' || !active()) return;
+ const ids = conversations.conversations.map(row => row.id), index = ids.indexOf(session);
+ const neighbor = ids[index + 1] || ids[index - 1];
+ deleting.add(session);
+ // A disabled focused button can lose native focus. Keep it on the origin while awaiting the request.
+ menuOrigin()?.focus({preventScroll: true}); updateMenu();
+ try {
+ const response = await agentPost(api, '/freevideo/agent/chat/delete', {session});
+ if (stopped) return;
+ const data = await response.json().catch(() => ({}));
+ if (stopped) return;
+ if (response.ok || response.status === 404 && data.error?.code === 'not_found') {
+ const current = conversations.current === session;
+ deleted.add(session); conversations = removeConversation(conversations, session, data.here);
+ if (menuState?.session === session) closeMenu();
+ if (current) {
+ selectedSession = undefined; selection++; focusSession = null; away = null;
+ const agent = data.agent || state.agent;
+ resetChat(); state.agent = agent; input.value = ''; grow(); render(); report(); void poll();
+ }
+ renderConversations();
+ (listNodes.get(neighbor)?.button || listNodes.values().next().value?.button || newChat).focus({preventScroll: true});
+ void readConversations(true);
+ } else if (response.status === 409) {
+ if (menuState?.session === session) closeMenu();
+ if (data.error?.code === 'not_connected') { state = {...state, agent: {connected: false, name: null}}; render(); report(); }
+ else void readConversations(true);
+ }
+ } catch { /* Keep the row available for another try, without interrupting the conversation. */ }
+ finally {
+ deleting.delete(session);
+ if (menuState?.session === session) closeMenu();
+ if (!stopped) renderConversations();
+ }
}
function chooseChat(session, focus = false) {
+ closeMenu();
selectedSession = session; selection++; pinned = true; away = null;
conversations = selectConversation(conversations, session); renderConversations();
input.value = ''; grow(); drawer(false);
@@ -199,6 +311,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
render(); void readConversations(true); void poll();
}
async function startChat() {
+ closeMenu();
if (creating || !active() || conversations.supported !== true) return;
creating = true; renderConversations(); render();
try {
@@ -223,6 +336,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
const data = response.ok ? await response.json() : null;
if (stopped) return;
conversations = mergeConversations(conversations, data, response.status);
+ // A list read started before a deletion must not put the deleted row back.
+ conversations = {...conversations, conversations: conversations.conversations.filter(row => !deleted.has(row.id))};
renderConversations();
if (conversations.supported === false && selectedSession !== undefined) { selectedSession = undefined; selection++; void poll(); }
} catch { /* List failures do not interrupt reading or sending. */ }
@@ -230,19 +345,33 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
if (listAgain) { listAgain = false; void readConversations(true); }
}
const outside = event => {
+ if (menuState && !inMenu(event.target)) closeMenu();
if (chats.getAttribute('aria-expanded') === 'true' && !sidebar.contains(event.target) && !chats.contains(event.target)) drawer(false, true);
};
const keys = event => {
+ if (event.key === 'Escape' && menuState) {
+ event.preventDefault(); event.stopImmediatePropagation(); closeMenu(true); return;
+ }
+ // Confirmation always cycles its two choices. In the drawer, the open menu owns Tab in both stages.
+ if (menuState && (event.key === 'Tab' && (narrow() || menuState.stage === 'confirm')
+ || menuState.stage === 'confirm' && ['ArrowLeft', 'ArrowRight'].includes(event.key))) {
+ event.preventDefault(); event.stopPropagation();
+ const buttons = (menuState.stage === 'confirm' ? [yes, cancel] : [remove]).filter(button => !button.disabled);
+ const at = buttons.indexOf(document.activeElement), back = event.shiftKey || event.key === 'ArrowLeft';
+ buttons[(at + (back ? -1 : 1) + buttons.length) % buttons.length]?.focus({preventScroll: true}); return;
+ }
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);
+ const buttons = [...sidebar.querySelectorAll('button')].filter(button => !button.disabled && !button.hidden && !menu.contains(button) && !button.closest('[hidden]'));
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); };
+ const resize = () => { closeMenu(); if (!narrow()) drawer(false); };
+ const listScroll = () => closeMenu();
+ list.addEventListener('scroll', listScroll);
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.
@@ -625,8 +754,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
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;
+ stop() { closeMenu(); 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);
+ document.removeEventListener('keydown', keys, true); window.removeEventListener('resize', resize); list.removeEventListener('scroll', listScroll);
log.querySelectorAll('video').forEach(video => video.pause()); }};
}
diff --git a/web/autopilot_conversations.js b/web/autopilot_conversations.js
index ce2baca..9974dd1 100644
--- a/web/autopilot_conversations.js
+++ b/web/autopilot_conversations.js
@@ -4,6 +4,20 @@ export const selectConversation = (state, session) => ({...state, current: sessi
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 const canDeleteConversation = row => !!row?.id && !(row.running > 0);
+// The one menu moves from closed to Delete, then to Delete/Cancel. Snapshots can close either stage.
+export function conversationMenu(state, menu, action = 'reconcile', session = null) {
+ const eligible = id => state.supported === true && state.conversations.some(row => row.id === id && canDeleteConversation(row));
+ if (action === 'close') return null;
+ if (action === 'open') return eligible(session) ? {session, stage: 'delete'} : null;
+ if (!menu || !eligible(menu.session)) return null;
+ if (action === 'confirm' && menu.stage === 'delete') return {...menu, stage: 'confirm'};
+ return menu;
+}
+// Only deleting the conversation being read changes the reader's destination. An unsaid `here` is valid too.
+export const removeConversation = (state, session, here = null) => ({...state,
+ current: state.current === session ? here ?? null : state.current,
+ conversations: state.conversations.filter(row => row.id !== session)});
export function mergeConversations(state, data, status = 200) {
// A legacy server is probed once per page; ordinary errors retain the last good snapshot.