Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Continue in a new chat from here (frontend) (#617)
Oleksandr Ivanchenkoc2f866c7d4de
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 1cbc5c4d..32edfb3f 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -157,7 +157,8 @@ import { canRunNow } from './engines';import { useEngines } from './useEngines';import { canInstall, setupApi } from './setupInstall';import { claudeNeedsSignIn } from './claudeLogin';-import { personFetch } from './auth';+import { PersonCancelledError, personFetch } from './auth';+import { ContinueError, continueChatApi, continueErrorLine, continuedLine, forkOf } from './continueChat';import { OPEN_ADD_TOOL_EVENT, type OpenAddTool } from './mcp';import { teamChannelOf, teamOfChannel } from './teamChannel';import { PromptContext, suggestedPrompts } from './suggestedPrompts';@@ -2436,6 +2437,26 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}};+ // Continue in a new chat from here (continueChat.ts). A 403 means this session is a bot's: the item hides.+ const [botSession, setBotSession] = useState(false);+ const [focusComposerKey, setFocusComposerKey] = useState(0);+ const handleContinueFrom = async (msg: ChatMessage): Promise<string | void> => {+ const kwantId = selectedIdRef.current;+ try {+ const t = await continueChatApi.fromMessage<Thread>(msg.id, personFetch);+ knownThreadsRef.current.add(t.id);+ setThreadsByKwant((prev) => ({ ...prev, [t.kwant_id]: upsertThread(prev[t.kwant_id], t) }));+ if (selectedIdRef.current !== kwantId || isChannelRef.current) return;+ setOpenThreadId(t.id);+ setFocusComposerKey((n) => n + 1);+ playSfx('click');+ } catch (err) {+ if (err instanceof PersonCancelledError) return err.message;+ if (err instanceof ContinueError && err.status === 403) setBotSession(true);+ return continueErrorLine(err);+ }+ };+/** Stops a thread's work: its delegation when one is open (so the lead hears), else its turns. */const handleStopThread = async (t: Thread): Promise<string | void> => {const d = t.delegation ? delegationsRef.current[t.delegation.id] ?? t.delegation : null;@@ -3557,6 +3578,26 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({// The bot's conversations, the open thread's controls, and "working on…" elsewhere.const agentThreads = currentKwant ? threadsByKwant[currentKwant.id] : undefined;const shownThread = openThreadId ? agentThreads?.find((t) => t.id === openThreadId) ?? null : null;+ // Continue in a new chat: only in a chat with one bot (its main chat or a `chat` thread we know), never a team's.+ const canContinueHere = !!currentKwant && !currentTeam && !botSession && (!openThreadId || shownThread?.kind === 'chat');+ const fork = forkOf(shownThread);+ const continuedFrom =+ fork && currentKwant+ ? {+ text: continuedLine(+ fork.context === currentKwant.id ? currentKwant.name : agentThreads?.find((t) => t.id === fork.context)?.title ?? 'an earlier chat',+ fork.copied,+ fork.truncated,+ fork.context === currentKwant.id,+ ),+ onOpen: () => {+ if (fork.context === currentKwant.id) setOpenThreadId(null);+ else openThreadChecked(currentKwant.id, fork.context);+ setHighlightMessageId(fork.messageId);+ playSfx('click');+ },+ }+ : null;const elsewhere = currentKwant ? backgroundTurns(turns, currentKwant.id).filter((t) => t.context_id !== openCtx) : [];const describeContext = (ctx: string, kwantId: string): string =>threadsByKwant[kwantId]?.find((t) => t.id === ctx)?.title ??@@ -4337,6 +4378,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}: undefined}+ onContinueFrom={canContinueHere ? handleContinueFrom : undefined}+ threadKind={shownThread?.kind ?? null}+ continuedFrom={continuedFrom}+ focusComposerKey={focusComposerKey}highlightMessageId={highlightMessageId}onHighlightDone={() => setHighlightMessageId(null)}subHeader={subHeader}diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex cf2ae0f2..47363720 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -84,6 +84,8 @@ import { APPROVE_TEXT, asksApproval, changePlaceholder, metaHidesApprove } fromimport { DoneCheckLine } from './DoneMarker';import { ApproveRow } from './ApproveRow';import { CopyGhost } from './CopyGhost';+import { ContinuedLine, MessageMore, MessageMoreError } from './MessageMore';+import { CONTINUE_LABEL, canContinueFrom } from '../continueChat';import { RoutineRow } from './RoutineRow';import { routineOf } from '../routineRow';import { BudgetPausedNotice, ExpiredApprovalNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';@@ -296,6 +298,17 @@ export interface ChatViewProps {pinned?: PinnedItem[];/** Opens the channel's instructions editor; only for channels. */onEditInstructions?: () => void;+ /**+ * Continue in a new chat from here (continueChat.ts): set only in a chat with one bot on a person's session.+ * Resolves to an error line when it failed; on success the app opens the new chat.+ */+ onContinueFrom?: (msg: ChatMessage) => Promise<string | void>;+ /** The open thread's kind ('chat' or 'delegation'); absent in the bot's main chat. */+ threadKind?: string | null;+ /** A continued chat's quiet first line, linking back to the message it came from. */+ continuedFrom?: { text: string; onOpen: () => void } | null;+ /** Goes up when the composer should take focus (a new continued chat just opened). */+ focusComposerKey?: number;/** A message to scroll to and flash (from search). */highlightMessageId?: string | null;onHighlightDone?: () => void;@@ -555,6 +568,10 @@ export const ChatView: React.FC<ChatViewProps> = ({pinned = [],onEditInstructions,highlightMessageId,+ onContinueFrom,+ threadKind,+ continuedFrom,+ focusComposerKey,onHighlightDone,viewingHistory,onJumpToLatest,@@ -1029,6 +1046,52 @@ export const ChatView: React.FC<ChatViewProps> = ({ta.focus();ta.setSelectionRange(ta.value.length, ta.value.length);};+ // Continue in a new chat: the message whose request runs, and the one plain line when it failed.+ const [continuing, setContinuing] = useState<string | null>(null);+ const [continueError, setContinueError] = useState<{ id: string; text: string } | null>(null);+ useEffect(() => {+ setContinuing(null);+ setContinueError(null);+ }, [contextKey]);+ useEffect(() => {+ if (!focusComposerKey) return;+ // After the new chat's first paint, so its composer is the one that takes focus+ const raf = requestAnimationFrame(() => focusComposer());+ return () => cancelAnimationFrame(raf);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [focusComposerKey]);+ const continueFrom = async (msg: ChatMessage) => {+ if (!onContinueFrom || continuing) return;+ setContinuing(msg.id);+ setContinueError(null);+ try {+ const err = await onContinueFrom(msg);+ if (err) setContinueError({ id: msg.id, text: err });+ } finally {+ setContinuing((cur) => (cur === msg.id ? null : cur));+ }+ };+ const newestId = messages.length ? messages[messages.length - 1].id : null;+ const continueMenu = (msg: ChatMessage, about: string, align: 'start' | 'end', reveal?: 'hover') =>+ onContinueFrom &&+ canContinueFrom({+ chatKind: home?.kind,+ threadKind,+ message: msg,+ newest: msg.id === newestId,+ streaming: isStreaming,+ botSession: false,+ }) ? (+ <MessageMore+ messageId={msg.id}+ about={about}+ align={align}+ reveal={reveal}+ busy={continuing === msg.id}+ busyLabel="Starting a new chat…"+ items={[{ label: CONTINUE_LABEL, run: () => void continueFrom(msg) }]}+ />+ ) : null;const startReply = (msg: ChatMessage) => {setReplyTo(msg);setChangeFor(null);@@ -1642,7 +1705,7 @@ export const ChatView: React.FC<ChatViewProps> = ({data-shared-under={underReply ? '' : undefined}// The log's space-y gap would win over a margin class; inline style pulls the tiles up to the reply's actionsstyle={underReply ? { marginTop: '0.5rem' } : undefined}- className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl focus:outline-none ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''} ${+ className={`group/msg flex items-start gap-3.5 w-full max-w-5xl rounded-xl focus:outline-none ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''} ${flashId === msg.id ? (flashKind === 'quote' ? 'kw-flash-quote' : 'kw-flash') : ''} ${freshTrack.current.fresh.has(msg.id) ? 'kws-in' : ''}`}>@@ -1750,6 +1813,12 @@ export const ChatView: React.FC<ChatViewProps> = ({{/* Message Body Bubble */}{!filesOnly && (text.trim() || !files.length) && (+ <div className={isUser ? 'relative w-full max-w-2xl' : 'contents'}>+ {isUser && (() => {+ // The person's message: the overflow sits in the empty gutter left of the bubble, bottom-aligned, no row+ const more = continueMenu(msg, 'your message', 'end', 'hover');+ return more ? <div className="absolute right-full bottom-0 mr-1" data-message-more-gutter="">{more}</div> : null;+ })()}<divclassName={`px-3.5 py-3 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full ${isUser@@ -1778,6 +1847,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<MarkdownRenderer content={text} results={msg.results} messageId={msg.id} />)}</div>+ </div>)}{files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} sharedBy={filesOnly && !isUser ? displayName : undefined} at={msg.created_at ?? null} />}{isUser && heldNotes?.[msg.id]}@@ -1855,9 +1925,11 @@ export const ChatView: React.FC<ChatViewProps> = ({</>)}<CopyGhost copied={copiedId === msg.id} tipId={`copy-tip-${msg.id}`} onCopy={() => handleCopy(text, msg.id)} />+ {continueMenu(msg, `${displayName}'s reply`, 'start')}{msg.results != null && <SmartActionsSlot messageId={msg.id} />}</div>)}+ {continueError?.id === msg.id && <MessageMoreError text={continueError.text} align={isUser ? 'end' : 'start'} />}</div></div>);@@ -2270,6 +2342,7 @@ export const ChatView: React.FC<ChatViewProps> = ({aria-busy={isStreaming}>{topCard}+ {continuedFrom && <ContinuedLine text={continuedFrom.text} onOpen={continuedFrom.onOpen} />}{welcome && messages.length === 0 && welcome}{showHome && home && (<div className="flex min-h-full items-center justify-center">diff --git a/frontend/src/components/MessageMore.tsx b/frontend/src/components/MessageMore.tsxnew file mode 100644index 00000000..d4bf1840--- /dev/null+++ b/frontend/src/components/MessageMore.tsx@@ -0,0 +1,185 @@+// The message overflow (continue-chat, brief "Frontend (Iris)" 2-5): a quiet ⋯ beside Copy holding+// "Continue in a new chat from here". Enter, Space or a click opens it with the first item focused, the arrow+// keys, Home and End move, Esc or Tab closes it, and Esc gives focus back to ⋯. 44 px targets on phones.++import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';+import { Loader2, MessageSquarePlus, MoreHorizontal } from 'lucide-react';+import { useEscapeLayer } from '../escape';++export interface MoreItem {+ label: string;+ run: () => void;+}++export const MessageMore: React.FC<{+ messageId: string;+ /** Who wrote it, for the button's name: "More for your message", "More for Cody's reply". */+ about: string;+ items: MoreItem[];+ /** 'end' for the person's messages (right side), 'start' for replies. */+ align?: 'start' | 'end';+ /**+ * 'hover': on hover devices ⋯ stays hidden until the message is hovered or focused, or the menu is open+ * (the person's gutter ⋯). Phones always show it.+ */+ reveal?: 'hover';+ /** An item is running (a new chat being made): ⋯ spins, can't be pressed, and keeps focus. */+ busy?: boolean;+ busyLabel?: string;+}> = ({ messageId, about, items, align = 'start', reveal, busy = false, busyLabel = 'Working…' }) => {+ const [open, setOpen] = useState(false);+ const wrapRef = useRef<HTMLSpanElement>(null);+ const btnRef = useRef<HTMLButtonElement>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ const menuId = `more-${messageId}`;+ // Opens toward the message's side, nudged once so it stays inside the window (a reply's ⋯ at 390 px).+ const [shift, setShift] = useState(0);+ useLayoutEffect(() => {+ if (!open) {+ setShift(0);+ return;+ }+ const r = menuRef.current?.getBoundingClientRect();+ if (!r || !r.width || typeof window === 'undefined') return;+ const room = window.innerWidth - 8;+ setShift(r.right > room ? Math.max(8 - r.left, room - r.right) : r.left < 8 ? 8 - r.left : 0);+ }, [open]);+ const close = (refocus: boolean) => {+ setOpen(false);+ if (refocus) btnRef.current?.focus();+ };+ useEscapeLayer(wrapRef, open, () => close(true));++ useEffect(() => {+ if (!open) return;+ wrapRef.current?.querySelector<HTMLButtonElement>('[role="menuitem"]:not([disabled])')?.focus();+ const away = (e: MouseEvent | TouchEvent) => {+ if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener('mousedown', away);+ document.addEventListener('touchstart', away);+ return () => {+ document.removeEventListener('mousedown', away);+ document.removeEventListener('touchstart', away);+ };+ }, [open]);++ const onMenuKey = (e: React.KeyboardEvent) => {+ if (e.key === 'Tab') {+ setOpen(false);+ return;+ }+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return;+ const list = [...(wrapRef.current?.querySelectorAll<HTMLButtonElement>('[role="menuitem"]:not([disabled])') ?? [])];+ if (!list.length) return;+ e.preventDefault();+ const at = list.indexOf(document.activeElement as HTMLButtonElement);+ const next = e.key === 'Home' ? 0 : e.key === 'End' ? list.length - 1 : (at + (e.key === 'ArrowDown' ? 1 : -1) + list.length) % list.length;+ list[next].focus();+ };++ const onButtonKey = (e: React.KeyboardEvent) => {+ // ArrowDown or ArrowUp on the closed button opens it too, as menus do+ if (!open && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {+ e.preventDefault();+ setOpen(true);+ }+ };++ // aria-disabled, not disabled: a disabled button drops focus to the page, and focus stays on ⋯ while it runs.+ const shown = open || busy;+ const revealCls =+ reveal === 'hover'+ ? `transition-opacity duration-[120ms] motion-reduce:transition-none ${+ shown ? 'opacity-100' : '[@media(hover:hover)]:opacity-0 group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-within:opacity-100'+ }`+ : '';++ return (+ <span ref={wrapRef} className={`relative inline-flex shrink-0 ${revealCls}`} data-message-more="" data-reveal={reveal}>+ <button+ ref={btnRef}+ type="button"+ aria-haspopup="menu"+ aria-expanded={open}+ aria-controls={open ? menuId : undefined}+ aria-label={busy ? busyLabel : `More for ${about}`}+ aria-busy={busy || undefined}+ aria-disabled={busy || undefined}+ title={busy ? busyLabel : 'More'}+ data-message-more-button=""+ data-busy={busy ? '' : undefined}+ onClick={() => {+ if (!busy) setOpen((o) => !o);+ }}+ onKeyDown={(e) => {+ if (busy) {+ if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown' || e.key === 'ArrowUp') e.preventDefault();+ return;+ }+ onButtonKey(e);+ }}+ className={`inline-flex h-11 w-11 sm:h-8 sm:w-8 items-center justify-center rounded-lg text-zinc-400 transition-colors duration-[120ms] motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 ${+ busy ? 'cursor-progress' : 'hover:bg-zinc-800 hover:text-zinc-100 cursor-pointer'+ } ${open ? 'bg-zinc-800 text-zinc-100' : ''}`}+ >+ {busy ? (+ <Loader2 size={15} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />+ ) : (+ <MoreHorizontal size={15} aria-hidden="true" />+ )}+ </button>+ {open && (+ <div+ ref={menuRef}+ id={menuId}+ role="menu"+ aria-label={`More for ${about}`}+ onKeyDown={onMenuKey}+ data-message-more-menu=""+ style={shift ? { transform: `translateX(${shift}px)` } : undefined}+ className={`absolute bottom-full z-30 mb-1 w-max max-w-[calc(100vw-2rem)] rounded-lg border border-hairline-strong bg-surface-overlay p-1 shadow-xl ${+ align === 'end' ? 'right-0' : 'left-0'+ }`}+ >+ {items.map((it) => (+ <button+ key={it.label}+ type="button"+ role="menuitem"+ onClick={() => {+ // Focus goes back to ⋯, so an error line lands next to it; a new chat moves it to the composer after.+ close(true);+ it.run();+ }}+ className="flex w-full items-center gap-2 rounded-md px-2.5 min-h-[44px] sm:min-h-8 text-left text-[13px] sm:text-xs text-zinc-200 hover:bg-zinc-800 focus:bg-zinc-800 focus:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-400 disabled:opacity-50 disabled:hover:bg-transparent cursor-pointer disabled:cursor-default"+ >+ <MessageSquarePlus size={14} aria-hidden="true" className="shrink-0 text-zinc-400" />+ <span className="whitespace-normal">{it.label}</span>+ </button>+ ))}+ </div>+ )}+ </span>+ );+};++/** The line by the message when the request fails; polite, so it's read once. */+export const MessageMoreError: React.FC<{ text: string; align?: 'start' | 'end' }> = ({ text, align = 'start' }) => (+ <p role="status" data-continue-error="" className={`mt-1 max-w-full text-xs leading-snug text-rose-300 break-words ${align === 'end' ? 'text-right' : ''}`}>+ {text}+ </p>+);++/** The quiet first line of a continued chat; the link goes back to the pressed message. */+export const ContinuedLine: React.FC<{ text: string; onOpen: () => void }> = ({ text, onOpen }) => (+ <div data-continued-from="" className="mx-auto mb-2 flex w-full max-w-5xl justify-center px-1">+ <button+ type="button"+ onClick={onOpen}+ className="inline-flex min-h-[44px] sm:min-h-7 max-w-full items-center rounded-md px-2 text-center text-xs leading-snug text-zinc-400 underline decoration-zinc-600 underline-offset-2 hover:text-zinc-200 hover:decoration-zinc-400 transition-colors motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 break-words whitespace-normal cursor-pointer"+ >+ {text}+ </button>+ </div>+);diff --git a/frontend/src/continueChat.ts b/frontend/src/continueChat.tsnew file mode 100644index 00000000..027c3287--- /dev/null+++ b/frontend/src/continueChat.ts@@ -0,0 +1,138 @@+// Continue in a new chat from here (roadmap Next 12d; autonomy/continue-chat/brief.md, "Frontend (Iris)").+// A message's overflow offers it in a chat with one bot; the server copies every message up to the pressed one+// into a new thread of the same bot (POST /api/messages/:id/continue, Lin) and the app opens it.+// Pure helpers plus one fetch, so the node tests can load it on its own.++/** The fields a continued thread carries (Lin's thread_view); all null or absent on any other thread. */+export interface ForkFields {+ /** The chat it came from: a thread id, or the bot's id for its main chat. */+ forked_from_context?: string | null;+ /** The message pressed, in that chat. */+ forked_from_message_id?: string | null;+ /** How many messages were copied. */+ forked_copied?: number | null;+ /** True when only the newest 1,000 were copied. */+ forked_truncated?: boolean | null;+}++/** The 201: the new thread plus `copied` and `truncated` at the top level. */+export type ContinueResult<T> = T & ForkFields & { id: string; kwant_id: string; copied?: number; truncated?: boolean };++/** The newest messages the server copies; more are cut and the line says so. */+export const CONTINUE_CAP = 1000;++export const CONTINUE_LABEL = 'Continue in a new chat from here';++/**+ * Where the item shows. Only a chat with one bot: its main chat or one of its `chat` threads (not a delegation,+ * a team or any channel). Not on a message still being written (a `temp-` id, or the newest one while a reply+ * streams), not on a system line, and not once the server has said this session is a bot's (403).+ */+export function canContinueFrom(o: {+ /** The open chat: 'bot' for a bot's own chat, anything else hides it. */+ chatKind: string | null | undefined;+ /** The open thread's kind; null or undefined in the bot's main chat. */+ threadKind?: string | null;+ /** A team chat shown in the bot's pane. */+ inTeam?: boolean;+ message: { id: string; sender_role: string };+ /** True for the newest message of the chat. */+ newest: boolean;+ streaming: boolean;+ /** A bot-token session: the route answered 403 once. */+ botSession: boolean;+}): boolean {+ if (o.chatKind !== 'bot' || o.inTeam || o.botSession) return false;+ if (o.threadKind && o.threadKind !== 'chat') return false;+ const m = o.message;+ if (!m?.id || m.id.startsWith('temp-')) return false;+ if (m.sender_role !== 'user' && m.sender_role !== 'kwant') return false;+ if (o.streaming && o.newest) return false;+ return true;+}++/**+ * The quiet first line of a continued chat. `count` unknown (an older server, a reload before Lin's fields): no count.+ * `fromMain`: it came from the bot's main chat, so `title` is the bot's name ("your main chat with Ben", no quotes).+ */+export function continuedLine(title: string, count: number | null | undefined, truncated?: boolean | null, fromMain?: boolean): string {+ const t = title.trim();+ const from = fromMain ? (t ? `your main chat with ${t}` : 'your main chat') : `"${t || 'the earlier chat'}"`;+ const n = typeof count === 'number' && Number.isFinite(count) && count >= 0 ? Math.floor(count) : null;+ const words = truncated+ ? ` · the newest ${CONTINUE_CAP.toLocaleString('en-US')} messages`+ : n === null+ ? ''+ : ` · ${n.toLocaleString('en-US')} ${n === 1 ? 'message' : 'messages'}`;+ return `Continued from ${from}${words}`;+}++/** The fork a thread records, or null when it wasn't continued from another chat. */+export function forkOf(t: ForkFields | null | undefined): { context: string; messageId: string; copied: number | null; truncated: boolean } | null {+ if (!t || !t.forked_from_context || !t.forked_from_message_id) return null;+ return {+ context: t.forked_from_context,+ messageId: t.forked_from_message_id,+ copied: typeof t.forked_copied === 'number' ? t.forked_copied : null,+ truncated: t.forked_truncated === true,+ };+}++/** The one plain line by the message when the request fails; the reason after the colon starts lower-case. */+export const continueErrorLine = (err: unknown): string => {+ const raw = err instanceof Error ? err.message : typeof err === 'string' ? err : '';+ const why = raw.trim().replace(/[.\s]+$/, '') || 'something went wrong';+ return `Couldn't start a new chat: ${why.charAt(0).toLowerCase()}${why.slice(1)}.`;+};++/** Thrown with the server's words and status; a 403 means this session belongs to a bot. */+export class ContinueError extends Error {+ constructor(message: string, readonly status: number) {+ super(message);+ }+}++/**+ * The failure in our own words. Only the 400 keeps the server's text ("Only a chat with one bot can be continued.");+ * Lin's 404 and 403 bodies ("message not found", "only the person continues a chat in a new one") read like logs.+ */+export async function continueFailure(res: Response): Promise<ContinueError> {+ if (res.status === 404) return new ContinueError('that message is no longer in this chat', 404);+ if (res.status === 403) return new ContinueError('only you can do this, not a bot', 403);+ if (res.status === 400) {+ let message = 'only a chat with one bot can be continued';+ try {+ const data = await res.json();+ if (data && typeof data.error === 'string' && data.error.trim()) message = data.error.trim();+ } catch {+ // no JSON body+ }+ return new ContinueError(message, 400);+ }+ return new ContinueError(`something went wrong (error ${res.status}). Try again`, res.status);+}++/** POST /api/messages/:id/continue. `send` is `personFetch` in the app (it asks "Confirm it's you" on a 401). */+export async function continueFromMessage<T = object>(id: string, send: (url: string, init?: RequestInit) => Promise<Response>): Promise<ContinueResult<T>> {+ let res: Response;+ try {+ res = await send(`/api/messages/${encodeURIComponent(id)}/continue`, { method: 'POST' });+ } catch (err) {+ if (err instanceof Error && err.name !== 'TypeError') throw err;+ throw new ContinueError("the server didn't answer", 0);+ }+ if (res.status !== 201 && res.status !== 200) throw await continueFailure(res);+ const body = (await res.json()) as ContinueResult<T>;+ if (!body || typeof body.id !== 'string' || typeof body.kwant_id !== 'string') throw new ContinueError('the server sent back no chat', res.status);+ // The thread view carries the fork fields on newer builds; the top-level copy keeps older ones working.+ return {+ ...body,+ forked_copied: typeof body.forked_copied === 'number' ? body.forked_copied : typeof body.copied === 'number' ? body.copied : null,+ forked_truncated: typeof body.forked_truncated === 'boolean' ? body.forked_truncated : body.truncated === true,+ };+}++/** Next to `threadsApi`; kept here so threads.ts stays import-free for its tests. */+export const continueChatApi = {+ fromMessage: <T = object>(id: string, send: (url: string, init?: RequestInit) => Promise<Response> = (u, i) => fetch(u, i)) => continueFromMessage<T>(id, send),+};diff --git a/frontend/src/threads.ts b/frontend/src/threads.tsindex cc783519..70c10c19 100644--- a/frontend/src/threads.ts+++ b/frontend/src/threads.ts@@ -50,6 +50,11 @@ export interface Thread {updated_at: string;delegation?: Delegation | null;active?: ActiveTurn[];+ /** Continue in a new chat (continueChat.ts): the chat and message it was continued from; null otherwise. */+ forked_from_context?: string | null;+ forked_from_message_id?: string | null;+ forked_copied?: number | null;+ forked_truncated?: boolean | null;}// ---------------------------------------------------------------------------diff --git a/frontend/tests/continueChat.test.mjs b/frontend/tests/continueChat.test.mjsnew file mode 100644index 00000000..b0c65bb2--- /dev/null+++ b/frontend/tests/continueChat.test.mjs@@ -0,0 +1,215 @@+// Continue in a new chat from here (autonomy/continue-chat/brief.md, "Frontend (Iris)"): the API helper, where the+// item shows, the Continued line, and the overflow's keyboard.+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });+}+globalThis.IS_REACT_ACT_ENVIRONMENT = false;++const m = await loadBundled(`export * from './src/continueChat';`);+const ui = await loadBundled(`+ import React from 'react';+ import { flushSync } from 'react-dom';+ import { MessageMore, MessageMoreError, ContinuedLine } from './src/components/MessageMore';+ export { createRoot } from 'react-dom/client';+ export { React, flushSync, MessageMore, MessageMoreError, ContinuedLine };+`);++const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });++// ---- the API helper ----++test('fromMessage posts to the continue route and reads the 201', async () => {+ const calls = [];+ const send = async (url, init) => {+ calls.push([url, init?.method]);+ return json(201, { id: 't2', kwant_id: 'k1', title: 'Prices (continued)', kind: 'chat', forked_from_context: 't1', forked_from_message_id: 'm 3', copied: 12, truncated: false });+ };+ const t = await m.continueChatApi.fromMessage('m 3', send);+ assert.deepEqual(calls, [['/api/messages/m%203/continue', 'POST']]);+ assert.equal(t.id, 't2');+ assert.equal(t.forked_copied, 12, 'the top-level copied fills in when the thread view has no count');+ assert.equal(t.forked_truncated, false);+});++test("fromMessage prefers the thread view's own counts (Lin's forked_copied / forked_truncated)", async () => {+ const send = async () => json(201, { id: 't2', kwant_id: 'k1', forked_from_context: 'k1', forked_from_message_id: 'm9', forked_copied: 1000, forked_truncated: true, copied: 1000, truncated: true });+ const t = await m.continueChatApi.fromMessage('m9', send);+ assert.equal(t.forked_copied, 1000);+ assert.equal(t.forked_truncated, true);+});++test("fromMessage errors: our own words for Lin's 404/403/5xx, the server's only for the 400", async () => {+ // Lin's exact bodies, from src/server/continue_chat.rs on lin-continue-chat (#618)+ const cases = [+ [400, { error: 'Only a chat with one bot can be continued.' }, "Couldn't start a new chat: only a chat with one bot can be continued."],+ [400, null, "Couldn't start a new chat: only a chat with one bot can be continued."],+ [404, { error: 'message not found' }, "Couldn't start a new chat: that message is no longer in this chat."],+ [404, { error: "that isn't in this space" }, "Couldn't start a new chat: that message is no longer in this chat."],+ [403, { error: 'only the person continues a chat in a new one' }, "Couldn't start a new chat: only you can do this, not a bot."],+ [500, { error: 'database is locked' }, "Couldn't start a new chat: something went wrong (error 500). Try again."],+ [502, null, "Couldn't start a new chat: something went wrong (error 502). Try again."],+ ];+ for (const [status, body, line] of cases) {+ const send = async () => (body ? json(status, body) : new Response('nope', { status }));+ await assert.rejects(m.continueChatApi.fromMessage('m1', send), (e) => e instanceof m.ContinueError && e.status === status && m.continueErrorLine(e) === line);+ }+ await assert.rejects(m.continueChatApi.fromMessage('m1', async () => { throw new TypeError('Failed to fetch'); }), (e) => e.status === 0 && /didn't answer/.test(e.message));+ await assert.rejects(m.continueChatApi.fromMessage('m1', async () => json(201, { nope: 1 })), /no chat/);+});++test('the error line is one plain sentence', () => {+ assert.equal(m.continueErrorLine(new Error('Only a chat with one bot can be continued.')), "Couldn't start a new chat: only a chat with one bot can be continued.");+ assert.equal(m.continueErrorLine(new m.ContinueError("the server didn't answer", 0)), "Couldn't start a new chat: the server didn't answer.");+ assert.equal(m.continueErrorLine(new Error('')), "Couldn't start a new chat: something went wrong.");+ assert.equal(m.continueErrorLine(null), "Couldn't start a new chat: something went wrong.");+});++// ---- where the item shows ----++const base = { chatKind: 'bot', threadKind: null, message: { id: 'm1', sender_role: 'kwant' }, newest: false, streaming: false, botSession: false };+const shows = (o = {}) => m.canContinueFrom({ ...base, ...o });++test('it shows on the person’s and the bot’s messages in a chat with one bot', () => {+ assert.equal(shows(), true, 'main chat, a reply');+ assert.equal(shows({ message: { id: 'm2', sender_role: 'user' } }), true, 'the person’s message');+ assert.equal(shows({ threadKind: 'chat' }), true, 'a chat thread');+ assert.equal(shows({ streaming: true }), true, 'an older message while a reply streams');+});++test('it hides in team chats, channels, delegations, bot sessions and on a message still being written', () => {+ for (const chatKind of ['team', 'channel', 'general', undefined]) assert.equal(shows({ chatKind }), false, String(chatKind));+ assert.equal(shows({ inTeam: true }), false);+ assert.equal(shows({ threadKind: 'delegation' }), false);+ assert.equal(shows({ botSession: true }), false);+ assert.equal(shows({ message: { id: 'temp-1', sender_role: 'user' } }), false, 'not sent yet');+ assert.equal(shows({ newest: true, streaming: true }), false, 'the newest while a reply streams');+ assert.equal(shows({ message: { id: 'm3', sender_role: 'system' } }), false);+});++// ---- the Continued line ----++test('continuedLine reads like the brief', () => {+ assert.equal(m.continuedLine('Price check', 12, false), 'Continued from "Price check" · 12 messages');+ assert.equal(m.continuedLine('Cody', 1), 'Continued from "Cody" · 1 message');+ assert.equal(m.continuedLine('Price check', 1000, true), 'Continued from "Price check" · the newest 1,000 messages');+ assert.equal(m.continuedLine('Ben', 4, false, true), 'Continued from your main chat with Ben · 4 messages', 'the main chat: no quotes');+ assert.equal(m.continuedLine('Ben', 1000, true, true), 'Continued from your main chat with Ben · the newest 1,000 messages');+ assert.equal(m.continuedLine('Old', null), 'Continued from "Old"', 'no count after a reload on an older server');+ assert.equal(m.continuedLine(' ', 3), 'Continued from "the earlier chat" · 3 messages');+});++test('forkOf reads the thread fields, null for a thread that was not continued', () => {+ assert.equal(m.forkOf({ forked_from_context: null, forked_from_message_id: null }), null);+ assert.equal(m.forkOf(null), null);+ assert.deepEqual(m.forkOf({ forked_from_context: 'k1', forked_from_message_id: 'm1', forked_copied: 4, forked_truncated: null }), { context: 'k1', messageId: 'm1', copied: 4, truncated: false });+});++// ---- the overflow ----++const mount = (Comp, props) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = ui.createRoot(host);+ const render = (p) => ui.flushSync(() => root.render(ui.React.createElement(Comp, p)));+ render(props);+ return { host, render, unmount: () => (root.unmount(), host.remove()) };+};+const tick = () => new Promise((r) => setTimeout(r, 0));+const key = (el, k) => el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true }));++test('the overflow: one button with a name, the menu opens with the item focused, Esc closes and returns focus', async () => {+ let ran = 0;+ const v = mount(ui.MessageMore, { messageId: 'm1', about: "Cody's reply", items: [{ label: m.CONTINUE_LABEL, run: () => ran++ }] });+ const btn = v.host.querySelector('[data-message-more-button]');+ assert.equal(btn.getAttribute('aria-label'), "More for Cody's reply");+ assert.equal(btn.getAttribute('aria-haspopup'), 'menu');+ assert.equal(btn.getAttribute('aria-expanded'), 'false');+ assert.equal(v.host.querySelector('[role="menu"]'), null, 'closed at first: not a fourth visible button');+ btn.focus();+ btn.click();+ await tick();+ assert.equal(btn.getAttribute('aria-expanded'), 'true');+ const item = v.host.querySelector('[role="menuitem"]');+ assert.equal(item.textContent, m.CONTINUE_LABEL);+ assert.equal(document.activeElement, item, 'the item takes focus');+ key(item, 'ArrowDown');+ assert.equal(document.activeElement, item, 'arrows wrap within one item');+ key(item, 'Escape');+ await tick();+ await tick();+ assert.equal(v.host.querySelector('[role="menu"]'), null);+ assert.equal(document.activeElement, btn, 'Esc gives focus back to ⋯');+ key(btn, 'ArrowDown');+ await tick();+ v.host.querySelector('[role="menuitem"]').click();+ await tick();+ assert.equal(ran, 1);+ assert.equal(v.host.querySelector('[role="menu"]'), null, 'it closes when the item runs');+ assert.equal(document.activeElement, v.host.querySelector('[data-message-more-button]'), 'focus stays at the message, by the error line if it fails');+ v.unmount();+});++test('while the new chat is made, ⋯ spins, cannot be pressed and keeps focus', async () => {+ const props = { messageId: 'm1', about: 'your message', align: 'end', reveal: 'hover', busyLabel: 'Starting a new chat…', items: [{ label: m.CONTINUE_LABEL, run: () => {} }] };+ const v = mount(ui.MessageMore, props);+ const btn = v.host.querySelector('[data-message-more-button]');+ btn.click();+ await tick();+ assert.match(v.host.querySelector('[role="menu"]').className, /right-0/, 'the person’s message opens to the left');+ v.host.querySelector('[role="menuitem"]').click();+ await tick();+ v.render({ ...props, busy: true });+ assert.equal(document.activeElement, btn, 'focus stays on ⋯ (aria-disabled, not disabled)');+ assert.equal(btn.getAttribute('aria-busy'), 'true');+ assert.equal(btn.getAttribute('aria-disabled'), 'true');+ assert.equal(btn.getAttribute('aria-label'), 'Starting a new chat…');+ assert.ok(btn.querySelector('svg.animate-spin.motion-reduce\\:animate-none'), 'the spinner, still under reduced motion');+ btn.click();+ key(btn, 'ArrowDown');+ await tick();+ assert.equal(v.host.querySelector('[role="menu"]'), null, 'a second press does nothing');+ assert.match(v.host.querySelector('[data-message-more]').className, /opacity-100/, 'visible while busy, even off hover');+ v.render({ ...props, busy: false });+ assert.equal(btn.hasAttribute('aria-busy'), false);+ assert.match(v.host.querySelector('[data-message-more]').className, /\[@media\(hover:hover\)\]:opacity-0/, 'hidden until hover on desktop');+ v.unmount();+});++test('the error line and the Continued link', async () => {+ const e = mount(ui.MessageMoreError, { text: "Couldn't start a new chat: Message not found." });+ assert.equal(e.host.querySelector('[data-continue-error]').getAttribute('role'), 'status');+ e.unmount();+ let opened = 0;+ const c = mount(ui.ContinuedLine, { text: 'Continued from "Prices" · 4 messages', onOpen: () => opened++ });+ const b = c.host.querySelector('[data-continued-from] button');+ assert.equal(b.textContent, 'Continued from "Prices" · 4 messages');+ b.click();+ assert.equal(opened, 1);+ c.unmount();+});++// ---- wiring (source checks) ----++test('ChatView puts ⋯ right after Copy, the line before the messages, and keeps it out of message text', () => {+ const src = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');+ const copy = src.indexOf('<CopyGhost copied=');+ const more = src.indexOf("continueMenu(msg, `${displayName}'s reply`, 'start')");+ assert.ok(copy > 0 && more > copy && more - copy < 200, '⋯ sits next to Copy');+ assert.match(src, /continueMenu\(msg, 'your message', 'end', 'hover'\)/);+ assert.match(src, /absolute right-full bottom-0 mr-1" data-message-more-gutter/, 'the person’s ⋯ sits in the gutter, no row of its own');+ assert.equal(/mt-1 flex justify-end">\{more\}/.test(src), false, 'no ⋯ row under the person’s bubble');+ assert.ok(src.indexOf('<ContinuedLine') > 0);+ assert.equal(/handleCopy\([^)]*continued/i.test(src), false);+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');+ assert.match(app, /continueChatApi\.fromMessage<Thread>\(msg\.id, personFetch\)/, 'person-only, so "Confirm it’s you" can answer a 401');+ assert.match(app, /fork\.truncated,\s*fork\.context === currentKwant\.id,/, 'the main chat reads "your main chat with <bot>"');+ assert.match(app, /canContinueHere = !!currentKwant && !currentTeam && !botSession && \(!openThreadId \|\| shownThread\?\.kind === 'chat'\)/);+});