UI iteration 3: question dock — pending questions morph the composer blob

- A pending quiz/ask now REPLACES the chat composer: one persistent
  rounded-2xl shell in the transcript overlay swaps contents (composer ↔
  question ↔ collapsed bar), never remounting — the structure a future
  grow-morph animation needs.
- Unified bottom row inside the question: the note field (select modes),
  the answer field (text-mode asks), or the Other text — one field, one
  'Submit answer' button, Enter submits.
- Collapse on scroll: uses useStickToBottomContext — scroll up and the
  dock folds to a slim bar (kind chip + LaTeX-flattened question teaser +
  'tap to answer'); click scrolls to bottom and re-expands. The expanded
  form stays mounted-hidden so a half-made selection survives.
- Pending/streaming tool parts no longer render inline; answered parts
  land in the transcript as graded cards on submit. Question generation
  shows a shimmer in the shell.
- Composer back to pure chat (no mode machinery); quiz-card.tsx and the
  pendingText/registerSubmit bridge deleted; render tests re-pointed at
  the dock (wrapped in StickToBottom).

Verified live: docked quiz submit (note+selection), ask-text Enter
submit, collapse/expand with selection survival, bar teaser text.
This commit is contained in:
Amos
2026-08-22 05:02:15 +03:00
parent 0baa00e418
commit cd789c11b1
6 changed files with 461 additions and 431 deletions
+67 -87
View File
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useChat } from "@ai-sdk/react"; import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from "ai"; import { DefaultChatTransport, isToolUIPart, lastAssistantMessageIsCompleteWithToolCalls } from "ai";
import { import {
Conversation, Conversation,
ConversationContent, ConversationContent,
@@ -13,26 +13,30 @@ import { Message, MessageContent, MessageResponse } from "@/components/ai-elemen
import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning"; import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";
import { Shimmer } from "@/components/ai-elements/shimmer"; import { Shimmer } from "@/components/ai-elements/shimmer";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { QuizCard, type QuizCardSubmitApi } from "@/components/quiz-card";
import { AnsweredCard } from "@/components/answered-card"; import { AnsweredCard } from "@/components/answered-card";
import { Composer, type ComposerMode } from "@/components/composer"; import { Composer } from "@/components/composer";
import { QuestionDock } from "@/components/question-dock";
import { SidebarToggle } from "@/components/sidebar"; import { SidebarToggle } from "@/components/sidebar";
import type { TeacherUIMessage } from "@/src/agent/ui-message"; import type { TeacherUIMessage } from "@/src/agent/ui-message";
import type { AskToolInput } from "@/src/agent/tools";
import type { QuestionAnswerData } from "@/src/core/question-core"; import type { QuestionAnswerData } from "@/src/core/question-core";
import { findPendingToolCall } from "@/src/core/pending"; import { findPendingToolCall } from "@/src/core/pending";
/** One width for everything: transcript, cards, composer all share this column. */ /** One width for everything: transcript, cards, and the bottom blob share this column. */
const COLUMN = "mx-auto w-full max-w-3xl px-4"; const COLUMN = "mx-auto w-full max-w-3xl px-4";
/** /**
* The teaching session. All chat state lives in useChat; the server persists * The teaching session. All chat state lives in useChat; the server persists
* the canonical transcript after every turn. A pending quiz/ask is just an * the canonical transcript after every turn.
* unanswered tool part — so reload/resume mid-question works for free.
* *
* The composer morphs while a question is pending (one text field on screen): * The bottom blob is ONE persistent shell (never remounts — this is what a
* select-mode question → the blob is the note field; free-text ask → the blob * future chat→question morph animation will animate). Its contents swap:
* is the answer field and its send submits via the card's registered API. * - no pending question → the chat Composer
* - question streaming in → "Preparing a question…" shimmer
* - pending quiz/ask → the QuestionDock (question + options + the
* unified note/answer field + Submit answer)
* A pending question is always the transcript tail (the lesson can't continue
* before it's answered), so docking it at the bottom loses nothing; on submit
* it lands in the transcript as an AnsweredCard.
*/ */
export function Chat({ export function Chat({
chatId, chatId,
@@ -67,43 +71,23 @@ export function Chat({
const pending = findPendingToolCall(messages); const pending = findPendingToolCall(messages);
const busy = status === "submitted" || status === "streaming"; const busy = status === "submitted" || status === "streaming";
// The single free-text field: chat input normally; note/answer while pending. // A tool call still streaming its input (question being generated): the
// blob shows a shimmer instead of the composer.
const questionStreaming =
!pending &&
messages.at(-1)?.role === "assistant" &&
(messages.at(-1)?.parts.some((p) => isToolUIPart(p) && p.state === "input-streaming") ?? false);
const [text, setText] = useState(""); const [text, setText] = useState("");
// The pending card registers its submit so the composer can send on Enter. const canSend = text.trim().length > 0 && !pending;
const cardApi = useRef<QuizCardSubmitApi | null>(null);
// Composer mode: free-text ask → "answer"; any other pending question → "note".
const pendingIsTextMode =
pending?.tool === "ask_user_question" &&
(() => {
const ask = pending.input as AskToolInput;
return ask.mode === "text" || !ask.options?.length;
})();
const mode: ComposerMode = pending ? (pendingIsTextMode ? "answer" : "note") : "chat";
// canSend mirrors the card's own predicate (text-mode: non-empty text).
// Reading cardApi.current here would lag one commit behind — the card
// re-registers its api in an effect AFTER this render pass.
const canSend = mode === "chat" ? text.trim().length > 0 && !pending : text.trim().length > 0;
const onSend = () => { const onSend = () => {
if (mode === "chat") { const t = text.trim();
const t = text.trim(); if (!t || busy || pending) return;
if (!t || busy || pending) return; setText("");
setText(""); void sendMessage({ text: t });
void sendMessage({ text: t });
} else if (mode === "answer") {
cardApi.current?.submit();
}
}; };
const hint =
mode === "note"
? "Answering the question above — text here becomes a note on your answer."
: mode === "answer"
? "Type your answer to the question above."
: null;
return ( return (
<div className="flex h-dvh flex-col"> <div className="flex h-dvh flex-col">
<header className="flex items-center gap-3 px-3 py-2"> <header className="flex items-center gap-3 px-3 py-2">
@@ -111,10 +95,10 @@ export function Chat({
<div className="min-w-0 flex-1 truncate font-medium">{title}</div> <div className="min-w-0 flex-1 truncate font-medium">{title}</div>
</header> </header>
{/* Transcript scrolls full-height; the composer floats on top. */} {/* Transcript scrolls full-height; the blob floats on top of it. */}
<div className="relative min-h-0 flex-1"> <div className="relative min-h-0 flex-1">
<Conversation className="h-full"> <Conversation className="h-full">
<ConversationContent className={`${COLUMN} gap-4 pt-4 pb-44`}> <ConversationContent className={`${COLUMN} gap-4 pt-4 ${pending || questionStreaming ? "pb-[32rem]" : "pb-44"}`}>
{messages.length === 0 && !busy && ( {messages.length === 0 && !busy && (
<ConversationEmptyState <ConversationEmptyState
title="New session" title="New session"
@@ -148,34 +132,12 @@ export function Chat({
return pi > 0 ? <Separator key={pi} className="my-3" /> : null; return pi > 0 ? <Separator key={pi} className="my-3" /> : null;
case "tool-quiz": case "tool-quiz":
case "tool-ask_user_question": { case "tool-ask_user_question": {
const tool = part.type === "tool-quiz" ? ("quiz" as const) : ("ask_user_question" as const); // Pending/streaming questions live in the dock, not the
// transcript; answered ones render as graded records.
if (part.state === "output-available") { if (part.state === "output-available") {
return <AnsweredCard key={pi} answer={part.output as QuestionAnswerData} />; return <AnsweredCard key={pi} answer={part.output as QuestionAnswerData} />;
} }
if (part.state === "input-available") { return null;
const isPending = pending?.toolCallId === part.toolCallId;
return (
<QuizCard
key={pi}
toolName={tool}
toolCallId={part.toolCallId}
input={part.input}
pendingText={isPending ? text : ""}
onPendingTextChange={isPending ? setText : () => {}}
registerSubmit={isPending ? (api) => (cardApi.current = api) : undefined}
onSubmit={(output) => {
setText("");
void addToolOutput({ tool, toolCallId: part.toolCallId, output });
}}
/>
);
}
// input-streaming: the question is still being generated
return (
<div key={pi} className="rounded-xl border bg-card p-4">
<Shimmer className="text-sm">Preparing a question…</Shimmer>
</div>
);
} }
default: default:
return null; return null;
@@ -194,28 +156,46 @@ export function Chat({
)} )}
</ConversationContent> </ConversationContent>
<ConversationScrollButton /> <ConversationScrollButton />
</Conversation>
{/* Floating composer: content fades out behind it. */} {/* The floating blob. ONE persistent shell — contents swap by mode.
<div className="pointer-events-none absolute inset-x-0 bottom-0"> Content fades out behind it. */}
<div className="h-24 bg-gradient-to-t from-background via-background/85 to-transparent" /> <div className="pointer-events-none absolute inset-x-0 bottom-0">
<div className="bg-background pb-4"> <div className="h-24 bg-gradient-to-t from-background via-background/85 to-transparent" />
<div className={COLUMN}> <div className="bg-background pb-4">
{hint && <div className="mb-1.5 text-center text-xs text-muted-foreground">{hint}</div>} <div className={COLUMN}>
<div className="pointer-events-auto"> <div className="pointer-events-auto rounded-2xl border bg-card shadow-lg">
<Composer {pending ? (
mode={mode} <QuestionDock
busy={busy} toolName={pending.tool as "quiz" | "ask_user_question"}
value={text} toolCallId={pending.toolCallId}
onChange={setText} input={pending.input as never}
onSend={onSend} onSubmit={(output) =>
onStop={() => stop()} void addToolOutput({
canSend={canSend} tool: pending.tool as "quiz" | "ask_user_question",
/> toolCallId: pending.toolCallId,
output,
})
}
/>
) : questionStreaming ? (
<div className="p-4">
<Shimmer className="text-sm">Preparing a question…</Shimmer>
</div>
) : (
<Composer
busy={busy}
value={text}
onChange={setText}
onSend={onSend}
onStop={() => stop()}
canSend={canSend}
/>
)}
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </Conversation>
</div> </div>
</div> </div>
); );
+28 -54
View File
@@ -4,31 +4,14 @@ import { CornerDownLeftIcon, SquareIcon } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
/** /**
* The floating composer blob. Sits on top of the transcript (the parent * The chat composer — content row ONLY (the persistent rounded shell lives in
* overlays it), persists at the bottom while scrolling, content fades out * the chat view's overlay, so the shell can later morph chat → question
* behind it. * without remounting).
* *
* Corner-radius math (concentric rounding — outer = inner + gap): * Corner-radius math (concentric with the shell): shell rounded-2xl (16px) −
* blob rounded-2xl (16px) − padding p-1.5 (6px) = button rounded-[10px]. * row padding p-1.5 (6px) = button rounded-[10px] = 25% of the 40px button.
* 10px is 25% of the 40px send button — matches the reference.
*
* Modes (one text field on screen, always):
* chat — normal message composer.
* note — a question is pending; text here becomes the answer's note.
* No send action (the card's Submit sends); Enter = newline.
* answer — a free-text ask is pending; this field IS the answer and the
* send button submits it.
*/ */
export type ComposerMode = "chat" | "note" | "answer";
const PLACEHOLDERS: Record<ComposerMode, string> = {
chat: "Ask, answer, or steer the lesson…",
note: "Add a note (optional) — anything you're unsure about",
answer: "Type your answer…",
};
export function Composer({ export function Composer({
mode,
busy, busy,
value, value,
onChange, onChange,
@@ -37,7 +20,6 @@ export function Composer({
canSend, canSend,
autoFocus, autoFocus,
}: { }: {
mode: ComposerMode;
busy: boolean; busy: boolean;
value: string; value: string;
onChange: (v: string) => void; onChange: (v: string) => void;
@@ -46,52 +28,44 @@ export function Composer({
canSend: boolean; canSend: boolean;
autoFocus?: boolean; autoFocus?: boolean;
}) { }) {
const showSend = mode !== "note";
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// Enter sends (chat/answer); Shift+Enter newline. Note mode: no send.
if (e.key === "Enter" && !e.shiftKey && mode !== "note") {
e.preventDefault();
if (busy) onStop();
else if (canSend) onSend();
}
};
return ( return (
<form <form
data-testid="composer" data-testid="composer"
data-mode={mode} className="flex items-end gap-1.5 p-1.5"
className="flex items-end gap-1.5 rounded-2xl border bg-card p-1.5 shadow-lg"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
if (busy) onStop(); if (busy) onStop();
else if (canSend && showSend) onSend(); else if (canSend) onSend();
}} }}
> >
<textarea <textarea
value={value} value={value}
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown} onKeyDown={(e) => {
placeholder={PLACEHOLDERS[mode]} if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
if (busy) onStop();
else if (canSend) onSend();
}
}}
placeholder="Ask, answer, or steer the lesson…"
autoFocus={autoFocus} autoFocus={autoFocus}
rows={1} rows={1}
className="field-sizing-content max-h-48 min-h-10 flex-1 resize-none bg-transparent px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground" className="field-sizing-content max-h-48 min-h-10 flex-1 resize-none bg-transparent px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground"
/> />
{showSend && ( <button
<button type="submit"
type="submit" aria-label={busy ? "Stop" : "Send"}
aria-label={busy ? "Stop" : "Send"} disabled={!busy && !canSend}
className={cn( className={cn(
"flex size-10 shrink-0 items-center justify-center rounded-[10px] transition-colors", "flex size-10 shrink-0 items-center justify-center rounded-[10px] transition-colors",
busy busy
? "bg-secondary text-foreground hover:bg-accent" ? "bg-secondary text-foreground hover:bg-accent"
: "bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-40", : "bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-40",
)} )}
disabled={!busy && !canSend} >
> {busy ? <SquareIcon className="size-4" /> : <CornerDownLeftIcon className="size-5" />}
{busy ? <SquareIcon className="size-4" /> : <CornerDownLeftIcon className="size-5" />} </button>
</button>
)}
</form> </form>
); );
} }
+325
View File
@@ -0,0 +1,325 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { ArrowDownIcon } from "lucide-react";
import { useStickToBottomContext } from "use-stick-to-bottom";
import { Button } from "@/components/ui/button";
import { MessageResponse } from "@/components/ai-elements/message";
import { cn } from "@/lib/utils";
import type { AskToolInput, QuizToolInput } from "@/src/agent/tools";
import {
buildAnswer,
coerceCorrectAnswer,
normalizeOptions,
resolveCorrect,
seededRandom,
shuffleOptions,
type AnswerRequest,
type QuestionAnswerData,
type QuestionData,
type QuestionMode,
} from "@/src/core/question-core";
/**
* The question dock — a pending quiz/ask REPLACES the chat composer: the
* persistent bottom blob morphs into the question. One unit, one action:
* the bottom field (note for select modes, the answer for free-text asks,
* "Other" text when Other is picked) plus the Submit button send together.
*
* Collapse: scroll up and the dock folds into a slim bar (question one-liner);
* click it (or scroll back to the bottom) to re-expand. The expanded content
* stays MOUNTED while collapsed (hidden, not unmounted) so a half-made
* selection survives scrolling.
*
* Rendered inside <Conversation> to read the stick-to-bottom context.
* Content only — the persistent shell lives in the chat view's overlay.
*/
export interface QuestionDockProps {
toolName: "quiz" | "ask_user_question";
toolCallId: string;
input: QuizToolInput | AskToolInput;
onSubmit: (output: QuestionAnswerData) => void;
}
export function QuestionDock({ toolName, toolCallId, input, onSubmit }: QuestionDockProps) {
const { isAtBottom, scrollToBottom } = useStickToBottomContext();
const [forceOpen, setForceOpen] = useState(false);
useEffect(() => {
if (!isAtBottom) setForceOpen(false);
}, [isAtBottom]);
const expanded = isAtBottom || forceOpen;
const expand = () => {
setForceOpen(true);
void scrollToBottom();
};
return (
<>
{!expanded && <QuestionDockBar toolName={toolName} question={input.question} onExpand={expand} />}
{/* Stays mounted while collapsed — selection state survives scrolling. */}
<div className={expanded ? undefined : "invisible h-0 overflow-hidden"}>
<QuestionDockForm
toolName={toolName}
toolCallId={toolCallId}
input={input}
onSubmit={onSubmit}
/>
</div>
</>
);
}
/** A plain-text teaser of a question for the collapsed bar: unwrap math, flatten common LaTeX. */
function teaserText(q: string): string {
return q
.replace(/\$\$?([^$]*)\$\$?/g, "$1")
.replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g, "$1/$2")
.replace(/\\([a-zA-Z]+)/g, "$1")
.replace(/[{}]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** The collapsed strip: kind chip + question one-liner; click to answer. */
export function QuestionDockBar({
toolName,
question,
onExpand,
}: {
toolName: "quiz" | "ask_user_question";
question: string;
onExpand: () => void;
}) {
return (
<button
type="button"
data-testid="question-dock-bar"
onClick={onExpand}
className="flex w-full items-center gap-2.5 px-4 py-2.5 text-left text-sm transition-colors hover:bg-accent/40"
>
<span className="shrink-0 text-xs font-medium uppercase tracking-wide text-muted-foreground">
{toolName === "quiz" ? "Quiz" : "Question"}
</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground">{teaserText(question)}</span>
<span className="flex shrink-0 items-center gap-1 text-xs font-medium">
Answer <ArrowDownIcon className="size-3.5" />
</span>
</button>
);
}
/** The expanded question: label, question, options, and the unified bottom row. */
function QuestionDockForm({ toolName, toolCallId, input, onSubmit }: QuestionDockProps) {
const kind = toolName === "quiz" ? ("quiz" as const) : ("ask" as const);
// Canonical QuestionData, built once per question. Quiz options are
// deterministically shuffled (seeded by toolCallId) so position never leaks
// correctness AND server/client render the same order (hydration-safe);
// the display order is snapshotted into the answer record at submit time.
const qd = useMemo<QuestionData>(() => {
const quizInput = kind === "quiz" ? (input as QuizToolInput) : null;
const askInput = kind === "ask" ? (input as AskToolInput) : null;
const multi = input.multiSelect === true;
const mode: QuestionMode =
kind === "quiz"
? multi
? "multi-select"
: "single-select"
: (askInput?.mode ?? (askInput?.options?.length ? (multi ? "multi-select" : "single-select") : "text"));
const options = normalizeOptions(
(quizInput?.options ?? askInput?.options ?? []) as { label: string; value?: string }[],
);
const ordered = kind === "quiz" && options.length > 0 ? shuffleOptions(options, seededRandom(toolCallId)) : options;
const q: QuestionData = {
id: toolCallId,
kind,
question: input.question,
context: input.details,
mode,
options: ordered,
createdAt: new Date().toISOString(),
};
if (quizInput) {
const resolved = resolveCorrect(coerceCorrectAnswer(quizInput.correctAnswer), ordered);
if (resolved.error) console.error("[quiz] correctAnswer did not resolve:", resolved.error);
q.correctIndices = resolved.indices;
q.explanation = quizInput.explanation;
}
return q;
}, [toolCallId, kind, input]);
const [selected, setSelected] = useState<Set<number>>(new Set()); // 0-based indices
const [dontKnow, setDontKnow] = useState(false);
const [showOther, setShowOther] = useState(false);
// The single free-text slot holds one of two values by mode.
const [note, setNote] = useState("");
const [other, setOther] = useState("");
const [text, setText] = useState("");
const toggle = (idx: number) => {
setDontKnow(false);
setShowOther(false);
setSelected((prev) => {
if (qd.mode === "multi-select") {
const next = new Set(prev);
if (next.has(idx)) next.delete(idx);
else next.add(idx);
return next;
}
return new Set([idx]);
});
};
const canSubmit =
qd.mode === "text"
? text.trim().length > 0
: dontKnow || (showOther && other.trim().length > 0) || selected.size > 0;
const submit = () => {
if (!canSubmit) return;
const req: AnswerRequest = {
dontKnow,
values: [...selected].map((i) => qd.options[i]!.value),
other: showOther ? other : undefined,
text: qd.mode === "text" ? text : undefined,
note: qd.mode !== "text" ? note.trim() || undefined : undefined,
};
onSubmit(buildAnswer(qd, req));
};
// The bottom field: answer (text mode) / own answer (Other) / note.
const field =
qd.mode === "text"
? { value: text, set: setText, placeholder: "Type your answer…" }
: showOther
? { value: other, set: setOther, placeholder: "Type your own answer…" }
: { value: note, set: setNote, placeholder: "Add a note (optional) — anything you're unsure about" };
return (
<div data-testid="question-dock">
{/* Question area — scrolls internally if very tall; the bottom row stays put. */}
<div className="max-h-[55dvh] overflow-y-auto px-4 pt-3">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
{kind === "quiz" ? "Quiz" : "Question"}
{qd.mode === "multi-select" && " · select all that apply"}
</div>
<div className="mb-3 font-medium">
<MessageResponse>{qd.question}</MessageResponse>
</div>
{qd.context && (
<div className="mb-3 text-sm text-muted-foreground">
<MessageResponse>{qd.context}</MessageResponse>
</div>
)}
{qd.mode !== "text" && (
<div className="flex flex-col gap-2 pb-1" role={qd.mode === "multi-select" ? "group" : "radiogroup"}>
{qd.options.map((opt, i) => {
const isSel = selected.has(i);
return (
<button
key={opt.value}
type="button"
role={qd.mode === "multi-select" ? "checkbox" : "radio"}
aria-checked={isSel}
onClick={() => toggle(i)}
className={cn(
"flex items-start gap-3 rounded-lg border px-3 py-2 text-left text-sm transition-colors",
isSel ? "border-primary bg-accent" : "hover:bg-accent/50",
)}
>
<span
className={cn(
"mt-0.5 flex size-4 shrink-0 items-center justify-center border",
qd.mode === "multi-select" ? "rounded-sm" : "rounded-full",
isSel ? "border-primary bg-primary text-primary-foreground" : "border-muted-foreground/40",
)}
>
{isSel && (
<span className={cn(qd.mode === "multi-select" ? "text-[10px]" : "size-1.5 rounded-full bg-current")}>
{qd.mode === "multi-select" ? "✓" : ""}
</span>
)}
</span>
<span>
<MessageResponse>{opt.label}</MessageResponse>
{opt.description && <span className="block text-xs text-muted-foreground">{opt.description}</span>}
</span>
</button>
);
})}
{kind === "quiz" && (
<button
type="button"
onClick={() => {
setSelected(new Set());
setShowOther(false);
setDontKnow((v) => !v);
}}
aria-pressed={dontKnow}
className={cn(
"rounded-lg border border-dashed px-3 py-2 text-left text-sm text-muted-foreground transition-colors",
dontKnow && "border-primary text-foreground",
)}
>
I don't know
</button>
)}
{kind === "ask" && (
<button
type="button"
onClick={() => {
setSelected(new Set());
setDontKnow(false);
setShowOther((v) => !v);
}}
aria-pressed={showOther}
className={cn(
"rounded-lg border border-dashed px-3 py-2 text-left text-sm text-muted-foreground transition-colors",
showOther && "border-primary text-foreground",
)}
>
Other…
</button>
)}
</div>
)}
</div>
{/* The unified bottom row — same slot and radii as the chat composer:
the text field plus Submit, which sends text + selection together. */}
<form
className="flex items-end gap-1.5 border-t border-border/60 p-1.5"
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<textarea
value={field.value}
onChange={(e) => field.set(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit();
}
}}
placeholder={field.placeholder}
rows={1}
className="field-sizing-content max-h-48 min-h-10 flex-1 resize-none bg-transparent px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground"
/>
<Button
type="submit"
disabled={!canSubmit}
className="h-10 shrink-0 rounded-[10px] px-3.5 text-sm font-medium"
>
Submit answer
</Button>
</form>
</div>
);
}
-242
View File
@@ -1,242 +0,0 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { MessageResponse } from "@/components/ai-elements/message";
import { cn } from "@/lib/utils";
import type { AskToolInput, QuizToolInput } from "@/src/agent/tools";
import {
buildAnswer,
coerceCorrectAnswer,
normalizeOptions,
resolveCorrect,
seededRandom,
shuffleOptions,
type AnswerRequest,
type QuestionAnswerData,
type QuestionData,
type QuestionMode,
} from "@/src/core/question-core";
/**
* The pending interaction card — renders when a quiz/ask tool part is in
* `input-available` state. Owns selection state (single source of truth —
* buttons, not native inputs), grades via question-core, and submits the
* structured answer record as the tool output.
*
* Quiz: graded (single/multi-select + "I don't know").
* Ask: not graded (single/multi-select + "Other" free text, or text mode).
*
* The card owns selection state; the free-text field lives in the composer
* blob (one text input on screen, never two). `pendingText` is the controlled
* text: the note for select modes, the answer for text mode. `registerSubmit`
* lets the composer trigger submit (Enter in answer mode).
*/
export interface QuizCardSubmitApi {
submit: () => void;
canSubmit: () => boolean;
}
export interface QuizCardProps {
toolName: "quiz" | "ask_user_question";
toolCallId: string;
input: QuizToolInput | AskToolInput;
onSubmit: (output: QuestionAnswerData) => void;
pendingText: string;
onPendingTextChange: (v: string) => void;
registerSubmit?: (api: QuizCardSubmitApi | null) => void;
}
export function QuizCard({ toolName, toolCallId, input, onSubmit, pendingText, onPendingTextChange, registerSubmit }: QuizCardProps) {
const kind = toolName === "quiz" ? ("quiz" as const) : ("ask" as const);
// Build the canonical QuestionData once per question. Quiz options are
// deterministically shuffled (seeded by toolCallId) so position never leaks
// correctness AND server/client render the same order (hydration-safe);
// the display order is snapshotted into the answer record at submit time.
const qd = useMemo<QuestionData>(() => {
const quizInput = kind === "quiz" ? (input as QuizToolInput) : null;
const askInput = kind === "ask" ? (input as AskToolInput) : null;
const multi = input.multiSelect === true;
const mode: QuestionMode =
kind === "quiz"
? multi
? "multi-select"
: "single-select"
: (askInput?.mode ?? (askInput?.options?.length ? (multi ? "multi-select" : "single-select") : "text"));
const options = normalizeOptions((quizInput?.options ?? askInput?.options ?? []) as { label: string; value?: string }[]);
const ordered = kind === "quiz" && options.length > 0 ? shuffleOptions(options, seededRandom(toolCallId)) : options;
const q: QuestionData = {
id: toolCallId,
kind,
question: input.question,
context: input.details,
mode,
options: ordered,
createdAt: new Date().toISOString(),
};
if (quizInput) {
const resolved = resolveCorrect(coerceCorrectAnswer(quizInput.correctAnswer), ordered);
if (resolved.error) console.error("[quiz] correctAnswer did not resolve:", resolved.error);
q.correctIndices = resolved.indices;
q.explanation = quizInput.explanation;
}
return q;
}, [toolCallId, kind, input]);
const [selected, setSelected] = useState<Set<number>>(new Set()); // 0-based indices
const [dontKnow, setDontKnow] = useState(false);
const [showOther, setShowOther] = useState(false);
const [other, setOther] = useState("");
// Free text lives in the composer blob: note (select modes) or answer (text mode).
const note = pendingText;
const text = pendingText;
const toggle = (idx: number) => {
setDontKnow(false);
setShowOther(false);
setSelected((prev) => {
if (qd.mode === "multi-select") {
const next = new Set(prev);
if (next.has(idx)) next.delete(idx);
else next.add(idx);
return next;
}
return new Set([idx]);
});
};
const pickDontKnow = () => {
setSelected(new Set());
setShowOther(false);
setDontKnow((v) => !v);
};
const pickOther = () => {
setSelected(new Set());
setDontKnow(false);
setShowOther(true);
};
const canSubmit =
qd.mode === "text"
? text.trim().length > 0
: dontKnow || (showOther && other.trim().length > 0) || selected.size > 0;
const submit = () => {
if (!canSubmit) return;
const req: AnswerRequest = {
dontKnow,
values: [...selected].map((i) => qd.options[i]!.value),
other: showOther ? other : undefined,
text: qd.mode === "text" ? text : undefined,
note: qd.mode !== "text" ? note.trim() || undefined : undefined,
};
onPendingTextChange("");
onSubmit(buildAnswer(qd, req));
};
// Let the composer blob submit on Enter (answer mode).
useEffect(() => {
if (!registerSubmit) return;
registerSubmit({ submit, canSubmit: () => canSubmit });
return () => registerSubmit(null);
});
return (
<div className="rounded-xl border bg-card p-4 text-card-foreground" data-testid="quiz-card">
<div className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
{kind === "quiz" ? "Quiz" : "Question"}
{qd.mode === "multi-select" && " · select all that apply"}
</div>
<div className="mb-3 font-medium">
<MessageResponse>{qd.question}</MessageResponse>
</div>
{qd.context && (
<div className="mb-3 text-sm text-muted-foreground">
<MessageResponse>{qd.context}</MessageResponse>
</div>
)}
{qd.mode !== "text" && (
<div className="flex flex-col gap-2" role={qd.mode === "multi-select" ? "group" : "radiogroup"}>
{qd.options.map((opt, i) => {
const isSel = selected.has(i);
return (
<button
key={opt.value}
type="button"
role={qd.mode === "multi-select" ? "checkbox" : "radio"}
aria-checked={isSel}
onClick={() => toggle(i)}
className={cn(
"flex items-start gap-3 rounded-lg border px-3 py-2 text-left text-sm transition-colors",
isSel ? "border-primary bg-accent" : "hover:bg-accent/50",
)}
>
<span
className={cn(
"mt-0.5 flex size-4 shrink-0 items-center justify-center border",
qd.mode === "multi-select" ? "rounded-sm" : "rounded-full",
isSel ? "border-primary bg-primary text-primary-foreground" : "border-muted-foreground/40",
)}
>
{isSel && <span className={cn(qd.mode === "multi-select" ? "text-[10px]" : "size-1.5 rounded-full bg-current")}>{qd.mode === "multi-select" ? "✓" : ""}</span>}
</span>
<span>
<MessageResponse>{opt.label}</MessageResponse>
{opt.description && <span className="block text-xs text-muted-foreground">{opt.description}</span>}
</span>
</button>
);
})}
{kind === "quiz" && (
<button
type="button"
onClick={pickDontKnow}
aria-pressed={dontKnow}
className={cn(
"rounded-lg border border-dashed px-3 py-2 text-left text-sm text-muted-foreground transition-colors",
dontKnow && "border-primary text-foreground",
)}
>
I don't know
</button>
)}
{kind === "ask" && (
<button
type="button"
onClick={pickOther}
aria-pressed={showOther}
className={cn(
"rounded-lg border border-dashed px-3 py-2 text-left text-sm text-muted-foreground transition-colors",
showOther && "border-primary text-foreground",
)}
>
Other…
</button>
)}
</div>
)}
{showOther && (
<textarea
className="mt-2 w-full rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring"
rows={2}
placeholder="Type your own answer…"
value={other}
onChange={(e) => setOther(e.target.value)}
/>
)}
<div className="mt-3 flex justify-end">
<Button size="sm" onClick={submit} disabled={!canSubmit}>
Submit answer
</Button>
</div>
</div>
);
}
+25 -23
View File
@@ -16,7 +16,8 @@ import assert from "node:assert/strict";
import { describe, it } from "node:test"; import { describe, it } from "node:test";
import { renderToStaticMarkup } from "react-dom/server"; import { renderToStaticMarkup } from "react-dom/server";
import { MessageResponse } from "../components/ai-elements/message.tsx"; import { MessageResponse } from "../components/ai-elements/message.tsx";
import { QuizCard } from "../components/quiz-card.tsx"; import { StickToBottom } from "use-stick-to-bottom";
import { QuestionDock } from "../components/question-dock.tsx";
import { AnsweredCard } from "../components/answered-card.tsx"; import { AnsweredCard } from "../components/answered-card.tsx";
import { buildAnswer, coerceCorrectAnswer, normalizeOptions, resolveCorrect, type QuestionData } from "../src/core/question-core.ts"; import { buildAnswer, coerceCorrectAnswer, normalizeOptions, resolveCorrect, type QuestionData } from "../src/core/question-core.ts";
@@ -41,40 +42,43 @@ function quizQD(): QuestionData {
}; };
} }
function renderDock(props: { toolName: "quiz" | "ask_user_question"; toolCallId: string; input: never; onSubmit?: () => void }) {
// The dock reads the stick-to-bottom scroll context; wrap it. In static
// render the context starts at isAtBottom=true → the expanded form renders.
return renderToStaticMarkup(
<StickToBottom><QuestionDock {...props} onSubmit={props.onSubmit ?? (() => {})} /></StickToBottom>,
);
}
describe("render smoke tests", () => { describe("render smoke tests", () => {
it("QuizCard renders question, options, and the automatic 'I don't know'", () => { it("QuizCard renders question, options, and the automatic 'I don't know'", () => {
const html = renderToStaticMarkup( const html = renderDock({ toolName: "quiz", toolCallId: "q1", input: quizInput as never });
<QuizCard toolName="quiz" toolCallId="q1" input={quizInput} onSubmit={() => {}} pendingText="" onPendingTextChange={() => {}} />,
);
assert.match(html, /Which planet is closest to the sun\?/); assert.match(html, /Which planet is closest to the sun\?/);
assert.match(html, /Mercury/); assert.match(html, /Mercury/);
assert.match(html, /I don&#x27;t know|I don't know/); assert.match(html, /I don&#x27;t know|I don't know/);
// The unified bottom row: note field + Submit answer live INSIDE the dock.
assert.match(html, /Add a note/, "note field is the dock's bottom row");
assert.match(html, /Submit answer/, "send becomes Submit answer");
// The v1 desync bug: options are buttons with ARIA roles, not native inputs. // The v1 desync bug: options are buttons with ARIA roles, not native inputs.
assert.ok(!html.includes('type="radio"'), "no native radio inputs"); assert.ok(!html.includes('type="radio"'), "no native radio inputs");
assert.ok(html.includes('role="radio"'), "button-based radio role present"); assert.ok(html.includes('role="radio"'), "button-based radio role present");
}); });
it("QuizCard never leaks the explanation or the correct answer before submit", () => { it("QuizCard never leaks the explanation or the correct answer before submit", () => {
const html = renderToStaticMarkup( const html = renderDock({ toolName: "quiz", toolCallId: "q1", input: quizInput as never });
<QuizCard toolName="quiz" toolCallId="q1" input={quizInput} onSubmit={() => {}} pendingText="" onPendingTextChange={() => {}} />,
);
assert.ok(!html.includes("innermost"), "explanation must not render pre-answer"); assert.ok(!html.includes("innermost"), "explanation must not render pre-answer");
}); });
it("ask card renders Other, no note field (note lives in the composer), no grading", () => { it("ask dock renders Other + note field, no grading affordance", () => {
const html = renderToStaticMarkup( const html = renderDock({
<QuizCard toolName: "ask_user_question",
toolName="ask_user_question" toolCallId: "a1",
toolCallId="a1" input: { question: "How confident are you?", options: [{ label: "Very" }, { label: "Somewhat" }] } as never,
input={{ question: "How confident are you?", options: [{ label: "Very" }, { label: "Somewhat" }] }} });
onSubmit={() => {}}
pendingText=""
onPendingTextChange={() => {}}
/>,
);
assert.match(html, /Other/); assert.match(html, /Other/);
assert.ok(!html.includes("I don&#x27;t know"), "ask has no 'I don't know'"); assert.ok(!html.includes("I don&#x27;t know"), "ask has no 'I don't know'");
assert.ok(!html.includes("Add a note"), "note field moved to the composer blob"); assert.match(html, /Add a note/, "ask select-mode also gets the note row");
}); });
it("AnsweredCard grades quiz answers (✓/✗ + explanation)", () => { it("AnsweredCard grades quiz answers (✓/✗ + explanation)", () => {
@@ -143,10 +147,8 @@ describe("math rendering (streamdown + KaTeX)", () => {
correctAnswer: "$2x$", correctAnswer: "$2x$",
explanation: "The power rule gives $\\frac{dy}{dx} = 2x$.", explanation: "The power rule gives $\\frac{dy}{dx} = 2x$.",
}; };
const pendingHtml = renderToStaticMarkup( const pendingHtml = renderDock({ toolName: "quiz", toolCallId: "m1", input: mathQuiz as never });
<QuizCard toolName="quiz" toolCallId="m1" input={mathQuiz} onSubmit={() => {}} pendingText="" onPendingTextChange={() => {}} />, assert.ok(pendingHtml.includes("katex"), "pending dock: question/options math renders");
);
assert.ok(pendingHtml.includes("katex"), "pending card: question/options math renders");
const options = normalizeOptions(mathQuiz.options); const options = normalizeOptions(mathQuiz.options);
const qd: QuestionData = { const qd: QuestionData = {
+16 -25
View File
@@ -1,6 +1,7 @@
/** /**
* Composer blob render tests — the morphing text field (chat / note / answer * Composer render tests — the chat input row (content only; the persistent
* modes), concentric corner radii, and the stop-while-busy button. * rounded shell lives in the chat view's overlay so it can morph into the
* question dock without remounting).
* *
* Same tsx classic-JSX shim as render-cards.test.tsx. * Same tsx classic-JSX shim as render-cards.test.tsx.
*/ */
@@ -12,10 +13,9 @@ import { describe, it } from "node:test";
import { renderToStaticMarkup } from "react-dom/server"; import { renderToStaticMarkup } from "react-dom/server";
import { Composer } from "../components/composer.tsx"; import { Composer } from "../components/composer.tsx";
function render(mode: "chat" | "note" | "answer", opts: { busy?: boolean; canSend?: boolean } = {}) { function render(opts: { busy?: boolean; canSend?: boolean } = {}) {
return renderToStaticMarkup( return renderToStaticMarkup(
<Composer <Composer
mode={mode}
busy={opts.busy ?? false} busy={opts.busy ?? false}
value="" value=""
onChange={() => {}} onChange={() => {}}
@@ -26,35 +26,26 @@ function render(mode: "chat" | "note" | "answer", opts: { busy?: boolean; canSen
); );
} }
describe("Composer blob", () => { describe("Composer", () => {
it("chat mode: chat placeholder + send button", () => { it("chat placeholder + send button", () => {
const html = render("chat"); const html = render();
assert.match(html, /Ask, answer, or steer the lesson/); assert.match(html, /Ask, answer, or steer the lesson/);
assert.ok(html.includes('aria-label="Send"'), "send button present"); assert.ok(html.includes('aria-label="Send"'), "send button present");
}); });
it("note mode: note placeholder and NO send button (card submits)", () => {
const html = render("note");
assert.match(html, /Add a note/);
assert.ok(!html.includes('aria-label="Send"'), "no send in note mode");
assert.ok(!html.includes('aria-label="Stop"'), "no stop either");
});
it("answer mode: answer placeholder + send button (submits the answer)", () => {
const html = render("answer");
assert.match(html, /Type your answer/);
assert.ok(html.includes('aria-label="Send"'), "send present in answer mode");
});
it("busy: send button becomes stop", () => { it("busy: send button becomes stop", () => {
const html = render("chat", { busy: true }); const html = render({ busy: true });
assert.ok(html.includes('aria-label="Stop"'), "stop replaces send while streaming"); assert.ok(html.includes('aria-label="Stop"'), "stop replaces send while streaming");
}); });
it("concentric corner radii: blob 16px, send 10px (25% of the 40px button)", () => { it("send button radius is 10px = 25% of the 40px button (concentric with the shell)", () => {
const html = render("chat"); const html = render();
assert.ok(html.includes("rounded-2xl"), "blob radius"); assert.ok(html.includes("rounded-[10px]"), "send radius = shell radius − row padding");
assert.ok(html.includes("rounded-[10px]"), "send radius = blob radius − padding");
assert.ok(html.includes("size-10"), "40px send button (10px = 25%)"); assert.ok(html.includes("size-10"), "40px send button (10px = 25%)");
}); });
it("disabled when nothing to send", () => {
const html = render({ canSend: false });
assert.ok(/aria-label="Send"[^>]*disabled|disabled[^>]*aria-label="Send"/.test(html), "send disabled");
});
}); });