Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

frontend: one-tap question cards for ask_user (batch 2 / C)

Pixel (kwant bot)f1ce30834fd2
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1b6971d3..e8ca1aad 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4,7 +4,8 @@ import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar
import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } from './components/ChatView';
import { ThreadBar, ThreadHeader } from './components/ThreadBar';
import { DelegationCard } from './components/DelegationCard';
-import { ListChecks, Loader2 } from 'lucide-react';
+import { QuestionCard } from './components/QuestionCard';
+import { HelpCircle, ListChecks, Loader2 } from 'lucide-react';
import { PendingApproval } from './components/ModernApprovalCard';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
@@ -46,6 +47,15 @@ import {
import type { PinnedItem } from './components/Instructions';
import type { EditTab } from './components/NewAgentModal';
import { Skill, applySkillEvent, pendingByKwant, skillsApi } from './skills';
+import {
+ Question,
+ QuestionMeta,
+ applyQuestion,
+ hydrateQuestions,
+ latestOpenQuestion,
+ questionsApi,
+ turnsAwaitingAnswer,
+} from './questions';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
// so both load right after start-up and opening them never waits.
@@ -135,6 +145,8 @@ export const App: React.FC = () => {
// Set each render once the select handlers exist; the SSE handler and notification clicks go through it.
// Opens an agent's settings on the Skills tab (set once the agents are known).
const openSkillsRef = useRef<(kwantId: string) => void>(() => undefined);
+ // Opens the chat of an agent's newest open question; false when it has none.
+ const openQuestionRef = useRef<(kwantId: string) => boolean>(() => false);
const openTargetRef = useRef<(t: { channel_id: string | null; kwant_id: string | null }) => boolean>(() => false);
const showNotification = (n: NotifyEvent) => {
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
@@ -147,7 +159,9 @@ export const App: React.FC = () => {
? undefined
: n.kind === 'skill_proposed'
? { label: 'Review', onClick: () => openSkillsRef.current(n.kwant_id) }
- : { label: 'Open', onClick: () => openTargetRef.current(target) };
+ : n.kind === 'question_asked'
+ ? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openTargetRef.current(target) }
+ : { 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;
@@ -158,7 +172,7 @@ export const App: React.FC = () => {
note.onclick = () => {
window.focus();
if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);
- else openTargetRef.current(target);
+ else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openTargetRef.current(target);
note.close();
};
} catch {
@@ -238,6 +252,14 @@ export const App: React.FC = () => {
/** Running turns after a (re)connect; chats whose reply ended meanwhile stop spinning. */
const hydrateFromServer = async () => {
skillsApi.list({ status: 'pending' }).then(setPendingSkills, () => undefined);
+ questionsApi.listOpen().then((list) => {
+ // Closed ones seen live stay; open ones come from the server.
+ setQuestions((prev) => {
+ const next = hydrateQuestions(list);
+ for (const q of Object.values(prev)) if (q.status !== 'open' && !next[q.id]) next[q.id] = q;
+ return next;
+ });
+ }, () => undefined);
try {
const { turns: list } = await threadsApi.turns();
const map = hydrateTurns(list);
@@ -268,6 +290,10 @@ export const App: React.FC = () => {
const [editingTab, setEditingTab] = useState<EditTab>('profile');
// Skills waiting for review, for the counts on the agent's header and Skills tab.
const [pendingSkills, setPendingSkills] = useState<Skill[]>([]);
+ // Agents' questions by id: open ones from the server, plus every question_updated since.
+ const [questions, setQuestions] = useState<Record<string, Question>>({});
+ const questionsRef = useRef(questions);
+ questionsRef.current = questions;
// Virtual Machine & Live Browser state
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
@@ -506,6 +532,12 @@ export const App: React.FC = () => {
setPendingSkills((prev) => applySkillEvent(prev, sk).filter((x) => x.status === 'pending'));
break;
}
+ case 'question_updated':
+ case 'QuestionUpdated': {
+ const q: Question | undefined = event.data?.question;
+ if (q?.id) setQuestions((prev) => applyQuestion(prev, q));
+ break;
+ }
case 'memory_changed':
case 'MemoryChanged':
emitContinuity({ type: 'memory_changed', data: event.data });
@@ -981,6 +1013,14 @@ export const App: React.FC = () => {
setEditingKwant(kwant);
playSfx('click');
};
+ openQuestionRef.current = (kwantId: string) => {
+ const q = latestOpenQuestion(questionsRef.current, kwantId);
+ if (!q) return false;
+ if (q.thread_id) openThread(q.kwant_id, q.thread_id);
+ else openTarget({ channel_id: q.channel_id, kwant_id: q.channel_id ? null : q.kwant_id });
+ if (q.message_id) setHighlightMessageId(q.message_id);
+ return true;
+ };
openSkillsRef.current = (kwantId: string) => {
const k = kwants.find((x) => x.id === kwantId);
if (k) openAgentSettings(k, 'skills');
@@ -1063,6 +1103,50 @@ export const App: React.FC = () => {
}
};
+ const handleAnswerQuestion = async (id: string, answer: { choice: number } | { text: string }): Promise<string | void> => {
+ try {
+ const { question } = await questionsApi.answer(id, answer);
+ setQuestions((prev) => applyQuestion(prev, question));
+ } catch (err) {
+ // Answered from another tab, dismissed, or its turn was stopped: show what happened.
+ try {
+ const { question } = await questionsApi.get(id);
+ setQuestions((prev) => applyQuestion(prev, question));
+ if (question.status === 'answered') return 'This was already answered.';
+ if (question.status === 'cancelled') return 'This question was closed.';
+ } catch {
+ // keep the first error
+ }
+ return `Couldn't send your answer: ${errText(err)}`;
+ }
+ };
+ const handleDismissQuestion = async (id: string): Promise<string | void> => {
+ try {
+ const q = await questionsApi.cancel(id);
+ setQuestions((prev) => applyQuestion(prev, q));
+ } catch (err) {
+ return `Couldn't skip it: ${errText(err)}`;
+ }
+ };
+ const renderQuestion = (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => {
+ const live = questions[meta.question_id];
+ const turnId = live?.turn_id;
+ const name = live ? kwantName(live.kwant_id) : undefined;
+ return (
+ <QuestionCard
+ meta={meta}
+ messageId={msg.id}
+ kwantName={name ?? (msg.sender_id && msg.sender_id.length <= 20 ? msg.sender_id : chatTitle)}
+ kwantId={live?.kwant_id}
+ live={live}
+ waiting={!!turnId && !!turns[turnId]}
+ onAnswer={handleAnswerQuestion}
+ onDismiss={handleDismissQuestion}
+ flash={flash}
+ />
+ );
+ };
+
const renderDelegation = (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => {
const queued = turnsIn(turns, meta.thread_id).find((t) => t.state === 'queued');
return (
@@ -1545,6 +1629,9 @@ export const App: React.FC = () => {
const isCurrentContextStreaming = openCtx in live;
const openTurns = turnsIn(turns, openCtx);
+ // Turns paused on a question wait for the person; they don't make the agent "busy".
+ const awaitingTurns = turnsAwaitingAnswer(questions);
+ const awaitingHere = openTurns.some((t) => t.state === 'running' && awaitingTurns.has(t.turn_id)) && !openTurns.some((t) => t.state === 'running' && !awaitingTurns.has(t.turn_id));
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' }
@@ -1570,9 +1657,13 @@ export const App: React.FC = () => {
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" />
+ {awaitingTurns.has(elsewhere[0].turn_id) ? (
+ <HelpCircle size={10} className="shrink-0 text-amber-300" aria-hidden="true" />
+ ) : (
+ <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 '}
+ {elsewhere[0].state === 'queued' ? 'Waiting to work on ' : awaitingTurns.has(elsewhere[0].turn_id) ? 'Asked you a question in ' : '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>}
@@ -1595,7 +1686,7 @@ export const App: React.FC = () => {
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)}`;
+ busyKwants[t.kwant_id] = `${t.state === 'queued' ? 'Waiting to work on' : awaitingTurns.has(t.turn_id) ? 'Asked you a question in' : 'Working on'} ${describeContext(t.context_id, t.kwant_id)}`;
}
const errorBar = messagesError ? (
@@ -1768,6 +1859,8 @@ export const App: React.FC = () => {
}
queued={queuedHere}
renderDelegation={renderDelegation}
+ renderQuestion={renderQuestion}
+ awaitingAnswer={awaitingHere}
contextKey={openCtx}
/>
</div>
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 7961970f..129a288e 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -10,6 +10,7 @@ import { playSfx } from '../audio/chiptune';
import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThreads';
import { PinnedInstructions, PinnedItem } from './Instructions';
import { DelegationMeta, parseDelegationMeta } from '../threads';
+import { QuestionMeta, parseQuestionMeta } from '../questions';
export interface ChatMessage {
id: string;
@@ -116,6 +117,10 @@ export interface ChatViewProps {
queued?: QueuedState | null;
/** Draws a delegation note or result (messages with delegation `meta`). */
renderDelegation?: (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => React.ReactNode;
+ /** Draws an agent's question card (messages with `ask_user` meta). */
+ renderQuestion?: (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => React.ReactNode;
+ /** The open chat's turn is paused on a question: it is waiting for the person, not working. */
+ awaitingAnswer?: boolean;
/** Changes when another chat opens, so the view jumps to its bottom. */
contextKey?: string;
}
@@ -250,6 +255,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
titleExtra,
queued,
renderDelegation,
+ renderQuestion,
+ awaitingAnswer,
contextKey,
}) => {
const [internalIsVmPaneOpen, setInternalIsVmPaneOpen] = useState(false);
@@ -489,6 +496,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 question = msg.meta && renderQuestion ? parseQuestionMeta(msg.meta) : null;
+ if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, 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);
@@ -827,6 +836,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
<span className="w-1.5 h-1.5 rounded-full bg-amber-300" aria-hidden="true" />
Queued
</span>
+ ) : awaitingAnswer ? (
+ <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" />
+ Waiting for your answer
+ </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" />
@@ -852,6 +866,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
</p>
) : streamingText ? (
<MarkdownRenderer content={stripDiscussionMarkers(streamingText)} isStreaming={true} />
+ ) : awaitingAnswer ? (
+ <p className="text-zinc-400" role="status">
+ Paused on the question above. Answer it there; this reply carries on from it.
+ </p>
) : (
<span className="inline-flex gap-1 py-1.5" aria-label="Waiting for the first words">
{[0, 1, 2].map((i) => (
diff --git a/frontend/src/components/QuestionCard.tsx b/frontend/src/components/QuestionCard.tsx
new file mode 100644
index 00000000..92041861
--- /dev/null
+++ b/frontend/src/components/QuestionCard.tsx
@@ -0,0 +1,222 @@
+import React, { useRef, useState } from 'react';
+import { ArrowUp, Check, CheckCircle2, Clock, HelpCircle, Loader2, MinusCircle } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { ANSWER_MAX, Question, QuestionMeta, answerTextError, questionView } from '../questions';
+
+export interface QuestionCardProps {
+ meta: QuestionMeta;
+ messageId: string;
+ kwantName: string;
+ kwantId?: string;
+ /** Live record from `question_updated`, when known; wins over `meta`. */
+ live?: Question | null;
+ /** A turn is paused on this question right now (else an answer starts a new reply). */
+ waiting: boolean;
+ /** Resolves to an error message on failure. */
+ onAnswer: (questionId: string, answer: { choice: number } | { text: string }) => Promise<string | void>;
+ onDismiss: (questionId: string) => Promise<string | void>;
+ flash?: boolean;
+}
+
+/**
+ * An agent's question in the chat: 2–5 one-tap choices plus a typed answer. Closed (answered or
+ * dismissed) cards keep the answer and disable everything. Choices are a group: arrow keys move.
+ */
+export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwantName, kwantId, live, waiting, onAnswer, onDismiss, flash }) => {
+ const view = questionView(meta, live);
+ const [text, setText] = useState('');
+ const [busy, setBusy] = useState<number | 'text' | 'dismiss' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // Shown right away; the server's question_updated confirms it.
+ const [sent, setSent] = useState<string | null>(null);
+ const choiceRefs = useRef<Array<HTMLButtonElement | null>>([]);
+
+ const open = view.status === 'open' && sent === null;
+ const answer = view.answer ?? sent;
+ const headingId = `q-${messageId}`;
+
+ const submit = async (a: { choice: number } | { text: string }) => {
+ if (!open || busy !== null) return;
+ if ('text' in a) {
+ const problem = answerTextError(a.text);
+ if (problem) {
+ setError(problem);
+ return;
+ }
+ }
+ setBusy('choice' in a ? a.choice : 'text');
+ setError(null);
+ const err = await onAnswer(meta.question_id, 'text' in a ? { text: a.text.trim() } : a);
+ setBusy(null);
+ if (err) setError(err);
+ else {
+ setSent('text' in a ? a.text.trim() : view.choices[a.choice]);
+ setText('');
+ }
+ };
+
+ const dismiss = async () => {
+ if (!open || busy !== null) return;
+ setBusy('dismiss');
+ setError(null);
+ const err = await onDismiss(meta.question_id);
+ setBusy(null);
+ if (err) setError(err);
+ };
+
+ const onChoiceKey = (e: React.KeyboardEvent, i: number) => {
+ const n = view.choices.length;
+ const to = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? (i + 1) % n : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? (i - 1 + n) % n : e.key === 'Home' ? 0 : e.key === 'End' ? n - 1 : -1;
+ if (to < 0) return;
+ e.preventDefault();
+ choiceRefs.current[to]?.focus();
+ };
+
+ const status =
+ view.status === 'cancelled' ? (
+ <span className="inline-flex items-center gap-1.5 text-zinc-400">
+ <MinusCircle size={13} aria-hidden="true" /> Dismissed: {kwantName} was told you skipped it
+ </span>
+ ) : !open ? (
+ <span className="inline-flex items-center gap-1.5 text-emerald-300">
+ <CheckCircle2 size={13} aria-hidden="true" /> Answered{view.status === 'open' ? ', sending…' : ''}
+ </span>
+ ) : waiting ? (
+ <span className="inline-flex items-center gap-1.5 text-amber-300">
+ <Clock size={13} aria-hidden="true" /> {kwantName} is waiting for your answer. You can keep chatting meanwhile.
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1.5 text-zinc-400">
+ <Clock size={13} aria-hidden="true" /> {kwantName} stopped waiting. Answer any time to pick it up in a new reply.
+ </span>
+ );
+
+ 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' : ''}`}
+ >
+ <ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} />
+ <div
+ className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${
+ open ? 'border-amber-500/35' : 'border-zinc-800'
+ }`}
+ >
+ <div className="px-4 pt-3 pb-2 space-y-1">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
+ <HelpCircle size={12} className="text-amber-300" aria-hidden="true" />
+ <span className="text-zinc-200">{kwantName}</span> asks
+ </span>
+ <h3 id={headingId} className="text-sm font-semibold text-zinc-100 whitespace-pre-wrap break-words leading-snug">
+ {view.question}
+ </h3>
+ </div>
+
+ <div role="group" aria-label="Choices" className="px-4 pb-2 flex flex-col sm:flex-row sm:flex-wrap gap-2">
+ {view.choices.map((c, i) => {
+ const chosen = !open && answer === c;
+ return (
+ <button
+ key={i}
+ ref={(el) => (choiceRefs.current[i] = el)}
+ type="button"
+ disabled={!open || busy !== null}
+ aria-pressed={chosen}
+ onClick={() => submit({ choice: i })}
+ onKeyDown={(e) => onChoiceKey(e, i)}
+ className={`inline-flex items-center justify-center sm:justify-start gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-sm text-left border transition-colors break-words focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400 ${
+ chosen
+ ? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-100'
+ : open
+ ? 'bg-zinc-800/80 border-zinc-700 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600 active:scale-[0.98] disabled:opacity-60'
+ : 'bg-zinc-900 border-zinc-800 text-zinc-500'
+ }`}
+ >
+ {busy === i ? (
+ <Loader2 size={13} className="shrink-0 animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : chosen ? (
+ <Check size={13} className="shrink-0" aria-hidden="true" />
+ ) : null}
+ <span className="min-w-0">{c}</span>
+ </button>
+ );
+ })}
+ </div>
+
+ {open ? (
+ <form
+ className="px-4 pb-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ submit({ text });
+ }}
+ >
+ <label htmlFor={`${headingId}-text`} className="sr-only">
+ Or type your own answer
+ </label>
+ <div className="flex items-end gap-2 rounded-xl bg-zinc-950 border border-zinc-800 focus-within:border-amber-500/50 p-1.5">
+ <textarea
+ id={`${headingId}-text`}
+ rows={1}
+ value={text}
+ maxLength={ANSWER_MAX}
+ disabled={busy !== null}
+ onChange={(e) => {
+ setText(e.target.value);
+ e.target.style.height = 'auto';
+ e.target.style.height = `${Math.min(e.target.scrollHeight, 120)}px`;
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ submit({ text });
+ }
+ }}
+ placeholder="Or type your own answer…"
+ className="flex-1 bg-transparent px-2 py-1 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none leading-relaxed"
+ />
+ <button
+ type="submit"
+ disabled={!text.trim() || busy !== null}
+ aria-label="Send answer"
+ className="w-7 h-7 shrink-0 rounded-lg flex items-center justify-center bg-amber-500 text-zinc-950 hover:bg-amber-400 disabled:bg-zinc-800 disabled:text-zinc-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"
+ >
+ {busy === 'text' ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ArrowUp size={14} strokeWidth={2.4} aria-hidden="true" />}
+ </button>
+ </div>
+ </form>
+ ) : (
+ answer &&
+ !view.choices.includes(answer) && (
+ <p className="mx-4 mb-2 px-3 py-2 rounded-xl bg-zinc-800/70 border border-zinc-700/60 text-sm text-zinc-100 whitespace-pre-wrap break-words">
+ <span className="sr-only">Your answer: </span>
+ {answer}
+ </p>
+ )
+ )}
+
+ <div className="px-4 pb-3 pt-0.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">
+ <p role="status" aria-live="polite" className="min-w-0">
+ {status}
+ </p>
+ {open && (
+ <button
+ type="button"
+ onClick={dismiss}
+ disabled={busy !== null}
+ className="ml-auto text-zinc-500 hover:text-zinc-300 underline-offset-2 hover:underline disabled:opacity-50 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-zinc-500"
+ >
+ {busy === 'dismiss' ? 'Skipping…' : 'Skip question'}
+ </button>
+ )}
+ {error && (
+ <span role="alert" className="basis-full text-rose-300">
+ {error}
+ </span>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/questions.ts b/frontend/src/questions.ts
new file mode 100644
index 00000000..939e422c
--- /dev/null
+++ b/frontend/src/questions.ts
@@ -0,0 +1,123 @@
+// Ask-user: an agent's one-tap question in a chat (batch 2 / C).
+import { request } from './threads';
+
+export type QuestionStatus = 'open' | 'answered' | 'cancelled';
+
+export interface Question {
+ id: string;
+ kwant_id: string;
+ channel_id: string | null;
+ direct_kwant_id: string | null;
+ thread_id: string | null;
+ /** The turn that asked; it may have ended since (then an answer starts a new turn). */
+ turn_id: string | null;
+ question: string;
+ choices: string[];
+ status: QuestionStatus;
+ answer: string | null;
+ message_id: string | null;
+ created_at: string;
+ answered_at: string | null;
+}
+
+/** `meta` of the card message. */
+export interface QuestionMeta {
+ kind: 'ask_user';
+ question_id: string;
+ question: string;
+ choices: string[];
+ status: QuestionStatus;
+ answer: string | null;
+}
+
+export const ANSWER_MAX = 2000;
+
+/** Message `meta` comes as a JSON string (or, from some paths, already parsed). */
+export function parseMetaObject(raw: unknown): Record<string, unknown> | null {
+ if (!raw) return null;
+ if (typeof raw === 'object') return raw as Record<string, unknown>;
+ if (typeof raw !== 'string') return null;
+ try {
+ const v = JSON.parse(raw);
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+export function parseQuestionMeta(raw: unknown): QuestionMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'ask_user' || typeof m.question_id !== 'string' || typeof m.question !== 'string') return null;
+ const choices = Array.isArray(m.choices) ? m.choices.filter((c): c is string => typeof c === 'string') : [];
+ const status: QuestionStatus = m.status === 'answered' || m.status === 'cancelled' ? m.status : 'open';
+ return { kind: 'ask_user', question_id: m.question_id, question: m.question, choices, status, answer: typeof m.answer === 'string' ? m.answer : null };
+}
+
+/** The chat a question lives in: the thread, else the channel, else the agent's direct chat. */
+export const questionContextId = (q: Pick<Question, 'thread_id' | 'channel_id' | 'direct_kwant_id'>) =>
+ q.thread_id || q.channel_id || q.direct_kwant_id || null;
+
+/** Card state: the live record from `question_updated` wins over the (possibly stale) message meta. */
+export function questionView(meta: QuestionMeta, live?: Question | null): QuestionMeta {
+ if (!live || live.id !== meta.question_id) return meta;
+ return { ...meta, status: live.status, answer: live.answer, choices: live.choices.length ? live.choices : meta.choices };
+}
+
+/** Keeps the latest known record per question. */
+export function applyQuestion(map: Record<string, Question>, q: Question): Record<string, Question> {
+ const prev = map[q.id];
+ if (prev && prev.status === q.status && prev.answer === q.answer) return map;
+ // A closed question never reopens (a late, out-of-order "open" event loses).
+ if (prev && prev.status !== 'open' && q.status === 'open') return map;
+ return { ...map, [q.id]: q };
+}
+
+export function hydrateQuestions(list: Question[]): Record<string, Question> {
+ const out: Record<string, Question> = {};
+ for (const q of list) out[q.id] = q;
+ return out;
+}
+
+/** Open questions per chat, newest last. */
+export function openQuestionsByContext(map: Record<string, Question>): Record<string, Question[]> {
+ const out: Record<string, Question[]> = {};
+ const open = Object.values(map)
+ .filter((q) => q.status === 'open')
+ .sort((a, b) => a.created_at.localeCompare(b.created_at));
+ for (const q of open) {
+ const ctx = questionContextId(q);
+ if (ctx) (out[ctx] ??= []).push(q);
+ }
+ return out;
+}
+
+/** The newest open question an agent asked, e.g. to open from a notification. */
+export function latestOpenQuestion(map: Record<string, Question>, kwantId: string): Question | null {
+ let best: Question | null = null;
+ for (const q of Object.values(map)) if (q.kwant_id === kwantId && q.status === 'open' && (!best || q.created_at > best.created_at)) best = q;
+ return best;
+}
+
+/** Turn ids that are paused on a question (not working, just waiting for the person). */
+export function turnsAwaitingAnswer(map: Record<string, Question>): Set<string> {
+ const out = new Set<string>();
+ for (const q of Object.values(map)) if (q.status === 'open' && q.turn_id) out.add(q.turn_id);
+ return out;
+}
+
+/** Problem with a typed answer, or null. */
+export function answerTextError(text: string): string | null {
+ if (!text.trim()) return 'Type an answer or tap a choice.';
+ if (text.length > ANSWER_MAX) return `Answers are at most ${ANSWER_MAX} characters.`;
+ return null;
+}
+
+const enc = encodeURIComponent;
+
+export const questionsApi = {
+ listOpen: () => request<Question[]>('GET', '/api/questions?status=open'),
+ get: (id: string) => request<{ question: Question; waiting: boolean }>('GET', `/api/questions/${enc(id)}`),
+ answer: (id: string, a: { choice: number } | { text: string }) =>
+ request<{ question: Question; resumed: 'turn' | 'new_turn' }>('POST', `/api/questions/${enc(id)}/answer`, a),
+ cancel: (id: string) => request<Question>('POST', `/api/questions/${enc(id)}/cancel`),
+};
diff --git a/frontend/tests/questions.test.mjs b/frontend/tests/questions.test.mjs
new file mode 100644
index 00000000..06f8bb9e
--- /dev/null
+++ b/frontend/tests/questions.test.mjs
@@ -0,0 +1,100 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const q = await loadBundled(`export * from './src/questions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { QuestionCard } from './src/components/QuestionCard';
+ export const render = (props) => renderToStaticMarkup(React.createElement(QuestionCard, props));
+`);
+
+const metaJson = (over = {}) =>
+ JSON.stringify({ kind: 'ask_user', question_id: 'q1', question: 'Which region?', choices: ['EU', 'US'], status: 'open', answer: null, ...over });
+const rec = (over = {}) => ({
+ id: 'q1', kwant_id: 'cto', channel_id: null, direct_kwant_id: null, thread_id: 'th1', turn_id: 't1',
+ question: 'Which region?', choices: ['EU', 'US'], status: 'open', answer: null, message_id: 'm1',
+ created_at: '2026-10-17T10:00:00Z', answered_at: null, ...over,
+});
+
+test('card meta parses from a string or object and ignores other kinds', () => {
+ const m = q.parseQuestionMeta(metaJson());
+ assert.deepEqual(m.choices, ['EU', 'US']);
+ assert.equal(m.status, 'open');
+ assert.equal(q.parseQuestionMeta({ kind: 'ask_user', question_id: 'x', question: 'y', choices: ['a', 1, 'b'], status: 'weird' }).status, 'open');
+ assert.deepEqual(q.parseQuestionMeta({ kind: 'ask_user', question_id: 'x', question: 'y', choices: ['a', 1, 'b'] }).choices, ['a', 'b']);
+ assert.equal(q.parseQuestionMeta('{"kind":"delegation_started"}'), null);
+ assert.equal(q.parseQuestionMeta('not json'), null);
+ assert.equal(q.parseQuestionMeta(null), null);
+});
+
+test('the live record wins over stale meta', () => {
+ const m = q.parseQuestionMeta(metaJson());
+ assert.equal(q.questionView(m, rec({ status: 'answered', answer: 'EU' })).answer, 'EU');
+ assert.equal(q.questionView(m, rec({ id: 'other', status: 'cancelled' })).status, 'open', 'another question’s record is ignored');
+ assert.equal(q.questionView(m, null), m);
+});
+
+test('question_updated: newest state, closed never reopens', () => {
+ let map = q.hydrateQuestions([rec()]);
+ const same = q.applyQuestion(map, rec());
+ assert.equal(same, map);
+ map = q.applyQuestion(map, rec({ status: 'answered', answer: 'US' }));
+ assert.equal(map.q1.status, 'answered');
+ assert.equal(q.applyQuestion(map, rec()), map, 'a late open event loses');
+});
+
+test('contexts, waiting turns and the newest question per agent', () => {
+ const map = q.hydrateQuestions([
+ rec(),
+ rec({ id: 'q2', thread_id: null, direct_kwant_id: 'cto', turn_id: null, created_at: '2026-10-17T11:00:00Z' }),
+ rec({ id: 'q3', thread_id: null, channel_id: 'general', turn_id: 't3', status: 'answered' }),
+ ]);
+ assert.equal(q.questionContextId(map.q1), 'th1');
+ assert.equal(q.questionContextId(map.q2), 'cto');
+ assert.deepEqual(Object.keys(q.openQuestionsByContext(map)).sort(), ['cto', 'th1']);
+ assert.deepEqual([...q.turnsAwaitingAnswer(map)], ['t1'], 'only open questions with a live turn');
+ assert.equal(q.latestOpenQuestion(map, 'cto').id, 'q2');
+ assert.equal(q.latestOpenQuestion(map, 'nobody'), null);
+});
+
+test('typed answers are checked before sending', () => {
+ assert.match(q.answerTextError(' '), /Type an answer/);
+ assert.match(q.answerTextError('x'.repeat(2001)), /2000/);
+ assert.equal(q.answerTextError('EU please'), null);
+});
+
+const props = (over = {}) => ({
+ meta: q.parseQuestionMeta(metaJson()), messageId: 'm1', kwantName: 'CTO', waiting: true,
+ onAnswer: async () => {}, onDismiss: async () => {}, ...over,
+});
+
+test('an open card offers the choices, a typed answer and skip; the agent is waiting, not busy', () => {
+ const html = ui.render(props());
+ assert.match(html, /Which region\?/);
+ assert.equal((html.match(/aria-pressed="false"/g) || []).length, 2);
+ assert.doesNotMatch(html, /<button[^>]*disabled=""[^>]*aria-pressed/);
+ assert.match(html, /Or type your own answer/);
+ assert.match(html, /Skip question/);
+ assert.match(html, /CTO is waiting for your answer\. You can keep chatting meanwhile\./);
+ assert.doesNotMatch(html, /busy|elsewhere/i);
+});
+
+test('after the wait ran out the card stays answerable', () => {
+ const html = ui.render(props({ waiting: false }));
+ assert.match(html, /stopped waiting\. Answer any time/);
+ assert.match(html, /Send answer/);
+});
+
+test('answered and dismissed cards are closed', () => {
+ const answered = ui.render(props({ live: rec({ status: 'answered', answer: 'US' }) }));
+ assert.match(answered, /aria-pressed="true"/);
+ assert.match(answered, /Answered/);
+ assert.doesNotMatch(answered, /Send answer|Skip question/);
+ const typed = ui.render(props({ live: rec({ status: 'answered', answer: 'Both, EU first' }) }));
+ assert.match(typed, /Both, EU first/, 'a typed answer is shown');
+ const dismissed = ui.render(props({ meta: q.parseQuestionMeta(metaJson({ status: 'cancelled' })) }));
+ assert.match(dismissed, /Dismissed/);
+ assert.equal((dismissed.match(/disabled=""/g) || []).length, 2, 'every choice disabled');
+});