From 1c3d288d08d46ca751c47565c77e71d8fb77f333 Mon Sep 17 00:00:00 2001 From: Amos Date: Tue, 1 Sep 2026 18:24:13 +0300 Subject: [PATCH 1/8] Three-phase session status: derived summaries for the picker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - core/phases.ts: Phase3 (probe/plan/teach) + pure derivations — phaseOfTree (point-in-time, from the stored plan tree: no nodes → probe, no occupied node → plan, occupied → teach) and phaseAt3 (monotonic transcript fold for the dividers: failed plan_init never marks a seam; phase only advances). - contracts.ts: ChatSummary gains record-derived phase + pendingQuestion; ChatListItem adds liveness-merged busy. - store/chats.ts listChats computes the record-derived fields (tree + pending question scan). - api/chats route merges busy = turn running || running background job. Lane crossing granted by master: contracts/store/api (schema arbitration). Data-only inference: pre-plan planning reads as probe until the plan lands. --- app/api/chats/route.ts | 13 ++++- src/core/contracts.ts | 25 ++++++++- src/core/phases.ts | 82 ++++++++++++++++++++++++++++++ src/store/chats.ts | 13 ++++- tests/phases.test.ts | 113 ++++++++++++++++++++++++++++++++++++++++- 5 files changed, 241 insertions(+), 5 deletions(-) diff --git a/app/api/chats/route.ts b/app/api/chats/route.ts index cb4c31b..7ac8e5a 100644 --- a/app/api/chats/route.ts +++ b/app/api/chats/route.ts @@ -1,7 +1,16 @@ -import { createChat, listChats, titleFromPrompt } from "@/src/server"; +import { createChat, isTurnRunning, listChats, listJobs, titleFromPrompt } from "@/src/server"; +import type { ChatListItem } from "@/src/core"; +/** The session picker's list: record-derived summaries (phase, pending + * question) + live liveness — a running turn OR a background job marks + * the session busy (contracts.ts ChatListItem; the store can't see + * liveness, the route is the merge point). */ export async function GET() { - return Response.json({ chats: listChats() }); + const chats: ChatListItem[] = listChats().map((c) => ({ + ...c, + busy: isTurnRunning(c.id) || listJobs(c.id).some((j) => j.status === "running"), + })); + return Response.json({ chats }); } export async function POST(req: Request) { diff --git a/src/core/contracts.ts b/src/core/contracts.ts index 2f2a1ed..a494da2 100644 --- a/src/core/contracts.ts +++ b/src/core/contracts.ts @@ -5,6 +5,7 @@ */ import type { UIMessage } from "ai"; +import type { Phase3 } from "./phases.ts"; // ─── Plan tree (vision §2 "formal plan tree") ──────────────────────────────── // A session-scoped dependency tree authored by the teacher via plan tools. @@ -257,13 +258,35 @@ export interface ChatRecord { tree?: PlanTree; } -/** The list view's shape (messageCount instead of full messages). */ +/** The list view's shape (messageCount instead of full messages) + the + * per-session status the picker renders. `phase` and `pendingQuestion` + * derive from the stored record (tree + messages); the store computes + * them in listChats. Liveness (`busy`) is NOT record-derived — the API + * route merges it in (see ChatListItem). + * + * Phase semantics (three phases, data-only): probe = no plan yet, plan = + * tree exists but no node occupied, teach = a node is occupied + * (core/phases.ts phaseOfTree). + */ export interface ChatSummary { id: string; title: string; createdAt: string; updatedAt: string; messageCount: number; + /** The session's current phase, derived from the stored plan tree. */ + phase: Phase3; + /** An unanswered quiz/ask question is waiting for the learner. */ + pendingQuestion: boolean; +} + +/** The sidebar's session row: a summary + live liveness. The chats list + * route attaches `busy` from the turn-liveness registry and the job store + * (a running turn OR a background job = the session is working). The store + * itself can't see liveness (import law: store never imports server), + * hence the split at exactly the record/liveness seam. */ +export interface ChatListItem extends ChatSummary { + busy: boolean; } // ─── Async sub-agent jobs (vision §2.5; plan.md Wave 0 protocol) ──────────── diff --git a/src/core/phases.ts b/src/core/phases.ts index 4312829..f0a22ea 100644 --- a/src/core/phases.ts +++ b/src/core/phases.ts @@ -45,3 +45,85 @@ export function phaseAt(messages: readonly PhaseMessage[], upToIndex?: number): } return "probe"; } + +// ─── The three-phase view (probe / plan / teach) ────────────────────────────── +// +// The session picker's color strips, the header chip, and the transcript +// dividers all speak THREE phases, derived data-only from the plan tree: +// +// probe — no plan output yet (the tree is empty or absent); +// plan — a tree exists but no node is occupied (plan_set_current not fired); +// teach — a node is occupied. +// +// The teacher's invisible PRE-plan planning (reasoning before plan_init +// fires) reads as probe until the plan lands — an accepted limitation: no +// observable signal marks "I'm now planning" (a teacher-side marker would be +// an agent change; see phases.md discussion in the transcript divider work). + +/** The three phases of a session, as the picker / header / dividers see it. */ +export type Phase3 = "probe" | "plan" | "teach"; + +/** The advance-only order of phases: a session never visibly regresses. */ +const PHASE3_RANK: Record = { probe: 0, plan: 1, teach: 2 }; + +/** Structural slice of a plan tree — anything with nodes + a current node. */ +export interface PhaseTree { + nodes: ReadonlyArray; + currentNodeId: string | null; +} + +/** + * The phase of a tree, point-in-time: no nodes → probe, no current node → + * plan, an occupied node → teach. Used for the chats summary (the stored + * tree IS the session state there). Empty trees (emptyTree(), a failed + * plan_init) read as probe — a seam only counts once a plan exists. + */ +export function phaseOfTree(tree: PhaseTree | null | undefined): Phase3 { + if (!tree || tree.nodes.length === 0) return "probe"; + return tree.currentNodeId === null ? "plan" : "teach"; +} + +/** + * Minimal structural slice of a UI message for the three-phase scan: parts + * with a state and (when a plan op completed) its output. + */ +export interface Phase3Message { + parts: ReadonlyArray<{ type: string; state?: string; output?: unknown }>; +} + +/** A successful plan-op output as it appears on the part (`PlanToolResult`). */ +interface PlanOutput { + tree?: { nodes?: unknown }; +} + +/** + * The three-phase boundary semantics over the TRANSCRIPT (the same data the + * tree panel reads): scanning forward from 0 to `upToIndex` (default: the + * last message), the phase advances probe → plan at the first plan part + * with a NON-EMPTY tree available (a failed plan_init carries an empty tree + * and never marks the seam), and plan → teach at the first tree output with + * an occupied node. MONOTONIC by design: the phase only ever advances — a + * node removal mid-teaching (currentNodeId → null) is an edit, not a phase + * regression, so no "Plan" divider ever appears below teaching content. + * + * `phaseAt` (two-phase) stays as-is: the plan_init call is its seam and the + * question dock's reveal logic leans on it. The two views differ only in + * the window between plan_init and the first plan_set_current, where + * three-phase reads "plan". + */ +export function phaseAt3(messages: readonly Phase3Message[], upToIndex?: number): Phase3 { + let phase: Phase3 = "probe"; + const last = Math.min(upToIndex ?? messages.length - 1, messages.length - 1); + for (let i = 0; i <= last; i++) { + const parts = messages[i]?.parts; + if (!parts) continue; + for (const part of parts) { + if (!part.type.startsWith("tool-plan_") || part.state !== "output-available") continue; + const tree = (part.output as PlanOutput | undefined)?.tree as PhaseTree | undefined; + if (!tree || !Array.isArray(tree.nodes)) continue; + const candidate = phaseOfTree(tree); + if (PHASE3_RANK[candidate] > PHASE3_RANK[phase]) phase = candidate; + } + } + return phase; +} diff --git a/src/store/chats.ts b/src/store/chats.ts index 007a5da..ca56ec4 100644 --- a/src/store/chats.ts +++ b/src/store/chats.ts @@ -13,6 +13,8 @@ import { PATHS } from "../../config.ts"; import type { ChatStore } from "../core/ports.ts"; import type { ChatRecord, ChatSummary, PlanTree } from "../core/contracts.ts"; import type { UIMessage } from "ai"; +import { findPendingToolCall } from "../core/pending.ts"; +import { phaseOfTree } from "../core/phases.ts"; function chatFile(id: string): string { if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error(`Invalid chat id: ${id}`); @@ -49,7 +51,16 @@ function listChats(): ChatSummary[] { .filter((f) => f.endsWith(".json")) .map((f) => getChat(f.slice(0, -5))) .filter((r): r is ChatRecord => r !== null) - .map(({ messages, ...summary }) => ({ ...summary, messageCount: messages.length })) + .map(({ messages, tree, ...summary }) => ({ + ...summary, + messageCount: messages.length, + // Record-derived status for the session picker: phase from the + // stored plan tree, pending question from the transcript's last + // unanswered quiz/ask part. Liveness (busy) is NOT record-derived — + // the API route merges it (contracts.ts ChatListItem). + phase: phaseOfTree(tree), + pendingQuestion: findPendingToolCall(messages) !== null, + })) .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); } catch { return []; diff --git a/tests/phases.test.ts b/tests/phases.test.ts index 0ce8005..14982a5 100644 --- a/tests/phases.test.ts +++ b/tests/phases.test.ts @@ -8,7 +8,13 @@ */ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { phaseAt, type PhaseMessage } from "../src/core/phases.ts"; +import { + phaseAt, + phaseAt3, + phaseOfTree, + type Phase3Message, + type PhaseMessage, +} from "../src/core/phases.ts"; /** A minimal message: just typed parts, exactly the structural slice phaseAt reads. */ function msg(...partTypes: string[]): PhaseMessage { @@ -83,3 +89,108 @@ describe("phaseAt", () => { assert.equal(phaseAt([]), "probe"); }); }); + +// ─── The three-phase view (picker strips, header chip, transcript dividers) ──── + +/** A minimal tree: nodes as opaque ids is all phaseOfTree reads. */ +function tree(nodes: string[], currentNodeId: string | null): { nodes: unknown[]; currentNodeId: string | null } { + return { nodes: nodes.map((id) => ({ id })), currentNodeId }; +} + +/** A message whose parts are full plan-op tool parts with outputs. */ +function planMsg( + ...ops: { tool: string; ok: boolean; tree: ReturnType }[] +): Phase3Message { + return { + parts: ops.map((op, i) => ({ + type: `tool-plan_${op.tool}`, + state: "output-available", + toolCallId: `p${i}`, + output: { ok: op.ok, tree: op.tree }, + })), + }; +} + +describe("phaseOfTree", () => { + it("no tree / empty tree → probe", () => { + assert.equal(phaseOfTree(undefined), "probe"); + assert.equal(phaseOfTree(null), "probe"); + assert.equal(phaseOfTree(tree([], null)), "probe", "emptyTree() (a failed init) reads probe"); + }); + + it("tree with no current node → plan", () => { + assert.equal(phaseOfTree(tree(["a", "b"], null)), "plan"); + }); + + it("occupied node → teach", () => { + assert.equal(phaseOfTree(tree(["a", "b"], "a")), "teach"); + }); +}); + +describe("phaseAt3", () => { + it("no plan parts anywhere → probe at every index", () => { + const messages: Phase3Message[] = [msg("text"), msg("tool-quiz"), msg("text")]; + for (let i = 0; i < messages.length; i++) { + assert.equal(phaseAt3(messages, i), "probe", `index ${i}`); + } + assert.equal(phaseAt3([]), "probe"); + }); + + it("the probe→plan seam: the first plan output with a non-empty tree", () => { + const messages: Phase3Message[] = [ + msg("text"), // probe chatter + planMsg({ tool: "plan_init", ok: false, tree: tree([], null) }), // failed init: NOT a seam + msg("text"), + planMsg({ tool: "plan_init", ok: true, tree: tree(["a", "b"], null) }), // ← the seam + msg("text"), + ]; + assert.equal(phaseAt3(messages, 0), "probe"); + assert.equal(phaseAt3(messages, 1), "probe", "a failed init carries an empty tree — no seam"); + assert.equal(phaseAt3(messages, 2), "probe"); + assert.equal(phaseAt3(messages, 3), "plan"); + assert.equal(phaseAt3(messages, 4), "plan"); + assert.equal(phaseAt3(messages), "plan", "default = current phase"); + }); + + it("the plan→teach seam: the first tree output with an occupied node", () => { + const messages: Phase3Message[] = [ + msg("text"), + planMsg({ tool: "plan_init", ok: true, tree: tree(["a", "b"], null) }), + msg("text"), + planMsg({ tool: "plan_set_current", ok: true, tree: tree(["a", "b"], "a") }), // ← the seam + msg("text"), + ]; + assert.equal(phaseAt3(messages, 2), "plan"); + assert.equal(phaseAt3(messages, 3), "teach"); + assert.equal(phaseAt3(messages, 4), "teach"); + }); + + it("collapsed seams: init and set_current in one message → straight to teach", () => { + const messages: Phase3Message[] = [ + msg("text"), + planMsg( + { tool: "plan_init", ok: true, tree: tree(["a"], null) }, + { tool: "plan_set_current", ok: true, tree: tree(["a"], "a") }, + ), + ]; + assert.equal(phaseAt3(messages, 0), "probe"); + assert.equal(phaseAt3(messages, 1), "teach"); + }); + + it("monotonic: a mid-teach node removal (current → null) never regresses the phase", () => { + const messages: Phase3Message[] = [ + planMsg({ tool: "plan_init", ok: true, tree: tree(["a", "b"], null) }), + planMsg({ tool: "plan_set_current", ok: true, tree: tree(["a", "b"], "a") }), + msg("text"), + planMsg({ tool: "plan_remove_node", ok: true, tree: tree(["b"], null) }), // edit, not a regression + ]; + assert.equal(phaseAt3(messages, 2), "teach"); + assert.equal(phaseAt3(messages, 3), "teach", "phase only ever advances"); + }); + + it("upToIndex past the end / negative → clamped, never throws", () => { + const messages: Phase3Message[] = [planMsg({ tool: "plan_init", ok: true, tree: tree(["a"], null) })]; + assert.equal(phaseAt3(messages, 99), "plan"); + assert.equal(phaseAt3(messages, -1), "probe", "empty scan range → probe"); + }); +}); From 05359301e2fa07e38ead600c92bb9925a3f2b302 Mon Sep 17 00:00:00 2001 From: Amos Date: Tue, 1 Sep 2026 18:28:35 +0300 Subject: [PATCH 2/8] Session picker: phase strips, status dots, live polling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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. --- app/globals.css | 73 ++++++++++++++++++ components/sidebar.tsx | 141 ++++++++++++++++++++++++++-------- tests/render-sidebar.test.tsx | 79 +++++++++++++++++++ 3 files changed, 263 insertions(+), 30 deletions(-) create mode 100644 tests/render-sidebar.test.tsx diff --git a/app/globals.css b/app/globals.css index a123a02..8f6c102 100644 --- a/app/globals.css +++ b/app/globals.css @@ -157,3 +157,76 @@ body { overflow-x: auto; overflow-y: hidden; } + +/* ============================================================ + * Session status — phase colors + status dots + * (picker strips, header chip, transcript dividers: one language) + * ============================================================ */ + +/* Phase colors: blue = probing, violet = planning, green = teaching. + Tuned per theme (light needs darker, dark lighter). The attention color + (an answer the learner owes) is deliberately outside the phase system — + dots and strips are separate channels and must not read as one. */ +:root { + --phase-probe: oklch(0.55 0.17 253); + --phase-plan: oklch(0.54 0.19 300); + --phase-teach: oklch(0.55 0.14 160); + --attention: oklch(0.62 0.15 65); +} + +.dark { + --phase-probe: oklch(0.72 0.13 250); + --phase-plan: oklch(0.72 0.14 300); + --phase-teach: oklch(0.74 0.12 160); + --attention: oklch(0.8 0.15 75); +} + +@theme inline { + --color-phase-probe: var(--phase-probe); + --color-phase-plan: var(--phase-plan); + --color-phase-teach: var(--phase-teach); + --color-attention: var(--attention); +} + +/* Status dots (session picker). Attention — a slow expanding ring, drawing + the eye to "your move". Working — a quiet breathing dot, opacity only, + never loud enough to compete with the attention ring. */ +@keyframes lh-dot-attention { + 0% { + box-shadow: 0 0 0 0 color-mix(in oklab, var(--attention) 60%, transparent); + } + + 70%, + 100% { + box-shadow: 0 0 0 5px transparent; + } +} + +.lh-dot-attention { + animation: lh-dot-attention 1.6s ease-out infinite; +} + +@keyframes lh-dot-breathe { + 0%, + 100% { + opacity: 0.35; + transform: scale(0.75); + } + + 50% { + opacity: 1; + transform: scale(1); + } +} + +.lh-dot-breathe { + animation: lh-dot-breathe 1.4s ease-in-out infinite; +} + +@media (prefers-reduced-motion: reduce) { + + .lh-dot-attention, + .lh-dot-breathe { + animation: none; + } +} diff --git a/components/sidebar.tsx b/components/sidebar.tsx index d705b13..9b27e5c 100644 --- a/components/sidebar.tsx +++ b/components/sidebar.tsx @@ -6,7 +6,7 @@ import { usePathname, useRouter } from "next/navigation"; import { PanelLeftCloseIcon, PanelLeftOpenIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -import type { ChatSummary } from "@/src/core"; +import type { ChatListItem, Phase3 } from "@/src/core"; /** * Toggleable sidebar — NOT a modal drawer: no backdrop, no focus theft. It @@ -65,23 +65,115 @@ export function SidebarToggle() { ); } +/** The left-edge phase strip color — one system with the header chip and + * the transcript dividers (globals.css --phase-*). */ +const PHASE_STRIP: Record = { + probe: "bg-phase-probe", + plan: "bg-phase-plan", + teach: "bg-phase-teach", +}; + +/** + * The session-status dot, left of the title. One visual family: a pulsing + * attention ring when an answer is owed (your move — the session is blocked + * on the learner), a quietly breathing dot while the teacher works (a turn + * running or a background job in flight), and NOTHING when it's simply the + * learner's turn to type — quiet is the correct default. A pending answer + * outranks "working": there is nothing else for the learner to do first. + */ +function SessionStatusDot({ pending, busy }: { pending: boolean; busy: boolean }) { + const label = pending ? "Waiting for your answer" : busy ? "Teacher is working" : null; + return ( + + {pending ? ( + + ) : busy ? ( + + ) : ( + /* empty slot: keeps every title on the same baseline */ + + )} + {label && {label}} + + ); +} + +/** + * One session row: the leftmost phase strip (bookmark tick, one color system + * with the header chip and transcript dividers), the status dot, then title + * + meta. Exported for render tests — pure function of the list item. + */ +export function SessionRow({ + chat, + active, + onOpen, +}: { + chat: ChatListItem; + active: boolean; + onOpen: () => void; +}) { + return ( + + ); +} + function SessionsSidebar() { const { open, toggle } = useSidebar(); - const [chats, setChats] = useState(null); + const [chats, setChats] = useState(null); const pathname = usePathname(); const router = useRouter(); + const refresh = useCallback(async () => { + try { + const res = await fetch("/api/chats", { cache: "no-store" }); + const d = (await res.json()) as { chats: ChatListItem[] }; + setChats(d.chats); + } catch { + // a transient failure on the periodic poll keeps the last snapshot + setChats((prev) => prev ?? []); + } + }, []); + useEffect(() => { if (!open) return; - let cancelled = false; - fetch("/api/chats", { cache: "no-store" }) - .then((r) => r.json()) - .then((d: { chats: ChatSummary[] }) => !cancelled && setChats(d.chats)) - .catch(() => !cancelled && setChats([])); - return () => { - cancelled = true; - }; - }, [open, pathname]); + void refresh(); + // Poll while open: the statuses are live (a question lands in another + // session, a turn finishes in the background) and the payload is tiny. + // Pause while the tab is hidden; navigation refetches via pathname. + const id = setInterval(() => { + if (!document.hidden) void refresh(); + }, 2500); + return () => clearInterval(id); + }, [open, pathname, refresh]); return (