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.

0.9.7: a chat waiting only on your answer says so (UX audit #2) (#567)

Oleksandr Ivanchenkoe0c27c9567d2
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 92335b82..524ddd96 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -27,6 +27,8 @@ import { StarAsk } from './components/StarAsk';
import { starAskStore } from './starAsk';
import { LiveActivity, appendThinking, applyActivity, parseStep, seedActivity } from './activity';
import { liveNamingOrder, namesToFill } from './workingStrip';
+import { doneLines } from './waitingState';
+import { botOf } from './sharedFiles';
import {
HumanStep,
HumanStepMeta,
@@ -3480,6 +3482,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const awaitingTurns = new Set([...turnsAwaitingAnswer(questions), ...browserTurns]);
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 awaitingBrowserHere = awaitingHere && openTurns.some((t) => t.state === 'running' && browserTurns.has(t.turn_id));
+ // The bot whose question the chat waits on, for the waiting banner (UX audit #2).
+ const awaitingTurnHere = awaitingHere ? openTurns.find((t) => t.state === 'running' && awaitingTurns.has(t.turn_id)) : undefined;
+ const awaitingBotHere = awaitingTurnHere ? { id: awaitingTurnHere.kwant_id, name: kwants.find((k) => k.id === awaitingTurnHere.kwant_id)?.name ?? '' } : null;
// The open chat's running turn's live steps (the newest, when several reply at once).
const activityHere = Object.values(activity).filter((a) => a.ctx === openCtx && turns[a.turnId]).pop() ?? null;
const needsYouByKwant = openStepsByKwant(humanSteps);
@@ -3616,6 +3621,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Sidebar: what busy bots are doing, "here" for the open chat.
const busyKwants = busyLines({ turns: Object.values(turns), openCtx, awaiting: awaitingTurns, browser: browserTurns, describe: describeContext });
+ // A team turn waiting on one bot's question: its teammates that already replied read "Done" (UX audit #2).
+ const doneKwants = doneLines(messages, awaitingBotHere, isChannel, (id) => botOf(id, kwants));
const botStatus = botStatuses({ turns: Object.values(turns), awaiting: awaitingTurns, needsYou: needsYouByKwant });
// Avatar moods and the background-tab signal come from the same state as the sidebar's dots.
@@ -3903,6 +3910,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
isChannel={isChannel}
selectedTeamId={selectedTeamId}
busyKwants={busyKwants}
+ doneKwants={doneKwants}
browsingOwners={globes.owners}
browsingBots={globes.bots}
browserNeedsYou={browserNeedsYou}
@@ -4243,6 +4251,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onSendToOtherBot={openThreadId ? undefined : handleSendToOtherBot}
awaitingAnswer={awaitingHere}
awaitingBrowser={awaitingBrowserHere}
+ awaitingBot={awaitingBotHere}
liveActivity={isCurrentContextStreaming ? activityHere : null}
renderHumanStep={renderHumanStep}
contextKey={openCtx}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 4cddab01..6f4d1f52 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -3,6 +3,8 @@ import { parseWatchMeta, type WatchMeta } from '../missionWatch';
import { flushSync } from 'react-dom';
import { queuedText } from '../claudeVm';
import { QueuedBeside } from './QueuedBeside';
+import { WaitingBanner } from './WaitingBanner';
+import { answerPlaceholder, isTeamTurn, onlyAskOpen, turnRail, waitingStopLabel } from '../waitingState';
import type { SwitchEntry } from '../watchLive';
import { emptyTrialReplyLine, trialCardsAfter, trialOf } from '../showOnce';
import { parsePick } from '../engines';
@@ -19,7 +21,7 @@ import { moodNoticed } from '../kwantMood';
import { NewTag } from './NewTag';
import { PHONE_QUERY, TOUCH_QUERY } from '../layout';
import { useMedia } from '../useMedia';
-import { composerStacked, keyboardMode, measureText16, phonePlaceholder } from '../composer';
+import { composerStacked, fitPlaceholder, keyboardMode, measureText16, phonePlaceholder } from '../composer';
import { markNewSeen } from '../whatsNew';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
@@ -344,6 +346,8 @@ export interface ChatViewProps {
awaitingAnswer?: boolean;
/** …and the pause is a browser step (sign-in, CAPTCHA) rather than a question. */
awaitingBrowser?: boolean;
+ /** The bot whose question the open chat's turn waits on (its id and name), for the waiting banner. */
+ awaitingBot?: { id: string; name: string } | null;
/** The running reply's steps so far (thinking, tools, waits). */
liveActivity?: LiveActivity | null;
/** Draws a bot's browser-step card (message meta kind "human_step"). */
@@ -557,6 +561,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
canRun = null,
awaitingAnswer,
awaitingBrowser,
+ awaitingBot,
liveActivity,
renderHumanStep,
contextKey,
@@ -792,7 +797,22 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (!card) return;
const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
card.scrollIntoView({ block: 'nearest', behavior: reduce ? 'auto' : 'smooth' });
+ // Keyboard users land on the card: its first choice, else its answer field (the amber ring shows where).
+ const target = card.querySelector<HTMLElement>('button[aria-pressed]') ?? card.querySelector<HTMLElement>('textarea');
+ target?.focus({ preventScroll: true });
};
+ // Waiting state (UX audit #2): the only open thing is a question, so the chat waits for the person.
+ const askOnly = onlyAskOpen({
+ streaming: isStreaming,
+ awaitingAnswer: !!awaitingAnswer,
+ awaitingBrowser: !!awaitingBrowser,
+ approvalOpen: pendingApprovals.length > 0,
+ queued: !!queued,
+ writing: !!streamingText,
+ });
+ // Team words ("Stop team", the rail) only for a team turn; a single bot asking in a channel gets "Stop".
+ const teamChat = isTeamTurn(home?.kind, !!discussionState?.inProgress);
+ const askRail = askOnly && teamChat ? turnRail(messages, awaitingBot?.id, (id) => botOf(id, knownBots)) : [];
const showApproval = () => {
const cards = scrollRef.current?.querySelectorAll<HTMLElement>('[data-approval-card]');
const card = cards?.[cards.length - 1];
@@ -805,7 +825,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
const { byBot: budgetsByBot } = useBudgets();
const chatBudget = budgetBotId ? budgetsByBot[budgetBotId] : undefined;
const budgetBanner = chatBudget?.state === 'paused' ? <BudgetPausedBanner budget={chatBudget} onRaise={onRaiseBudget} /> : null;
- const workingStrip = (
+ // Waiting state: the banner says whose move it is, so no strip and no running clock.
+ const workingStrip = askOnly ? null : (
<WorkingStrip
active={isStreaming}
name={discussionState?.inProgress && discussionState.currentSpeaker ? discussionState.currentSpeaker : streamingSpeakerName || title}
@@ -885,7 +906,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
return;
}
if (!messages.some((m) => m.id === highlightMessageId)) return;
- const thread = groupDiscussionThreads(messages).find(
+ const thread = groupDiscussionThreads(messages, { foldOpen: askOnly }).find(
(item) => item.kind === 'thread' && item.turns.some((t) => t.id === highlightMessageId),
);
if (thread && thread.kind === 'thread' && !openThoughts[`thread:${thread.id}`]) {
@@ -942,7 +963,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
useEffect(() => {
if (!quoteJump) return;
- const thread = groupDiscussionThreads(messages).find((item) => item.kind === 'thread' && item.turns.some((t) => t.id === quoteJump.id));
+ const thread = groupDiscussionThreads(messages, { foldOpen: askOnly }).find((item) => item.kind === 'thread' && item.turns.some((t) => t.id === quoteJump.id));
if (thread && thread.kind === 'thread' && !openThoughts[`thread:${thread.id}`]) {
setOpenThoughts((prev) => ({ ...prev, [`thread:${thread.id}`]: true }));
return;
@@ -1114,7 +1135,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
});
return;
}
- if (!canSend || (isStreaming && discussionState?.inProgress)) return;
+ // While the only open thing is a question, a typed message answers it (the server closes the question).
+ if (!canSend || (isStreaming && discussionState?.inProgress && !askOnly)) return;
playSfx('click');
stickRef.current = true;
const replying = replyTo;
@@ -1865,7 +1887,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
// obvious (channels and team chats, or a direct chat with an @mention typed).
const showAnswers = !ideaMode && (!phone || home?.kind !== 'bot' || target.kind === 'mention');
const showHintText = !(phone && touch);
- const placeholder = phone
+ const measure16 = (t: string) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : '');
+ const placeholder = askOnly
+ ? phone
+ ? fitPlaceholder(answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title), 'Your answer…', fieldWidth, measure16)
+ : answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title)
+ : phone
? phonePlaceholder(title, fieldWidth, (t) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : ''))
: spaceName && !narrow
? `Message ${title} in ${spaceName}`
@@ -2029,8 +2056,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
<PinnedInstructions items={pinned} onEdit={onEditInstructions} />
</div>
+ {/* Waiting for the person: replaces the discussion banner while the only open thing is a question */}
+ {askOnly && (
+ <WaitingBanner
+ lines={[{ kind: 'answer', bot: awaitingBot?.name || streamingSpeakerName || title }]}
+ rail={askRail}
+ stopLabel={waitingStopLabel(teamChat)}
+ onStop={onCancelDiscussion}
+ onShow={() => showWaitingCard('question')}
+ />
+ )}
{/* Discussion In-Flight Banner */}
- {discussionState?.inProgress && (
+ {discussionState?.inProgress && !askOnly && (
<div className="px-3 sm:px-6 pt-3 select-none flex-shrink-0">
<div className="flex items-center justify-between gap-2 px-3 sm:px-4 py-2 bg-sky-950/40 border border-sky-800/40 rounded-xl mb-3 text-xs">
<div className="flex items-center gap-2 text-sky-200 min-w-0">
@@ -2106,7 +2143,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
<AccountCard onOpenAccounts={onOpenAccounts} />
</div>
)}
- {groupDiscussionThreads(arranged.messages).map((item, n, items) => {
+ {groupDiscussionThreads(arranged.messages, { foldOpen: askOnly }).map((item, n, items) => {
if (item.kind === 'message') {
const trial = trialCards.get(item.message.id);
const above = items[n - 1];
@@ -2166,7 +2203,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
{/* Live Streaming Assistant Message (or its place in the queue, in the same frame) */}
- {isStreaming && !deciding && routingState?.phase !== 'deciding' && (
+ {isStreaming && !deciding && routingState?.phase !== 'deciding' && !askOnly && (
<div className="flex items-start gap-3.5 w-full max-w-5xl">
<ModernAvatar
role={
@@ -2585,7 +2622,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
/>
)}
- {isStreaming && (
+ {isStreaming && !askOnly && (
<button
type="button"
onClick={onCancelDiscussion}
@@ -2621,10 +2658,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
>
<JarIcon size={phone ? 18 : 17} />
</button>
- ) : !(isStreaming && (discussionState?.inProgress || !canSend)) && (
+ ) : (askOnly || !(isStreaming && (discussionState?.inProgress || !canSend))) && (
<button
type="submit"
- aria-label={stillUploading ? 'Send (waiting for uploads)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}
+ aria-label={stillUploading ? 'Send (waiting for uploads)' : askOnly ? 'Send (answers the question)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}
title={stillUploading ? 'Waiting for uploads to finish' : undefined}
disabled={!canSend}
data-send-ready={canSend ? 'true' : 'false'}
diff --git a/frontend/src/components/QuestionCard.tsx b/frontend/src/components/QuestionCard.tsx
index 33e2fb08..7d158019 100644
--- a/frontend/src/components/QuestionCard.tsx
+++ b/frontend/src/components/QuestionCard.tsx
@@ -1,9 +1,10 @@
-import React, { useRef, useState } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import { ArrowUp, Check, CheckCircle2, Clock, HelpCircle, Loader2, MinusCircle } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ViaTelegram } from './TelegramMarks';
import { ANSWER_MAX, Question, QuestionMeta, answerTextError, questionView } from '../questions';
import { whyYouText } from '../decideFirst';
+import { askedAgo } from '../waitingState';
export interface QuestionCardProps {
meta: QuestionMeta;
@@ -34,6 +35,14 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwa
const choiceRefs = useRef<Array<HTMLButtonElement | null>>([]);
const open = view.status === 'open' && sent === null;
+ // "asked N min ago" on an open card: a quiet minute tick, no running timer (UX audit #2).
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!open || !live?.created_at) return;
+ const id = window.setInterval(() => setNow(Date.now()), 60_000);
+ return () => window.clearInterval(id);
+ }, [open, live?.created_at]);
+ const ago = open ? askedAgo(live?.created_at, now) : null;
const answer = view.answer ?? sent;
const headingId = `q-${messageId}`;
const whyYou = whyYouText(view.why_you);
@@ -95,7 +104,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwa
) : waiting ? (
// Not on a phone: the working strip under the chat already says the bot waits, and says it once (spec C2).
<span className="inline-flex items-center gap-1.5 text-amber-300 max-md:hidden" data-question-waiting="">
- <Clock size={13} aria-hidden="true" /> {kwantName} is waiting for your answer. You can keep chatting meanwhile.
+ <Clock size={13} aria-hidden="true" /> {kwantName} is waiting for your answer. A message you send here answers it.
</span>
) : (
<span className="inline-flex items-center gap-1.5 text-zinc-400">
@@ -113,13 +122,19 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwa
<ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} modelBadge={false} />
<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'
+ open ? 'border-amber-400/60' : '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
+ {ago && (
+ <span className="text-zinc-500" data-asked-ago="">
+ {' · '}
+ {ago}
+ </span>
+ )}
</span>
<h3 id={headingId} className="text-sm font-semibold text-zinc-100 whitespace-pre-wrap break-words leading-snug">
{view.question}
@@ -140,7 +155,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwa
aria-pressed={chosen}
onClick={() => submit({ choice: i })}
onKeyDown={(e) => onChoiceKey(e, i)}
- className={`w-full sm:w-auto inline-flex items-center justify-center sm:justify-start gap-1.5 min-h-[48px] max-sm:!min-h-[48px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-base leading-[22px] sm:text-sm sm:leading-normal text-left border transition-colors break-words focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400 ${
+ className={`w-full sm:w-auto inline-flex items-center justify-center sm:justify-start gap-1.5 min-h-[48px] max-sm:!min-h-[48px] sm:min-h-[44px] px-3 py-1.5 rounded-xl text-base leading-[22px] sm:text-sm sm:leading-normal 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
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 829884d5..d78049d3 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -115,6 +115,8 @@ export interface SidebarProps {
selectedTeamId?: string | null;
/** What busy bots are doing ("Working on …", "Working here"), shown under their name. */
busyKwants?: Record<string, string>;
+ /** Teammates who already replied in a team turn now waiting on the person: "Done · replied in @team". */
+ doneKwants?: Record<string, string>;
/** Busy bots' status for the avatar dot; bots not listed are Available (or Can't run). */
botStatus?: Record<string, BotStatus>;
/** Open browser steps per bot ("Needs you" pill). */
@@ -361,6 +363,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
isChannel,
selectedTeamId,
busyKwants = {},
+ doneKwants = {},
botStatus = {},
needsYou = {},
browsingOwners = {},
@@ -560,6 +563,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
: budgetPaused && !busyKwants[k.id]
? PAUSED_ROW_LINE
: busyKwants[k.id];
+ // A teammate who finished its part of a team turn that now waits on the person (UX audit #2)
+ const doneLine = !busyLine && !warn ? doneKwants[k.id] : undefined;
// A stuck or finished row opens where that happened (its thread or chat), like its Inbox card
// A review row opens its item in the Inbox
const open = asked && onOpenNeedsYou
@@ -695,6 +700,11 @@ export const Sidebar: React.FC<SidebarProps> = ({
/>
<span className="truncate">{busyLine}</span>
</p>
+ ) : doneLine ? (
+ <p className={`flex items-center gap-1.5 text-meta text-zinc-400 truncate${actionRoom}`} title={doneLine} data-bot-done="">
+ <span className="kw-status-dot !h-1.5 !w-1.5 kw-status-ok" aria-hidden="true" />
+ <span className="truncate">{doneLine}</span>
+ </p>
) : (
// Keeps its one line even with no title, so Edit and Remove sit under the name, never on it (#290 N1)
<p className={`text-meta text-zinc-400 truncate${actionRoom}${!phone && hasRowActions ? ' min-h-[1.125rem]' : ''}`}>{k.title}</p>
diff --git a/frontend/src/components/WaitingBanner.tsx b/frontend/src/components/WaitingBanner.tsx
new file mode 100644
index 00000000..1eca3892
--- /dev/null
+++ b/frontend/src/components/WaitingBanner.tsx
@@ -0,0 +1,90 @@
+// Waiting state (UX audit #2, 0.9.7): one amber banner while the only open thing in a chat is a
+// question for the person. It replaces the sky "summarizing" banner and the working card, and holds the
+// only Stop (a ghost button). It takes a list of lines so later waits (waiting checks) can join it.
+import { ArrowUp, Check, Circle, Square } from 'lucide-react';
+import { RailStep, WaitingLine, waitingBannerShortText, waitingBannerText } from '../waitingState';
+
+const WARN_BORDER = 'color-mix(in srgb, var(--kw-warn) 40%, transparent)';
+
+export function WaitingBanner({
+ lines,
+ rail,
+ stopLabel,
+ onStop,
+ onShow,
+}: {
+ lines: WaitingLine[];
+ rail?: RailStep[];
+ stopLabel: string;
+ onStop?: () => void;
+ /** Brings the open question card into view. */
+ onShow?: () => void;
+}) {
+ if (!lines.length) return null;
+ const hasRail = !!rail && rail.length > 0;
+ const bot = lines[0]?.bot.trim() || 'the bot';
+ // Phone (below sm): the text takes the full width; the rail and the buttons share the second row.
+ // From sm: text and rail on the left, the buttons on the right.
+ return (
+ <div className="px-3 sm:px-6 pt-3 flex-shrink-0" data-waiting-banner="">
+ <div
+ role="group"
+ aria-label="Waiting for you"
+ className="flex flex-wrap items-center gap-x-3 gap-y-0.5 sm:gap-y-1 sm:grid sm:grid-cols-[minmax(0,1fr)_auto] px-3 sm:px-4 py-1.5 sm:py-2 mb-3 rounded-xl border bg-surface-raised text-xs"
+ style={{ borderColor: WARN_BORDER }}
+ >
+ {/* Only the lines are a live region: the rail and the buttons are not read out on each change. */}
+ <div role="status" className="basis-full min-w-0 flex flex-col gap-1 sm:col-start-1 sm:row-start-1">
+ {lines.map((l, i) => (
+ <p key={`${l.kind}-${i}`} className="flex items-center gap-2 min-w-0 text-warn font-medium" data-waiting-line={l.kind}>
+ <span aria-hidden="true" className="inline-block w-2 h-2 rounded-full shrink-0" style={{ background: 'var(--kw-warn)' }} />
+ <span className="min-w-0 max-sm:hidden">{waitingBannerText(l)}</span>
+ <span className="min-w-0 sm:hidden">{waitingBannerShortText(l)}</span>
+ </p>
+ ))}
+ </div>
+ {hasRail && (
+ <ol aria-label="Where the team is" className="flex-1 min-w-0 flex flex-wrap items-center gap-x-2.5 gap-y-0.5 text-meta text-zinc-400 sm:col-start-1 sm:row-start-2" data-waiting-rail="">
+ {rail!.map((s, i) => (
+ <li key={`${s.state}-${i}`} className={`flex items-center gap-1 ${s.state === 'you' ? 'text-warn' : ''}`}>
+ {s.state === 'done' ? (
+ <Check size={11} aria-hidden="true" className="text-ok" />
+ ) : (
+ <Circle size={8} aria-hidden="true" className={s.state === 'you' ? 'fill-current' : ''} />
+ )}
+ <span>
+ {s.state === 'done' && <span className="sr-only">Replied: </span>}
+ {s.state === 'next' && <span className="sr-only">Next: </span>}
+ {s.name}
+ </span>
+ </li>
+ ))}
+ </ol>
+ )}
+ <div className={`ml-auto flex items-center gap-1.5 shrink-0 sm:col-start-2 sm:row-start-1 ${hasRail ? 'sm:row-span-2' : ''}`}>
+ {onShow && (
+ <button
+ type="button"
+ onClick={onShow}
+ aria-label={`Go to ${bot}'s question`}
+ className="min-h-[32px] max-sm:min-h-[44px] inline-flex items-center gap-1 px-2.5 rounded-lg text-warn hover:bg-white/5 cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-300"
+ >
+ <ArrowUp size={12} aria-hidden="true" /> Answer
+ </button>
+ )}
+ {onStop && (
+ <button
+ type="button"
+ onClick={onStop}
+ data-waiting-stop=""
+ className="min-h-[32px] max-sm:min-h-[44px] inline-flex items-center gap-1 px-2.5 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-white/5 cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-400"
+ >
+ <Square size={10} className="fill-current" aria-hidden="true" />
+ {stopLabel}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/composer.ts b/frontend/src/composer.ts
index 8b56fa81..9afcec63 100644
--- a/frontend/src/composer.ts
+++ b/frontend/src/composer.ts
@@ -28,9 +28,13 @@ export const PLACEHOLDER_PAD = 24;
* long one would wrap and be cut mid-glyph. Unknown width (before layout): the short one.
*/
export function phonePlaceholder(name: string, fieldWidth: number, measure: (text: string) => number): string {
- const long = `Message ${name}`;
- if (!(fieldWidth > PLACEHOLDER_PAD)) return 'Message';
- return measure(long) <= fieldWidth - PLACEHOLDER_PAD ? long : 'Message';
+ return fitPlaceholder(`Message ${name}`, 'Message', fieldWidth, measure);
+}
+
+/** The long placeholder when it fits the field, else the short one. */
+export function fitPlaceholder(long: string, short: string, fieldWidth: number, measure: (text: string) => number): string {
+ if (!(fieldWidth > PLACEHOLDER_PAD)) return short;
+ return measure(long) <= fieldWidth - PLACEHOLDER_PAD ? long : short;
}
let ctx: CanvasRenderingContext2D | null | undefined;
diff --git a/frontend/src/discussionThreads.ts b/frontend/src/discussionThreads.ts
index 35d71751..4c5b3146 100644
--- a/frontend/src/discussionThreads.ts
+++ b/frontend/src/discussionThreads.ts
@@ -17,8 +17,12 @@ export type ChatItem<M> =
const isTurn = (m: LabeledMessage) => !!m.reasoning_content?.startsWith(TURN_LABEL);
const isSummary = (m: LabeledMessage) => !!m.reasoning_content?.startsWith(SUMMARY_LABEL);
-/** Groups runs of discussion turns that end in a team summary; turns still in progress stay inline. */
-export function groupDiscussionThreads<M extends LabeledMessage>(messages: M[]): ChatItem<M>[] {
+/**
+ * Groups runs of discussion turns that end in a team summary; turns still in progress stay inline.
+ * `foldOpen` (0.9.7 waiting state): the team turn waits on the person's answer, so its last run of turns
+ * folds too, and the question card sits right under the banner.
+ */
+export function groupDiscussionThreads<M extends LabeledMessage>(messages: M[], opts: { foldOpen?: boolean } = {}): ChatItem<M>[] {
const items: ChatItem<M>[] = [];
let i = 0;
while (i < messages.length) {
@@ -30,7 +34,8 @@ export function groupDiscussionThreads<M extends LabeledMessage>(messages: M[]):
let j = i;
while (j < messages.length && isTurn(messages[j])) j += 1;
const turns = messages.slice(i, j);
- if (j < messages.length && isSummary(messages[j])) {
+ const lastRun = !messages.slice(j).some(isTurn);
+ if ((j < messages.length && isSummary(messages[j])) || (opts.foldOpen && lastRun)) {
const speakers = Array.from(new Set(turns.map((t) => t.sender_id)));
items.push({ kind: 'thread', id: turns[0].id, turns, speakers });
} else {
diff --git a/frontend/src/waitingState.ts b/frontend/src/waitingState.ts
new file mode 100644
index 00000000..40f1b573
--- /dev/null
+++ b/frontend/src/waitingState.ts
@@ -0,0 +1,123 @@
+// Waiting state (UX audit #2, 0.9.7): while the only open thing in a chat is a bot's question for the
+// person, the chat reads as "waiting for you", not as working. Pure helpers; ChatView draws them.
+import type { WorkingState } from './workingStrip';
+
+export interface AskOnlyState extends WorkingState {
+ /** A reply is running in this chat (its turn hasn't ended). */
+ streaming?: boolean;
+ /** The running turn is paused on an approval card (shell command, production floor). */
+ approvalOpen?: boolean;
+}
+
+/**
+ * Whether the only open thing here is a question the person has to answer: a turn is running, it is
+ * paused on a question (not a browser step or an approval), nothing is queued and no words are streaming.
+ * Then the working card, the "Paused on the question above" box and the red Stop hide, Send stays, and
+ * Stop moves to the banner's ghost button.
+ */
+export function onlyAskOpen(s: AskOnlyState): boolean {
+ return !!s.streaming && !!s.awaitingAnswer && !s.awaitingBrowser && !s.approvalOpen && !s.queued && !s.writing;
+}
+
+/** One line for each thing the chat waits on the person for. Later lines (waiting checks) add a kind. */
+export interface WaitingLine {
+ kind: 'answer';
+ bot: string;
+}
+
+/** The banner's words for one waiting line. */
+export function waitingBannerText(line: WaitingLine): string {
+ const bot = line.bot.trim() || 'A bot';
+ return `Waiting for you: ${bot} needs one answer to finish`;
+}
+
+/** The banner line on a phone (below sm): the same words without "to finish". */
+export function waitingBannerShortText(line: WaitingLine): string {
+ const bot = line.bot.trim() || 'A bot';
+ return `Waiting for you: ${bot} needs one answer`;
+}
+
+/** A team turn (a team chat, or a discussion running in a channel) gets "Stop team" and the rail; a
+ * single bot asking in a channel or its own chat does not. */
+export function isTeamTurn(homeKind: string | undefined, discussionInProgress: boolean): boolean {
+ return homeKind === 'team' || discussionInProgress;
+}
+
+/** The composer's placeholder while the chat waits on a bot's answer: a message sent here answers it. */
+export function answerPlaceholder(bot: string | undefined): string {
+ return `Type your answer to ${bot?.trim() || 'the bot'}…`;
+}
+
+/** The banner's Stop button: a team turn stops the team, a single bot's turn stops that reply. */
+export function waitingStopLabel(team: boolean): string {
+ return team ? 'Stop team' : 'Stop';
+}
+
+/** "asked just now", "asked 1 min ago", "asked 12 min ago", "asked 2 h ago". Null without a valid time. */
+export function askedAgo(createdAt: string | null | undefined, now: number): string | null {
+ if (!createdAt) return null;
+ // The server writes UTC without a zone in some places ("2026-11-13 07:01:02").
+ const iso = /[zZ]|[+-]\d\d:?\d\d$/.test(createdAt) ? createdAt : `${createdAt.replace(' ', 'T')}Z`;
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return null;
+ const mins = Math.floor(Math.max(0, now - t) / 60000);
+ if (mins < 1) return 'asked just now';
+ if (mins < 60) return `asked ${mins} min ago`;
+ return `asked ${Math.floor(mins / 60)} h ago`;
+}
+
+export interface RailStep {
+ name: string;
+ state: 'done' | 'you' | 'next';
+}
+
+/**
+ * The team turn rail under the banner, from messages the chat already has: each teammate who replied
+ * since the person's last message (done), then "You pick" (you), then the asker wrapping up (next).
+ * Empty when no teammate replied yet (a single bot's ask has no rail).
+ */
+export function turnRail(
+ messages: { sender_role: string; sender_id: string }[],
+ askerId: string | null | undefined,
+ botOf: (senderId: string) => { id: string; name: string } | null | undefined,
+): RailStep[] {
+ const done = repliedSinceYou(messages, askerId, botOf);
+ if (!done.length) return [];
+ const asker = (askerId && botOf(askerId)?.name) || 'The lead';
+ return [...done.map((b) => ({ name: b.name, state: 'done' as const })), { name: 'You pick', state: 'you' }, { name: `${asker} wraps up`, state: 'next' }];
+}
+
+/** The bots other than the asker that replied since the person's last message, in reply order. */
+export function repliedSinceYou(
+ messages: { sender_role: string; sender_id: string }[],
+ askerId: string | null | undefined,
+ botOf: (senderId: string) => { id: string; name: string } | null | undefined,
+): { id: string; name: string }[] {
+ let start = 0;
+ for (let i = messages.length - 1; i >= 0; i--)
+ if (messages[i].sender_role === 'user') {
+ start = i + 1;
+ break;
+ }
+ const done: { id: string; name: string }[] = [];
+ for (const m of messages.slice(start)) {
+ if (m.sender_role !== 'kwant') continue;
+ const bot = botOf(m.sender_id);
+ if (bot && bot.id !== askerId && !done.some((d) => d.id === bot.id)) done.push(bot);
+ }
+ return done;
+}
+
+/** The sidebar's line for a teammate that finished its part of a team turn now waiting on the person. */
+export const DONE_HERE_LINE = 'Done · replied here';
+
+/** Sidebar "Done" lines, by bot id, for a team chat waiting on one bot's question; empty otherwise. */
+export function doneLines(
+ messages: { sender_role: string; sender_id: string }[],
+ asker: { id: string } | null | undefined,
+ team: boolean,
+ botOf: (senderId: string) => { id: string; name: string } | null | undefined,
+): Record<string, string> {
+ if (!asker || !team) return {};
+ return Object.fromEntries(repliedSinceYou(messages, asker.id, botOf).map((b) => [b.id, DONE_HERE_LINE]));
+}
diff --git a/frontend/tests/questions.test.mjs b/frontend/tests/questions.test.mjs
index 5e62884f..f7b77170 100644
--- a/frontend/tests/questions.test.mjs
+++ b/frontend/tests/questions.test.mjs
@@ -77,7 +77,7 @@ test('an open card offers the choices, a typed answer and skip; the agent is wai
assert.doesNotMatch(html, /<button[^>]*disabled=""[^>]*aria-pressed/);
assert.match(html, /Your own answer/);
assert.match(html, /Skip question/);
- assert.match(html, /CTO is waiting for your answer\. You can keep chatting meanwhile\./);
+ assert.match(html, /CTO is waiting for your answer\. A message you send here answers it\./);
assert.doesNotMatch(html, /busy|elsewhere/i);
});
diff --git a/frontend/tests/waitingState.test.mjs b/frontend/tests/waitingState.test.mjs
new file mode 100644
index 00000000..c4ba1610
--- /dev/null
+++ b/frontend/tests/waitingState.test.mjs
@@ -0,0 +1,252 @@
+// 0.9.7 waiting state (Mira's UX audit #2, autonomy/waiting-state/brief.md): while the only open thing in
+// a chat is a bot's question, the chat waits for the person. One amber banner replaces the "summarizing"
+// banner, the working card and the "Paused" box hide, the composer keeps Send, and Stop lives only on the
+// banner's ghost button. The question card says when it was asked and has no spinner or running clock.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const w = await loadBundled(`export * from './src/waitingState';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ChatView } from './src/components/ChatView';
+ import { QuestionCard } from './src/components/QuestionCard';
+ import { WaitingBanner } from './src/components/WaitingBanner';
+ export const chat = (props) => renderToStaticMarkup(React.createElement(ChatView, props));
+ export const question = (props) => renderToStaticMarkup(React.createElement(QuestionCard, props));
+ export const banner = (props) => renderToStaticMarkup(React.createElement(WaitingBanner, props));
+`);
+
+const ask = { streaming: true, awaitingAnswer: true };
+
+test('only an ask is open: a running turn paused on a question, nothing else going on', () => {
+ assert.equal(w.onlyAskOpen(ask), true);
+ assert.equal(w.onlyAskOpen({ ...ask, streaming: false }), false, 'no turn running');
+ assert.equal(w.onlyAskOpen({ ...ask, awaitingAnswer: false }), false, 'working, not waiting');
+ assert.equal(w.onlyAskOpen({ ...ask, awaitingBrowser: true }), false, 'a browser step has its own card');
+ assert.equal(w.onlyAskOpen({ ...ask, approvalOpen: true }), false, 'an approval is open too');
+ assert.equal(w.onlyAskOpen({ ...ask, queued: true }), false, 'waiting in line');
+ assert.equal(w.onlyAskOpen({ ...ask, writing: true }), false, 'words are streaming');
+});
+
+test('banner text names the bot and never says anyone is summarizing or speaking', () => {
+ assert.equal(w.waitingBannerText({ kind: 'answer', bot: 'Ann' }), 'Waiting for you: Ann needs one answer to finish');
+ assert.equal(w.waitingBannerText({ kind: 'answer', bot: ' ' }), 'Waiting for you: A bot needs one answer to finish');
+ assert.equal(w.waitingStopLabel(true), 'Stop team');
+ assert.equal(w.waitingStopLabel(false), 'Stop');
+ const html = ui.banner({ lines: [{ kind: 'answer', bot: 'Ann' }], stopLabel: 'Stop team', onStop: () => {}, onShow: () => {} });
+ assert.match(html, /role="status"/);
+ assert.match(html, /Waiting for you: Ann needs one answer to finish/);
+ assert.match(html, /data-waiting-stop=""[^>]*>.*Stop team<\/button>/);
+ assert.doesNotMatch(html, /summariz|speaking|animate-spin|bg-red/);
+ // Several lines fit (a waiting check can join later); none renders nothing.
+ const two = ui.banner({ lines: [{ kind: 'answer', bot: 'Ann' }, { kind: 'answer', bot: 'Ben' }], stopLabel: 'Stop' });
+ assert.equal(two.match(/data-waiting-line="answer"/g).length, 2);
+ assert.equal(ui.banner({ lines: [], stopLabel: 'Stop' }), '');
+});
+
+test('asked N min ago: just now, minutes, hours; server times without a zone are UTC', () => {
+ const now = Date.parse('2026-11-13T07:30:00Z');
+ assert.equal(w.askedAgo('2026-11-13T07:29:40Z', now), 'asked just now');
+ assert.equal(w.askedAgo('2026-11-13T07:29:00Z', now), 'asked 1 min ago');
+ assert.equal(w.askedAgo('2026-11-13 07:18:00', now), 'asked 12 min ago');
+ assert.equal(w.askedAgo('2026-11-13T05:10:00+00:00', now), 'asked 2 h ago');
+ assert.equal(w.askedAgo('2026-11-13T07:31:00Z', now), 'asked just now', 'a clock a little ahead');
+ assert.equal(w.askedAgo('', now), null);
+ assert.equal(w.askedAgo('nonsense', now), null);
+});
+
+const bots = [{ id: 'k-ann', name: 'Ann' }, { id: 'k-ben', name: 'Ben' }, { id: 'k-cody', name: 'Cody' }];
+const botOf = (id) => bots.find((b) => b.id === id || b.name === id) ?? null;
+const turn = [
+ { sender_role: 'user', sender_id: 'me' },
+ { sender_role: 'kwant', sender_id: 'k-ben' }, // an earlier turn
+ { sender_role: 'user', sender_id: 'me' },
+ { sender_role: 'kwant', sender_id: 'k-ann' },
+ { sender_role: 'kwant', sender_id: 'Ben' }, // older messages name the sender
+ { sender_role: 'kwant', sender_id: 'k-cody' },
+ { sender_role: 'kwant', sender_id: 'k-ben' },
+];
+
+test('turn rail and sidebar Done lines: teammates who replied since your message, not the asker', () => {
+ assert.deepEqual(w.turnRail(turn, 'k-ann', botOf), [
+ { name: 'Ben', state: 'done' },
+ { name: 'Cody', state: 'done' },
+ { name: 'You pick', state: 'you' },
+ { name: 'Ann wraps up', state: 'next' },
+ ]);
+ assert.deepEqual(w.turnRail(turn.slice(0, 4), 'k-ann', botOf), [], 'nobody else replied yet: no rail');
+ assert.deepEqual(w.doneLines(turn, { id: 'k-ann' }, true, botOf), { 'k-ben': 'Done · replied here', 'k-cody': 'Done · replied here' });
+ assert.deepEqual(w.doneLines(turn, { id: 'k-ann' }, false, botOf), {}, 'a single bot chat');
+ assert.deepEqual(w.doneLines(turn, null, true, botOf), {}, 'nothing waits on you');
+});
+
+const msgs = [
+ { id: 'u1', sender_role: 'user', sender_id: 'me', text: 'Plan our spring offer.' },
+ { id: 'b1', sender_role: 'kwant', sender_id: 'k-ben', text: 'Here is my take.' },
+];
+const chatProps = (over = {}) => ({
+ title: 'spring-launch', subtitle: '', messages: msgs, streamingText: '', streamingThinking: '', isStreaming: true,
+ pendingApprovals: [], onSendMessage: () => {}, onResolveApproval: () => {}, onCancelDiscussion: () => {},
+ kwants: bots, teams: [], awaitingAnswer: true, awaitingBot: { id: 'k-ann', name: 'Ann' },
+ discussionState: { inProgress: true, currentSpeaker: 'Ann', currentTurn: 3, totalTurns: 3, kind: 'discussion', phase: 'summary' },
+ ...over,
+});
+const submit = (html) => /<button[^>]*type="submit"[^>]*>/.exec(html)?.[0];
+
+test('team turn waiting on an answer: amber banner, no summarizing, no working card, Send stays', () => {
+ const html = chat(chatProps());
+ assert.match(html, /data-waiting-banner/);
+ assert.match(html, /Waiting for you: Ann needs one answer to finish/);
+ assert.doesNotMatch(html, /summarizing/, 'nobody is summarizing while the turn waits');
+ assert.doesNotMatch(html, /Paused on the question above/);
+ assert.doesNotMatch(html, /Waiting for your answer/, 'the live block with its label is gone');
+ assert.doesNotMatch(html, /Stop Discussion/, 'no red Stop in the composer or the old banner');
+ assert.match(html, /Stop team<\/button>/);
+ assert.match(html, /data-waiting-rail[\s\S]*Ben[\s\S]*You pick[\s\S]*Ann wraps up/);
+ assert.match(submit(html), /aria-label="Send \(answers the question\)"/);
+});
+
+function chat(props) {
+ return ui.chat(props);
+}
+
+test('single bot waiting on an answer: banner Stop, no team words', () => {
+ const html = chat(chatProps({ title: 'Ann', discussionState: null, home: { kind: 'bot', bot: { id: 'k-ann', name: 'Ann' } }, messages: msgs.slice(0, 1) }));
+ assert.match(html, /Waiting for you: Ann needs one answer to finish/);
+ assert.match(html, /data-waiting-stop=""[^>]*>.*>Stop<\/button>/);
+ assert.doesNotMatch(html, /Stop team|data-waiting-rail/);
+ assert.ok(submit(html), 'Send is there');
+});
+
+test('anything else open keeps today\'s view: a browser step, words streaming, nothing waiting', () => {
+ for (const over of [{ awaitingBrowser: true }, { streamingText: 'Here is' }, { awaitingAnswer: false }]) {
+ const html = chat(chatProps(over));
+ assert.doesNotMatch(html, /data-waiting-banner/, JSON.stringify(over));
+ }
+ const working = chat(chatProps({ awaitingAnswer: false }));
+ assert.match(working, /Stop Discussion/, 'the discussion banner and red Stop come back');
+ // After answering, nothing runs: plain Send, no banner.
+ const after = chat(chatProps({ isStreaming: false, awaitingAnswer: false, discussionState: null }));
+ assert.doesNotMatch(after, /data-waiting-banner|Stop team/);
+ assert.match(submit(after), /aria-label="Send"/);
+});
+
+const meta = { kind: 'question', question_id: 'q1', question: 'Which spring offer should we run?', choices: ['15% off', '20% off'], status: 'open' };
+
+test('ask card: amber border, asked N min ago, no spinner, choices at least 44 px everywhere', () => {
+ const live = { id: 'q1', kwant_id: 'k-ann', question: meta.question, choices: meta.choices, status: 'open', created_at: new Date(Date.now() - 3 * 60000).toISOString(), turn_id: 't1' };
+ const html = ui.question({ meta, live, messageId: 'm1', kwantName: 'Ann', waiting: true, onAnswer: async () => {}, onDismiss: async () => {} });
+ assert.match(html, /border-amber-400\/60/);
+ assert.match(html, /data-asked-ago="">.*asked 3 min ago/);
+ assert.doesNotMatch(html, /animate-spin/);
+ const choices = [...html.matchAll(/<button([^>]*aria-pressed[^>]*)>/g)].map((x) => x[1]);
+ assert.equal(choices.length, 2);
+ for (const c of choices) assert.match(c, /min-h-\[48px\] max-sm:!min-h-\[48px\] sm:min-h-\[44px\]/);
+ // An answered card says nothing about when it was asked.
+ const done = ui.question({ meta: { ...meta, status: 'answered', answer: '15% off' }, live: { ...live, status: 'answered' }, messageId: 'm1', kwantName: 'Ann', onAnswer: async () => {}, onDismiss: async () => {} });
+ assert.doesNotMatch(done, /asked .* ago|asked just now/);
+});
+
+test('the sidebar draws Done lines quietly, and never over a busy or needs-you line', () => {
+ const src = readFileSync(new URL('../src/components/Sidebar.tsx', import.meta.url), 'utf8');
+ assert.match(src, /const doneLine = !busyLine && !warn \? doneKwants\[k\.id\] : undefined;/);
+ assert.match(src, /data-bot-done=""/);
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /doneKwants=\{doneKwants\}/);
+ assert.match(app, /awaitingBot=\{awaitingBotHere\}/);
+});
+
+const d = await loadBundled(`export * from './src/discussionThreads';`);
+
+test('earlier replies fold into the existing "Team discussed" row only while the team waits on an answer', () => {
+ const ms = [
+ { id: 'u', sender_id: 'me', sender_role: 'user' },
+ { id: 'a1', sender_id: 'Ann', reasoning_content: 'Team Discussion • Turn 1' },
+ { id: 'b1', sender_id: 'Ben', reasoning_content: 'Team Discussion • Turn 2' },
+ { id: 'q', sender_id: 'Ann', reasoning_content: '' }, // the question card
+ ];
+ assert.deepEqual(d.groupDiscussionThreads(ms).map((i) => i.kind), ['message', 'message', 'message', 'message'], 'today: inline');
+ const folded = d.groupDiscussionThreads(ms, { foldOpen: true });
+ assert.deepEqual(folded.map((i) => i.kind), ['message', 'thread', 'message']);
+ assert.deepEqual(folded[1].speakers, ['Ann', 'Ben']);
+ assert.equal(folded[2].message.id, 'q', 'the question stays out of the fold');
+ // An earlier unfinished run stays inline; only the last run folds.
+ const two = [...ms.slice(0, 2), { id: 'x', sender_id: 'me', sender_role: 'user' }, ...ms.slice(2)];
+ assert.deepEqual(d.groupDiscussionThreads(two, { foldOpen: true }).map((i) => i.kind), ['message', 'message', 'message', 'thread', 'message']);
+});
+
+// Round 2 (Mira's design check, autonomy/waiting-state/design-check.md "Verdict: FIX").
+test('copy is true while waiting: the card footer and the composer say a message here answers it', () => {
+ const card = ui.question({ meta, messageId: 'm1', kwantName: 'Ann', live: true, waiting: true, onAnswer: () => {}, onDismiss: () => {} });
+ assert.match(card, /Ann is waiting for your answer\. A message you send here answers it\./);
+ assert.doesNotMatch(card, /keep chatting meanwhile/);
+ assert.match(chat(chatProps()), /placeholder="Type your answer to Ann…"/);
+ // Every other state keeps today's words.
+ assert.doesNotMatch(chat(chatProps({ awaitingAnswer: false })), /Type your answer/);
+ assert.equal(w.answerPlaceholder('Ann'), 'Type your answer to Ann…');
+ assert.equal(w.answerPlaceholder(' '), 'Type your answer to the bot…');
+});
+
+test('phone placeholder falls back to "Your answer…" when the long one does not fit', async () => {
+ const c = await loadBundled(`export * from './src/composer';`);
+ const m = (t) => t.length * 9;
+ assert.equal(c.fitPlaceholder('Type your answer to Ann…', 'Your answer…', 400, m), 'Type your answer to Ann…');
+ assert.equal(c.fitPlaceholder('Type your answer to Ann…', 'Your answer…', 150, m), 'Your answer…');
+ assert.equal(c.fitPlaceholder('Type your answer to Ann…', 'Your answer…', 0, m), 'Your answer…');
+ assert.equal(c.phonePlaceholder('Ann', 0, m), 'Message', 'the other states are unchanged');
+ const src = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
+ assert.match(src, /fitPlaceholder\(answerPlaceholder\([^)]*\), 'Your answer…', fieldWidth/);
+});
+
+test('screen readers: only the lines are a live region; the box is a labelled group; Answer says where it goes', () => {
+ const html = ui.banner({ lines: [{ kind: 'answer', bot: 'Ann' }], rail: [{ name: 'Ben', state: 'done' }, { name: 'You pick', state: 'you' }], stopLabel: 'Stop team', onStop: () => {}, onShow: () => {} });
+ assert.match(html, /role="group" aria-label="Waiting for you"/);
+ assert.equal(html.match(/role="status"/g).length, 1);
+ const status = /<div role="status"[^>]*>([\s\S]*?)<\/div>/.exec(html)[1];
+ assert.match(status, /Waiting for you: Ann needs one answer/);
+ assert.doesNotMatch(status, /<button|<ol|Replied|Stop team/, 'rail and buttons sit outside the live region');
+ assert.match(html, /aria-label="Go to Ann&#x27;s question"[^>]*>.*Answer<\/button>/);
+});
+
+test('phone layout: short text below sm, buttons right-aligned on the rail row, 44 px targets; Stop is a ghost', () => {
+ assert.equal(w.waitingBannerShortText({ kind: 'answer', bot: 'Ann' }), 'Waiting for you: Ann needs one answer');
+ const html = ui.banner({ lines: [{ kind: 'answer', bot: 'Ann' }], rail: [{ name: 'Ben', state: 'done' }], stopLabel: 'Stop team', onStop: () => {}, onShow: () => {} });
+ assert.match(html, /class="min-w-0 max-sm:hidden">Waiting for you: Ann needs one answer to finish</);
+ assert.match(html, /class="min-w-0 sm:hidden">Waiting for you: Ann needs one answer</);
+ assert.match(html, /role="status" class="basis-full/, 'the text takes the whole first row on a phone');
+ assert.match(html, /<ol[^>]*class="flex-1/, 'the rail fills the second row and wraps');
+ assert.match(html, /class="ml-auto[^"]*sm:row-span-2/, 'buttons right-aligned');
+ assert.equal(html.match(/max-sm:min-h-\[44px\]/g).length, 2);
+ const stop = /<button[^>]*data-waiting-stop=""[^>]*>/.exec(html)[0];
+ assert.doesNotMatch(stop, /border/, 'a ghost: no border');
+ assert.match(stop, /text-zinc-300 hover:text-zinc-100 hover:bg-white\/5/);
+ assert.match(stop, /outline-rose-400/);
+ const solo = ui.banner({ lines: [{ kind: 'answer', bot: 'Ann' }], stopLabel: 'Stop', onStop: () => {}, onShow: () => {} });
+ assert.doesNotMatch(solo, /row-span-2|data-waiting-rail/);
+});
+
+test('Answer moves keyboard focus to the open card: first choice, else its answer field, without a second scroll', () => {
+ const src = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
+ const fn = /const showWaitingCard = [\s\S]*?\n \};/.exec(src)[0];
+ assert.match(fn, /scrollIntoView[\s\S]*querySelector<HTMLElement>\('button\[aria-pressed\]'\) \?\? card\.querySelector<HTMLElement>\('textarea'\)/);
+ assert.match(fn, /focus\(\{ preventScroll: true \}\)/);
+ assert.match(ui.question({ meta, messageId: 'm1', kwantName: 'Ann', live: true, waiting: true, onAnswer: () => {}, onDismiss: () => {} }), /aria-pressed/, 'the choices the selector finds');
+});
+
+test('a single bot asking in a channel: "Stop", no rail; a team turn keeps the team words', () => {
+ assert.equal(w.isTeamTurn('channel', false), false);
+ assert.equal(w.isTeamTurn('general', false), false);
+ assert.equal(w.isTeamTurn('team', false), true);
+ assert.equal(w.isTeamTurn('channel', true), true, 'a discussion running in a channel');
+ const html = chat(chatProps({ title: 'general', discussionState: null, home: { kind: 'channel' } }));
+ assert.match(html, /Waiting for you: Ann needs one answer to finish/);
+ assert.match(html, /data-waiting-stop=""[^>]*>.*>Stop<\/button>/);
+ assert.doesNotMatch(html, /Stop team|data-waiting-rail/);
+ const team = chat(chatProps({ title: 'spring-launch', discussionState: null, home: { kind: 'team' } }));
+ assert.match(team, /Stop team<\/button>/);
+});
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 7d25c1c9..6918120d 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -4351,6 +4351,35 @@ async fn send_chat_routed(
}
}
}
+ // A direct chat (`kwant_id`) or a team chat (`team_id` and its channel) with no @mention: an
+ // open question card of that bot, or of one of the team's members, takes the typed message as
+ // its answer, as the card promises. Only the answer step below uses this; routing is unchanged.
+ let mut typed_answer: Option<(String, String)> = None;
+ if let (None, None) = (kwant_mention, team_mention) {
+ let chat: Option<(&str, Vec<Kwant>)> = match (payload.kwant_id.as_deref(), payload.team_id.as_deref(), payload.channel_id.as_deref()) {
+ (Some(kid), None, None) => all_kwants.iter().find(|k| k.id == kid).map(|k| (kid, vec![k.clone()])),
+ (None, Some(tid), Some(cid)) => all_teams.iter().find(|t| t.id == tid || t.name.eq_ignore_ascii_case(tid)).map(|t| {
+ let ids: Vec<String> = serde_json::from_str(&t.member_kwants).unwrap_or_default();
+ (cid, all_kwants.iter().filter(|k| ids.contains(&k.id)).cloned().collect())
+ }),
+ _ => None,
+ };
+ if let Some((ctx, members)) = chat {
+ let recent = state.db.list_messages(ctx, 30).await.unwrap_or_default();
+ let open = state.db.list_questions(Some("open"), Some(ctx), None).await.unwrap_or_default();
+ let direct = payload.kwant_id.is_some();
+ let open: Vec<_> = open
+ .into_iter()
+ .filter(|q| q.thread_id.is_none())
+ .filter(|q| if direct { q.channel_id.is_none() && q.direct_kwant_id.as_deref() == Some(ctx) } else { q.channel_id.as_deref() == Some(ctx) })
+ .collect();
+ if let Some(a) = crate::router::sticky::awaiting_answer(&recent, &open, &members) {
+ if let (true, Some(qid)) = (a.card, a.question_id) {
+ typed_answer = Some((a.kwant.name.clone(), qid));
+ }
+ }
+ }
+ }
// Detect if a team is targeted
let target_team = if let Some(tid) = payload.team_id.as_ref().filter(|_| reply_bot.is_none()) {
@@ -4511,12 +4540,16 @@ async fn send_chat_routed(
// Typed instead of tapped: the answer closes the bot's open question, and a turn still waiting
// on it carries on with it (no second turn)
- if let Some((asker, Some(qid))) = &awaiting {
+ let asked = match &awaiting {
+ Some((asker, Some(qid))) => Some((asker.name.clone(), qid.clone())),
+ _ => typed_answer,
+ };
+ if let Some((asker, qid)) = &asked {
if super::questions::answer_by_message(&state, qid, &payload.prompt).await {
return Ok(Json(json!({
"status": "answered",
"user_message_id": saved_user_msg.id,
- "kwant": asker.name,
+ "kwant": asker,
"question_id": qid,
})));
}
diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rs
index a34c30e8..ab50e1b2 100644
--- a/tests/ask_user_test.rs
+++ b/tests/ask_user_test.rs
@@ -6,6 +6,7 @@ mod common;
use axum::http::StatusCode;
use common::*;
+use kwnt::db::questions::QuestionPlace;
use kwnt::server::continuity::SelfScope;
use kwnt::RuntimeEvent;
use serde_json::{json, Value};
@@ -321,3 +322,77 @@ async fn a_late_answer_in_a_delegation_reaches_the_lead() {
assert_eq!((meta["kind"].as_str(), meta["late"].as_bool()), (Some("delegation_result"), Some(true)));
assert_eq!(invocations_with("got the person's answer").len(), 1, "the lead is resumed once");
}
+
+/// Typed instead of tapped (#567): in a direct chat, a message sent while the bot's question card
+/// is open answers it. The waiting turn goes on with the text, and no second turn starts.
+#[tokio::test]
+async fn a_typed_reply_answers_the_open_question_in_a_direct_chat() {
+ let env = setup().await;
+ send_direct(&env, &env.a, &format!("{} REPLYTAG:ta1", ask_marker("Which offer should the shop run this week?", &["15% off", "Free shipping"])), json!({})).await;
+ let q = open_question(&env, &env.a).await;
+ let id = q["id"].as_str().unwrap();
+
+ let v = send_direct(&env, &env.a, "TYPED_DIRECT free shipping over $35, please", json!({})).await;
+ assert_eq!((v["status"].as_str(), v["question_id"].as_str()), (Some("answered"), Some(id)), "{v}");
+ let reply = wait_reply(&env, &env.a, "answer ta1").await;
+ assert!(reply.text.contains("The user answered: TYPED_DIRECT free shipping over $35, please]"), "{}", reply.text);
+ let q = &question(&env, id).await["question"];
+ assert_eq!((q["status"].as_str(), q["answer"].as_str()), (Some("answered"), Some("TYPED_DIRECT free shipping over $35, please")));
+ assert!(invocations_with("TYPED_DIRECT").is_empty(), "no second turn");
+}
+
+/// The same in a team chat (`team_id` and the team's channel): the member's open question takes
+/// the typed message instead of the team router starting a new turn.
+#[tokio::test]
+async fn a_typed_reply_answers_the_open_question_in_a_team_chat() {
+ let env = setup().await;
+ let (s, v) = call(&env.app, "POST", "/api/teams", Some(json!({"name": "shop", "lead_kwant_id": env.a, "member_kwants": [env.a, env.b]}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let team = v["id"].as_str().or(v["team"]["id"].as_str()).unwrap().to_string();
+ let (_, channels) = call(&env.app, "GET", "/api/channels", None).await;
+ let channel = channels.as_array().unwrap().iter().find(|c| c["name"] == "team-shop").unwrap()["id"].as_str().unwrap().to_string();
+ let app = &env.app;
+ let say = |prompt: String| {
+ let body = json!({"channel_id": channel, "team_id": team, "prompt": prompt, "sender_id": "user"});
+ async move { call(app, "POST", "/api/chat/send", Some(body)).await }
+ };
+
+ // A's turn asks in the team chat (named, so it is A's turn whichever member the router would
+ // pick). Each test asks its own question: the fake CLI calls a given tool marker only once.
+ let a_name = env.state.db.get_kwant(&env.a).await.unwrap().unwrap().name;
+ let ask = format!("@{a_name} {} REPLYTAG:tt1", ask_marker("Which offer should the team shop run?", &["15% off", "Free shipping"]));
+ let (s, v) = call(app, "POST", "/api/chat/send", Some(json!({"channel_id": channel, "prompt": ask, "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let q = open_question(&env, &channel).await;
+ let id = q["id"].as_str().unwrap();
+ assert_eq!(q["kwant_id"], env.a.as_str(), "{q}");
+
+ let (s, v) = say("TYPED_TEAM free shipping over $35, please".into()).await;
+ assert_eq!((s, v["status"].as_str(), v["question_id"].as_str()), (StatusCode::OK, Some("answered"), Some(id)), "{v}");
+ let reply = wait_reply(&env, &channel, "answer tt1").await;
+ assert!(reply.text.contains("The user answered: TYPED_TEAM free shipping over $35, please]"), "{}", reply.text);
+ assert_eq!(question(&env, id).await["question"]["status"], "answered");
+ assert!(invocations_with("TYPED_TEAM").is_empty(), "the team router started no turn");
+}
+
+/// A direct chat only answers its own bot's question: another bot's open question (in its own
+/// chat, or one it left in this chat) stays open, and the message is an ordinary new turn.
+#[tokio::test]
+async fn a_typed_reply_never_answers_another_bots_question() {
+ let env = setup().await;
+ send_direct(&env, &env.b, &format!("{} REPLYTAG:tn0", ask_marker("Which courier?", &["DHL", "UPS"])), json!({})).await;
+ let theirs = open_question(&env, &env.b).await;
+ let place = QuestionPlace { kwant_id: env.b.clone(), direct_kwant_id: Some(env.a.clone()), ..Default::default() };
+ let left_here = env.state.db.create_question(&place, "Which warehouse?", &["north".into(), "south".into()]).await.unwrap();
+
+ let v = send_direct(&env, &env.a, "Free shipping over $35, please REPLYTAG:tn1", json!({})).await;
+ assert_ne!(v["status"], "answered", "{v}");
+ wait_reply(&env, &env.a, "answer tn1").await;
+ for id in [theirs["id"].as_str().unwrap(), left_here.id.as_str()] {
+ assert_eq!(question(&env, id).await["question"]["status"], "open", "{id}");
+ }
+
+ let (s, _) = call(&env.app, "POST", &format!("/api/questions/{}/answer", theirs["id"].as_str().unwrap()), Some(json!({"choice": 0}))).await;
+ assert_eq!(s, StatusCode::OK);
+ wait_reply(&env, &env.b, "answer tn0").await;
+}