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.

Reactions and Reply on bot messages (react-reply PR B) (#292)

Oleksandr Ivanchenko19e9b977a33c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 0b60d609..64701ba5 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -8,7 +8,8 @@ import { PHONE_QUERY } from './layout';
import { useSettingsCover } from './settingsFocus';
import { FirstRunWelcome } from './components/FirstRunWelcome';
import { SpaceTile } from './components/Spaces';
-import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } from './components/ChatView';
+import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState, SendOptions } from './components/ChatView';
+import { ReactResult, Reaction, optimisticReplyRef, reactionOf, saveReaction, senderLabel } from './reactReply';
import { ThreadBar, ThreadHeader } from './components/ThreadBar';
import { DelegationCard } from './components/DelegationCard';
import { ApprovalsOffBadge } from './components/ApprovalsSetting';
@@ -387,6 +388,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}, delay);
};
const toastIdRef = useRef(0);
+ const applyReactionRef = useRef<((id: string, reaction: Reaction | null) => void) | null>(null);
const dismissToast = useCallback((id: number) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);
// Set each render once the select handlers exist; the SSE handler and notification clicks go through it.
// Opens a bot's settings on the Skills tab (set once the bots are known).
@@ -1372,7 +1374,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
});
};
- const handleSendMessage = async (text: string, attachments: AttachmentRef[] = []): Promise<boolean> => {
+ const handleSendMessage = async (text: string, attachments: AttachmentRef[] = [], opts: SendOptions = {}): Promise<boolean> => {
haptic('tap');
setHistoryWindow(null);
const targetId = openCtx;
@@ -1402,7 +1404,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
sender_id: 'PlayerHero',
text,
meta: attachments.length ? JSON.stringify({ attachments }) : null,
+ reply_to: opts.replyTo ? optimisticReplyRef(opts.replyTo) : null,
};
+ const reply_to_message_id = opts.replyTo?.id;
const cached = messagesCacheRef.current[targetId] || messages;
const updated = [...cached, userMsg];
messagesCacheRef.current[targetId] = updated;
@@ -1417,7 +1421,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(
threadId
- ? { thread_id: threadId, prompt: text, sender_id: 'PlayerHero', attachment_ids }
+ ? { thread_id: threadId, prompt: text, sender_id: 'PlayerHero', attachment_ids, ...(reply_to_message_id ? { reply_to_message_id } : {}) }
: {
channel_id: isTargetChannel ? targetId : null,
kwant_id: !isTargetChannel ? targetId : null,
@@ -1425,6 +1429,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
prompt: text,
sender_id: 'PlayerHero',
attachment_ids,
+ ...(reply_to_message_id ? { reply_to_message_id } : {}),
},
),
});
@@ -1638,6 +1643,60 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setToasts((prev) => [...prev.slice(-2), { id, title, detail }]);
};
+ /** Sets one message's reaction wherever it is shown: every cached chat and the open history window. */
+ const applyReaction = (messageId: string, reaction: Reaction | null) => {
+ const patch = (list: ChatMessage[]) =>
+ list.some((m) => m.id === messageId) ? list.map((m) => (m.id === messageId ? { ...m, reaction } : m)) : list;
+ for (const ctx of Object.keys(messagesCacheRef.current)) {
+ const list = messagesCacheRef.current[ctx];
+ const next = patch(list);
+ if (next !== list) {
+ messagesCacheRef.current[ctx] = next;
+ if (ctx === openCtxRef.current) setMessages(next);
+ }
+ }
+ setHistoryWindow((w) => {
+ if (!w) return w;
+ const next = patch(w.messages);
+ return next === w.messages ? w : { ...w, messages: next };
+ });
+ };
+ applyReactionRef.current = applyReaction;
+
+ /**
+ * Shows the new reaction at once; if the save fails, puts the old one back (ChatView says so).
+ * A thumb on the bot's newest question is the person's yes or no: the server starts a turn, and the
+ * chat shows the bot working exactly as after a send.
+ */
+ const handleReact = async (msg: ChatMessage, reaction: Reaction | null): Promise<ReactResult> => {
+ const before = reactionOf(msg.reaction);
+ applyReaction(msg.id, reaction);
+ try {
+ const saved = await saveReaction(fetch, msg.id, reaction);
+ if (saved.reaction !== reaction) applyReaction(msg.id, saved.reaction);
+ if (saved.answered) {
+ const ctx = messageContextId(msg) ?? openCtxRef.current;
+ if (ctx) {
+ haptic('tap');
+ streamingContextIdRef.current = ctx;
+ if (!(ctx in liveRef.current)) {
+ streamsRef.current[ctx] = { text: '', thinking: '' };
+ if (ctx === openCtxRef.current) {
+ setStreamingText('');
+ setStreamingThinking('');
+ }
+ }
+ markLive(ctx, senderLabel(msg.sender_role, msg.sender_id, liveRef.current[ctx] || 'Bot'));
+ }
+ }
+ return { ok: true, answered: saved.answered };
+ } catch (err) {
+ applyReaction(msg.id, before);
+ haptic('warning');
+ return { ok: false, answered: false, error: err instanceof Error ? err.message : undefined };
+ }
+ };
+
/** Opens one of a bot'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);
@@ -3092,6 +3151,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
isStreaming={isCurrentContextStreaming}
streamingSpeakerName={live[openCtx] || undefined}
onSendMessage={handleSendMessage}
+ onReact={handleReact}
onResolveApproval={handleResolveApproval}
kwants={kwants}
teams={teams}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 11d3fa71..7bd1ccc6 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -57,6 +57,8 @@ import { SmartActionsSlot, actionClass } from './results/SmartActions';
import { WorkingStrip } from './WorkingStrip';
import { COMPOSE_PREFILL_EVENT, withPrefill } from './results/SmartResult';
import { FilesPreviewOnly } from './results/Files';
+import { ReactionButtons, ReplyButton, ReplyChip, ReplyQuote } from './MessageReactions';
+import { ReactResult, Reaction, ReplyRef, botNameOf, excerptOf, questionMessageId, reactionOf, replyRefOf } from '../reactReply';
/** A swipeable chip row whose right fade edge (phones only, see .kw-scroll-row) goes away once
* it is scrolled to the end, or when everything already fits. */
@@ -102,6 +104,16 @@ export interface ChatMessage {
created_at?: string | null;
/** Smart Results blocks for a bot reply; null or absent while the setting is off. */
results?: unknown;
+ /** The person's thumbs on a bot reply; absent on servers before reactions (read as none). */
+ reaction?: Reaction | null;
+ /** The message the person replied to; absent or null when it isn't a reply. */
+ reply_to?: ReplyRef | null;
+}
+
+/** Extra details of a message being sent. */
+export interface SendOptions {
+ /** The bot message this one replies to. */
+ replyTo?: ChatMessage;
}
/** The open chat's turn is waiting for a free slot. */
@@ -166,7 +178,9 @@ export interface ChatViewProps {
streamingSpeakerName?: string;
/** `attachments` are files already uploaded from the composer. */
/** Resolves to false when the message couldn't be sent. */
- onSendMessage: (text: string, attachments: AttachmentRef[]) => void | Promise<boolean | void>;
+ onSendMessage: (text: string, attachments: AttachmentRef[], opts?: SendOptions) => void | Promise<boolean | void>;
+ /** Saves the person's thumbs on a bot reply; absent hides the thumbs. */
+ onReact?: (msg: ChatMessage, reaction: Reaction | null) => Promise<ReactResult> | void;
onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
@@ -388,6 +402,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
isStreaming,
streamingSpeakerName,
onSendMessage,
+ onReact,
onResolveApproval,
kwants: kwantsProp,
teams: teamsProp,
@@ -661,6 +676,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
// 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.
const [flashId, setFlashId] = useState<string | null>(null);
+ // A search hit glows amber for 2.4 s; the original of a reply quote gets a violet ring for 1.6 s.
+ const [flashKind, setFlashKind] = useState<'search' | 'quote'>('search');
useEffect(() => {
if (!highlightMessageId || !messages.some((m) => m.id === highlightMessageId)) return;
const thread = groupDiscussionThreads(messages).find(
@@ -674,14 +691,77 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (!el) return;
const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
el.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
+ setFlashKind('search');
setFlashId(highlightMessageId);
onHighlightDone?.();
}, [highlightMessageId, messages, openThoughts, onHighlightDone]);
useEffect(() => {
if (!flashId) return;
- const t = setTimeout(() => setFlashId(null), 2400);
+ const t = setTimeout(() => setFlashId(null), flashKind === 'quote' ? 1600 : 2400);
return () => clearTimeout(t);
- }, [flashId]);
+ }, [flashId, flashKind]);
+
+ // Reply: the bot message the next send answers. Cleared on send and when the chat changes.
+ const [replyTo, setReplyTo] = useState<ChatMessage | null>(null);
+ useEffect(() => {
+ setReplyTo(null);
+ }, [contextKey]);
+ const focusComposer = () => {
+ const ta = textareaRef.current;
+ if (!ta) return;
+ ta.focus();
+ ta.setSelectionRange(ta.value.length, ta.value.length);
+ };
+ const startReply = (msg: ChatMessage) => {
+ setReplyTo(msg);
+ focusComposer();
+ };
+ /** The chip's name: the bot by id or name, else this chat's title. */
+ const replyBotName = (msg: ChatMessage) => {
+ const name = botNameOf(msg.sender_id, activeKwants);
+ return name === 'a bot' ? title : name;
+ };
+ const cancelReply = () => {
+ setReplyTo(null);
+ focusComposer();
+ };
+ /**
+ * Jumps to a quote's original: opens its folded discussion if needed, centres it, moves focus there
+ * and rings it. False when it isn't loaded in this chat.
+ */
+ const [quoteJump, setQuoteJump] = useState<{ id: string; n: number } | null>(null);
+ const showOriginal = (id: string): boolean => {
+ if (!messages.some((m) => m.id === id)) return false;
+ stickRef.current = false;
+ setQuoteJump((p) => ({ id, n: (p?.n ?? 0) + 1 }));
+ return true;
+ };
+ useEffect(() => {
+ if (!quoteJump) return;
+ const thread = groupDiscussionThreads(messages).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;
+ }
+ const el = scrollRef.current?.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(quoteJump.id)}"]`);
+ setQuoteJump(null);
+ if (!el) return;
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ el.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });
+ if (el.tabIndex < 0 || el.hasAttribute('tabindex')) el.focus({ preventScroll: true });
+ setFlashId(null);
+ setFlashKind('quote');
+ requestAnimationFrame(() => setFlashId(quoteJump.id));
+ }, [quoteJump, messages, openThoughts]);
+
+ // Thumbs on the bot's newest question are a yes or no; once one has answered it, they're feedback again.
+ const [answered, setAnswered] = useState<ReadonlySet<string>>(() => new Set());
+ const questionId = questionMessageId(messages, isStreaming);
+ const react = async (msg: ChatMessage, reaction: Reaction | null): Promise<boolean> => {
+ const result = await onReact?.(msg, reaction);
+ if (result?.answered) setAnswered((prev) => new Set(prev).add(msg.id));
+ return result ? result.ok : true;
+ };
const toggleThought = (id: string) => {
setOpenThoughts((prev) => ({ ...prev, [id]: !prev[id] }));
@@ -781,7 +861,14 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (!canSend || (isStreaming && discussionState?.inProgress)) return;
playSfx('click');
stickRef.current = true;
- onSendMessage(inputVal.trim(), readyAttachments(uploads));
+ const replying = replyTo;
+ const sent = onSendMessage(inputVal.trim(), readyAttachments(uploads), replying ? { replyTo: replying } : undefined);
+ setReplyTo(null);
+ // A send that fails keeps the reply, unless the person has moved on to another one.
+ if (replying && sent && typeof (sent as Promise<unknown>).then === 'function')
+ void (sent as Promise<boolean | void>).then((ok) => {
+ if (ok === false) setReplyTo((now) => now ?? replying);
+ });
// The bots this goes to blink once, so you see who received it.
recipientsOf(inputVal, activeKwants, home?.kind === 'bot' ? home.bot?.id : undefined).forEach(moodNoticed);
setInputVal('');
@@ -821,6 +908,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
}
+ if (e.key === 'Escape' && replyTo) {
+ e.preventDefault();
+ setReplyTo(null);
+ return;
+ }
+
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit();
@@ -983,6 +1076,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
const text = shownDecisions ? shownDecisions.text : msg.text;
const workAhead = isUser ? null : parseWorkAhead(msg.meta);
const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
+ const replyQuote = isUser ? replyRefOf(msg.reply_to) : null;
// Whose mood the reply header shows (Pixel's AvatarMood, drawn by ModernAvatar given a kwantId):
// Laya's pick, else this bot chat's bot, else the team member with that name. Unknown: no mood.
const replyKwantId = isUser
@@ -993,8 +1087,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div
key={msg.id}
data-message-id={msg.id}
- className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''} ${
- flashId === msg.id ? 'kw-flash' : ''
+ tabIndex={-1}
+ className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl focus:outline-none ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''} ${
+ flashId === msg.id ? (flashKind === 'quote' ? 'kw-flash-quote' : 'kw-flash') : ''
} ${freshTrack.current.fresh.has(msg.id) ? 'kws-in' : ''}`}
>
{/* Phones show the avatar inside the name line instead, so the bubble gets the full width */}
@@ -1094,7 +1189,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
data-work-ahead={workAhead ? '' : undefined}
>
{isUser ? (
- <div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>
+ <>
+ {replyQuote && (
+ <ReplyQuote reply={replyQuote} botName={botNameOf(replyQuote.sender_id, activeKwants)} onOpen={() => showOriginal(replyQuote.id)} />
+ )}
+ <div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>
+ </>
) : workAhead ? (
<WorkAheadBody messageId={msg.id} text={text} />
) : (
@@ -1146,6 +1246,19 @@ export const ChatView: React.FC<ChatViewProps> = ({
</>
)}
</button>
+ {msg.sender_role === 'kwant' && !workAhead && !msg.id.startsWith('temp-') && (
+ <>
+ {onReact && (
+ <ReactionButtons
+ messageId={msg.id}
+ reaction={reactionOf(msg.reaction)}
+ asks={msg.id === questionId && !answered.has(msg.id)}
+ onReact={(r) => react(msg, r)}
+ />
+ )}
+ <ReplyButton botName={displayName} active={replyTo?.id === msg.id} onReply={() => startReply(msg)} />
+ </>
+ )}
{msg.results != null && <SmartActionsSlot messageId={msg.id} />}
</div>
)}
@@ -1597,6 +1710,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
<Paperclip size={15} aria-hidden="true" /> Drop files to attach
</div>
)}
+ {replyTo && (
+ <ReplyChip
+ key={replyTo.id}
+ botName={replyBotName(replyTo)}
+ excerpt={excerptOf(replyTo.text, 200)}
+ onOpen={() => showOriginal(replyTo.id)}
+ onCancel={cancelReply}
+ />
+ )}
{(uploads.length > 0 || uploadNote) && (
<div className="basis-full min-w-0 px-1 pt-0.5 space-y-1.5">
{uploads.length > 0 && (
diff --git a/frontend/src/components/MessageReactions.tsx b/frontend/src/components/MessageReactions.tsx
new file mode 100644
index 00000000..ccd21f8a
--- /dev/null
+++ b/frontend/src/components/MessageReactions.tsx
@@ -0,0 +1,192 @@
+import { useEffect, useState } from 'react';
+import { Reply, ThumbsDown, ThumbsUp, X } from 'lucide-react';
+import { Reaction, ReplyRef, nextReaction, reactionLabels } from '../reactReply';
+
+// Thumbs and Reply on a bot message, the "Replying to" chip in the composer, and the quote in the
+// person's bubble. Look and states: react-reply/design.md (Mira); behaviour: contract.md §1 and §3.
+
+/** Ghost buttons, quieter than the Copy chip; 44 px on phones, 36 px from `sm`. */
+export const reactClass =
+ 'inline-flex items-center justify-center gap-1.5 min-h-11 min-w-11 sm:min-h-9 sm:min-w-9 px-2 rounded-lg border border-transparent text-xs font-medium text-zinc-400 hover:text-zinc-100 hover:bg-white/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 transition-colors duration-150 motion-reduce:transition-none cursor-pointer';
+const SELECTED: Record<Reaction, string> = {
+ up: '!text-sky-200 bg-sky-400/15 !border-sky-400/40 hover:!bg-sky-400/20 hover:!text-sky-100',
+ down: '!text-zinc-100 bg-white/[0.10] !border-white/20 hover:!bg-white/[0.14]',
+};
+
+/** A short note that removes itself, for "Not saved" and "not loaded here". */
+function useBriefNote(ms = 4000) {
+ const [note, setNote] = useState<{ text: string; n: number } | null>(null);
+ useEffect(() => {
+ if (!note) return;
+ const t = setTimeout(() => setNote(null), ms);
+ return () => clearTimeout(t);
+ }, [note, ms]);
+ return [note?.text ?? null, (text: string) => setNote((p) => ({ text, n: (p?.n ?? 0) + 1 }))] as const;
+}
+
+export function ReactionButtons({
+ messageId,
+ reaction,
+ asks,
+ onReact,
+}: {
+ messageId: string;
+ reaction: Reaction | null;
+ /** This is the bot's newest message and it asks something: a thumb is a yes or no. */
+ asks: boolean;
+ /** Resolves false when the save failed (the parent has already rolled the reaction back). */
+ onReact: (reaction: Reaction | null) => Promise<boolean> | void;
+}) {
+ // The pop plays on the icon of the thumb just selected; a new key replays it on the next select.
+ const [pop, setPop] = useState<{ which: Reaction; n: number } | null>(null);
+ const [failed, showFailed] = useBriefNote();
+ const labels = reactionLabels(asks);
+
+ const press = async (which: Reaction) => {
+ const next = nextReaction(reaction, which);
+ if (next) setPop((p) => ({ which: next, n: (p?.n ?? 0) + 1 }));
+ else setPop(null);
+ const ok = await onReact(next);
+ if (ok === false) {
+ setPop(null);
+ showFailed('Not saved. Try again.');
+ }
+ };
+
+ const thumb = (which: Reaction) => {
+ const on = reaction === which;
+ const Icon = which === 'up' ? ThumbsUp : ThumbsDown;
+ const popping = pop?.which === which;
+ return (
+ <button
+ type="button"
+ aria-pressed={on}
+ aria-label={labels[which]}
+ title={on ? `${labels[which]} · click to undo` : labels[which]}
+ data-reaction={which}
+ onClick={() => press(which)}
+ className={`${reactClass} ${on ? SELECTED[which] : ''} ${popping ? 'kw-react-pop' : ''} ${which === 'down' ? 'kw-react-down' : ''}`}
+ >
+ <Icon key={popping ? pop.n : 0} size={15} strokeWidth={2} aria-hidden="true" fill={on ? 'currentColor' : 'none'} />
+ </button>
+ );
+ };
+
+ return (
+ <>
+ <div role="group" aria-label="React to this reply" className="flex items-center gap-1" data-message-reactions={messageId}>
+ {thumb('up')}
+ {thumb('down')}
+ </div>
+ {failed && (
+ <span role="status" className="text-meta text-bad">
+ {failed}
+ </span>
+ )}
+ </>
+ );
+}
+
+export function ReplyButton({ botName, active, onReply }: { botName: string; active: boolean; onReply: () => void }) {
+ return (
+ <button
+ type="button"
+ onClick={onReply}
+ className={`${reactClass} ${active ? '!text-sky-200' : ''}`}
+ aria-label={`Reply to ${botName}`}
+ title="Reply to this message"
+ data-reply-button
+ >
+ <Reply size={15} strokeWidth={2} aria-hidden="true" />
+ <span>Reply</span>
+ </button>
+ );
+}
+
+/** The first row of the composer while a reply is being written. */
+export function ReplyChip({
+ botName,
+ excerpt,
+ onOpen,
+ onCancel,
+}: {
+ botName: string;
+ excerpt: string;
+ onOpen: () => void;
+ onCancel: () => void;
+}) {
+ return (
+ <div
+ data-reply-chip
+ aria-live="polite"
+ className="basis-full min-w-0 flex items-center gap-2 pl-2.5 pr-1 py-1 rounded-xl border-l-2 border-sky-400 bg-white/[0.04] kw-fade-in motion-reduce:animate-none"
+ >
+ <Reply size={13} aria-hidden="true" className="shrink-0 text-sky-300" />
+ <button
+ type="button"
+ onClick={onOpen}
+ title={excerpt}
+ className="min-w-0 flex-1 flex items-baseline gap-1 text-left text-meta rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 cursor-pointer"
+ >
+ <span className="shrink-0 text-zinc-400">Replying to</span>
+ <span className="shrink-0 max-w-[40%] truncate font-semibold text-zinc-100">{botName}:</span>
+ <span className="min-w-0 truncate text-zinc-300">{excerpt}</span>
+ </button>
+ <button
+ type="button"
+ onClick={onCancel}
+ aria-label="Cancel reply"
+ title="Cancel reply (Esc)"
+ className="shrink-0 flex items-center justify-center h-11 w-11 sm:h-7 sm:w-7 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-white/[0.08] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 cursor-pointer"
+ >
+ <X size={14} aria-hidden="true" />
+ </button>
+ </div>
+ );
+}
+
+const quoteBox = 'mb-2 flex w-full min-w-0 items-center gap-1.5 rounded-lg border-l-2 border-sky-400/70 bg-white/[0.04] pl-2 pr-2.5 py-1 text-left text-meta';
+
+/** The one-line quote at the top of the person's bubble. */
+export function ReplyQuote({
+ reply,
+ botName,
+ onOpen,
+}: {
+ reply: ReplyRef;
+ botName: string;
+ /** False when the original isn't loaded in this chat; the quote then says so instead of scrolling. */
+ onOpen: () => boolean;
+}) {
+ const [note, showNote] = useBriefNote();
+ if (reply.missing)
+ return (
+ <div data-reply-quote={reply.id} className={quoteBox}>
+ <Reply size={12} aria-hidden="true" className="shrink-0 text-sky-300" />
+ <span className="italic text-zinc-300">Original message was deleted</span>
+ </div>
+ );
+ const excerpt = reply.excerpt ?? '';
+ return (
+ <>
+ <button
+ type="button"
+ data-reply-quote={reply.id}
+ onClick={() => {
+ if (!onOpen()) showNote("That message isn't loaded here.");
+ }}
+ aria-label={`Replying to ${botName}${excerpt ? `: ${excerpt}` : ''}. Show the original`}
+ className={`${quoteBox} min-h-11 sm:min-h-0 hover:bg-white/[0.07] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 transition-colors duration-150 motion-reduce:transition-none cursor-pointer`}
+ >
+ <Reply size={12} aria-hidden="true" className="shrink-0 text-sky-300" />
+ <span className="shrink-0 max-w-[40%] truncate font-semibold text-zinc-100">{botName}</span>
+ {excerpt && <span className="min-w-0 truncate text-zinc-300">{excerpt}</span>}
+ </button>
+ {note && (
+ <span role="status" className="block -mt-1 mb-2 text-meta text-zinc-300">
+ {note}
+ </span>
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/reactReply.ts b/frontend/src/reactReply.ts
new file mode 100644
index 00000000..250b63fd
--- /dev/null
+++ b/frontend/src/reactReply.ts
@@ -0,0 +1,145 @@
+// Reactions and replies on bot messages (react-reply contract, section 3).
+// Pure helpers, so the toggle, the excerpt and the save-with-rollback are testable without a DOM.
+
+export type Reaction = 'up' | 'down';
+
+/** What a reply points at: the server's shape, or a target that was deleted. */
+export interface ReplyRef {
+ id: string;
+ sender_role?: string;
+ sender_id?: string;
+ excerpt?: string;
+ missing?: boolean;
+}
+
+/** Older servers (before the backend PR) leave both fields out; anything unexpected reads as none. */
+export function reactionOf(value: unknown): Reaction | null {
+ return value === 'up' || value === 'down' ? value : null;
+}
+
+export function replyRefOf(value: unknown): ReplyRef | null {
+ if (!value || typeof value !== 'object') return null;
+ const v = value as Record<string, unknown>;
+ if (typeof v.id !== 'string' || !v.id) return null;
+ if (v.missing === true) return { id: v.id, missing: true };
+ return {
+ id: v.id,
+ sender_role: typeof v.sender_role === 'string' ? v.sender_role : undefined,
+ sender_id: typeof v.sender_id === 'string' ? v.sender_id : undefined,
+ excerpt: typeof v.excerpt === 'string' ? v.excerpt : '',
+ };
+}
+
+/** Pressing the selected reaction clears it; pressing the other one switches. */
+export function nextReaction(current: Reaction | null, pressed: Reaction): Reaction | null {
+ return current === pressed ? null : pressed;
+}
+
+/**
+ * One line of a message for the reply chip and the optimistic quote: markdown marks dropped,
+ * whitespace folded, cut at `max` characters with an ellipsis. Display only; the server's excerpt wins once it arrives.
+ */
+export function excerptOf(text: string, max = 120): string {
+ const plain = text
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/`([^`]*)`/g, '$1')
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, '')
+ .replace(/(\*\*|__|\*|_|~~)(?=\S)([^*_~]*?\S)\1/g, '$2')
+ .replace(/\s+/g, ' ')
+ .trim();
+ if (plain.length <= max) return plain;
+ return `${plain.slice(0, max - 1).trimEnd()}…`;
+}
+
+/** Who a message or quote is from, as the chat shows it: long ids (uuids) fall back to the chat's title. */
+export function senderLabel(senderRole: string | undefined, senderId: string | undefined, fallback: string): string {
+ if (senderRole === 'user') return 'You';
+ if (!senderId) return fallback;
+ return senderId.length > 20 ? fallback : senderId;
+}
+
+/** The reply a just-sent message carries until the server's own copy replaces it. */
+export function optimisticReplyRef(target: { id: string; sender_role: string; sender_id: string; text: string }): ReplyRef {
+ return { id: target.id, sender_role: target.sender_role, sender_id: target.sender_id, excerpt: excerptOf(target.text, 200) };
+}
+
+export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>;
+
+/** What a reaction save came to; `answered` means it started a turn as the person's yes or no. */
+export interface ReactResult {
+ ok: boolean;
+ answered: boolean;
+ error?: string;
+}
+
+/**
+ * Saves a reaction. Resolves to the server's value and whether it answered the bot's question
+ * (servers before the backend PR leave `answered` out: read as false), or throws with a short reason.
+ */
+export async function saveReaction(
+ fetcher: FetchLike,
+ messageId: string,
+ reaction: Reaction | null,
+): Promise<{ reaction: Reaction | null; answered: boolean }> {
+ const res = await fetcher(`/api/messages/${encodeURIComponent(messageId)}/reaction`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ reaction }),
+ });
+ if (!res.ok) {
+ let reason = res.status === 404 ? 'That message is gone.' : `HTTP ${res.status}`;
+ try {
+ const data = (await res.json()) as { error?: unknown };
+ if (typeof data?.error === 'string' && data.error) reason = data.error;
+ } catch {
+ // no JSON body
+ }
+ throw new Error(reason);
+ }
+ const data = (await res.json().catch(() => null)) as { reaction?: unknown; answered?: unknown } | null;
+ return {
+ reaction: data && 'reaction' in data ? reactionOf(data.reaction) : reaction,
+ answered: data?.answered === true,
+ };
+}
+
+/** The last paragraph has a question mark: the server's own test for "this message asks something". */
+export function endsWithQuestion(text: string): boolean {
+ const paras = text
+ .split(/\n\s*\n/)
+ .map((p) => p.trim())
+ .filter(Boolean);
+ return (paras[paras.length - 1] ?? '').includes('?');
+}
+
+/**
+ * The id of the bot message a thumb would answer: the newest message from a bot, with nothing from the
+ * person after it, whose last paragraph asks something. Null while a reply is running.
+ */
+export function questionMessageId(
+ messages: ReadonlyArray<{ id: string; sender_role: string; text: string }>,
+ running: boolean,
+): string | null {
+ if (running) return null;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const m = messages[i];
+ if (m.sender_role === 'user') return null;
+ if (m.sender_role === 'kwant') return !m.id.startsWith('temp-') && endsWithQuestion(m.text) ? m.id : null;
+ }
+ return null;
+}
+
+/** The two thumbs' words: a yes or no on the bot's open question, otherwise feedback. */
+export function reactionLabels(asks: boolean): Record<Reaction, string> {
+ return asks ? { up: 'Yes, go ahead', down: 'No' } : { up: 'Good reply', down: 'Not helpful' };
+}
+
+/** A bot's name for a quote or the chip: from the bot list by id or name, else a short sender id, else "a bot". */
+export function botNameOf(senderId: string | undefined, bots: ReadonlyArray<{ id: string; name: string }>): string {
+ if (!senderId) return 'a bot';
+ const known = bots.find((b) => b.id === senderId || b.name === senderId);
+ if (known) return known.name;
+ return senderId.length > 20 ? 'a bot' : senderId;
+}
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
index 609f8d3f..2f030a96 100644
--- a/frontend/src/styles/modern.css
+++ b/frontend/src/styles/modern.css
@@ -509,3 +509,35 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:
.kw-stage-in, .kw-scrim-in, .kw-pop-in { animation: none; }
.kw-veil-in { transition: none; }
}
+
+/* Reactions and Reply (react-reply design.md §1, §3). The pop is on the thumb's icon only, so the
+ button never changes size; the down thumb dips the other way. The quote's flash is a violet ring. */
+@keyframes kw-react-pop {
+ 0% { transform: scale(1) rotate(0deg); }
+ 45% { transform: scale(1.32) rotate(var(--kw-react-tilt, -12deg)); }
+ 75% { transform: scale(0.94) rotate(0deg); }
+ 100% { transform: scale(1) rotate(0deg); }
+}
+.kw-react-pop > svg {
+ transform-origin: 50% 70%;
+ animation: kw-react-pop 200ms cubic-bezier(0.34, 1.56, 0.64, 1) both;
+}
+.kw-react-down { --kw-react-tilt: 12deg; }
+
+@keyframes kw-flash-quote { 0%, 55% { opacity: 1; } 100% { opacity: 0; } }
+.kw-flash-quote { position: relative; }
+.kw-flash-quote::after {
+ content: '';
+ position: absolute;
+ inset: -4px;
+ border-radius: 14px;
+ pointer-events: none;
+ box-shadow: 0 0 0 2px rgb(157 143 255 / 0.7);
+ background: rgb(157 143 255 / 0.08);
+ animation: kw-flash-quote 1.6s var(--kw-ease, ease-out) both;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .kw-react-pop > svg { animation: none; }
+ .kw-flash-quote::after { animation: none; }
+}
diff --git a/frontend/tests/reactReply.test.mjs b/frontend/tests/reactReply.test.mjs
new file mode 100644
index 00000000..fa658966
--- /dev/null
+++ b/frontend/tests/reactReply.test.mjs
@@ -0,0 +1,300 @@
+// Thumbs and Reply on bot messages (react-reply contract §3): the toggle, the excerpt, the save with
+// rollback, and ChatView's chip, Esc, send and quote, rendered in JSDOM.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'CSS']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+if (!g.CSS) g.CSS = { escape: (s) => s };
+g.window.matchMedia = g.window.matchMedia || ((q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }));
+g.ResizeObserver = g.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
+g.IntersectionObserver = g.window.IntersectionObserver = class { observe() {} unobserve() {} disconnect() {} };
+g.window.HTMLElement.prototype.scrollIntoView = function () { g.__scrolled = this.getAttribute('data-message-id'); };
+g.fetch = g.window.fetch = async () => new Response('[]', { status: 200, headers: { 'Content-Type': 'application/json' } });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export * from './src/reactReply';
+ export { ChatView } from './src/components/ChatView';
+`);
+const { React, createRoot, flushSync } = m;
+const h = React.createElement;
+const settle = () => new Promise((r) => setImmediate(r));
+
+test('a pressed thumb clears; the other one switches', () => {
+ assert.equal(m.nextReaction(null, 'up'), 'up');
+ assert.equal(m.nextReaction('up', 'up'), null);
+ assert.equal(m.nextReaction('up', 'down'), 'down');
+ assert.equal(m.nextReaction('down', 'down'), null);
+});
+
+test('missing or odd reaction and reply_to read as none', () => {
+ assert.equal(m.reactionOf(undefined), null);
+ assert.equal(m.reactionOf('love'), null);
+ assert.equal(m.reactionOf('down'), 'down');
+ assert.equal(m.replyRefOf(undefined), null);
+ assert.equal(m.replyRefOf({}), null);
+ assert.deepEqual(m.replyRefOf({ id: 'a', missing: true }), { id: 'a', missing: true });
+ assert.deepEqual(m.replyRefOf({ id: 'a', sender_role: 'kwant', sender_id: 'Ada', excerpt: 'Hi' }), { id: 'a', sender_role: 'kwant', sender_id: 'Ada', excerpt: 'Hi' });
+});
+
+test('the excerpt is one plain line, cut with an ellipsis', () => {
+ assert.equal(m.excerptOf('# Plan\n\n- **Ship** the [fix](http://x) `now`'), 'Plan Ship the fix now');
+ assert.equal(m.excerptOf('```js\ncode()\n```\nAfter'), 'After');
+ const cut = m.excerptOf('word '.repeat(80), 40);
+ assert.equal(cut.length <= 40, true);
+ assert.equal(cut.endsWith('…'), true);
+ assert.equal(m.excerptOf('<b>tag</b>'), '<b>tag</b>', 'kept as text, never parsed');
+});
+
+test('names: uuids fall back to the chat title, the person is You', () => {
+ assert.equal(m.senderLabel('kwant', 'Ada', 'Chat'), 'Ada');
+ assert.equal(m.senderLabel('kwant', '4c6677dc-533e-4706-8028-4afa492d95a4', 'Chat'), 'Chat');
+ assert.equal(m.senderLabel('user', 'PlayerHero', 'Chat'), 'You');
+});
+
+test('saveReaction PUTs the contract body and reports failures', async () => {
+ const calls = [];
+ const ok = async (url, init) => (calls.push([url, init]), { ok: true, status: 200, json: async () => ({ message_id: 'm 1', reaction: 'up' }) });
+ assert.deepEqual(await m.saveReaction(ok, 'm 1', 'up'), { reaction: 'up', answered: false }, 'no `answered` (before the backend PR) reads as false');
+ const yes = async () => ({ ok: true, status: 200, json: async () => ({ message_id: 'm', reaction: 'up', answered: true }) });
+ assert.deepEqual(await m.saveReaction(yes, 'm', 'up'), { reaction: 'up', answered: true });
+ assert.equal(calls[0][0], '/api/messages/m%201/reaction');
+ assert.equal(calls[0][1].method, 'PUT');
+ assert.deepEqual(JSON.parse(calls[0][1].body), { reaction: 'up' });
+ await m.saveReaction(ok, 'x', null);
+ assert.deepEqual(JSON.parse(calls[1][1].body), { reaction: null });
+ const gone = async () => ({ ok: false, status: 404, json: async () => { throw new Error('no body'); } });
+ await assert.rejects(m.saveReaction(gone, 'x', 'up'), /gone/);
+ const bad = async () => ({ ok: false, status: 400, json: async () => ({ error: 'reactions are for bot messages' }) });
+ await assert.rejects(m.saveReaction(bad, 'x', 'up'), /bot messages/);
+});
+
+test('a thumb is a yes or no only on the newest bot message that asks something', () => {
+ assert.equal(m.endsWithQuestion('Done.\n\nShall I deploy it?'), true);
+ assert.equal(m.endsWithQuestion('Did it work? Yes.\n\nAll done.'), false, 'only the last paragraph counts');
+ const q = { id: 'q', sender_role: 'kwant', text: 'Ready. Go ahead?' };
+ const done = { id: 'd', sender_role: 'kwant', text: 'Done.' };
+ const you = { id: 'u', sender_role: 'user', text: 'ok?' };
+ const note = { id: 'n', sender_role: 'system', text: 'note' };
+ assert.equal(m.questionMessageId([done, q], false), 'q');
+ assert.equal(m.questionMessageId([q, note], false), 'q', 'system notes after it do not count');
+ assert.equal(m.questionMessageId([q, done], false), null, 'not the newest bot message');
+ assert.equal(m.questionMessageId([q, you], false), null, 'the person already answered');
+ assert.equal(m.questionMessageId([q], true), null, 'a reply is running');
+ assert.deepEqual(m.reactionLabels(true), { up: 'Yes, go ahead', down: 'No' });
+ assert.deepEqual(m.reactionLabels(false), { up: 'Good reply', down: 'Not helpful' });
+});
+
+test('bot names for quotes: from the list, else the short id, else "a bot"', () => {
+ const bots = [{ id: 'k1', name: 'Ada' }];
+ assert.equal(m.botNameOf('k1', bots), 'Ada');
+ assert.equal(m.botNameOf('Ada', bots), 'Ada');
+ assert.equal(m.botNameOf('Lin', bots), 'Lin');
+ assert.equal(m.botNameOf('4c6677dc-533e-4706-8028-4afa492d95a4', bots), 'a bot');
+ assert.equal(m.botNameOf(undefined, bots), 'a bot');
+});
+
+const bot = { id: 'b1', sender_role: 'kwant', sender_id: 'Ada', text: '**Plan**: ship the fix today' };
+const mine = { id: 'u1', sender_role: 'user', sender_id: 'PlayerHero', text: 'Do it', reply_to: { id: 'b1', sender_role: 'kwant', sender_id: 'Ada', excerpt: 'Plan: ship the fix today' } };
+const older = { id: 'u0', sender_role: 'user', sender_id: 'PlayerHero', text: 'Old', reply_to: { id: 'gone', missing: true } };
+const sys = { id: 's1', sender_role: 'system', sender_id: 'system', text: 'Note' };
+
+function mount(props) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const sent = [];
+ const reacts = [];
+ const base = {
+ title: 'Ada',
+ messages: [older, bot, mine, sys],
+ streamingText: '',
+ streamingThinking: '',
+ pendingApprovals: [],
+ isStreaming: false,
+ onSendMessage: (text, att, opts) => { sent.push({ text, opts }); return true; },
+ onReact: async (msg, r) => (reacts.push([msg.id, r]), g.__reactResult ?? { ok: true, answered: false }),
+ onResolveApproval: () => {},
+ contextKey: 'k1',
+ };
+ const render = (p) => flushSync(() => root.render(h(m.ChatView, { ...base, ...props, ...p })));
+ render({});
+ return { host, root, sent, reacts, render };
+}
+const type = (ta, value) => {
+ const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;
+ setter.call(ta, value);
+ ta.dispatchEvent(new window.Event('input', { bubbles: true }));
+};
+
+test('ChatView: thumbs only on bot messages, toggles with aria-pressed', async () => {
+ const v = mount({});
+ await settle();
+ const thumbs = v.host.querySelectorAll('[data-reaction]');
+ assert.equal(thumbs.length, 2, 'one bot message, two thumbs; none on the person or system notes');
+ const up = v.host.querySelector('[data-reaction="up"]');
+ assert.equal(up.getAttribute('aria-pressed'), 'false');
+ assert.equal(up.getAttribute('aria-label'), 'Good reply');
+ assert.equal(v.host.querySelector('[data-reaction="down"]').getAttribute('aria-label'), 'Not helpful');
+ assert.equal(up.closest('[role="group"]').getAttribute('aria-label'), 'React to this reply');
+ flushSync(() => up.click());
+ assert.deepEqual(v.reacts.at(-1), ['b1', 'up']);
+ v.render({ messages: [older, { ...bot, reaction: 'up' }, mine, sys] });
+ const up2 = v.host.querySelector('[data-reaction="up"]');
+ assert.equal(up2.getAttribute('aria-pressed'), 'true');
+ assert.equal(up2.getAttribute('title'), 'Good reply · click to undo');
+ flushSync(() => up2.click());
+ assert.deepEqual(v.reacts.at(-1), ['b1', null], 'pressing the selected thumb clears it');
+ flushSync(() => v.host.querySelector('[data-reaction="down"]').click());
+ assert.deepEqual(v.reacts.at(-1), ['b1', 'down']);
+ v.root.unmount();
+});
+
+test('ChatView: Reply opens the chip, Esc cancels, send carries the reply and clears it', async () => {
+ const v = mount({});
+ await settle();
+ const reply = [...v.host.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Reply to Ada');
+ assert.ok(reply);
+ flushSync(() => reply.click());
+ const chip = v.host.querySelector('[data-reply-chip]');
+ assert.ok(chip);
+ assert.match(chip.textContent, /Replying toAda:Plan: ship the fix today/);
+ assert.equal(chip.getAttribute('aria-live'), 'polite');
+ assert.equal(v.host.querySelector('form').querySelector('[data-reply-chip]'), chip, 'the chip is inside the composer');
+ assert.ok(reply.className.includes('text-sky-200'), 'the Reply being written is marked');
+ const ta = v.host.querySelector('textarea[data-composer]');
+ assert.equal(document.activeElement, ta, 'focus goes to the composer');
+ flushSync(() => ta.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
+ assert.equal(v.host.querySelector('[data-reply-chip]'), null, 'Esc cancels');
+
+ flushSync(() => reply.click());
+ flushSync(() => v.host.querySelector('[aria-label="Cancel reply"]').click());
+ assert.equal(v.host.querySelector('[data-reply-chip]'), null, 'the x cancels');
+
+ flushSync(() => reply.click());
+ flushSync(() => type(ta, 'Yes, go'));
+ flushSync(() => ta.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ assert.equal(v.sent.length, 1);
+ assert.equal(v.sent[0].text, 'Yes, go');
+ assert.equal(v.sent[0].opts.replyTo.id, 'b1');
+ assert.equal(v.host.querySelector('[data-reply-chip]'), null, 'cleared after send');
+
+ flushSync(() => type(ta, 'Plain'));
+ flushSync(() => ta.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ assert.equal(v.sent[1].opts, undefined, 'the next message is not a reply');
+ v.root.unmount();
+});
+
+test('ChatView: switching chats drops the reply', async () => {
+ const v = mount({});
+ await settle();
+ flushSync(() => [...v.host.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Reply to Ada').click());
+ assert.ok(v.host.querySelector('[data-reply-chip]'));
+ v.render({ contextKey: 'k2' });
+ await settle();
+ assert.equal(v.host.querySelector('[data-reply-chip]'), null);
+ v.root.unmount();
+});
+
+test('ChatView: the quote in the bubble opens the original; a deleted one says so', async () => {
+ const v = mount({});
+ await settle();
+ const quote = v.host.querySelector('button[data-reply-quote="b1"]');
+ assert.ok(quote, 'a loaded original makes the quote a button');
+ assert.match(quote.textContent, /AdaPlan: ship the fix today/);
+ assert.match(quote.getAttribute('aria-label'), /Show the original$/);
+ g.__scrolled = null;
+ flushSync(() => quote.click());
+ await new Promise((r) => setTimeout(r, 30));
+ assert.equal(g.__scrolled, 'b1');
+ const row = v.host.querySelector('[data-message-id="b1"]');
+ assert.ok(row.className.includes('kw-flash-quote'), 'violet ring, not the amber search flash');
+ assert.equal(document.activeElement, row, 'focus lands on the original');
+ const gone = v.host.querySelector('[data-reply-quote="gone"]');
+ assert.equal(gone.tagName, 'DIV');
+ assert.match(gone.textContent, /deleted/);
+ v.root.unmount();
+});
+
+test('ChatView: a quote whose original is not loaded says so instead of scrolling', async () => {
+ const v = mount({ messages: [mine] });
+ await settle();
+ g.__scrolled = null;
+ flushSync(() => v.host.querySelector('[data-reply-quote="b1"]').click());
+ await settle();
+ assert.equal(g.__scrolled, null);
+ assert.match(v.host.querySelector('[role="status"]').textContent, /isn't loaded here/);
+ v.root.unmount();
+});
+
+test('ChatView: thumbs on the newest question read yes/no, and go back to feedback once answered', async () => {
+ const q = { id: 'q1', sender_role: 'kwant', sender_id: 'Ada', text: 'Tests pass.\n\nShall I open the PR?' };
+ const v = mount({ messages: [bot, q] });
+ await settle();
+ const upQ = v.host.querySelector('[data-message-reactions="q1"] [data-reaction="up"]');
+ assert.equal(upQ.getAttribute('aria-label'), 'Yes, go ahead');
+ assert.equal(v.host.querySelector('[data-message-reactions="q1"] [data-reaction="down"]').getAttribute('aria-label'), 'No');
+ assert.equal(v.host.querySelector('[data-message-reactions="b1"] [data-reaction="up"]').getAttribute('aria-label'), 'Good reply', 'older messages are feedback');
+ g.__reactResult = { ok: true, answered: true };
+ flushSync(() => upQ.click());
+ await settle();
+ await settle();
+ g.__reactResult = undefined;
+ assert.equal(v.host.querySelector('[data-message-reactions="q1"] [data-reaction="up"]').getAttribute('aria-label'), 'Good reply');
+ v.render({ messages: [bot, q], isStreaming: true });
+ v.root.unmount();
+});
+
+test('ChatView: a failed save says "Not saved" next to the thumbs', async () => {
+ const v = mount({});
+ await settle();
+ g.__reactResult = { ok: false, answered: false, error: 'HTTP 500' };
+ flushSync(() => v.host.querySelector('[data-reaction="down"]').click());
+ await settle();
+ await settle();
+ g.__reactResult = undefined;
+ assert.match(v.host.querySelector('[data-message-reactions="b1"]').parentElement.textContent, /Not saved\. Try again\./);
+ v.root.unmount();
+});
+
+test('ChatView: a send that fails keeps the reply chip', async () => {
+ const v = mount({ onSendMessage: async () => false });
+ await settle();
+ flushSync(() => v.host.querySelector('[data-reply-button]').click());
+ const ta = v.host.querySelector('textarea[data-composer]');
+ flushSync(() => type(ta, 'Go'));
+ flushSync(() => ta.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
+ await settle();
+ await settle();
+ assert.ok(v.host.querySelector('[data-reply-chip]'));
+ v.root.unmount();
+});
+
+test('a message_added for a known bot message updates its thumbs (the backend sends reactions this way)', async () => {
+ const { readFileSync } = await import('node:fs');
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ // No invented reaction events: the full updated message arrives as message_added and replaces by id.
+ assert.doesNotMatch(app, /case '(reaction_updated|ReactionUpdated|message_reaction|MessageReaction|message_reaction_updated|MessageReactionUpdated)'/);
+ assert.match(app, /case 'message_added':[\s\S]*?if \(list\.some\(\(x\) => x\.id === m\.id\)\) \{\s*const replaced = list\.map\(\(x\) => \(x\.id === m\.id \? m : x\)\)/);
+ const v = mount({});
+ await settle();
+ assert.equal(v.host.querySelector('[data-reaction="down"]').getAttribute('aria-pressed'), 'false');
+ // What App does with the event: the same id is replaced by the server's copy.
+ const event = { type: 'message_added', data: { message: { ...bot, reaction: 'down' } } };
+ const list = [older, bot, mine, sys].map((x) => (x.id === event.data.message.id ? event.data.message : x));
+ v.render({ messages: list });
+ assert.equal(v.host.querySelector('[data-reaction="down"]').getAttribute('aria-pressed'), 'true');
+ assert.equal(v.host.querySelector('[data-reaction="up"]').getAttribute('aria-pressed'), 'false');
+ v.render({ messages: list.map((x) => (x.id === 'b1' ? { ...x, reaction: null } : x)) });
+ assert.equal(v.host.querySelector('[data-reaction="down"]').getAttribute('aria-pressed'), 'false', 'a cleared reaction from another window clears here');
+ v.root.unmount();
+});