practice: the chain table — every reasoning chain in one selectable overlay (owner-approved plan, 2026-09-29)
- core formatChainLine: names + arrow one-liner, singleton marker, pure
- graph-view Chains button (chrome row, empty-graph hidden) opens the
overlay: fuzzy search (names/aliases/statements), collapsible chain →
member → statement rows, birth-session + created columns, no
understanding-levels column
- pinned Selected section derives the agents' actual input live
(chainsForSelection over the selection; premise without its
conclusion shows as the singleton it becomes)
- Generate opens the creation dialog in CUSTOM mode: selection summary
+ dated default title, posts {nodeIds, params, note}; cluster mode
untouched on /practice
- live-verified on the owner's dev server: 219 chains, derived preview,
search-never-filters-Selected, dialog handoff (selection pass-through
bug caught + fixed en route), Esc/backdrop dismiss, zero writes
- practice UI files re-normalized to tabs (my earlier prettier runs had
drifted them to the 2-space default; whitespace-only)
17 render/unit pins added; gates: tsc 0, 1174/1174, lint 0, build 0
This commit is contained in:
@@ -156,7 +156,7 @@ data/ chats/ · graph/ (six ledgers + positions/source
|
|||||||
|
|
||||||
**The knowledge graph (two channels, one writer).** The write channel: the extraction pipeline — extractor (LLM: sees only the session, rendered as readable markdown by the shared `core/session-markdown.ts` engine — propositions as true statements, `follows`/`supports` edges with verbatim evidence; fully trusted, graph-blind) → auditor (LLM, an agentic loop that never sees the source: explores the existing graph through `find` / `list_sessions` / `list_propositions` tools, stamps each proposition with an identity verdict — link to an existing node (equivalence bias: paraphrases merge) or create — and may draw bridging edges between existing nodes and the new batch) → merger (`mergeFindings`, deterministic: applies the verdicts, link-appends phrasings/provenance, resolves and dedupes edges, checkpoints coverage) → layout settle. No quiz outcomes or understanding assessments live in the graph (2026-09-27 cleanup); practice (`/practice`) consumes the graph as feedback-only problem sets and writes nothing back. Triggered when a chat's **uncovered tokens** (message-view fingerprints, `coverage.jsonl`) cross `graph.extractionChunkTokens` (a settings knob, default 4096, floor 500 — read fresh per turn); failure checkpoints nothing, the next trigger re-runs. The same pipeline serves the **notes front door** (`POST /api/graph/import`: any `*.md`/`*.txt` becomes a source; re-imports are idempotent by path hash). The read channel: `GET /api/graph` derives the snapshot from the ledgers — a pure read; the home view is a hand-rolled Canvas 2D renderer (one rAF loop, dirty-flag idle, d3-zoom camera, zoom-gated labels, cluster hulls) over a d3-force layout, with server-persisted render settings and drag-committed positions. Clusters are **birth-session groupings**: a node joins the cluster of the session that birthed it (a chat, or an imported notes file as a file-kind session), derived at read — no embedding pass, no naming pass. The teacher reaches the graph on its own terms through the gated prober tools (`list_sessions` / `list_propositions`, the `agent.graphTools` setting) — there is no automatic context injection.
|
**The knowledge graph (two channels, one writer).** The write channel: the extraction pipeline — extractor (LLM: sees only the session, rendered as readable markdown by the shared `core/session-markdown.ts` engine — propositions as true statements, `follows`/`supports` edges with verbatim evidence; fully trusted, graph-blind) → auditor (LLM, an agentic loop that never sees the source: explores the existing graph through `find` / `list_sessions` / `list_propositions` tools, stamps each proposition with an identity verdict — link to an existing node (equivalence bias: paraphrases merge) or create — and may draw bridging edges between existing nodes and the new batch) → merger (`mergeFindings`, deterministic: applies the verdicts, link-appends phrasings/provenance, resolves and dedupes edges, checkpoints coverage) → layout settle. No quiz outcomes or understanding assessments live in the graph (2026-09-27 cleanup); practice (`/practice`) consumes the graph as feedback-only problem sets and writes nothing back. Triggered when a chat's **uncovered tokens** (message-view fingerprints, `coverage.jsonl`) cross `graph.extractionChunkTokens` (a settings knob, default 4096, floor 500 — read fresh per turn); failure checkpoints nothing, the next trigger re-runs. The same pipeline serves the **notes front door** (`POST /api/graph/import`: any `*.md`/`*.txt` becomes a source; re-imports are idempotent by path hash). The read channel: `GET /api/graph` derives the snapshot from the ledgers — a pure read; the home view is a hand-rolled Canvas 2D renderer (one rAF loop, dirty-flag idle, d3-zoom camera, zoom-gated labels, cluster hulls) over a d3-force layout, with server-persisted render settings and drag-committed positions. Clusters are **birth-session groupings**: a node joins the cluster of the session that birthed it (a chat, or an imported notes file as a file-kind session), derived at read — no embedding pass, no naming pass. The teacher reaches the graph on its own terms through the gated prober tools (`list_sessions` / `list_propositions`, the `agent.graphTools` setting) — there is no automatic context injection.
|
||||||
|
|
||||||
**Practice (problem sets).** The graph's `follows`-edges become reasoning chains; the `/practice` creation dialog picks a birth-session cluster (the graph view's own groups) and freezes its propositions + chains into a self-contained `ProblemSet`. Three named-level axes steer generation (ladder rung 0–4, cue distance 0–2, Theory|Application — never a number to interpolate; defaults Direct exercise · Adjacent context · Theory), plus an optional free-form note the agents weigh but need not follow. A partitioner agent covers every chain exactly once, one generator per partition writes problems against the owner's problem-engineering framework (commit-before-pose: statement + solution + rubric together), and grading is **strengthening, not assessment** — one attempt per problem with its own submit button, instant solution/rubric reveal, then a score 0–10 with brief reasoning landing live; nothing ever written back to the graph. Runs are registry-backed background jobs on the activity dock (no steer, never wakes the teacher); sets live in `data/practice`, crash-swept on boot.
|
**Practice (problem sets).** The graph's `follows`-edges become reasoning chains; the `/practice` creation dialog picks a birth-session cluster (the graph view's own groups) and freezes its propositions + chains into a self-contained `ProblemSet`. Three named-level axes steer generation (ladder rung 0–4, cue distance 0–2, Theory|Application — never a number to interpolate; defaults Direct exercise · Adjacent context · Theory), plus an optional free-form note the agents weigh but need not follow. Creation has two entries: the cluster picker on `/practice`, or the graph view's chain table — every reasoning chain in one selectable overlay whose pinned preview shows the exact `N propositions → M chains` the agents will receive — handing a free-form node selection to the same dialog. A partitioner agent covers every chain exactly once, one generator per partition writes problems against the owner's problem-engineering framework (commit-before-pose: statement + solution + rubric together), and grading is **strengthening, not assessment** — one attempt per problem with its own submit button, instant solution/rubric reveal, then a score 0–10 with brief reasoning landing live; nothing ever written back to the graph. Runs are registry-backed background jobs on the activity dock (no steer, never wakes the teacher); sets live in `data/practice`, crash-swept on boot.
|
||||||
|
|
||||||
**Dictation.** Optional speech-to-text: the server mints short-lived Deepgram tokens; audio streams browser→Deepgram over WebSocket, never through the server.
|
**Dictation.** Optional speech-to-text: the server mints short-lived Deepgram tokens; audio streams browser→Deepgram over WebSocket, never through the server.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,519 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* THE CHAIN TABLE (chains overlay, owner-approved plan 2026-09-29): every
|
||||||
|
* reasoning chain of the graph in one selectable table — the graph view's
|
||||||
|
* practice entry for FREE-FORM selections, complementing the cluster
|
||||||
|
* picker (which stays the /practice page's only creation mode). Read-only
|
||||||
|
* toward the graph: it renders the snapshot it is handed, selects node
|
||||||
|
* ids, and hands the selection to the practice dialog's CUSTOM mode.
|
||||||
|
*
|
||||||
|
* MOUNT IDIOM (the session-overlay precedent, session-overlay.tsx): the
|
||||||
|
* overlay is ABSOLUTE INSIDE the graph area (never a body portal) —
|
||||||
|
* inset-0, z-40, bg-background/80 + backdrop blur — so the app chrome
|
||||||
|
* (drag bar, sidebar) stays sharp and reachable; Esc and backdrop clicks
|
||||||
|
* dismiss.
|
||||||
|
*
|
||||||
|
* STRUCTURE: a fuzzy search box (names, aliases, statements — core's
|
||||||
|
* fuzzyScore) at the very top filters the chain list only; the SELECTED
|
||||||
|
* section is pinned beneath it, never filtered — N propositions → M
|
||||||
|
* chains via chainsForSelection over the selection (the agents' ACTUAL
|
||||||
|
* input: a selected premise without its conclusion shows as the singleton
|
||||||
|
* it becomes). Chain rows (the core formatter's name line) expand to
|
||||||
|
* indented member proposition rows; each member expands its full
|
||||||
|
* statement inline. Columns: checkbox | chain/proposition tree | birth
|
||||||
|
* session(s) | created. NO understanding-levels column (explicitly not
|
||||||
|
* built — no dead markup).
|
||||||
|
*
|
||||||
|
* Named neutrally (ChainTable, not Practice*) — the table is a
|
||||||
|
* graph-surface; only the Generate handoff knows about practice.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { ListTreeIcon, SearchIcon, XIcon } from "lucide-react";
|
||||||
|
import { chainsForSelection, formatChainLine, fuzzyScore } from "@/src/core";
|
||||||
|
import type { GraphEdge, GraphNode } from "@/src/core";
|
||||||
|
import {
|
||||||
|
Collapsible,
|
||||||
|
CollapsibleContent,
|
||||||
|
CollapsibleTrigger,
|
||||||
|
} from "@/components/ui/collapsible";
|
||||||
|
import { PracticeDialog } from "@/components/practice-dialog";
|
||||||
|
|
||||||
|
/** The grid every row shares: checkbox | tree | birth | date. */
|
||||||
|
const ROW_COLS = "grid-cols-[1.5rem_minmax(0,1fr)_9rem_5.5rem]";
|
||||||
|
|
||||||
|
/** A node's birth-session label, mirroring the clusters' honesty join:
|
||||||
|
* the first surviving provenance point's chatId → chat title / notes
|
||||||
|
* file path, null when unnameable (rendered muted "unlabeled", never
|
||||||
|
* guessed). Inlined here (one line) because session-clusters.ts is not
|
||||||
|
* barrel-exported — the graph stream owns it; the shape is contract-
|
||||||
|
* pinned (provenance[0] is the birth by the getGraph fold order). */
|
||||||
|
function birthLabelOf(
|
||||||
|
node: Pick<GraphNode, "provenance">,
|
||||||
|
sessions: Record<string, string>,
|
||||||
|
fileSources: Record<string, string>,
|
||||||
|
): string | null {
|
||||||
|
const birth = node.provenance[0]?.chatId ?? null;
|
||||||
|
if (birth === null) return null;
|
||||||
|
return sessions[birth] ?? fileSources[birth] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One chain's birth labels — unique over its members, sorted by session
|
||||||
|
* id (deterministic); a member with no nameable birth contributes a
|
||||||
|
* muted "unlabeled" entry (honest, per the clusters law). */
|
||||||
|
function chainBirthLabels(
|
||||||
|
chain: { premises: string[]; conclusion: string },
|
||||||
|
byId: Map<string, GraphNode>,
|
||||||
|
sessions: Record<string, string>,
|
||||||
|
fileSources: Record<string, string>,
|
||||||
|
): string[] {
|
||||||
|
const labels = new Map<string, string>();
|
||||||
|
for (const id of [...chain.premises, chain.conclusion]) {
|
||||||
|
const node = byId.get(id);
|
||||||
|
if (!node) continue;
|
||||||
|
const birth = node.provenance[0]?.chatId ?? null;
|
||||||
|
if (birth === null) {
|
||||||
|
labels.set("\0unlabeled", "unlabeled");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
labels.set(birth, sessions[birth] ?? fileSources[birth] ?? "unlabeled");
|
||||||
|
}
|
||||||
|
return [...labels.entries()]
|
||||||
|
.sort((a, b) => (a[0] < b[0] ? -1 : 1))
|
||||||
|
.map(([, label]) => label);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The checkbox — checked/indeterminate (a chain with SOME members
|
||||||
|
* selected); clicks stop at the checkbox so they never toggle the
|
||||||
|
* surrounding Collapsible row. */
|
||||||
|
function RowCheckbox({
|
||||||
|
checked,
|
||||||
|
indeterminate = false,
|
||||||
|
onToggle,
|
||||||
|
testid,
|
||||||
|
label,
|
||||||
|
}: {
|
||||||
|
checked: boolean;
|
||||||
|
indeterminate?: boolean;
|
||||||
|
onToggle: (next: boolean) => void;
|
||||||
|
testid: string;
|
||||||
|
label: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
// `indeterminate` is a DOM property React does not expose — set it
|
||||||
|
// on the node directly (the chain rows' partial state).
|
||||||
|
ref={(el) => {
|
||||||
|
if (el) el.indeterminate = indeterminate;
|
||||||
|
}}
|
||||||
|
data-testid={testid}
|
||||||
|
aria-label={label}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
onChange={(e) => onToggle(e.target.checked)}
|
||||||
|
className="size-3.5 accent-primary"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The table's pure body — exported for SSR pins (the render-suite
|
||||||
|
* discipline). All state (query, selection) arrives via props; the
|
||||||
|
* overlay wrapper below owns it. */
|
||||||
|
export function ChainTableBody({
|
||||||
|
nodes,
|
||||||
|
edges,
|
||||||
|
sessions,
|
||||||
|
fileSources,
|
||||||
|
query,
|
||||||
|
onQuery,
|
||||||
|
selection,
|
||||||
|
onToggleNode,
|
||||||
|
onToggleChain,
|
||||||
|
onClear,
|
||||||
|
onGenerate,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
nodes: GraphNode[];
|
||||||
|
edges: GraphEdge[];
|
||||||
|
sessions: Record<string, string>;
|
||||||
|
fileSources: Record<string, string>;
|
||||||
|
query: string;
|
||||||
|
onQuery: (v: string) => void;
|
||||||
|
selection: ReadonlySet<string>;
|
||||||
|
onToggleNode: (id: string, next: boolean) => void;
|
||||||
|
onToggleChain: (ids: string[], next: boolean) => void;
|
||||||
|
onClear: () => void;
|
||||||
|
onGenerate: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const byId = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
|
||||||
|
const chains = useMemo(
|
||||||
|
() => chainsForSelection(nodes, edges),
|
||||||
|
[nodes, edges],
|
||||||
|
);
|
||||||
|
const nameOf = (id: string) => byId.get(id)?.name ?? id;
|
||||||
|
|
||||||
|
// The fuzzy filter: a chain is visible when ANY member matches the
|
||||||
|
// query on name, aliases, or statement; chains rank by their best
|
||||||
|
// member's score (desc), ties by chain id — deterministic.
|
||||||
|
const visibleChains = useMemo(() => {
|
||||||
|
const scored = chains.map((chain) => {
|
||||||
|
const memberIds = [...chain.premises, chain.conclusion];
|
||||||
|
// Empty query matches everything at score 0; a non-empty query
|
||||||
|
// starts at null (no match) and takes the best member score.
|
||||||
|
let best: number | null = query.trim() === "" ? 0 : null;
|
||||||
|
for (const id of memberIds) {
|
||||||
|
const node = byId.get(id);
|
||||||
|
if (!node) continue;
|
||||||
|
const s = fuzzyScore(query, node.name, node.statement, ...node.aliases);
|
||||||
|
if (s === null) continue;
|
||||||
|
if (best === null || s > best) best = s;
|
||||||
|
}
|
||||||
|
return { chain, best };
|
||||||
|
});
|
||||||
|
return scored
|
||||||
|
.filter((row): row is { chain: (typeof chains)[number]; best: number } => row.best !== null)
|
||||||
|
.sort((a, b) => b.best - a.best || (a.chain.id < b.chain.id ? -1 : 1))
|
||||||
|
.map(({ chain }) => chain);
|
||||||
|
}, [chains, byId, query]);
|
||||||
|
|
||||||
|
// The agents' ACTUAL input: chainsForSelection over the selection —
|
||||||
|
// a selected premise without its conclusion shows as the singleton it
|
||||||
|
// becomes. This is the pinned preview, never search-filtered.
|
||||||
|
const derived = useMemo(() => {
|
||||||
|
const selectedNodes = [...selection]
|
||||||
|
.map((id) => byId.get(id))
|
||||||
|
.filter((n): n is GraphNode => n !== undefined);
|
||||||
|
return chainsForSelection(selectedNodes, edges);
|
||||||
|
}, [selection, byId, edges]);
|
||||||
|
const propositions = useMemo(() => {
|
||||||
|
const known = new Set([...selection].filter((id) => byId.has(id)));
|
||||||
|
return known;
|
||||||
|
}, [selection, byId]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div data-testid="chain-table" className="flex h-full min-h-0 flex-col">
|
||||||
|
{/* Header: title + count + close (the session-overlay chrome). */}
|
||||||
|
<div className="flex shrink-0 items-center gap-2 px-4 pb-2 pt-3">
|
||||||
|
<ListTreeIcon className="size-4 text-muted-foreground" />
|
||||||
|
<span className="font-title text-lg tracking-tight">Chains</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{chains.length} {chains.length === 1 ? "chain" : "chains"} ·{" "}
|
||||||
|
{nodes.length} propositions
|
||||||
|
</span>
|
||||||
|
<div className="flex-1" />
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="chain-table-close"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="Close chains"
|
||||||
|
className="flex size-7 items-center justify-center rounded-md border border-border/70 bg-card/80 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||||
|
>
|
||||||
|
<XIcon className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* The fuzzy search — very top; filters the LIST only. */}
|
||||||
|
<div className="shrink-0 px-4 pb-2">
|
||||||
|
<div className="relative">
|
||||||
|
<SearchIcon className="absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||||
|
<input
|
||||||
|
value={query}
|
||||||
|
data-testid="chain-table-search"
|
||||||
|
onChange={(e) => onQuery(e.target.value)}
|
||||||
|
placeholder="Search propositions…"
|
||||||
|
aria-label="Search propositions"
|
||||||
|
spellCheck={false}
|
||||||
|
className="h-8 w-full rounded-lg border bg-background pl-8 pr-3 text-xs outline-none placeholder:text-muted-foreground focus:border-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* The SELECTED section — pinned, always visible, never filtered. */}
|
||||||
|
<div
|
||||||
|
data-testid="chain-table-selected"
|
||||||
|
className="mx-4 mb-2 shrink-0 rounded-lg border bg-accent/30 px-3 py-2"
|
||||||
|
>
|
||||||
|
{propositions.size === 0 ? (
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
Nothing selected — check whole chains or single propositions below.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div
|
||||||
|
data-testid="chain-selected-summary"
|
||||||
|
className="text-xs font-medium"
|
||||||
|
>
|
||||||
|
{propositions.size}{" "}
|
||||||
|
{propositions.size === 1 ? "proposition" : "propositions"} →{" "}
|
||||||
|
{derived.length} {derived.length === 1 ? "chain" : "chains"}
|
||||||
|
</div>
|
||||||
|
<ul
|
||||||
|
data-testid="chain-derived-list"
|
||||||
|
className="mt-1 max-h-20 overflow-y-auto text-xs leading-relaxed text-muted-foreground"
|
||||||
|
>
|
||||||
|
{derived.map((chain) => (
|
||||||
|
<li key={chain.id} data-testid={`chain-derived-${chain.id}`}>
|
||||||
|
{formatChainLine(
|
||||||
|
chain,
|
||||||
|
Object.fromEntries(
|
||||||
|
[...byId.entries()].map(([id, n]) => [
|
||||||
|
id,
|
||||||
|
{ name: n.name },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="flex shrink-0 flex-col gap-1.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="chain-generate"
|
||||||
|
onClick={onGenerate}
|
||||||
|
className="rounded-md bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90"
|
||||||
|
>
|
||||||
|
Generate problem set
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="chain-clear"
|
||||||
|
onClick={onClear}
|
||||||
|
className="rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||||
|
>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Column headers + the chain rows (scrollable). */}
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4">
|
||||||
|
<div
|
||||||
|
className={`grid ${ROW_COLS} gap-2 px-1 pb-1 text-[11px] uppercase tracking-widest text-muted-foreground/70`}
|
||||||
|
>
|
||||||
|
<span />
|
||||||
|
<span>Chain</span>
|
||||||
|
<span className="truncate">Born in</span>
|
||||||
|
<span>Created</span>
|
||||||
|
</div>
|
||||||
|
{visibleChains.length === 0 && (
|
||||||
|
<div
|
||||||
|
data-testid="chain-table-nomatch"
|
||||||
|
className="px-1 pt-2 text-xs text-muted-foreground"
|
||||||
|
>
|
||||||
|
No matching chains.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
{visibleChains.map((chain, index) => {
|
||||||
|
const memberIds = [...chain.premises, chain.conclusion];
|
||||||
|
const selectedCount = memberIds.filter((id) =>
|
||||||
|
selection.has(id),
|
||||||
|
).length;
|
||||||
|
const conclusion = byId.get(chain.conclusion);
|
||||||
|
return (
|
||||||
|
<Collapsible key={chain.id} defaultOpen={index === 0}>
|
||||||
|
<CollapsibleTrigger
|
||||||
|
data-testid={`chain-row-${chain.id}`}
|
||||||
|
className={`grid ${ROW_COLS} w-full items-center gap-2 rounded-lg px-1 py-1.5 text-left text-sm transition-colors hover:bg-accent`}
|
||||||
|
>
|
||||||
|
<RowCheckbox
|
||||||
|
checked={
|
||||||
|
selectedCount === memberIds.length && memberIds.length > 0
|
||||||
|
}
|
||||||
|
indeterminate={
|
||||||
|
selectedCount > 0 && selectedCount < memberIds.length
|
||||||
|
}
|
||||||
|
onToggle={(next) => onToggleChain(memberIds, next)}
|
||||||
|
testid={`chain-checkbox-${chain.id}`}
|
||||||
|
label={`Select chain ${nameOf(chain.conclusion)}`}
|
||||||
|
/>
|
||||||
|
<span className="min-w-0 truncate">
|
||||||
|
{formatChainLine(
|
||||||
|
chain,
|
||||||
|
Object.fromEntries(
|
||||||
|
[...byId.entries()].map(([id, n]) => [
|
||||||
|
id,
|
||||||
|
{ name: n.name },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="truncate text-xs text-muted-foreground"
|
||||||
|
data-testid={`chain-birth-${chain.id}`}
|
||||||
|
>
|
||||||
|
{chainBirthLabels(chain, byId, sessions, fileSources)
|
||||||
|
.map((label) =>
|
||||||
|
label === "unlabeled" ? "unlabeled" : label,
|
||||||
|
)
|
||||||
|
.join(" · ")}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="truncate text-xs tabular-nums text-muted-foreground"
|
||||||
|
data-testid={`chain-date-${chain.id}`}
|
||||||
|
>
|
||||||
|
{conclusion ? conclusion.createdAt.slice(0, 10) : ""}
|
||||||
|
</span>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent>
|
||||||
|
<div className="flex flex-col gap-0.5 py-0.5">
|
||||||
|
{memberIds.map((id) => {
|
||||||
|
const node = byId.get(id);
|
||||||
|
if (!node) return null;
|
||||||
|
const isConclusion = id === chain.conclusion;
|
||||||
|
return (
|
||||||
|
<Collapsible key={id}>
|
||||||
|
<CollapsibleTrigger
|
||||||
|
data-testid={`prop-row-${id}`}
|
||||||
|
className={`grid ${ROW_COLS} w-full items-center gap-2 rounded-md px-1 py-1 text-left text-xs transition-colors hover:bg-accent`}
|
||||||
|
>
|
||||||
|
<span className="pl-3">
|
||||||
|
<RowCheckbox
|
||||||
|
checked={selection.has(id)}
|
||||||
|
onToggle={(next) => onToggleNode(id, next)}
|
||||||
|
testid={`prop-checkbox-${id}`}
|
||||||
|
label={`Select proposition ${node.name}`}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 truncate pl-6 text-muted-foreground">
|
||||||
|
{isConclusion && (
|
||||||
|
<span className="mr-1 text-foreground/70">
|
||||||
|
→
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{node.name}
|
||||||
|
</span>
|
||||||
|
<span />
|
||||||
|
<span />
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent>
|
||||||
|
<div
|
||||||
|
data-testid={`prop-statement-${id}`}
|
||||||
|
className="ml-[calc(1.5rem+1rem+1.25rem)] rounded-md bg-muted/40 px-3 py-1.5 text-xs leading-relaxed text-muted-foreground"
|
||||||
|
>
|
||||||
|
{node.statement}
|
||||||
|
</div>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The graph view's overlay wrapper: owns query + selection + the custom
|
||||||
|
* practice dialog; mounts ABSOLUTE INSIDE the graph area (the
|
||||||
|
* session-overlay idiom — never a body portal). Read-only toward the
|
||||||
|
* graph — selection lives in component state only. */
|
||||||
|
export function ChainTableOverlay({
|
||||||
|
open,
|
||||||
|
nodes,
|
||||||
|
edges,
|
||||||
|
sessions,
|
||||||
|
fileSources,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
nodes: GraphNode[];
|
||||||
|
edges: GraphEdge[];
|
||||||
|
sessions: Record<string, string>;
|
||||||
|
fileSources: Record<string, string>;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [selection, setSelection] = useState<ReadonlySet<string>>(
|
||||||
|
() => new Set(),
|
||||||
|
);
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
|
|
||||||
|
// Esc dismisses (unless the practice dialog has focus — its own Esc
|
||||||
|
// owns that layer; both listen on window, so the guard is explicit).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || dialogOpen) return;
|
||||||
|
const onKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === "Escape") onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKeyDown);
|
||||||
|
return () => window.removeEventListener("keydown", onKeyDown);
|
||||||
|
}, [open, dialogOpen, onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const byId = new Map(nodes.map((n) => [n.id, n]));
|
||||||
|
const selectedNodes = [...selection]
|
||||||
|
.map((id) => byId.get(id))
|
||||||
|
.filter((n): n is GraphNode => n !== undefined);
|
||||||
|
const derived = chainsForSelection(selectedNodes, edges);
|
||||||
|
const nodeIds = [...selection].sort();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
data-testid="chain-table-overlay"
|
||||||
|
className="absolute inset-0 z-40 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="flex h-full w-full max-w-4xl flex-col overflow-hidden rounded-xl border bg-card shadow-xl"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<ChainTableBody
|
||||||
|
nodes={nodes}
|
||||||
|
edges={edges}
|
||||||
|
sessions={sessions}
|
||||||
|
fileSources={fileSources}
|
||||||
|
query={query}
|
||||||
|
onQuery={setQuery}
|
||||||
|
selection={selection}
|
||||||
|
onToggleNode={(id, next) =>
|
||||||
|
setSelection((prev) => {
|
||||||
|
const s = new Set(prev);
|
||||||
|
if (next) s.add(id);
|
||||||
|
else s.delete(id);
|
||||||
|
return s;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
onToggleChain={(ids, next) =>
|
||||||
|
setSelection((prev) => {
|
||||||
|
const s = new Set(prev);
|
||||||
|
for (const id of ids) {
|
||||||
|
if (next) s.add(id);
|
||||||
|
else s.delete(id);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
})
|
||||||
|
}
|
||||||
|
onClear={() => setSelection(new Set())}
|
||||||
|
onGenerate={() => setDialogOpen(true)}
|
||||||
|
onClose={onClose}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{dialogOpen && (
|
||||||
|
<PracticeDialog
|
||||||
|
mode="custom"
|
||||||
|
selection={{
|
||||||
|
nodeIds,
|
||||||
|
propositions: selectedNodes.length,
|
||||||
|
chains: derived.length,
|
||||||
|
}}
|
||||||
|
onClose={() => setDialogOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -66,13 +66,14 @@
|
|||||||
|
|
||||||
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { FileTextIcon, Loader2Icon, SearchIcon, SettingsIcon, UploadIcon, WaypointsIcon } from "lucide-react";
|
import { FileTextIcon, ListTreeIcon, Loader2Icon, SearchIcon, SettingsIcon, UploadIcon, WaypointsIcon } from "lucide-react";
|
||||||
import { incrementalLayout, type GraphCostSummary, type GraphNode, type GraphSnapshot } from "@/src/core";
|
import { incrementalLayout, type GraphCostSummary, type GraphNode, type GraphSnapshot } from "@/src/core";
|
||||||
import { GraphCanvasRenderer, type GraphRenderSettings } from "./graph-canvas.ts";
|
import { GraphCanvasRenderer, type GraphRenderSettings } from "./graph-canvas.ts";
|
||||||
import { usePopoverDismiss } from "@/components/popover-dismiss";
|
import { usePopoverDismiss } from "@/components/popover-dismiss";
|
||||||
import { useActivity } from "@/components/activity-dock";
|
import { useActivity } from "@/components/activity-dock";
|
||||||
import { MenuShell } from "@/components/menu-shell.tsx";
|
import { MenuShell } from "@/components/menu-shell.tsx";
|
||||||
import { DeleteNodeDialog } from "@/components/delete-node-dialog.tsx";
|
import { DeleteNodeDialog } from "@/components/delete-node-dialog.tsx";
|
||||||
|
import { ChainTableOverlay } from "@/components/chain-table.tsx";
|
||||||
import { Hint } from "@/components/ui/hint";
|
import { Hint } from "@/components/ui/hint";
|
||||||
import {
|
import {
|
||||||
ARROW_LENGTH_LADDER,
|
ARROW_LENGTH_LADDER,
|
||||||
@@ -860,6 +861,7 @@ export function GraphChromeRow({
|
|||||||
onImportFiles,
|
onImportFiles,
|
||||||
settings,
|
settings,
|
||||||
changeSettings,
|
changeSettings,
|
||||||
|
onOpenChains,
|
||||||
}: {
|
}: {
|
||||||
isEmpty: boolean;
|
isEmpty: boolean;
|
||||||
query: string;
|
query: string;
|
||||||
@@ -873,6 +875,9 @@ export function GraphChromeRow({
|
|||||||
onImportFiles: (files: FileList | null) => void;
|
onImportFiles: (files: FileList | null) => void;
|
||||||
settings: GraphRenderSettings;
|
settings: GraphRenderSettings;
|
||||||
changeSettings: (update: (cur: RenderSettings) => RenderSettings) => void;
|
changeSettings: (update: (cur: RenderSettings) => RenderSettings) => void;
|
||||||
|
/** Opens the chain table overlay (the chains-overlay plan,
|
||||||
|
* 2026-09-29). */
|
||||||
|
onOpenChains: () => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -902,6 +907,24 @@ export function GraphChromeRow({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{/* The chain table (chains overlay, owner plan 2026-09-29) — the
|
||||||
|
graph's free-form practice entry. Own container (36px band),
|
||||||
|
between the search and Import. */}
|
||||||
|
{!isEmpty && (
|
||||||
|
<div className="graph-chrome-fade-in shrink-0 rounded-xl border bg-card/85 px-1 py-[3px] shadow-lg backdrop-blur">
|
||||||
|
<Hint label="Every reasoning chain, selectable for practice" side="bottom">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onOpenChains}
|
||||||
|
data-testid="open-chain-table"
|
||||||
|
className="flex h-7 items-center gap-1.5 rounded-lg px-2.5 text-xs text-muted-foreground transition-colors hover:bg-accent"
|
||||||
|
>
|
||||||
|
<ListTreeIcon className="size-3" />
|
||||||
|
Chains
|
||||||
|
</button>
|
||||||
|
</Hint>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{/* Import notes — its own container (36px, header band); ALWAYS
|
{/* Import notes — its own container (36px, header band); ALWAYS
|
||||||
rendered (the empty-graph ruling above — the entry point). */}
|
rendered (the empty-graph ruling above — the entry point). */}
|
||||||
<div className="shrink-0 rounded-xl border bg-card/85 px-1 py-[3px] shadow-lg backdrop-blur">
|
<div className="shrink-0 rounded-xl border bg-card/85 px-1 py-[3px] shadow-lg backdrop-blur">
|
||||||
@@ -1050,6 +1073,9 @@ export function GraphView() {
|
|||||||
// Fetch the derived graph. Re-runs when a background pipeline run
|
// Fetch the derived graph. Re-runs when a background pipeline run
|
||||||
// finishes (refreshTick) — its merges just landed in the ledger.
|
// finishes (refreshTick) — its merges just landed in the ledger.
|
||||||
const [refreshTick, setRefreshTick] = useState(0);
|
const [refreshTick, setRefreshTick] = useState(0);
|
||||||
|
// The chain table overlay (chains-overlay plan, 2026-09-29) —
|
||||||
|
// component-local: a browsing surface, not graph state.
|
||||||
|
const [chainsOpen, setChainsOpen] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
fetch("/api/graph")
|
fetch("/api/graph")
|
||||||
@@ -1529,6 +1555,20 @@ export function GraphView() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* The chain table overlay (chains-overlay plan, 2026-09-29):
|
||||||
|
ABSOLUTE INSIDE the graph area (the session-overlay idiom —
|
||||||
|
never a body portal) so the app chrome stays sharp and
|
||||||
|
reachable; the overlay itself is read-only toward the graph
|
||||||
|
and owns its selection + the custom practice dialog. */}
|
||||||
|
<ChainTableOverlay
|
||||||
|
open={chainsOpen && !isEmpty}
|
||||||
|
nodes={snapshot?.nodes ?? []}
|
||||||
|
edges={snapshot?.edges ?? []}
|
||||||
|
sessions={snapshot?.sessions ?? {}}
|
||||||
|
fileSources={snapshot?.fileSources ?? {}}
|
||||||
|
onClose={() => setChainsOpen(false)}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Legend + filters: search box and per-state toggle rows. */}
|
{/* Legend + filters: search box and per-state toggle rows. */}
|
||||||
{/* Top-right controls — separate floating containers (owner,
|
{/* Top-right controls — separate floating containers (owner,
|
||||||
graph-view round 2). Row order (2026-09-17): search,
|
graph-view round 2). Row order (2026-09-17): search,
|
||||||
@@ -1576,6 +1616,7 @@ export function GraphView() {
|
|||||||
onImportFiles={onImportFiles}
|
onImportFiles={onImportFiles}
|
||||||
settings={settings}
|
settings={settings}
|
||||||
changeSettings={changeSettings}
|
changeSettings={changeSettings}
|
||||||
|
onOpenChains={() => setChainsOpen(true)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+404
-334
@@ -33,364 +33,434 @@ import type { GraphClusterGroup, PracticeParams } from "@/src/core";
|
|||||||
/** The creation defaults (owner, 2026-09-29): rung 2 Direct exercise,
|
/** The creation defaults (owner, 2026-09-29): rung 2 Direct exercise,
|
||||||
* cue 1 Adjacent context, Theory. */
|
* cue 1 Adjacent context, Theory. */
|
||||||
export const DEFAULT_PRACTICE_PARAMS: PracticeParams = {
|
export const DEFAULT_PRACTICE_PARAMS: PracticeParams = {
|
||||||
ladderRung: 2,
|
ladderRung: 2,
|
||||||
cueDistance: 1,
|
cueDistance: 1,
|
||||||
presentation: "theory",
|
presentation: "theory",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The two creation modes (chains overlay, owner plan 2026-09-29):
|
||||||
|
* "cluster" — the /practice page's picker (stays cluster-ONLY, owner
|
||||||
|
* ruling 2026-09-29); "custom" — the graph view's chain table hands in
|
||||||
|
* a free-form node selection; no picker, a selection summary instead. */
|
||||||
|
export type PracticeDialogMode = "cluster" | "custom";
|
||||||
|
|
||||||
|
/** The custom mode's handoff: the flat node-id selection + the derived
|
||||||
|
* shape (chainsForSelection over the selection — the overlay computes
|
||||||
|
* it for its pinned preview and passes the same numbers here). */
|
||||||
|
export interface PracticeSelection {
|
||||||
|
nodeIds: string[];
|
||||||
|
propositions: number;
|
||||||
|
chains: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PracticeFailure {
|
export interface PracticeFailure {
|
||||||
status: number;
|
status: number;
|
||||||
error: string;
|
error: string;
|
||||||
code?: string;
|
code?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The dialog's pure body — exported for SSR pins (the delete-session /
|
/** The dialog's pure body — exported for SSR pins (the delete-session /
|
||||||
* settings body pattern). The wrapper owns state + fetch + portal. */
|
* settings body pattern). The wrapper owns state + fetch + portal. */
|
||||||
export function PracticeDialogBody({
|
export function PracticeDialogBody({
|
||||||
params,
|
mode = "cluster",
|
||||||
onParam,
|
params,
|
||||||
note,
|
onParam,
|
||||||
onNote,
|
note,
|
||||||
clusters,
|
onNote,
|
||||||
selectedKey,
|
clusters,
|
||||||
onSelect,
|
selectedKey,
|
||||||
busy,
|
onSelect,
|
||||||
failure,
|
selection,
|
||||||
onOpenSettings,
|
busy,
|
||||||
onClose,
|
failure,
|
||||||
onRun,
|
onOpenSettings,
|
||||||
|
onClose,
|
||||||
|
onRun,
|
||||||
}: {
|
}: {
|
||||||
params: PracticeParams;
|
mode?: PracticeDialogMode;
|
||||||
onParam: (patch: Partial<PracticeParams>) => void;
|
params: PracticeParams;
|
||||||
/** The learner's free-form note (owner, 2026-09-29) — optional,
|
onParam: (patch: Partial<PracticeParams>) => void;
|
||||||
* typing-only; carried to the partitioner + generators as additional
|
/** The learner's free-form note (owner, 2026-09-29) — optional,
|
||||||
* input they weigh but need not follow. */
|
* typing-only; carried to the partitioner + generators as additional
|
||||||
note: string;
|
* input they weigh but need not follow. */
|
||||||
onNote: (note: string) => void;
|
note: string;
|
||||||
clusters: GraphClusterGroup[];
|
onNote: (note: string) => void;
|
||||||
selectedKey: string | null;
|
clusters: GraphClusterGroup[];
|
||||||
onSelect: (key: string) => void;
|
selectedKey: string | null;
|
||||||
busy: boolean;
|
onSelect: (key: string) => void;
|
||||||
failure: PracticeFailure | null;
|
/** The custom mode's handoff (chain-table selections). */
|
||||||
onOpenSettings: () => void;
|
selection?: PracticeSelection;
|
||||||
onClose: () => void;
|
busy: boolean;
|
||||||
onRun: () => void;
|
failure: PracticeFailure | null;
|
||||||
|
onOpenSettings: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onRun: () => void;
|
||||||
}) {
|
}) {
|
||||||
const canRun = !busy && selectedKey !== null;
|
const canRun = !busy && (mode === "custom" ? (selection?.nodeIds.length ?? 0) > 0 : selectedKey !== null);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
role="dialog"
|
role="dialog"
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
aria-label="New problem set"
|
aria-label="New problem set"
|
||||||
data-testid="practice-dialog"
|
data-testid="practice-dialog"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
className="flex max-h-[85vh] w-[32rem] max-w-[calc(100vw-2rem)] flex-col rounded-xl border bg-card p-5 shadow-xl"
|
className="flex max-h-[85vh] w-[32rem] max-w-[calc(100vw-2rem)] flex-col rounded-xl border bg-card p-5 shadow-xl"
|
||||||
>
|
>
|
||||||
<h2 className="font-title text-2xl tracking-tight">New problem set</h2>
|
<h2 className="font-title text-2xl tracking-tight">New problem set</h2>
|
||||||
|
|
||||||
{/* The cluster: a birth-session group of the graph, resolved to
|
{/* The cluster picker — CLUSTER mode only (custom mode replaces
|
||||||
node ids on create (graph-domain, owner 2026-09-29). */}
|
it with the selection summary below): a birth-session group of
|
||||||
<div className="mt-4 flex flex-col gap-1">
|
the graph, resolved to node ids on create (graph-domain, owner
|
||||||
<span className="text-xs uppercase tracking-widest text-muted-foreground/70">
|
2026-09-29). */}
|
||||||
Cluster
|
{mode === "cluster" && (
|
||||||
</span>
|
<div className="mt-4 flex flex-col gap-1">
|
||||||
<div
|
<span className="text-xs uppercase tracking-widest text-muted-foreground/70">
|
||||||
className="max-h-40 overflow-y-auto rounded-lg border"
|
Cluster
|
||||||
data-testid="practice-dialog-clusters"
|
</span>
|
||||||
>
|
<div
|
||||||
{clusters.map((cluster) => (
|
className="max-h-40 overflow-y-auto rounded-lg border"
|
||||||
<button
|
data-testid="practice-dialog-clusters"
|
||||||
type="button"
|
>
|
||||||
key={cluster.key}
|
{clusters.map((cluster) => (
|
||||||
data-testid={`practice-cluster-${cluster.key}`}
|
<button
|
||||||
onClick={() => onSelect(cluster.key)}
|
type="button"
|
||||||
className={`flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-accent ${
|
key={cluster.key}
|
||||||
selectedKey === cluster.key ? "bg-accent" : ""
|
data-testid={`practice-cluster-${cluster.key}`}
|
||||||
}`}
|
onClick={() => onSelect(cluster.key)}
|
||||||
>
|
className={`flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-accent ${
|
||||||
<span className="min-w-0 truncate">
|
selectedKey === cluster.key ? "bg-accent" : ""
|
||||||
{cluster.label ?? (
|
}`}
|
||||||
<span className="text-muted-foreground/60">
|
>
|
||||||
unlabeled cluster
|
<span className="min-w-0 truncate">
|
||||||
</span>
|
{cluster.label ?? (
|
||||||
)}
|
<span className="text-muted-foreground/60">
|
||||||
</span>
|
unlabeled cluster
|
||||||
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
|
</span>
|
||||||
{cluster.kind === "notes" ? "notes · " : ""}
|
)}
|
||||||
{cluster.nodeCount} propositions
|
</span>
|
||||||
</span>
|
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
|
||||||
</button>
|
{cluster.kind === "notes" ? "notes · " : ""}
|
||||||
))}
|
{cluster.nodeCount} propositions
|
||||||
{clusters.length === 0 && (
|
</span>
|
||||||
<div className="px-3 py-2 text-sm text-muted-foreground">
|
</button>
|
||||||
No clusters yet — a cluster appears once a session births its
|
))}
|
||||||
first proposition.
|
{clusters.length === 0 && (
|
||||||
</div>
|
<div className="px-3 py-2 text-sm text-muted-foreground">
|
||||||
)}
|
No clusters yet — a cluster appears once a session births its
|
||||||
</div>
|
first proposition.
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* The three parameters — named levels, never a number to
|
{/* CUSTOM mode: no picker — the chain table already chose. The
|
||||||
|
dated default title (the pipeline's own `Practice — date`,
|
||||||
|
stamped server-side when no title is posted) + the derived
|
||||||
|
shape of the handoff. */}
|
||||||
|
{mode === "custom" && (
|
||||||
|
<div className="mt-4 flex flex-col gap-1" data-testid="practice-dialog-selection">
|
||||||
|
<span className="text-xs uppercase tracking-widest text-muted-foreground/70">
|
||||||
|
Selection
|
||||||
|
</span>
|
||||||
|
<div className="rounded-lg border bg-accent/30 px-3 py-2 text-sm">
|
||||||
|
<div className="text-muted-foreground">Practice — {new Date().toISOString().slice(0, 10)}</div>
|
||||||
|
<div data-testid="practice-dialog-selection-line">
|
||||||
|
{selection?.propositions ?? 0} {selection?.propositions === 1 ? "proposition" : "propositions"} →{" "}
|
||||||
|
{selection?.chains ?? 0} {selection?.chains === 1 ? "chain" : "chains"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* The three parameters — named levels, never a number to
|
||||||
interpolate (owner, 2026-09-29). Stepped sliders snap to the
|
interpolate (owner, 2026-09-29). Stepped sliders snap to the
|
||||||
detents; each shows the level's NAME + its one-line
|
detents; each shows the level's NAME + its one-line
|
||||||
definition; presentation is a two-segment toggle. */}
|
definition; presentation is a two-segment toggle. */}
|
||||||
<div className="mt-4 flex flex-col gap-3">
|
<div className="mt-4 flex flex-col gap-3">
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<span className="flex items-center justify-between text-[11px] text-muted-foreground">
|
<span className="flex items-center justify-between text-[11px] text-muted-foreground">
|
||||||
Ladder
|
Ladder
|
||||||
<span className="text-muted-foreground/80">0 · 1 · 2 · 3 · 4</span>
|
<span className="text-muted-foreground/80">0 · 1 · 2 · 3 · 4</span>
|
||||||
</span>
|
</span>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min={0}
|
min={0}
|
||||||
max={4}
|
max={4}
|
||||||
step={1}
|
step={1}
|
||||||
value={params.ladderRung}
|
value={params.ladderRung}
|
||||||
data-testid="param-ladder"
|
data-testid="param-ladder"
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
onParam({
|
onParam({
|
||||||
ladderRung: Number(
|
ladderRung: Number(
|
||||||
e.target.value,
|
e.target.value,
|
||||||
) as PracticeParams["ladderRung"],
|
) as PracticeParams["ladderRung"],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
className="h-1.5 w-full accent-primary"
|
className="h-1.5 w-full accent-primary"
|
||||||
/>
|
/>
|
||||||
<span data-testid="param-ladder-level" className="text-xs">
|
<span data-testid="param-ladder-level" className="text-xs">
|
||||||
<span className="font-medium">
|
<span className="font-medium">
|
||||||
{LADDER_RUNGS[params.ladderRung].name}
|
{LADDER_RUNGS[params.ladderRung].name}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-muted-foreground">
|
<span className="text-muted-foreground">
|
||||||
{" "}
|
{" "}
|
||||||
— {LADDER_RUNGS[params.ladderRung].definition}
|
— {LADDER_RUNGS[params.ladderRung].definition}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<span className="flex items-center justify-between text-[11px] text-muted-foreground">
|
<span className="flex items-center justify-between text-[11px] text-muted-foreground">
|
||||||
Cue distance
|
Cue distance
|
||||||
<span className="text-muted-foreground/80">0 · 1 · 2</span>
|
<span className="text-muted-foreground/80">0 · 1 · 2</span>
|
||||||
</span>
|
</span>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
min={0}
|
min={0}
|
||||||
max={2}
|
max={2}
|
||||||
step={1}
|
step={1}
|
||||||
value={params.cueDistance}
|
value={params.cueDistance}
|
||||||
data-testid="param-cue"
|
data-testid="param-cue"
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
onParam({
|
onParam({
|
||||||
cueDistance: Number(
|
cueDistance: Number(
|
||||||
e.target.value,
|
e.target.value,
|
||||||
) as PracticeParams["cueDistance"],
|
) as PracticeParams["cueDistance"],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
className="h-1.5 w-full accent-primary"
|
className="h-1.5 w-full accent-primary"
|
||||||
/>
|
/>
|
||||||
<span data-testid="param-cue-level" className="text-xs">
|
<span data-testid="param-cue-level" className="text-xs">
|
||||||
<span className="font-medium">
|
<span className="font-medium">
|
||||||
{CUE_LEVELS[params.cueDistance].name}
|
{CUE_LEVELS[params.cueDistance].name}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-muted-foreground">
|
<span className="text-muted-foreground">
|
||||||
{" "}
|
{" "}
|
||||||
— {CUE_LEVELS[params.cueDistance].definition}
|
— {CUE_LEVELS[params.cueDistance].definition}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<span className="text-[11px] text-muted-foreground">
|
<span className="text-[11px] text-muted-foreground">
|
||||||
Presentation
|
Presentation
|
||||||
</span>
|
</span>
|
||||||
<div className="flex gap-1" data-testid="param-presentation">
|
<div className="flex gap-1" data-testid="param-presentation">
|
||||||
{(["theory", "application"] as const).map((pres) => (
|
{(["theory", "application"] as const).map((pres) => (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
key={pres}
|
key={pres}
|
||||||
data-testid={`param-presentation-${pres}`}
|
data-testid={`param-presentation-${pres}`}
|
||||||
onClick={() => onParam({ presentation: pres })}
|
onClick={() => onParam({ presentation: pres })}
|
||||||
className={`flex-1 rounded-md border px-3 py-1.5 text-xs transition-colors ${
|
className={`flex-1 rounded-md border px-3 py-1.5 text-xs transition-colors ${
|
||||||
params.presentation === pres
|
params.presentation === pres
|
||||||
? "border-primary bg-primary/10 font-medium text-foreground"
|
? "border-primary bg-primary/10 font-medium text-foreground"
|
||||||
: "text-muted-foreground hover:bg-accent"
|
: "text-muted-foreground hover:bg-accent"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{PRESENTATIONS[pres].name}
|
{PRESENTATIONS[pres].name}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<span
|
<span
|
||||||
data-testid="param-presentation-level"
|
data-testid="param-presentation-level"
|
||||||
className="text-xs text-muted-foreground"
|
className="text-xs text-muted-foreground"
|
||||||
>
|
>
|
||||||
{PRESENTATIONS[params.presentation].definition}
|
{PRESENTATIONS[params.presentation].definition}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{/* The learner's free-form note — the last word before create:
|
{/* The learner's free-form note — the last word before create:
|
||||||
wishes for the problems, weighed by the agents, nothing owed. */}
|
wishes for the problems, weighed by the agents, nothing owed. */}
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<span className="text-[11px] text-muted-foreground">
|
<span className="text-[11px] text-muted-foreground">
|
||||||
Anything else? (optional)
|
Anything else? (optional)
|
||||||
</span>
|
</span>
|
||||||
<textarea
|
<textarea
|
||||||
value={note}
|
value={note}
|
||||||
data-testid="practice-note"
|
data-testid="practice-note"
|
||||||
onChange={(e) => onNote(e.target.value)}
|
onChange={(e) => onNote(e.target.value)}
|
||||||
rows={3}
|
rows={3}
|
||||||
maxLength={2000}
|
maxLength={2000}
|
||||||
placeholder="Anything you want the problems to lean toward — situations, emphasis, context about you. The agents weigh it; nothing is promised."
|
placeholder="Anything you want the problems to lean toward — situations, emphasis, context about you. The agents weigh it; nothing is promised."
|
||||||
className="w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
className="w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{failure && (
|
{failure && (
|
||||||
<div
|
<div
|
||||||
data-testid="practice-dialog-error"
|
data-testid="practice-dialog-error"
|
||||||
className="mt-3 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive"
|
className="mt-3 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive"
|
||||||
>
|
>
|
||||||
{failure.code === "empty_selection"
|
{failure.code === "empty_selection"
|
||||||
? "Nothing practicable is left in that cluster — the graph changed."
|
? "Nothing practicable is left in that cluster — the graph changed."
|
||||||
: failure.error}
|
: failure.error}
|
||||||
{failure.status === 503 && (
|
{failure.status === 503 && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid="practice-dialog-open-settings"
|
data-testid="practice-dialog-open-settings"
|
||||||
onClick={onOpenSettings}
|
onClick={onOpenSettings}
|
||||||
className="ml-2 underline underline-offset-2"
|
className="ml-2 underline underline-offset-2"
|
||||||
>
|
>
|
||||||
Open settings
|
Open settings
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="mt-5 flex justify-end gap-2">
|
<div className="mt-5 flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
className="rounded-md px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
className="rounded-md px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid="practice-dialog-create"
|
data-testid="practice-dialog-create"
|
||||||
onClick={onRun}
|
onClick={onRun}
|
||||||
disabled={!canRun}
|
disabled={!canRun}
|
||||||
className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-40"
|
className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-40"
|
||||||
>
|
>
|
||||||
{busy ? "Creating…" : "Create"}
|
{busy ? "Creating…" : "Create"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The stateful wrapper: fetches the cluster list, runs the create POST
|
/** The stateful wrapper: fetches the cluster list, runs the create POST
|
||||||
* (nodeIds + the cluster's label as title + params), navigates on 202. */
|
* (nodeIds + the cluster's label as title + params), navigates on 202. */
|
||||||
export function PracticeDialog({ onClose }: { onClose: () => void }) {
|
export function PracticeDialog({
|
||||||
const router = useRouter();
|
mode = "cluster",
|
||||||
const { open: openSettings } = useSettingsDialog();
|
selection,
|
||||||
const [params, setParams] = useState<PracticeParams>({
|
onClose,
|
||||||
...DEFAULT_PRACTICE_PARAMS,
|
}: {
|
||||||
});
|
mode?: PracticeDialogMode;
|
||||||
const [note, setNote] = useState("");
|
selection?: PracticeSelection;
|
||||||
const [clusters, setClusters] = useState<GraphClusterGroup[] | null>(null);
|
onClose: () => void;
|
||||||
const [selectedKey, setSelectedKey] = useState<string | null>(null);
|
}) {
|
||||||
const [busy, setBusy] = useState(false);
|
const router = useRouter();
|
||||||
const [failure, setFailure] = useState<PracticeFailure | null>(null);
|
const { open: openSettings } = useSettingsDialog();
|
||||||
|
const [params, setParams] = useState<PracticeParams>({
|
||||||
|
...DEFAULT_PRACTICE_PARAMS,
|
||||||
|
});
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
const [clusters, setClusters] = useState<GraphClusterGroup[] | null>(null);
|
||||||
|
const [selectedKey, setSelectedKey] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [failure, setFailure] = useState<PracticeFailure | null>(null);
|
||||||
|
|
||||||
// The picker's truth is the graph's clustering (fresh on open).
|
// The picker's truth is the graph's clustering (fresh on open).
|
||||||
useEffect(() => {
|
// The picker's truth is the graph's clustering (fresh on open) —
|
||||||
let alive = true;
|
// cluster mode only; custom mode arrives with its selection in hand.
|
||||||
fetch("/api/graph/clusters", { cache: "no-store" })
|
useEffect(() => {
|
||||||
.then((res) => res.json() as Promise<{ clusters: GraphClusterGroup[] }>)
|
if (mode !== "cluster") return;
|
||||||
.then((d) => {
|
let alive = true;
|
||||||
if (alive) setClusters(d.clusters);
|
fetch("/api/graph/clusters", { cache: "no-store" })
|
||||||
})
|
.then((res) => res.json() as Promise<{ clusters: GraphClusterGroup[] }>)
|
||||||
.catch(() => {
|
.then((d) => {
|
||||||
if (alive) setClusters([]);
|
if (alive) setClusters(d.clusters);
|
||||||
});
|
})
|
||||||
return () => {
|
.catch(() => {
|
||||||
alive = false;
|
if (alive) setClusters([]);
|
||||||
};
|
});
|
||||||
}, []);
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Esc closes (claimed, the delete-session discipline).
|
// Esc closes (claimed, the delete-session discipline).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKeyDown = (e: KeyboardEvent) => {
|
const onKeyDown = (e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape") {
|
if (e.key === "Escape") {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
onClose();
|
onClose();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
window.addEventListener("keydown", onKeyDown);
|
window.addEventListener("keydown", onKeyDown);
|
||||||
return () => window.removeEventListener("keydown", onKeyDown);
|
return () => window.removeEventListener("keydown", onKeyDown);
|
||||||
}, [onClose]);
|
}, [onClose]);
|
||||||
|
|
||||||
const run = useCallback(async () => {
|
const run = useCallback(async () => {
|
||||||
const picked = (clusters ?? []).find((c) => c.key === selectedKey);
|
if (busy) return;
|
||||||
if (!picked || busy) return;
|
// The POST payload, by mode: custom mode sends the chain table's
|
||||||
setBusy(true);
|
// nodeIds with NO title (the pipeline stamps its dated default);
|
||||||
setFailure(null);
|
// cluster mode resolves the group + posts its label as title.
|
||||||
try {
|
let postNodeIds: string[];
|
||||||
const res = await fetch("/api/practice/sets", {
|
let postTitle: string | undefined;
|
||||||
method: "POST",
|
if (mode === "custom") {
|
||||||
headers: { "content-type": "application/json" },
|
if (!selection || selection.nodeIds.length === 0) return;
|
||||||
body: JSON.stringify({
|
postNodeIds = selection.nodeIds;
|
||||||
nodeIds: picked.nodeIds,
|
postTitle = undefined;
|
||||||
params,
|
} else {
|
||||||
title: picked.label ?? undefined,
|
const picked = (clusters ?? []).find((c) => c.key === selectedKey);
|
||||||
note: note.trim() || undefined,
|
if (!picked) return;
|
||||||
}),
|
postNodeIds = picked.nodeIds;
|
||||||
});
|
postTitle = picked.label ?? undefined;
|
||||||
const body = (await res.json()) as {
|
}
|
||||||
id?: string;
|
setBusy(true);
|
||||||
error?: string;
|
setFailure(null);
|
||||||
code?: string;
|
try {
|
||||||
};
|
const res = await fetch("/api/practice/sets", {
|
||||||
if (!res.ok || !body.id) {
|
method: "POST",
|
||||||
setFailure({
|
headers: { "content-type": "application/json" },
|
||||||
status: res.status,
|
body: JSON.stringify({
|
||||||
error: body.error ?? `Create failed (${res.status})`,
|
nodeIds: postNodeIds,
|
||||||
code: body.code,
|
params,
|
||||||
});
|
title: postTitle,
|
||||||
setBusy(false);
|
note: note.trim() || undefined,
|
||||||
return;
|
}),
|
||||||
}
|
});
|
||||||
router.push(`/practice/${body.id}`);
|
const body = (await res.json()) as {
|
||||||
} catch {
|
id?: string;
|
||||||
setFailure({
|
error?: string;
|
||||||
status: 0,
|
code?: string;
|
||||||
error: "Create failed — network error. Try again.",
|
};
|
||||||
});
|
if (!res.ok || !body.id) {
|
||||||
setBusy(false);
|
setFailure({
|
||||||
}
|
status: res.status,
|
||||||
}, [clusters, selectedKey, busy, params, note, router]);
|
error: body.error ?? `Create failed (${res.status})`,
|
||||||
|
code: body.code,
|
||||||
|
});
|
||||||
|
setBusy(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
router.push(`/practice/${body.id}`);
|
||||||
|
} catch {
|
||||||
|
setFailure({
|
||||||
|
status: 0,
|
||||||
|
error: "Create failed — network error. Try again.",
|
||||||
|
});
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [mode, selection, clusters, selectedKey, busy, params, note, router]);
|
||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-background/80"
|
className="fixed inset-0 z-50 flex items-center justify-center bg-background/80"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!busy) onClose();
|
if (!busy) onClose();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PracticeDialogBody
|
<PracticeDialogBody
|
||||||
params={params}
|
mode={mode}
|
||||||
onParam={(patch) => setParams((prev) => ({ ...prev, ...patch }))}
|
params={params}
|
||||||
note={note}
|
selection={selection}
|
||||||
onNote={setNote}
|
onParam={(patch) => setParams((prev) => ({ ...prev, ...patch }))}
|
||||||
clusters={clusters ?? []}
|
note={note}
|
||||||
selectedKey={selectedKey}
|
onNote={setNote}
|
||||||
onSelect={setSelectedKey}
|
clusters={clusters ?? []}
|
||||||
busy={busy}
|
selectedKey={selectedKey}
|
||||||
failure={failure}
|
onSelect={setSelectedKey}
|
||||||
onOpenSettings={() => openSettings()}
|
busy={busy}
|
||||||
onClose={onClose}
|
failure={failure}
|
||||||
onRun={() => void run()}
|
onOpenSettings={() => openSettings()}
|
||||||
/>
|
onClose={onClose}
|
||||||
</div>,
|
onRun={() => void run()}
|
||||||
document.body,
|
/>
|
||||||
);
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+379
-379
@@ -37,402 +37,402 @@ import { SidebarToggle } from "@/components/sidebar";
|
|||||||
|
|
||||||
/** One answerable problem: textarea + focus-gated dictation bar. */
|
/** One answerable problem: textarea + focus-gated dictation bar. */
|
||||||
export function ProblemBox({
|
export function ProblemBox({
|
||||||
problem,
|
problem,
|
||||||
draft,
|
draft,
|
||||||
onDraft,
|
onDraft,
|
||||||
}: {
|
}: {
|
||||||
problem: Pick<Problem, "id">;
|
problem: Pick<Problem, "id">;
|
||||||
draft: string;
|
draft: string;
|
||||||
onDraft: (text: string) => void;
|
onDraft: (text: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const [focused, setFocused] = useState(false);
|
const [focused, setFocused] = useState(false);
|
||||||
// The dictation appends into THIS box only (per-box instance).
|
// The dictation appends into THIS box only (per-box instance).
|
||||||
const dictation = useDictation({
|
const dictation = useDictation({
|
||||||
append: (text) => onDraft(text),
|
append: (text) => onDraft(text),
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="flex flex-col gap-1.5"
|
className="flex flex-col gap-1.5"
|
||||||
data-testid={`problem-box-${problem.id}`}
|
data-testid={`problem-box-${problem.id}`}
|
||||||
>
|
>
|
||||||
<textarea
|
<textarea
|
||||||
data-testid={`answer-${problem.id}`}
|
data-testid={`answer-${problem.id}`}
|
||||||
value={draft}
|
value={draft}
|
||||||
rows={5}
|
rows={5}
|
||||||
placeholder="Think out loud — dictation or typing, both fine."
|
placeholder="Think out loud — dictation or typing, both fine."
|
||||||
onChange={(e) => onDraft(e.target.value)}
|
onChange={(e) => onDraft(e.target.value)}
|
||||||
onFocus={() => setFocused(true)}
|
onFocus={() => setFocused(true)}
|
||||||
onBlur={() => setFocused(false)}
|
onBlur={() => setFocused(false)}
|
||||||
className="w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
className="w-full resize-y rounded-lg border bg-background px-3 py-2 text-sm outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||||
/>
|
/>
|
||||||
{focused && <DictationBar dictation={dictation} />}
|
{focused && <DictationBar dictation={dictation} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The exam page's pure body — exported for SSR pins. */
|
/** The exam page's pure body — exported for SSR pins. */
|
||||||
export function PracticeExamBody({
|
export function PracticeExamBody({
|
||||||
set,
|
set,
|
||||||
drafts,
|
drafts,
|
||||||
onDraft,
|
onDraft,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
submittingId,
|
submittingId,
|
||||||
submitErrors,
|
submitErrors,
|
||||||
liveGradeIds,
|
liveGradeIds,
|
||||||
}: {
|
}: {
|
||||||
set: ProblemSet;
|
set: ProblemSet;
|
||||||
drafts: Record<string, string>;
|
drafts: Record<string, string>;
|
||||||
onDraft: (problemId: string, text: string) => void;
|
onDraft: (problemId: string, text: string) => void;
|
||||||
/** Per-problem submit (owner 2026-09-29): ONE attempt per problem. */
|
/** Per-problem submit (owner 2026-09-29): ONE attempt per problem. */
|
||||||
onSubmit: (problemId: string) => void;
|
onSubmit: (problemId: string) => void;
|
||||||
/** The problem whose submit POST is in flight. */
|
/** The problem whose submit POST is in flight. */
|
||||||
submittingId: string | null;
|
submittingId: string | null;
|
||||||
/** Per-problem submit failures, keyed by problem id. */
|
/** Per-problem submit failures, keyed by problem id. */
|
||||||
submitErrors: Record<string, string>;
|
submitErrors: Record<string, string>;
|
||||||
/** Problems whose grade rows are LIVE (the poll's activity feed). */
|
/** Problems whose grade rows are LIVE (the poll's activity feed). */
|
||||||
liveGradeIds: ReadonlySet<string>;
|
liveGradeIds: ReadonlySet<string>;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-dvh">
|
<div className="flex h-dvh">
|
||||||
<div className="flex min-w-0 flex-1 flex-col">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
{/* The top bar (owner, UI round 2026-09-29): the new-session
|
{/* The top bar (owner, UI round 2026-09-29): the new-session
|
||||||
pattern — h-15, lh-drag (the Electron window-drag surface, so
|
pattern — h-15, lh-drag (the Electron window-drag surface, so
|
||||||
the traffic lights never cover content), the sidebar reopen
|
the traffic lights never cover content), the sidebar reopen
|
||||||
toggle first, the set title truncating beside it. */}
|
toggle first, the set title truncating beside it. */}
|
||||||
<header className="lh-drag flex h-15 items-center gap-3 border-b border-border px-3">
|
<header className="lh-drag flex h-15 items-center gap-3 border-b border-border px-3">
|
||||||
<SidebarToggle />
|
<SidebarToggle />
|
||||||
<div
|
<div
|
||||||
className="min-w-0 flex-1 truncate font-title text-3xl tracking-tight"
|
className="min-w-0 flex-1 truncate font-title text-3xl tracking-tight"
|
||||||
data-testid="practice-exam-title"
|
data-testid="practice-exam-title"
|
||||||
>
|
>
|
||||||
{set.title}
|
{set.title}
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<div className="relative flex min-h-0 flex-1">
|
<div className="relative flex min-h-0 flex-1">
|
||||||
<div
|
<div
|
||||||
className="h-full min-w-0 flex-1 overflow-y-auto"
|
className="h-full min-w-0 flex-1 overflow-y-auto"
|
||||||
data-testid="practice-exam-scroll"
|
data-testid="practice-exam-scroll"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6"
|
className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6"
|
||||||
data-testid="practice-exam"
|
data-testid="practice-exam"
|
||||||
>
|
>
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<p
|
<p
|
||||||
className="text-xs text-muted-foreground/80"
|
className="text-xs text-muted-foreground/80"
|
||||||
data-testid="practice-exam-levels"
|
data-testid="practice-exam-levels"
|
||||||
>
|
>
|
||||||
{LADDER_RUNGS[set.params.ladderRung].name} ·{" "}
|
{LADDER_RUNGS[set.params.ladderRung].name} ·{" "}
|
||||||
{CUE_LEVELS[set.params.cueDistance].name} ·{" "}
|
{CUE_LEVELS[set.params.cueDistance].name} ·{" "}
|
||||||
{PRESENTATIONS[set.params.presentation].name}
|
{PRESENTATIONS[set.params.presentation].name}
|
||||||
</p>
|
</p>
|
||||||
<p
|
<p
|
||||||
className="text-sm text-muted-foreground"
|
className="text-sm text-muted-foreground"
|
||||||
data-testid="practice-exam-status"
|
data-testid="practice-exam-status"
|
||||||
>
|
>
|
||||||
{set.status === "partitioning" && "Partitioning the chains…"}
|
{set.status === "partitioning" && "Partitioning the chains…"}
|
||||||
{set.status === "generating" &&
|
{set.status === "generating" &&
|
||||||
`Generating — ${set.problems.filter((p) => p.status === "ready").length}/${set.problems.length} problems ready`}
|
`Generating — ${set.problems.filter((p) => p.status === "ready").length}/${set.problems.length} problems ready`}
|
||||||
{set.status === "error" &&
|
{set.status === "error" &&
|
||||||
(set.error ?? "Something went wrong")}
|
(set.error ?? "Something went wrong")}
|
||||||
{set.status === "ready" &&
|
{set.status === "ready" &&
|
||||||
(liveGradeIds.size > 0
|
(liveGradeIds.size > 0
|
||||||
? "Grading your answers…"
|
? "Grading your answers…"
|
||||||
: `${set.problems.length} problems · ${set.problems.filter((p) => p.grade).length} graded`)}
|
: `${set.problems.length} problems · ${set.problems.filter((p) => p.grade).length} graded`)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{set.problems.map((problem, i) => (
|
{set.problems.map((problem, i) => (
|
||||||
<section
|
<section
|
||||||
key={problem.id}
|
key={problem.id}
|
||||||
className="rounded-xl border bg-card p-4"
|
className="rounded-xl border bg-card p-4"
|
||||||
data-testid={`problem-${problem.id}`}
|
data-testid={`problem-${problem.id}`}
|
||||||
>
|
>
|
||||||
<h2 className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
<h2 className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||||
Problem {i + 1}
|
Problem {i + 1}
|
||||||
</h2>
|
</h2>
|
||||||
{problem.status === "generating" ? (
|
{problem.status === "generating" ? (
|
||||||
// The stub: propositions NEVER surface (never-announce law).
|
// The stub: propositions NEVER surface (never-announce law).
|
||||||
<div
|
<div
|
||||||
className="flex items-center gap-2 text-sm text-muted-foreground"
|
className="flex items-center gap-2 text-sm text-muted-foreground"
|
||||||
data-testid={`generating-${problem.id}`}
|
data-testid={`generating-${problem.id}`}
|
||||||
>
|
>
|
||||||
<BrailleSpinner className="size-4" />
|
<BrailleSpinner className="size-4" />
|
||||||
Generating problem…
|
Generating problem…
|
||||||
</div>
|
</div>
|
||||||
) : problem.status === "error" ? (
|
) : problem.status === "error" ? (
|
||||||
<p
|
<p
|
||||||
className="text-sm text-destructive"
|
className="text-sm text-destructive"
|
||||||
data-testid={`problem-error-${problem.id}`}
|
data-testid={`problem-error-${problem.id}`}
|
||||||
>
|
>
|
||||||
This problem failed to generate
|
This problem failed to generate
|
||||||
{problem.error ? ` — ${problem.error}` : ""}.
|
{problem.error ? ` — ${problem.error}` : ""}.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<div className="lh-prose text-sm">
|
<div className="lh-prose text-sm">
|
||||||
<MessageResponse mode="static">
|
<MessageResponse mode="static">
|
||||||
{restoreMathEscapes(problem.statement)}
|
{restoreMathEscapes(problem.statement)}
|
||||||
</MessageResponse>
|
</MessageResponse>
|
||||||
</div>
|
</div>
|
||||||
{problem.answer === undefined ? (
|
{problem.answer === undefined ? (
|
||||||
// ANSWERABLE (owner 2026-09-29): the box + its OWN submit
|
// ANSWERABLE (owner 2026-09-29): the box + its OWN submit
|
||||||
// button — one attempt, submitted the moment it's clicked.
|
// button — one attempt, submitted the moment it's clicked.
|
||||||
<div className="flex flex-col items-start gap-2">
|
<div className="flex flex-col items-start gap-2">
|
||||||
<div className="w-full">
|
<div className="w-full">
|
||||||
<ProblemBox
|
<ProblemBox
|
||||||
problem={problem}
|
problem={problem}
|
||||||
draft={drafts[problem.id] ?? ""}
|
draft={drafts[problem.id] ?? ""}
|
||||||
onDraft={(text) => onDraft(problem.id, text)}
|
onDraft={(text) => onDraft(problem.id, text)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid={`practice-submit-${problem.id}`}
|
data-testid={`practice-submit-${problem.id}`}
|
||||||
onClick={() => onSubmit(problem.id)}
|
onClick={() => onSubmit(problem.id)}
|
||||||
disabled={
|
disabled={
|
||||||
set.status !== "ready" ||
|
set.status !== "ready" ||
|
||||||
(drafts[problem.id] ?? "").trim() === "" ||
|
(drafts[problem.id] ?? "").trim() === "" ||
|
||||||
submittingId !== null
|
submittingId !== null
|
||||||
}
|
}
|
||||||
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-40"
|
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-40"
|
||||||
>
|
>
|
||||||
{submittingId === problem.id
|
{submittingId === problem.id
|
||||||
? "Submitting…"
|
? "Submitting…"
|
||||||
: "Submit answer"}
|
: "Submit answer"}
|
||||||
</button>
|
</button>
|
||||||
{submitErrors[problem.id] && (
|
{submitErrors[problem.id] && (
|
||||||
<p
|
<p
|
||||||
data-testid={`practice-submit-error-${problem.id}`}
|
data-testid={`practice-submit-error-${problem.id}`}
|
||||||
className="text-sm text-destructive"
|
className="text-sm text-destructive"
|
||||||
>
|
>
|
||||||
{submitErrors[problem.id]}
|
{submitErrors[problem.id]}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// SUBMITTED (owner 2026-09-29): the answer locks, the
|
// SUBMITTED (owner 2026-09-29): the answer locks, the
|
||||||
// model solution reveals INSTANTLY, the rubric stays
|
// model solution reveals INSTANTLY, the rubric stays
|
||||||
// collapsed, and the grade lands live when it lands.
|
// collapsed, and the grade lands live when it lands.
|
||||||
<div className="mt-4 flex flex-col gap-3">
|
<div className="mt-4 flex flex-col gap-3">
|
||||||
<textarea
|
<textarea
|
||||||
data-testid={`answer-${problem.id}`}
|
data-testid={`answer-${problem.id}`}
|
||||||
value={problem.answer}
|
value={problem.answer}
|
||||||
readOnly
|
readOnly
|
||||||
rows={5}
|
rows={5}
|
||||||
className="w-full resize-y rounded-lg border bg-muted/40 px-3 py-2 text-sm text-muted-foreground"
|
className="w-full resize-y rounded-lg border bg-muted/40 px-3 py-2 text-sm text-muted-foreground"
|
||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
className="rounded-lg border bg-background p-3"
|
className="rounded-lg border bg-background p-3"
|
||||||
data-testid={`reveal-${problem.id}`}
|
data-testid={`reveal-${problem.id}`}
|
||||||
>
|
>
|
||||||
{problem.grade ? (
|
{problem.grade ? (
|
||||||
<div className="flex flex-col gap-1.5">
|
<div className="flex flex-col gap-1.5">
|
||||||
<div className="flex items-baseline gap-2">
|
<div className="flex items-baseline gap-2">
|
||||||
<span
|
<span
|
||||||
data-testid={`grade-${problem.id}`}
|
data-testid={`grade-${problem.id}`}
|
||||||
className="font-mono text-sm font-medium"
|
className="font-mono text-sm font-medium"
|
||||||
>
|
>
|
||||||
{problem.grade.score}/10
|
{problem.grade.score}/10
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className="lh-prose text-sm"
|
className="lh-prose text-sm"
|
||||||
data-testid={`reasoning-${problem.id}`}
|
data-testid={`reasoning-${problem.id}`}
|
||||||
>
|
>
|
||||||
<MessageResponse mode="static">
|
<MessageResponse mode="static">
|
||||||
{restoreMathEscapes(
|
{restoreMathEscapes(
|
||||||
problem.grade.reasoning,
|
problem.grade.reasoning,
|
||||||
)}
|
)}
|
||||||
</MessageResponse>
|
</MessageResponse>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : liveGradeIds.has(problem.id) ? (
|
) : liveGradeIds.has(problem.id) ? (
|
||||||
<div
|
<div
|
||||||
className="flex items-center gap-2 text-sm text-muted-foreground"
|
className="flex items-center gap-2 text-sm text-muted-foreground"
|
||||||
data-testid={`grading-${problem.id}`}
|
data-testid={`grading-${problem.id}`}
|
||||||
>
|
>
|
||||||
<BrailleSpinner className="size-4" />
|
<BrailleSpinner className="size-4" />
|
||||||
Grading…
|
Grading…
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<p
|
<p
|
||||||
className="text-sm text-muted-foreground"
|
className="text-sm text-muted-foreground"
|
||||||
data-testid={`grade-interrupted-${problem.id}`}
|
data-testid={`grade-interrupted-${problem.id}`}
|
||||||
>
|
>
|
||||||
Grade interrupted — the answer stands.
|
Grade interrupted — the answer stands.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<div className="mt-3 text-xs uppercase tracking-wide text-muted-foreground">
|
<div className="mt-3 text-xs uppercase tracking-wide text-muted-foreground">
|
||||||
Model solution
|
Model solution
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className="lh-prose text-sm"
|
className="lh-prose text-sm"
|
||||||
data-testid={`solution-${problem.id}`}
|
data-testid={`solution-${problem.id}`}
|
||||||
>
|
>
|
||||||
<MessageResponse mode="static">
|
<MessageResponse mode="static">
|
||||||
{restoreMathEscapes(problem.solution)}
|
{restoreMathEscapes(problem.solution)}
|
||||||
</MessageResponse>
|
</MessageResponse>
|
||||||
</div>
|
</div>
|
||||||
<details
|
<details
|
||||||
className="mt-3"
|
className="mt-3"
|
||||||
data-testid={`rubric-${problem.id}`}
|
data-testid={`rubric-${problem.id}`}
|
||||||
>
|
>
|
||||||
<summary className="cursor-pointer select-none text-xs uppercase tracking-wide text-muted-foreground">
|
<summary className="cursor-pointer select-none text-xs uppercase tracking-wide text-muted-foreground">
|
||||||
Rubric
|
Rubric
|
||||||
</summary>
|
</summary>
|
||||||
<div className="mt-2 lh-prose text-sm">
|
<div className="mt-2 lh-prose text-sm">
|
||||||
<MessageResponse mode="static">
|
<MessageResponse mode="static">
|
||||||
{restoreMathEscapes(problem.rubric)}
|
{restoreMathEscapes(problem.rubric)}
|
||||||
</MessageResponse>
|
</MessageResponse>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PracticeExam({ initial }: { initial: ProblemSet }) {
|
export function PracticeExam({ initial }: { initial: ProblemSet }) {
|
||||||
const [set, setSet] = useState<ProblemSet>(initial);
|
const [set, setSet] = useState<ProblemSet>(initial);
|
||||||
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||||
const [submittingId, setSubmittingId] = useState<string | null>(null);
|
const [submittingId, setSubmittingId] = useState<string | null>(null);
|
||||||
const [submitErrors, setSubmitErrors] = useState<Record<string, string>>({});
|
const [submitErrors, setSubmitErrors] = useState<Record<string, string>>({});
|
||||||
// Which problems' grade rows are LIVE (activity feed) — drives the
|
// Which problems' grade rows are LIVE (activity feed) — drives the
|
||||||
// per-problem "Grading…" spinners and the status line.
|
// per-problem "Grading…" spinners and the status line.
|
||||||
const [liveGradeIds, setLiveGradeIds] = useState<Set<string>>(new Set());
|
const [liveGradeIds, setLiveGradeIds] = useState<Set<string>>(new Set());
|
||||||
// True from a successful submit until the feed shows no live grade
|
// True from a successful submit until the feed shows no live grade
|
||||||
// rows for this set — keeps the poll alive across refetches.
|
// rows for this set — keeps the poll alive across refetches.
|
||||||
const [gradingLive, setGradingLive] = useState(false);
|
const [gradingLive, setGradingLive] = useState(false);
|
||||||
const mounted = useRef(true);
|
const mounted = useRef(true);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
mounted.current = true;
|
mounted.current = true;
|
||||||
return () => {
|
return () => {
|
||||||
mounted.current = false;
|
mounted.current = false;
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const refetch = useCallback(async () => {
|
const refetch = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/practice/sets/${initial.id}`, {
|
const res = await fetch(`/api/practice/sets/${initial.id}`, {
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
if (!res.ok) return;
|
if (!res.ok) return;
|
||||||
const d = (await res.json()) as { set: ProblemSet };
|
const d = (await res.json()) as { set: ProblemSet };
|
||||||
if (mounted.current) setSet(d.set);
|
if (mounted.current) setSet(d.set);
|
||||||
} catch {
|
} catch {
|
||||||
// transient poll failures keep the last snapshot
|
// transient poll failures keep the last snapshot
|
||||||
}
|
}
|
||||||
}, [initial.id]);
|
}, [initial.id]);
|
||||||
|
|
||||||
// The poll: while not ready (generation), or while a grading run is
|
// The poll: while not ready (generation), or while a grading run is
|
||||||
// live for this set with outstanding ungraded answers. The activity
|
// live for this set with outstanding ungraded answers. The activity
|
||||||
// feed's practice rows are ROW-KEYED (setId:grade:problemId) — the
|
// feed's practice rows are ROW-KEYED (setId:grade:problemId) — the
|
||||||
// live rows name exactly which grades are pending; a dropped grade
|
// live rows name exactly which grades are pending; a dropped grade
|
||||||
// (no live row) settles the page instead of polling forever.
|
// (no live row) settles the page instead of polling forever.
|
||||||
const pendingGrade = set.problems.some(
|
const pendingGrade = set.problems.some(
|
||||||
(p) => p.answer !== undefined && !p.grade,
|
(p) => p.answer !== undefined && !p.grade,
|
||||||
);
|
);
|
||||||
const needsPoll = set.status !== "ready" || (gradingLive && pendingGrade);
|
const needsPoll = set.status !== "ready" || (gradingLive && pendingGrade);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!needsPoll) return;
|
if (!needsPoll) return;
|
||||||
let stopped = false;
|
let stopped = false;
|
||||||
const tick = async () => {
|
const tick = async () => {
|
||||||
await refetch();
|
await refetch();
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/activity", { cache: "no-store" });
|
const res = await fetch("/api/activity", { cache: "no-store" });
|
||||||
if (!res.ok) return;
|
if (!res.ok) return;
|
||||||
const feed = (await res.json()) as {
|
const feed = (await res.json()) as {
|
||||||
practice?: Array<{ id: string; kind: string }>;
|
practice?: Array<{ id: string; kind: string }>;
|
||||||
};
|
};
|
||||||
if (!stopped && mounted.current) {
|
if (!stopped && mounted.current) {
|
||||||
const prefix = `${initial.id}:grade:`;
|
const prefix = `${initial.id}:grade:`;
|
||||||
const pids = (feed.practice ?? [])
|
const pids = (feed.practice ?? [])
|
||||||
.filter((row) => row.id.startsWith(prefix))
|
.filter((row) => row.id.startsWith(prefix))
|
||||||
.map((row) => row.id.slice(prefix.length));
|
.map((row) => row.id.slice(prefix.length));
|
||||||
setLiveGradeIds(new Set(pids));
|
setLiveGradeIds(new Set(pids));
|
||||||
setGradingLive(pids.length > 0);
|
setGradingLive(pids.length > 0);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// keep the last liveness read
|
// keep the last liveness read
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
void tick();
|
void tick();
|
||||||
const t = setInterval(() => void tick(), 2000);
|
const t = setInterval(() => void tick(), 2000);
|
||||||
return () => {
|
return () => {
|
||||||
stopped = true;
|
stopped = true;
|
||||||
clearInterval(t);
|
clearInterval(t);
|
||||||
};
|
};
|
||||||
}, [needsPoll, refetch, initial.id]);
|
}, [needsPoll, refetch, initial.id]);
|
||||||
|
|
||||||
// ONE attempt per problem (owner 2026-09-29): the submit posts THAT
|
// ONE attempt per problem (owner 2026-09-29): the submit posts THAT
|
||||||
// problem's answer alone; the server refuses a second submission
|
// problem's answer alone; the server refuses a second submission
|
||||||
// forever after. On success the box locks (answer persisted) and the
|
// forever after. On success the box locks (answer persisted) and the
|
||||||
// reveal shows instantly; the grade arrives via the poll.
|
// reveal shows instantly; the grade arrives via the poll.
|
||||||
const submit = useCallback(
|
const submit = useCallback(
|
||||||
async (problemId: string) => {
|
async (problemId: string) => {
|
||||||
if (submittingId !== null) return;
|
if (submittingId !== null) return;
|
||||||
const p = set.problems.find((q) => q.id === problemId);
|
const p = set.problems.find((q) => q.id === problemId);
|
||||||
if (!p || p.answer !== undefined) return; // done problems never resubmit
|
if (!p || p.answer !== undefined) return; // done problems never resubmit
|
||||||
const text = drafts[problemId] ?? "";
|
const text = drafts[problemId] ?? "";
|
||||||
if (text.trim() === "") return;
|
if (text.trim() === "") return;
|
||||||
setSubmittingId(problemId);
|
setSubmittingId(problemId);
|
||||||
setSubmitErrors((prev) => {
|
setSubmitErrors((prev) => {
|
||||||
const next = { ...prev };
|
const next = { ...prev };
|
||||||
delete next[problemId];
|
delete next[problemId];
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/practice/sets/${set.id}/answers`, {
|
const res = await fetch(`/api/practice/sets/${set.id}/answers`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/json" },
|
headers: { "content-type": "application/json" },
|
||||||
body: JSON.stringify({ answers: [{ problemId, text }] }),
|
body: JSON.stringify({ answers: [{ problemId, text }] }),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const body = (await res.json().catch(() => ({}))) as {
|
const body = (await res.json().catch(() => ({}))) as {
|
||||||
error?: string;
|
error?: string;
|
||||||
};
|
};
|
||||||
setSubmitErrors((prev) => ({
|
setSubmitErrors((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
[problemId]: body.error ?? `Submit failed (${res.status})`,
|
[problemId]: body.error ?? `Submit failed (${res.status})`,
|
||||||
}));
|
}));
|
||||||
setSubmittingId(null);
|
setSubmittingId(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSubmittingId(null);
|
setSubmittingId(null);
|
||||||
setGradingLive(true); // the grade lands via the poll
|
setGradingLive(true); // the grade lands via the poll
|
||||||
await refetch();
|
await refetch();
|
||||||
} catch {
|
} catch {
|
||||||
setSubmitErrors((prev) => ({
|
setSubmitErrors((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
[problemId]: "Submit failed — network error. Try again.",
|
[problemId]: "Submit failed — network error. Try again.",
|
||||||
}));
|
}));
|
||||||
setSubmittingId(null);
|
setSubmittingId(null);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[submittingId, set, drafts, refetch],
|
[submittingId, set, drafts, refetch],
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PracticeExamBody
|
<PracticeExamBody
|
||||||
set={set}
|
set={set}
|
||||||
drafts={drafts}
|
drafts={drafts}
|
||||||
onDraft={(problemId, text) =>
|
onDraft={(problemId, text) =>
|
||||||
setDrafts((prev) => ({ ...prev, [problemId]: text }))
|
setDrafts((prev) => ({ ...prev, [problemId]: text }))
|
||||||
}
|
}
|
||||||
onSubmit={(problemId) => void submit(problemId)}
|
onSubmit={(problemId) => void submit(problemId)}
|
||||||
submittingId={submittingId}
|
submittingId={submittingId}
|
||||||
submitErrors={submitErrors}
|
submitErrors={submitErrors}
|
||||||
liveGradeIds={liveGradeIds}
|
liveGradeIds={liveGradeIds}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+240
-240
@@ -19,273 +19,273 @@ import { PracticeDialog } from "@/components/practice-dialog";
|
|||||||
|
|
||||||
/** A set's status word — plain and honest, no invented progress. */
|
/** A set's status word — plain and honest, no invented progress. */
|
||||||
export function setStatusWord(set: Pick<ProblemSet, "status">): string {
|
export function setStatusWord(set: Pick<ProblemSet, "status">): string {
|
||||||
return set.status === "partitioning"
|
return set.status === "partitioning"
|
||||||
? "partitioning"
|
? "partitioning"
|
||||||
: set.status === "generating"
|
: set.status === "generating"
|
||||||
? "generating"
|
? "generating"
|
||||||
: set.status;
|
: set.status;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The list's pure body — exported for SSR pins. Rows are buttons
|
/** The list's pure body — exported for SSR pins. Rows are buttons
|
||||||
* (click-through); the delete affordance is a nested icon button. */
|
* (click-through); the delete affordance is a nested icon button. */
|
||||||
export function PracticeListBody({
|
export function PracticeListBody({
|
||||||
sets,
|
sets,
|
||||||
onOpen,
|
onOpen,
|
||||||
onDelete,
|
onDelete,
|
||||||
onNew,
|
onNew,
|
||||||
}: {
|
}: {
|
||||||
sets: ProblemSet[];
|
sets: ProblemSet[];
|
||||||
onOpen: (id: string) => void;
|
onOpen: (id: string) => void;
|
||||||
onDelete: (set: ProblemSet) => void;
|
onDelete: (set: ProblemSet) => void;
|
||||||
onNew: () => void;
|
onNew: () => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-dvh">
|
<div className="flex h-dvh">
|
||||||
<div className="flex min-w-0 flex-1 flex-col">
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
{/* The top bar (owner, UI round 2026-09-29): the new-session
|
{/* The top bar (owner, UI round 2026-09-29): the new-session
|
||||||
pattern — h-15, lh-drag (the Electron window-drag surface),
|
pattern — h-15, lh-drag (the Electron window-drag surface),
|
||||||
the sidebar reopen toggle first, "Practice" beside it, the
|
the sidebar reopen toggle first, "Practice" beside it, the
|
||||||
page's one action at the right edge (lh-no-drag — it must
|
page's one action at the right edge (lh-no-drag — it must
|
||||||
stay clickable inside the drag band). */}
|
stay clickable inside the drag band). */}
|
||||||
<header className="lh-drag flex h-15 items-center gap-3 border-b border-border px-3">
|
<header className="lh-drag flex h-15 items-center gap-3 border-b border-border px-3">
|
||||||
<SidebarToggle />
|
<SidebarToggle />
|
||||||
<div className="min-w-0 flex-1 truncate font-title text-3xl tracking-tight">
|
<div className="min-w-0 flex-1 truncate font-title text-3xl tracking-tight">
|
||||||
Practice
|
Practice
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid="practice-new"
|
data-testid="practice-new"
|
||||||
onClick={onNew}
|
onClick={onNew}
|
||||||
className="lh-no-drag flex shrink-0 items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm transition-colors hover:bg-accent"
|
className="lh-no-drag flex shrink-0 items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm transition-colors hover:bg-accent"
|
||||||
>
|
>
|
||||||
<PlusIcon className="size-3.5" />
|
<PlusIcon className="size-3.5" />
|
||||||
New problem set
|
New problem set
|
||||||
</button>
|
</button>
|
||||||
</header>
|
</header>
|
||||||
<div className="relative flex min-h-0 flex-1">
|
<div className="relative flex min-h-0 flex-1">
|
||||||
<div
|
<div
|
||||||
className="h-full min-w-0 flex-1 overflow-y-auto"
|
className="h-full min-w-0 flex-1 overflow-y-auto"
|
||||||
data-testid="practice-list-scroll"
|
data-testid="practice-list-scroll"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="mx-auto flex w-full max-w-3xl flex-col gap-3 p-6"
|
className="mx-auto flex w-full max-w-3xl flex-col gap-3 p-6"
|
||||||
data-testid="practice-list"
|
data-testid="practice-list"
|
||||||
>
|
>
|
||||||
{sets.length === 0 && (
|
{sets.length === 0 && (
|
||||||
<div
|
<div
|
||||||
className="rounded-xl border bg-card p-6 text-sm text-muted-foreground"
|
className="rounded-xl border bg-card p-6 text-sm text-muted-foreground"
|
||||||
data-testid="practice-empty"
|
data-testid="practice-empty"
|
||||||
>
|
>
|
||||||
No problem sets yet — create one from a session.
|
No problem sets yet — create one from a session.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
{sets.map((set) => {
|
{sets.map((set) => {
|
||||||
const ready = set.problems.filter(
|
const ready = set.problems.filter(
|
||||||
(p) => p.status === "ready",
|
(p) => p.status === "ready",
|
||||||
).length;
|
).length;
|
||||||
const graded = set.problems.filter((p) => p.grade).length;
|
const graded = set.problems.filter((p) => p.grade).length;
|
||||||
return (
|
return (
|
||||||
<div key={set.id} className="flex items-stretch gap-1">
|
<div key={set.id} className="flex items-stretch gap-1">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid={`practice-row-${set.id}`}
|
data-testid={`practice-row-${set.id}`}
|
||||||
onClick={() => onOpen(set.id)}
|
onClick={() => onOpen(set.id)}
|
||||||
className="flex flex-1 items-center justify-between gap-4 rounded-xl border bg-card px-4 py-3 text-left transition-colors hover:bg-accent/50"
|
className="flex flex-1 items-center justify-between gap-4 rounded-xl border bg-card px-4 py-3 text-left transition-colors hover:bg-accent/50"
|
||||||
>
|
>
|
||||||
<span className="min-w-0">
|
<span className="min-w-0">
|
||||||
<span className="block truncate font-medium">
|
<span className="block truncate font-medium">
|
||||||
{set.title}
|
{set.title}
|
||||||
</span>
|
</span>
|
||||||
<span className="block text-xs text-muted-foreground">
|
<span className="block text-xs text-muted-foreground">
|
||||||
{set.createdAt.slice(0, 10)} ·{" "}
|
{set.createdAt.slice(0, 10)} ·{" "}
|
||||||
{set.problems.length > 0
|
{set.problems.length > 0
|
||||||
? `${ready}/${set.problems.length} problems`
|
? `${ready}/${set.problems.length} problems`
|
||||||
: "no problems yet"}
|
: "no problems yet"}
|
||||||
{graded > 0 ? ` · ${graded} graded` : ""}
|
{graded > 0 ? ` · ${graded} graded` : ""}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
data-testid={`practice-status-${set.id}`}
|
data-testid={`practice-status-${set.id}`}
|
||||||
className={`shrink-0 text-xs uppercase tracking-wide ${
|
className={`shrink-0 text-xs uppercase tracking-wide ${
|
||||||
set.status === "error"
|
set.status === "error"
|
||||||
? "text-destructive"
|
? "text-destructive"
|
||||||
: "text-muted-foreground"
|
: "text-muted-foreground"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{setStatusWord(set)}
|
{setStatusWord(set)}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid={`practice-delete-${set.id}`}
|
data-testid={`practice-delete-${set.id}`}
|
||||||
aria-label={`Delete ${set.title}`}
|
aria-label={`Delete ${set.title}`}
|
||||||
onClick={() => onDelete(set)}
|
onClick={() => onDelete(set)}
|
||||||
className="flex items-center rounded-xl border px-3 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
|
className="flex items-center rounded-xl border px-3 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
|
||||||
>
|
>
|
||||||
<TrashIcon className="size-4" />
|
<TrashIcon className="size-4" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The delete confirm — the delete-session dialog's shape (no mode
|
/** The delete confirm — the delete-session dialog's shape (no mode
|
||||||
* checkbox: a set has no preserve-graph question). Pure body + portal
|
* checkbox: a set has no preserve-graph question). Pure body + portal
|
||||||
* wrapper. */
|
* wrapper. */
|
||||||
export function DeleteSetBody({
|
export function DeleteSetBody({
|
||||||
title,
|
title,
|
||||||
busy,
|
busy,
|
||||||
failure,
|
failure,
|
||||||
onClose,
|
onClose,
|
||||||
onRun,
|
onRun,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
busy: boolean;
|
busy: boolean;
|
||||||
failure: string | null;
|
failure: string | null;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onRun: () => void;
|
onRun: () => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
role="dialog"
|
role="dialog"
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
aria-label="Delete problem set"
|
aria-label="Delete problem set"
|
||||||
data-testid="delete-set-dialog"
|
data-testid="delete-set-dialog"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
className="w-[32rem] max-w-[calc(100vw-2rem)] rounded-xl border bg-card p-5 shadow-xl"
|
className="w-[32rem] max-w-[calc(100vw-2rem)] rounded-xl border bg-card p-5 shadow-xl"
|
||||||
>
|
>
|
||||||
<h2 className="font-title text-2xl tracking-tight text-destructive">
|
<h2 className="font-title text-2xl tracking-tight text-destructive">
|
||||||
Delete problem set?
|
Delete problem set?
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-2 font-mono text-sm">{title}</p>
|
<p className="mt-2 font-mono text-sm">{title}</p>
|
||||||
<p className="mt-3 text-sm text-muted-foreground">
|
<p className="mt-3 text-sm text-muted-foreground">
|
||||||
The set and its problems are removed. Nothing in the graph or your
|
The set and its problems are removed. Nothing in the graph or your
|
||||||
sessions changes.
|
sessions changes.
|
||||||
</p>
|
</p>
|
||||||
{failure && (
|
{failure && (
|
||||||
<p
|
<p
|
||||||
data-testid="delete-set-error"
|
data-testid="delete-set-error"
|
||||||
className="mt-3 text-sm text-destructive"
|
className="mt-3 text-sm text-destructive"
|
||||||
>
|
>
|
||||||
{failure}
|
{failure}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<div className="mt-5 flex justify-end gap-2">
|
<div className="mt-5 flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
className="rounded-md px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
className="rounded-md px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
data-testid="delete-set-run"
|
data-testid="delete-set-run"
|
||||||
onClick={onRun}
|
onClick={onRun}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
className="rounded-md bg-destructive px-3 py-1.5 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90 disabled:opacity-40"
|
className="rounded-md bg-destructive px-3 py-1.5 text-sm font-medium text-destructive-foreground transition-colors hover:bg-destructive/90 disabled:opacity-40"
|
||||||
>
|
>
|
||||||
{busy ? "Deleting…" : "Delete"}
|
{busy ? "Deleting…" : "Delete"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PracticeListPage({
|
export function PracticeListPage({
|
||||||
initialSets,
|
initialSets,
|
||||||
}: {
|
}: {
|
||||||
initialSets: ProblemSet[];
|
initialSets: ProblemSet[];
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [sets, setSets] = useState<ProblemSet[]>(initialSets);
|
const [sets, setSets] = useState<ProblemSet[]>(initialSets);
|
||||||
const [creating, setCreating] = useState(false);
|
const [creating, setCreating] = useState(false);
|
||||||
const [deleting, setDeleting] = useState<ProblemSet | null>(null);
|
const [deleting, setDeleting] = useState<ProblemSet | null>(null);
|
||||||
const [deleteBusy, setDeleteBusy] = useState(false);
|
const [deleteBusy, setDeleteBusy] = useState(false);
|
||||||
const [deleteFailure, setDeleteFailure] = useState<string | null>(null);
|
const [deleteFailure, setDeleteFailure] = useState<string | null>(null);
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/practice/sets", { cache: "no-store" });
|
const res = await fetch("/api/practice/sets", { cache: "no-store" });
|
||||||
if (!res.ok) return;
|
if (!res.ok) return;
|
||||||
const d = (await res.json()) as { sets: ProblemSet[] };
|
const d = (await res.json()) as { sets: ProblemSet[] };
|
||||||
setSets(d.sets);
|
setSets(d.sets);
|
||||||
} catch {
|
} catch {
|
||||||
// a transient failure on the poll keeps the last snapshot
|
// a transient failure on the poll keeps the last snapshot
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// The reveal poll: while any set is partitioning/generating, statuses
|
// The reveal poll: while any set is partitioning/generating, statuses
|
||||||
// live-update; a settled list goes quiet.
|
// live-update; a settled list goes quiet.
|
||||||
const anyRunning = sets.some(
|
const anyRunning = sets.some(
|
||||||
(s) => s.status === "partitioning" || s.status === "generating",
|
(s) => s.status === "partitioning" || s.status === "generating",
|
||||||
);
|
);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!anyRunning) return;
|
if (!anyRunning) return;
|
||||||
const t = setInterval(() => void refresh(), 2000);
|
const t = setInterval(() => void refresh(), 2000);
|
||||||
return () => clearInterval(t);
|
return () => clearInterval(t);
|
||||||
}, [anyRunning, refresh]);
|
}, [anyRunning, refresh]);
|
||||||
|
|
||||||
const runDelete = useCallback(async () => {
|
const runDelete = useCallback(async () => {
|
||||||
if (!deleting || deleteBusy) return;
|
if (!deleting || deleteBusy) return;
|
||||||
setDeleteBusy(true);
|
setDeleteBusy(true);
|
||||||
setDeleteFailure(null);
|
setDeleteFailure(null);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/practice/sets/${deleting.id}`, {
|
const res = await fetch(`/api/practice/sets/${deleting.id}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const body = (await res.json().catch(() => ({}))) as { error?: string };
|
const body = (await res.json().catch(() => ({}))) as { error?: string };
|
||||||
setDeleteFailure(body.error ?? `Delete failed (${res.status})`);
|
setDeleteFailure(body.error ?? `Delete failed (${res.status})`);
|
||||||
setDeleteBusy(false);
|
setDeleteBusy(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setDeleting(null);
|
setDeleting(null);
|
||||||
setDeleteBusy(false);
|
setDeleteBusy(false);
|
||||||
await refresh();
|
await refresh();
|
||||||
} catch {
|
} catch {
|
||||||
setDeleteFailure("Delete failed — network error. Try again.");
|
setDeleteFailure("Delete failed — network error. Try again.");
|
||||||
setDeleteBusy(false);
|
setDeleteBusy(false);
|
||||||
}
|
}
|
||||||
}, [deleting, deleteBusy, refresh]);
|
}, [deleting, deleteBusy, refresh]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PracticeListBody
|
<PracticeListBody
|
||||||
sets={sets}
|
sets={sets}
|
||||||
onOpen={(id) => router.push(`/practice/${id}`)}
|
onOpen={(id) => router.push(`/practice/${id}`)}
|
||||||
onDelete={(set) => setDeleting(set)}
|
onDelete={(set) => setDeleting(set)}
|
||||||
onNew={() => setCreating(true)}
|
onNew={() => setCreating(true)}
|
||||||
/>
|
/>
|
||||||
{creating && <PracticeDialog onClose={() => setCreating(false)} />}
|
{creating && <PracticeDialog onClose={() => setCreating(false)} />}
|
||||||
{deleting &&
|
{deleting &&
|
||||||
createPortal(
|
createPortal(
|
||||||
<div
|
<div
|
||||||
className="fixed inset-0 z-50 flex items-center justify-center bg-background/80"
|
className="fixed inset-0 z-50 flex items-center justify-center bg-background/80"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!deleteBusy) setDeleting(null);
|
if (!deleteBusy) setDeleting(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DeleteSetBody
|
<DeleteSetBody
|
||||||
title={deleting.title}
|
title={deleting.title}
|
||||||
busy={deleteBusy}
|
busy={deleteBusy}
|
||||||
failure={deleteFailure}
|
failure={deleteFailure}
|
||||||
onClose={() => setDeleting(null)}
|
onClose={() => setDeleting(null)}
|
||||||
onRun={() => void runDelete()}
|
onRun={() => void runDelete()}
|
||||||
/>
|
/>
|
||||||
</div>,
|
</div>,
|
||||||
document.body,
|
document.body,
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -382,7 +382,7 @@ Practice turns the graph into problem sets the learner reasons through out loud.
|
|||||||
|
|
||||||
**The jobs pattern — registry, not JobRecords.** Practice runs are NOT Workbench jobs: no `JobStore` records, no steer messages, nothing ever wakes the teacher — a practice run isn't chat-scoped (a set outlives its birth session and has no lesson to re-enter; its result is itself, persisted in its own store and read by its own page). What it shares with the Workbench is the observability surface: a `globalThis` run registry (the module-instance idiom — `__lhPracticeRuns`) with PER-PROBLEM ROWS (owner ruling, 2026-09-29 — matching the extraction per-chunk pattern): `setId:partition` while the partitioner runs ("Partitioning — title"), then one `setId:gen:problemId` per problem ("queued"→"generating", label "Problem i/N — title"), and one `setId:grade:problemId` per graded answer ("queued"→"grading", "Grading i/N — title") — each row its OWN abort controller and its OWN usage accumulation; the row key IS the feed id (the dock dup-key law) and the abort target. ABORT ROUTES BY ROW SHAPE: a gen-row abort kills THAT problem only (siblings continue; the set still settles `ready` with one errored problem), a partition-row abort ends the whole run, a grade-row abort drops that grade (answer kept — one attempt, the problem stays done); set-level abort (delete) composes from row aborts plus the synchronous persisted marks. Model calls — partitioner included — run under the SHARED background-LLM semaphore (`bg-llm-semaphore.ts`): one process-wide pool of 3 permits for ALL background LLM jobs, extraction chunks included (total background LLM concurrency bounded at 3, whoever calls). A boot sweep marks orphaned `partitioning`/`generating` sets as `error "Interrupted (server restarted)"` — once per process, and only when the set's `updatedAt` heartbeat is >120s stale (a live run's 30s FILE watchdog keeps the heartbeat fresh even across dev's per-worker processes — the registry is not shared between them; the guard trio closed a live-stamping bug from the first live test) — the job runner's crash-honesty at set grain. Store writes serialize behind a per-set mutex; the pipeline is the sole writer of `data/practice`.
|
**The jobs pattern — registry, not JobRecords.** Practice runs are NOT Workbench jobs: no `JobStore` records, no steer messages, nothing ever wakes the teacher — a practice run isn't chat-scoped (a set outlives its birth session and has no lesson to re-enter; its result is itself, persisted in its own store and read by its own page). What it shares with the Workbench is the observability surface: a `globalThis` run registry (the module-instance idiom — `__lhPracticeRuns`) with PER-PROBLEM ROWS (owner ruling, 2026-09-29 — matching the extraction per-chunk pattern): `setId:partition` while the partitioner runs ("Partitioning — title"), then one `setId:gen:problemId` per problem ("queued"→"generating", label "Problem i/N — title"), and one `setId:grade:problemId` per graded answer ("queued"→"grading", "Grading i/N — title") — each row its OWN abort controller and its OWN usage accumulation; the row key IS the feed id (the dock dup-key law) and the abort target. ABORT ROUTES BY ROW SHAPE: a gen-row abort kills THAT problem only (siblings continue; the set still settles `ready` with one errored problem), a partition-row abort ends the whole run, a grade-row abort drops that grade (answer kept — one attempt, the problem stays done); set-level abort (delete) composes from row aborts plus the synchronous persisted marks. Model calls — partitioner included — run under the SHARED background-LLM semaphore (`bg-llm-semaphore.ts`): one process-wide pool of 3 permits for ALL background LLM jobs, extraction chunks included (total background LLM concurrency bounded at 3, whoever calls). A boot sweep marks orphaned `partitioning`/`generating` sets as `error "Interrupted (server restarted)"` — once per process, and only when the set's `updatedAt` heartbeat is >120s stale (a live run's 30s FILE watchdog keeps the heartbeat fresh even across dev's per-worker processes — the registry is not shared between them; the guard trio closed a live-stamping bug from the first live test) — the job runner's crash-honesty at set grain. Store writes serialize behind a per-set mutex; the pipeline is the sole writer of `data/practice`.
|
||||||
|
|
||||||
**API + UI.** Creation is GRAPH-DOMAIN, not chat-domain (owner ruling 2026-09-29: "problem sets always take in nodes — graph objects"): `POST /api/practice/sets` takes `{nodeIds, params, title?, note?}` ONLY — no chatId, no clusterId; the UI resolves a picked cluster to its member node ids and passes the cluster's label as the title. The `note` is the learner's optional free-form creation input (owner, same evening: more learner control, no other purpose): trimmed, capped at 2000 characters, persisted on the set, and carried to the partitioner and every generator as `THE LEARNER'S NOTE` — an additional input the agents WEIGH but are never obliged to follow (the doctrine pins the stance: it never moves a problem off its rung or out of its band, and the partition laws always win). `GET /api/graph/clusters` serves the picker: the birth-session partition itself (`birthSessionPartition`, same ordering — size desc, ties by id) — EVERY group regardless of size (owner ruling, same evening: MIN_CLUSTER_SIZE is a hull-drawing rule; practice availability must not inherit a visual threshold), each as `{key, kind: "chat"|"notes", label, nodeIds, nodeCount}`; a cluster whose naming record is gone keeps `label: null` — honest, never guessed. 202 `{id}` with generation fire-and-forget; 400 empty selection (empty intersection with live nodes — the vanished-nodes edge) / bad params; 503 model/key refusal. `GET /api/practice/sets` · `GET/DELETE /api/practice/sets/[id]` (delete aborts live runs first) · `POST /api/practice/sets/[id]/answers` (202; 409 when not ready; 400 re-answering a submitted problem — one attempt). Surfaces: `/practice` (the list — the chat-pattern top bar with the sidebar reopen toggle and the New action at the right edge, status/counts rows, delete confirm, the new-set dialog with the named-level controls (a 5-detent ladder slider, a 3-detent cue slider, a Theory|Application toggle — each showing the level's name + definition), the cluster picker, and the optional free-form note textarea (typing-only) — the ONLY creation entry for now; the graph-view cluster entry comes later with the free-form selection UI) and `/practice/[id]` (the exam page — the chat-pattern top bar, a levels + status line, numbered problems, markdown statements with math healing at the display seam, a textarea + focus-gated dictation bar per problem with its OWN Submit button — one attempt per problem, instant solution/rubric reveal, the score landing live). Entry: the sidebar's Practice nav row.
|
**API + UI.** Creation is GRAPH-DOMAIN, not chat-domain (owner ruling 2026-09-29: "problem sets always take in nodes — graph objects"): `POST /api/practice/sets` takes `{nodeIds, params, title?, note?}` ONLY — no chatId, no clusterId; the UI resolves a picked cluster to its member node ids and passes the cluster's label as the title. The `note` is the learner's optional free-form creation input (owner, same evening: more learner control, no other purpose): trimmed, capped at 2000 characters, persisted on the set, and carried to the partitioner and every generator as `THE LEARNER'S NOTE` — an additional input the agents WEIGH but are never obliged to follow (the doctrine pins the stance: it never moves a problem off its rung or out of its band, and the partition laws always win). `GET /api/graph/clusters` serves the picker: the birth-session partition itself (`birthSessionPartition`, same ordering — size desc, ties by id) — EVERY group regardless of size (owner ruling, same evening: MIN_CLUSTER_SIZE is a hull-drawing rule; practice availability must not inherit a visual threshold), each as `{key, kind: "chat"|"notes", label, nodeIds, nodeCount}`; a cluster whose naming record is gone keeps `label: null` — honest, never guessed. 202 `{id}` with generation fire-and-forget; 400 empty selection (empty intersection with live nodes — the vanished-nodes edge) / bad params; 503 model/key refusal. `GET /api/practice/sets` · `GET/DELETE /api/practice/sets/[id]` (delete aborts live runs first) · `POST /api/practice/sets/[id]/answers` (202; 409 when not ready; 400 re-answering a submitted problem — one attempt). Surfaces: `/practice` (the list — the chat-pattern top bar with the sidebar reopen toggle and the New action at the right edge, status/counts rows, delete confirm, the new-set dialog with the named-level controls (a 5-detent ladder slider, a 3-detent cue slider, a Theory|Application toggle — each showing the level's name + definition), the cluster picker, and the optional free-form note textarea (typing-only). The SECOND creation entry (owner plan, same evening): the graph view's **chain table** — a `Chains` button in the graph chrome (empty graph: hidden) opens a full-screen overlay (the session-overlay idiom: absolute inside the graph area, Esc/backdrop dismiss) listing EVERY reasoning chain via the core `formatChainLine` one-liner (`"Premise one, Premise two → Conclusion"`, singletons marked `"(no premises)"`), each row expanding to its member propositions and each member to its full statement; columns are birth session(s) (the clusters' honest label join — chat title / notes path / muted `unlabeled`) and created date; NO understanding-levels column (explicitly not built). Selection is checkboxes on whole chains or single propositions — a flat node-id set (a node in several chains is one selection) — with a fuzzy search (names, aliases, statements) that filters the LIST only. The pinned Selected section derives the agents' ACTUAL input live (`chainsForSelection` over the selection: a premise picked without its conclusion shows as the singleton it becomes) as `N propositions → M chains` + the derived lines, with Clear and **Generate problem set**, which opens the SAME creation dialog in **custom mode**: no cluster picker — a selection summary (the derived shape + the dated default title the pipeline will stamp) — posting `{nodeIds, params, note}` with no title. The overlay is read-only toward the graph and `/practice/[id]` (the exam page — the chat-pattern top bar, a levels + status line, numbered problems, markdown statements with math healing at the display seam, a textarea + focus-gated dictation bar per problem with its OWN Submit button — one attempt per problem, instant solution/rubric reveal, the score landing live). Entry: the sidebar's Practice nav row.
|
||||||
|
|
||||||
**Model wiring.** Three roles — `partitioner`, `problemGenerator`, `grader` — all pinned to the **strong** slot (quality-critical, one settings edit from cheap) and in `BACKGROUND_MODEL_ROLES` (per-role overrides). The stage agents are single-submit loops on the shared `runSubmitAgent` seam (`submit-agent.ts`, extracted from extraction for exactly this): a `validate` hook turns a bad submit into a tool-input error the model retries against, within `maxTurns 4`; exhaustion fails the stage honestly (the set says so, the chains re-run cleanly on a new set).
|
**Model wiring.** Three roles — `partitioner`, `problemGenerator`, `grader` — all pinned to the **strong** slot (quality-critical, one settings edit from cheap) and in `BACKGROUND_MODEL_ROLES` (per-role overrides). The stage agents are single-submit loops on the shared `runSubmitAgent` seam (`submit-agent.ts`, extracted from extraction for exactly this): a `validate` hook turns a bad submit into a tool-input error the model retries against, within `maxTurns 4`; exhaustion fails the stage honestly (the set says so, the chains re-run cleanly on a new set).
|
||||||
|
|
||||||
@@ -469,7 +469,7 @@ All deterministic, no network: engines are injected (pi-ai's **faux provider**
|
|||||||
1. **Pure core units** — merger via real adapters, derivation, coverage, question grading, plan tree, phases, clusters, layout, tool-parts, prices, fuzzy search.
|
1. **Pure core units** — merger via real adapters, derivation, coverage, question grading, plan tree, phases, clusters, layout, tool-parts, prices, fuzzy search.
|
||||||
2. **Server flows** — `handleChatRequest` driven end-to-end with scripted faux engines: persistence, liveness, steer claiming, the wake pipeline (409 retry, quiz deferral, idempotency), crash recovery, the data-dir seam (including a fresh child process).
|
2. **Server flows** — `handleChatRequest` driven end-to-end with scripted faux engines: persistence, liveness, steer claiming, the wake pipeline (409 retry, quiz deferral, idempotency), crash recovery, the data-dir seam (including a fresh child process).
|
||||||
3. **Sub-agent loops** — researcher/demo-builder/visual-maker with fake headless APIs; the extraction pipeline end-to-end (audit drops, failure-checkpoints-nothing, single-flight, abort); the practice pipeline end-to-end (partition echo/coverage retries, failure isolation, semaphore width, abort mid-generation, grading, boot sweep).
|
3. **Sub-agent loops** — researcher/demo-builder/visual-maker with fake headless APIs; the extraction pipeline end-to-end (audit drops, failure-checkpoints-nothing, single-flight, abort); the practice pipeline end-to-end (partition echo/coverage retries, failure isolation, semaphore width, abort mid-generation, grading, boot sweep).
|
||||||
4. **Render tests** — transcript, cards, docks, composer, sidebar, coverage, stats, practice surfaces (creation dialog, list, exam states) via React server-side rendering (`renderToStaticMarkup`), no DOM library.
|
4. **Render tests** — transcript, cards, docks, composer, sidebar, coverage, stats, practice surfaces (creation dialog both modes, chain table, list, exam states) via React server-side rendering (`renderToStaticMarkup`), no DOM library.
|
||||||
|
|
||||||
Gates on every change: `tsc` clean, all tests, `eslint` clean, `next build` clean.
|
Gates on every change: `tsc` clean, all tests, `eslint` clean, `next build` clean.
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,24 @@ export function chainsToGraph(
|
|||||||
return { nodeIds: [...nodeIds].sort(), edges };
|
return { nodeIds: [...nodeIds].sort(), edges };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A chain as one world-facing line — the propositions' NAMES joined
|
||||||
|
* by the derivation arrow: "Premise one, Premise two → Conclusion"; a
|
||||||
|
* singleton shows its "(no premises)" marker. Pure + browser-safe:
|
||||||
|
* the shell (chain table, derived previews) cannot import the agent
|
||||||
|
* module — the level tables set this precedent. Unknown ids fall back
|
||||||
|
* to the raw id (honest, never guessed). Premises sort by id — the
|
||||||
|
* same determinism law as chainsForSelection. */
|
||||||
|
export function formatChainLine(
|
||||||
|
chain: Pick<ReasoningChain, "premises" | "conclusion">,
|
||||||
|
propositions: Readonly<Record<string, { name: string }>>,
|
||||||
|
): string {
|
||||||
|
const nameOf = (id: string) => propositions[id]?.name ?? id;
|
||||||
|
const premises = [...chain.premises].sort().map(nameOf).join(", ");
|
||||||
|
return premises !== ""
|
||||||
|
? `${premises} → ${nameOf(chain.conclusion)}`
|
||||||
|
: `${nameOf(chain.conclusion)} (no premises)`;
|
||||||
|
}
|
||||||
|
|
||||||
/** chainCoverage()'s report. `missing` fails the partition; `duplicated`
|
/** chainCoverage()'s report. `missing` fails the partition; `duplicated`
|
||||||
* is informational — a chain MAY legitimately be exercised by several
|
* is informational — a chain MAY legitimately be exercised by several
|
||||||
* problems (the operations make that sound). */
|
* problems (the operations make that sound). */
|
||||||
|
|||||||
+22
-1
@@ -9,7 +9,7 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { describe, it } from "node:test";
|
import { describe, it } from "node:test";
|
||||||
import type { EdgeType } from "../src/core/contracts.ts";
|
import type { EdgeType } from "../src/core/contracts.ts";
|
||||||
import { chainCoverage, chainsForSelection, chainsToGraph } from "../src/core/practice.ts";
|
import { chainCoverage, chainsForSelection, chainsToGraph, formatChainLine } from "../src/core/practice.ts";
|
||||||
|
|
||||||
// ─── fixtures ────────────────────────────────────────────────────────────────
|
// ─── fixtures ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -138,3 +138,24 @@ describe("chainCoverage", () => {
|
|||||||
assert.deepEqual(chainCoverage(set), { missing: [], duplicated: [] });
|
assert.deepEqual(chainCoverage(set), { missing: [], duplicated: [] });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("formatChainLine (the chain table's one-line shape, 2026-09-29)", () => {
|
||||||
|
const props = {
|
||||||
|
p1: { name: "Premise one" },
|
||||||
|
p2: { name: "Premise two" },
|
||||||
|
c1: { name: "Conclusion" },
|
||||||
|
solo: { name: "Standalone" },
|
||||||
|
};
|
||||||
|
|
||||||
|
it("joins sorted premise NAMES by the derivation arrow", () => {
|
||||||
|
assert.equal(formatChainLine({ premises: ["p2", "p1"], conclusion: "c1" }, props), "Premise one, Premise two → Conclusion");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a singleton shows its (no premises) marker", () => {
|
||||||
|
assert.equal(formatChainLine({ premises: [], conclusion: "solo" }, props), "Standalone (no premises)");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unknown ids fall back to the raw id (honest, never guessed)", () => {
|
||||||
|
assert.equal(formatChainLine({ premises: ["ghost"], conclusion: "c1" }, props), "ghost → Conclusion");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
/**
|
||||||
|
* THE CHAIN TABLE — SSR render pins (the render-suite discipline: pure
|
||||||
|
* bodies, renderToStaticMarkup, testids). The chains overlay (owner-
|
||||||
|
* approved plan, 2026-09-29): every reasoning chain in one selectable
|
||||||
|
* table; the pinned Selected section derives N propositions → M chains
|
||||||
|
* via chainsForSelection over the selection (the agents' ACTUAL input);
|
||||||
|
* fuzzy search filters the list only; the practice dialog opens in
|
||||||
|
* CUSTOM mode from the Generate button.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React from "react";
|
||||||
|
(globalThis as Record<string, unknown>).React = React;
|
||||||
|
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { createElement } from "react";
|
||||||
|
import { renderToStaticMarkup } from "react-dom/server";
|
||||||
|
import { describe, it } from "node:test";
|
||||||
|
import { ChainTableBody } from "../components/chain-table.tsx";
|
||||||
|
import type { GraphEdge, GraphNode } from "../src/core/contracts.ts";
|
||||||
|
|
||||||
|
/** The fixture graph — two follows-chains + one standalone:
|
||||||
|
* a → c1, b → c1 (chain one), d → e (chain two), solo (singleton). */
|
||||||
|
function node(id: string, name: string, statement: string, chatId: string | null): GraphNode {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
statement,
|
||||||
|
aliases: [],
|
||||||
|
state: "new",
|
||||||
|
createdAt: "2026-09-20T10:00:00.000Z",
|
||||||
|
provenance: chatId === null ? [] : [{ chatId, messageId: `m_${id}` }],
|
||||||
|
} as unknown as GraphNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const NODES: GraphNode[] = [
|
||||||
|
node("a", "Premise one", "Statement A.", "chat1"),
|
||||||
|
node("b", "Premise two", "Statement B.", "chat2"),
|
||||||
|
node("c1", "Conclusion", "Statement C.", "chat1"),
|
||||||
|
node("d", "Support", "Statement D.", null),
|
||||||
|
node("e", "Follow-up", "Statement E with keyword zebra.", "notes1"),
|
||||||
|
node("solo", "Standalone", "Statement S.", "chat1"),
|
||||||
|
];
|
||||||
|
|
||||||
|
const EDGES: GraphEdge[] = [
|
||||||
|
{ from: "a", to: "c1", type: "follows" },
|
||||||
|
{ from: "b", to: "c1", type: "follows" },
|
||||||
|
{ from: "d", to: "e", type: "follows" },
|
||||||
|
] as GraphEdge[];
|
||||||
|
|
||||||
|
const SESSIONS = { chat1: "Ethics lesson", chat2: "Second chat" };
|
||||||
|
const FILE_SOURCES = { notes1: "notes/raw/ethics.md" };
|
||||||
|
|
||||||
|
const BASE = {
|
||||||
|
nodes: NODES,
|
||||||
|
edges: EDGES,
|
||||||
|
sessions: SESSIONS,
|
||||||
|
fileSources: FILE_SOURCES,
|
||||||
|
query: "",
|
||||||
|
onQuery: () => {},
|
||||||
|
selection: new Set<string>(),
|
||||||
|
onToggleNode: () => {},
|
||||||
|
onToggleChain: () => {},
|
||||||
|
onClear: () => {},
|
||||||
|
onGenerate: () => {},
|
||||||
|
onClose: () => {},
|
||||||
|
};
|
||||||
|
|
||||||
|
function render(props: Partial<typeof BASE> = {}) {
|
||||||
|
return renderToStaticMarkup(createElement(ChainTableBody, { ...BASE, ...props }));
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("ChainTableBody — the chain rows", () => {
|
||||||
|
it("renders every chain as a formatted name line, with birth + created columns", () => {
|
||||||
|
const html = render();
|
||||||
|
// chain ids are the conclusion ids (chainsForSelection's law)
|
||||||
|
assert.ok(html.includes('data-testid="chain-row-c1"'), "chain row for c1");
|
||||||
|
assert.ok(html.includes('data-testid="chain-row-e"'), "chain row for e");
|
||||||
|
assert.ok(html.includes('data-testid="chain-row-solo"'), "the singleton renders as its own chain");
|
||||||
|
assert.ok(html.includes("Premise one, Premise two → Conclusion"), "the two-premise line");
|
||||||
|
assert.ok(html.includes("Support → Follow-up"), "the one-premise line");
|
||||||
|
assert.ok(html.includes("Standalone (no premises)"), "the singleton marker");
|
||||||
|
// birth labels: the union of member labels, honest "unlabeled" included
|
||||||
|
assert.ok(html.includes("Ethics lesson · Second chat"), "chain one spans two labeled sessions");
|
||||||
|
assert.ok(html.includes("notes/raw/ethics.md"), "a notes birth shows the file path");
|
||||||
|
assert.ok(html.includes("unlabeled"), "an unnameable birth is honest about it");
|
||||||
|
// created = the conclusion's createdAt (the practice-list date shape)
|
||||||
|
assert.ok(html.includes('data-testid="chain-date-c1"'));
|
||||||
|
assert.ok(html.includes("2026-09-20"), "the date column renders");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the first chain row expands by default to member proposition rows; closed members keep their statements unmounted", () => {
|
||||||
|
const html = render();
|
||||||
|
assert.ok(html.includes('data-testid="prop-row-a"'), "premise row a");
|
||||||
|
assert.ok(html.includes('data-testid="prop-row-c1"'), "conclusion row");
|
||||||
|
// member statements expand on click — Radix unmounts closed
|
||||||
|
// content, so SSR honestly does not contain them
|
||||||
|
assert.ok(!html.includes("Statement A."), "statements wait for their click");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("every chain has a checkbox; expanded chains expose member checkboxes", () => {
|
||||||
|
const html = render();
|
||||||
|
assert.ok(html.includes('data-testid="chain-checkbox-c1"'));
|
||||||
|
assert.ok(html.includes('data-testid="chain-checkbox-e"'));
|
||||||
|
assert.ok(html.includes('data-testid="chain-checkbox-solo"'));
|
||||||
|
assert.ok(html.includes('data-testid="prop-checkbox-a"'), "inside the default-open chain");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ChainTableBody — the pinned Selected section", () => {
|
||||||
|
it("empty selection: guidance, no summary, no generate enablement pins", () => {
|
||||||
|
const html = render();
|
||||||
|
assert.ok(html.includes("Nothing selected"));
|
||||||
|
assert.ok(!html.includes('data-testid="chain-selected-summary"'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a full chain selection: N propositions → M chains + derived line", () => {
|
||||||
|
const html = render({ selection: new Set(["a", "b", "c1"]) });
|
||||||
|
assert.ok(html.includes('data-testid="chain-selected-summary"'));
|
||||||
|
assert.ok(html.includes("3 propositions → 1 chain"), "the derived shape, exactly");
|
||||||
|
assert.ok(html.includes("Premise one, Premise two → Conclusion"), "the derived chain line");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a premise WITHOUT its conclusion derives as the singleton it becomes", () => {
|
||||||
|
const html = render({ selection: new Set(["a", "d"]) });
|
||||||
|
assert.ok(html.includes("2 propositions → 2 chains"), "no follows-edge survives inside the selection");
|
||||||
|
assert.ok(html.includes("Premise one (no premises)"), "regrouped singleton a");
|
||||||
|
assert.ok(html.includes("Support (no premises)"), "regrouped singleton d");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("a node in several chains is ONE flat selection wherever it appears", () => {
|
||||||
|
// e is conclusion of d→e; picking e alone = 1 proposition, 1 singleton chain
|
||||||
|
const html = render({ selection: new Set(["e"]) });
|
||||||
|
assert.ok(html.includes("1 proposition → 1 chain"));
|
||||||
|
assert.ok(html.includes("Follow-up (no premises)"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Clear + Generate problem set render in the pinned section", () => {
|
||||||
|
const html = render({ selection: new Set(["a"]) });
|
||||||
|
assert.ok(html.includes('data-testid="chain-clear"'));
|
||||||
|
assert.ok(html.includes('data-testid="chain-generate"'));
|
||||||
|
assert.ok(html.includes("Generate problem set"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ChainTableBody — the fuzzy search (list only, never Selected)", () => {
|
||||||
|
it("filters chains by member name / statement / alias; the pinned selection survives", () => {
|
||||||
|
const aliased = NODES.map((n) =>
|
||||||
|
n.id === "b" ? { ...n, aliases: ["zebra alias"] } : n,
|
||||||
|
);
|
||||||
|
const html = render({
|
||||||
|
nodes: aliased,
|
||||||
|
query: "zebra",
|
||||||
|
selection: new Set(["a", "b", "c1"]), // selection spans BOTH chains
|
||||||
|
});
|
||||||
|
// zebra hits: chain e (statement) + chain c1 (alias on b)
|
||||||
|
assert.ok(html.includes('data-testid="chain-row-c1"'), "alias match keeps the chain");
|
||||||
|
assert.ok(html.includes('data-testid="chain-row-e"'), "statement match keeps the chain");
|
||||||
|
assert.ok(!html.includes('data-testid="chain-row-solo"'), "non-matching chain hidden");
|
||||||
|
// the pinned section is never filtered — it still shows the full derived line
|
||||||
|
assert.ok(html.includes("3 propositions → 1 chain"));
|
||||||
|
assert.ok(html.includes("Premise one, Premise two → Conclusion"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("no matches: the honest empty line", () => {
|
||||||
|
const html = render({ query: "qqqq" });
|
||||||
|
assert.ok(html.includes('data-testid="chain-table-nomatch"'));
|
||||||
|
assert.ok(html.includes("No matching chains."));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -31,6 +31,7 @@ const PROPS = {
|
|||||||
onImportFiles: () => {},
|
onImportFiles: () => {},
|
||||||
settings: {} as GraphRenderSettings,
|
settings: {} as GraphRenderSettings,
|
||||||
changeSettings: () => {},
|
changeSettings: () => {},
|
||||||
|
onOpenChains: () => {},
|
||||||
};
|
};
|
||||||
|
|
||||||
describe("GraphChromeRow — the empty-graph ruling (owner, 2026-09-25)", () => {
|
describe("GraphChromeRow — the empty-graph ruling (owner, 2026-09-25)", () => {
|
||||||
@@ -42,16 +43,18 @@ describe("GraphChromeRow — the empty-graph ruling (owner, 2026-09-25)", () =>
|
|||||||
// the settings gear is the lucide-settings svg (tooltip wave: its old
|
// the settings gear is the lucide-settings svg (tooltip wave: its old
|
||||||
// native title is gone — the styled tooltip carries the label now)
|
// native title is gone — the styled tooltip carries the label now)
|
||||||
assert.ok(!html.includes("lucide-settings"), "settings is a lie on an empty graph");
|
assert.ok(!html.includes("lucide-settings"), "settings is a lie on an empty graph");
|
||||||
|
assert.ok(!html.includes('data-testid="open-chain-table"'), "chains is a lie on an empty graph");
|
||||||
assert.ok(!html.includes("graph-chrome-fade-in"), "nothing gated = nothing fading in");
|
assert.ok(!html.includes("graph-chrome-fade-in"), "nothing gated = nothing fading in");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("POPULATED graph: all three render, the gated pair carries the fade", () => {
|
it("POPULATED graph: all four render, the gated trio carries the fade", () => {
|
||||||
const html = renderToStaticMarkup(createElement(GraphChromeRow, { ...PROPS, isEmpty: false }));
|
const html = renderToStaticMarkup(createElement(GraphChromeRow, { ...PROPS, isEmpty: false }));
|
||||||
assert.ok(html.includes('data-testid="import-notes"'));
|
assert.ok(html.includes('data-testid="import-notes"'));
|
||||||
assert.ok(html.includes("Search nodes…"));
|
assert.ok(html.includes("Search nodes…"));
|
||||||
assert.ok(html.includes("lucide-settings"), "the settings gear renders");
|
assert.ok(html.includes("lucide-settings"), "the settings gear renders");
|
||||||
// the appear-once fade rides exactly the two gated controls, never Import Notes
|
assert.ok(html.includes('data-testid="open-chain-table"'), "the chains entry renders");
|
||||||
assert.equal(html.split("graph-chrome-fade-in").length - 1, 2, "two fade carriers: search + settings");
|
// the appear-once fade rides exactly the three gated controls, never Import Notes
|
||||||
|
assert.equal(html.split("graph-chrome-fade-in").length - 1, 3, "three fade carriers: search + chains + settings");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("the no-match note renders only when the wrapper says so (its truth stays upstream)", () => {
|
it("the no-match note renders only when the wrapper says so (its truth stays upstream)", () => {
|
||||||
|
|||||||
@@ -189,6 +189,49 @@ describe("PracticeDialogBody — creation (cluster picker)", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("PracticeDialogBody — creation (CUSTOM mode, the chains overlay's handoff)", () => {
|
||||||
|
const base = {
|
||||||
|
params: { ...DEFAULT_PRACTICE_PARAMS },
|
||||||
|
onParam: () => {},
|
||||||
|
note: "",
|
||||||
|
onNote: () => {},
|
||||||
|
clusters: clusters(),
|
||||||
|
selectedKey: null,
|
||||||
|
onSelect: () => {},
|
||||||
|
busy: false,
|
||||||
|
failure: null as PracticeFailure | null,
|
||||||
|
onOpenSettings: () => {},
|
||||||
|
onClose: () => {},
|
||||||
|
onRun: () => {},
|
||||||
|
};
|
||||||
|
|
||||||
|
it("no cluster picker — the selection summary + dated default title instead", () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<PracticeDialogBody
|
||||||
|
{...base}
|
||||||
|
mode="custom"
|
||||||
|
selection={{ nodeIds: ["n1", "n2", "n3", "n4"], propositions: 4, chains: 2 }}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
assert.ok(!html.includes('data-testid="practice-dialog-clusters"'), "custom mode has no picker");
|
||||||
|
assert.ok(html.includes('data-testid="practice-dialog-selection"'));
|
||||||
|
assert.match(html, /Practice — (<!-- -->)?\d{4}-\d{2}-\d{2}/, "the dated default title (the pipeline's own stamp)");
|
||||||
|
assert.ok(html.includes('data-testid="practice-dialog-selection-line"'));
|
||||||
|
assert.ok(html.includes("4 propositions"));
|
||||||
|
assert.ok(html.includes("2 chains"));
|
||||||
|
assert.ok(!html.includes('disabled=""'), "a non-empty selection enables Create immediately");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dials + note still ride along — the params/note laws are mode-independent", () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<PracticeDialogBody {...base} mode="custom" selection={{ nodeIds: ["n1"], propositions: 1, chains: 1 }} />,
|
||||||
|
);
|
||||||
|
assert.ok(html.includes('data-testid="param-ladder"'));
|
||||||
|
assert.ok(html.includes('data-testid="practice-note"'));
|
||||||
|
assert.ok(html.includes("1 proposition →"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// ─── the list page ───────────────────────────────────────────────────────────
|
// ─── the list page ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
describe("PracticeListBody — the set list", () => {
|
describe("PracticeListBody — the set list", () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user