diff --git a/README.md b/README.md index 1a0aa00..5a937ac 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Without a provider, links are plain `` and nothing is "active". "./theme": "resolveTheme, resolveBase, themeFromToml, the registry, colour utils", "./ratchet": "runRatchet, defineRatchetSuite, formatViolations, RULES, strictRules, ATLAS_PREFIX_RULE, TRANSITION_ALL_RULE, SURFACE_CARD_RULE", "./animations": "INFINITE_ANIMATIONS, INFINITE_ANIMATION_FPS_VAR, infiniteAnimationFps (no React, no DOM at import)", - "./session": "the SessionView types and helpers, StreamingMarkdown, ToolCallCard, TurnRow, SessionTimeline, SessionPipeline", + "./session": "the transcript (row model, TranscriptProvider, TranscriptRowItem, TranscriptView, its parts), StreamingMarkdown, the SessionView types and helpers, SessionPipeline", "./timeline-calendar": "TimelineCalendar, which needs @tanstack/react-virtual", "./checkpoint-trace": "CheckpointTrace and its types, which needs @tanstack/react-virtual", "./keys.toml": "the derivation source", @@ -82,30 +82,59 @@ which desktop and web already have), and the root entry imports none of them. ### Sessions -Desktop and web each adapt their own session shape (the delta wire, the -server's `TimelineEntry` pages) onto one presentational type, `SessionView`, -and render it with the same blocks. The field-by-field mapping is the -docblock of `src/components/session/session-view.ts`. +The session transcript is one composition, the one desktop draws, and both +apps render it. Each app adapts its own data (desktop's delta wire, the +server's timeline pages and RC transcript) into the package's row model, +`Row` (`src/components/session/transcript/model.ts`): a closed set of +`RowKind`s, plain data compared shallowly, so a memoised row re-renders only +when its own data changes. The label helpers that turn a tool call into a +row's text (`toolDisplayName`, `toolIconFor`, `summarizeMarkers`, +`liveMarkerLabel`, `parseShellCommand`, `thoughtHeadline`) are exported for +those adapters. + +What only an app can do comes in through one `TranscriptProvider`: the +markdown renderer, the actions under a message, comment pills, the +changed-files card, and what a click on a tool line opens. Only `Markdown`, +`onToggleExpand` and `onToggleGroup` are required; a slot left unset draws +nothing. ```tsx import rehypeHighlight from "rehype-highlight"; -import { SessionTimeline, toolKindOf, type SessionView } from "@tryatlas/design/session"; +import { + StreamingMarkdown, + TranscriptProvider, + TranscriptRowItem, + TranscriptView, + type TranscriptMarkdownProps, +} from "@tryatlas/design/session"; const plugins = [rehypeHighlight]; // stable identity: blocks re-render on a new array +function Markdown({ source, streaming }: TranscriptMarkdownProps) { + return ; +} - } - onLoadPayload={(callId, part) => loadPayload(callId, part)} - errorAction={} -/>; + + ( + + ))} + turnInProgress={live} + working={live && waiting} + more={false} + /> +; ``` -The package highlights nothing itself: pass `rehype-highlight` (or anything -that emits highlight.js classes), and `syntax.css`, part of `styles.css`, -colours them from the theme's `syntax.*` keys. `StreamingMarkdown` never -re-parses a finished block, so stream into it as fast as text arrives. +The rows' styles are `transcript.css`, part of both stylesheets. The column +is `--transcript-column` (760px unless the app sets it). The package +highlights nothing itself: pass `rehype-highlight` (or anything that emits +highlight.js classes), and `syntax.css`, part of `styles.css`, colours them +from the theme's `syntax.*` keys. `StreamingMarkdown` never re-parses a +finished block, so stream into it as fast as text arrives. ### Server components @@ -424,6 +453,19 @@ foundations page). - The package sets no root font size; desktop and web both use 13px, so `rem` spacing matches between them. +### Unreleased + +- **The session transcript replaces the session blocks.** `SessionTimeline`, + `TurnRow` and `ToolCallCard` are gone from `./session`. In their place is + the transcript desktop draws: the `Row` model, `TranscriptProvider`, + `TranscriptRowItem`, `TranscriptView`, `LoadingState`, + `LoadingTranscriptState`, `JumpToBottomPill` and the label helpers + ([Sessions](#sessions) has the shape). `SessionView`, its helpers and + `SessionPipeline` stay. +- **`transcript.css`** is new and is imported by both stylesheets. It + carries the rows' `atlas-*` classes, their animations and + `--transcript-column`. + ### Upgrading to 0.1.18 Motion, surfaces and variants from the web design audit. **One breaking change:** `Panel`'s `delay` prop is now `index` (stagger position). diff --git a/fixtures/consumer/check.mjs b/fixtures/consumer/check.mjs index 8cc4893..38300c4 100644 --- a/fixtures/consumer/check.mjs +++ b/fixtures/consumer/check.mjs @@ -22,26 +22,38 @@ assert.match(html, /data-slot="button"/, "Button renders on the server"); // The session entry, with its optional markdown peers installed: the blocks // render on the server, and the root entry above never needed those peers. const session = await import("@tryatlas/design/session"); +const Markdown = ({ source, className }) => + createElement("div", { className: className ?? "prose-session" }, source); assert.match( renderToString( - createElement(session.SessionTimeline, { - session: { - meta: { title: "Sort pinned sessions" }, - phase: "done", - turns: [ - { - key: "t1", - user: { id: "u1", text: "Sort them" }, - items: [{ kind: "text", id: "a1", text: "## Done\n\n```ts\nconst x = 1\n```" }], - }, - ], - }, - }), + createElement( + session.TranscriptProvider, + { value: { Markdown, onToggleExpand() {}, onToggleGroup() {} } }, + createElement(session.TranscriptRowItem, { + row: { + kind: session.RowKind.Prose, + id: "p:a1", + turnId: "t1", + firstInTurn: true, + text: "Done", + streaming: false, + showHeader: true, + model: "claude-sonnet", + timestamp: "2026-11-13T10:00:00Z", + }, + priority: 0, + agentLabel: "Claude Code", + }), + ), ), - /data-slot="turn-row".*

Done<\/h2>.*language-ts/s, - "SessionTimeline renders markdown on the server", + /data-row-id="p:a1".*claude-sonnet.*Done/s, + "a transcript row renders on the server", +); +assert.equal( + session.summarizeMarkers([]).summary, + "Used tools", + "the transcript's label helpers ship", ); -assert.equal(session.toolKindOf("Bash"), "execute"); const require = createRequire(import.meta.url); diff --git a/src/components/session/session-timeline.test.tsx b/src/components/session/session-timeline.test.tsx deleted file mode 100644 index 357e3ab..0000000 --- a/src/components/session/session-timeline.test.tsx +++ /dev/null @@ -1,377 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { afterEach, describe, expect, it, vi } from "vitest"; - -import { - attachmentsTurn, - cancelledSession, - editRunTurn, - erroredSession, - hugeTurnsSession, - longAnswerTurn, - longSession, - manyToolCallsSession, - planSession, - truncatedBodiesTurn, - webShapedSession, -} from "../../../stories/components/session/fixtures.ts"; -import { SessionPipeline } from "./session-pipeline.tsx"; -import { SessionTimeline } from "./session-timeline.tsx"; -import type { SessionPhase } from "./session-view.ts"; -import { TurnRow } from "./turn-row.tsx"; - -afterEach(cleanup); - -describe("SessionTimeline", () => { - it.each<[SessionPhase, string]>([ - ["queued", "Session queued"], - ["running", "Session running"], - ["waiting", "Waiting for you"], - ["done", "Session complete"], - ["failed", "Session failed"], - ["cancelled", "Session cancelled"], - ])("heads a %s session with %s", (phase, heading) => { - render(); - expect(screen.getByText(heading)).toBeTruthy(); - }); - - it("renders a session error as an alert", () => { - render( - , - ); - expect(screen.getByRole("alert").textContent).toContain("Agent disconnected"); - }); - - it("leaves the head out with heading={false}, but keeps a session error", () => { - render( - , - ); - expect(screen.queryByText("Session complete")).toBeNull(); - expect(screen.queryByText("Sort pinned sessions")).toBeNull(); - expect(screen.getByRole("alert").textContent).toContain("Agent disconnected"); - }); - - it("puts agentMark on the node of a turn the agent started, and only there", () => { - const session = longSession(2); - session.turns[1] = { ...session.turns[1]!, user: undefined }; - render(} />); - expect(screen.getAllByTestId("mark")).toHaveLength(1); - }); - - it("puts authorFace on the node of each turn a person started", () => { - const session = longSession(3); - session.turns[1] = { ...session.turns[1]!, user: undefined }; - render(} />); - expect(screen.getAllByTestId("face")).toHaveLength(2); - }); - - it("keeps the glyphs when a slot is false or null", () => { - const session = longSession(2); - session.turns[1] = { ...session.turns[1]!, user: undefined }; - const { container } = render( - , - ); - expect(container.querySelectorAll("svg.lucide-user")).toHaveLength(1); - expect(container.querySelectorAll("svg.lucide-sparkles")).toHaveLength(1); - }); - - it("renders a turn per TurnView, keyed", () => { - const { container } = render(); - const rows = container.querySelectorAll('[data-slot="turn-row"]'); - expect([...rows].map((r) => r.getAttribute("data-turn-key"))).toEqual([ - "t0", - "t1", - "t2", - "t3", - "t4", - ]); - }); -}); - -describe("SessionTimeline forwarding", () => { - it("passes TurnRow's opt-in props through to each row", () => { - const onLoadBody = vi.fn(); - const footers: string[] = []; - const session = { ...longSession(1), turns: [truncatedBodiesTurn()] }; - render( - { - footers.push(item.kind === "tool" ? item.call.id : item.id); - return null; - }} - />, - ); - fireEvent.click(screen.getAllByRole("button", { name: /^Read the rest/ })[1]!); - expect(onLoadBody).toHaveBeenCalledWith("tb:answer"); - expect(footers).toEqual(expect.arrayContaining(["tb:prompt", "tb:answer"])); - }); - - it("draws renderCheckpointFooter under each checkpoint", () => { - render( -

{`footer:${c.id}`}

} - />, - ); - expect(screen.getByText("footer:e6")).toBeTruthy(); - expect(screen.getByText("footer:e7")).toBeTruthy(); - }); - - it("opens a folded run held in openToolRunIds", () => { - const { container } = render( - , - ); - expect(container.querySelectorAll('[data-slot="tool-call-card"]')).toHaveLength(12); - }); -}); - -describe("SessionTimeline revealItemId", () => { - const deep = () => { - const base = hugeTurnsSession(400); - base.turns[300] = { - ...base.turns[300]!, - checkpoints: [{ id: "deep:cp", commitSha: "7c1e9a04b2d5", subject: "Deep commit" }], - }; - return base; - }; - const rows = (container: HTMLElement) => - container.querySelectorAll('[data-slot="turn-row"]').length; - - it("draws only the window without it", () => { - const { container } = render(); - expect(rows(container)).toBeLessThan(300); - expect(screen.queryByText("Deep commit")).toBeNull(); - }); - - it.each([ - ["a checkpoint", "deep:cp"], - ["a prompt", "h350:user"], - ["an answer", "h399:answer"], - ])("draws the turn holding %s past the window", (_, id) => { - const { container } = render(); - expect( - container.querySelector(`[data-comment-anchor="${id}"], [data-slot="checkpoint"]`), - ).not.toBeNull(); - expect(rows(container)).toBeGreaterThan(300); - }); - - it("unfolds an uncontrolled run holding the revealed call", () => { - const { container, rerender } = render(); - expect(container.querySelector('[data-tool-call-id="many:9"]')).toBeNull(); - rerender(); - expect(container.querySelector('[data-tool-call-id="many:9"]')).not.toBeNull(); - }); - - it("draws a revealed call past its run's window", () => { - const session = manyToolCallsSession(150); - const open = new Set(["many:0"]); - const { container, rerender } = render( - , - ); - expect(container.querySelector('[data-tool-call-id="many:140"]')).toBeNull(); - rerender(); - expect(container.querySelector('[data-tool-call-id="many:140"]')).not.toBeNull(); - }); -}); - -describe("TurnRow", () => { - it("says Truncated without onLoadBody, as before", () => { - render(); - expect(screen.getAllByText("Truncated")).toHaveLength(2); - expect(screen.queryByRole("button", { name: /Read the rest/ })).toBeNull(); - }); - - it("offers Read the rest on a truncated prompt and answer, with the size", () => { - const onLoadBody = vi.fn(); - render(); - const [prompt, answer] = screen.getAllByRole("button", { name: /^Read the rest/ }); - expect(prompt!.textContent).toBe("Read the rest · 47.2 KB"); - fireEvent.click(prompt!); - fireEvent.click(answer!); - expect(onLoadBody.mock.calls).toEqual([["tb:prompt"], ["tb:answer"]]); - expect(screen.queryByText("Truncated")).toBeNull(); - }); - - it("disables Read the rest while loading and offers a retry after a failure", () => { - const onLoadBody = vi.fn(); - render( - , - ); - const loading = screen.getByRole("button", { name: /^Read the rest/ }); - expect(loading.getAttribute("aria-disabled")).toBe("true"); - expect(loading.getAttribute("aria-busy")).toBe("true"); - fireEvent.click(loading); - expect(onLoadBody).not.toHaveBeenCalled(); - fireEvent.click(screen.getByRole("button", { name: "Couldn't load the rest, retry" })); - expect(onLoadBody).toHaveBeenCalledWith("tb:answer"); - }); - - it("drops Read the rest once the body is whole", () => { - const whole = truncatedBodiesTurn(); - whole.user = { ...whole.user!, truncated: false }; - whole.items = whole.items.map((i) => (i.kind === "text" ? { ...i, truncated: false } : i)); - render( {}} />); - expect(screen.queryByRole("button", { name: /Read the rest/ })).toBeNull(); - }); - - it("leaves a run folded and closed to the host's set, and reports toggles", () => { - const changes: string[][] = []; - const turn = manyToolCallsSession(12).turns[0]!; - const onChange = (next: ReadonlySet) => changes.push([...next]); - const { container, rerender } = render( - , - ); - const head = () => container.querySelector("button[aria-expanded]")!; - expect(head().getAttribute("aria-expanded")).toBe("false"); - fireEvent.click(head()); - // Controlled: nothing opens until the host passes the new set. - expect(container.querySelectorAll('[data-slot="tool-call-card"]')).toHaveLength(0); - expect(changes).toEqual([["many:0"]]); - - rerender( - , - ); - expect(head().getAttribute("aria-expanded")).toBe("true"); - expect(container.querySelectorAll('[data-slot="tool-call-card"]')).toHaveLength(12); - fireEvent.click(head()); - expect(changes[1]).toEqual(["other"]); - }); - - it("clamps a long answer only with clampResponses, and never a streaming one", () => { - const spy = vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(900); - try { - const turn = longAnswerTurn(); - const { container, rerender } = render(); - expect(container.querySelector('[data-slot="response-clamp"]')).toBeNull(); - rerender(); - const clampButtons = () => - container.querySelectorAll('[data-slot="response-clamp"] button[aria-expanded]'); - // The prompt has its own "Show more"; these are the answers'. - expect(clampButtons()).toHaveLength(2); - rerender( - , - ); - expect(clampButtons()).toHaveLength(1); - } finally { - spy.mockRestore(); - } - }); - - it("sums a folded run's files and lines with toolRunSummary files", () => { - const { container, rerender } = render(); - const line = () => container.querySelector("button[aria-expanded]")!.textContent; - expect(line()).toContain("4 edited · 3 read · 1 ran · 1 searched"); - rerender(); - // The failed edit adds neither its file nor its lines. - expect(line()).toContain("2 modified · 3 read"); - expect(line()).toContain("+27−9"); - }); - - it("asks an expired sign-in to sign in again, with the app's action", () => { - const turn = erroredSession().turns.at(-1)!; - render(Sign in} />); - expect(screen.getByRole("alert").textContent).toContain("Sign in again to continue"); - expect(screen.getByRole("button", { name: "Sign in" })).toBeTruthy(); - }); - - it("marks a cancelled turn", () => { - render(); - expect(screen.getByText("Cancelled")).toBeTruthy(); - }); - - it("folds a run of more than three calls behind one line", () => { - const { container } = render(); - expect(container.querySelectorAll('[data-slot="tool-call-card"]')).toHaveLength(0); - fireEvent.click(container.querySelector('button[aria-expanded="false"]')!); - expect(container.querySelectorAll('[data-slot="tool-call-card"]')).toHaveLength(12); - }); - - it("anchors comments to the prompt, the answers, the thinking, the calls and the checkpoints", () => { - const anchors: string[] = []; - render( - { - anchors.push(`${anchor.kind}:${anchor.id}`); - return null; - }} - />, - ); - expect(new Set(anchors)).toEqual( - new Set([ - "message:e1", - // A thought is a message too, and takes comments beside its disclosure. - "message:e2", - "message:e5", - "tool_call:e3", - "tool_call:e4", - "checkpoint:e6", - "checkpoint:e7", - ]), - ); - }); - - it("hides an orphaned checkpoint's branch and caps its files at 12", () => { - const { container } = render(); - const [linked, orphaned] = container.querySelectorAll('[data-slot="checkpoint"]'); - expect(linked!.textContent).toContain("+3 more"); - expect(linked!.textContent).toContain("uzayermasud/pinned-first"); - expect(orphaned!.textContent).toContain("Orphaned"); - expect(orphaned!.textContent).not.toContain("uzayermasud/pinned-first"); - }); - - it("shows image attachments and file chips", () => { - const { container } = render(); - expect(container.querySelectorAll("img")).toHaveLength(2); - expect(screen.getByText("sidebar-spec.pdf")).toBeTruthy(); - }); -}); - -describe("SessionPipeline", () => { - it("uses the plan's steps when there is a plan", () => { - const { container } = render(); - expect(container.querySelectorAll("[data-state]")).toHaveLength(6); - expect( - screen - .getByText("Write StreamingMarkdown") - .closest("[data-state]")! - .getAttribute("data-state"), - ).toBe("running"); - }); - - it("uses the tool calls when there is no plan", () => { - const { container } = render(); - expect(container.querySelectorAll("[data-state]")).toHaveLength(12); - expect(container.querySelector('[data-state="failed"]')).not.toBeNull(); - }); - - it("says when there are no steps", () => { - render(); - expect(screen.getByText("No steps yet")).toBeTruthy(); - }); -}); diff --git a/src/components/session/session-timeline.tsx b/src/components/session/session-timeline.tsx deleted file mode 100644 index 0cc35f0..0000000 --- a/src/components/session/session-timeline.tsx +++ /dev/null @@ -1,295 +0,0 @@ -"use client"; - -import { SparklesIcon, UserIcon } from "lucide-react"; -import { useMemo, useState } from "react"; -import type { ReactNode } from "react"; - -import { cn } from "../../lib/utils.ts"; -import { Icon } from "../../ui/icon.tsx"; -import { Rail } from "../patterns/rail.tsx"; -import { Callout } from "../ui/callout.tsx"; -import { StatusIcon } from "../ui/status-icon.tsx"; -import { statusIconOf, useWindow } from "./session-view-helpers.ts"; -import type { SessionPhase, SessionView, TurnView } from "./session-view.ts"; -import { TurnRow } from "./turn-row.tsx"; -import type { TurnRowProps } from "./turn-row.tsx"; - -/** - * A whole session, read top to bottom: a head that says where it stands, then - * every turn on a thin rail in the gutter. Desktop's session timeline: the - * rail is a hairline with a node per turn, so the shape of the session scans - * without reading a word and the prose keeps the column. - * - * Long sessions are windowed, not virtualised (`useWindow`): real DOM rows, - * grown as the reader nears the edge, so a fast flick never shows blank space. - * `grow="up"` is for a live session read newest-first, which opens at the - * bottom and grows upward without moving what the reader is looking at. - * - * Only the first rows on screen fade in, once, as a CSS animation (it plays - * while the app is busy loading the session, where a JS-driven one would drop - * frames) and not at all under reduced motion. A row the window adds while - * the reader scrolls is already where they are looking and appears as it is. - * - * Every other prop goes to each `TurnRow`. A turn holding a call in - * `openToolCallIds` or `openToolRunIds`, or the item `revealItemId` names, is - * drawn even past the window, so the host can scroll to it (a comment link - * into turn 300). - */ - -export interface SessionTimelineProps extends Pick< - TurnRowProps, - | "commentSlot" - | "renderMarkdown" - | "rehypePlugins" - | "onLoadPayload" - | "renderDiff" - | "errorAction" - | "renderItemFooter" - | "renderCheckpointFooter" - | "clampResponses" - | "toolRunSummary" - | "openToolCallIds" - | "onOpenToolCallIdsChange" - | "thinkingLabel" - | "thinkingBody" - | "onOpenAttachment" - | "onCopyPayload" - | "onLoadBody" - | "openToolRunIds" - | "onOpenToolRunIdsChange" -> { - session: SessionView; - /** - * An item to keep drawn, by id: a prompt, an answer, a thought, a plan, a - * tool call or a checkpoint. Its turn is drawn even past the window, a call - * past its run's window is drawn, and a folded run holding it unfolds - * (unless `openToolRunIds` is set, when the host decides). For a deep link: - * set it, then scroll to the item. Like a held call, the reach it adds stays - * once the id changes or clears. - */ - revealItemId?: string; - /** - * The head: the phase ("Session complete"), the title and the agent line. - * `false` for a host that draws its own title above the timeline; the rail - * then starts at the first turn, and a session error still shows, as an - * alert above it. - */ - heading?: boolean; - /** - * The agent's mark, in the rail node of a turn the agent started on its own, - * in place of the sparkle: desktop's session-detail rail, where the agent's - * glyph identifies its turns. Pass a 16px glyph (`ModelMark`, a brand mark). - */ - agentMark?: ReactNode; - /** - * The face of whoever prompted (the session's author), as the rail node of - * each turn a person started, in place of the ringed person glyph: web's - * reader drew it there. Pass a 32px avatar (`Avatar size="lg"`). Desktop's - * rail keeps the glyph; leave this unset to match it. - */ - authorFace?: ReactNode; - /** `down` (the default) for a record read from the top; `up` for a live session. */ - grow?: "down" | "up"; - className?: string; -} - -const HEADING: Record = { - queued: "Session queued", - running: "Session running", - waiting: "Waiting for you", - done: "Session complete", - failed: "Session failed", - cancelled: "Session cancelled", -}; - -/** Rows that fade in on first render. */ -const ENTRANCE_ROWS = 20; - -export function SessionTimeline({ - session, - grow = "down", - revealItemId, - heading = true, - agentMark, - authorFace, - className, - ...rowProps -}: SessionTimelineProps) { - const { turns, meta } = session; - const { - start: windowStart, - end: windowEnd, - sentinelRef, - } = useWindow({ - count: turns.length, - grow, - }); - const { openToolCallIds, openToolRunIds } = rowProps; - const held = useMemo( - () => heldTurns(turns, [openToolCallIds, openToolRunIds], revealItemId), - [turns, openToolCallIds, openToolRunIds, revealItemId], - ); - // Only the turn holding it hears the id, so a new jump re-renders the turn - // that held it and the one that does now, not every row. - const revealKey = useMemo( - () => - revealItemId === undefined ? undefined : turns.find((t) => turnHolds(t, revealItemId))?.key, - [turns, revealItemId], - ); - // Only ever widens: closing a held card must not unmount the turn under the - // reader. A list that shrank past it (another session) starts over. - const [reach, setReach] = useState(held); - const stale = reach !== null && reach.last >= turns.length; - if (held && (stale || !reach || held.first < reach.first || held.last > reach.last)) { - setReach( - stale || !reach - ? held - : { first: Math.min(reach.first, held.first), last: Math.max(reach.last, held.last) }, - ); - } else if (!held && stale) { - setReach(null); - } - const start = reach && !stale ? Math.min(windowStart, reach.first) : windowStart; - const end = reach && !stale ? Math.max(windowEnd, reach.last + 1) : windowEnd; - // Decided once: the rows on screen at mount. Never the ones a window adds. - const [entering] = useState(() => { - const first = grow === "up" ? turns.slice(-ENTRANCE_ROWS) : turns.slice(0, ENTRANCE_ROWS); - return new Set(first.map((t) => t.key)); - }); - const visible = turns.slice(start, end); - const firstKey = turns[0]?.key; - const lastKey = turns[turns.length - 1]?.key; - const details = [meta.agent, meta.model, meta.branch].filter(Boolean); - - return ( -
- {!heading && session.error && ( - - {session.error.message} - - )} - {heading && ( - }> -
- {HEADING[session.phase]} - {meta.title && ( - {meta.title} - )} - {details.length > 0 && ( - - {details.join(" · ")} - - )} - {session.error && ( - - {session.error.message} - - )} -
-
- )} - - {grow === "up" && start > 0 &&
} - {visible.map((turn, i) => ( -
- - ) : ( - - ) - } - > - - -
- ))} - {grow === "down" && end < turns.length && ( -
- )} -
- ); -} - -/** Does the turn hold the item with this id: its prompt, an agent item or a checkpoint? */ -function turnHolds(turn: TurnView, id: string): boolean { - return ( - turn.user?.id === id || - turn.items.some((item) => (item.kind === "tool" ? item.call.id : item.id) === id) || - (turn.checkpoints?.some((c) => c.id === id) ?? false) - ); -} - -/** The first and last turn holding a call in any of `sets`, or the item `reveal`, or `null`. */ -function heldTurns( - turns: SessionView["turns"], - sets: (ReadonlySet | undefined)[], - reveal: string | undefined, -): { first: number; last: number } | null { - const live = sets.filter((s): s is ReadonlySet => s !== undefined && s.size > 0); - if (live.length === 0 && reveal === undefined) return null; - let first = -1; - let last = -1; - turns.forEach((turn, i) => { - const holds = - (reveal !== undefined && turnHolds(turn, reveal)) || - turn.items.some((item) => item.kind === "tool" && live.some((s) => s.has(item.call.id))); - if (!holds) return; - if (first < 0) first = i; - last = i; - }); - return first < 0 ? null : { first, last }; -} - -/** Opaque, so the hairline behind it does not cross the glyph. */ -const NODE = - "relative flex size-8 shrink-0 items-center justify-center rounded-full border bg-card"; - -function HeadNode({ phase }: { phase: SessionPhase }) { - return ( - - - - ); -} - -/** A person's face as the node: opaque behind it, so the hairline never shows through. */ -function FaceNode({ face }: { face: ReactNode }) { - return ( - - {face} - - ); -} - -/** The person's mark, or the agent's for a turn it started on its own. */ -function TurnNode({ agent, agentMark }: { agent: boolean; agentMark?: ReactNode }) { - return ( - - {agent && drawn(agentMark) ? ( - agentMark - ) : ( - - )} - - ); -} - -/** A slot holds something to draw: not `undefined`, `null` or a boolean (`cond && `). */ -function drawn(node: ReactNode): boolean { - return node != null && typeof node !== "boolean"; -} diff --git a/src/components/session/session-view.ts b/src/components/session/session-view.ts index 1ba6d49..7bf05e3 100644 --- a/src/components/session/session-view.ts +++ b/src/components/session/session-view.ts @@ -1,11 +1,12 @@ /** - * SessionView: the one presentational shape every session block renders. + * SessionView: a session's summary shape, which `SessionPipeline` and the + * session helpers render. The transcript itself renders the row model in + * `./transcript/model.ts`, not this. * - * Desktop renders a session from the session-delta wire and web from the - * server's `TimelineEntry` pages. Neither shape reaches the blocks: each app - * writes an adapter onto this one, so "web matches desktop" holds by - * construction rather than by two transcripts happening to agree. Nothing here - * imports either side's contract types; this file is the contract. + * Desktop and web each write an adapter onto this shape from their own + * sources (the session-delta wire, the server's `TimelineEntry` pages). + * Nothing here imports either side's contract types; this file is the + * contract. * * A field only one source can supply is optional, and no id exists on only one * side: item ids are the message or entry ids both already have, which is what diff --git a/src/components/session/tool-call-card.test.tsx b/src/components/session/tool-call-card.test.tsx deleted file mode 100644 index 064abdf..0000000 --- a/src/components/session/tool-call-card.test.tsx +++ /dev/null @@ -1,250 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { afterEach, describe, expect, it, vi } from "vitest"; - -import { hugeOutputCalls, toolCall } from "../../../stories/components/session/fixtures.ts"; -import { ToolCallCard } from "./tool-call-card.tsx"; - -afterEach(cleanup); - -const header = () => screen.getAllByRole("button")[0]!; - -describe("ToolCallCard", () => { - it("shows a binary output's size, never its text", () => { - render( - , - ); - expect(screen.getByText("Binary output, 470.8 KB")).toBeTruthy(); - expect(screen.queryByText("SECRET")).toBeNull(); - }); - - it("asks the app for a truncated output", () => { - const onLoadPayload = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByRole("button", { name: "Load full output (94.1 KB)" })); - expect(onLoadPayload).toHaveBeenCalledWith("output"); - }); - - it("holds Load full while the app fetches, focusable and busy", () => { - const onLoadPayload = vi.fn(); - render( - , - ); - const button = screen.getByRole("button", { name: "Load full output (94.1 KB)" }); - expect(button.getAttribute("aria-disabled")).toBe("true"); - expect(button.getAttribute("aria-busy")).toBe("true"); - expect(button.hasAttribute("disabled")).toBe(false); - fireEvent.click(button); - expect(onLoadPayload).not.toHaveBeenCalled(); - }); - - it("offers a retry after a failed load", () => { - const onLoadPayload = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByRole("button", { name: "Couldn't load the full input, retry" })); - expect(onLoadPayload).toHaveBeenCalledWith("input"); - }); - - it("says a truncated output is truncated when it cannot load it", () => { - render( - , - ); - expect(screen.getByText("Output truncated")).toBeTruthy(); - }); - - it("marks a failed call with the error icon", () => { - const { container } = render(); - expect(container.querySelector('[data-status="failed"]')).not.toBeNull(); - expect(screen.getByLabelText("Failed")).toBeTruthy(); - }); - - it("is a keyboard-operable disclosure", () => { - render(); - expect(header().getAttribute("aria-expanded")).toBe("false"); - // A native button activates on Enter; the browser turns it into a click. - fireEvent.keyDown(header(), { key: "Enter" }); - fireEvent.click(header()); - expect(header().getAttribute("aria-expanded")).toBe("true"); - expect(document.getElementById(header().getAttribute("aria-controls")!)).not.toBeNull(); - }); - - it("shows the tail of a huge terminal run, 400 lines, then 2,000 more", () => { - const { container } = render(); - const terminal = () => - container - .querySelectorAll('[data-slot="payload-lines"]')[1]! - .querySelectorAll('[data-slot="payload-line"]'); - expect(terminal()).toHaveLength(400); - expect(terminal()[399]!.textContent).toContain("[49999]"); - expect(terminal()[0]!.textContent).not.toContain("\u001b"); - fireEvent.click(screen.getByRole("button", { name: "Show 2,000 more lines" })); - expect(terminal()).toHaveLength(2400); - }); - - it("says when nothing was recorded", () => { - render(); - expect(screen.getByText("Nothing else was recorded for this call.")).toBeTruthy(); - }); - - it("draws a terminal's non-zero exit in the error ink", () => { - render( - , - ); - expect(screen.getByText("exit 1").className).toContain("text-error"); - }); - - describe("Copy", () => { - const big = Array.from({ length: 1000 }, (_, i) => `line ${i}`).join("\n"); - const flush = () => act(async () => {}); - - it("shows Copied only when onCopy resolves true, and copies the whole payload", async () => { - const onCopy = vi.fn().mockResolvedValue(true); - render( - , - ); - fireEvent.click(screen.getByRole("button", { name: "Copy" })); - await flush(); - expect(onCopy).toHaveBeenCalledWith("output", big); - expect(screen.getByRole("button", { name: "Copied" })).toBeTruthy(); - }); - - it("stays Copy when onCopy resolves false or throws", async () => { - for (const onCopy of [ - vi.fn().mockResolvedValue(false), - vi.fn().mockRejectedValue(new Error("denied")), - vi.fn(() => { - throw new Error("denied"); - }), - ]) { - render( - , - ); - fireEvent.click(screen.getByRole("button", { name: "Copy" })); - await flush(); - expect(onCopy).toHaveBeenCalledWith("input", "in"); - expect(screen.queryByRole("button", { name: "Copied" })).toBeNull(); - cleanup(); - } - }); - - it("copies a terminal run without its escapes", async () => { - const onCopy = vi.fn().mockResolvedValue(true); - render( - , - ); - fireEvent.click(screen.getByRole("button", { name: "Copy" })); - await flush(); - expect(onCopy).toHaveBeenCalledWith("output", "red\n"); - }); - - it("offers no Copy on a binary or truncated payload, or without onCopy", () => { - render( - true} - call={toolCall({ id: "b", output: { text: null, binary: true, bytes: 10 } })} - />, - ); - expect(screen.queryByRole("button", { name: "Copy" })).toBeNull(); - cleanup(); - render(); - expect(screen.queryByRole("button", { name: "Copy" })).toBeNull(); - cleanup(); - // A truncated payload holds only its head: no partial copy. - render( - true} - call={toolCall({ id: "t", output: { text: "head", truncated: true } })} - />, - ); - expect(screen.queryByRole("button", { name: "Copy" })).toBeNull(); - }); - }); - - it("respects a controlled open and reports toggles", () => { - const onOpenChange = vi.fn(); - const { container, rerender } = render( - , - ); - expect(container.querySelector('[data-tool-call-id="o"]')).not.toBeNull(); - fireEvent.click(header()); - expect(onOpenChange).toHaveBeenCalledWith(true); - // Still closed: the parent decides. - expect(header().getAttribute("aria-expanded")).toBe("false"); - rerender( - , - ); - expect(header().getAttribute("aria-expanded")).toBe("true"); - }); - - it("draws its strings from labels", () => { - render( - `${part} coupé` }} - call={toolCall({ id: "l" })} - />, - ); - expect(screen.getByText("Rien.")).toBeTruthy(); - }); -}); diff --git a/src/components/session/tool-call-card.tsx b/src/components/session/tool-call-card.tsx deleted file mode 100644 index 8f13ef6..0000000 --- a/src/components/session/tool-call-card.tsx +++ /dev/null @@ -1,599 +0,0 @@ -"use client"; - -import { - ArrowRightLeftIcon, - BookOpenIcon, - BrainIcon, - CheckIcon, - ChevronRightIcon, - CopyIcon, - CircleXIcon, - FileCode2Icon, - GlobeIcon, - PencilIcon, - SearchIcon, - SquareTerminalIcon, - Trash2Icon, - WrenchIcon, -} from "lucide-react"; -import type { LucideIcon } from "lucide-react"; -import { useEffect, useId, useMemo, useRef, useState } from "react"; -import type { ReactNode } from "react"; - -import { cn } from "../../lib/utils.ts"; -import { Button } from "../../ui/button.tsx"; -import { IconButton } from "../../ui/icon-button.tsx"; -import { Icon } from "../../ui/icon.tsx"; -import { DiffStat } from "../ui/code-block.tsx"; -import { Spinner } from "../ui/spinner.tsx"; -import { formatBytes, formatDuration, stripAnsi } from "./session-view-helpers.ts"; -import type { CommentAnchor, DiffData, Payload, ToolCallView, ToolKind } from "./session-view.ts"; - -/** - * One tool call: a one-line header you click, and what was recorded behind it. - * - * Desktop's session call row. The line is a sentence (glyph, the call's title, - * its target) with the figures in a right-hand gutter (`+n −m`, the duration), - * so a column of calls scans as text on the left and numbers on the right. - * Opened, it shows the paths, the input and the output (or the terminal run), - * then each diff. It never fetches: a truncated payload offers - * `onLoadPayload`, and the app fills it in. - * - * Rows have no border of their own: a run of calls sits in one bordered box, - * divided by hairlines (`TurnRow` draws it), as desktop's call table does. - * - * Huge payloads stay cheap. At most 400 lines of each render, the head for - * input and diffs and the tail for terminal output (the end is where a command - * says what happened), and "Show more" adds 2,000 at a time. - */ - -/** One glyph per kind, desktop's tool vocabulary. Shapes only; the one tint is red on failure. */ -export const TOOL_KIND_ICON: Record = { - read: BookOpenIcon, - edit: PencilIcon, - delete: Trash2Icon, - move: ArrowRightLeftIcon, - search: SearchIcon, - execute: SquareTerminalIcon, - think: BrainIcon, - fetch: GlobeIcon, - other: WrenchIcon, -}; - -/** Kinds whose target is a file, drawn as a dotted link-like run. */ -const FILE_KINDS: ReadonlySet = new Set(["read", "edit", "delete", "move"]); - -const LINES_INITIAL = 400; -const LINES_STEP = 2000; - -/** How long Copy shows that it copied. */ -const COPIED_MS = 1200; - -/** Every string the card draws beyond the call's own data. */ -export interface ToolCallCardLabels { - copy: string; - copied: string; - /** The button that shows the next `n` lines. */ - showMore: (n: number) => string; - /** A truncated payload's load button; `size` is formatted ("94.1 KB") when known. */ - loadFull: (part: "input" | "output", size?: string) => string; - /** The load button after the app's fetch failed (`Payload.load` `failed`); clicking retries. */ - loadFailed?: (part: "input" | "output") => string; - /** A truncated payload with nothing to load it. */ - truncated: (part: "input" | "output") => string; - /** A binary payload; `size` is formatted when known. */ - binary: (part: "input" | "output", size?: string) => string; - /** An opened call that recorded nothing. */ - empty: string; -} - -export const DEFAULT_TOOL_CALL_CARD_LABELS: ToolCallCardLabels = { - copy: "Copy", - copied: "Copied", - showMore: (n) => `Show ${n.toLocaleString("en-US")} more lines`, - loadFull: (part, size) => `Load full ${part}${size ? ` (${size})` : ""}`, - loadFailed: (part) => `Couldn't load the full ${part}, retry`, - truncated: (part) => `${part === "input" ? "Input" : "Output"} truncated`, - binary: (part, size) => `Binary ${part}${size ? `, ${size}` : ""}`, - empty: "Nothing else was recorded for this call.", -}; - -/** `loadFailed` is optional in `ToolCallCardLabels`, so a full labels object from before it still type-checks. */ -const DEFAULT_LOAD_FAILED = DEFAULT_TOOL_CALL_CARD_LABELS.loadFailed!; - -/** What a payload's Copy asks the app to put on the clipboard. */ -type CopyPayload = (part: "input" | "output", text: string) => Promise | boolean; - -export interface ToolCallCardProps { - call: ToolCallView; - /** Open on first render. Uncontrolled after that. */ - defaultOpen?: boolean; - /** Controlled open state; leave undefined for an uncontrolled card. */ - open?: boolean; - /** Called with the next open state when the header is clicked. */ - onOpenChange?: (open: boolean) => void; - /** Adds Copy to each whole text payload; resolve `true` once the text is on the clipboard. */ - onCopy?: CopyPayload; - /** Overrides for the card's strings. */ - labels?: Partial; - /** A truncated payload's "Load full …" asks the app for the rest. */ - onLoadPayload?: (part: "input" | "output") => void; - /** Draws each of `call.diffs`. Defaults to `DefaultDiff`. */ - renderDiff?: (diff: DiffData) => ReactNode; - /** Beside the header, outside the disclosure: the app's comment control. */ - commentSlot?: (anchor: CommentAnchor) => ReactNode; - className?: string; -} - -export function ToolCallCard({ - call, - defaultOpen = false, - open: openProp, - onOpenChange, - onCopy, - labels: labelOverrides, - onLoadPayload, - renderDiff, - commentSlot, - className, -}: ToolCallCardProps) { - const [openState, setOpenState] = useState(defaultOpen); - const open = openProp ?? openState; - const toggle = () => { - if (openProp === undefined) setOpenState(!open); - onOpenChange?.(!open); - }; - const labels = labelOverrides - ? { ...DEFAULT_TOOL_CALL_CARD_LABELS, ...labelOverrides } - : DEFAULT_TOOL_CALL_CARD_LABELS; - const bodyId = useId(); - const failed = call.status === "failed"; - const running = call.status === "running"; - const pending = call.status === "pending"; - const target = call.title ? undefined : call.paths?.[0]; - const added = call.diffs?.reduce((n, d) => n + (d.insertions ?? 0), 0) ?? 0; - const removed = call.diffs?.reduce((n, d) => n + (d.deletions ?? 0), 0) ?? 0; - const empty = !call.input && !call.output && !call.terminal && !call.diffs?.length; - - return ( -
-
- - {commentSlot?.({ kind: "tool_call", id: call.id })} -
- - {open && ( -
- {call.paths && call.paths.length > 0 && ( -
    - {call.paths.map((path) => ( -
  • - {path} -
  • - ))} -
- )} - {call.input && ( - onLoadPayload("input"))} - /> - )} - {call.terminal ? ( - - ) : ( - call.output && ( - onLoadPayload("output"))} - /> - ) - )} - {call.diffs?.map((diff, i) => ( -
- {renderDiff ? renderDiff(diff) : } -
- ))} - {empty &&

{labels.empty}

} -
- )} -
- ); -} - -/** The bordered mono box every payload sits in, with its header. */ -function Frame({ - label, - icon = FileCode2Icon, - aside, - terminal, - children, -}: { - label: ReactNode; - icon?: LucideIcon; - aside?: ReactNode; - terminal?: boolean; - children: ReactNode; -}) { - return ( -
-
- - - {label} - - {aside} -
- {children} -
- ); -} - -type LineTone = "added" | "removed" | "hunk" | undefined; - -/** - * At most `LINES_INITIAL` lines, the head or the tail, and a button for the - * next 2,000. The text is split once per payload. - */ -function Lines({ - lines, - from, - tone, - dim, - showMore = DEFAULT_TOOL_CALL_CARD_LABELS.showMore, -}: { - lines: string[]; - from: "head" | "tail"; - showMore?: (n: number) => string; - tone?: (line: string) => LineTone; - /** Lines in the surface's own ink rather than the secondary one. */ - dim?: boolean; -}) { - const [shown, setShown] = useState(LINES_INITIAL); - const hidden = Math.max(0, lines.length - shown); - const visible = - hidden === 0 - ? lines - : from === "head" - ? lines.slice(0, shown) - : lines.slice(lines.length - shown); - const more = hidden > 0 && ( - - ); - return ( -
- {from === "tail" && more} - {/* Focusable, so a keyboard can scroll what a pointer can. */} -
- {visible.map((line, i) => { - const t = tone?.(line); - return ( -
- {/* The 2px edge: a tinted row alone is not reliable on every - display, and which way a change went must not be missed. */} - {(t === "added" || t === "removed") && ( - - )} - {line || " "} -
- ); - })} -
- {from === "head" && more} -
- ); -} - -function splitLines(text: string): string[] { - const lines = text.split("\n"); - // A trailing newline is the end of the last line, not an empty one. - if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop(); - return lines; -} - -/** - * Copy for one payload: the whole text, not the window on screen. The check - * shows only once the app says the text is on the clipboard; a refusal, a - * throw or a rejection leaves the button as it was. - */ -function CopyPayloadButton({ - part, - text, - onCopy, - labels, -}: { - part: "input" | "output"; - text: string; - onCopy: CopyPayload; - labels: ToolCallCardLabels; -}) { - const [copied, setCopied] = useState(false); - const timer = useRef>(undefined); - useEffect(() => () => clearTimeout(timer.current), []); - const copy = async () => { - let ok = false; - try { - ok = (await onCopy(part, text)) === true; - } catch { - ok = false; - } - if (!ok) return; - clearTimeout(timer.current); - setCopied(true); - timer.current = setTimeout(() => setCopied(false), COPIED_MS); - }; - return ( - void copy()} - className="shrink-0" - /> - ); -} - -function PayloadBlock({ - part, - payload, - from, - labels, - onCopy, - onLoad, -}: { - part: "input" | "output"; - payload: Payload; - from: "head" | "tail"; - labels: ToolCallCardLabels; - onCopy?: CopyPayload; - onLoad?: () => void; -}) { - // Output that came from a command carries its escapes even outside a terminal block. - const text = useMemo(() => (payload.text ? stripAnsi(payload.text) : null), [payload.text]); - const lines = useMemo(() => (text ? splitLines(text) : []), [text]); - const size = payload.bytes !== undefined ? formatBytes(payload.bytes) : undefined; - const loading = payload.load === "loading"; - if (payload.binary) { - return

{labels.binary(part, size)}

; - } - return ( - - ) - } - > - {lines.length > 0 && } - {payload.truncated && - (onLoad ? ( - - ) : ( -

- {labels.truncated(part)} -

- ))} - - ); -} - -function TerminalBlock({ - terminal, - labels, - onCopy, -}: { - terminal: NonNullable; - labels: ToolCallCardLabels; - onCopy?: CopyPayload; -}) { - const text = useMemo(() => stripAnsi(terminal.output), [terminal.output]); - const lines = useMemo(() => splitLines(text), [text]); - const failed = terminal.exitCode !== undefined && terminal.exitCode !== 0; - return ( - - {failed && ( - - exit {terminal.exitCode} - - )} - {onCopy && ( - - )} - - ) - } - > - - - ); -} - -function diffLines(diff: DiffData): { lines: string[]; tone: (line: string) => LineTone } { - if (diff.patch !== undefined) { - return { - lines: splitLines(diff.patch), - tone: (line) => - line.startsWith("@@") - ? "hunk" - : line.startsWith("+++") || line.startsWith("---") - ? "hunk" - : line.startsWith("+") - ? "added" - : line.startsWith("-") - ? "removed" - : undefined, - }; - } - // No patch: the texts as they are, removed above added. Not a diff - // algorithm; a real diff view plugs into `renderDiff`. - const removed = diff.oldText ? splitLines(diff.oldText).map((l) => `-${l}`) : []; - const added = diff.newText ? splitLines(diff.newText).map((l) => `+${l}`) : []; - return { - lines: [...removed, ...added], - tone: (line) => (line.startsWith("+") ? "added" : "removed"), - }; -} - -export interface DefaultDiffProps { - diff: DiffData; - /** The "Show more" label; `ToolCallCard` passes its own. */ - labels?: Partial>; -} - -/** - * A diff as the patch's lines, tinted by sign, or the old text above the new - * when there is no patch. The fallback for `ToolCallCard`'s `renderDiff`. - */ -export function DefaultDiff({ diff, labels }: DefaultDiffProps) { - const { lines, tone } = useMemo(() => diffLines(diff), [diff]); - const known = diff.insertions !== undefined || diff.deletions !== undefined; - return ( -
- - ) - } - > - {lines.length > 0 ? ( - - ) : ( -

No changes recorded.

- )} - -
- ); -} diff --git a/src/components/session/transcript/context.tsx b/src/components/session/transcript/context.tsx new file mode 100644 index 0000000..ff0ab2b --- /dev/null +++ b/src/components/session/transcript/context.tsx @@ -0,0 +1,149 @@ +"use client"; + +import { createContext, useContext, type ComponentType, type ReactNode } from "react"; + +import type { MarkerRow, SubagentRow, TranscriptImage, TurnFooterRow, UserRow } from "./model.ts"; + +/** + * What a transcript's rows need from the app around them, handed in once. + * + * The rows are props-only: they never read an app's store or call its + * backend. Everything an app owns (how markdown is parsed, the actions under a + * message, comment pills, the changed-files card, what clicking a tool line + * opens) arrives here, as components and callbacks, through one context + * rather than as props threaded through every row. That keeps each row's + * `memo` comparing only its own data. + * + * **Keep the value stable.** Every component and callback should be defined at + * module level or memoised for the transcript's lifetime: a new value + * re-renders every row, and the two `use…Discussed` hooks are called as hooks, + * so one must not appear or disappear between renders. + */ + +/** Props for the app's markdown renderer. */ +export interface TranscriptMarkdownProps { + source: string; + /** Position in the thread: a renderer that parses lazily does the newest + * first. */ + priority: number; + /** The live streaming tail: only this one changes per frame. */ + streaming?: boolean; + /** Set on the markdown root: `prose-session-user` for a prompt bubble. A + * response passes none, and the renderer's root is `.prose-session`. */ + className?: string; + /** The outside paths a prompt attached (`UserRow.trustedPaths`). */ + trustedPaths?: readonly string[]; +} + +/** The hover actions under a prompt. */ +export interface TranscriptUserActionsProps { + row: UserRow; + /** The message id behind the row (`userRowMessageId(row.id)`). */ + messageId: string; + canRetry: boolean; + /** A "Show more" toggle sits above the actions. */ + toggleAbove: boolean; +} + +/** The hover actions under a settled response. */ +export interface TranscriptResponseActionsProps { + messageId: string; + text: string; + timestamp: string; + canBranch: boolean; + showTimestamp: boolean; + /** Placement override, from the turn footer row. */ + className?: string; +} + +export interface TranscriptImagesProps { + images: readonly TranscriptImage[]; + className?: string; +} + +export interface TranscriptRemoteAuthorProps { + id: string | null; + fallback: string; +} + +/** A comment pill beside one discussed row. */ +export interface TranscriptCommentPillProps { + anchorId: string; +} + +/** The aggregate pill beside a folded block whose calls are discussed. */ +export interface TranscriptGroupCommentPillProps { + anchorIds: readonly string[]; + onOpen: () => void; +} + +export interface TranscriptChangedFilesProps { + row: TurnFooterRow; +} + +export interface TranscriptContextValue { + /** Renders every prompt and response body. */ + Markdown: ComponentType; + UserActions?: ComponentType; + ResponseActions?: ComponentType; + /** Image tiles above a prompt. Absent, a prompt's images are not drawn. */ + Images?: ComponentType; + /** Who sent a prompt from elsewhere (`UserRow.remoteAuthor`). */ + RemoteAuthor?: ComponentType; + CommentPill?: ComponentType; + GroupCommentPill?: ComponentType; + /** The card at the end of a turn that edited files. */ + ChangedFiles?: ComponentType; + /** Whether a row's anchor has a visible comment thread. Called as a hook. */ + useRowDiscussed?: (anchorId: string) => boolean; + /** Whether any of a block's calls is discussed. Called as a hook. */ + useGroupDiscussed?: (anchorIds: readonly string[]) => boolean; + /** A response header's clock. Defaults to the locale's hour and minute. */ + formatTime?: (timestamp: string) => string; + + /** Open or close a prompt bubble's clamp, or a thinking row. */ + onToggleExpand: (rowId: string) => void; + /** Open or close a folded block, or a turn's work header. */ + onToggleGroup: (rowId: string) => void; + /** A tool line with something to open (`MarkerRow.opens`). */ + onOpenMarker?: (row: MarkerRow) => void; + /** A delegated child. */ + onOpenSubagent?: (row: SubagentRow) => void; + /** An interrupted latest turn's Retry. */ + onRetry?: () => void; + /** An interrupted latest turn's Continue. */ + onContinue?: () => void; +} + +const TranscriptContext = createContext(null); + +export function TranscriptProvider({ + value, + children, +}: { + value: TranscriptContextValue; + children: ReactNode; +}) { + return {children}; +} + +/** The transcript's context. Throws outside a `TranscriptProvider`. */ +export function useTranscript(): TranscriptContextValue { + const value = useContext(TranscriptContext); + if (!value) throw new Error("A transcript row rendered outside ."); + return value; +} + +const notDiscussed = (): boolean => false; + +/** `useRowDiscussed`, or never discussed when the app has no comments. */ +export function useRowDiscussed(anchorId: string): boolean { + const use = useTranscript().useRowDiscussed ?? notDiscussed; + return use(anchorId); +} + +/** `useGroupDiscussed`, or never discussed when the app has no comments. */ +export function useGroupDiscussed(anchorIds: readonly string[]): boolean { + const use = useTranscript().useGroupDiscussed ?? notDiscussed; + return use(anchorIds); +} diff --git a/src/components/session/transcript/injected-row.tsx b/src/components/session/transcript/injected-row.tsx new file mode 100644 index 0000000..9442d6d --- /dev/null +++ b/src/components/session/transcript/injected-row.tsx @@ -0,0 +1,60 @@ +"use client"; + +import { memo, useState } from "react"; +import { ChevronRight, GitPullRequest, RotateCcw } from "lucide-react"; + +import { cn } from "../../../lib/utils.ts"; +import type { InjectedRow } from "./model.ts"; +import { TRANSCRIPT_COLUMN } from "./parts.tsx"; +import { ICON_PX, ICON_STROKE } from "./tool-glyph.tsx"; + +/** + * A prompt Atlas sent the agent on its own — a watched pull request changed, + * and Atlas woke the agent about it, or Atlas came back from a quit, crash or + * update and continued the turn it cut short. + * + * It opens a turn the way a user message does, but it is not the user's words, + * so it is not their bubble: one quiet line in the interruption row's + * register, saying who spoke and why. The full text the agent received folds + * behind Details, for when the user wants to see exactly what it was told. + * + * No entrance animation, for the reason `InterruptionRowView` gives: rows + * remount as they scroll back into view. + */ +export const InjectedRowView = memo(function InjectedRowView({ row }: { row: InjectedRow }) { + const [open, setOpen] = useState(false); + const restart = row.injected.source === "restart"; + const headline = restart ? row.injected.summary : `Pull request watch · ${row.injected.summary}`; + const Icon = restart ? RotateCcw : GitPullRequest; + + return ( +
+
+ + + + + {headline} + + +
+ {open && ( +

+ {row.text} +

+ )} +
+ ); +}); diff --git a/src/components/session/transcript/interruption-row.tsx b/src/components/session/transcript/interruption-row.tsx new file mode 100644 index 0000000..8c229ae --- /dev/null +++ b/src/components/session/transcript/interruption-row.tsx @@ -0,0 +1,124 @@ +"use client"; + +import { memo, useState } from "react"; +import { ChevronRight, CornerDownRight, MoonStar, RotateCcw } from "lucide-react"; + +import { cn } from "../../../lib/utils.ts"; +import { Button } from "../../../ui/button.tsx"; +import { useTranscript } from "./context.tsx"; +import type { InterruptionRow, TranscriptInterruption } from "./model.ts"; +import { TRANSCRIPT_COLUMN } from "./parts.tsx"; +import { ICON_PX, ICON_STROKE } from "./tool-glyph.tsx"; + +/** "45s", "21m", "1h", "1h 3m": a sleep is told in the unit a person would + * use; "21m 14s" reads as a stopwatch. */ +export function formatSlept(secs: number): string { + const s = Math.max(0, Math.round(secs)); + if (s < 60) return `${s}s`; + const m = Math.round(s / 60); + if (m < 60) return `${m}m`; + const h = Math.floor(m / 60); + return m % 60 === 0 ? `${h}h` : `${h}h ${m % 60}m`; +} + +/** The interruption row's one line: what happened, and what it means for the + * reply, in that order. The agent's own error is a detail, never the + * headline. */ +export function interruptionHeadline(x: TranscriptInterruption): string { + const slept = `Your computer slept for ${formatSlept(x.sleptSecs)}`; + switch (x.outcome) { + case "finished": + return `${slept} during this reply — it may be incomplete.`; + case "stopped": + return `${slept} during this reply before it was stopped.`; + case "failed": + return `${slept} and the reply was cut off.`; + case "disconnected": + return `${slept} and the agent exited before finishing.`; + } +} + +/** + * A turn something outside the conversation cut into — today, the computer + * sleeping mid-reply (`TurnInterruption`). + * + * One quiet line in the footer's register, under the turn: the reply stays the + * loudest thing on screen, and this says only what happened to it. The moon is + * the one coloured mark, in the warning token — it is a caution about the + * reply, not an error the user caused. The agent's own error, when there is + * one, is folded behind Details: it is for diagnosis, not the headline. + * + * No entrance animation. Rows remount as they scroll in and out, so a fade + * here would replay every time the turn came back into view. + * + * Retry and Continue appear on the latest turn only, since both act on the + * thread's last reply, and only where the app wires them (`onRetry`, + * `onContinue`). + */ +export const InterruptionRowView = memo(function InterruptionRowView({ + row, + canRetry, + canContinue, +}: { + row: InterruptionRow; + canRetry: boolean; + canContinue: boolean; +}) { + const { onRetry, onContinue } = useTranscript(); + const [open, setOpen] = useState(false); + const { interruption } = row; + const headline = interruptionHeadline(interruption); + const showRetry = row.latest && canRetry && onRetry !== undefined; + const showContinue = row.latest && canContinue && onContinue !== undefined; + + return ( +
+
+ + + + {/* Not `flex-1`: the actions follow the sentence they answer rather + than sitting a column's width away from it. */} + + {headline} + + {interruption.error && ( + + )} + {(showRetry || showContinue) && ( + + {showContinue && ( + + )} + {showRetry && ( + + )} + + )} +
+ {open && interruption.error && ( +

+ {interruption.error} +

+ )} +
+ ); +}); diff --git a/src/components/session/transcript/jump-to-bottom-pill.tsx b/src/components/session/transcript/jump-to-bottom-pill.tsx new file mode 100644 index 0000000..045837f --- /dev/null +++ b/src/components/session/transcript/jump-to-bottom-pill.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { memo } from "react"; +import { ChevronDown } from "lucide-react"; + +import { cn } from "../../../lib/utils.ts"; + +/** + * "Scroll to bottom" / "N new messages", floated above the composer stack. + * + * Positioned against its parent's top edge (`bottom-full`), so the app puts it + * in the box the composer stack sits in. The wrapper is `pointer-events-none` + * so the empty width either side of the pill never swallows clicks meant for + * the transcript. + */ +export const JumpToBottomPill = memo(function JumpToBottomPill({ + count, + onClick, +}: { + count: number; + onClick: () => void; +}) { + return ( +
+ +
+ ); +}); diff --git a/src/components/session/transcript/labels.ts b/src/components/session/transcript/labels.ts new file mode 100644 index 0000000..c04f44d --- /dev/null +++ b/src/components/session/transcript/labels.ts @@ -0,0 +1,265 @@ +/** + * The words a transcript's tool lines are made of: a path cut to one line, the + * icon a call leads with, the counted sentence a folded block reads as and the + * live line it shows while a call runs. + * + * Shared so every projection names work the same way. Desktop's projection + * calls these as it builds its marker rows, and web's adapters call the same + * ones, so "Ran 3 commands and read 2 files" is one sentence on both. + */ + +import type { MarkerRow, MarkerTool } from "./model.ts"; +import { commandProgramName } from "./parse-shell-command.ts"; + +/** Trim a path to something that reads in one line without the eye scanning. */ +export function shortPath(p: string): string { + const parts = p.split("/").filter(Boolean); + if (parts.length <= 2) return parts.join("/"); + return parts.slice(-2).join("/"); +} + +/** ACP's semantic class, which every agent that sets `kind` at all gets right. */ +const TOOL_ICON_BY_KIND: Record = { + execute: "run", + read: "read", + edit: "edit", + delete: "delete", + move: "move", + search: "search", + fetch: "fetch", + think: "think", +}; + +/** + * How a marker names a call no verb branch recognised. Atlas's own tool + * servers read as their tool, in words: `mcp__atlas_code__find_symbol` + * (Claude Code's name for it) and `atlas_code.find_symbol` (Atlas Agent's) + * both become "Find symbol". Any other tool keeps its own name. + */ +export function toolDisplayName(toolName: string): string { + const tool = /^(?:mcp__atlas_[a-z]+__|atlas_[a-z]+\.)([a-z_]+)$/.exec(toolName)?.[1]; + if (!tool) return toolName; + const words = tool.replace(/_/g, " "); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** + * The icon key for a call the verb branches did not already classify. + * + * `kind` first — it is the protocol's own answer. The name sniff below only + * catches MCP servers, which are free to send no kind at all; it is + * deliberately narrow, because a wrong icon is worse than the generic wrench. + * Substrings that appear inside unrelated words ("rm" in "confirm", "web" in + * "webhook") are not in it for that reason. + */ +export function toolIconFor(kind: string | null | undefined, toolName: string): MarkerTool { + const byKind = TOOL_ICON_BY_KIND[kind ?? ""]; + if (byKind) return byKind; + const name = toolName.toLowerCase(); + if (name.includes("search") || name.includes("grep") || name.includes("glob")) return "search"; + if (name.includes("fetch") || name.includes("http") || name.includes("url")) return "fetch"; + if (name.includes("delete") || name.includes("remove")) return "delete"; + if (name.includes("rename") || name.includes("move")) return "move"; + return "tool"; +} + +/** + * A call to a third-party MCP server, by Claude Code's name for it + * (`mcp____`): the server in words, and the tool as a phrase. + * Atlas's own servers are not here — memory, organisation and code calls + * already read as what they did. + */ +export function mcpToolOf(toolName: string): { server: string; tool: string } | null { + const match = /^mcp__(.+?)__(.+)$/.exec(toolName); + if (!match || match[1].startsWith("atlas_")) return null; + const [, server, tool] = match; + // Every browser-driving server is one thing to the reader. The server + // decides it; a tool name only by a `browser_` prefix, so + // `vercel__get_preview_deployment` stays vercel's. + const label = + /browser|playwright|puppeteer|chrome|preview/i.test(server) || /^browser[_-]/i.test(tool) + ? "browser" + : server.replace(/[_-]+/g, " ").toLowerCase(); + const words = tool.replace(/[_-]+/g, " ").trim(); + return { server: label, tool: words.charAt(0).toUpperCase() + words.slice(1) }; +} + +// ── Folded-block summary ─────────────────────────────────────────────────── +// +// "Ran 3 commands and read 2 files": a block of tool calls as one counted +// sentence. Calls are grouped by what they did. The two most telling groups +// are named, in the order they first happened, and anything left over is +// counted as "performed N other actions". Changing the project (commands, +// edits) outranks looking at it (reads, searches, lookups), which outranks a +// generic tool, so a block that ran a build is never summarised by the file +// it read on the way. + +type SummaryAction = + | "run" + | "edit" + | "read" + | "search" + | "fetch" + | "org" + | "memory" + | "server" + | "tool"; + +/** Which group each row glyph counts toward. */ +const SUMMARY_ACTION: Record = { + run: "run", + edit: "edit", + delete: "edit", + move: "edit", + read: "read", + list: "read", + file: "read", + search: "search", + fetch: "fetch", + org: "org", + memory: "memory", + browser: "server", + tool: "tool", + think: "tool", +}; + +/** Lower is named first. */ +const SUMMARY_PRIORITY: Record = { + run: 0, + edit: 0, + read: 1, + search: 1, + fetch: 1, + org: 1, + memory: 1, + server: 1, + tool: 2, +}; + +function counted(n: number, one: string, many: string): string { + return `${n} ${n === 1 ? one : many}`; +} + +function actionLabel(action: SummaryAction, n: number, server: string | undefined): string { + switch (action) { + case "run": + return `Ran ${counted(n, "command", "commands")}`; + case "edit": + return `Changed ${counted(n, "file", "files")}`; + case "read": + return `Read ${counted(n, "file", "files")}`; + case "search": + return n === 1 ? "Searched code once" : `Searched code ${n} times`; + case "fetch": + return n === 1 ? "Fetched a page" : `Fetched ${n} pages`; + case "org": + return n === 1 ? "Checked your organization" : `Checked your organization ${n} times`; + case "memory": + return n === 1 ? "Used Atlas memory" : `Used Atlas memory ${n} times`; + case "server": + return n === 1 ? `Used ${server}` : `Used ${server} ${n} times`; + case "tool": + return n === 1 ? "Used a tool" : `Used ${n} tools`; + } +} + +/** One block → the sentence on its header, and the glyph of the group that + * leads it. */ +export function summarizeMarkers(markers: MarkerRow[]): { summary: string; tool: MarkerTool } { + // Keyed by action, and an MCP server's calls by server: two servers are two + // groups, each named for itself. + const groups = new Map(); + for (const m of markers) { + const key = m.server ? `server:${m.server}` : SUMMARY_ACTION[m.tool]; + const group = groups.get(key); + if (group) group.push(m); + else groups.set(key, [m]); + } + if (groups.size === 0) return { summary: "Used tools", tool: "tool" }; + + const all = [...groups.values()].map((calls, index) => { + const action: SummaryAction = calls[0].server ? "server" : SUMMARY_ACTION[calls[0].tool]; + return { + action, + server: calls[0].server, + glyph: calls[0].tool, + index, + calls: calls.length, + // Edits count files, not calls: three edits to one file changed one file. + n: + action === "edit" + ? new Set(calls.map((c) => c.path ?? (c.detail || c.toolCallId))).size + : calls.length, + }; + }); + const named = [...all] + .sort((a, b) => SUMMARY_PRIORITY[a.action] - SUMMARY_PRIORITY[b.action] || a.index - b.index) + .slice(0, 2) + .sort((a, b) => a.index - b.index); + const labels = named.map((g) => actionLabel(g.action, g.n, g.server)); + const rest = markers.length - named.reduce((sum, g) => sum + g.calls, 0); + if (rest > 0) labels.push(`Performed ${counted(rest, "other action", "other actions")}`); + + const parts = labels.map((l, i) => (i === 0 ? l : l.charAt(0).toLowerCase() + l.slice(1))); + const summary = + parts.length < 3 + ? parts.join(" and ") + : `${parts.slice(0, -1).join(", ")}, and ${parts[parts.length - 1]}`; + return { summary, tool: named[0].action === "server" ? named[0].glyph : named[0].action }; +} + +/** + * A live disclosure names the current action, then returns to its aggregate + * sentence when that action finishes. Keep the phrase short enough to occupy + * the same quiet, single-line slot as the collapsed summary. + * + * The rule is "name the target, fall back to the generic phrase" — the generic + * phrases exist for calls whose target Atlas could not read, NOT as the normal + * case. `run` is why: "Running command" made `bun run build:app` and `ls` + * render as the same line, and the command is the entire content of a run. + * + * Which part of the target gets named differs by tool, and it is not a style + * choice. A path's basename identifies it ("Reading turn-rows.ts") while its + * parent directories are noise at this size; a command, a pattern or a URL has + * no such tail, and slicing one on "/" would cut it mid-token. So paths take + * the last segment and everything else is used whole — CSS truncates the line. + */ +export function liveMarkerLabel(marker: MarkerRow): string { + const target = marker.detail; + const basename = target.split("/").pop() ?? target; + switch (marker.tool) { + case "read": + return target ? `Reading ${basename}` : "Reading files"; + case "edit": + return target ? `Editing ${basename}` : "Editing files"; + case "delete": + return target ? `Deleting ${basename}` : "Deleting files"; + case "move": + return target ? `Moving ${basename}` : "Moving files"; + case "list": + return target ? `Listing ${basename}` : "Listing files"; + case "file": + return target ? `Opening ${basename}` : "Opening a file"; + // `search`'s detail is already a phrase ("pattern in dir"), so it reads as + // the object of "searching for" rather than as a name. + case "search": + return target ? `Searching for ${target}` : "Searching files"; + // The program, not the whole command line: "Running sed" holds the one + // line at any width, and the command is a click away in the block. + case "run": { + const program = target ? commandProgramName(target) : null; + return program ? `Running ${program}` : target ? `Running ${target}` : "Running command"; + } + case "fetch": + return target ? `Fetching ${target}` : "Fetching content"; + case "think": + return "Thinking…"; + // An organisation call's line is already a phrase ("Looked up Grace"). + case "org": + return target ? `${marker.verb} ${target}` : marker.verb; + default: + // An MCP call's verb is already the tool, in words ("Take snapshot"). + if (marker.server) return target ? `${marker.verb} ${target}` : marker.verb; + return target ? `Running ${marker.verb} ${target}` : "Using a tool"; + } +} diff --git a/src/components/session/transcript/loading-state.test.tsx b/src/components/session/transcript/loading-state.test.tsx new file mode 100644 index 0000000..979ea05 --- /dev/null +++ b/src/components/session/transcript/loading-state.test.tsx @@ -0,0 +1,52 @@ +// @vitest-environment happy-dom +// +// The working indicator is only ever on screen BEFORE the model has produced +// anything: a streaming assistant turn exists as soon as it emits a row, and +// the indicator is gone by then. So what it says during that window is a claim +// about a request in flight, not about a model thinking (desktop issue 291). + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import { LoadingState, SHOW_ELAPSED_AFTER_MS, WAITING_LABEL } from "./loading-state.tsx"; + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); + cleanup(); +}); + +/** The elapsed clock is written straight to the DOM, bypassing React. */ +function elapsedText(container: HTMLElement): string { + return container.querySelector(".tabular-nums")?.textContent ?? ""; +} + +describe("LoadingState", () => { + it("says it is waiting, not thinking", () => { + render(); + expect(screen.getByRole("status").getAttribute("aria-label")).toBe(WAITING_LABEL); + expect(screen.getByText(WAITING_LABEL)).toBeTruthy(); + expect(screen.queryByText("Thinking")).toBeNull(); + }); + + it("still lets a caller name a different wait", () => { + render(); + expect(screen.getByText("Starting Claude Code")).toBeTruthy(); + }); + + it("shows no clock while the wait is too short to be worth counting", () => { + const { container } = render(); + expect(elapsedText(container)).toBe(""); + + vi.advanceTimersByTime(SHOW_ELAPSED_AFTER_MS - 500); + expect(elapsedText(container)).toBe(""); + }); + + it("starts counting once the wait is long enough to ask about", () => { + const { container } = render(); + vi.advanceTimersByTime(SHOW_ELAPSED_AFTER_MS + 500); + expect(elapsedText(container)).toMatch(/^\d+\.\ds$/); + }); +}); diff --git a/src/components/session/transcript/loading-state.tsx b/src/components/session/transcript/loading-state.tsx new file mode 100644 index 0000000..ddc577e --- /dev/null +++ b/src/components/session/transcript/loading-state.tsx @@ -0,0 +1,179 @@ +"use client"; + +import { memo, useEffect, useRef, useState, type ReactNode } from "react"; + +import { cn } from "../../../lib/utils.ts"; +import { useVisibleAnimation } from "./visible-animation.ts"; + +/** + * LOADING STATE — the pixel-grid loader shown while a turn is doing work the + * transcript can't render yet (the ACP round-trip, the first tokens, the beat + * before a tool call). + * + * Three parts, in order: a 3×3 grid of dots lit by a travelling wavefront, a + * shimmering label, and a live elapsed timer in mono tabular figures. + * + * Default variant is `dots` — the round cells. `drive` is the same wavefront + * with square cells, `orbit` a comet lapping the perimeter. + * + * Perf notes — this sits INSIDE the transcript, above a long thread of real + * DOM rows: + * - the grid animates `opacity` only (paint, no layout, no transform), on + * nine 2.5px cells, so it can't touch the scroll path; + * - the timer writes `textContent` through a ref on a 100ms interval. A + * `useState` tick would re-render this component 10×/s while the transcript + * is also draining stream deltas; the DOM write costs nothing and React + * never hears about it; + * - the row is a fixed height, so its mount/unmount doesn't jolt the thread. + * + * Reduced motion freezes the grid to its dim state; the timer still ticks. + */ + +/** Cell delays (ms) for a chevron wavefront driving left→right. The 650ms cycle + * is shorter than the sweep, so two fronts are always in flight. */ +const CHEVRON = Array.from({ length: 9 }, (_, i) => { + const r = Math.floor(i / 3); + const c = i % 3; + return (c + Math.abs(r - 1)) * 90; +}); + +/** Perimeter order for the orbit variant; the centre cell stays dark (`null`). */ +const ORBIT_ORDER = [0, 1, 2, 5, 8, 7, 6, 3]; +const ORBIT = Array.from({ length: 9 }, (_, i) => { + const k = ORBIT_ORDER.indexOf(i); + return k === -1 ? null : k * 110; +}); + +const PATTERNS = { + drive: { delays: CHEVRON, dur: 650, round: false }, + dots: { delays: CHEVRON, dur: 650, round: true }, + orbit: { delays: ORBIT, dur: 950, round: false }, +} satisfies Record; + +export type LoaderVariant = keyof typeof PATTERNS; + +function format(ms: number): string { + const total = ms / 1000; + if (total < 60) return `${total.toFixed(1)}s`; + return `${Math.floor(total / 60)}m ${(total % 60).toFixed(1)}s`; +} + +/** How long the indicator waits before calling the wait a stall. */ +export const STALL_AFTER_MS = 30_000; + +/** How long a wait has to run before the elapsed clock is worth showing. + * + * Below this the number is noise: it appears, reads "0.2s", and is gone + * before anyone has finished looking at it. Past it the wait is long enough + * that "how long has this been going?" is a real question, which is the + * moment the clock starts earning its place. */ +export const SHOW_ELAPSED_AFTER_MS = 3_000; + +/** What the indicator says while the request is still in flight. + * + * Not "Thinking": this indicator is only ever on screen BEFORE the model has + * produced anything (a streaming assistant turn only exists once it + * emits a row, and the indicator is gone by then). Saying "Thinking" through a five-second wait claims the model is + * working when the request may not even have reached it. */ +export const WAITING_LABEL = "Waiting for model"; + +/** Elapsed since mount, written straight to the DOM — see the perf note above. + * + * `stalled` is the one piece of React state here: it flips true ONCE, when + * the wait has outlasted `stallAfterMs`, so the caller can swap in a "still + * going…" affordance. One re-render in thirty seconds; the ticking label + * itself never goes through React. */ +function useElapsed(stallAfterMs: number, showAfterMs: number) { + const ref = useRef(null); + const [stalled, setStalled] = useState(false); + useEffect(() => { + const start = performance.now(); + const paint = () => { + // A backgrounded window with a running agent was repainting this label + // 10×/s forever; elapsed time is derived from `start` at paint time, so + // skipping ticks while hidden loses nothing — the next visible paint is + // exact. + if (document.visibilityState !== "visible") return; + if (!ref.current) return; + const elapsed = performance.now() - start; + // Blank until the wait is worth counting, so a turn that starts promptly + // never flashes a number at the reader. + ref.current.textContent = elapsed < showAfterMs ? "" : format(elapsed); + }; + paint(); + const id = window.setInterval(paint, 100); + const stallId = window.setTimeout(() => setStalled(true), stallAfterMs); + document.addEventListener("visibilitychange", paint); + return () => { + window.clearInterval(id); + window.clearTimeout(stallId); + document.removeEventListener("visibilitychange", paint); + }; + }, [stallAfterMs, showAfterMs]); + return { ref, stalled }; +} + +export const LoadingState = memo(function LoadingState({ + label = WAITING_LABEL, + variant = "dots", + className, + stalledContent, + stallAfterMs = STALL_AFTER_MS, + showElapsedAfterMs = SHOW_ELAPSED_AFTER_MS, +}: { + label?: string; + variant?: LoaderVariant; + className?: string; + /** Rendered under the indicator once the wait has outlasted `stallAfterMs` + * — the way out of a start that is not going to finish on its own. Nothing + * is rendered (and no state flips) when this is not given. */ + stalledContent?: ReactNode; + stallAfterMs?: number; + /** How long before the elapsed clock appears. See `SHOW_ELAPSED_AFTER_MS`. */ + showElapsedAfterMs?: number; +}) { + const { ref: elapsed, stalled } = useElapsed(stallAfterMs, showElapsedAfterMs); + const shimmer = useVisibleAnimation(); + const { delays, dur, round } = PATTERNS[variant] ?? PATTERNS.dots; + + const indicator = ( +
+ + {delays.map((d, i) => ( + + ))} + + {label} + +
+ ); + if (!stalledContent || !stalled) return indicator; + return ( +
+ {indicator} + {stalledContent} +
+ ); +}); diff --git a/src/components/session/transcript/marker-rows.tsx b/src/components/session/transcript/marker-rows.tsx new file mode 100644 index 0000000..a0c41a0 --- /dev/null +++ b/src/components/session/transcript/marker-rows.tsx @@ -0,0 +1,289 @@ +"use client"; + +import { memo, useCallback, useMemo } from "react"; +import { ChevronRight } from "lucide-react"; + +import { cn } from "../../../lib/utils.ts"; +import { useGroupDiscussed, useRowDiscussed, useTranscript } from "./context.tsx"; +import type { MarkerGroupRow, MarkerRow, SubagentRow } from "./model.ts"; +import { + AgentOrb, + Column, + formatCalls, + LiveElapsed, + settledFigure, + SUBAGENT_STATE, +} from "./parts.tsx"; +import { FILE_DETAIL, ICON_PX, ICON_STROKE, ToolGlyph } from "./tool-glyph.tsx"; +import { useVisibleAnimation } from "./visible-animation.ts"; + +// ── Marker ───────────────────────────────────────────────────────────────── + +/** + * One tool call: a single muted line, and nothing else. + * + * The group expands, while each action stays one line. Clicking an action with + * output or a diff opens its detail view. There is no trailing chevron, as in + * Codex: a file target reads as a link (dotted underline) and every clickable + * row brightens on hover. + * + * What a click opens is the app's (`onOpenMarker`); a call it can open nothing + * for (`opens: "none"`) is not a button anyone can press. + */ +export const MarkerRowView = memo(function MarkerRowView({ + row, + embedded = false, +}: { + row: MarkerRow; + embedded?: boolean; +}) { + const { CommentPill, onOpenMarker } = useTranscript(); + const onClick = useCallback(() => onOpenMarker?.(row), [onOpenMarker, row]); + const discussed = useRowDiscussed(row.toolCallId) && CommentPill !== undefined; + const clickable = row.opens !== "none" && onOpenMarker !== undefined; + const fileLink = clickable && FILE_DETAIL.has(row.tool); + const shimmer = useVisibleAnimation(); + + const line = ( + + ); + // A discussed call wears its pill beside the line; the wrapper exists only + // then, so every other marker row's DOM is exactly what it was. + const body = + discussed && CommentPill ? ( +
+ {line} + +
+ ) : ( + line + ); + // `py-1` at top level: the same box as a block's header, so a lone call + // reads at the rhythm of the blocks around it. + return embedded ? body : {body}; +}); + +/** + * A folded sequence of consecutive tool calls, kept between the prose around it. + * + * One counted sentence you click — "Ran 3 commands and read 2 files" — led + * by the icon of the group it names first. While a call + * is running the line names that call instead ("Running bun run typecheck") + * and wears its icon, then returns to the sentence when it finishes. + * + * The block does NOT open itself while live. The one line carries the live + * state instead, and earns it by saying three things the settled sentence + * cannot: what is running right now, how many actions are already behind it, + * and how long the current one has been going. Auto-expanding was the + * alternative and was rejected — it makes the transcript reflow under the + * reader mid-turn, for detail that is one click away and that the folded + * summary reports a second later anyway. + * + * The numeric gutter is the same right-hand slot `MarkerRowView` puts `+n −m` + * in, for the same reason: the left of a marker line is a sentence, the right + * is a column of figures, and they should not interleave. + * + * The chevron appears on hover and stays visible when open. + */ +export const MarkerGroupRowView = memo(function MarkerGroupRowView({ + row, +}: { + row: MarkerGroupRow; +}) { + const { GroupCommentPill, onToggleGroup: onExpandTurn } = useTranscript(); + // The ids of the calls behind this line, which is what a comment on any of + // them is keyed by. Derived here rather than carried on the row: it is a map + // over a list the row already holds, and the projection would have to redo + // it on every marker state change. + const callIds = useMemo(() => row.markers.map((marker) => marker.toolCallId), [row.markers]); + const discussed = useGroupDiscussed(callIds) && GroupCommentPill !== undefined; + // Derived rather than carried on the row: the projection would have to + // recompute it on every marker state change anyway, and it is a scan of a + // list the row already holds. + const failed = row.markers.some((marker) => marker.state === "failed"); + const shimmer = useVisibleAnimation(); + const summary = ( + + ); + return ( + + {/* A discussed sequence wears the fold's aggregate beside its summary — + faces and a count over the calls inside, opening the fold so the call + that was discussed can show its own pill. The wrapper exists only + then, so every other group's DOM is exactly what it was. */} + {discussed && GroupCommentPill ? ( +
+ {summary} + { + if (!row.open) onExpandTurn(row.id); + }} + /> +
+ ) : ( + summary + )} + {row.open && ( + // Laid out in the thread, not in a 240px scroller. A nested scroll area + // inside a scrolling transcript is two scrollbars fighting over the + // same wheel gesture, and it hides the end of the list behind an + // interaction the reader has to discover. Opening a sequence is a + // deliberate act on one turn at a time, so its rows are just rows. +
+ {row.markers.map((marker) => ( + + ))} +
+ )} +
+ ); +}); + +/** + * A delegated child — one line, the same line a tool call gets. + * + * Minimal on purpose: a subagent is not a card, it is one more thing the turn + * did, and the transcript's whole bargain is that work reads as a quiet column + * you scan. What sets it apart is the glyph — a filled orb rather than a tool + * icon, which is how both Codex and Claude Desktop mark an agent among tool + * calls — and nothing else. + * + * Clicking opens the child in the side panel rather than expanding in place: + * its prompt, its calls and its answer are a body, and a row that grows into + * one is exactly the unpredictable height a transcript should not absorb. + */ +export const SubagentRowView = memo(function SubagentRowView({ row }: { row: SubagentRow }) { + const { onOpenSubagent } = useTranscript(); + const onOpen = useCallback(() => onOpenSubagent?.(row), [onOpenSubagent, row]); + const running = row.status === "running"; + const failed = row.status === "failed"; + const shimmer = useVisibleAnimation(); + return ( + + + + ); +}); diff --git a/src/components/session/transcript/model.ts b/src/components/session/transcript/model.ts new file mode 100644 index 0000000..bf07512 --- /dev/null +++ b/src/components/session/transcript/model.ts @@ -0,0 +1,386 @@ +/** + * The transcript's row model: a session projected into a closed set of row + * kinds, each carrying everything its view needs. Desktop's transcript and + * web's session reader and remote-control view all render these. + * + * Nothing here knows either app's wire. Each app writes the projection from + * its own data (desktop's `projectRows` over the session-delta messages; web's + * adapters over `TimelineEntry` pages and the remote-control transcript), so + * the row views are the one place a transcript's look is decided. The + * vocabulary is closed on purpose: a new row kind is a deliberate addition to + * what a transcript can say, not an ad-hoc branch in a render function. + * + * Rows are plain data compared shallowly by the views' `memo`, so a projection + * that hands back the previous object for an unchanged row keeps its view from + * re-rendering. + */ + +/** An image sent with a prompt: its MIME type and its bytes, base64. */ +export interface TranscriptImage { + mimeType: string; + dataBase64: string; +} + +/** One file a turn read or modified, with edit line counts (0 for reads). */ +export interface TranscriptFile { + path: string; + kind: "read" | "edit"; + added: number; + removed: number; + /** For edits only: the file was created new. Undefined for reads. */ + created?: boolean; + /** For a renamed file, the path it had before; `path` is where it went. */ + movedFrom?: string; +} + +/** Something outside the conversation that cut into a turn: today, the + * computer sleeping mid-reply. */ +export interface TranscriptInterruption { + cause: "sleep"; + /** How long the machine was asleep. */ + sleptSecs: number; + /** How the turn ended after it. */ + outcome: "finished" | "failed" | "stopped" | "disconnected"; + /** The agent's own error, for `failed`: kept for diagnosis, shown folded. */ + error?: string; +} + +/** What sent a prompt Atlas wrote on its own. */ +export type InjectedPromptSource = "pull-request-watch" | "restart"; + +/** How a user-role message came from Atlas rather than the user. */ +export interface InjectedPrompt { + source: InjectedPromptSource; + /** One line for the row (`#12: checks failed`). */ + summary: string; +} + +/** Where a delegated child agent is. A child the parent interrupted is + * neither completed nor failed. */ +export type SubagentStatus = "running" | "completed" | "failed" | "interrupted"; + +// ── Row kinds ────────────────────────────────────────────────────────────── + +export const RowKind = { + User: 0, + Prose: 1, + Thinking: 2, + Marker: 3, + MarkerGroup: 4, + Separator: 5, + TurnFooter: 6, + WorkHeader: 7, + Subagent: 8, + Interruption: 9, + Injected: 10, +} as const; + +/** Marker execution state — drives the leading glyph, nothing else. */ +export type MarkerState = "pending" | "running" | "done" | "failed"; + +/** What a marker click opens in the detail panel. */ +export type MarkerDetail = "diff" | "output" | "none"; + +interface RowBase { + /** Stable across projections: the list keys on this. */ + id: string; + turnId: string; + /** True for the first row of its turn (anchor target for scroll/expand). */ + firstInTurn: boolean; +} + +export interface UserRow extends RowBase { + kind: typeof RowKind.User; + text: string; + /** Heavy @-mention context, collapsed behind a chip. */ + contextBlocks: number; + /** Set once the user has expanded a clamped bubble. Expanding swaps the row + * for a taller one — a data change with a known new height, never a reflow. */ + expanded: boolean; + /** The images sent with the prompt, shown as tiles above the bubble. */ + attachments: readonly TranscriptImage[]; + /** The remote-control driver who sent it, when it was not this window's + * composer: shown under the bubble so the thread says whose prompt it was. + * The name the wire carried, or "Someone else" — the room never names a + * user, so the row resolves `remoteAuthorId` against the roster first. */ + remoteAuthor: string | null; + /** Their principal id, for a face and a real name (`useRcPeople`). */ + remoteAuthorId: string | null; + timestamp: string; + /** `timestamp` is only when Atlas replayed the message; show no clock. */ + timestampApproximate?: true; + /** The outside paths the composer attached, the only ones a click in this + * bubble may open. */ + trustedPaths?: readonly string[]; +} + +/** The message id behind a user row. Row ids are minted as `u:` + * by the projection; anything that has to address the + * MESSAGE (pins, jumps) goes through this rather than slicing the prefix at + * the call site. */ +export function userRowMessageId(rowId: string): string { + return rowId.startsWith("u:") ? rowId.slice(2) : rowId; +} + +export interface ProseRow extends RowBase { + kind: typeof RowKind.Prose; + text: string; + /** The live streaming tail; the only row whose content changes per frame. */ + streaming: boolean; + /** Shown on the first prose row of an assistant turn. */ + showHeader: boolean; + model: string | null; + timestamp: string; + /** `timestamp` is only when Atlas replayed the message; show no clock. */ + timestampApproximate?: true; + /** Set on the turn's last response when the turn ends on a footer row: its + * hover footer (copy, branch, pin, time) moves below the changed-files card, + * to the end of the response, and this row reserves no gap for it. */ + footerBelow?: true; +} + +export interface ThinkingRow extends RowBase { + kind: typeof RowKind.Thinking; + /** The full reasoning, only while the reader has the row open. Collapsed it + * is empty, so a streaming thought re-renders its row when the headline + * changes rather than on every chunk. */ + text: string; + /** What the agent is thinking about, from `thoughtHeadline`. */ + headline: string | null; + /** The thought as it arrives, from `liveThought`: set only while this is + * the turn's current step — streaming, with no tool call or answer after + * it yet. The row shows it open, then folds to `headline` the moment the + * agent moves on. */ + live: string | null; + streaming: boolean; + expanded: boolean; +} + +/** + * Which glyph a marker row leads with — a closed set, mapped to an icon by the + * renderer. + * + * A key rather than a component: rows are plain data compared shallowly by + * `memo`, and a freshly-minted component reference per projection would miss + * on every row, every frame. It is also the reason this lives here and not in + * the render layer — classification already happens once, in `markerFor`, from + * the same signals that pick the verb. + */ +export type MarkerTool = + | "run" + | "read" + | "edit" + | "search" + | "list" + | "fetch" + | "think" + | "delete" + | "move" + | "file" + | "org" + | "memory" + | "browser" + | "tool"; + +export interface MarkerRow extends RowBase { + kind: typeof RowKind.Marker; + /** Verb shown in muted weight: "Ran", "Read", "Edited", "Searched". */ + verb: string; + /** Icon key for the leading slot, paired with `verb`. */ + tool: MarkerTool; + /** Monospace remainder — the command, path or pattern. Truncated in CSS. */ + detail: string; + state: MarkerState; + toolCallId: string; + opens: MarkerDetail; + /** Full path for edit markers — `detail` is shortened for display, and the + * diff viewer needs the real one. */ + path?: string; + /** The untouched shell command, on bash rows whose verb came from parsing it. + * `detail` shows the file those rows read, not the command that read it, so + * this is what the hover title falls back to — the information the + * reclassification hid has to stay reachable without opening the panel. */ + cmd?: string; + /** The MCP server the call went to, in words ("browser", "github"), for + * calls Atlas has no verb for. A block counts these per server: "Used + * browser 2 times" says more than "Used 2 tools". */ + server?: string; + /** Only set for edit markers, so the row can show `+n −m` inline. */ + added: number; + removed: number; + /** Epoch ms the call was first seen (desktop: `ToolCallDisplay.startedAt`). Feeds the + * live elapsed figure; nothing settled reads it. */ + startedAt: number | undefined; + /** How long the call took, once it settled — set only when both ends were + * stamped. An expanded block shows it in the right gutter for calls that + * took a second or more. Derived from the call, so a segment that holds + * holds this too. */ + durationMs?: number; +} + +export interface MarkerGroupRow extends RowBase { + kind: typeof RowKind.MarkerGroup; + /** The whole block as one counted sentence: "Ran 3 commands and read 2 + * files". See "Folded-block summary". */ + summary: string; + /** How many tool calls the block stands for. Not rendered — the summary is + * the whole line — but it is what `summary` was counted from, and the thing + * to assert on when testing that projection. */ + count: number; + /** The glyph for the whole block: the icon of the group `summary` names + * first. */ + tool: MarkerTool; + /** Calls in this consecutive sequence, shown inside the disclosure. */ + markers: MarkerRow[]; + open: boolean; + /** At least one call in the sequence is still active. */ + running: boolean; + liveLabel: string | null; + /** The active call's own glyph while `running` — the live line names that + * call, so it wears that call's icon rather than the block's. */ + liveTool: MarkerTool | null; + /** Epoch ms the active call started, for the ticking figure in the live line's + * right gutter. The turn header above already counts the whole turn; this + * answers the different question a folded block otherwise hides — how long + * THIS command has been going, and therefore whether it is stuck. */ + liveStartedAt: number | null; + /** Calls in this block already finished, shown beside the live line. + * + * Deliberately not "3 of 6": tool calls stream in one at a time, so the + * total does not exist until the block ends. Counting what is DONE is the + * only honest progress a collapsed block can report, and it is the whole of + * the accumulation a one-line live state can show. */ + liveDone: number; +} + +/** + * "Working for 46s" / "Worked for 7m 37s ›" — the head of an assistant turn. + * + * Once the turn settles, everything before its final answer (earlier prose, + * thinking, tool blocks) is folded behind this row and simply not projected, so + * a finished turn costs a header, its answer and its footer however much work + * it did. Opening it puts those rows back in the thread, in flow. + */ +export interface WorkHeaderRow extends RowBase { + kind: typeof RowKind.WorkHeader; + /** The turn is still running: the row ticks and nothing is folded. */ + live: boolean; + /** Epoch ms the live clock counts from — the user's message. */ + startedAt: number | null; + /** Settled wall time, when Rust timed the turn (desktop: `ChatMessage.workedMs`). */ + workedMs: number | null; + /** The user stopped the turn (`ChatMessage.stopReason` is `cancelled`): + * the settled label reads "Stopped after" rather than "Worked for". */ + stopped: boolean; + /** There are rows behind the header to fold; without them it is a caption. */ + foldable: boolean; + open: boolean; +} + +/** + * A child agent the turn delegated to — the launching tool call, rendered as + * the child rather than as the call. + * + * The call that spawns a subagent is a poor row: its name is the agent's word + * for the mechanism ("Task", "spawn_agent", "Start subagent counter") and its + * result is a transport detail. The child is the thing the reader is following, + * so the row carries the child's name, status and work instead, and the launch + * survives only as the identity (`toolCallId`). + * + * Deliberately NOT folded into a `MarkerGroup`. A folded block says "loaded + * tools" and hides how many agents are running and whether any has come back — + * which is the whole question a delegating turn raises. + */ +export interface SubagentRow extends RowBase { + kind: typeof RowKind.Subagent; + /** The launching call's id — the child's identity, and what its own calls + * point back to (`ToolCallDisplay.parentToolCallId`). */ + toolCallId: string; + name: string; + status: SubagentStatus; + /** The child's role, when the launch named one: Claude's `subagent_type`, + * the engine's `agent_type`. */ + role: string | undefined; + /** What it was asked to do, for the row's second line. */ + prompt: string | undefined; + /** What it reported back. For a mail child (the native engine's) this is the + * whole of what it ever says. */ + result: string | undefined; + /** Epoch ms the launch was first seen — the live elapsed figure counts from + * here, exactly as a marker's does. */ + startedAt: number; + /** Set once it has ended, so a settled row states a duration rather than + * ticking forever. */ + endedAt: number | undefined; + /** Its own tool calls, when the agent attributes them. ALWAYS EMPTY for a + * mail child, whose calls run on a thread this session never sees — so an + * empty list is "not visible", never "did nothing". */ + markers: MarkerRow[]; + /** How many calls the CHILD reports having made, which is not + * `markers.length`: the agent can count work whose calls it never attributed + * to this session. Zero means "nothing visible", so a row renders no count + * rather than "0" — which would be a claim about the child that is false. */ + workCount: number; +} + +export interface SeparatorRow extends RowBase { + kind: typeof RowKind.Separator; + label: string; +} + +export interface TurnFooterRow extends RowBase { + kind: typeof RowKind.TurnFooter; + /** The turn's frozen `turnSummary.files`, by identity: the same array every + * projection, so a settled turn's changed-files card never re-renders. */ + files: readonly TranscriptFile[]; + repoAtTurn: boolean; + /** The turn's stable key (`stableTurnKey`): what the card opens and + * remembers its folders by, since `turnId` changes when the log reloads. */ + turnKey: string; + /** Message id, so the footer can reach usage/suggestions/contextUsage. */ + messageId: string; + hasSuggestions: boolean; + contextChip: boolean; + /** The turn's last response, whose hover footer this row draws after the + * card (that prose row carries `footerBelow`). Flat fields rather than one + * object so the shallow row comparison keeps a settled footer row stable. */ + responseRowId?: string; + responseText?: string; + responseTimestamp?: string; + /** False when the response's header line already shows the time. */ + responseShowTimestamp?: boolean; +} + +/** A prompt Atlas sent the agent on its own (`ChatMessage.injected`): a user + * turn, but not the user's words, so not drawn as their bubble. */ +export interface InjectedRow extends RowBase { + kind: typeof RowKind.Injected; + injected: InjectedPrompt; + /** The prompt as the agent received it, shown when the row is opened. */ + text: string; + timestamp: string; +} + +/** Something outside the conversation cut into this turn (`TurnInterruption`). + * Its own row, after the footer, so it reads as Atlas speaking about the turn + * rather than as more of the reply. */ +export interface InterruptionRow extends RowBase { + kind: typeof RowKind.Interruption; + interruption: TranscriptInterruption; + /** True when this is the thread's last turn — the only one whose Retry and + * Continue would act on the reply the row is about. */ + latest: boolean; +} + +export type Row = + | UserRow + | InjectedRow + | InterruptionRow + | ProseRow + | ThinkingRow + | MarkerRow + | MarkerGroupRow + | SeparatorRow + | TurnFooterRow + | WorkHeaderRow + | SubagentRow; diff --git a/src/components/session/transcript/parse-shell-command.test.ts b/src/components/session/transcript/parse-shell-command.test.ts new file mode 100644 index 0000000..d79811e --- /dev/null +++ b/src/components/session/transcript/parse-shell-command.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from "vitest"; +import { commandProgramName, parseShellCommand } from "./parse-shell-command.ts"; + +/** The classification alone — the field every assertion below is really about. */ +const kindOf = (cmd: string) => parseShellCommand(cmd).kind; + +describe("the commands an agent actually runs", () => { + // These are lifted verbatim from a real Atlas transcript, which is the whole + // point: before the parser every one of them rendered as "Ran" with the same + // terminal glyph, because they are all the same `execute` tool call. + it("recovers the action from a real turn's worth of commands", () => { + expect(kindOf("ls src/features/chat/components/ | head -80")).toBe("list"); + expect(kindOf('grep -rl "tool" src/features/chat/components/ | head -30')).toBe("search"); + expect(kindOf("sed -n '1,120p' src/features/chat/components/transcript-rows.tsx")).toBe("read"); + expect(kindOf("cargo test -p atlas-memory")).toBe("run"); + }); + + it("names the file a read read, and the thing a search looked for", () => { + expect(parseShellCommand("cat src/lib/utils.ts")).toEqual({ + kind: "read", + path: "src/lib/utils.ts", + }); + expect(parseShellCommand("rg 'TODO' src/")).toEqual({ + kind: "search", + query: "TODO", + path: "src/", + }); + }); +}); + +describe("pipelines", () => { + it("looks past the stage that only formats the output", () => { + // `| head -40` shapes what you see; it is not what the command did. + expect(kindOf("rg 'foo' src | head -40")).toBe("search"); + expect(kindOf("ls -la | wc -l")).toBe("list"); + expect(kindOf("cat pkg.json | tr -d ' ' | sort")).toBe("read"); + }); + + it("still treats those tools as reads when they name a file themselves", () => { + // The same binary, two jobs: `head -n 40` is a pipe stage, `head -n 40 f` + // is how you read the top of a file. + expect(parseShellCommand("head -n 40 notes.md")).toEqual({ kind: "read", path: "notes.md" }); + expect(kindOf("head -n 40")).toBe("run"); + }); + + it("falls back to Ran when two real commands are chained", () => { + // Upstream's TUI shows this exact command as "Ran", and for the same + // reason: one row cannot honestly claim both actions. + expect(kindOf("pwd && rg --files -g '*.ts'")).toBe("run"); + expect(kindOf("git status --short; git log -1 --oneline")).toBe("run"); + }); + + it("drops the scaffolding that is not a command in its own right", () => { + expect(kindOf("cd src && cat main.ts")).toBe("read"); + expect(kindOf("echo hi && ls")).toBe("list"); + }); +}); + +describe("commands this must refuse to classify", () => { + // The governing rule: a wrong verb is worse than a generic one. A row that + // says "Read" over a command that deleted something is a lie the reader has + // no way to catch, so anything opaque to the tokenizer is "run". + it("refuses a redirect that writes somewhere", () => { + expect(kindOf("cat template.txt > out.txt")).toBe("run"); + expect(kindOf("ls > listing.txt")).toBe("run"); + }); + + it("allows a discard, which says nothing about what was read", () => { + expect(kindOf("rg 'foo' src 2>/dev/null")).toBe("search"); + }); + + it("refuses substitutions and backticks it cannot see into", () => { + expect(kindOf("cat $(ls | head -1)")).toBe("run"); + expect(kindOf("cat `which node`")).toBe("run"); + expect(kindOf('rg "$(cat pattern.txt)" src')).toBe("run"); + }); + + it("refuses an unbalanced quote rather than guessing where it ended", () => { + expect(kindOf("rg 'unterminated src")).toBe("run"); + }); + + it("does not mistake a mutating command for a read", () => { + expect(kindOf("sed -i 's/a/b/' file.ts")).toBe("run"); + expect(kindOf("rm -rf build")).toBe("run"); + expect(kindOf("git commit -m 'wip'")).toBe("run"); + }); +}); + +describe("quoting and flag values", () => { + it("keeps a quoted pattern whole, spaces and all", () => { + expect(parseShellCommand("rg 'hello world' src")).toEqual({ + kind: "search", + query: "hello world", + path: "src", + }); + }); + + it("does not mistake a flag's value for a path", () => { + // `-g '*.ts'` and `--glob=*.ts` both feed a flag; neither is where to look. + expect(parseShellCommand("rg -g '*.ts' foo src")).toEqual({ + kind: "search", + query: "foo", + path: "src", + }); + expect(parseShellCommand("rg --glob=*.ts foo")).toEqual({ + kind: "search", + query: "foo", + path: null, + }); + }); + + it("takes grep's pattern from -e when it is given that way", () => { + expect(parseShellCommand("grep -rn -e 'foo|bar' src/")).toEqual({ + kind: "search", + query: "foo|bar", + path: "src/", + }); + }); + + it("reads through a bash -lc wrapper to the script inside", () => { + expect(parseShellCommand("bash -lc 'cat README.md'")).toEqual({ + kind: "read", + path: "README.md", + }); + }); +}); + +describe("the list and search split within one tool", () => { + it("counts rg --files as enumerating, not matching", () => { + // `rg --files` prints paths; it has no pattern at all. + expect(parseShellCommand("rg --files src")).toEqual({ kind: "list", path: "src" }); + }); + + it("splits find on whether it was given a name filter", () => { + expect(parseShellCommand("find src -name '*.rs'")).toEqual({ + kind: "search", + query: "*.rs", + path: "src", + }); + expect(parseShellCommand("find src -type f")).toEqual({ kind: "list", path: "src" }); + }); + + it("reads a lone fd operand as a directory only when it looks like one", () => { + expect(kindOf("fd ./src")).toBe("list"); + expect(kindOf("fd parse_command")).toBe("search"); + }); +}); + +describe("sed, which is a read only in one exact shape", () => { + it("accepts a line-range print with a file", () => { + expect(parseShellCommand("sed -n '10,40p' src/a.ts")).toEqual({ + kind: "read", + path: "src/a.ts", + }); + expect(parseShellCommand("sed -n '40p' a.ts")).toEqual({ kind: "read", path: "a.ts" }); + }); + + it("rejects every other sed", () => { + expect(kindOf("sed -n 's/a/b/p' a.ts")).toBe("run"); + expect(kindOf("sed 's/a/b/' a.ts")).toBe("run"); + }); +}); + +describe("the program a live line names", () => { + it("is the command past scaffolding, assignments and launchers", () => { + expect(commandProgramName("sed -n '1,200p' src/a.ts")).toBe("sed"); + expect(commandProgramName("cd crates/x && cargo test -p atlas")).toBe("cargo"); + expect(commandProgramName("RUST_LOG=debug sudo /usr/local/bin/node x.js")).toBe("node"); + expect(commandProgramName("bash -lc 'rg foo | head -20'")).toBe("rg"); + }); + + it("steps over a launcher's options and their values", () => { + expect(commandProgramName("sudo -u root cargo test")).toBe("cargo"); + expect(commandProgramName("sudo -E -u root cargo test")).toBe("cargo"); + expect(commandProgramName("sudo -uroot cargo test")).toBe("cargo"); + expect(commandProgramName("env -i PATH=/bin make")).toBe("make"); + expect(commandProgramName("nice -n 10 make")).toBe("make"); + expect(commandProgramName("time -v cargo build")).toBe("cargo"); + expect(commandProgramName("sudo -- rm -rf x")).toBe("rm"); + }); + + it("ignores shell comments", () => { + expect(commandProgramName("# setup\ncargo test")).toBe("cargo"); + expect(commandProgramName("cargo test # all of it")).toBe("cargo"); + expect(commandProgramName("echo a#b")).toBe("echo"); + expect(commandProgramName("rg '#include'")).toBe("rg"); + }); +}); diff --git a/src/components/session/transcript/parse-shell-command.ts b/src/components/session/transcript/parse-shell-command.ts new file mode 100644 index 0000000..af20297 --- /dev/null +++ b/src/components/session/transcript/parse-shell-command.ts @@ -0,0 +1,528 @@ +// What a shell command actually DID, recovered from the command string. +// +// Agents do most of their work through one tool. `cat`, `rg`, `ls` and `cargo +// test` all arrive as the same `execute` call, so classifying by tool name puts +// the same terminal glyph on every row of a turn and tells the reader nothing — +// which is exactly what the transcript looked like before this existed. +// +// This is a port of the engine's own answer to that problem, +// `vendor/atlas-engine/shell-command/src/parse_command.rs`, which is why the command +// tables below match its lists rather than anyone's intuition. Ported to TS +// rather than piped through from Rust for two reasons: the delta wire does not +// carry a parsed command today (an additive field would be the way), and the classification has +// to work for EVERY agent — an ACP agent's bash call carries a command string +// and nothing else, so a native-agent-only `parsed_cmd` field would leave the +// installed agents exactly as undifferentiated as they are now. +// +// Two deliberate narrowings against upstream: +// +// - Upstream parses `bash -lc` scripts with a real shell grammar and returns +// a LIST of parsed commands, because its TUI prints one line each. A marker +// row is one line per tool call and stays that way, so this reduces to a +// single classification and answers "run" whenever the pieces disagree. +// - Anything with a redirect, a subshell or a backtick is "run" without +// further thought. Upstream's grammar can see through those; a regex +// tokenizer cannot, and a command that writes a file must never be able to +// render as a book. +// +// The bias throughout is that `run` is the honest fallback. A wrong verb is +// worse than a generic one: "Read" over a command that deleted something is a +// lie the reader has no way to catch. + +/** What a command did, in the vocabulary the marker rows render. */ +export type ParsedShell = + | { kind: "read"; path: string } + | { kind: "list"; path: string | null } + | { kind: "search"; query: string | null; path: string | null } + | { kind: "run" }; + +const RUN: ParsedShell = { kind: "run" }; + +// ── Tokenizing ───────────────────────────────────────────────────────────── + +/** Connectors that end one command and start the next. */ +const CONNECTOR = new Set(["|", "||", "&&", ";", "\n"]); + +/** Redirections to the void. They say nothing about what was read, so they are + * dropped rather than disqualifying the command — `rg foo 2>/dev/null` is + * still a search. Every OTHER redirect disqualifies it. */ +const NULL_REDIRECTS = new Set(["2>/dev/null", ">/dev/null", "&>/dev/null", "2>&1"]); + +/** + * Split a command into shell words, keeping connectors as their own tokens. + * + * Returns null when the command contains something this cannot safely reason + * about — an unbalanced quote, a substitution, a redirect that isn't a discard. + * Null means "run": the caller must not fall back to a partial parse, because + * a half-understood command is the case where a wrong icon gets minted. + */ +function tokenize(command: string): string[] | null { + const tokens: string[] = []; + let cur = ""; + let started = false; + const push = () => { + if (started) tokens.push(cur); + cur = ""; + started = false; + }; + + for (let i = 0; i < command.length; i++) { + const c = command[i]; + + if (c === "\\") { + // A trailing backslash-newline is a line continuation, not a token. + if (command[i + 1] === "\n") { + i++; + continue; + } + if (i + 1 >= command.length) return null; + cur += command[++i]; + started = true; + continue; + } + + if (c === "'" || c === '"') { + const close = command.indexOf(c, i + 1); + if (close === -1) return null; + const body = command.slice(i + 1, close); + // `"$(...)"` and `` "`...`" `` still substitute inside double quotes. + if (c === '"' && (body.includes("$(") || body.includes("`"))) return null; + cur += body; + started = true; + i = close; + continue; + } + + // An unquoted `#` at the start of a word opens a comment to the end of + // the line (`# setup\ncargo test`); inside a word (`a#b`) it is text. + if (c === "#" && !started) { + while (i + 1 < command.length && command[i + 1] !== "\n") i++; + continue; + } + + if (c === "$" && command[i + 1] === "(") return null; + if (c === "`") return null; + + if (c === " " || c === "\t" || c === "\r") { + push(); + continue; + } + + if (c === "\n" || c === ";") { + push(); + tokens.push("\n"); + continue; + } + + if (c === "|" || c === "&") { + push(); + const doubled = command[i + 1] === c; + if (doubled) i++; + // A lone `&` is backgrounding, which this has no story for. + if (c === "&" && !doubled) return null; + tokens.push(doubled ? c + c : c); + continue; + } + + if (c === "<") return null; + if (c === ">") { + // Only survives as part of a discard like `2>/dev/null`, which the + // current token already holds the `2` of. + const rest = command.slice(i).split(/\s/, 1)[0]; + const whole = cur + rest; + if (!NULL_REDIRECTS.has(whole)) return null; + i += rest.length - 1; + cur = ""; + started = false; + continue; + } + + cur += c; + started = true; + } + push(); + return tokens; +} + +// ── Shaping ──────────────────────────────────────────────────────────────── + +/** Strip the wrappers that carry no meaning of their own. */ +function unwrap(tokens: string[]): string[] { + // `bash -lc '