"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ArrowDownIcon, ChevronRightIcon, PlayIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { joinDictation, useDictationTarget } from "@/components/dictation";
import { MessageResponse } from "@/components/ai-elements/message";
import { cn } from "@/lib/utils";
import {
buildAnswer,
coerceCorrectAnswer,
emptyDockSelection,
normalizeOptions,
resolveCorrect,
seededRandom,
shuffleOptions,
parseAskInput,
parseQuizInput,
toggleOption,
toggleOther,
type AnswerRequest,
type AskToolInput,
type DockSelection,
type QuestionAnswerData,
type QuestionData,
type QuestionMode,
type QuizToolInput,
type SelectMode,
type Phase3,
} from "@/src/core";
/**
* The question dock — a pending quiz/ask REPLACES the chat composer: the
* persistent bottom blob morphs into the question. Two voices meet here:
* the teacher's (question, options, explanation) and the learner's —
* "Your thinking", a labeled composer-twin field for dumping reasoning,
* with Submit docked inside it exactly like the chat composer's send.
*
* The thinking field is the transfer channel of the whole product (wave-2):
* never called "optional", Enter makes a NEWLINE (it is for dumping — soon
* dictated, not typed), submission is the button only, and its size scales
* with the phase (probing stays quick; teaching invites depth). The
* "Other…" option is an editable option ROW — circle + inline input,
* styled like its siblings — so picking Other never displaces thinking.
*
* Collapse behavior (scroll-up → slim bar) is owned by the DockOverlay in the
* chat view, which also owns the persistent shell and its height morph. This
* component is content only. The expanded form stays MOUNTED while collapsed
* (hidden, not unmounted) so a half-made selection survives scrolling.
*/
export interface QuestionDockProps {
toolName: "quiz" | "ask_user_question";
toolCallId: string;
input: QuizToolInput | AskToolInput;
/** Collapse state, owned by the DockOverlay (it drives the shell's height morph). */
expanded: boolean;
/**
* Teach-phase check awaiting its reveal (vision §2, W5): while collapsed,
* the bar is the "Check your understanding" invitation instead of the
* scroll-collapse strip. Owned by the DockOverlay; false once the learner
* has revealed (afterwards the normal collapse machine rules apply).
*/
reveal?: boolean;
onExpand: () => void;
onSubmit: (output: QuestionAnswerData) => void;
/** Escape in a question field stops dictation (STT wave) — threaded
* from the page that owns the dictation hook. */
onEscape?: () => void;
/** The keyboard machine (wave B) is armed only while the dock is
* expanded — the collapsed bar keeps its native Enter-to-expand. */
active?: boolean;
/** Session phase at the question — scales the thinking field: probing
* stays quick (one row), teaching invites dumping (three rows). */
phase?: Phase3;
}
export function QuestionDock({
toolName,
toolCallId,
input,
expanded,
reveal = false,
onExpand,
onSubmit,
onEscape,
phase = "probe",
}: QuestionDockProps) {
// Parse, don't cast (src/core/tool-parts.ts): the model authored this
// input, and only the schema the tool declared vouches for its shape.
// The dock mounts on input-available parts (already validated at the
// bridge), so this is pure defense in depth — but it is STRUCTURAL now:
// anything that slips through renders the quiet fallback, never a
// crash on `.map` over model-authored bytes.
const parsed = toolName === "quiz" ? parseQuizInput(input) : parseAskInput(input);
if (!parsed) {
return (
This question arrived malformed — the transcript keeps the retry.
);
}
return (
<>
{!expanded && (
)}
>
);
}
/** A plain-text teaser of a question for the collapsed bar: unwrap math, flatten common LaTeX. */
function teaserText(q: string): string {
return q
.replace(/\\\(([\s\S]*?)\\\)/g, "$1") // \(...\) inline math
.replace(/\\\[([\s\S]*?)\\\]/g, "$1") // \[...\] display math
.replace(/\$\$?([^$]*)\$\$?/g, "$1") // legacy $...$ (pre-switch sessions)
.replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g, "$1/$2")
.replace(/\\([a-zA-Z]+)/g, "$1")
.replace(/[{}]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** The collapsed strip. Two species (W5): "collapsed" is the scroll minimization
* (kind chip + one-liner + Answer ↓); "reveal" is the teach-check invitation —
* a distinct, more inviting affordance, because it asks the learner to start
* something, not to resume something. */
export function QuestionDockBar({
toolName,
question,
onExpand,
variant = "collapsed",
}: {
toolName: "quiz" | "ask_user_question";
question: string;
onExpand: () => void;
variant?: "collapsed" | "reveal";
}) {
if (variant === "reveal") {
return (
);
}
return (
);
}
/** The expanded question: label, question, options, and the unified bottom row. */
function QuestionDockForm({
toolName,
toolCallId,
input,
phase = "probe",
active,
onSubmit,
onEscape,
}: Omit) {
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(() => {
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?.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]);
// The selection state machine lives in question-core (pure, tested):
// single-select displaces, multi-select coexists — picking the ask
// "Other…" row in a multi-select must never clear already-picked
// options, and picking an option must never clear a typed custom answer.
const [sel, setSel] = useState(emptyDockSelection());
// The learner's transfer channel — thinking, never "a note".
const [thinking, setThinking] = useState("");
const [other, setOther] = useState("");
const [text, setText] = useState("");
const selectMode: SelectMode = qd.mode === "multi-select" ? "multi-select" : "single-select";
// The PRIMARY dictation input (owner, STT round 1): while a question
// waits, dictated finals land HERE, never in the hidden composer — text
// mode owns "Your answer", select modes own "Your thinking". The claim
// is effect-scoped, so the question unmounting releases it and
// dictation falls back to the composer automatically.
useDictationTarget(
useCallback(
(t: string) => {
if (qd.mode === "text") setText((v) => joinDictation(v, t));
else setThinking((v) => joinDictation(v, t));
},
[qd.mode],
),
true,
);
const toggle = (idx: number) => setSel(toggleOption(selectMode, sel, idx));
const canSubmit =
qd.mode === "text"
? text.trim().length > 0
: sel.dontKnow || (sel.otherSelected && other.trim().length > 0) || sel.selected.size > 0;
const submit = () => {
if (!canSubmit) return;
const req: AnswerRequest = {
dontKnow: sel.dontKnow,
values: [...sel.selected].map((i) => qd.options[i]!.value),
other: sel.otherSelected ? other : undefined,
text: qd.mode === "text" ? text : undefined,
note: qd.mode !== "text" ? thinking.trim() || undefined : undefined,
};
onSubmit(buildAnswer(qd, req));
};
// Selecting Other never clears the thinking field — two channels, the
// answer and the reasoning behind it, side by side.
const selectOther = () => setSel(toggleOther(selectMode, sel));
/* ── The keyboard machine (shortcut wave B, owner rounds 2026-09-17) ──
↑/↓ walk EVERY answerable row in order — options first, then the
quiz's "I don't know" or the ask's "Other…" (whichever exists) —
CLAMPED at the ends, no wrap (owner: faster to navigate when the
walk stops at the last row). Space acts on the walked row exactly
like a click (multi toggles, single displaces; Other also focuses
its input for typing), Enter submits once an answer exists.
Tab toggles FOCUS between the thinking field and the answer rows
(owner round 3) — nothing else; Shift+Tab is NOT ours (the global
thinking-level cycle owns it). Two guards keep native behavior
intact: keys from a TYPING SURFACE keep their meaning (arrows move
the caret, space types), and modifier combos are never ours
(Alt+arrows cycle sessions — they must not ALSO walk the rows).
The listener is document-level and lives only while the dock is
expanded — collapsed, the bar's native Enter expands it. */
const [kbdIdx, setKbdIdx] = useState(null);
const rootRef = useRef(null);
const otherInputRef = useRef(null);
const thinkingRef = useRef(null);
// One row past the options is the trailing row: quiz → don't-know,
// ask → Other (a question never has both).
const optionCount = qd.mode === "text" ? 0 : qd.options.length;
const rowCount = qd.mode === "text" ? 0 : optionCount + 1;
const kbdAct = (idx: number) => {
if (idx < optionCount) toggle(idx);
else if (kind === "quiz")
setSel((prev) => ({ ...prev, selected: new Set(), otherSelected: false, dontKnow: !prev.dontKnow }));
else {
// Space on the ask's Other row (owner refinement round,
// 2026-09-24): SELECTING it focuses the input for typing, but
// the Space that DESELECTS an already-selected Other must never
// drop the user back into the typing field — the core's
// toggleOther has no single-select off-path (it displaces), so
// the off-path lives here: clear the pick, keep the typed text,
// focus stays where it is. Re-selecting is the way back into
// the field.
if (sel.otherSelected) setSel((prev) => ({ ...prev, otherSelected: false, dontKnow: false }));
else {
otherInputRef.current?.focus();
selectOther();
}
}
};
// Focus the walked row's focusable element — the Other row is a div,
// so its inline input is the focus target there.
const focusRow = (idx: number) => {
const row = rootRef.current?.querySelector(`[data-kbdrow="${idx}"]`) as HTMLElement | null;
if (!row) return;
const el = (row.querySelector("input") as HTMLElement | null) ?? row;
el.focus();
};
useEffect(() => {
if (!active || rowCount === 0) return;
const onKeyDown = (e: KeyboardEvent) => {
const t = e.target as HTMLElement | null;
const typing = !!t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable);
// Alt/Cmd/Ctrl combos are never ours (Alt+arrows cycle sessions
// globally — they must not ALSO walk the question rows).
const modded = e.altKey || e.metaKey || e.ctrlKey;
// Plain Tab toggles focus: rows → thinking, anything else → the
// walked (or first) row. Shift+Tab falls through (the global
// thinking-level cycle owns it), so the shift check matters.
if (e.key === "Tab" && !e.shiftKey && !modded) {
e.preventDefault();
e.stopPropagation();
if (t?.closest?.("[data-kbdrow]")) thinkingRef.current?.focus();
else {
const idx = kbdIdx ?? 0;
setKbdIdx(idx);
focusRow(idx);
}
return;
}
// Keys from a typing surface keep their meaning (arrows move
// the caret, space types).
if (typing || modded) return;
if (e.key === "ArrowDown") {
e.preventDefault();
const next = Math.min((kbdIdx ?? -1) + 1, rowCount - 1);
setKbdIdx(next);
// Focus follows the walk while the user is IN the rows (Tab
// put them there) so focused and walked never diverge.
if (t?.closest?.("[data-kbdrow]")) focusRow(next);
} else if (e.key === "ArrowUp") {
e.preventDefault();
const next = Math.max((kbdIdx ?? rowCount) - 1, 0);
setKbdIdx(next);
if (t?.closest?.("[data-kbdrow]")) focusRow(next);
} else if (e.key === " ") {
if (kbdIdx === null) return; // plain Space keeps scrolling the page
e.preventDefault();
kbdAct(kbdIdx);
} else if (e.key === "Enter") {
if (kbdIdx === null || !canSubmit) return;
e.preventDefault();
submit();
}
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
});
// Keep the walked row visible (the question area scrolls internally).
useEffect(() => {
if (kbdIdx === null) return;
rootRef.current
?.querySelector(`[data-kbdrow="${kbdIdx}"]`)
?.scrollIntoView({ block: "nearest" });
}, [kbdIdx]);
return (