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 notice for capped hand-offs; board owners show their avatar
Pixel (kwant bot)3ce60607d778
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9082a029..75e58c70 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,6 +33,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).- **Teams can hand on more before kwant pauses them.** One teammate can now be asked by mention up to 4times per message (was 2), and one message can start up to 16 hand-offs (was 8). Past that, instead of"Send a new message to go on", the chat shows a notice with a Continue button (or say "continue").+- **The pause notice reads plainly and continues in one click.** It now says "Paused after 16 hand-offs+ so it doesn't loop. Continue?", lists who's waiting, and its **Continue** button hands the turn on+ straight away. Once continued (by the button or by typing "continue") it says who it went to.+- **Mission board owners show their avatar.** Board cards, the task panel and "How tasks connect" show+ the owner's bot avatar, the same one as in the sidebar and chat, instead of a letter circle. A bot+ that no longer exists still shows its initials.### Fixed- **Board notes aren't lost when kwant is busy.** A task's notes (such as "the hand-off finished;diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex bd91654d..42623e54 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -2853,11 +2853,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({/>);const missionNames = Object.fromEntries(kwants.map((k) => [k.id, k.name]));+ const missionAvatars = Object.fromEntries(kwants.map((k) => [k.id, k.avatar_sprite ?? '']));const missionsPage = (<MissionBoardPagekey={space.id}spaceId={space.id}names={missionNames}+ avatars={missionAvatars}onBack={isPhone ? () => { setShowMissions(false); setPhoneView('list'); } : undefined}onOpenChat={(t, place) => {const c = place ?? sourceChat(t);diff --git a/frontend/src/chainBudget.ts b/frontend/src/chainBudget.tsindex 9a21f4aa..2af2ca62 100644--- a/frontend/src/chainBudget.ts+++ b/frontend/src/chainBudget.ts@@ -32,6 +32,53 @@ export function parseBudgetPaused(meta: string | null | undefined): BudgetPaused}}+/** Hand-offs past the per-message caps: kwnt holds them in one notice (meta kind "handoff_capped") with Continue. */+export interface HandoffCappedMeta {+ kind: 'handoff_capped';+ /** Hand-offs this message already started. */+ sent: number;+ /** Teammates not handed the turn yet. */+ waiting: string[];+ resumed: boolean;+}++export function parseHandoffCapped(meta: string | null | undefined): HandoffCappedMeta | null {+ if (!meta) return null;+ try {+ const m = JSON.parse(meta);+ if (!m || m.kind !== 'handoff_capped') return null;+ return {+ kind: 'handoff_capped',+ sent: typeof m.sent === 'number' && Number.isFinite(m.sent) && m.sent > 0 ? Math.floor(m.sent) : 0,+ waiting: Array.isArray(m.waiting) ? m.waiting.filter((w: unknown): w is string => typeof w === 'string' && w.trim() !== '') : [],+ resumed: m.resumed === true,+ };+ } catch {+ return null;+ }+}++/** The notice's plain line: "Paused after 16 hand-offs so it doesn't loop. Continue?" */+export function handoffCappedText(meta: HandoffCappedMeta): { headline: string; detail: string | null } {+ const n = meta.sent;+ const headline = n > 0 ? `Paused after ${n} hand-off${n === 1 ? '' : 's'} so it doesn't loop.` : "Paused so the hand-offs don't loop.";+ const who = meta.waiting.length <= 3 ? meta.waiting.join(', ') : `${meta.waiting.slice(0, 3).join(', ')} and ${meta.waiting.length - 3} more`;+ if (meta.resumed) return { headline, detail: who ? `Continued: handed on to ${who}.` : 'Continued.' };+ return { headline: `${headline} Continue?`, detail: who ? `Waiting: ${who}` : null };+}++const httpStatus = (e: unknown): number | undefined => {+ const status = e instanceof Error ? (e as Error & { status?: unknown }).status : undefined;+ return typeof status === 'number' ? status : undefined;+};++/** 409: someone (or a typed "continue") already carried the chain on. */+export const isAlreadyContinued = (e: unknown): boolean =>+ httpStatus(e) === 409 || (e instanceof Error && /already continued/i.test(e.message));++/** 410: the lead (or the chain's bots) were removed, so nothing can carry it on. */+export const isChainGone = (e: unknown): boolean => httpStatus(e) === 410;+/** Error text for the budget field, or null for a whole number from 0 (off) to BUDGET_MAX. */export function budgetError(raw: string): string | null {const s = raw.trim().replace(/[ _,]/g, '');diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 0140c656..d042f833 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -38,8 +38,8 @@ import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';import { ConnectionSuggestionMeta, parseConnectionMeta } from '../connectionSuggestions';import { routeReasonText } from '../routeReason';-import { BudgetPausedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';-import { chainBudgetApi, parseBudgetPaused } from '../chainBudget';+import { BudgetPausedNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';+import { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainBudget';import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';import { consultedNames, parseDecisions, parseWorkAhead } from '../decideFirst';import { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';@@ -865,6 +865,17 @@ export const ChatView: React.FC<ChatViewProps> = ({flash={flashId === msg.id}/>);+ const capped = parseHandoffCapped(msg.meta);+ if (capped)+ return (+ <HandoffCappedNotice+ key={msg.id}+ messageId={msg.id}+ meta={capped}+ onContinue={canRun === false ? undefined : chainBudgetApi.continue}+ flash={flashId === msg.id}+ />+ );if (isSystemNotice(msg) && !parseAttachments(msg.meta).length)return <SystemNotice key={msg.id} messageId={msg.id} text={msg.text} flash={flashId === msg.id} />;const isUser = msg.sender_role === 'user';diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsxindex 6cee024c..8fa27b6b 100644--- a/frontend/src/components/MissionBoardView.tsx+++ b/frontend/src/components/MissionBoardView.tsx@@ -27,6 +27,7 @@ import {XCircle,} from 'lucide-react';import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';+import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import {ACTION_DONE,@@ -317,6 +318,32 @@ const initials = (name: string) =>.map((w) => w[0]!.toUpperCase()).join('') || '?';+/** Bot id → avatar sprite, so owner chips show the same creature as the sidebar and chat. */+const NO_AVATARS: Record<string, string> = {};+export const AvatarsContext = React.createContext<Record<string, string>>(NO_AVATARS);++/** The owner's avatar: the bot's own creature, or their initials when the bot isn't known (removed, or no id). */+export const OwnerAvatar: React.FC<{ kwantId?: string | null; name: string; size?: number }> = ({ kwantId, name, size = 16 }) => {+ const avatars = React.useContext(AvatarsContext);+ const sprite = kwantId ? avatars[kwantId] : undefined;+ if (kwantId && sprite !== undefined)+ return (+ <span aria-hidden="true" className="shrink-0 inline-flex" data-owner-avatar={kwantId}>+ <ModernAvatar role={sprite || undefined} name={name} size={size} kwantId={kwantId} />+ </span>+ );+ return (+ <span+ aria-hidden="true"+ data-owner-initials+ className="shrink-0 rounded-full bg-zinc-700 font-semibold text-zinc-100 grid place-items-center"+ style={{ width: size, height: size, fontSize: Math.max(8, Math.round(size / 2)) }}+ >+ {initials(name)}+ </span>+ );+};+// ---------- Insights ----------export const InsightsStrip: React.FC<{@@ -513,9 +540,7 @@ export const TaskCard: React.FC<{<span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-zinc-400">{owner ? (<span className="inline-flex items-center gap-1 min-w-0">- <span aria-hidden="true" className="shrink-0 w-4 h-4 rounded-full bg-zinc-700 text-[8px] font-semibold text-zinc-100 grid place-items-center">- {initials(owner)}- </span>+ <OwnerAvatar kwantId={t.owner_kwant_id} name={owner} /><span className="truncate">{owner}</span></span>) : (@@ -1646,7 +1671,16 @@ export const TaskDetailBody: React.FC<{</section><dl className="grid grid-cols-2 gap-3">- <Fact label="Owner">{owner ?? <span className="text-zinc-500">No owner yet</span>}</Fact>+ <Fact label="Owner">+ {owner ? (+ <span className="inline-flex items-center gap-1.5 min-w-0" data-panel-owner>+ <OwnerAvatar kwantId={t.owner_kwant_id} name={owner} size={20} />+ <span className="truncate">{owner}</span>+ </span>+ ) : (+ <span className="text-zinc-500">No owner yet</span>+ )}+ </Fact><Fact label="From">{sourceLabel(t.source_kind)}</Fact><Fact label="Cost"><span className="tabular-nums" data-task-cost>@@ -1931,7 +1965,12 @@ export const WorkGraphView: React.FC<{{notFlaggedText}</span>)}- {owner && <span className="block text-[11px] text-zinc-500 truncate">{owner}</span>}+ {owner && (+ <span className="flex items-center gap-1 min-w-0 text-[11px] text-zinc-500">+ <OwnerAvatar kwantId={n.owner_kwant_id} name={owner} size={14} />+ <span className="truncate">{owner}</span>+ </span>+ )}</button></li>);@@ -2188,9 +2227,11 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({export const MissionBoardPage: React.FC<{spaceId: string;names: Record<string, string>;+ /** Bot id → avatar sprite; owners not in it show their initials. */+ avatars?: Record<string, string>;onBack?: () => void;onOpenChat?: (t: Task, place?: ChatPlace | null) => void;-}> = ({ spaceId, names, onBack, onOpenChat }) => {+}> = ({ spaceId, names, avatars, onBack, onOpenChat }) => {const [tasks, setTasks] = useState<Task[] | null>(null);const [missions, setMissions] = useState<Mission[]>([]);const [insights, setInsights] = useState<Insights | null>(null);@@ -2649,7 +2690,7 @@ export const MissionBoardPage: React.FC<{const listed = openId ? tasksById[openId] : undefined;return (- <>+ <AvatarsContext.Provider value={avatars ?? NO_AVATARS}><MissionBoardViewtasks={tasks}missions={missions}@@ -2742,6 +2783,6 @@ export const MissionBoardPage: React.FC<{)}</TaskPanel>)}- </>+ </AvatarsContext.Provider>);};diff --git a/frontend/src/components/SystemNotice.tsx b/frontend/src/components/SystemNotice.tsxindex 555492da..a9ca4ff7 100644--- a/frontend/src/components/SystemNotice.tsx+++ b/frontend/src/components/SystemNotice.tsx@@ -1,6 +1,6 @@-import React, { useRef, useState } from 'react';-import { AlertTriangle, Check, Gauge, Info, Loader2, Play, RotateCcw } from 'lucide-react';-import { BudgetPausedMeta } from '../chainBudget';+import React, { useEffect, useRef, useState } from 'react';+import { AlertTriangle, Check, Gauge, Info, Loader2, PauseCircle, Play, RotateCcw } from 'lucide-react';+import { BudgetPausedMeta, HandoffCappedMeta, handoffCappedText, isAlreadyContinued, isChainGone } from '../chainBudget';import { compactTokens } from '../modelUsage';import { Interruption, RetryState, RetryTarget, interruptionText, runRetryOnce } from '../interruptions';@@ -155,3 +155,92 @@ export const BudgetPausedNotice: React.FC<BudgetPausedNoticeProps> = ({ messageI</section>);};++export interface HandoffCappedNoticeProps {+ messageId: string;+ meta: HandoffCappedMeta;+ /** Hands the turn to the waiting teammates; without it (a read-only view) there's no button. */+ onContinue?: (noticeId: string) => Promise<unknown>;+ flash?: boolean;+}++/** The team paused at the hand-off cap: one line and a one-click Continue, so nobody has to type a new message. */+export const HandoffCappedNotice: React.FC<HandoffCappedNoticeProps> = ({ messageId, meta, onContinue, flash }) => {+ // sent: continued here or on load; already: a 409, someone else got there first; gone: a 410, the lead was removed.+ const [state, setState] = useState<'idle' | 'sending' | 'sent' | 'already' | 'gone' | 'error'>(meta.resumed ? 'sent' : 'idle');+ const [error, setError] = useState<string | null>(null);+ const lock = useRef(false);+ const headingId = `capped-${messageId}`;+ // A typed "continue" resumes it too; the refreshed message then arrives with resumed set.+ useEffect(() => {+ if (meta.resumed) setState((s) => (s === 'already' ? s : 'sent'));+ }, [meta.resumed]);+ const done = state === 'sent' || state === 'already';+ const stopped = done || state === 'gone';+ const text = handoffCappedText({ ...meta, resumed: stopped });+ const headline = text.headline;+ const detail = state === 'already' ? 'Already continued.' : state === 'gone' ? null : text.detail;+ const run = async () => {+ if (!onContinue || lock.current) return;+ lock.current = true;+ setState('sending');+ setError(null);+ try {+ await onContinue(messageId);+ setState('sent');+ } catch (e) {+ // Typing "continue" (or another tab) got there first: that's the outcome the button wanted.+ if (isAlreadyContinued(e)) return setState('already');+ if (isChainGone(e)) {+ setState('gone');+ return setError("Can't continue: the lead of this chat was removed. Send a new message to start again.");+ }+ lock.current = false;+ setState('error');+ const why = e instanceof Error && e.message ? e.message : 'Could not continue.';+ setError(why.charAt(0).toUpperCase() + why.slice(1));+ }+ };+ return (+ <section+ data-message-id={messageId}+ data-handoff-capped+ data-resumed={done || undefined}+ data-state={state}+ aria-labelledby={headingId}+ className={`w-full max-w-5xl rounded-xl border px-3.5 py-2.5 sm:px-4 ${done ? 'border-zinc-800 bg-zinc-900/40' : 'border-sky-500/30 bg-sky-950/20'} ${flash ? 'kw-flash' : ''}`}+ >+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">+ <div className="min-w-0 flex-1 basis-56">+ <p id={headingId} className={`flex items-start gap-2 text-sm break-words ${done ? 'text-zinc-400' : 'text-sky-100'}`}>+ {done ? (+ <Check size={15} className="mt-0.5 shrink-0 text-emerald-400" aria-hidden="true" />+ ) : (+ <PauseCircle size={15} className="mt-0.5 shrink-0 text-sky-400" aria-hidden="true" />+ )}+ <span className="min-w-0">{headline}</span>+ </p>+ {detail && <p className="mt-1 pl-[23px] text-[11px] text-zinc-400 break-words">{detail}</p>}+ </div>+ {onContinue && !stopped && (+ <button+ type="button"+ onClick={run}+ disabled={state === 'sending'}+ aria-describedby={headingId}+ data-handoff-continue+ className="shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[36px] px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-colors cursor-pointer disabled:cursor-default text-white bg-sky-600 hover:bg-sky-500 disabled:opacity-70 disabled:hover:bg-sky-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400"+ >+ {state === 'sending' ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Play size={13} aria-hidden="true" />}+ <span>{state === 'sending' ? 'Continuing…' : 'Continue'}</span>+ </button>+ )}+ </div>+ {error && (+ <p role="alert" className="mt-2 pl-[23px] text-[11px] text-rose-300">+ {error}+ </p>+ )}+ </section>+ );+};diff --git a/frontend/src/threads.ts b/frontend/src/threads.tsindex 0a3f3b38..deb21cb8 100644--- a/frontend/src/threads.ts+++ b/frontend/src/threads.ts@@ -367,7 +367,8 @@ export async function request<T>(method: string, url: string, body?: unknown): P} catch {// no JSON body}- throw new Error(message);+ // The status rides along so callers can tell a 409 or 410 apart without matching wording.+ throw Object.assign(new Error(message), { status: res.status });}if (res.status === 204) return undefined as T;return res.json();diff --git a/frontend/tests/handoffCapped.test.mjs b/frontend/tests/handoffCapped.test.mjsnew file mode 100644index 00000000..6ef41c06--- /dev/null+++ b/frontend/tests/handoffCapped.test.mjs@@ -0,0 +1,119 @@+// Hand-offs past the per-message caps: one plain notice with a one-click Continue (meta kind+// "handoff_capped", POST /api/chains/:id/continue), and board owners shown with their real avatar.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const m = await loadBundled(`+ export { parseHandoffCapped, handoffCappedText, isAlreadyContinued, isChainGone, parseBudgetPaused, chainBudgetApi } from './src/chainBudget';+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { HandoffCappedNotice } from './src/components/SystemNotice';+ import { OwnerAvatar, AvatarsContext } from './src/components/MissionBoardView';+ export const notice = (props) => renderToStaticMarkup(React.createElement(HandoffCappedNotice, props));+ export const owner = (props) => renderToStaticMarkup(React.createElement(OwnerAvatar, props));+ export const ownerIn = (avatars, props) => renderToStaticMarkup(React.createElement(AvatarsContext.Provider, { value: avatars }, React.createElement(OwnerAvatar, props)));+`);++const capped = (over = {}) =>+ JSON.stringify({+ kind: 'handoff_capped',+ lead: 'k-lead',+ waiting: ['Parser', 'Frontend', 'Backend'],+ waiting_ids: ['k1', 'k2', 'k3'],+ sent: 16,+ text: 'lead reply',+ user_prompt: 'ship it',+ resumed: false,+ ...over,+ });++test('handoff_capped meta parses; other kinds and junk do not', () => {+ assert.deepEqual(m.parseHandoffCapped(capped()), { kind: 'handoff_capped', sent: 16, waiting: ['Parser', 'Frontend', 'Backend'], resumed: false });+ assert.equal(m.parseHandoffCapped(JSON.stringify({ kind: 'budget_paused', used: 1, budget: 2 })), null);+ assert.equal(m.parseHandoffCapped('not json'), null);+ assert.equal(m.parseHandoffCapped(null), null);+ // A capped notice is not mistaken for a budget pause+ assert.equal(m.parseBudgetPaused(capped()), null);+ // Bad fields fall back instead of breaking the chat+ assert.deepEqual(m.parseHandoffCapped(JSON.stringify({ kind: 'handoff_capped', sent: 'x', waiting: [3, '', 'Ada'] })), {+ kind: 'handoff_capped',+ sent: 0,+ waiting: ['Ada'],+ resumed: false,+ });+});++test('the wording is plain and asks to continue', () => {+ const t = m.handoffCappedText(m.parseHandoffCapped(capped()));+ assert.equal(t.headline, "Paused after 16 hand-offs so it doesn't loop. Continue?");+ assert.equal(t.detail, 'Waiting: Parser, Frontend, Backend');+ assert.equal(m.handoffCappedText({ kind: 'handoff_capped', sent: 1, waiting: [], resumed: false }).headline, "Paused after 1 hand-off so it doesn't loop. Continue?");+ const many = m.handoffCappedText({ kind: 'handoff_capped', sent: 4, waiting: ['A', 'B', 'C', 'D', 'E'], resumed: false });+ assert.equal(many.detail, 'Waiting: A, B, C and 2 more');+ const done = m.handoffCappedText({ kind: 'handoff_capped', sent: 4, waiting: ['A'], resumed: true });+ assert.equal(done.headline, "Paused after 4 hand-offs so it doesn't loop.");+ assert.equal(done.detail, 'Continued: handed on to A.');+ // The old "Send a new message to go on" wording is gone+ assert.doesNotMatch(JSON.stringify([t, done]), /new message|already asked/i);+});++test('the notice has one primary Continue button, and none once continued or read-only', () => {+ const html = m.notice({ messageId: 'msg1', meta: m.parseHandoffCapped(capped()), onContinue: async () => {} });+ assert.match(html, /data-handoff-capped/);+ assert.match(html, /Paused after 16 hand-offs so it doesn't loop\. Continue\?/);+ assert.equal((html.match(/<button/g) || []).length, 1);+ assert.match(html, /data-handoff-continue[^>]*>.*Continue<\/span><\/button>/);+ assert.match(html, /aria-labelledby="capped-msg1"/);++ const resumed = m.notice({ messageId: 'msg1', meta: m.parseHandoffCapped(capped({ resumed: true })), onContinue: async () => {} });+ assert.doesNotMatch(resumed, /<button/);+ assert.match(resumed, /Continued: handed on to Parser, Frontend, Backend\./);++ assert.doesNotMatch(m.notice({ messageId: 'msg1', meta: m.parseHandoffCapped(capped()) }), /<button/);+});++test('Continue posts to the chain continue route; a 409 counts as already continued', async () => {+ const calls = [];+ const realFetch = globalThis.fetch;+ globalThis.fetch = async (url, init) => {+ calls.push([init.method, url]);+ return new Response(JSON.stringify({ status: 'continued' }), { status: 200, headers: { 'content-type': 'application/json' } });+ };+ try {+ assert.deepEqual(await m.chainBudgetApi.continue('msg 1'), { status: 'continued' });+ assert.deepEqual(calls, [['POST', '/api/chains/msg%201/continue']]);+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'this chain was already continued' }), { status: 409 });+ const err = await m.chainBudgetApi.continue('msg1').catch((e) => e);+ assert.equal(m.isAlreadyContinued(err), true);+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'the lead of this chat is gone' }), { status: 410 });+ const gone = await m.chainBudgetApi.continue('msg1').catch((e) => e);+ assert.equal(m.isAlreadyContinued(gone), false);+ assert.equal(m.isChainGone(gone), true);+ assert.equal(gone.status, 410);+ } finally {+ globalThis.fetch = realFetch;+ }+});++test('owners show their bot avatar, with initials when the bot is unknown', () => {+ // No avatar map (outside the board page) or an unknown bot: initials+ const fallback = m.owner({ kwantId: 'k-gone', name: 'Front End' });+ assert.match(fallback, /data-owner-initials/);+ assert.match(fallback, />FE</);+ assert.doesNotMatch(fallback, /<svg/);+ assert.match(m.owner({ name: 'Backend' }), />B</);+ assert.match(m.ownerIn({ k1: 'robot' }, { kwantId: 'k-gone', name: 'Front End' }), /data-owner-initials/);+});++test('a known bot gets the same pixel avatar as the sidebar, even without a chosen sprite', () => {+ const html = m.ownerIn({ k1: 'robot', k2: '' }, { kwantId: 'k1', name: 'Frontend' });+ assert.match(html, /data-owner-avatar="k1"/);+ assert.match(html, /kw-avatar/);+ assert.match(html, /<svg/);+ assert.doesNotMatch(html, /data-owner-initials/);+ // An empty sprite still draws the name-picked creature, not initials+ assert.match(m.ownerIn({ k2: '' }, { kwantId: 'k2', name: 'Backend' }), /data-owner-avatar="k2"/);+});diff --git a/frontend/tests/handoffCappedClick.test.mjs b/frontend/tests/handoffCappedClick.test.mjsnew file mode 100644index 00000000..d09ec7aa--- /dev/null+++ b/frontend/tests/handoffCappedClick.test.mjs@@ -0,0 +1,117 @@+// The hand-off cap notice in a DOM: pressing Continue against the real POST /api/chains/:id/continue+// client, for each answer the route gives (200 continued, 409 already continued, 410 lead gone).+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'MouseEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}++let calls = [];+let answer = { status: 200, body: { status: 'continued' } };+g.fetch = async (url, init = {}) => {+ calls.push([init.method ?? 'GET', String(url)]);+ return new Response(JSON.stringify(answer.body), { status: answer.status, headers: { 'Content-Type': 'application/json' } });+};+g.window.fetch = g.fetch;++const { React, createRoot, HandoffCappedNotice, parseHandoffCapped, chainBudgetApi } = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export { HandoffCappedNotice } from './src/components/SystemNotice';+ export { parseHandoffCapped, chainBudgetApi } from './src/chainBudget';+`);++const settle = async () => {+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));+};++const meta = (resumed = false) =>+ parseHandoffCapped(JSON.stringify({ kind: 'handoff_capped', lead: 'k0', waiting: ['Parser', 'Backend'], waiting_ids: ['k1', 'k2'], sent: 16, text: 'r', user_prompt: 'p', resumed }));++const mount = async (m) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ root.render(React.createElement(HandoffCappedNotice, { messageId: 'n1', meta: m, onContinue: chainBudgetApi.continue }));+ await settle();+ return { host, root, section: () => host.querySelector('[data-handoff-capped]'), button: () => host.querySelector('[data-handoff-continue]') };+};++const press = async (v) => {+ v.button().dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await settle();+};++test('200: Continue posts once, then says who it went to and the button goes', async () => {+ calls = [];+ answer = { status: 200, body: { status: 'continued' } };+ const v = await mount(meta());+ assert.match(v.section().textContent, /Paused after 16 hand-offs so it doesn't loop\. Continue\?/);+ assert.match(v.section().textContent, /Waiting: Parser, Backend/);+ await press(v);+ assert.deepEqual(calls, [['POST', '/api/chains/n1/continue']]);+ assert.equal(v.button(), null);+ assert.equal(v.section().dataset.state, 'sent');+ assert.match(v.section().textContent, /Continued: handed on to Parser, Backend\./);+ assert.doesNotMatch(v.section().textContent, /Continue\?/);+ v.root.unmount();+});++test('409: someone already continued it — say so, no button, no error', async () => {+ answer = { status: 409, body: { error: 'this chain was already continued' } };+ const v = await mount(meta());+ await press(v);+ assert.equal(v.button(), null);+ assert.equal(v.section().dataset.state, 'already');+ assert.match(v.section().textContent, /Already continued\./);+ assert.equal(v.section().querySelector('[role="alert"]'), null);+ v.root.unmount();+});++test('410: the lead is gone — say so plainly and drop the button', async () => {+ answer = { status: 410, body: { error: 'the lead of this chat is gone' } };+ const v = await mount(meta());+ await press(v);+ assert.equal(v.button(), null);+ assert.equal(v.section().dataset.state, 'gone');+ assert.match(v.section().querySelector('[role="alert"]').textContent, /lead of this chat was removed/);+ assert.doesNotMatch(v.section().textContent, /Continue\?/);+ v.root.unmount();+});++test('other failures keep the button so the person can try again', async () => {+ answer = { status: 500, body: { error: 'could not set up the chat' } };+ const v = await mount(meta());+ await press(v);+ assert.equal(v.section().dataset.state, 'error');+ assert.match(v.section().querySelector('[role="alert"]').textContent, /Could not set up the chat/);+ assert.ok(v.button() && !v.button().disabled);+ v.root.unmount();+});++test('resumed:true on load shows it already continued, with no button', async () => {+ calls = [];+ const v = await mount(meta(true));+ assert.equal(v.button(), null);+ assert.equal(v.section().dataset.state, 'sent');+ assert.match(v.section().textContent, /Continued: handed on to Parser, Backend\./);+ assert.deepEqual(calls, []);+ v.root.unmount();+});++test('a typed "continue" flips a live notice to continued when the message refreshes', async () => {+ answer = { status: 200, body: { status: 'continued' } };+ const v = await mount(meta());+ assert.ok(v.button());+ v.root.render(React.createElement(HandoffCappedNotice, { messageId: 'n1', meta: meta(true), onContinue: chainBudgetApi.continue }));+ await settle();+ assert.equal(v.button(), null);+ assert.equal(v.section().dataset.state, 'sent');+ v.root.unmount();+});