v2 web interface: fix delivery races, real URLs, optimistic echo, thinking stream, button-based quiz UI

Root causes of the v1 browser bugs (all fixed + covered by deterministic tests):
- duplicated messages: per-socket snapshot + global broadcast marking raced;
  replaced with a single append-only entry log (exactly-once per socket,
  structurally) — covered by tests/server.test.ts
- delayed/missing echo of own messages: optimistic append with sending/failed
  status, reconciled by text when the real entry arrives
- no thinking shown: thinking deltas streamed live (kind: thinking) and
  persisted in assistant entries so they survive reloads
- ask answers graded as wrong: AnsweredCard no longer applies quiz grading to
  ask answers (no ✓/✗, no verdict)
- broken option selection: native radio/checkbox inputs fighting React state
  replaced with button-based options (single source of truth, one-click select)
- no URLs: History API routing — / home, /s/<file> per session (deep links,
  refresh, back button); session view resumes its file on mount
- lost connection = dead UI: exponential-backoff reconnect with full resync
- stick-to-bottom transcript with jump-to-latest pill

Server: startServer() with injectable runtime factory (scripted model in
tests); createSession returns file for routing; scripted model gained thinking
turns. 51 deterministic tests green.
This commit is contained in:
Amos
2026-08-22 00:57:16 +03:00
parent 25063b2a3e
commit 296cc1b7b6
14 changed files with 1485 additions and 441 deletions
+75 -116
View File
@@ -1,31 +1,45 @@
/**
* App — URL-routed shell.
*
* / home (session list, graph placeholder, new-session input)
* /s/<file> teaching session (own URL → deep links, refresh, back button)
*
* History API navigation (no router dependency). The server only ever has ONE
* active session, so we track which file we last activated this SPA lifetime:
* a session view mounts "already active" only for that file; anything else
* resumes via POST before connecting.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import type { ServerMessage, SessionSummary } from "../../src/shared/protocol.ts";
import type { NewSessionResponse, SessionSummary } from "../../src/shared/protocol.ts";
import { Home } from "./views/Home.tsx";
import { SessionView } from "./views/SessionView.tsx";
export interface LiveState {
connected: boolean;
entries: import("../../src/shared/protocol.ts").ClientEntry[];
pending: import("../../src/shared/protocol.ts").ClientQuestion | null;
liveText: string;
streaming: boolean;
error: string | null;
type Route = { view: "home" } | { view: "session"; file: string };
function parseRoute(): Route {
const m = location.pathname.match(/^\/s\/([^/]+)\/?$/);
if (m && m[1]) return { view: "session", file: decodeURIComponent(m[1]) };
return { view: "home" };
}
export function App() {
const [view, setView] = useState<"home" | "session">("home");
const [route, setRoute] = useState<Route>(parseRoute);
const [sessions, setSessions] = useState<SessionSummary[]>([]);
const [live, setLive] = useState<LiveState>({
connected: false,
entries: [],
pending: null,
liveText: "",
streaming: false,
error: null,
});
const [homeError, setHomeError] = useState<string | null>(null);
/** Session file last activated on the server during this SPA lifetime. */
const activeFileRef = useRef<string | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const liveTextRef = useRef("");
useEffect(() => {
const onPop = () => setRoute(parseRoute());
window.addEventListener("popstate", onPop);
return () => window.removeEventListener("popstate", onPop);
}, []);
const navigate = useCallback((to: string) => {
history.pushState(null, "", to);
setRoute(parseRoute());
}, []);
const refreshSessions = useCallback(async () => {
try {
@@ -38,116 +52,61 @@ export function App() {
}, []);
useEffect(() => {
void refreshSessions();
}, [refreshSessions]);
// ─── WebSocket lifecycle ──────────────────────────────────────────────
const connect = useCallback(() => {
const proto = location.protocol === "https:" ? "wss" : "ws";
const ws = new WebSocket(`${proto}://${location.host}/ws`);
wsRef.current = ws;
ws.onopen = () => setLive((s) => ({ ...s, connected: true, error: null }));
ws.onclose = () => setLive((s) => ({ ...s, connected: false }));
ws.onerror = () => setLive((s) => ({ ...s, connected: false, error: "connection error" }));
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data as string) as ServerMessage;
switch (msg.type) {
case "hello":
setLive((s) => ({ ...s, entries: [], pending: null, liveText: "", streaming: false }));
liveTextRef.current = "";
break;
case "backfill":
setLive((s) => ({ ...s, entries: msg.entries }));
break;
case "entry":
setLive((s) => ({ ...s, entries: [...s.entries, msg.entry] }));
if (msg.entry.type === "assistant") {
liveTextRef.current = "";
setLive((s) => ({ ...s, liveText: "" }));
}
break;
case "pending":
setLive((s) => ({ ...s, pending: msg.question }));
break;
case "delta":
liveTextRef.current += msg.delta;
setLive((s) => ({ ...s, liveText: liveTextRef.current }));
break;
case "streaming":
setLive((s) => ({ ...s, streaming: msg.value }));
break;
case "error":
setLive((s) => ({ ...s, error: msg.message }));
break;
}
};
}, []);
useEffect(() => {
if (view === "session") connect();
return () => {
wsRef.current?.close();
wsRef.current = null;
};
}, [view, connect]);
const send = useCallback((msg: unknown) => {
wsRef.current?.send(JSON.stringify(msg));
}, []);
// ─── actions ──────────────────────────────────────────────────────────
const startSession = useCallback(
async (topic: string) => {
const res = await fetch("/api/sessions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ topic }),
});
if (!res.ok) {
setLive((s) => ({ ...s, error: `failed to create session (${res.status})` }));
return;
}
setView("session");
void refreshSessions();
},
[refreshSessions],
);
const resumeSession = useCallback(
async (file: string) => {
const res = await fetch(`/api/sessions/${encodeURIComponent(file)}/resume`, { method: "POST" });
if (!res.ok) {
setLive((s) => ({ ...s, error: `failed to resume session (${res.status})` }));
return;
}
setView("session");
},
[],
);
if (route.view === "home") void refreshSessions();
}, [route, refreshSessions]);
const goHome = useCallback(() => {
wsRef.current?.close();
wsRef.current = null;
setView("home");
void refreshSessions();
}, [refreshSessions]);
navigate("/");
}, [navigate]);
if (view === "home") {
const startSession = useCallback(
async (topic: string) => {
setHomeError(null);
try {
const res = await fetch("/api/sessions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ topic }),
});
if (!res.ok) throw new Error(`failed to create session (${res.status})`);
const data = (await res.json()) as NewSessionResponse;
activeFileRef.current = data.file;
navigate(`/s/${encodeURIComponent(data.file)}`);
} catch (err) {
setHomeError(String(err instanceof Error ? err.message : err));
}
},
[navigate],
);
const openSession = useCallback(
(file: string) => {
// SessionView resumes the file itself if it isn't the active one.
navigate(`/s/${encodeURIComponent(file)}`);
},
[navigate],
);
if (route.view === "home") {
return (
<Home
sessions={sessions}
onStart={startSession}
onResume={resumeSession}
onOpen={openSession}
onRefresh={refreshSessions}
hasActive={live.connected}
error={homeError}
/>
);
}
return (
<SessionView
live={live}
send={send}
key={route.file}
file={route.file}
active={activeFileRef.current === route.file}
onActivated={(file) => {
activeFileRef.current = file;
}}
onHome={goHome}
/>
);
+206
View File
@@ -586,3 +586,209 @@ textarea:disabled {
background: var(--bg-raised);
border-radius: 6px;
}
/* ─── v2: transcript wrap + stick-to-bottom ─────────────────────────── */
.transcript-wrap {
flex: 1;
position: relative;
min-height: 0;
display: flex;
flex-direction: column;
}
.transcript-wrap .transcript {
flex: 1;
}
.jump-latest {
position: absolute;
bottom: 16px;
left: 50%;
transform: translateX(-50%);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text);
font-size: 12.5px;
padding: 6px 14px;
cursor: pointer;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.35);
z-index: 5;
}
.jump-latest:hover {
border-color: var(--accent);
}
/* ─── v2: message status (optimistic echo) ──────────────────────────── */
.msg.user.sending .msg-bubble {
opacity: 0.55;
}
.msg.user.failed .msg-bubble {
border-color: var(--error);
opacity: 0.8;
}
.msg-status {
font-size: 11.5px;
color: var(--text-muted);
align-self: flex-end;
margin: 4px 6px 0 0;
}
.msg-status.error {
color: var(--error);
}
/* ─── v2: thinking blocks ───────────────────────────────────────────── */
.thinking {
margin-bottom: 10px;
}
.thinking-toggle {
background: none;
border: none;
color: var(--text-muted);
font-size: 12.5px;
cursor: pointer;
padding: 2px 0;
display: inline-flex;
gap: 6px;
align-items: center;
}
.thinking-toggle:hover {
color: var(--text);
}
.thinking-caret {
font-size: 10px;
}
.thinking-body {
border-left: 2px solid var(--border);
padding: 4px 0 4px 12px;
margin-top: 6px;
color: var(--text-muted);
font-size: 13px;
line-height: 1.55;
white-space: pre-wrap;
max-height: 320px;
overflow-y: auto;
}
.thinking.streaming .thinking-body {
animation: thinking-pulse 1.6s ease-in-out infinite;
}
.thinking-pulse {
animation: thinking-pulse 1.6s ease-in-out infinite;
}
@keyframes thinking-pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.45;
}
}
/* ─── v2: live streaming text ───────────────────────────────────────── */
.live-text {
position: relative;
}
.stream-cursor {
display: inline-block;
width: 8px;
height: 15px;
background: var(--accent);
margin-left: 2px;
animation: cursor-blink 1s step-end infinite;
vertical-align: text-bottom;
}
@keyframes cursor-blink {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
/* ─── v2: button-based quiz options ─────────────────────────────────── */
.quiz-option {
display: flex;
width: 100%;
text-align: left;
align-items: flex-start;
gap: 10px;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 8px;
cursor: pointer;
background: var(--bg-raised);
font: inherit;
color: inherit;
transition: border-color 0.12s ease;
}
.quiz-option:hover {
border-color: var(--accent);
}
.quiz-option.selected {
border-color: var(--accent);
}
.quiz-marker {
flex: none;
width: 15px;
height: 15px;
border-radius: 50%;
border: 1.5px solid var(--border);
margin-top: 3px;
position: relative;
transition: border-color 0.12s ease;
background: transparent;
}
.quiz-option.multi .quiz-marker {
border-radius: 4px;
}
.quiz-option.selected .quiz-marker {
border-color: var(--accent);
}
.quiz-option.selected .quiz-marker::after {
content: "";
position: absolute;
inset: 3px;
border-radius: 50%;
background: var(--accent);
}
.quiz-option.multi.selected .quiz-marker::after {
border-radius: 1px;
}
.quiz-option.dont-know {
border-style: dashed;
color: var(--text-muted);
}
.quiz-option.dont-know.selected {
color: var(--text);
}
/* answered cards: option rows are static divs — keep old marker sizing */
.quiz-option.static .quiz-marker {
width: 15px;
height: 15px;
margin-top: 2px;
}
/* ─── v2: boot screen / reconnecting ────────────────────────────────── */
.boot-screen {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted);
font-size: 14px;
}
.boot-error {
color: var(--error);
}
+34 -18
View File
@@ -2,9 +2,12 @@ import type { QuestionAnswerData } from "../../../src/shared/protocol.ts";
/**
* AnsweredCard — static rendering of a question that has been answered.
* All the grading data (correct indices, explanation) is in the answer record
* (it lived in a custom entry, which never entered LLM context).
*
* QUIZ answers are graded (correct/incorrect marks, explanation).
* ASK answers are NOT graded — selections are highlighted, no ✓/✗, no verdict
* (the v1 bug: ask answers were run through quiz grading and showed as wrong).
*/
export function AnsweredCard({ data }: { data: QuestionAnswerData }) {
if (data.dismissed) {
return (
@@ -16,25 +19,41 @@ export function AnsweredCard({ data }: { data: QuestionAnswerData }) {
);
}
const isQuiz = data.kind === "quiz";
const selectedSet = new Set(data.answers.map((a) => a.index));
const correctSet = new Set(data.correctIndices ?? []);
const correctSet = new Set(isQuiz ? (data.correctIndices ?? []) : []);
return (
<div className={`quiz-card answered ${data.kind}`}>
<div className="quiz-kind">{data.kind === "quiz" ? "Quiz" : "Question"}</div>
<div className="quiz-kind">{isQuiz ? "Quiz" : "Question"}</div>
<div className="quiz-question">{data.questionText}</div>
{data.options && data.options.length > 0 && (
<div className="quiz-options">
{data.options.map((opt) => {
const isSelected = selectedSet.has(opt.index);
const isKey = correctSet.has(opt.index);
const isKey = isQuiz && correctSet.has(opt.index);
let cls = "";
if (data.dontKnow) cls = isKey ? "correct" : "";
else if (isSelected && isKey) cls = "correct selected";
else if (isSelected) cls = "wrong";
else if (isKey) cls = "correct";
const mark = isSelected ? (isKey || data.dontKnow ? "✓" : "✗") : isKey ? "✓" : "";
let mark = "";
if (isQuiz) {
if (data.dontKnow) {
cls = isKey ? "correct" : "";
mark = isKey ? "✓" : "";
} else if (isSelected && isKey) {
cls = "correct selected";
mark = "✓";
} else if (isSelected) {
cls = "wrong";
mark = "✗";
} else if (isKey) {
cls = "correct";
mark = "✓";
}
} else {
// ask: no grading — just show what was selected
cls = isSelected ? "selected" : "";
mark = isSelected ? "●" : "";
}
return (
<div key={opt.index} className={`quiz-option static ${cls}`}>
<span className="quiz-mark">{mark}</span>
@@ -45,26 +64,23 @@ export function AnsweredCard({ data }: { data: QuestionAnswerData }) {
);
})}
{data.other && (
<div className="quiz-option static">
<span className="quiz-mark">✓</span>
<div className={`quiz-option static ${isQuiz ? "" : "selected"}`}>
<span className="quiz-mark">{isQuiz ? "✓" : "●"}</span>
<span className="quiz-option-label">Other: {data.other}</span>
</div>
)}
</div>
)}
{(data.text || (!data.options?.length && !data.answers.length)) && data.text && (
<div className="quiz-text-answer">{data.text}</div>
)}
{data.other && !data.options?.length && <div className="quiz-text-answer">Other: {data.other}</div>}
{data.text && <div className="quiz-text-answer">{data.text}</div>}
{data.kind === "quiz" && (
{isQuiz && (
<div className={`quiz-verdict ${data.dontKnow ? "dont-know" : data.correct ? "correct" : "wrong"}`}>
{data.dontKnow ? "I don't know" : data.correct ? "Correct" : "Incorrect"}
</div>
)}
{data.note && <div className="quiz-note-display">Note: {data.note}</div>}
{data.kind === "quiz" && data.explanation && (
{isQuiz && data.explanation && (
<div className="quiz-explanation">{data.explanation}</div>
)}
</div>
+90
View File
@@ -0,0 +1,90 @@
/**
* Message components — one entry of the transcript.
*
* Assistant messages render as: thinking (collapsible) → tool chips → text.
* Thinking is streamed live in the session view (expanded while streaming,
* collapses when the message lands) and persisted in the entry, so it
* survives reloads and resumes.
*/
import { useEffect, useState } from "react";
import type { ClientToolCall } from "../../../src/shared/protocol.ts";
import { Markdown } from "./Markdown.tsx";
// ─── thinking ───────────────────────────────────────────────────────────────
export function ThinkingBlock({ text, streaming }: { text: string; streaming?: boolean }) {
const [open, setOpen] = useState(false);
// Auto-collapse when the stream finishes (expanded-while-live pattern).
useEffect(() => {
if (streaming) setOpen(true);
else setOpen(false);
}, [streaming]);
if (!text) return null;
return (
<div className={`thinking ${streaming ? "streaming" : ""}`}>
<button type="button" className="thinking-toggle" onClick={() => setOpen((v) => !v)}>
{streaming ? <span className="thinking-pulse">Thinking…</span> : <span>Thought process</span>}
{!streaming && <span className="thinking-caret">{open ? "▾" : "▸"}</span>}
</button>
{open && <div className="thinking-body">{text}</div>}
</div>
);
}
// ─── tool calls ─────────────────────────────────────────────────────────────
const TOOL_LABELS: Record<string, string> = {
quiz: "asked a quiz",
ask_user_question: "asked a question",
};
export function ToolChips({ toolCalls }: { toolCalls: ClientToolCall[] }) {
if (toolCalls.length === 0) return null;
return (
<div className="tool-chips">
{toolCalls.map((tc, i) => (
<div key={i} className="tool-chip">
<span className="tool-name">{TOOL_LABELS[tc.name] ?? tc.name}</span>
{typeof tc.args.question === "string" && tc.args.question && (
<span className="tool-arg"> {tc.args.question}</span>
)}
</div>
))}
</div>
);
}
// ─── user ───────────────────────────────────────────────────────────────────
export function UserMessage({ text, status }: { text: string; status?: "sending" | "failed" }) {
return (
<div className={`msg user ${status === "failed" ? "failed" : status === "sending" ? "sending" : ""}`}>
<div className="msg-bubble">{text}</div>
{status === "failed" && <div className="msg-status error">failed to send</div>}
{status === "sending" && <div className="msg-status">sending…</div>}
</div>
);
}
// ─── assistant ──────────────────────────────────────────────────────────────
export function AssistantMessage({
text,
thinking,
toolCalls,
}: {
text: string;
thinking?: string;
toolCalls: ClientToolCall[];
}) {
return (
<div className="msg assistant">
<ThinkingBlock text={thinking ?? ""} />
<ToolChips toolCalls={toolCalls} />
{text && <Markdown text={text} />}
</div>
);
}
+92 -67
View File
@@ -1,3 +1,16 @@
/**
* QuizCard — the interactive answer UI for a pending quiz/ask question.
*
* Options are BUTTONS with a custom marker: React state is the single source
* of truth for selection (no native radio/checkbox inputs fighting it — that
* desync was the v1 selection bug). One click anywhere on the row selects.
*
* Semantics mirror the terminal quiz:
* - single-select: exactly one of {options, Other (ask), I-don't-know (quiz)}
* - multi-select: toggle options; I-don't-know/Other are exclusive toggles
* - text mode (ask): free-form answer
*/
import { useMemo, useState } from "react";
import type { ClientQuestion } from "../../../src/shared/protocol.ts";
@@ -6,55 +19,64 @@ interface QuizCardProps {
send: (msg: unknown) => void;
}
/**
* QuizCard — the interactive answer UI for a pending quiz/ask question.
* Mirrors the terminal quiz semantics: single/multi-select, automatic
* "I don't know" (quiz only), "Other" free text (ask only), optional note.
* Grading happens server-side; the graded card arrives afterwards as a
* questionAnswered entry.
*/
export function QuizCard({ question, send }: QuizCardProps) {
const multi = question.mode === "multi-select";
const isQuiz = question.kind === "quiz";
const isText = question.mode === "text";
const [selected, setSelected] = useState<Set<string>>(new Set());
// Selection state — the ONLY source of truth.
const [selected, setSelected] = useState<string[]>([]);
const [dontKnow, setDontKnow] = useState(false);
const [otherSelected, setOtherSelected] = useState(false);
const [other, setOther] = useState("");
const [showOther, setShowOther] = useState(false);
const [text, setText] = useState("");
const [note, setNote] = useState("");
const pickOption = (value: string) => {
setDontKnow(false);
if (multi) {
setSelected((prev) => (prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value]));
} else {
setOtherSelected(false);
setSelected([value]);
}
};
const pickOther = () => {
if (multi) {
setOtherSelected((v) => !v);
} else {
setDontKnow(false);
setSelected([]);
setOtherSelected(true);
}
};
const pickDontKnow = () => {
if (dontKnow) {
setDontKnow(false);
} else {
setDontKnow(true);
setSelected([]);
setOtherSelected(false);
}
};
const canSubmit = useMemo(() => {
if (dontKnow) return true;
if (isText) return text.trim().length > 0;
if (showOther && other.trim()) return true;
return selected.size > 0;
}, [dontKnow, isText, text, showOther, other, selected]);
const toggle = (value: string) => {
setDontKnow(false);
setSelected((prev) => {
const next = new Set(multi ? prev : undefined);
if (multi) {
if (next.has(value)) next.delete(value);
else next.add(value);
} else {
next.clear();
next.add(value);
}
return next;
});
};
if (otherSelected && other.trim()) return true;
return selected.length > 0;
}, [dontKnow, isText, text, otherSelected, other, selected]);
const submit = () => {
if (!canSubmit) return;
send({
type: "answer",
questionId: question.id,
dontKnow,
values: [...selected],
other: showOther && other.trim() ? other.trim() : undefined,
dontKnow: dontKnow || undefined,
values: selected.length > 0 ? selected : undefined,
other: otherSelected && other.trim() ? other.trim() : undefined,
text: isText ? text.trim() : undefined,
note: note.trim() || undefined,
});
@@ -79,41 +101,45 @@ export function QuizCard({ question, send }: QuizCardProps) {
onChange={(e) => setText(e.target.value)}
/>
) : (
<div className="quiz-options">
{question.options.map((opt) => (
<label key={opt.value} className={`quiz-option ${selected.has(opt.value) ? "selected" : ""}`}>
<input
type={multi ? "checkbox" : "radio"}
name={question.id}
checked={selected.has(opt.value)}
onChange={() => toggle(opt.value)}
/>
<span className="quiz-option-label">
{opt.label}
{opt.description && <span className="quiz-option-desc">{opt.description}</span>}
</span>
</label>
))}
<div className="quiz-options" role="group" aria-label="options">
{question.options.map((opt) => {
const isSelected = selected.includes(opt.value);
return (
<button
key={opt.value}
type="button"
className={`quiz-option ${multi ? "multi" : "single"} ${isSelected ? "selected" : ""}`}
role={multi ? "checkbox" : "radio"}
aria-checked={isSelected}
onClick={() => pickOption(opt.value)}
>
<span className="quiz-marker" aria-hidden="true" />
<span className="quiz-option-label">
{opt.label}
{opt.description && <span className="quiz-option-desc">{opt.description}</span>}
</span>
</button>
);
})}
{!isQuiz && (
<label className={`quiz-option ${showOther ? "selected" : ""}`}>
<input
type={multi ? "checkbox" : "radio"}
name={question.id}
checked={showOther}
onChange={() => {
setDontKnow(false);
setShowOther((v) => !v);
}}
/>
<button
type="button"
className={`quiz-option ${multi ? "multi" : "single"} ${otherSelected ? "selected" : ""}`}
role={multi ? "checkbox" : "radio"}
aria-checked={otherSelected}
onClick={pickOther}
>
<span className="quiz-marker" aria-hidden="true" />
<span className="quiz-option-label">Other</span>
</label>
</button>
)}
{showOther && (
{otherSelected && (
<input
type="text"
className="quiz-other"
placeholder="Your custom answer…"
value={other}
autoFocus
onChange={(e) => setOther(e.target.value)}
/>
)}
@@ -121,17 +147,16 @@ export function QuizCard({ question, send }: QuizCardProps) {
)}
{isQuiz && (
<label className={`quiz-option dont-know ${dontKnow ? "selected" : ""}`}>
<input
type="checkbox"
checked={dontKnow}
onChange={() => {
setDontKnow((v) => !v);
if (!dontKnow) setSelected(new Set());
}}
/>
<button
type="button"
className={`quiz-option dont-know ${dontKnow ? "selected" : ""}`}
role="checkbox"
aria-checked={dontKnow}
onClick={pickDontKnow}
>
<span className="quiz-marker" aria-hidden="true" />
<span className="quiz-option-label">I don&apos;t know</span>
</label>
</button>
)}
<textarea
+43
View File
@@ -0,0 +1,43 @@
/**
* Transcript — the scrollable message list with stick-to-bottom behavior:
* auto-scrolls while the learner is at the bottom; if they scroll up to read,
* auto-scrolling pauses and a "jump to latest" pill appears.
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
export function Transcript({ children, scrollToken }: { children: ReactNode; scrollToken: string | number }) {
const ref = useRef<HTMLDivElement>(null);
const [pinned, setPinned] = useState(true);
const onScroll = () => {
const el = ref.current;
if (!el) return;
const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
setPinned(atBottom);
};
useEffect(() => {
const el = ref.current;
if (el && pinned) el.scrollTop = el.scrollHeight;
}, [scrollToken, pinned]);
const jumpToLatest = () => {
const el = ref.current;
if (el) el.scrollTop = el.scrollHeight;
setPinned(true);
};
return (
<div className="transcript-wrap">
<div className="transcript" ref={ref} onScroll={onScroll}>
{children}
</div>
{!pinned && (
<button type="button" className="jump-latest" onClick={jumpToLatest}>
↓ Jump to latest
</button>
)}
</div>
);
}
+191
View File
@@ -0,0 +1,191 @@
/**
* useSession — the interaction core of the session view.
*
* Owns the WebSocket lifecycle and the client-side message state machine,
* following the standard chat-UI patterns:
*
* - optimistic echo: a sent prompt renders instantly with status "sending";
* when the server's real entry arrives it REPLACES the optimistic copy
* (matched by text), flipping to a normal message. If a reconnect's
* backfill proves the message never landed, it flips to "failed".
* - reconnect: on drop, retry with exponential backoff; the server's
* hello+backfill on reconnect fully replaces local state (no dupes —
* the server guarantees exactly-once per socket).
* - streaming: thinking and text deltas accumulate in separate live
* buffers; when the assistant entry lands, the buffers reset.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import type { ClientEntry, ClientQuestion, ServerMessage } from "../../src/shared/protocol.ts";
export type MessageStatus = "sending" | "failed";
export type DisplayEntry =
| { type: "user"; id: string; text: string; status?: MessageStatus }
| Exclude<ClientEntry, { type: "user" }>;
export interface SessionState {
status: "connecting" | "open" | "reconnecting";
entries: DisplayEntry[];
liveThinking: string;
liveText: string;
streaming: boolean;
pending: ClientQuestion | null;
error: string | null;
}
const INITIAL: SessionState = {
status: "connecting",
entries: [],
liveThinking: "",
liveText: "",
streaming: false,
pending: null,
error: null,
};
function localId(): string {
return `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
export function useSession(): {
state: SessionState;
sendPrompt: (text: string) => void;
sendAnswer: (payload: Record<string, unknown>) => void;
sendDismiss: (questionId: string) => void;
sendAbort: () => void;
} {
const [state, setState] = useState<SessionState>(INITIAL);
const wsRef = useRef<WebSocket | null>(null);
const retryRef = useRef(0);
const aliveRef = useRef(true);
const connect = useCallback(() => {
if (!aliveRef.current) return;
const proto = location.protocol === "https:" ? "wss" : "ws";
const ws = new WebSocket(`${proto}://${location.host}/ws`);
wsRef.current = ws;
ws.onopen = () => {
retryRef.current = 0;
setState((s) => ({ ...s, status: "open", error: null }));
};
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data as string) as ServerMessage;
setState((s) => {
switch (msg.type) {
case "hello":
// Session switch or fresh connect: full resync follows.
return { ...s, entries: [], liveThinking: "", liveText: "", pending: null, streaming: false };
case "backfill":
return { ...s, entries: reconcileBackfill(s.entries, msg.entries) };
case "entry":
return applyEntry(s, msg.entry);
case "pending":
return { ...s, pending: msg.question };
case "delta":
return msg.kind === "thinking"
? { ...s, liveThinking: s.liveThinking + msg.delta }
: { ...s, liveText: s.liveText + msg.delta };
case "streaming":
return { ...s, streaming: msg.value };
case "error":
return { ...s, error: msg.message };
}
});
};
ws.onclose = () => {
if (!aliveRef.current) return;
setState((s) => ({ ...s, status: "reconnecting", streaming: false }));
const delay = Math.min(1000 * 2 ** retryRef.current, 8000);
retryRef.current++;
setTimeout(connect, delay);
};
ws.onerror = () => {
// onclose follows and schedules the retry
};
}, []);
useEffect(() => {
aliveRef.current = true;
connect();
return () => {
aliveRef.current = false;
wsRef.current?.close();
wsRef.current = null;
};
}, [connect]);
const sendPrompt = useCallback((text: string) => {
const trimmed = text.trim();
if (!trimmed) return;
const optimistic: DisplayEntry = { type: "user", id: localId(), text: trimmed, status: "sending" };
if (wsRef.current?.readyState !== WebSocket.OPEN) {
setState((s) => ({ ...s, entries: [...s.entries, { ...optimistic, status: "failed" }] }));
return;
}
wsRef.current.send(JSON.stringify({ type: "prompt", text: trimmed }));
setState((s) => ({ ...s, entries: [...s.entries, optimistic], error: null }));
}, []);
const sendRaw = useCallback((msg: unknown) => {
wsRef.current?.send(JSON.stringify(msg));
}, []);
const sendAnswer = useCallback(
(payload: Record<string, unknown>) => {
sendRaw({ type: "answer", ...payload });
},
[sendRaw],
);
const sendDismiss = useCallback(
(questionId: string) => {
sendRaw({ type: "dismiss", questionId });
},
[sendRaw],
);
const sendAbort = useCallback(() => {
sendRaw({ type: "abort" });
}, [sendRaw]);
return { state, sendPrompt, sendAnswer, sendDismiss, sendAbort };
}
// ─── state transitions ──────────────────────────────────────────────────────
/** Replace an optimistic (status: sending) copy of the same text; else append. */
function applyEntry(s: SessionState, entry: ClientEntry): SessionState {
if (entry.type === "user") {
const idx = s.entries.findIndex(
(e) => e.type === "user" && e.status === "sending" && e.text === entry.text,
);
if (idx >= 0) {
const entries = [...s.entries];
entries[idx] = entry;
return { ...s, entries };
}
}
if (entry.type === "assistant") {
// The finished message supersedes the live streaming buffers.
return { ...s, entries: [...s.entries, entry], liveThinking: "", liveText: "" };
}
return { ...s, entries: [...s.entries, entry] };
}
/** After a reconnect backfill: adopt the server's truth; optimistic messages
* the server never received become "failed". */
function reconcileBackfill(local: DisplayEntry[], backfill: ClientEntry[]): DisplayEntry[] {
const sentTexts = new Set(backfill.filter((e) => e.type === "user").map((e) => e.text));
const orphans = local
.filter(
(e): e is Extract<DisplayEntry, { type: "user" }> =>
e.type === "user" && e.status === "sending" && !sentTexts.has(e.text),
)
.map((e) => ({ ...e, status: "failed" as const }));
return [...backfill, ...orphans];
}
+7 -6
View File
@@ -4,10 +4,10 @@ import { GraphPlaceholder } from "../components/GraphPlaceholder.tsx";
interface HomeProps {
sessions: SessionSummary[];
onStart: (topic: string) => void;
onResume: (file: string) => void;
onStart: (topic: string) => Promise<void>;
onOpen: (file: string) => void;
onRefresh: () => void;
hasActive: boolean;
error: string | null;
}
function formatDate(iso: string): string {
@@ -24,7 +24,7 @@ function formatDate(iso: string): string {
}
}
export function Home({ sessions, onStart, onResume, onRefresh }: HomeProps) {
export function Home({ sessions, onStart, onOpen, onRefresh, error }: HomeProps) {
const [topic, setTopic] = useState("");
const [busy, setBusy] = useState(false);
@@ -52,7 +52,7 @@ export function Home({ sessions, onStart, onResume, onRefresh }: HomeProps) {
<div className="session-list">
{sessions.length === 0 && <div className="empty">No sessions yet</div>}
{sessions.map((s) => (
<button key={s.id} className="session-item" onClick={() => onResume(s.file)}>
<button key={s.id} className="session-item" onClick={() => onOpen(s.file)}>
<div className="session-name">{s.name || s.preview || "Untitled"}</div>
<div className="session-meta">
{formatDate(s.updatedAt)} · {s.messageCount} msg{s.messageCount === 1 ? "" : "s"}
@@ -75,9 +75,10 @@ export function Home({ sessions, onStart, onResume, onRefresh }: HomeProps) {
}}
/>
<button onClick={() => void submit()} disabled={busy || !topic.trim()}>
{busy ? "…" : "Start"}
{busy ? "Starting…" : "Start"}
</button>
</div>
{error && <div className="error-banner">{error}</div>}
</main>
</div>
);
+166 -75
View File
@@ -1,47 +1,46 @@
import { useEffect, useRef, useState } from "react";
import type { ClientEntry } from "../../../src/shared/protocol.ts";
import type { LiveState } from "../App.tsx";
/**
* SessionView — the teaching session at /s/<file>.
*
* Two phases:
* 1. boot — if this file isn't the server's active session, POST resume
* first ("Opening session…"); fresh page loads and cross-session
* navigation land here.
* 2. live — useSession owns the WS + state machine; this component renders
* the transcript (entries + live streaming block + pending quiz card)
* and the composer.
*/
import { useEffect, useState } from "react";
import type { DisplayEntry, SessionState } from "../useSession.ts";
import { useSession } from "../useSession.ts";
import { Markdown } from "../components/Markdown.tsx";
import { AssistantMessage, ThinkingBlock, ToolChips, UserMessage } from "../components/Message.tsx";
import { QuizCard } from "../components/QuizCard.tsx";
import { AnsweredCard } from "../components/AnsweredCard.tsx";
import { Transcript } from "../components/Transcript.tsx";
interface SessionViewProps {
live: LiveState;
send: (msg: unknown) => void;
file: string;
active: boolean;
onActivated: (file: string) => void;
onHome: () => void;
}
/** User messages that are already rendered as answer cards — don't duplicate. */
/** User messages already rendered as answer cards — don't duplicate them. */
const HIDDEN_USER_PREFIXES = ["[Quiz answer]", "[Answer to your question]"];
function EntryBlock({ entry }: { entry: ClientEntry }) {
function EntryBlock({ entry }: { entry: DisplayEntry }) {
switch (entry.type) {
case "user":
if (HIDDEN_USER_PREFIXES.some((p) => entry.text.startsWith(p))) return null;
return (
<div className="msg user">
<div className="msg-bubble">{entry.text}</div>
</div>
);
return <UserMessage text={entry.text} status={entry.status} />;
case "assistant":
return (
<div className="msg assistant">
{entry.toolCalls.map((tc, i) => (
<div key={i} className="tool-chip">
<span className="tool-name">{tc.name}</span>
{typeof tc.args.question === "string" && (
<span className="tool-arg"> {tc.args.question}</span>
)}
</div>
))}
{entry.text && <Markdown text={entry.text} />}
</div>
);
return <AssistantMessage text={entry.text} thinking={entry.thinking} toolCalls={entry.toolCalls} />;
case "toolResult":
return <div className="tool-result">{entry.text}</div>;
case "question":
// Rendered by the pending-question flow below (cards need answer state);
// when answered, the questionAnswered entry renders instead.
// Rendered by the pending-question flow; when answered, the
// questionAnswered entry renders instead.
return null;
case "questionAnswered":
return <AnsweredCard data={entry.data} />;
@@ -50,21 +49,117 @@ function EntryBlock({ entry }: { entry: ClientEntry }) {
}
}
export function SessionView({ live, send, onHome }: SessionViewProps) {
const [input, setInput] = useState("");
const bottomRef = useRef<HTMLDivElement>(null);
export function SessionView({ file, active, onActivated, onHome }: SessionViewProps) {
// ── boot: make sure the server has this session active ─────────────────
const [boot, setBoot] = useState<"resuming" | "ready" | "error">(active ? "ready" : "resuming");
const [bootError, setBootError] = useState<string | null>(null);
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, [live.entries.length, live.liveText, live.pending?.id]);
if (active) {
setBoot("ready");
return;
}
let cancelled = false;
resumeOnce(file)
.then(() => {
if (cancelled) return;
onActivated(file);
setBoot("ready");
})
.catch((err) => {
if (cancelled) return;
setBootError(String(err instanceof Error ? err.message : err));
setBoot("error");
});
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [file, active]);
if (boot !== "ready") {
return (
<div className="session">
<header className="session-head">
<button className="icon-btn" onClick={onHome} title="Back">
←
</button>
<div className="session-head-status">
{boot === "error" ? (
<span className="boot-error">{bootError}</span>
) : (
<>
<span className="dot on" /> opening session…
</>
)}
</div>
</header>
<div className="boot-screen">{boot === "error" ? bootError : "Opening session…"}</div>
</div>
);
}
return <SessionLive onHome={onHome} />;
}
// ─── live phase ─────────────────────────────────────────────────────────────
const resumePromises = new Map<string, Promise<void>>();
function resumeOnce(file: string): Promise<void> {
let p = resumePromises.get(file);
if (!p) {
p = fetch(`/api/sessions/${encodeURIComponent(file)}/resume`, { method: "POST" })
.then((res) => {
if (!res.ok) throw new Error(`could not open session (${res.status})`);
})
// don't cache failures — a remount should be able to retry
.catch((err) => {
resumePromises.delete(file);
throw err;
});
resumePromises.set(file, p);
}
return p;
}
function SessionLive({ onHome }: { onHome: () => void }) {
const { state, sendPrompt, sendAnswer, sendDismiss, sendAbort } = useSession();
const [input, setInput] = useState("");
const submit = () => {
const text = input.trim();
if (!text || live.streaming || live.pending !== null) return;
send({ type: "prompt", text });
if (!text || state.streaming || state.pending !== null || state.status !== "open") return;
sendPrompt(text);
setInput("");
};
const inputDisabled =
state.streaming || state.pending !== null || state.status !== "open";
const placeholder =
state.status !== "open"
? "Reconnecting…"
: state.pending !== null
? "Answer the question above first…"
: state.streaming
? "Teaching…"
: "Reply to the teacher…";
const statusLabel =
state.status === "connecting"
? "connecting…"
: state.status === "reconnecting"
? "reconnecting…"
: state.streaming
? "teaching…"
: state.pending !== null
? "waiting for your answer"
: "ready";
const scrollToken =
state.entries.length + state.liveText.length + state.liveThinking.length + (state.pending?.id ?? "");
return (
<div className="session">
<header className="session-head">
@@ -72,70 +167,66 @@ export function SessionView({ live, send, onHome }: SessionViewProps) {
←
</button>
<div className="session-head-status">
{!live.connected ? (
<>
<span className="dot off" /> connecting…
</>
) : live.streaming ? (
<>
<span className="dot on" /> teaching…
</>
) : live.pending !== null ? (
<>
<span className="dot q" /> waiting for your answer
</>
) : (
<>
<span className="dot ok" /> ready
</>
)}
<span className={`dot ${state.status === "open" ? (state.streaming ? "on" : "ok") : "off"}`} />{" "}
{statusLabel}
</div>
{live.streaming && (
<button className="abort-btn" onClick={() => send({ type: "abort" })}>
{state.streaming && (
<button className="abort-btn" onClick={sendAbort}>
Stop
</button>
)}
</header>
<div className="transcript">
{live.entries.map((entry) => (
<Transcript scrollToken={scrollToken}>
{state.entries.map((entry) => (
<EntryBlock key={entry.id} entry={entry} />
))}
{live.liveText && (
<div className="msg assistant">
<Markdown text={live.liveText} />
{(state.liveThinking || state.liveText) && (
<div className="msg assistant live">
<ThinkingBlock text={state.liveThinking} streaming={state.streaming} />
{state.liveText && (
<div className="live-text">
<Markdown text={state.liveText} />
{state.streaming && <span className="stream-cursor" />}
</div>
)}
</div>
)}
{live.pending && (
{state.pending && (
<QuizCard
question={live.pending}
send={send}
question={state.pending}
send={(msg) => {
if (msg && typeof msg === "object" && (msg as { type?: string }).type === "answer") {
sendAnswer(msg as Record<string, unknown>);
} else if (msg && typeof msg === "object" && (msg as { type?: string }).type === "dismiss") {
sendDismiss(String((msg as { questionId?: string }).questionId ?? ""));
}
}}
/>
)}
{live.error && <div className="error-banner">{live.error}</div>}
<div ref={bottomRef} />
</div>
{state.error && <div className="error-banner">{state.error}</div>}
</Transcript>
<div className="composer">
<input
type="text"
placeholder={
live.pending !== null
? "Answer the question above first…"
: live.streaming
? "Teaching…"
: "Reply to the teacher…"
}
placeholder={placeholder}
value={input}
disabled={live.streaming || live.pending !== null}
disabled={inputDisabled}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submit();
}}
/>
<button onClick={submit} disabled={live.streaming || live.pending !== null || !input.trim()}>
Send
</button>
{state.streaming ? (
<button className="abort" onClick={sendAbort}>
Stop
</button>
) : (
<button onClick={submit} disabled={inputDisabled || !input.trim()}>
Send
</button>
)}
</div>
</div>
);