chat.tsx now uses createChatTransport(chatId): a send racing the wake
pipeline waits for the in-flight turn, merges onto the fresh server
record, and re-POSTs instead of surfacing the 409 banner. Also fixes the
transport's import to the core barrel (shell import law).
The optional "server-ahead heal" line in the jobs poller was considered
and skipped: the racing turn IS the wake turn, whose completion flips the
job to done within a poll tick or two — the existing settle-triggered
syncFromServer already heals the post-merge gap within ~1-2s. The extra
record fetch on every poll tick would double poll traffic for a path the
settle sync already covers.
- components/chat-transport.ts (NEW): createChatTransport(chatId) — the
chat.tsx seam is now a one-line swap. Its fetch turns a 409 on POST
/api/chat (a learner send racing the wake pipeline's ~1s adoption window)
into: wait out the in-flight turn (poll turnInFlight, 30s cap), refetch
the record, MERGE the outgoing messages onto the fresh server list, re-POST.
A bare retry would clobber the steer + wake messages via the write-ahead
persist (steerDelivered makes that loss permanent) — merging is the whole
point. Unit-tested: pass-through, wait+merge+reorder, dedupe by id,
repeated-409 loop, bounded give-up.
- src/core/pending.ts: findPendingJobCall deleted (dead since wave 1 —
job tools resolve server-side with an ack, nothing pends client-side).
JOB_TOOLS kept (runner.ts still uses it). Header doc rewritten.
- src/server/jobs.ts: GRACE_MS 1500 → 750, with the evidence in the
comment: the race window is only the learner's answer→POST flight
(sendAutomaticallyWhen dispatches synchronously; ~10ms localhost,
<300ms realistic RTT — 750 is 2.5× worst case) and misses self-heal
via the pump's gate recheck, the 409 backoff ramp, and the new
transport merge-retry. POLL_MS=400 kept (sampling granularity only).
- tests/jobs.test.ts: prompt-size guard — every fragment ≤8k chars,
composed prompt ≤60k — the README-leak class (815 bytes ≈ 200 tokens
per teacher turn before wave 1's fix) can't silently recur.
Gates: typecheck, 279/279 tests, lint, build — all green.
The fit zoom was capped at 1×, so any graph smaller than the panel
rendered at natural size, centered, with big empty margins above and
below — the common case for early-session chains in the 384px panel.
The fit now scales up to fill (FIT_ZOOM_MAX 1.5 — a lone node doesn't
become a billboard), floor-clamped as before. Math extracted into
fitZoomFor() and unit-tested (scale-up, cap, width/height-bound,
floor, unmeasured viewport).
The right sidebar's mode (rail | list | graph) is now shared state: a
new useTreePanelMode() hook lets every sidebar section collapse and
expand together. With sub-agents running in rail mode the fleet shows a
quiet strip — bot icon (click expands the sidebar) + vertical 'N running'
count — mirroring the plan rail's node-count strip below it. The sidebar
now collapses all the way regardless of running jobs.
End-to-end verified through the real flow (dispatch part in the
transcript + running job record, the 1s jobs poll rendering the panel):
rail column exactly w-10 with both rails stacked and aligned (40px), the
fleet rail's expand click transitions to list mode and persists, fleet +
plan panels equal widths in list (256/256) and graph (384/384) modes,
9-node graph intact, console clean.
The sub-agents fleet panel was a w-64 fixed aside with no left edge —
aligned with the plan panel only by coincidence in list mode, floating
detached in rail (w-10) and graph (w-96) modes. It now stretches to the
sidebar column's current width and shares the panel's border-l, so the
sidebar is one continuous panel with SUB-AGENTS above PLAN (thin border-b
divider). Verified headlessly in list and graph mode: identical edges and
widths (256/256 and 384/384), perfect vertical stack (fleet 0..99.5, tree
99.5..800), no overlap, 9-node graph intact.
The rail-mode-while-jobs-run question (fleet cards would cram into w-10)
is logged as wave-2 UX design work for the UI stream.
The weave had nested the right sidebar inside the transcript column
(below the header), so the phase chip sat above the panel instead of left
of it and the panel was bounded by the scroller area. The column is now
a true sibling of the middle column under flex h-dvh, per the UI stream's
original design; TreePanel's aside gets flex-1 min-h-0 so it shares the
column with the fleet panel instead of overflowing it. The plan-graph
viewport (ResizeObserver-measured) now has real size, so the mermaid
view draws.
Headless-verified at 1280x800: panel spans 0..800 top-to-bottom in both
modes, chip right edge < panel left edge in both modes, graph SVG = 9
boxes + 8 beziers, console clean.
Node names word-wrapped as muted labels below nodes (global zoom gate),
constant-radius static glow in the node's own state color with
enter/leave crossfades, node-anchored detail card, and padded node
picking (+10px pickable radius via a picking-mode-only shader — the
maintainer-endorsed fix for sigma v3's half-resolution hitbox reads;
visible rendering pixel-identical).
chat.tsx woven by hand: UI's session-surface layout (transcript column +
right sidebar as full-height siblings, h-10 header with PhaseChip) wrapped
in sub-agents' JobsContext.Provider; the message map carries both the
steer ternary (steers bypass the Message wrapper — the model-facing glue
text never renders) and UI's PhaseDivider emission (steers are verified
phase-boundary no-ops). Right sidebar = sub-agents' fleet panel column
(SubAgentsPanel above TreePanel, xl-only) carried onto UI's skeleton.
contracts.ts auto-merged (ChatSummary.phase/pendingQuestion + ChatListItem,
additive above the async-protocol section).
Smoke-verified on the merged tree: steer renders bare as its artifact
badge with no learner bubble, no rendered glue text, and no spurious
phase divider at the steer boundary.
Figures now always fill the card's width (h-auto keeps the aspect
ratio): narrower svgs scale up instead of leaving a white strip on the
right when they carry their own background color; oversized ones still
shrink to fit. bg-white stays as a neutral backing for svgs without
their own background.
Fixes the hover flicker the maintainers' way (jacomyal/sigma.js#1493):
sigma v3 picks nodes by reading a single pixel from a picking
framebuffer rendered at HALF the CSS resolution, and has no setting
for hit padding. Small nodes get tiny, ragged hit edges, and our glow
halo (9px beyond the disc) was NOT pickable — moving the cursor from
the disc onto its own halo de-hovered it, an oscillation loop.
NodeCircleProgram subclass (registered via nodeProgramClasses)
replaces only VERTEX_SHADER_SOURCE: a verbatim copy of sigma 3.0.3's
circle vertex shader that adds PICKING_PAD_PX (10) of radius under
#ifdef PICKING_MODE alone. The visible pass never takes that branch,
so rendering is pixel-identical (verified headless); the pickable
disc is disc + 10px, covering the whole hover halo, so the halo is
now hoverable and small candidate nodes are comfortable to hit.
sigma/rendering is imported dynamically (its ESM build touches
WebGL globals at module scope; SSR-safe like the sigma import).
This replaces the reverted prototype-patch approach (f12480e).
sigma v4 ships this officially as the nodePickingPadding setting —
noted for a future upgrade.
The persistTurn id hygiene (2d7b004) only covers NEW writes — records
persisted before it still carry messages with empty SDK ids, and two of
those in one transcript re-trigger the duplicate-React-key error.
- data/chats: backfilled all empty ids (6 messages across 5 records,
msg_<ts>_<hex> scheme matching withMessageIds).
- chat.tsx: key={m.id || `m-${mi}`} on both message branches — even an
unmigrated legacy record can never collide keys again.
NOTE for master at merge: the master tree's data/ needs the same
one-time backfill (any chat saved before the withMessageIds commit).
Three refinements from live testing:
- Steer messages no longer sit inside the user Message container (the
bubble background + right alignment it gave artifact cards). chat.tsx
renders SubagentSteerCard directly in the transcript column — full
width, centered, same register as the teacher's artifacts.
- Research steers render a quiet "Research complete · N sources" badge
(the dispatch-settled idiom), not the full brief: briefs are long, the
wake turn weaves them into the lesson anyway, and the full text stays
persisted in the artifact part — a "view full research" affordance
can be added later without any protocol change. Failures keep the
failure card (the brief explains what went wrong).
- The sub-agents' verification notes (visual/demo builder notes) are
model-facing glue and no longer render on success; failure notes
remain the error explanation.
SSR-verified against a synthetic record: badge + SVG bare in the
transcript (no is-user wrapper), notes/brief confined to the RSC
payload. 229/229, typecheck, lint, build green.
The persisted mode (lh:tree-panel-mode) was read inside TreePanel — a
per-page component that remounts on every session navigation. First
paint rendered the SSR-safe "list" default, then the mount effect
applied the stored mode: with the animated frame, opening a session
visibly opened the panel and then closed it. The mode now lives in a
root-layout provider (the SidebarProvider pattern) and survives
navigations untouched — the panel mounts already in the right mode.
The default stays "list" so SSR and first client render agree; the
stored preference applies once, on provider mount.
Root cause: sigma's getNodeAtPosition reads the picking framebuffer,
which is rendered at HALF the device resolution
(pickingDownSizingRatio = 2 * pixelRatio). Small nodes' hit circles
are a couple of device pixels across in that buffer with ragged,
quantized edges — near a node boundary, tiny cursor movements flip
the hover state on/off, and each flip makes sigma clear the hover
layer immediately. That state churn is the flicker; it survived every
animation change because it was never in the animation.
Mitigations:
- patchNodePicking() replaces Sigma.prototype.getNodeAtPosition with
a smooth distance test (rendered radius + HIT_PAD_PX = 6px) built on
public renderer APIs only (getGraph, getNodeDisplayData,
framedGraphToViewport, scaleSize). No ragged edges, and small
candidate nodes get roughly double the hoverable area.
- Leave-debounce (90ms): when hover drops, hold repainting the
captured hover paint at the current fade (sigma would otherwise
clear the layer the instant hoveredNode flips to null), and only
fade out if the cursor hasn't bounced back within the window. A
re-enter cancels the fade, so boundary oscillation never visibly
dims anything.
- The three panel modes were three separate fixed-width asides, so a
mode switch jumped the whole transcript column width in one frame:
scrollbar flash, overshoot, re-correct. Now ONE aside animates its
width exactly like the left sidebar (reusing the sidebar-motion
hook, so it inherits the provider's mount-gated transition), with
a FIXED-width inner layer clipped by overflow-hidden — content
never reflows mid-transition.
- The chat header was auto-height: the sidebar toggle (a size-9 icon
button) renders only while the sidebar is closed, so opening it
collapsed the row and slid the title + phase chip up. The header is
now a constant h-10.
The instant muted->bright color swap felt abrupt next to the fading
halo. The hover name is again drawn at partial alpha over the muted
resting label, using the SAME transition factor as the halo — text
and glow fade in/out in sync. Because every enter/leave interpolates
from the current fade value, rapid hover toggles at a node's hit
boundary glide instead of snapping (the flicker-damping fix).
The pi-style ack protocol (previous commit) left the client describing the
old world: artifact cards read the ack string as a result ("could not be
displayed"), the only job poller rendered on input-available parts that no
longer exist (so wake turns landed invisibly until re-navigation), steers
rendered as learner bubbles with no SVG anywhere, and server-persisted
assistant messages carried empty SDK ids (duplicate React keys).
- persistTurn (turn-service): fill empty message ids at the canonical write
— server-only messages (last turn's, wake turns') now key uniquely;
client-authored ids untouched.
- chat.tsx: ONE central /api/jobs poll (fast while jobs run, slow discovery
cadence, off for job-less sessions) drives every job surface, re-syncs
once when a job settles (the record already holds the steer + wake
response at flip time), and adopts server-side wake turns via the same
turnInFlight machinery as returning mid-turn. Steers branch to the
artifact card — never a bubble. Composer no longer gates on jobs.
- /api/jobs now reports turnInFlight alongside the job list.
- dispatch-card: the tool-call box — live activity by toolCallId while
running, quiet "delivered"/"failed" one-liner after; the ack is visible
observability, the artifact lives in the steer.
- steer-card: renders the delivered artifact by kind (research brief /
sanitized SVG / sandboxed demo iframe) from the data-subagent-artifact
part; result renderers extracted and exported from the artifact cards.
- sub-agents-panel: right-sidebar section above the plan tree listing
running sub-agents (kind, elapsed, live activity) — vanishes when idle.
- tests: dispatch/steer/panel render tests re-target the new protocol;
persistTurn id-hygiene suite. 229/229 green, build green.
Out-of-lane touches for master review: chat.tsx + components/** (cleared
this wave), app/api/jobs/route.ts, src/server/turn-service.ts, contracts
protocol doc §2. Live-verified on :3003 (full loop, SSR DOM checked).
- The halo no longer grows during the fade: radius is constant at
size + 9px; only its opacity fades in/out over ~180ms.
- The hover name is drawn opaque in the bright color instead of
cross-fading over the muted resting label. Partial-alpha text
oscillated whenever hover toggles rapidly at a small node's hit
boundary (sigma fires enterNode/leaveNode on every state change) —
an un-animated color can't flicker.
- The glow no longer pulses: it's a static halo (9px beyond the disc,
0.45 alpha at the edge fading outward) in the node's state color.
- Hover enter/leave now cross-fades over ~180ms instead of appearing
instantly: entering schedules sigma renders so drawHover repaints at
the interpolated fade; leaving draws through a repainter captured on
the last hover paint (sigma stops calling drawHover once unhovered).
The text cross-fades too — the brighter hover name is drawn at
partial alpha over the muted resting label on the layer beneath.
- The halo starts flush at the node disc edge (was size+1, leaving a
dark gap ring that read as a gray border between node and glow).
- Both fade directions cancel each other and stop on completion, so
there is no continuous loop — idle CPU stays near zero.
- defaultDrawNodeHover no longer paints a background box: the hovered
node now pulses a soft radial-gradient halo ring in its own state
color (evenodd punch-out keeps the node disc untouched), phase driven
by performance.now() inside the drawer.
- The hovered label text brightens (muted-foreground -> foreground) at
identical geometry — drawName is shared by both drawers so nothing
shifts when hover begins/ends.
- The pulse is animated by a rAF loop that only runs while a node is
hovered (enterNode starts, leaveNode/leaveStage stop, cleanup
cancels) — idle CPU stays near zero, preserving run-then-freeze.
- roundedRect removed with the pill (its only remaining consumer).
Redesign per review feedback: the colored phase strips were too busy —
removed. One small dot now carries two channels:
- COLOR = phase (sky/violet/emerald, same system as chip + dividers)
- FILL + MOTION = what's owed:
- pulsing = teacher is working (the only state that deserves motion)
- solid = a question awaits the learner's answer — the dominant
resting state of real sessions, so deliberately calm
- hollow = idle, nothing owed
The amber attention channel is gone entirely (it would read as a
phantom fourth phase). The meta line now leads with the useful fact:
"Waiting for your answer · 5m ago" / "Teacher is working…" — the
message count only shows when idle. Ordering stays pure recency.
- Chat page: the tree panel is now a full-height sibling of the whole
transcript column (header + scroller), exactly like the left sidebar —
the session header (name + phase chip) spans from the left sidebar's
edge to the panel's edge instead of riding over the panel.
- Plan graph: the zoom controls sit inside the pan surface, so their
pointerdown started a capture drag and the click never reached the
button (felt dead). startDrag now ignores presses on buttons.
- Fully zoomed out IS the fit view: zooming to the floor snaps to the
centered fit (pure zoomedGraphView), pan is locked there (no drag
begins, cursor-default instead of grab), and sitting at the floor
re-arms auto-fit so later tree edits keep the graph fitting.
- Fit padding 48px → 16px: the default view fits more graph.
- roundedRect typo: the first arcTo's second control point used y+width
as the x-coordinate (y + width instead of x + width). Since arcTo
tangent math is in absolute coordinates, the pill outline sprouted a
stray wedge/notch whose size scaled with the pill's on-screen
position (diagnosed live by the tester subagent: ~1000px left spike
on a top-right node, right-side bites near the left edge).
- Labels now fade instead of popping: fully visible at fit zoom or
closer, then the labels canvas layer's opacity is interpolated across
a 0.5 camera-ratio zoom span before renderLabels switches off, with
the setSetting call guarded so pans don't spam refreshes.
The nested list stays as the default/collapsed view; the new expand
toggle (list header) opens the graph — a hand-built SVG diagram
(mermaid STYLE, no mermaid renderer: full control of the styling so it
speaks this app's design language):
- Top-down layered layout (topoLayout depth = rows, authoring order
within a row, rows centered on the widest) — vertical space is the
cheap axis; boxes + vertical bezier arrows with arrowheads.
- Status coloring matches the list marks: done nodes are colored in
(teach-phase green tint — the graph fills in as the session
progresses), current = the highlighted position, next = unlocked
ring, upcoming = quiet.
- Drag pan + wheel zoom (to the cursor, non-passive), +/- and
fit-to-panel buttons. The zoom FLOOR is fit: fully zoomed out, the
whole diagram always fits the panel — it can never disappear into
nothing. Auto-fits on measure/layout change until the learner takes
manual control; fit re-enables it.
- Panel widens to w-96 in graph mode; mode persists
(lh:tree-panel-mode: rail|list|graph, legacy key migrated).
- wrapTitle + graphLayout pure, unit-tested; TreeGraph SSR-render
tested (statuses, arrows, wrapping, data-next).
- components/phase-divider.tsx: PhaseChip (header, next to the session
title: phase-colored dot + Probing/Planning/Teaching) and PhaseDivider
(the transcript boundary: color-coded dotted rules + a small chip —
'Plan · N nodes' at the plan seam, 'Teaching' at the teach seam; probe
never renders, phases only advance). planNodeCount reads the seam
message's first plan tree.
- chat.tsx: dividers render at MESSAGE boundaries (phaseTimeline, one
linear fold) — the seam is the transition to the message's phase, so
the seam message's prose sits below its divider. requiresReveal now
uses phaseAt3 teach (an occupied node), so probe- AND plan-phase
questions auto-open.
- Retired the part-level plan-divider (artifact registry): the boundary
is message-level, not part-level. Its tests replaced by
render-phase-divider tests; core/phases gains tested phaseTimeline.
- SessionRow (extracted, exported for tests): leftmost phase strip
(bookmark tick, per-phase color: probe/plan/teach) + status dot left of
the title — pulsing amber attention dot when an answer is owed, quiet
breathing dot while the teacher works, nothing when it's the learner's
turn. A pending answer outranks 'working'.
- globals.css: phase + attention color tokens (one system shared with the
upcoming header chip and dividers) and the two dot animations, both
disabled under prefers-reduced-motion.
- SessionsSidebar polls /api/chats every 2.5s while open (payload is tiny
now that busy/phase/pendingQuestion come from the list) and pauses while
the tab is hidden; fetch-on-navigation preserved.
labelRenderedSizeThreshold gated each node's label by its own rendered
size, so big (taught) nodes showed names several zoom stops before
small (candidate) ones. Zero the per-node threshold and instead toggle
renderLabels from the camera ratio: every name appears at fit zoom or
closer and they all vanish together when zooming further out. Hover
still reveals any node's name regardless of zoom.
- Custom sigma label drawers replace the defaults: every label renders
the node name word-wrapped under the node (max 170px line, overlong
words hard-broken, never truncated) instead of one long strip to the
right of the node.
- Hover swaps sigma's hardcoded white box for a dark rounded pill using
the app's popover tokens; hover always shows the name, even below the
zoom threshold.
- labelRenderedSizeThreshold 12 -> 6 (names are short now) and labels
use the app's body font at weight 500.
- Click card anchors just below the clicked node's viewport position
(flipping above near the bottom edge, clamped horizontally, measured
in a layout effect so the flip never flashes); any pan/zoom dismisses
it via the camera 'updated' event.
Schema: GraphNode + ExtractedProposition carry 'name' — a short 2-6 word
header, the rendering handle. Node theory made explicit: a node is an
objective world-facing fact; the learner's relationship to it lives
entirely in the event ledger (state labels are derived, never stored).
Extractor + auditor instructions enforce it — misconceptions state the
wrong idea itself as a claim, never 'the learner believes Y'. Legacy
ledger lines without a name derive one from the statement on read.
graph-view: labels use the name; the detail panel shows name as header
and statement as body.
Compared the port against the original pi setup
(vault/π/learn/.pi: quiz.ts, ask-user-question.ts, teach SKILL.md) —
the pi version never produced invalid correctAnswer values. Root cause
of the port's validation failures: the pi options schema's 'Give each
option a stable value; you reference the correct one by that value in
correctAnswer' sentence was dropped in the port. Without it the model
omits values and must copy a long natural-language label verbatim into
correctAnswer — and instead slugifies it ('cultural-diagnosis' for
'A cultural diagnosis') every turn.
Now matched to pi:
- quiz schema: pi's field order (question, details, options,
multiSelect, correctAnswer, explanation) and descriptions — options
carry the stable-value instruction, correctAnswer is phrased as a
value reference ('the value field of the option you intend'), not a
copy-exact-or-fail threat. nodeId (lh-only, graph) stays.
- ask schema: dropped the redundant 'mode' param (pi has none; the dock
already infers from options presence), pi's descriptions.
- quiz tool description: pi's full text (ask contrast, note field,
dontKnow semantics) minus terminal-only details, plus lh's turn
protocol sentence.
- system-prompt: fixed the stale 'exactly two tools' line (plan/research/
demo/visual tools have their own sections).
Not matched, deliberately: tool results stay JSON (pi sends curated
text; formatAnswerMessage exists if we want it later), shuffle param
(lh always shuffles seeded), pi's ask '(Recommended)' label hint.
The bug: answering a quiz and navigating away mid-turn, then returning,
re-prompted the same question. Root causes: (1) the answer was durable only
at onFinish — every mid-turn view read the stale pre-answer record;
(2) the server had no notion of a turn in flight; (3) remount treated the
stale record as current, with no re-attach path. Worse, the stale dock let
the quiz be answered again, racing two turns into a last-writer-wins
saveMessages clobber.
Fix (four pieces):
- Write-ahead persist in chat-handler: the request body IS the client's
canonical state — saved to disk BEFORE the stream starts. The answer is
durable the instant the request arrives; crashes recover via the existing
mount continuation.
- Turn liveness registry (src/server/turn-liveness.ts): in-memory chatId →
in-flight map with a TTL leak guard; beginTurn rejects concurrent turns
(409) so one turn ever owns a chat. endTurn runs in onFinish AFTER
persistTurn, so pollers that see not-in-flight always read a finished
record; a turn-start failure clears the registry (no lockout).
- GET /api/chats/[id] reports turnInFlight; the chat page passes
initiallyInFlight to the client.
- Client re-attach (components/chat.tsx): while in flight, busy shimmer +
composer gated + mount continuation suppressed; poll /api/chats/[id] until
the turn finishes, then syncFromServer adopts the completed transcript.
Stop stays local-stream only (a server turn has no client request to
abort).
Verified by scripted-model tests: concurrent turn 409 + registry lifecycle,
write-ahead durability mid-turn, failed-turn lockout guard.
The shell now imports through exactly two barrels, enforced by
import/no-restricted-paths (npm run lint):
components/** -> "@/src/core" (pure core API, browser-safe)
app/** -> "@/src/core" + "@/src/server" (server entries)
Zone violations are lint errors with architecture-pointer messages; the
pure-core modules (contracts, question-core, plan-tree, phases, pending,
math-delims, ui-message) may never import agent/server/store.
Supporting moves (direction: IO layers -> core):
- core/index.ts: the core public API barrel
- core/ui-message.ts: moved from src/agent (it was shell-facing all along)
- quiz/ask input zod schemas moved agent/tools -> core/question-core
(the question contract, alongside the grading logic)
- ChatRecord/ChatSummary moved store/chats -> core/contracts (single schema)
- GraphSnapshot/NodeStateClass moved core/graph -> core/contracts (the
/api/graph payload IS a contract; the pure renderer needs only these)
- src/server/{chats,graph,jobs}.ts + index.ts: thin server entries for the
transport layer; GET /api/graph's fold side-effect now lives behind
graphView() instead of inline in the route
Gates: tsc clean, 190/190 tests, eslint clean (law verified to fire on
store/agent/subpath violations), production build clean.
(Repo repair en route: a git object (app/chat/[id] tree) was missing from
the object store — reconstructed byte-exactly via mktree from its blob;
the broken node_modules that stalled the build was cleanly reinstalled.)
Gate 1 found the teacher staying silent after a research brief landed.
The SDK only evaluates sendAutomaticallyWhen inside addToolOutput — an
external setMessages (our syncFromServer) updates the UI but never
triggers the continuation. Fix: syncFromServer checks
lastAssistantMessageIsCompleteWithToolCalls and calls sendMessage()
(itself a valid continuation trigger); plus a mount-continuation effect
for the reload case (job fulfilled while no client was open).
- src/core/math-delims.ts: pure preprocessing for the \(...\)/\[...\] math
contract — balanced delimiters rewrite to the two-dollar forms remark-math
parses ($ is never math). Skips code fences/spans, escaped delimiters, and
leaves unbalanced (mid-stream) delimiters untouched. Display math renders
as a block: mid-paragraph gets blank-line padding; indented (list items)
degrades to inline so list continuations don't half-parse.
- message.tsx: transform in the render path (children-memoized); math plugin
now singleDollarTextMath: false — the currency hazard dies structurally.
remark-breaks via the cjk remarkPluginsAfter slot (the bare remarkPlugins
prop would replace the [remark-gfm, codeMeta] defaults).
- mermaid: dark theme + sans font via Streamdown's mermaid prop; dark-styled
error fallback (components/mermaid-error.tsx) with error, source in
<details>, and retry.
- globals.css (appended): @source for streamdown dist — its internal UI
chrome (code blocks, mermaid containers, tables) was entirely unstyled
because Tailwind v4 never scans node_modules; --color-sidebar → card; wide
mermaid SVGs capped to the column; .katex-display scrolls.
- tests/render-markdown.test.tsx: 26 tests (transform unit + render). The
math describe block in render-cards.test.tsx is updated to the new
contract ($...$ now renders as literal text — pinned).
- src/store/jobs.ts: per-job JSON store in data/jobs (create/get/update/list,
dedup by toolCallId)
- src/agent/tools/jobs.ts: research tool — client-side (no execute), turn ends
at the call; input per contracts ResearchToolInput
- src/agent/tools/web.ts: server-side web_search (Google CSE) + web_fetch
(Readability/Turndown/linkedom, Jina fallback) — errors return as strings,
never thrown into the agent loop. Deps: @mozilla/readability, linkedom,
turndown (+@types/turndown dev)
- src/agent/subagents/researcher.ts: isolated ToolLoopAgent (web tools only,
12-step cap), researcher prompt ported from pi
- src/agent/subagents/runner.ts: spawnPendingJobs hook + runResearchJob —
fire-and-forget, activity line per tool call, fulfills the part in the
LATEST chat record (output-available) before flipping job status; failure
still fulfills the part so the teacher learns the outcome
- src/server/chat-handler.ts: onFinish spawn hook after saveMessages
- app/api/jobs/route.ts: GET ?chatId= polling endpoint
- components/artifacts/job-card.tsx + registry entry: polling activity card
(2s) → syncFromServer on finish; research-brief card (markdown + sources)
- src/agent/prompts/20-jobs.md: research doctrine for the teacher
- tests/jobs.test.ts: store CRUD, spawn hook via scripted mock teacher,
runner completion/failure with fake model + stubbed fetch
Clicking the collapsed bar set expanded=true and started a smooth
scrollToBottom — but the scroll position was still legitimately inside
the collapse zone (that's why the bar was showing), so the hysteresis
listener re-collapsed the dock on the very next scroll event, then
re-opened it when the scroll arrived: open → snap shut → reopen.
The machine had no notion of intent. Now the bar click sets an
expandIntent flag that suppresses the collapse branch; it clears when
the scrollToBottom promise settles (completion or interruption) or after
a 2s safety net, so a user yanking the scroll away mid-reveal collapses
the dock again instead of wedging it open.
Verified live: click = exactly one transition (bar→open at ~26ms, stays
open, lands at d=1); collapse still healthy afterward; mid-reveal
interrupt re-collapses within ~300ms.
- Chat now remounts per session (key={chat.id}): fresh StickToBottom,
fresh DockOverlay (no cross-session morph from the previous shell
height), fresh useChat.
- Conversation initial="instant" (was "smooth"): the mount scroll to
bottom is a jump, not a slide.
- DockOverlay skips the pending-question scroll/expand effect for the
session's INITIAL pending question (dock starts expanded; the initial
scroll positions us) — previously it fired a second smooth
scrollToBottom right after the library's initial scroll (the visible
'pause, then the quiz pops and pushes everything up').
- The dock-variant fade/rise no longer plays for the session's opening
variant; reserved for mid-session transitions.
Verified live: client-side switch settles at d=1px from the bottom within
one frame of content swap, dock open from the first frame, both
directions (quiz session, plain session).
- Oscillation fix: collapsing the dock frees ~Δpx of flow height; within
Δ of the bottom the browser clamps scrollTop to the new max, landing
the learner AT the bottom, which re-expanded the dock → loop. Now a
hysteresis state machine on the scroller's scroll events: collapse only
when distance-from-bottom > Δ+64 (strictly clamp-proof), expand only
within 16px of the bottom. ~370px dead band; exactly one transition per
direction verified live. Heights measured live per question.
- Reaching the bottom re-expands the dock AND scrolls to reveal it fully
(previously it grew over the content and left you short of the bottom).
- Streaming follow fixed: ConversationContent had h-full, so the observed
content box never grew and use-stick-to-bottom's ResizeObserver never
fired — no auto-scroll during streaming. min-h-full restores growth.
Verified: distance-from-bottom ≤70px transient during a 25s stream,
settles at 1px.
- Animation: the blob's shell morphs height (WAAPI, 180ms) on every
variant change — chat ↔ question ↔ collapsed bar — plus a quick
fade/rise (160ms) on the swapped content. Gotcha pinned in code: never
measure the shell while a morph is in flight (getBoundingClientRect
reads the ANIMATED value and corrupts the next morph's start height);
cancel running morphs before measuring, refresh settled height only
when no morph is running.
- Gradient-over-scrollbar fixed structurally: the dock is no longer an
absolute overlay on the conversation root — it's sticky bottom-0 INSIDE
the scroller (in flow). The transcript scrolls fully clear of the dock,
the fade never touches the scrollbar lane, and the pb-hack clearances
are gone.
- New question while at the bottom scrolls to reveal the dock; scrolled
up → collapsed bar, no yank.
- Thin dark native scrollbar app-wide (8px webkit + scrollbar-width:thin,
dark thumb, transparent track). Note: use-stick-to-bottom sets
scrollbar-gutter: stable both-edges on its scroller — the lane is
outside the content flow by design.
- 'Writing a question…' transcript shimmer while a tool call streams its
input (same slot as 'Thinking…'). Protocol pinned by a test asserting
tool-input-start precedes tool-input-available; scripted mock now
streams tool input as deltas like real providers do. (OpenRouter/
Anthropic often delivers the whole input in ONE delta — then the dock
appears instantly and no indicator is needed or shown.)
Verified live: grow 54→349px and shrink 349→54px fire with correct
from/to; collapse/expand intact; gradient stops before the gutter;
Thinking… observed in-page; 58/58 tests.
- A pending quiz/ask now REPLACES the chat composer: one persistent
rounded-2xl shell in the transcript overlay swaps contents (composer ↔
question ↔ collapsed bar), never remounting — the structure a future
grow-morph animation needs.
- Unified bottom row inside the question: the note field (select modes),
the answer field (text-mode asks), or the Other text — one field, one
'Submit answer' button, Enter submits.
- Collapse on scroll: uses useStickToBottomContext — scroll up and the
dock folds to a slim bar (kind chip + LaTeX-flattened question teaser +
'tap to answer'); click scrolls to bottom and re-expands. The expanded
form stays mounted-hidden so a half-made selection survives.
- Pending/streaming tool parts no longer render inline; answered parts
land in the transcript as graded cards on submit. Question generation
shows a shimmer in the shell.
- Composer back to pure chat (no mode machinery); quiz-card.tsx and the
pendingText/registerSubmit bridge deleted; render tests re-pointed at
the dock (wrapped in StickToBottom).
Verified live: docked quiz submit (note+selection), ask-text Enter
submit, collapse/expand with selection survival, bar teaser text.