Stepwise

Live · Jul–Oct 2026

At a glance

problems across 4 tiers
0
problems across 4 tiers
renderers, one per data structure
0
renderers, one per data structure
tools the AI tutor can drive
0
tools the AI tutor can drive

Open with

Try it liveSource code

Chat about Stepwise

Yash ›

psst, I answer from my notes on Stepwise, so ask me about the hard bits.

Today

Stepwise

Interactive DSA visualizer: every data structure drawn as itself, stepped one operation at a time, with an AI tutor that can drive the playback.

  • Next.js
  • TypeScript
  • Framer Motion
  • SVG
Try it live Source code

19

problems across 4 tiers

8

renderers, one per data structure

7

tools the AI tutor can drive

“
Most DSA tools are slideshows. You click Next, watch pointers shuffle, and still can't do it on a blank page.
why I built it

01How it flows

  1. 1Pick a problemarrays, trees, graphs, sorting
  2. 2Step through the real algorithmscrub forward and back
  3. 3Change the inputworst case, or your own values
  4. 4Ask Ada when you're stuckshe asks back

02The fun part3 problems

Streaming without deadlocking Next

1/3

Next buffers patched fetch bodies, which silently hung the tutor's stream in production. The fix was cache no-store, an eager pump loop, and a comment as the very first byte.

app/api/tutor/route.ts

Tool calls arriving in pieces

2/3

A single goto_step can arrive split across three deltas. An accumulator stitches the fragments by index before anything runs.

envelopeStream()

A tutor, not a chatbot

3/3

Ada sees your step, its "why" and your wrong guesses, and must never hint at an open prediction, even when you ask "so it's not C, right?"

TutorContext

03What broke

  • Hand-written "why" notes pass CI even when they explain the step badly.
  • Very large graphs make share links longer than browsers allow, with no fallback yet.

04Things people ask

What's the stack?

Next.js 16 App Router, React 19, TypeScript, Tailwind v4 (CSS-first, no config file), Zustand 5 for player and workspace state, motion (the renamed framer-motion) for spring physics, @xyflow/react for the canvas drafting pad, OpenRouter for the LLM, Drizzle ORM + Neon Postgres for auth and conversation history, Better Auth for auth, lz-string for URL state encoding.

Why are traces computed at runtime instead of stored in a database?

Because run_custom_input exists. Ada can re-run any algorithm on arbitrary values the learner types. If traces were stored rows, custom input would require either a write on every query (expensive, stateful) or a separate code path (inconsistency). Running the tracer function on demand means custom input is the same call as the default — just a different dataset. Traces are memoized in memory, so re-visiting a problem is still O(1).

How does Ada know what's on my screen?

Every message to the tutor API includes a TutorContext snapshot: the current step index, its narration string, its why annotation (the authored reason the algorithm had no other choice), variables in scope, what scene kind is on screen, the current dataset, and the last few wrong predictions with ground-truth reasons. Ada doesn't have a camera — she has structured telemetry, which is more reliable.

Can Ada just give me the answer if I push hard enough?

The system prompt has explicit negative constraints: never hand over the approach on first ask, escalate only after 2–3 real attempts, and if an open predict-gate is on screen, do not state, hint at, or eliminate any option. It took several iterations to make those hold under adversarial phrasing ("so it's not C, right?"). If you genuinely get stuck after multiple attempts, she will give you a real foothold — withholding help entirely is also a failure mode.

How does the URL sharing work?

The full canvas state (nodes, edges, pointer assignments) is serialized to JSON, LZ-compressed with lz-string, and base64url-encoded into a ?state= query parameter. No backend write, no login required. The limitation is URL length — very large graphs hit browser limits.

What's the validate:traces script?

pnpm validate:traces executes every registered problem against every dataset and runs 12 checks: things like "narration must not be empty," "code line anchors must point to lines that exist in the source string," "step indices must be sequential," "why annotations on ratcheted problems must be present on semantic steps," and "every narration must survive the speakable() normalizer without leaving unreadable glyphs." It exits non-zero on any failure and runs in CI. It cannot tell you the algorithm is correct — only a human can — but it catches the bugs that rot silently.

What was the hardest part technically?

Getting the SSE streaming to not deadlock. Next.js patches global fetch and buffers response bodies for caching, which hangs a streaming body. The fix required cache: "no-store" on the OpenRouter fetch, switching from a pull-gated to an eager pump reader, and emitting a comment as the literal first byte to force header flush. Any one of those missing causes a silent hang in production that doesn't show up locally.

What's the ListView's "head label" trick?

ListView.tsx computes the head as "the node nothing points to." Once the list is reversed mid-algorithm, the first box is no longer the head, so the "Head" label is dropped — not left lying. The principle is: withdraw information that has become false. State that's gone stale is worse than state never shown. Ada applies the same logic: she won't confirm or eliminate predict-gate options because doing so would be false while the gate is still open.

Can I try it without an account?

Yes — the full problem catalog and Ada are available anonymously. Signing in adds conversation history persistence per problem.

Why OpenRouter instead of calling a model provider directly?

OpenRouter lets you swap the underlying model via an env var without touching code. During development the free tier (currently poolside/laguna-s-2.1:free) is good enough to verify tool-calling works end to end. In production you can point it at Claude or any other model by changing one env var. The API surface is OpenAI-compatible, so the streaming logic is the same either way.

What's the predict-gate?

At authored moments in a trace, the player pauses and asks the learner to predict the algorithm's next move before it plays. The options are authored alongside the tracer step, with per-option explanations of why each is right or wrong. Ada can also trigger a gate mid-conversation (pose_prediction tool). Wrong predictions are logged and sent to Ada as context so she coaches from the actual ground truth rather than guessing.

The whole write-up6 min read, for the curious

The itch

The problem I kept running into was that every DSA tool I found was either a passive slideshow or a dense editorial that explained what an algorithm does without ever making you feel why it works. You click Next, watch pointers shuffle, and still can't reproduce it on a blank page five minutes later. I wanted something that makes you interact with the mechanism, not just observe it.

What it does

You pick a problem from the catalog — Reverse Linked List, Two Sum, Dijkstra's, 19 others across arrays, trees, graphs, sorting, and more. The visualizer runs the real algorithm and snapshots every meaningful step. You can scrub forward and backward, switch to a different dataset (e.g. worst-case input), or type in your own values and watch it re-run from scratch. Ada, an AI tutor, lives in a side panel. She sees exactly what step you're on, what variables are in scope, and what the narration says. Ask her why the algorithm saved a pointer before rewiring it, and she'll point you at the specific node on screen and ask you a question back. She doesn't hand over the answer on the first ask — that refusal is the product.

How it works

The core idea is that traces are functions, not data. When you open /problem/reverse-linked-list, the server calls getTrace("reverse-linked-list", "default"), which runs the actual reverseListTrace() function — a TypeScript reimplementation of the algorithm, instrumented with a ListTracer that extends BaseTracer. Every meaningful operation calls commit(), which snapshots the full scene (node positions, pointer states, variable values, a narration string, which code lines are highlighted) into an immutable Step. The result is a Trace: an array of steps that the player scrubs through.

slug → getTrace() → registry → ExampleDef.build(dataset) → BaseTracer.commit() → Step[]

Because traces are computed at request time and memoized in memory, run_custom_input just calls the same function with different input — no stored data to invalidate, no re-indexing.

The player is Zustand. The UI subscribes to index, advances on tick or button press, and passes the current Step.scene to one of 8 scene-specific SVG renderers (ArrayView, ListView, TreeView, GraphView, etc.). Each renderer is a pure function of scene state — no local animation state, motion springs handle the transitions.

Ada runs on OpenRouter via a server route (app/api/tutor/route.ts, runtime = "nodejs"). The route builds a system prompt from a TutorContext snapshot — current step, narration, the step's why field, variable values, dataset options, recent wrong predictions — and streams the reply back as SSE. Ada gets 7 tools she can call: goto_step, play, pause, set_dataset, run_custom_input, pose_prediction, and highlight_node. Tool calls arrive as typed SSE events ({type: "tool_use", name, input}) and execute client-side against the Zustand player store. Rate limiting is two sliding windows via Upstash Redis (10 req/min burst, 100 req/day); signed-in users get their own bucket instead of sharing the IP bucket.

Canvas state is shared via URL using lz-string — the full node/edge graph is serialized and LZ-compressed into a URI-safe query param. No backend write, no login required, no storage cost.

Auth is Better Auth backed by Neon Postgres via Drizzle ORM. Signed-in users get conversation history persisted per problem; anonymous users get the full experience but nothing is saved.

The fun part

Streaming without deadlocking Next.js. The tutor route streams SSE from OpenRouter, but Next.js patches global fetch and will buffer the response body to populate its cache — which deadlocks a streaming body. The upstream sends keep-alive comment lines that produce no data events, so nothing gets enqueued; Next then won't flush response headers (no first byte), stops driving the consumer, which stops us reading upstream. The fix was two things: cache: "no-store" on the fetch call (tells Next not to touch it), and switching from a pull-gated reader to an eager pump loop that drains the upstream on its own schedule regardless of backpressure. The very first byte enqueued is a comment (": open\n\n") — that alone flushes headers immediately. Losing either of these causes a silent hang in production that doesn't reproduce in local dev.

Tool fragments arrive split across SSE deltas. OpenRouter streams tool calls as partial JSON across multiple delta events, keyed by index. A single goto_step might arrive as {"goto_ / step": / 4} across three chunks. The accumulator in envelopeStream() builds a Map<number, {name, args}> that collects fragments by tool index, then parses and flushes all complete tool calls as typed events once the upstream closes. If the args JSON is malformed, it silently skips that tool rather than emitting a broken event.

Making Ada a tutor, not a chatbot. The behavioral constraint — "withhold the approach, ask a leading question, escalate only after 2–3 real attempts" — is entirely in the system prompt. But the prompt also has to be grounded: Ada must be able to refer to what's on screen right now. So the TutorContext that rides every request includes the step's why field (the authored "why this step had no choice" annotation on each tracer commit), the current predict-gate if one is open (Ada must never reveal the answer to an open gate), and the last three wrong predictions with ground-truth reasons. Ada's constraint about open gates — "do not state, hint at, or eliminate any option" — is one of the harder negative constraints to get right, because a helpful-sounding deflection can still leak the answer. Getting this to hold up under adversarial questions ("is it A?", "so it's not C, right?") took several prompt iterations.

What broke / what I'd change

The why annotations on each tracer step are authored by hand — a string that explains why the algorithm had no other choice at that moment. For the ~20 problems on the "why-ratchet" (WHY_ENFORCED in validate-traces.ts), every semantic step (push, pop, swap, insert, visit, set, mark) must carry one. The 12 mechanical checks in trace-checks.ts verify presence and shape, but they can't tell a good why from a bad one. A why that's technically present but pedagogically wrong ("we swap these elements") passes CI and silently gives Ada bad ground truth. The only real gate is human review on every new problem — which is fine at the current scale but doesn't compose.

The URL-based state sharing also has a ceiling: deeply nested graphs or very long linked lists compress to URLs that exceed browser limits. There's no fallback yet.

Numbers

  • 19 problems across 4 tiers (Foundations, Linear & Recursive, Trees, Graphs/Sorting/Search)
  • 8 scene renderers: array, list, stack, queue, hash, tree, graph, grid
  • 12 mechanical checks per trace run by pnpm validate:traces
  • ~20 traces on the why ratchet — every semantic step in those traces carries an authored explanation of why the algorithm had no other choice
  • 7 Ada tools: goto_step, play, pause, set_dataset, run_custom_input, pose_prediction, highlight_node
  • 2-window rate limit: 10 req/min burst, 100 req/day per IP or user ID
  • Code panel shows Python, TypeScript, and C++ implementations on problems that have alt-language maps (e.g. reverseListTrace carries PY_SRC and C_SRC with line-number remappings)