perf: reduce frontend idle CPU (#2965)
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "./lib/utils";
|
||||
|
||||
const DEFAULT_DURATION_MS = 1_000;
|
||||
const useCompositorEffect = typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;
|
||||
|
||||
/**
|
||||
* Keeps a persistent rotation on an HTML transform target so its SVG child can
|
||||
* remain static and be promoted without per-frame SVG style work.
|
||||
*/
|
||||
function CompositorSpin({ className, style, ...props }: React.ComponentProps<"span">) {
|
||||
const elementRef = React.useRef<HTMLSpanElement>(null);
|
||||
const [compositorReady, setCompositorReady] = React.useState(false);
|
||||
|
||||
useCompositorEffect(() => {
|
||||
const element = elementRef.current;
|
||||
if (!element || typeof element.animate !== "function") return;
|
||||
|
||||
element.style.removeProperty("animation");
|
||||
const computedStyle = window.getComputedStyle(element);
|
||||
const duration = parseAnimationDuration(computedStyle.animationDuration);
|
||||
element.style.animation = "none";
|
||||
void window.getComputedStyle(element).animationName;
|
||||
element.style.transform = "translateZ(0)";
|
||||
const animation = element.animate(
|
||||
[{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
|
||||
{
|
||||
duration,
|
||||
easing: "linear",
|
||||
iterations: Infinity,
|
||||
},
|
||||
);
|
||||
setCompositorReady(true);
|
||||
|
||||
return () => animation.cancel();
|
||||
}, [className]);
|
||||
|
||||
const compositorStyle = compositorReady
|
||||
? { ...style, animation: "none", transform: "translateZ(0)" }
|
||||
: style;
|
||||
|
||||
return (
|
||||
<span
|
||||
{...props}
|
||||
ref={elementRef}
|
||||
className={cn("inline-flex animate-spin will-change-transform", className)}
|
||||
style={compositorStyle}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parseAnimationDuration(value: string): number {
|
||||
const duration = value.split(",")[0]?.trim();
|
||||
if (!duration) return DEFAULT_DURATION_MS;
|
||||
|
||||
const numericValue = Number.parseFloat(duration);
|
||||
if (!Number.isFinite(numericValue)) return DEFAULT_DURATION_MS;
|
||||
return duration.endsWith("ms") ? numericValue : numericValue * 1_000;
|
||||
}
|
||||
|
||||
export { CompositorSpin };
|
||||
@@ -14,6 +14,7 @@ export * from "./chart";
|
||||
export * from "./checkbox";
|
||||
export * from "./collapsible";
|
||||
export * from "./command";
|
||||
export * from "./compositor-spin";
|
||||
export * from "./context-menu";
|
||||
export * from "./dialog";
|
||||
export * from "./drawer";
|
||||
|
||||
Generated
+9
@@ -571,6 +571,9 @@ importers:
|
||||
eslint-plugin-unused-imports:
|
||||
specifier: ^4.4.1
|
||||
version: 4.4.1(@typescript-eslint/eslint-plugin@8.53.0(@typescript-eslint/parser@8.53.0(eslint@9.39.2(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.2(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.2(jiti@2.7.0))
|
||||
fake-indexeddb:
|
||||
specifier: ^6.2.5
|
||||
version: 6.2.5
|
||||
happy-dom:
|
||||
specifier: ^20.8.9
|
||||
version: 20.8.9
|
||||
@@ -4159,6 +4162,10 @@ packages:
|
||||
extend@3.0.2:
|
||||
resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
|
||||
|
||||
fake-indexeddb@6.2.5:
|
||||
resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
fast-deep-equal@3.1.3:
|
||||
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
|
||||
|
||||
@@ -10075,6 +10082,8 @@ snapshots:
|
||||
|
||||
extend@3.0.2: {}
|
||||
|
||||
fake-indexeddb@6.2.5: {}
|
||||
|
||||
fast-deep-equal@3.1.3: {}
|
||||
|
||||
fast-equals@5.4.0: {}
|
||||
|
||||
@@ -4,6 +4,7 @@ import Link from "@/components/routing/app-link";
|
||||
import { usePathname } from "@/lib/routing/client-router";
|
||||
import { IconLoader2 } from "@tabler/icons-react";
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { AgentRunSummary } from "@/lib/api/domains/office-extended-api";
|
||||
import { timeAgo } from "@/lib/utils/time";
|
||||
@@ -84,11 +85,13 @@ function RecentRunsRow({ run, agentId, active }: RowProps) {
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{isRunning && (
|
||||
<IconLoader2
|
||||
className="h-3 w-3 animate-spin text-primary shrink-0"
|
||||
<CompositorSpin
|
||||
className="h-3 w-3 text-primary shrink-0"
|
||||
data-testid={`recent-run-row-running-icon-${run.id}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
>
|
||||
<IconLoader2 className="size-full" />
|
||||
</CompositorSpin>
|
||||
)}
|
||||
<span className="font-mono text-[11px]">{run.id_short}</span>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
|
||||
@@ -71,6 +71,13 @@ describe("AgentCard", () => {
|
||||
expect(screen.getByTestId(SUBTITLE_TESTID).textContent).toBe("Live now");
|
||||
const pill = screen.getByTestId(TASK_PILL_TESTID);
|
||||
expect(pill).toBeTruthy();
|
||||
const spinner = within(pill).getByTestId("agent-card-task-pill-spinner");
|
||||
expect(spinner.tagName).toBe("SPAN");
|
||||
expect(spinner.classList.contains("animate-spin")).toBe(true);
|
||||
expect(spinner.classList.contains("will-change-transform")).toBe(true);
|
||||
const spinnerSvg = spinner.querySelector("svg");
|
||||
expect(spinnerSvg).not.toBeNull();
|
||||
expect(spinnerSvg?.classList.contains("animate-spin")).toBe(false);
|
||||
expect(within(pill).getByText("KAN-3")).toBeTruthy();
|
||||
expect(within(pill).getByText("present yourself")).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { memo } from "react";
|
||||
import Link from "@/components/routing/app-link";
|
||||
import { IconExternalLink, IconLoader2 } from "@tabler/icons-react";
|
||||
import { Card } from "@kandev/ui/card";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import type { AgentSummary, SessionSummary } from "@/lib/api/domains/office-api";
|
||||
import { AgentAvatar as RoleAwareAgentAvatar } from "./agent-avatar";
|
||||
import { timeAgo } from "@/lib/utils/time";
|
||||
@@ -159,11 +160,12 @@ function TaskPill({ pill, isLive }: { pill: ActivePill; isLive: boolean }) {
|
||||
className="flex items-center gap-2 rounded-md border bg-muted/30 px-2 py-1 text-sm hover:bg-muted/50 transition-colors cursor-pointer truncate"
|
||||
>
|
||||
{isLive ? (
|
||||
<IconLoader2
|
||||
<CompositorSpin
|
||||
data-testid="agent-card-task-pill-spinner"
|
||||
className="h-3.5 w-3.5 shrink-0 animate-spin text-primary"
|
||||
aria-label={t("office:beingWorkedOn")}
|
||||
/>
|
||||
className="h-3.5 w-3.5 shrink-0 text-primary"
|
||||
>
|
||||
<IconLoader2 aria-label={t("office:beingWorkedOn")} className="size-full" />
|
||||
</CompositorSpin>
|
||||
) : null}
|
||||
{pill.identifier ? (
|
||||
<span className="font-mono text-xs text-muted-foreground shrink-0">{pill.identifier}</span>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useRouter } from "@/lib/routing/client-router";
|
||||
import { IconChevronRight, IconLoader2 } from "@tabler/icons-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { formatRelativeTime } from "@/lib/utils";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { selectLiveSessionForTask } from "@/lib/state/slices/session/selectors";
|
||||
@@ -70,10 +71,12 @@ export function TaskRow({
|
||||
<span className="w-3.5 shrink-0" />
|
||||
)}
|
||||
{isRunning ? (
|
||||
<IconLoader2
|
||||
className="h-4 w-4 shrink-0 animate-spin text-yellow-500"
|
||||
<CompositorSpin
|
||||
className="h-4 w-4 shrink-0 text-yellow-500"
|
||||
data-testid="task-row-running-spinner"
|
||||
/>
|
||||
>
|
||||
<IconLoader2 className="size-full" />
|
||||
</CompositorSpin>
|
||||
) : (
|
||||
<StatusIcon status={task.status} className="h-4 w-4 shrink-0" />
|
||||
)}
|
||||
|
||||
@@ -21,7 +21,7 @@ vi.mock("@/components/gitlab/mr-task-icon", () => ({
|
||||
}));
|
||||
|
||||
import { pluginRegistry } from "@/lib/plugins/registry";
|
||||
import { KanbanCardBody } from "./kanban-card-content";
|
||||
import { KanbanCardBody, renderTaskStatusIcon } from "./kanban-card-content";
|
||||
import type { Task } from "./kanban-card";
|
||||
|
||||
const TASK: Task = {
|
||||
@@ -72,6 +72,18 @@ describe("KanbanCardBody — task-card-indicators slot", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Kanban task status motion", () => {
|
||||
it("animates the fallback running status on an HTML wrapper", () => {
|
||||
const { container } = render(<>{renderTaskStatusIcon(TASK, true, false, false)}</>);
|
||||
const animated = container.querySelector(".animate-spin");
|
||||
|
||||
expect(animated?.tagName).toBe("SPAN");
|
||||
const svg = animated?.querySelector("svg");
|
||||
expect(svg).not.toBeNull();
|
||||
expect(svg?.classList.contains("animate-spin")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("KanbanCardBody — task-card-tags slot", () => {
|
||||
it("renders no extra markup when no plugin is registered for the slot (AC3)", () => {
|
||||
const { container } = render(<KanbanCardBody task={TASK} repositoryChips={[]} />);
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
IconAlertCircle,
|
||||
IconArrowsMaximize,
|
||||
IconDots,
|
||||
IconLoader2,
|
||||
IconLock,
|
||||
IconSubtask,
|
||||
IconUsersGroup,
|
||||
@@ -329,17 +328,16 @@ export function renderTaskStatusIcon(
|
||||
// session creation leaves a session-less SCHEDULING/IN_PROGRESS task, which
|
||||
// reads as showRunningSpinner=true — the exact shape the failure marker exists
|
||||
// to surface.
|
||||
if (
|
||||
const foregroundActivity =
|
||||
showRunningSpinner &&
|
||||
!needsMe &&
|
||||
!showAutoStartFailed &&
|
||||
task.foregroundActivity !== "background"
|
||||
) {
|
||||
return <IconLoader2 className="h-4 w-4 text-blue-500 animate-spin" />;
|
||||
}
|
||||
? "generating"
|
||||
: task.foregroundActivity;
|
||||
return getTaskStateIcon(task.state, "h-4 w-4", {
|
||||
hasPendingClarification,
|
||||
foregroundActivity: task.foregroundActivity,
|
||||
foregroundActivity,
|
||||
hasPendingPermission,
|
||||
interrupted: showInterrupted,
|
||||
autoStartFailed: showAutoStartFailed,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
IconShieldQuestion,
|
||||
} from "@tabler/icons-react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { renderSubagentCountChip, renderTaskStatusIcon } from "./kanban-card-content";
|
||||
import { AutoStartFailedTaskIcon } from "@/lib/ui/state-icons";
|
||||
import type { Task } from "./kanban-card";
|
||||
@@ -23,6 +24,9 @@ function task(overrides: Partial<Task>): Task {
|
||||
|
||||
function iconType(node: ReactNode) {
|
||||
if (!isValidElement(node)) throw new Error("Expected React element");
|
||||
if (node.type === CompositorSpin) {
|
||||
return iconType((node.props as { children: ReactNode }).children);
|
||||
}
|
||||
return node.type;
|
||||
}
|
||||
|
||||
|
||||
@@ -226,7 +226,12 @@ describe("MobileSessionsPicker activity precedence", () => {
|
||||
|
||||
// background-running: the shared spinner, in motion, and a label that says so.
|
||||
expect(svgClass(bg)).toContain("tabler-icon-loader-2");
|
||||
expect(svgClass(bg)).toContain("animate-spin");
|
||||
const spinner = bg.querySelector(".animate-spin");
|
||||
expect(spinner).not.toBeNull();
|
||||
expect(spinner?.tagName).toBe("SPAN");
|
||||
const spinnerSvg = spinner?.querySelector("svg");
|
||||
expect(spinnerSvg).not.toBeNull();
|
||||
expect(spinnerSvg?.classList.contains("animate-spin")).toBe(false);
|
||||
expect(bg.textContent).toMatch(/background/i);
|
||||
|
||||
// Distinct from generating: a static solid dot, no spin — a different SHAPE,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { IconChevronDown, IconLoader2 } from "@tabler/icons-react";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
|
||||
import { useSessionMessages } from "@/hooks/domains/session/use-session-messages";
|
||||
import { MessageRenderer } from "@/components/task/chat/message-renderer";
|
||||
@@ -73,7 +74,9 @@ export function AgentTurnPanel({
|
||||
<Collapsible open={open} onOpenChange={setOpen} className="mt-2">
|
||||
<CollapsibleTrigger className="flex items-center gap-2 w-full py-1 text-xs text-muted-foreground cursor-pointer hover:text-foreground transition-colors">
|
||||
{isLive ? (
|
||||
<IconLoader2 className="h-3 w-3 animate-spin text-primary shrink-0" />
|
||||
<CompositorSpin className="h-3 w-3 text-primary shrink-0">
|
||||
<IconLoader2 className="size-full" />
|
||||
</CompositorSpin>
|
||||
) : (
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/40 shrink-0" />
|
||||
)}
|
||||
|
||||
@@ -221,7 +221,11 @@ describe("SessionTimelineEntry — office (multi-agent)", () => {
|
||||
),
|
||||
);
|
||||
expect(screen.getByText(/working/)).toBeTruthy();
|
||||
expect(screen.getByTestId("session-state-running")).toBeTruthy();
|
||||
const spinner = screen.getByTestId("session-state-running");
|
||||
expect(spinner.tagName).toBe("SPAN");
|
||||
const spinnerSvg = spinner.querySelector("svg");
|
||||
expect(spinnerSvg).not.toBeNull();
|
||||
expect(spinnerSvg?.classList.contains("animate-spin")).toBe(false);
|
||||
// Embed visible because expanded by default while live.
|
||||
expect(screen.getByTestId(EMBED_TID)).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { forwardRef, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { IconChevronDown, IconLoader2 } from "@tabler/icons-react";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { selectOfficeAgentProfiles } from "@/lib/state/slices/office/selectors";
|
||||
@@ -106,10 +107,9 @@ function writePersistedCollapsed(sessionId: string, collapsed: boolean): void {
|
||||
function StateGlyph({ isLive, isTerminal }: { isLive: boolean; isTerminal: boolean }) {
|
||||
if (isLive) {
|
||||
return (
|
||||
<IconLoader2
|
||||
className="h-3 w-3 animate-spin text-primary shrink-0"
|
||||
data-testid="session-state-running"
|
||||
/>
|
||||
<CompositorSpin className="h-3 w-3 text-primary shrink-0" data-testid="session-state-running">
|
||||
<IconLoader2 className="size-full" />
|
||||
</CompositorSpin>
|
||||
);
|
||||
}
|
||||
return (
|
||||
|
||||
@@ -43,11 +43,14 @@ describe("TopbarWorkingIndicator", () => {
|
||||
|
||||
it("renders 'Working' button when a live session exists for the task", () => {
|
||||
const sessions = { "s-1": liveSession("task-1") };
|
||||
render(wrap(<TopbarWorkingIndicator taskId="task-1" />, sessions));
|
||||
const { container } = render(wrap(<TopbarWorkingIndicator taskId="task-1" />, sessions));
|
||||
expect(screen.getByTestId(INDICATOR_TID)).toBeTruthy();
|
||||
expect(screen.getByText("Working")).toBeTruthy();
|
||||
// E2E hook: a more specific data-testid only present while live.
|
||||
expect(screen.getByTestId("topbar-working-active")).toBeTruthy();
|
||||
const spinner = container.querySelector(".animate-spin");
|
||||
expect(spinner?.tagName).toBe("SPAN");
|
||||
expect(spinner?.querySelector("svg")?.classList.contains("animate-spin")).toBe(false);
|
||||
});
|
||||
|
||||
it("drops the spinner when an office session goes RUNNING → IDLE", () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { IconLoader2 } from "@tabler/icons-react";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { selectLiveSessionForTask } from "@/lib/state/slices/session/selectors";
|
||||
import { useActiveSessionRef } from "./active-session-ref-context";
|
||||
@@ -38,7 +39,9 @@ export function TopbarWorkingIndicator({ taskId }: TopbarWorkingIndicatorProps)
|
||||
aria-label={t("task:scrollToActiveSession")}
|
||||
data-testid="topbar-working-indicator"
|
||||
>
|
||||
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
<CompositorSpin className="h-3.5 w-3.5">
|
||||
<IconLoader2 className="size-full" />
|
||||
</CompositorSpin>
|
||||
<span data-testid="topbar-working-active">{t("task:working3")}</span>
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -32,7 +32,12 @@ describe("UserCommentRunBadge", () => {
|
||||
expect(badge.getAttribute(DATA_STATUS)).toBe("claimed");
|
||||
expect(badge.textContent).toContain("Working");
|
||||
// Spinner uses the animate-spin utility class.
|
||||
expect(container.querySelector(".animate-spin")).toBeTruthy();
|
||||
const spinner = container.querySelector(".animate-spin");
|
||||
expect(spinner).not.toBeNull();
|
||||
expect(spinner?.tagName).toBe("SPAN");
|
||||
const spinnerSvg = spinner?.querySelector("svg");
|
||||
expect(spinnerSvg).not.toBeNull();
|
||||
expect(spinnerSvg?.classList.contains("animate-spin")).toBe(false);
|
||||
});
|
||||
|
||||
it("renders nothing for status=finished", () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { IconAlertCircle, IconLoader2 } from "@tabler/icons-react";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import type { TaskRunStatus } from "@/app/office/tasks/[id]/types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -53,7 +54,9 @@ export function UserCommentRunBadge({ status, errorMessage }: UserCommentRunBadg
|
||||
data-testid="user-comment-run-badge"
|
||||
data-status={status}
|
||||
>
|
||||
<IconLoader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
<CompositorSpin className="h-3 w-3" aria-hidden>
|
||||
<IconLoader2 className="size-full" />
|
||||
</CompositorSpin>
|
||||
{t("task:working4")}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -116,6 +116,19 @@ function expectPreparingSpinner(): void {
|
||||
}
|
||||
|
||||
describe("TaskItem status icon", () => {
|
||||
it("animates the running status on an HTML wrapper", () => {
|
||||
renderTaskItem({ state: "IN_PROGRESS", sessionState: "RUNNING" });
|
||||
|
||||
const spinner = screen.getByTestId(RUNNING_ICON_TEST_ID);
|
||||
expect(spinner.tagName).toBe("SPAN");
|
||||
expect(spinner.classList.contains(SPIN_CLASS)).toBe(true);
|
||||
const spinnerSvg = spinner.querySelector("svg");
|
||||
expect(spinnerSvg).not.toBeNull();
|
||||
expect(spinnerSvg?.classList.contains(SPIN_CLASS)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TaskItem status icon states", () => {
|
||||
it("shows the autopilot icon with an accessible description", () => {
|
||||
renderTaskItem({ autopilot: true });
|
||||
|
||||
@@ -188,7 +201,9 @@ describe("TaskItem status icon", () => {
|
||||
|
||||
expectPreparingSpinner();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TaskItem status icon fallbacks", () => {
|
||||
it("does not show a spinner for a created task waiting for manual start", () => {
|
||||
renderTaskItem({ state: "CREATED" });
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import { TaskItemComparisonUnavailable } from "./task-item-comparison-unavailabl
|
||||
import type { WipQueueStatus } from "@/lib/kanban/wip-queue";
|
||||
import { TaskMenuButton } from "./task-item-menu-button";
|
||||
import { TaskItemLeadingBadges } from "./task-item-leading-badges";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
|
||||
type DiffStats = {
|
||||
additions: number;
|
||||
@@ -189,11 +190,13 @@ function BackgroundWorkTaskIcon() {
|
||||
tabIndex={0}
|
||||
className="mt-[1px] flex shrink-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-500 focus-visible:ring-offset-1"
|
||||
>
|
||||
<IconCircleDashed
|
||||
<CompositorSpin
|
||||
aria-hidden="true"
|
||||
data-testid="task-state-background-running"
|
||||
className="h-3.5 w-3.5 shrink-0 animate-spin text-violet-500"
|
||||
/>
|
||||
className="h-3.5 w-3.5 shrink-0 text-violet-500"
|
||||
>
|
||||
<IconCircleDashed className="size-full" />
|
||||
</CompositorSpin>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">{t("task:backgroundWorkIsRunning")}</TooltipContent>
|
||||
@@ -201,6 +204,24 @@ function BackgroundWorkTaskIcon() {
|
||||
);
|
||||
}
|
||||
|
||||
function TaskRunningIcon({
|
||||
phase,
|
||||
className,
|
||||
}: {
|
||||
phase: "running" | "preparing";
|
||||
className: string;
|
||||
}) {
|
||||
return (
|
||||
<CompositorSpin
|
||||
data-testid="task-state-running"
|
||||
data-loading-phase={phase}
|
||||
className={className}
|
||||
>
|
||||
<IconCircleDashed className="size-full" />
|
||||
</CompositorSpin>
|
||||
);
|
||||
}
|
||||
|
||||
function TaskStateIcon({
|
||||
sessionState,
|
||||
state,
|
||||
@@ -239,11 +260,7 @@ function TaskStateIcon({
|
||||
}
|
||||
if (foregroundActivity === "generating") {
|
||||
return (
|
||||
<IconCircleDashed
|
||||
data-testid="task-state-running"
|
||||
data-loading-phase="running"
|
||||
className="mt-[1px] h-3.5 w-3.5 shrink-0 text-yellow-500 animate-spin"
|
||||
/>
|
||||
<TaskRunningIcon phase="running" className="mt-[1px] h-3.5 w-3.5 shrink-0 text-yellow-500" />
|
||||
);
|
||||
}
|
||||
if (foregroundActivity === "background") {
|
||||
@@ -259,10 +276,9 @@ function TaskStateIcon({
|
||||
}
|
||||
if (computeIsPreparing(state, sessionState)) {
|
||||
return (
|
||||
<IconCircleDashed
|
||||
data-testid="task-state-running"
|
||||
data-loading-phase="preparing"
|
||||
className="mt-[1px] h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground/40 [animation-duration:2s]"
|
||||
<TaskRunningIcon
|
||||
phase="preparing"
|
||||
className="mt-[1px] h-3.5 w-3.5 shrink-0 text-muted-foreground/40 [animation-duration:2s]"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -270,11 +286,7 @@ function TaskStateIcon({
|
||||
// established generating spinner rather than a done affordance.
|
||||
if (isInProgress) {
|
||||
return (
|
||||
<IconCircleDashed
|
||||
data-testid="task-state-running"
|
||||
data-loading-phase="running"
|
||||
className="mt-[1px] h-3.5 w-3.5 shrink-0 text-yellow-500 animate-spin"
|
||||
/>
|
||||
<TaskRunningIcon phase="running" className="mt-[1px] h-3.5 w-3.5 shrink-0 text-yellow-500" />
|
||||
);
|
||||
}
|
||||
// The task's session was mid-turn when the backend died (startup
|
||||
|
||||
@@ -151,7 +151,25 @@ test.describe("Office agent run detail", () => {
|
||||
await expect(otherRow).not.toHaveAttribute("aria-current", "page");
|
||||
|
||||
// The running row carries the animated icon testid.
|
||||
await expect(testPage.getByTestId(`recent-run-row-running-icon-${runningId}`)).toBeVisible();
|
||||
const runningIcon = testPage.getByTestId(`recent-run-row-running-icon-${runningId}`);
|
||||
await expect(runningIcon).toBeVisible();
|
||||
await expect
|
||||
.poll(() =>
|
||||
runningIcon.evaluate((element) => ({
|
||||
tagName: element.tagName,
|
||||
wrapperAnimated: element.classList.contains("animate-spin"),
|
||||
promoted: element.classList.contains("will-change-transform"),
|
||||
svgCount: element.querySelectorAll("svg").length,
|
||||
svgAnimated: element.querySelector("svg")?.classList.contains("animate-spin") ?? false,
|
||||
})),
|
||||
)
|
||||
.toEqual({
|
||||
tagName: "SPAN",
|
||||
wrapperAnimated: true,
|
||||
promoted: true,
|
||||
svgCount: 1,
|
||||
svgAnimated: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("run detail renders header, sidebar highlight, conversation, and events", async ({
|
||||
|
||||
@@ -21,7 +21,10 @@ test.describe("Mobile task status summary", () => {
|
||||
"Mobile summary navigation",
|
||||
stepOptions,
|
||||
);
|
||||
const targetTask = await apiClient.seedTask(seedData.workspaceId, TARGET_TITLE, stepOptions);
|
||||
const targetTask = await apiClient.seedTask(seedData.workspaceId, TARGET_TITLE, {
|
||||
...stepOptions,
|
||||
state: "IN_PROGRESS",
|
||||
});
|
||||
await apiClient.seedTaskSession(navTask.task_id, {
|
||||
state: "WAITING_FOR_INPUT",
|
||||
agentProfileId: seedData.agentProfileId,
|
||||
@@ -41,6 +44,21 @@ test.describe("Mobile task status summary", () => {
|
||||
});
|
||||
await expect(targetRow).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await apiClient.seedTaskSession(targetTask.task_id, {
|
||||
sessionId: targetSession.session_id,
|
||||
state: "RUNNING",
|
||||
});
|
||||
const runningStatus = targetRow.getByTestId("task-state-running");
|
||||
await expect(runningStatus).toBeVisible({ timeout: 15_000 });
|
||||
await expect
|
||||
.poll(async () =>
|
||||
runningStatus.evaluate((element) => ({
|
||||
tagName: element.tagName,
|
||||
svgAnimated: element.querySelector("svg")?.classList.contains("animate-spin") ?? false,
|
||||
})),
|
||||
)
|
||||
.toEqual({ tagName: "SPAN", svgAnimated: false });
|
||||
|
||||
await apiClient.seedSessionMessage(targetSession.session_id, {
|
||||
type: "clarification_request",
|
||||
content: "Choose a mobile-safe approach",
|
||||
|
||||
@@ -16,8 +16,9 @@
|
||||
* post-settle fresh load only hydrates the durable settled state and would pass
|
||||
* against an unfixed parent revision.
|
||||
*/
|
||||
import { expect, test } from "../../fixtures/test-base";
|
||||
import { expect } from "@playwright/test";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
import { test } from "../../fixtures/test-base";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
|
||||
/** Hold RUNNING long enough for the sidebar spinner assertion, then finish. */
|
||||
@@ -84,6 +85,15 @@ test.describe("Sidebar spinner clears when a session settles", () => {
|
||||
await expect(settledRow.getByTestId("task-state-running")).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
const runningStatus = settledRow.getByTestId("task-state-running");
|
||||
await expect
|
||||
.poll(async () =>
|
||||
runningStatus.evaluate((element) => ({
|
||||
tagName: element.tagName,
|
||||
svgAnimated: element.querySelector("svg")?.classList.contains("animate-spin") ?? false,
|
||||
})),
|
||||
)
|
||||
.toEqual({ tagName: "SPAN", svgAnimated: false });
|
||||
|
||||
await waitForSessionWaitingForInput(
|
||||
apiClient,
|
||||
|
||||
@@ -1,9 +1,30 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import "fake-indexeddb/auto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { retentionPlan } from "./indexeddb-store";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LogEntry } from "./buffer";
|
||||
import { IndexedDBLogStore, retentionPlan } from "./indexeddb-store";
|
||||
|
||||
describe("IndexedDB log retention", () => {
|
||||
const DATABASE_NAME = "kandev-diagnostic-logs-v1";
|
||||
const ENTRIES_STORE = "entries";
|
||||
const METADATA_STORE = "metadata";
|
||||
const RETENTION_KEY = "retention";
|
||||
const MAX_ENTRIES = 10_000;
|
||||
const MAX_BYTES = 20 * 1024 * 1024;
|
||||
const THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1000;
|
||||
|
||||
type PersistedTestEntry = {
|
||||
id?: number;
|
||||
identity_scope: string;
|
||||
timestamp_ms: number;
|
||||
bytes: number;
|
||||
entry: LogEntry;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
await deleteDatabase();
|
||||
});
|
||||
|
||||
describe("IndexedDB log retention planning and schema", () => {
|
||||
it("prunes age first and then oldest records until count and byte caps hold", () => {
|
||||
const now = Date.UTC(2026, 6, 30);
|
||||
const records = [
|
||||
@@ -27,11 +48,314 @@ describe("IndexedDB log retention", () => {
|
||||
expect(result.retainedCount).toBe(10_000);
|
||||
});
|
||||
|
||||
it("walks the timestamp index without materializing the full store", () => {
|
||||
const source = readFileSync("lib/logger/indexeddb-store.ts", "utf8");
|
||||
it("initializes version two totals without changing the database name", async () => {
|
||||
const store = new IndexedDBLogStore();
|
||||
|
||||
expect(source).toContain('index("timestamp_ms")');
|
||||
expect(source).toContain("index.openCursor()");
|
||||
expect(source).not.toContain("store.getAll()");
|
||||
await expect(store.snapshot("a")).resolves.toEqual([]);
|
||||
|
||||
const database = await openDatabase();
|
||||
expect(database.name).toBe(DATABASE_NAME);
|
||||
expect(database.version).toBe(2);
|
||||
expect([...database.objectStoreNames]).toEqual([ENTRIES_STORE, METADATA_STORE]);
|
||||
database.close();
|
||||
|
||||
await expect(readMetadata()).resolves.toEqual({
|
||||
key: RETENTION_KEY,
|
||||
count: 0,
|
||||
bytes: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("rebuilds totals once while upgrading an existing version one database", async () => {
|
||||
const now = Date.now();
|
||||
const first = logEntry("a", now - 2_000, "first");
|
||||
const second = logEntry("b", now - 1_000, "second");
|
||||
await createVersionOneDatabase([
|
||||
persisted(first, now - 2_000, 11),
|
||||
persisted(second, now - 1_000, 22),
|
||||
]);
|
||||
|
||||
const store = new IndexedDBLogStore();
|
||||
await expect(store.snapshot("a")).resolves.toEqual([first]);
|
||||
await expect(readMetadata()).resolves.toEqual({
|
||||
key: RETENTION_KEY,
|
||||
count: 2,
|
||||
bytes: 33,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a blocked schema upgrade and retries after the older tab closes", async () => {
|
||||
const blocker = await openVersionOneDatabase();
|
||||
const store = new IndexedDBLogStore();
|
||||
|
||||
try {
|
||||
await expect(store.append([logEntry("a", Date.now(), "blocked")])).rejects.toThrow(
|
||||
"IndexedDB upgrade blocked",
|
||||
);
|
||||
} finally {
|
||||
blocker.close();
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
await expect(store.append([logEntry("a", Date.now(), "retried")])).resolves.toBeUndefined();
|
||||
await expect(store.snapshot("a")).resolves.toEqual([
|
||||
expect.objectContaining({ message: "retried" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("IndexedDB log retention writes", () => {
|
||||
it("retains the newest entries and records exact transactional totals", async () => {
|
||||
const now = Date.now();
|
||||
const store = new IndexedDBLogStore();
|
||||
const entries = [
|
||||
logEntry("a", now - THREE_DAYS_MS - 1, "expired"),
|
||||
...Array.from({ length: MAX_ENTRIES }, (_, index) =>
|
||||
logEntry("a", now - 1_000 + index, `entry-${index}`),
|
||||
),
|
||||
];
|
||||
|
||||
await store.append(entries);
|
||||
|
||||
const records = await readEntries();
|
||||
expect(records).toHaveLength(MAX_ENTRIES);
|
||||
expect(records[0].entry.message).toBe("entry-0");
|
||||
expect(records.at(-1)?.entry.message).toBe(`entry-${MAX_ENTRIES - 1}`);
|
||||
await expect(readMetadata()).resolves.toEqual({
|
||||
key: RETENTION_KEY,
|
||||
count: MAX_ENTRIES,
|
||||
bytes: records.reduce((total, record) => total + record.bytes, 0),
|
||||
});
|
||||
});
|
||||
|
||||
it("evicts the oldest rows only until the byte cap holds", async () => {
|
||||
const now = Date.now();
|
||||
const store = new IndexedDBLogStore();
|
||||
const entries = Array.from({ length: 4_300 }, (_, index) =>
|
||||
logEntry("a", now - 4_300 + index, `${index}-${"x".repeat(5_000)}`),
|
||||
);
|
||||
|
||||
await store.append(entries);
|
||||
|
||||
const records = await readEntries();
|
||||
const metadata = await readMetadata();
|
||||
expect(metadata.count).toBe(records.length);
|
||||
expect(metadata.bytes).toBe(records.reduce((total, record) => total + record.bytes, 0));
|
||||
expect(metadata.count).toBeLessThan(MAX_ENTRIES);
|
||||
expect(metadata.bytes).toBeLessThanOrEqual(MAX_BYTES);
|
||||
expect(records.at(-1)?.entry.message).toContain("4299-");
|
||||
expect(records[0].entry.message).not.toContain("0-");
|
||||
});
|
||||
|
||||
it("keeps identity snapshots partitioned while sharing the global caps", async () => {
|
||||
const store = new IndexedDBLogStore();
|
||||
await store.append([
|
||||
logEntry("identity-a", Date.now(), "a"),
|
||||
logEntry("identity-b", Date.now() + 1, "b"),
|
||||
]);
|
||||
|
||||
await expect(store.snapshot("identity-a")).resolves.toHaveLength(1);
|
||||
await expect(store.snapshot("identity-b")).resolves.toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("IndexedDB log retention repair and concurrency", () => {
|
||||
it("repairs missing or invalid totals during the next write", async () => {
|
||||
const store = new IndexedDBLogStore();
|
||||
await store.append([logEntry("a", Date.now(), "before repair")]);
|
||||
await overwriteMetadata({ key: RETENTION_KEY, count: -1, bytes: Number.NaN });
|
||||
|
||||
await store.append([logEntry("a", Date.now() + 1, "after repair")]);
|
||||
|
||||
const records = await readEntries();
|
||||
await expect(readMetadata()).resolves.toEqual({
|
||||
key: RETENTION_KEY,
|
||||
count: records.length,
|
||||
bytes: records.reduce((total, record) => total + record.bytes, 0),
|
||||
});
|
||||
});
|
||||
|
||||
it("clears entries and resets totals in one transaction", async () => {
|
||||
const store = new IndexedDBLogStore();
|
||||
await store.append([logEntry("a", Date.now(), "to clear")]);
|
||||
|
||||
await store.clear();
|
||||
|
||||
await expect(readEntries()).resolves.toEqual([]);
|
||||
await expect(readMetadata()).resolves.toEqual({
|
||||
key: RETENTION_KEY,
|
||||
count: 0,
|
||||
bytes: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps concurrent store instances transactionally consistent", async () => {
|
||||
const stores = [new IndexedDBLogStore(), new IndexedDBLogStore()];
|
||||
const batches = Array.from({ length: 24 }, (_, batchIndex) =>
|
||||
Array.from({ length: 8 }, (_, entryIndex) =>
|
||||
logEntry(
|
||||
"a",
|
||||
Date.now() + batchIndex * 10 + entryIndex,
|
||||
`batch-${batchIndex}-${entryIndex}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await Promise.all(batches.map((batch, index) => stores[index % stores.length].append(batch)));
|
||||
|
||||
const records = await readEntries();
|
||||
const metadata = await readMetadata();
|
||||
expect(records).toHaveLength(24 * 8);
|
||||
expect(metadata).toEqual({
|
||||
key: RETENTION_KEY,
|
||||
count: records.length,
|
||||
bytes: records.reduce((total, record) => total + record.bytes, 0),
|
||||
});
|
||||
});
|
||||
|
||||
it("uses only the bounded timestamp cursor for a within-limit append", async () => {
|
||||
const store = new IndexedDBLogStore();
|
||||
await store.append([logEntry("a", Date.now(), "first")]);
|
||||
|
||||
const objectStoreCursor = vi.spyOn(IDBObjectStore.prototype, "openCursor");
|
||||
const timestampCursor = vi.spyOn(IDBIndex.prototype, "openCursor");
|
||||
|
||||
try {
|
||||
await store.append([logEntry("a", Date.now() + 1, "second")]);
|
||||
|
||||
expect(objectStoreCursor).not.toHaveBeenCalled();
|
||||
expect(timestampCursor).toHaveBeenCalledTimes(1);
|
||||
expect(timestampCursor.mock.calls[0]?.[0]).toBeInstanceOf(IDBKeyRange);
|
||||
expect(timestampCursor.mock.calls[0]?.[0]).toMatchObject({
|
||||
upper: expect.any(Number),
|
||||
});
|
||||
} finally {
|
||||
objectStoreCursor.mockRestore();
|
||||
timestampCursor.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function logEntry(identityScope: string, timestamp: number, message: string): LogEntry {
|
||||
return {
|
||||
timestamp: new Date(timestamp).toISOString(),
|
||||
level: "info",
|
||||
source: "test",
|
||||
message,
|
||||
identity_scope: identityScope,
|
||||
};
|
||||
}
|
||||
|
||||
function persisted(entry: LogEntry, timestamp: number, bytes: number): PersistedTestEntry {
|
||||
return {
|
||||
identity_scope: entry.identity_scope ?? "",
|
||||
timestamp_ms: timestamp,
|
||||
bytes,
|
||||
entry,
|
||||
};
|
||||
}
|
||||
|
||||
function deleteDatabase(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.deleteDatabase(DATABASE_NAME);
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () => reject(request.error ?? new Error("failed to delete test database"));
|
||||
});
|
||||
}
|
||||
|
||||
function openDatabase(version?: number): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request =
|
||||
version === undefined
|
||||
? indexedDB.open(DATABASE_NAME)
|
||||
: indexedDB.open(DATABASE_NAME, version);
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error ?? new Error("failed to open test database"));
|
||||
});
|
||||
}
|
||||
|
||||
function createVersionOneDatabase(records: PersistedTestEntry[]): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DATABASE_NAME, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
const store = request.result.createObjectStore(ENTRIES_STORE, {
|
||||
keyPath: "id",
|
||||
autoIncrement: true,
|
||||
});
|
||||
store.createIndex("identity_scope", "identity_scope", { unique: false });
|
||||
store.createIndex("timestamp_ms", "timestamp_ms", { unique: false });
|
||||
};
|
||||
request.onerror = () =>
|
||||
reject(request.error ?? new Error("failed to create version one database"));
|
||||
request.onsuccess = () => {
|
||||
const database = request.result;
|
||||
const transaction = database.transaction(ENTRIES_STORE, "readwrite");
|
||||
for (const record of records) transaction.objectStore(ENTRIES_STORE).add(record);
|
||||
transaction.oncomplete = () => {
|
||||
database.close();
|
||||
resolve();
|
||||
};
|
||||
transaction.onerror = () =>
|
||||
reject(transaction.error ?? new Error("failed to seed version one database"));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function openVersionOneDatabase(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DATABASE_NAME, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
const store = request.result.createObjectStore(ENTRIES_STORE, {
|
||||
keyPath: "id",
|
||||
autoIncrement: true,
|
||||
});
|
||||
store.createIndex("identity_scope", "identity_scope", { unique: false });
|
||||
store.createIndex("timestamp_ms", "timestamp_ms", { unique: false });
|
||||
};
|
||||
request.onerror = () =>
|
||||
reject(request.error ?? new Error("failed to open version one blocker"));
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
|
||||
async function readEntries(): Promise<PersistedTestEntry[]> {
|
||||
const database = await openDatabase();
|
||||
const transaction = database.transaction(ENTRIES_STORE, "readonly");
|
||||
const request = transaction.objectStore(ENTRIES_STORE).getAll();
|
||||
const records = await requestResult(request);
|
||||
await transactionComplete(transaction);
|
||||
database.close();
|
||||
return records as PersistedTestEntry[];
|
||||
}
|
||||
|
||||
async function readMetadata(): Promise<Record<string, unknown>> {
|
||||
const database = await openDatabase();
|
||||
const transaction = database.transaction(METADATA_STORE, "readonly");
|
||||
const value = await requestResult(transaction.objectStore(METADATA_STORE).get(RETENTION_KEY));
|
||||
await transactionComplete(transaction);
|
||||
database.close();
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
async function overwriteMetadata(value: Record<string, unknown>): Promise<void> {
|
||||
const database = await openDatabase();
|
||||
const transaction = database.transaction(METADATA_STORE, "readwrite");
|
||||
transaction.objectStore(METADATA_STORE).put(value);
|
||||
await transactionComplete(transaction);
|
||||
database.close();
|
||||
}
|
||||
|
||||
function requestResult<T>(request: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error ?? new Error("test request failed"));
|
||||
});
|
||||
}
|
||||
|
||||
function transactionComplete(transaction: IDBTransaction): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(transaction.error ?? new Error("test transaction failed"));
|
||||
transaction.onabort = () => reject(transaction.error ?? new Error("test transaction aborted"));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { LogEntry } from "./buffer";
|
||||
|
||||
const DATABASE_NAME = "kandev-diagnostic-logs-v1";
|
||||
const DATABASE_VERSION = 2;
|
||||
const STORE_NAME = "entries";
|
||||
const METADATA_STORE_NAME = "metadata";
|
||||
const RETENTION_METADATA_KEY = "retention";
|
||||
const THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1000;
|
||||
const MAX_ENTRIES = 10_000;
|
||||
const MAX_BYTES = 20 * 1024 * 1024;
|
||||
@@ -14,27 +17,55 @@ type PersistedEntry = {
|
||||
entry: LogEntry;
|
||||
};
|
||||
|
||||
type RetentionTotals = { count: number; bytes: number };
|
||||
|
||||
type RetentionMetadata = RetentionTotals & { key: string };
|
||||
|
||||
const EMPTY_TOTALS: RetentionTotals = { count: 0, bytes: 0 };
|
||||
|
||||
export class IndexedDBLogStore {
|
||||
private database: Promise<IDBDatabase> | null = null;
|
||||
|
||||
async append(entries: LogEntry[]): Promise<void> {
|
||||
if (entries.length === 0) return;
|
||||
const database = await this.open();
|
||||
const transaction = database.transaction(STORE_NAME, "readwrite");
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
for (const entry of entries) {
|
||||
const persistedEntries = entries.flatMap((entry) => {
|
||||
const identity = entry.identity_scope;
|
||||
if (!identity) continue;
|
||||
if (!identity) return [];
|
||||
|
||||
const serialized = JSON.stringify(entry);
|
||||
store.add({
|
||||
identity_scope: identity,
|
||||
timestamp_ms: Date.parse(entry.timestamp) || Date.now(),
|
||||
bytes: new TextEncoder().encode(serialized).byteLength,
|
||||
entry,
|
||||
} satisfies PersistedEntry);
|
||||
const timestamp = Date.parse(entry.timestamp);
|
||||
return [
|
||||
{
|
||||
identity_scope: identity,
|
||||
timestamp_ms: Number.isNaN(timestamp) ? Date.now() : timestamp,
|
||||
bytes: new TextEncoder().encode(serialized).byteLength,
|
||||
entry,
|
||||
} satisfies PersistedEntry,
|
||||
];
|
||||
});
|
||||
if (persistedEntries.length === 0) return;
|
||||
|
||||
const database = await this.open();
|
||||
const transaction = database.transaction([STORE_NAME, METADATA_STORE_NAME], "readwrite");
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const metadataStore = transaction.objectStore(METADATA_STORE_NAME);
|
||||
const storedMetadata = await requestResult<RetentionMetadata | undefined>(
|
||||
metadataStore.get(RETENTION_METADATA_KEY),
|
||||
);
|
||||
const totals = isValidTotals(storedMetadata)
|
||||
? { count: storedMetadata.count, bytes: storedMetadata.bytes }
|
||||
: await scanTotals(store);
|
||||
|
||||
for (const entry of persistedEntries) {
|
||||
store.add(entry);
|
||||
totals.count += 1;
|
||||
totals.bytes += entry.bytes;
|
||||
}
|
||||
|
||||
const cutoff = Date.now() - THREE_DAYS_MS;
|
||||
await deleteExpiredPrefix(store.index("timestamp_ms"), cutoff, totals);
|
||||
await deleteOldestUntilWithinBounds(store.index("timestamp_ms"), totals);
|
||||
metadataStore.put({ key: RETENTION_METADATA_KEY, ...totals } satisfies RetentionMetadata);
|
||||
await transactionDone(transaction);
|
||||
await this.prune();
|
||||
}
|
||||
|
||||
async snapshot(identityScope: string): Promise<LogEntry[]> {
|
||||
@@ -54,47 +85,102 @@ export class IndexedDBLogStore {
|
||||
|
||||
async clear(): Promise<void> {
|
||||
const database = await this.open();
|
||||
const transaction = database.transaction(STORE_NAME, "readwrite");
|
||||
const transaction = database.transaction([STORE_NAME, METADATA_STORE_NAME], "readwrite");
|
||||
transaction.objectStore(STORE_NAME).clear();
|
||||
const metadataStore = transaction.objectStore(METADATA_STORE_NAME);
|
||||
metadataStore.clear();
|
||||
metadataStore.put({ key: RETENTION_METADATA_KEY, ...EMPTY_TOTALS } satisfies RetentionMetadata);
|
||||
await transactionDone(transaction);
|
||||
}
|
||||
|
||||
private open(): Promise<IDBDatabase> {
|
||||
if (this.database) return this.database;
|
||||
if (typeof indexedDB === "undefined") return Promise.reject(new Error("IndexedDB unavailable"));
|
||||
this.database = new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DATABASE_NAME, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
const store = request.result.createObjectStore(STORE_NAME, {
|
||||
keyPath: "id",
|
||||
autoIncrement: true,
|
||||
});
|
||||
store.createIndex("identity_scope", "identity_scope", { unique: false });
|
||||
store.createIndex("timestamp_ms", "timestamp_ms", { unique: false });
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed"));
|
||||
});
|
||||
return this.database;
|
||||
}
|
||||
|
||||
private async prune(): Promise<void> {
|
||||
const database = await this.open();
|
||||
const transaction = database.transaction(STORE_NAME, "readwrite");
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const index = store.index("timestamp_ms");
|
||||
const totals = await scanAndDeleteExpired(index, Date.now() - THREE_DAYS_MS);
|
||||
await deleteOldestUntilWithinBounds(index, totals);
|
||||
await transactionDone(transaction);
|
||||
let failed = false;
|
||||
const databasePromise = new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const fail = (error: Error) => {
|
||||
if (failed) return;
|
||||
failed = true;
|
||||
if (this.database === databasePromise) this.database = null;
|
||||
reject(error);
|
||||
};
|
||||
const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
const database = request.result;
|
||||
const transaction = request.transaction;
|
||||
if (!transaction) {
|
||||
fail(new Error("IndexedDB upgrade transaction unavailable"));
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = database.objectStoreNames.contains(STORE_NAME)
|
||||
? transaction.objectStore(STORE_NAME)
|
||||
: createEntriesStore(database);
|
||||
const metadata = database.objectStoreNames.contains(METADATA_STORE_NAME)
|
||||
? transaction.objectStore(METADATA_STORE_NAME)
|
||||
: database.createObjectStore(METADATA_STORE_NAME, { keyPath: "key" });
|
||||
|
||||
rebuildTotalsDuringUpgrade(entries, metadata);
|
||||
};
|
||||
request.onblocked = () => fail(new Error("IndexedDB upgrade blocked"));
|
||||
request.onsuccess = () => {
|
||||
const database = request.result;
|
||||
if (failed) {
|
||||
database.close();
|
||||
return;
|
||||
}
|
||||
database.onversionchange = () => database.close();
|
||||
resolve(database);
|
||||
};
|
||||
request.onerror = () => fail(request.error ?? new Error("IndexedDB open failed"));
|
||||
});
|
||||
this.database = databasePromise;
|
||||
return databasePromise;
|
||||
}
|
||||
}
|
||||
|
||||
type RetentionTotals = { count: number; bytes: number };
|
||||
function createEntriesStore(database: IDBDatabase): IDBObjectStore {
|
||||
const store = database.createObjectStore(STORE_NAME, {
|
||||
keyPath: "id",
|
||||
autoIncrement: true,
|
||||
});
|
||||
store.createIndex("identity_scope", "identity_scope", { unique: false });
|
||||
store.createIndex("timestamp_ms", "timestamp_ms", { unique: false });
|
||||
return store;
|
||||
}
|
||||
|
||||
function scanAndDeleteExpired(index: IDBIndex, cutoff: number): Promise<RetentionTotals> {
|
||||
function rebuildTotalsDuringUpgrade(entries: IDBObjectStore, metadata: IDBObjectStore): void {
|
||||
const totals = { ...EMPTY_TOTALS };
|
||||
const request = entries.openCursor();
|
||||
request.onerror = () => request.transaction?.abort();
|
||||
request.onsuccess = () => {
|
||||
const cursor = request.result;
|
||||
if (!cursor) {
|
||||
metadata.put({ key: RETENTION_METADATA_KEY, ...totals } satisfies RetentionMetadata);
|
||||
return;
|
||||
}
|
||||
const record = cursor.value as PersistedEntry;
|
||||
totals.count += 1;
|
||||
totals.bytes += record.bytes;
|
||||
cursor.continue();
|
||||
};
|
||||
}
|
||||
|
||||
function isValidTotals(value: RetentionMetadata | undefined): value is RetentionMetadata {
|
||||
return (
|
||||
value?.key === RETENTION_METADATA_KEY &&
|
||||
Number.isSafeInteger(value.count) &&
|
||||
value.count >= 0 &&
|
||||
Number.isFinite(value.bytes) &&
|
||||
value.bytes >= 0
|
||||
);
|
||||
}
|
||||
|
||||
function scanTotals(store: IDBObjectStore): Promise<RetentionTotals> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const totals = { count: 0, bytes: 0 };
|
||||
const request = index.openCursor();
|
||||
const totals = { ...EMPTY_TOTALS };
|
||||
const request = store.openCursor();
|
||||
request.onerror = () => reject(request.error ?? new Error("IndexedDB cursor failed"));
|
||||
request.onsuccess = () => {
|
||||
const cursor = request.result;
|
||||
@@ -103,12 +189,31 @@ function scanAndDeleteExpired(index: IDBIndex, cutoff: number): Promise<Retentio
|
||||
return;
|
||||
}
|
||||
const record = cursor.value as PersistedEntry;
|
||||
if (record.timestamp_ms < cutoff) {
|
||||
cursor.delete();
|
||||
} else {
|
||||
totals.count += 1;
|
||||
totals.bytes += record.bytes;
|
||||
totals.count += 1;
|
||||
totals.bytes += record.bytes;
|
||||
cursor.continue();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function deleteExpiredPrefix(
|
||||
index: IDBIndex,
|
||||
cutoff: number,
|
||||
totals: RetentionTotals,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = index.openCursor(IDBKeyRange.upperBound(cutoff, true));
|
||||
request.onerror = () => reject(request.error ?? new Error("IndexedDB cursor failed"));
|
||||
request.onsuccess = () => {
|
||||
const cursor = request.result;
|
||||
if (!cursor) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const record = cursor.value as PersistedEntry;
|
||||
cursor.delete();
|
||||
totals.count -= 1;
|
||||
totals.bytes -= record.bytes;
|
||||
cursor.continue();
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { _resetForTesting, MAX_ENTRY_BYTES } from "./buffer";
|
||||
import { _resetRuntimeForTesting, snapshotBrowserLogs, stageLogEntry } from "./runtime";
|
||||
import {
|
||||
_resetRuntimeForTesting,
|
||||
browserLogMetadata,
|
||||
snapshotBrowserLogs,
|
||||
stageLogEntry,
|
||||
} from "./runtime";
|
||||
|
||||
const storeMocks = vi.hoisted(() => ({
|
||||
append: vi.fn(),
|
||||
@@ -34,4 +39,67 @@ describe("browser logger runtime", () => {
|
||||
|
||||
expect(storeMocks.append).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to memory when a persistence drain is rejected", async () => {
|
||||
storeMocks.append.mockRejectedValueOnce(new Error("IndexedDB upgrade blocked"));
|
||||
stageLogEntry({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: "error",
|
||||
source: "test",
|
||||
message: "kept in memory",
|
||||
});
|
||||
|
||||
await expect(snapshotBrowserLogs("default-user")).resolves.toHaveLength(1);
|
||||
expect(browserLogMetadata()).toMatchObject({
|
||||
storage_mode: "memory",
|
||||
persistence_failures: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("serializes runtime drains and makes snapshots join the in-flight drain", async () => {
|
||||
vi.useFakeTimers();
|
||||
let activeAppends = 0;
|
||||
let maximumActiveAppends = 0;
|
||||
let appendCalls = 0;
|
||||
let releaseFirstAppend: (() => void) | undefined;
|
||||
const firstAppend = new Promise<void>((resolve) => {
|
||||
releaseFirstAppend = resolve;
|
||||
});
|
||||
storeMocks.append.mockImplementation(async () => {
|
||||
appendCalls += 1;
|
||||
activeAppends += 1;
|
||||
maximumActiveAppends = Math.max(maximumActiveAppends, activeAppends);
|
||||
if (appendCalls === 1) await firstAppend;
|
||||
activeAppends -= 1;
|
||||
});
|
||||
|
||||
try {
|
||||
stageLogEntry({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: "info",
|
||||
source: "test",
|
||||
message: "first",
|
||||
});
|
||||
const snapshot = snapshotBrowserLogs("default-user");
|
||||
await vi.waitFor(() => expect(storeMocks.append).toHaveBeenCalledTimes(1));
|
||||
|
||||
stageLogEntry({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: "info",
|
||||
source: "test",
|
||||
message: "second",
|
||||
});
|
||||
vi.runOnlyPendingTimers();
|
||||
await Promise.resolve();
|
||||
expect(storeMocks.append).toHaveBeenCalledTimes(1);
|
||||
releaseFirstAppend?.();
|
||||
|
||||
await snapshot;
|
||||
expect(storeMocks.append).toHaveBeenCalledTimes(2);
|
||||
expect(maximumActiveAppends).toBe(1);
|
||||
} finally {
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ let identityScope: string | null = "default-user";
|
||||
let staging: Staged[] = [];
|
||||
let stagingBytes = 0;
|
||||
let scheduled = false;
|
||||
let drainPromise: Promise<void> | null = null;
|
||||
let storageMode: "indexeddb" | "memory" = "indexeddb";
|
||||
let persistenceFailures = 0;
|
||||
let stagingDropped = 0;
|
||||
@@ -85,11 +86,11 @@ function makeStagingRoom(level: LogLevel, bytes: number): boolean {
|
||||
}
|
||||
|
||||
function scheduleDrain(): void {
|
||||
if (scheduled) return;
|
||||
if (scheduled || drainPromise) return;
|
||||
scheduled = true;
|
||||
const drain = () => {
|
||||
scheduled = false;
|
||||
void drainBatch();
|
||||
void requestDrain();
|
||||
};
|
||||
if (typeof requestIdleCallback === "function") {
|
||||
requestIdleCallback(drain, { timeout: 1_000 });
|
||||
@@ -98,8 +99,24 @@ function scheduleDrain(): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function drainBatch(): Promise<void> {
|
||||
if (storageMode === "memory" || staging.length === 0) return;
|
||||
function requestDrain(): Promise<void> {
|
||||
if (drainPromise) return drainPromise;
|
||||
if (storageMode === "memory" || staging.length === 0) return Promise.resolve();
|
||||
drainPromise = drainLoop().finally(() => {
|
||||
drainPromise = null;
|
||||
if (storageMode === "indexeddb" && staging.length > 0) scheduleDrain();
|
||||
});
|
||||
return drainPromise;
|
||||
}
|
||||
|
||||
async function drainLoop(): Promise<void> {
|
||||
while (storageMode === "indexeddb" && staging.length > 0) {
|
||||
if (!(await drainBatch())) return;
|
||||
}
|
||||
}
|
||||
|
||||
async function drainBatch(): Promise<boolean> {
|
||||
if (storageMode === "memory" || staging.length === 0) return true;
|
||||
const batch: Staged[] = [];
|
||||
let bytes = 0;
|
||||
while (staging.length > 0 && batch.length < DRAIN_ENTRY_LIMIT) {
|
||||
@@ -118,14 +135,14 @@ async function drainBatch(): Promise<void> {
|
||||
stagingBytes += item.bytes;
|
||||
}
|
||||
degradePersistence();
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (staging.length > 0) scheduleDrain();
|
||||
return true;
|
||||
}
|
||||
|
||||
async function flushStaging(): Promise<void> {
|
||||
while (storageMode === "indexeddb" && staging.length > 0) {
|
||||
await drainBatch();
|
||||
while (drainPromise || (storageMode === "indexeddb" && staging.length > 0)) {
|
||||
await requestDrain();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +166,7 @@ export function _resetRuntimeForTesting(): void {
|
||||
staging = [];
|
||||
stagingBytes = 0;
|
||||
scheduled = false;
|
||||
drainPromise = null;
|
||||
storageMode = "indexeddb";
|
||||
persistenceFailures = 0;
|
||||
stagingDropped = 0;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { isValidElement, type ReactNode } from "react";
|
||||
import { render } from "@testing-library/react";
|
||||
import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import {
|
||||
IconCheck,
|
||||
IconCircleCheck,
|
||||
@@ -19,8 +20,15 @@ import {
|
||||
shouldShowTaskRunningSpinner,
|
||||
} from "./state-icons";
|
||||
|
||||
const WILL_CHANGE_TRANSFORM = "will-change-transform";
|
||||
const SPIN_CLASS = "animate-spin";
|
||||
const SPIN_SELECTOR = `.${SPIN_CLASS}`;
|
||||
|
||||
function iconType(node: ReactNode) {
|
||||
if (!isValidElement(node)) throw new Error("Expected React element");
|
||||
if (node.type === CompositorSpin) {
|
||||
return iconType((node.props as { children: ReactNode }).children);
|
||||
}
|
||||
return node.type;
|
||||
}
|
||||
|
||||
@@ -30,6 +38,47 @@ function iconClassName(node: ReactNode): string {
|
||||
}
|
||||
|
||||
describe("getTaskStateIcon", () => {
|
||||
it("uses a compositor transform animation when Web Animations are available", () => {
|
||||
const originalAnimate = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "animate");
|
||||
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
|
||||
Object.defineProperty(HTMLElement.prototype, "animate", {
|
||||
configurable: true,
|
||||
value: animate,
|
||||
});
|
||||
|
||||
try {
|
||||
const { container } = render(
|
||||
<TooltipProvider>{getTaskStateIcon("IN_PROGRESS")}</TooltipProvider>,
|
||||
);
|
||||
const wrapper = container.querySelector(SPIN_SELECTOR) as HTMLElement;
|
||||
|
||||
expect(wrapper.style.animation).toBe("none");
|
||||
expect(animate).toHaveBeenCalledWith(
|
||||
[{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
|
||||
expect.objectContaining({ duration: 1_000, easing: "linear", iterations: Infinity }),
|
||||
);
|
||||
} finally {
|
||||
if (originalAnimate) {
|
||||
Object.defineProperty(HTMLElement.prototype, "animate", originalAnimate);
|
||||
} else {
|
||||
Reflect.deleteProperty(HTMLElement.prototype, "animate");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("animates an HTML wrapper while keeping the status SVG static", () => {
|
||||
const { container } = render(
|
||||
<TooltipProvider>{getTaskStateIcon("IN_PROGRESS")}</TooltipProvider>,
|
||||
);
|
||||
const animated = container.querySelector(SPIN_SELECTOR);
|
||||
|
||||
expect(animated?.tagName).toBe("SPAN");
|
||||
expect(animated?.classList.contains(WILL_CHANGE_TRANSFORM)).toBe(true);
|
||||
const svg = animated?.querySelector("svg");
|
||||
expect(svg).not.toBeNull();
|
||||
expect(svg?.classList.contains(SPIN_CLASS)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses the question icon for waiting-for-input task state", () => {
|
||||
expect(iconType(getTaskStateIcon("WAITING_FOR_INPUT"))).toBe(IconMessageQuestion);
|
||||
});
|
||||
@@ -331,7 +380,7 @@ describe("getSessionStateIcon — fine-grained busy tri-state", () => {
|
||||
// running affordance is deliberately left as it always was (static dot).
|
||||
const a = getSessionStateIcon("RUNNING", undefined, "generating");
|
||||
expect(iconType(a)).toBe(IconCircleFilled);
|
||||
expect(iconClassName(a)).not.toContain("animate-spin");
|
||||
expect(iconClassName(a)).not.toContain(SPIN_CLASS);
|
||||
});
|
||||
|
||||
it("(a) defaults to the running dot when the substate is unknown", () => {
|
||||
@@ -340,17 +389,34 @@ describe("getSessionStateIcon — fine-grained busy tri-state", () => {
|
||||
expect(iconType(getSessionStateIcon("RUNNING", undefined, null))).toBe(IconCircleFilled);
|
||||
});
|
||||
|
||||
it("animates a STARTING session on an HTML wrapper", () => {
|
||||
const { container } = render(<>{getSessionStateIcon("STARTING")}</>);
|
||||
const animated = container.querySelector(SPIN_SELECTOR);
|
||||
|
||||
expect(animated?.tagName).toBe("SPAN");
|
||||
expect(animated?.classList.contains(WILL_CHANGE_TRANSFORM)).toBe(true);
|
||||
const svg = animated?.querySelector("svg");
|
||||
expect(svg).not.toBeNull();
|
||||
expect(svg?.classList.contains(SPIN_CLASS)).toBe(false);
|
||||
});
|
||||
|
||||
it("(b) shows a working spinner — never the done checkmark — while background work runs", () => {
|
||||
const b = getSessionStateIcon("WAITING_FOR_INPUT", undefined, "background");
|
||||
expect(iconType(b)).toBe(IconLoader2);
|
||||
expect(iconType(b)).not.toBe(IconCircleCheck);
|
||||
expect(iconClassName(b)).toContain("animate-spin");
|
||||
const { container } = render(<>{b}</>);
|
||||
const animated = container.querySelector(SPIN_SELECTOR);
|
||||
expect(animated).not.toBeNull();
|
||||
expect(animated?.tagName).toBe("SPAN");
|
||||
const svg = animated?.querySelector("svg");
|
||||
expect(svg).not.toBeNull();
|
||||
expect(svg?.classList.contains(SPIN_CLASS)).toBe(false);
|
||||
});
|
||||
|
||||
it("(b) is visually distinct from (a) so the operator can tell them apart", () => {
|
||||
it("(b) shares (a)'s hue while shape and motion distinguish them", () => {
|
||||
const a = iconClassName(getSessionStateIcon("RUNNING", undefined, "generating"));
|
||||
const b = iconClassName(getSessionStateIcon("RUNNING", undefined, "background"));
|
||||
expect(a).not.toBe(b);
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("(c) flips to the done checkmark once background activity is cleared", () => {
|
||||
|
||||
@@ -15,15 +15,17 @@ import {
|
||||
IconX,
|
||||
} from "@tabler/icons-react";
|
||||
import type { ForegroundActivity, TaskSessionState, TaskState } from "@/lib/types/http";
|
||||
import { CompositorSpin } from "@kandev/ui/compositor-spin";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type IconConfig = {
|
||||
Icon: ComponentType<{ className?: string }>;
|
||||
className: string;
|
||||
animated?: boolean;
|
||||
};
|
||||
|
||||
const STYLE_MUTED = "text-muted-foreground";
|
||||
const STYLE_LOADING = "text-blue-500 animate-spin";
|
||||
const STYLE_LOADING = "text-blue-500";
|
||||
const STYLE_WARNING = "text-yellow-500";
|
||||
const STYLE_PERMISSION = "text-amber-500";
|
||||
const STYLE_ERROR = "text-red-500";
|
||||
@@ -31,8 +33,8 @@ const WAITING_FOR_INPUT = "WAITING_FOR_INPUT";
|
||||
|
||||
const TASK_STATE_ICONS: Record<TaskState, IconConfig> = {
|
||||
CREATED: { Icon: IconAlertCircle, className: STYLE_MUTED },
|
||||
SCHEDULING: { Icon: IconLoader2, className: STYLE_LOADING },
|
||||
IN_PROGRESS: { Icon: IconLoader2, className: STYLE_LOADING },
|
||||
SCHEDULING: { Icon: IconLoader2, className: STYLE_LOADING, animated: true },
|
||||
IN_PROGRESS: { Icon: IconLoader2, className: STYLE_LOADING, animated: true },
|
||||
REVIEW: { Icon: IconCheck, className: STYLE_WARNING },
|
||||
BLOCKED: { Icon: IconAlertCircle, className: STYLE_WARNING },
|
||||
WAITING_FOR_INPUT: { Icon: IconMessageQuestion, className: STYLE_WARNING },
|
||||
@@ -44,7 +46,7 @@ const TASK_STATE_ICONS: Record<TaskState, IconConfig> = {
|
||||
|
||||
const SESSION_STATE_ICONS: Record<TaskSessionState, IconConfig> = {
|
||||
CREATED: { Icon: IconAlertCircle, className: STYLE_MUTED },
|
||||
STARTING: { Icon: IconLoader2, className: STYLE_LOADING },
|
||||
STARTING: { Icon: IconLoader2, className: STYLE_LOADING, animated: true },
|
||||
// (a) generating: the foreground agent is actively producing output. This is
|
||||
// the established "session is running" indicator and is deliberately left
|
||||
// unchanged — the fine-grained busy signal only ADDS a distinct
|
||||
@@ -74,7 +76,8 @@ const SESSION_STATE_ICONS: Record<TaskSessionState, IconConfig> = {
|
||||
// foreground_activity rather than re-deriving its own icon.
|
||||
const SESSION_BACKGROUND_ICON: IconConfig = {
|
||||
Icon: IconLoader2,
|
||||
className: "text-emerald-500 animate-spin",
|
||||
className: "text-emerald-500",
|
||||
animated: true,
|
||||
};
|
||||
|
||||
// The task-level generating affordance — the established running spinner
|
||||
@@ -84,6 +87,7 @@ const SESSION_BACKGROUND_ICON: IconConfig = {
|
||||
const TASK_GENERATING_ICON: IconConfig = {
|
||||
Icon: IconLoader2,
|
||||
className: STYLE_LOADING,
|
||||
animated: true,
|
||||
};
|
||||
|
||||
// The task-level background-running affordance:
|
||||
@@ -100,7 +104,8 @@ const TASK_GENERATING_ICON: IconConfig = {
|
||||
// from ever being mistaken for the done check.
|
||||
const TASK_BACKGROUND_ICON: IconConfig = {
|
||||
Icon: IconLoader,
|
||||
className: "text-violet-500 animate-spin",
|
||||
className: "text-violet-500",
|
||||
animated: true,
|
||||
};
|
||||
|
||||
const PENDING_PERMISSION_ICON: IconConfig = {
|
||||
@@ -333,6 +338,18 @@ function getTaskStateIconConfig(state?: TaskState, options: TaskStateIconOptions
|
||||
return TASK_STATE_ICONS[state] ?? DEFAULT_TASK_ICON;
|
||||
}
|
||||
|
||||
function renderConfiguredIcon(config: IconConfig, className?: string) {
|
||||
const wrapperClassName = cn("h-4 w-4", config.className, className);
|
||||
if (!config.animated) {
|
||||
return <config.Icon className={wrapperClassName} />;
|
||||
}
|
||||
return (
|
||||
<CompositorSpin className={wrapperClassName}>
|
||||
<config.Icon className="size-full" />
|
||||
</CompositorSpin>
|
||||
);
|
||||
}
|
||||
|
||||
export function getTaskStateIcon(
|
||||
state?: TaskState,
|
||||
className?: string,
|
||||
@@ -348,7 +365,7 @@ export function getTaskStateIcon(
|
||||
if (config === TASK_AUTO_START_FAILED_ICON) {
|
||||
return <AutoStartFailedTaskIcon className={cn("h-4 w-4", className)} />;
|
||||
}
|
||||
return <config.Icon className={cn("h-4 w-4", config.className, className)} />;
|
||||
return renderConfiguredIcon(config, className);
|
||||
}
|
||||
|
||||
function getSessionStateIconConfig(
|
||||
@@ -380,5 +397,5 @@ export function getSessionStateIcon(
|
||||
hasPendingClarification,
|
||||
hasPendingPermission,
|
||||
);
|
||||
return <config.Icon className={cn("h-4 w-4", config.className, className)} />;
|
||||
return renderConfiguredIcon(config, className);
|
||||
}
|
||||
|
||||
@@ -55,8 +55,8 @@
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@kandev/theme": "workspace:*",
|
||||
"@kandev/plugin-sdk": "workspace:*",
|
||||
"@kandev/theme": "workspace:*",
|
||||
"@kandev/types": "workspace:*",
|
||||
"@kandev/ui": "workspace:*",
|
||||
"@lezer/highlight": "^1.2.3",
|
||||
@@ -154,6 +154,7 @@
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-sonarjs": "^3.0.7",
|
||||
"eslint-plugin-unused-imports": "^4.4.1",
|
||||
"fake-indexeddb": "^6.2.5",
|
||||
"happy-dom": "^20.8.9",
|
||||
"opencc-js": "1.4.1",
|
||||
"tailwindcss": "^4",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ADR-2026-07-30-file-backed-diagnostic-bundles: File-backed diagnostic bundles
|
||||
|
||||
**Status:** accepted (backend file retention amended by ADR-2026-08-22-preserve-newest-bounded-backend-logs)
|
||||
**Status:** accepted (amended 2026-08-23; backend file retention amended by ADR-2026-08-22-preserve-newest-bounded-backend-logs)
|
||||
**Date:** 2026-07-30
|
||||
**Area:** backend, frontend, infra, protocol, workflow
|
||||
|
||||
@@ -56,6 +56,14 @@ owns that upload so interleaved tabs cannot mix snapshots. Local records are
|
||||
partitioned by authenticated Kandev identity so an account switch inside one
|
||||
browser profile cannot disclose the previous user's history.
|
||||
|
||||
Browser retention totals live beside the entries in the same IndexedDB
|
||||
database. The entry count, serialized byte count, appends, age removals, and
|
||||
capacity evictions commit in one transaction. Transactions cover both the entry
|
||||
and metadata stores, so IndexedDB serializes competing writers across tabs.
|
||||
The schema upgrade scans existing entries once to initialize the totals. Normal
|
||||
writes inspect the appended batch, the expired prefix, and only the oldest rows
|
||||
that must be evicted. Each tab also serializes its staged write batches.
|
||||
|
||||
Users download one clearly disclosed combined ZIP from System Logs. It contains
|
||||
separate `backend/` and `frontend/` directories plus `manifest.json`. Frontend
|
||||
capture may time out without blocking backend evidence; the bundle then becomes
|
||||
@@ -124,6 +132,11 @@ request/HTTP chunk response adds a short-lived capture protocol, and bundles
|
||||
need expiry and cleanup ownership. A combined ZIP may be partial, so consumers
|
||||
must inspect the manifest before assuming both sources are present.
|
||||
|
||||
Transactional totals add one metadata record and a one-time schema-upgrade
|
||||
scan. They keep the entry and byte limits exact across tabs. If the totals are
|
||||
missing or invalid, one repair transaction rebuilds them before normal
|
||||
incremental maintenance resumes.
|
||||
|
||||
Some lower-priority logs can be deliberately omitted during sustained resource
|
||||
pressure. The manifest exposes queue, persistence, and archive loss so support
|
||||
does not mistake a best-effort bundle for complete evidence. Diagnostic bundle
|
||||
@@ -189,6 +202,11 @@ backend custody of raw frames, at the cost of some historical completeness.
|
||||
tool payloads, file content, identities, and arbitrary configuration.
|
||||
- **Upload only the current 500-entry memory buffer.** Rejected because it
|
||||
cannot match the selected three-day diagnostic window across reloads.
|
||||
- **Scan every retained browser entry after each append batch.** Rejected
|
||||
because work grows with retained history and can consume a renderer core
|
||||
during active logging.
|
||||
- **Cache retention totals in each tab's memory.** Rejected because tabs can
|
||||
commit stale totals and exceed shared browser-profile limits.
|
||||
- **Have the initiating frontend attach logs directly to the ZIP request.**
|
||||
Rejected in favor of a backend-requested capture protocol that also supports
|
||||
agent-triggered frontend bundles and multiple connected browser profiles.
|
||||
|
||||
@@ -103,7 +103,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
|
||||
| 2026-07-29-interactive-accent-surface-semantics | [Separate Brand Accent from Interactive Surface Fills](2026-07-29-interactive-accent-surface-semantics.md) | accepted | frontend | 2026-07-29 |
|
||||
| 2026-07-30-embedded-editor-executor-capabilities | [Derive Embedded Editor Availability from the Active Executor](2026-07-30-embedded-editor-executor-capabilities.md) | accepted | backend, frontend, protocol | 2026-07-30 |
|
||||
| 2026-07-30-session-owned-mcp-observability | [Keep MCP Attachment Evidence Session Owned](2026-07-30-session-owned-mcp-observability.md) | accepted | backend, frontend, protocol, security | 2026-07-30 |
|
||||
| 2026-07-30-file-backed-diagnostic-bundles | [File-backed diagnostic bundles](2026-07-30-file-backed-diagnostic-bundles.md) | accepted (backend file retention amended by 2026-08-22) | backend, frontend, infra, protocol, workflow | 2026-07-30 |
|
||||
| 2026-07-30-file-backed-diagnostic-bundles | [File-backed diagnostic bundles](2026-07-30-file-backed-diagnostic-bundles.md) | accepted (amended 2026-08-23; backend file retention amended by 2026-08-22) | backend, frontend, infra, protocol, workflow | 2026-07-30 |
|
||||
| 2026-07-30-runtime-task-state-before-running-event | [Publish Task State Before Running Session State](2026-07-30-runtime-task-state-before-running-event.md) | accepted | backend, frontend, protocol, workflow | 2026-07-30 |
|
||||
| 2026-07-31-authenticated-plugin-actions | [Authenticated Plugin Actions](2026-07-31-authenticated-plugin-actions.md) | accepted | backend, frontend, protocol, security | 2026-07-31 |
|
||||
| 2026-07-31-plugin-repository-provider-extensions | [Plugin Repository Provider Extensions](2026-07-31-plugin-repository-provider-extensions.md) | accepted | frontend, backend, protocol | 2026-07-31 |
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
specs:
|
||||
- docs/specs/ui/requirements/persistent-status-motion.md
|
||||
- docs/specs/platform/requirements/browser-console-retention.md
|
||||
created: 2026-08-23
|
||||
status: completed
|
||||
---
|
||||
|
||||
# Implementation Plan: Frontend Idle CPU
|
||||
|
||||
## Overview
|
||||
|
||||
Reduce idle CPU on a focused task page without removing working-state motion or
|
||||
weakening diagnostic retention. The first change moves long-lived status
|
||||
rotation to a compositor-prepared HTML wrapper. The second change makes browser
|
||||
log retention incremental and serializes each tab's write drain.
|
||||
|
||||
The supplied 8.34-second Chromium trace showed seven persistent animations on
|
||||
most frames. It recorded 1,155 `Layerize` events and 921 layout-tree updates
|
||||
with seven affected elements. The same trace showed about 50,000 IndexedDB
|
||||
success callbacks from repeated walks of a store near its 10,000-entry limit.
|
||||
|
||||
## Requirements and design
|
||||
|
||||
- [Persistent status motion requirements](../../specs/ui/requirements/persistent-status-motion.md)
|
||||
- [Persistent status motion design](../../specs/ui/system-design/persistent-status-motion.md)
|
||||
- [Browser console retention requirements](../../specs/platform/requirements/browser-console-retention.md)
|
||||
- [Browser console retention design](../../specs/platform/system-design/browser-console-retention.md)
|
||||
- [Amended diagnostic-bundle decision](../../decisions/2026-07-30-file-backed-diagnostic-bundles.md)
|
||||
|
||||
## Delivery strategy
|
||||
|
||||
### Compositor-backed persistent status motion
|
||||
|
||||
Add one shared UI primitive for a static SVG inside an animated HTML wrapper.
|
||||
Audit task, session, agent, and run status surfaces that can remain mounted for
|
||||
the lifetime of domain state. Migrate those call sites and preserve their
|
||||
existing state selection, motion, visual style, semantics, and selectors.
|
||||
|
||||
Use focused component tests for wrapper ownership, state precedence, and the
|
||||
live Web Animations API path. Extend the existing desktop settled-spinner and
|
||||
mobile task-status flows. Capture a new Chromium trace after implementation
|
||||
and attribute its steady-state rendering events to individual animation
|
||||
targets. The acceptance trace keeps the production target running while
|
||||
disabling unrelated grid and status animations, then compares it with a CSS
|
||||
animation control and the Web Animations API path so page-wide frame events are
|
||||
not misattributed to the shared compositor primitive.
|
||||
|
||||
### Incremental browser-log retention
|
||||
|
||||
Increase the existing IndexedDB schema version and add one retention metadata
|
||||
record. Initialize it from existing rows once during the upgrade. Each later
|
||||
append updates entries and totals in one transaction, scans only the expired
|
||||
prefix, and visits oldest rows only while a cap is exceeded.
|
||||
|
||||
Make `runtime.ts` own one in-flight drain promise. Scheduled drains and
|
||||
snapshots join the same loop. Use `fake-indexeddb` only in development tests to
|
||||
exercise the upgrade and transaction rules.
|
||||
|
||||
## Backend
|
||||
|
||||
No backend or protocol change is required.
|
||||
|
||||
## Desktop and mobile contract
|
||||
|
||||
The spinner wrapper is shared by desktop and mobile. It preserves dimensions
|
||||
and adds no route, overlay, touch target, or scroll owner. The mobile task
|
||||
switcher remains the native compact status surface and keeps touch navigation.
|
||||
|
||||
Browser-log retention has no user-interface composition change.
|
||||
|
||||
## Verification strategy
|
||||
|
||||
Work Order 01 owns component, desktop Playwright, mobile Playwright, and trace
|
||||
evidence for status motion. Work Order 02 owns IndexedDB integration tests,
|
||||
runtime concurrency tests, and frontend type checking.
|
||||
|
||||
No public documentation changes are required. The behavior and user-facing
|
||||
copy remain unchanged.
|
||||
|
||||
## Implementation waves and parallel candidates
|
||||
|
||||
Wave 1:
|
||||
|
||||
- [x] [Task 01: Move persistent status motion to the compositor](task-01-compositor-status-motion.md) (completed)
|
||||
- [x] [Task 02: Make browser-log retention incremental](task-02-incremental-browser-log-retention.md) (completed)
|
||||
|
||||
The work orders have no code dependency. The primary session implements them
|
||||
sequentially so each performance result has one clear cause.
|
||||
|
||||
## Risks
|
||||
|
||||
- Moving classes from an SVG to a wrapper can change size, margins, inherited
|
||||
color, accessible names, or test selectors if attributes are split
|
||||
incorrectly.
|
||||
- `will-change` is a promotion hint. The repeated trace is required because
|
||||
browser compositor decisions cannot be proven by class inspection alone.
|
||||
- Retention totals become incorrect if any entry mutation commits without the
|
||||
metadata store in the same transaction.
|
||||
- The version-2 upgrade must preserve existing browser history and must not run
|
||||
a rebuild on every page load.
|
||||
@@ -0,0 +1,158 @@
|
||||
---
|
||||
id: "01-compositor-status-motion"
|
||||
title: "Move persistent status motion to the compositor"
|
||||
status: completed
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/ui/requirements/persistent-status-motion.md"
|
||||
---
|
||||
|
||||
# Task 01: Move Persistent Status Motion to the Compositor
|
||||
|
||||
## Outcome
|
||||
|
||||
Persistent task, session, agent, and run indicators keep rotating with the same
|
||||
meaning and appearance. Their SVG children no longer own the animation.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add the shared compositor-prepared motion primitive in `apps/packages/ui`.
|
||||
- Audit long-lived domain-status spinners on task lists, task board cards, the
|
||||
focused task page, shared state icons, and Office status rows.
|
||||
- Migrate the in-scope spinners to an animated HTML wrapper and a static SVG.
|
||||
- Preserve state precedence, dimensions, color, duration, selectors, tooltip
|
||||
behavior, and accessible meaning.
|
||||
- Add focused component tests and desktop and mobile Playwright assertions.
|
||||
- Record a repeat Chromium trace in the same steady focused-task state.
|
||||
|
||||
## Exclusions
|
||||
|
||||
- Short request, save, refresh, upload, and download spinners.
|
||||
- Task, session, agent, or run state changes.
|
||||
- New copy or localization keys.
|
||||
- Changes to reduced-motion behavior.
|
||||
|
||||
## Requirements and design
|
||||
|
||||
- `REQ-UI-PERSISTENT-STATUS-MOTION-001`
|
||||
- `AC-UI-PERSISTENT-STATUS-MOTION-001.1` through
|
||||
`AC-UI-PERSISTENT-STATUS-MOTION-001.5`
|
||||
- `docs/specs/ui/system-design/persistent-status-motion.md`
|
||||
|
||||
## Acceptance conditions
|
||||
|
||||
1. Every in-scope persistent indicator places `animate-spin` and the transform
|
||||
promotion hint on an HTML wrapper. Its nested SVG has no animation class.
|
||||
2. Existing component tests still prove icon precedence and settling. Desktop
|
||||
and mobile Playwright tests prove visible rotation, state exit, touch
|
||||
navigation, and no horizontal overflow.
|
||||
3. A repeat steady-state Chromium trace shows that the migrated indicators do
|
||||
not account for recurring main-thread `UpdateLayoutTree` or `Layerize` work
|
||||
after their layers are established.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
cd apps && pnpm install --frozen-lockfile
|
||||
pnpm --filter @kandev/web exec vitest run lib/ui/state-icons.test.tsx components/task/task-item.test.tsx components/kanban-card-content.test.tsx components/task/simple/components/topbar-working-indicator.test.tsx components/task/simple/components/session-timeline-entry.test.tsx components/task/simple/components/user-comment-run-badge.test.tsx app/office/components/agent-card.test.tsx --reporter=dot
|
||||
cd web && pnpm run typecheck
|
||||
pnpm e2e:run --project chromium tests/task/sidebar-settled-spinner.spec.ts
|
||||
pnpm e2e:run --project mobile-chrome tests/task/mobile-task-status-summary.spec.ts
|
||||
```
|
||||
|
||||
Capture and inspect one Chromium performance trace after the automated checks.
|
||||
Use a focused task with the same persistent running indicators as the supplied
|
||||
trace. Attribute recurring events to individual animation targets, include a
|
||||
settled control with unrelated persistent animations disabled, and record the
|
||||
animation target type and steady-state event counts in this work order's
|
||||
results.
|
||||
|
||||
## Files likely touched
|
||||
|
||||
- `apps/packages/ui/src/compositor-spin.tsx`
|
||||
- `apps/web/lib/ui/state-icons.tsx`
|
||||
- `apps/web/lib/ui/state-icons.test.tsx`
|
||||
- `apps/web/components/task/task-item.tsx`
|
||||
- `apps/web/components/task/task-item.test.tsx`
|
||||
- `apps/web/components/kanban-card-content.tsx`
|
||||
- `apps/web/components/kanban-card-content.test.tsx`
|
||||
- `apps/web/components/task/simple/components/`
|
||||
- `apps/web/app/tasks/`
|
||||
- `apps/web/app/office/`
|
||||
- `apps/web/e2e/tests/task/sidebar-settled-spinner.spec.ts`
|
||||
- `apps/web/e2e/tests/task/mobile-task-status-summary.spec.ts`
|
||||
|
||||
## Dependencies
|
||||
|
||||
None.
|
||||
|
||||
## Parallelism
|
||||
|
||||
Sequential. The shared primitive and its attribute contract must land before
|
||||
call-site migration and browser evidence.
|
||||
|
||||
## Inputs
|
||||
|
||||
- The supplied Chromium trace and investigation findings in `plan.md`.
|
||||
- The persistent status motion requirement and design.
|
||||
- Existing state-icon precedence tests and task-row test IDs.
|
||||
- Existing desktop and mobile task-status E2E flows.
|
||||
|
||||
## Output contract
|
||||
|
||||
Report the audited call sites, migrated files, animation target, preserved
|
||||
semantics, test results, trace event comparison, risks, and blockers. Update
|
||||
this task and `plan.md` with exact results.
|
||||
|
||||
## Risks
|
||||
|
||||
- A wrapper can add an unwanted inline box if size and margin classes move to
|
||||
the wrong element.
|
||||
- An SVG test selector can silently change meaning if it is not moved to the
|
||||
status wrapper.
|
||||
- Other page activity can affect total trace counts. Attribute the comparison
|
||||
to the persistent animation targets and record the capture state.
|
||||
|
||||
## Results
|
||||
|
||||
- Added `apps/packages/ui/src/compositor-spin.tsx` and exported it from the UI
|
||||
package. The primitive renders an `inline-flex` HTML `span` with
|
||||
`animate-spin will-change-transform`; its nested SVG is static. When
|
||||
`Element.animate` is available, it reads the existing CSS duration, disables
|
||||
the CSS animation, and starts an infinite linear Web Animations API
|
||||
transform animation on the HTML wrapper. The CSS class remains as the
|
||||
compatibility fallback, and the Web Animations API instance is cancelled on
|
||||
cleanup.
|
||||
- Migrated the shared state icons, task-list rows, Kanban cards, focused-task
|
||||
topbar/session/agent/run indicators, and Office task/agent/run rows. Existing
|
||||
dimensions, colors, selectors, state precedence, labels, and mobile layout
|
||||
remain on the same surfaces.
|
||||
- Component coverage includes the static-SVG wrapper assertion and a Web
|
||||
Animations API assertion for the live compositor path. Desktop and mobile
|
||||
Playwright status flows each passed one test, including settling behavior,
|
||||
mobile touch navigation, and overflow checks.
|
||||
- A node-attributed 8.34-second Chromium trace found the migrated target as
|
||||
`span.inline-flex.animate-spin.will-change-transform` with a static SVG child.
|
||||
With the page's nine `spinner-grid-cube` animations enabled, the capture
|
||||
recorded 150 `UpdateLayoutTree` and 150 `Layerize` events. The trace
|
||||
attributed 1,350 invalidations to those grid-cube elements and 150
|
||||
co-occurring invalidations to the target wrapper.
|
||||
- The decisive production control kept the Web Animations API-backed
|
||||
`CompositorSpin` running, disabled the grid-cube animation and all other
|
||||
persistent status wrappers, and waited one second for the page to settle.
|
||||
The following 8.34-second window recorded zero `UpdateLayoutTree`,
|
||||
`Layerize`, `Layout`, or `Paint` events and no target invalidations. The
|
||||
target had zero class or style mutations during the window. Its four
|
||||
`animate` calls were one-time lifecycle setup before the settled window. A
|
||||
CSS-animation control for the same target
|
||||
recorded 41 `UpdateLayoutTree` and 41 `Layerize` events with target
|
||||
invalidations, while the Web Animations API control had no recurring events.
|
||||
This confirms that the remaining enabled-page frame work is unrelated grid
|
||||
animation, and closes the performance acceptance condition.
|
||||
- Typecheck, lint, i18n checks, spec lint, and `git diff --check` passed.
|
||||
- Review remediation also marks the `STARTING` session icon as animated, keeps
|
||||
the accessible label on the agent status SVG, and strengthens the wrapper
|
||||
assertions so a missing child SVG cannot pass silently.
|
||||
- The full frontend suite surfaced one stale Kanban status-icon shape helper;
|
||||
it now unwraps `CompositorSpin`, and that focused file passes all 17 tests.
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
id: "02-incremental-browser-log-retention"
|
||||
title: "Make browser-log retention incremental"
|
||||
status: completed
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/platform/requirements/browser-console-retention.md"
|
||||
---
|
||||
|
||||
# Task 02: Make Browser-Log Retention Incremental
|
||||
|
||||
## Outcome
|
||||
|
||||
Browser diagnostics keep the existing exact limits. Normal append batches no
|
||||
longer walk every retained row, and one tab cannot start overlapping writes.
|
||||
|
||||
## Scope
|
||||
|
||||
- Increase the existing IndexedDB schema to version 2 without changing its
|
||||
database name.
|
||||
- Add transactionally maintained count and serialized-byte totals.
|
||||
- Rebuild totals once for existing version-1 data.
|
||||
- Combine append, expired-prefix deletion, cap eviction, and total updates in
|
||||
one transaction over both stores.
|
||||
- Reset totals with entry clearing.
|
||||
- Serialize scheduled drains and snapshot flushing in `runtime.ts`.
|
||||
- Add `fake-indexeddb` as a development-only test dependency.
|
||||
- Add store integration tests and runtime concurrency tests.
|
||||
|
||||
## Exclusions
|
||||
|
||||
- Retention limit, identity partition, entry schema, or bundle protocol changes.
|
||||
- Backend changes.
|
||||
- Continuous upload or retry behavior.
|
||||
- New settings or user-facing copy.
|
||||
|
||||
## Requirements and design
|
||||
|
||||
- `REQ-PLATFORM-BROWSER-CONSOLE-RETENTION-001`
|
||||
- `AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.1` through
|
||||
`AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.7`
|
||||
- `docs/specs/platform/system-design/browser-console-retention.md`
|
||||
- `docs/decisions/2026-07-30-file-backed-diagnostic-bundles.md`
|
||||
|
||||
## Acceptance conditions
|
||||
|
||||
1. A version-1 database upgrades in place, preserves entries, initializes exact
|
||||
totals once, and uses incremental maintenance on later batches.
|
||||
2. Appends from separate store instances preserve age, count, and byte limits
|
||||
through one shared transaction scope. Clearing entries also clears totals.
|
||||
3. A held append proves that later scheduled work and a snapshot do not start a
|
||||
second append in the same tab.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
cd apps && pnpm install --frozen-lockfile
|
||||
pnpm --filter @kandev/web exec vitest run lib/logger/indexeddb-store.test.ts lib/logger/runtime.test.ts --reporter=dot
|
||||
cd web && pnpm run typecheck
|
||||
```
|
||||
|
||||
## Files likely touched
|
||||
|
||||
- `apps/web/lib/logger/indexeddb-store.ts`
|
||||
- `apps/web/lib/logger/indexeddb-store.test.ts`
|
||||
- `apps/web/lib/logger/runtime.ts`
|
||||
- `apps/web/lib/logger/runtime.test.ts`
|
||||
- `apps/web/package.json`
|
||||
- `apps/pnpm-lock.yaml`
|
||||
|
||||
## Dependencies
|
||||
|
||||
None.
|
||||
|
||||
## Parallelism
|
||||
|
||||
Sequential in the primary session. This keeps performance evidence attributable
|
||||
to one change at a time.
|
||||
|
||||
## Inputs
|
||||
|
||||
- The browser console retention requirement and design.
|
||||
- The amended diagnostic-bundle decision.
|
||||
- Existing staging and per-batch limits in `runtime.ts`.
|
||||
- Existing entry indexes and identity partition in `indexeddb-store.ts`.
|
||||
|
||||
## Output contract
|
||||
|
||||
Report the schema version, metadata record, transaction scope, cursor bounds,
|
||||
maximum observed append concurrency, migrated test data, verification results,
|
||||
risks, and blockers. Update this task and `plan.md` with exact results.
|
||||
|
||||
## Risks
|
||||
|
||||
- Any mutation outside the two-store transaction can make totals stale.
|
||||
- An upgrade cursor must keep the upgrade transaction alive until totals are
|
||||
written.
|
||||
- A failed batch must return its staged entries once and then enter the existing
|
||||
memory fallback without a retry loop.
|
||||
|
||||
## Results
|
||||
|
||||
- Upgraded `kandev-diagnostic-logs-v1` to IndexedDB schema version 2. The
|
||||
existing entries store and indexes remain unchanged, and the new metadata
|
||||
store contains one `retention` record with transactional `count` and `bytes`
|
||||
totals.
|
||||
- Version-1 data rebuilds totals once during upgrade. Normal appends use one
|
||||
readwrite transaction over entries and metadata, delete the expired
|
||||
timestamp prefix, evict oldest rows only when a count or byte cap requires
|
||||
it, and commit the updated totals atomically. Clearing entries resets the
|
||||
metadata record.
|
||||
- Runtime staging now owns one in-flight drain promise. Scheduled drains and
|
||||
snapshots join the same loop; the held-append test observed a maximum append
|
||||
concurrency of one.
|
||||
- Added `fake-indexeddb` as a development-only dependency and coverage for
|
||||
schema initialization, upgrade totals, exact count and byte caps, retention
|
||||
ordering, identity partitioning, metadata repair, clearing, concurrent store
|
||||
instances, cursor bounds, and non-overlapping runtime drains.
|
||||
- The focused store and runtime suite passed 12 tests. Frontend typecheck and
|
||||
the broader affected unit suite also passed.
|
||||
- An IndexedDB upgrade blocked by an older tab now rejects promptly, clears the
|
||||
cached open promise, closes any late successful connection, and permits a
|
||||
later retry. The runtime fallback test confirms a rejected drain preserves the
|
||||
existing memory-mode behavior.
|
||||
@@ -39,6 +39,7 @@ localization, feature toggles, health, and shared session recovery services.
|
||||
- [Bounded Task Status Delivery](requirements/bounded-task-status-delivery.md)
|
||||
- [Shared Cron Loop Safety When Office Is Disabled](requirements/cron-office-disabled-safety.md)
|
||||
- [Environment-specific browser tab title prefixes](requirements/dev-preview-title-prefixes.md)
|
||||
- [Browser console retention](requirements/browser-console-retention.md)
|
||||
- [Diagnostic logging](requirements/diagnostic-logging.md)
|
||||
- [Duration-aware E2E sharding and CI reliability](requirements/e2e-duration-aware-sharding.md)
|
||||
- [Expected runtime log severity](requirements/expected-runtime-log-severity.md)
|
||||
@@ -69,6 +70,7 @@ localization, feature toggles, health, and shared session recovery services.
|
||||
|
||||
|
||||
|
||||
- [Browser console retention](system-design/browser-console-retention.md)
|
||||
- [Bounded Task Status Delivery](system-design/bounded-task-status-delivery.md)
|
||||
- [Diagnostic logging System Design Part 1](system-design/diagnostic-logging-01.md)
|
||||
- [Diagnostic logging System Design Part 2](system-design/diagnostic-logging-02.md)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
status: active
|
||||
system: platform
|
||||
created: 2026-08-23
|
||||
owners:
|
||||
- kandev
|
||||
---
|
||||
|
||||
# Browser Console Retention Requirements
|
||||
|
||||
## Overview
|
||||
|
||||
Kandev keeps bounded browser diagnostics for explicit support bundles. Logging
|
||||
must remain off the application-critical path. Retention work must not consume
|
||||
large amounts of CPU when the store is already within its limits.
|
||||
|
||||
## Terminology
|
||||
|
||||
- **Committed batch:** One group of staged entries that IndexedDB accepts in a
|
||||
successful write transaction.
|
||||
- **Retained history:** All browser log entries across identity partitions in
|
||||
one browser profile.
|
||||
|
||||
## Requirements
|
||||
|
||||
### REQ-PLATFORM-BROWSER-CONSOLE-RETENTION-001: Bounded incremental retention
|
||||
|
||||
**Intent:** Preserve exact diagnostic limits without scanning the complete
|
||||
retained history after every log batch.
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.1:** After each committed batch,
|
||||
retained history shall contain no entry older than three days, no more than
|
||||
10,000 entries, and no more than 20 MiB of serialized entry data.
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.2:** When entries exceed a limit,
|
||||
retention shall remove expired entries first and shall then remove the oldest
|
||||
entries until all limits hold.
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.3:** When multiple tabs write to
|
||||
the same browser profile, every committed transaction shall preserve the
|
||||
shared count and byte limits.
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.4:** After retention totals are
|
||||
initialized, a batch that is within all limits shall not scan unexpired
|
||||
retained entries.
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.5:** When log batches arrive while
|
||||
persistence is active in one tab, that tab shall run no more than one browser
|
||||
log write at a time.
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.6:** A console call shall not wait
|
||||
for IndexedDB work. If persistence fails, the bounded memory fallback and
|
||||
diagnostic loss metadata shall remain available.
|
||||
- **AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.7:** Clearing browser diagnostic
|
||||
history shall also reset its retained count and byte totals.
|
||||
|
||||
## Compatibility and persistence
|
||||
|
||||
- The existing database name and retained entries survive the schema upgrade.
|
||||
- Entries remain partitioned by the authenticated Kandev identity.
|
||||
- Each entry remains limited to 64 KiB.
|
||||
- A diagnostic snapshot returns only the requested identity partition.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Changing bundle upload limits or permissions.
|
||||
- Uploading browser logs continuously.
|
||||
- Adding user-configurable retention limits.
|
||||
- Changing the 500-entry memory fallback or the staging byte limit.
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
status: current
|
||||
system: platform
|
||||
requirements:
|
||||
- REQ-PLATFORM-BROWSER-CONSOLE-RETENTION-001
|
||||
---
|
||||
|
||||
# Browser Console Retention System Design
|
||||
|
||||
## Purpose and boundaries
|
||||
|
||||
This design makes browser-log retention incremental. It preserves the existing
|
||||
diagnostic limits, identity partitions, capture protocol, and memory fallback.
|
||||
It changes IndexedDB bookkeeping and the per-tab drain coordinator.
|
||||
|
||||
## Requirement mapping
|
||||
|
||||
| Requirement | Design section |
|
||||
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `REQ-PLATFORM-BROWSER-CONSOLE-RETENTION-001` | [IndexedDB model](#indexeddb-model), [Write transaction](#write-transaction), [Per-tab drain ownership](#per-tab-drain-ownership), [Migration and recovery](#migration-and-recovery) |
|
||||
|
||||
## IndexedDB model
|
||||
|
||||
`apps/web/lib/logger/indexeddb-store.ts` keeps the database name
|
||||
`kandev-diagnostic-logs-v1` so existing profiles retain their history. The
|
||||
IndexedDB schema version increases from 1 to 2.
|
||||
|
||||
The existing `entries` store and its `identity_scope` and `timestamp_ms`
|
||||
indexes remain. A new metadata object store owns one retention record with
|
||||
these fields:
|
||||
|
||||
```text
|
||||
key: "retention"
|
||||
count: number
|
||||
bytes: number
|
||||
```
|
||||
|
||||
The totals cover all identity partitions. They use each entry's stored `bytes`
|
||||
field, which is the existing serialized-size measure.
|
||||
|
||||
## Write transaction
|
||||
|
||||
Each append opens one `readwrite` transaction over the `entries` and metadata
|
||||
stores. It performs these steps in order:
|
||||
|
||||
1. Read the retention totals.
|
||||
2. Add valid entries and add their count and bytes to the totals.
|
||||
3. Use a bounded `timestamp_ms` cursor to delete only entries before the
|
||||
three-day cutoff. Subtract each deleted entry from the totals.
|
||||
4. If a count or byte limit is still exceeded, walk the oldest entries only
|
||||
until both limits hold.
|
||||
5. Write the updated totals and commit.
|
||||
|
||||
The transaction makes entries and totals one atomic state. IndexedDB serializes
|
||||
overlapping `readwrite` transactions whose store scopes overlap. Tabs therefore
|
||||
cannot commit stale retention totals or exceed a shared limit after commit.
|
||||
|
||||
The normal within-limit path does not open an unrestricted cursor. It touches
|
||||
the new batch, the expired prefix, and only the oldest entries that it must
|
||||
evict. `clear()` uses both stores in one transaction and writes zero totals.
|
||||
|
||||
## Per-tab drain ownership
|
||||
|
||||
`apps/web/lib/logger/runtime.ts` owns one in-flight drain promise. Idle and
|
||||
timeout callbacks request work from the same drain loop. They do not start a
|
||||
second `store.append()` while the first call is pending.
|
||||
|
||||
The loop removes one bounded batch, waits for its append transaction, and then
|
||||
continues if staging still contains entries. `flushStaging()` awaits that same
|
||||
loop before a diagnostic snapshot. It does not create a parallel writer.
|
||||
|
||||
The console interception path remains synchronous and bounded. It only adds a
|
||||
reference-free entry to staging and schedules the loop.
|
||||
|
||||
## Migration and recovery
|
||||
|
||||
The version-2 upgrade transaction creates the metadata store and walks the
|
||||
existing entries once to calculate count and bytes. It writes the retention
|
||||
record before the upgrade commits. An interrupted upgrade rolls back as one
|
||||
IndexedDB transaction.
|
||||
|
||||
If a version-2 database lacks a valid retention record, the next write rebuilds
|
||||
the totals in one repair transaction before it accepts normal incremental
|
||||
maintenance. This is a recovery path, not a per-batch scan.
|
||||
|
||||
If a write, migration, or repair fails, the existing runtime degrades to the
|
||||
bounded memory store and increments persistence-failure metadata. It does not
|
||||
retry in a tight loop or delay the original console call.
|
||||
|
||||
## Test strategy
|
||||
|
||||
Store tests cover the version-1 to version-2 total rebuild, a normal append
|
||||
without an unrestricted cursor, expired-prefix deletion, oldest-first count and
|
||||
byte eviction, atomic clear, and two writers using the shared transaction
|
||||
scope. Vitest uses the dev-only `fake-indexeddb` package so these tests exercise
|
||||
real IndexedDB request and transaction behavior without a product dependency.
|
||||
|
||||
Runtime tests hold the first append promise while more entries arrive. They
|
||||
confirm that append concurrency stays at one and that a snapshot waits for the
|
||||
same drain.
|
||||
|
||||
## Related decisions
|
||||
|
||||
- [File-backed diagnostic bundles](../../../decisions/2026-07-30-file-backed-diagnostic-bundles.md)
|
||||
@@ -24,6 +24,9 @@ This design preserves the technical source detail for `REQ-PLATFORM-DIAGNOSTIC-L
|
||||
Decisions: [bundles](../../../decisions/2026-07-30-file-backed-diagnostic-bundles.md),
|
||||
[bounded logs](../../../decisions/2026-08-22-preserve-newest-bounded-backend-logs.md).
|
||||
|
||||
Browser retention: [requirements](../requirements/browser-console-retention.md) and
|
||||
[system design](../system-design/browser-console-retention.md).
|
||||
|
||||
Implementation plan: [diagnostic-logging](../../../plans/diagnostic-logging/plan.md)
|
||||
|
||||
## Why
|
||||
@@ -69,9 +72,6 @@ history or returning an unbounded log export.
|
||||
- The structured backend in-memory ring buffer is removed. The System Logs
|
||||
page, Improve Kandev, and agent diagnostics use the files and bundles
|
||||
described below.
|
||||
- The structured backend in-memory ring buffer is removed. The System Logs
|
||||
page, Improve Kandev, and agent diagnostics use the files and bundles
|
||||
described below.
|
||||
|
||||
### Error-toast reporting
|
||||
|
||||
@@ -100,22 +100,22 @@ history or returning an unbounded log export.
|
||||
|
||||
### Browser console history
|
||||
|
||||
The browser retention limits, persistence guarantees, write serialization, and
|
||||
incremental maintenance contract are authoritative in
|
||||
[Browser console retention](../requirements/browser-console-retention.md) and its
|
||||
paired [system design](../system-design/browser-console-retention.md).
|
||||
|
||||
- The frontend intercepts `console.debug`, `console.info`, `console.warn`, and
|
||||
`console.error`, plus `window.error` and `unhandledrejection`, without
|
||||
changing their normal browser behavior.
|
||||
- Entries remain local to the browser until a diagnostic bundle explicitly
|
||||
requests them. Kandev does not continuously stream console logs to the
|
||||
backend.
|
||||
- Browser history is stored in IndexedDB for a rolling three-day UTC window.
|
||||
Each browser profile has an opaque random installation ID shared by its tabs.
|
||||
- Each browser profile has an opaque random installation ID shared by its tabs.
|
||||
- Entries are partitioned by the current authenticated Kandev identity. A
|
||||
capture returns only that identity's partition; signing into another account
|
||||
in the same browser profile cannot expose the previous account's entries.
|
||||
Auth-disabled mode uses the existing synthetic single-user scope.
|
||||
- The browser store keeps at most 10,000 entries and 20 MiB after
|
||||
serialization across all identity partitions. Each entry is capped at
|
||||
64 KiB. Age is pruned first, then the oldest entries are evicted until both
|
||||
bounds hold.
|
||||
- Entries contain a client timestamp, level, source, message, bounded
|
||||
JSON-safe arguments, available stack, full URL, and a task ID derived from a
|
||||
recognized task route when available.
|
||||
@@ -125,9 +125,9 @@ history or returning an unbounded log export.
|
||||
prototypes or invoking getters. At most 20 arguments are inspected; strings
|
||||
are capped at 4 KiB, error messages at 8 KiB, and stacks at 16 KiB before the
|
||||
overall 64 KiB entry cap.
|
||||
- If IndexedDB is unavailable or fails, the frontend falls back to the existing
|
||||
500-entry in-memory buffer. A resulting bundle identifies the degraded
|
||||
capture in its manifest.
|
||||
- Persistence failure and memory fallback behavior follow
|
||||
`AC-PLATFORM-BROWSER-CONSOLE-RETENTION-001.6`. A resulting bundle identifies
|
||||
the degraded capture in its manifest.
|
||||
|
||||
### Performance and resource contract
|
||||
|
||||
@@ -157,7 +157,7 @@ history or returning an unbounded log export.
|
||||
limits above. Its reference-free staging queue holds at most 500 entries or
|
||||
2 MiB. It persists at most 50 entries or 256 KiB per transaction, scheduled
|
||||
after 250 ms or during browser idle time with a one-second timeout fallback.
|
||||
IndexedDB opening, serialization, pruning, and quota handling never run
|
||||
IndexedDB opening, serialization, retention maintenance, and quota handling never run
|
||||
synchronously in the intercepted console call. A full staging queue drops
|
||||
lower-priority `debug`/`info` entries first and records loss metadata; it
|
||||
never delays the original console call.
|
||||
|
||||
@@ -84,6 +84,7 @@ interaction contracts that do not own backend state.
|
||||
- [PR Task Status Summary](requirements/pr-task-status-summary.md)
|
||||
- [Pull Request Walkthrough Generation](requirements/pr-walkthrough.md)
|
||||
- [Preview Sprites Transient Retry](requirements/preview-sprites-transient-retry.md)
|
||||
- [Persistent status motion](requirements/persistent-status-motion.md)
|
||||
- [Prompt History Panel](requirements/prompt-history-panel.md)
|
||||
- [Render Nerd Font glyphs pasted from a styled terminal](requirements/prompt-paste-nerd-font-glyphs.md)
|
||||
- [Prompt Turn Duration on Message Hover](requirements/prompt-turn-duration.md)
|
||||
@@ -140,6 +141,7 @@ interaction contracts that do not own backend state.
|
||||
- [Task PR Automation Controls System Design Part 2](system-design/ci-pr-automation-02.md)
|
||||
- [Task PR Automation Controls System Design Part 3](system-design/ci-pr-automation-03.md)
|
||||
- [Entity Reference Composer](system-design/entity-reference-composer.md)
|
||||
- [Persistent status motion](system-design/persistent-status-motion.md)
|
||||
- [Prompt History Panel](system-design/prompt-history-panel.md)
|
||||
- [Quick Chat and Terminal Tabs](system-design/quick-terminal.md)
|
||||
- [Task Layout Profiles](system-design/task-layout-profiles.md)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
status: active
|
||||
system: ui
|
||||
created: 2026-08-23
|
||||
owners:
|
||||
- kandev
|
||||
---
|
||||
|
||||
# Persistent Status Motion Requirements
|
||||
|
||||
## Overview
|
||||
|
||||
Kandev uses rotating icons to show that tasks, sessions, runs, and agents are active.
|
||||
These indicators can stay visible for a long time. Their motion must remain
|
||||
clear without causing continuous main-thread rendering work.
|
||||
|
||||
## Terminology
|
||||
|
||||
- **Persistent status indicator:** A status icon whose lifetime follows a
|
||||
task, session, agent, or run state instead of a short UI request.
|
||||
- **Compositor-prepared motion:** A transform-only animation on an HTML element
|
||||
that the browser can move to its compositor.
|
||||
|
||||
## Requirements
|
||||
|
||||
### REQ-UI-PERSISTENT-STATUS-MOTION-001: Efficient persistent rotation
|
||||
|
||||
**Intent:** Keep visible working-state motion while avoiding unnecessary idle
|
||||
CPU use.
|
||||
|
||||
**User story:** As a Kandev user, I want active status icons to keep rotating,
|
||||
so that I can identify ongoing work without high idle CPU use.
|
||||
|
||||
#### Acceptance criteria
|
||||
|
||||
- **AC-UI-PERSISTENT-STATUS-MOTION-001.1:** When a task, session, agent, or run
|
||||
has a long-lived active status, the matching indicator shall remain visibly
|
||||
rotating on desktop and mobile.
|
||||
- **AC-UI-PERSISTENT-STATUS-MOTION-001.2:** When the active status ends, the
|
||||
indicator shall stop rotating and the existing next-state icon shall appear.
|
||||
- **AC-UI-PERSISTENT-STATUS-MOTION-001.3:** While an indicator rotates, the UI
|
||||
shall animate an HTML transform target and shall not animate the SVG element.
|
||||
- **AC-UI-PERSISTENT-STATUS-MOTION-001.4:** The change shall preserve each
|
||||
indicator's size, color, speed, status precedence, accessible meaning, and
|
||||
test selector.
|
||||
- **AC-UI-PERSISTENT-STATUS-MOTION-001.5:** The desktop and mobile surfaces
|
||||
shall use the same status state and motion primitive without horizontal
|
||||
overflow or a new interaction.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Removing status motion.
|
||||
- Changing task, session, or run state rules.
|
||||
- Changing reduced-motion behavior.
|
||||
- Migrating short request, save, refresh, upload, or download spinners that do
|
||||
not remain mounted as domain status.
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
status: current
|
||||
system: ui
|
||||
requirements:
|
||||
- REQ-UI-PERSISTENT-STATUS-MOTION-001
|
||||
---
|
||||
|
||||
# Persistent Status Motion System Design
|
||||
|
||||
## Purpose and boundaries
|
||||
|
||||
This design moves persistent task, session, and run rotation from SVG elements
|
||||
to a shared HTML transform wrapper. It changes rendering ownership only. Task
|
||||
state, icon selection, copy, and interaction behavior do not change.
|
||||
|
||||
Short request spinners remain outside this design. They have bounded lifetimes
|
||||
and were not a material source in the captured steady-state trace.
|
||||
|
||||
## Requirement mapping
|
||||
|
||||
| Requirement | Design section |
|
||||
| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `REQ-UI-PERSISTENT-STATUS-MOTION-001` | [Motion primitive](#motion-primitive), [Status surfaces](#status-surfaces), [Desktop and mobile composition](#desktop-and-mobile-composition) |
|
||||
|
||||
## Motion primitive
|
||||
|
||||
`apps/packages/ui/src/compositor-spin.tsx` owns a small presentation primitive.
|
||||
It renders an `inline-flex` HTML `span` with the existing transform rotation and
|
||||
the `will-change: transform` hint. The child SVG stays static and inherits its
|
||||
size and color from the wrapper.
|
||||
|
||||
The wrapper retains the `animate-spin` class for the existing selector and
|
||||
compatibility contract. In browsers with `Element.animate`, the primitive reads
|
||||
the duration from that class, disables the CSS animation, and starts an
|
||||
infinite linear Web Animations API animation from `rotate(0deg)` to
|
||||
`rotate(360deg)` on the HTML element. It applies the transform promotion hint
|
||||
and cancels the animation when the primitive is cleaned up. If Web Animations
|
||||
are unavailable, the retained CSS animation remains the fallback.
|
||||
|
||||
The wrapper owns animation classes, dimensions, margins, status test IDs, and
|
||||
other non-SVG attributes. The SVG owns only its path and `aria-hidden` state.
|
||||
This split gives Chromium a stable HTML transform target that it can promote to
|
||||
a compositor layer.
|
||||
|
||||
The primitive accepts normal wrapper attributes and children. It does not
|
||||
select task state, add labels, or own status precedence.
|
||||
|
||||
## Status surfaces
|
||||
|
||||
The first migration covers persistent indicators that can remain mounted in an
|
||||
active Kandev task view:
|
||||
|
||||
- shared task and session icons in `apps/web/lib/ui/state-icons.tsx`;
|
||||
- sidebar task rows in `apps/web/components/task/task-item.tsx`;
|
||||
- task board cards in `apps/web/components/kanban-card-content.tsx`;
|
||||
- focused-task topbar, session timeline, agent-turn, and queued-run indicators
|
||||
in `apps/web/components/task/simple/components/`;
|
||||
- task-list and Office task, agent, and run status rows that use the same
|
||||
long-lived domain states.
|
||||
|
||||
Implementation starts with a call-site audit. A spinner is in scope only when
|
||||
its lifetime follows task, session, agent, or run state. A spinner that follows
|
||||
one bounded UI request stays unchanged.
|
||||
|
||||
`getTaskStateIcon` and `getSessionStateIcon` keep their current selection and
|
||||
precedence logic. Their icon configuration separates static icon classes from
|
||||
the Boolean rotation state. Rotating configurations use the shared wrapper.
|
||||
|
||||
## Desktop and mobile composition
|
||||
|
||||
Desktop and mobile task switchers share task-row rendering. The wrapper keeps
|
||||
the current inline size and does not add a new touch target, scroll owner, or
|
||||
layout branch. Focusable tooltip wrappers and accessible labels stay outside
|
||||
the rotating element.
|
||||
|
||||
The closest mobile exemplar is the existing task-switcher row. Mobile coverage
|
||||
uses this shared row and also confirms that the document has no horizontal
|
||||
overflow.
|
||||
|
||||
## Verification and performance evidence
|
||||
|
||||
Component tests assert that the animation class and transform hint are on an
|
||||
HTML wrapper. They also assert that the nested SVG has no animation class.
|
||||
Existing state-precedence tests continue to validate which icon appears.
|
||||
|
||||
Desktop Playwright coverage holds a task in its running state. It checks the
|
||||
rotating wrapper and then checks the settled icon after the state changes.
|
||||
Mobile Playwright coverage checks the same wrapper in the task switcher and
|
||||
confirms the existing touch navigation.
|
||||
|
||||
After implementation, capture the same steady focused-task state in Chromium.
|
||||
Attribute recurring `UpdateLayoutTree`, `Layerize`, and frame activity to
|
||||
individual animation targets. In the production control, keep the live
|
||||
Web Animations API target running while disabling unrelated grid and persistent
|
||||
status animations, wait for the page to settle, and inspect the following
|
||||
8.34-second window. That window records zero recurring layout-tree or layerize
|
||||
events and no target invalidations. With the unrelated grid animation enabled,
|
||||
the page records 150 of each event and 1,350 grid-cube invalidations. A CSS
|
||||
animation control for the same target records 41 of each event, while the Web
|
||||
Animations API path records only one-time setup activity. The remaining
|
||||
enabled-page frame work is therefore attributed to the unrelated grid
|
||||
animation, not the migrated status target.
|
||||
|
||||
## Failure and compatibility
|
||||
|
||||
If a browser does not provide Web Animations, the retained CSS animation still
|
||||
rotates the wrapper normally. No state or content is lost. The duration is
|
||||
read from the existing CSS class on the Web Animations path, so speed and
|
||||
visual timing remain compatible.
|
||||
|
||||
The wrapper preserves existing test IDs and semantic attributes. Tests and
|
||||
assistive technology do not need to depend on the nested SVG element.
|
||||
Reference in New Issue
Block a user