Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(chat): redesign loading indicator — editorial-cockpit

Yuting Zhonga7d996ada364
diff --git a/src/app/globals.css b/src/app/globals.css
index f99c2b96..3b258cdb 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -88,6 +88,56 @@
}
}
+/* ────────────────────────────────────────────────────────────────────
+ WorkingIndicator animations.
+
+ Four custom keyframes drive the live "agent is working" card in the
+ chat. Each is intentionally narrow in scope so the indicator reads
+ as one coordinated piece rather than a jittery collection of
+ independent loops.
+
+ - aurora-sweep: thin gradient bar travels L→R across the top edge.
+ Establishes "alive" without taking attention. Slow.
+ - shimmer-bar: identical pattern at the bottom edge, slightly
+ faster + thinner, creates a sense of forward motion
+ when the model is between events.
+ - heartbeat: two-stage scale on the mood dot — a quick squeeze
+ followed by a soft swell, ~1.4s cycle. Reads as
+ a living pulse rather than a steady spinner.
+ - phase-glow: subtle glow + lift on the currently-active phase
+ chip. Repeats at 2s so it's clearly the active one.
+ ──────────────────────────────────────────────────────────────────── */
+
+@keyframes aurora-sweep {
+ 0% { transform: translateX(-110%); opacity: 0.4; }
+ 50% { opacity: 1; }
+ 100% { transform: translateX(220%); opacity: 0.4; }
+}
+
+@keyframes shimmer-bar {
+ 0% { transform: translateX(-120%); }
+ 100% { transform: translateX(260%); }
+}
+
+@keyframes heartbeat {
+ 0%, 100% { transform: scale(0.92); opacity: 0.85; }
+ 20% { transform: scale(1.18); opacity: 1; }
+ 35% { transform: scale(0.96); opacity: 0.9; }
+ 60% { transform: scale(1.08); opacity: 1; }
+}
+
+@keyframes phase-glow {
+ 0%, 100% { box-shadow: 0 0 0 0 currentColor; }
+ 50% { box-shadow: 0 0 0 4px transparent; }
+}
+
+@theme inline {
+ --animate-aurora-sweep: aurora-sweep 2.6s linear infinite;
+ --animate-shimmer-bar: shimmer-bar 1.8s ease-in-out infinite;
+ --animate-heartbeat: heartbeat 1.4s ease-in-out infinite;
+ --animate-phase-glow: phase-glow 2s ease-in-out infinite;
+}
+
:root {
--sidebar: hsl(0 0% 98%);
--sidebar-foreground: hsl(240 5.3% 26.1%);
diff --git a/src/components/beaming-indicator.test.tsx b/src/components/beaming-indicator.test.tsx
deleted file mode 100644
index 24f0fd33..00000000
--- a/src/components/beaming-indicator.test.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { render, screen, act } from "@testing-library/react";
-
-import { BeamingGlyph, BeamingHeadline } from "./beaming-indicator";
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe("BeamingHeadline", () => {
- it("renders a verb and the prefix", () => {
- render(<BeamingHeadline prefix="CMO" />);
- // Status node carries the verb in aria-label so the test doesn't
- // depend on which random verb mounted.
- const node = screen.getByRole("status");
- expect(node).toBeInTheDocument();
- expect(node.getAttribute("aria-label")).toMatch(/\w+…/);
- // Prefix rendered too.
- expect(node.textContent ?? "").toMatch(/CMO/);
- });
-
- it("rotates the verb on a timer", () => {
- vi.useFakeTimers();
- render(<BeamingHeadline prefix="CMO" />);
- const node = screen.getByRole("status");
- const first = node.getAttribute("aria-label");
- // Advance past the verb interval (2.5s) plus margin.
- act(() => {
- vi.advanceTimersByTime(3_000);
- });
- const second = node.getAttribute("aria-label");
- // Random cycle picks a different verb each tick, so labels must differ.
- expect(second).not.toBe(first);
- });
-});
-
-describe("BeamingGlyph", () => {
- it("renders a glyph by default", () => {
- const { container } = render(<BeamingGlyph />);
- // The glyph is inside the only span we render.
- const span = container.querySelector("span[aria-hidden]");
- expect(span).not.toBeNull();
- expect((span?.textContent ?? "").length).toBeGreaterThan(0);
- });
-
- it("honors an explicit glyph prop", () => {
- const { container } = render(<BeamingGlyph glyph="✶" />);
- expect(container.textContent).toBe("✶");
- });
-});
diff --git a/src/components/beaming-indicator.tsx b/src/components/beaming-indicator.tsx
deleted file mode 100644
index 0acc5483..00000000
--- a/src/components/beaming-indicator.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import { cn } from "@/lib/utils";
-
-/**
- * Active "agent is working" indicator. Mimics the Claude Code CLI's
- * "✳ Beaming…" / "✳ Pondering…" pattern: an asterisk glyph that
- * morphs every ~120 ms paired with a quirky verb that swaps every
- * ~2.5 s. The point is to make the chat view obviously alive during
- * the 10–20s pre-first-token wait — a single small pulsing dot is
- * easy to miss and reads as "stuck".
- *
- * Pure visual. The verb cycles independently of any backend signal —
- * lifecycle/tool info, when available, is shown by the parent in a
- * separate row (we don't try to claim the model is "Pondering" while
- * it's actually executing a tool call). Use this only in the "we
- * don't have a better label" branch of WorkingStatus.
- */
-
-// Quirky verbs lifted in spirit from Claude Code. Kept short so they
-// don't reflow the headline as they swap. New entries should also be
-// gerunds ("-ing") so the trailing "…" reads naturally.
-const VERBS = [
- "Beaming",
- "Brewing",
- "Cogitating",
- "Computing",
- "Conjuring",
- "Crunching",
- "Deliberating",
- "Distilling",
- "Effervescing",
- "Elaborating",
- "Mulling",
- "Musing",
- "Percolating",
- "Pondering",
- "Processing",
- "Ruminating",
- "Simmering",
- "Spinning",
- "Sublimating",
- "Synthesizing",
- "Thinking",
- "Tinkering",
- "Whirring",
-] as const;
-
-// Glyph sequence the leading "✳" morphs through. Bright/sparse to dense/full
-// and back so the eye reads it as one pulsing thing rather than a flicker.
-const GLYPHS = ["✳", "✺", "✷", "✸", "✹", "✷", "✺"] as const;
-
-const GLYPH_INTERVAL_MS = 130;
-const VERB_INTERVAL_MS = 2_500;
-
-function useTickingIndex(intervalMs: number, length: number): number {
- const [idx, setIdx] = useState(0);
- useEffect(() => {
- if (length <= 1) return;
- const id = setInterval(() => {
- setIdx((i) => (i + 1) % length);
- }, intervalMs);
- return () => clearInterval(id);
- }, [intervalMs, length]);
- return idx;
-}
-
-function useRandomCycle(intervalMs: number, length: number): number {
- // Random pick each tick (skip same-as-current so it always moves) so
- // the user doesn't see the same fixed sequence and decide it's a loop.
- const [idx, setIdx] = useState(() => Math.floor(Math.random() * length));
- useEffect(() => {
- if (length <= 1) return;
- const id = setInterval(() => {
- setIdx((current) => {
- if (length <= 1) return current;
- let next = Math.floor(Math.random() * length);
- if (next === current) next = (next + 1) % length;
- return next;
- });
- }, intervalMs);
- return () => clearInterval(id);
- }, [intervalMs, length]);
- return idx;
-}
-
-export function BeamingHeadline({
- className,
- prefix,
-}: {
- className?: string;
- /** Optional agent name prefix, rendered before the verb (e.g. "CMO ·"). */
- prefix?: string | null;
-}) {
- const glyphIdx = useTickingIndex(GLYPH_INTERVAL_MS, GLYPHS.length);
- const verbIdx = useRandomCycle(VERB_INTERVAL_MS, VERBS.length);
- const glyph = GLYPHS[glyphIdx]!;
- const verb = VERBS[verbIdx]!;
- return (
- <span
- role="status"
- aria-label={`${verb}…`}
- className={cn("inline-flex items-baseline gap-1.5", className)}
- >
- <BeamingGlyph glyph={glyph} />
- <span className="italic text-muted-foreground">
- {prefix ? `${prefix} ` : ""}
- {verb}
- <AnimatedDots />
- </span>
- </span>
- );
-}
-
-/** Just the morphing glyph, for places that already render their own text. */
-export function BeamingGlyph({
- className,
- glyph,
-}: {
- className?: string;
- glyph?: string;
-}) {
- const idx = useTickingIndex(GLYPH_INTERVAL_MS, GLYPHS.length);
- const ch = glyph ?? GLYPHS[idx]!;
- return (
- <span
- aria-hidden
- className={cn(
- "inline-block text-sky-500 motion-safe:transition-opacity",
- className,
- )}
- >
- {ch}
- </span>
- );
-}
-
-/** Trailing "…" that grows from "." to "..." over time. */
-function AnimatedDots() {
- const idx = useTickingIndex(450, 4); // 0=" ", 1=".", 2="..", 3="..."
- const dots = idx === 0 ? "" : ".".repeat(idx);
- return (
- <span aria-hidden className="inline-block w-3 text-left">
- {dots}
- </span>
- );
-}
diff --git a/src/components/live-transcript.test.tsx b/src/components/live-transcript.test.tsx
index 45c168f0..707c73b3 100644
--- a/src/components/live-transcript.test.tsx
+++ b/src/components/live-transcript.test.tsx
@@ -96,10 +96,11 @@ describe("LiveTranscript empty state", () => {
expect(
screen.queryByText(/no messages yet/i),
).not.toBeInTheDocument();
- // WorkingStatus shows BeamingHeadline in "beam" mode (no specific
- // tool/lifecycle info yet). The agent prefix is rendered alongside
- // a cycling verb; assert on the prefix since the verb rotates.
- expect(screen.getByText(/CMO/)).toBeInTheDocument();
+ // WorkingIndicator renders the agent display name as the accent
+ // header. With no events yet, mood is "waiting" and the headline
+ // is "<agent> is starting".
+ expect(screen.getByText("CMO")).toBeInTheDocument();
+ expect(screen.getByText(/is starting/i)).toBeInTheDocument();
});
});
diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsx
index 000baae6..54774d5f 100644
--- a/src/components/live-transcript.tsx
+++ b/src/components/live-transcript.tsx
@@ -28,7 +28,11 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Markdown } from "@/components/markdown";
import { RunningDot } from "@/components/running-dot";
-import { BeamingGlyph, BeamingHeadline } from "@/components/beaming-indicator";
+import {
+ WorkingIndicator,
+ type WorkingMood,
+ type WorkingPhase,
+} from "@/components/working-indicator";
import { SlashCommandPopover } from "@/components/slash-command-popover";
import { cn } from "@/lib/utils";
import {
@@ -502,7 +506,7 @@ export function LiveTranscript({
{blockedReason ? (
<BlockedStatus reason={blockedReason} />
) : (
- <WorkingStatus
+ <LiveWorkingIndicator
agentDisplayName={agentDisplayName}
events={events}
turnStartedAt={turnStartedAt}
@@ -1040,16 +1044,21 @@ function BlockedStatus({ reason }: { reason: string }) {
}
/**
- * Live "agent is working" indicator. Beyond just a pulse, surfaces:
- * - what phase we're in (starting / thinking / wrapping up / running a tool)
- * - the last tool the agent ran (so the user sees forward motion)
- * - elapsed time since the most recent transcript event (ticks every 1s)
- * - cumulative tool count so far
+ * LiveWorkingIndicator — the bottom-anchored "agent is working" card.
+ *
+ * Wraps the presentational WorkingIndicator with the project-specific
+ * logic: derive headline/subtitle/mood/phases from a mix of SSE-leading
+ * pending state and JSONL-trailing committed events, then drive the
+ * 1Hz elapsed counter. Kept inside live-transcript so the derivation
+ * has the full union of TranscriptEvent + ToolEntry types in scope
+ * without exporting either across the module boundary.
*
- * Falls back to a bare pulse when we have nothing more useful to say (e.g.
- * the SSE composer-send case where transcript events haven't landed yet).
+ * Replaces the old WorkingStatus that paired a small cyan ✳ with
+ * cycling verbs (Pondering / Cogitating / Effervescing …). The new
+ * indicator carries the same information in a denser, more vivid
+ * layout — see working-indicator.tsx for the visual treatment.
*/
-function WorkingStatus({
+function LiveWorkingIndicator({
agentDisplayName,
events,
turnStartedAt,
@@ -1059,35 +1068,9 @@ function WorkingStatus({
}: {
agentDisplayName: string;
events: TranscriptEvent[];
- /**
- * Wallclock when the current send/turn began. When present and more
- * recent than the latest event's ts, drives the elapsed counter — keeps
- * "elapsed" from showing the gap-since-the-previous-turn while the new
- * turn's first event hasn't been written to JSONL yet.
- */
turnStartedAt: number | null;
- /**
- * Most recent OpenClaw lifecycle phase (e.g. "run.start", "warming",
- * "compacting") for the in-flight turn. Used to give the user a more
- * specific status than "thinking…" during the pre-first-token wait,
- * which is the dominant chunk of latency for kickoffs against codex/
- * gpt-5.5 with a multi-KB system prompt.
- */
lifecyclePhase?: string | null;
- /**
- * Tool calls streamed via the active SSE connection. These can lead the
- * committed JSONL `events` list by a few seconds (the file is buffered
- * per turn in codex-app-server mode), so consulting both gives us a
- * more accurate "what's the agent doing right now?" headline while the
- * indicator sits at the bottom of the transcript.
- */
pendingTools?: ToolEntry[];
- /**
- * True when the active SSE stream has emitted at least one assistant
- * text delta — indicates the model is currently writing its response.
- * Drives a "Writing the response…" headline so the indicator's caption
- * matches what the user is watching scroll in above it.
- */
hasPendingAssistant?: boolean;
}) {
const [now, setNow] = useState<number>(() => Date.now());
@@ -1096,157 +1079,218 @@ function WorkingStatus({
return () => clearInterval(id);
}, []);
+ const view = deriveWorkingView({
+ agentDisplayName,
+ events,
+ lifecyclePhase: lifecyclePhase ?? null,
+ pendingTools: pendingTools ?? [],
+ hasPendingAssistant: hasPendingAssistant ?? false,
+ });
+
+ // Anchor elapsed to whichever is later: the turn-start wallclock the
+ // composer recorded, or the last event's timestamp. Keeps the counter
+ // honest during the SSE-only window where events are still empty.
const lastEvent = events.length > 0 ? events[events.length - 1] : null;
- const lastToolResult = [...events]
- .reverse()
- .find((e): e is Extract<TranscriptEvent, { kind: "tool_result" }> =>
- e.kind === "tool_result",
- );
- const inFlightToolCall = (() => {
- // Last tool_call with no later tool_result for the same id. ToolGroup
- // already shows this with a spinner — we mirror it here only when it's
- // the latest event so the working pulse reflects the same thing.
+ const anchorTs = (() => {
+ const lastTs = lastEvent?.ts ?? null;
+ if (turnStartedAt && lastTs) return Math.max(turnStartedAt, lastTs);
+ return turnStartedAt ?? lastTs;
+ })();
+ const elapsedMs = anchorTs != null ? Math.max(0, now - anchorTs) : null;
+
+ return (
+ <WorkingIndicator
+ agentDisplayName={agentDisplayName}
+ headline={view.headline}
+ subtitle={view.subtitle}
+ phases={view.phases}
+ mood={view.mood}
+ elapsedMs={elapsedMs}
+ />
+ );
+}
+
+type WorkingView = {
+ headline: string;
+ subtitle: string | null;
+ phases: WorkingPhase[];
+ mood: WorkingMood;
+};
+
+/**
+ * Build the visible state for the working indicator from the current
+ * SSE pending state + committed JSONL events.
+ *
+ * Precedence (most-specific first):
+ * 1. An SSE-pending tool start that hasn't reported a result → that's
+ * the active phase, mood "tool".
+ * 2. An SSE-pending assistant text stream → mood "writing".
+ * 3. No events yet (pre-first-token kickoff wait) → mood "waiting"
+ * with the gateway lifecycle hint as subtitle.
+ * 4. A committed in-flight tool_call → mood "tool" (polling caught up
+ * before the SSE state did, e.g. on rejoin from another tab).
+ * 5. Last committed event is a tool_result → mood "waiting".
+ * 6. Last committed event is assistant_text → mood "wrapping".
+ *
+ * Phases are derived from BOTH sources so the trajectory chips include
+ * recent SSE tools the JSONL hasn't seen yet, then dedupe by tool name.
+ */
+function deriveWorkingView(input: {
+ agentDisplayName: string;
+ events: TranscriptEvent[];
+ lifecyclePhase: string | null;
+ pendingTools: ToolEntry[];
+ hasPendingAssistant: boolean;
+}): WorkingView {
+ const { agentDisplayName, events, lifecyclePhase, pendingTools, hasPendingAssistant } = input;
+ const lastEvent = events.length > 0 ? events[events.length - 1] : null;
+ const pendingInFlightTool = pendingTools.find((t) => !t.done) ?? null;
+ const inFlightCommittedToolCall: Extract<
+ TranscriptEvent,
+ { kind: "tool_call" }
+ > | null = (() => {
if (!lastEvent || lastEvent.kind !== "tool_call") return null;
const matched = events.some(
(e) => e.kind === "tool_result" && e.tool_call_id === lastEvent.tool_call_id,
);
return matched ? null : lastEvent;
})();
- const toolsRun = events.reduce(
- (n, e) => n + (e.kind === "tool_result" ? 1 : 0),
- 0,
- );
+ const phases = buildPhases(events, pendingTools);
- // Pick the strongest "what's happening right now" signal across SSE
- // pending state (leads) and committed JSONL events (trails). During SSE
- // streaming, pendingTools / pendingAssistant know the truth seconds
- // before the file flushes. After polling catches up, `events` reflects
- // the same content. Either way the indicator at the bottom of the
- // transcript stays accurate.
- const pendingInFlightTool =
- pendingTools && pendingTools.length > 0
- ? pendingTools.find((t) => !t.done) ?? null
- : null;
- const pendingLastDoneTool =
- !pendingInFlightTool && pendingTools && pendingTools.length > 0
- ? [...pendingTools].reverse().find((t) => t.done) ?? null
- : null;
-
- // Two display modes:
- // - `beam`: cycle through "Pondering… / Cogitating… / Beaming…" verbs
- // with a morphing ✳ glyph. Used whenever we have nothing more
- // specific to say (pre-first-token wait, between tool calls). This
- // keeps the chat visibly alive during the 10-20s Codex pause that
- // used to read as "stuck".
- // - `static`: render a fixed headline + subtitle (specific tool in
- // flight, currently writing the response, last tool result, wrapping
- // up assistant text). The specific info is more useful than a quirky
- // verb, so we keep it.
- //
- // The leading glyph is morphing in both modes so the eye always has
- // something animating.
- let mode: "beam" | "static" = "beam";
- let headline: string = `${agentDisplayName} is thinking…`;
- let subtitle: string | null = null;
- let beamPrefix: string | null = agentDisplayName;
if (pendingInFlightTool) {
- // SSE-derived in-flight tool wins: most accurate live signal.
- mode = "static";
- headline = `Calling ${formatToolName(pendingInFlightTool.name)}…`;
- subtitle = pendingInFlightTool.label ?? null;
- } else if (hasPendingAssistant) {
- // Model is currently emitting assistant text via SSE. Match the user's
- // experience — they're watching text scroll in above the indicator.
- mode = "static";
- headline = `${agentDisplayName} is writing the response…`;
- subtitle = pendingLastDoneTool
- ? `Last step · ${formatToolName(pendingLastDoneTool.name)} ${pendingLastDoneTool.ok ? "✓" : "failed"}`
- : null;
- } else if (!lastEvent || lastEvent.kind === "user_message" || lastEvent.kind === "unknown") {
- // Pre-first-event window — typical kickoff wait. Use the gateway
- // lifecycle hint as the subtitle so power users see "calling the
- // model…" but the headline still gets the Beaming treatment.
- mode = "beam";
- beamPrefix = agentDisplayName;
+ return {
+ headline: `Calling ${formatToolName(pendingInFlightTool.name)}`,
+ subtitle: pendingInFlightTool.label ?? null,
+ phases,
+ mood: "tool",
+ };
+ }
+ if (hasPendingAssistant) {
+ return {
+ headline: "Writing the response",
+ subtitle: subtitleForLastTool(pendingTools, events),
+ phases,
+ mood: "writing",
+ };
+ }
+ if (!lastEvent || lastEvent.kind === "user_message" || lastEvent.kind === "unknown") {
const lifecycleSummary = lifecyclePhase
? humanLifecyclePhase(lifecyclePhase)
: null;
- subtitle = lifecycleSummary ?? "Delivering the brief to OpenClaw.";
- } else if (inFlightToolCall) {
- mode = "static";
- headline = `Calling ${formatToolName(inFlightToolCall.name)}…`;
- subtitle = inFlightToolCall.label ?? null;
- } else if (lastEvent.kind === "tool_result") {
- mode = "beam";
- beamPrefix = agentDisplayName;
- subtitle = lastEvent.ok
- ? `Last step · ${formatToolName(lastEvent.name)} ✓`
- : `Last step · ${formatToolName(lastEvent.name)} failed — retrying`;
- } else if (lastEvent.kind === "assistant_text") {
- mode = "static";
- headline = `${agentDisplayName} is wrapping up…`;
+ return {
+ headline: `${agentDisplayName} is starting`,
+ subtitle: lifecycleSummary ?? "Delivering the brief to OpenClaw",
+ phases,
+ mood: "waiting",
+ };
}
+ if (inFlightCommittedToolCall) {
+ return {
+ headline: `Calling ${formatToolName(inFlightCommittedToolCall.name)}`,
+ subtitle: inFlightCommittedToolCall.label ?? null,
+ phases,
+ mood: "tool",
+ };
+ }
+ if (lastEvent.kind === "tool_result") {
+ return {
+ headline: `${agentDisplayName} is thinking`,
+ subtitle: lastEvent.ok
+ ? `${formatToolName(lastEvent.name)} ✓ — picking next step`
+ : `${formatToolName(lastEvent.name)} failed — retrying`,
+ phases,
+ mood: "waiting",
+ };
+ }
+ // assistant_text
+ return {
+ headline: "Wrapping up",
+ subtitle: subtitleForLastTool(pendingTools, events),
+ phases,
+ mood: "wrapping",
+ };
+}
- const anchorTs = (() => {
- const lastTs = lastEvent?.ts ?? null;
- if (turnStartedAt && lastTs) return Math.max(turnStartedAt, lastTs);
- return turnStartedAt ?? lastTs;
- })();
- const elapsedMs = anchorTs != null ? Math.max(0, now - anchorTs) : null;
-
- return (
- <div className="flex items-start gap-2.5 rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 px-3 py-2 text-xs">
- <span className="mt-0.5">
- <BeamingGlyph />
- </span>
- <div className="min-w-0 flex-1 space-y-0.5">
- <div className="flex items-baseline gap-2">
- {mode === "beam" ? (
- <BeamingHeadline prefix={beamPrefix} />
- ) : (
- <span className="italic text-muted-foreground">{headline}</span>
- )}
- {elapsedMs != null && (
- <span className="tabular-nums text-[10px] text-muted-foreground/70">
- {formatElapsed(elapsedMs)}
- </span>
- )}
- </div>
- {(subtitle || toolsRun > 0) && (
- <div className="flex min-w-0 items-center gap-1.5 text-[10px] text-muted-foreground/80">
- {subtitle && (
- <span className="truncate font-mono">{subtitle}</span>
- )}
- {subtitle && toolsRun > 0 && <span aria-hidden>·</span>}
- {toolsRun > 0 && (
- <span className="tabular-nums">
- {toolsRun} tool{toolsRun === 1 ? "" : "s"} run
- </span>
- )}
- {!subtitle && lastToolResult && toolsRun > 0 && (
- <>
- <span aria-hidden>·</span>
- <span className="truncate font-mono">
- last · {formatToolName(lastToolResult.name)}
- </span>
- </>
- )}
- </div>
- )}
- </div>
- </div>
- );
+function subtitleForLastTool(
+ pendingTools: ToolEntry[],
+ events: TranscriptEvent[],
+): string | null {
+ const lastDonePending = [...pendingTools].reverse().find((t) => t.done);
+ if (lastDonePending) {
+ return `${formatToolName(lastDonePending.name)} ${lastDonePending.ok ? "✓" : "failed"}`;
+ }
+ const lastDoneCommitted = [...events]
+ .reverse()
+ .find((e): e is Extract<TranscriptEvent, { kind: "tool_result" }> =>
+ e.kind === "tool_result",
+ );
+ if (lastDoneCommitted) {
+ return `${formatToolName(lastDoneCommitted.name)} ${lastDoneCommitted.ok ? "✓" : "failed"}`;
+ }
+ return null;
}
-function formatElapsed(ms: number): string {
- if (ms < 1500) return "just now";
- const s = Math.floor(ms / 1000);
- if (s < 60) return `${s}s`;
- const m = Math.floor(s / 60);
- const rem = s % 60;
- if (m < 60) return rem === 0 ? `${m}m` : `${m}m ${rem}s`;
- const h = Math.floor(m / 60);
- return `${h}h ${m % 60}m`;
+/**
+ * Build the trajectory pills shown in the indicator. Order:
+ * 1. Committed tools (in order, deduped by tool_call_id).
+ * 2. SSE-pending tools not yet in the committed list.
+ * The last entry is the "active" one. Done entries get a check, the
+ * active one gets the mood-colored ring + wrench glyph.
+ */
+function buildPhases(
+ events: TranscriptEvent[],
+ pendingTools: ToolEntry[],
+): WorkingPhase[] {
+ const seen = new Set<string>();
+ const phases: WorkingPhase[] = [];
+
+ // Walk committed events to build phases in order.
+ const committedById = new Map<
+ string,
+ { name: string; done: boolean; ok: boolean }
+ >();
+ for (const e of events) {
+ if (e.kind === "tool_call") {
+ committedById.set(e.tool_call_id, { name: e.name, done: false, ok: true });
+ } else if (e.kind === "tool_result") {
+ const prev = committedById.get(e.tool_call_id);
+ if (prev) {
+ prev.done = true;
+ prev.ok = e.ok;
+ } else {
+ committedById.set(e.tool_call_id, { name: e.name, done: true, ok: e.ok });
+ }
+ }
+ }
+ for (const [id, t] of committedById) {
+ seen.add(id);
+ phases.push({
+ id,
+ label: formatToolName(t.name),
+ state: !t.done ? "active" : t.ok ? "done" : "failed",
+ });
+ }
+
+ // Then any SSE-pending tools the committed list doesn't have yet.
+ for (const t of pendingTools) {
+ if (seen.has(t.toolCallId)) continue;
+ phases.push({
+ id: t.toolCallId,
+ label: formatToolName(t.name),
+ state: !t.done ? "active" : t.ok ? "done" : "failed",
+ detail: t.label ?? null,
+ });
+ }
+
+ // If multiple phases are flagged "active" (shouldn't happen, but defend),
+ // demote all but the last so the visual stays clear.
+ let lastActive = -1;
+ for (let i = 0; i < phases.length; i++) {
+ if (phases[i]!.state === "active") lastActive = i;
+ }
+ return phases.map((p, i) =>
+ p.state === "active" && i !== lastActive ? { ...p, state: "done" } : p,
+ );
}
/**
diff --git a/src/components/working-indicator.test.tsx b/src/components/working-indicator.test.tsx
new file mode 100644
index 00000000..012871df
--- /dev/null
+++ b/src/components/working-indicator.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+
+import { WorkingIndicator, type WorkingPhase } from "./working-indicator";
+
+function basePhases(): WorkingPhase[] {
+ return [
+ { id: "1", label: "list_project_agents", state: "done" },
+ { id: "2", label: "summarizeAccountSetup", state: "done" },
+ { id: "3", label: "runScript", state: "active" },
+ ];
+}
+
+describe("WorkingIndicator", () => {
+ it("renders the agent name, headline, and elapsed readout", () => {
+ render(
+ <WorkingIndicator
+ agentDisplayName="CMO"
+ headline="Calling runScript"
+ subtitle={`{"accountId":"3251706605"}`}
+ phases={basePhases()}
+ elapsedMs={18_000}
+ mood="tool"
+ />,
+ );
+ expect(screen.getByText("CMO")).toBeInTheDocument();
+ expect(screen.getByText(/Calling runScript/)).toBeInTheDocument();
+ // The elapsed pill formats mm:ss when >= 1s and < 1min.
+ expect(screen.getByText(/0:18/)).toBeInTheDocument();
+ });
+
+ it("renders the trajectory chips (done + active)", () => {
+ render(
+ <WorkingIndicator
+ agentDisplayName="CMO"
+ headline="Calling runScript"
+ phases={basePhases()}
+ elapsedMs={0}
+ mood="tool"
+ />,
+ );
+ // Last 3 phases are visible by design (the trajectory cap).
+ expect(screen.getByText("list_project_agents")).toBeInTheDocument();
+ expect(screen.getByText("summarizeAccountSetup")).toBeInTheDocument();
+ // Multiple "runScript" text appearances may exist (chip + headline)
+ expect(screen.getAllByText("runScript").length).toBeGreaterThanOrEqual(1);
+ });
+
+ it("hides the elapsed pill when elapsedMs is null", () => {
+ render(
+ <WorkingIndicator
+ agentDisplayName="CMO"
+ headline="Starting"
+ phases={[]}
+ elapsedMs={null}
+ mood="waiting"
+ />,
+ );
+ // 0:00 / Nan etc shouldn't appear; the digital pill is gone entirely.
+ expect(screen.queryByText(/^\d+:\d{2}$/)).not.toBeInTheDocument();
+ });
+
+ it("formats elapsed as mm:ss past 60s", () => {
+ render(
+ <WorkingIndicator
+ agentDisplayName="CMO"
+ headline="Calling runScript"
+ phases={basePhases()}
+ elapsedMs={75_000}
+ mood="tool"
+ />,
+ );
+ expect(screen.getByText("1:15")).toBeInTheDocument();
+ });
+
+ it("uses mood-specific ring color (smoke test via class presence)", () => {
+ const { container, rerender } = render(
+ <WorkingIndicator
+ agentDisplayName="CMO"
+ headline="..."
+ phases={[]}
+ elapsedMs={0}
+ mood="waiting"
+ />,
+ );
+ expect(container.querySelector(".ring-sky-500\\/15")).not.toBeNull();
+ rerender(
+ <WorkingIndicator
+ agentDisplayName="CMO"
+ headline="..."
+ phases={[]}
+ elapsedMs={0}
+ mood="writing"
+ />,
+ );
+ expect(container.querySelector(".ring-emerald-500\\/15")).not.toBeNull();
+ });
+});
diff --git a/src/components/working-indicator.tsx b/src/components/working-indicator.tsx
new file mode 100644
index 00000000..1593be88
--- /dev/null
+++ b/src/components/working-indicator.tsx
@@ -0,0 +1,375 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Check, ChevronRight, Wrench } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+/**
+ * WorkingIndicator — the bottom-anchored "agent is doing work" card.
+ *
+ * Replaces the previous BeamingHeadline (cyan ✳ + cycling verb) that
+ * looked janky next to the rest of the UI. The new design is
+ * editorial-cockpit: a thin colored aurora bar across the top, a
+ * trajectory of phase chips (past tools → active step), an animated
+ * mood dot, a monospace subtitle for tool args, a digital elapsed
+ * readout, and a shimmer bar across the bottom. The mood color cycles
+ * by phase so a quick glance tells you where the agent is:
+ *
+ * - waiting (pre-first-token / between events): sky → cyan
+ * - tool in flight: violet → fuchsia
+ * - writing response: emerald → teal
+ * - wrapping up: amber → orange
+ *
+ * Everything past the trajectory chips is decoration; the chips
+ * themselves carry the real "what is happening right now" signal.
+ */
+
+export type WorkingPhase = {
+ /** Stable key so React reconciles correctly across renders. */
+ id: string;
+ /** Human-readable tool name (already display-formatted upstream). */
+ label: string;
+ /** Compact arg / detail line shown for the active phase. */
+ detail?: string | null;
+ state: "done" | "active" | "failed";
+};
+
+export type WorkingMood = "waiting" | "tool" | "writing" | "wrapping";
+
+export function WorkingIndicator({
+ agentDisplayName,
+ headline,
+ subtitle,
+ phases,
+ elapsedMs,
+ mood,
+}: {
+ agentDisplayName: string;
+ /** Primary sentence shown in the active row. */
+ headline: string;
+ /** Optional monospace context line (tool args, lifecycle phase). */
+ subtitle?: string | null;
+ /** Recent + active trajectory chips. Most recent right-most. */
+ phases: WorkingPhase[];
+ /** ms since the turn began. null = hide the readout. */
+ elapsedMs: number | null;
+ /** Drives the color story. */
+ mood: WorkingMood;
+}) {
+ const palette = MOOD_PALETTES[mood];
+ // Only show the last few phases — older ones scroll off-screen, the
+ // full transcript is the source of truth for history. Three keeps the
+ // strip dense without wrapping at common widths.
+ const visiblePhases = phases.slice(-3);
+
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-label={`${agentDisplayName} ${headline}`}
+ className={cn(
+ "relative overflow-hidden rounded-lg border bg-card/40 backdrop-blur-sm",
+ "ring-1 ring-inset",
+ palette.ring,
+ )}
+ >
+ {/* Aurora top edge — primary "alive" signal. */}
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 top-0 h-[2px] overflow-hidden"
+ >
+ <span
+ className={cn(
+ "absolute inset-y-0 left-0 w-1/3",
+ "motion-safe:animate-aurora-sweep",
+ )}
+ style={{
+ backgroundImage: `linear-gradient(to right, transparent, ${palette.beam}, transparent)`,
+ }}
+ />
+ </span>
+
+ <div className="flex items-start gap-3 px-3.5 py-2.5">
+ {/* Mood dot: scaling heartbeat with a soft halo. */}
+ <span
+ aria-hidden
+ className="relative mt-1 inline-flex h-2.5 w-2.5 shrink-0 items-center justify-center"
+ >
+ <span
+ className={cn(
+ "absolute inset-[-2px] rounded-full blur-sm",
+ palette.haloBg,
+ )}
+ />
+ <span
+ className={cn(
+ "relative inline-block h-2 w-2 rounded-full",
+ palette.dotBg,
+ "motion-safe:animate-heartbeat",
+ )}
+ />
+ </span>
+
+ <div className="min-w-0 flex-1 space-y-1.5">
+ {/* Active row: agent · headline + cycling verb fallback. */}
+ <div className="flex items-baseline gap-2 text-xs leading-tight">
+ <span className={cn("font-semibold", palette.accentText)}>
+ {agentDisplayName}
+ </span>
+ <span className="text-muted-foreground/60">·</span>
+ <span className="text-foreground/85">
+ {headline}
+ <BreathingDots />
+ </span>
+ </div>
+
+ {/* Subtitle: monospace context (tool args, lifecycle hint). */}
+ {subtitle && (
+ <div className="truncate font-mono text-[10.5px] tracking-tight text-muted-foreground/80">
+ {subtitle}
+ </div>
+ )}
+
+ {/* Trajectory chips — what's been done + what's active. */}
+ {visiblePhases.length > 0 && (
+ <ol className="-ml-0.5 flex flex-wrap items-center gap-1 pt-0.5">
+ {visiblePhases.map((phase, idx) => (
+ <li
+ key={phase.id}
+ className="flex items-center gap-1"
+ >
+ <PhaseChip phase={phase} palette={palette} />
+ {idx < visiblePhases.length - 1 && (
+ <ChevronRight
+ className="size-3 text-muted-foreground/35"
+ aria-hidden
+ />
+ )}
+ </li>
+ ))}
+ </ol>
+ )}
+ </div>
+
+ {/* Elapsed readout — small digital pill, right aligned. */}
+ {elapsedMs != null && (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center rounded border px-1.5 py-0.5",
+ "border-border/40 bg-background/70",
+ "font-mono text-[10px] tabular-nums tracking-wider",
+ "text-muted-foreground",
+ )}
+ >
+ {formatElapsed(elapsedMs)}
+ </span>
+ )}
+ </div>
+
+ {/* Shimmer bottom edge — continuous motion when waiting. */}
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-[1.5px] overflow-hidden"
+ >
+ <span
+ className={cn(
+ "absolute inset-y-0 left-0 w-1/4 opacity-70",
+ "motion-safe:animate-shimmer-bar",
+ )}
+ style={{
+ backgroundImage: `linear-gradient(to right, transparent, ${palette.beam}, transparent)`,
+ }}
+ />
+ </span>
+ </div>
+ );
+}
+
+function PhaseChip({
+ phase,
+ palette,
+}: {
+ phase: WorkingPhase;
+ palette: MoodPalette;
+}) {
+ if (phase.state === "done") {
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center gap-1 rounded-full px-1.5 py-0.5",
+ "bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",
+ )}
+ >
+ <Check className="size-2.5" aria-hidden />
+ <span className="max-w-[12rem] truncate font-mono text-[10px]">
+ {phase.label}
+ </span>
+ </span>
+ );
+ }
+ if (phase.state === "failed") {
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center gap-1 rounded-full px-1.5 py-0.5",
+ "bg-destructive/10 text-destructive",
+ )}
+ >
+ <span className="size-1.5 rounded-full bg-destructive" aria-hidden />
+ <span className="max-w-[12rem] truncate font-mono text-[10px]">
+ {phase.label}
+ </span>
+ </span>
+ );
+ }
+ // active
+ return (
+ <span
+ className={cn(
+ "relative inline-flex items-center gap-1 rounded-full px-1.5 py-0.5",
+ "ring-1 ring-inset",
+ palette.chipBg,
+ palette.chipText,
+ palette.chipRing,
+ )}
+ >
+ <Wrench className="size-2.5" aria-hidden />
+ <span className="max-w-[14rem] truncate font-mono text-[10px] font-medium">
+ {phase.label}
+ </span>
+ {/* tiny in-chip pulse ring */}
+ <span
+ aria-hidden
+ className={cn(
+ "absolute inset-0 rounded-full ring-1 ring-inset",
+ palette.chipRing,
+ "motion-safe:animate-phase-glow",
+ )}
+ />
+ </span>
+ );
+}
+
+/**
+ * Trailing three-dot animation. Smooth amplitude pulse on each dot
+ * staggered by ~150 ms — reads as a wave traveling left-to-right.
+ * Done with state instead of CSS because we want each dot to be
+ * independent of the others (a single keyframe applied to all three
+ * would have them all pulse together, which is harsher).
+ */
+function BreathingDots() {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ const id = setInterval(() => setTick((t) => (t + 1) % 6), 220);
+ return () => clearInterval(id);
+ }, []);
+ return (
+ <span aria-hidden className="ml-0.5 inline-flex gap-[2px]">
+ {[0, 1, 2].map((i) => (
+ <span
+ key={i}
+ className="inline-block h-1 w-1 rounded-full bg-current"
+ style={{
+ opacity: dotOpacity(tick, i),
+ transform: `translateY(${dotOffset(tick, i)}px)`,
+ transition: "opacity 200ms ease, transform 200ms ease",
+ }}
+ />
+ ))}
+ </span>
+ );
+}
+
+function dotOpacity(tick: number, i: number): number {
+ // Each dot peaks 2 ticks apart, gives a wave-like feel.
+ const phase = (tick - i + 6) % 6;
+ if (phase === 0) return 1;
+ if (phase === 1 || phase === 5) return 0.7;
+ return 0.3;
+}
+
+function dotOffset(tick: number, i: number): number {
+ const phase = (tick - i + 6) % 6;
+ if (phase === 0) return -1;
+ return 0;
+}
+
+function formatElapsed(ms: number): string {
+ const totalSec = Math.floor(ms / 1000);
+ if (totalSec < 60) return `0:${totalSec.toString().padStart(2, "0")}`;
+ const m = Math.floor(totalSec / 60);
+ const s = totalSec % 60;
+ return `${m}:${s.toString().padStart(2, "0")}`;
+}
+
+// ────────────────────────────────────────────────────────────────────
+// Mood palettes
+//
+// Tailwind classnames are static (so the JIT can pick them up) but
+// the inline-gradient `beam` color is a raw hex/HSL because the
+// gradient is built via inline style. Keeping the two in lockstep is
+// the whole point of bundling them per-mood — change a mood's vibe
+// here and the dot, halo, chip, beam, and shimmer all update together.
+
+type MoodPalette = {
+ /** Outermost ring around the card. */
+ ring: string;
+ /** Filled mood dot background. */
+ dotBg: string;
+ /** Soft glow behind the dot. */
+ haloBg: string;
+ /** Active phase chip background. */
+ chipBg: string;
+ /** Active phase chip text. */
+ chipText: string;
+ /** Active phase chip ring. */
+ chipRing: string;
+ /** Agent name accent text color. */
+ accentText: string;
+ /** Inline-style gradient stop for the aurora + shimmer bars. */
+ beam: string;
+};
+
+const MOOD_PALETTES: Record<WorkingMood, MoodPalette> = {
+ waiting: {
+ ring: "ring-sky-500/15",
+ dotBg: "bg-sky-500",
+ haloBg: "bg-sky-400/40",
+ chipBg: "bg-sky-500/10",
+ chipText: "text-sky-700 dark:text-sky-300",
+ chipRing: "ring-sky-500/30",
+ accentText: "text-sky-700 dark:text-sky-300",
+ beam: "hsl(199 89% 60%)",
+ },
+ tool: {
+ ring: "ring-violet-500/15",
+ dotBg: "bg-violet-500",
+ haloBg: "bg-violet-400/40",
+ chipBg: "bg-violet-500/10",
+ chipText: "text-violet-700 dark:text-violet-300",
+ chipRing: "ring-violet-500/30",
+ accentText: "text-violet-700 dark:text-violet-300",
+ beam: "hsl(258 90% 66%)",
+ },
+ writing: {
+ ring: "ring-emerald-500/15",
+ dotBg: "bg-emerald-500",
+ haloBg: "bg-emerald-400/40",
+ chipBg: "bg-emerald-500/10",
+ chipText: "text-emerald-700 dark:text-emerald-300",
+ chipRing: "ring-emerald-500/30",
+ accentText: "text-emerald-700 dark:text-emerald-300",
+ beam: "hsl(160 84% 45%)",
+ },
+ wrapping: {
+ ring: "ring-amber-500/15",
+ dotBg: "bg-amber-500",
+ haloBg: "bg-amber-400/40",
+ chipBg: "bg-amber-500/10",
+ chipText: "text-amber-700 dark:text-amber-300",
+ chipRing: "ring-amber-500/30",
+ accentText: "text-amber-700 dark:text-amber-300",
+ beam: "hsl(38 92% 55%)",
+ },
+};