fix(web): let the view decide the blink, not the CSS colour class

A dot's animation was keyed on its colour class plus a component wrapper:
`html[data-pi-blink-fast="dim"] .tree-row .dot--ok` made green blink only inside
the session tree, `.dot--busy`/`.dot--err` blazed everywhere they appeared, and
`dot--steady` existed only to subtract what that selector had just added. Two
consequences the matrix in docs/session-dot.md already forbids: a failed task's
red blinked forever with no gesture to acknowledge it, and the same session
could blink in the list and sit solid in the stream head.

`DotView` now carries the rate (`blink: "fast" | "slow"`, omitted = solid) next
to the colour, and `<StatusDot>` renders it as `dot--blink-fast` /
`dot--blink-slow`. `dot--steady` is gone — to make a dot solid you omit `blink`.
app.css keeps exactly two dim rules, with no colour or component scoping and no
knowledge of *whether* anything blinks, only of when the shared clock dims it.

Filling in the matrix this exposed: parent `err`/`ok`/`busy` blink fast and
`compacting` slow; a viewed child or subagent failure is solid while an unviewed
one blinks; `interrupted` is the same solid dead red as `exited` (the plugin has
no interrupted, and in the plugin `exited` outranks its own unread flags —
`sessionDot(active)` is now rendered `viewed: true` for the stream head, so one
session can never show two different rates); task dots follow `:PiTasks`
(`taskDotView`, shared by the tray and the output modal) where only `running`
blinks, `completed` is solid green and `stopped` is amber attention. The
`/status` task card renders the same colours, solid, since nothing there
acknowledges anything.
This commit is contained in:
yuez committed 2026-10-28 08:14:25 +08:00
1 parent 604fec5ea0
commit e7ce064817
16 files changed
+660 -141

No files matched your search

+29 -4
View File
@@ -3,6 +3,17 @@ import { cn } from "@/lib/utils";
/** Status-dot vocabulary from the design's `:PiSessions` state matrix. */ /** Status-dot vocabulary from the design's `:PiSessions` state matrix. */
export type DotStatus = "busy" | "compacting" | "idle" | "ok" | "err" | "attention" | "exited" | "dead"; export type DotStatus = "busy" | "compacting" | "idle" | "ok" | "err" | "attention" | "exited" | "dead";
/**
* Blink rate, in shared-clock phases (`web/src/lib/blink.ts`): `fast` follows
* `data-pi-blink-fast` (500ms), `slow` follows `data-pi-blink-slow` (1000ms).
*/
export type BlinkRate = "fast" | "slow";
/**
* Colour only. Whether a dot blinks is NOT encoded here: `dot--busy` is amber
* whether it pulses (a running turn) or not (a startup `connecting` chip), so a
* class-keyed dim rule cannot express the matrix. `blink` carries it instead.
*/
export const DOT_CLASS: Record<DotStatus, string> = { export const DOT_CLASS: Record<DotStatus, string> = {
busy: "dot--busy", busy: "dot--busy",
compacting: "dot--compacting", compacting: "dot--compacting",
@@ -14,6 +25,11 @@ export const DOT_CLASS: Record<DotStatus, string> = {
dead: "dot--dead", dead: "dot--dead",
}; };
export const BLINK_CLASS: Record<BlinkRate, string> = {
fast: "dot--blink-fast",
slow: "dot--blink-slow",
};
export type ServerStatus = "online" | "degraded" | "offline"; export type ServerStatus = "online" | "degraded" | "offline";
/** Server / connection status mapping (online → ok, degraded → attention, else exited). */ /** Server / connection status mapping (online → ok, degraded → attention, else exited). */
@@ -27,20 +43,29 @@ export function serverDotClass(status: ServerStatus | string | null | undefined)
export interface StatusDotProps { export interface StatusDotProps {
status: DotStatus; status: DotStatus;
/**
* Blink rate decided by the *view* that owns the dot (`DotView.blink`), never
* by the DOM location or the colour class. Omitted/`null` = solid.
*/
blink?: BlinkRate | null;
title?: string; title?: string;
className?: string; className?: string;
/** Pin the dot solid (no blink) — nvim's "focused child error is steady red". */
steady?: boolean;
/** "You are here" overlay (nvim `PiSessionsListCurrent`, agent blue). */ /** "You are here" overlay (nvim `PiSessionsListCurrent`, agent blue). */
current?: boolean; current?: boolean;
/** Decorative by default; pass a title to expose the state to assistive tech. */ /** Decorative by default; pass a title to expose the state to assistive tech. */
"aria-hidden"?: boolean; "aria-hidden"?: boolean;
} }
export function StatusDot({ status, title, className, steady, current, ...rest }: StatusDotProps) { export function StatusDot({ status, blink, title, className, current, ...rest }: StatusDotProps) {
return ( return (
<span <span
className={cn("dot", DOT_CLASS[status], steady && "dot--steady", current && "dot--current", className)} className={cn(
"dot",
DOT_CLASS[status],
blink ? BLINK_CLASS[blink] : null,
current && "dot--current",
className,
)}
title={title} title={title}
aria-label={title} aria-label={title}
aria-hidden={title ? undefined : true} aria-hidden={title ? undefined : true}
+2 -1
View File
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Icon } from "@/components/icons"; import { Icon } from "@/components/icons";
import { StatusDot } from "@/components/ui/status-dot";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { TrayTab } from "./store"; import type { TrayTab } from "./store";
@@ -80,7 +81,7 @@ export function HeadChips({
> >
<Icon name="terminal" /> <Icon name="terminal" />
<span className="head-chip__label">{t("chat.tabTasks")}</span> <span className="head-chip__label">{t("chat.tabTasks")}</span>
{running ? <span className="dot dot--busy" aria-hidden="true" /> : null} {running ? <StatusDot status="busy" blink="fast" /> : null}
<span className="head-chip__count tabular">{taskCount}</span> <span className="head-chip__count tabular">{taskCount}</span>
</button> </button>
</div> </div>
+4 -1
View File
@@ -6,12 +6,14 @@ import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog"; import { Modal } from "@/components/ui/dialog";
import { KV } from "@/components/ui/kv"; import { KV } from "@/components/ui/kv";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
import { StatusDot } from "@/components/ui/status-dot";
import { toast } from "@/components/ui/toast"; import { toast } from "@/components/ui/toast";
import { ApiError, errorI18nKey } from "@/lib/api"; import { ApiError, errorI18nKey } from "@/lib/api";
import { chatCommands, runCommand } from "./commands"; import { chatCommands, runCommand } from "./commands";
import type { ModelGroup } from "./data"; import type { ModelGroup } from "./data";
import { withCurrentModel } from "./data"; import { withCurrentModel } from "./data";
import { formatDuration, THINKING_LEVELS } from "./format"; import { formatDuration, THINKING_LEVELS } from "./format";
import { taskDotView } from "./session-tray";
function rec(value: unknown): Record<string, unknown> | undefined { function rec(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined; return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
@@ -259,6 +261,7 @@ export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOu
if (!task) return null; if (!task) return null;
const status = result?.status ?? task.status; const status = result?.status ?? task.status;
const running = status === "running"; const running = status === "running";
const dot = taskDotView(status);
const duration = result?.durationMs ?? (running ? Date.now() - task.startTime : (task.durationMs ?? 0)); const duration = result?.durationMs ?? (running ? Date.now() - task.startTime : (task.durationMs ?? 0));
const exitCode = result?.exitCode !== undefined ? result.exitCode : (task.exitCode ?? null); const exitCode = result?.exitCode !== undefined ? result.exitCode : (task.exitCode ?? null);
const outputFile = result?.outputFile ?? task.outputFile; const outputFile = result?.outputFile ?? task.outputFile;
@@ -295,7 +298,7 @@ export function TaskOutputModal({ open, session, task, onClose, onStop }: TaskOu
<div> <div>
<KV label={t("chat.status")}> <KV label={t("chat.status")}>
<span className="row"> <span className="row">
<span className={`dot ${running ? "dot--busy" : status === "completed" ? "dot--ok" : status === "failed" ? "dot--err" : "dot--idle"}`} /> <StatusDot status={dot.status} blink={dot.blink} />
{t(`state.${status}`)} {t(`state.${status}`)}
</span> </span>
</KV> </KV>
+23 -12
View File
@@ -1,6 +1,6 @@
import { applyEvent, createReducer, type Reducer } from "@protocol/reducer"; import { applyEvent, createReducer, type Reducer } from "@protocol/reducer";
import type { Entry, ModelRef, SessionEvent, SessionState, ThinkingLevel } from "@protocol/types"; import type { Entry, ModelRef, SessionEvent, SessionState, ThinkingLevel } from "@protocol/types";
import type { DotStatus } from "@/components/ui/status-dot"; import type { BlinkRate, DotStatus } from "@/components/ui/status-dot";
import { normalizeTodos, projectEntries, type ProjectedEntry } from "@/lib/entry-projection"; import { normalizeTodos, projectEntries, type ProjectedEntry } from "@/lib/entry-projection";
const EMPTY_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }; const EMPTY_USAGE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
@@ -509,12 +509,14 @@ function attentionPending(state: SessionState): boolean {
} }
/** /**
* A dot render decision: the base status plus the two overlay modifiers. * A dot render decision: the colour, its blink rate and the "you are here"
* `steady` pins the dot solid, `current` paints the "you are here" overlay. * overlay. `blink` is the *only* place the animation is decided — the renderer
* never infers it from the colour class or from where the dot is mounted — and
* omitting it means the dot is solid.
*/ */
export interface DotView { export interface DotView {
status: DotStatus; status: DotStatus;
steady?: boolean; blink?: BlinkRate;
current?: boolean; current?: boolean;
} }
@@ -531,7 +533,10 @@ function withCurrent(view: DotView, state: SessionState, viewed: boolean): DotVi
// The plugin's `markable` is a positive list: only a live session carries the // The plugin's `markable` is a positive list: only a live session carries the
// marker, and a `compacting` one blinks at the busy rate under it. // marker, and a `compacting` one blinks at the busy rate under it.
if (state.status !== "idle" && state.status !== "busy" && state.status !== "compacting") return view; if (state.status !== "idle" && state.status !== "busy" && state.status !== "compacting") return view;
return { current: true, status: state.status === "compacting" ? "busy" : view.status }; // The rate follows the painted status, so a focused compacting row blinks at
// the busy rate (fast) instead of half speed, exactly like the plugin.
if (state.status === "compacting") return { current: true, status: "busy", blink: "fast" };
return { ...view, current: true };
} }
/** /**
@@ -545,11 +550,11 @@ function parentDot(state: SessionState): DotView {
// plugin every "not running" row is `exited` (sessions.lua:75-78), which is // plugin every "not running" row is `exited` (sessions.lua:75-78), which is
// why a dead row outranks its own unread error/attention/done flags. // why a dead row outranks its own unread error/attention/done flags.
if (state.status === "exited" || state.status === "interrupted") return { status: "dead" }; if (state.status === "exited" || state.status === "interrupted") return { status: "dead" };
if (state.flags.error) return { status: "err" }; if (state.flags.error) return { status: "err", blink: "fast" };
if (attentionPending(state)) return { status: "attention" }; if (attentionPending(state)) return { status: "attention" };
if (state.flags.done) return { status: "ok" }; if (state.flags.done) return { status: "ok", blink: "fast" };
if (state.status === "busy") return { status: "busy" }; if (state.status === "busy") return { status: "busy", blink: "fast" };
if (state.status === "compacting") return { status: "compacting" }; if (state.status === "compacting") return { status: "compacting", blink: "slow" };
return { status: "idle" }; return { status: "idle" };
} }
@@ -569,8 +574,8 @@ export function sessionDot(state: SessionState, opts: { viewed?: boolean } = {})
function childDot(state: SessionState, viewed: boolean): DotView { function childDot(state: SessionState, viewed: boolean): DotView {
if (state.status === "exited") return { status: "exited" }; if (state.status === "exited") return { status: "exited" };
if (state.status === "interrupted") return { status: "dead" }; if (state.status === "interrupted") return { status: "dead" };
if (state.flags.error) return { status: "err", steady: viewed }; if (state.flags.error) return viewed ? { status: "err" } : { status: "err", blink: "fast" };
if (state.status === "busy" || state.status === "compacting") return { status: "busy" }; if (state.status === "busy" || state.status === "compacting") return { status: "busy", blink: "fast" };
return { status: "idle" }; return { status: "idle" };
} }
@@ -591,12 +596,18 @@ export function subagentDot(
): DotView { ): DotView {
switch (subagent.status) { switch (subagent.status) {
case "active": case "active":
// A manifest entry with a live session is rendered as *that* session
// row, so this branch only ever sees a manifest nothing live owns (a
// spawn in flight, or a stale entry). The plugin colours a child by its
// live status (`sessions.lua` `append_child_row`) and blinks only the
// live busy one, so the amber is informative but must stay solid —
// nothing acknowledges a manifest blink and it would blink forever.
return { status: "busy" }; return { status: "busy" };
case "completed": case "completed":
case "dormant": case "dormant":
return { status: "exited" }; return { status: "exited" };
case "failed": case "failed":
return { status: "err", steady: opts.viewed === true }; return opts.viewed === true ? { status: "err" } : { status: "err", blink: "fast" };
case "interrupted": case "interrupted":
return { status: "dead" }; return { status: "dead" };
default: default:
+17 -7
View File
@@ -6,11 +6,12 @@ import { Icon } from "@/components/icons";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Empty } from "@/components/ui/empty"; import { Empty } from "@/components/ui/empty";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { StatusDot, type DotStatus } from "@/components/ui/status-dot"; import { StatusDot } from "@/components/ui/status-dot";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { TodoList } from "./blocks"; import { TodoList } from "./blocks";
import { formatDuration } from "./format"; import { formatDuration } from "./format";
import type { DotView } from "./session-state";
import { subagentTitle } from "./session-title"; import { subagentTitle } from "./session-title";
import type { TrayTab } from "./store"; import type { TrayTab } from "./store";
@@ -36,11 +37,19 @@ export interface SessionTrayProps {
const TABS: TrayTab[] = ["todo", "tasks"]; const TABS: TrayTab[] = ["todo", "tasks"];
function taskDot(status: TaskItem["status"]): DotStatus { /**
if (status === "running") return "busy"; * `:PiTasks` (`lua/pi/ui/tasks.lua` `dot_hl`) parity, shared with the
if (status === "completed") return "ok"; * task-output modal: only a *running* task blinks. A finished task is solid —
if (status === "failed") return "err"; * a `completed` green is not an unread notification, and a `failed` red has no
return "idle"; * acknowledgement path, so blinking it would blink forever next to session dots
* that the user has already seen.
*/
export function taskDotView(status: TaskItem["status"]): DotView {
if (status === "running") return { status: "busy", blink: "fast" };
if (status === "completed") return { status: "ok" };
if (status === "failed") return { status: "err" };
if (status === "stopped") return { status: "attention" };
return { status: "idle" };
} }
/** /**
@@ -274,9 +283,10 @@ export function SessionTray({
{tasks.map((task) => { {tasks.map((task) => {
const running = task.status === "running"; const running = task.status === "running";
const duration = running ? Date.now() - task.startTime : task.durationMs; const duration = running ? Date.now() - task.startTime : task.durationMs;
const dot = taskDotView(task.status);
return ( return (
<div key={task.id} className="task-row" data-task-id={task.id}> <div key={task.id} className="task-row" data-task-id={task.id}>
<StatusDot status={taskDot(task.status)} /> <StatusDot status={dot.status} blink={dot.blink} />
<button <button
type="button" type="button"
className="task-row__main" className="task-row__main"
+2 -2
View File
@@ -213,7 +213,7 @@ export function SessionTree({
aria-current={selected ? "true" : undefined} aria-current={selected ? "true" : undefined}
onClick={() => onSelectSession(session.sessionId)} onClick={() => onSelectSession(session.sessionId)}
> >
<StatusDot status={dot.status} steady={dot.steady} current={dot.current} /> <StatusDot status={dot.status} blink={dot.blink} current={dot.current} />
{title.spinner ? <SessionTitleSpinner /> : null} {title.spinner ? <SessionTitleSpinner /> : null}
<span <span
className={cn( className={cn(
@@ -280,7 +280,7 @@ export function SessionTree({
data-sub-id={subagent.id} data-sub-id={subagent.id}
onClick={() => onSelectSubagent(session.sessionId, subagent.id)} onClick={() => onSelectSubagent(session.sessionId, subagent.id)}
> >
<StatusDot status={dot.status} steady={dot.steady} /> <StatusDot status={dot.status} blink={dot.blink} />
<span <span
className={cn( className={cn(
"t-name truncate", "t-name truncate",
+1 -5
View File
@@ -279,11 +279,7 @@ export function SubagentView({
<span className="sub-back__label">{t("chat.subview.back")}</span> <span className="sub-back__label">{t("chat.subview.back")}</span>
</button> </button>
<div className="stream-title"> <div className="stream-title">
<StatusDot <StatusDot status={dot.status} blink={dot.blink} title={t(`state.${subagent.status}`)} />
status={dot.status}
steady={dot.steady}
title={t(`state.${subagent.status}`)}
/>
<h2 className="stream-name truncate" tabIndex={-1} title={task ? `${name} · ${task}` : name}> <h2 className="stream-name truncate" tabIndex={-1} title={task ? `${name} · ${task}` : name}>
{name} {name}
</h2> </h2>
+1 -1
View File
@@ -188,7 +188,7 @@ export function Telemetry({ session, subagent, entries, className }: TelemetryPr
data-testid="telemetry" data-testid="telemetry"
> >
<span className={cn("telemetry__state", "sub-state", tone)} data-testid="telemetry-state"> <span className={cn("telemetry__state", "sub-state", tone)} data-testid="telemetry-state">
<StatusDot status={dot.status} steady={dot.steady} /> <StatusDot status={dot.status} blink={dot.blink} />
{t(`state.${subagent.status}`)} {t(`state.${subagent.status}`)}
</span> </span>
{elapsed ? ( {elapsed ? (
+4 -1
View File
@@ -8,11 +8,14 @@ import { ErrorBlock, LoadingBlock, StatusCard, StatusEmpty } from "./card-parts"
export type { StatusTask }; export type { StatusTask };
/** `:PiTasks` (`lua/pi/ui/tasks.lua` `dot_hl`) vocabulary — the same colours the
* chat tray renders through `taskDotView`; this card just never blinks (a
* monitoring report has no acknowledgement gesture). */
const TASK_DOT: Record<string, DotStatus> = { const TASK_DOT: Record<string, DotStatus> = {
running: "busy", running: "busy",
completed: "ok", completed: "ok",
failed: "err", failed: "err",
stopped: "exited", stopped: "attention",
}; };
export interface TasksCardProps { export interface TasksCardProps {
+11 -2
View File
@@ -126,6 +126,10 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
if (!viewedSessionId || (!viewedDone && !viewedError)) return; if (!viewedSessionId || (!viewedDone && !viewedError)) return;
useSessionsStore.getState().markSeen(viewedSessionId); useSessionsStore.getState().markSeen(viewedSessionId);
}, [viewedSessionId, viewedDone, viewedError]); }, [viewedSessionId, viewedDone, viewedError]);
// The stream head shows the same session the selected tree row does, so it
// renders that row's `DotView` (`viewed: true`) rather than re-deriving a
// colour: one session must never show two different blink rates.
const headDot = active ? sessionDot(active, { viewed: true }) : null;
const history = useSessionHistory( const history = useSessionHistory(
active?.sessionId, active?.sessionId,
active?.entries ?? NO_ENTRIES, active?.entries ?? NO_ENTRIES,
@@ -544,8 +548,13 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
</button> </button>
) : null} ) : null}
<div className="stream-title"> <div className="stream-title">
{active ? ( {active && headDot ? (
<StatusDot status={sessionDot(active).status} title={t(`state.${sessionStatusKey(active)}`)} /> <StatusDot
status={headDot.status}
blink={headDot.blink}
current={headDot.current}
title={t(`state.${sessionStatusKey(active)}`)}
/>
) : null} ) : null}
<h2 className="stream-name truncate" tabIndex={-1} ref={streamNameRef}> <h2 className="stream-name truncate" tabIndex={-1} ref={streamNameRef}>
{active ? activeTitle?.text : (workspace?.name ?? t("nav.chat"))} {active ? activeTitle?.text : (workspace?.name ?? t("nav.chat"))}
+12 -5
View File
@@ -387,13 +387,20 @@ code, pre { font-family: var(--font-mono); font-size: 0.875em; }
.dot--dead { background: var(--err); } .dot--dead { background: var(--err); }
.dot--attention { background: var(--warn); box-shadow: 0 0 0 2px color-mix(in oklch, var(--warn) 22%, transparent); } .dot--attention { background: var(--warn); box-shadow: 0 0 0 2px color-mix(in oklch, var(--warn) 22%, transparent); }
.dot--exited { background: transparent; box-shadow: inset 0 0 0 1.5px var(--muted-foreground); } .dot--exited { background: transparent; box-shadow: inset 0 0 0 1.5px var(--muted-foreground); }
/* "You are here" (nvim `PiSessionsListCurrent`): agent blue wherever the dot is
mounted, so the stream-head dot and its list row cannot disagree. Scoping this
to `.tree-row` would leave the head's `dot--current` inert. */
.dot--current { background: var(--info); }
@keyframes pulse { 50% { opacity: .35; } } @keyframes pulse { 50% { opacity: .35; } }
/* Shared blink phase driven by html[data-pi-blink-*] attributes (single window clock) */ /* One blink contract. The <html> attributes are the shared clock (lib/blink.ts);
html[data-pi-blink-fast="dim"] .dot--busy:not(.dot--steady), whether a dot participates — and at which rate — is decided once, by the view
html[data-pi-blink-fast="dim"] .dot--err:not(.dot--steady), that renders it (`DotView.blink` → `.dot--blink-fast` / `.dot--blink-slow`).
html[data-pi-blink-fast="dim"] .tree-row .dot--ok { opacity: .35; } Nothing here may key on a colour class or on a component wrapper: the same
html[data-pi-blink-slow="dim"] .dot--compacting:not(.dot--steady) { opacity: .35; } status must blink the same in the session list, the stream head, a task row
or a dialog. A dot without a `dot--blink-*` class is solid. */
html[data-pi-blink-fast="dim"] .dot--blink-fast,
html[data-pi-blink-slow="dim"] .dot--blink-slow { opacity: .35; }
.chip { .chip {
display: inline-flex; align-items: center; gap: var(--space-2); display: inline-flex; align-items: center; gap: var(--space-2);
+2 -4
View File
@@ -446,10 +446,8 @@
} }
/* 状态圆点:由 <html> 根节点上的单一全局时钟驱动(data-pi-blink-* 属性,见 app.css 与 blink.ts), /* 状态圆点:由 <html> 根节点上的单一全局时钟驱动(data-pi-blink-* 属性,见 app.css 与 blink.ts),
不再使用每个圆点独立的 CSS animation,避免相位漂移。当前聚焦会话叠加高亮背景。 */ 不再使用每个圆点独立的 CSS animation,避免相位漂移。当前会话的蓝色标记在 app.css 的
.tree-row .dot--current { `.dot--current`(不按容器限定:流头圆点与列表行必须同色)。 */
background: var(--info);
}
/* 子会话 / 子代理行:更矮、更小、灰一档;状态只由圆点表达。 */ /* 子会话 / 子代理行:更矮、更小、灰一档;状态只由圆点表达。 */
.tree-row--sub .tree-row__main { .tree-row--sub .tree-row__main {
+50 -9
View File
@@ -188,34 +188,55 @@ describe("session tree rows", () => {
expect(s3Dot).toHaveClass("dot", "dot--ok"); expect(s3Dot).toHaveClass("dot", "dot--ok");
expect(s3Dot).not.toHaveClass("dot--current"); expect(s3Dot).not.toHaveClass("dot--current");
// 2. Child exited row renders hollow dot--exited (never dead red). // 2. Child exited row renders hollow dot--exited (never dead red, never blinking).
const c1Dot = rowMain("c1").querySelector(".dot"); const c1Dot = rowMain("c1").querySelector(".dot");
expect(c1Dot).toHaveClass("dot", "dot--exited"); expect(c1Dot).toHaveClass("dot", "dot--exited");
expect(c1Dot).not.toHaveClass("dot--dead"); expect(c1Dot).not.toHaveClass("dot--dead");
expect(c1Dot).not.toHaveClass("dot--current"); expect(c1Dot).not.toHaveClass("dot--current");
expect(c1Dot).not.toHaveClass("dot--blink-fast");
// 3. Child error row unselected renders dot--err without steady modifier. // 3. Child error row unselected renders dot--err + dot--blink-fast in the list.
const c2DotUnselected = rowMain("c2").querySelector(".dot"); const c2DotUnselected = rowMain("c2").querySelector(".dot");
expect(c2DotUnselected).toHaveClass("dot", "dot--err"); expect(c2DotUnselected).toHaveClass("dot", "dot--err", "dot--blink-fast");
expect(c2DotUnselected).not.toHaveClass("dot--steady"); expect(c2DotUnselected).not.toHaveClass("dot--blink-slow");
// 4. Selected idle row renders dot--current (and dot--idle when done flag consumed). // 4. Selected idle row renders dot--current (and dot--idle when done flag consumed).
rerender(treeElement({ sessions, selectedId: "s2" })); rerender(treeElement({ sessions, selectedId: "s2" }));
const s2DotSelected = rowMain("s2").querySelector(".dot"); const s2DotSelected = rowMain("s2").querySelector(".dot");
expect(s2DotSelected).toHaveClass("dot", "dot--idle", "dot--current"); expect(s2DotSelected).toHaveClass("dot", "dot--idle", "dot--current");
expect(s2DotSelected).not.toHaveClass("dot--steady"); // A focused idle session is solid.
expect(s2DotSelected).not.toHaveClass("dot--blink-fast");
expect(s2DotSelected).not.toHaveClass("dot--blink-slow");
// 5. Selected busy row renders dot--busy + dot--current. // 5. Selected busy row renders dot--busy + dot--current and keeps blinking.
rerender(treeElement({ sessions, selectedId: "s4" })); rerender(treeElement({ sessions, selectedId: "s4" }));
const s4DotSelected = rowMain("s4").querySelector(".dot"); const s4DotSelected = rowMain("s4").querySelector(".dot");
expect(s4DotSelected).toHaveClass("dot", "dot--busy", "dot--current"); expect(s4DotSelected).toHaveClass("dot", "dot--busy", "dot--current");
expect(s4DotSelected).not.toHaveClass("dot--steady"); expect(s4DotSelected).toHaveClass("dot--blink-fast");
// 6. Selected child with error renders dot--err + dot--steady. // 6. Selected child with error renders steady dot--err: viewed red is
// acknowledged, so it carries NO blink class while the unselected
// sibling above does.
rerender(treeElement({ sessions, selectedId: "c2" })); rerender(treeElement({ sessions, selectedId: "c2" }));
const c2DotSelected = rowMain("c2").querySelector(".dot"); const c2DotSelected = rowMain("c2").querySelector(".dot");
expect(c2DotSelected).toHaveClass("dot", "dot--err", "dot--steady"); expect(c2DotSelected).toHaveClass("dot", "dot--err");
expect(c2DotSelected).not.toHaveClass("dot--blink-fast");
expect(c2DotSelected).not.toHaveClass("dot--blink-slow");
expect(c2DotSelected).not.toHaveClass("dot--current"); expect(c2DotSelected).not.toHaveClass("dot--current");
// 7. The regression: a `done` row blinks in the list. The old CSS keyed
// the green animation on `.tree-row .dot--ok`, so it only pulsed here
// and stayed solid everywhere else; the class must now be explicit.
const s3DotFinal = rowMain("s3").querySelector(".dot");
expect(s3DotFinal).toHaveClass("dot", "dot--ok");
expect(s3DotFinal).toHaveClass("dot--blink-fast");
expect(s3DotFinal).not.toHaveClass("dot--blink-slow");
// 8. An attention row never blinks (nothing to acknowledge twice).
const s1DotFinal = rowMain("s1").querySelector(".dot");
expect(s1DotFinal).toHaveClass("dot", "dot--attention");
expect(s1DotFinal).not.toHaveClass("dot--blink-fast");
expect(s1DotFinal).not.toHaveClass("dot--blink-slow");
}); });
it("draws child rows as a single line without a child-count badge", () => { it("draws child rows as a single line without a child-count badge", () => {
@@ -703,6 +724,19 @@ describe("chat session deep link", () => {
expect(requestedUrls(fetchMock)).toContainEqual( expect(requestedUrls(fetchMock)).toContainEqual(
expect.stringContaining("/api/v1/sessions/s2/entries"), expect.stringContaining("/api/v1/sessions/s2/entries"),
); );
// "One session, one blink": the stream head renders the same `DotView`
// as the selected tree row (`sessionDot(active, { viewed: true })`), so
// the colour, the blink rate and the current marker must agree. The bug
// was that the list blinked while the head did not (or vice versa).
const blinkClasses = (el: Element | null | undefined) =>
["dot--blink-fast", "dot--blink-slow"].filter((cls) => el?.classList.contains(cls));
const headDot = streamPane().querySelector(".stream-title .dot");
const selectedRowDot = rowMain("s2").querySelector(".dot");
expect(headDot).not.toBeNull();
expect(headDot).toHaveClass("dot", "dot--busy", "dot--current");
expect(blinkClasses(headDot)).toEqual(["dot--blink-fast"]);
expect(blinkClasses(headDot)).toEqual(blinkClasses(selectedRowDot));
}); });
it("keeps the first-session fallback for the /chat index", async () => { it("keeps the first-session fallback for the /chat index", async () => {
@@ -718,6 +752,13 @@ describe("chat session deep link", () => {
expect(await screen.findByText("Alpha first message")).toBeInTheDocument(); expect(await screen.findByText("Alpha first message")).toBeInTheDocument();
expect(screen.queryByTestId("session-not-found")).toBeNull(); expect(screen.queryByTestId("session-not-found")).toBeNull();
expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha"); expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha");
// The same rule for a solid dot: an idle session is steady in the head
// and in the list — no wrapper may add or remove a blink.
const headDot = streamPane().querySelector(".stream-title .dot");
expect(headDot).toHaveClass("dot", "dot--idle", "dot--current");
expect(headDot).not.toHaveClass("dot--blink-fast");
expect(headDot?.className).toBe(rowMain("s1").querySelector(".dot")?.className);
}); });
it("renders a deep-linked hidden sub-session and offers the way back to its parent", async () => { it("renders a deep-linked hidden sub-session and offers the way back to its parent", async () => {
+43 -14
View File
@@ -66,17 +66,35 @@ describe("StatusDot", () => {
expect(container.firstElementChild).toHaveClass("dot", expected); expect(container.firstElementChild).toHaveClass("dot", expected);
}); });
it("applies dot--steady modifier when steady is true", () => { it("applies the fast blink class only when blink='fast'", () => {
const { container } = render(<StatusDot status="err" steady={true} />); const { container } = render(<StatusDot status="err" blink="fast" />);
expect(container.firstElementChild).toHaveClass("dot", "dot--err", "dot--steady"); expect(container.firstElementChild).toHaveClass("dot", "dot--err", "dot--blink-fast");
expect(container.firstElementChild).not.toHaveClass("dot--blink-slow");
}); });
it("does not apply dot--steady when steady is false or omitted", () => { it("applies the slow blink class only when blink='slow'", () => {
const { container: c1 } = render(<StatusDot status="err" steady={false} />); const { container } = render(<StatusDot status="compacting" blink="slow" />);
expect(c1.firstElementChild).not.toHaveClass("dot--steady"); expect(container.firstElementChild).toHaveClass("dot", "dot--compacting", "dot--blink-slow");
expect(container.firstElementChild).not.toHaveClass("dot--blink-fast");
});
const { container: c2 } = render(<StatusDot status="err" />); it("carries neither blink class when blink is omitted or null", () => {
expect(c2.firstElementChild).not.toHaveClass("dot--steady"); const { container: c1 } = render(<StatusDot status="err" />);
expect(c1.firstElementChild).not.toHaveClass("dot--blink-fast");
expect(c1.firstElementChild).not.toHaveClass("dot--blink-slow");
const { container: c2 } = render(<StatusDot status="err" blink={null} />);
expect(c2.firstElementChild).not.toHaveClass("dot--blink-fast");
expect(c2.firstElementChild).not.toHaveClass("dot--blink-slow");
});
it("never encodes the blink in the colour class (a solid err dot is still dot--err)", () => {
// The old bug: the animation was keyed on the colour class + the wrapper.
const solid = render(<StatusDot status="err" />);
const blinking = render(<StatusDot status="err" blink="fast" />);
expect(solid.container.firstElementChild).toHaveClass("dot--err");
expect(blinking.container.firstElementChild).toHaveClass("dot--err");
expect(solid.container.firstElementChild).not.toHaveClass("dot--blink-fast");
}); });
it("applies dot--current modifier when current is true", () => { it("applies dot--current modifier when current is true", () => {
@@ -92,14 +110,25 @@ describe("StatusDot", () => {
expect(c2.firstElementChild).not.toHaveClass("dot--current"); expect(c2.firstElementChild).not.toHaveClass("dot--current");
}); });
it("supports steady and current modifiers together", () => { it("composes blink, current and a custom className", () => {
const { container } = render(<StatusDot status="busy" steady current />); const { container } = render(<StatusDot status="busy" blink="fast" current className="custom-dot" />);
expect(container.firstElementChild).toHaveClass("dot", "dot--busy", "dot--steady", "dot--current"); expect(container.firstElementChild).toHaveClass(
"dot",
"dot--busy",
"dot--blink-fast",
"dot--current",
"custom-dot",
);
}); });
it("preserves custom className alongside modifiers", () => { it("composes a slow blink with the current marker", () => {
const { container } = render(<StatusDot status="idle" steady current className="custom-dot" />); const { container } = render(<StatusDot status="compacting" blink="slow" current />);
expect(container.firstElementChild).toHaveClass("dot", "dot--idle", "dot--steady", "dot--current", "custom-dot"); expect(container.firstElementChild).toHaveClass(
"dot",
"dot--compacting",
"dot--blink-slow",
"dot--current",
);
}); });
it("exposes the state label when a title is provided", () => { it("exposes the state label when a title is provided", () => {
+184 -73
View File
@@ -9,6 +9,23 @@ import {
subagentDot, subagentDot,
} from "@/features/chat/session-state"; } from "@/features/chat/session-state";
/**
* The dot contract, in one place.
*
* `DotView` is the *only* decision about whether a dot blinks and at which
* rate: `blink: "fast"` → `.dot--blink-fast`, `blink: "slow"` →
* `.dot--blink-slow`, omitted → solid. The renderer never infers the animation
* from the colour class or from where the dot is mounted (`status-dot.tsx`,
* `app.css`), so every row below asserts the *whole* view with `toEqual` —
* an unexpected `blink` is a failure, and a stray `steady` key can never come
* back unnoticed.
*
* Regression this pins: `done` (green) used to blink only inside `.tree-row`
* because the animation was keyed on `html[data-pi-blink-fast="dim"]
* .tree-row .dot--ok`, while `.dot--busy`/`.dot--err` blazed globally and
* `dot--steady` could not stop `ok` at all.
*/
type SessionOverrides = Omit<Partial<SessionState>, "flags"> & { type SessionOverrides = Omit<Partial<SessionState>, "flags"> & {
flags?: Partial<SessionFlags>; flags?: Partial<SessionFlags>;
}; };
@@ -44,58 +61,81 @@ describe("sessionDot (parent rows)", () => {
describe("base status matrix", () => { describe("base status matrix", () => {
it.each([ it.each([
{ {
name: "exited -> dead", name: "exited -> dead, solid (a dead process does not blink)",
state: makeSession({ status: "exited" }), state: makeSession({ status: "exited" }),
expected: { status: "dead" }, expected: { status: "dead" },
}, },
{ {
name: "error -> err", name: "error -> err, blinking fast",
state: makeSession({ flags: { error: true } }), state: makeSession({ flags: { error: true } }),
expected: { status: "err" }, expected: { status: "err", blink: "fast" },
}, },
{ {
name: "attention flag -> attention", name: "attention flag -> attention, solid",
state: makeSession({ flags: { attention: true } }), state: makeSession({ flags: { attention: true } }),
expected: { status: "attention" }, expected: { status: "attention" },
}, },
{ {
name: "attention array non-empty -> attention", name: "attention array non-empty -> attention, solid",
state: makeSession({ attention: [{ id: "q1" } as any] }), state: makeSession({ attention: [{ id: "q1" } as any] }),
expected: { status: "attention" }, expected: { status: "attention" },
}, },
{ {
name: "done -> ok", name: "done -> ok, blinking fast (the green that used to be tree-scoped)",
state: makeSession({ flags: { done: true } }), state: makeSession({ flags: { done: true } }),
expected: { status: "ok" }, expected: { status: "ok", blink: "fast" },
}, },
{ {
name: "busy -> busy", name: "busy -> busy, blinking fast",
state: makeSession({ status: "busy" }), state: makeSession({ status: "busy" }),
expected: { status: "busy" }, expected: { status: "busy", blink: "fast" },
}, },
{ {
name: "compacting -> compacting", name: "compacting -> compacting, blinking slow",
state: makeSession({ status: "compacting" }), state: makeSession({ status: "compacting" }),
expected: { status: "compacting" }, expected: { status: "compacting", blink: "slow" },
}, },
{ {
name: "interrupted -> dead", name: "interrupted -> dead, solid",
state: makeSession({ status: "interrupted" }), state: makeSession({ status: "interrupted" }),
expected: { status: "dead" }, expected: { status: "dead" },
}, },
{ {
name: "starting -> idle", name: "starting -> idle, solid",
state: makeSession({ status: "starting" }), state: makeSession({ status: "starting" }),
expected: { status: "idle" }, expected: { status: "idle" },
}, },
{ {
name: "idle -> idle", name: "idle -> idle, solid",
state: makeSession({ status: "idle" }), state: makeSession({ status: "idle" }),
expected: { status: "idle" }, expected: { status: "idle" },
}, },
])("$name", ({ state, expected }) => { ])("$name", ({ state, expected }) => {
expect(sessionDot(state)).toEqual(expected); expect(sessionDot(state)).toEqual(expected);
}); });
it("compacting blinks at the slow rate, never at the busy rate, unviewed", () => {
expect(sessionDot(makeSession({ status: "compacting" }))).toEqual({
status: "compacting",
blink: "slow",
});
expect(sessionDot(makeSession({ status: "compacting" })).blink).not.toBe("fast");
});
it("exited and interrupted never blink (no acknowledgement path needed)", () => {
expect(sessionDot(makeSession({ status: "exited" }))).toEqual({ status: "dead" });
expect(sessionDot(makeSession({ status: "interrupted" }))).toEqual({ status: "dead" });
for (const status of ["exited", "interrupted"] as const) {
expect(sessionDot(makeSession({ status }))).not.toHaveProperty("blink");
}
});
it("attention never blinks, from the flag or the request array", () => {
expect(sessionDot(makeSession({ flags: { attention: true } }))).toEqual({ status: "attention" });
expect(sessionDot(makeSession({ attention: [{ id: "q1" } as any] }))).toEqual({
status: "attention",
});
});
}); });
describe("priority collisions (bug fixes: exited > error > attention > done > busy)", () => { describe("priority collisions (bug fixes: exited > error > attention > done > busy)", () => {
@@ -103,7 +143,7 @@ describe("sessionDot (parent rows)", () => {
const state = makeSession({ const state = makeSession({
flags: { error: true, attention: true }, flags: { error: true, attention: true },
}); });
expect(sessionDot(state)).toEqual({ status: "err" }); expect(sessionDot(state)).toEqual({ status: "err", blink: "fast" });
}); });
it("error beats attention (flags.error outranks populated attention array)", () => { it("error beats attention (flags.error outranks populated attention array)", () => {
@@ -111,7 +151,7 @@ describe("sessionDot (parent rows)", () => {
flags: { error: true }, flags: { error: true },
attention: [{ id: "q1" } as any], attention: [{ id: "q1" } as any],
}); });
expect(sessionDot(state)).toEqual({ status: "err" }); expect(sessionDot(state)).toEqual({ status: "err", blink: "fast" });
}); });
it("exited beats error (status: exited outranks flags.error)", () => { it("exited beats error (status: exited outranks flags.error)", () => {
@@ -125,9 +165,15 @@ describe("sessionDot (parent rows)", () => {
it("interrupted is a dead process too (outranks error, attention and done)", () => { it("interrupted is a dead process too (outranks error, attention and done)", () => {
// The plugin has no `interrupted`: any "not running" row is `exited` // The plugin has no `interrupted`: any "not running" row is `exited`
// (sessions.lua:75-78), and `exited` sits at the top of dot_hl. // (sessions.lua:75-78), and `exited` sits at the top of dot_hl.
expect(sessionDot(makeSession({ status: "interrupted", flags: { error: true } })).status).toBe("dead"); expect(sessionDot(makeSession({ status: "interrupted", flags: { error: true } }))).toEqual({
expect(sessionDot(makeSession({ status: "interrupted", flags: { attention: true } })).status).toBe("dead"); status: "dead",
expect(sessionDot(makeSession({ status: "interrupted", flags: { done: true } })).status).toBe("dead"); });
expect(sessionDot(makeSession({ status: "interrupted", flags: { attention: true } }))).toEqual({
status: "dead",
});
expect(sessionDot(makeSession({ status: "interrupted", flags: { done: true } }))).toEqual({
status: "dead",
});
// …and it never wears the blue current marker either. // …and it never wears the blue current marker either.
expect(sessionDot(makeSession({ status: "interrupted" }), { viewed: true })).toEqual({ status: "dead" }); expect(sessionDot(makeSession({ status: "interrupted" }), { viewed: true })).toEqual({ status: "dead" });
}); });
@@ -152,7 +198,7 @@ describe("sessionDot (parent rows)", () => {
status: "busy", status: "busy",
flags: { done: true }, flags: { done: true },
}); });
expect(sessionDot(state)).toEqual({ status: "ok" }); expect(sessionDot(state)).toEqual({ status: "ok", blink: "fast" });
}); });
it("exited beats attention (status: exited outranks flags.attention and attention array)", () => { it("exited beats attention (status: exited outranks flags.attention and attention array)", () => {
@@ -168,7 +214,7 @@ describe("sessionDot (parent rows)", () => {
const state = makeSession({ const state = makeSession({
flags: { error: true, done: true }, flags: { error: true, done: true },
}); });
expect(sessionDot(state)).toEqual({ status: "err" }); expect(sessionDot(state)).toEqual({ status: "err", blink: "fast" });
}); });
it("attention beats busy (flags.attention outranks status: busy)", () => { it("attention beats busy (flags.attention outranks status: busy)", () => {
@@ -178,38 +224,53 @@ describe("sessionDot (parent rows)", () => {
}); });
expect(sessionDot(state)).toEqual({ status: "attention" }); expect(sessionDot(state)).toEqual({ status: "attention" });
}); });
it("a busy session keeps the fast rate (compacting never downgrades it)", () => {
const state = makeSession({ status: "busy" });
expect(sessionDot(state)).toEqual({ status: "busy", blink: "fast" });
});
}); });
describe("viewed overlay (you are here)", () => { describe("viewed overlay (you are here)", () => {
it.each([ it.each([
{ {
name: "idle -> current", name: "idle -> current, solid",
state: makeSession({ status: "idle" }), state: makeSession({ status: "idle" }),
expected: { status: "idle", current: true }, expected: { status: "idle", current: true },
}, },
{ {
name: "busy -> current (busy)", name: "busy -> current (busy), blinking fast",
state: makeSession({ status: "busy" }), state: makeSession({ status: "busy" }),
expected: { status: "busy", current: true }, expected: { status: "busy", blink: "fast", current: true },
}, },
{ {
name: "compacting -> current with status flipped to busy", name: "compacting -> current with status flipped to busy, blinking fast (not slow)",
state: makeSession({ status: "compacting" }), state: makeSession({ status: "compacting" }),
expected: { status: "busy", current: true }, expected: { status: "busy", blink: "fast", current: true },
}, },
])("$name", ({ state, expected }) => { ])("$name", ({ state, expected }) => {
expect(sessionDot(state, { viewed: true })).toEqual(expected); expect(sessionDot(state, { viewed: true })).toEqual(expected);
}); });
describe("no overlay when notification flags are set", () => { it("focused compacting blinks at the busy rate under the marker", () => {
it("suppresses current overlay when error is set", () => { const viewed = sessionDot(makeSession({ status: "compacting" }), { viewed: true });
const state = makeSession({ status: "idle", flags: { error: true } }); expect(viewed).toEqual({ status: "busy", blink: "fast", current: true });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "err" }); // The unfocused row keeps the slow rate: the rate follows the view.
expect(sessionDot(makeSession({ status: "compacting" }))).toEqual({
status: "compacting",
blink: "slow",
});
}); });
it("suppresses current overlay when done is set", () => { describe("no overlay when notification flags are set", () => {
it("suppresses current overlay when error is set, but keeps the fast blink", () => {
const state = makeSession({ status: "idle", flags: { error: true } });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "err", blink: "fast" });
});
it("suppresses current overlay when done is set, but keeps the fast blink", () => {
const state = makeSession({ status: "idle", flags: { done: true } }); const state = makeSession({ status: "idle", flags: { done: true } });
expect(sessionDot(state, { viewed: true })).toEqual({ status: "ok" }); expect(sessionDot(state, { viewed: true })).toEqual({ status: "ok", blink: "fast" });
}); });
it("suppresses current overlay when flags.attention is set", () => { it("suppresses current overlay when flags.attention is set", () => {
@@ -243,12 +304,12 @@ describe("sessionDot (parent rows)", () => {
it("does not apply current when viewed: false on busy", () => { it("does not apply current when viewed: false on busy", () => {
const state = makeSession({ status: "busy" }); const state = makeSession({ status: "busy" });
expect(sessionDot(state, { viewed: false })).toEqual({ status: "busy" }); expect(sessionDot(state, { viewed: false })).toEqual({ status: "busy", blink: "fast" });
}); });
it("does not apply current or flip status when viewed: false on compacting", () => { it("does not apply current or flip status when viewed: false on compacting", () => {
const state = makeSession({ status: "compacting" }); const state = makeSession({ status: "compacting" });
expect(sessionDot(state, { viewed: false })).toEqual({ status: "compacting" }); expect(sessionDot(state, { viewed: false })).toEqual({ status: "compacting", blink: "slow" });
}); });
it("does not apply current when opts is omitted", () => { it("does not apply current when opts is omitted", () => {
@@ -257,55 +318,92 @@ describe("sessionDot (parent rows)", () => {
}); });
}); });
}); });
describe("the view is the only animation decision (no `steady`, no colour-keyed blink)", () => {
const samples: SessionState[] = [
makeSession({ status: "idle" }),
makeSession({ status: "busy" }),
makeSession({ status: "compacting" }),
makeSession({ status: "exited" }),
makeSession({ status: "interrupted" }),
makeSession({ status: "starting" }),
makeSession({ flags: { error: true } }),
makeSession({ flags: { done: true } }),
makeSession({ flags: { attention: true } }),
];
it.each(samples.map((state) => [state.status, state] as const))(
"renders only status/blink/current keys for a %s session",
(_status, state) => {
for (const viewed of [false, true]) {
const view = sessionDot(state, { viewed });
const unexpected = Object.keys(view).filter(
(key) => !["status", "blink", "current"].includes(key),
);
expect(unexpected, `unexpected DotView keys on ${state.status}`).toEqual([]);
expect(view).not.toHaveProperty("steady");
if (view.blink !== undefined) expect(["fast", "slow"]).toContain(view.blink);
}
},
);
it("a dot without a blink is solid", () => {
expect(sessionDot(makeSession({ status: "idle" })).blink).toBeUndefined();
expect(sessionDot(makeSession({ status: "starting" })).blink).toBeUndefined();
expect(sessionDot(makeSession({ flags: { attention: true } })).blink).toBeUndefined();
expect(sessionDot(makeSession({ status: "exited" })).blink).toBeUndefined();
expect(sessionDot(makeSession({ status: "interrupted" })).blink).toBeUndefined();
});
});
}); });
describe("childSessionDot (sub-session / tree depth > 0)", () => { describe("childSessionDot (sub-session / tree depth > 0)", () => {
describe("base status matrix", () => { describe("base status matrix", () => {
it.each([ it.each([
{ {
name: "exited -> exited (hollow ring)", name: "exited -> exited (hollow ring), solid",
state: makeChild({ status: "exited" }), state: makeChild({ status: "exited" }),
opts: undefined, opts: undefined,
expected: { status: "exited" }, expected: { status: "exited" },
}, },
{ {
name: "interrupted -> dead", name: "interrupted -> dead, solid",
state: makeChild({ status: "interrupted" }), state: makeChild({ status: "interrupted" }),
opts: undefined, opts: undefined,
expected: { status: "dead" }, expected: { status: "dead" },
}, },
{ {
name: "error with viewed -> { status: 'err', steady: true }", name: "error with viewed -> err, solid (acknowledged red)",
state: makeChild({ flags: { error: true } }), state: makeChild({ flags: { error: true } }),
opts: { viewed: true }, opts: { viewed: true },
expected: { status: "err", steady: true }, expected: { status: "err" },
}, },
{ {
name: "error without viewed (viewed: false) -> { status: 'err', steady: false } (blinking)", name: "error with viewed: false -> err, blinking fast",
state: makeChild({ flags: { error: true } }), state: makeChild({ flags: { error: true } }),
opts: { viewed: false }, opts: { viewed: false },
expected: { status: "err", steady: false }, expected: { status: "err", blink: "fast" },
}, },
{ {
name: "error without viewed (opts omitted) -> { status: 'err', steady: false } (blinking)", name: "error with opts omitted -> err, blinking fast",
state: makeChild({ flags: { error: true } }), state: makeChild({ flags: { error: true } }),
opts: undefined, opts: undefined,
expected: { status: "err", steady: false }, expected: { status: "err", blink: "fast" },
}, },
{ {
name: "busy -> busy", name: "busy -> busy, blinking fast",
state: makeChild({ status: "busy" }), state: makeChild({ status: "busy" }),
opts: undefined, opts: undefined,
expected: { status: "busy" }, expected: { status: "busy", blink: "fast" },
}, },
{ {
name: "compacting -> busy (NOT compacting)", name: "compacting -> busy (NOT compacting), blinking fast",
state: makeChild({ status: "compacting" }), state: makeChild({ status: "compacting" }),
opts: undefined, opts: undefined,
expected: { status: "busy" }, expected: { status: "busy", blink: "fast" },
}, },
{ {
name: "idle -> idle", name: "idle -> idle, solid",
state: makeChild({ status: "idle" }), state: makeChild({ status: "idle" }),
opts: undefined, opts: undefined,
expected: { status: "idle" }, expected: { status: "idle" },
@@ -313,28 +411,30 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
])("$name", ({ state, opts, expected }) => { ])("$name", ({ state, opts, expected }) => {
expect(childSessionDot(state, opts)).toEqual(expected); expect(childSessionDot(state, opts)).toEqual(expected);
}); });
it("a viewed failed child is steady red while the unviewed one blinks", () => {
const viewed = childSessionDot(makeChild({ flags: { error: true } }), { viewed: true });
const unviewed = childSessionDot(makeChild({ flags: { error: true } }));
expect(viewed).toEqual({ status: "err" });
expect(unviewed).toEqual({ status: "err", blink: "fast" });
expect(viewed).not.toHaveProperty("blink");
});
}); });
describe("child never returns ok or attention", () => { describe("child never returns ok or attention", () => {
it("returns idle instead of ok when flags.done is set on idle child", () => { it("returns idle instead of ok when flags.done is set on idle child", () => {
const state = makeChild({ status: "idle", flags: { done: true } }); const state = makeChild({ status: "idle", flags: { done: true } });
const dot = childSessionDot(state); expect(childSessionDot(state)).toEqual({ status: "idle" });
expect(dot.status).not.toBe("ok");
expect(dot.status).toBe("idle");
}); });
it("returns busy instead of ok when flags.done is set on busy child", () => { it("returns busy instead of ok when flags.done is set on busy child", () => {
const state = makeChild({ status: "busy", flags: { done: true } }); const state = makeChild({ status: "busy", flags: { done: true } });
const dot = childSessionDot(state); expect(childSessionDot(state)).toEqual({ status: "busy", blink: "fast" });
expect(dot.status).not.toBe("ok");
expect(dot.status).toBe("busy");
}); });
it("returns idle instead of attention when flags.attention is set on idle child", () => { it("returns idle instead of attention when flags.attention is set on idle child", () => {
const state = makeChild({ status: "idle", flags: { attention: true } }); const state = makeChild({ status: "idle", flags: { attention: true } });
const dot = childSessionDot(state); expect(childSessionDot(state)).toEqual({ status: "idle" });
expect(dot.status).not.toBe("attention");
expect(dot.status).toBe("idle");
}); });
it("returns idle instead of attention when attention array is populated on idle child", () => { it("returns idle instead of attention when attention array is populated on idle child", () => {
@@ -342,9 +442,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
status: "idle", status: "idle",
attention: [{ id: "q1" } as any], attention: [{ id: "q1" } as any],
}); });
const dot = childSessionDot(state); expect(childSessionDot(state)).toEqual({ status: "idle" });
expect(dot.status).not.toBe("attention");
expect(dot.status).toBe("idle");
}); });
it("returns busy instead of attention when flags.attention is set on busy child", () => { it("returns busy instead of attention when flags.attention is set on busy child", () => {
@@ -353,9 +451,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
flags: { attention: true }, flags: { attention: true },
attention: [{ id: "q1" } as any], attention: [{ id: "q1" } as any],
}); });
const dot = childSessionDot(state); expect(childSessionDot(state)).toEqual({ status: "busy", blink: "fast" });
expect(dot.status).not.toBe("attention");
expect(dot.status).toBe("busy");
}); });
it("does not return ok or current when flags.done is set with viewed: true", () => { it("does not return ok or current when flags.done is set with viewed: true", () => {
@@ -370,7 +466,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
}); });
describe("viewed overlay on child rows", () => { describe("viewed overlay on child rows", () => {
it("applies current overlay to idle child when viewed", () => { it("applies current overlay to idle child when viewed (still solid)", () => {
const state = makeChild({ status: "idle" }); const state = makeChild({ status: "idle" });
expect(childSessionDot(state, { viewed: true })).toEqual({ expect(childSessionDot(state, { viewed: true })).toEqual({
status: "idle", status: "idle",
@@ -382,6 +478,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
const state = makeChild({ status: "busy" }); const state = makeChild({ status: "busy" });
expect(childSessionDot(state, { viewed: true })).toEqual({ expect(childSessionDot(state, { viewed: true })).toEqual({
status: "busy", status: "busy",
blink: "fast",
current: true, current: true,
}); });
}); });
@@ -390,6 +487,7 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
const state = makeChild({ status: "compacting" }); const state = makeChild({ status: "compacting" });
expect(childSessionDot(state, { viewed: true })).toEqual({ expect(childSessionDot(state, { viewed: true })).toEqual({
status: "busy", status: "busy",
blink: "fast",
current: true, current: true,
}); });
}); });
@@ -407,25 +505,32 @@ describe("childSessionDot (sub-session / tree depth > 0)", () => {
status: "dead", status: "dead",
}); });
}); });
it("does not apply current overlay to a failed child, and the error stays solid", () => {
const state = makeChild({ flags: { error: true } });
expect(childSessionDot(state, { viewed: true })).toEqual({ status: "err" });
});
}); });
}); });
describe("subagentDot (manifest-only subagent tree rows)", () => { describe("subagentDot (manifest-only subagent tree rows)", () => {
it.each([ it.each([
{ {
name: "active -> busy", // A manifest-only entry has no live child (a live one renders as its
// own session row), and nvim blinks only a live busy child: amber, solid.
name: "active -> busy, solid",
subagent: makeSubagent({ status: "active" }), subagent: makeSubagent({ status: "active" }),
opts: undefined, opts: undefined,
expected: { status: "busy" }, expected: { status: "busy" },
}, },
{ {
name: "completed -> exited", name: "completed -> exited, solid",
subagent: makeSubagent({ status: "completed" }), subagent: makeSubagent({ status: "completed" }),
opts: undefined, opts: undefined,
expected: { status: "exited" }, expected: { status: "exited" },
}, },
{ {
name: "dormant -> exited", name: "dormant -> exited, solid",
subagent: makeSubagent({ status: "dormant" }), subagent: makeSubagent({ status: "dormant" }),
opts: undefined, opts: undefined,
expected: { status: "exited" }, expected: { status: "exited" },
@@ -434,28 +539,28 @@ describe("subagentDot (manifest-only subagent tree rows)", () => {
name: "failed with viewed -> steady err", name: "failed with viewed -> steady err",
subagent: makeSubagent({ status: "failed" }), subagent: makeSubagent({ status: "failed" }),
opts: { viewed: true }, opts: { viewed: true },
expected: { status: "err", steady: true }, expected: { status: "err" },
}, },
{ {
name: "failed without viewed (viewed: false) -> blinking err", name: "failed with viewed: false -> blinking err",
subagent: makeSubagent({ status: "failed" }), subagent: makeSubagent({ status: "failed" }),
opts: { viewed: false }, opts: { viewed: false },
expected: { status: "err", steady: false }, expected: { status: "err", blink: "fast" },
}, },
{ {
name: "failed without viewed (opts omitted) -> blinking err", name: "failed with opts omitted -> blinking err",
subagent: makeSubagent({ status: "failed" }), subagent: makeSubagent({ status: "failed" }),
opts: undefined, opts: undefined,
expected: { status: "err", steady: false }, expected: { status: "err", blink: "fast" },
}, },
{ {
name: "interrupted -> dead", name: "interrupted -> dead, solid",
subagent: makeSubagent({ status: "interrupted" }), subagent: makeSubagent({ status: "interrupted" }),
opts: undefined, opts: undefined,
expected: { status: "dead" }, expected: { status: "dead" },
}, },
{ {
name: "unknown status -> idle", name: "unknown status -> idle, solid",
subagent: makeSubagent({ status: "unknown" as any }), subagent: makeSubagent({ status: "unknown" as any }),
opts: undefined, opts: undefined,
expected: { status: "idle" }, expected: { status: "idle" },
@@ -463,6 +568,12 @@ describe("subagentDot (manifest-only subagent tree rows)", () => {
])("$name", ({ subagent, opts, expected }) => { ])("$name", ({ subagent, opts, expected }) => {
expect(subagentDot(subagent, opts)).toEqual(expected); expect(subagentDot(subagent, opts)).toEqual(expected);
}); });
it("a failed subagent stops blinking once it is the viewed child view", () => {
const failed = makeSubagent({ status: "failed" });
expect(subagentDot(failed, { viewed: true })).toEqual({ status: "err" });
expect(subagentDot(failed)).toEqual({ status: "err", blink: "fast" });
});
}); });
describe("sessionStatusKey (stays distinct from dot)", () => { describe("sessionStatusKey (stays distinct from dot)", () => {
+275
View File
@@ -0,0 +1,275 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import appCss from "@/styles/app.css?raw";
import chatCss from "@/styles/pages/chat.css?raw";
import { cn } from "@/lib/utils";
/**
* The CSS half of the blink contract.
*
* `session-dot.test.ts` pins *which* dots ask to blink (`DotView.blink`);
* this file pins that the stylesheet honours exactly that request and nothing
* else. The bug it guards: the animation used to be keyed on the colour class
* *and* on the component wrapper —
*
* html[data-pi-blink-fast="dim"] .tree-row .dot--ok { opacity: .35; }
* .dot--busy { animation: … } /* global, unacknowledgeable *\/
*
* — so green blinked only in the session list, busy/err blazed everywhere, and
* a dot could not opt out. The fix keeps exactly two dim rules, keyed on the
* blink class alone.
*
* jsdom 30 runs a real specificity/attribute-selector cascade for
* `getComputedStyle` against injected `<style>` sheets, so these assertions are
* browser truth rather than a text grep. (The `@import`s are stripped because
* jsdom cannot resolve them against `about:blank`; the imported token sheet
* only supplies colours, never opacity.)
*/
/** `@import "tailwindcss";` / `@import "./tokens.css";` — jsdom cannot fetch them. */
function stripImports(source: string): string {
return source.replace(/^[ \t]*@import[^;\n]*;[ \t]*$/gm, "");
}
/** Whitespace-insensitive view of a sheet, for "the rule still says X" checks. */
function compact(source: string): string {
return source
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/\s+/g, " ")
.trim();
}
function escapeRe(literal: string): string {
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const DIM_FAST = 'html[data-pi-blink-fast="dim"]';
const DIM_SLOW = 'html[data-pi-blink-slow="dim"]';
/** The two (and only two) dim selectors, exactly as they must read in `app.css`. */
const BLINK_SELECTORS = `${DIM_FAST} .dot--blink-fast, ${DIM_SLOW} .dot--blink-slow`;
let style: HTMLStyleElement;
let host: HTMLElement;
beforeAll(() => {
style = document.createElement("style");
style.textContent = `${stripImports(appCss)}\n${stripImports(chatCss)}`;
document.head.appendChild(style);
});
afterAll(() => {
style.remove();
});
beforeEach(() => {
// Phase attributes are global state on the shared jsdom document; `blink.test.ts`
// asserts on them and the suite runs with `isolate: false`, so start clean.
clearPhases();
host = document.createElement("div");
host.className = "blink-css-host";
document.body.appendChild(host);
});
afterEach(() => {
clearPhases();
host.remove();
});
function clearPhases(): void {
document.documentElement.removeAttribute("data-pi-blink-fast");
document.documentElement.removeAttribute("data-pi-blink-slow");
}
function setPhase({ fast, slow }: { fast?: "on" | "dim"; slow?: "on" | "dim" } = {}): void {
clearPhases();
if (fast) document.documentElement.setAttribute("data-pi-blink-fast", fast);
if (slow) document.documentElement.setAttribute("data-pi-blink-slow", slow);
}
/**
* Mount a dot the way `StatusDot` renders one (`cn("dot", DOT_CLASS[status],
* BLINK_CLASS[blink])`), optionally inside `.tree-row` — the wrapper the old
* rule scoped on.
*/
function mountDot(classes: string[], { inTreeRow = false }: { inTreeRow?: boolean } = {}): HTMLElement {
const dot = document.createElement("span");
dot.className = cn("dot", ...classes);
if (inTreeRow) {
const row = document.createElement("div");
row.className = "tree-row";
row.appendChild(dot);
host.appendChild(row);
} else {
host.appendChild(dot);
}
return dot;
}
/** Computed opacity, or `NaN` when the sheet never applies one. */
function opacityOf(el: HTMLElement): number {
return Number.parseFloat(getComputedStyle(el).opacity);
}
const DIM = 0.35;
const SOLID = 1;
describe("blink CSS: the stylesheet defines exactly one dim contract", () => {
/** The single `data-pi-blink-*` rule, split into selector list and body. */
function blinkRule() {
const css = compact(appCss);
const start = css.indexOf(DIM_FAST);
expect(start, "missing the dim rule").toBeGreaterThanOrEqual(0);
const open = css.indexOf("{", start);
const close = css.indexOf("}", open);
return {
css,
selectors: css.slice(start, open).trim(),
body: css.slice(open + 1, close).trim(),
};
}
it("keeps the two blink rules verbatim in app.css (no silent rename)", () => {
const { selectors, body } = blinkRule();
expect(selectors).toBe(BLINK_SELECTORS);
expect(body.replace(/\s+/g, "")).toBe("opacity:.35;");
});
it("keys both dim rules on the blink class alone (no colour class, no wrapper)", () => {
const { css, selectors } = blinkRule();
// Exactly one rule mentions either clock attribute…
expect(css.match(/data-pi-blink-fast="dim"/g)).toHaveLength(1);
expect(css.match(/data-pi-blink-slow="dim"/g)).toHaveLength(1);
// …and the blink classes exist nowhere else (a second, scoped rule would
// show up as a third occurrence).
expect(css.match(/\.dot--blink-(?:fast|slow)/g)).toHaveLength(2);
expect(selectors).not.toMatch(/tree-row|session-list|\.dot--(?:ok|busy|err|attention|idle|compacting|dead|exited)/);
});
it("leaves chat.css free of any dim rule (page CSS must not re-scope the blink)", () => {
const css = compact(chatCss);
expect(css).not.toContain("data-pi-blink");
expect(css).not.toMatch(/\.dot--blink-(?:fast|slow)/);
});
it("paints the current marker wherever the dot is mounted", () => {
// The head dot and its list row must agree on the blue marker too, so
// `.dot--current` may not be scoped to a wrapper either (jsdom cannot
// resolve `var(--info)`, so this half has to read the sheet).
expect(compact(appCss)).toMatch(/(?:^|[},\s])\.dot--current\s*\{[^}]*background:\s*var\(--info\)/);
expect(compact(chatCss)).not.toMatch(/\.tree-row\s+\.dot--current/);
});
it("no colour class owns an animation or an opacity any more", () => {
const css = compact(appCss);
// `@keyframes pulse` may stay for unrelated chrome, but a `.dot--*`
// colour class may not animate or fade itself again.
for (const selector of [".dot--busy", ".dot--ok", ".dot--err", ".dot--attention", ".dot--compacting"]) {
const rule = new RegExp(`${escapeRe(selector)}\\s*\\{([^}]*)\\}`).exec(css);
if (!rule) continue;
expect(rule[1], selector).not.toMatch(/animation:|opacity:/);
}
expect(css).not.toMatch(/\.tree-row[^{,]*\.dot--(?:ok|busy|err)[^{]*\{[^}]*(?:opacity|animation)/);
});
});
describe("blink CSS: nothing blinks without a phase attribute", () => {
it.each([
["dot--blink-fast"],
["dot--blink-slow"],
["dot--ok", "dot--blink-fast"],
["dot--compacting", "dot--blink-slow"],
["dot--busy"],
["dot--ok"],
])("%s is solid", (...classes) => {
setPhase();
expect(opacityOf(mountDot(classes))).toBe(SOLID);
expect(opacityOf(mountDot(classes, { inTreeRow: true }))).toBe(SOLID);
});
});
describe("blink CSS: data-pi-blink-fast='dim'", () => {
it("dims .dot--blink-fast identically inside and outside .tree-row", () => {
setPhase({ fast: "dim" });
// The original bug in one line: the wrapper used to change the answer.
const outside = opacityOf(mountDot(["dot--ok", "dot--blink-fast"]));
const inside = opacityOf(mountDot(["dot--ok", "dot--blink-fast"], { inTreeRow: true }));
expect(outside).toBe(DIM);
expect(inside).toBe(DIM);
});
it("dims every real fast-blink combination (ok / busy / err)", () => {
setPhase({ fast: "dim" });
for (const colour of ["dot--ok", "dot--busy", "dot--err"]) {
expect(opacityOf(mountDot([colour, "dot--blink-fast"])), colour).toBe(DIM);
expect(opacityOf(mountDot([colour, "dot--blink-fast"], { inTreeRow: true })), colour).toBe(DIM);
}
});
it("leaves .dot--blink-slow, and colour-only .dot--idle/.dot--ok/.dot--attention solid", () => {
setPhase({ fast: "dim" });
expect(opacityOf(mountDot(["dot--ok", "dot--blink-slow"]))).toBe(SOLID);
expect(opacityOf(mountDot(["dot--compacting", "dot--blink-slow"]))).toBe(SOLID);
for (const colour of ["dot--idle", "dot--ok", "dot--attention", "dot--compacting", "dot--exited", "dot--dead"]) {
expect(opacityOf(mountDot([colour])), colour).toBe(SOLID);
expect(opacityOf(mountDot([colour], { inTreeRow: true })), `${colour} in tree-row`).toBe(SOLID);
}
});
it("does not dim a dot that also carries dot--blink-slow at the fast-phase step", () => {
// A dot only ever carries one rate (`DotView.blink` is a single value);
// if both were present the fast clock would still win, which is why the
// matrix must not emit both.
setPhase({ fast: "dim", slow: "on" });
expect(opacityOf(mountDot(["dot--busy", "dot--blink-fast", "dot--blink-slow"]))).toBe(DIM);
});
});
describe("blink CSS: data-pi-blink-slow='dim'", () => {
it("dims .dot--blink-slow identically inside and outside .tree-row", () => {
setPhase({ slow: "dim" });
expect(opacityOf(mountDot(["dot--compacting", "dot--blink-slow"]))).toBe(DIM);
expect(opacityOf(mountDot(["dot--compacting", "dot--blink-slow"], { inTreeRow: true }))).toBe(DIM);
});
it("leaves every fast-blink and colour-only dot solid", () => {
setPhase({ slow: "dim" });
for (const classes of [
["dot--ok", "dot--blink-fast"],
["dot--busy", "dot--blink-fast"],
["dot--err", "dot--blink-fast"],
["dot--idle"],
["dot--ok"],
["dot--attention"],
]) {
expect(opacityOf(mountDot(classes)), classes.join(" ")).toBe(SOLID);
expect(opacityOf(mountDot(classes, { inTreeRow: true })), `${classes.join(" ")} in tree-row`).toBe(SOLID);
}
});
});
describe("blink CSS: regression pin — the colour class alone can never blink", () => {
// The old sheet animated `.dot--busy`/`.dot--err` globally and `.dot--ok`
// inside `.tree-row`. A dot that asks for no blink must stay solid in every
// phase, in every wrapper: no re-introduced tree-scoped green, no
// forever-blinking red/green task dot.
const colourOnly = ["dot--busy", "dot--err", "dot--ok", "dot--attention", "dot--idle"];
it.each(colourOnly)("%s stays solid across every phase and wrapper", (colour) => {
for (const phase of [{}, { fast: "dim" as const }, { slow: "dim" as const }, { fast: "on" as const, slow: "on" as const }]) {
setPhase(phase);
expect(opacityOf(mountDot([colour])), `${colour} ${JSON.stringify(phase)}`).toBe(SOLID);
expect(opacityOf(mountDot([colour], { inTreeRow: true })), `${colour} in tree-row`).toBe(SOLID);
}
});
it("the same colour blinks only when the view asked for it", () => {
setPhase({ fast: "dim" });
// `ok` (a done row) blinks *because* of dot--blink-fast, not because of
// where it is mounted.
expect(opacityOf(mountDot(["dot--ok"]))).toBe(SOLID);
expect(opacityOf(mountDot(["dot--ok"], { inTreeRow: true }))).toBe(SOLID);
expect(opacityOf(mountDot(["dot--ok", "dot--blink-fast"]))).toBe(DIM);
expect(opacityOf(mountDot(["dot--ok", "dot--blink-fast"], { inTreeRow: true }))).toBe(DIM);
});
});