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
frontend: agent threads, delegation cards and background-turn UI (section A)
Lin (kwant bot)f79ce8a6e66f
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 0704b497..3b78cf71 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,18 +1,41 @@import React, { Suspense, lazy, useState, useEffect, useRef, useCallback } from 'react';import { AppHeader } from './components/AppHeader';import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';-import { ChatView, ChatMessage, DiscussionState, RoutingState } from './components/ChatView';+import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } from './components/ChatView';+import { ThreadBar, ThreadHeader } from './components/ThreadBar';+import { DelegationCard } from './components/DelegationCard';+import { Loader2 } from 'lucide-react';import { PendingApproval } from './components/ModernApprovalCard';import type { AgentFormData } from './components/NewAgentModal';import { NewTeamModal } from './components/NewTeamModal';import { ManageTeamModal } from './components/ManageTeamModal';import { playSfx } from './audio/chiptune';import { Toasts, Toast } from './components/Toasts';-import { clearAllTurns, turnEnded, turnStarted } from './kwantActivity';+import { clearAllTurns, resetTurns, turnEnded, turnStarted } from './kwantActivity';+import {+ Delegation,+ DelegationMeta,+ Thread,+ TurnMap,+ applyDelegation,+ applyTurnEvent,+ backgroundTurns,+ hydrateTurns,+ messageContextId,+ parseDelegationMeta,+ queuePosition,+ shouldRenderDelta,+ streamTarget,+ threadBadge,+ threadsApi,+ turnsIn,+ upsertThread,+} from './threads';import { Profile, describeProfileSwitch, profilesApi } from './profiles';import {NotifyEvent,SearchHit,+ TOAST_KINDS,browserNotifyEnabled,channelLabel,continuityApi,@@ -42,13 +65,36 @@ export const App: React.FC = () => {const [isChannel, setIsChannel] = useState(true);const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);const [messages, setMessages] = useState<ChatMessage[]>([]);+ const [messagesError, setMessagesError] = useState<string | null>(null);+ // The open thread of the selected agent; null for its direct chat (and for channels).+ const [openThreadId, setOpenThreadId] = useState<string | null>(null);+ const openCtx = openThreadId || selectedId;+ const openCtxRef = useRef(openCtx);+ openCtxRef.current = openCtx;+ // What the open chat is streaming; other chats' streams are kept in streamsRef until opened.const [streamingText, setStreamingText] = useState('');const [streamingThinking, setStreamingThinking] = useState('');- const [isStreaming, setIsStreaming] = useState(false);- const [streamingContextId, setStreamingContextId] = useState<string | null>(null);- const [streamingSpeakerName, setStreamingSpeakerName] = useState<string>('');+ const streamsRef = useRef<Record<string, { text: string; thinking: string }>>({});+ // Chats with a reply in flight -> who is replying. Several can stream at once.+ const [live, setLive] = useState<Record<string, string>>({});+ const liveRef = useRef(live);+ // Chat the last send or discussion started in; untagged events (team discussions) go here.const streamingContextIdRef = useRef<string | null>(null);- const streamingSpeakerNameRef = useRef<string>('');+ const [turns, setTurns] = useState<TurnMap>({});+ const turnsRef = useRef(turns);+ turnsRef.current = turns;+ const [threadsByKwant, setThreadsByKwant] = useState<Record<string, Thread[] | undefined>>({});+ const threadsByKwantRef = useRef(threadsByKwant);+ threadsByKwantRef.current = threadsByKwant;+ const [threadErrors, setThreadErrors] = useState<Record<string, string | null>>({});+ const [showArchived, setShowArchived] = useState(false);+ const [delegations, setDelegations] = useState<Record<string, Delegation>>({});+ const delegationsRef = useRef(delegations);+ delegationsRef.current = delegations;+ /** Ids known to be threads, so their messages load from the thread route. */+ const knownThreadsRef = useRef<Set<string>>(new Set());+ const threadsLoadingRef = useRef<Set<string>>(new Set());+ const delegationsFetchedRef = useRef<Set<string>>(new Set());const selectedIdRef = useRef<string>(selectedId);selectedIdRef.current = selectedId;const isChannelRef = useRef<boolean>(isChannel);@@ -87,9 +133,14 @@ export const App: React.FC = () => {// Set each render once the select handlers exist; the SSE handler and notification clicks go through it.const openTargetRef = useRef<(t: { channel_id: string | null; kwant_id: string | null }) => boolean>(() => false);const showNotification = (n: NotifyEvent) => {- if (!document.hidden && n.kind === 'routine_failed') {+ const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };+ // Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.+ if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {+ if (n.kind !== 'routine_failed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;const id = ++toastIdRef.current;- setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body }]);+ const action = n.kind === 'routine_failed' ? undefined : { label: 'Open', onClick: () => openTargetRef.current(target) };+ setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body, action }]);+ if (n.kind !== 'routine_failed') playSfx('alert');return;}if (!shouldShowOsNotification({ enabled: browserNotifyEnabled(), permission: notificationPermission(), hidden: document.hidden, kind: n.kind })) return;@@ -97,16 +148,106 @@ export const App: React.FC = () => {const note = new Notification(n.title, { body: n.body, tag: `kwnt-${n.kind}-${n.channel_id ?? n.kwant_id}` });note.onclick = () => {window.focus();- openTargetRef.current({ channel_id: n.channel_id, kwant_id: n.kwant_id });+ openTargetRef.current(target);note.close();};} catch {// Some mobile browsers only allow notifications from a service worker.}};+ const showNotificationRef = useRef(showNotification);+ showNotificationRef.current = showNotification;const refreshProfiles = useCallback(() => {profilesApi.list().then(setProfiles, () => undefined);}, []);+ const markLive = (ctx: string | null | undefined, speaker?: string) => {+ if (!ctx) return;+ const name = speaker ?? liveRef.current[ctx] ?? '';+ if (liveRef.current[ctx] === name) return;+ liveRef.current = { ...liveRef.current, [ctx]: name };+ setLive(liveRef.current);+ };+ const clearLive = (ctx: string | null | undefined) => {+ if (ctx) delete streamsRef.current[ctx];+ if (ctx === openCtxRef.current) {+ setStreamingText('');+ setStreamingThinking('');+ }+ if (!ctx || !(ctx in liveRef.current)) return;+ const next = { ...liveRef.current };+ delete next[ctx];+ liveRef.current = next;+ setLive(next);+ };+ const kwantName = (id: unknown) => (typeof id === 'string' ? kwantsRef.current.find((k) => k.id === id)?.name : undefined);++ /** Loads a chat's latest messages into the cache, and on screen if it's open. */+ const refreshContext = async (ctx: string | null | undefined): Promise<void> => {+ if (!ctx) return;+ try {+ let data: ChatMessage[];+ if (knownThreadsRef.current.has(ctx)) {+ data = await threadsApi.messages<ChatMessage>(ctx);+ } else {+ const res = await fetch(`/api/channels/${encodeURIComponent(ctx)}/messages`);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ data = await res.json();+ }+ messagesCacheRef.current[ctx] = data;+ if (openCtxRef.current === ctx) {+ setMessages(data);+ setMessagesError(null);+ }+ } catch {+ if (openCtxRef.current === ctx) setMessagesError('Could not load this chat.');+ }+ };++ const rememberThreads = (list: Thread[]) => list.forEach((t) => knownThreadsRef.current.add(t.id));++ const loadThreads = async (kwantId: string, includeArchived = false) => {+ if (!kwantId || threadsLoadingRef.current.has(kwantId)) return;+ threadsLoadingRef.current.add(kwantId);+ setThreadErrors((prev) => ({ ...prev, [kwantId]: null }));+ try {+ const list = await threadsApi.list(kwantId, includeArchived);+ rememberThreads(list);+ setThreadsByKwant((prev) => ({ ...prev, [kwantId]: list }));+ setDelegations((prev) => {+ const next = { ...prev };+ for (const t of list) if (t.delegation) next[t.delegation.id] = t.delegation;+ return next;+ });+ } catch (err) {+ setThreadErrors((prev) => ({ ...prev, [kwantId]: err instanceof Error ? err.message : 'Failed' }));+ } finally {+ threadsLoadingRef.current.delete(kwantId);+ }+ };++ /** Running turns after a (re)connect; chats whose reply ended meanwhile stop spinning. */+ const hydrateFromServer = async () => {+ try {+ const { turns: list } = await threadsApi.turns();+ const map = hydrateTurns(list);+ for (const t of Object.values(map)) if (t.thread_id) knownThreadsRef.current.add(t.thread_id);+ turnsRef.current = map;+ setTurns(map);+ resetTurns(Object.values(map).filter((t) => t.state === 'running'));+ const busy = new Set(Object.values(map).map((t) => t.context_id));+ for (const ctx of Object.keys(liveRef.current)) {+ if (!busy.has(ctx) && !discussionInProgressRef.current) clearLive(ctx);+ }+ for (const t of Object.values(map)) markLive(t.context_id, kwantName(t.kwant_id));+ // Titles for the "working on" badges+ for (const t of Object.values(map)) {+ if (t.thread_id && !threadsByKwantRef.current[t.kwant_id]) loadThreads(t.kwant_id);+ }+ } catch {+ clearAllTurns();+ }+ };+const [isNewAgentOpen, setIsNewAgentOpen] = useState(false);// Team that a newly created agent should join (set by a team's "Add member")const [newAgentTeam, setNewAgentTeam] = useState<Team | null>(null);@@ -174,39 +315,86 @@ export const App: React.FC = () => {refreshProfiles();}, [refreshProfiles]);- // Load messages when selected channel/kwant changes+ // The open chat (channel, direct chat or thread): show what's cached, then load the latest.useEffect(() => {- if (!selectedId) return;- const currentTargetId = selectedId;- async function loadMessages() {- try {- const res = await fetch(`/api/channels/${currentTargetId}/messages`);- if (res.ok) {- const data: ChatMessage[] = await res.json();- messagesCacheRef.current[currentTargetId] = data;- if (selectedIdRef.current === currentTargetId) {- setMessages(data);- const totalTokens = data.reduce((acc, m) => acc + (m.tokens_used || 0), 0);- setTokensUsed(totalTokens);- }- }- } catch (err) {- console.error('Failed loading messages:', err);- }+ if (!openCtx) return;+ const b = streamsRef.current[openCtx];+ setStreamingText(b?.text ?? '');+ setStreamingThinking(b?.thinking ?? '');+ setMessages(messagesCacheRef.current[openCtx] || []);+ setMessagesError(null);+ refreshContext(openCtx).then(() => {+ if (openCtxRef.current !== openCtx) return;+ const data = messagesCacheRef.current[openCtx] || [];+ setTokensUsed(data.reduce((acc, m) => acc + (m.tokens_used || 0), 0));+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [openCtx]);++ // An agent's conversations load when its chat opens; SSE keeps them current from then on.+ useEffect(() => {+ if (!selectedId || isChannel || threadsByKwantRef.current[selectedId] !== undefined) return;+ loadThreads(selectedId);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selectedId, isChannel]);++ // Delegation notes need the live record for their status; fetch each unknown one once.+ useEffect(() => {+ for (const m of messages) {+ const meta = parseDelegationMeta(m.meta);+ if (!meta || delegationsRef.current[meta.delegation_id] || delegationsFetchedRef.current.has(meta.delegation_id)) continue;+ delegationsFetchedRef.current.add(meta.delegation_id);+ knownThreadsRef.current.add(meta.thread_id);+ threadsApi.delegation(meta.delegation_id).then(+ (d) => setDelegations((prev) => (prev[d.id] ? prev : { ...prev, [d.id]: d })),+ () => undefined,+ );}- loadMessages();- }, [selectedId]);+ }, [messages]);// Connect to SSE streamuseEffect(() => {const sse = new EventSource('/api/events');- // After a reconnect a `turn_ended` may have been missed; drop working states rather than spin forever.let dropped = false;+ /** TurnComplete already refreshed these turns' chats; their turn_ended needn't again. */+ const completed = new Set<string>();++ /** After a reply: drop the chat's stream once nothing else runs or waits there. */+ const settle = (ctx: string | null) => {+ if (!ctx) return;+ if (discussionInProgressRef.current && ctx === streamingContextIdRef.current) return;+ if (turnsIn(turnsRef.current, ctx).length > 0) {+ streamsRef.current[ctx] = { text: '', thinking: '' };+ if (ctx === openCtxRef.current) {+ setStreamingText('');+ setStreamingThinking('');+ }+ return;+ }+ clearLive(ctx);+ if (ctx === streamingContextIdRef.current) {+ streamingContextIdRef.current = null;+ setRoutingState(null);+ }+ };++ const setTurnMap = (next: TurnMap) => {+ if (next === turnsRef.current) return;+ turnsRef.current = next;+ setTurns(next);+ };+sse.onerror = () => {dropped = true;};+ // First connect and every reconnect: running turns from the server. After a drop, also+ // whatever changed meanwhile in the open chat and the open agent's conversations.sse.onopen = () => {- if (dropped) clearAllTurns();+ hydrateFromServer();+ if (dropped) {+ refreshContext(openCtxRef.current);+ if (!isChannelRef.current && selectedIdRef.current) loadThreads(selectedIdRef.current);+ }dropped = false;};@@ -214,14 +402,78 @@ export const App: React.FC = () => {try {const event = JSON.parse(e.data);switch (event.type) {+ case 'turn_queued':+ case 'TurnQueued':case 'turn_started':case 'TurnStarted':- turnStarted(event.data?.kwant_id, event.data?.context_id);- break;case 'turn_ended':- case 'TurnEnded':- turnEnded(event.data?.kwant_id, event.data?.context_id);+ case 'TurnEnded': {+ const d = event.data ?? {};+ const ctx: string | null = d.context_id ?? d.thread_id ?? d.kwant_id ?? null;+ setTurnMap(applyTurnEvent(turnsRef.current, event));+ if (d.thread_id) {+ knownThreadsRef.current.add(d.thread_id);+ const list = threadsByKwantRef.current[d.kwant_id];+ if (list && !list.some((t) => t.id === d.thread_id)) loadThreads(d.kwant_id);+ }+ const key = d.turn_id ?? d.context_id;+ if (event.type === 'turn_ended' || event.type === 'TurnEnded') {+ turnEnded(d.kwant_id, key);+ if (d.turn_id && completed.delete(d.turn_id)) settle(ctx);+ else refreshContext(ctx).then(() => settle(ctx));+ } else {+ if (event.type === 'turn_started' || event.type === 'TurnStarted') turnStarted(d.kwant_id, key);+ if (!discussionInProgressRef.current || ctx !== streamingContextIdRef.current) markLive(ctx, kwantName(d.kwant_id));+ }+ break;+ }+ case 'thread_updated':+ case 'ThreadUpdated': {+ const t: Thread | undefined = event.data?.thread;+ if (!t?.id) break;+ knownThreadsRef.current.add(t.id);+ setThreadsByKwant((prev) =>+ prev[t.kwant_id] === undefined ? prev : { ...prev, [t.kwant_id]: upsertThread(prev[t.kwant_id], t) },+ );+ break;+ }+ case 'delegation_updated':+ case 'DelegationUpdated': {+ const dl: Delegation | undefined = event.data?.delegation;+ if (!dl?.id) break;+ knownThreadsRef.current.add(dl.thread_id);+ setDelegations((prev) => ({ ...prev, [dl.id]: dl }));+ const list = threadsByKwantRef.current[dl.specialist_kwant_id];+ if (list && !list.some((t) => t.id === dl.thread_id)) loadThreads(dl.specialist_kwant_id);+ else setThreadsByKwant((prev) => {+ const next = applyDelegation(prev[dl.specialist_kwant_id], dl);+ return next === prev[dl.specialist_kwant_id] ? prev : { ...prev, [dl.specialist_kwant_id]: next };+ });break;+ }+ case 'message_added':+ case 'MessageAdded': {+ const m: ChatMessage | undefined = event.data?.message;+ const ctx = m ? messageContextId(m) : null;+ if (!m?.id || !ctx) break;+ if (m.thread_id) knownThreadsRef.current.add(m.thread_id);+ const list = messagesCacheRef.current[ctx];+ if (!list) {+ if (ctx === openCtxRef.current) refreshContext(ctx);+ break;+ }+ if (list.some((x) => x.id === m.id)) break;+ // The person's own message replaces its optimistic copy.+ let base = list;+ if (m.sender_role === 'user') {+ const i = list.findIndex((x) => x.id.startsWith('temp-') && x.text === m.text);+ if (i >= 0) base = list.filter((_, j) => j !== i);+ }+ const updated = [...base, m];+ messagesCacheRef.current[ctx] = updated;+ if (ctx === openCtxRef.current) setMessages(updated);+ break;+ }case 'profile_switched':case 'ProfileSwitched': {const kwantName = kwantsRef.current.find((k) => k.id === event.data?.kwant_id)?.name;@@ -242,15 +494,25 @@ export const App: React.FC = () => {break;case 'notify':case 'Notify':- showNotification(event.data as NotifyEvent);+ showNotificationRef.current(event.data as NotifyEvent);break;case 'TextDelta':- setStreamingText((prev) => prev + event.data);- playSfx('blip');- break;- case 'ThinkingDelta':- setStreamingThinking(event.data);+ case 'ThinkingDelta': {+ // Each chat streams into its own buffer; only the open chat's is drawn.+ const ctx = streamTarget(event, streamingContextIdRef.current);+ if (!ctx) break;+ const buf = (streamsRef.current[ctx] ??= { text: '', thinking: '' });+ if (event.type === 'TextDelta') buf.text += event.data;+ else buf.thinking = event.data;+ if (!(ctx in liveRef.current)) markLive(ctx, kwantName(event.kwant_id));+ if (shouldRenderDelta(event, openCtxRef.current, streamingContextIdRef.current)) {+ if (event.type === 'TextDelta') {+ setStreamingText(buf.text);+ playSfx('blip');+ } else setStreamingThinking(buf.thinking);+ }break;+ }case 'routing_started':case 'RoutingStarted': {const ctx = event.data?.context_id;@@ -262,8 +524,7 @@ export const App: React.FC = () => {contextId: ctx || targetId || undefined,candidates: event.data?.candidates || [],});- setStreamingSpeakerName('Laya');- streamingSpeakerNameRef.current = 'Laya';+ markLive(ctx || targetId, 'Laya');break;}case 'routing_decided':@@ -285,10 +546,7 @@ export const App: React.FC = () => {reason: event.data?.reason,mode: event.data?.mode,}));- if (name) {- setStreamingSpeakerName(name);- streamingSpeakerNameRef.current = name;- }+ if (name && (ctx || targetId) && (ctx || targetId) in liveRef.current) markLive(ctx || targetId, name);playSfx('blip');};// Keep Laya's "deciding" visible briefly so instant heuristic routing doesn't just flash.@@ -321,10 +579,8 @@ export const App: React.FC = () => {);const contextId = matchedChannel ? matchedChannel.id : (teamId || selectedIdRef.current);- setStreamingContextId(contextId);streamingContextIdRef.current = contextId;- setStreamingSpeakerName(initialSpeakerName);- streamingSpeakerNameRef.current = initialSpeakerName;+ markLive(contextId, initialSpeakerName);setDiscussionState({inProgress: true,@@ -336,7 +592,6 @@ export const App: React.FC = () => {currentTurn: 1,kind: event.data?.kind,});- setIsStreaming(true);playSfx('alert');break;}@@ -344,8 +599,6 @@ export const App: React.FC = () => {case 'DiscussionTurnStarted': {discussionInProgressRef.current = true;const spkName = event.data?.speaker_name;- setStreamingSpeakerName(spkName);- streamingSpeakerNameRef.current = spkName;setDiscussionState((prev) => ({...prev,inProgress: true,@@ -355,20 +608,16 @@ export const App: React.FC = () => {currentTurn: event.data?.turn_index,totalTurns: event.data?.total_turns ?? prev.totalTurns,}));- setIsStreaming(true);- setStreamingText('');- setStreamingThinking('');const targetId = streamingContextIdRef.current || selectedIdRef.current;if (targetId) {- fetch(`/api/channels/${targetId}/messages`)- .then((r) => r.json())- .then((msgs) => {- messagesCacheRef.current[targetId] = msgs;- if (selectedIdRef.current === targetId) {- setMessages(msgs);- }- })- .catch(() => {});+ refreshContext(targetId).then(() => {+ streamsRef.current[targetId] = { text: '', thinking: '' };+ if (openCtxRef.current === targetId) {+ setStreamingText('');+ setStreamingThinking('');+ }+ });+ markLive(targetId, spkName);}break;}@@ -377,53 +626,23 @@ export const App: React.FC = () => {discussionInProgressRef.current = false;setDiscussionState({ inProgress: false });setRoutingState(null);- setIsStreaming(false);- setStreamingText('');- setStreamingThinking('');const targetId = streamingContextIdRef.current || selectedIdRef.current;- setStreamingContextId(null);streamingContextIdRef.current = null;- setStreamingSpeakerName('');- streamingSpeakerNameRef.current = '';playSfx('coin');- if (targetId) {- fetch(`/api/channels/${targetId}/messages`)- .then((r) => r.json())- .then((msgs) => {- messagesCacheRef.current[targetId] = msgs;- if (selectedIdRef.current === targetId) {- setMessages(msgs);- }- })- .catch(() => {});- }+ refreshContext(targetId).then(() => settle(targetId));break;}case 'TurnComplete': {- playSfx('coin');- setStreamingText('');- setStreamingThinking('');- setTokensUsed((prev) => prev + (event.data?.tokens || 0));- const targetId = streamingContextIdRef.current || selectedIdRef.current;- if (targetId) {- fetch(`/api/channels/${targetId}/messages`)- .then((r) => r.json())- .then((msgs) => {- messagesCacheRef.current[targetId] = msgs;- if (selectedIdRef.current === targetId) {- setMessages(msgs);- }- })- .catch(() => {});- }- if (!discussionInProgressRef.current) {- setRoutingState(null);- setIsStreaming(false);- setStreamingContextId(null);- streamingContextIdRef.current = null;- setStreamingSpeakerName('');- streamingSpeakerNameRef.current = '';+ const ctx = streamTarget(event, streamingContextIdRef.current);+ if (ctx === openCtxRef.current) {+ playSfx('coin');+ setTokensUsed((prev) => prev + (event.data?.tokens || 0));}+ if (typeof event.turn_id === 'string') completed.add(event.turn_id);+ // The stream stays up until the saved reply is on screen, so nothing jumps.+ refreshContext(ctx).then(() => {+ if (!discussionInProgressRef.current) settle(ctx);+ });break;}case 'browser_navigated':@@ -509,16 +728,13 @@ export const App: React.FC = () => {break;}case 'Error': {- discussionInProgressRef.current = false;- setDiscussionState({ inProgress: false });- setRoutingState(null);- setIsStreaming(false);- setStreamingContextId(null);- streamingContextIdRef.current = null;- setStreamingSpeakerName('');- streamingSpeakerNameRef.current = '';- setStreamingText('');- setStreamingThinking('');+ const ctx = streamTarget(event, streamingContextIdRef.current);+ if (ctx && ctx === streamingContextIdRef.current) {+ discussionInProgressRef.current = false;+ setDiscussionState({ inProgress: false });+ setRoutingState(null);+ }+ refreshContext(ctx).then(() => settle(ctx));break;}}@@ -533,60 +749,62 @@ export const App: React.FC = () => {};}, [refreshProfiles]);+ /** Stop in the composer: the open thread's turn, the direct chat's, or the channel's. */const handleCancelDiscussion = async () => {- const targetId = selectedIdRef.current;+ const ctx = openCtxRef.current;+ const threadId = openThreadId;try {- await fetch('/api/chat/cancel', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- channel_id: isChannelRef.current ? targetId : null,- kwant_id: !isChannelRef.current ? targetId : null,- team_id: activeTeamIdRef.current || null,- }),- });+ if (threadId) {+ await threadsApi.cancel(threadId);+ } else {+ const running = turnsIn(turnsRef.current, ctx).find((t) => t.state === 'running');+ const direct = !isChannelRef.current;+ const res = await fetch('/api/chat/cancel', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(+ direct+ ? { kwant_id: ctx, turn_id: running?.turn_id }+ : { channel_id: ctx, team_id: activeTeamIdRef.current || null },+ ),+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ }} catch (err) {console.error('Failed cancelling chat/discussion:', err);+ pushToast('Could not stop the reply.', err instanceof Error ? err.message : undefined);+ return;}- discussionInProgressRef.current = false;- setDiscussionState({ inProgress: false });- setRoutingState(null);- setIsStreaming(false);- setStreamingContextId(null);- streamingContextIdRef.current = null;- setStreamingSpeakerName('');- streamingSpeakerNameRef.current = '';- setStreamingText('');- setStreamingThinking('');- if (targetId) {- fetch(`/api/channels/${targetId}/messages`)- .then((r) => r.json())- .then((msgs) => {- messagesCacheRef.current[targetId] = msgs;- if (selectedIdRef.current === targetId) {- setMessages(msgs);- }- })- .catch(() => {});+ if (ctx === streamingContextIdRef.current) {+ discussionInProgressRef.current = false;+ setDiscussionState({ inProgress: false });+ setRoutingState(null);+ streamingContextIdRef.current = null;}+ refreshContext(ctx).then(() => {+ if (turnsIn(turnsRef.current, ctx).length === 0) clearLive(ctx);+ });};const handleSendMessage = async (text: string) => {- const targetId = selectedId;+ const targetId = openCtx;+ const threadId = openThreadId;const isTargetChannel = isChannel;const targetTeam = selectedTeamId;const speakerName = !isTargetChannel ? (currentKwant?.name || 'Agent') : chatTitle;- discussionInProgressRef.current = false;- setDiscussionState({ inProgress: false });- setRoutingState(null);- setIsStreaming(true);- setStreamingContextId(targetId);+ if (!threadId) {+ discussionInProgressRef.current = false;+ setDiscussionState({ inProgress: false });+ setRoutingState(null);+ }streamingContextIdRef.current = targetId;- setStreamingSpeakerName(speakerName);- streamingSpeakerNameRef.current = speakerName;- setStreamingText('');- setStreamingThinking('');+ if (!(targetId in liveRef.current)) {+ streamsRef.current[targetId] = { text: '', thinking: '' };+ setStreamingText('');+ setStreamingThinking('');+ }+ markLive(targetId, speakerName);// Optimistically add user messageconst tempId = `temp-${Date.now()}`;@@ -599,30 +817,47 @@ export const App: React.FC = () => {const cached = messagesCacheRef.current[targetId] || messages;const updated = [...cached, userMsg];messagesCacheRef.current[targetId] = updated;- if (selectedIdRef.current === targetId) {+ if (openCtxRef.current === targetId) {setMessages(updated);}try {- await fetch('/api/chat/send', {+ const res = await fetch('/api/chat/send', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- channel_id: isTargetChannel ? targetId : null,- kwant_id: !isTargetChannel ? targetId : null,- team_id: targetTeam || null,- prompt: text,- sender_id: 'PlayerHero',- }),+ body: JSON.stringify(+ threadId+ ? { thread_id: threadId, prompt: text, sender_id: 'PlayerHero' }+ : {+ channel_id: isTargetChannel ? targetId : null,+ kwant_id: !isTargetChannel ? targetId : null,+ team_id: targetTeam || null,+ prompt: text,+ sender_id: 'PlayerHero',+ },+ ),});+ if (!res.ok) {+ let message = `HTTP ${res.status}`;+ try {+ const data = await res.json();+ if (typeof data?.error === 'string') message = data.error;+ } catch {+ // no JSON body+ }+ throw new Error(message);+ }} catch (err) {console.error('Failed sending chat:', err);- setRoutingState(null);- setIsStreaming(false);- setStreamingContextId(null);- streamingContextIdRef.current = null;- setStreamingSpeakerName('');- streamingSpeakerNameRef.current = '';+ const rest = (messagesCacheRef.current[targetId] || []).filter((m) => m.id !== tempId);+ messagesCacheRef.current[targetId] = rest;+ if (openCtxRef.current === targetId) setMessages(rest);+ pushToast('Message not sent.', err instanceof Error ? err.message : undefined);+ if (turnsIn(turnsRef.current, targetId).length === 0) clearLive(targetId);+ if (streamingContextIdRef.current === targetId) {+ setRoutingState(null);+ streamingContextIdRef.current = null;+ }}};@@ -643,6 +878,7 @@ export const App: React.FC = () => {};const handleSelectTeam = (team: Team) => {+ setOpenThreadId(null);setSelectedTeamId(team.id);const targetChannel = channels.find((c) => c.name === `team-${team.name}` || c.id === team.id@@ -680,6 +916,7 @@ export const App: React.FC = () => {};const handleSelectChannel = (channel: Channel) => {+ setOpenThreadId(null);setSelectedId(channel.id);selectedIdRef.current = channel.id;setIsChannel(true);@@ -693,6 +930,7 @@ export const App: React.FC = () => {};const handleSelectKwant = (kwant: Kwant) => {+ setOpenThreadId(null);setSelectedId(kwant.id);selectedIdRef.current = kwant.id;setIsChannel(false);@@ -712,7 +950,7 @@ export const App: React.FC = () => {}const kwant = kwants.find((k) => k.id === t.kwant_id);if (!kwant) return false;- if (selectedIdRef.current !== kwant.id) handleSelectKwant(kwant);+ if (selectedIdRef.current !== kwant.id || openThreadId) handleSelectKwant(kwant);return true;};openTargetRef.current = openTarget;@@ -722,6 +960,94 @@ export const App: React.FC = () => {setToasts((prev) => [...prev.slice(-2), { id, title, detail }]);};+ /** Opens one of an agent's threads (from the thread list, a delegation card or a badge). */+ const openThread = (kwantId: string, threadId: string) => {+ const kwant = kwants.find((k) => k.id === kwantId);+ if (!kwant) {+ pushToast('That agent no longer exists.');+ return;+ }+ knownThreadsRef.current.add(threadId);+ if (selectedIdRef.current !== kwant.id || isChannelRef.current) handleSelectKwant(kwant);+ else playSfx('click');+ setOpenThreadId(threadId);+ if (threadsByKwantRef.current[kwantId] === undefined) loadThreads(kwantId);+ };++ const openDirectChat = () => {+ if (!openThreadId) return;+ setOpenThreadId(null);+ playSfx('click');+ };++ const errText = (err: unknown) => (err instanceof Error ? err.message : 'Something went wrong.');++ const handleNewThread = async (): Promise<string | void> => {+ const kwantId = selectedIdRef.current;+ try {+ const t = await threadsApi.create(kwantId);+ knownThreadsRef.current.add(t.id);+ messagesCacheRef.current[t.id] = [];+ setThreadsByKwant((prev) => ({ ...prev, [kwantId]: upsertThread(prev[kwantId], t) }));+ if (selectedIdRef.current === kwantId) setOpenThreadId(t.id);+ } catch (err) {+ return `Couldn't start a conversation: ${errText(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;+ try {+ if (d && (d.status === 'queued' || d.status === 'running')) {+ const next = await threadsApi.cancelDelegation(d.id);+ setDelegations((prev) => ({ ...prev, [next.id]: next }));+ } else {+ await threadsApi.cancel(t.id);+ }+ } catch (err) {+ return `Couldn't stop it: ${errText(err)}`;+ }+ };++ const handleArchiveThread = async (t: Thread, archived: boolean): Promise<string | void> => {+ try {+ const next = await threadsApi.patch(t.id, { archived });+ setThreadsByKwant((prev) => ({ ...prev, [next.kwant_id]: upsertThread(prev[next.kwant_id], next) }));+ if (archived && openThreadId === t.id) {+ setOpenThreadId(null);+ pushToast(`Archived “${t.title}”`, 'Find it under Archived in the conversation list.');+ }+ } catch (err) {+ return `Couldn't ${archived ? 'archive' : 'unarchive'} it: ${errText(err)}`;+ }+ };++ const handleCancelDelegation = async (id: string): Promise<string | void> => {+ try {+ const next = await threadsApi.cancelDelegation(id);+ setDelegations((prev) => ({ ...prev, [next.id]: next }));+ } catch (err) {+ return `Couldn't stop it: ${errText(err)}`;+ }+ };++ const renderDelegation = (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => {+ const queued = turnsIn(turns, meta.thread_id).find((t) => t.state === 'queued');+ return (+ <DelegationCard+ meta={meta}+ text={msg.text}+ messageId={msg.id}+ live={delegations[meta.delegation_id]}+ queuePos={queued ? queuePosition(turns, queued.turn_id) : null}+ onOpenThread={(m) => openThread(m.specialist_id, m.thread_id)}+ onCancel={handleCancelDelegation}+ flash={flash}+ />+ );+ };+// Search result picked: open its chat, then scroll to the message if it's among the ones loaded.const handleJump = async (hit: SearchHit) => {const targetId = hit.channel_id ?? hit.kwant_id;@@ -1186,7 +1512,94 @@ export const App: React.FC = () => {const closeProfiles = useCallback(() => setIsProfilesOpen(false), []);- const isCurrentContextStreaming = isStreaming && streamingContextId === selectedId;+ const isCurrentContextStreaming = openCtx in live;+ const openTurns = turnsIn(turns, openCtx);+ const waiting = openTurns.some((t) => t.state === 'running') ? undefined : openTurns.find((t) => t.state === 'queued');+ const queuedHere: QueuedState | null = waiting+ ? { position: queuePosition(turns, waiting.turn_id), reason: waiting.reason ?? 'agent_busy', speaker: kwantName(waiting.kwant_id) ?? live[openCtx] ?? 'The agent' }+ : null;++ // The agent'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;+ 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 ??+ (ctx === kwantId ? 'the direct chat' : channels.find((c) => c.id === ctx) ? channelLabel(channels.find((c) => c.id === ctx)!.name) : 'another conversation');+ const workingBadge =+ currentKwant && elsewhere.length > 0 ? (+ <button+ type="button"+ onClick={() => {+ const t = elsewhere[0];+ if (t.thread_id) openThread(t.kwant_id, t.thread_id);+ else if (t.context_id === t.kwant_id) openDirectChat();+ else openTarget({ channel_id: t.context_id, kwant_id: null });+ }}+ className="inline-flex items-center gap-1.5 min-w-0 max-w-[16rem] sm:max-w-xs px-2 py-0.5 rounded-full border border-sky-500/30 bg-sky-500/10 text-[11px] text-sky-200 hover:bg-sky-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ title={elsewhere.map((t) => describeContext(t.context_id, t.kwant_id)).join(', ')}+ >+ <Loader2 size={10} className="shrink-0 animate-spin motion-reduce:animate-none" aria-hidden="true" />+ <span className="truncate">+ {elsewhere[0].state === 'queued' ? 'Waiting to work on ' : 'Working on '}+ {describeContext(elsewhere[0].context_id, elsewhere[0].kwant_id)}+ </span>+ {elsewhere.length > 1 && <span className="shrink-0 text-sky-300/80">+{elsewhere.length - 1} more</span>}+ </button>+ ) : null;+ // Sidebar: agents busy somewhere other than the open chat.+ const busyKwants: Record<string, string> = {};+ for (const t of Object.values(turns)) {+ if (t.context_id === openCtx || busyKwants[t.kwant_id]) continue;+ busyKwants[t.kwant_id] = `${t.state === 'queued' ? 'Waiting to work on' : 'Working on'} ${describeContext(t.context_id, t.kwant_id)}`;+ }++ const errorBar = messagesError ? (+ <div role="alert" className="px-3 sm:px-6 py-2 border-b border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">+ <span>{messagesError}</span>+ <button+ type="button"+ onClick={() => refreshContext(openCtx)}+ className="px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"+ >+ Retry+ </button>+ </div>+ ) : null;+ const subHeader = currentKwant ? (+ <>+ <ThreadBar+ kwantName={currentKwant.name}+ threads={agentThreads}+ error={threadErrors[currentKwant.id] ?? null}+ openThreadId={openThreadId}+ turns={turns}+ directBadge={threadBadge({ id: currentKwant.id, delegation: null }, turns)}+ showArchived={showArchived}+ onToggleArchived={() => setShowArchived((v) => !v)}+ onOpenDirect={openDirectChat}+ onOpenThread={(t) => openThread(t.kwant_id, t.id)}+ onNewThread={handleNewThread}+ onRetry={() => loadThreads(currentKwant.id)}+ />+ {shownThread && (+ <ThreadHeader+ thread={shownThread}+ badge={threadBadge(+ { id: shownThread.id, delegation: shownThread.delegation ? delegations[shownThread.delegation.id] ?? shownThread.delegation : null },+ turns,+ )}+ delegatedBy={kwantName(shownThread.delegation?.lead_kwant_id ?? shownThread.created_by)}+ onBack={openDirectChat}+ onStop={() => handleStopThread(shownThread)}+ onArchive={(archived) => handleArchiveThread(shownThread, archived)}+ />+ )}+ {errorBar}+ </>+ ) : (+ errorBar+ );const pinned: PinnedItem[] = [];if (currentTeam?.instructions?.trim()) pinned.push({ label: `Team @${currentTeam.name}`, text: currentTeam.instructions });if (isChannel && currentChannel?.instructions?.trim())@@ -1219,6 +1632,7 @@ export const App: React.FC = () => {selectedId={selectedId}isChannel={isChannel}selectedTeamId={selectedTeamId}+ busyKwants={busyKwants}onSelectKwant={handleSelectKwant}onSelectChannel={handleSelectChannel}onSelectTeam={handleSelectTeam}@@ -1250,7 +1664,7 @@ export const App: React.FC = () => {streamingThinking={isCurrentContextStreaming ? streamingThinking : ''}pendingApproval={pendingApproval}isStreaming={isCurrentContextStreaming}- streamingSpeakerName={streamingSpeakerName}+ streamingSpeakerName={live[openCtx] || undefined}onSendMessage={handleSendMessage}onResolveApproval={handleResolveApproval}kwants={kwants}@@ -1301,6 +1715,11 @@ export const App: React.FC = () => {}highlightMessageId={highlightMessageId}onHighlightDone={() => setHighlightMessageId(null)}+ subHeader={subHeader}+ titleExtra={workingBadge}+ queued={queuedHere}+ renderDelegation={renderDelegation}+ contextKey={openCtx}/></div>diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex a822077d..7961970f 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -9,6 +9,7 @@ import { VirtualMachinePane, TerminalLogEntry } from './VirtualMachinePane';import { playSfx } from '../audio/chiptune';import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThreads';import { PinnedInstructions, PinnedItem } from './Instructions';+import { DelegationMeta, parseDelegationMeta } from '../threads';export interface ChatMessage {id: string;@@ -18,6 +19,18 @@ export interface ChatMessage {reasoning_content?: string | null;tool_calls?: string | null;tokens_used?: number;+ channel_id?: string | null;+ direct_kwant_id?: string | null;+ thread_id?: string | null;+ /** JSON string kwnt sets on messages it writes itself, e.g. delegation notes. */+ meta?: string | null;+}++/** The open chat's turn is waiting for a free slot. */+export interface QueuedState {+ position: number | null;+ reason: 'agent_busy' | 'server_busy';+ speaker: string;}export interface DiscussionState {@@ -95,6 +108,16 @@ export interface ChatViewProps {/** A message to scroll to and flash (from search). */highlightMessageId?: string | null;onHighlightDone?: () => void;+ /** Under the header: the agent's conversations and the open thread's controls. */+ subHeader?: React.ReactNode;+ /** Next to the title, e.g. "Working on …" while the agent has background turns. */+ titleExtra?: React.ReactNode;+ /** Set while the open chat's turn waits in the queue. */+ queued?: QueuedState | null;+ /** Draws a delegation note or result (messages with delegation `meta`). */+ renderDelegation?: (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => React.ReactNode;+ /** Changes when another chat opens, so the view jumps to its bottom. */+ contextKey?: string;}export const renderFormattedText = (text: string): React.ReactNode => {@@ -223,6 +246,11 @@ export const ChatView: React.FC<ChatViewProps> = ({onEditInstructions,highlightMessageId,onHighlightDone,+ subHeader,+ titleExtra,+ queued,+ renderDelegation,+ contextKey,}) => {const [internalIsVmPaneOpen, setInternalIsVmPaneOpen] = useState(false);const vmOpen = isVmPaneOpen !== undefined ? isVmPaneOpen : internalIsVmPaneOpen;@@ -352,12 +380,20 @@ export const ChatView: React.FC<ChatViewProps> = ({}, 0);};- // Auto-scroll on new tokens+ // Follow new tokens only while the reader is at the bottom; scrolling up to read stays put.+ const stickRef = useRef(true);+ const onScroll = () => {+ const el = scrollRef.current;+ if (el) stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;+ };+ useEffect(() => {+ stickRef.current = true;+ }, [contextKey]);useEffect(() => {- if (scrollRef.current) {+ if (scrollRef.current && stickRef.current) {scrollRef.current.scrollTop = scrollRef.current.scrollHeight;}- }, [messages, streamingText, streamingThinking, pendingApproval, routingState]);+ }, [messages, streamingText, streamingThinking, pendingApproval, routingState, queued, contextKey]);// Jump to a search hit: open its folded discussion if needed, then centre and flash it.// Runs after the auto-scroll above, so it wins.@@ -397,8 +433,10 @@ export const ChatView: React.FC<ChatViewProps> = ({const handleSubmit = (e?: React.FormEvent) => {if (e) e.preventDefault();- if (!inputVal.trim() || isStreaming) return;+ // A reply in progress doesn't block the next message (it waits its turn); a team discussion does.+ if (!inputVal.trim() || (isStreaming && discussionState?.inProgress)) return;playSfx('click');+ stickRef.current = true;onSendMessage(inputVal.trim());setInputVal('');setMentionQuery(null);@@ -449,6 +487,8 @@ export const ChatView: React.FC<ChatViewProps> = ({};const renderMessage = (msg: ChatMessage) => {+ const meta = msg.meta && renderDelegation ? parseDelegationMeta(msg.meta) : null;+ if (meta && renderDelegation) return <React.Fragment key={msg.id}>{renderDelegation(msg, meta, flashId === msg.id)}</React.Fragment>;const isUser = msg.sender_role === 'user';const isThoughtOpen = !!openThoughts[msg.id];const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);@@ -549,8 +589,9 @@ export const ChatView: React.FC<ChatViewProps> = ({{/* Channel / Agent Header */}<div className="h-14 border-b border-zinc-800/80 px-6 flex items-center justify-between bg-zinc-900/30 backdrop-blur-sm select-none"><div>- <h2 className="text-sm font-semibold text-zinc-100 flex items-center gap-2">- <span>{title}</span>+ <h2 className="text-sm font-semibold text-zinc-100 flex items-center gap-2 min-w-0">+ <span className="truncate">{title}</span>+ {titleExtra}</h2><p className="text-[11px] text-zinc-400 truncate max-w-lg mt-0.5">{subtitle}</p></div>@@ -663,6 +704,8 @@ export const ChatView: React.FC<ChatViewProps> = ({</div></div>+ {subHeader}+<PinnedInstructions items={pinned} onEdit={onEditInstructions} />{/* Discussion In-Flight Banner */}@@ -713,7 +756,14 @@ export const ChatView: React.FC<ChatViewProps> = ({<div className="flex-1 flex overflow-hidden min-h-0"><div className="flex-1 flex flex-col h-full overflow-hidden min-w-0">{/* Messages Stream */}- <div ref={scrollRef} className="flex-1 overflow-y-auto p-6 space-y-6">+ <div+ ref={scrollRef}+ onScroll={onScroll}+ className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-6"+ role="log"+ aria-label={`Messages in ${title}`}+ aria-busy={isStreaming}+ >{groupDiscussionThreads(messages).map((item) => {if (item.kind === 'message') return renderMessage(item.message);const threadKey = `thread:${item.id}`;@@ -749,7 +799,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<LayaRoutingCard routing={routingState} />)}- {/* Live Streaming Assistant Message */}+ {/* Live Streaming Assistant Message (or its place in the queue, in the same frame) */}{isStreaming && routingState?.phase !== 'deciding' && (<div className="flex items-start gap-3.5 w-full max-w-5xl"><ModernAvatar@@ -772,10 +822,17 @@ export const ChatView: React.FC<ChatViewProps> = ({? discussionState.currentSpeaker: streamingSpeakerName || title}</span>- <span className="inline-flex items-center gap-1 text-sky-400 text-[10px]">- <span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-ping" />- {discussionState?.inProgress ? 'Speaking...' : 'Generating...'}- </span>+ {queued ? (+ <span className="inline-flex items-center gap-1 text-amber-300 text-[10px]">+ <span className="w-1.5 h-1.5 rounded-full bg-amber-300" aria-hidden="true" />+ Queued+ </span>+ ) : (+ <span className="inline-flex items-center gap-1 text-sky-400 text-[10px]">+ <span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-ping motion-reduce:animate-none" aria-hidden="true" />+ {discussionState?.inProgress ? 'Speaking...' : 'Generating...'}+ </span>+ )}</div>{streamingThinking && (@@ -785,8 +842,27 @@ export const ChatView: React.FC<ChatViewProps> = ({</div>)}- <div className="p-4 sm:p-5 rounded-2xl rounded-tl-sm bg-zinc-900/60 text-zinc-200 border border-zinc-800/80 text-sm leading-relaxed shadow-sm w-full">- <MarkdownRenderer content={stripDiscussionMarkers(streamingText)} isStreaming={true} />+ <div className="p-4 sm:p-5 min-h-[3.5rem] rounded-2xl rounded-tl-sm bg-zinc-900/60 text-zinc-200 border border-zinc-800/80 text-sm leading-relaxed shadow-sm w-full">+ {queued ? (+ <p className="text-zinc-300" role="status">+ {queued.position ? <strong className="text-amber-200">#{queued.position} in line.</strong> : <strong className="text-amber-200">In line.</strong>}{' '}+ {queued.reason === 'server_busy'+ ? 'kwnt is running as many turns as it allows right now; this one starts as soon as a slot frees up.'+ : `${queued.speaker} is busy with other work; this starts as soon as one of those finishes.`}+ </p>+ ) : streamingText ? (+ <MarkdownRenderer content={stripDiscussionMarkers(streamingText)} isStreaming={true} />+ ) : (+ <span className="inline-flex gap-1 py-1.5" aria-label="Waiting for the first words">+ {[0, 1, 2].map((i) => (+ <span+ key={i}+ className="w-1.5 h-1.5 rounded-full bg-zinc-500 animate-bounce motion-reduce:animate-none"+ style={{ animationDelay: `${i * 150}ms` }}+ />+ ))}+ </span>+ )}</div></div></div>@@ -888,18 +964,21 @@ export const ChatView: React.FC<ChatViewProps> = ({className="flex-1 bg-transparent px-3 py-1.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"/>- {isStreaming ? (+ {isStreaming && (<buttontype="button"onClick={onCancelDiscussion}- className="w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 bg-red-500/20 hover:bg-red-500/30 text-red-400 border border-red-500/30 shadow-sm cursor-pointer"+ className="w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 bg-red-500/20 hover:bg-red-500/30 text-red-400 border border-red-500/30 shadow-sm cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"title={discussionState?.inProgress ? 'Stop Discussion' : 'Stop generation'}+ aria-label={discussionState?.inProgress ? 'Stop discussion' : 'Stop the reply'}>- <Square size={12} fill="currentColor" />+ <Square size={12} fill="currentColor" aria-hidden="true" /></button>- ) : (+ )}+ {!(isStreaming && (discussionState?.inProgress || !inputVal.trim())) && (<buttontype="submit"+ aria-label={isStreaming ? 'Send (waits for the current reply)' : 'Send'}disabled={!inputVal.trim()}className={`w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${inputVal.trim()diff --git a/frontend/src/components/DelegationCard.tsx b/frontend/src/components/DelegationCard.tsxnew file mode 100644index 00000000..7aee2d5a--- /dev/null+++ b/frontend/src/components/DelegationCard.tsx@@ -0,0 +1,139 @@+import React, { useState } from 'react';+import { ArrowRightLeft, CheckCircle2, Clock, ExternalLink, Loader2, Square, XCircle, AlertTriangle } from 'lucide-react';+import { MarkdownRenderer } from './MarkdownRenderer';+import { ModernAvatar } from './ModernAvatar';+import { Delegation, DelegationMeta, DelegationStatus, delegationStatusLine, isOpenDelegation } from '../threads';++export interface DelegationCardProps {+ meta: DelegationMeta;+ /** The message text: the result for `delegation_result`, kwnt's note otherwise. */+ text: string;+ messageId: string;+ /** Live record from `delegation_updated`, when known; wins over `meta.status`. */+ live?: Delegation | null;+ /** Place in line while the specialist's turn waits for a slot. */+ queuePos?: number | null;+ onOpenThread: (meta: DelegationMeta) => void;+ /** Stops the delegation; resolves to an error message on failure. */+ onCancel: (delegationId: string) => Promise<string | void>;+ flash?: boolean;+}++const LONG_RESULT = 1400;++const tone: Record<DelegationStatus, { icon: React.ReactNode; ring: string; text: string }> = {+ queued: { icon: <Clock size={13} aria-hidden="true" />, ring: 'border-amber-500/30', text: 'text-amber-300' },+ running: { icon: <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />, ring: 'border-sky-500/30', text: 'text-sky-300' },+ completed: { icon: <CheckCircle2 size={13} aria-hidden="true" />, ring: 'border-emerald-500/30', text: 'text-emerald-300' },+ failed: { icon: <XCircle size={13} aria-hidden="true" />, ring: 'border-rose-500/30', text: 'text-rose-300' },+ cancelled: { icon: <Square size={11} aria-hidden="true" />, ring: 'border-zinc-700', text: 'text-zinc-400' },+ interrupted: { icon: <AlertTriangle size={13} aria-hidden="true" />, ring: 'border-amber-500/30', text: 'text-amber-300' },+};++/**+ * A delegation in the lead's chat: who got the task, its live status, a link to the specialist's+ * thread and Stop while it runs. The result card also shows the specialist's answer.+ */+export const DelegationCard: React.FC<DelegationCardProps> = ({ meta, text, messageId, live, queuePos, onOpenThread, onCancel, flash }) => {+ const [stopping, setStopping] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [expanded, setExpanded] = useState(false);++ const status: DelegationStatus = live?.status ?? meta.status;+ const t = tone[status] ?? tone.queued;+ const isResult = meta.kind === 'delegation_result';+ const running = isOpenDelegation({ status });+ const line = delegationStatusLine(status, meta.specialist_name, { queuePos, error: live?.error });+ const headingId = `dlg-${messageId}`;+ const long = isResult && text.length > LONG_RESULT;++ const stop = async () => {+ setStopping(true);+ setError(null);+ const err = await onCancel(meta.delegation_id);+ if (err) setError(err);+ setStopping(false);+ };++ return (+ <section+ data-message-id={messageId}+ aria-labelledby={headingId}+ className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}+ >+ {isResult ? (+ <ModernAvatar role={meta.specialist_name} name={meta.specialist_name} size={34} kwantId={meta.specialist_id || undefined} />+ ) : (+ <div className="w-[34px] h-[34px] flex-shrink-0 rounded-full bg-zinc-900 border border-zinc-800 flex items-center justify-center">+ <ArrowRightLeft size={15} className="text-amber-300" aria-hidden="true" />+ </div>+ )}+ <div className={`flex-1 min-w-0 max-w-4xl rounded-2xl rounded-tl-sm border ${t.ring} bg-zinc-900/60 shadow-sm`}>+ <div className="px-4 pt-3 pb-2 flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="text-[11px] font-medium text-zinc-400">+ {isResult ? 'Result from' : meta.kind === 'delegation_stalled' ? 'Still running at' : 'Delegated to'}{' '}+ <span className="text-zinc-200">{meta.specialist_name}</span>+ </span>+ <h3 id={headingId} className="basis-full text-sm font-semibold text-zinc-100 break-words">+ {meta.title}+ </h3>+ <p className={`basis-full flex items-center gap-1.5 text-[11px] ${t.text}`} role="status" aria-live="polite">+ {t.icon}+ <span className="min-w-0 break-words">{line}</span>+ </p>+ </div>++ {isResult ? (+ <div className="px-4 pb-2 text-sm text-zinc-200 leading-relaxed border-t border-zinc-800/80 pt-3">+ <div className={long && !expanded ? 'max-h-72 overflow-hidden relative' : ''}>+ <MarkdownRenderer content={text} />+ {long && !expanded && (+ <div className="absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-zinc-900 to-transparent" aria-hidden="true" />+ )}+ </div>+ {long && (+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ aria-expanded={expanded}+ className="mt-1 text-[11px] font-medium text-sky-300 hover:text-sky-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 rounded"+ >+ {expanded ? 'Show less' : 'Show the whole answer'}+ </button>+ )}+ </div>+ ) : (+ meta.kind === 'delegation_stalled' && <p className="px-4 pb-2 text-xs text-zinc-400">{text}</p>+ )}++ <div className="px-4 pb-3 pt-1 flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={() => onOpenThread(meta)}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-sky-300 bg-sky-500/10 border border-sky-500/30 hover:bg-sky-500/20 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <ExternalLink size={12} aria-hidden="true" />+ Open {meta.specialist_name}'s thread+ </button>+ {running && (+ <button+ type="button"+ onClick={stop}+ disabled={stopping}+ aria-label={`Stop “${meta.title}”`}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-rose-300 bg-rose-500/10 border border-rose-500/30 hover:bg-rose-500/20 transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"+ >+ <Square size={10} fill="currentColor" aria-hidden="true" />+ {stopping ? 'Stopping…' : 'Stop'}+ </button>+ )}+ {error && (+ <span role="alert" className="text-[11px] text-rose-300">+ {error}+ </span>+ )}+ </div>+ </div>+ </section>+ );+};diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsxindex f3e7838e..68d641d9 100644--- a/frontend/src/components/ModernAvatar.tsx+++ b/frontend/src/components/ModernAvatar.tsx@@ -19,7 +19,7 @@ export const useKwantWorking = (kwantId: string | undefined): boolean => {(onChange: () => void) => (kwantId ? subscribeKwant(kwantId, onChange) : noopUnsubscribe),[kwantId],);- return useSyncExternalStore(subscribe, () => isKwantWorking(kwantId));+ return useSyncExternalStore(subscribe, () => isKwantWorking(kwantId), () => false);};type Accessory =diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex bbc02591..ca45843a 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -1,5 +1,6 @@import React, { useState, useEffect, useRef } from 'react';-import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle } from 'lucide-react';+import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle, Layers } from 'lucide-react';+import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';import {BROWSER_NOTIFY_KEY,MASK,@@ -26,8 +27,17 @@ interface SettingsData {/** "••••••••" when one is saved, "" otherwise. */notify_webhook_url?: string;notify_on?: NotifyKind[];+ max_turns_per_agent?: number;+ max_turns_global?: number;+ delegation_follow_up_minutes?: number;}+const LIMIT_FIELDS: { key: TurnLimitKey; label: string; hint: string }[] = [+ { key: 'max_turns_per_agent', label: 'Replies at once per agent', hint: 'More than this and an agent’s next request waits in line.' },+ { key: 'max_turns_global', label: 'Replies at once in total', hint: 'Across all agents; keeps the server responsive.' },+ { key: 'delegation_follow_up_minutes', label: 'Check on delegated work after (minutes)', hint: '0 turns the check-in off.' },+];+interface SettingsModalProps {isOpen: boolean;onClose: () => void;@@ -50,6 +60,14 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oconst [browserNotify, setBrowserNotify] = useState(browserNotifyEnabled);const [permission, setPermission] = useState(notificationPermission);const webhookError = webhookUrlError(webhookUrl);+ // Kept as typed text so a half-typed value can be shown with its error; null until loaded.+ const [limits, setLimits] = useState<Record<TurnLimitKey, string> | null>(null);+ const limitErrors = Object.fromEntries(+ LIMIT_FIELDS.map(({ key }) => [key, limits ? limitError(key, limits[key]) : null]),+ ) as Record<TurnLimitKey, string | null>;+ const limitsInvalid = Object.values(limitErrors).some(Boolean);+ const perAgentOverGlobal =+ !!limits && !limitsInvalid && Number(limits.max_turns_per_agent) > Number(limits.max_turns_global);const closeRef = useRef(onClose);closeRef.current = onClose;@@ -75,6 +93,15 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, osetOllamaUrl(data.ollama_url || 'http://localhost:11434/v1');setWebhookUrl(data.notify_webhook_url ?? '');if (Array.isArray(data.notify_on)) setNotifyOn(data.notify_on);+ setLimits(+ typeof data.max_turns_per_agent === 'number'+ ? {+ max_turns_per_agent: String(data.max_turns_per_agent),+ max_turns_global: String(data.max_turns_global ?? ''),+ delegation_follow_up_minutes: String(data.delegation_follow_up_minutes ?? ''),+ }+ : null,+ );}).catch((err) => console.error('Failed to load settings:', err));}@@ -101,7 +128,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oconst handleSave = async (e: React.FormEvent) => {e.preventDefault();- if (webhookError) return;+ if (webhookError || limitsInvalid) return;setSaveError(null);setSaving(true);playSfx('click');@@ -117,6 +144,13 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oollama_url: ollamaUrl,notify_webhook_url: webhookUrl.trim(),notify_on: notifyOn,+ ...(limits+ ? {+ max_turns_per_agent: Number(limits.max_turns_per_agent),+ max_turns_global: Number(limits.max_turns_global),+ delegation_follow_up_minutes: Number(limits.delegation_follow_up_minutes),+ }+ : {}),}),});@@ -308,6 +342,51 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div></div>+ {limits && (+ <fieldset className="space-y-3 pt-2 border-t border-zinc-800">+ <legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">+ <Layers size={14} className="text-sky-300" aria-hidden="true" />+ <span>Parallel work</span>+ </legend>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">+ {LIMIT_FIELDS.map(({ key, label, hint }) => {+ const err = limitErrors[key];+ const { min, max } = TURN_LIMITS[key];+ return (+ <div key={key} className="space-y-1">+ <label htmlFor={`limit-${key}`} className="block text-[11px] font-medium text-zinc-300">+ {label}+ </label>+ <input+ id={`limit-${key}`}+ type="number"+ inputMode="numeric"+ min={min}+ max={max}+ step={1}+ value={limits[key]}+ onChange={(e) => setLimits((prev) => (prev ? { ...prev, [key]: e.target.value } : prev))}+ aria-invalid={!!err}+ aria-describedby={`limit-${key}-hint`}+ className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-xs text-zinc-100 focus:outline-none transition-colors ${+ err ? 'border-rose-500/60 focus:border-rose-400' : 'border-zinc-800 focus:border-sky-500'+ }`}+ />+ <p id={`limit-${key}-hint`} className={`text-[11px] ${err ? 'text-rose-300' : 'text-zinc-500'}`}>+ {err ?? `${hint} (${min}–${max})`}+ </p>+ </div>+ );+ })}+ </div>+ {perAgentOverGlobal && (+ <p className="text-[11px] text-amber-300" role="status">+ The total is lower than the per-agent limit, so an agent never gets more than {limits.max_turns_global} at once.+ </p>+ )}+ </fieldset>+ )}+<fieldset className="space-y-3 pt-2 border-t border-zinc-800"><legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3"><Bell size={14} className="text-amber-300" />@@ -437,7 +516,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</button><buttontype="submit"- disabled={saving || !!webhookError}+ disabled={saving || !!webhookError || limitsInvalid}className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50">{saving ? 'Saving...' : 'Save Settings'}diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 13573d76..1bf86567 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -49,6 +49,8 @@ export interface SidebarProps {selectedId: string;isChannel: boolean;selectedTeamId?: string | null;+ /** Agents busy outside the open chat -> "Working on …", shown under their name. */+ busyKwants?: Record<string, string>;onSelectKwant: (kwant: Kwant) => void;onSelectChannel: (channel: Channel) => void;onSelectTeam: (team: Team) => void;@@ -74,6 +76,7 @@ export const Sidebar: React.FC<SidebarProps> = ({selectedId,isChannel,selectedTeamId,+ busyKwants = {},onSelectKwant,onSelectChannel,onSelectTeam,@@ -272,10 +275,16 @@ export const Sidebar: React.FC<SidebarProps> = ({className={`group/member flex items-center gap-2 px-1.5 py-1 rounded-md cursor-pointer text-[11px] transition-colors ${memberActive ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-200'}`}- title={`Chat with ${k.name}`}+ title={busyKwants[k.id] ? `Chat with ${k.name} · ${busyKwants[k.id]}` : `Chat with ${k.name}`}><ModernAvatar role={k.avatar_sprite} name={k.name} size={18} kwantId={k.id} />- <span className="truncate flex-1">{k.name}</span>+ <span className="truncate flex-1">+ {k.name}+ {busyKwants[k.id] && <span className="sr-only"> ({busyKwants[k.id]})</span>}+ </span>+ {busyKwants[k.id] && (+ <span className="w-1.5 h-1.5 shrink-0 rounded-full bg-sky-400 animate-pulse motion-reduce:animate-none" aria-hidden="true" />+ )}{onEditKwant && (<buttontype="button"@@ -454,7 +463,13 @@ export const Sidebar: React.FC<SidebarProps> = ({{k.preferred_model === 'auto' ? 'Laya' : k.preferred_model.split('-')[0]}</span></div>- <p className="text-[11px] text-zinc-400 truncate mt-0.5">{k.title}</p>+ {busyKwants[k.id] ? (+ <p className="text-[11px] text-sky-300 truncate mt-0.5" title={busyKwants[k.id]}>+ {busyKwants[k.id]}+ </p>+ ) : (+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">{k.title}</p>+ )}</div></div>);diff --git a/frontend/src/components/ThreadBar.tsx b/frontend/src/components/ThreadBar.tsxnew file mode 100644index 00000000..38e890cf--- /dev/null+++ b/frontend/src/components/ThreadBar.tsx@@ -0,0 +1,254 @@+import React, { useState } from 'react';+import { Archive, ArchiveRestore, ArrowLeft, ArrowRightLeft, Loader2, MessageSquare, Plus, RotateCw, Square } from 'lucide-react';+import { Badge, BadgeKind, Thread, TurnMap, sortThreads, threadBadge } from '../threads';++const BADGE_STYLE: Record<BadgeKind, string> = {+ working: 'text-sky-300 bg-sky-500/10 border-sky-500/30',+ queued: 'text-amber-300 bg-amber-500/10 border-amber-500/30',+ done: 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30',+ failed: 'text-rose-300 bg-rose-500/10 border-rose-500/30',+ interrupted: 'text-amber-300 bg-amber-500/10 border-amber-500/30',+ cancelled: 'text-zinc-400 bg-zinc-800/60 border-zinc-700',+};++export const StatusBadge: React.FC<{ badge: Badge; className?: string }> = ({ badge, className = '' }) => (+ <span+ className={`inline-flex items-center gap-1 px-1.5 py-px rounded-full border text-[10px] font-medium whitespace-nowrap ${BADGE_STYLE[badge.kind]} ${className}`}+ >+ {badge.kind === 'working' && <Loader2 size={9} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {badge.label}+ </span>+);++export interface ThreadBarProps {+ kwantName: string;+ /** undefined while loading. */+ threads: Thread[] | undefined;+ error: string | null;+ openThreadId: string | null;+ turns: TurnMap;+ /** Badge for the direct chat itself (working / queued). */+ directBadge: Badge | null;+ showArchived: boolean;+ onToggleArchived: () => void;+ onOpenDirect: () => void;+ onOpenThread: (t: Thread) => void;+ onNewThread: () => Promise<string | void>;+ onRetry: () => void;+}++const chip =+ 'flex items-center gap-1.5 shrink-0 max-w-[15rem] px-2.5 py-1 rounded-lg border text-xs transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const chipIdle = 'border-zinc-800 bg-zinc-900/60 text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/70';+const chipOpen = 'border-zinc-600 bg-zinc-800 text-zinc-100';++/**+ * An agent's conversations: the direct chat first, then delegated and user threads, each with its+ * status. Scrolls sideways, so it fits narrow screens.+ */+export const ThreadBar: React.FC<ThreadBarProps> = ({+ kwantName,+ threads,+ error,+ openThreadId,+ turns,+ directBadge,+ showArchived,+ onToggleArchived,+ onOpenDirect,+ onOpenThread,+ onNewThread,+ onRetry,+}) => {+ const [creating, setCreating] = useState(false);+ const [createError, setCreateError] = useState<string | null>(null);+ const visible = threads ? sortThreads(threads, showArchived) : [];+ const archivedCount = threads?.filter((t) => t.archived).length ?? 0;++ const create = async () => {+ setCreating(true);+ setCreateError(null);+ const err = await onNewThread();+ if (err) setCreateError(err);+ setCreating(false);+ };++ return (+ <nav aria-label={`Conversations with ${kwantName}`} className="border-b border-zinc-800/80 bg-zinc-950/60 px-3 sm:px-6 py-2">+ <ul className="flex items-center gap-1.5 overflow-x-auto pb-0.5 -mb-0.5" role="list">+ <li>+ <button+ type="button"+ onClick={onOpenDirect}+ aria-current={!openThreadId ? 'page' : undefined}+ className={`${chip} ${!openThreadId ? chipOpen : chipIdle}`}+ >+ <MessageSquare size={12} aria-hidden="true" className="shrink-0" />+ <span className="truncate">Direct chat</span>+ {directBadge && <StatusBadge badge={directBadge} />}+ </button>+ </li>++ {threads === undefined && !error && (+ <li className="flex items-center gap-1.5 px-2 text-[11px] text-zinc-500" aria-live="polite">+ <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />+ Loading conversations…+ </li>+ )}++ {error && (+ <li className="flex items-center gap-1.5 px-1 text-[11px] text-rose-300" role="alert">+ <span>Couldn't load conversations.</span>+ <button+ type="button"+ onClick={onRetry}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"+ >+ <RotateCw size={10} aria-hidden="true" /> Retry+ </button>+ </li>+ )}++ {visible.map((t) => {+ const badge = threadBadge(t, turns);+ const isOpen = openThreadId === t.id;+ const delegated = t.kind === 'delegation';+ return (+ <li key={t.id}>+ <button+ type="button"+ onClick={() => onOpenThread(t)}+ aria-current={isOpen ? 'page' : undefined}+ title={t.title}+ className={`${chip} ${isOpen ? chipOpen : chipIdle} ${t.archived ? 'opacity-60' : ''}`}+ >+ {delegated ? (+ <ArrowRightLeft size={12} aria-hidden="true" className="shrink-0 text-amber-300/90" />+ ) : (+ <MessageSquare size={12} aria-hidden="true" className="shrink-0" />+ )}+ <span className="truncate">+ <span className="sr-only">{delegated ? 'Delegated: ' : 'Conversation: '}</span>+ {t.title}+ {t.archived && <span className="sr-only"> (archived)</span>}+ </span>+ {badge && <StatusBadge badge={badge} />}+ </button>+ </li>+ );+ })}++ {threads !== undefined && visible.length === 0 && !error && (+ <li className="hidden sm:block px-1 text-[11px] text-zinc-500">No other conversations yet.</li>+ )}++ <li>+ <button+ type="button"+ onClick={create}+ disabled={creating}+ className={`${chip} border-dashed border-zinc-700 text-sky-300 hover:bg-sky-500/10 disabled:opacity-50`}+ title={`Start a separate conversation with ${kwantName}`}+ >+ <Plus size={12} aria-hidden="true" />+ <span>{creating ? 'Starting…' : 'New'}</span>+ </button>+ </li>++ {archivedCount > 0 && (+ <li>+ <button+ type="button"+ onClick={onToggleArchived}+ aria-pressed={showArchived}+ className={`${chip} ${chipIdle}`}+ >+ <Archive size={12} aria-hidden="true" />+ <span>{showArchived ? 'Hide archived' : `Archived (${archivedCount})`}</span>+ </button>+ </li>+ )}+ </ul>+ {createError && (+ <p role="alert" className="mt-1 text-[11px] text-rose-300">+ {createError}+ </p>+ )}+ </nav>+ );+};++export interface ThreadHeaderProps {+ thread: Thread;+ badge: Badge | null;+ /** Name of the agent that delegated it, for delegation threads. */+ delegatedBy?: string;+ onBack: () => void;+ onStop: () => Promise<string | void>;+ onArchive: (archived: boolean) => Promise<string | void>;+}++/** Above an open thread: what it is, its status, Stop while it runs, and Archive. */+export const ThreadHeader: React.FC<ThreadHeaderProps> = ({ thread, badge, delegatedBy, onBack, onStop, onArchive }) => {+ const [busy, setBusy] = useState<'stop' | 'archive' | null>(null);+ const [error, setError] = useState<string | null>(null);+ const running = badge?.kind === 'working' || badge?.kind === 'queued';++ const act = async (kind: 'stop' | 'archive', fn: () => Promise<string | void>) => {+ setBusy(kind);+ setError(null);+ const err = await fn();+ if (err) setError(err);+ setBusy(null);+ };++ return (+ <div className="px-3 sm:px-6 py-2 border-b border-zinc-800/80 bg-zinc-900/20 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">+ <button+ type="button"+ onClick={onBack}+ className="inline-flex items-center gap-1 text-zinc-400 hover:text-zinc-100 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <ArrowLeft size={13} aria-hidden="true" />+ <span>Direct chat</span>+ </button>+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <h3 className="min-w-0 truncate text-zinc-200 font-medium" title={thread.title}>+ {thread.title}+ </h3>+ <span className="text-zinc-500 shrink-0 hidden sm:inline">+ {thread.kind === 'delegation' ? `Delegated by ${delegatedBy ?? 'another agent'}` : 'Separate conversation'}+ </span>+ {badge && <StatusBadge badge={badge} />}+ {thread.archived && <span className="text-[10px] text-zinc-500">Archived</span>}+ </div>+ <div className="flex items-center gap-1.5">+ {running && (+ <button+ type="button"+ onClick={() => act('stop', onStop)}+ disabled={busy !== null}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-medium text-rose-300 bg-rose-500/10 border border-rose-500/30 hover:bg-rose-500/20 disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"+ >+ <Square size={10} fill="currentColor" aria-hidden="true" />+ {busy === 'stop' ? 'Stopping…' : 'Stop'}+ </button>+ )}+ <button+ type="button"+ onClick={() => act('archive', () => onArchive(!thread.archived))}+ disabled={busy !== null}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-medium text-zinc-300 bg-zinc-800/80 border border-zinc-700/60 hover:bg-zinc-700/80 disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ {thread.archived ? <ArchiveRestore size={12} aria-hidden="true" /> : <Archive size={12} aria-hidden="true" />}+ {thread.archived ? 'Unarchive' : 'Archive'}+ </button>+ </div>+ {error && (+ <p role="alert" className="basis-full text-[11px] text-rose-300">+ {error}+ </p>+ )}+ </div>+ );+};diff --git a/frontend/src/components/Toasts.tsx b/frontend/src/components/Toasts.tsxindex 979eb668..80e4173f 100644--- a/frontend/src/components/Toasts.tsx+++ b/frontend/src/components/Toasts.tsx@@ -5,6 +5,8 @@ export interface Toast {id: number;title: string;detail?: string;+ /** One button, e.g. "Open" a chat the toast is about. */+ action?: { label: string; onClick: () => void };}const TOAST_MS = 7000;@@ -20,6 +22,18 @@ const ToastItem: React.FC<{ toast: Toast; onDismiss: (id: number) => void }> = (<div className="flex-1 min-w-0"><p className="font-medium text-zinc-100">{toast.title}</p>{toast.detail && <p className="mt-0.5 text-zinc-400">{toast.detail}</p>}+ {toast.action && (+ <button+ type="button"+ onClick={() => {+ toast.action?.onClick();+ onDismiss(toast.id);+ }}+ className="mt-1.5 px-2 py-0.5 rounded-md text-[11px] font-medium text-sky-300 bg-sky-500/10 border border-sky-500/30 hover:bg-sky-500/20 transition-colors"+ >+ {toast.action.label}+ </button>+ )}</div><buttontype="button"diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.tsindex 4670eb3e..c315eb6b 100644--- a/frontend/src/continuity.ts+++ b/frontend/src/continuity.ts@@ -79,13 +79,18 @@ export interface RoutineInput {enabled: boolean;}-export type NotifyKind = 'turn_finished' | 'approval_needed' | 'routine_failed';+export type NotifyKind = 'turn_finished' | 'approval_needed' | 'routine_failed' | 'delegation_finished' | 'delegation_stalled';export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [{ id: 'turn_finished', label: 'A kwant finished replying' },{ id: 'approval_needed', label: 'A kwant needs your approval' },{ id: 'routine_failed', label: 'A routine failed' },+ { id: 'delegation_finished', label: 'A delegated task finished' },+ { id: 'delegation_stalled', label: 'A delegated task is taking long' },];+/** Kinds also shown as an in-app toast while kwnt is visible (the others only matter in the background). */+export const TOAST_KINDS: NotifyKind[] = ['routine_failed', 'delegation_finished', 'delegation_stalled'];+export interface NotifyEvent {kind: NotifyKind;kwant_id: string;diff --git a/frontend/src/kwantActivity.ts b/frontend/src/kwantActivity.tsindex 57d7a70d..c003957a 100644--- a/frontend/src/kwantActivity.ts+++ b/frontend/src/kwantActivity.ts@@ -3,7 +3,7 @@type Listener = () => void;-/** kwant id -> the contexts it's working in (a kwant can run in a DM and a team at once). */+/** kwant id -> its running turns, by turn id (or context id from servers that don't send turn ids). */const active = new Map<string, Set<string>>();const listeners = new Map<string, Set<Listener>>();@@ -38,6 +38,18 @@ export function clearAllTurns(): void {ids.forEach(notify);}+/** Replaces everything with the server's running turns (GET /api/turns after a (re)connect). */+export function resetTurns(running: Array<{ kwant_id: string; turn_id: string }>): void {+ const before = new Set(active.keys());+ active.clear();+ for (const t of running) {+ const set = active.get(t.kwant_id) ?? new Set<string>();+ set.add(t.turn_id);+ active.set(t.kwant_id, set);+ }+ new Set([...before, ...active.keys()]).forEach(notify);+}+export const isKwantWorking = (kwantId: string | undefined): boolean => !!kwantId && active.has(kwantId);export function subscribeKwant(kwantId: string, listener: Listener): () => void {diff --git a/frontend/src/threads.ts b/frontend/src/threads.tsnew file mode 100644index 00000000..42bcb404--- /dev/null+++ b/frontend/src/threads.ts@@ -0,0 +1,371 @@+// Threads, delegations and concurrent turns (batch 2 / A). Pure helpers, so App and the tests share+// them; the API calls at the bottom are thin wrappers over the routes in design-A.md. No imports, so+// the node tests can load it on its own.++export type DelegationStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled' | 'interrupted';++export interface Delegation {+ id: string;+ thread_id: string;+ lead_kwant_id: string;+ specialist_kwant_id: string;+ origin_channel_id: string | null;+ origin_kwant_id: string | null;+ origin_thread_id: string | null;+ task: string;+ title: string;+ status: DelegationStatus;+ result_message_id: string | null;+ error: string | null;+ created_at: string;+ started_at: string | null;+ ended_at: string | null;+}++export interface ActiveTurn {+ turn_id: string;+ kwant_id: string;+ context_id: string;+ thread_id: string | null;+ state: 'queued' | 'running';+ since?: string;+}++export interface Thread {+ id: string;+ kwant_id: string;+ title: string;+ kind: 'chat' | 'delegation';+ team_id: string | null;+ /** 'user' or the id of the kwant that delegated into it. */+ created_by: string;+ archived: boolean;+ created_at: string;+ updated_at: string;+ delegation?: Delegation | null;+ active?: ActiveTurn[];+}++// ---------------------------------------------------------------------------+// Which chat an SSE event belongs to++/** The open chat's context id: a channel id, a kwant id (direct chat) or a thread id. */+export const contextOf = (open: { selectedId: string; threadId?: string | null }): string => open.threadId || open.selectedId;++/** The chat a turn event belongs to; turn events carry it at the top level, lifecycle events in `data`. */+export function eventContextId(ev: { context_id?: unknown; data?: unknown }): string | null {+ if (typeof ev.context_id === 'string' && ev.context_id) return ev.context_id;+ const d = ev.data as { context_id?: unknown } | null | undefined;+ if (d && typeof d === 'object' && typeof d.context_id === 'string' && d.context_id) return d.context_id;+ return null;+}++/**+ * Where a streamed event (TextDelta, ThinkingDelta, TurnComplete, Error…) should go. Tagged events+ * go to their own chat; untagged ones (older servers, team discussions) to the chat that started+ * the foreground stream.+ */+export const streamTarget = (ev: { context_id?: unknown; data?: unknown }, fallback: string | null): string | null =>+ eventContextId(ev) ?? fallback;++/** True when a streamed event should be drawn in the chat that's open. */+export const shouldRenderDelta = (+ ev: { context_id?: unknown; data?: unknown },+ openContextId: string,+ fallback: string | null,+): boolean => !!openContextId && streamTarget(ev, fallback) === openContextId;++// ---------------------------------------------------------------------------+// Turns: running and queued, from turn_queued / turn_started / turn_ended and GET /api/turns++export interface TrackedTurn extends ActiveTurn {+ /** Order seen; the queue is FIFO. */+ seq: number;+ reason?: 'agent_busy' | 'server_busy';+ /** Position reported by the server when it queued; only ever goes down. */+ reported?: number;+}++export type TurnMap = Readonly<Record<string, TrackedTurn>>;++let seqCounter = 0;++export function hydrateTurns(list: ActiveTurn[] | undefined): TurnMap {+ const out: Record<string, TrackedTurn> = {};+ const sorted = [...(list ?? [])].sort((a, b) => (a.since ?? '').localeCompare(b.since ?? ''));+ for (const t of sorted) {+ if (!t?.turn_id) continue;+ out[t.turn_id] = { ...t, thread_id: t.thread_id ?? null, seq: ++seqCounter };+ }+ return out;+}++/** Applies one SSE event; returns the same map when the event isn't about turns. */+export function applyTurnEvent(turns: TurnMap, ev: { type?: string; data?: any }): TurnMap {+ const d = ev.data ?? {};+ const id: unknown = d.turn_id;+ switch (ev.type) {+ case 'turn_queued':+ case 'TurnQueued': {+ if (typeof id !== 'string') return turns;+ return {+ ...turns,+ [id]: {+ turn_id: id,+ kwant_id: d.kwant_id,+ context_id: d.context_id ?? d.thread_id ?? d.kwant_id,+ thread_id: d.thread_id ?? null,+ state: 'queued',+ seq: turns[id]?.seq ?? ++seqCounter,+ reason: d.reason === 'server_busy' ? 'server_busy' : 'agent_busy',+ reported: typeof d.position === 'number' ? d.position : undefined,+ since: new Date().toISOString(),+ },+ };+ }+ case 'turn_started':+ case 'TurnStarted': {+ if (typeof id !== 'string') return turns;+ const prev = turns[id];+ return {+ ...turns,+ [id]: {+ turn_id: id,+ kwant_id: d.kwant_id,+ context_id: d.context_id ?? d.thread_id ?? d.kwant_id,+ thread_id: d.thread_id ?? null,+ state: 'running',+ seq: prev?.seq ?? ++seqCounter,+ since: prev?.since ?? new Date().toISOString(),+ },+ };+ }+ case 'turn_ended':+ case 'TurnEnded': {+ if (typeof id !== 'string' || !turns[id]) return turns;+ const next = { ...turns };+ delete next[id];+ return next;+ }+ default:+ return turns;+ }+}++/** 1 = next to start. Counts the queued turns ahead in the same line (the agent's, or the server's). */+export function queuePosition(turns: TurnMap, turnId: string): number | null {+ const t = turns[turnId];+ if (!t || t.state !== 'queued') return null;+ let ahead = 0;+ for (const o of Object.values(turns)) {+ if (o.state !== 'queued' || o.seq >= t.seq) continue;+ if (t.reason === 'server_busy' || o.kwant_id === t.kwant_id) ahead++;+ }+ const computed = ahead + 1;+ return t.reported ? Math.min(t.reported, computed) : computed;+}++export const turnsIn = (turns: TurnMap, contextId: string): TrackedTurn[] =>+ Object.values(turns)+ .filter((t) => t.context_id === contextId)+ .sort((a, b) => a.seq - b.seq);++/** The kwant's turns outside its direct chat (threads, delegations, team channels), oldest first. */+export const backgroundTurns = (turns: TurnMap, kwantId: string): TrackedTurn[] =>+ Object.values(turns)+ .filter((t) => t.kwant_id === kwantId && t.context_id !== kwantId)+ .sort((a, b) => a.seq - b.seq);++// ---------------------------------------------------------------------------+// Thread list and status badges++export type BadgeKind = 'working' | 'queued' | 'done' | 'failed' | 'interrupted' | 'cancelled';++export interface Badge {+ kind: BadgeKind;+ /** Short visible text, e.g. "Queued · #2". */+ label: string;+}++const FINAL_LABEL: Record<string, Badge> = {+ completed: { kind: 'done', label: 'Done' },+ failed: { kind: 'failed', label: 'Failed' },+ cancelled: { kind: 'cancelled', label: 'Cancelled' },+ interrupted: { kind: 'interrupted', label: 'Interrupted' },+};++/** A thread's badge: live turns win over the delegation record; idle user threads have none. */+export function threadBadge(thread: Pick<Thread, 'id' | 'delegation'>, turns: TurnMap): Badge | null {+ const live = turnsIn(turns, thread.id);+ if (live.some((t) => t.state === 'running')) return { kind: 'working', label: 'Working' };+ const queued = live.find((t) => t.state === 'queued');+ if (queued) {+ const pos = queuePosition(turns, queued.turn_id);+ return { kind: 'queued', label: pos ? `Queued · #${pos}` : 'Queued' };+ }+ const st = thread.delegation?.status;+ if (!st) return null;+ if (st === 'running') return { kind: 'working', label: 'Working' };+ if (st === 'queued') return { kind: 'queued', label: 'Queued' };+ return FINAL_LABEL[st] ?? null;+}++export const isOpenDelegation = (d: Pick<Delegation, 'status'> | null | undefined): boolean =>+ !!d && (d.status === 'queued' || d.status === 'running');++/** Visible threads: delegated ones first, then the person's, newest activity first within each. */+export function sortThreads(threads: Thread[], includeArchived = false): Thread[] {+ return threads+ .filter((t) => includeArchived || !t.archived)+ .sort((a, b) => {+ if (a.archived !== b.archived) return a.archived ? 1 : -1;+ if (a.kind !== b.kind) return a.kind === 'delegation' ? -1 : 1;+ return (b.updated_at ?? '').localeCompare(a.updated_at ?? '');+ });+}++/** Inserts or replaces a thread, keeping fields only the list route sends (delegation, active). */+export function upsertThread(list: Thread[] | undefined, t: Thread): Thread[] {+ const prev = list ?? [];+ const i = prev.findIndex((x) => x.id === t.id);+ if (i < 0) return [t, ...prev];+ const merged = { ...prev[i], ...t, delegation: t.delegation ?? prev[i].delegation, active: t.active ?? prev[i].active };+ return prev.map((x, j) => (j === i ? merged : x));+}++/** Puts a delegation update on its thread; unknown threads are left alone (the list fetch brings them). */+export function applyDelegation(list: Thread[] | undefined, d: Delegation): Thread[] | undefined {+ if (!list || !list.some((t) => t.id === d.thread_id)) return list;+ return list.map((t) => (t.id === d.thread_id ? { ...t, delegation: d } : t));+}++// ---------------------------------------------------------------------------+// Messages kwnt writes about delegations (`meta` is a JSON string on the wire)++export type DelegationMetaKind = 'delegation_started' | 'delegation_result' | 'delegation_stalled';++export interface DelegationMeta {+ kind: DelegationMetaKind;+ delegation_id: string;+ thread_id: string;+ specialist_id: string;+ specialist_name: string;+ lead_id?: string;+ status: DelegationStatus;+ title: string;+}++const META_KINDS: DelegationMetaKind[] = ['delegation_started', 'delegation_result', 'delegation_stalled'];++/** Parses `message.meta`; null for anything that isn't a well-formed delegation note. Never throws. */+export function parseDelegationMeta(raw: unknown): DelegationMeta | null {+ let v: unknown = raw;+ if (typeof raw === 'string') {+ if (!raw.trim()) return null;+ try {+ v = JSON.parse(raw);+ } catch {+ return null;+ }+ }+ if (!v || typeof v !== 'object') return null;+ const m = v as Record<string, unknown>;+ if (!META_KINDS.includes(m.kind as DelegationMetaKind)) return null;+ if (typeof m.delegation_id !== 'string' || typeof m.thread_id !== 'string') return null;+ const str = (x: unknown, d = '') => (typeof x === 'string' ? x : d);+ return {+ kind: m.kind as DelegationMetaKind,+ delegation_id: m.delegation_id,+ thread_id: m.thread_id,+ specialist_id: str(m.specialist_id),+ specialist_name: str(m.specialist_name, 'The specialist'),+ lead_id: typeof m.lead_id === 'string' ? m.lead_id : undefined,+ status: (str(m.status, 'queued') as DelegationStatus),+ title: str(m.title, 'Delegated task'),+ };+}++/** The one-line status under a delegation card, from the live record when there is one. */+export function delegationStatusLine(+ status: DelegationStatus,+ specialist: string,+ opts: { queuePos?: number | null; error?: string | null } = {},+): string {+ switch (status) {+ case 'queued':+ return opts.queuePos ? `Waiting for ${specialist} · #${opts.queuePos} in line` : `Waiting for ${specialist} to start`;+ case 'running':+ return `${specialist} is working on it`;+ case 'completed':+ return `${specialist} finished`;+ case 'failed':+ return opts.error ? `${specialist} couldn't finish: ${opts.error}` : `${specialist} couldn't finish`;+ case 'cancelled':+ return 'Stopped';+ case 'interrupted':+ return 'Interrupted by a restart';+ default:+ return '';+ }+}++/** Where a message belongs, for `message_added`. */+export const messageContextId = (m: { thread_id?: string | null; channel_id?: string | null; direct_kwant_id?: string | null }) =>+ m.thread_id || m.channel_id || m.direct_kwant_id || null;++// ---------------------------------------------------------------------------+// API++async function request<T>(method: string, url: string, body?: unknown): Promise<T> {+ const res = await fetch(url, {+ method,+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ if (!res.ok) {+ let message = res.status === 404 ? 'It no longer exists.' : `Request failed (HTTP ${res.status}).`;+ try {+ const data = await res.json();+ if (data && typeof data.error === 'string' && data.error) message = data.error;+ } catch {+ // no JSON body+ }+ throw new Error(message);+ }+ return res.json();+}++const enc = encodeURIComponent;++export const threadsApi = {+ list: (kwantId: string, includeArchived = false) =>+ request<Thread[]>('GET', `/api/kwants/${enc(kwantId)}/threads${includeArchived ? '?include_archived=1' : ''}`),+ create: (kwantId: string, title?: string) => request<Thread>('POST', `/api/kwants/${enc(kwantId)}/threads`, title ? { title } : {}),+ patch: (id: string, body: { title?: string; archived?: boolean }) => request<Thread>('PATCH', `/api/threads/${enc(id)}`, body),+ messages: <M>(id: string) => request<M[]>('GET', `/api/threads/${enc(id)}/messages`),+ cancel: (id: string) => request<{ cancelled: number }>('POST', `/api/threads/${enc(id)}/cancel`),+ turns: () => request<{ turns: ActiveTurn[] }>('GET', '/api/turns'),+ delegation: (id: string) => request<Delegation>('GET', `/api/delegations/${enc(id)}`),+ cancelDelegation: (id: string) => request<Delegation>('POST', `/api/delegations/${enc(id)}/cancel`),+};++// ---------------------------------------------------------------------------+// Settings++export const TURN_LIMITS = {+ max_turns_per_agent: { min: 1, max: 16 },+ max_turns_global: { min: 1, max: 64 },+ delegation_follow_up_minutes: { min: 0, max: 1440 },+} as const;++export type TurnLimitKey = keyof typeof TURN_LIMITS;++/** Error text for one limit field, or null when it's a whole number in range. */+export function limitError(key: TurnLimitKey, raw: string): string | null {+ const { min, max } = TURN_LIMITS[key];+ const s = raw.trim();+ if (!/^\d+$/.test(s)) return `Enter a whole number from ${min} to ${max}.`;+ const n = Number(s);+ if (n < min || n > max) return `Use ${min}–${max}.`;+ return null;+}diff --git a/frontend/tests/threads.test.mjs b/frontend/tests/threads.test.mjsnew file mode 100644index 00000000..2878d224--- /dev/null+++ b/frontend/tests/threads.test.mjs@@ -0,0 +1,267 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import test from 'node:test';+import ts from 'typescript';+import { build } from 'esbuild';++const load = async (path) => {+ const source = await readFile(new URL(path, import.meta.url), 'utf8');+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext } });+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);+};++const t = await load('../src/threads.ts');++// ---------------------------------------------------------------------------+// Deltas only reach the chat they belong to++test('a tagged delta renders only in its own chat', () => {+ const delta = { type: 'TextDelta', data: 'hi', turn_id: 'u1', kwant_id: 'cto', context_id: 'thread-1', thread_id: 'thread-1' };+ assert.equal(t.shouldRenderDelta(delta, 'thread-1', null), true);+ // The specialist's direct chat is open while it works on the delegated thread: nothing leaks in.+ assert.equal(t.shouldRenderDelta(delta, 'cto', 'cto'), false);+ assert.equal(t.shouldRenderDelta(delta, 'general', 'thread-1'), false, 'the tag wins over the fallback');+ assert.equal(t.streamTarget(delta, 'cto'), 'thread-1');+});++test('untagged deltas (older servers, team discussions) go to the chat that started the stream', () => {+ const delta = { type: 'TextDelta', data: 'hi' };+ assert.equal(t.eventContextId(delta), null);+ assert.equal(t.shouldRenderDelta(delta, 'general', 'general'), true);+ assert.equal(t.shouldRenderDelta(delta, 'cto', 'general'), false);+ assert.equal(t.shouldRenderDelta(delta, 'cto', null), false);+ assert.equal(t.shouldRenderDelta(delta, '', ''), false, 'nothing open, nothing drawn');+});++test('lifecycle events carry their chat in data', () => {+ assert.equal(t.eventContextId({ type: 'turn_started', data: { context_id: 'c1' } }), 'c1');+ assert.equal(t.eventContextId({ type: 'TurnComplete', context_id: 'top', data: { context_id: 'inner' } }), 'top');+ assert.equal(t.eventContextId({ type: 'TextDelta', data: 'context_id' }), null, 'string data is not a tag');+ assert.equal(t.contextOf({ selectedId: 'cto', threadId: 'th' }), 'th');+ assert.equal(t.contextOf({ selectedId: 'cto', threadId: null }), 'cto');+});++// ---------------------------------------------------------------------------+// Turns and the queue++const ev = (type, data) => ({ type, data });++test('turns move queued -> running -> gone, and the queue counts down', () => {+ let m = t.hydrateTurns([{ turn_id: 'a', kwant_id: 'cto', context_id: 'th', thread_id: 'th', state: 'running', since: '1' }]);+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'b', kwant_id: 'cto', context_id: 'cto', position: 1, reason: 'agent_busy' }));+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'c', kwant_id: 'cto', context_id: 'cto', position: 2, reason: 'agent_busy' }));+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'd', kwant_id: 'ellis', context_id: 'ellis', position: 1, reason: 'agent_busy' }));+ assert.equal(t.queuePosition(m, 'b'), 1);+ assert.equal(t.queuePosition(m, 'c'), 2);+ assert.equal(t.queuePosition(m, 'd'), 1, 'another agent has its own line');+ assert.equal(t.queuePosition(m, 'a'), null, 'running turns have no position');++ m = t.applyTurnEvent(m, ev('turn_started', { turn_id: 'b', kwant_id: 'cto', context_id: 'cto' }));+ assert.equal(m.b.state, 'running');+ assert.equal(t.queuePosition(m, 'c'), 1, 'moves up when the one ahead starts');+ m = t.applyTurnEvent(m, ev('turn_ended', { turn_id: 'a', kwant_id: 'cto', context_id: 'th', outcome: 'completed' }));+ assert.equal(m.a, undefined);+ const same = t.applyTurnEvent(m, ev('turn_ended', { turn_id: 'zzz' }));+ assert.equal(same, m, 'unknown turns leave the map alone');+ assert.equal(t.applyTurnEvent(m, ev('TextDelta', 'x')), m);+});++test('server-wide queue counts every agent', () => {+ let m = t.hydrateTurns([]);+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'x', kwant_id: 'a', context_id: 'a', position: 1, reason: 'server_busy' }));+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'y', kwant_id: 'b', context_id: 'b', position: 2, reason: 'server_busy' }));+ assert.equal(t.queuePosition(m, 'y'), 2);+});++test('background turns are the agent’s work outside its direct chat', () => {+ const m = t.hydrateTurns([+ { turn_id: '1', kwant_id: 'cto', context_id: 'cto', thread_id: null, state: 'running', since: '1' },+ { turn_id: '2', kwant_id: 'cto', context_id: 'th', thread_id: 'th', state: 'running', since: '2' },+ { turn_id: '3', kwant_id: 'ellis', context_id: 'th2', thread_id: 'th2', state: 'running', since: '3' },+ ]);+ assert.deepEqual(t.backgroundTurns(m, 'cto').map((x) => x.turn_id), ['2']);+ assert.deepEqual(t.turnsIn(m, 'cto').map((x) => x.turn_id), ['1']);+});++// ---------------------------------------------------------------------------+// Thread list++const thread = (id, extra = {}) => ({+ id,+ kwant_id: 'cto',+ title: id,+ kind: 'chat',+ team_id: null,+ created_by: 'user',+ archived: false,+ created_at: '2026-10-01',+ updated_at: '2026-10-01',+ ...extra,+});+const delegation = (status) => ({ id: 'd1', thread_id: 'th', status, error: null });++test('thread badges: live turns first, then the delegation record', () => {+ const none = t.hydrateTurns([]);+ assert.equal(t.threadBadge(thread('th'), none), null, 'idle user threads have no badge');+ assert.deepEqual(t.threadBadge(thread('th', { delegation: delegation('completed') }), none), { kind: 'done', label: 'Done' });+ assert.equal(t.threadBadge(thread('th', { delegation: delegation('interrupted') }), none).kind, 'interrupted');+ assert.equal(t.threadBadge(thread('th', { delegation: delegation('cancelled') }), none).kind, 'cancelled');+ let m = t.applyTurnEvent(none, ev('turn_queued', { turn_id: 'q', kwant_id: 'cto', context_id: 'th', position: 3, reason: 'agent_busy' }));+ assert.deepEqual(t.threadBadge(thread('th', { delegation: delegation('queued') }), m), { kind: 'queued', label: 'Queued · #1' });+ m = t.applyTurnEvent(m, ev('turn_started', { turn_id: 'q', kwant_id: 'cto', context_id: 'th' }));+ assert.equal(t.threadBadge(thread('th', { delegation: delegation('completed') }), m).kind, 'working');+});++test('threads sort delegated first, newest first, archived hidden unless asked', () => {+ const list = [+ thread('old-chat', { updated_at: '2026-10-01' }),+ thread('new-chat', { updated_at: '2026-10-05' }),+ thread('task', { kind: 'delegation', updated_at: '2026-09-01' }),+ thread('gone', { archived: true, updated_at: '2026-10-09' }),+ ];+ assert.deepEqual(t.sortThreads(list).map((x) => x.id), ['task', 'new-chat', 'old-chat']);+ assert.deepEqual(t.sortThreads(list, true).map((x) => x.id), ['task', 'new-chat', 'old-chat', 'gone']);+});++test('thread updates keep the delegation the list route sent', () => {+ const d = delegation('running');+ const list = [thread('th', { delegation: d })];+ const next = t.upsertThread(list, thread('th', { title: 'Renamed' }));+ assert.equal(next[0].title, 'Renamed');+ assert.equal(next[0].delegation, d);+ assert.equal(t.upsertThread(list, thread('other')).length, 2);+ assert.equal(t.applyDelegation(list, { ...d, status: 'completed' })[0].delegation.status, 'completed');+ assert.equal(t.applyDelegation(list, { ...d, thread_id: 'unknown' }), list);+});++// ---------------------------------------------------------------------------+// Delegation notes++const metaJson = (extra = {}) =>+ JSON.stringify({+ kind: 'delegation_result',+ delegation_id: 'd1',+ thread_id: 'th',+ specialist_id: 'cto',+ specialist_name: 'CTO',+ lead_id: 'ellis',+ status: 'completed',+ title: 'Research vector DBs',+ ...extra,+ });++test('meta arrives as a JSON string and anything else is ignored safely', () => {+ const m = t.parseDelegationMeta(metaJson());+ assert.equal(m.kind, 'delegation_result');+ assert.equal(m.specialist_name, 'CTO');+ assert.equal(m.thread_id, 'th');+ assert.equal(t.parseDelegationMeta(JSON.parse(metaJson())).delegation_id, 'd1', 'objects work too');+ for (const bad of [null, undefined, '', ' ', '{not json', '"str"', '42', metaJson({ kind: 'routine' }), metaJson({ delegation_id: 5 })]) {+ assert.equal(t.parseDelegationMeta(bad), null, String(bad));+ }+ const sparse = t.parseDelegationMeta(JSON.stringify({ kind: 'delegation_started', delegation_id: 'd', thread_id: 't' }));+ assert.equal(sparse.specialist_name, 'The specialist');+ assert.equal(sparse.title, 'Delegated task');+});++test('status lines read as sentences', () => {+ assert.equal(t.delegationStatusLine('queued', 'CTO', { queuePos: 2 }), 'Waiting for CTO · #2 in line');+ assert.equal(t.delegationStatusLine('queued', 'CTO'), 'Waiting for CTO to start');+ assert.equal(t.delegationStatusLine('running', 'CTO'), 'CTO is working on it');+ assert.equal(t.delegationStatusLine('failed', 'CTO', { error: 'quota' }), "CTO couldn't finish: quota");+ assert.equal(t.delegationStatusLine('interrupted', 'CTO'), 'Interrupted by a restart');+});++test('messages are placed by thread, channel, then direct chat', () => {+ assert.equal(t.messageContextId({ thread_id: 'th', channel_id: 'c', direct_kwant_id: 'k' }), 'th');+ assert.equal(t.messageContextId({ channel_id: 'c', direct_kwant_id: 'k' }), 'c');+ assert.equal(t.messageContextId({ direct_kwant_id: 'k' }), 'k');+ assert.equal(t.messageContextId({}), null);+});++test('limit fields accept whole numbers in range only', () => {+ assert.equal(t.limitError('max_turns_per_agent', '4'), null);+ assert.equal(t.limitError('max_turns_per_agent', '0'), 'Use 1–16.');+ assert.equal(t.limitError('max_turns_global', '65'), 'Use 1–64.');+ assert.equal(t.limitError('delegation_follow_up_minutes', '0'), null);+ assert.equal(t.limitError('delegation_follow_up_minutes', '1441'), 'Use 0–1440.');+ for (const bad of ['', ' ', '2.5', '-1', 'abc', '1e2']) {+ assert.match(t.limitError('max_turns_per_agent', bad), /whole number/, bad);+ }+});++// ---------------------------------------------------------------------------+// The delegation card, rendered++// The card's imports touch browser storage (sound settings) when they load.+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };++const card = await (async () => {+ const root = fileURLToPath(new URL('..', import.meta.url));+ const out = await build({+ stdin: {+ contents: `+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { DelegationCard } from './src/components/DelegationCard';+ export const render = (props) => renderToStaticMarkup(React.createElement(DelegationCard, props));+ `,+ resolveDir: root,+ loader: 'tsx',+ },+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'node',+ jsx: 'automatic',+ logLevel: 'silent',+ define: { 'process.env.NODE_ENV': '"production"' },+ });+ return import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`);+})();++const props = (extra = {}) => ({+ meta: t.parseDelegationMeta(metaJson({ kind: 'delegation_started', status: 'queued' })),+ text: 'CTO is on it.',+ messageId: 'm1',+ onOpenThread: () => {},+ onCancel: async () => {},+ ...extra,+});++test('a running delegation card shows its status, the thread link and Stop', () => {+ const html = card.render(props({ live: { ...delegation('running'), id: 'd1' } }));+ assert.match(html, /Delegated to/);+ assert.match(html, /Research vector DBs/);+ assert.match(html, /role="status"[^>]*>.*CTO is working on it/s);+ assert.match(html, /Open CTO's thread|Open CTO's thread/);+ assert.match(html, /aria-label="Stop “Research vector DBs”"/);+ assert.match(html, /aria-labelledby="dlg-m1"/);+});++test('a queued card shows its place in line, not an error', () => {+ const html = card.render(props({ queuePos: 2 }));+ assert.match(html, /Waiting for CTO · #2 in line/);+ assert.doesNotMatch(html, /role="alert"/);+});++test('a result card shows the answer and no Stop', () => {+ const html = card.render(props({ meta: t.parseDelegationMeta(metaJson()), text: 'Use **pgvector**.' }));+ assert.match(html, /Result from/);+ assert.match(html, /CTO finished/);+ assert.match(html, /<strong[^>]*>pgvector<\/strong>/);+ assert.doesNotMatch(html, /Stop “/);+ assert.match(html, /Open CTO/);+});++test('the live record wins over the status frozen in meta', () => {+ const html = card.render(props({ live: { ...delegation('cancelled'), id: 'd1' } }));+ assert.match(html, />Stopped</);+ assert.doesNotMatch(html, /Stop “/);+});++test('long answers collapse behind a toggle', () => {+ const html = card.render(props({ meta: t.parseDelegationMeta(metaJson()), text: 'x '.repeat(1000) }));+ assert.match(html, /aria-expanded="false"[^>]*>Show the whole answer/);+});