Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

Agent runtime status redesign: split presence into availability + last-task (#1794)

Naiyuan Qing21e3cfaa01f5
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index 0e53f2b48b..40e016cc2b 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -1,4 +1,4 @@
-import { app, ipcMain, BrowserWindow } from "electron";
+import { app, ipcMain, BrowserWindow, shell } from "electron";
import { execFile } from "child_process";
import {
readFile,
@@ -914,6 +914,20 @@ export function setupDaemonManager(
stopLogTail();
});
+ // Reveal the daemon's log file in the user's default editor / Console
+ // app. Acts as the escape hatch when the in-app log viewer isn't enough
+ // (full history, complex search, copy-to-clipboard at scale).
+ ipcMain.handle("daemon:open-log-file", async () => {
+ const active = await ensureActiveProfile();
+ const logPath = profileLogPath(active.name);
+ if (!existsSync(logPath)) {
+ return { success: false, error: "Log file not found yet" };
+ }
+ // shell.openPath returns "" on success, error string on failure.
+ const error = await shell.openPath(logPath);
+ return error === "" ? { success: true } : { success: false, error };
+ });
+
// First-run CLI install kicks off here. Status bar shows "Setting up…"
// until the managed binary is on disk (instant on subsequent launches).
currentState = "installing_cli";
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index fc4cb4c025..e9136e4c27 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -68,6 +68,7 @@ interface DaemonAPI {
startLogStream: () => void;
stopLogStream: () => void;
onLogLine: (callback: (line: string) => void) => () => void;
+ openLogFile: () => Promise<{ success: boolean; error?: string }>;
}
interface UpdaterAPI {
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 0c0d92f595..78d45de63e 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -145,6 +145,8 @@ const daemonAPI = {
ipcRenderer.on("daemon:log-line", handler);
return () => ipcRenderer.removeListener("daemon:log-line", handler);
},
+ openLogFile: (): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke("daemon:open-log-file"),
};
const updaterAPI = {
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index 5dfbf27828..b0a11fa1d1 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -14,6 +14,7 @@ import { PageviewTracker } from "./components/pageview-tracker";
import { UpdateNotification } from "./components/update-notification";
import { useTabStore } from "./stores/tab-store";
import { useWindowOverlayStore } from "./stores/window-overlay-store";
+import { useDaemonIPCBridge } from "./platform/daemon-ipc-bridge";
function AppContent() {
@@ -99,6 +100,16 @@ function AppContent() {
const wsCount = workspaces.length;
const hasOnboarded = useHasOnboarded();
+ // Bridge local daemon IPC status into the runtimes cache so this user's
+ // own daemon flips to offline/online sub-second instead of waiting on the
+ // server's 75s sweeper. Resolves wsId from the active tab so workspace
+ // switches automatically rebind the subscription.
+ const activeWorkspaceSlug = useTabStore((s) => s.activeWorkspaceSlug);
+ const activeWsId = activeWorkspaceSlug
+ ? workspaces.find((w) => w.slug === activeWorkspaceSlug)?.id
+ : undefined;
+ useDaemonIPCBridge(activeWsId);
+
// Onboarding and zero-workspace both resolve to an overlay, but
// onboarding wins: a user who hasn't completed it gets the onboarding
// overlay regardless of how many workspaces already exist.
diff --git a/apps/desktop/src/renderer/src/components/daemon-panel.tsx b/apps/desktop/src/renderer/src/components/daemon-panel.tsx
index ed08c8f1f5..4575a4199e 100644
--- a/apps/desktop/src/renderer/src/components/daemon-panel.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-panel.tsx
@@ -1,150 +1,261 @@
-import { useState, useEffect, useRef, useCallback } from "react";
import {
- Play,
- Square,
- RotateCw,
+ Fragment,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import {
+ ArrowDown,
+ Copy as CopyIcon,
+ Search,
Server,
- ChevronDown,
+ Trash2,
X,
} from "lucide-react";
import { cn } from "@multica/ui/lib/utils";
import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
import { toast } from "sonner";
+import type { DaemonStatus } from "../../../shared/daemon-types";
import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@multica/ui/components/ui/sheet";
-import type { DaemonStatus, DaemonState } from "../../../shared/daemon-types";
-import { DAEMON_STATE_COLORS, DAEMON_STATE_LABELS } from "../../../shared/daemon-types";
+ DAEMON_STATE_COLORS,
+ DAEMON_STATE_LABELS,
+ formatUptime,
+} from "../../../shared/daemon-types";
+import { parseLogLine, type LogLevel, type ParsedLogLine } from "./parse-daemon-log";
interface DaemonPanelProps {
open: boolean;
onOpenChange: (open: boolean) => void;
status: DaemonStatus;
+ /** Number of runtimes this local daemon has registered (for the context badge). */
+ runtimeCount: number;
}
-const LOG_LEVEL_COLORS: Record<string, string> = {
- INFO: "text-info",
- WARN: "text-warning",
- ERROR: "text-destructive",
- DEBUG: "text-muted-foreground",
+const MAX_LOG_LINES = 500;
+const LEVELS: readonly LogLevel[] = ["DEBUG", "INFO", "WARN", "ERROR"];
+
+const LEVEL_BADGE_CLASS: Record<LogLevel, string> = {
+ DEBUG: "border-muted-foreground/25 text-muted-foreground/70",
+ INFO: "border-foreground/15 text-foreground/80",
+ WARN: "border-warning/40 text-warning",
+ ERROR: "border-destructive/40 text-destructive",
};
-function colorizeLogLine(line: string): { level: string; className: string } {
- for (const [level, className] of Object.entries(LOG_LEVEL_COLORS)) {
- if (line.includes(level)) return { level, className };
- }
- return { level: "", className: "text-muted-foreground" };
-}
+// What gets rendered in the viewport — a single line or a folded group of
+// consecutive lines that share the same `message`. The group form is what
+// turns a wall of `DBG poll: no tasks` into a single placeholder.
+type DisplayItem =
+ | { kind: "line"; line: ParsedLogLine }
+ | { kind: "group"; first: ParsedLogLine; rest: ParsedLogLine[] };
-function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
- return (
- <div className="flex items-baseline justify-between gap-4 py-1">
- <span className="shrink-0 text-xs text-muted-foreground">{label}</span>
- <span className="truncate text-right text-sm">{value}</span>
- </div>
+export function DaemonPanel({
+ open,
+ onOpenChange,
+ status,
+ runtimeCount,
+}: DaemonPanelProps) {
+ const [logs, setLogs] = useState<ParsedLogLine[]>([]);
+ const [search, setSearch] = useState("");
+ // Each level chip is an independent toggle. DEBUG is off by default so
+ // poll-loop noise doesn't drown out real events when the panel opens —
+ // users opt in if they want to see it.
+ const [enabledLevels, setEnabledLevels] = useState<Set<LogLevel>>(
+ () => new Set<LogLevel>(["INFO", "WARN", "ERROR"]),
);
-}
-
-function StatusDot({ state }: { state: DaemonState }) {
- return <span className={cn("inline-block size-2 rounded-full", DAEMON_STATE_COLORS[state])} />;
-}
-
-interface LogEntry {
- id: number;
- line: string;
-}
-
-const MAX_LOG_LINES = 500;
-let logIdCounter = 0;
-
-export function DaemonPanel({ open, onOpenChange, status }: DaemonPanelProps) {
- const [logs, setLogs] = useState<LogEntry[]>([]);
const [autoScroll, setAutoScroll] = useState(true);
- const [actionLoading, setActionLoading] = useState(false);
+ const [expandedFields, setExpandedFields] = useState<Set<number>>(new Set());
+ const [expandedGroups, setExpandedGroups] = useState<Set<number>>(new Set());
+
+ const idCounterRef = useRef(0);
const logContainerRef = useRef<HTMLDivElement>(null);
+ // --- Log stream subscription ---
+ // Active only while the modal is open. On open we replay the file's tail
+ // (~200 lines) so users have context for "what just happened"; on close
+ // we tear down the watcher so the main process isn't doing work for a
+ // hidden UI.
useEffect(() => {
if (!open) return;
+ setLogs([]);
+ setExpandedFields(new Set());
+ setExpandedGroups(new Set());
+ idCounterRef.current = 0;
window.daemonAPI.startLogStream();
const unsub = window.daemonAPI.onLogLine((line) => {
setLogs((prev) => {
- const next = [...prev, { id: ++logIdCounter, line }];
- return next.length > MAX_LOG_LINES ? next.slice(-MAX_LOG_LINES) : next;
+ const id = ++idCounterRef.current;
+ const parsed = parseLogLine(line, id);
+ const next =
+ prev.length >= MAX_LOG_LINES
+ ? [...prev.slice(prev.length - MAX_LOG_LINES + 1), parsed]
+ : [...prev, parsed];
+ return next;
});
});
-
return () => {
unsub();
window.daemonAPI.stopLogStream();
};
}, [open]);
- useEffect(() => {
- if (autoScroll && logContainerRef.current) {
- logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
+ // --- Derived: counts per level (for filter chip badges) ---
+ const levelCounts = useMemo(() => {
+ const counts: Record<LogLevel, number> = {
+ DEBUG: 0,
+ INFO: 0,
+ WARN: 0,
+ ERROR: 0,
+ };
+ for (const l of logs) {
+ if (l.level) counts[l.level] += 1;
+ }
+ return counts;
+ }, [logs]);
+
+ // --- Derived: filtered list (level toggle + search) ---
+ // Lines that didn't parse (level = null) always pass — they're typically
+ // panic stack traces / partial writes; never silently drop them.
+ const filtered = useMemo(() => {
+ let result = logs;
+ result = result.filter((l) => {
+ if (!l.level) return true;
+ return enabledLevels.has(l.level);
+ });
+ if (search) {
+ const q = search.toLowerCase();
+ result = result.filter((l) => l.raw.toLowerCase().includes(q));
+ }
+ return result;
+ }, [logs, enabledLevels, search]);
+
+ // --- Derived: collapse runs of consecutive lines that share the same
+ // message into a single group placeholder. The most common case is the
+ // 1-min `DBG poll: no tasks` heartbeat that otherwise pushes real events
+ // off-screen. Grouping happens AFTER filtering so toggling DEBUG off
+ // doesn't strand groups.
+ const displayed = useMemo<DisplayItem[]>(() => {
+ const out: DisplayItem[] = [];
+ for (const line of filtered) {
+ const last = out[out.length - 1];
+ if (!last) {
+ out.push({ kind: "line", line });
+ continue;
+ }
+ const lastMessage =
+ last.kind === "line" ? last.line.message : last.first.message;
+ if (lastMessage && lastMessage === line.message) {
+ if (last.kind === "line") {
+ out[out.length - 1] = {
+ kind: "group",
+ first: last.line,
+ rest: [line],
+ };
+ } else {
+ last.rest.push(line);
+ }
+ } else {
+ out.push({ kind: "line", line });
+ }
}
- }, [logs, autoScroll]);
+ return out;
+ }, [filtered]);
- const handleLogScroll = useCallback(() => {
+ // --- Auto-scroll: pin to bottom while live; release on user scroll ---
+ useEffect(() => {
+ if (!autoScroll) return;
+ const el = logContainerRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [displayed, autoScroll]);
+
+ const handleScroll = useCallback(() => {
const el = logContainerRef.current;
if (!el) return;
const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
- setAutoScroll(atBottom);
+ // Only flip auto-scroll OFF on user-initiated scroll-up; never flip ON
+ // here. Re-enabling lives in the "Jump to latest" footer button so a
+ // burst of lines doesn't yank a reading user back to the bottom.
+ if (!atBottom && autoScroll) setAutoScroll(false);
+ }, [autoScroll]);
+
+ const handleResume = useCallback(() => {
+ setAutoScroll(true);
+ const el = logContainerRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
}, []);
- const scrollToBottom = useCallback(() => {
- if (logContainerRef.current) {
- logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
- setAutoScroll(true);
+ const handleCopy = useCallback(async () => {
+ const text = filtered.map((l) => l.raw).join("\n");
+ try {
+ await navigator.clipboard.writeText(text);
+ toast.success(
+ `Copied ${filtered.length} line${filtered.length === 1 ? "" : "s"}`,
+ );
+ } catch (err) {
+ toast.error("Failed to copy", {
+ description: err instanceof Error ? err.message : String(err),
+ });
}
+ }, [filtered]);
+
+ const handleClear = useCallback(() => {
+ setLogs([]);
+ setExpandedFields(new Set());
+ setExpandedGroups(new Set());
}, []);
- const handleStart = useCallback(async () => {
- setActionLoading(true);
- const result = await window.daemonAPI.start();
- setActionLoading(false);
- if (!result.success) {
- toast.error("Failed to start daemon", { description: result.error });
- }
+ const toggleLevel = useCallback((lv: LogLevel) => {
+ setEnabledLevels((prev) => {
+ const next = new Set(prev);
+ if (next.has(lv)) next.delete(lv);
+ else next.add(lv);
+ return next;
+ });
}, []);
- const handleStop = useCallback(async () => {
- setActionLoading(true);
- const result = await window.daemonAPI.stop();
- setActionLoading(false);
- if (!result.success) {
- toast.error("Failed to stop daemon", { description: result.error });
- }
+ const toggleFields = useCallback((id: number) => {
+ setExpandedFields((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
}, []);
- const handleRestart = useCallback(async () => {
- setActionLoading(true);
- const result = await window.daemonAPI.restart();
- setActionLoading(false);
- if (!result.success) {
- toast.error("Failed to restart daemon", { description: result.error });
- }
+ const toggleGroup = useCallback((id: number) => {
+ setExpandedGroups((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
}, []);
- const isTransitioning = status.state === "starting" || status.state === "stopping";
+ const hasActiveFilter = !!search || enabledLevels.size < LEVELS.length;
return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent
- side="right"
- className="flex flex-col sm:max-w-md"
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className="flex h-[85vh] flex-col gap-0 overflow-hidden p-0 sm:max-w-5xl"
showCloseButton={false}
- style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
>
- <SheetHeader className="flex-row items-center justify-between gap-2 pr-3">
- <SheetTitle className="flex items-center gap-2">
- <Server className="size-4" />
- Local Daemon
- </SheetTitle>
+ {/* Header */}
+ <div className="flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <Server className="size-4 shrink-0 text-muted-foreground" />
+ <DialogTitle className="text-sm font-medium">
+ Local daemon logs
+ </DialogTitle>
+ <ContextBadge status={status} runtimeCount={runtimeCount} />
+ </div>
<button
type="button"
onClick={() => onOpenChange(false)}
@@ -153,157 +264,412 @@ export function DaemonPanel({ open, onOpenChange, status }: DaemonPanelProps) {
>
<X className="size-4" />
</button>
- </SheetHeader>
-
- <div className="flex-1 min-h-0 flex flex-col gap-4 px-4">
- <div className="shrink-0 space-y-4">
- {/* Status info */}
- <div className="rounded-lg border p-3 space-y-0.5">
- <InfoRow
- label="Status"
- value={
- <span className="flex items-center gap-1.5">
- <StatusDot state={status.state} />
- {DAEMON_STATE_LABELS[status.state]}
- </span>
- }
+ </div>
+
+ {/* Toolbar */}
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-4 py-2">
+ {/* Search */}
+ <div className="relative w-56">
+ <Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search…"
+ className="h-7 w-full rounded-md border bg-background pl-7 pr-2 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
/>
- {status.uptime && <InfoRow label="Uptime" value={status.uptime} />}
- <InfoRow label="Profile" value={status.profile || "default"} />
- {status.serverUrl && (
- <InfoRow
- label="Server"
- value={
- <span className="font-mono text-xs" title={status.serverUrl}>
- {status.serverUrl}
- </span>
- }
- />
- )}
- {status.agents && status.agents.length > 0 && (
- <InfoRow label="Agents" value={status.agents.join(", ")} />
- )}
- {status.deviceName && <InfoRow label="Device" value={status.deviceName} />}
- {status.daemonId && (
- <InfoRow
- label="Daemon ID"
- value={<span className="font-mono text-xs">{status.daemonId}</span>}
- />
- )}
- {typeof status.workspaceCount === "number" && (
- <InfoRow label="Workspaces" value={status.workspaceCount} />
- )}
- {status.pid && (
- <InfoRow
- label="PID"
- value={<span className="font-mono text-xs">{status.pid}</span>}
+ </div>
+
+ {/* Level toggle chips. Each chip is independent — click to
+ show/hide that level. DEBUG starts hidden because the
+ poll-loop heartbeat dominates otherwise. */}
+ <div className="flex items-center gap-1">
+ {LEVELS.map((lv) => (
+ <FilterChip
+ key={lv}
+ active={enabledLevels.has(lv)}
+ onClick={() => toggleLevel(lv)}
+ label={lv}
+ count={levelCounts[lv]}
+ variant={lv}
/>
- )}
+ ))}
</div>
- {/* Actions */}
- {status.state === "installing_cli" ? (
- <div className="rounded-lg border border-dashed p-3 text-sm text-muted-foreground">
- Setting up the local runtime… this only happens the first time.
- </div>
- ) : status.state === "cli_not_found" ? (
- <div className="rounded-lg border border-destructive/40 bg-destructive/5 p-3 space-y-2">
- <p className="text-sm">
- Couldn&apos;t download the local runtime. Check your network
- connection and try again.
- </p>
- <Button
- size="sm"
- variant="outline"
- onClick={async () => {
- setActionLoading(true);
- try {
- await window.daemonAPI.retryInstall();
- } finally {
- setActionLoading(false);
- }
- }}
- disabled={actionLoading}
- >
- <RotateCw className="size-3.5 mr-1.5" />
- Retry
- </Button>
- </div>
+ {/* Right-aligned actions */}
+ <div className="ml-auto flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7"
+ onClick={handleCopy}
+ disabled={filtered.length === 0}
+ >
+ <CopyIcon className="size-3.5 mr-1.5" />
+ Copy
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7"
+ onClick={handleClear}
+ disabled={logs.length === 0}
+ >
+ <Trash2 className="size-3.5 mr-1.5" />
+ Clear
+ </Button>
+ </div>
+ </div>
+
+ {/* Logs viewport */}
+ <div
+ ref={logContainerRef}
+ onScroll={handleScroll}
+ className="min-h-0 flex-1 overflow-y-auto bg-muted/20 px-2 py-1 font-mono text-xs"
+ >
+ {displayed.length === 0 ? (
+ <EmptyState
+ hasLogs={logs.length > 0}
+ hasFilter={hasActiveFilter}
+ isRunning={status.state === "running"}
+ />
) : (
- <div className="flex gap-2">
- {status.state === "stopped" ? (
- <Button size="sm" onClick={handleStart} disabled={actionLoading}>
- <Play className="size-3.5 mr-1.5" />
- Start
- </Button>
- ) : (
- <>
- <Button
- variant="outline"
- size="sm"
- onClick={handleStop}
- disabled={actionLoading || isTransitioning}
- >
- <Square className="size-3.5 mr-1.5" />
- Stop
- </Button>
- <Button
- variant="outline"
- size="sm"
- onClick={handleRestart}
- disabled={actionLoading || isTransitioning}
- >
- <RotateCw className="size-3.5 mr-1.5" />
- Restart
- </Button>
- </>
+ <div className="flex flex-col">
+ {displayed.map((item) =>
+ item.kind === "line" ? (
+ <LogLineRow
+ key={item.line.id}
+ line={item.line}
+ expanded={expandedFields.has(item.line.id)}
+ onToggle={() => toggleFields(item.line.id)}
+ search={search}
+ />
+ ) : (
+ <GroupRows
+ key={item.first.id}
+ first={item.first}
+ rest={item.rest}
+ expanded={expandedGroups.has(item.first.id)}
+ onToggle={() => toggleGroup(item.first.id)}
+ expandedFields={expandedFields}
+ onToggleFields={toggleFields}
+ search={search}
+ />
+ ),
)}
</div>
)}
+ </div>
- </div>
-
- {/* Logs — fills remaining vertical space down to the sheet bottom */}
- <div className="flex-1 min-h-0 flex flex-col gap-2 pb-4">
- <div className="flex items-center justify-between shrink-0">
- <h3 className="text-sm font-medium">Logs</h3>
- {!autoScroll && (
- <Button
- variant="ghost"
- size="sm"
- className="h-6 px-2 text-xs"
- onClick={scrollToBottom}
- >
- <ChevronDown className="size-3 mr-1" />
- Scroll to bottom
- </Button>
- )}
- </div>
- <div
- ref={logContainerRef}
- onScroll={handleLogScroll}
- className="flex-1 min-h-0 overflow-y-auto rounded-lg border bg-muted/30 p-2 font-mono text-xs leading-relaxed"
+ {/* Status bar — count only. The "is the user following" state is
+ communicated implicitly by the presence of the Jump-to-latest
+ button below; an explicit "Paused" word read as "log stream is
+ paused" (it isn't — data keeps flowing into the buffer). */}
+ <div className="flex shrink-0 items-center justify-between border-t bg-muted/30 px-4 py-1.5 text-xs text-muted-foreground">
+ <span className="tabular-nums">
+ Showing {filtered.length} of {logs.length}
+ {logs.length === MAX_LOG_LINES && (
+ <span className="ml-1 text-muted-foreground/60">
+ (buffer full)
+ </span>
+ )}
+ </span>
+ {!autoScroll && (
+ <button
+ type="button"
+ onClick={handleResume}
+ className="inline-flex items-center gap-1 rounded-md px-2 py-0.5 hover:bg-muted hover:text-foreground"
>
- {logs.length === 0 ? (
- <p className="text-muted-foreground/50 text-center py-8">
- {status.state === "running"
- ? "Waiting for logs…"
- : "Start the daemon to see logs"}
- </p>
- ) : (
- logs.map((entry) => {
- const { className } = colorizeLogLine(entry.line);
- return (
- <div key={entry.id} className={cn("whitespace-pre-wrap break-all", className)}>
- {entry.line}
- </div>
- );
- })
- )}
- </div>
- </div>
+ <ArrowDown className="size-3" />
+ Jump to latest
+ </button>
+ )}
</div>
- </SheetContent>
- </Sheet>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+// ---------- Sub-components ----------
+
+function ContextBadge({
+ status,
+ runtimeCount,
+}: {
+ status: DaemonStatus;
+ runtimeCount: number;
+}) {
+ const isRunning = status.state === "running";
+ return (
+ <span className="inline-flex items-center gap-1.5 rounded-md border bg-background px-1.5 py-0.5 text-xs font-normal">
+ <span
+ className={cn(
+ "size-1.5 rounded-full",
+ DAEMON_STATE_COLORS[status.state],
+ )}
+ />
+ <span
+ className={cn(
+ "tabular-nums",
+ isRunning ? "text-foreground" : "text-muted-foreground",
+ )}
+ >
+ {DAEMON_STATE_LABELS[status.state]}
+ </span>
+ {isRunning && status.uptime && (
+ <span className="text-muted-foreground">
+ · {formatUptime(status.uptime)}
+ </span>
+ )}
+ {isRunning && runtimeCount > 0 && (
+ <span className="text-muted-foreground">
+ · {runtimeCount} runtime{runtimeCount === 1 ? "" : "s"}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function FilterChip({
+ active,
+ onClick,
+ label,
+ count,
+ variant,
+}: {
+ active: boolean;
+ onClick: () => void;
+ label: string;
+ count: number;
+ variant?: LogLevel;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "inline-flex h-7 items-center gap-1 rounded-md border bg-background px-2 text-xs transition-colors hover:bg-accent",
+ active
+ ? variant
+ ? LEVEL_BADGE_CLASS[variant]
+ : "bg-accent text-accent-foreground"
+ : "border-dashed text-muted-foreground/50",
+ )}
+ >
+ {label}
+ <span
+ className={cn(
+ "tabular-nums",
+ active ? "text-current/80" : "text-muted-foreground/40",
+ )}
+ >
+ {count}
+ </span>
+ </button>
+ );
+}
+
+function LevelBadge({ level }: { level: LogLevel }) {
+ return (
+ <span
+ className={cn(
+ "inline-flex h-4 shrink-0 items-center rounded border px-1 text-[10px] font-medium uppercase tracking-wide",
+ LEVEL_BADGE_CLASS[level],
+ )}
+ >
+ {level}
+ </span>
+ );
+}
+
+function LogLineRow({
+ line,
+ expanded,
+ onToggle,
+ search,
+}: {
+ line: ParsedLogLine;
+ expanded: boolean;
+ onToggle: () => void;
+ search: string;
+}) {
+ const fieldEntries = Object.entries(line.fields);
+ const hasFields = fieldEntries.length > 0;
+
+ // Unparseable line — render the raw text so nothing is hidden. Common
+ // for panic stack traces and partial writes during log rotation.
+ if (!line.timestamp || !line.level) {
+ return (
+ <div className="break-all whitespace-pre-wrap px-2 py-0.5 text-muted-foreground/70">
+ {highlight(line.raw, search)}
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={cn(
+ "grid grid-cols-[auto_auto_minmax(0,1fr)] items-baseline gap-2 rounded px-2 py-0.5 hover:bg-accent/30",
+ hasFields && "cursor-pointer",
+ )}
+ onClick={hasFields ? onToggle : undefined}
+ >
+ <span className="shrink-0 tabular-nums text-muted-foreground/60">
+ {line.timestamp}
+ </span>
+ <LevelBadge level={line.level} />
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-baseline gap-2">
+ <span className="break-words">{highlight(line.message, search)}</span>
+ {hasFields && !expanded && (
+ <span className="min-w-0 truncate text-muted-foreground/60">
+ {fieldEntries
+ .map(([k, v]) => `${k}=${truncateValue(v)}`)
+ .join(" ")}
+ </span>
+ )}
+ </div>
+ {expanded && hasFields && (
+ <div className="ml-1 mt-1 grid grid-cols-[max-content_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-muted-foreground">
+ {fieldEntries.map(([k, v]) => (
+ <Fragment key={k}>
+ <span className="text-muted-foreground/70">{k}</span>
+ <span className="break-all text-foreground/85">{v}</span>
+ </Fragment>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function GroupRows({
+ first,
+ rest,
+ expanded,
+ onToggle,
+ expandedFields,
+ onToggleFields,
+ search,
+}: {
+ first: ParsedLogLine;
+ rest: ParsedLogLine[];
+ expanded: boolean;
+ onToggle: () => void;
+ expandedFields: Set<number>;
+ onToggleFields: (id: number) => void;
+ search: string;
+}) {
+ // Folded: show the first occurrence so the user still sees a sample
+ // (timestamp, level, message), then a click-to-expand placeholder for
+ // the suppressed run. The placeholder uses a dashed border + italics
+ // so the eye reads it as "not a real line".
+ if (!expanded) {
+ return (
+ <>
+ <LogLineRow
+ line={first}
+ expanded={expandedFields.has(first.id)}
+ onToggle={() => onToggleFields(first.id)}
+ search={search}
+ />
+ <button
+ type="button"
+ onClick={onToggle}
+ className="my-0.5 ml-2 inline-flex w-fit items-center gap-2 rounded border border-dashed border-muted-foreground/25 bg-muted/30 px-2 py-0.5 text-[11px] italic text-muted-foreground/70 hover:bg-muted/60 hover:text-foreground"
+ >
+ <span>···</span>
+ <span>
+ {rest.length} more &ldquo;{truncateValue(first.message, 48)}
+ &rdquo; — click to expand
+ </span>
+ </button>
+ </>
+ );
+ }
+
+ // Unfolded: render every line, then a small "collapse" affordance at
+ // the end so the user can put the toothpaste back in the tube.
+ return (
+ <>
+ <LogLineRow
+ line={first}
+ expanded={expandedFields.has(first.id)}
+ onToggle={() => onToggleFields(first.id)}
+ search={search}
+ />
+ {rest.map((l) => (
+ <LogLineRow
+ key={l.id}
+ line={l}
+ expanded={expandedFields.has(l.id)}
+ onToggle={() => onToggleFields(l.id)}
+ search={search}
+ />
+ ))}
+ <button
+ type="button"
+ onClick={onToggle}
+ className="my-0.5 ml-2 inline-flex w-fit items-center gap-2 rounded border border-dashed border-muted-foreground/25 px-2 py-0.5 text-[11px] italic text-muted-foreground/60 hover:text-foreground"
+ >
+ <span>···</span>
+ <span>collapse {rest.length + 1} repeated</span>
+ </button>
+ </>
+ );
+}
+
+function EmptyState({
+ hasLogs,
+ hasFilter,
+ isRunning,
+}: {
+ hasLogs: boolean;
+ hasFilter: boolean;
+ isRunning: boolean;
+}) {
+ let title: string;
+ let subtitle: string;
+ if (hasFilter) {
+ title = "No matching log lines";
+ subtitle = "Try a different search or level toggle.";
+ } else if (!isRunning) {
+ title = "Daemon isn't running";
+ subtitle = "Start the daemon to see logs here.";
+ } else if (!hasLogs) {
+ title = "Waiting for logs…";
+ subtitle = "New entries will appear in real time.";
+ } else {
+ title = "";
+ subtitle = "";
+ }
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-1 text-center text-muted-foreground/70">
+ <p className="text-sm">{title}</p>
+ <p className="text-xs text-muted-foreground/50">{subtitle}</p>
+ </div>
+ );
+}
+
+// ---------- Helpers ----------
+
+function truncateValue(value: string, max = 32): string {
+ return value.length > max ? `${value.slice(0, max)}…` : value;
+}
+
+function highlight(text: string, query: string): ReactNode {
+ if (!query) return text;
+ const q = query.toLowerCase();
+ const lower = text.toLowerCase();
+ const idx = lower.indexOf(q);
+ if (idx === -1) return text;
+ return (
+ <>
+ {text.slice(0, idx)}
+ <mark className="rounded bg-warning/30 px-0.5 text-foreground">
+ {text.slice(idx, idx + query.length)}
+ </mark>
+ {text.slice(idx + query.length)}
+ </>
);
}
diff --git a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
index 0b13a0391e..a9e9dcdde8 100644
--- a/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx
@@ -1,22 +1,94 @@
-import { useState, useEffect, useCallback } from "react";
+import { useState, useEffect, useCallback, useMemo } from "react";
import {
+ AlertCircle,
Play,
Square,
RotateCw,
Server,
Activity,
+ ScrollText,
} from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { runtimeListOptions } from "@multica/core/runtimes";
+import { agentTaskSnapshotOptions } from "@multica/core/agents";
import { cn } from "@multica/ui/lib/utils";
import { Button } from "@multica/ui/components/ui/button";
+import {
+ Card,
+ CardAction,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@multica/ui/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
import { toast } from "sonner";
import { DaemonPanel } from "./daemon-panel";
import type { DaemonStatus } from "../../../shared/daemon-types";
-import { DAEMON_STATE_COLORS, DAEMON_STATE_LABELS, formatUptime } from "../../../shared/daemon-types";
+import {
+ DAEMON_STATE_COLORS,
+ DAEMON_STATE_LABELS,
+ daemonStateDescription,
+ formatUptime,
+} from "../../../shared/daemon-types";
+/**
+ * Header card on the desktop Runtimes page that surfaces the daemon embedded
+ * in this Electron app. The same daemon process registers N runtimes with the
+ * server (one per detected CLI), which appear in the runtime list below — so
+ * this card is the parent control surface for "what's running on this Mac".
+ *
+ * Why this lives only on desktop: web users don't have an embedded daemon;
+ * they bring their own (CLI-launched or remote VM) and just see runtimes in
+ * the list. The `desktop-runtimes-page` wrapper is the only mount point.
+ */
export function DaemonRuntimeCard() {
const [status, setStatus] = useState<DaemonStatus>({ state: "stopped" });
const [panelOpen, setPanelOpen] = useState(false);
const [actionLoading, setActionLoading] = useState(false);
+ const [confirmStop, setConfirmStop] = useState(false);
+
+ const wsId = useWorkspaceId();
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
+ // Snapshot also includes each agent's latest terminal; the filter below
+ // drops anything that isn't running/dispatched, so terminal rows pass
+ // through harmlessly.
+ const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));
+
+ // Set of runtime IDs registered by THIS daemon (one per detected CLI).
+ // Used both to count "how many CLIs am I contributing" and to figure
+ // out which active tasks would be impacted by a Stop.
+ const localRuntimeIds = useMemo(() => {
+ if (!status.daemonId) return new Set<string>();
+ return new Set(
+ runtimes
+ .filter((r) => r.daemon_id === status.daemonId)
+ .map((r) => r.id),
+ );
+ }, [runtimes, status.daemonId]);
+
+ const runtimeCount = localRuntimeIds.size;
+
+ // Tasks that are actually doing work on this daemon right now —
+ // running or dispatched. Queued tasks haven't claimed a runtime yet,
+ // so stopping the daemon won't break them (they'll wait for any
+ // available daemon). The number drives the Stop-confirmation dialog.
+ const affectedTasks = useMemo(
+ () =>
+ snapshot.filter(
+ (t) =>
+ localRuntimeIds.has(t.runtime_id) &&
+ (t.status === "running" || t.status === "dispatched"),
+ ),
+ [snapshot, localRuntimeIds],
+ );
useEffect(() => {
window.daemonAPI.getStatus().then((s) => setStatus(s));
@@ -36,7 +108,10 @@ export function DaemonRuntimeCard() {
}
}, []);
- const handleStop = useCallback(async () => {
+ // The actual stop call, separated from the click handler so we can call
+ // it both from the direct path (no active tasks) and from the confirm
+ // dialog's confirm button.
+ const performStop = useCallback(async () => {
setActionLoading(true);
const result = await window.daemonAPI.stop();
if (!result.success) {
@@ -44,112 +119,214 @@ export function DaemonRuntimeCard() {
}
}, []);
+ // Click on the Stop button. If there's nothing running, just stop;
+ // otherwise pop a confirm dialog explaining the blast radius.
+ const handleStopClick = useCallback(() => {
+ if (affectedTasks.length === 0) {
+ void performStop();
+ } else {
+ setConfirmStop(true);
+ }
+ }, [affectedTasks.length, performStop]);
+
const handleRestart = useCallback(async () => {
setActionLoading(true);
const result = await window.daemonAPI.restart();
if (!result.success) {
toast.error("Failed to restart daemon", { description: result.error });
+ return;
}
+ // Success feedback — the daemon takes a few seconds to come back online,
+ // and the only other UI signal is the state badge flipping briefly. A
+ // toast confirms the click was received and tells the user what to expect.
+ toast.success("Restarting daemon", {
+ description: "Runtimes will be back online in a few seconds.",
+ });
}, []);
- const isTransitioning = status.state === "starting" || status.state === "stopping";
- const isRunning = status.state === "running";
- const isStopped = status.state === "stopped" || status.state === "cli_not_found";
+ const handleRetryInstall = useCallback(async () => {
+ setActionLoading(true);
+ try {
+ await window.daemonAPI.retryInstall();
+ } finally {
+ setActionLoading(false);
+ }
+ }, []);
- const stopPropagation = (e: React.MouseEvent) => e.stopPropagation();
+ const isRunning = status.state === "running";
+ const isStopped = status.state === "stopped";
+ const isCliMissing = status.state === "cli_not_found";
+ const isTransitioning =
+ status.state === "starting" || status.state === "stopping";
+ const isInstalling = status.state === "installing_cli";
return (
<>
- <div
- role="button"
- tabIndex={0}
- onClick={() => setPanelOpen(true)}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- setPanelOpen(true);
- }
- }}
- className="border-b px-4 py-3 cursor-pointer transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:bg-muted/40"
- >
- <div className="flex items-start justify-between gap-3">
- <div className="flex items-center gap-2.5">
- <div className="flex size-8 items-center justify-center rounded-lg bg-muted">
- <Server className="size-4 text-muted-foreground" />
- </div>
- <div>
- <h3 className="text-sm font-medium">Local Daemon</h3>
- <div className="flex items-center gap-1.5 mt-0.5">
- <span className={cn("size-1.5 rounded-full", DAEMON_STATE_COLORS[status.state])} />
- <span className="text-xs text-muted-foreground">{DAEMON_STATE_LABELS[status.state]}</span>
- {isRunning && status.uptime && (
- <>
- <span className="text-xs text-muted-foreground">·</span>
- <span className="text-xs text-muted-foreground">{formatUptime(status.uptime)}</span>
- </>
+ <Card size="sm">
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Server className="size-4 text-muted-foreground" />
+ Local daemon
+ <span className="inline-flex items-center gap-1.5 rounded-md border bg-background px-1.5 py-0.5 text-xs font-normal">
+ <span
+ className={cn(
+ "size-1.5 rounded-full",
+ DAEMON_STATE_COLORS[status.state],
)}
- {isRunning && status.agents && status.agents.length > 0 && (
- <>
- <span className="text-xs text-muted-foreground">·</span>
- <span className="text-xs text-muted-foreground">{status.agents.join(", ")}</span>
- </>
+ />
+ <span
+ className={cn(
+ "tabular-nums",
+ isRunning ? "text-foreground" : "text-muted-foreground",
)}
- </div>
- </div>
- </div>
-
- <div
- className="flex items-center gap-1.5 shrink-0"
- onClick={stopPropagation}
- >
- {isStopped && (
- <Button
- size="sm"
- variant="outline"
- onClick={handleStart}
- disabled={actionLoading || status.state === "cli_not_found"}
>
- {actionLoading ? (
- <Activity className="size-3.5 mr-1.5 animate-pulse" />
- ) : (
- <Play className="size-3.5 mr-1.5" />
- )}
- Start
- </Button>
- )}
- {isRunning && (
- <>
+ {DAEMON_STATE_LABELS[status.state]}
+ </span>
+ {isRunning && status.uptime && (
+ <span className="text-muted-foreground">
+ · {formatUptime(status.uptime)}
+ </span>
+ )}
+ </span>
+ </CardTitle>
+ <CardDescription>
+ {daemonStateDescription(status.state, runtimeCount)}
+ </CardDescription>
+ <CardAction className="self-center">
+ <div className="flex items-center gap-1.5">
+ {isRunning && (
+ <>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setPanelOpen(true)}
+ >
+ <ScrollText className="size-3.5 mr-1.5" />
+ View logs
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleRestart}
+ disabled={actionLoading}
+ >
+ <RotateCw className="size-3.5 mr-1.5" />
+ Restart
+ </Button>
+ <Button
+ size="sm"
+ variant="destructive"
+ onClick={handleStopClick}
+ disabled={actionLoading}
+ >
+ <Square className="size-3.5 mr-1.5" />
+ Stop
+ </Button>
+ </>
+ )}
+
+ {isStopped && (
<Button
size="sm"
- variant="ghost"
- onClick={handleRestart}
+ onClick={handleStart}
disabled={actionLoading}
>
- <RotateCw className="size-3.5 mr-1.5" />
- Restart
+ {actionLoading ? (
+ <Activity className="size-3.5 mr-1.5 animate-pulse" />
+ ) : (
+ <Play className="size-3.5 mr-1.5" />
+ )}
+ Start
</Button>
+ )}
+
+ {isCliMissing && (
<Button
size="sm"
variant="outline"
- onClick={handleStop}
+ onClick={handleRetryInstall}
disabled={actionLoading}
>
- <Square className="size-3.5 mr-1.5" />
- Stop
+ <RotateCw className="size-3.5 mr-1.5" />
+ Retry setup
</Button>
- </>
- )}
- {isTransitioning && (
- <Button size="sm" variant="outline" disabled>
- <Activity className="size-3.5 mr-1.5 animate-pulse" />
- {DAEMON_STATE_LABELS[status.state]}
- </Button>
- )}
- </div>
- </div>
- </div>
+ )}
- <DaemonPanel open={panelOpen} onOpenChange={setPanelOpen} status={status} />
+ {(isTransitioning || isInstalling) && (
+ <Button size="sm" variant="outline" disabled>
+ <Activity className="size-3.5 mr-1.5 animate-pulse" />
+ {DAEMON_STATE_LABELS[status.state]}
+ </Button>
+ )}
+ </div>
+ </CardAction>
+ </CardHeader>
+ </Card>
+
+ <DaemonPanel
+ open={panelOpen}
+ onOpenChange={setPanelOpen}
+ status={status}
+ runtimeCount={runtimeCount}
+ />
+
+ <StopConfirmDialog
+ open={confirmStop}
+ onOpenChange={setConfirmStop}
+ affectedCount={affectedTasks.length}
+ onConfirm={() => {
+ setConfirmStop(false);
+ void performStop();
+ }}
+ />
</>
);
}
+
+// ---------- Sub-components ----------
+
+function StopConfirmDialog({
+ open,
+ onOpenChange,
+ affectedCount,
+ onConfirm,
+}: {
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+ affectedCount: number;
+ onConfirm: () => void;
+}) {
+ const plural = affectedCount === 1 ? "" : "s";
+ const verb = affectedCount === 1 ? "is" : "are";
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-sm" showCloseButton={false}>
+ <div className="flex items-start gap-3">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-destructive/10">
+ <AlertCircle className="h-5 w-5 text-destructive" />
+ </div>
+ <DialogHeader className="flex-1 gap-1">
+ <DialogTitle className="text-sm font-semibold">
+ Stop daemon with {affectedCount} active task{plural}?
+ </DialogTitle>
+ <DialogDescription className="text-xs leading-relaxed">
+ {affectedCount} task{plural} {verb} currently running on this
+ device. Stopping now will interrupt {affectedCount === 1 ? "it" : "them"}{" "}
+ — affected tasks get marked <strong>failed</strong> once the
+ timeout hits. The daemon won&apos;t auto-restart.
+ </DialogDescription>
+ </DialogHeader>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button variant="destructive" onClick={onConfirm}>
+ Stop daemon
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
index b2be04e79c..0bc66e50f5 100644
--- a/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
+++ b/apps/desktop/src/renderer/src/components/daemon-settings-tab.tsx
@@ -1,7 +1,13 @@
-import { useState, useEffect, useCallback } from "react";
+import { useState, useEffect, useCallback, type ReactNode } from "react";
import { Button } from "@multica/ui/components/ui/button";
import { Switch } from "@multica/ui/components/ui/switch";
-import type { DaemonPrefs } from "../../../shared/daemon-types";
+import { cn } from "@multica/ui/lib/utils";
+import type { DaemonPrefs, DaemonStatus } from "../../../shared/daemon-types";
+import {
+ DAEMON_STATE_COLORS,
+ DAEMON_STATE_LABELS,
+ formatUptime,
+} from "../../../shared/daemon-types";
function SettingRow({
label,
@@ -10,7 +16,7 @@ function SettingRow({
}: {
label: string;
description: string;
- children: React.ReactNode;
+ children: ReactNode;
}) {
return (
<div className="flex items-center justify-between gap-6 py-4">
@@ -23,14 +29,44 @@ function SettingRow({
);
}
+// One row inside the diagnostics block. Values that are likely to be
+// long IDs / URLs render as monospaced + truncated with a tooltip.
+function DiagnosticsRow({
+ label,
+ value,
+ mono,
+}: {
+ label: string;
+ value: ReactNode;
+ mono?: boolean;
+}) {
+ return (
+ <div className="grid grid-cols-[140px_minmax(0,1fr)] items-baseline gap-3 py-1.5">
+ <span className="text-xs text-muted-foreground">{label}</span>
+ <span
+ className={cn(
+ "min-w-0 truncate text-sm",
+ mono && "font-mono text-xs",
+ )}
+ title={typeof value === "string" ? value : undefined}
+ >
+ {value}
+ </span>
+ </div>
+ );
+}
+
export function DaemonSettingsTab() {
const [prefs, setPrefs] = useState<DaemonPrefs>({ autoStart: true, autoStop: false });
const [cliInstalled, setCliInstalled] = useState<boolean | null>(null);
const [saving, setSaving] = useState(false);
+ const [status, setStatus] = useState<DaemonStatus>({ state: "stopped" });
useEffect(() => {
window.daemonAPI.getPrefs().then(setPrefs);
window.daemonAPI.isCliInstalled().then(setCliInstalled);
+ window.daemonAPI.getStatus().then(setStatus);
+ return window.daemonAPI.onStatusChange(setStatus);
}, []);
const updatePref = useCallback(
@@ -98,6 +134,68 @@ export function DaemonSettingsTab() {
)}
</div>
</div>
+
+ {/* Diagnostics — moved out of the logs panel so the panel can focus
+ on logs. These fields matter for support tickets and bug reports,
+ not for everyday use. */}
+ <div className="mt-8">
+ <h3 className="text-sm font-semibold">Diagnostics</h3>
+ <p className="text-xs text-muted-foreground mt-1">
+ Identification and connection details. Useful when filing a bug
+ report or investigating why a runtime isn&apos;t showing up.
+ </p>
+ <div className="mt-3 rounded-lg border bg-muted/20 px-4 py-2">
+ <DiagnosticsRow
+ label="State"
+ value={
+ <span className="inline-flex items-center gap-1.5">
+ <span
+ className={cn(
+ "size-1.5 rounded-full",
+ DAEMON_STATE_COLORS[status.state],
+ )}
+ />
+ {DAEMON_STATE_LABELS[status.state]}
+ </span>
+ }
+ />
+ <DiagnosticsRow
+ label="Uptime"
+ value={status.uptime ? formatUptime(status.uptime) : "—"}
+ />
+ <DiagnosticsRow
+ label="PID"
+ value={status.pid ?? "—"}
+ mono={!!status.pid}
+ />
+ <DiagnosticsRow
+ label="Daemon ID"
+ value={status.daemonId ?? "—"}
+ mono={!!status.daemonId}
+ />
+ <DiagnosticsRow
+ label="Profile"
+ value={status.profile || "default"}
+ />
+ <DiagnosticsRow
+ label="Server URL"
+ value={status.serverUrl ?? "—"}
+ mono={!!status.serverUrl}
+ />
+ <DiagnosticsRow
+ label="Device name"
+ value={status.deviceName ?? "—"}
+ />
+ <DiagnosticsRow
+ label="Workspaces"
+ value={
+ typeof status.workspaceCount === "number"
+ ? status.workspaceCount
+ : "—"
+ }
+ />
+ </div>
+ </div>
</div>
);
}
diff --git a/apps/desktop/src/renderer/src/components/parse-daemon-log.test.ts b/apps/desktop/src/renderer/src/components/parse-daemon-log.test.ts
new file mode 100644
index 0000000000..84e057c5e0
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/parse-daemon-log.test.ts
@@ -0,0 +1,124 @@
+import { describe, it, expect } from "vitest";
+import { parseLogLine } from "./parse-daemon-log";
+
+// All sample lines below are taken verbatim from real daemon output (Go
+// `slog` + `lmittmann/tint` v1.1.3 with NoColor=true). The parser must
+// stay aligned with what tint actually writes — not what we assume.
+
+describe("parseLogLine", () => {
+ it("parses tint's 3-letter INF level", () => {
+ const line =
+ "17:52:35.587 INF task completed component=daemon task=c45266e5 status=completed";
+ const r = parseLogLine(line, 1);
+ expect(r.timestamp).toBe("17:52:35.587");
+ expect(r.level).toBe("INFO");
+ expect(r.message).toBe("task completed");
+ expect(r.fields).toEqual({
+ component: "daemon",
+ task: "c45266e5",
+ status: "completed",
+ });
+ });
+
+ it("parses 3-letter DBG / WRN / ERR levels", () => {
+ expect(parseLogLine("17:53:06.644 DBG agent component=daemon", 1).level).toBe("DEBUG");
+ expect(parseLogLine("07:48:09.391 WRN claim task failed component=daemon", 1).level).toBe("WARN");
+ expect(parseLogLine("12:00:00.000 ERR something bad component=daemon", 1).level).toBe("ERROR");
+ });
+
+ it("still accepts 4-letter level names (defensive against config changes)", () => {
+ const r = parseLogLine("12:00:00.000 INFO regular component=daemon", 1);
+ expect(r.level).toBe("INFO");
+ expect(r.message).toBe("regular");
+ });
+
+ it("tolerates the +N / -N delta tint appends for non-standard slog levels", () => {
+ // tint emits e.g. "INF+1" when slog.Log is called with LevelInfo+1.
+ // We treat the base level as canonical and drop the delta from the UI.
+ const r = parseLogLine("12:00:00.000 INF+1 unusual delta component=daemon", 1);
+ expect(r.level).toBe("INFO");
+ expect(r.message).toBe("unusual delta");
+ });
+
+ it("preserves message text containing colons and special chars", () => {
+ // Real sample: "tool #1: Skill component=daemon task=..."
+ const r = parseLogLine(
+ "17:52:54.578 INF tool #1: Skill component=daemon task=8791b717",
+ 1,
+ );
+ expect(r.message).toBe("tool #1: Skill");
+ expect(r.fields).toEqual({ component: "daemon", task: "8791b717" });
+ });
+
+ it("unquotes a double-quoted value containing escaped quotes", () => {
+ // Real sample with escaped quotes inside the agent's emitted text.
+ const line =
+ '17:53:06.644 DBG agent component=daemon task=8791b717 text="The issue is just \\"ping\\" with no description."';
+ const r = parseLogLine(line, 1);
+ expect(r.message).toBe("agent");
+ expect(r.fields.text).toBe('The issue is just "ping" with no description.');
+ expect(r.fields.task).toBe("8791b717");
+ });
+
+ it("handles a quoted value containing a URL with embedded escaped quotes and a colon", () => {
+ // Real sample: error="Post \"http://...\": dial tcp ..."
+ const line =
+ '07:48:09.391 WRN claim task failed component=daemon runtime_id=03f8ff17-276d error="Post \\"http://localhost:8080/api/daemon/runtimes/abc/tasks/claim\\": dial tcp [::1]:8080: connect: connection refused"';
+ const r = parseLogLine(line, 1);
+ expect(r.level).toBe("WARN");
+ expect(r.message).toBe("claim task failed");
+ expect(r.fields.runtime_id).toBe("03f8ff17-276d");
+ expect(r.fields.error).toBe(
+ 'Post "http://localhost:8080/api/daemon/runtimes/abc/tasks/claim": dial tcp [::1]:8080: connect: connection refused',
+ );
+ });
+
+ it("handles a quoted value with internal whitespace (e.g. args array)", () => {
+ const line =
+ '17:52:48.757 INF agent command component=daemon exec=claude args="[-p --output-format stream-json --verbose]"';
+ const r = parseLogLine(line, 1);
+ expect(r.message).toBe("agent command");
+ expect(r.fields.exec).toBe("claude");
+ expect(r.fields.args).toBe("[-p --output-format stream-json --verbose]");
+ });
+
+ it("handles message words ending with characters before the field block", () => {
+ // 'execenv:' is part of the message — the colon shouldn't confuse parsing.
+ const r = parseLogLine(
+ "17:52:48.757 INF execenv: prepared env component=daemon repos_available=0",
+ 1,
+ );
+ expect(r.message).toBe("execenv: prepared env");
+ expect(r.fields).toEqual({ component: "daemon", repos_available: "0" });
+ });
+
+ it("falls back to raw rendering for non-matching lines (panic stack frame)", () => {
+ const r = parseLogLine("\tat github.com/multica/foo (line 42)", 1);
+ expect(r.timestamp).toBeNull();
+ expect(r.level).toBeNull();
+ expect(r.message).toBe("\tat github.com/multica/foo (line 42)");
+ expect(r.fields).toEqual({});
+ expect(r.raw).toBe("\tat github.com/multica/foo (line 42)");
+ });
+
+ it("falls back to raw rendering for unrecognised level tokens", () => {
+ // If tint ever emits something we don't know, never crash; show raw.
+ const r = parseLogLine("12:00:00.000 TRACE something exotic", 1);
+ expect(r.timestamp).toBeNull();
+ expect(r.level).toBeNull();
+ expect(r.raw).toBe("12:00:00.000 TRACE something exotic");
+ });
+
+ it("attaches an id to every parsed line for stable React keys", () => {
+ const a = parseLogLine("17:52:35.587 INF first component=daemon", 7);
+ const b = parseLogLine("17:52:35.588 INF second component=daemon", 8);
+ expect(a.id).toBe(7);
+ expect(b.id).toBe(8);
+ });
+
+ it("returns empty fields object when there are no key=value pairs", () => {
+ const r = parseLogLine("17:52:35.587 INF a bare message with no fields", 1);
+ expect(r.message).toBe("a bare message with no fields");
+ expect(r.fields).toEqual({});
+ });
+});
diff --git a/apps/desktop/src/renderer/src/components/parse-daemon-log.ts b/apps/desktop/src/renderer/src/components/parse-daemon-log.ts
new file mode 100644
index 0000000000..b0fbcbf695
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/parse-daemon-log.ts
@@ -0,0 +1,96 @@
+// Pure parser for daemon log lines. The daemon writes via Go's slog with
+// the `tint` handler in NoColor mode (the file isn't a TTY), so each line
+// has a stable shape:
+//
+// HH:MM:SS.mmm LEVEL message text key=value key2="quoted value"
+//
+// We split it into structured pieces so the UI can render timestamp,
+// level, message and structured fields in separate columns and let users
+// filter / search across them. Anything that doesn't match (panic stack
+// traces, third-party prints, partial writes during log rotation) falls
+// back to a raw view — we never drop input.
+
+export type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR";
+
+export interface ParsedLogLine {
+ /** Monotonic id assigned at receive time; stable across re-renders. */
+ id: number;
+ /** "HH:MM:SS.mmm" or null when the line didn't match the standard shape. */
+ timestamp: string | null;
+ level: LogLevel | null;
+ /** Human-readable message body, with structured fields stripped off. */
+ message: string;
+ /** key/value pairs trailing the message. Empty if there were none. */
+ fields: Record<string, string>;
+ /** The original line, kept for fallback rendering and copy-to-clipboard. */
+ raw: string;
+}
+
+// `tint` v1.x emits the 3-letter short form (DBG / INF / WRN / ERR) and,
+// for non-standard slog levels, appends a signed delta (e.g. "INF+1",
+// "DBG-2"). We accept both the short and 4-letter long forms (defensive
+// against future config changes) and normalize them to a canonical
+// 4-letter LogLevel. The optional `[+-]\d+` suffix is captured into the
+// regex and discarded — surfacing `INF+1` to the UI doesn't help users
+// and complicates the level filter chips.
+const HEADER_RE =
+ /^(\d{2}:\d{2}:\d{2}\.\d{3})\s+(DEBUG|DBG|INFO|INF|WARN|WRN|ERROR|ERR)(?:[+-]\d+)?\s+(.+)$/;
+
+const LEVEL_NORMALIZE: Record<string, LogLevel> = {
+ DEBUG: "DEBUG",
+ DBG: "DEBUG",
+ INFO: "INFO",
+ INF: "INFO",
+ WARN: "WARN",
+ WRN: "WARN",
+ ERROR: "ERROR",
+ ERR: "ERROR",
+};
+// Anchored to the END of the remaining string so we peel one field at a
+// time from the right. `value` is either a double-quoted string (which may
+// contain escaped chars) or any non-whitespace run.
+const TRAILING_FIELD_RE = /\s+([a-zA-Z_][a-zA-Z0-9_.]*)=("(?:[^"\\]|\\.)*"|\S+)$/;
+
+function unquote(value: string): string {
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
+ return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
+ }
+ return value;
+}
+
+function extractTrailingFields(rest: string): {
+ message: string;
+ fields: Record<string, string>;
+} {
+ const fields: Record<string, string> = {};
+ let work = rest;
+ while (true) {
+ const match = work.match(TRAILING_FIELD_RE);
+ if (!match || match.index === undefined) break;
+ fields[match[1]!] = unquote(match[2]!);
+ work = work.slice(0, match.index);
+ }
+ return { message: work.trim(), fields };
+}
+
+export function parseLogLine(raw: string, id: number): ParsedLogLine {
+ const match = raw.match(HEADER_RE);
+ if (!match) {
+ return { id, timestamp: null, level: null, message: raw, fields: {}, raw };
+ }
+ const [, timestamp, level, rest] = match;
+ const normalized = LEVEL_NORMALIZE[level!];
+ if (!normalized) {
+ // Unknown level token — keep raw shape so we don't mis-categorize.
+ return { id, timestamp: null, level: null, message: raw, fields: {}, raw };
+ }
+ const { message, fields } = extractTrailingFields(rest!);
+ return {
+ id,
+ timestamp: timestamp!,
+ level: normalized,
+ message,
+ fields,
+ raw,
+ };
+}
diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
index 8d1dc476b3..27f9021eb7 100644
--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
@@ -9,6 +9,7 @@ import {
import { setCurrentWorkspace } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";
+import { WorkspacePresencePrefetch } from "@multica/views/layout";
import { useTabStore } from "@/stores/tab-store";
/**
@@ -82,6 +83,7 @@ export function WorkspaceRouteLayout() {
return (
<WorkspaceSlugProvider slug={workspaceSlug}>
+ <WorkspacePresencePrefetch />
<Outlet />
</WorkspaceSlugProvider>
);
diff --git a/apps/desktop/src/renderer/src/pages/agent-detail-page.tsx b/apps/desktop/src/renderer/src/pages/agent-detail-page.tsx
new file mode 100644
index 0000000000..4ba7235729
--- /dev/null
+++ b/apps/desktop/src/renderer/src/pages/agent-detail-page.tsx
@@ -0,0 +1,18 @@
+import { useParams } from "react-router-dom";
+import { useQuery } from "@tanstack/react-query";
+import { AgentDetailPage as SharedAgentDetailPage } from "@multica/views/agents";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import { useDocumentTitle } from "@/hooks/use-document-title";
+
+export function AgentDetailPage() {
+ const { id } = useParams<{ id: string }>();
+ const wsId = useWorkspaceId();
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const agent = agents.find((a) => a.id === id) ?? null;
+
+ useDocumentTitle(agent?.name ?? "Agent");
+
+ if (!id) return null;
+ return <SharedAgentDetailPage agentId={id} />;
+}
diff --git a/apps/desktop/src/renderer/src/pages/runtime-detail-page.tsx b/apps/desktop/src/renderer/src/pages/runtime-detail-page.tsx
new file mode 100644
index 0000000000..4e31e1ac09
--- /dev/null
+++ b/apps/desktop/src/renderer/src/pages/runtime-detail-page.tsx
@@ -0,0 +1,18 @@
+import { useParams } from "react-router-dom";
+import { useQuery } from "@tanstack/react-query";
+import { RuntimeDetailPage as SharedRuntimeDetailPage } from "@multica/views/runtimes";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import { useDocumentTitle } from "@/hooks/use-document-title";
+
+export function RuntimeDetailPage() {
+ const { id } = useParams<{ id: string }>();
+ const wsId = useWorkspaceId();
+ const { data: runtimes } = useQuery(runtimeListOptions(wsId));
+ const runtime = runtimes?.find((r) => r.id === id);
+
+ useDocumentTitle(runtime?.name ?? "Runtime");
+
+ if (!id) return null;
+ return <SharedRuntimeDetailPage runtimeId={id} />;
+}
diff --git a/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts b/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts
new file mode 100644
index 0000000000..71b7d310af
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts
@@ -0,0 +1,76 @@
+"use client";
+
+import { useEffect } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { runtimeKeys } from "@multica/core/runtimes";
+import type { AgentRuntime } from "@multica/core/types";
+
+/**
+ * DesktopAPI exposes a richer DaemonStatus shape than the public AgentRuntime
+ * type — we redeclare the fields we consume here to avoid coupling the bridge
+ * to the desktop preload typings (which live in apps/desktop/src/preload).
+ */
+interface DaemonStatusLike {
+ state: "running" | "stopped" | "starting" | "stopping" | "installing_cli" | "cli_not_found";
+ daemonId?: string;
+}
+
+/**
+ * Merges a local DaemonStatus into an AgentRuntime row. Only the `status`
+ * field is overridden; other fields (name, provider, last_seen_at, etc)
+ * remain server-authoritative. We deliberately ignore intermediate states
+ * (starting / stopping / installing_cli / cli_not_found) so the cache
+ * doesn't flap during boot — if the daemon is in such a state, the runtime
+ * is effectively offline anyway, and the server-side sweeper will mark it
+ * within 75s.
+ */
+function mergeDaemonStatus(rt: AgentRuntime, status: DaemonStatusLike): AgentRuntime {
+ if (status.state === "stopped" || status.state === "stopping") {
+ return { ...rt, status: "offline" };
+ }
+ if (status.state === "running") {
+ return {
+ ...rt,
+ status: "online",
+ last_seen_at: new Date().toISOString(),
+ };
+ }
+ return rt;
+}
+
+/**
+ * Subscribes to local daemon status changes via Electron IPC and writes them
+ * into the runtimes Query cache for the active workspace.
+ *
+ * Why: the server-side runtime sweeper takes up to 75s to flip a runtime to
+ * offline (heartbeat timeout 45s + sweep interval 30s). On the desktop app
+ * we know about local daemon state instantly via IPC, so we use it to
+ * pre-populate the cache and give users a sub-second feedback loop. Web and
+ * "looking at someone else's daemon" still go through the server path.
+ *
+ * Same-daemon-multiple-runtimes: a single daemon can back several runtimes
+ * in the same workspace (one per provider). We map across all matches so
+ * every related runtime row sees the same status flip.
+ */
+export function useDaemonIPCBridge(wsId: string | undefined): void {
+ const qc = useQueryClient();
+
+ useEffect(() => {
+ if (!wsId) return;
+ if (typeof window === "undefined") return;
+ const daemonAPI = (window as unknown as { daemonAPI?: { onStatusChange?: (cb: (s: DaemonStatusLike) => void) => () => void } }).daemonAPI;
+ if (!daemonAPI?.onStatusChange) return;
+
+ const unsubscribe = daemonAPI.onStatusChange((status) => {
+ if (!status.daemonId) return;
+ qc.setQueryData<AgentRuntime[]>(runtimeKeys.list(wsId), (old) => {
+ if (!old) return old;
+ return old.map((rt) =>
+ rt.daemon_id === status.daemonId ? mergeDaemonStatus(rt, status) : rt,
+ );
+ });
+ });
+
+ return unsubscribe;
+ }, [wsId, qc]);
+}
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index 06dd0b81c2..09f65415b5 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -10,6 +10,8 @@ import { IssueDetailPage } from "./pages/issue-detail-page";
import { ProjectDetailPage } from "./pages/project-detail-page";
import { AutopilotDetailPage } from "./pages/autopilot-detail-page";
import { SkillDetailPage } from "./pages/skill-detail-page";
+import { AgentDetailPage } from "./pages/agent-detail-page";
+import { RuntimeDetailPage } from "./pages/runtime-detail-page";
import { IssuesPage } from "@multica/views/issues/components";
import { ProjectsPage } from "@multica/views/projects/components";
import { AutopilotsPage } from "@multica/views/autopilots/components";
@@ -117,6 +119,11 @@ export const appRoutes: RouteObject[] = [
element: <DesktopRuntimesPage />,
handle: { title: "Runtimes" },
},
+ {
+ path: "runtimes/:id",
+ element: <RuntimeDetailPage />,
+ handle: { title: "Runtime" },
+ },
{ path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },
{
path: "skills/:id",
@@ -124,6 +131,11 @@ export const appRoutes: RouteObject[] = [
handle: { title: "Skill" },
},
{ path: "agents", element: <AgentsPage />, handle: { title: "Agents" } },
+ {
+ path: "agents/:id",
+ element: <AgentDetailPage />,
+ handle: { title: "Agent" },
+ },
{ path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },
{
path: "settings",
diff --git a/apps/desktop/src/shared/daemon-types.ts b/apps/desktop/src/shared/daemon-types.ts
index 17e2a9e854..8005d437c5 100644
--- a/apps/desktop/src/shared/daemon-types.ts
+++ b/apps/desktop/src/shared/daemon-types.ts
@@ -51,3 +51,35 @@ export function formatUptime(uptime?: string): string {
const m = match[2] ? `${match[2]}m` : "";
return `${h}${m}`.trim() || uptime;
}
+
+/**
+ * User-facing description for the local daemon's current state. Replaces the
+ * raw state label ("Running" / "Stopped") with a sentence that answers
+ * "what does this mean for me?" — i.e. whether tasks can run on this device.
+ *
+ * `runtimeCount` is the number of runtimes the local daemon has registered
+ * (claude / codex / gemini / ... — one per detected CLI). It's only consulted
+ * when state === "running".
+ */
+export function daemonStateDescription(state: DaemonState, runtimeCount: number): string {
+ switch (state) {
+ case "running":
+ if (runtimeCount === 0) {
+ return "Running, but no runtimes have registered yet.";
+ }
+ if (runtimeCount === 1) {
+ return "Running here · 1 runtime available for tasks.";
+ }
+ return `Running here · ${runtimeCount} runtimes available for tasks.`;
+ case "stopped":
+ return "Not running · this device can't take new tasks.";
+ case "starting":
+ return "Starting up the local daemon…";
+ case "stopping":
+ return "Shutting down the local daemon…";
+ case "installing_cli":
+ return "Setting up the runtime for the first time. Only happens once.";
+ case "cli_not_found":
+ return "Setup failed · couldn't download the runtime. Check your network.";
+ }
+}
diff --git a/apps/web/.gitignore b/apps/web/.gitignore
new file mode 100644
index 0000000000..e985853ed8
--- /dev/null
+++ b/apps/web/.gitignore
@@ -0,0 +1 @@
+.vercel
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/[id]/page.tsx
new file mode 100644
index 0000000000..fe38e9a159
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/[id]/page.tsx
@@ -0,0 +1,13 @@
+"use client";
+
+import { use } from "react";
+import { AgentDetailPage } from "@multica/views/agents";
+
+export default function AgentDetailRoute({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = use(params);
+ return <AgentDetailPage agentId={id} />;
+}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/runtimes/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/runtimes/[id]/page.tsx
new file mode 100644
index 0000000000..9c9300ddee
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/runtimes/[id]/page.tsx
@@ -0,0 +1,13 @@
+"use client";
+
+import { use } from "react";
+import { RuntimeDetailPage } from "@multica/views/runtimes";
+
+export default function RuntimeDetailRoute({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = use(params);
+ return <RuntimeDetailPage runtimeId={id} />;
+}
diff --git a/docs/agent-runtime-status-redesign.md b/docs/agent-runtime-status-redesign.md
new file mode 100644
index 0000000000..8a533bb22e
--- /dev/null
+++ b/docs/agent-runtime-status-redesign.md
@@ -0,0 +1,802 @@
+# Agent / Runtime 状态系统重设计
+
+> **文档定位**:这是一份完整的设计 + 实施方案。任何一个新加入的工程师 / 设计师 / 产品,看完这份文档应该能:
+> - 理解我们要解决的问题、为什么这么解决
+> - 知道每个阶段做什么、按什么顺序做、产出什么
+> - 在不读代码的前提下能独立讨论方案
+>
+> 本文档是 [agent-status-design-brief.md](./agent-status-design-brief.md) 和 [agent-status-redesign-plan.md](./agent-status-redesign-plan.md) 的合并升级版,达成共识后会取代它们。
+
+---
+
+## 目录
+
+1. [背景与目标](#一背景与目标)
+2. [核心思想](#二核心思想)
+3. [状态系统规范](#三状态系统规范)
+4. [数据架构](#四数据架构)
+5. [跨平台策略](#五跨平台策略)
+6. [设计语言](#六设计语言)
+7. [实施分阶段](#七实施分阶段)
+8. [验收标准](#八验收标准)
+9. [边界与不做的事](#九边界与不做的事)
+10. [风险与注意事项](#十风险与注意事项)
+11. [参考](#十一参考)
+
+---
+
+## 一、背景与目标
+
+### 1.1 Multica 的产品定位提醒
+
+Multica 是 AI-native 的任务管理平台——agent 是和人对等的"同事"。一个工作区里同时有人和 agent 在协作,相互分配任务、评论、订阅。
+
+理解这个定位很重要,因为它直接决定了状态系统的需求:**用户对 agent 的预期跟"对同事的预期"是相同的**——我希望随时知道这个同事现在能不能接活、在不在线、是不是出问题了。
+
+### 1.2 当前的核心问题
+
+**所有界面都在直接展示后端的原始字段,缺少"用户视角"的状态翻译层。**
+
+具体表现(按用户感知严重度排序):
+
+1. **Agent 列表的 "Idle" 绿点会骗人**——daemon 已经死了,agent 仍然显示 Idle。用户分配任务后没有任何反馈,长时间困惑"为什么 agent 不动"。
+2. **Runtime 列表只有一个圆点**——"刚断线 5 分钟"和"3 个月前断线"视觉一模一样,用户判断不出严重程度。
+3. **Issue 详情页多个 agent 同时工作时只有 1 个可见**——其他 agent 的卡片埋在下方滚动区,没有总览。
+4. **任务失败时只有红色 X**——`agent_error`(agent 自己挂了)和 `runtime_offline`(daemon 离线)处理方式完全不同,但视觉上不区分。
+5. **Chat 发消息后只有一个 spinner 转数分钟**——无法区分"排队"、"思考"、"调用工具"、"生成回答"四个阶段。
+
+### 1.3 根本原因
+
+后端字段是**任务调度的内部状态**(`agent.status` = idle/working/blocked/error),不是给用户看的。当前前端把后端字段直接渲染给用户,就把"调度内部视角"暴露成了"用户视角"。
+
+但用户不关心 agent 的内部调度状态,用户关心的是:
+
+- **能不能用?**(在线 / 离线)
+- **如果在用,在干什么?**(工作中 / 排队中 / 失败了)
+- **如果不能用,为什么?**(daemon 离线 / CLI 没装 / 任务超时)
+
+这些问题的答案,**没有任何一个能从单一字段直接得到**——它们都需要把多个数据源聚合后才能算出来。
+
+### 1.4 目标
+
+**做一套"用户视角"的状态系统**,覆盖三类对象:
+
+- **Agent**:5 态(available / working / pending / failed / offline),跨界面一致
+- **Runtime**:4 态(online / recently_lost / offline / about_to_gc)
+- **Task**:阶段化(queued / dispatched / thinking / using_tool / generating / completed / failed)
+
+完成这套系统后,下列现有界面会自然变好:
+
+- Agents 列表 / 详情:看到真实可用性
+- Runtimes 列表 / 详情:看到机器健康度
+- Issue Detail:多 agent 全景 + 失败原因显示
+- 跨界面 hover card(issue assignee / autopilot / chat / @mention):状态一致
+- Chat:分阶段进度
+
+---
+
+## 二、核心思想
+
+### 2.1 一句话
+
+**把"用户视角的状态"做成前端的派生量**——后端只暴露真相(任务存在、心跳到达),前端按 UI 需要把这些真相聚合成"用户能理解的状态"。
+
+### 2.2 三个设计原则
+
+#### 原则 1:派生函数住在前端,不污染后端
+
+`agent.status` / `runtime.status` 这些后端字段是 **物理事实**:
+- "task X 现在 running"
+- "daemon Y 45 秒前发了心跳"
+
+而 "Available / Working / Pending / Failed / Offline" 这些是 **UI 翻译**:
+- "FAILED 状态保持 2 分钟" 是设计决策
+- "蓝色表示 working" 是视觉决策
+- 不同界面可能要不同视角(issue 里看"任务阶段"、列表里看"是否可分配")
+
+**UI 翻译应该住在前端,跟着设计需求一起迭代。** 把它放进后端,每改一次都要 migration + WS payload 兼容 + 老客户端处理,迭代周期从分钟变周。
+
+#### 原则 2:服务器状态住在 TanStack Query cache,不复制进 Zustand
+
+我们的全局状态有两套:
+- **Zustand** 管 client state(UI 选中、筛选器、modal 开关)
+- **TanStack Query cache** 管 server state(来自 API 的所有数据)
+
+TQ cache 不是组件级缓存,**它本身就是 server state 的全局状态管理**。跨组件共享、按 key 索引、自动去重。
+
+派生状态是 server data 的纯函数。结果不存——每次组件渲染时按需用 `useMemo` 算一遍。算的成本是几个 filter + some 调用,可忽略。
+
+#### 原则 3:聚合在前端做,但要避免 N+1
+
+派生状态需要 3 份原始数据:
+- agents 列表
+- runtimes 列表
+- 当前活跃任务列表(active tasks)
+
+朴素做法:每个组件 `useAgentTasks(agentId)`——一个 issues 列表 30 个 agent 头像 = 30 次请求。这就是 N+1。
+
+正解:**进工作区时一次性拉"全工作区的活跃任务"**(数据量天然不大,活跃任务永远是少数),存进 TQ cache。所有组件共享这一份缓存,按 agentId 在内存里 filter——零额外请求。
+
+这是把"per-agent 的数据需求"转换成"全工作区的集合数据需求"。集合数据天然只需要 1 次请求。
+
+---
+
+## 三、状态系统规范
+
+### 3.1 Agent 五态
+
+| 状态 | 颜色 | 用户语义 | 出现条件 |
+|---|---|---|---|
+| **Available** | 🟢 绿 | 在线空闲,可以接活 | runtime 在线 + 没有活跃任务 |
+| **Working** | 🔵 蓝 | 正在干活 | runtime 在线 + 至少一个任务在执行 |
+| **Pending** | 🟡 黄 | 任务排着但没在跑 | runtime 在线 + 0 个执行中 + ≥1 个排队 |
+| **Failed** | 🔴 红 | 最近一次失败 | 最近 2 分钟内有任务失败 |
+| **Offline** | ⚫ 灰 | Daemon 离线,不可用 | runtime 离线(包含 CLI 未安装) |
+
+**复合维度**:当 agent 是 Working 但同时有任务排队,主状态保持 Working,旁边带 `+N` 角标("还有 N 个排队")。
+
+**派生规则**(按优先级匹配,命中即返回):
+
+```ts
+type AgentPresence = "available" | "working" | "pending" | "failed" | "offline"
+
+function deriveAgentPresence(input: {
+ agent: Agent
+ runtime: AgentRuntime
+ recentTasks: AgentTask[] // 该 agent 最近 N 个任务
+ now: number // 当前时间戳
+}): AgentPresence {
+ // 1. Runtime 离线(含 CLI 未安装)→ offline
+ if (input.runtime.status === "offline") return "offline"
+
+ // 2. 最近窗口内有 failed task → failed
+ const recentFailed = input.recentTasks.find(
+ t => t.status === "failed" &&
+ (input.now - new Date(t.completed_at).getTime()) < FAILED_WINDOW_MS
+ )
+ if (recentFailed) return "failed"
+
+ // 3. 有 running task → working
+ if (input.recentTasks.some(t => t.status === "running")) return "working"
+
+ // 4. 有 queued/dispatched task → pending
+ if (input.recentTasks.some(t => t.status === "queued" || t.status === "dispatched")) {
+ return "pending"
+ }
+
+ // 5. Otherwise → available
+ return "available"
+}
+```
+
+**复合维度的派生**:
+
+```ts
+function deriveAgentPresenceDetail(...): {
+ presence: AgentPresence
+ runningCount: number
+ queuedCount: number
+ failureReason?: TaskFailureReason // 仅 presence === "failed" 时有值
+}
+```
+
+**待确认常量**:
+
+- `FAILED_WINDOW_MS = 2 * 60 * 1000`(2 分钟)。
+ - 短到避免污染(任务失败的红点不会一直黏着)
+ - 长到让用户能看见(不会还没看就消失)
+ - **未来可能扩展**:2 分钟内强提示(红色动效),之后降级为 tooltip 的"最近失败"摘要——这样既不刺眼,又不丢信息。本期先用固定 2 分钟。
+
+### 3.2 Runtime 四态
+
+| 状态 | 触发条件 | 用户语义 |
+|---|---|---|
+| **Online** | 最近 45 秒内有心跳 | 健康,能接任务 |
+| **Recently Lost** | 离线但 < 5 分钟 | 可能短暂网络抖动 |
+| **Offline** | 离线 5 分钟 ~ 7 天 | 长期离线,需要排查 |
+| **About to GC** | 离线接近 7 天阈值 | 系统将自动清理 |
+
+```ts
+function deriveRuntimeHealth(runtime: AgentRuntime, now: number): RuntimeHealth {
+ if (runtime.status === "online") return "online"
+
+ const lastSeen = runtime.last_seen_at
+ ? new Date(runtime.last_seen_at).getTime()
+ : 0
+ const offlineFor = now - lastSeen
+
+ if (offlineFor < 5 * 60 * 1000) return "recently_lost"
+ if (offlineFor > 6 * 24 * 3600 * 1000) return "about_to_gc" // 7d - 1d
+ return "offline"
+}
+```
+
+> **关于 CLI 未安装等"runtime 在线但跑不了"的场景**:归并到 `offline`,tooltip 写明具体原因("CLI 未安装"、"Daemon 启动中")。不为此引入第六态——状态空间膨胀代价高,分辨率应该用 tooltip / detail 而不是顶层枚举。
+
+### 3.3 Task 阶段化
+
+用于 Issue Detail 和 Chat 显示当前任务在哪一步:
+
+```ts
+type TaskStage =
+ | "queued"
+ | "dispatched" // dispatched 但进程没起来
+ | "thinking" // running,最后一条 message 是 thinking
+ | "using_tool" // running,最后一条是 tool_use / tool_result
+ | "generating" // running,最后一条是 text
+ | "completed"
+ | "failed"
+ | "cancelled"
+```
+
+派生函数读 task 状态 + 最后一条 message 的 type 即可决定阶段。
+
+### 3.4 失败原因映射
+
+`task.failure_reason` 来自后端 migration 055,5 个值映射到中文标签:
+
+```ts
+const FAILURE_REASON_LABEL: Record<TaskFailureReason, string> = {
+ agent_error: "Agent 执行报错",
+ timeout: "执行超时",
+ runtime_offline: "Daemon 离线",
+ runtime_recovery: "Daemon 重启回收",
+ manual: "用户取消",
+}
+```
+
+每种原因要给用户对应的处理建议(具体文案待设计师定)。
+
+> ⚠️ **当前差异**:后端 schema 已有 `failure_reason`(migration 055),但前端 `packages/core/types/agent.ts` 的 `AgentTask` 接口**未暴露此字段**。阶段 0 必须同步:
+> - 前端类型补 `failure_reason: TaskFailureReason | null`
+> - 检查后端 `ListAgentTasks` / 新增的 `ListActiveTasksByWorkspace` 是否 SELECT 了这个字段
+
+---
+
+## 四、数据架构
+
+### 4.1 数据流
+
+```
+ 后端真相
+ ┌────────────┬─────────────┬──────────────┐
+ │ agents │ runtimes │ active_tasks│
+ │ (HTTP) │ (HTTP) │ (HTTP) │
+ └─────┬──────┴──────┬──────┴───────┬──────┘
+ │ │ │
+ └─────────────┴──────────────┘
+ ▼
+ TanStack Query cache
+ (全局共享)
+ ▼
+ 派生函数(纯函数)
+ ┌───────────────┴───────────────┐
+ ▼ ▼
+ AgentPresence RuntimeHealth
+ │ │
+ ▼ ▼
+ 组件渲染(5 态视觉) 组件渲染(4 态视觉)
+
+ ──────────────────────────────────────────────
+
+ 实时更新
+
+ 后端 WS 事件 ──→ 前端 invalidate query ──→ 重拉 ──→ 派生重算 ──→ UI 更新
+
+ 桌面端额外:本机 IPC ──→ setQueryData 直接预填 ──→ 亚秒级响应
+```
+
+### 4.2 三个 query
+
+```ts
+// 进工作区时一次性拉
+useQuery(['ws', wsId, 'agents']) // listAgents
+useQuery(['ws', wsId, 'runtimes']) // listRuntimes
+useQuery(['ws', wsId, 'active-tasks']) // ★ 新增:getActiveTasksForWorkspace
+```
+
+**`active-tasks` 是新增 query**——返回当前工作区所有 status ∈ {queued, dispatched, running} 的任务。这份数据天然小(活跃任务不会很多),值得做成"全工作区一次拉"。
+
+> ⚠️ **当前差异**:后端**没有此 endpoint**。现有只有 `listAgentTasks(agentId)`(per-agent)和 `getActiveTasksForIssue(issueId)`(per-issue)。阶段 0 必须新增 `GET /api/workspaces/:slug/active-tasks`——它仍然返回原始 task 列表,不做任何派生,**不违反"零后端聚合"原则**。
+
+#### Runtime → Agents 是 reverse query
+
+后端没有 "runtime 服务的 agent 列表" API。Agent 持有 `runtime_id` 外键,但 Runtime 没有反向关联。
+
+**前端处理**:从已缓存的 `agents` 列表 `filter(a => a.runtime_id === rtId)` 即可。这不算 N+1(agents 列表本来就要拉),是免费的 join。
+
+### 4.3 WS 事件接线表
+
+| WS 事件 | 触发的 invalidate |
+|---|---|
+| `agent:created` / `agent:archived` / `agent:updated` | `['ws', wsId, 'agents']` |
+| `agent:status` | `['ws', wsId, 'agents']`(即使我们不用这个值,缓存 fresh 仍要) |
+| `daemon:register` | `['ws', wsId, 'runtimes']` |
+| `task:dispatch` / `task:completed` / `task:failed` / `task:cancelled` | `['ws', wsId, 'active-tasks']` |
+| `task:progress` | (考虑节流,避免高频任务刷新缓存) |
+| `daemon:heartbeat` | **故意忽略** —— 后端发送但前端不订阅,避免每 15 秒过度 refetch。后果:runtime online → recently_lost 切换最坏延迟 75 秒(45s sweeper + 30s 间隔)。设计上接受这个延迟。 |
+
+**关键不变量**:每个派生函数依赖的字段都必须有对应 WS 事件覆盖。任何字段没事件覆盖,状态会卡住。每次新增派生维度都要回头检查这张表。
+
+### 4.4 桌面端 IPC 桥接
+
+桌面端通过 Electron IPC 直接读本机 daemon。这份数据:
+- 比 server WS **快 75 秒**(IPC 亚秒,server sweep 最坏 75s)
+- 包含 server 看不到的 `starting` / `stopping` / `cli_not_found` 等中间态
+
+**不修改派生函数签名**——桌面端把 IPC 数据用 `setQueryData` 直接写进 runtime cache:
+
+```ts
+// 仅桌面端:apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts
+window.electron.onDaemonStatus((status) => {
+ queryClient.setQueryData(
+ ['ws', wsId, 'runtimes'],
+ (old) => old?.map(rt =>
+ rt.id === status.runtimeId ? mergeDaemonStatus(rt, status) : rt
+ )
+ )
+})
+```
+
+派生函数完全不知道数据从哪来——它只读 cache。**桌面端自动获得亚秒级体验,零派生函数改动**。
+
+---
+
+## 五、跨平台策略
+
+### 5.1 状态系统是平台无关的
+
+派生函数、5 态/4 态规范、UI 视觉——**两端共享同一套**。设计稿只画一份。
+
+### 5.2 数据源平台相关
+
+| 平台 | Runtime 数据来源 | 状态变化感知延迟 |
+|---|---|---|
+| Web | server WS / HTTP | 最坏 75 秒 |
+| Desktop(本机 daemon) | IPC + server | < 1 秒 |
+| Desktop(别人的 daemon) | server WS / HTTP | 跟 Web 一样 |
+
+数据源不同不影响 UI——派生函数读 cache,cache 是"哪边更新就更新"。
+
+### 5.3 操作能力平台相关
+
+| 操作 | Web | Desktop(自己机器) | Desktop(别人机器) |
+|---|---|---|---|
+| 看状态 | ✅ | ✅ | ✅ |
+| 重启 daemon | ❌ | ✅ | ❌ |
+| 看 daemon logs | ❌ | ✅ | ❌ |
+| 看 CLI 安装详情 | ❌ | ✅ | ❌ |
+
+实现方式:组件按 `isLocalDaemon && isOwner` 条件渲染按钮。**不需要写进派生函数 / 状态系统**,是 UI 局部决策。
+
+### 5.4 Daemon 卡片视觉对齐
+
+桌面端 settings 里的"本机 daemon 卡片"必须跟云端 runtime 列表项视觉一致。同一台机器同一个概念,不能两套设计。
+
+---
+
+## 六、设计语言
+
+### 6.1 直接复用 Skills 界面(PR #1607、#1614、#1618、#1610)
+
+Skills 界面已经在 2026-04 完成重设计,是当前产品的视觉锚点。Agents / Runtimes 直接照搬其规则:
+
+1. **统一页头** `PageHeader`(h-12 + mobile sidebar trigger)
+2. **响应式网格列表**:`grid-cols-[minmax(0,1.6fr)_minmax(0,0.8fr)_minmax(0,1.2fr)_minmax(0,6rem)_auto]`
+3. **每行三层信息**:主标题 → 描述(line-clamp-1 muted)→ 元数据(xs muted)
+4. **关联对象用头像堆栈**:最多 3 + `+N`,size=22 + `ring-2 ring-background` + `-space-x-1.5`
+5. **卡片化列表 + 卡片内工具栏**:搜索和 scope tab 在 `CardToolbar`(h-12),不在页面级
+6. **创建用多步 dialog**:chooser → 表单,可回退;宽度按方法切换,300ms 过渡
+7. **空状态分文案**:图标 + 标题 + 三行说明 + 清晰 CTA
+8. **长列表 `useScrollFade`**:上下边缘淡出
+9. **头像统一 `ActorAvatar`**:传 `size`,自动支持 agent / 人
+10. **权限检查 hook 化**:`useCanEdit...`,UI 提前隐藏/禁用
+
+### 6.2 状态视觉的三个层级
+
+每种派生状态在三个层级要保持一致:
+
+- **Dot**(圆点):列表项、头像旁,最紧凑
+- **Badge**(徽章):详情页头部、卡片角落,带图标 + 文字
+- **Tooltip / Hover Card**:鼠标悬停展开完整信息
+
+**跨界面一致性**:同一个 agent 无论出现在哪(agents 列表 / issue assignee picker / autopilot 编辑 / chat 选择面板 / 评论 @),状态视觉必须完全一致。
+
+---
+
+## 七、实施分阶段
+
+### 阶段 0 — 数据层地基(无 UI 改动)
+
+**目标**:派生函数 + cache + WS + IPC 桥接全部就位。UI 暂不动。完成后所有 UI 阶段都能放心假设"派生状态可用、零额外请求"。
+
+#### 后端工作(Go)
+
+| 文件 | 改动 |
+|---|---|
+| `server/pkg/db/queries/agent_task.sql` | 新增 sqlc query:`ListActiveTasksByWorkspace`,SELECT 所有字段含 `failure_reason`,过滤 status ∈ {queued, dispatched, running} |
+| `server/pkg/db/agent_task.sql.go` | `make sqlc` 自动生成 |
+| `server/internal/handler/agent.go`(或新建 task handler) | `ListActiveTasksByWorkspace` handler,权限校验:用户必须是 workspace member |
+| `server/cmd/server/router.go` | 注册路由 `GET /api/workspaces/{slug}/active-tasks` |
+| **核查**:现有 `ListAgentTasks` query | 确认 SELECT `failure_reason` 字段;如未 SELECT,补上 |
+
+#### 前端类型补全
+
+| 文件 | 改动 |
+|---|---|
+| `packages/core/types/agent.ts` | `AgentTask` 接口加 `failure_reason: TaskFailureReason \| null`;新增 `TaskFailureReason = "agent_error" \| "timeout" \| "runtime_offline" \| "runtime_recovery" \| "manual"` |
+
+#### 前端 API client
+
+| 文件 | 改动 |
+|---|---|
+| `packages/core/api/client.ts` | 新增方法 `getActiveTasksForWorkspace(wsSlug): Promise<AgentTask[]>` |
+
+#### 前端派生函数 + 类型
+
+| 文件 | 内容 |
+|---|---|
+| `packages/core/agents/types.ts`(如不存在则新建) | `AgentPresence` / `AgentPresenceDetail` / `RuntimeHealth` 等类型 |
+| `packages/core/agents/derive-presence.ts` | `deriveAgentPresence` / `deriveAgentPresenceDetail` 纯函数 |
+| `packages/core/agents/derive-presence.test.ts` | 5 态全分支 + 边界 case(runtime null / tasks 空 / 时钟边界) |
+| `packages/core/runtimes/derive-health.ts` | `deriveRuntimeHealth` |
+| `packages/core/runtimes/derive-health.test.ts` | 4 态全分支 |
+
+#### 前端 query + hook
+
+| 文件 | 内容 |
+|---|---|
+| `packages/core/agents/active-tasks-query.ts` | `activeTasksOptions(wsId)` query options |
+| `packages/core/agents/use-agent-presence.ts` | `useAgentPresence(agentId)` hook:读 3 份 cache → 派生 |
+| `packages/core/runtimes/use-runtime-health.ts` | `useRuntimeHealth(runtimeId)` hook |
+| `packages/core/runtimes/use-runtime-agents.ts` | `useRuntimeAgents(runtimeId)` hook:从 agents cache filter 出绑定的 agents |
+
+#### 前端 WS 接线
+
+| 文件 | 改动 |
+|---|---|
+| `packages/core/realtime/agent-runtime-sync.ts` | 新增专用 sync。订阅 `agent:*` / `task:dispatch` / `task:completed` / `task:failed` / `task:cancelled` / `daemon:register` → invalidate 对应 query。**显式不订阅 `daemon:heartbeat`**(接受 75 秒延迟) |
+| `packages/core/realtime/use-realtime-sync.ts`(如已有全局 hook) | 集成新 sync |
+
+#### 桌面端 IPC 桥接
+
+| 文件 | 内容 |
+|---|---|
+| `apps/desktop/src/renderer/src/platform/daemon-ipc-bridge.ts` | 监听 `window.daemonAPI.onStatus(...)`,用 `queryClient.setQueryData` 把本机 daemon status merge 进对应 runtime cache |
+
+#### 完成标准
+
+- [ ] 后端 `GET /api/workspaces/:slug/active-tasks` 通 curl 测试,返回 active tasks 列表
+- [ ] `deriveAgentPresence` / `deriveRuntimeHealth` 单测全部通过
+- [ ] 控制台调用 `useActiveTasks(wsId)` 能拿到全工作区活跃任务
+- [ ] 控制台调用 `useAgentPresence(agentId)` 能拿到正确的 5 态状态
+- [ ] WS 接线表里所有事件都能正确 invalidate(手测覆盖)
+- [ ] 关本机 daemon 后桌面端 runtime cache **1 秒内**变 offline
+- [ ] 不动任何 UI 文件——这阶段 zero UI delta
+
+### 阶段 1 — Agents + Runtimes 列表页
+
+**目标**:两个列表用上派生状态,互相能看到对方。
+
+#### 设计师产出(先于代码)
+
+- 5 态 dot / badge / tooltip 三层视觉规范
+- Working + 排队角标的复合视觉
+- Failed 状态的 2 分钟时间窗口动效
+- Runtime 4 态的视觉差异(不能再是同一个浅灰圆点)
+
+#### 改造文件
+
+| 文件 | 改动 |
+|---|---|
+| `packages/views/agents/components/agent-list-item.tsx` | 替换 `statusConfig[agent.status]` 为 `useAgentPresence(agentId)` |
+| `packages/views/agents/components/agents-page.tsx` | 接 WS 订阅 |
+| `packages/views/agents/config.ts` | 删除 `statusConfig`,新建 `presenceConfig` |
+| `packages/views/runtimes/components/runtime-list.tsx` | 用派生 4 态;展示 last_seen、关联 agent 数、当前任务数 |
+| `packages/views/runtimes/components/runtimes-page.tsx` | 接 WS 订阅 |
+| `apps/desktop/.../local-daemon-card.tsx` | 视觉对齐云端 runtime 卡片 |
+
+### 阶段 2 — Agents + Runtimes 详情页
+
+**目标**:详情页头部、profile card 状态联动;Runtime token usage 信息架构整理。
+
+#### 改造文件
+
+| 文件 | 改动 |
+|---|---|
+| `packages/views/agents/components/agent-detail.tsx` | 头部 status badge 用派生 |
+| `packages/views/agents/components/agent-profile-card.tsx` | 状态行和 runtime 行联动;展示当前任务数 + 最近失败原因 |
+| `packages/views/runtimes/components/runtime-detail.tsx` | Token usage 主次重排:核心指标置顶,5 个图表折叠 / 下沉 |
+| `packages/views/runtimes/components/usage-section.tsx` | API 调用按时间窗口拉(不再总是 90 天) |
+
+### 阶段 3 — Issue Detail 任务展示
+
+**目标**:多 agent 全景视图;任务阶段化;失败原因显式。
+
+#### 新增文件
+
+| 文件 | 内容 |
+|---|---|
+| `packages/core/agents/derive-task-stage.ts` | `deriveTaskStage` |
+| `packages/core/agents/derive-task-stage.test.ts` | 单测 |
+| `packages/views/issues/components/agent-task-row.tsx` | 单 agent 单任务一行 |
+
+#### 改造文件
+
+| 文件 | 改动 |
+|---|---|
+| `packages/views/issues/components/agent-live-card.tsx` | 从"sticky 一个 + 折叠列表"改为"每个 agent 一行" |
+| `packages/views/issues/components/agent-transcript-dialog.tsx` | 失败时展示 failure_reason |
+
+### 阶段 4 — 跨界面 Hover Card
+
+**目标**:所有 agent 头像出现的位置都用统一的 hover card。
+
+#### Hover Card 必须显示的内容(按重要度排序)
+
+1. 派生 5 态状态
+2. Runtime 健康(在线性 + last_seen 相对时间)
+3. 当前任务(N running / M queued)
+4. 最近失败(如果有):原因 + 时间
+5. Agent 名称 + description
+6. 关联 skills(前 3 个 + `+N`)
+7. Owner
+
+#### 必须接入的位置
+
+| 位置 | 当前状态 |
+|---|---|
+| Agents 列表 / 详情 | ✅ 已有 |
+| Issue Assignee Picker | ❌ 仅头像无状态 |
+| Issue Detail 头部 assignee | ❌ 仅头像无状态 |
+| Issue 列表 / 看板的分配头像 | ❌ 仅头像 |
+| Autopilot 列表 / 编辑(assignee) | ❌ 仅头像 |
+| Project lead picker | ❌ 仅头像 |
+| Chat 选择 agent 面板 | ❌ 待确认 |
+| 评论里的 @agent | ❌ 仅头像 |
+
+#### 实施
+
+`ActorAvatar` 组件挂载 hover card——一处改动,上面所有位置自动获得统一卡片。
+
+**N+1 风险已经被阶段 0 的"全工作区 active-tasks"消除**——hover card 只读 cache,零额外请求。
+
+### 阶段 5 — Chat 状态分阶段(独立 PR)
+
+工作量较大,跟流式渲染相关,单独排期。
+
+#### 改造文件
+
+| 文件 | 改动 |
+|---|---|
+| `packages/views/chat/components/chat-message-list.tsx` | `AssistantMessage` 用 `deriveTaskStage` 替代单 spinner |
+| `packages/views/chat/components/chat-page.tsx` | WS 断线重连后的消息回拉 fallback |
+
+#### 必须解决
+
+- 取代单 spinner,按阶段显示
+- Failed task 显示原因
+- WS 断线重连后能拉回历史消息
+
+#### 加分项
+
+- Typing indicator(generating 阶段的逐字感)
+- 全局任务进度 FAB
+- Stop 按钮的明确反馈
+
+---
+
+## 八、验收标准
+
+### 阶段 0
+
+- [ ] `deriveAgentPresence` / `deriveRuntimeHealth` 单测覆盖所有分支 + 边界 case(runtime null / tasks 空 / 时钟边界)
+- [ ] 控制台调用 `useActiveTasks(wsId)` 能拿到数据
+- [ ] WS 事件接线表里每个事件都能正确 invalidate(手测)
+- [ ] 桌面端关本机 daemon 后 runtime cache 在 1s 内变 offline
+
+### 阶段 1
+
+- [ ] Daemon 关闭后,Agent 列表项 75 秒内变成 Offline 灰点
+- [ ] Agent 跑任务时,列表项变成 Working 蓝点;排队 N 个时带 `+N` 角标
+- [ ] Agent 任务失败后,列表项 2 分钟内显示 Failed 红点 + tooltip 含失败原因,2 分钟后自动恢复
+- [ ] Runtime 列表能区分 Online / Recently Lost / Offline / About to GC 四态
+- [ ] Runtime 列表行展示关联 agent 数 + 当前任务数
+- [ ] 桌面端本机 daemon 卡片视觉跟云端 runtime 列表项一致
+- [ ] 全局 grep `agent.status` 在 views 层无引用
+
+### 阶段 2
+
+- [ ] Agent 详情头部状态跟列表一致
+- [ ] Profile card 状态行 + runtime 行不再自相矛盾
+- [ ] Runtime 详情页能在不展开图表的前提下看到本期成本
+- [ ] Token usage API 按选中的时间窗口拉(不再总是 90 天)
+
+### 阶段 3
+
+- [ ] 同一 issue 多 agent 工作时,每个 agent 一行实时状态
+- [ ] queued / dispatched / running 三态视觉差异清晰
+- [ ] 任务失败时,行内显示中文 failure reason + 处理建议
+- [ ] 不支持 live log 的 provider 显式说明"等任务完成后查看结果"
+
+### 阶段 4
+
+- [ ] 所有展示 agent 头像的位置 hover 都能看到完整状态卡
+- [ ] 渲染 30+ agent 头像的页面,hover 不触发任何新 HTTP 请求
+
+### 阶段 5
+
+- [ ] Chat 中能看到任务在哪个阶段
+- [ ] WS 断线后重连能补齐历史消息
+- [ ] Failed task 显示原因
+
+---
+
+## 九、边界与不做的事
+
+明确**不在本次范围内**:
+
+1. **不改后端 schema**——`agent.status` / `blocked` / `error` 字段保留(迁移风险大,无收益)
+2. **不让后端做派生**——所有派生在前端做(迭代速度 + UI 解耦)
+3. **不新增 WS 事件类型**——只订阅现有但未用的(如 `agent:status`)
+4. **不动 `agent_runtime.status` 的 online/offline 二态**——前端从这两态 + `last_seen_at` 派生四态
+5. **不重构 Skills 界面**——它已经是参考样板
+6. **Phase 5 不做"逐字流式渲染"**——后端 stream-json 是批量推送,typing indicator 是视觉技巧
+7. **不做"agent 健康综合评分"**——只暴露原始信号,不算综合分
+8. **不为 CLI 未安装等场景引入第六态**——归到 offline 的 tooltip 子分类
+9. **不在 Zustand 里存派生结果**——server data 不能复制进 store
+
+---
+
+## 十、风险与注意事项
+
+### 10.1 WS 事件覆盖完整性
+
+派生函数的"实时性"靠的是依赖 query 都被 WS 正确 invalidate。一个事件没接好,状态就会卡住。
+
+**缓解**:阶段 0 的接线表是必须维护的"契约"。每次新增派生维度,回头检查这张表,确保新依赖的字段有事件覆盖。
+
+### 10.2 时钟一致性
+
+Failed 状态依赖客户端时间和 `completed_at` 的差。客户端时钟漂移会让 2 分钟窗口不准。
+
+**缓解**:2 分钟 ± 30 秒不影响判断,可接受。需要时可用 server 在 WS 心跳里携带的时间作为参考。
+
+### 10.3 旧字段引用残留
+
+`statusConfig` 删除后,遗漏的引用会运行时错误。
+
+**缓解**:
+- TypeScript 严格模式 + 改类型
+- 全局 grep 验证
+- 长期防御:在 `packages/core/agents/types.ts` 把 `agent.status` 从外部消费的 Agent 类型里 omit 掉,仅保留在 RawAgent 内部类型里给 API 层用
+
+### 10.4 跨界面状态一致性
+
+不同地方调用同一个 agent 的派生函数,必须结果一致。
+
+**缓解**:所有调用方走 `useAgentPresence(agentId)` 这个唯一 hook,不允许直接调派生函数。Hook 集中管理输入数据收集。
+
+### 10.5 active-tasks 数据量
+
+如果工作区某天有 1000+ 活跃任务,全工作区一次拉的设计会受影响。
+
+**缓解**:
+- 当前活跃任务有天然上限(受 `max_concurrent_tasks` × agent 数量约束)
+- 监控加上:cache 大小超过阈值时上报
+- 必要时再考虑 windowing(最近 N 个)或 server 端聚合
+
+---
+
+## 十一、参考
+
+- [产品全景文档](./product-overview.md) —— Agent / Runtime / Daemon 的产品定位
+- [Skills 界面源代码](../packages/views/skills/) —— 设计语言样板
+- 关键 PR:#1607(Skills 重设计)、#1614(Card + PageHeader)、#1618(描述恢复)、#1610(Dialog 闪烁修复)
+- 后端关键代码:
+ - `server/internal/service/task.go` —— `agent.status` 更新逻辑(`ReconcileAgentStatus`)
+ - `server/cmd/server/runtime_sweeper.go` —— Runtime 心跳 / sweeper 时间常量
+ - `server/migrations/055_task_lease_and_retry.up.sql` —— Task `failure_reason` 五态
+ - `server/migrations/037_fix_pending_task_unique_index.up.sql` —— 一个 issue 多 agent 处理的设计依据
+
+---
+
+## 附录 A:当前现状清单(保留作为重设计前的存档)
+
+> 这部分原本在 design-brief.md 里,迁移过来作为重设计前的现状记录。设计师在画稿前可以贴上当前界面截图作为对照。
+
+### A.1 Agent 字段可见性
+
+| 字段 | 当前状态 | 备注 |
+|---|---|---|
+| `name` / `avatar_url` / `description` | ✅ | 列表 + 详情都展示 |
+| `archived_at` | ✅ | 列表项灰显 + 详情头部 banner |
+| `status`(idle/working/...) | ✅ 但语义错误 | **要替换成派生 5 态** |
+| `runtime_mode`(local/cloud) | ✅ 图标 | 列表项右侧 Cloud / Monitor 图标 |
+| `instructions` | ✅ | Instructions tab |
+| `custom_env` / `custom_env_redacted` | ✅ | Env tab |
+| `custom_args` | ✅ | Custom Args tab |
+| `visibility`(workspace / private) | ✅ | Settings tab |
+| `max_concurrent_tasks` | ✅ | Settings tab |
+| `model` | ✅ | Settings tab |
+| `runtime_id` 关联 | ✅ | Settings tab |
+| `skills` | ✅ | Skills tab + profile card 前 3 个 |
+| `owner_id` | ✅ | Profile card |
+| `created_at` / `updated_at` | 🆕 | 后端有,UI 完全没展示 |
+| `archived_by` | 🆕 | 后端有,UI 隐藏 |
+
+### A.2 Runtime 字段可见性
+
+| 字段 | 当前状态 | 备注 |
+|---|---|---|
+| `name` | ✅ | 列表 + 详情头部 |
+| `provider` | ✅ Logo | 9 种 |
+| `runtime_mode` | ✅ 文字 | `RuntimeModeIcon` 组件存在但从未被调用 |
+| `status`(online/offline) | ✅ 圆点 + 徽章 | 离线圆点浅色主题下几乎不可见 |
+| `last_seen_at` | ✅ 仅详情页 | **列表完全看不到** |
+| `device_info` | ✅ 详情页 | 没有人类可读化 |
+| `daemon_id` | ✅ mono 字体 | 不可复制 |
+| `metadata.cli_version` | ✅ | CLI 更新部分 |
+| `metadata.launched_by` | ✅ | "Managed by Desktop" |
+| `owner_id` | ✅ | 头像 + 名字 |
+| `created_at` / `updated_at` | ✅ | ISO 时间戳 |
+
+### A.3 桌面端 IPC 数据
+
+```
+DaemonStatus (本地 IPC)
+├─ state: running / stopped / starting / stopping / installing_cli / cli_not_found
+├─ pid, uptime
+├─ daemonId, deviceName, serverUrl
+├─ agents: 当前运行的 agent IDs
+├─ workspaceCount
+└─ profile
+```
+
+### A.4 截图占位区
+
+设计师拿到这份文档后,请把以下界面的当前截图贴在对应位置:
+
+- **Agents 界面**:列表页 / 详情页(每 tab 一张)/ 创建对话框
+- **Runtimes 界面**:列表页 / 详情页(含 5 个图表)/ 桌面端 daemon 卡片
+- **Issue Detail**:无任务执行时 / 单 agent 执行中 / 多 agent 并发 / 全屏 transcript dialog
+
+### A.5 Token Usage 5 个图表的数据细节
+
+Runtime 详情页底部 token usage 部分,5 个图表 + 1 张表格全部展开,没有主次。阶段 2 改造时按下表理解每个图表的数据契约:
+
+| 图表 | 数据源 | 时间粒度 | 维度 | 度量 |
+|---|---|---|---|---|
+| **Activity Heatmap** | `getRuntimeUsage?days=90` | 日 | date | 4 级强度,按 token 总量百分位分级 |
+| **Hourly Activity** | `getRuntimeTaskActivity` | 小时(0-23) | hour | 任务数 |
+| **Daily Token Chart** | 同 Heatmap,客户端聚合 | 日 | date | input/output/cacheRead/cacheWrite 总和 |
+| **Daily Cost Chart** | 同上 + 客户端定价计算 | 日 | date | 美元成本,按 model pricing 表 |
+| **Model Distribution** | 同上聚合 by model | 全周期 | model | tokens 占比 + cost |
+
+**当前实现的问题**:API 总是取 90 天数据,客户端做 7d/30d 过滤——浪费服务端资源,首次加载慢。改造时按选中窗口拉。
+
+### A.6 Issue Detail 任务展示的当前实现
+
+主要组件:`packages/views/issues/components/agent-live-card.tsx`
+
+#### 已有能力
+
+- 多 agent 并发执行同一 issue 时,第一个卡片是 sticky(顶部固定),其他在下方滚动
+- 每个 task 卡片可展开 timeline,显示 tool_use / tool_result / thinking / text / error 五种消息类型
+- 实时滚动:WS 事件 `task:message` 到达时追加 timeline
+- 工具调用计数 badge
+- Stop 按钮可取消任务
+- 全屏 transcript dialog(支持事件类型筛选 + 复制)
+- 已完成/失败/取消的任务进入 TaskRunHistory 折叠区
+
+#### 数据来源
+
+| 数据 | API |
+|---|---|
+| 当前 issue 的活跃 task 列表 | `getActiveTasksForIssue(issueId)` |
+| 每个 task 的历史消息 | `listTaskMessages(taskId)` |
+| 实时消息流 | WS `task:message` |
+| 状态变化 | WS `task:dispatch` / `task:completed` / `task:failed` / `task:cancelled` |
+| 取消任务 | `cancelTask(issueId, taskId)` |
+
+阶段 3 在此基础上重构成"每个 agent 一行的全景视图"。
diff --git a/docs/agent-runtime-ui-design-brief.md b/docs/agent-runtime-ui-design-brief.md
new file mode 100644
index 0000000000..c673705088
--- /dev/null
+++ b/docs/agent-runtime-ui-design-brief.md
@@ -0,0 +1,530 @@
+# Agents & Runtimes 界面重设计 · 设计师 Brief
+
+> **文档定位**:这份文档专门给负责重设计 Agents 和 Runtimes 界面的 UI/UX 设计师。
+>
+> 看完这份文档,你应该能:
+> - 理解我们在解决什么问题、目标体感是什么
+> - 知道每个界面有哪些数据可用、哪些是新展示的、哪些需要工程补
+> - 知道有哪些现有交互不能动(避免破坏用户已建立的习惯)
+> - 知道可以参考哪些已经做完的设计(Skills 是样板)
+> - 直接进入设计稿环节
+>
+> **必读伴侣文档**:[Agent / Runtime 状态系统重设计](./agent-runtime-status-redesign.md) —— 完整的工程方案、状态规范、实施阶段。本 brief 是它的"设计师视角切片"。
+
+---
+
+## 目录
+
+1. [一句话目标](#一一句话目标)
+2. [必读:状态视觉规范](#二必读状态视觉规范)
+3. [Agents 界面](#三agents-界面)
+4. [Runtimes 界面](#四runtimes-界面)
+5. [跨界面统一:Agent Hover Card](#五跨界面统一agent-hover-card)
+6. [跨平台差异处理](#六跨平台差异处理)
+7. [设计语言参考:Skills 界面](#七设计语言参考skills-界面)
+8. [工程会同步交付的能力](#八工程会同步交付的能力)
+9. [设计师产出清单](#九设计师产出清单)
+10. [附录:截图占位区](#十附录截图占位区)
+
+---
+
+## 一、一句话目标
+
+**当前所有界面都在直接展示后端字段,缺少"用户视角"的状态翻译层。**
+
+用户看到 `Idle` / `Online` / spinner,但这些词没有回答"agent 现在能不能用 / 在做什么 / 出问题了没"。我们要做的是一套**用户视角的状态系统**:让用户一眼就知道一个 agent / runtime 的健康状况,跨界面一致。
+
+---
+
+## 二、必读:状态视觉规范
+
+这套规范是所有界面的共同基础。**先输出这套规范,再画具体界面**。
+
+### 2.1 Agent 五态
+
+| 状态 | 颜色 | 用户语义 | 出现条件 |
+|---|---|---|---|
+| **Available** | 🟢 绿 | 在线空闲,可以接活 | runtime 在线 + 没有活跃任务 |
+| **Working** | 🔵 蓝(品牌色) | 正在干活 | runtime 在线 + 至少一个任务在执行 |
+| **Pending** | 🟡 黄 | 任务排着但没在跑 | runtime 在线 + 0 个执行中 + ≥1 个排队 |
+| **Failed** | 🔴 红 | 最近一次失败 | 最近 2 分钟内有任务失败 |
+| **Offline** | ⚫ 灰 | Daemon 离线,不可用 | runtime 离线 |
+
+**复合维度**:当 agent 是 Working 但同时有任务排队,主状态保持 Working,旁边带 `+N` 角标("还有 N 个排队")。
+
+**Failed 状态特别说明**:失败显示**保持 2 分钟**,之后自动恢复(避免红点黏太久)。设计上要表达"这是临时强提示"。
+
+### 2.2 Runtime 四态
+
+| 状态 | 触发条件 | 用户语义 |
+|---|---|---|
+| **Online** | 最近 45 秒内有心跳 | 健康 |
+| **Recently Lost** | 离线但 < 5 分钟 | 可能短暂网络抖动 |
+| **Offline** | 离线 5 分钟 ~ 7 天 | 长期离线,需排查 |
+| **About to GC** | 离线接近 7 天阈值 | 系统将自动清理 |
+
+> **关于 CLI 未安装等"runtime 在线但跑不了"的场景**:归并到 Offline,tooltip 写明具体原因("CLI 未安装"、"Daemon 启动中")。**不要为这些子情况新设状态色**,色彩枚举太多反而失去信号。
+
+### 2.3 视觉表达分三层
+
+每种状态在以下三个层级要保持一致:
+
+- **Dot**(圆点):列表项、头像旁的小圆点,最紧凑场景
+- **Badge**(徽章):详情页头部、卡片角落,带图标 + 文字
+- **Tooltip / Hover Card**:鼠标悬停时展开完整信息
+
+**跨界面一致性**:同一个 agent,无论出现在哪(agents 列表 / issue assignee picker / autopilot 编辑 / chat 选择面板 / 评论 @),状态视觉**必须完全一致**。这是这次设计能立住的关键。
+
+---
+
+## 三、Agents 界面
+
+### 3.1 当前界面长什么样
+
+主要文件:
+- `packages/views/agents/components/agents-page.tsx` — 列表页容器
+- `packages/views/agents/components/agent-list-item.tsx` — 列表项
+- `packages/views/agents/components/agent-detail.tsx` — 详情页(含 tabs:Instructions / Skills / Tasks / Environment / Custom Args / Settings)
+- `packages/views/agents/components/agent-profile-card.tsx` — 详情顶部的 profile 卡片
+- `packages/views/agents/components/create-agent-dialog.tsx` — 创建对话框
+
+**当前的视觉语言跟 Skills 重设计前一样——这次目标是迁到 Skills 风格。**
+
+### 3.2 当前的核心痛点
+
+按用户感知严重度排列:
+
+1. **列表上的 "Idle" 绿点会骗人**——daemon 已经死了,agent 仍然显示 Idle。用户分配任务后没有任何反馈。**根因**:`agent-list-item.tsx` 完全忽略 runtime 在线性,只读 `agent.status` 这个后端字段。
+2. **`agent-profile-card` 状态行和 runtime 行不联动**——状态显 Idle,runtime 显 Offline,自相矛盾。
+3. **跨界面状态展示不一致**——issue assignee picker、autopilot picker、chat 选择 agent 时**完全不显示状态**,用户做选择时不知道哪个能用。
+4. **创建 agent 时无法预知能否立即跑起来**——dialog 显示了 runtime 在线点,但不知道 model 是否合法、初始化会不会失败。
+5. **Archived agent 和 active agent 混在同一列表**——切换视图全靠手动按钮,不够清晰。
+6. **零 WS 订阅**——离线/上线必须手动刷新页面才能感知。
+
+### 3.3 重设计目标
+
+#### 必须达成
+
+- 列表项一眼能看出 agent 是否真的可用(融合 runtime 在线性的派生 5 态)
+- Hover card 内必须看到:派生状态、当前任务数、runtime 健康、最近失败原因
+- 跨界面一致:所有显示 agent 头像的位置都用同一个 hover card(详见第 5 节)
+- 创建/编辑 agent 时,能预看"如果保存,agent 会变成什么状态"
+- 实时更新——状态变化 75 秒内反映到 UI
+
+#### 加分项
+
+- Archived agent 独立 tab/折叠区,不再和 active 混在一起
+- 列表支持按"最近活动时间"排序
+- 支持按状态筛选("显示所有 Failed"、"显示所有 Pending")
+
+### 3.4 可用数据清单(设计稿可以放心假设可用)
+
+> **图例**:✅ = 当前已展示;🆕 = 已可用但当前 UI 没用;🔧 = 工程会在阶段 0 补上;📡 = 实时事件可用
+
+#### Agent 主体字段(来自 `Agent` type)
+
+| 字段 | 类型 | 当前状态 | 说明 |
+|---|---|---|---|
+| `name` / `avatar_url` / `description` | string | ✅ | 已展示 |
+| `archived_at` / `archived_by` | string | ✅ / 🆕 | 列表灰显;archived_by 后端有但 UI 隐藏 |
+| `runtime_mode` | "local" / "cloud" | ✅ 图标 | Cloud / Monitor 图标区分 |
+| `instructions` | string | ✅ | Instructions tab |
+| `custom_env` / `custom_env_redacted` | KV / bool | ✅ | Env tab,权限控制隐藏值 |
+| `custom_args` | string[] | ✅ | Custom Args tab |
+| `visibility` | "workspace" / "private" | ✅ | Settings tab |
+| `max_concurrent_tasks` | number | ✅ | Settings tab,默认 6 |
+| `model` | string | ✅ | Settings tab |
+| `runtime_id` | string | ✅ 选择器 | Settings tab |
+| `skills` | Skill[] | ✅ | Skills tab + profile card 前 3 个 |
+| `owner_id` | string | ✅ | Profile card 显示名字 |
+| `created_at` / `updated_at` | string | 🆕 | **后端有,UI 完全没展示** —— 可以做"最近创建"、"最近修改"标签 |
+| ~~`status`~~(idle/working/blocked/error/offline) | enum | ✅ 但**已废弃**展示 | 后端字段保留但 UI 完全不读 |
+
+#### 派生数据(工程在阶段 0 提供,设计稿可放心引用)
+
+| 派生信息 | 来源 |
+|---|---|
+| **Agent 派生 5 态状态** | 🔧 由 agent + runtime + active tasks 派生 |
+| **当前 running 任务数** | 🔧 派生 |
+| **当前 queued 任务数** | 🔧 派生 |
+| **最近一次失败的原因**(5 种 enum) | 🔧 派生 |
+| **关联 runtime 健康状态** | 🔧 派生 |
+| **runtime last_seen 相对时间** | 🔧 已有工具函数 |
+
+**失败原因 5 个枚举(中文文案待你定)**:
+- `agent_error` — Agent 执行报错
+- `timeout` — 执行超时
+- `runtime_offline` — Daemon 离线
+- `runtime_recovery` — Daemon 重启回收
+- `manual` — 用户取消
+
+每种原因用户的处理方式不同,UI 应给出对应建议(你来设计文案)。
+
+#### 实时事件(WS)
+
+| 事件 | 状态 | 用途 |
+|---|---|---|
+| `agent:status` | 📡 后端发,工程接 | agent 字段变化 |
+| `agent:created` / `agent:archived` / `agent:restored` | 📡 工程接 | 列表增删 |
+| `task:dispatch` / `task:completed` / `task:failed` / `task:cancelled` | 📡 工程接 | 状态派生关键信号 |
+| `daemon:register` | 📡 工程接 | runtime 上下线 |
+
+设计上**不需要为"加载/loading"过度设计**——状态变化是实时的,几乎不会出现"等数据"的 loading 态。
+
+### 3.5 不能动的现有交互(必须保留)
+
+- 创建 agent dialog 的 chooser → 表单两步流(见 Skills 的 `create-skill-dialog`)
+- 各 tab 的编辑能力:Instructions / Env / Custom Args / Settings 全部可编辑
+- Archive / Restore 操作
+- Tasks tab:展示该 agent 的历史 task 列表(按状态分组:活跃 → 完成)
+- Skills tab:可挂载/卸载 skills
+
+### 3.6 关键问题留给你定的
+
+1. **Archived agent 怎么收纳**:独立 tab、折叠区、还是 segment 切换?
+2. **状态筛选**是 chips 还是 dropdown?
+3. **Failed 红点的 2 分钟动效**:脉冲?颜色渐变?
+4. **复合状态(Working + 排队 N)**:角标位置(dot 旁 / 头像下角 / Badge 内嵌)?
+5. **创建 dialog 的"预览状态"**:怎么不打扰主流程的同时让用户知道"这个 agent 创建出来会是什么色"?
+
+---
+
+## 四、Runtimes 界面
+
+### 4.1 当前界面长什么样
+
+主要文件:
+- `packages/views/runtimes/components/runtimes-page.tsx` — 容器,含 owner filter(mine/all)
+- `packages/views/runtimes/components/runtime-list.tsx` — 列表
+- `packages/views/runtimes/components/runtime-detail.tsx` — 详情头部
+- `packages/views/runtimes/components/usage-section.tsx` — Token usage 主区
+- `packages/views/runtimes/components/charts/` — 5 个图表组件
+- `packages/views/runtimes/components/update-section.tsx` — CLI 更新流程
+- `apps/desktop/src/renderer/src/components/daemon-runtime-card.tsx` — 桌面端独有:本机 daemon 卡片(通过 IPC,独立于 server runtime 列表)
+
+### 4.2 当前的核心痛点
+
+按严重度排列:
+
+1. **离线圆点几乎不可见**——浅色主题下 `bg-muted-foreground/40` 视觉上消失。
+2. **列表无 last_seen**——无法区分"刚断线 5 分钟"和"3 个月前断线"。
+3. **看不到 runtime 服务了哪些 agent / 当前有几个 task 在跑**——runtime 在用户心智里成了"孤岛"。
+4. **7 天 GC 阈值无任何 UI 提示**——runtime 突然消失,用户不知道为什么。
+5. **桌面端 daemon 卡片和云端 runtime 卡片视觉分裂**——同一台机器同一概念,两套设计。
+6. **Token usage 信息过载**——5 个图表 + 1 张表全部展开,普通用户找不到"本月花了多少钱"。
+7. **无 ping / 诊断按钮**——遇到断线没法主动验证。
+8. **`RuntimeModeIcon` 死代码**——本地 vs 云端在列表项里没有图标区分。
+
+### 4.3 重设计目标
+
+#### 必须达成
+
+- 列表项一眼区分四态:Online / Recently Lost / Offline / About to GC
+- 列表项展示**关联 agent 数量** + **当前任务数**(runtime 不再是孤岛)
+- 桌面端 daemon 卡片和云端 runtime 卡片用统一视觉语言
+- Token usage 区分主次:核心指标(本期成本、token 总量)放顶部,详细图表折叠或下沉
+
+#### 加分项
+
+- Runtime 健康综合评分(在线 + 心跳新鲜度 + 任务负载)
+- 7 天 GC 倒计时提示
+- Ping / 诊断按钮
+- 高使用量 runtime 的视觉强调(成本警告、利用率热图 sparkline)
+- Local vs Cloud 图标区分(启用废弃组件 `RuntimeModeIcon`)
+
+### 4.4 可用数据清单
+
+#### Runtime 主体字段(来自 `RuntimeDevice` type)
+
+| 字段 | 类型 | 当前状态 | 说明 |
+|---|---|---|---|
+| `name` | string | ✅ | 列表 + 详情头部 |
+| `provider` | string | ✅ Logo | 9 种:claude / codex / opencode / openclaw / hermes / gemini / pi / cursor 等 |
+| `runtime_mode` | "local" / "cloud" | ✅ 文字 | 列表项里没图标(死代码) |
+| `status` | "online" / "offline" | ✅ 圆点 | 浅色主题下离线几乎不可见 |
+| `last_seen_at` | string | ✅ 仅详情页 | **列表完全看不到** |
+| `device_info` | string | ✅ 详情页 | 显示原始字符串如 `darwin-arm64`,无人类可读化 |
+| `daemon_id` | string | ✅ mono 字体 | 不可复制 / 不可点击 |
+| `metadata.cli_version` | string | ✅ | CLI 更新部分用 |
+| `metadata.launched_by` | string | ✅ | 桌面端启动时显示 "Managed by Desktop" |
+| `owner_id` | string | ✅ | 头像 + 名字 |
+| `created_at` / `updated_at` | string | ✅ | 详情页底部 ISO 时间戳 |
+
+#### 派生数据(工程阶段 0 提供)
+
+| 派生信息 | 来源 |
+|---|---|
+| **Runtime 4 态健康** | 🔧 由 status + last_seen_at 派生 |
+| **服务的 agent 列表 + 数量** | 🔧 前端 join(agent 持有 runtime_id,列表数据已在 cache) |
+| **当前在跑 task 数** | 🔧 前端 filter active-tasks |
+| **last_seen 相对时间字符串**("5 minutes ago") | 🔧 工具函数已有 |
+
+#### Token Usage 5 个图表的数据契约
+
+| 图表 | 数据源 | 时间粒度 | 维度 | 度量 |
+|---|---|---|---|---|
+| **Activity Heatmap** | `getRuntimeUsage?days=90` | 日 | date | 4 级强度,按 token 总量百分位分级 |
+| **Hourly Activity** | `getRuntimeTaskActivity` | 小时(0-23) | hour | 任务数 |
+| **Daily Token Chart** | 同 Heatmap,客户端聚合 | 日 | date | input/output/cacheRead/cacheWrite 总和 |
+| **Daily Cost Chart** | 同上 + 客户端定价 | 日 | date | 美元成本 |
+| **Model Distribution** | 同上聚合 by model | 全周期 | model | tokens 占比 + cost |
+
+**当前实现的问题**:API 总是取 90 天数据,客户端做 7d/30d 过滤——浪费服务端资源。改造时按选中窗口拉。
+
+#### 实时事件
+
+| 事件 | 状态 |
+|---|---|
+| `daemon:register` | 📡 已订阅,触发列表刷新 |
+| `daemon:heartbeat` | 📡 后端发但前端**故意忽略**(防过度刷新)。设计时假设状态变化最坏 75 秒内可见 |
+
+#### 桌面端独有的本机 IPC 数据(仅桌面端可见)
+
+```
+DaemonStatus (本机 IPC,亚秒级实时)
+├─ state: running / stopped / starting / stopping / installing_cli / cli_not_found
+├─ pid, uptime, daemonId, deviceName, serverUrl
+├─ agents: 当前运行的 agent IDs
+├─ workspaceCount
+└─ profile
+```
+
+工程会把这份数据自动喂进 cache,**设计上不要为"桌面端有更多数据"做特殊视觉**——派生状态对设计师而言是统一的,只是桌面端响应更快。但桌面端**对自己的本机 daemon 有更多操作能力**(见第 6 节)。
+
+### 4.5 不能动的现有交互(必须保留)
+
+- Owner filter(mine/all toggle)
+- Delete runtime 操作(含权限检查)
+- CLI 更新流程(`update-section.tsx`):检查更新、触发更新、查看更新状态
+- 5 个图表的数据展示(信息架构可以重排,但数据本身要保留)
+- 桌面端:start/stop/restart 本机 daemon 的按钮
+
+### 4.6 关键问题留给你定的
+
+1. **列表项到底放多少信息**:last_seen + agent count + active tasks 放哪?避免拥挤
+2. **桌面端 daemon 卡片和云端 runtime 卡片"视觉对齐"的尺度**:100% 同模板?还是同卡片框 + 内容差异化?
+3. **Token usage 主次怎么排**:本期成本数字 + 单图表 + "查看更多" 折叠?或者 dashboard 化?
+4. **About to GC 怎么提示**:横幅?badge?倒计时?
+5. **Ping / 诊断按钮的位置**:详情页头部?右上角菜单?
+6. **关联 agent 列表展示**:堆叠头像?文字 "3 agents"?还是子区块?
+
+---
+
+## 五、跨界面统一:Agent Hover Card
+
+### 5.1 现有组件
+
+`packages/views/agents/components/agent-profile-card.tsx`——已经存在,但只在 Agents 主页 hover 时出现。
+
+这次会把它升级成**统一 hover card**,挂到所有展示 agent 头像的地方。
+
+### 5.2 必须出现的位置
+
+| 位置 | 当前状态 |
+|---|---|
+| Agents 列表 / 详情 | ✅ 已有 |
+| Issue Assignee Picker | ❌ 仅头像无状态 |
+| Issue Detail 头部 assignee | ❌ 仅头像无状态 |
+| Issue 列表 / 看板的分配头像 | ❌ 仅头像 |
+| Autopilot 列表 / 编辑(assignee) | ❌ 仅头像 |
+| Project lead picker | ❌ 仅头像 |
+| Chat 选择 agent 面板 | ❌ 待确认 |
+| 评论里的 @agent | ❌ 仅头像 |
+
+### 5.3 卡片必须显示什么(按重要度)
+
+1. **派生 5 态状态**(不是 `agent.status` 原始值)
+2. **Runtime 健康**:在线性 + last_seen 相对时间
+3. **当前任务**:N running / M queued
+4. **最近失败**(如果有):原因 + 时间
+5. **Agent 名称 + description**
+6. **关联 skills**(前 3 个 + `+N`)
+7. **Owner**
+
+### 5.4 设计要点
+
+- 卡片宽度跨多种使用场景要适配(issue 列表很窄、设置页很宽)
+- 触发延迟(hover delay)跟 Skills 已有的卡片保持一致
+- 暗色主题下信息层级要清晰
+
+---
+
+## 六、跨平台差异处理
+
+### 6.1 状态视觉是平台无关的
+
+派生 5 态 / 4 态、视觉规范、hover card——**两端共享同一套设计**。设计稿只画一份。
+
+### 6.2 数据响应速度差异(不影响视觉)
+
+| 平台 | Runtime 状态变化感知延迟 |
+|---|---|
+| Web | 最坏 75 秒 |
+| Desktop(看自己机器) | < 1 秒(IPC) |
+| Desktop(看别人机器) | 最坏 75 秒(跟 Web 一样) |
+
+设计上不需要透出"快慢"——用户感知不到这是 IPC 还是 server。
+
+### 6.3 操作能力差异(影响按钮可见性)
+
+| 操作 | Web | Desktop(自己机器) | Desktop(别人机器) |
+|---|---|---|---|
+| 看状态 | ✅ | ✅ | ✅ |
+| 重启 daemon | ❌ | ✅ | ❌ |
+| 看 daemon logs | ❌ | ✅ | ❌ |
+| 看 CLI 安装详情 | ❌ | ✅ | ❌ |
+
+**设计要点**:操作按钮在不该有权限的位置应该**直接隐藏**,不要灰显(避免视觉噪音)。
+
+### 6.4 桌面端独有的"本机 daemon 卡片"
+
+当前桌面端有一个独立卡片显示本机 daemon。重设计后:
+- 视觉上跟云端 runtime 列表项**用同一套视觉语言**
+- 但承载更多本地操作(重启、看日志、安装 CLI、profile 切换)
+- 位置:列表顶部 sticky / 列表头部突出 / 右侧独立 panel —— 由你定
+
+---
+
+## 七、设计语言参考:Skills 界面
+
+### 7.1 Skills 是这次重设计的视觉锚点
+
+Skills 界面已经在 2026-04 完成重设计(PR #1607、#1614、#1618、#1610)。这次 Agents 和 Runtimes **直接照搬 Skills 的视觉语言**,保持产品体感一致。
+
+参考目录:`packages/views/skills/`
+
+### 7.2 必须复用的 10 条规则
+
+1. **统一页头** `PageHeader`(h-12 + mobile sidebar trigger)
+2. **响应式网格列表**:`grid-cols-[minmax(0,1.6fr)_minmax(0,0.8fr)_minmax(0,1.2fr)_minmax(0,6rem)_auto]`,不用 flexbox
+3. **每行三层信息**:主标题(font-medium)→ 描述(line-clamp-1 muted)→ 元数据(xs muted)
+4. **关联对象用头像堆栈**:最多 3 + `+N`,size=22 + `ring-2 ring-background` + `-space-x-1.5`
+5. **卡片化列表 + 卡片内工具栏**:搜索和 scope tab 在 `CardToolbar`(h-12),不在页面级
+6. **创建用多步 dialog**:chooser → 表单可回退;Dialog 宽度按方法切换(manual/url 用 `!max-w-md`,runtime 用 `!max-w-2xl`),300ms 平滑过渡
+7. **空状态 / 筛选无结果分别有详细文案**:图标 + 标题 + 三行说明 + 清晰 CTA
+8. **长列表加 `useScrollFade`**:滚动容器上下边缘淡出
+9. **头像统一用 `ActorAvatar`**:传 `size`,自动支持 agent / 人员
+10. **权限检查 hook 化**:`useCanEdit...`,UI 提前隐藏/禁用操作按钮
+
+---
+
+## 八、工程会同步交付的能力
+
+阶段 0(数据层地基)完成后,**设计稿可以放心假设以下能力都到位**:
+
+- 任意位置都能拿到一个 agent 的派生 5 态状态
+- 任意位置都能拿到 agent 的当前任务数(running / queued)
+- 任意位置都能拿到 agent 关联的 runtime 4 态健康
+- 任意位置都能拿到 runtime 服务的 agent 列表 + 数量
+- 任意位置都能拿到 runtime 当前任务数
+- 状态变化是实时的(订阅 WS 事件后会自动更新)
+- 桌面端会自动获得"亚秒级"响应——不需要为此画两套稿
+
+### 已有 API(不需要新加,可放心引用)
+
+- `listAgents` / `getAgent` / `createAgent` / `updateAgent` / `archiveAgent` / `restoreAgent`
+- `listAgentTasks(agentId)` — 单 agent 历史任务
+- `listRuntimes` / `deleteRuntime`
+- `getRuntimeUsage(runtimeId, { days })` — token 用量
+- `getRuntimeTaskActivity(runtimeId)` — 小时级活动
+
+### 工程要在阶段 0 补的(设计稿可以假设有,但要知道这是新增)
+
+- **后端**:`GET /api/workspaces/:slug/active-tasks` — 全工作区活跃任务一次拉
+- **后端**:诊断 / Ping API(如果你的设计稿用到,工程要评估优先级)
+- **前端类型**:`AgentTask.failure_reason` 字段(5 枚举:agent_error / timeout / runtime_offline / runtime_recovery / manual)暴露到前端类型
+- **前端**:派生函数(`deriveAgentPresence` / `deriveRuntimeHealth`)+ 全工作区 active-tasks query + WS 接线
+
+### 工程不会做的(设计稿不要假设有)
+
+- 不引入"agent 健康综合评分"——只暴露原始信号
+- 不做"从历史 task 自动推断 agent 类型"等 AI 派生
+- 不为 runtime 引入新状态色(稳定在 4 态)
+- 不做后端聚合 API(除了 active-tasks 这个补全)
+
+---
+
+## 九、设计师产出清单
+
+按优先级排列,**P0 必须先于 P1**。
+
+### P0 — 状态视觉规范(基础,所有界面共用)
+
+- 5 态颜色 token(Available / Working / Pending / Failed / Offline)
+- 4 态颜色 token(Online / Recently Lost / Offline / About to GC)
+- Dot / Badge / Tooltip 三层视觉规范
+- 复合维度(Working + 排队角标)的视觉表达
+- Failed 状态的 2 分钟时间窗口动效(强提示 + 自动消失)
+
+### P0 — Agents 界面
+
+- 列表页(含派生状态、关联 runtime 健康、最近活动时间)
+- 详情页头部 + Profile Card(状态行联动)
+- 创建对话框(保留两步流,加入 runtime 在线状态预览)
+
+### P0 — Runtimes 界面
+
+- 列表页(暴露 last_seen、关联 agents、当前 task 数)
+- 详情页头部(4 态 badge、device info 人类可读化)
+- Token usage 信息架构重整:核心指标置顶,详细图表下沉/折叠
+
+### P1 — Hover Card 跨界面统一
+
+- 一个适配多场景宽度的卡片设计
+- 7 项内容的信息层级
+- hover 触发交互(与 Skills 一致)
+
+### P1 — 桌面端本机 daemon 卡片
+
+- 视觉对齐云端 runtime 卡片
+- 本机操作按钮(重启 / 日志 / CLI 安装)的位置
+- Profile 切换(如果做多 profile)
+
+### P2 — 加分项
+
+- Runtime 健康综合评分(视觉化)
+- 7 天 GC 倒计时
+- 高使用量 runtime 的成本警告
+- Local vs Cloud 图标区分
+- Agent archived 独立 tab/折叠区
+- 列表按"最近活动"排序、按状态筛选
+
+---
+
+## 十、附录:截图占位区
+
+> 设计师拿到这份文档后,请把以下三个界面的当前截图贴在对应位置,作为重设计前的现状记录,方便对比。
+
+### 10.1 Agents 界面
+
+- 列表页截图:__待贴__
+- 详情页截图(每个 tab 一张:Instructions / Skills / Tasks / Environment / Custom Args / Settings):__待贴__
+- Profile Card 截图:__待贴__
+- 创建对话框截图(chooser + form 两步):__待贴__
+- Hover card 当前样式截图:__待贴__
+
+### 10.2 Runtimes 界面
+
+- 列表页截图(mine / all 两态):__待贴__
+- 详情页截图(含 5 个图表全部展开):__待贴__
+- 桌面端 daemon 卡片截图:__待贴__
+- CLI 更新流程截图:__待贴__
+
+### 10.3 跨界面 agent 头像出现的位置
+
+- Issue Assignee Picker:__待贴__
+- Issue Detail 头部 assignee:__待贴__
+- Issue 列表 / 看板:__待贴__
+- Autopilot 列表 / 编辑:__待贴__
+- Project lead picker:__待贴__
+- Chat agent 选择面板:__待贴__
+- 评论 @agent:__待贴__
+
+---
+
+## 参考文档
+
+- [Agent / Runtime 状态系统重设计(主文档)](./agent-runtime-status-redesign.md) — 完整工程方案、状态规范、实施阶段
+- [产品全景文档](./product-overview.md) — 理解 agent / runtime / daemon 在整个产品里的位置
+- [Skills 界面源代码](../packages/views/skills/) — 直接参考的设计语言样板
+- 相关 PR:#1607(Skills 重设计)、#1614(Card + PageHeader)、#1618(描述恢复)、#1610(Dialog 闪烁修复)
diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.ts
new file mode 100644
index 0000000000..e7708cc31e
--- /dev/null
+++ b/packages/core/agents/derive-presence.test.ts
@@ -0,0 +1,424 @@
+import { describe, expect, it } from "vitest";
+import type { Agent, AgentRuntime, AgentTask, TaskFailureReason } from "../types";
+import {
+ buildPresenceMap,
+ deriveAgentAvailability,
+ deriveAgentPresenceDetail,
+ deriveLastTaskState,
+} from "./derive-presence";
+
+function makeAgent(overrides: Partial<Agent> = {}): Agent {
+ return {
+ id: "agent-1",
+ workspace_id: "ws-1",
+ runtime_id: "rt-1",
+ name: "Test Agent",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_env: {},
+ custom_args: [],
+ custom_env_redacted: false,
+ visibility: "workspace",
+ status: "idle",
+ max_concurrent_tasks: 6,
+ model: "",
+ owner_id: null,
+ skills: [],
+ created_at: "2026-04-01T00:00:00Z",
+ updated_at: "2026-04-01T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+ ...overrides,
+ };
+}
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "rt-1",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-1",
+ name: "Test Runtime",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: null,
+ last_seen_at: "2026-04-27T11:59:50Z",
+ created_at: "2026-04-01T00:00:00Z",
+ updated_at: "2026-04-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+// Anchor for all wall-clock comparisons in the suite. Pairs with the
+// runtime fixture's last_seen_at (10s before NOW) so an "online" runtime
+// looks fresh by default.
+const NOW = new Date("2026-04-27T12:00:00Z").getTime();
+
+function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {
+ return {
+ id: "task-1",
+ agent_id: "agent-1",
+ runtime_id: "rt-1",
+ issue_id: "",
+ status: "queued",
+ priority: 0,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ result: null,
+ error: null,
+ created_at: "2026-04-27T11:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("deriveAgentAvailability", () => {
+ // Reachability dimension only — runtime + clock decide it; tasks are
+ // irrelevant. The whole point of splitting from LastTaskState is that
+ // these tests can ignore task fixtures entirely.
+
+ it("returns online when runtime is fresh-online", () => {
+ expect(deriveAgentAvailability(makeRuntime(), NOW)).toBe("online");
+ });
+
+ it("returns unstable when runtime just dropped (< 5 min)", () => {
+ expect(
+ deriveAgentAvailability(
+ makeRuntime({ status: "offline", last_seen_at: "2026-04-27T11:59:30Z" }),
+ NOW,
+ ),
+ ).toBe("unstable");
+ });
+
+ it("returns offline when runtime has been gone > 5 min", () => {
+ expect(
+ deriveAgentAvailability(
+ makeRuntime({ status: "offline", last_seen_at: "2026-04-27T11:50:00Z" }),
+ NOW,
+ ),
+ ).toBe("offline");
+ });
+
+ it("collapses about_to_gc into offline (it's a runtime-card concern, not the dot)", () => {
+ expect(
+ deriveAgentAvailability(
+ // 6.5 days ago — past the 6-day about_to_gc threshold.
+ makeRuntime({ status: "offline", last_seen_at: "2026-04-21T00:00:00Z" }),
+ NOW,
+ ),
+ ).toBe("offline");
+ });
+
+ it("returns offline when the runtime is null (deleted / never registered)", () => {
+ expect(deriveAgentAvailability(null, NOW)).toBe("offline");
+ });
+});
+
+describe("deriveLastTaskState", () => {
+ // Task dimension only — runtime status is not consulted.
+
+ it("returns idle when no tasks at all", () => {
+ const r = deriveLastTaskState([]);
+ expect(r.state).toBe("idle");
+ expect(r.runningCount).toBe(0);
+ expect(r.queuedCount).toBe(0);
+ });
+
+ it("returns running when at least one task is running", () => {
+ const r = deriveLastTaskState([makeTask({ status: "running" })]);
+ expect(r.state).toBe("running");
+ expect(r.runningCount).toBe(1);
+ });
+
+ it("returns running when only queued / dispatched tasks exist (no running yet)", () => {
+ const r = deriveLastTaskState([
+ makeTask({ status: "queued" }),
+ makeTask({ id: "t2", status: "dispatched" }),
+ ]);
+ expect(r.state).toBe("running");
+ expect(r.runningCount).toBe(0);
+ expect(r.queuedCount).toBe(2);
+ });
+
+ it("returns running even when an older terminal exists (active wins over historical)", () => {
+ const r = deriveLastTaskState([
+ makeTask({
+ id: "old-failed",
+ status: "failed",
+ completed_at: "2026-04-27T10:00:00Z",
+ }),
+ makeTask({ id: "new-running", status: "running" }),
+ ]);
+ expect(r.state).toBe("running");
+ });
+
+ it("returns the latest terminal state when no tasks are active (latest = failed)", () => {
+ const r = deriveLastTaskState([
+ makeTask({
+ id: "old",
+ status: "completed",
+ completed_at: "2026-04-27T10:00:00Z",
+ }),
+ makeTask({
+ id: "new",
+ status: "failed",
+ completed_at: "2026-04-27T11:30:00Z",
+ }),
+ ]);
+ expect(r.state).toBe("failed");
+ expect(r.lastTaskCompletedAt).toBe("2026-04-27T11:30:00Z");
+ });
+
+ it("returns the latest terminal state when no tasks are active (latest = completed)", () => {
+ const r = deriveLastTaskState([
+ makeTask({
+ id: "old",
+ status: "failed",
+ completed_at: "2026-04-27T10:00:00Z",
+ }),
+ makeTask({
+ id: "new",
+ status: "completed",
+ completed_at: "2026-04-27T11:30:00Z",
+ }),
+ ]);
+ expect(r.state).toBe("completed");
+ });
+
+ it("surfaces failure_reason on a failed latest terminal", () => {
+ const reason: TaskFailureReason = "runtime_offline";
+ const r = deriveLastTaskState([
+ makeTask({
+ status: "failed",
+ completed_at: "2026-04-27T11:30:00Z",
+ failure_reason: reason,
+ }),
+ ]);
+ expect(r.state).toBe("failed");
+ expect(r.failureReason).toBe(reason);
+ });
+
+ it("leaves failureReason undefined when the failed terminal has empty failure_reason", () => {
+ const r = deriveLastTaskState([
+ makeTask({
+ status: "failed",
+ completed_at: "2026-04-27T11:30:00Z",
+ failure_reason: "",
+ }),
+ ]);
+ expect(r.state).toBe("failed");
+ expect(r.failureReason).toBeUndefined();
+ });
+
+ it("returns cancelled when the latest terminal is cancelled", () => {
+ // Under the new model cancelled is a real state — the dot is
+ // availability-driven so honestly surfacing it doesn't lie.
+ const r = deriveLastTaskState([
+ makeTask({
+ status: "cancelled",
+ completed_at: "2026-04-27T11:30:00Z",
+ }),
+ ]);
+ expect(r.state).toBe("cancelled");
+ });
+
+ it("ignores terminals without completed_at (treated as not-terminal)", () => {
+ // Defensive: a malformed row (no completed_at) shouldn't derail the
+ // latest-terminal scan. With nothing else in flight, idle.
+ const r = deriveLastTaskState([makeTask({ status: "failed", completed_at: null })]);
+ expect(r.state).toBe("idle");
+ });
+});
+
+describe("deriveAgentPresenceDetail", () => {
+ // Composition: the two dimensions are derived independently and the
+ // detail object exposes both. No cross-axis override (the old "unstable
+ // overrides failed" rule is gone — they coexist now).
+
+ it("composes online + running for the common busy case", () => {
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent(),
+ runtime: makeRuntime(),
+ tasks: [
+ makeTask({ status: "running" }),
+ makeTask({ id: "t2", status: "queued" }),
+ ],
+ now: NOW,
+ });
+ expect(detail.availability).toBe("online");
+ expect(detail.lastTask).toBe("running");
+ expect(detail.runningCount).toBe(1);
+ expect(detail.queuedCount).toBe(1);
+ expect(detail.capacity).toBe(6);
+ });
+
+ it("composes online + failed — agent is reachable but last task failed (no longer sticky red dot)", () => {
+ // The whole motivation for the split: this combination was previously
+ // collapsed to a single red "failed" state, hiding the fact that the
+ // runtime is fine. Now the two dimensions are visible separately.
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent(),
+ runtime: makeRuntime(),
+ tasks: [
+ makeTask({
+ status: "failed",
+ completed_at: "2026-04-27T11:30:00Z",
+ failure_reason: "agent_error",
+ }),
+ ],
+ now: NOW,
+ });
+ expect(detail.availability).toBe("online");
+ expect(detail.lastTask).toBe("failed");
+ expect(detail.failureReason).toBe("agent_error");
+ expect(detail.lastTaskCompletedAt).toBe("2026-04-27T11:30:00Z");
+ });
+
+ it("composes unstable + running — runtime hiccup with queued tasks still in flight", () => {
+ // Previously "unstable" overrode "working"; now both signals are
+ // surfaced. The UI shows amber dot AND running chip — user sees both
+ // "connection issue" and "queue is paused".
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent(),
+ runtime: makeRuntime({
+ status: "offline",
+ last_seen_at: "2026-04-27T11:59:00Z",
+ }),
+ tasks: [makeTask({ status: "queued" })],
+ now: NOW,
+ });
+ expect(detail.availability).toBe("unstable");
+ expect(detail.lastTask).toBe("running");
+ expect(detail.queuedCount).toBe(1);
+ });
+
+ it("composes offline + idle for a brand-new agent on a dead runtime", () => {
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent(),
+ runtime: makeRuntime({
+ status: "offline",
+ last_seen_at: "2026-04-27T11:50:00Z",
+ }),
+ tasks: [],
+ now: NOW,
+ });
+ expect(detail.availability).toBe("offline");
+ expect(detail.lastTask).toBe("idle");
+ });
+
+ it("handles a missing runtime by reporting offline + the task-driven last state", () => {
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent(),
+ runtime: null,
+ tasks: [
+ makeTask({
+ status: "completed",
+ completed_at: "2026-04-27T11:30:00Z",
+ }),
+ ],
+ now: NOW,
+ });
+ expect(detail.availability).toBe("offline");
+ expect(detail.lastTask).toBe("completed");
+ });
+
+ it("leaves failureReason / lastTaskCompletedAt undefined when not relevant", () => {
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent(),
+ runtime: makeRuntime(),
+ tasks: [makeTask({ status: "running" })],
+ now: NOW,
+ });
+ expect(detail.failureReason).toBeUndefined();
+ expect(detail.lastTaskCompletedAt).toBeUndefined();
+ });
+
+ it("mirrors agent.max_concurrent_tasks into capacity", () => {
+ const detail = deriveAgentPresenceDetail({
+ agent: makeAgent({ max_concurrent_tasks: 3 }),
+ runtime: makeRuntime(),
+ tasks: [],
+ now: NOW,
+ });
+ expect(detail.capacity).toBe(3);
+ });
+});
+
+describe("buildPresenceMap", () => {
+ it("returns one entry per agent, sourcing tasks by agent_id from a flat list", () => {
+ const agentA = makeAgent({ id: "a", runtime_id: "rt-1" });
+ const agentB = makeAgent({ id: "b", runtime_id: "rt-1" });
+ const map = buildPresenceMap({
+ agents: [agentA, agentB],
+ runtimes: [makeRuntime()],
+ snapshot: [
+ makeTask({ id: "t1", agent_id: "a", status: "running" }),
+ makeTask({
+ id: "t2",
+ agent_id: "b",
+ status: "failed",
+ completed_at: "2026-04-27T11:30:00Z",
+ }),
+ ],
+ now: NOW,
+ });
+ const a = map.get("a");
+ const b = map.get("b");
+ expect(a?.availability).toBe("online");
+ expect(a?.lastTask).toBe("running");
+ expect(b?.availability).toBe("online");
+ expect(b?.lastTask).toBe("failed");
+ });
+
+ it("returns offline availability for agents whose runtime_id has no matching runtime", () => {
+ const orphan = makeAgent({ id: "orphan", runtime_id: "missing" });
+ const map = buildPresenceMap({
+ agents: [orphan],
+ runtimes: [],
+ snapshot: [makeTask({ agent_id: "orphan", status: "running" })],
+ now: NOW,
+ });
+ const o = map.get("orphan");
+ expect(o?.availability).toBe("offline");
+ // Task dimension still resolves independently — running task counts.
+ expect(o?.lastTask).toBe("running");
+ });
+
+ it("threads the same `now` so every agent on a shared runtime gets the same availability", () => {
+ // Multi-agent scenario: one local daemon backs N agents, daemon dies.
+ // All dependent agents should report unstable together — the shared
+ // `now` parameter is what guarantees consistent bucket boundaries.
+ const agentA = makeAgent({ id: "a", runtime_id: "rt-1" });
+ const agentB = makeAgent({ id: "b", runtime_id: "rt-1" });
+ const map = buildPresenceMap({
+ agents: [agentA, agentB],
+ runtimes: [
+ makeRuntime({
+ status: "offline",
+ last_seen_at: "2026-04-27T11:59:00Z",
+ }),
+ ],
+ snapshot: [
+ makeTask({ id: "t1", agent_id: "a", status: "queued" }),
+ makeTask({
+ id: "t2",
+ agent_id: "b",
+ status: "failed",
+ completed_at: "2026-04-27T11:00:00Z",
+ }),
+ ],
+ now: NOW,
+ });
+ expect(map.get("a")?.availability).toBe("unstable");
+ expect(map.get("b")?.availability).toBe("unstable");
+ // Last-task remains independent: a is running (queued), b is failed.
+ expect(map.get("a")?.lastTask).toBe("running");
+ expect(map.get("b")?.lastTask).toBe("failed");
+ });
+});
diff --git a/packages/core/agents/derive-presence.ts b/packages/core/agents/derive-presence.ts
new file mode 100644
index 0000000000..e6d375df8e
--- /dev/null
+++ b/packages/core/agents/derive-presence.ts
@@ -0,0 +1,166 @@
+// Pure derivation of an agent's user-facing presence from raw server data.
+// The back-end stores facts (which tasks exist, their statuses, the runtime
+// last_seen_at); the front-end translates them into two orthogonal
+// dimensions:
+//
+// 1. AgentAvailability — derived from runtime reachability only.
+// 2. LastTaskState — derived from the task snapshot only.
+//
+// They are computed independently and assembled into AgentPresenceDetail.
+// No cross-dimension override logic — that was the source of the previous
+// model's "sticky red dot" confusion.
+
+import { deriveRuntimeHealth } from "../runtimes/derive-health";
+import type { Agent, AgentRuntime, AgentTask, TaskFailureReason } from "../types";
+import type {
+ AgentAvailability,
+ AgentPresenceDetail,
+ LastTaskState,
+} from "./types";
+
+// AgentAvailability mirrors RuntimeHealth's reachability buckets but folds
+// `about_to_gc` into `offline` — both mean "long unreachable" from the
+// user's standpoint; the GC-warning copy belongs to the runtime card, not
+// the agent dot.
+export function deriveAgentAvailability(
+ runtime: AgentRuntime | null,
+ now: number,
+): AgentAvailability {
+ if (!runtime) return "offline";
+ const health = deriveRuntimeHealth(runtime, now);
+ if (health === "online") return "online";
+ if (health === "recently_lost") return "unstable";
+ return "offline"; // offline | about_to_gc collapse here
+}
+
+interface LastTaskResult {
+ state: LastTaskState;
+ runningCount: number;
+ queuedCount: number;
+ failureReason?: TaskFailureReason;
+ lastTaskCompletedAt?: string;
+}
+
+// Single pass: count actives + track latest terminal by completed_at. A
+// running OR queued task means the agent is currently busy ("running"
+// state); only when nothing is in flight do we fall through to the latest
+// terminal (which can be completed / failed / cancelled). With no terminal
+// history at all, we report `idle`.
+//
+// Cancelled is no longer filtered out — under the new model the dot is
+// availability-driven so honestly surfacing "cancelled" doesn't risk
+// lying about whether the agent works. The previous "exclude cancelled
+// to keep red sticky" hack is gone.
+export function deriveLastTaskState(tasks: readonly AgentTask[]): LastTaskResult {
+ let runningCount = 0;
+ let queuedCount = 0;
+ let latestTerminal: AgentTask | null = null;
+ let latestTerminalAt = -Infinity;
+
+ for (const t of tasks) {
+ if (t.status === "running") {
+ runningCount += 1;
+ } else if (t.status === "queued" || t.status === "dispatched") {
+ queuedCount += 1;
+ } else if (t.completed_at) {
+ const ts = new Date(t.completed_at).getTime();
+ if (!Number.isNaN(ts) && ts > latestTerminalAt) {
+ latestTerminalAt = ts;
+ latestTerminal = t;
+ }
+ }
+ }
+
+ if (runningCount + queuedCount > 0) {
+ return { state: "running", runningCount, queuedCount };
+ }
+
+ if (!latestTerminal) {
+ return { state: "idle", runningCount: 0, queuedCount: 0 };
+ }
+
+ const completedAt = latestTerminal.completed_at ?? undefined;
+ if (latestTerminal.status === "failed") {
+ return {
+ state: "failed",
+ runningCount: 0,
+ queuedCount: 0,
+ failureReason: latestTerminal.failure_reason || undefined,
+ lastTaskCompletedAt: completedAt,
+ };
+ }
+ if (latestTerminal.status === "cancelled") {
+ return {
+ state: "cancelled",
+ runningCount: 0,
+ queuedCount: 0,
+ lastTaskCompletedAt: completedAt,
+ };
+ }
+ // completed
+ return {
+ state: "completed",
+ runningCount: 0,
+ queuedCount: 0,
+ lastTaskCompletedAt: completedAt,
+ };
+}
+
+interface DerivePresenceInput {
+ agent: Agent;
+ runtime: AgentRuntime | null;
+ // Tasks for THIS agent only. Callers (buildPresenceMap, hooks) pre-filter
+ // by agent_id — we don't re-check here.
+ tasks: readonly AgentTask[];
+ // Wall-clock millis used by deriveAgentAvailability to bucket runtime
+ // health. Threading it as a parameter keeps the function pure.
+ now: number;
+}
+
+export function deriveAgentPresenceDetail(input: DerivePresenceInput): AgentPresenceDetail {
+ const availability = deriveAgentAvailability(input.runtime, input.now);
+ const last = deriveLastTaskState(input.tasks);
+
+ return {
+ availability,
+ lastTask: last.state,
+ runningCount: last.runningCount,
+ queuedCount: last.queuedCount,
+ capacity: input.agent.max_concurrent_tasks,
+ failureReason: last.failureReason,
+ lastTaskCompletedAt: last.lastTaskCompletedAt,
+ };
+}
+
+// Workspace-level batch builder. One pass over the workspace's agents
+// produces a Map<agentId, AgentPresenceDetail> that every list / card /
+// runtime sub-page can read without re-deriving.
+export function buildPresenceMap(args: {
+ agents: readonly Agent[];
+ runtimes: readonly AgentRuntime[];
+ // The workspace agent task snapshot: every active task + each agent's
+ // most recent terminal task. Comes straight from getAgentTaskSnapshot()
+ // — no pre-filtering needed.
+ snapshot: readonly AgentTask[];
+ now: number;
+}): Map<string, AgentPresenceDetail> {
+ const out = new Map<string, AgentPresenceDetail>();
+ const runtimesById = new Map<string, AgentRuntime>();
+ for (const r of args.runtimes) runtimesById.set(r.id, r);
+
+ // Group tasks by agent_id once — O(N) — so per-agent derivation is O(1)
+ // task scans rather than O(N×M).
+ const tasksByAgent = new Map<string, AgentTask[]>();
+ for (const t of args.snapshot) {
+ const list = tasksByAgent.get(t.agent_id);
+ if (list) list.push(t);
+ else tasksByAgent.set(t.agent_id, [t]);
+ }
+
+ for (const agent of args.agents) {
+ const runtime = runtimesById.get(agent.runtime_id) ?? null;
+ const tasks = tasksByAgent.get(agent.id) ?? [];
+ out.set(agent.id, deriveAgentPresenceDetail({ agent, runtime, tasks, now: args.now }));
+ }
+ return out;
+}
diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.ts
new file mode 100644
index 0000000000..5770bce513
--- /dev/null
+++ b/packages/core/agents/index.ts
@@ -0,0 +1,6 @@
+export * from "./types";
+export * from "./derive-presence";
+export * from "./queries";
+export * from "./use-agent-presence";
+export * from "./use-agent-activity";
+export * from "./use-workspace-presence-prefetch";
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.ts
new file mode 100644
index 0000000000..5152a4a3c6
--- /dev/null
+++ b/packages/core/agents/queries.ts
@@ -0,0 +1,84 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+export const agentTaskSnapshotKeys = {
+ all: (wsId: string) => ["workspaces", wsId, "agent-task-snapshot"] as const,
+ list: (wsId: string) => [...agentTaskSnapshotKeys.all(wsId), "list"] as const,
+};
+
+export const agentActivityKeys = {
+ all: (wsId: string) => ["workspaces", wsId, "agent-activity"] as const,
+ last30d: (wsId: string) => [...agentActivityKeys.all(wsId), "30d"] as const,
+};
+
+export const agentRunCountsKeys = {
+ all: (wsId: string) => ["workspaces", wsId, "agent-run-counts"] as const,
+ last30d: (wsId: string) => [...agentRunCountsKeys.all(wsId), "30d"] as const,
+};
+
+// Workspace-scoped agent task snapshot — every active task plus each agent's
+// most recent terminal task. This is the single shared source of truth that
+// powers per-agent presence derivation across the app. One fetch per
+// workspace; all agent dots / hover cards / list rows derive presence from
+// this cache with zero additional network traffic.
+//
+// The 30s staleTime is a safety net only; the primary freshness signal is
+// WS task events, which invalidate this query immediately. Without WS,
+// presence still updates within 30s on focus / mount.
+export function agentTaskSnapshotOptions(wsId: string) {
+ return queryOptions({
+ queryKey: agentTaskSnapshotKeys.list(wsId),
+ queryFn: () => api.getAgentTaskSnapshot(),
+ staleTime: 30 * 1000,
+ gcTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: true,
+ });
+}
+
+// Workspace-wide daily task activity for the last 30 days, anchored on
+// completed_at. One fetch backs both the Agents-list sparkline (which
+// only uses the trailing 7 buckets via `summarizeActivityWindow`) and
+// the agent detail "Last 30 days" panel. WS task lifecycle events
+// invalidate this query in useRealtimeSync; the staleTime is a
+// tab-focus safety net.
+export function agentActivity30dOptions(wsId: string) {
+ return queryOptions({
+ queryKey: agentActivityKeys.last30d(wsId),
+ queryFn: () => api.getWorkspaceAgentActivity30d(),
+ staleTime: 60 * 1000,
+ gcTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: true,
+ });
+}
+
+// Workspace-wide 30-day run counts for the Agents-list RUNS column. Same
+// single-fetch / WS-invalidate pattern as activity24hOptions.
+export function agentRunCounts30dOptions(wsId: string) {
+ return queryOptions({
+ queryKey: agentRunCountsKeys.last30d(wsId),
+ queryFn: () => api.getWorkspaceAgentRunCounts(),
+ staleTime: 60 * 1000,
+ gcTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: true,
+ });
+}
+
+export const agentTasksKeys = {
+ all: (wsId: string) => ["workspaces", wsId, "agent-tasks"] as const,
+ detail: (wsId: string, agentId: string) =>
+ [...agentTasksKeys.all(wsId), agentId] as const,
+};
+
+// All tasks for a single agent (the agent detail page consumer). Powers both
+// the inspector's 7-day throughput stats and the Tasks tab list — shared so
+// they don't fetch twice. WS task events invalidate this via the existing
+// task-prefix invalidation in useRealtimeSync.
+export function agentTasksOptions(wsId: string, agentId: string) {
+ return queryOptions({
+ queryKey: agentTasksKeys.detail(wsId, agentId),
+ queryFn: () => api.listAgentTasks(agentId),
+ staleTime: 30 * 1000,
+ gcTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: true,
+ });
+}
diff --git a/packages/core/agents/types.ts b/packages/core/agents/types.ts
new file mode 100644
index 0000000000..34df759c36
--- /dev/null
+++ b/packages/core/agents/types.ts
@@ -0,0 +1,69 @@
+// Derived presence types for agents — the user-facing state we display
+// across the UI (list dots, hover cards, status lines). Computed in the
+// front-end from raw server data (agent + runtime + recent tasks); the
+// back-end never knows about these enums.
+//
+// Two orthogonal dimensions, derived independently:
+//
+// 1. AgentAvailability — "Can this agent take work right now?"
+// Depends only on runtime reachability. The dot colour everywhere in
+// the app reflects this single dimension; never sticky-red because of
+// a past task outcome.
+//
+// 2. LastTaskState — "What was the last thing this agent did?"
+// Depends only on the workspace task snapshot. Surfaced as text + icon
+// on focused surfaces (hover card, agent detail, agent list, runtime
+// detail). Never colours the dot.
+//
+// The previous single 5-state union conflated the two: a runtime-healthy
+// agent whose last task failed would show a red dot indistinguishable from
+// a daemon-dead agent. Splitting them lets each signal be unambiguous.
+
+import type { TaskFailureReason } from "../types";
+
+// Runtime-reachability dimension. `unstable` is the transient amber state
+// during the runtime sweeper's grace window (offline < 5 min); it decays
+// into `offline` with no new server data, hence the 30s presence tick on
+// the consuming hooks.
+export type AgentAvailability =
+ | "online" // 🟢 runtime online and reachable
+ | "unstable" // 🟡 runtime recently_lost (< 5 min) — transient
+ | "offline"; // ⚫ runtime long offline / missing / never registered
+
+// Last-task dimension. Active and terminal merged into one enum because
+// only one applies at a time: while there's any in-flight task the state
+// is `running`; once everything terminates we read the latest outcome;
+// with no history at all, `idle`.
+//
+// `running` covers both `running` and `queued/dispatched` tasks because
+// from the user's perspective "agent is busy" is the same answer; the
+// running/queued counts on the detail object preserve the breakdown.
+//
+// `cancelled` is included as a discrete state (vs. folding into the
+// previous filter that excluded cancelled from terminal selection). With
+// the dot no longer colour-coded by task state, surfacing "cancelled"
+// honestly is fine — it doesn't risk lying about availability.
+export type LastTaskState =
+ | "running" // ≥1 task running or queued right now
+ | "completed" // latest terminal: completed
+ | "failed" // latest terminal: failed
+ | "cancelled" // latest terminal: cancelled
+ | "idle"; // no active task and no terminal history
+
+export interface AgentPresenceDetail {
+ availability: AgentAvailability;
+ lastTask: LastTaskState;
+ runningCount: number;
+ queuedCount: number;
+ // Mirrors agent.max_concurrent_tasks — pulled into the detail so the UI
+ // can render `running / capacity` ratios without re-fetching the agent.
+ capacity: number;
+ // Set only when lastTask === "failed". The label lookup happens at the
+ // UI layer; deriving exposes the raw classifier so the UI can choose copy.
+ failureReason?: TaskFailureReason;
+ // Wall-clock timestamp of the latest terminal task. Set whenever
+ // lastTask is one of completed / failed / cancelled. Used to render
+ // "Last run: failed · 12 min ago" copy. Undefined for `running` (no
+ // terminal yet) and `idle` (no history).
+ lastTaskCompletedAt?: string;
+}
diff --git a/packages/core/agents/use-agent-activity.test.ts b/packages/core/agents/use-agent-activity.test.ts
new file mode 100644
index 0000000000..b50174bc53
--- /dev/null
+++ b/packages/core/agents/use-agent-activity.test.ts
@@ -0,0 +1,192 @@
+import { describe, expect, it } from "vitest";
+import type { Agent, AgentActivityBucket } from "../types";
+import {
+ buildActivityMap,
+ deriveAgentActivity,
+ summarizeActivityWindow,
+} from "./use-agent-activity";
+
+const DAY = 24 * 60 * 60 * 1000;
+
+// Fixed anchor — derivation uses local-time start of "today", a real
+// clock would drift. 12:00 also keeps "today" stable across odd timezones.
+const NOW = new Date("2026-04-28T12:00:00").getTime();
+
+function bucket(
+ agentId: string,
+ daysAgo: number,
+ taskCount: number,
+ failedCount = 0,
+): AgentActivityBucket {
+ const t = new Date(NOW);
+ t.setHours(0, 0, 0, 0);
+ return {
+ agent_id: agentId,
+ bucket_at: new Date(t.getTime() - daysAgo * DAY).toISOString(),
+ task_count: taskCount,
+ failed_count: failedCount,
+ };
+}
+
+const fullHistoryAgent: Agent = {
+ id: "a1",
+ workspace_id: "w",
+ runtime_id: "r1",
+ name: "Old Agent",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "cloud",
+ runtime_config: {},
+ custom_env: {},
+ custom_args: [],
+ custom_env_redacted: false,
+ visibility: "workspace",
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "",
+ owner_id: null,
+ skills: [],
+ // Older than the window so daysSinceCreated saturates at DAYS.
+ created_at: new Date(NOW - 100 * DAY).toISOString(),
+ updated_at: new Date(NOW).toISOString(),
+ archived_at: null,
+ archived_by: null,
+};
+
+describe("deriveAgentActivity", () => {
+ it("places buckets in oldest→newest slots across 30 days", () => {
+ const buckets = [
+ bucket("a1", 29, 1), // slot 0
+ bucket("a1", 0, 5), // slot 29
+ ];
+ const result = deriveAgentActivity(
+ buckets,
+ fullHistoryAgent.created_at,
+ NOW,
+ );
+ expect(result.buckets).toHaveLength(30);
+ expect(result.buckets[0]).toEqual({ total: 1, failed: 0 });
+ expect(result.buckets[29]).toEqual({ total: 5, failed: 0 });
+ expect(result.daysSinceCreated).toBe(30);
+ });
+
+ it("clamps daysSinceCreated for young agents", () => {
+ const created = new Date(NOW - 3 * DAY - 60 * 1000).toISOString();
+ const result = deriveAgentActivity([bucket("fresh", 1, 4)], created, NOW);
+ expect(result.daysSinceCreated).toBe(3);
+ });
+
+ it("treats sub-day-old agents as daysSinceCreated = 0", () => {
+ const created = new Date(NOW - 2 * 60 * 60 * 1000).toISOString();
+ const result = deriveAgentActivity([bucket("fresh", 0, 1)], created, NOW);
+ expect(result.daysSinceCreated).toBe(0);
+ // Today's bucket still records — pre-life days simply look like zero
+ // days, which is on purpose.
+ expect(result.buckets[29]).toEqual({ total: 1, failed: 0 });
+ });
+
+ it("ignores buckets older than the 30-day window", () => {
+ const result = deriveAgentActivity(
+ [bucket("a1", 60, 99)],
+ fullHistoryAgent.created_at,
+ NOW,
+ );
+ expect(
+ result.buckets.reduce((s, b) => s + b.total, 0),
+ ).toBe(0);
+ });
+
+ it("zero-fills when the agent has no buckets", () => {
+ const result = deriveAgentActivity(
+ [],
+ fullHistoryAgent.created_at,
+ NOW,
+ );
+ expect(result.buckets).toHaveLength(30);
+ expect(result.buckets.every((b) => b.total === 0 && b.failed === 0)).toBe(
+ true,
+ );
+ });
+});
+
+describe("summarizeActivityWindow", () => {
+ it("rolls up totals across the trailing N buckets", () => {
+ // 5 runs total over the 30-day series.
+ const result = deriveAgentActivity(
+ [
+ bucket("a1", 25, 1), // outside 7d, inside 30d
+ bucket("a1", 6, 1), // inside 7d
+ bucket("a1", 0, 3, 1), // inside 7d
+ ],
+ fullHistoryAgent.created_at,
+ NOW,
+ );
+ const last7 = summarizeActivityWindow(result, 7);
+ expect(last7.totalRuns).toBe(4);
+ expect(last7.totalFailed).toBe(1);
+ expect(last7.buckets).toHaveLength(7);
+
+ const last30 = summarizeActivityWindow(result, 30);
+ expect(last30.totalRuns).toBe(5);
+ expect(last30.totalFailed).toBe(1);
+ expect(last30.buckets).toHaveLength(30);
+ });
+
+ it("returns an empty summary for missing activity", () => {
+ const summary = summarizeActivityWindow(undefined, 7);
+ expect(summary.buckets).toEqual([]);
+ expect(summary.totalRuns).toBe(0);
+ expect(summary.totalFailed).toBe(0);
+ expect(summary.windowDays).toBe(7);
+ });
+
+ it("clamps an oversized window to the available bucket count", () => {
+ const result = deriveAgentActivity(
+ [bucket("a1", 0, 2)],
+ fullHistoryAgent.created_at,
+ NOW,
+ );
+ const summary = summarizeActivityWindow(result, 1000);
+ expect(summary.buckets).toHaveLength(30);
+ expect(summary.totalRuns).toBe(2);
+ });
+
+ it("returns no buckets when window is 0", () => {
+ const result = deriveAgentActivity(
+ [bucket("a1", 0, 5)],
+ fullHistoryAgent.created_at,
+ NOW,
+ );
+ const summary = summarizeActivityWindow(result, 0);
+ expect(summary.buckets).toEqual([]);
+ expect(summary.totalRuns).toBe(0);
+ });
+});
+
+describe("buildActivityMap", () => {
+ it("groups buckets by agent and yields a derivation per agent", () => {
+ const agents: Agent[] = [
+ fullHistoryAgent,
+ { ...fullHistoryAgent, id: "a2" },
+ ];
+ const buckets: AgentActivityBucket[] = [
+ bucket("a1", 0, 3),
+ bucket("a2", 1, 2, 1),
+ bucket("a1", 2, 4),
+ ];
+ const map = buildActivityMap(agents, buckets, NOW);
+ expect(map.size).toBe(2);
+ expect(summarizeActivityWindow(map.get("a1"), 30).totalRuns).toBe(7);
+ expect(summarizeActivityWindow(map.get("a2"), 30).totalRuns).toBe(2);
+ expect(summarizeActivityWindow(map.get("a2"), 30).totalFailed).toBe(1);
+ });
+
+ it("emits a zero-filled entry for an agent with no buckets", () => {
+ const agents: Agent[] = [fullHistoryAgent];
+ const map = buildActivityMap(agents, [], NOW);
+ const a = map.get("a1");
+ expect(a?.buckets).toHaveLength(30);
+ expect(summarizeActivityWindow(a, 30).totalRuns).toBe(0);
+ });
+});
diff --git a/packages/core/agents/use-agent-activity.ts b/packages/core/agents/use-agent-activity.ts
new file mode 100644
index 0000000000..e6965fc028
--- /dev/null
+++ b/packages/core/agents/use-agent-activity.ts
@@ -0,0 +1,204 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent, AgentActivityBucket } from "../types";
+import { agentListOptions } from "../workspace/queries";
+import { agentActivity30dOptions } from "./queries";
+
+const DAYS = 30;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** One day's tally for the sparkline. */
+export interface ActivityBucket {
+ total: number;
+ failed: number;
+}
+
+export interface AgentActivity {
+ /**
+ * 30 daily buckets, oldest → newest. Days with no activity are
+ * zero-filled. Each surface picks how much of the tail to render: the
+ * Agents list uses 7, the agent detail uses all 30. Reading is the
+ * caller's job (see `summarizeActivityWindow` for the standard
+ * tail-slice + roll-up).
+ */
+ buckets: ActivityBucket[];
+ /**
+ * Days the agent has existed, capped at DAYS. Pure cosmetic — used by
+ * tooltip copy ("Created 3 days ago"). The sparkline doesn't change
+ * shape for young agents on purpose; pre-life days look the same as
+ * zero days.
+ */
+ daysSinceCreated: number;
+}
+
+/**
+ * Window-sized roll-up of an agent's activity series. Both the Agents
+ * list (windowDays=7) and the detail "Last 30 days" panel (windowDays=30)
+ * read through this so the totals can never drift from the bars they
+ * label.
+ */
+export interface ActivityWindowSummary {
+ /** Trailing-N buckets from the activity series (newest end). */
+ buckets: ActivityBucket[];
+ /** Sum of `bucket.total` across the window. */
+ totalRuns: number;
+ /** Sum of `bucket.failed` across the window. */
+ totalFailed: number;
+ /** Echo of the input window — the renderer uses it for copy. */
+ windowDays: number;
+}
+
+const EMPTY: AgentActivity = {
+ buckets: Array.from({ length: DAYS }, () => ({ total: 0, failed: 0 })),
+ daysSinceCreated: DAYS,
+};
+
+const EMPTY_SUMMARY: ActivityWindowSummary = {
+ buckets: [],
+ totalRuns: 0,
+ totalFailed: 0,
+ windowDays: 0,
+};
+
+/**
+ * Workspace-wide activity map keyed by `agent.id`. Single-pass batch:
+ * one fetch + one derivation pass backs every row's sparkline on the
+ * list AND the detail panel — adding rows costs O(1) HTTP and O(N)
+ * compute (not O(N) HTTP).
+ */
+export function useWorkspaceActivityMap(wsId: string | undefined): {
+ byAgent: Map<string, AgentActivity>;
+ loading: boolean;
+} {
+ const { data: agents, isPending: agentsPending } = useQuery({
+ ...agentListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { data: buckets, isPending: bucketsPending } = useQuery({
+ ...agentActivity30dOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+
+ const byAgent = useMemo(() => {
+ if (!agents || !buckets) return new Map<string, AgentActivity>();
+ return buildActivityMap(agents, buckets, Date.now());
+ }, [agents, buckets]);
+
+ return { byAgent, loading: agentsPending || bucketsPending };
+}
+
+export function buildActivityMap(
+ agents: readonly Agent[],
+ buckets: readonly AgentActivityBucket[],
+ now: number,
+): Map<string, AgentActivity> {
+ // Group buckets by agent once so per-agent derivation is O(buckets) not
+ // O(agents × buckets).
+ const bucketsByAgent = new Map<string, AgentActivityBucket[]>();
+ for (const b of buckets) {
+ const list = bucketsByAgent.get(b.agent_id);
+ if (list) list.push(b);
+ else bucketsByAgent.set(b.agent_id, [b]);
+ }
+
+ const out = new Map<string, AgentActivity>();
+ for (const agent of agents) {
+ out.set(
+ agent.id,
+ deriveAgentActivity(
+ bucketsByAgent.get(agent.id) ?? [],
+ agent.created_at,
+ now,
+ ),
+ );
+ }
+ return out;
+}
+
+/**
+ * Pure derivation: filter the workspace-wide buckets to one agent and
+ * normalise to a fixed 30-element series ending at `now`. Exported for
+ * unit-testing and direct reuse on surfaces that already have the
+ * workspace-wide buckets in hand.
+ */
+export function deriveAgentActivity(
+ buckets: readonly AgentActivityBucket[],
+ agentCreatedAt: string,
+ now: number,
+): AgentActivity {
+ const series: ActivityBucket[] = Array.from({ length: DAYS }, () => ({
+ total: 0,
+ failed: 0,
+ }));
+
+ // Newest slot is the start of "today" in local time; we walk back DAYS
+ // slots so index 0 = oldest, index DAYS-1 = today.
+ const today = startOfDay(now);
+
+ for (const b of buckets) {
+ const ts = new Date(b.bucket_at).getTime();
+ if (Number.isNaN(ts)) continue;
+ const daysAgo = Math.floor((today - startOfDay(ts)) / DAY_MS);
+ if (daysAgo < 0 || daysAgo >= DAYS) continue;
+ const slot = DAYS - 1 - daysAgo;
+ series[slot]!.total += b.task_count;
+ series[slot]!.failed += b.failed_count;
+ }
+
+ const createdAt = new Date(agentCreatedAt).getTime();
+ const ageMs = Number.isFinite(createdAt) ? now - createdAt : Infinity;
+ const daysSinceCreated = Math.min(
+ DAYS,
+ Math.max(0, Math.floor(ageMs / DAY_MS)),
+ );
+
+ return {
+ buckets: series,
+ daysSinceCreated,
+ };
+}
+
+/**
+ * Take the trailing N buckets and roll up totals over them. This is the
+ * single entry point both surfaces (list + detail) read through, so the
+ * numbers can never disagree with the bars they label.
+ *
+ * `windowDays` is clamped to the available bucket count, so passing a
+ * value larger than `activity.buckets.length` returns the full series
+ * rather than an out-of-range slice.
+ */
+export function summarizeActivityWindow(
+ activity: AgentActivity | undefined,
+ windowDays: number,
+): ActivityWindowSummary {
+ if (!activity) return { ...EMPTY_SUMMARY, windowDays };
+ const safeWindow = Math.min(
+ Math.max(0, windowDays),
+ activity.buckets.length,
+ );
+ // `slice(-0)` returns the full array (JS quirk: -0 === 0), so guard
+ // explicitly when no window is requested.
+ const slice =
+ safeWindow === 0 ? [] : activity.buckets.slice(-safeWindow);
+ let totalRuns = 0;
+ let totalFailed = 0;
+ for (const b of slice) {
+ totalRuns += b.total;
+ totalFailed += b.failed;
+ }
+ return { buckets: slice, totalRuns, totalFailed, windowDays };
+}
+
+function startOfDay(ts: number): number {
+ // Local-time day boundary. The back-end truncates to UTC midnight, but
+ // the user's mental model is "today/yesterday in the timezone they're
+ // looking at"; using local matches that and keeps "today" stable across
+ // a working session even when buckets cross UTC midnight.
+ const d = new Date(ts);
+ d.setHours(0, 0, 0, 0);
+ return d.getTime();
+}
+
+export const __EMPTY_ACTIVITY = EMPTY;
diff --git a/packages/core/agents/use-agent-presence.ts b/packages/core/agents/use-agent-presence.ts
new file mode 100644
index 0000000000..38e62b4986
--- /dev/null
+++ b/packages/core/agents/use-agent-presence.ts
@@ -0,0 +1,129 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { agentListOptions } from "../workspace/queries";
+import { runtimeListOptions } from "../runtimes/queries";
+import { agentTaskSnapshotOptions } from "./queries";
+import {
+ buildPresenceMap,
+ deriveAgentPresenceDetail,
+} from "./derive-presence";
+import type { AgentPresenceDetail } from "./types";
+
+// 30s tick, mirroring useRuntimeHealth. Presence depends on wall-clock time
+// for one reason: `unstable` (= RuntimeHealth.recently_lost) decays into
+// `offline` at the 5-minute mark with no new server data. Without a tick the
+// transition would only render on the next unrelated query update.
+// The earlier 2-minute "clear failed badge" tick was removed when failed
+// became sticky; this one re-introduces ticking with a different motivation.
+const PRESENCE_TICK_MS = 30_000;
+
+function usePresenceTick(): number {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ const id = setInterval(() => setTick((t) => t + 1), PRESENCE_TICK_MS);
+ return () => clearInterval(id);
+ }, []);
+ return tick;
+}
+
+/**
+ * Workspace-wide presence map keyed by `agent.id`. **The single entry point
+ * for any list / card / runtime sub-view that needs presence for more than
+ * one agent.**
+ *
+ * Why this exists (vs calling `useAgentPresence` per row): the per-agent
+ * hook subscribes to 3 queries. With 30+ rows that's a forest of redundant
+ * memos. This batch hook pays the cost once for the whole page; rows just
+ * `Map.get(id)` — O(1) reads, no extra subscriptions.
+ *
+ * Returned value:
+ * - `byAgent`: ready-to-read Map. Empty if data is still loading.
+ * - `loading`: true until all three input queries have resolved at least
+ * once. Callers can render skeletons during loading.
+ *
+ * Single-agent consumers should keep using `useAgentPresenceDetail`; this
+ * hook is for surfaces that already have a list of agents in hand.
+ */
+export function useWorkspacePresenceMap(wsId: string | undefined): {
+ byAgent: Map<string, AgentPresenceDetail>;
+ loading: boolean;
+} {
+ const { data: agents, isPending: agentsPending } = useQuery({
+ ...agentListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { data: runtimes, isPending: runtimesPending } = useQuery({
+ ...runtimeListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { data: snapshot, isPending: snapshotPending } = useQuery({
+ ...agentTaskSnapshotOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const tick = usePresenceTick();
+
+ const byAgent = useMemo(() => {
+ if (!agents || !runtimes || !snapshot) {
+ return new Map<string, AgentPresenceDetail>();
+ }
+ return buildPresenceMap({
+ agents,
+ runtimes,
+ snapshot,
+ now: Date.now(),
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [agents, runtimes, snapshot, tick]);
+
+ return {
+ byAgent,
+ loading: agentsPending || runtimesPending || snapshotPending,
+ };
+}
+
+/**
+ * Single-agent presence detail: availability + last task state + counts +
+ * (when failed) failure reason and timestamp. Returns "loading" only while
+ * the underlying queries haven't resolved yet — a missing runtime is a
+ * real state (offline) and resolves into a non-loading detail.
+ *
+ * For surfaces that already have a list of agents in hand (Agents page,
+ * Runtime detail), prefer `useWorkspacePresenceMap` to avoid forest of
+ * redundant subscriptions.
+ */
+export function useAgentPresenceDetail(
+ wsId: string | undefined,
+ agentId: string | undefined,
+): AgentPresenceDetail | "loading" {
+ const { data: agents } = useQuery({
+ ...agentListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { data: runtimes } = useQuery({
+ ...runtimeListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { data: snapshot } = useQuery({
+ ...agentTaskSnapshotOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const tick = usePresenceTick();
+
+ return useMemo<AgentPresenceDetail | "loading">(() => {
+ if (!wsId || !agentId) return "loading";
+ if (!agents || !runtimes || !snapshot) return "loading";
+
+ const agent = agents.find((a) => a.id === agentId);
+ if (!agent) return "loading";
+ // Missing runtime is a legitimate state (offline) — pass null and let
+ // derive handle it. The previous implementation looped forever in
+ // "loading" when runtime was deleted.
+ const runtime = runtimes.find((r) => r.id === agent.runtime_id) ?? null;
+
+ const tasks = snapshot.filter((t) => t.agent_id === agentId);
+ return deriveAgentPresenceDetail({ agent, runtime, tasks, now: Date.now() });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [wsId, agentId, agents, runtimes, snapshot, tick]);
+}
diff --git a/packages/core/agents/use-workspace-presence-prefetch.ts b/packages/core/agents/use-workspace-presence-prefetch.ts
new file mode 100644
index 0000000000..81b2d604f0
--- /dev/null
+++ b/packages/core/agents/use-workspace-presence-prefetch.ts
@@ -0,0 +1,26 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { agentListOptions } from "../workspace/queries";
+import { runtimeListOptions } from "../runtimes/queries";
+import { agentTaskSnapshotOptions } from "./queries";
+
+// Subscribe to the three queries that power agent presence so they're warm
+// by the time any hover card / inline indicator first renders. Without this
+// warm-up, surfaces that don't otherwise touch the snapshot (inbox, issues,
+// chat) flash a skeleton on first hover while the fetch is in flight.
+//
+// useRealtimeSync (WS task / agent / daemon invalidations) and the 30s
+// presence tick keep these caches fresh after the initial fetch — this hook
+// only collapses the cold-start window.
+//
+// All three are workspace-scoped; the queryKeys include wsId so workspace
+// switch automatically refetches the new workspace's data with no extra
+// wiring here. The workspace-scoped layouts on both apps gate rendering on
+// "workspace resolved", so callers can safely pass useWorkspaceId() — by the
+// time this hook mounts, wsId is guaranteed non-empty.
+export function useWorkspacePresencePrefetch(wsId: string | undefined): void {
+ useQuery({ ...agentListOptions(wsId ?? ""), enabled: !!wsId });
+ useQuery({ ...runtimeListOptions(wsId ?? ""), enabled: !!wsId });
+ useQuery({ ...agentTaskSnapshotOptions(wsId ?? ""), enabled: !!wsId });
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 8822d4f917..a54af46ff6 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -13,6 +13,8 @@ import type {
CreateAgentRequest,
UpdateAgentRequest,
AgentTask,
+ AgentActivityBucket,
+ AgentRunCount,
AgentRuntime,
InboxItem,
IssueSubscriber,
@@ -33,6 +35,8 @@ import type {
RuntimeUsage,
IssueUsageSummary,
RuntimeHourlyActivity,
+ RuntimeUsageByAgent,
+ RuntimeUsageByHour,
RuntimeUpdate,
RuntimeModelListRequest,
RuntimeLocalSkillListRequest,
@@ -566,6 +570,14 @@ export class ApiClient {
return this.fetch(`/api/agents/${id}/restore`, { method: "POST" });
}
+ // Bulk-cancel every active task (queued/dispatched/running) for the agent.
+ // Permission: agent owner or workspace admin/owner. Server returns the
+ // count of cancelled rows; broadcasts task:cancelled for each so other
+ // surfaces can clear their live cards.
+ async cancelAgentTasks(id: string): Promise<{ cancelled: number }> {
+ return this.fetch(`/api/agents/${id}/cancel-tasks`, { method: "POST" });
+ }
+
async listRuntimes(params?: { workspace_id?: string; owner?: "me" }): Promise<AgentRuntime[]> {
const search = new URLSearchParams();
if (params?.workspace_id) search.set("workspace_id", params.workspace_id);
@@ -587,6 +599,24 @@ export class ApiClient {
return this.fetch(`/api/runtimes/${runtimeId}/activity`);
}
+ async getRuntimeUsageByAgent(
+ runtimeId: string,
+ params?: { days?: number },
+ ): Promise<RuntimeUsageByAgent[]> {
+ const search = new URLSearchParams();
+ if (params?.days) search.set("days", String(params.days));
+ return this.fetch(`/api/runtimes/${runtimeId}/usage/by-agent?${search}`);
+ }
+
+ async getRuntimeUsageByHour(
+ runtimeId: string,
+ params?: { days?: number },
+ ): Promise<RuntimeUsageByHour[]> {
+ const search = new URLSearchParams();
+ if (params?.days) search.set("days", String(params.days));
+ return this.fetch(`/api/runtimes/${runtimeId}/usage/by-hour?${search}`);
+ }
+
async initiateUpdate(
runtimeId: string,
targetVersion: string,
@@ -651,6 +681,28 @@ export class ApiClient {
return this.fetch(`/api/agents/${agentId}/tasks`);
}
+ // Workspace-scoped agent task snapshot: every active task
+ // (queued/dispatched/running) plus each agent's most recent terminal task.
+ // Powers the front-end's "active wins, else latest terminal" presence
+ // derivation; one fetch backs every per-agent presence read in the app.
+ // Workspace is resolved server-side from the X-Workspace-Slug header.
+ async getAgentTaskSnapshot(): Promise<AgentTask[]> {
+ return this.fetch(`/api/agent-task-snapshot`);
+ }
+
+ // Per-agent daily activity for the last 30 days, anchored on
+ // completed_at. One workspace-wide fetch backs both the Agents-list
+ // sparkline (uses trailing 7 buckets) and the agent detail "Last 30
+ // days" panel (uses all 30).
+ async getWorkspaceAgentActivity30d(): Promise<AgentActivityBucket[]> {
+ return this.fetch(`/api/agent-activity-30d`);
+ }
+
+ // Per-agent 30-day total run count for the Agents-list RUNS column.
+ async getWorkspaceAgentRunCounts(): Promise<AgentRunCount[]> {
+ return this.fetch(`/api/agent-run-counts`);
+ }
+
async getActiveTasksForIssue(issueId: string): Promise<{ tasks: AgentTask[] }> {
return this.fetch(`/api/issues/${issueId}/active-task`);
}
diff --git a/packages/core/package.json b/packages/core/package.json
index 2b962c7131..cbc2e1fdf3 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -42,6 +42,10 @@
"./runtimes/queries": "./runtimes/queries.ts",
"./runtimes/mutations": "./runtimes/mutations.ts",
"./runtimes/hooks": "./runtimes/hooks.ts",
+ "./agents": "./agents/index.ts",
+ "./agents/queries": "./agents/queries.ts",
+ "./agents/derive-presence": "./agents/derive-presence.ts",
+ "./agents/use-agent-presence": "./agents/use-agent-presence.ts",
"./projects": "./projects/index.ts",
"./projects/queries": "./projects/queries.ts",
"./projects/mutations": "./projects/mutations.ts",
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
index a7c20860f0..27b0b3cd37 100644
--- a/packages/core/paths/paths.ts
+++ b/packages/core/paths/paths.ts
@@ -25,9 +25,11 @@ function workspaceScoped(slug: string) {
autopilots: () => `${ws}/autopilots`,
autopilotDetail: (id: string) => `${ws}/autopilots/${encode(id)}`,
agents: () => `${ws}/agents`,
+ agentDetail: (id: string) => `${ws}/agents/${encode(id)}`,
inbox: () => `${ws}/inbox`,
myIssues: () => `${ws}/my-issues`,
runtimes: () => `${ws}/runtimes`,
+ runtimeDetail: (id: string) => `${ws}/runtimes/${encode(id)}`,
skills: () => `${ws}/skills`,
skillDetail: (id: string) => `${ws}/skills/${encode(id)}`,
settings: () => `${ws}/settings`,
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 001fae3190..52b21fd24f 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -14,6 +14,7 @@ import { projectKeys } from "../projects/queries";
import { pinKeys } from "../pins/queries";
import { autopilotKeys } from "../autopilots/queries";
import { runtimeKeys } from "../runtimes/queries";
+import { agentTaskSnapshotKeys, agentActivityKeys, agentRunCountsKeys } from "../agents/queries";
import {
onIssueCreated,
onIssueUpdated,
@@ -143,6 +144,25 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });
},
+ // Powers the agent presence cache: any task lifecycle change
+ // (dispatch / completed / failed / cancelled) refreshes the
+ // workspace-wide agent-task-snapshot query so per-agent presence
+ // reflects the change. task:message is NOT in this prefix path — it
+ // stays in specificEvents to avoid an invalidate storm during long runs.
+ task: () => {
+ const wsId = getCurrentWsId();
+ if (!wsId) return;
+ qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.list(wsId) });
+ // 30d activity series shares the same lifecycle signal — any task
+ // completion / failure shifts the histogram. (Dispatch alone
+ // doesn't change a completed_at-anchored series, but invalidating
+ // here keeps the WS-handler shape uniform; the resulting refetch
+ // is cheap.) Both the list (trailing 7d slice) and the detail
+ // panel read off this single cache.
+ qc.invalidateQueries({ queryKey: agentActivityKeys.last30d(wsId) });
+ // 30-day run count likewise increments per task lifecycle event.
+ qc.invalidateQueries({ queryKey: agentRunCountsKeys.last30d(wsId) });
+ },
};
const timers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -167,9 +187,18 @@ export function useRealtimeSync(
"issue_reaction:added", "issue_reaction:removed",
"subscriber:added", "subscriber:removed",
"daemon:heartbeat",
- // Chat / task events are handled explicitly below; do not double-invalidate.
+ // Chat events are handled explicitly below; do not double-invalidate.
"chat:message", "chat:done", "chat:session_read",
- "task:message", "task:completed", "task:failed",
+ // task:message stays out of the prefix path because it fires per
+ // streamed message during a long run — invalidating the snapshot on
+ // every message would flood the network. Specific chat handlers below
+ // still receive it via ws.on() (a separate subscription channel).
+ "task:message",
+ // task:completed / task:failed deliberately NOT here. They go through
+ // both the task-prefix invalidate (refreshes the agent-task-snapshot
+ // cache) AND the chat-specific ws.on() handlers below. The two
+ // channels are independent — onAny dispatch and ws.on are separate
+ // subscriptions.
]);
const unsubAny = ws.onAny((msg) => {
@@ -566,6 +595,9 @@ export function useRealtimeSync(
qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: agentActivityKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: agentRunCountsKeys.all(wsId) });
}
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
} catch (e) {
diff --git a/packages/core/runtimes/derive-health.test.ts b/packages/core/runtimes/derive-health.test.ts
new file mode 100644
index 0000000000..9e8f0d0e90
--- /dev/null
+++ b/packages/core/runtimes/derive-health.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from "vitest";
+import type { AgentRuntime } from "../types";
+import { deriveRuntimeHealth } from "./derive-health";
+
+const FIXED_NOW = new Date("2026-04-27T12:00:00Z").getTime();
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "rt-1",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-1",
+ name: "Test Runtime",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: null,
+ last_seen_at: new Date(FIXED_NOW - 10_000).toISOString(),
+ created_at: "2026-04-01T00:00:00Z",
+ updated_at: "2026-04-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("deriveRuntimeHealth", () => {
+ it("returns online when status is online (regardless of last_seen_at)", () => {
+ expect(
+ deriveRuntimeHealth(makeRuntime({ status: "online", last_seen_at: null }), FIXED_NOW),
+ ).toBe("online");
+ });
+
+ it("returns recently_lost when offline less than 5 minutes", () => {
+ expect(
+ deriveRuntimeHealth(
+ makeRuntime({
+ status: "offline",
+ last_seen_at: new Date(FIXED_NOW - 2 * 60_000).toISOString(),
+ }),
+ FIXED_NOW,
+ ),
+ ).toBe("recently_lost");
+ });
+
+ it("returns offline when offline between 5 minutes and 6 days", () => {
+ expect(
+ deriveRuntimeHealth(
+ makeRuntime({
+ status: "offline",
+ last_seen_at: new Date(FIXED_NOW - 60 * 60_000).toISOString(), // 1 hour
+ }),
+ FIXED_NOW,
+ ),
+ ).toBe("offline");
+ });
+
+ it("returns about_to_gc when offline beyond 6 days (within 1 day of GC)", () => {
+ expect(
+ deriveRuntimeHealth(
+ makeRuntime({
+ status: "offline",
+ last_seen_at: new Date(FIXED_NOW - 6.5 * 24 * 3600_000).toISOString(),
+ }),
+ FIXED_NOW,
+ ),
+ ).toBe("about_to_gc");
+ });
+
+ it("treats null last_seen_at as long-offline (about_to_gc)", () => {
+ // last_seen_at = null means lastSeen = 0 (epoch), so offlineFor is huge.
+ expect(
+ deriveRuntimeHealth(
+ makeRuntime({ status: "offline", last_seen_at: null }),
+ FIXED_NOW,
+ ),
+ ).toBe("about_to_gc");
+ });
+
+ it("respects the 5-minute boundary (just inside → recently_lost)", () => {
+ expect(
+ deriveRuntimeHealth(
+ makeRuntime({
+ status: "offline",
+ last_seen_at: new Date(FIXED_NOW - (5 * 60_000 - 1_000)).toISOString(),
+ }),
+ FIXED_NOW,
+ ),
+ ).toBe("recently_lost");
+ });
+
+ it("respects the 5-minute boundary (just outside → offline)", () => {
+ expect(
+ deriveRuntimeHealth(
+ makeRuntime({
+ status: "offline",
+ last_seen_at: new Date(FIXED_NOW - (5 * 60_000 + 1_000)).toISOString(),
+ }),
+ FIXED_NOW,
+ ),
+ ).toBe("offline");
+ });
+});
diff --git a/packages/core/runtimes/derive-health.ts b/packages/core/runtimes/derive-health.ts
new file mode 100644
index 0000000000..f19fab7303
--- /dev/null
+++ b/packages/core/runtimes/derive-health.ts
@@ -0,0 +1,27 @@
+// Pure derivation of a runtime's user-facing "health" state from the raw
+// server fields (status + last_seen_at). Splitting the offline state into
+// time-bucketed flavors lets the UI distinguish "just lost — likely
+// transient" from "long gone — needs attention" with no schema change.
+
+import type { AgentRuntime } from "../types";
+import type { RuntimeHealth } from "./types";
+
+const FIVE_MINUTES_MS = 5 * 60 * 1000;
+// The runtime sweeper GCs runtimes that have been offline for 7 days. We
+// flag the last 24 hours of that window so users can rescue a runtime
+// before it disappears silently.
+const ABOUT_TO_GC_THRESHOLD_MS = 6 * 24 * 3600 * 1000; // 6 days
+
+export function deriveRuntimeHealth(runtime: AgentRuntime, now: number): RuntimeHealth {
+ if (runtime.status === "online") return "online";
+
+ // No last_seen timestamp ever recorded — treat as long-offline. This is
+ // an unusual case (the back-end always sets last_seen_at on register),
+ // but defending against it keeps the UI from crashing on legacy rows.
+ const lastSeen = runtime.last_seen_at ? new Date(runtime.last_seen_at).getTime() : 0;
+ const offlineFor = now - lastSeen;
+
+ if (offlineFor < FIVE_MINUTES_MS) return "recently_lost";
+ if (offlineFor > ABOUT_TO_GC_THRESHOLD_MS) return "about_to_gc";
+ return "offline";
+}
diff --git a/packages/core/runtimes/index.ts b/packages/core/runtimes/index.ts
index cc25aa8250..59c6af048d 100644
--- a/packages/core/runtimes/index.ts
+++ b/packages/core/runtimes/index.ts
@@ -3,3 +3,6 @@ export * from "./mutations";
export * from "./hooks";
export * from "./models";
export * from "./local-skills";
+export * from "./types";
+export * from "./derive-health";
+export * from "./use-runtime-health";
diff --git a/packages/core/runtimes/queries.ts b/packages/core/runtimes/queries.ts
index 6c02e8c2b9..dbdd3c168d 100644
--- a/packages/core/runtimes/queries.ts
+++ b/packages/core/runtimes/queries.ts
@@ -5,9 +5,47 @@ export const runtimeKeys = {
all: (wsId: string) => ["runtimes", wsId] as const,
list: (wsId: string) => [...runtimeKeys.all(wsId), "list"] as const,
listMine: (wsId: string) => [...runtimeKeys.all(wsId), "list", "mine"] as const,
+ usage: (rid: string, days: number) =>
+ ["runtimes", "usage", rid, days] as const,
+ usageByAgent: (rid: string, days: number) =>
+ ["runtimes", "usage", "by-agent", rid, days] as const,
+ usageByHour: (rid: string, days: number) =>
+ ["runtimes", "usage", "by-hour", rid, days] as const,
latestVersion: () => ["runtimes", "latestVersion"] as const,
};
+// Per-runtime usage. Used by the list view (each row pulls its own activity
+// sparkline + 30d cost) and by the detail page. TanStack Query naturally
+// deduplicates concurrent calls for the same runtime, so multiple components
+// observing the same runtimeId share one network request.
+export function runtimeUsageOptions(runtimeId: string, days: number) {
+ return queryOptions({
+ queryKey: runtimeKeys.usage(runtimeId, days),
+ queryFn: () => api.getRuntimeUsage(runtimeId, { days }),
+ staleTime: 60 * 1000,
+ });
+}
+
+// Per-agent token totals for one runtime — drives the "Cost by agent" tab
+// on the runtime detail page. Server-side aggregation keeps the response
+// small (one row per agent) regardless of task volume.
+export function runtimeUsageByAgentOptions(runtimeId: string, days: number) {
+ return queryOptions({
+ queryKey: runtimeKeys.usageByAgent(runtimeId, days),
+ queryFn: () => api.getRuntimeUsageByAgent(runtimeId, { days }),
+ staleTime: 60 * 1000,
+ });
+}
+
+// Hourly (0..23) token totals for one runtime — drives the "By hour" tab.
+export function runtimeUsageByHourOptions(runtimeId: string, days: number) {
+ return queryOptions({
+ queryKey: runtimeKeys.usageByHour(runtimeId, days),
+ queryFn: () => api.getRuntimeUsageByHour(runtimeId, { days }),
+ staleTime: 60 * 1000,
+ });
+}
+
export function runtimeListOptions(wsId: string, owner?: "me") {
return queryOptions({
queryKey: owner === "me" ? runtimeKeys.listMine(wsId) : runtimeKeys.list(wsId),
diff --git a/packages/core/runtimes/types.ts b/packages/core/runtimes/types.ts
new file mode 100644
index 0000000000..79dffaa185
--- /dev/null
+++ b/packages/core/runtimes/types.ts
@@ -0,0 +1,10 @@
+// Derived "health" type for runtimes — the user-facing state we display
+// in lists, cards, and tooltips. The raw server field is binary (online /
+// offline + last_seen_at); this enum splits the offline state into three
+// time-bucketed flavors so users can tell "just lost" from "long gone".
+
+export type RuntimeHealth =
+ | "online" // green — within heartbeat threshold
+ | "recently_lost" // amber — offline < 5 minutes (likely transient)
+ | "offline" // grey — offline 5 minutes ~ 7 days
+ | "about_to_gc"; // dim — within 1 day of the 7-day GC threshold
diff --git a/packages/core/runtimes/use-runtime-health.ts b/packages/core/runtimes/use-runtime-health.ts
new file mode 100644
index 0000000000..776e54b7f9
--- /dev/null
+++ b/packages/core/runtimes/use-runtime-health.ts
@@ -0,0 +1,46 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { runtimeListOptions } from "./queries";
+import { deriveRuntimeHealth } from "./derive-health";
+import type { RuntimeHealth } from "./types";
+
+// Re-render every 30s so transitions like recently_lost → offline (which
+// happens at the 5-minute mark with no new data) reflect in the UI.
+const HEALTH_TICK_MS = 30_000;
+
+function useHealthTick(): number {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ const id = setInterval(() => setTick((t) => t + 1), HEALTH_TICK_MS);
+ return () => clearInterval(id);
+ }, []);
+ return tick;
+}
+
+/**
+ * Derived runtime health (online / recently_lost / offline / about_to_gc),
+ * or "loading" while the runtime list is still resolving.
+ *
+ * Accepts wsId as a parameter so the hook works outside WorkspaceIdProvider.
+ */
+export function useRuntimeHealth(
+ wsId: string | undefined,
+ runtimeId: string | undefined,
+): RuntimeHealth | "loading" {
+ const { data: runtimes } = useQuery({
+ ...runtimeListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const tick = useHealthTick();
+
+ return useMemo<RuntimeHealth | "loading">(() => {
+ if (!wsId || !runtimeId) return "loading";
+ if (!runtimes) return "loading";
+ const runtime = runtimes.find((r) => r.id === runtimeId);
+ if (!runtime) return "loading";
+ return deriveRuntimeHealth(runtime, Date.now());
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [wsId, runtimeId, runtimes, tick]);
+}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 196cf20e12..773007a140 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -23,6 +23,34 @@ export interface RuntimeDevice {
export type AgentRuntime = RuntimeDevice;
+// Coarse classifier set by the backend when a task transitions to "failed".
+// Mirrors the migration-055 enum in agent_task_queue.failure_reason. Used by
+// the agent presence derivation and the UI failure-message lookup.
+export type TaskFailureReason =
+ | "agent_error"
+ | "timeout"
+ | "runtime_offline"
+ | "runtime_recovery"
+ | "manual";
+
+// One daily bucket for the Agents-list ACTIVITY sparkline. The back-end
+// only returns days that had at least one completion; the front-end fills
+// in missing days with zero when rendering the 7-bucket series. The series
+// is anchored on completed_at (a task in flight contributes nothing).
+export interface AgentActivityBucket {
+ agent_id: string;
+ // ISO timestamp at midnight UTC of the day.
+ bucket_at: string;
+ task_count: number;
+ failed_count: number;
+}
+
+// 30-day total run count per agent, drives the Agents-list RUNS column.
+export interface AgentRunCount {
+ agent_id: string;
+ run_count: number;
+}
+
export interface AgentTask {
id: string;
agent_id: string;
@@ -38,6 +66,9 @@ export interface AgentTask {
completed_at: string | null;
result: unknown;
error: string | null;
+ // Empty string when the task is not in a failed state (the backend uses
+ // `omitempty`, so the field may also be missing on non-failed tasks).
+ failure_reason?: TaskFailureReason | "";
created_at: string;
/** Non-empty when the task was spawned from a chat session. */
chat_session_id?: string;
@@ -170,6 +201,33 @@ export interface RuntimeHourlyActivity {
count: number;
}
+// One (agent, model) row of the "Cost by agent" tab on the runtime detail
+// page. Model stays on the wire because cost is computed client-side from
+// a per-model pricing table — the client groups these rows by agent_id and
+// sums cost per agent across models.
+export interface RuntimeUsageByAgent {
+ agent_id: string;
+ model: string;
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens: number;
+ cache_write_tokens: number;
+ task_count: number;
+}
+
+// One (hour, model) row for the "By hour" tab; hour ∈ 0..23. Hours with
+// zero activity are omitted by the server; the client fills the gap to
+// render a continuous axis. Model preserved for client-side cost math.
+export interface RuntimeUsageByHour {
+ hour: number;
+ model: string;
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens: number;
+ cache_write_tokens: number;
+ task_count: number;
+}
+
export type RuntimeUpdateStatus =
| "pending"
| "running"
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index d7fba25184..1bc447015e 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -5,6 +5,9 @@ export type {
AgentRuntimeMode,
AgentVisibility,
AgentTask,
+ AgentActivityBucket,
+ AgentRunCount,
+ TaskFailureReason,
AgentRuntime,
RuntimeDevice,
CreateAgentRequest,
@@ -16,6 +19,8 @@ export type {
SetAgentSkillsRequest,
RuntimeUsage,
RuntimeHourlyActivity,
+ RuntimeUsageByAgent,
+ RuntimeUsageByHour,
RuntimeUpdate,
RuntimeUpdateStatus,
RuntimeModel,
diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsx
index 4b5c0b8d84..b3d8e9a9a7 100644
--- a/packages/ui/markdown/Markdown.tsx
+++ b/packages/ui/markdown/Markdown.tsx
@@ -12,6 +12,7 @@ import { CodeBlock, InlineCode } from './CodeBlock'
import { preprocessFileCards } from './file-cards'
import { preprocessLinks } from './linkify'
import { preprocessMentionShortcodes } from './mentions'
+import 'katex/dist/katex.min.css'
import './markdown.css'
/**
diff --git a/packages/ui/markdown/markdown.css b/packages/ui/markdown/markdown.css
index e2a366c905..5b258bd17b 100644
--- a/packages/ui/markdown/markdown.css
+++ b/packages/ui/markdown/markdown.css
@@ -1,5 +1,3 @@
-@import "katex/dist/katex.min.css";
-
.markdown-content .katex-display {
margin: 0.75rem 0;
overflow-x: auto;
diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.css
index fcf269a2da..24303029c7 100644
--- a/packages/ui/styles/tokens.css
+++ b/packages/ui/styles/tokens.css
@@ -70,11 +70,16 @@
--border: oklch(0.92 0.004 286.32);
--input: oklch(0.92 0.004 286.32);
--ring: oklch(0.705 0.015 286.067);
- --chart-1: oklch(0.705 0.015 286.067);
- --chart-2: oklch(0.552 0.016 285.938);
- --chart-3: oklch(0.442 0.017 285.786);
- --chart-4: oklch(0.37 0.013 285.805);
- --chart-5: oklch(0.274 0.006 286.033);
+ /* Brand-derived blue gradient (h=255 = brand hue). chart-1 equals brand
+ so the most important series visually anchors to the product colour;
+ chart-2..5 step lighter + less saturated so a stacked bar reads
+ "primary → secondary → tertiary" at a glance instead of fighting
+ for attention as five equally-weighted greys. */
+ --chart-1: oklch(0.55 0.16 255);
+ --chart-2: oklch(0.66 0.13 255);
+ --chart-3: oklch(0.76 0.10 255);
+ --chart-4: oklch(0.85 0.06 255);
+ --chart-5: oklch(0.92 0.03 255);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.141 0.005 285.823);
@@ -114,11 +119,15 @@
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.552 0.016 285.938);
- --chart-1: oklch(0.871 0.006 286.286);
- --chart-2: oklch(0.75 0.016 285.938);
- --chart-3: oklch(0.62 0.017 285.786);
- --chart-4: oklch(0.52 0.013 285.805);
- --chart-5: oklch(0.42 0.006 286.033);
+ /* Dark mode mirrors light mode's "primary → secondary" gradient on the
+ brand hue, but flips the lightness curve: the most important series
+ is the brightest (so it pops on the dark background) and trailing
+ series get progressively darker / less saturated. */
+ --chart-1: oklch(0.72 0.16 255);
+ --chart-2: oklch(0.62 0.13 255);
+ --chart-3: oklch(0.52 0.10 255);
+ --chart-4: oklch(0.42 0.06 255);
+ --chart-5: oklch(0.32 0.03 255);
--sidebar: oklch(0.21 0.006 285.885);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsx
new file mode 100644
index 0000000000..7ac315bf84
--- /dev/null
+++ b/packages/views/agents/components/agent-detail-inspector.tsx
@@ -0,0 +1,472 @@
+"use client";
+
+import {
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { Camera, Loader2, Pencil } from "lucide-react";
+import { toast } from "sonner";
+import type {
+ Agent,
+ AgentRuntime,
+ MemberWithUser,
+} from "@multica/core/types";
+import type { AgentPresenceDetail } from "@multica/core/agents";
+import { api } from "@multica/core/api";
+import { useFileUpload } from "@multica/core/hooks/use-file-upload";
+import { timeAgo } from "@multica/core/utils";
+import { Button } from "@multica/ui/components/ui/button";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@multica/ui/components/ui/popover";
+import { PropRow } from "../../common/prop-row";
+import { availabilityConfig } from "../presence";
+import { ConcurrencyPicker } from "./inspector/concurrency-picker";
+import { ModelPicker } from "./inspector/model-picker";
+import { RuntimePicker } from "./inspector/runtime-picker";
+import { SkillAttach } from "./inspector/skill-attach";
+import { VisibilityPicker } from "./inspector/visibility-picker";
+
+interface InspectorProps {
+ agent: Agent;
+ runtime: AgentRuntime | null;
+ owner: MemberWithUser | null;
+ presence: AgentPresenceDetail | null | undefined;
+ // Below: needed for inline edit. The inspector now owns the editing surface
+ // (no Settings tab anymore), so the parent has to pass through everything
+ // a write needs.
+ runtimes: AgentRuntime[];
+ members: MemberWithUser[];
+ currentUserId: string | null;
+ onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+}
+
+/**
+ * Left 320px column of the agent detail page. Holds the agent's identity card
+ * (avatar / name / description / status), inline-editable properties, and
+ * skills.
+ *
+ * **All editing happens here** — there is no separate Settings tab. The
+ * trade-off is that the inspector carries some weight (4 inline pickers plus
+ * 3 popovers for name/description/avatar), but it eliminates the "see vs
+ * edit" mode split that the previous Settings tab created. Users no longer
+ * have to switch tabs and hunt for the field they were already looking at.
+ */
+export function AgentDetailInspector({
+ agent,
+ runtime,
+ owner,
+ presence,
+ runtimes,
+ members,
+ currentUserId,
+ onUpdate,
+}: InspectorProps) {
+ const update = (data: Record<string, unknown>) => onUpdate(agent.id, data);
+ const isOnline = runtime?.status === "online";
+
+ return (
+ <aside className="flex h-full min-h-0 w-full flex-col overflow-y-auto rounded-lg border bg-background">
+ {/* Identity */}
+ <div className="flex flex-col gap-3 border-b px-5 pb-5 pt-5">
+ <AvatarEditor agent={agent} onUpdate={update} />
+ <NameAndDescription agent={agent} onUpdate={update} />
+ <PresenceBadge presence={presence} />
+ </div>
+
+ {/* Properties — editable. Row hover is OFF here on purpose: each chip
+ (RuntimePicker, ModelPicker, …) carries its own border + hover-bg
+ treatment that already telegraphs "this is a button". A second
+ row-wide hover layer on top would just smudge the chip boundary
+ and make it harder, not easier, to see what's clickable. */}
+ <Section label="Properties">
+ <PropRow label="Runtime" interactive={false}>
+ <RuntimePicker
+ value={agent.runtime_id}
+ runtimes={runtimes}
+ members={members}
+ currentUserId={currentUserId}
+ onChange={(id) => update({ runtime_id: id })}
+ />
+ </PropRow>
+ <PropRow label="Model" interactive={false}>
+ <ModelPicker
+ runtimeId={agent.runtime_id}
+ runtimeOnline={!!isOnline}
+ value={agent.model ?? ""}
+ onChange={(m) => update({ model: m })}
+ />
+ </PropRow>
+ <PropRow label="Visibility" interactive={false}>
+ <VisibilityPicker
+ value={agent.visibility}
+ onChange={(v) => update({ visibility: v })}
+ />
+ </PropRow>
+ <PropRow label="Concurrency" interactive={false}>
+ <ConcurrencyPicker
+ value={agent.max_concurrent_tasks}
+ onChange={(n) => update({ max_concurrent_tasks: n })}
+ />
+ </PropRow>
+ </Section>
+
+ {/* Details — read-only (no hover, no chip styling — these aren't clickable) */}
+ <Section label="Details">
+ {owner && (
+ <PropRow label="Owner" interactive={false}>
+ <span className="flex min-w-0 items-center gap-1.5">
+ <ActorAvatar
+ actorType="member"
+ actorId={owner.user_id}
+ size={14}
+ />
+ <span className="truncate">{owner.name}</span>
+ </span>
+ </PropRow>
+ )}
+ <PropRow label="Created" interactive={false}>
+ <span className="text-muted-foreground">
+ {timeAgo(agent.created_at)}
+ </span>
+ </PropRow>
+ <PropRow label="Updated" interactive={false}>
+ <span className="text-muted-foreground">
+ {timeAgo(agent.updated_at)}
+ </span>
+ </PropRow>
+ </Section>
+
+ {/* Skills */}
+ <div className="flex flex-col border-b px-5 py-4">
+ <div className="mb-2 flex items-center gap-2">
+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
+ Skills
+ </span>
+ <span className="font-mono text-[10px] tabular-nums text-muted-foreground/70">
+ {agent.skills.length}
+ </span>
+ </div>
+ <div className="flex flex-wrap gap-1">
+ {agent.skills.map((s) => (
+ <span
+ key={s.id}
+ className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium text-muted-foreground"
+ >
+ {s.name}
+ </span>
+ ))}
+ <SkillAttach agent={agent} />
+ </div>
+ </div>
+ </aside>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Layout helpers
+// ---------------------------------------------------------------------------
+
+function Section({
+ label,
+ children,
+}: {
+ label: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-0.5 border-b px-5 py-4">
+ <div className="mb-1 px-2 -mx-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
+ {label}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Identity — avatar / name / description editors
+// ---------------------------------------------------------------------------
+
+function AvatarEditor({
+ agent,
+ onUpdate,
+}: {
+ agent: Agent;
+ onUpdate: (data: Record<string, unknown>) => Promise<void>;
+}) {
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const { upload, uploading } = useFileUpload(api);
+
+ const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ e.target.value = "";
+ try {
+ const result = await upload(file);
+ if (!result) return;
+ await onUpdate({ avatar_url: result.link });
+ toast.success("Avatar updated");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to upload avatar");
+ }
+ };
+
+ return (
+ <>
+ <button
+ type="button"
+ // rounded-lg matches the standard agent avatar treatment used in
+ // list rows. Avoid rounded-full — circles are reserved for humans.
+ className="group relative h-14 w-14 shrink-0 overflow-hidden rounded-lg bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={uploading}
+ aria-label="Change avatar"
+ >
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size={56}
+ className="rounded-none"
+ />
+ <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
+ {uploading ? (
+ <Loader2 className="h-4 w-4 animate-spin text-white" />
+ ) : (
+ <Camera className="h-4 w-4 text-white" />
+ )}
+ </div>
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ onChange={handleFile}
+ />
+ </>
+ );
+}
+
+function NameAndDescription({
+ agent,
+ onUpdate,
+}: {
+ agent: Agent;
+ onUpdate: (data: Record<string, unknown>) => Promise<void>;
+}) {
+ return (
+ <div className="flex flex-col gap-1">
+ <InlineEditPopover
+ value={agent.name}
+ onSave={(v) => onUpdate({ name: v.trim() })}
+ kind="input"
+ title="Rename agent"
+ placeholder="Agent name"
+ validate={(v) => (v.trim().length > 0 ? null : "Name is required")}
+ >
+ {(triggerProps) => (
+ <button
+ type="button"
+ {...triggerProps}
+ className="group -mx-1 inline-flex items-center gap-1.5 self-start rounded px-1 text-left text-base font-semibold leading-tight transition-colors hover:bg-accent/50"
+ >
+ <span>{agent.name}</span>
+ <Pencil className="h-3 w-3 shrink-0 text-muted-foreground/0 transition-colors group-hover:text-muted-foreground" />
+ </button>
+ )}
+ </InlineEditPopover>
+
+ <InlineEditPopover
+ value={agent.description ?? ""}
+ onSave={(v) => onUpdate({ description: v })}
+ kind="textarea"
+ title="Edit description"
+ placeholder="What does this agent do?"
+ >
+ {(triggerProps) => (
+ <button
+ type="button"
+ {...triggerProps}
+ className="group -mx-1 inline-flex items-start gap-1.5 self-start rounded px-1 text-left text-xs leading-relaxed transition-colors hover:bg-accent/50"
+ >
+ {agent.description ? (
+ <span className="text-muted-foreground">{agent.description}</span>
+ ) : (
+ <span className="italic text-muted-foreground/50">
+ No description
+ </span>
+ )}
+ <Pencil className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/0 transition-colors group-hover:text-muted-foreground" />
+ </button>
+ )}
+ </InlineEditPopover>
+ </div>
+ );
+}
+
+// Generic single-field popover editor used for name / description. Keeps the
+// trigger styling fully in the caller's hands by using a render prop.
+function InlineEditPopover({
+ value,
+ onSave,
+ kind,
+ title,
+ placeholder,
+ validate,
+ children,
+}: {
+ value: string;
+ onSave: (next: string) => Promise<void>;
+ kind: "input" | "textarea";
+ title: string;
+ placeholder?: string;
+ validate?: (v: string) => string | null;
+ children: (triggerProps: {
+ onClick: (e: React.MouseEvent) => void;
+ }) => ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState(value);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Reset draft when popover opens or upstream value changes between sessions.
+ useEffect(() => {
+ if (open) {
+ setDraft(value);
+ setError(null);
+ }
+ }, [open, value]);
+
+ const commit = async () => {
+ const err = validate?.(draft) ?? null;
+ if (err) {
+ setError(err);
+ return;
+ }
+ if (draft === value) {
+ setOpen(false);
+ return;
+ }
+ setSaving(true);
+ try {
+ await onSave(draft);
+ setOpen(false);
+ } catch {
+ // toast handled by parent's onUpdate
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ render={children({ onClick: () => setOpen(true) }) as React.ReactElement}
+ />
+ <PopoverContent align="start" className="w-72 p-3">
+ <div className="space-y-2">
+ <p className="text-xs font-medium">{title}</p>
+ {kind === "input" ? (
+ <Input
+ autoFocus
+ value={draft}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ if (error) setError(null);
+ }}
+ placeholder={placeholder}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void commit();
+ } else if (e.key === "Escape") {
+ setOpen(false);
+ }
+ }}
+ className="h-8"
+ />
+ ) : (
+ <textarea
+ autoFocus
+ value={draft}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ if (error) setError(null);
+ }}
+ placeholder={placeholder}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") setOpen(false);
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ void commit();
+ }
+ }}
+ rows={3}
+ className="w-full resize-none rounded-md border bg-transparent px-2 py-1.5 text-xs outline-none focus-visible:border-input"
+ />
+ )}
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setOpen(false)}
+ disabled={saving}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => void commit()}
+ disabled={saving || draft === value}
+ >
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ "Save"
+ )}
+ </Button>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Presence badge — unchanged from the previous version
+// ---------------------------------------------------------------------------
+
+function PresenceBadge({
+ presence,
+}: {
+ presence: AgentPresenceDetail | null | undefined;
+}) {
+ if (!presence) {
+ return (
+ <span className="inline-flex h-5 w-20 animate-pulse rounded-md bg-muted" />
+ );
+ }
+ const av = availabilityConfig[presence.availability];
+ // Last-task chip / failure copy intentionally omitted on the detail page
+ // — the Recent work panel below shows the same data with full context.
+
+ return (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span
+ className={`inline-flex items-center gap-1.5 rounded-md border px-1.5 py-0.5 text-xs ${av.textClass}`}
+ >
+ <span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} />
+ {av.label}
+ </span>
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
new file mode 100644
index 0000000000..63f8d0b8e3
--- /dev/null
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -0,0 +1,357 @@
+"use client";
+
+import { useState } from "react";
+import {
+ AlertCircle,
+ ArrowLeft,
+ MoreHorizontal,
+ Trash2,
+} from "lucide-react";
+import { toast } from "sonner";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import type { Agent, UpdateAgentRequest } from "@multica/core/types";
+import {
+ type AgentPresenceDetail,
+ useWorkspacePresenceMap,
+} from "@multica/core/agents";
+import { api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import {
+ agentListOptions,
+ memberListOptions,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
+import { runtimeListOptions } from "@multica/core/runtimes";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { AppLink, useNavigation } from "../../navigation";
+import { PageHeader } from "../../layout/page-header";
+import { availabilityConfig } from "../presence";
+import { AgentDetailInspector } from "./agent-detail-inspector";
+import { AgentOverviewPane } from "./agent-overview-pane";
+
+interface AgentDetailPageProps {
+ agentId: string;
+}
+
+export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const qc = useQueryClient();
+ const currentUser = useAuthStore((s) => s.user);
+
+ const {
+ data: agents = [],
+ isLoading: agentsLoading,
+ error: agentsError,
+ refetch: refetchAgents,
+ } = useQuery(agentListOptions(wsId));
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+
+ // Single workspace-level presence pass; this page just reads its slot.
+ // The hook owns the 30s tick so the failed-window auto-clears here too.
+ const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
+
+ const agent = agents.find((a) => a.id === agentId) ?? null;
+ const presence: AgentPresenceDetail | null =
+ agent ? presenceMap.get(agent.id) ?? null : null;
+
+ const [confirmArchive, setConfirmArchive] = useState(false);
+
+ const handleUpdate = async (id: string, data: Record<string, unknown>) => {
+ try {
+ await api.updateAgent(id, data as UpdateAgentRequest);
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ toast.success("Agent updated");
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to update agent");
+ throw e;
+ }
+ };
+
+ const handleArchive = async (id: string) => {
+ try {
+ await api.archiveAgent(id);
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ toast.success("Agent archived");
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to archive agent");
+ }
+ };
+
+ const handleRestore = async (id: string) => {
+ try {
+ await api.restoreAgent(id);
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ toast.success("Agent restored");
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to restore agent");
+ }
+ };
+
+ // --- Loading ---
+ if (agentsLoading && !agent) {
+ return <DetailLoadingSkeleton />;
+ }
+
+ // --- Not found / error ---
+ if (!agent) {
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <BackHeader paths={paths.agents()} title="Agents" />
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
+ <AlertCircle className="h-8 w-8 text-destructive" />
+ <div>
+ <p className="text-sm font-medium">Agent not found</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {agentsError instanceof Error
+ ? agentsError.message
+ : "This agent may have been archived or deleted."}
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => refetchAgents()}
+ >
+ Try again
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={() => navigation.push(paths.agents())}
+ >
+ Back to agents
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const isArchived = !!agent.archived_at;
+ const runtime = agent.runtime_id
+ ? runtimes.find((r) => r.id === agent.runtime_id) ?? null
+ : null;
+ const owner = agent.owner_id
+ ? members.find((m) => m.user_id === agent.owner_id) ?? null
+ : null;
+
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <DetailHeader
+ agent={agent}
+ presence={presence}
+ backHref={paths.agents()}
+ onArchive={() => setConfirmArchive(true)}
+ />
+
+ {isArchived && (
+ <div className="flex shrink-0 items-center gap-2 border-b bg-muted/50 px-6 py-2 text-xs text-muted-foreground">
+ <AlertCircle className="h-3.5 w-3.5 shrink-0" />
+ <span className="flex-1">
+ This agent is archived. It cannot be assigned or mentioned.
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-xs"
+ onClick={() => handleRestore(agent.id)}
+ >
+ Restore
+ </Button>
+ </div>
+ )}
+
+ <div className="grid flex-1 min-h-0 grid-cols-[320px_minmax(0,1fr)] gap-4 p-6">
+ <AgentDetailInspector
+ agent={agent}
+ runtime={runtime}
+ owner={owner}
+ presence={presence}
+ runtimes={runtimes}
+ members={members}
+ currentUserId={currentUser?.id ?? null}
+ onUpdate={handleUpdate}
+ />
+
+ <AgentOverviewPane
+ agent={agent}
+ runtimes={runtimes}
+ onUpdate={handleUpdate}
+ />
+ </div>
+
+ {confirmArchive && (
+ <Dialog
+ open
+ onOpenChange={(v) => {
+ if (!v) setConfirmArchive(false);
+ }}
+ >
+ <DialogContent className="max-w-sm" showCloseButton={false}>
+ <div className="flex items-center gap-3">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-destructive/10">
+ <AlertCircle className="h-5 w-5 text-destructive" />
+ </div>
+ <DialogHeader className="flex-1 gap-1">
+ <DialogTitle className="text-sm font-semibold">
+ Archive agent?
+ </DialogTitle>
+ <DialogDescription className="text-xs">
+ &quot;{agent.name}&quot; will be archived. It won&apos;t be
+ assignable or mentionable, but all history is preserved. You
+ can restore it later.
+ </DialogDescription>
+ </DialogHeader>
+ </div>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => setConfirmArchive(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ setConfirmArchive(false);
+ handleArchive(agent.id);
+ navigation.push(paths.agents());
+ }}
+ >
+ Archive
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )}
+ </div>
+ );
+}
+
+function DetailHeader({
+ agent,
+ presence,
+ backHref,
+ onArchive,
+}: {
+ agent: Agent;
+ presence: AgentPresenceDetail | null;
+ backHref: string;
+ onArchive: () => void;
+}) {
+ const isArchived = !!agent.archived_at;
+ const av = presence ? availabilityConfig[presence.availability] : null;
+ // Last-task state is intentionally not surfaced in the header — the
+ // Recent work section on this page already shows the same information
+ // (and richer: titles, timestamps, error messages). Showing "Completed"
+ // up here was redundant chrome.
+
+ return (
+ <PageHeader className="justify-between gap-3 px-5">
+ <div className="flex min-w-0 items-center gap-2">
+ <AppLink
+ href={backHref}
+ className="inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Agents
+ </AppLink>
+ <span className="text-muted-foreground/40">/</span>
+ <h1 className="truncate text-sm font-medium">{agent.name}</h1>
+ {!isArchived && av && presence && (
+ <span
+ className={`inline-flex items-center gap-1.5 rounded-md border px-1.5 py-0.5 text-xs ${av.textClass}`}
+ >
+ <span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} />
+ {av.label}
+ </span>
+ )}
+ </div>
+
+ {!isArchived && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<Button variant="ghost" size="icon-sm" />}
+ >
+ <MoreHorizontal className="h-4 w-4 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto">
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={onArchive}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ Archive Agent
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </PageHeader>
+ );
+}
+
+function BackHeader({ paths, title }: { paths: string; title: string }) {
+ return (
+ <PageHeader className="justify-between px-5">
+ <div className="flex items-center gap-2">
+ <AppLink
+ href={paths}
+ className="inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ {title}
+ </AppLink>
+ </div>
+ </PageHeader>
+ );
+}
+
+function DetailLoadingSkeleton() {
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <PageHeader className="px-5">
+ <Skeleton className="h-5 w-48" />
+ </PageHeader>
+ <div className="grid flex-1 min-h-0 grid-cols-[320px_minmax(0,1fr)] gap-4 p-6">
+ <div className="flex flex-col gap-4 rounded-lg border p-5">
+ <Skeleton className="h-14 w-14 rounded-lg" />
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-3 w-full" />
+ <div className="space-y-2">
+ <Skeleton className="h-3 w-3/4" />
+ <Skeleton className="h-3 w-2/3" />
+ <Skeleton className="h-3 w-1/2" />
+ </div>
+ </div>
+ <div className="flex flex-col gap-4 rounded-lg border p-6">
+ <Skeleton className="h-6 w-64" />
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-5/6" />
+ <Skeleton className="h-4 w-4/6" />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/agent-detail.tsx b/packages/views/agents/components/agent-detail.tsx
deleted file mode 100644
index 06e4707618..0000000000
--- a/packages/views/agents/components/agent-detail.tsx
+++ /dev/null
@@ -1,230 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import {
- Cloud,
- Monitor,
- FileText,
- BookOpenText,
- ListTodo,
- Trash2,
- AlertCircle,
- MoreHorizontal,
- Settings,
- KeyRound,
- Terminal,
-} from "lucide-react";
-import type { Agent, RuntimeDevice, MemberWithUser } from "@multica/core/types";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
- DialogFooter,
-} from "@multica/ui/components/ui/dialog";
-import {
- DropdownMenu,
- DropdownMenuTrigger,
- DropdownMenuContent,
- DropdownMenuItem,
-} from "@multica/ui/components/ui/dropdown-menu";
-import { Button } from "@multica/ui/components/ui/button";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { statusConfig } from "../config";
-import { InstructionsTab } from "./tabs/instructions-tab";
-import { SkillsTab } from "./tabs/skills-tab";
-import { TasksTab } from "./tabs/tasks-tab";
-import { SettingsTab } from "./tabs/settings-tab";
-import { EnvTab } from "./tabs/env-tab";
-import { CustomArgsTab } from "./tabs/custom-args-tab";
-
-function getRuntimeDevice(agent: Agent, runtimes: RuntimeDevice[]): RuntimeDevice | undefined {
- return runtimes.find((runtime) => runtime.id === agent.runtime_id);
-}
-
-type DetailTab = "instructions" | "skills" | "tasks" | "env" | "custom_args" | "settings";
-
-const detailTabs: { id: DetailTab; label: string; icon: typeof FileText }[] = [
- { id: "instructions", label: "Instructions", icon: FileText },
- { id: "skills", label: "Skills", icon: BookOpenText },
- { id: "tasks", label: "Tasks", icon: ListTodo },
- { id: "env", label: "Environment", icon: KeyRound },
- { id: "custom_args", label: "Custom Args", icon: Terminal },
- { id: "settings", label: "Settings", icon: Settings },
-];
-
-export function AgentDetail({
- agent,
- runtimes,
- members,
- currentUserId,
- onUpdate,
- onArchive,
- onRestore,
-}: {
- agent: Agent;
- runtimes: RuntimeDevice[];
- members: MemberWithUser[];
- currentUserId: string | null;
- onUpdate: (id: string, data: Partial<Agent>) => Promise<void>;
- onArchive: (id: string) => Promise<void>;
- onRestore: (id: string) => Promise<void>;
-}) {
- const st = statusConfig[agent.status];
- const runtimeDevice = getRuntimeDevice(agent, runtimes);
- const [activeTab, setActiveTab] = useState<DetailTab>("instructions");
- const [confirmArchive, setConfirmArchive] = useState(false);
- const isArchived = !!agent.archived_at;
-
- return (
- <div className="flex h-full flex-col">
- {/* Archive Banner */}
- {isArchived && (
- <div className="flex items-center gap-2 bg-muted/50 px-4 py-2 text-xs text-muted-foreground border-b">
- <AlertCircle className="h-3.5 w-3.5 shrink-0" />
- <span className="flex-1">This agent is archived. It cannot be assigned or mentioned.</span>
- <Button variant="outline" size="sm" className="h-6 text-xs" onClick={() => onRestore(agent.id)}>
- Restore
- </Button>
- </div>
- )}
-
- {/* Header */}
- <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">
- <ActorAvatar actorType="agent" actorId={agent.id} size={28} className={`rounded-md ${isArchived ? "opacity-50" : ""}`} disableHoverCard />
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <h2 className={`text-sm font-semibold truncate ${isArchived ? "text-muted-foreground" : ""}`}>{agent.name}</h2>
- {isArchived ? (
- <span className="rounded-md bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
- Archived
- </span>
- ) : (
- <span className={`flex items-center gap-1.5 text-xs ${st.color}`}>
- <span className={`h-1.5 w-1.5 rounded-full ${st.dot}`} />
- {st.label}
- </span>
- )}
- <span className="flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
- {agent.runtime_mode === "cloud" ? (
- <Cloud className="h-3 w-3" />
- ) : (
- <Monitor className="h-3 w-3" />
- )}
- {runtimeDevice?.name ?? (agent.runtime_mode === "cloud" ? "Cloud" : "Local")}
- </span>
- </div>
- </div>
- {!isArchived && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button variant="ghost" size="icon-sm" />
- }
- >
- <MoreHorizontal className="h-4 w-4 text-muted-foreground" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuItem
- className="text-destructive"
- onClick={() => setConfirmArchive(true)}
- >
- <Trash2 className="h-3.5 w-3.5" />
- Archive Agent
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </div>
-
- {/* Tabs */}
- <div className="flex border-b px-6">
- {detailTabs.map((tab) => (
- <button
- key={tab.id}
- onClick={() => setActiveTab(tab.id)}
- className={`flex items-center gap-1.5 border-b-2 px-3 py-2.5 text-xs font-medium transition-colors ${
- activeTab === tab.id
- ? "border-primary text-foreground"
- : "border-transparent text-muted-foreground hover:text-foreground"
- }`}
- >
- <tab.icon className="h-3.5 w-3.5" />
- {tab.label}
- </button>
- ))}
- </div>
-
- {/* Tab Content */}
- <div className="flex-1 overflow-y-auto p-6">
- {activeTab === "instructions" && (
- <InstructionsTab
- agent={agent}
- onSave={(instructions) => onUpdate(agent.id, { instructions })}
- />
- )}
- {activeTab === "skills" && (
- <SkillsTab agent={agent} />
- )}
- {activeTab === "tasks" && <TasksTab agent={agent} />}
- {activeTab === "env" && (
- <EnvTab
- agent={agent}
- readOnly={agent.custom_env_redacted}
- onSave={(updates) => onUpdate(agent.id, updates)}
- />
- )}
- {activeTab === "custom_args" && (
- <CustomArgsTab
- agent={agent}
- runtimeDevice={runtimeDevice}
- onSave={(updates) => onUpdate(agent.id, updates)}
- />
- )}
- {activeTab === "settings" && (
- <SettingsTab
- agent={agent}
- runtimes={runtimes}
- members={members}
- currentUserId={currentUserId}
- onSave={(updates) => onUpdate(agent.id, updates)}
- />
- )}
- </div>
-
- {/* Archive Confirmation */}
- {confirmArchive && (
- <Dialog open onOpenChange={(v) => { if (!v) setConfirmArchive(false); }}>
- <DialogContent className="max-w-sm" showCloseButton={false}>
- <div className="flex items-center gap-3">
- <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-destructive/10">
- <AlertCircle className="h-5 w-5 text-destructive" />
- </div>
- <DialogHeader className="flex-1 gap-1">
- <DialogTitle className="text-sm font-semibold">Archive agent?</DialogTitle>
- <DialogDescription className="text-xs">
- &quot;{agent.name}&quot; will be archived. It won&apos;t be assignable or mentionable, but all history is preserved. You can restore it later.
- </DialogDescription>
- </DialogHeader>
- </div>
- <DialogFooter>
- <Button variant="ghost" onClick={() => setConfirmArchive(false)}>
- Cancel
- </Button>
- <Button
- variant="destructive"
- onClick={() => {
- setConfirmArchive(false);
- onArchive(agent.id);
- }}
- >
- Archive
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )}
- </div>
- );
-}
diff --git a/packages/views/agents/components/agent-list-item.tsx b/packages/views/agents/components/agent-list-item.tsx
index fe4aacc6cc..d3cc530a4e 100644
--- a/packages/views/agents/components/agent-list-item.tsx
+++ b/packages/views/agents/components/agent-list-item.tsx
@@ -1,51 +1,354 @@
"use client";
-import { Cloud, Monitor } from "lucide-react";
-import type { Agent } from "@multica/core/types";
+import { Cloud, Lock, Monitor } from "lucide-react";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import {
+ type AgentActivity,
+ type AgentPresenceDetail,
+ summarizeActivityWindow,
+} from "@multica/core/agents";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "../../common/actor-avatar";
-import { statusConfig } from "../config";
+import { AppLink } from "../../navigation";
+import { availabilityConfig, taskStateConfig } from "../presence";
+import { AgentPresenceIndicator } from "./agent-presence-indicator";
+import { AgentRowActions } from "./agent-row-actions";
+import { Sparkline } from "./sparkline";
+
+// Shared grid template used by both the list header and every row, so the
+// sticky header columns stay aligned with the rows below it.
+//
+// Why grid (not <Table table-fixed>): table-fixed forces every column to a
+// declared width, which means the Status column was always reserving space
+// for the worst case ("Working · 0 / 6 · +5 queued"), even when no agent in
+// the workspace was in that state. Switching to grid + `max-content` lets the
+// column shrink automatically when the longest cell is just "Available", and
+// only widen when there's an agent that actually needs the room. The freed
+// space flows into the Agent column (the primary content), via its `1.6fr`
+// share — same ratio Skills uses, so the two list pages read as one family.
+//
+// Leading-avatar column (1.75rem) is a dedicated grid track so the header's
+// "Agent" label sits on the same x as the row's name text. Without this the
+// avatar (28px) + the internal flex gap pushes the name 40px right of the
+// header label, which reads as misalignment. Same pattern is used in Runtimes
+// (icon-box and Health dot extracted into their own tracks).
+//
+// Responsive strategy mirrors the previous table:
+// <md → [avatar] Agent · Status (compact dot only) · Actions
+// md+ → adds Last run + Runtime + Runs
+// lg+ → adds Activity sparkline
+// Cells use `hidden md:block` / `hidden lg:block` so they participate in the
+// grid only at their breakpoint; the grid template at each tier matches the
+// number of visible cells exactly.
+//
+// Two presence columns at md+ (Status + Last run) instead of one merged
+// cell — splitting them lets the user scan each axis independently. The
+// dot column is the same 3-color availability everywhere; the Last run
+// column shows the task icon + label (running/completed/failed/etc).
+export const AGENT_LIST_GRID =
+ "grid items-center gap-4 " +
+ "grid-cols-[1.75rem_minmax(0,1fr)_max-content_2.5rem] " +
+ "md:grid-cols-[1.75rem_minmax(0,1.4fr)_5rem_minmax(0,max-content)_minmax(0,0.8fr)_4rem_2.5rem] " +
+ "lg:grid-cols-[1.75rem_minmax(0,1.5fr)_5rem_minmax(0,max-content)_minmax(0,0.8fr)_5rem_4rem_2.5rem]";
+
+interface AgentListItemProps {
+ agent: Agent;
+ runtime: AgentRuntime | null;
+ presence: AgentPresenceDetail | null | undefined;
+ // 30d activity series for this agent. Page derives once for the whole
+ // workspace and passes a row-specific slice here, so the row component
+ // doesn't subscribe to its own query (avoids N timers / N subscriptions).
+ // The list only surfaces the trailing 7 days; we still take the 30d
+ // shape so the cache stays aligned with the agent detail panel.
+ activity: AgentActivity | null | undefined;
+ // 30-day cumulative run count for the RUNS column. Same single-source pattern.
+ runCount: number | null | undefined;
+ // Inline owner avatar — non-null when the page wants to attribute the
+ // agent to a teammate (typically All scope on someone else's agent).
+ // The page does the "scope === all && owner !== me" decision so the row
+ // stays pure presentation.
+ ownerIdToShow: string | null;
+ // True when the current user can archive / cancel-tasks on this agent.
+ // Mirrors the back-end's canManageAgent check; the row uses it to gate
+ // entries in the actions dropdown.
+ canManage: boolean;
+ // Page-level callback to open Create dialog with this agent as a
+ // template (Duplicate action).
+ onDuplicate: (agent: Agent) => void;
+ href: string;
+}
export function AgentListItem({
agent,
- isSelected,
- onClick,
-}: {
- agent: Agent;
- isSelected: boolean;
- onClick: () => void;
-}) {
- const st = statusConfig[agent.status];
+ runtime,
+ presence,
+ activity,
+ runCount,
+ ownerIdToShow,
+ canManage,
+ onDuplicate,
+ href,
+}: AgentListItemProps) {
const isArchived = !!agent.archived_at;
+ const isPrivate = agent.visibility === "private";
+ const isCloud = agent.runtime_mode === "cloud";
+ const RuntimeIcon = isCloud ? Cloud : Monitor;
+ const runtimeLabel = runtime?.name ?? (isCloud ? "Cloud" : "Local");
return (
- <button
- onClick={onClick}
- className={`flex w-full items-center gap-3 px-4 py-3 text-left transition-colors ${
- isSelected ? "bg-accent" : "hover:bg-accent/50"
- }`}
+ <AppLink
+ href={href}
+ className={`${AGENT_LIST_GRID} group border-b px-4 py-3 text-sm transition-colors last:border-b-0 hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none`}
>
- <ActorAvatar actorType="agent" actorId={agent.id} size={32} className={`rounded-lg ${isArchived ? "opacity-50 grayscale" : ""}`} disableHoverCard />
+ {/* Avatar — dedicated leading column so the header label "Agent"
+ aligns with the name text below it. */}
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size={28}
+ className={`rounded-md ${isArchived ? "opacity-50 grayscale" : ""}`}
+ showStatusDot
+ />
- <div className="min-w-0 flex-1">
+ {/* Agent — primary text column, eats remaining space. */}
+ <div className="min-w-0">
<div className="flex items-center gap-2">
- <span className={`truncate text-sm font-medium ${isArchived ? "text-muted-foreground" : ""}`}>{agent.name}</span>
- {agent.runtime_mode === "cloud" ? (
- <Cloud className="h-3 w-3 text-muted-foreground" />
- ) : (
- <Monitor className="h-3 w-3 text-muted-foreground" />
+ <span
+ className={`truncate font-medium ${
+ isArchived ? "text-muted-foreground" : ""
+ }`}
+ >
+ {agent.name}
+ </span>
+ {/* Lock = private visibility — back-end rejects assignment by
+ non-owners, so flag it visually. We deliberately do NOT
+ filter private agents out of the list (mirrors server's
+ ListAgents behaviour); the icon warns the viewer that
+ picking this in a picker will fail. */}
+ {isPrivate && !isArchived && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Lock className="h-3 w-3 shrink-0 text-muted-foreground/60" />
+ }
+ />
+ <TooltipContent>
+ Private — only the owner can assign work
+ </TooltipContent>
+ </Tooltip>
)}
- </div>
- <div className="flex items-center gap-1.5 mt-0.5">
- {isArchived ? (
- <span className="text-xs text-muted-foreground">Archived</span>
- ) : (
- <>
- <span className={`h-1.5 w-1.5 rounded-full ${st.dot}`} />
- <span className={`text-xs ${st.color}`}>{st.label}</span>
- </>
+ {/* Owner attribution — only set in "All" scope when the agent
+ isn't yours. Tiny avatar (14px) keeps it lightweight; the
+ hover card on the agent's main avatar already covers the
+ full owner detail. */}
+ {ownerIdToShow && (
+ <ActorAvatar
+ actorType="member"
+ actorId={ownerIdToShow}
+ size={14}
+ />
+ )}
+ {isArchived && (
+ <span className="shrink-0 rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
+ Archived
+ </span>
)}
</div>
+ <div
+ className={`mt-0.5 line-clamp-1 text-xs ${
+ agent.description
+ ? "text-muted-foreground"
+ : "italic text-muted-foreground/50"
+ }`}
+ >
+ {agent.description || "No description"}
+ </div>
</div>
- </button>
+
+ {/* Status — availability dimension only. Compact dot under md;
+ dot + label at md+. Always 3 colours. */}
+ <div className="flex items-center">
+ {isArchived ? (
+ <span className="text-xs text-muted-foreground">—</span>
+ ) : (
+ <>
+ <span className="md:hidden">
+ <AgentPresenceIndicator detail={presence} compact />
+ </span>
+ <span className="hidden md:inline-flex">
+ <AvailabilityCell presence={presence} />
+ </span>
+ </>
+ )}
+ </div>
+
+ {/* Last run — md+. Task icon + label + (running counts | reason | time).
+ Dedicated column so the user can scan "what just happened" without
+ merging it into the availability cell. */}
+ <div className="hidden items-center md:flex">
+ {isArchived ? (
+ <span className="text-xs text-muted-foreground">—</span>
+ ) : (
+ <LastRunCell presence={presence} />
+ )}
+ </div>
+
+ {/* Runtime — md+. Sans-font label fits ~25% more chars per pixel than
+ the previous mono treatment, so most hostnames no longer truncate. */}
+ <div className="hidden min-w-0 items-center gap-1.5 text-xs text-muted-foreground md:flex">
+ <RuntimeIcon className="h-3 w-3 shrink-0" />
+ <Tooltip>
+ <TooltipTrigger
+ render={<span className="min-w-0 truncate">{runtimeLabel}</span>}
+ />
+ <TooltipContent>{runtimeLabel}</TooltipContent>
+ </Tooltip>
+ </div>
+
+ {/* Activity (7d) — lg+. The 7d sparkline is sliced off the 30d
+ workspace cache here (single source of truth shared with the
+ detail panel); no extra request. */}
+ <div className="hidden lg:block">
+ {isArchived ? (
+ <span className="text-xs text-muted-foreground/50">—</span>
+ ) : !activity ? (
+ <span
+ className="inline-block animate-pulse rounded bg-muted/60"
+ style={{ width: 64, height: 20 }}
+ />
+ ) : (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <div className="inline-flex cursor-default items-center">
+ <Sparkline
+ buckets={summarizeActivityWindow(activity, 7).buckets}
+ width={64}
+ height={20}
+ />
+ </div>
+ }
+ />
+ <TooltipContent>
+ <ActivityTooltip activity={activity} />
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+
+ {/* Runs (30d) — md+. tabular-nums + right-align keeps the digit column
+ visually clean across orders of magnitude. */}
+ <div className="hidden text-right font-mono text-xs tabular-nums text-muted-foreground md:block">
+ {runCount == null ? "—" : runCount.toLocaleString()}
+ </div>
+
+ {/* Actions — kebab dropdown, always visible. Empty cell is preserved
+ (the column has fixed width) when the user has no operable
+ actions, so column alignment stays stable across rows. */}
+ <div className="flex justify-end">
+ <AgentRowActions
+ agent={agent}
+ presence={presence}
+ canManage={canManage}
+ onDuplicate={onDuplicate}
+ />
+ </div>
+ </AppLink>
+ );
+}
+
+// Availability cell — dot + label, colour from availabilityConfig. Three
+// states only; the colour reflects "can the agent take work right now".
+function AvailabilityCell({
+ presence,
+}: {
+ presence: AgentPresenceDetail | null | undefined;
+}) {
+ if (!presence) {
+ return <span className="inline-flex h-3 w-16 animate-pulse rounded bg-muted/60" />;
+ }
+ const av = availabilityConfig[presence.availability];
+ return (
+ <span className="inline-flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${av.dotClass}`} />
+ <span className={`text-xs ${av.textClass}`}>{av.label}</span>
+ </span>
+ );
+}
+
+// Last-run cell — task icon + label, with running counts only when active.
+// No timestamp: it eats horizontal space and the relative age of a
+// completed task isn't actionable in a scan. Hidden when idle so brand-
+// new agents show "—" instead of "Idle" everywhere.
+function LastRunCell({
+ presence,
+}: {
+ presence: AgentPresenceDetail | null | undefined;
+}) {
+ if (!presence) {
+ return <span className="inline-flex h-3 w-20 animate-pulse rounded bg-muted/60" />;
+ }
+ if (presence.lastTask === "idle") {
+ return <span className="text-xs text-muted-foreground/50">—</span>;
+ }
+ const ts = taskStateConfig[presence.lastTask];
+ const isRunning = presence.lastTask === "running";
+ const counts =
+ isRunning && presence.queuedCount > 0
+ ? `${presence.runningCount}/${presence.capacity} +${presence.queuedCount}q`
+ : isRunning
+ ? `${presence.runningCount}/${presence.capacity}`
+ : null;
+ return (
+ <span className="inline-flex min-w-0 items-center gap-1 text-xs">
+ <ts.icon className={`h-3 w-3 shrink-0 ${ts.textClass}`} />
+ <span className={`shrink-0 ${ts.textClass}`}>{ts.label}</span>
+ {counts && (
+ <span className="truncate text-muted-foreground">{counts}</span>
+ )}
+ </span>
+ );
+}
+
+/**
+ * Tooltip body for the activity sparkline. Header = window label, body =
+ * the actual counts (rolled up from the same 7-day slice the bars
+ * render). Two short lines so the eye lands on the numbers immediately
+ * on hover.
+ */
+function ActivityTooltip({ activity }: { activity: AgentActivity }) {
+ const summary = summarizeActivityWindow(activity, 7);
+ const { totalRuns, totalFailed } = summary;
+ const { daysSinceCreated } = activity;
+
+ // Header: when the agent is younger than the rendered window, label by
+ // age so an empty sparkline reads as "new agent" not "broken agent".
+ const isPartial = daysSinceCreated < 7;
+ const headerText = isPartial
+ ? `Created ${daysSinceCreated === 0 ? "today" : `${daysSinceCreated} day${daysSinceCreated === 1 ? "" : "s"} ago`}`
+ : "Last 7 days";
+
+ let bodyText: string;
+ if (totalRuns === 0) {
+ bodyText = "No activity";
+ } else {
+ const failedFragment =
+ totalFailed > 0
+ ? ` · ${totalFailed} failed (${Math.round((totalFailed / totalRuns) * 100)}%)`
+ : "";
+ bodyText = `${totalRuns} run${totalRuns === 1 ? "" : "s"}${failedFragment}`;
+ }
+
+ return (
+ <div className="flex flex-col gap-0.5">
+ <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
+ {headerText}
+ </span>
+ <span className="text-xs">{bodyText}</span>
+ </div>
);
}
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
new file mode 100644
index 0000000000..ed05989d20
--- /dev/null
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import { useState } from "react";
+import {
+ Activity,
+ BookOpenText,
+ FileText,
+ KeyRound,
+ Terminal,
+} from "lucide-react";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { ActivityTab } from "./tabs/activity-tab";
+import { InstructionsTab } from "./tabs/instructions-tab";
+import { SkillsTab } from "./tabs/skills-tab";
+import { EnvTab } from "./tabs/env-tab";
+import { CustomArgsTab } from "./tabs/custom-args-tab";
+
+type DetailTab =
+ | "activity"
+ | "instructions"
+ | "skills"
+ | "env"
+ | "custom_args";
+
+const detailTabs: {
+ id: DetailTab;
+ label: string;
+ icon: typeof FileText;
+}[] = [
+ { id: "activity", label: "Activity", icon: Activity },
+ { id: "instructions", label: "Instructions", icon: FileText },
+ { id: "skills", label: "Skills", icon: BookOpenText },
+ { id: "env", label: "Environment", icon: KeyRound },
+ { id: "custom_args", label: "Custom Args", icon: Terminal },
+];
+
+interface AgentOverviewPaneProps {
+ agent: Agent;
+ runtimes: AgentRuntime[];
+ onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+}
+
+/**
+ * Right-pane on the agent detail page. Five tabs of equal weight:
+ *
+ * - Activity (default) — what the agent is doing now / how it's been doing /
+ * what it just finished. The "watch state" surface.
+ * - Instructions / Skills / Env / Custom Args — four editing surfaces.
+ *
+ * The previous Settings tab was deleted because every field on it is now
+ * inline-editable in the inspector (left column) — runtime / model /
+ * visibility / concurrency via PropRow + Picker, and avatar / name /
+ * description via popover. Two entry points for the same writes was just
+ * extra concept count without extra capability.
+ *
+ * Activity is the landing tab because most visits to this page are diagnostic
+ * ("what is this agent doing / why did it fail?"), not configuration tweaks.
+ *
+ * **Unsaved-changes guard**: every config tab reports its dirty state up via
+ * `onDirtyChange`. Switching to another tab while the active tab is dirty
+ * pops a confirm dialog — without it, switching tabs would silently drop
+ * unsaved edits because each tab manages its own local state and remounts on
+ * tab change.
+ */
+export function AgentOverviewPane({
+ agent,
+ runtimes,
+ onUpdate,
+}: AgentOverviewPaneProps) {
+ const [activeTab, setActiveTab] = useState<DetailTab>("activity");
+ const [activeDirty, setActiveDirty] = useState(false);
+ // Holds the destination when a tab change is intercepted by the dirty
+ // guard. Null means no pending change. The AlertDialog reads non-null as
+ // "open".
+ const [pendingTab, setPendingTab] = useState<DetailTab | null>(null);
+
+ const runtime = agent.runtime_id
+ ? runtimes.find((r) => r.id === agent.runtime_id) ?? null
+ : null;
+
+ const requestTabChange = (next: DetailTab) => {
+ if (next === activeTab) return;
+ if (activeDirty) {
+ setPendingTab(next);
+ return;
+ }
+ setActiveTab(next);
+ };
+
+ const commitTabChange = () => {
+ if (pendingTab) {
+ setActiveTab(pendingTab);
+ // The new tab mounts fresh; its effect will report its own dirty state.
+ // We pre-clear so the guard can't trip from stale state on the way in.
+ setActiveDirty(false);
+ setPendingTab(null);
+ }
+ };
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-hidden rounded-lg border bg-background">
+ <div className="flex shrink-0 items-center gap-0 border-b px-4">
+ {detailTabs.map((tab) => (
+ <button
+ key={tab.id}
+ type="button"
+ onClick={() => requestTabChange(tab.id)}
+ className={`flex items-center gap-1.5 border-b-2 px-3 py-2.5 text-xs font-medium transition-colors ${
+ activeTab === tab.id
+ ? "border-foreground text-foreground"
+ : "border-transparent text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ <tab.icon className="h-3.5 w-3.5" />
+ {tab.label}
+ </button>
+ ))}
+ </div>
+
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ {activeTab === "activity" && <ActivityTab agent={agent} />}
+ {activeTab === "instructions" && (
+ <TabContent>
+ <InstructionsTab
+ agent={agent}
+ onSave={(instructions) => onUpdate(agent.id, { instructions })}
+ onDirtyChange={setActiveDirty}
+ />
+ </TabContent>
+ )}
+ {activeTab === "skills" && (
+ <TabContent>
+ <SkillsTab agent={agent} />
+ </TabContent>
+ )}
+ {activeTab === "env" && (
+ <TabContent>
+ <EnvTab
+ agent={agent}
+ readOnly={agent.custom_env_redacted}
+ onSave={(updates) => onUpdate(agent.id, updates)}
+ onDirtyChange={setActiveDirty}
+ />
+ </TabContent>
+ )}
+ {activeTab === "custom_args" && (
+ <TabContent>
+ <CustomArgsTab
+ agent={agent}
+ runtimeDevice={runtime ?? undefined}
+ onSave={(updates) => onUpdate(agent.id, updates)}
+ onDirtyChange={setActiveDirty}
+ />
+ </TabContent>
+ )}
+ </div>
+
+ {pendingTab !== null && (
+ <AlertDialog
+ open
+ onOpenChange={(v) => {
+ if (!v) setPendingTab(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Discard unsaved changes?</AlertDialogTitle>
+ <AlertDialogDescription>
+ You have unsaved changes in this tab. Leaving now will discard
+ them.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep editing</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={commitTabChange}
+ >
+ Discard changes
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+ </div>
+ );
+}
+
+// Centred, max-width container shared by every config tab. `h-full flex
+// flex-col` lets a tab opt into "fill the viewport" by giving its root
+// element `flex-1 min-h-0` (Instructions does this so the editor expands
+// instead of pushing the Save row off-screen). Tabs that don't opt in
+// behave as natural-height blocks; long content (e.g. Settings, long Skills
+// list) still scrolls via the parent's overflow-y-auto.
+function TabContent({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="mx-auto flex h-full max-w-2xl flex-col p-6">{children}</div>
+ );
+}
diff --git a/packages/views/agents/components/agent-presence-indicator.tsx b/packages/views/agents/components/agent-presence-indicator.tsx
new file mode 100644
index 0000000000..893a35e0c0
--- /dev/null
+++ b/packages/views/agents/components/agent-presence-indicator.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import type { AgentPresenceDetail } from "@multica/core/agents";
+import { availabilityConfig, taskStateConfig } from "../presence";
+
+interface PresenceIndicatorProps {
+ // null/undefined = still loading. Caller passes the detail computed at
+ // the page level (or via the useAgentPresenceDetail hook for single-agent
+ // views). Keeping this as a prop avoids per-row hook subscriptions in
+ // long lists.
+ detail: AgentPresenceDetail | null | undefined;
+ // Compact = dot only, no label / no last-task chip. Used in dense rows.
+ compact?: boolean;
+}
+
+/**
+ * Renders an agent's two-dimension presence: an availability dot + an
+ * optional last-task chip. The dot's colour reads only from the
+ * availability dimension (3 colours), so a runtime-healthy agent whose
+ * last task failed shows a green dot + a red "Failed" chip — the dot
+ * stops being sticky-red.
+ *
+ * Compact mode collapses to dot-only — used in dense surfaces where the
+ * full chip would crowd the row.
+ *
+ * Pure presentation — takes the already-derived detail object as a prop.
+ * The page-level component is responsible for sourcing it (via
+ * `useAgentPresenceDetail` for a single agent, or `useWorkspacePresenceMap`
+ * for lists).
+ */
+export function AgentPresenceIndicator({
+ detail,
+ compact,
+}: PresenceIndicatorProps) {
+ if (!detail) {
+ return compact ? (
+ <Skeleton className="h-1.5 w-1.5 rounded-full" />
+ ) : (
+ <Skeleton className="h-3 w-24 rounded" />
+ );
+ }
+
+ const av = availabilityConfig[detail.availability];
+ const ts = taskStateConfig[detail.lastTask];
+ const isRunning = detail.lastTask === "running";
+ const showQueueBadge = isRunning && detail.queuedCount > 0;
+
+ if (compact) {
+ return (
+ <span
+ className="inline-flex items-center"
+ title={`${av.label}${detail.lastTask !== "idle" ? ` · ${ts.label}` : ""}`}
+ >
+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${av.dotClass}`} />
+ </span>
+ );
+ }
+
+ return (
+ <span className="inline-flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
+ {/* Availability — dot + label. Single dimension, single colour. */}
+ <span className="inline-flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 shrink-0 rounded-full ${av.dotClass}`} />
+ <span className={`text-xs ${av.textClass}`}>{av.label}</span>
+ </span>
+
+ {/* Last task — separator + label, with running counts when active.
+ Hidden for `idle` to keep brand-new agents clean. */}
+ {detail.lastTask !== "idle" && (
+ <span className="inline-flex items-center gap-1">
+ <span className="text-xs text-muted-foreground">·</span>
+ <span className={`text-xs ${ts.textClass}`}>{ts.label}</span>
+ {isRunning && (
+ <span className="font-mono text-xs tabular-nums text-muted-foreground">
+ {detail.runningCount} / {detail.capacity}
+ </span>
+ )}
+ {showQueueBadge && (
+ <span className="rounded-md bg-muted px-1 py-0 text-xs font-medium text-muted-foreground">
+ +{detail.queuedCount} queued
+ </span>
+ )}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/packages/views/agents/components/agent-profile-card.tsx b/packages/views/agents/components/agent-profile-card.tsx
index 318f53e79a..7d1300ab33 100644
--- a/packages/views/agents/components/agent-profile-card.tsx
+++ b/packages/views/agents/components/agent-profile-card.tsx
@@ -1,15 +1,21 @@
"use client";
-import { Cloud, Monitor, Wifi, WifiOff } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import type { Agent, AgentRuntime } from "@multica/core/types";
+import { useAgentPresenceDetail } from "@multica/core/agents";
import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ deriveRuntimeHealth,
+ type RuntimeHealth,
+} from "@multica/core/runtimes";
import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import { useWorkspacePaths } from "@multica/core/paths";
import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { statusConfig } from "../config";
-import { formatLastSeen } from "../../runtimes/utils";
+import { AppLink } from "../../navigation";
+import { HealthIcon } from "../../runtimes/components/shared";
+import { availabilityConfig } from "../presence";
interface AgentProfileCardProps {
agentId: string;
@@ -17,9 +23,10 @@ interface AgentProfileCardProps {
export function AgentProfileCard({ agentId }: AgentProfileCardProps) {
const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
const { data: agents = [], isLoading: agentsLoading } = useQuery(agentListOptions(wsId));
- const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
const agent = agents.find((a) => a.id === agentId);
@@ -41,10 +48,10 @@ export function AgentProfileCard({ agentId }: AgentProfileCardProps) {
);
}
- const runtime = runtimes.find((r) => r.id === agent.runtime_id) ?? null;
const owner = agent.owner_id
? members.find((m) => m.user_id === agent.owner_id) ?? null
: null;
+ const runtime = runtimes.find((r) => r.id === agent.runtime_id) ?? null;
const isArchived = !!agent.archived_at;
const initials = agent.name
.split(" ")
@@ -54,8 +61,14 @@ export function AgentProfileCard({ agentId }: AgentProfileCardProps) {
.slice(0, 2);
return (
- <div className="flex flex-col gap-3 text-left">
- {/* Header */}
+ // `group` enables the hover-only Detail link on the top-right —
+ // it fades in only when the user is hovering the card chrome,
+ // staying out of the way during a quick glance.
+ <div className="group flex flex-col gap-3 text-left">
+ {/* Header — avatar + name + availability on the left, "Detail →" link
+ on the right (hover-only). Card stays minimal: only the 3-state
+ availability dot is surfaced here; last-task state lives in the
+ agents list and the agent detail page. */}
<div className="flex items-start gap-3">
<ActorAvatarBase
name={agent.name}
@@ -74,8 +87,18 @@ export function AgentProfileCard({ agentId }: AgentProfileCardProps) {
</span>
)}
</div>
- <AgentStatusLine agent={agent} />
+ {!isArchived && (
+ <AgentAvailabilityLine wsId={wsId} agentId={agent.id} />
+ )}
</div>
+ {!isArchived && (
+ <AppLink
+ href={p.agentDetail(agent.id)}
+ className="mr-1 mt-0.5 shrink-0 text-xs font-normal text-brand opacity-0 transition-opacity group-hover:opacity-100"
+ >
+ Detail →
+ </AppLink>
+ )}
</div>
{/* Description */}
@@ -85,10 +108,11 @@ export function AgentProfileCard({ agentId }: AgentProfileCardProps) {
</p>
)}
- {/* Meta rows */}
+ {/* Meta rows — minimal set: runtime (where it lives), skills (what
+ it knows), owner (who manages it). Model is intentionally
+ omitted — power-user detail lives on the detail page. */}
<div className="flex flex-col gap-1.5 text-xs">
<RuntimeRow agent={agent} runtime={runtime} />
- {agent.model && <MetaRow label="Model" value={agent.model} mono />}
{agent.skills.length > 0 && (
<SkillsRow skills={agent.skills.map((s) => s.name)} />
)}
@@ -98,16 +122,37 @@ export function AgentProfileCard({ agentId }: AgentProfileCardProps) {
);
}
-function AgentStatusLine({ agent }: { agent: Agent }) {
- const st = statusConfig[agent.status];
+// Compact availability line under the agent name — single 3-state signal
+// (online / unstable / offline). Last-task state is intentionally NOT
+// shown here; it belongs in the agents list and the detail page where
+// there's room for icon + label + reason without crowding the popover.
+function AgentAvailabilityLine({
+ wsId,
+ agentId,
+}: {
+ wsId: string | undefined;
+ agentId: string;
+}) {
+ const detail = useAgentPresenceDetail(wsId, agentId);
+ if (detail === "loading") {
+ return <Skeleton className="mt-0.5 h-3 w-16" />;
+ }
+ const av = availabilityConfig[detail.availability];
return (
- <div className="mt-0.5 flex items-center gap-1.5">
- <span className={`h-1.5 w-1.5 rounded-full ${st.dot}`} />
- <span className={`text-xs ${st.color}`}>{st.label}</span>
+ <div className="mt-0.5 inline-flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} />
+ <span className={`text-xs ${av.textClass}`}>{av.label}</span>
</div>
);
}
+// Compact runtime row — wifi-style health icon + runtime name. The icon
+// shape (Wifi / WifiOff) plus colour reflects the live runtime health
+// derived from runtime + clock; cloud runtimes always read as online.
+// This is duplicate signal with the availability dot above by design —
+// the dot is the agent's effective availability (which mostly tracks
+// runtime health), and seeing the same wifi icon next to the runtime
+// name confirms WHICH runtime is the one currently in the dot's state.
function RuntimeRow({
agent,
runtime,
@@ -116,34 +161,19 @@ function RuntimeRow({
runtime: AgentRuntime | null;
}) {
const isCloud = agent.runtime_mode === "cloud";
- const Icon = isCloud ? Cloud : Monitor;
- const isOnline = runtime?.status === "online";
- // Cloud runtimes are always reachable from the user's perspective.
- const showOnline = isCloud || isOnline;
-
- let detail: string;
- if (isCloud) {
- detail = runtime?.name ?? "Cloud";
- } else if (runtime) {
- detail = isOnline
- ? runtime.name
- : `${runtime.name} · last seen ${formatLastSeen(runtime.last_seen_at)}`;
- } else {
- detail = "Unknown runtime";
- }
-
+ const health: RuntimeHealth = isCloud
+ ? "online"
+ : runtime
+ ? deriveRuntimeHealth(runtime, Date.now())
+ : "offline";
+ const label = runtime?.name ?? (isCloud ? "Cloud" : "Unknown runtime");
return (
<div className="flex items-center gap-1.5">
<span className="w-12 shrink-0 text-muted-foreground">Runtime</span>
- <Icon className="h-3 w-3 shrink-0 text-muted-foreground" />
- <span className="truncate" title={detail}>
- {detail}
+ <HealthIcon health={health} className="h-3 w-3 shrink-0" />
+ <span className="min-w-0 truncate" title={label}>
+ {label}
</span>
- {showOnline ? (
- <Wifi className="ml-auto h-3 w-3 shrink-0 text-success" />
- ) : (
- <WifiOff className="ml-auto h-3 w-3 shrink-0 text-muted-foreground" />
- )}
</div>
);
}
diff --git a/packages/views/agents/components/agent-row-actions.tsx b/packages/views/agents/components/agent-row-actions.tsx
new file mode 100644
index 0000000000..5d6c1d36e4
--- /dev/null
+++ b/packages/views/agents/components/agent-row-actions.tsx
@@ -0,0 +1,289 @@
+"use client";
+
+import { useState } from "react";
+import {
+ AlertCircle,
+ Copy,
+ MoreHorizontal,
+ RotateCcw,
+ Square,
+ Trash2,
+} from "lucide-react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { Agent } from "@multica/core/types";
+import type { AgentPresenceDetail } from "@multica/core/agents";
+import { api } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+
+interface AgentRowActionsProps {
+ agent: Agent;
+ presence: AgentPresenceDetail | null | undefined;
+ // True when the current user can manage this agent (owner of agent or
+ // workspace admin/owner). Mirrors the back-end's canManageAgent check —
+ // the server is still the source of truth, this only hides UI for ops
+ // the user can't perform.
+ canManage: boolean;
+ // Called when the user picks "Duplicate" — the page opens a Create
+ // dialog pre-populated with this agent's config as a template.
+ onDuplicate: (agent: Agent) => void;
+}
+
+/**
+ * Per-row dropdown menu for the agents list. The set of actions is derived
+ * from (a) the agent's lifecycle state (active vs archived) and (b) the
+ * caller's permission level. If no actions apply, the trigger is omitted so
+ * the row renders an empty cell (column width still preserved by the parent
+ * `<TableCell className="w-10" />`).
+ *
+ * All triggers stop event propagation so clicks don't bubble up to the
+ * row's navigate-to-detail handler.
+ */
+export function AgentRowActions({
+ agent,
+ presence,
+ canManage,
+ onDuplicate,
+}: AgentRowActionsProps) {
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+
+ const [confirmArchive, setConfirmArchive] = useState(false);
+ const [confirmCancel, setConfirmCancel] = useState(false);
+
+ const isArchived = !!agent.archived_at;
+ const runningCount = presence?.runningCount ?? 0;
+ const queuedCount = presence?.queuedCount ?? 0;
+ const hasActiveWork = runningCount + queuedCount > 0;
+
+ // Derive which menu items to render. Doing this once here keeps the JSX
+ // below a flat list of conditionals rather than a tangle of role/state
+ // branches.
+ const showStop = canManage && !isArchived && hasActiveWork;
+ const showDuplicate = !isArchived; // any workspace member can duplicate
+ const showArchive = canManage && !isArchived;
+ const showRestore = canManage && isArchived;
+
+ const hasAnyAction = showStop || showDuplicate || showArchive || showRestore;
+
+ const invalidateAgents = () => {
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ };
+
+ const handleArchive = async () => {
+ try {
+ await api.archiveAgent(agent.id);
+ invalidateAgents();
+ toast.success("Agent archived");
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to archive agent");
+ }
+ };
+
+ const handleRestore = async () => {
+ try {
+ await api.restoreAgent(agent.id);
+ invalidateAgents();
+ toast.success("Agent restored");
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to restore agent");
+ }
+ };
+
+ const handleCancelTasks = async () => {
+ try {
+ const { cancelled } = await api.cancelAgentTasks(agent.id);
+ // Server broadcasts task:cancelled per row; useRealtimeSync will
+ // invalidate the agent-task-snapshot cache for us. We still kick
+ // agents in case the back-end's ReconcileAgentStatus changed
+ // agent.status.
+ invalidateAgents();
+ toast.success(
+ cancelled === 0
+ ? "No active tasks to cancel"
+ : `Cancelled ${cancelled} task${cancelled === 1 ? "" : "s"}`,
+ );
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to cancel tasks");
+ }
+ };
+
+ if (!hasAnyAction) {
+ return null;
+ }
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Row actions"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ />
+ }
+ >
+ <MoreHorizontal className="h-4 w-4 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-auto"
+ // Prevent the row's onClick from firing if a click on a menu item
+ // somehow bubbles back through the portal.
+ onClick={(e) => e.stopPropagation()}
+ >
+ {showStop && (
+ <DropdownMenuItem
+ onClick={() => setConfirmCancel(true)}
+ >
+ <Square className="h-3.5 w-3.5" />
+ Cancel all tasks
+ </DropdownMenuItem>
+ )}
+ {showDuplicate && (
+ <DropdownMenuItem onClick={() => onDuplicate(agent)}>
+ <Copy className="h-3.5 w-3.5" />
+ Duplicate
+ </DropdownMenuItem>
+ )}
+ {showRestore && (
+ <DropdownMenuItem onClick={handleRestore}>
+ <RotateCcw className="h-3.5 w-3.5" />
+ Restore
+ </DropdownMenuItem>
+ )}
+ {showArchive && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={() => setConfirmArchive(true)}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ Archive
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ {confirmCancel && (
+ <AlertDialog
+ open
+ onOpenChange={(v) => {
+ if (!v) setConfirmCancel(false);
+ }}
+ >
+ <AlertDialogContent
+ // Keep clicks inside the dialog from bubbling to the row.
+ onClick={(e) => e.stopPropagation()}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ Cancel all tasks for &ldquo;{agent.name}&rdquo;?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {describeCancelImpact(runningCount, queuedCount)}
+ {runningCount > 0 && (
+ <>
+ {" "}Running tasks may take up to 5 seconds to fully halt.
+ </>
+ )}{" "}
+ Cancelled tasks cannot be resumed.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep them</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setConfirmCancel(false);
+ void handleCancelTasks();
+ }}
+ >
+ Cancel all tasks
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+
+ {confirmArchive && (
+ <AlertDialog
+ open
+ onOpenChange={(v) => {
+ if (!v) setConfirmArchive(false);
+ }}
+ >
+ <AlertDialogContent onClick={(e) => e.stopPropagation()}>
+ <AlertDialogHeader>
+ <div className="flex items-start gap-3">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-destructive/10">
+ <AlertCircle className="h-5 w-5 text-destructive" />
+ </div>
+ <div className="flex-1">
+ <AlertDialogTitle>
+ Archive &ldquo;{agent.name}&rdquo;?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ The agent won&apos;t be assignable or mentionable, and any
+ active tasks will be cancelled. All history is preserved
+ and you can restore it later.
+ </AlertDialogDescription>
+ </div>
+ </div>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setConfirmArchive(false);
+ void handleArchive();
+ }}
+ >
+ Archive
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+ </>
+ );
+}
+
+function describeCancelImpact(running: number, queued: number): string {
+ // Both zero shouldn't happen — the menu item is gated on hasActiveWork —
+ // but guarding anyway so the copy never reads "stop 0 tasks and 0 tasks".
+ if (running === 0 && queued === 0) {
+ return "There are no active tasks to cancel.";
+ }
+ const parts: string[] = [];
+ if (running > 0) parts.push(`${running} running`);
+ if (queued > 0) parts.push(`${queued} queued`);
+ return `This will cancel ${parts.join(" and ")} ${
+ running + queued === 1 ? "task" : "tasks"
+ }.`;
+}
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index a772969c6e..d9b05a7c0a 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -1,229 +1,544 @@
"use client";
-import { useState, useEffect, useMemo } from "react";
-import { useDefaultLayout } from "react-resizable-panels";
-import { Bot, Plus, Archive } from "lucide-react";
-import type { CreateAgentRequest, UpdateAgentRequest } from "@multica/core/types";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
-} from "@multica/ui/components/ui/resizable";
-import { Button } from "@multica/ui/components/ui/button";
-import { toast } from "sonner";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
+ AlertCircle,
+ ArrowLeft,
+ ArrowUpDown,
+ Bot,
+ Plus,
+ Search,
+} from "lucide-react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import type { Agent, AgentRuntime, CreateAgentRequest } from "@multica/core/types";
+import {
+ type AgentAvailability,
+ type LastTaskState,
+ agentRunCounts30dOptions,
+ summarizeActivityWindow,
+ useWorkspaceActivityMap,
+ useWorkspacePresenceMap,
+} from "@multica/core/agents";
import { api } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
-import { runtimeListOptions } from "@multica/core/runtimes/queries";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
-import { agentListOptions, memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";
+import { useWorkspacePaths } from "@multica/core/paths";
+import {
+ agentListOptions,
+ memberListOptions,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
+import { runtimeListOptions } from "@multica/core/runtimes";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Input } from "@multica/ui/components/ui/input";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import { useNavigation } from "../../navigation";
import { PageHeader } from "../../layout/page-header";
+import {
+ availabilityConfig,
+ availabilityOrder,
+ lastTaskOrder,
+ taskStateConfig,
+} from "../presence";
import { CreateAgentDialog } from "./create-agent-dialog";
-import { AgentListItem } from "./agent-list-item";
-import { AgentDetail } from "./agent-detail";
+import { AGENT_LIST_GRID, AgentListItem } from "./agent-list-item";
+
+// Filter axes layered top → bottom by frequency:
+//
+// View = which dataset are we looking at (Active vs Archived).
+// Archived is low-frequency, so it is NOT a top-level
+// segment — it is a ghost link in the toolbar.
+// Scope = ownership lens (All vs Mine). Layer-1 segment.
+// Availability = "Can it take work?" — 3-state chip group.
+// Last task = "What was the last thing it did?" — 5-state chip group.
+//
+// Availability and Last task are independent axes (Option B). Filter is
+// the intersection: "online + last failed" is a meaningful combination
+// (find broken-but-alive agents). Counts on each chip reflect "if I
+// selected this chip on this axis (with the other axis's current
+// selection), this many agents would match".
+type View = "active" | "archived";
+type Scope = "all" | "mine";
+type AvailabilityFilter = "all" | AgentAvailability;
+type LastTaskFilter = "all" | LastTaskState;
+
+const AVAILABILITY_DESCRIPTION: Record<AgentAvailability, string> = {
+ online: "Runtime online — agent ready to take work",
+ unstable:
+ "Runtime just dropped (< 5 min) — queued work is paused, system is auto-retrying",
+ offline: "Runtime unreachable",
+};
+
+const LAST_TASK_DESCRIPTION: Record<LastTaskState, string> = {
+ running: "At least one task running or queued right now",
+ completed: "Most recent task completed successfully",
+ failed: "Most recent task failed — needs attention",
+ cancelled: "Most recent task was cancelled",
+ idle: "No task history yet",
+};
+
+type SortKey = "recent" | "name" | "runs" | "created";
+const SORT_KEYS: SortKey[] = ["recent", "name", "runs", "created"];
+const SORT_LABEL: Record<SortKey, string> = {
+ recent: "Recent activity",
+ name: "Name",
+ runs: "Most runs",
+ created: "Recently created",
+};
export function AgentsPage() {
- const currentUser = useAuthStore((s) => s.user);
- const qc = useQueryClient();
const wsId = useWorkspaceId();
- const { data: agents = [], isLoading } = useQuery(agentListOptions(wsId));
- const [selectedId, setSelectedId] = useState<string>("");
- const [showArchived, setShowArchived] = useState(false);
- const [showCreate, setShowCreate] = useState(false);
- const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(runtimeListOptions(wsId));
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const qc = useQueryClient();
+ const currentUser = useAuthStore((s) => s.user);
+
+ const {
+ data: agents = [],
+ isLoading,
+ error: listError,
+ refetch: refetchList,
+ } = useQuery(agentListOptions(wsId));
+ const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
+ runtimeListOptions(wsId),
+ );
const { data: members = [] } = useQuery(memberListOptions(wsId));
- const { defaultLayout, onLayoutChanged } = useDefaultLayout({
- id: "multica_agents_layout",
- });
+ const { data: runCountsRaw = [] } = useQuery(agentRunCounts30dOptions(wsId));
- const filteredAgents = useMemo(
- () => showArchived ? agents.filter((a) => !!a.archived_at) : agents.filter((a) => !a.archived_at),
- [agents, showArchived],
+ // Single source of truth for derived agent state. The hook owns the
+ // 30s tick + the runtime/null/task orchestration; the page only reads
+ // the resulting Maps. Replaces the 24-line useMemo presenceMap +
+ // 12-line activityMap that lived here previously.
+ const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
+ const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);
+
+ const [view, setView] = useState<View>("active");
+ // Default to "mine" — matches runtimes page convention and the visual
+ // ordering (Mine first). All is one click away when users want the
+ // workspace-wide view.
+ const [scope, setScope] = useState<Scope>("mine");
+ const [availabilityFilter, setAvailabilityFilter] =
+ useState<AvailabilityFilter>("all");
+ const [lastTaskFilter, setLastTaskFilter] = useState<LastTaskFilter>("all");
+ const [sort, setSort] = useState<SortKey>("recent");
+ const [search, setSearch] = useState("");
+ const [showCreate, setShowCreate] = useState(false);
+ // When set, the Create dialog opens pre-populated with this agent's
+ // config — driven by the row-level "Duplicate" action. We keep this
+ // separate from `showCreate` so a stray null-template doesn't open the
+ // dialog: the dialog opens iff `showCreate || duplicateTemplate`.
+ const [duplicateTemplate, setDuplicateTemplate] = useState<Agent | null>(
+ null,
);
- const archivedCount = useMemo(() => agents.filter((a) => !!a.archived_at).length, [agents]);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const fadeStyle = useScrollFade(scrollRef);
- // Select first agent on initial load or when filter changes
- useEffect(() => {
- if (filteredAgents.length > 0 && !filteredAgents.some((a) => a.id === selectedId)) {
- setSelectedId(filteredAgents[0]!.id);
+ const runtimesById = useMemo(() => {
+ const m = new Map<string, AgentRuntime>();
+ for (const r of runtimes) m.set(r.id, r);
+ return m;
+ }, [runtimes]);
+
+ const runCountsById = useMemo(() => {
+ const m = new Map<string, number>();
+ for (const r of runCountsRaw) m.set(r.agent_id, r.run_count);
+ return m;
+ }, [runCountsRaw]);
+
+ // Workspace role of the current user, used to gate row-level "manage"
+ // operations (archive / cancel-tasks). Mirrors the back-end's
+ // canManageAgent rule: workspace owner/admin OR the agent's owner.
+ const myRole = useMemo(() => {
+ if (!currentUser) return null;
+ return members.find((m) => m.user_id === currentUser.id)?.role ?? null;
+ }, [members, currentUser]);
+ const isWorkspaceAdmin = myRole === "owner" || myRole === "admin";
+
+ // Layer 1a — view (active / archived).
+ const inView = useMemo(
+ () =>
+ agents.filter((a) =>
+ view === "archived" ? !!a.archived_at : !a.archived_at,
+ ),
+ [agents, view],
+ );
+
+ // Layer 1b — ownership scope. Counts shown on the segment are
+ // computed against the inView set so the numbers always reflect
+ // "what would I see if I clicked this".
+ const scopeCounts = useMemo(() => {
+ let mine = 0;
+ if (currentUser) {
+ for (const a of inView) {
+ if (a.owner_id === currentUser.id) mine += 1;
+ }
}
- }, [filteredAgents, selectedId]);
+ return { all: inView.length, mine };
+ }, [inView, currentUser]);
- const handleCreate = async (data: CreateAgentRequest) => {
- const agent = await api.createAgent(data);
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- setSelectedId(agent.id);
- };
+ const inScope = useMemo(() => {
+ if (scope === "all" || !currentUser) return inView;
+ return inView.filter((a) => a.owner_id === currentUser.id);
+ }, [inView, scope, currentUser]);
- const handleUpdate = async (id: string, data: Record<string, unknown>) => {
- try {
- await api.updateAgent(id, data as UpdateAgentRequest);
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- toast.success("Agent updated");
- } catch (e) {
- toast.error(e instanceof Error ? e.message : "Failed to update agent");
- throw e;
+ // Layer 2 — chip counts on each axis. Counts cross-filter against the
+ // OTHER axis so the displayed number is "if I clicked this chip with
+ // the other axis as-is, this many agents would match". Stable mental
+ // model: numbers don't dance unless the user actually changes scope.
+ const availabilityCounts = useMemo(() => {
+ const counts: Record<AgentAvailability, number> = {
+ online: 0,
+ unstable: 0,
+ offline: 0,
+ };
+ let total = 0;
+ for (const a of inScope) {
+ const detail = presenceMap.get(a.id);
+ if (!detail) continue;
+ if (lastTaskFilter !== "all" && detail.lastTask !== lastTaskFilter) {
+ continue;
+ }
+ counts[detail.availability] += 1;
+ total += 1;
}
- };
+ return { counts, total };
+ }, [inScope, presenceMap, lastTaskFilter]);
- const handleArchive = async (id: string) => {
- try {
- await api.archiveAgent(id);
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- toast.success("Agent archived");
- } catch (e) {
- toast.error(e instanceof Error ? e.message : "Failed to archive agent");
+ const lastTaskCounts = useMemo(() => {
+ const counts: Record<LastTaskState, number> = {
+ running: 0,
+ completed: 0,
+ failed: 0,
+ cancelled: 0,
+ idle: 0,
+ };
+ let total = 0;
+ for (const a of inScope) {
+ const detail = presenceMap.get(a.id);
+ if (!detail) continue;
+ if (
+ availabilityFilter !== "all" &&
+ detail.availability !== availabilityFilter
+ ) {
+ continue;
+ }
+ counts[detail.lastTask] += 1;
+ total += 1;
}
- };
+ return { counts, total };
+ }, [inScope, presenceMap, availabilityFilter]);
- const handleRestore = async (id: string) => {
- try {
- await api.restoreAgent(id);
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- toast.success("Agent restored");
- } catch (e) {
- toast.error(e instanceof Error ? e.message : "Failed to restore agent");
+ // Final cut — apply both axes + search.
+ const filteredAgents = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ return inScope.filter((a) => {
+ // Filter chips only apply to the Active view; Archived hides the
+ // chip rows entirely (presence is undefined for archived agents).
+ if (view === "active") {
+ const detail = presenceMap.get(a.id);
+ if (
+ availabilityFilter !== "all" &&
+ detail?.availability !== availabilityFilter
+ ) {
+ return false;
+ }
+ if (
+ lastTaskFilter !== "all" &&
+ detail?.lastTask !== lastTaskFilter
+ ) {
+ return false;
+ }
+ }
+ if (q) {
+ if (
+ !a.name.toLowerCase().includes(q) &&
+ !(a.description ?? "").toLowerCase().includes(q)
+ )
+ return false;
+ }
+ return true;
+ });
+ }, [inScope, availabilityFilter, lastTaskFilter, view, search, presenceMap]);
+
+ const sortedAgents = useMemo(() => {
+ const xs = [...filteredAgents];
+ switch (sort) {
+ case "name":
+ xs.sort((a, b) => a.name.localeCompare(b.name));
+ break;
+ case "runs":
+ xs.sort(
+ (a, b) =>
+ (runCountsById.get(b.id) ?? 0) - (runCountsById.get(a.id) ?? 0),
+ );
+ break;
+ case "created":
+ xs.sort((a, b) => +new Date(b.created_at) - +new Date(a.created_at));
+ break;
+ case "recent":
+ default:
+ // "Recent activity" prioritises 7d total completions (the same
+ // window the row's sparkline shows), then 30d run count, then
+ // created_at. We don't have a precise last-touched timestamp on
+ // Agent today; this approximates it closely without a new column.
+ xs.sort((a, b) => {
+ const aSum = summarizeActivityWindow(
+ activityMap.get(a.id),
+ 7,
+ ).totalRuns;
+ const bSum = summarizeActivityWindow(
+ activityMap.get(b.id),
+ 7,
+ ).totalRuns;
+ if (aSum !== bSum) return bSum - aSum;
+ const aRuns = runCountsById.get(a.id) ?? 0;
+ const bRuns = runCountsById.get(b.id) ?? 0;
+ if (aRuns !== bRuns) return bRuns - aRuns;
+ return +new Date(b.created_at) - +new Date(a.created_at);
+ });
+ break;
}
+ return xs;
+ }, [filteredAgents, sort, runCountsById, activityMap]);
+
+ const archivedCount = useMemo(
+ () => agents.filter((a) => !!a.archived_at).length,
+ [agents],
+ );
+
+ const totalActiveCount = useMemo(
+ () => agents.filter((a) => !a.archived_at).length,
+ [agents],
+ );
+
+ // Auto-bounce out of Archived if the population empties (e.g. user
+ // restored the last archived agent from another surface).
+ useEffect(() => {
+ if (view === "archived" && archivedCount === 0) setView("active");
+ }, [view, archivedCount]);
+
+ const handleCreate = async (data: CreateAgentRequest) => {
+ const agent = await api.createAgent(data);
+ // When duplicating, carry the source agent's skill assignments over.
+ // Skills aren't part of CreateAgentRequest (they're managed via
+ // setAgentSkills) so the create endpoint can't take them inline; we
+ // do a follow-up call. Failure here doesn't abort the duplicate —
+ // the agent already exists and the user can re-attach skills from
+ // the detail page.
+ if (duplicateTemplate?.skills.length) {
+ try {
+ await api.setAgentSkills(agent.id, {
+ skill_ids: duplicateTemplate.skills.map((s) => s.id),
+ });
+ } catch {
+ // Surfaced softly; the agent itself is fine.
+ }
+ }
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ setShowCreate(false);
+ setDuplicateTemplate(null);
+ navigation.push(paths.agentDetail(agent.id));
};
- const selected = agents.find((a) => a.id === selectedId) ?? null;
+ const handleDuplicate = (agent: Agent) => {
+ setDuplicateTemplate(agent);
+ setShowCreate(true);
+ };
+ // ---- Loading ----
if (isLoading) {
return (
- <div className="flex flex-1 min-h-0">
- {/* List skeleton */}
- <div className="w-72 border-r">
- <div className="flex h-12 items-center justify-between border-b px-4">
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-6 w-6 rounded" />
- </div>
- <div className="divide-y">
- {Array.from({ length: 4 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3 px-4 py-3">
- <Skeleton className="h-8 w-8 rounded-full" />
- <div className="flex-1 space-y-1.5">
- <Skeleton className="h-4 w-24" />
- <Skeleton className="h-3 w-16" />
- </div>
- </div>
- ))}
- </div>
- </div>
- {/* Detail skeleton */}
- <div className="flex-1 p-6 space-y-6">
- <div className="flex items-center gap-3">
- <Skeleton className="h-10 w-10 rounded-full" />
- <div className="space-y-1.5">
- <Skeleton className="h-5 w-32" />
- <Skeleton className="h-3 w-20" />
+ <div className="flex flex-1 min-h-0 flex-col">
+ <PageHeaderBar totalCount={0} onCreate={() => setShowCreate(true)} />
+ <div className="flex flex-1 min-h-0 flex-col gap-4 p-6">
+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border">
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
+ <Skeleton className="h-7 w-32 rounded-md" />
+ <Skeleton className="h-7 w-32 rounded-md" />
+ </div>
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b px-4">
+ <Skeleton className="h-6 w-16 rounded-full" />
+ <Skeleton className="h-6 w-24 rounded-full" />
+ <Skeleton className="h-6 w-20 rounded-full" />
+ </div>
+ <div className="space-y-2 p-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-14 w-full rounded-md" />
+ ))}
</div>
</div>
- <div className="space-y-3">
- <Skeleton className="h-8 w-full rounded-lg" />
- <Skeleton className="h-8 w-full rounded-lg" />
- <Skeleton className="h-8 w-3/4 rounded-lg" />
+ </div>
+ </div>
+ );
+ }
+
+ // ---- List request error ----
+ if (listError) {
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <PageHeaderBar totalCount={0} onCreate={() => setShowCreate(true)} />
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
+ <AlertCircle className="h-8 w-8 text-destructive" />
+ <div>
+ <p className="text-sm font-medium">Couldn&rsquo;t load agents</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {listError instanceof Error
+ ? listError.message
+ : "Something went wrong fetching the agent list."}
+ </p>
</div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => refetchList()}
+ >
+ Try again
+ </Button>
</div>
</div>
);
}
+ const showEmpty = totalActiveCount === 0 && archivedCount === 0;
+
return (
- <ResizablePanelGroup
- orientation="horizontal"
- className="flex-1 min-h-0"
- defaultLayout={defaultLayout}
- onLayoutChanged={onLayoutChanged}
- >
- <ResizablePanel id="list" defaultSize={280} minSize={240} maxSize={400} groupResizeBehavior="preserve-pixel-size">
- {/* Left column — agent list */}
- <div className="overflow-y-auto h-full border-r">
- <PageHeader className="justify-between">
- <h1 className="text-sm font-semibold">Agents</h1>
- <div className="flex items-center gap-1">
- {archivedCount > 0 && (
- <Button
- variant={showArchived ? "secondary" : "ghost"}
- size="icon-sm"
- onClick={() => setShowArchived(!showArchived)}
- title={showArchived ? "Show active agents" : "Show archived agents"}
- >
- <Archive className="text-muted-foreground" />
- </Button>
- )}
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setShowCreate(true)}
+ <div className="flex flex-1 min-h-0 flex-col">
+ <PageHeaderBar
+ totalCount={totalActiveCount}
+ onCreate={() => setShowCreate(true)}
+ />
+
+ <div className="flex flex-1 min-h-0 flex-col gap-4 p-6">
+ {showEmpty ? (
+ <div className="flex flex-1 items-center justify-center">
+ <EmptyState onCreate={() => setShowCreate(true)} />
+ </div>
+ ) : (
+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border bg-background">
+ {view === "active" ? (
+ <>
+ <ActiveToolbarRow
+ scope={scope}
+ setScope={setScope}
+ scopeCounts={scopeCounts}
+ sort={sort}
+ setSort={setSort}
+ search={search}
+ setSearch={setSearch}
+ />
+ <PresenceFilterRows
+ availabilityFilter={availabilityFilter}
+ setAvailabilityFilter={setAvailabilityFilter}
+ availabilityCounts={availabilityCounts.counts}
+ availabilityTotal={availabilityCounts.total}
+ lastTaskFilter={lastTaskFilter}
+ setLastTaskFilter={setLastTaskFilter}
+ lastTaskCounts={lastTaskCounts.counts}
+ lastTaskTotal={lastTaskCounts.total}
+ visibleCount={sortedAgents.length}
+ totalCount={inScope.length}
+ archivedCount={archivedCount}
+ onShowArchived={() => setView("archived")}
+ />
+ </>
+ ) : (
+ <ArchivedToolbarRow
+ onBack={() => setView("active")}
+ archivedCount={archivedCount}
+ sort={sort}
+ setSort={setSort}
+ />
+ )}
+
+ {sortedAgents.length === 0 ? (
+ <NoMatches
+ view={view}
+ search={search}
+ hasFilter={
+ availabilityFilter !== "all" || lastTaskFilter !== "all"
+ }
+ scope={scope}
+ />
+ ) : (
+ <div
+ ref={scrollRef}
+ style={fadeStyle}
+ className="flex-1 min-h-0 overflow-y-auto"
>
- <Plus className="text-muted-foreground" />
- </Button>
- </div>
- </PageHeader>
- {filteredAgents.length === 0 ? (
- <div className="flex flex-col items-center justify-center px-4 py-12">
- <Bot className="h-8 w-8 text-muted-foreground/40" />
- <p className="mt-3 text-sm text-muted-foreground">
- {showArchived ? "No archived agents" : archivedCount > 0 ? "No active agents" : "No agents yet"}
- </p>
- {!showArchived && (
- <Button
- onClick={() => setShowCreate(true)}
- size="xs"
- className="mt-3"
+ {/*
+ Layout strategy — CSS Grid + `max-content` on Status, ratio
+ fr's elsewhere. The Status column shrinks to fit when no
+ agent is in a high-load Working state, and only widens
+ when the data demands it; the freed space flows into the
+ Agent (1.6fr) primary column. See AGENT_LIST_GRID for the
+ full breakpoint ladder. Sticky header reuses the same grid
+ template so column edges align with rows pixel-for-pixel.
+ */}
+ <div
+ role="row"
+ className={`${AGENT_LIST_GRID} sticky top-0 z-10 border-b bg-muted/30 px-4 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground backdrop-blur`}
>
- <Plus className="h-3 w-3" />
- Create Agent
- </Button>
- )}
- </div>
- ) : (
- <div className="divide-y">
- {filteredAgents.map((agent) => (
- <AgentListItem
- key={agent.id}
- agent={agent}
- isSelected={agent.id === selectedId}
- onClick={() => setSelectedId(agent.id)}
- />
- ))}
- </div>
- )}
- </div>
- </ResizablePanel>
-
- <ResizableHandle />
-
- <ResizablePanel id="detail" minSize="50%">
- {/* Right column — agent detail */}
- {selected ? (
- <AgentDetail
- key={selected.id}
- agent={selected}
- runtimes={runtimes}
- members={members}
- currentUserId={currentUser?.id ?? null}
- onUpdate={handleUpdate}
- onArchive={handleArchive}
- onRestore={handleRestore}
- />
- ) : (
- <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
- <Bot className="h-10 w-10 text-muted-foreground/30" />
- <p className="mt-3 text-sm">Select an agent to view details</p>
- <Button
- onClick={() => setShowCreate(true)}
- size="xs"
- className="mt-3"
- >
- <Plus className="h-3 w-3" />
- Create Agent
- </Button>
+ {/* Avatar leading slot — empty header cell so the "Agent"
+ label below aligns with the row's name text, not the
+ avatar's left edge. */}
+ <span aria-hidden />
+ <span>Agent</span>
+ <span>Status</span>
+ <span className="hidden md:block">Last run</span>
+ <span className="hidden md:block">Runtime</span>
+ <span className="hidden lg:block">Activity (7d)</span>
+ <span className="hidden text-right md:block">Runs</span>
+ {/* Operations column header — kept silent; the kebab
+ cell speaks for itself. */}
+ <span aria-label="Actions" />
+ </div>
+ {sortedAgents.map((agent) => {
+ const isOwner =
+ !!currentUser?.id && agent.owner_id === currentUser.id;
+ const canManage = isWorkspaceAdmin || isOwner;
+ // Inline owner avatar only in All scope on a teammate's
+ // agent — Mine scope means owner is always you, so a
+ // self-avatar everywhere would be visual noise.
+ const ownerIdToShow =
+ scope === "all" &&
+ agent.owner_id &&
+ agent.owner_id !== currentUser?.id
+ ? agent.owner_id
+ : null;
+ return (
+ <AgentListItem
+ key={agent.id}
+ agent={agent}
+ runtime={runtimesById.get(agent.runtime_id) ?? null}
+ presence={presenceMap.get(agent.id) ?? null}
+ activity={activityMap.get(agent.id) ?? null}
+ runCount={runCountsById.get(agent.id) ?? 0}
+ ownerIdToShow={ownerIdToShow}
+ canManage={canManage}
+ onDuplicate={handleDuplicate}
+ href={paths.agentDetail(agent.id)}
+ />
+ );
+ })}
+ </div>
+ )}
</div>
)}
- </ResizablePanel>
+ </div>
{showCreate && (
<CreateAgentDialog
@@ -231,10 +546,456 @@ export function AgentsPage() {
runtimesLoading={runtimesLoading}
members={members}
currentUserId={currentUser?.id ?? null}
- onClose={() => setShowCreate(false)}
+ template={duplicateTemplate}
+ onClose={() => {
+ setShowCreate(false);
+ setDuplicateTemplate(null);
+ }}
onCreate={handleCreate}
/>
)}
- </ResizablePanelGroup>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Page header — icon + title + count + create CTA. Unchanged.
+// ---------------------------------------------------------------------------
+
+function PageHeaderBar({
+ totalCount,
+ onCreate,
+}: {
+ totalCount: number;
+ onCreate: () => void;
+}) {
+ return (
+ <PageHeader className="justify-between px-5">
+ <div className="flex items-center gap-2">
+ <Bot className="h-4 w-4 text-muted-foreground" />
+ <h1 className="text-sm font-medium">Agents</h1>
+ {totalCount > 0 && (
+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">
+ {totalCount}
+ </span>
+ )}
+ {/* Tagline next to the title — mirrors Runtimes / Skills. Single
+ sentence + docs link, hidden below md so it never collides with
+ the title on narrow screens. The presence chip row below carries
+ the state-legend job, so the tagline only needs to anchor what
+ an agent IS, not what each colour means. */}
+ <p className="ml-2 hidden text-xs text-muted-foreground md:block">
+ AI teammates that pick up issues, comment, and update status.{" "}
+ <a
+ href="https://multica.ai/docs/agents"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline decoration-muted-foreground/30 underline-offset-4 transition-colors hover:text-foreground"
+ >
+ Learn more →
+ </a>
+ </p>
+ </div>
+ <Button type="button" size="sm" onClick={onCreate}>
+ <Plus className="h-3 w-3" />
+ New agent
+ </Button>
+ </PageHeader>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Active view — Layer 1: scope segment + sort + search + archived link + live
+// ---------------------------------------------------------------------------
+
+function ActiveToolbarRow({
+ scope,
+ setScope,
+ scopeCounts,
+ sort,
+ setSort,
+ search,
+ setSearch,
+}: {
+ scope: Scope;
+ setScope: (v: Scope) => void;
+ scopeCounts: { all: number; mine: number };
+ sort: SortKey;
+ setSort: (v: SortKey) => void;
+ search: string;
+ setSearch: (v: string) => void;
+}) {
+ // Layout follows Skills: [Search] [Mine|All] [Sort ▼]
+ // Search and the scope segment cluster on the left (Skills puts its
+ // filter buttons immediately after the search the same way). Sort
+ // gets pushed to the far right via ml-auto.
+ return (
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search agents…"
+ className="h-8 w-64 pl-8 text-sm"
+ />
+ </div>
+ <ScopeSegment scope={scope} setScope={setScope} counts={scopeCounts} />
+ <div className="ml-auto">
+ <SortDropdown sort={sort} setSort={setSort} />
+ </div>
+ </div>
+ );
+}
+
+function ScopeSegment({
+ scope,
+ setScope,
+ counts,
+}: {
+ scope: Scope;
+ setScope: (v: Scope) => void;
+ counts: { all: number; mine: number };
+}) {
+ // Mine first — that's the more frequent scope (your own agents) and
+ // also the default selection, so it lives in the leading slot.
+ return (
+ <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">
+ <ScopeButton
+ active={scope === "mine"}
+ label="Mine"
+ count={counts.mine}
+ onClick={() => setScope("mine")}
+ />
+ <ScopeButton
+ active={scope === "all"}
+ label="All"
+ count={counts.all}
+ onClick={() => setScope("all")}
+ />
+ </div>
+ );
+}
+
+function ScopeButton({
+ active,
+ label,
+ count,
+ onClick,
+}: {
+ active: boolean;
+ label: string;
+ count: number;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs font-medium transition-colors ${
+ active
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ <span>{label}</span>
+ <span
+ className={`font-mono tabular-nums ${
+ active ? "text-muted-foreground/80" : "text-muted-foreground/50"
+ }`}
+ >
+ {count}
+ </span>
+ </button>
+ );
+}
+
+function SortDropdown({
+ sort,
+ setSort,
+}: {
+ sort: SortKey;
+ setSort: (v: SortKey) => void;
+}) {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-foreground"
+ />
+ }
+ >
+ <ArrowUpDown className="h-3 w-3" />
+ {SORT_LABEL[sort]}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-auto">
+ {SORT_KEYS.map((k) => (
+ <DropdownMenuItem
+ key={k}
+ onClick={() => setSort(k)}
+ className="text-xs"
+ >
+ {SORT_LABEL[k]}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Active view — Layer 2: two independent filter axes (availability + last
+// task) + visible/total count. The right edge hosts the low-frequency
+// "Show archived" link, kept out of Layer 1 so the primary toolbar stays
+// uncluttered.
+//
+// Two rows because cramming both axes into a single row makes the chip
+// labels feel ambiguous ("Online" and "Failed" side by side reads as a
+// single stack of facets, but they're on different axes). Two rows with
+// a leading label make the axis split obvious.
+// ---------------------------------------------------------------------------
+
+function PresenceFilterRows({
+ availabilityFilter,
+ setAvailabilityFilter,
+ availabilityCounts,
+ availabilityTotal,
+ lastTaskFilter,
+ setLastTaskFilter,
+ lastTaskCounts,
+ lastTaskTotal,
+ visibleCount,
+ totalCount,
+ archivedCount,
+ onShowArchived,
+}: {
+ availabilityFilter: AvailabilityFilter;
+ setAvailabilityFilter: (v: AvailabilityFilter) => void;
+ availabilityCounts: Record<AgentAvailability, number>;
+ availabilityTotal: number;
+ lastTaskFilter: LastTaskFilter;
+ setLastTaskFilter: (v: LastTaskFilter) => void;
+ lastTaskCounts: Record<LastTaskState, number>;
+ lastTaskTotal: number;
+ visibleCount: number;
+ totalCount: number;
+ archivedCount: number;
+ onShowArchived: () => void;
+}) {
+ return (
+ <div className="flex shrink-0 flex-col gap-1.5 border-b px-4 py-2.5">
+ {/* Row 1: Availability — 3 chips. */}
+ <div className="flex items-center gap-2">
+ <span className="w-16 shrink-0 text-xs text-muted-foreground">
+ Status
+ </span>
+ <PresenceChip
+ active={availabilityFilter === "all"}
+ onClick={() => setAvailabilityFilter("all")}
+ label="All"
+ count={availabilityTotal}
+ description="No availability filter"
+ />
+ {availabilityOrder.map((a) => {
+ const cfg = availabilityConfig[a];
+ return (
+ <PresenceChip
+ key={a}
+ active={availabilityFilter === a}
+ onClick={() => setAvailabilityFilter(a)}
+ label={cfg.label}
+ count={availabilityCounts[a]}
+ dotClass={cfg.dotClass}
+ description={AVAILABILITY_DESCRIPTION[a]}
+ />
+ );
+ })}
+ <div className="ml-auto flex items-center gap-3">
+ {archivedCount > 0 && (
+ <button
+ type="button"
+ onClick={onShowArchived}
+ className="text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ Show archived ({archivedCount}) →
+ </button>
+ )}
+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">
+ {visibleCount} of {totalCount}
+ </span>
+ </div>
+ </div>
+ {/* Row 2: Last task — 5 chips. */}
+ <div className="flex items-center gap-2">
+ <span className="w-16 shrink-0 text-xs text-muted-foreground">
+ Last run
+ </span>
+ <PresenceChip
+ active={lastTaskFilter === "all"}
+ onClick={() => setLastTaskFilter("all")}
+ label="All"
+ count={lastTaskTotal}
+ description="No last-run filter"
+ />
+ {lastTaskOrder.map((t) => {
+ const cfg = taskStateConfig[t];
+ return (
+ <PresenceChip
+ key={t}
+ active={lastTaskFilter === t}
+ onClick={() => setLastTaskFilter(t)}
+ label={cfg.label}
+ count={lastTaskCounts[t]}
+ description={LAST_TASK_DESCRIPTION[t]}
+ />
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+// Same Button + Tooltip pattern Skills uses for its scope filters. Selected
+// state mirrors Skills' `bg-accent text-accent-foreground hover:bg-accent/80`,
+// so any future global tweak to that token cascades here for free.
+function PresenceChip({
+ active,
+ onClick,
+ label,
+ count,
+ dotClass,
+ description,
+}: {
+ active: boolean;
+ onClick: () => void;
+ label: string;
+ count: number;
+ dotClass?: string;
+ description: string;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onClick}
+ className={
+ active
+ ? "bg-accent text-accent-foreground hover:bg-accent/80"
+ : "text-muted-foreground"
+ }
+ >
+ {dotClass && (
+ <span className={`h-1.5 w-1.5 rounded-full ${dotClass}`} />
+ )}
+ <span>{label}</span>
+ <span className="font-mono tabular-nums text-muted-foreground/70">
+ {count}
+ </span>
+ </Button>
+ }
+ />
+ <TooltipContent side="top">{description}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Archived view — single toolbar row (back link + title + count + sort).
+// No presence chip row: presence is undefined for archived agents.
+// ---------------------------------------------------------------------------
+
+function ArchivedToolbarRow({
+ onBack,
+ archivedCount,
+ sort,
+ setSort,
+}: {
+ onBack: () => void;
+ archivedCount: number;
+ sort: SortKey;
+ setSort: (v: SortKey) => void;
+}) {
+ return (
+ <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">
+ <button
+ type="button"
+ onClick={onBack}
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ArrowLeft className="h-3 w-3" />
+ Active agents
+ </button>
+ <span className="text-muted-foreground/40">/</span>
+ <span className="text-xs font-medium">Archived agents</span>
+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">
+ {archivedCount}
+ </span>
+ <div className="ml-auto">
+ <SortDropdown sort={sort} setSort={setSort} />
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Empty / no-matches states
+// ---------------------------------------------------------------------------
+
+function EmptyState({ onCreate }: { onCreate: () => void }) {
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center px-6 py-16 text-center">
+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
+ <Bot className="h-6 w-6 text-muted-foreground" />
+ </div>
+ <h2 className="mt-4 text-base font-semibold">No agents yet</h2>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">
+ Create an agent and assign it issues, like any teammate. Local agents
+ run on your machine; cloud agents run on Multica&rsquo;s runtime.
+ </p>
+ <Button type="button" onClick={onCreate} size="sm" className="mt-5">
+ <Plus className="h-3 w-3" />
+ New agent
+ </Button>
+ </div>
+ );
+}
+
+function NoMatches({
+ view,
+ search,
+ hasFilter: filterActive,
+ scope,
+}: {
+ view: View;
+ search: string;
+ hasFilter: boolean;
+ scope: Scope;
+}) {
+ const hasSearch = search.length > 0;
+ const hasFilter = filterActive || scope === "mine";
+
+ let body: string;
+ if (view === "archived") {
+ body = hasSearch
+ ? `No archived agents match "${search}".`
+ : "No archived agents yet.";
+ } else if (hasSearch) {
+ body = `No agents match "${search}"${hasFilter ? " in this filter" : ""}.`;
+ } else {
+ body = "No agents match this filter.";
+ }
+
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center gap-2 px-4 py-16 text-center text-muted-foreground">
+ <Search className="h-8 w-8 text-muted-foreground/40" />
+ <p className="text-sm">No matches</p>
+ <p className="max-w-xs text-xs">{body}</p>
+ </div>
);
}
diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsx
index 39893481e5..7107b9acba 100644
--- a/packages/views/agents/components/create-agent-dialog.tsx
+++ b/packages/views/agents/components/create-agent-dialog.tsx
@@ -6,6 +6,7 @@ import { ProviderLogo } from "../../runtimes/components/provider-logo";
import { ActorAvatar } from "../../common/actor-avatar";
import { ModelDropdown } from "./model-dropdown";
import type {
+ Agent,
AgentVisibility,
RuntimeDevice,
MemberWithUser,
@@ -36,6 +37,7 @@ export function CreateAgentDialog({
runtimesLoading,
members,
currentUserId,
+ template,
onClose,
onCreate,
}: {
@@ -43,13 +45,26 @@ export function CreateAgentDialog({
runtimesLoading?: boolean;
members: MemberWithUser[];
currentUserId: string | null;
+ // When provided, the dialog opens in "Duplicate" mode: the visible
+ // fields (name / description / runtime / visibility / model) are
+ // pre-populated from this agent, and the hidden fields
+ // (instructions / custom_args / custom_env / max_concurrent_tasks)
+ // are forwarded to the create call so the new agent is a true clone.
+ // Skills are copied separately by the caller after createAgent
+ // succeeds — they're not part of CreateAgentRequest.
+ template?: Agent | null;
onClose: () => void;
onCreate: (data: CreateAgentRequest) => Promise<void>;
}) {
- const [name, setName] = useState("");
- const [description, setDescription] = useState("");
- const [visibility, setVisibility] = useState<AgentVisibility>("private");
- const [model, setModel] = useState("");
+ const isDuplicate = !!template;
+ const [name, setName] = useState(
+ template ? `${template.name} (Copy)` : "",
+ );
+ const [description, setDescription] = useState(template?.description ?? "");
+ const [visibility, setVisibility] = useState<AgentVisibility>(
+ template?.visibility ?? "private",
+ );
+ const [model, setModel] = useState(template?.model ?? "");
const [creating, setCreating] = useState(false);
const [runtimeOpen, setRuntimeOpen] = useState(false);
const [runtimeFilter, setRuntimeFilter] = useState<RuntimeFilter>("mine");
@@ -72,7 +87,11 @@ export function CreateAgentDialog({
});
}, [runtimes, runtimeFilter, currentUserId]);
- const [selectedRuntimeId, setSelectedRuntimeId] = useState(filteredRuntimes[0]?.id ?? "");
+ // When duplicating, default to the template's runtime so the clone
+ // lands on the same machine — caller can still switch in the picker.
+ const [selectedRuntimeId, setSelectedRuntimeId] = useState(
+ template?.runtime_id ?? filteredRuntimes[0]?.id ?? "",
+ );
useEffect(() => {
if (!selectedRuntimeId && filteredRuntimes[0]) {
@@ -86,13 +105,34 @@ export function CreateAgentDialog({
if (!name.trim() || !selectedRuntime) return;
setCreating(true);
try {
- await onCreate({
+ // When duplicating, forward the hidden config fields the template
+ // carries (instructions / custom_args / custom_env / max_concurrent_tasks)
+ // so the clone is functional out of the box without the user
+ // having to walk back through every settings tab. Skills are
+ // copied by the caller in a follow-up setAgentSkills call.
+ const data: CreateAgentRequest = {
name: name.trim(),
description: description.trim(),
runtime_id: selectedRuntime.id,
visibility,
model: model.trim() || undefined,
- });
+ };
+ if (template) {
+ if (template.instructions) data.instructions = template.instructions;
+ if (template.custom_args.length) data.custom_args = template.custom_args;
+ // Skip env when the template's values are redacted from the API
+ // response — copying placeholders would create a broken clone.
+ if (
+ !template.custom_env_redacted &&
+ Object.keys(template.custom_env).length > 0
+ ) {
+ data.custom_env = template.custom_env;
+ }
+ if (template.max_concurrent_tasks) {
+ data.max_concurrent_tasks = template.max_concurrent_tasks;
+ }
+ }
+ await onCreate(data);
onClose();
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create agent");
@@ -104,9 +144,13 @@ export function CreateAgentDialog({
<Dialog open onOpenChange={(v) => { if (!v) onClose(); }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>Create Agent</DialogTitle>
+ <DialogTitle>
+ {isDuplicate ? "Duplicate Agent" : "Create Agent"}
+ </DialogTitle>
<DialogDescription>
- Create a new AI agent for your workspace.
+ {isDuplicate
+ ? `Create a new agent based on "${template!.name}". Instructions, env, and skills are copied for you.`
+ : "Create a new AI agent for your workspace."}
</DialogDescription>
</DialogHeader>
diff --git a/packages/views/agents/components/index.ts b/packages/views/agents/components/index.ts
index 01cdf9ce75..c459fd7799 100644
--- a/packages/views/agents/components/index.ts
+++ b/packages/views/agents/components/index.ts
@@ -1 +1,2 @@
export { AgentsPage } from "./agents-page";
+export { AgentDetailPage } from "./agent-detail-page";
diff --git a/packages/views/agents/components/inspector/chip.ts b/packages/views/agents/components/inspector/chip.ts
new file mode 100644
index 0000000000..a3d97c726b
--- /dev/null
+++ b/packages/views/agents/components/inspector/chip.ts
@@ -0,0 +1,18 @@
+/**
+ * Shared trigger styling for inspector pickers (Runtime / Model / Visibility /
+ * Concurrency).
+ *
+ * The defining choices:
+ * - `rounded-md` (6px) — soft enough to feel like a button, not a tab.
+ * - `hover:bg-accent` — single hover layer carries the entire "this is a
+ * button" signal. We tried adding a hover-border on top, but layered hover
+ * states (border + bg) made the chip outline busier without adding info.
+ * - `min-w-0` so children that `truncate` don't overflow the inspector's
+ * 320px column.
+ *
+ * No default border on purpose: at rest the chip should sit quietly inside
+ * the row; the moment the cursor enters, the bg flips and the affordance is
+ * obvious.
+ */
+export const CHIP_CLASS =
+ "group flex min-w-0 cursor-pointer items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs transition-colors hover:bg-accent";
diff --git a/packages/views/agents/components/inspector/concurrency-picker.tsx b/packages/views/agents/components/inspector/concurrency-picker.tsx
new file mode 100644
index 0000000000..5383eaadb7
--- /dev/null
+++ b/packages/views/agents/components/inspector/concurrency-picker.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { PropertyPicker } from "../../../issues/components/pickers";
+import { CHIP_CLASS } from "./chip";
+
+const MIN = 1;
+const MAX = 50;
+
+export function ConcurrencyPicker({
+ value,
+ onChange,
+}: {
+ value: number;
+ onChange: (next: number) => Promise<void> | void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState(String(value));
+
+ // Reset draft from authoritative value whenever the popover (re-)opens or
+ // the prop changes from elsewhere — protects against stale draft state if
+ // the user closes mid-edit and reopens later.
+ useEffect(() => {
+ if (open) setDraft(String(value));
+ }, [open, value]);
+
+ const commit = async () => {
+ const n = Number(draft);
+ if (!Number.isFinite(n) || n < MIN || n > MAX) return;
+ setOpen(false);
+ if (n !== value) await onChange(n);
+ };
+
+ const tooltip = `Concurrency · ${value} max concurrent tasks`;
+
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ width="w-auto"
+ align="start"
+ tooltip={tooltip}
+ triggerRender={
+ <button type="button" className={CHIP_CLASS} aria-label={tooltip} />
+ }
+ trigger={
+ <span className="font-mono tabular-nums">{value}</span>
+ }
+ >
+ <div className="space-y-2 p-2">
+ <p className="text-xs text-muted-foreground">
+ Max concurrent tasks ({MIN}–{MAX})
+ </p>
+ <div className="flex items-center gap-2">
+ <Input
+ type="number"
+ min={MIN}
+ max={MAX}
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void commit();
+ }
+ }}
+ autoFocus
+ className="h-8 w-20 font-mono text-xs"
+ />
+ <Button size="sm" onClick={() => void commit()}>
+ Save
+ </Button>
+ </div>
+ </div>
+ </PropertyPicker>
+ );
+}
diff --git a/packages/views/agents/components/inspector/model-picker.tsx b/packages/views/agents/components/inspector/model-picker.tsx
new file mode 100644
index 0000000000..25dc610b03
--- /dev/null
+++ b/packages/views/agents/components/inspector/model-picker.tsx
@@ -0,0 +1,184 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Loader2, Plus } from "lucide-react";
+import { runtimeModelsOptions } from "@multica/core/runtimes";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ PickerItem,
+ PropertyPicker,
+} from "../../../issues/components/pickers";
+import { CHIP_CLASS } from "./chip";
+
+/**
+ * Inline model picker for the agent inspector. Lighter cousin of
+ * `ModelDropdown` (which is used in the create-agent dialog) — same data
+ * source via `runtimeModelsOptions`, but renders inside a PropertyPicker so
+ * it fits a single PropRow. Drops the "select a runtime first" state because
+ * the inspector only renders this picker after a runtime is bound.
+ *
+ * Unsupported providers (e.g. hermes, which reads its own config) render an
+ * inert italic "Managed by runtime" label instead of a clickable picker —
+ * the back-end ignores agent.model for those runtimes anyway.
+ */
+export function ModelPicker({
+ runtimeId,
+ runtimeOnline,
+ value,
+ onChange,
+}: {
+ runtimeId: string | null;
+ runtimeOnline: boolean;
+ value: string;
+ onChange: (next: string) => Promise<void> | void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [search, setSearch] = useState("");
+
+ const modelsQuery = useQuery(
+ runtimeModelsOptions(runtimeOnline ? runtimeId : null),
+ );
+ const supported = modelsQuery.data?.supported ?? true;
+ // Memoise the model list so every downstream useMemo gets a stable
+ // reference — `?? []` would mint a fresh array on every render and
+ // invalidate filters / defaultModel needlessly.
+ const models = useMemo(
+ () => modelsQuery.data?.models ?? [],
+ [modelsQuery.data],
+ );
+ const defaultModel = useMemo(() => models.find((m) => m.default), [models]);
+
+ const filtered = useMemo(() => {
+ const s = search.trim().toLowerCase();
+ if (!s) return models;
+ return models.filter(
+ (m) =>
+ m.id.toLowerCase().includes(s) || m.label.toLowerCase().includes(s),
+ );
+ }, [models, search]);
+
+ const trimmedSearch = search.trim();
+ const exactMatch = models.some(
+ (m) => m.id === trimmedSearch || m.label === trimmedSearch,
+ );
+ const canCreate = trimmedSearch.length > 0 && !exactMatch;
+
+ const select = async (id: string) => {
+ setOpen(false);
+ setSearch("");
+ if (id !== value) await onChange(id);
+ };
+
+ if (!supported && !modelsQuery.isLoading) {
+ return (
+ <span className="truncate italic text-muted-foreground">
+ Managed by runtime
+ </span>
+ );
+ }
+
+ const triggerLabel =
+ value ||
+ (defaultModel ? `Default — ${defaultModel.label}` : "Default");
+ const triggerTitle = `Model · ${triggerLabel}`;
+
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ width="w-auto min-w-[16rem] max-w-md"
+ align="start"
+ tooltip={triggerTitle}
+ triggerRender={
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ aria-label={triggerTitle}
+ />
+ }
+ trigger={
+ <span className="min-w-0 truncate font-mono text-[11px]">
+ {triggerLabel}
+ </span>
+ }
+ header={
+ <div className="p-1.5">
+ <Input
+ autoFocus
+ placeholder="Search or type a model ID"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ className="h-7 text-xs"
+ />
+ </div>
+ }
+ >
+ {modelsQuery.isLoading && (
+ <div className="flex items-center gap-2 p-3 text-xs text-muted-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ Discovering models…
+ </div>
+ )}
+
+ {!modelsQuery.isLoading &&
+ filtered.map((m) => (
+ <PickerItem
+ key={m.id}
+ selected={m.id === value}
+ onClick={() => void select(m.id)}
+ // Tooltip carries the canonical model id even when the chip
+ // shows the friendlier label, so users can always see what
+ // string actually ships to the agent.
+ tooltip={m.label !== m.id ? `${m.label} · ${m.id}` : m.id}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate font-medium">{m.label}</span>
+ {m.default && (
+ <span className="shrink-0 rounded bg-primary/10 px-1 text-[10px] font-medium text-primary">
+ default
+ </span>
+ )}
+ </div>
+ {m.label !== m.id && (
+ <div className="truncate font-mono text-[10px] text-muted-foreground">
+ {m.id}
+ </div>
+ )}
+ </div>
+ </PickerItem>
+ ))}
+
+ {!modelsQuery.isLoading && filtered.length === 0 && !canCreate && (
+ <p className="px-3 py-3 text-center text-xs text-muted-foreground">
+ No models available
+ </p>
+ )}
+
+ {canCreate && (
+ <PickerItem
+ selected={false}
+ onClick={() => void select(trimmedSearch)}
+ tooltip={`Use “${trimmedSearch}” as a custom model id`}
+ >
+ <Plus className="h-3.5 w-3.5 shrink-0 text-primary" />
+ <span className="truncate text-primary">
+ Use &ldquo;{trimmedSearch}&rdquo;
+ </span>
+ </PickerItem>
+ )}
+
+ {value && (
+ <button
+ type="button"
+ onClick={() => void select("")}
+ className="mt-1 flex w-full items-center border-t px-3 py-2 text-left text-xs text-muted-foreground transition-colors hover:bg-accent/50"
+ title="Clear and fall back to the runtime's provider default"
+ >
+ Clear (use provider default)
+ </button>
+ )}
+ </PropertyPicker>
+ );
+}
diff --git a/packages/views/agents/components/inspector/runtime-picker.tsx b/packages/views/agents/components/inspector/runtime-picker.tsx
new file mode 100644
index 0000000000..ce8178402c
--- /dev/null
+++ b/packages/views/agents/components/inspector/runtime-picker.tsx
@@ -0,0 +1,223 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { Cloud, Monitor } from "lucide-react";
+import type { AgentRuntime, MemberWithUser } from "@multica/core/types";
+import { ActorAvatar } from "../../../common/actor-avatar";
+import {
+ PickerItem,
+ PropertyPicker,
+} from "../../../issues/components/pickers";
+import { ProviderLogo } from "../../../runtimes/components/provider-logo";
+import { CHIP_CLASS } from "./chip";
+
+type Filter = "mine" | "all";
+
+/**
+ * Inline runtime picker for the agent inspector. Mirrors the runtime selector
+ * the previous Settings tab embedded — same Mine/All filter, same provider
+ * logos, same online dot — but renders inside the inspector's PropRow so
+ * users don't have to leave the page to switch runtime.
+ */
+export function RuntimePicker({
+ value,
+ runtimes,
+ members,
+ currentUserId,
+ onChange,
+}: {
+ value: string;
+ runtimes: AgentRuntime[];
+ members: MemberWithUser[];
+ currentUserId: string | null;
+ onChange: (runtimeId: string) => Promise<void> | void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [filter, setFilter] = useState<Filter>("mine");
+
+ const selected = runtimes.find((r) => r.id === value) ?? null;
+ const Icon = selected?.runtime_mode === "cloud" ? Cloud : Monitor;
+ // The chip shows only the runtime name. `runtime.name` already comes back
+ // from the back-end pre-formatted as e.g. "Claude (host.local)", so we
+ // deliberately do NOT append `device_info` to the tooltip — that string
+ // also leads with the host and would just repeat what's already in name,
+ // producing the "Claude (host) (host · 2.1.121 (Claude Code))" mess.
+ // device_info still shows on each row in the popover (small mono line),
+ // which is the right place for system detail.
+ const triggerLabel = selected?.name ?? "No runtime";
+ const isOnline = selected?.status === "online";
+ const triggerTitle = selected
+ ? `Runtime · ${selected.name} · ${isOnline ? "online" : "offline"}`
+ : "Runtime · none selected";
+
+ const hasOtherRuntimes = runtimes.some((r) => r.owner_id !== currentUserId);
+
+ const filtered = useMemo(() => {
+ const list =
+ filter === "mine" && currentUserId
+ ? runtimes.filter((r) => r.owner_id === currentUserId)
+ : runtimes;
+ return [...list].sort((a, b) => {
+ if (a.owner_id === currentUserId && b.owner_id !== currentUserId)
+ return -1;
+ if (a.owner_id !== currentUserId && b.owner_id === currentUserId)
+ return 1;
+ return 0;
+ });
+ }, [runtimes, filter, currentUserId]);
+
+ const getOwner = (id: string | null) =>
+ id ? members.find((m) => m.user_id === id) ?? null : null;
+
+ const select = async (id: string) => {
+ setOpen(false);
+ if (id !== value) await onChange(id);
+ };
+
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ width="w-auto min-w-[18rem] max-w-md"
+ align="start"
+ tooltip={triggerTitle}
+ triggerRender={
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ aria-label={triggerTitle}
+ />
+ }
+ trigger={
+ <>
+ <Icon className="h-3 w-3 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 truncate font-mono">{triggerLabel}</span>
+ {selected && (
+ <span
+ className={`ml-auto h-1.5 w-1.5 shrink-0 rounded-full ${
+ isOnline ? "bg-success" : "bg-muted-foreground/40"
+ }`}
+ />
+ )}
+ </>
+ }
+ header={
+ hasOtherRuntimes ? (
+ <div className="p-2">
+ <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">
+ <FilterButton
+ active={filter === "mine"}
+ onClick={() => setFilter("mine")}
+ >
+ Mine
+ </FilterButton>
+ <FilterButton
+ active={filter === "all"}
+ onClick={() => setFilter("all")}
+ >
+ All
+ </FilterButton>
+ </div>
+ </div>
+ ) : undefined
+ }
+ >
+ {filtered.length === 0 ? (
+ <p className="px-2 py-3 text-center text-xs text-muted-foreground">
+ No runtimes
+ </p>
+ ) : (
+ filtered.map((rt) => {
+ const owner = getOwner(rt.owner_id);
+ const rtOnline = rt.status === "online";
+ // Tooltip echoes the chip's structure: name + owner + status. Skip
+ // device_info because rt.name already embeds the host (it'd just
+ // repeat), and the row visually shows device_info on its second
+ // line anyway for users who do need that detail.
+ const tooltip = [
+ rt.name,
+ owner ? `owned by ${owner.name}` : null,
+ rtOnline ? "online" : "offline",
+ ]
+ .filter(Boolean)
+ .join(" · ");
+ return (
+ <PickerItem
+ key={rt.id}
+ selected={rt.id === value}
+ onClick={() => void select(rt.id)}
+ tooltip={tooltip}
+ >
+ <ProviderLogo
+ provider={rt.provider}
+ className="h-4 w-4 shrink-0"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate text-sm font-medium">
+ {rt.name}
+ </span>
+ {rt.runtime_mode === "cloud" && (
+ <span className="shrink-0 rounded bg-info/10 px-1 text-[10px] font-medium text-info">
+ Cloud
+ </span>
+ )}
+ </div>
+ <div className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground">
+ {owner && (
+ <span className="flex min-w-0 items-center gap-1">
+ <ActorAvatar
+ actorType="member"
+ actorId={owner.user_id}
+ size={12}
+ />
+ <span className="truncate">{owner.name}</span>
+ </span>
+ )}
+ {owner && rt.device_info && (
+ <span className="text-muted-foreground/40">·</span>
+ )}
+ {rt.device_info && (
+ <span className="truncate font-mono text-[10px]">
+ {rt.device_info}
+ </span>
+ )}
+ </div>
+ </div>
+ <span
+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${
+ rtOnline ? "bg-success" : "bg-muted-foreground/40"
+ }`}
+ aria-label={rtOnline ? "online" : "offline"}
+ />
+ </PickerItem>
+ );
+ })
+ )}
+ </PropertyPicker>
+ );
+}
+
+function FilterButton({
+ active,
+ onClick,
+ children,
+}: {
+ active: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`flex-1 rounded px-2 py-0.5 text-xs font-medium transition-colors ${
+ active
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {children}
+ </button>
+ );
+}
diff --git a/packages/views/agents/components/inspector/skill-attach.tsx b/packages/views/agents/components/inspector/skill-attach.tsx
new file mode 100644
index 0000000000..bd9b8cb30e
--- /dev/null
+++ b/packages/views/agents/components/inspector/skill-attach.tsx
@@ -0,0 +1,47 @@
+"use client";
+
+import { useState } from "react";
+import { Plus } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent } from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { skillListOptions } from "@multica/core/workspace/queries";
+import { SkillAddDialog } from "../skill-add-dialog";
+
+/**
+ * Inline "+ Attach" trigger for the inspector's Skills row. The trigger is
+ * the dashed-border chip; clicking it opens the shared `SkillAddDialog` —
+ * same surface the SkillsTab uses for its own "Add skill" button. Single
+ * source of truth for the attach flow, single visual for the picker.
+ *
+ * Hidden when there's nothing left to attach so we don't dangle a chip
+ * that opens an empty dialog.
+ */
+export function SkillAttach({ agent }: { agent: Agent }) {
+ const wsId = useWorkspaceId();
+ const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
+ const [open, setOpen] = useState(false);
+
+ const agentSkillIds = new Set(agent.skills.map((s) => s.id));
+ const availableCount = workspaceSkills.filter(
+ (s) => !agentSkillIds.has(s.id),
+ ).length;
+
+ if (availableCount === 0) return null;
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ aria-label="Attach a workspace skill"
+ title="Attach a workspace skill"
+ className="inline-flex cursor-pointer items-center gap-0.5 rounded-md border border-dashed border-muted-foreground/30 px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground/70 transition-colors hover:border-muted-foreground/60 hover:bg-accent/50 hover:text-muted-foreground"
+ >
+ <Plus className="h-2.5 w-2.5" />
+ Attach
+ </button>
+ <SkillAddDialog agent={agent} open={open} onOpenChange={setOpen} />
+ </>
+ );
+}
diff --git a/packages/views/agents/components/inspector/visibility-picker.tsx b/packages/views/agents/components/inspector/visibility-picker.tsx
new file mode 100644
index 0000000000..85be4bce43
--- /dev/null
+++ b/packages/views/agents/components/inspector/visibility-picker.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { useState } from "react";
+import { Globe, Lock } from "lucide-react";
+import type { AgentVisibility } from "@multica/core/types";
+import {
+ PickerItem,
+ PropertyPicker,
+} from "../../../issues/components/pickers";
+import { CHIP_CLASS } from "./chip";
+
+export function VisibilityPicker({
+ value,
+ onChange,
+}: {
+ value: AgentVisibility;
+ onChange: (next: AgentVisibility) => Promise<void> | void;
+}) {
+ const [open, setOpen] = useState(false);
+ const Icon = value === "private" ? Lock : Globe;
+ const label = value === "private" ? "Private" : "Workspace";
+ const tooltip =
+ value === "private"
+ ? "Visibility · Private — only you can assign"
+ : "Visibility · Workspace — all members can assign";
+
+ const select = async (next: AgentVisibility) => {
+ setOpen(false);
+ if (next !== value) await onChange(next);
+ };
+
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ width="w-auto min-w-[12rem]"
+ align="start"
+ tooltip={tooltip}
+ triggerRender={
+ <button type="button" className={CHIP_CLASS} aria-label={tooltip} />
+ }
+ trigger={
+ <>
+ <Icon className="h-3 w-3 shrink-0 text-muted-foreground" />
+ <span className="truncate">{label}</span>
+ </>
+ }
+ >
+ <PickerItem
+ selected={value === "workspace"}
+ onClick={() => select("workspace")}
+ >
+ <Globe className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <div className="text-left">
+ <div className="font-medium">Workspace</div>
+ <div className="text-xs text-muted-foreground">
+ All members can assign
+ </div>
+ </div>
+ </PickerItem>
+ <PickerItem
+ selected={value === "private"}
+ onClick={() => select("private")}
+ >
+ <Lock className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <div className="text-left">
+ <div className="font-medium">Private</div>
+ <div className="text-xs text-muted-foreground">
+ Only you can assign
+ </div>
+ </div>
+ </PickerItem>
+ </PropertyPicker>
+ );
+}
diff --git a/packages/views/agents/components/skill-add-dialog.tsx b/packages/views/agents/components/skill-add-dialog.tsx
new file mode 100644
index 0000000000..455d78163d
--- /dev/null
+++ b/packages/views/agents/components/skill-add-dialog.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { useState } from "react";
+import { FileText } from "lucide-react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { Agent } from "@multica/core/types";
+import { api } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ skillListOptions,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+
+/**
+ * Single source of truth for "attach a workspace skill to this agent".
+ * Used by both:
+ * - SkillsTab — full surface, "Add skill" button
+ * - Inspector → SkillAttach — inline dashed `+ Attach` chip
+ *
+ * Owns the workspace-skill list query, the "what's still attachable" filter,
+ * the API call, and the optimistic invalidation. Callers only manage the
+ * open/close state — they don't repeat the attach logic.
+ */
+export function SkillAddDialog({
+ agent,
+ open,
+ onOpenChange,
+}: {
+ agent: Agent;
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+}) {
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
+ const [saving, setSaving] = useState(false);
+
+ const agentSkillIds = new Set(agent.skills.map((s) => s.id));
+ const availableSkills = workspaceSkills.filter(
+ (s) => !agentSkillIds.has(s.id),
+ );
+
+ const handleAdd = async (skillId: string) => {
+ setSaving(true);
+ try {
+ const newIds = [...agent.skills.map((s) => s.id), skillId];
+ await api.setAgentSkills(agent.id, { skill_ids: newIds });
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ onOpenChange(false);
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : "Failed to add skill");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle className="text-sm">Add skill</DialogTitle>
+ <DialogDescription className="text-xs">
+ Select a workspace skill to assign to this agent.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="max-h-64 space-y-1 overflow-y-auto">
+ {availableSkills.map((skill) => (
+ <button
+ key={skill.id}
+ onClick={() => handleAdd(skill.id)}
+ disabled={saving}
+ className="flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-accent/50"
+ >
+ <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{skill.name}</div>
+ {skill.description && (
+ <div className="truncate text-xs text-muted-foreground">
+ {skill.description}
+ </div>
+ )}
+ </div>
+ </button>
+ ))}
+ {availableSkills.length === 0 && (
+ <p className="py-6 text-center text-xs text-muted-foreground">
+ All workspace skills are already assigned.
+ </p>
+ )}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/agents/components/sparkline.tsx b/packages/views/agents/components/sparkline.tsx
new file mode 100644
index 0000000000..579a10e511
--- /dev/null
+++ b/packages/views/agents/components/sparkline.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+interface ActivityBucketLike {
+ total: number;
+ failed: number;
+}
+
+interface SparklineProps {
+ /**
+ * Buckets in display order (oldest → newest). One column per bucket;
+ * total drives column height, failed renders on top in destructive so
+ * the column conveys *throughput + failure share* in one glance — both
+ * dimensions live on the same shape, no extra row chrome required.
+ */
+ buckets: readonly ActivityBucketLike[];
+ width: number;
+ height: number;
+ className?: string;
+}
+
+const SUCCESS_FILL = "var(--color-brand)";
+const SUCCESS_OPACITY = 0.6;
+const FAILED_FILL = "var(--color-destructive)";
+const BASELINE_FILL = "var(--color-muted-foreground)";
+const BASELINE_OPACITY = 0.25;
+
+/**
+ * Stacked bar sparkline — success bottom, failure top. One row, one shape,
+ * two dimensions:
+ *
+ * - **Column height** = total throughput that day (per-component scaled
+ * so a quiet agent reads "its own shape", not flattened by a noisy
+ * neighbour).
+ * - **Red share** = failure rate. A 100-runs-1-failed agent and a
+ * 100-runs-99-failed agent must be told apart at scan speed; the only
+ * way to do that with a single column is to encode the second
+ * dimension *inside* the column.
+ *
+ * Why not just colour the whole column red on any failure (the "binary"
+ * approach we shipped first)? Because it loses the failure-rate dimension
+ * — 1/100 and 99/100 paint the same. Splitting the segment keeps the
+ * dimension while staying within "one element per cell", which is the
+ * scan-speed budget.
+ *
+ * Pre-life days (the agent didn't exist yet) and real zero days look the
+ * same here on purpose — distinguishing them adds row variety the column
+ * doesn't earn (Tufte data-ink); the tooltip carries "Created N days ago"
+ * where it actually matters.
+ */
+export function Sparkline({
+ buckets,
+ width,
+ height,
+ className,
+}: SparklineProps) {
+ const n = buckets.length;
+ if (n === 0) {
+ return (
+ <svg
+ width={width}
+ height={height}
+ viewBox={`0 0 ${width} ${height}`}
+ className={className}
+ aria-hidden
+ />
+ );
+ }
+
+ // Column geometry — gap = 1px, columns share the rest equally. Round to
+ // whole pixels so sub-pixel rects don't render fuzzy at this size.
+ const gap = 1;
+ const colWidth = Math.max(1, Math.floor((width - gap * (n - 1)) / n));
+ const usedWidth = colWidth * n + gap * (n - 1);
+ const offsetX = Math.floor((width - usedWidth) / 2);
+
+ // Per-component max so a low-volume agent's shape isn't flattened by a
+ // single noisy day from a neighbour.
+ let maxTotal = 0;
+ for (const b of buckets) if (b.total > maxTotal) maxTotal = b.total;
+ const scaleDenominator = Math.max(1, maxTotal);
+
+ // Reserve 1px so columns visually sit on something rather than floating.
+ const baselineY = height - 1;
+ const usableH = height - 1;
+
+ return (
+ <svg
+ width={width}
+ height={height}
+ viewBox={`0 0 ${width} ${height}`}
+ className={className}
+ aria-hidden
+ >
+ {/* Faint floor — a row with zero history still reads as "a row",
+ not a missing cell. */}
+ <rect
+ x={0}
+ y={baselineY}
+ width={width}
+ height={1}
+ fill={BASELINE_FILL}
+ fillOpacity={BASELINE_OPACITY}
+ />
+ {buckets.map((b, i) => {
+ if (b.total === 0) return null;
+ const x = offsetX + i * (colWidth + gap);
+ const totalH = Math.max(
+ 1,
+ Math.round((usableH * b.total) / scaleDenominator),
+ );
+ // 1px floor on the failed segment so a single failure is still
+ // visible; clamp by total so 1-of-1 doesn't make the failed
+ // segment taller than the column itself.
+ const failedH =
+ b.failed > 0
+ ? Math.min(
+ totalH,
+ Math.max(1, Math.round((usableH * b.failed) / scaleDenominator)),
+ )
+ : 0;
+ const successH = totalH - failedH;
+ const colTop = baselineY - totalH;
+ return (
+ <g key={i}>
+ {successH > 0 && (
+ <rect
+ x={x}
+ y={colTop + failedH}
+ width={colWidth}
+ height={successH}
+ fill={SUCCESS_FILL}
+ fillOpacity={SUCCESS_OPACITY}
+ />
+ )}
+ {failedH > 0 && (
+ <rect
+ x={x}
+ y={colTop}
+ width={colWidth}
+ height={failedH}
+ fill={FAILED_FILL}
+ />
+ )}
+ </g>
+ );
+ })}
+ </svg>
+ );
+}
diff --git a/packages/views/agents/components/tabs/activity-tab.test.ts b/packages/views/agents/components/tabs/activity-tab.test.ts
new file mode 100644
index 0000000000..822678e63e
--- /dev/null
+++ b/packages/views/agents/components/tabs/activity-tab.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vitest";
+import type { AgentTask } from "@multica/core/types";
+import {
+ deriveAvgDurationLast30d,
+ formatDurationMs,
+} from "./activity-tab";
+
+const NOW = new Date("2026-04-28T12:00:00Z").getTime();
+const HOUR = 60 * 60 * 1000;
+const DAY = 24 * HOUR;
+
+function task(overrides: Partial<AgentTask>): AgentTask {
+ return {
+ id: "t",
+ agent_id: "a",
+ runtime_id: "r",
+ issue_id: "",
+ status: "completed",
+ priority: 0,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ result: null,
+ error: null,
+ created_at: new Date(NOW - HOUR).toISOString(),
+ ...overrides,
+ };
+}
+
+describe("deriveAvgDurationLast30d", () => {
+ it("returns 0 when no tasks have both started_at and completed_at", () => {
+ const tasks = [
+ task({ started_at: null, completed_at: new Date(NOW).toISOString() }),
+ task({
+ started_at: new Date(NOW - HOUR).toISOString(),
+ completed_at: null,
+ }),
+ ];
+ expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(0);
+ });
+
+ it("averages durations across in-window tasks", () => {
+ const tasks = [
+ task({
+ started_at: new Date(NOW - 60_000).toISOString(),
+ completed_at: new Date(NOW).toISOString(),
+ }), // 60s
+ task({
+ started_at: new Date(NOW - 180_000).toISOString(),
+ completed_at: new Date(NOW).toISOString(),
+ }), // 180s
+ ];
+ expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(120_000);
+ });
+
+ it("excludes tasks completed more than 30 days ago", () => {
+ const tasks = [
+ task({
+ started_at: new Date(NOW - 60_000).toISOString(),
+ completed_at: new Date(NOW).toISOString(),
+ }), // in window, 60s
+ task({
+ started_at: new Date(NOW - 60 * DAY - 60_000).toISOString(),
+ completed_at: new Date(NOW - 60 * DAY).toISOString(),
+ }), // 60d ago, ignored
+ ];
+ expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(60_000);
+ });
+
+ it("ignores non-positive durations defensively", () => {
+ const tasks = [
+ task({
+ // Wall-clock anomaly: completed before it started. The aggregation
+ // should still produce a sensible average from the well-formed rows
+ // rather than poisoning the count with a zero-or-negative entry.
+ started_at: new Date(NOW).toISOString(),
+ completed_at: new Date(NOW - 1000).toISOString(),
+ }),
+ task({
+ started_at: new Date(NOW - 4000).toISOString(),
+ completed_at: new Date(NOW).toISOString(),
+ }), // 4s
+ ];
+ expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(4000);
+ });
+});
+
+describe("formatDurationMs", () => {
+ it("renders sub-minute durations in seconds", () => {
+ expect(formatDurationMs(800)).toBe("1s"); // floor avoidance
+ expect(formatDurationMs(12_000)).toBe("12s");
+ expect(formatDurationMs(59_500)).toBe("60s");
+ });
+
+ it("renders sub-hour durations as 'm SS' with padded seconds", () => {
+ expect(formatDurationMs(60_000)).toBe("1m 00s");
+ expect(formatDurationMs(125_000)).toBe("2m 05s");
+ expect(formatDurationMs(605_000)).toBe("10m 05s");
+ });
+
+ it("renders multi-hour durations as 'h m'", () => {
+ expect(formatDurationMs(3 * 60 * 60_000 + 30 * 60_000)).toBe("3h 30m");
+ });
+
+ it("handles zero / negative defensively", () => {
+ expect(formatDurationMs(0)).toBe("—");
+ expect(formatDurationMs(-100)).toBe("—");
+ });
+});
diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsx
new file mode 100644
index 0000000000..cc33f9e64d
--- /dev/null
+++ b/packages/views/agents/components/tabs/activity-tab.tsx
@@ -0,0 +1,540 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { useMemo } from "react";
+import {
+ ArrowUpRight,
+ CircleHelp,
+ Hash,
+ MessageSquare,
+ Workflow,
+} from "lucide-react";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { useQueries, useQuery } from "@tanstack/react-query";
+import type {
+ Agent,
+ AgentTask,
+ Issue,
+ TaskFailureReason,
+} from "@multica/core/types";
+import {
+ type AgentActivity,
+ agentTaskSnapshotOptions,
+ agentTasksOptions,
+ summarizeActivityWindow,
+ useWorkspaceActivityMap,
+} from "@multica/core/agents";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import { timeAgo } from "@multica/core/utils";
+import { AppLink } from "../../../navigation";
+import { TranscriptButton } from "../../../common/task-transcript";
+import { taskStatusConfig } from "../../config";
+import { failureReasonLabel } from "../../presence";
+import { Sparkline } from "../sparkline";
+
+const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
+const RECENT_LIMIT = 5;
+
+interface ActivityTabProps {
+ agent: Agent;
+}
+
+/**
+ * Right-pane Activity tab on the agent detail page. Three sections framed
+ * around the user's three diagnostic questions, in scan order:
+ *
+ * Now — what's it doing right this second?
+ * Last 7 days — how has it been doing in aggregate?
+ * Recent work — what did it just finish?
+ *
+ * All three read from caches the rest of the page already fills (the
+ * workspace task snapshot for "Now", per-agent task list for "Recent",
+ * the workspace 7d activity buckets for the trend), so opening this tab
+ * adds no extra fetches once the page is hydrated.
+ */
+export function ActivityTab({ agent }: ActivityTabProps) {
+ const wsId = useWorkspaceId();
+
+ const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));
+ const { data: agentTasks = [] } = useQuery(agentTasksOptions(wsId, agent.id));
+ const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);
+ const activity = activityMap.get(agent.id);
+
+ const activeTasks = useMemo(() => {
+ return snapshot.filter(
+ (t) =>
+ t.agent_id === agent.id &&
+ (t.status === "running" ||
+ t.status === "queued" ||
+ t.status === "dispatched"),
+ );
+ }, [snapshot, agent.id]);
+
+ // Most recent terminal tasks. Includes cancelled — users searching
+ // "what just happened" want to see cancellations alongside completions
+ // and failures.
+ const recentTasks = useMemo(() => {
+ return [...agentTasks]
+ .filter(
+ (t) =>
+ !!t.completed_at &&
+ (t.status === "completed" ||
+ t.status === "failed" ||
+ t.status === "cancelled"),
+ )
+ .sort(
+ (a, b) =>
+ new Date(b.completed_at!).getTime() -
+ new Date(a.completed_at!).getTime(),
+ )
+ .slice(0, RECENT_LIMIT);
+ }, [agentTasks]);
+
+ const avgDurationMs = useMemo(
+ () => deriveAvgDurationLast30d(agentTasks, Date.now()),
+ [agentTasks],
+ );
+
+ // Resolve issue identifiers + titles for any task we'll render. Going
+ // through `issueDetailOptions` is the same lookup the rest of the app
+ // uses, so the cache is shared and we don't pay for a duplicate request.
+ const displayedTasks = useMemo(
+ () => [...activeTasks, ...recentTasks],
+ [activeTasks, recentTasks],
+ );
+ const issueIds = useMemo(
+ () =>
+ Array.from(
+ new Set(displayedTasks.map((t) => t.issue_id).filter((id) => id !== "")),
+ ),
+ [displayedTasks],
+ );
+ const issueQueries = useQueries({
+ queries: issueIds.map((id) => issueDetailOptions(wsId, id)),
+ });
+ const issueMap = useMemo(() => {
+ const m = new Map<string, Issue>();
+ issueQueries.forEach((q, i) => {
+ const id = issueIds[i]!;
+ if (q.data) m.set(id, q.data);
+ });
+ return m;
+ }, [issueQueries, issueIds]);
+
+ return (
+ <div className="flex flex-col gap-4 p-6">
+ <NowSection tasks={activeTasks} issueMap={issueMap} agent={agent} />
+ <Last30dSection activity={activity} avgDurationMs={avgDurationMs} />
+ <RecentWorkSection
+ tasks={recentTasks}
+ issueMap={issueMap}
+ agent={agent}
+ />
+ </div>
+ );
+}
+
+function NowSection({
+ tasks,
+ issueMap,
+ agent,
+}: {
+ tasks: AgentTask[];
+ issueMap: Map<string, Issue>;
+ agent: Agent;
+}) {
+ return (
+ <Section
+ title="Now"
+ subtitle={
+ tasks.length === 0
+ ? "No active work"
+ : `${tasks.length} active task${tasks.length === 1 ? "" : "s"}`
+ }
+ >
+ {tasks.length === 0 ? (
+ <EmptyText>This agent isn&apos;t running anything right now.</EmptyText>
+ ) : (
+ <TaskList
+ tasks={tasks}
+ issueMap={issueMap}
+ timeMode="active"
+ agent={agent}
+ />
+ )}
+ </Section>
+ );
+}
+
+function Last30dSection({
+ activity,
+ avgDurationMs,
+}: {
+ activity: AgentActivity | undefined;
+ avgDurationMs: number;
+}) {
+ const summary = summarizeActivityWindow(activity, 30);
+ const { totalRuns, totalFailed } = summary;
+ const successPct =
+ totalRuns > 0
+ ? Math.round(((totalRuns - totalFailed) / totalRuns) * 100)
+ : 100;
+
+ return (
+ <Section title="Last 30 days" subtitle="Performance">
+ {totalRuns === 0 ? (
+ <EmptyText>No completions in the last 30 days.</EmptyText>
+ ) : (
+ // Layout: number is the hero, sparkline is a garnish on the
+ // right. Reversed from "chart hero + tiny number" because at
+ // detail-page sample sizes (often <30 over the window) a wide
+ // sparkline reads as mostly-empty space, which looks broken;
+ // the headline number stays legible at any sample size and
+ // anchors the section. Stripe / Vercel / Shopify metric cards
+ // all follow this pattern for the same reason.
+ <div className="flex items-end justify-between gap-5">
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex items-baseline gap-1.5">
+ <span className="text-3xl font-bold leading-none tabular-nums">
+ {totalRuns}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ run{totalRuns === 1 ? "" : "s"}
+ </span>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {successPct}% success
+ {avgDurationMs > 0 && (
+ <>
+ <Sep />
+ <span>avg {formatDurationMs(avgDurationMs)}</span>
+ </>
+ )}
+ {totalFailed > 0 && (
+ <>
+ <Sep />
+ <span className="text-destructive">
+ {totalFailed} failed
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ {/* Garnish, not hero — small enough that a sparse 30-day series
+ doesn't read as visually broken. Bottom-aligned with the
+ number so the dense end of the bars sits on the same
+ baseline as the digits. */}
+ <Sparkline
+ buckets={summary.buckets}
+ width={120}
+ height={32}
+ className="shrink-0"
+ />
+ </div>
+ )}
+ </Section>
+ );
+}
+
+function RecentWorkSection({
+ tasks,
+ issueMap,
+ agent,
+}: {
+ tasks: AgentTask[];
+ issueMap: Map<string, Issue>;
+ agent: Agent;
+}) {
+ return (
+ <Section
+ title="Recent work"
+ subtitle={
+ tasks.length === 0
+ ? "Nothing finished yet"
+ : `${tasks.length} latest`
+ }
+ >
+ {tasks.length === 0 ? (
+ <EmptyText>This agent hasn&apos;t completed anything yet.</EmptyText>
+ ) : (
+ <TaskList
+ tasks={tasks}
+ issueMap={issueMap}
+ timeMode="completed"
+ agent={agent}
+ />
+ )}
+ </Section>
+ );
+}
+
+function TaskList({
+ tasks,
+ issueMap,
+ timeMode,
+ agent,
+}: {
+ tasks: AgentTask[];
+ issueMap: Map<string, Issue>;
+ timeMode: "active" | "completed";
+ agent: Agent;
+}) {
+ return (
+ <div className="space-y-1.5">
+ {tasks.map((task) => (
+ <TaskRow
+ key={task.id}
+ task={task}
+ issueMap={issueMap}
+ timeMode={timeMode}
+ agent={agent}
+ />
+ ))}
+ </div>
+ );
+}
+
+function TaskRow({
+ task,
+ issueMap,
+ timeMode,
+ agent,
+}: {
+ task: AgentTask;
+ issueMap: Map<string, Issue>;
+ timeMode: "active" | "completed";
+ agent: Agent;
+}) {
+ const paths = useWorkspacePaths();
+ const cfg = taskStatusConfig[task.status] ?? taskStatusConfig.queued!;
+ const Icon = cfg.icon;
+ const hasIssue = task.issue_id !== "";
+ const issue = hasIssue ? issueMap.get(task.issue_id) : undefined;
+ const isRunning = task.status === "running";
+ // Queued tasks have no messages yet — hiding the transcript button avoids
+ // a guaranteed "No execution data recorded." dialog open.
+ const showTranscript = task.status !== "queued";
+
+ const sourceFallback = !hasIssue
+ ? task.chat_session_id
+ ? "Chat session"
+ : task.autopilot_run_id
+ ? "Autopilot run"
+ : "Untracked"
+ : null;
+
+ // Origin marker — issue / chat / autopilot / untracked. The issue
+ // identifier alone is technically enough for the issue case, but
+ // pairing it with a Hash icon keeps the four sources visually aligned
+ // so the row reads at a glance instead of requiring a parse.
+ const SourceIcon = hasIssue
+ ? Hash
+ : task.chat_session_id
+ ? MessageSquare
+ : task.autopilot_run_id
+ ? Workflow
+ : CircleHelp;
+ const sourceLabel = hasIssue
+ ? "Issue"
+ : task.chat_session_id
+ ? "Chat"
+ : task.autopilot_run_id
+ ? "Autopilot"
+ : "Untracked";
+
+ const timeText =
+ timeMode === "active"
+ ? activeTaskTimeText(task)
+ : task.completed_at
+ ? timeAgo(task.completed_at)
+ : "—";
+
+ // Failure reason. The back-end emits "" on non-failed tasks (omitempty
+ // strips it on the wire) so the truthy guard is the right shape; the
+ // cast is safe because the back-end only emits one of the enum values.
+ const failureLabel =
+ task.status === "failed" && task.failure_reason
+ ? failureReasonLabel[task.failure_reason as TaskFailureReason]
+ : null;
+
+ // Only show duration for terminal rows. An active row's duration is
+ // inferred from the timeText already ("Started 2m ago") and adding a
+ // second time bubble next to it just clutters the line.
+ let durationText: string | null = null;
+ if (timeMode === "completed" && task.started_at && task.completed_at) {
+ const dur =
+ new Date(task.completed_at).getTime() -
+ new Date(task.started_at).getTime();
+ if (dur > 0) durationText = formatDurationMs(dur);
+ }
+
+ const rowClass = `group flex items-center gap-3 rounded-md border px-3 py-2.5 ${
+ isRunning ? "border-success/40 bg-success/5" : ""
+ }`;
+
+ return (
+ <div className={rowClass}>
+ <Icon
+ className={`h-4 w-4 shrink-0 ${cfg.color} ${
+ isRunning ? "animate-spin" : ""
+ }`}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <SourceIcon
+ className="h-3 w-3 shrink-0 text-muted-foreground/70"
+ aria-label={sourceLabel}
+ />
+ {issue && (
+ <span className="shrink-0 font-mono text-xs text-muted-foreground">
+ {issue.identifier}
+ </span>
+ )}
+ <span className="truncate text-sm">
+ {issue?.title ??
+ (hasIssue
+ ? `Issue ${task.issue_id.slice(0, 8)}…`
+ : (sourceFallback ?? "Untracked"))}
+ </span>
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
+ <span>{timeText}</span>
+ {durationText && (
+ <>
+ <Sep />
+ <span>{durationText}</span>
+ </>
+ )}
+ {failureLabel && (
+ <>
+ <Sep />
+ <span className="text-destructive">{failureLabel}</span>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Hover-only actions. The row is intentionally non-clickable so
+ neither destination is privileged — issue detail and transcript
+ are equally valid follow-ups. focus-within keeps the slot
+ reachable for keyboard users. */}
+ <div className="ml-2 flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-100 group-hover:opacity-100 group-focus-within:opacity-100">
+ {hasIssue && (
+ <Tooltip>
+ <TooltipTrigger
+ render={<AppLink href={paths.issueDetail(task.issue_id)} />}
+ aria-label="Open issue"
+ className="flex items-center justify-center rounded p-1 text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors"
+ >
+ <ArrowUpRight className="h-3.5 w-3.5" />
+ </TooltipTrigger>
+ <TooltipContent>Open issue</TooltipContent>
+ </Tooltip>
+ )}
+ {showTranscript && (
+ <TranscriptButton
+ task={task}
+ agentName={agent.name}
+ isLive={isRunning}
+ title="View transcript"
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Section({
+ title,
+ subtitle,
+ children,
+}: {
+ title: string;
+ subtitle: string;
+ children: ReactNode;
+}) {
+ return (
+ <section className="flex flex-col gap-3 rounded-lg border bg-background p-5">
+ <div className="flex items-baseline gap-2">
+ <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
+ {title}
+ </h3>
+ <span className="text-[11px] text-muted-foreground/70">{subtitle}</span>
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function EmptyText({ children }: { children: ReactNode }) {
+ return <p className="text-xs italic text-muted-foreground/60">{children}</p>;
+}
+
+function Sep() {
+ // mx-1 puts visible whitespace around the dot; without it inline JSX
+ // collapses neighbouring tokens to "100% success·avg 30s" which reads
+ // as "successdotavg" at a glance.
+ return <span className="mx-1 text-muted-foreground/40">·</span>;
+}
+
+function activeTaskTimeText(task: AgentTask): string {
+ if (task.status === "running" && task.started_at) {
+ return `Started ${timeAgo(task.started_at)}`;
+ }
+ if (task.status === "dispatched" && task.dispatched_at) {
+ return `Dispatched ${timeAgo(task.dispatched_at)}`;
+ }
+ return `Queued ${timeAgo(task.created_at)}`;
+}
+
+/**
+ * Average wall-clock duration of completed/failed tasks whose completion
+ * lands in the last 30 days. Pure function so callers can pass a
+ * deterministic `now` in tests.
+ */
+export function deriveAvgDurationLast30d(
+ tasks: readonly AgentTask[],
+ now: number,
+): number {
+ let sum = 0;
+ let count = 0;
+ for (const t of tasks) {
+ if (!t.completed_at || !t.started_at) continue;
+ const completedAt = new Date(t.completed_at).getTime();
+ if (Number.isNaN(completedAt)) continue;
+ if (now - completedAt > THIRTY_DAYS_MS) continue;
+ const startedAt = new Date(t.started_at).getTime();
+ const dur = completedAt - startedAt;
+ if (Number.isFinite(dur) && dur > 0) {
+ sum += dur;
+ count += 1;
+ }
+ }
+ return count > 0 ? Math.round(sum / count) : 0;
+}
+
+/**
+ * Compact human-readable duration ("12s", "2m 04s", "1h 30m"). Pads the
+ * seconds inside the minute formatter so the column stays visually
+ * aligned across rows.
+ */
+export function formatDurationMs(ms: number): string {
+ if (ms <= 0) return "—";
+ if (ms < 60_000) {
+ return `${Math.max(1, Math.round(ms / 1000))}s`;
+ }
+ if (ms < 60 * 60_000) {
+ const m = Math.floor(ms / 60_000);
+ const s = Math.round((ms % 60_000) / 1000);
+ return `${m}m ${String(s).padStart(2, "0")}s`;
+ }
+ const h = Math.floor(ms / (60 * 60_000));
+ const m = Math.floor((ms % (60 * 60_000)) / 60_000);
+ return `${h}h ${m}m`;
+}
diff --git a/packages/views/agents/components/tabs/custom-args-tab.tsx b/packages/views/agents/components/tabs/custom-args-tab.tsx
index 36ec733c6f..feedcad3c2 100644
--- a/packages/views/agents/components/tabs/custom-args-tab.tsx
+++ b/packages/views/agents/components/tabs/custom-args-tab.tsx
@@ -1,17 +1,11 @@
"use client";
-import { useState } from "react";
-import {
- Loader2,
- Save,
- Plus,
- Trash2,
-} from "lucide-react";
+import { useEffect, useState } from "react";
+import { Loader2, Plus, Save, Trash2 } from "lucide-react";
import type { Agent, RuntimeDevice } from "@multica/core/types";
import { createSafeId } from "@multica/core/utils";
import { Button } from "@multica/ui/components/ui/button";
import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
import { toast } from "sonner";
interface ArgEntry {
@@ -23,6 +17,11 @@ function argsToEntries(args: string[]): ArgEntry[] {
return args.map((value) => ({ id: createSafeId(), value }));
}
+// Each row may contain a single arg ("--model") or several space-separated
+// tokens ("--model claude-sonnet-4"). We split on whitespace so users can
+// paste multi-token flags into one row without having to break them apart
+// manually. The placeholder + helper text explain this so users aren't
+// surprised when "--flag value" lands as two args at the back-end.
function entriesToArgs(entries: ArgEntry[]): string[] {
return entries.flatMap((e) => e.value.trim().split(/\s+/)).filter(Boolean);
}
@@ -31,10 +30,12 @@ export function CustomArgsTab({
agent,
runtimeDevice,
onSave,
+ onDirtyChange,
}: {
agent: Agent;
runtimeDevice?: RuntimeDevice;
onSave: (updates: Partial<Agent>) => Promise<void>;
+ onDirtyChange?: (dirty: boolean) => void;
}) {
const [entries, setEntries] = useState<ArgEntry[]>(
argsToEntries(agent.custom_args ?? []),
@@ -45,6 +46,10 @@ export function CustomArgsTab({
const originalArgs = agent.custom_args ?? [];
const dirty = JSON.stringify(currentArgs) !== JSON.stringify(originalArgs);
+ useEffect(() => {
+ onDirtyChange?.(dirty);
+ }, [dirty, onDirtyChange]);
+
const addEntry = () => {
setEntries([...entries, { id: createSafeId(), value: "" }]);
};
@@ -74,18 +79,16 @@ export function CustomArgsTab({
const launchHeader = runtimeDevice?.launch_header;
return (
- <div className="max-w-lg space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <Label className="text-xs text-muted-foreground">
- Custom Arguments
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
+ <div className="space-y-4">
+ <div className="flex items-start justify-between gap-3">
+ <div className="space-y-1">
+ <p className="text-xs text-muted-foreground">
Additional CLI arguments appended to the agent command at launch.
- Supported flags depend on the agent's CLI.
+ Multi-token flags can share one row — they&apos;ll be split on
+ whitespace before being passed to the CLI.
</p>
{launchHeader && (
- <p className="mt-2 text-xs text-muted-foreground">
+ <p className="text-xs text-muted-foreground">
Launch mode:{" "}
<code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
{launchHeader} &lt;your args&gt;
@@ -98,12 +101,13 @@ export function CustomArgsTab({
variant="outline"
size="sm"
onClick={addEntry}
- className="h-7 gap-1 text-xs"
+ className="shrink-0"
>
<Plus className="h-3 w-3" />
Add
</Button>
</div>
+
{entries.length > 0 && (
<div className="space-y-2">
{entries.map((entry, index) => (
@@ -114,26 +118,33 @@ export function CustomArgsTab({
placeholder="--flag value"
className="flex-1 font-mono text-xs"
/>
- <button
- type="button"
+ <Button
+ variant="ghost"
+ size="icon-sm"
onClick={() => removeEntry(index)}
- className="shrink-0 text-muted-foreground hover:text-destructive"
+ className="text-muted-foreground hover:text-destructive"
+ aria-label="Remove argument"
>
<Trash2 className="h-3.5 w-3.5" />
- </button>
+ </Button>
</div>
))}
</div>
)}
- <Button onClick={handleSave} disabled={!dirty || saving} size="sm">
- {saving ? (
- <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
- ) : (
- <Save className="h-3.5 w-3.5 mr-1.5" />
+ <div className="flex items-center justify-end gap-3">
+ {dirty && (
+ <span className="text-xs text-muted-foreground">Unsaved changes</span>
)}
- Save
- </Button>
+ <Button onClick={handleSave} disabled={!dirty || saving} size="sm">
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Save className="h-3.5 w-3.5" />
+ )}
+ Save
+ </Button>
+ </div>
</div>
);
}
diff --git a/packages/views/agents/components/tabs/env-tab.tsx b/packages/views/agents/components/tabs/env-tab.tsx
index 17e8faeead..7637b6926e 100644
--- a/packages/views/agents/components/tabs/env-tab.tsx
+++ b/packages/views/agents/components/tabs/env-tab.tsx
@@ -1,19 +1,18 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import {
- Loader2,
- Save,
- Plus,
- Trash2,
Eye,
EyeOff,
+ Loader2,
Lock,
+ Plus,
+ Save,
+ Trash2,
} from "lucide-react";
import type { Agent } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
import { toast } from "sonner";
let nextEnvId = 0;
@@ -49,10 +48,12 @@ export function EnvTab({
agent,
readOnly = false,
onSave,
+ onDirtyChange,
}: {
agent: Agent;
readOnly?: boolean;
onSave: (updates: Partial<Agent>) => Promise<void>;
+ onDirtyChange?: (dirty: boolean) => void;
}) {
const [envEntries, setEnvEntries] = useState<EnvEntry[]>(
envMapToEntries(agent.custom_env ?? {}),
@@ -64,6 +65,10 @@ export function EnvTab({
const dirty =
JSON.stringify(currentEnvMap) !== JSON.stringify(originalEnvMap);
+ useEffect(() => {
+ onDirtyChange?.(dirty);
+ }, [dirty, onDirtyChange]);
+
const addEnvEntry = () => {
setEnvEntries([
...envEntries,
@@ -116,15 +121,11 @@ export function EnvTab({
if (readOnly) {
return (
- <div className="max-w-lg space-y-4">
- <div>
- <Label className="text-xs text-muted-foreground">
- Environment Variables
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- Injected into the agent process at launch. Values are hidden — only the agent owner or workspace admin can view and edit them.
- </p>
- </div>
+ <div className="space-y-4">
+ <p className="text-xs text-muted-foreground">
+ Injected into the agent process at launch. Values are hidden — only
+ the agent owner or workspace admin can view and edit them.
+ </p>
{envEntries.length > 0 ? (
<div className="space-y-2">
{envEntries.map((entry) => (
@@ -132,50 +133,55 @@ export function EnvTab({
<Input
value={entry.key}
readOnly
- className="w-[40%] font-mono text-xs bg-muted"
+ className="w-[40%] bg-muted font-mono text-xs"
/>
<div className="relative flex-1">
<Input
type="password"
value="****"
readOnly
- className="pr-8 font-mono text-xs bg-muted"
+ className="bg-muted pr-8 font-mono text-xs"
/>
- <Lock className="absolute right-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
+ <Lock className="absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
</div>
</div>
))}
</div>
) : (
- <p className="text-xs text-muted-foreground italic">No environment variables configured.</p>
+ <p className="text-xs italic text-muted-foreground">
+ No environment variables configured.
+ </p>
)}
</div>
);
}
return (
- <div className="max-w-lg space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <Label className="text-xs text-muted-foreground">
- Environment Variables
- </Label>
- <p className="text-xs text-muted-foreground mt-0.5">
- Injected into the agent process at launch (e.g. ANTHROPIC_API_KEY,
- ANTHROPIC_BASE_URL)
- </p>
- </div>
+ <div className="space-y-4">
+ <div className="flex items-start justify-between gap-3">
+ <p className="text-xs text-muted-foreground">
+ Injected into the agent process at launch (e.g.{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
+ ANTHROPIC_API_KEY
+ </code>
+ ,{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[11px]">
+ ANTHROPIC_BASE_URL
+ </code>
+ ).
+ </p>
<Button
type="button"
variant="outline"
size="sm"
onClick={addEnvEntry}
- className="h-7 gap-1 text-xs"
+ className="shrink-0"
>
<Plus className="h-3 w-3" />
Add
</Button>
</div>
+
{envEntries.length > 0 && (
<div className="space-y-2">
{envEntries.map((entry, index) => (
@@ -200,6 +206,7 @@ export function EnvTab({
type="button"
onClick={() => toggleEnvVisibility(index)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ aria-label={entry.visible ? "Hide value" : "Show value"}
>
{entry.visible ? (
<EyeOff className="h-3.5 w-3.5" />
@@ -208,26 +215,33 @@ export function EnvTab({
)}
</button>
</div>
- <button
- type="button"
+ <Button
+ variant="ghost"
+ size="icon-sm"
onClick={() => removeEnvEntry(index)}
- className="shrink-0 text-muted-foreground hover:text-destructive"
+ className="text-muted-foreground hover:text-destructive"
+ aria-label="Remove variable"
>
<Trash2 className="h-3.5 w-3.5" />
- </button>
+ </Button>
</div>
))}
</div>
)}
- <Button onClick={handleSave} disabled={!dirty || saving} size="sm">
- {saving ? (
- <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
- ) : (
- <Save className="h-3.5 w-3.5 mr-1.5" />
+ <div className="flex items-center justify-end gap-3">
+ {dirty && (
+ <span className="text-xs text-muted-foreground">Unsaved changes</span>
)}
- Save
- </Button>
+ <Button onClick={handleSave} disabled={!dirty || saving} size="sm">
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Save className="h-3.5 w-3.5" />
+ )}
+ Save
+ </Button>
+ </div>
</div>
);
}
diff --git a/packages/views/agents/components/tabs/instructions-tab.tsx b/packages/views/agents/components/tabs/instructions-tab.tsx
index 419966f6c8..890b9a3964 100644
--- a/packages/views/agents/components/tabs/instructions-tab.tsx
+++ b/packages/views/agents/components/tabs/instructions-tab.tsx
@@ -1,16 +1,33 @@
"use client";
-import { useState, useEffect } from "react";
+import { useEffect, useState } from "react";
import { Loader2, Save } from "lucide-react";
import type { Agent } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
+import { ContentEditor } from "../../../editor/content-editor";
+
+const INSTRUCTIONS_PLACEHOLDER = `Define this agent's role, expertise, and working style.
+
+# Example
+You are a frontend engineer specializing in React and TypeScript.
+
+## Working Style
+- Write small, focused PRs — one commit per logical change
+- Prefer composition over inheritance
+- Always add unit tests for new components
+
+## Constraints
+- Do not modify shared/ types without explicit approval
+- Follow the existing component patterns in features/`;
export function InstructionsTab({
agent,
onSave,
+ onDirtyChange,
}: {
agent: Agent;
onSave: (instructions: string) => Promise<void>;
+ onDirtyChange?: (dirty: boolean) => void;
}) {
const [value, setValue] = useState(agent.instructions ?? "");
const [saving, setSaving] = useState(false);
@@ -21,6 +38,11 @@ export function InstructionsTab({
setValue(agent.instructions ?? "");
}, [agent.id, agent.instructions]);
+ // Report dirty state up so the parent can guard tab switches.
+ useEffect(() => {
+ onDirtyChange?.(isDirty);
+ }, [isDirty, onDirtyChange]);
+
const handleSave = async () => {
setSaving(true);
try {
@@ -33,35 +55,54 @@ export function InstructionsTab({
};
return (
- <div className="space-y-4">
- <div>
- <h3 className="text-sm font-semibold">Agent Instructions</h3>
- <p className="text-xs text-muted-foreground mt-0.5">
- Define this agent&apos;s identity and working style. These instructions are
- injected into the agent&apos;s context for every task.
- </p>
- </div>
+ // Fill the parent TabContent (h-full flex-col): helper + footer take
+ // their natural height, the editor wrapper fills the rest. Without this
+ // the Save row scrolls off-screen as the user writes longer prompts.
+ <div className="flex h-full flex-col gap-4">
+ <p className="text-xs text-muted-foreground">
+ Define this agent&apos;s identity and working style. Injected into the
+ agent&apos;s context for every task. Markdown is supported.
+ </p>
- <textarea
- value={value}
- onChange={(e) => setValue(e.target.value)}
- placeholder={`Define this agent's role, expertise, and working style.\n\nExample:\nYou are a frontend engineer specializing in React and TypeScript.\n\n## Working Style\n- Write small, focused PRs — one commit per logical change\n- Prefer composition over inheritance\n- Always add unit tests for new components\n\n## Constraints\n- Do not modify shared/ types without explicit approval\n- Follow the existing component patterns in features/`}
- className="w-full min-h-[300px] rounded-md border bg-transparent px-3 py-2 text-sm font-mono placeholder:text-muted-foreground/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring resize-y"
- />
+ <div
+ // flex-1 min-h-0 so the wrapper claims the leftover height in the
+ // column. overflow-y-auto so very long prompts scroll inside the
+ // editor instead of pushing the Save row down.
+ className="flex-1 min-h-0 overflow-y-auto rounded-md border bg-background px-4 py-3 transition-colors focus-within:border-input"
+ >
+ <ContentEditor
+ // Keyed by agent id so navigating between agents fully remounts the
+ // editor — Tiptap's `defaultValue` is read once, so without the key
+ // the second agent's instructions wouldn't load.
+ key={agent.id}
+ defaultValue={value}
+ onUpdate={setValue}
+ placeholder={INSTRUCTIONS_PLACEHOLDER}
+ debounceMs={150}
+ // Mention has no business meaning in agent system prompts — typing
+ // `@` would just confuse users with a member/agent picker.
+ disableMentions
+ // min-h-full lets the editor fill the wrapper even when the user
+ // has typed nothing yet, so the click target matches the visual
+ // box. Combined with the wrapper's overflow-y-auto, long content
+ // grows past the wrapper height and scrolls within it.
+ className="min-h-full"
+ />
+ </div>
- <div className="flex items-center justify-between">
- <span className="text-xs text-muted-foreground">
- {value.length > 0 ? `${value.length} characters` : "No instructions set"}
- </span>
+ <div className="flex items-center justify-end gap-3">
+ {isDirty && (
+ <span className="text-xs text-muted-foreground">Unsaved changes</span>
+ )}
<Button
- size="xs"
+ size="sm"
onClick={handleSave}
disabled={!isDirty || saving}
>
{saving ? (
- <Loader2 className="h-3 w-3 animate-spin" />
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
- <Save className="h-3 w-3" />
+ <Save className="h-3.5 w-3.5" />
)}
Save
</Button>
diff --git a/packages/views/agents/components/tabs/settings-tab.tsx b/packages/views/agents/components/tabs/settings-tab.tsx
deleted file mode 100644
index 69b4364cdf..0000000000
--- a/packages/views/agents/components/tabs/settings-tab.tsx
+++ /dev/null
@@ -1,342 +0,0 @@
-"use client";
-
-import { useState, useRef, useMemo } from "react";
-import {
- Loader2,
- Save,
- Globe,
- Lock,
- Camera,
- ChevronDown,
-} from "lucide-react";
-import type { Agent, AgentVisibility, RuntimeDevice, MemberWithUser } from "@multica/core/types";
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
-} from "@multica/ui/components/ui/popover";
-import { Button } from "@multica/ui/components/ui/button";
-import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import { toast } from "sonner";
-import { api } from "@multica/core/api";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
-import { ActorAvatar } from "../../../common/actor-avatar";
-import { ProviderLogo } from "../../../runtimes/components/provider-logo";
-import { ModelDropdown } from "../model-dropdown";
-
-type RuntimeFilter = "mine" | "all";
-
-export function SettingsTab({
- agent,
- runtimes,
- members,
- currentUserId,
- onSave,
-}: {
- agent: Agent;
- runtimes: RuntimeDevice[];
- members: MemberWithUser[];
- currentUserId: string | null;
- onSave: (updates: Partial<Agent>) => Promise<void>;
-}) {
- const [name, setName] = useState(agent.name);
- const [description, setDescription] = useState(agent.description ?? "");
- const [visibility, setVisibility] = useState<AgentVisibility>(agent.visibility);
- const [maxTasks, setMaxTasks] = useState(agent.max_concurrent_tasks);
- const [selectedRuntimeId, setSelectedRuntimeId] = useState(agent.runtime_id);
- const [model, setModel] = useState(agent.model ?? "");
- const [runtimeOpen, setRuntimeOpen] = useState(false);
- const [runtimeFilter, setRuntimeFilter] = useState<RuntimeFilter>("mine");
- const [saving, setSaving] = useState(false);
- const { upload, uploading } = useFileUpload(api);
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- const getOwnerMember = (ownerId: string | null) => {
- if (!ownerId) return null;
- return members.find((m) => m.user_id === ownerId) ?? null;
- };
-
- const hasOtherRuntimes = runtimes.some((r) => r.owner_id !== currentUserId);
-
- const filteredRuntimes = useMemo(() => {
- const filtered = runtimeFilter === "mine" && currentUserId
- ? runtimes.filter((r) => r.owner_id === currentUserId)
- : runtimes;
- return [...filtered].sort((a, b) => {
- if (a.owner_id === currentUserId && b.owner_id !== currentUserId) return -1;
- if (a.owner_id !== currentUserId && b.owner_id === currentUserId) return 1;
- return 0;
- });
- }, [runtimes, runtimeFilter, currentUserId]);
-
- const selectedRuntime = runtimes.find((d) => d.id === selectedRuntimeId) ?? null;
- const selectedOwnerMember = selectedRuntime ? getOwnerMember(selectedRuntime.owner_id) : null;
-
- const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file) return;
- e.target.value = "";
- try {
- const result = await upload(file);
- if (!result) return;
- await onSave({ avatar_url: result.link });
- toast.success("Avatar updated");
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to upload avatar");
- }
- };
-
- const dirty =
- name !== agent.name ||
- description !== (agent.description ?? "") ||
- visibility !== agent.visibility ||
- maxTasks !== agent.max_concurrent_tasks ||
- selectedRuntimeId !== agent.runtime_id ||
- model !== (agent.model ?? "");
-
- const handleSave = async () => {
- if (!name.trim()) {
- toast.error("Name is required");
- return;
- }
-
- setSaving(true);
- try {
- await onSave({
- name: name.trim(),
- description,
- visibility,
- max_concurrent_tasks: maxTasks,
- runtime_id: selectedRuntimeId,
- model,
- });
- toast.success("Settings saved");
- } catch {
- toast.error("Failed to save settings");
- } finally {
- setSaving(false);
- }
- };
-
- return (
- <div className="max-w-lg space-y-6">
- <div>
- <Label className="text-xs text-muted-foreground">Avatar</Label>
- <div className="mt-1.5 flex items-center gap-4">
- <button
- type="button"
- className="group relative h-16 w-16 shrink-0 rounded-full bg-muted overflow-hidden focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- onClick={() => fileInputRef.current?.click()}
- disabled={uploading}
- >
- <ActorAvatar actorType="agent" actorId={agent.id} size={64} className="rounded-none" disableHoverCard />
- <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
- {uploading ? (
- <Loader2 className="h-5 w-5 animate-spin text-white" />
- ) : (
- <Camera className="h-5 w-5 text-white" />
- )}
- </div>
- </button>
- <input
- ref={fileInputRef}
- type="file"
- accept="image/*"
- className="hidden"
- onChange={handleAvatarUpload}
- />
- <div className="text-xs text-muted-foreground">
- Click to upload avatar
- </div>
- </div>
- </div>
-
- <div>
- <Label className="text-xs text-muted-foreground">Name</Label>
- <Input
- value={name}
- onChange={(e) => setName(e.target.value)}
- className="mt-1"
- />
- </div>
-
- <div>
- <Label className="text-xs text-muted-foreground">Description</Label>
- <Input
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- placeholder="What does this agent do?"
- className="mt-1"
- />
- </div>
-
- <div>
- <Label className="text-xs text-muted-foreground">Visibility</Label>
- <div className="mt-1.5 flex gap-2">
- <button
- type="button"
- onClick={() => setVisibility("workspace")}
- className={`flex flex-1 items-center gap-2 rounded-lg border px-3 py-2.5 text-sm transition-colors ${
- visibility === "workspace"
- ? "border-primary bg-primary/5"
- : "border-border hover:bg-muted"
- }`}
- >
- <Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="text-left">
- <div className="font-medium">Workspace</div>
- <div className="text-xs text-muted-foreground">All members can assign</div>
- </div>
- </button>
- <button
- type="button"
- onClick={() => setVisibility("private")}
- className={`flex flex-1 items-center gap-2 rounded-lg border px-3 py-2.5 text-sm transition-colors ${
- visibility === "private"
- ? "border-primary bg-primary/5"
- : "border-border hover:bg-muted"
- }`}
- >
- <Lock className="h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="text-left">
- <div className="font-medium">Private</div>
- <div className="text-xs text-muted-foreground">Only you can assign</div>
- </div>
- </button>
- </div>
- </div>
-
- <div>
- <Label className="text-xs text-muted-foreground">Max Concurrent Tasks</Label>
- <Input
- type="number"
- min={1}
- max={50}
- value={maxTasks}
- onChange={(e) => setMaxTasks(Number(e.target.value))}
- className="mt-1 w-24"
- />
- </div>
-
- <div>
- <div className="flex items-center justify-between">
- <Label className="text-xs text-muted-foreground">Runtime</Label>
- {hasOtherRuntimes && (
- <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">
- <button
- type="button"
- onClick={() => setRuntimeFilter("mine")}
- className={`rounded px-2 py-0.5 text-xs font-medium transition-colors ${
- runtimeFilter === "mine"
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground"
- }`}
- >
- Mine
- </button>
- <button
- type="button"
- onClick={() => setRuntimeFilter("all")}
- className={`rounded px-2 py-0.5 text-xs font-medium transition-colors ${
- runtimeFilter === "all"
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground"
- }`}
- >
- All
- </button>
- </div>
- )}
- </div>
- <Popover open={runtimeOpen} onOpenChange={setRuntimeOpen}>
- <PopoverTrigger
- disabled={runtimes.length === 0}
- className="flex w-full items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 mt-1.5 text-left text-sm transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50"
- >
- {selectedRuntime ? (
- <ProviderLogo provider={selectedRuntime.provider} className="h-4 w-4 shrink-0" />
- ) : (
- <ProviderLogo provider="" className="h-4 w-4 shrink-0" />
- )}
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span className="truncate font-medium">
- {selectedRuntime?.name ?? "No runtime available"}
- </span>
- {selectedRuntime?.runtime_mode === "cloud" && (
- <span className="shrink-0 rounded bg-info/10 px-1.5 py-0.5 text-xs font-medium text-info">
- Cloud
- </span>
- )}
- </div>
- <div className="truncate text-xs text-muted-foreground">
- {selectedRuntime ? (
- selectedOwnerMember ? selectedOwnerMember.name : selectedRuntime.device_info
- ) : "Select a runtime"}
- </div>
- </div>
- <ChevronDown className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${runtimeOpen ? "rotate-180" : ""}`} />
- </PopoverTrigger>
- <PopoverContent align="start" className="w-[var(--anchor-width)] p-1 max-h-60 overflow-y-auto">
- {filteredRuntimes.map((device) => {
- const ownerMember = getOwnerMember(device.owner_id);
- return (
- <button
- key={device.id}
- onClick={() => {
- setSelectedRuntimeId(device.id);
- setRuntimeOpen(false);
- }}
- className={`flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-left text-sm transition-colors ${
- device.id === selectedRuntimeId ? "bg-accent" : "hover:bg-accent/50"
- }`}
- >
- <ProviderLogo provider={device.provider} className="h-4 w-4 shrink-0" />
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span className="truncate font-medium">{device.name}</span>
- {device.runtime_mode === "cloud" && (
- <span className="shrink-0 rounded bg-info/10 px-1.5 py-0.5 text-xs font-medium text-info">
- Cloud
- </span>
- )}
- </div>
- <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
- {ownerMember ? (
- <>
- <ActorAvatar actorType="member" actorId={ownerMember.user_id} size={14} />
- <span className="truncate">{ownerMember.name}</span>
- </>
- ) : (
- <span className="truncate">{device.device_info}</span>
- )}
- </div>
- </div>
- <span
- className={`h-2 w-2 shrink-0 rounded-full ${
- device.status === "online" ? "bg-success" : "bg-muted-foreground/40"
- }`}
- />
- </button>
- );
- })}
- </PopoverContent>
- </Popover>
- </div>
-
- <ModelDropdown
- runtimeId={selectedRuntime?.id ?? null}
- runtimeOnline={selectedRuntime?.status === "online"}
- value={model}
- onChange={setModel}
- disabled={!selectedRuntime}
- />
-
- <Button onClick={handleSave} disabled={!dirty || saving} size="sm">
- {saving ? <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" /> : <Save className="h-3.5 w-3.5 mr-1.5" />}
- Save Changes
- </Button>
- </div>
- );
-}
diff --git a/packages/views/agents/components/tabs/skills-tab.tsx b/packages/views/agents/components/tabs/skills-tab.tsx
index 04a3182017..821c0d6f58 100644
--- a/packages/views/agents/components/tabs/skills-tab.tsx
+++ b/packages/views/agents/components/tabs/skills-tab.tsx
@@ -1,22 +1,18 @@
"use client";
import { useState } from "react";
-import { Plus, FileText, Trash2, Info } from "lucide-react";
-import type { Agent } from "@multica/core/types";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
- DialogFooter,
-} from "@multica/ui/components/ui/dialog";
-import { Button } from "@multica/ui/components/ui/button";
+import { FileText, Info, Plus, Trash2 } from "lucide-react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
+import type { Agent } from "@multica/core/types";
import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
-import { skillListOptions, workspaceKeys } from "@multica/core/workspace/queries";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ skillListOptions,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
+import { SkillAddDialog } from "../skill-add-dialog";
export function SkillsTab({
agent,
@@ -25,100 +21,91 @@ export function SkillsTab({
}) {
const qc = useQueryClient();
const wsId = useWorkspaceId();
+ // Same query the SkillAddDialog uses (TanStack Query dedupes by key, so
+ // this isn't an extra request) — used here only to grey out the "Add skill"
+ // button when there's nothing left to attach.
const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
- const [saving, setSaving] = useState(false);
- const [showPicker, setShowPicker] = useState(false);
+ const [removing, setRemoving] = useState(false);
+ const [showAdd, setShowAdd] = useState(false);
const agentSkillIds = new Set(agent.skills.map((s) => s.id));
- const availableSkills = workspaceSkills.filter((s) => !agentSkillIds.has(s.id));
-
- const handleAdd = async (skillId: string) => {
- setSaving(true);
- try {
- const newIds = [...agent.skills.map((s) => s.id), skillId];
- await api.setAgentSkills(agent.id, { skill_ids: newIds });
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- } catch (e) {
- toast.error(e instanceof Error ? e.message : "Failed to add skill");
- } finally {
- setSaving(false);
- setShowPicker(false);
- }
- };
+ const availableCount = workspaceSkills.filter(
+ (s) => !agentSkillIds.has(s.id),
+ ).length;
const handleRemove = async (skillId: string) => {
- setSaving(true);
+ setRemoving(true);
try {
- const newIds = agent.skills.filter((s) => s.id !== skillId).map((s) => s.id);
+ const newIds = agent.skills
+ .filter((s) => s.id !== skillId)
+ .map((s) => s.id);
await api.setAgentSkills(agent.id, { skill_ids: newIds });
qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to remove skill");
} finally {
- setSaving(false);
+ setRemoving(false);
}
};
return (
<div className="space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <h3 className="text-sm font-semibold">Skills</h3>
- <p className="text-xs text-muted-foreground mt-0.5">
- Workspace skills assigned to this agent.
- </p>
- </div>
+ <div className="flex items-start justify-between gap-3">
+ <p className="text-xs text-muted-foreground">
+ Workspace skills assigned to this agent. Local runtime skills are
+ always available automatically.
+ </p>
<Button
variant="outline"
- size="xs"
- onClick={() => setShowPicker(true)}
- disabled={saving || availableSkills.length === 0}
+ size="sm"
+ onClick={() => setShowAdd(true)}
+ disabled={availableCount === 0}
+ className="shrink-0"
>
<Plus className="h-3 w-3" />
- Add Skill
+ Add skill
</Button>
</div>
<div className="flex items-start gap-2 rounded-md border border-info/20 bg-info/5 px-3 py-2.5">
- <Info className="h-3.5 w-3.5 shrink-0 text-info mt-0.5" />
+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0 text-info" />
<p className="text-xs text-muted-foreground">
- Local runtime skills are always available automatically. Importing creates a workspace copy that your team can edit and reuse.
+ Importing creates a workspace copy that your team can edit and reuse.
</p>
</div>
{agent.skills.length === 0 ? (
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-12">
<FileText className="h-8 w-8 text-muted-foreground/40" />
- <p className="mt-3 text-sm text-muted-foreground">No skills assigned</p>
- <p className="mt-1 text-xs text-muted-foreground">
- Add workspace skills to share team knowledge with this agent. Local skills are already used automatically.
+ <p className="mt-3 text-sm text-muted-foreground">
+ No skills assigned
+ </p>
+ <p className="mt-1 max-w-xs text-center text-xs text-muted-foreground">
+ Add workspace skills to share team knowledge with this agent.
</p>
- {availableSkills.length > 0 && (
+ {availableCount > 0 && (
<Button
- onClick={() => setShowPicker(true)}
- size="xs"
+ onClick={() => setShowAdd(true)}
+ size="sm"
className="mt-3"
- disabled={saving}
>
<Plus className="h-3 w-3" />
- Add Skill
+ Add skill
</Button>
)}
</div>
) : (
- <div className="space-y-2">
+ <ul className="space-y-1.5">
{agent.skills.map((skill) => (
- <div
+ <li
key={skill.id}
- className="flex items-center gap-3 rounded-lg border px-4 py-3"
+ className="flex items-center gap-2.5 rounded-md border px-3 py-2"
>
- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted">
- <FileText className="h-4 w-4 text-muted-foreground" />
- </div>
+ <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">{skill.name}</div>
{skill.description && (
- <div className="text-xs text-muted-foreground truncate">
+ <div className="truncate text-xs text-muted-foreground">
{skill.description}
</div>
)}
@@ -127,60 +114,17 @@ export function SkillsTab({
variant="ghost"
size="icon-sm"
onClick={() => handleRemove(skill.id)}
- disabled={saving}
+ disabled={removing}
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
- </div>
+ </li>
))}
- </div>
- )}
-
- {/* Skill Picker Dialog */}
- {showPicker && (
- <Dialog open onOpenChange={(v) => { if (!v) setShowPicker(false); }}>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle className="text-sm">Add Skill</DialogTitle>
- <DialogDescription className="text-xs">
- Select a skill to assign to this agent.
- </DialogDescription>
- </DialogHeader>
- <div className="max-h-64 overflow-y-auto space-y-1">
- {availableSkills.map((skill) => (
- <button
- key={skill.id}
- onClick={() => handleAdd(skill.id)}
- disabled={saving}
- className="flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-left text-sm transition-colors hover:bg-accent/50"
- >
- <FileText className="h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <div className="font-medium">{skill.name}</div>
- {skill.description && (
- <div className="text-xs text-muted-foreground truncate">
- {skill.description}
- </div>
- )}
- </div>
- </button>
- ))}
- {availableSkills.length === 0 && (
- <p className="py-6 text-center text-xs text-muted-foreground">
- All workspace skills are already assigned.
- </p>
- )}
- </div>
- <DialogFooter>
- <Button variant="ghost" onClick={() => setShowPicker(false)}>
- Cancel
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </ul>
)}
+ <SkillAddDialog agent={agent} open={showAdd} onOpenChange={setShowAdd} />
</div>
);
}
diff --git a/packages/views/agents/components/tabs/tasks-tab.test.tsx b/packages/views/agents/components/tabs/tasks-tab.test.tsx
deleted file mode 100644
index c8318bf7d6..0000000000
--- a/packages/views/agents/components/tabs/tasks-tab.test.tsx
+++ /dev/null
@@ -1,257 +0,0 @@
-// @vitest-environment jsdom
-
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { Agent, AgentTask, Issue } from "@multica/core/types";
-
-const mockListAgentTasks = vi.hoisted(() => vi.fn());
-const mockGetIssue = vi.hoisted(() => vi.fn());
-
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "ws-1",
-}));
-
-vi.mock("@multica/core/paths", async () => {
- const actual = await vi.importActual<typeof import("@multica/core/paths")>(
- "@multica/core/paths",
- );
- return {
- ...actual,
- useWorkspacePaths: () => actual.paths.workspace("test"),
- };
-});
-
-vi.mock("@multica/core/api", () => ({
- api: {
- listAgentTasks: (...args: unknown[]) => mockListAgentTasks(...args),
- getIssue: (...args: unknown[]) => mockGetIssue(...args),
- },
-}));
-
-vi.mock("../../../navigation", () => ({
- AppLink: ({ children, href, ...props }: any) => (
- <a href={href} {...props}>
- {children}
- </a>
- ),
-}));
-
-import { TasksTab } from "./tasks-tab";
-
-const agent: Agent = {
- id: "agent-1",
- workspace_id: "ws-1",
- runtime_id: "runtime-1",
- name: "Agent",
- description: "",
- instructions: "",
- avatar_url: null,
- runtime_mode: "local",
- runtime_config: {},
- custom_env: {},
- custom_args: [],
- custom_env_redacted: false,
- visibility: "workspace",
- status: "idle",
- max_concurrent_tasks: 1,
- model: "",
- owner_id: null,
- skills: [],
- created_at: "2026-04-16T00:00:00Z",
- updated_at: "2026-04-16T00:00:00Z",
- archived_at: null,
- archived_by: null,
-};
-
-function renderTasksTab(tasks: AgentTask[], issues: Issue[]) {
- mockListAgentTasks.mockResolvedValue(tasks);
- mockGetIssue.mockImplementation((id: string) => {
- const found = issues.find((i) => i.id === id);
- return found ? Promise.resolve(found) : Promise.reject(new Error("not found"));
- });
-
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- });
-
- return render(
- <QueryClientProvider client={queryClient}>
- <TasksTab agent={agent} />
- </QueryClientProvider>,
- );
-}
-
-describe("TasksTab", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("uses workspace-scoped issue detail paths when issue data is loaded", async () => {
- renderTasksTab(
- [
- {
- id: "task-1",
- agent_id: "agent-1",
- runtime_id: "runtime-1",
- issue_id: "issue-1",
- status: "queued",
- priority: 1,
- dispatched_at: null,
- started_at: null,
- completed_at: null,
- result: null,
- error: null,
- created_at: "2026-04-16T00:00:00Z",
- },
- ],
- [
- {
- id: "issue-1",
- workspace_id: "ws-1",
- number: 1,
- identifier: "MUL-1",
- title: "Fix agent task routing",
- description: "",
- status: "todo",
- priority: "medium",
- assignee_type: null,
- assignee_id: null,
- creator_type: "member",
- creator_id: "user-1",
- parent_issue_id: null,
- project_id: null,
- position: 1,
- due_date: null,
- created_at: "2026-04-16T00:00:00Z",
- updated_at: "2026-04-16T00:00:00Z",
- },
- ],
- );
-
- const title = await screen.findByText("Fix agent task routing");
- const link = title.closest("a");
-
- expect(link?.getAttribute("href")).toBe("/test/issues/issue-1");
- });
-
- it("keeps task rows clickable when the issue is missing from the list query", async () => {
- renderTasksTab(
- [
- {
- id: "task-2",
- agent_id: "agent-1",
- runtime_id: "runtime-1",
- issue_id: "12345678-fallback",
- status: "completed",
- priority: 1,
- dispatched_at: null,
- started_at: null,
- completed_at: "2026-04-16T01:00:00Z",
- result: null,
- error: null,
- created_at: "2026-04-16T00:00:00Z",
- },
- ],
- [],
- );
-
- await waitFor(() => {
- expect(mockListAgentTasks).toHaveBeenCalledWith("agent-1");
- });
-
- const title = await screen.findByText("Issue 12345678...");
- const link = title.closest("a");
-
- expect(link?.getAttribute("href")).toBe("/test/issues/12345678-fallback");
- });
-
- it("renders tasks with empty issue_id as inert rows and does not fetch issue detail", async () => {
- // Tasks persisted with NULL issue_id — autopilot run_only runs and
- // chat-spawned tasks — arrive here with issue_id === "". The tab used
- // to feed that empty id into `/api/issues/`, which crashed the whole
- // page after the list-cache paginate refactor (#1422). It must now:
- // - skip the detail fetch entirely,
- // - render a neutral label instead of an "Issue ..." stub, and
- // - NOT wrap the row in an anchor.
- renderTasksTab(
- [
- {
- id: "task-no-issue",
- agent_id: "agent-1",
- runtime_id: "runtime-1",
- issue_id: "",
- status: "completed",
- priority: 1,
- dispatched_at: null,
- started_at: null,
- completed_at: "2026-04-16T01:00:00Z",
- result: null,
- error: null,
- created_at: "2026-04-16T00:00:00Z",
- },
- ],
- [],
- );
-
- const label = await screen.findByText("Task without linked issue");
- expect(label.closest("a")).toBeNull();
- expect(mockGetIssue).not.toHaveBeenCalled();
- });
-
- it("labels chat-spawned tasks as 'Chat session'", async () => {
- renderTasksTab(
- [
- {
- id: "task-chat",
- agent_id: "agent-1",
- runtime_id: "runtime-1",
- issue_id: "",
- chat_session_id: "chat-42",
- status: "running",
- priority: 1,
- dispatched_at: "2026-04-16T00:30:00Z",
- started_at: "2026-04-16T00:31:00Z",
- completed_at: null,
- result: null,
- error: null,
- created_at: "2026-04-16T00:00:00Z",
- },
- ],
- [],
- );
-
- const label = await screen.findByText("Chat session");
- expect(label.closest("a")).toBeNull();
- });
-
- it("labels autopilot-spawned tasks as 'Autopilot run'", async () => {
- renderTasksTab(
- [
- {
- id: "task-autopilot",
- agent_id: "agent-1",
- runtime_id: "runtime-1",
- issue_id: "",
- autopilot_run_id: "run-7",
- status: "completed",
- priority: 1,
- dispatched_at: null,
- started_at: null,
- completed_at: "2026-04-16T01:00:00Z",
- result: null,
- error: null,
- created_at: "2026-04-16T00:00:00Z",
- },
- ],
- [],
- );
-
- const label = await screen.findByText("Autopilot run");
- expect(label.closest("a")).toBeNull();
- });
-});
diff --git a/packages/views/agents/components/tabs/tasks-tab.tsx b/packages/views/agents/components/tabs/tasks-tab.tsx
deleted file mode 100644
index 8a121bd338..0000000000
--- a/packages/views/agents/components/tabs/tasks-tab.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-"use client";
-
-import { useMemo, useState, useEffect } from "react";
-import { ListTodo } from "lucide-react";
-import type { Agent, AgentTask, Issue } from "@multica/core/types";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { api } from "@multica/core/api";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { useWorkspacePaths } from "@multica/core/paths";
-import { issueDetailOptions } from "@multica/core/issues/queries";
-import { useQueries } from "@tanstack/react-query";
-import { AppLink } from "../../../navigation";
-import { taskStatusConfig } from "../../config";
-
-export function TasksTab({ agent }: { agent: Agent }) {
- const [tasks, setTasks] = useState<AgentTask[]>([]);
- const [loading, setLoading] = useState(true);
- const wsId = useWorkspaceId();
- const paths = useWorkspacePaths();
-
- useEffect(() => {
- setLoading(true);
- api
- .listAgentTasks(agent.id)
- .then(setTasks)
- .catch(() => setTasks([]))
- .finally(() => setLoading(false));
- }, [agent.id]);
-
- // Resolve each task's issue via its own cached detail query. A task's
- // issue may or may not be in the paginated issue-list cache, so going
- // through `issueDetailOptions` is the reliable lookup path (and it shares
- // the same cache as the issue detail page).
- //
- // Not every task has a linked issue — autopilot `run_only` runs and
- // chat-spawned tasks both persist with NULL issue_id, which the server
- // serializes as "". Filter those out before issuing detail queries so we
- // don't hit `/api/issues/` with an empty id (which was crashing the
- // whole tab). The UI treats the two cases the same here; a follow-up
- // will surface the task source once the server exposes it.
- const issueIds = useMemo(
- () => Array.from(new Set(tasks.map((t) => t.issue_id).filter((id) => id !== ""))),
- [tasks],
- );
- const issueQueries = useQueries({
- queries: issueIds.map((id) => issueDetailOptions(wsId, id)),
- });
- const issueMap = useMemo(() => {
- const map = new Map<string, Issue>();
- issueQueries.forEach((q, i) => {
- const id = issueIds[i]!;
- if (q.data) map.set(id, q.data);
- });
- return map;
- }, [issueQueries, issueIds]);
-
- if (loading) {
- return (
- <div className="space-y-2">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3 rounded-lg border px-4 py-3">
- <Skeleton className="h-4 w-4 rounded shrink-0" />
- <div className="flex-1 space-y-1.5">
- <Skeleton className="h-4 w-1/2" />
- <Skeleton className="h-3 w-1/3" />
- </div>
- <Skeleton className="h-4 w-16" />
- </div>
- ))}
- </div>
- );
- }
-
- // Sort: active tasks (running > dispatched > queued) first, then completed/failed by date
- const activeStatuses = ["running", "dispatched", "queued"];
- const sortedTasks = [...tasks].sort((a, b) => {
- const aActive = activeStatuses.indexOf(a.status);
- const bActive = activeStatuses.indexOf(b.status);
- const aIsActive = aActive !== -1;
- const bIsActive = bActive !== -1;
- if (aIsActive && !bIsActive) return -1;
- if (!aIsActive && bIsActive) return 1;
- if (aIsActive && bIsActive) return aActive - bActive;
- return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
- });
-
- return (
- <div className="space-y-4">
- <div>
- <h3 className="text-sm font-semibold">Task Queue</h3>
- <p className="text-xs text-muted-foreground mt-0.5">
- Issues assigned to this agent and their execution status.
- </p>
- </div>
-
- {tasks.length === 0 ? (
- <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-12">
- <ListTodo className="h-8 w-8 text-muted-foreground/40" />
- <p className="mt-3 text-sm text-muted-foreground">No tasks in queue</p>
- <p className="mt-1 text-xs text-muted-foreground">
- Assign an issue to this agent to get started.
- </p>
- </div>
- ) : (
- <div className="space-y-1.5">
- {sortedTasks.map((task) => {
- const config = taskStatusConfig[task.status] ?? taskStatusConfig.queued!;
- const Icon = config.icon;
- // Tasks without a linked issue carry issue_id = "" — skip the
- // detail lookup and render them as non-link rows. The source
- // label is picked from chat_session_id / autopilot_run_id,
- // which the server populates for chat- and autopilot-spawned
- // tasks respectively.
- const hasIssue = task.issue_id !== "";
- const issue = hasIssue ? issueMap.get(task.issue_id) : undefined;
- const sourcelessLabel = task.chat_session_id
- ? "Chat session"
- : task.autopilot_run_id
- ? "Autopilot run"
- : "Task without linked issue";
- const isActive = task.status === "running" || task.status === "dispatched";
- const isRunning = task.status === "running";
- const rowClassName = `flex items-center gap-3 rounded-lg border px-4 py-3 transition-shadow hover:shadow-sm ${
- isRunning
- ? "border-success/40 bg-success/5"
- : task.status === "dispatched"
- ? "border-info/40 bg-info/5"
- : ""
- }`;
-
- const content = (
- <>
- <Icon
- className={`h-4 w-4 shrink-0 ${config.color} ${
- isRunning ? "animate-spin" : ""
- }`}
- />
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- {issue && (
- <span className="shrink-0 text-xs font-mono text-muted-foreground">
- {issue.identifier}
- </span>
- )}
- <span className={`text-sm truncate ${isActive ? "font-medium" : ""}`}>
- {issue?.title ?? (hasIssue ? `Issue ${task.issue_id.slice(0, 8)}...` : sourcelessLabel)}
- </span>
- </div>
- <div className="mt-0.5 text-xs text-muted-foreground">
- {isRunning && task.started_at
- ? `Started ${new Date(task.started_at).toLocaleString()}`
- : task.status === "dispatched" && task.dispatched_at
- ? `Dispatched ${new Date(task.dispatched_at).toLocaleString()}`
- : task.status === "completed" && task.completed_at
- ? `Completed ${new Date(task.completed_at).toLocaleString()}`
- : task.status === "failed" && task.completed_at
- ? `Failed ${new Date(task.completed_at).toLocaleString()}`
- : `Queued ${new Date(task.created_at).toLocaleString()}`}
- </div>
- </div>
- <span className={`shrink-0 text-xs font-medium ${config.color}`}>
- {config.label}
- </span>
- </>
- );
-
- if (!hasIssue) {
- return (
- <div key={task.id} className={rowClassName}>
- {content}
- </div>
- );
- }
-
- return (
- <AppLink
- key={task.id}
- href={paths.issueDetail(task.issue_id)}
- className={`${rowClassName} text-foreground no-underline hover:no-underline`}
- >
- {content}
- </AppLink>
- );
- })}
- </div>
- )}
- </div>
- );
-}
diff --git a/packages/views/agents/config.ts b/packages/views/agents/config.ts
index 43c65a15c6..a1319238a5 100644
--- a/packages/views/agents/config.ts
+++ b/packages/views/agents/config.ts
@@ -1,4 +1,3 @@
-import type { AgentStatus } from "@multica/core/types";
import {
Clock,
CheckCircle2,
@@ -7,14 +6,6 @@ import {
Play,
} from "lucide-react";
-export const statusConfig: Record<AgentStatus, { label: string; color: string; dot: string }> = {
- idle: { label: "Idle", color: "text-muted-foreground", dot: "bg-muted-foreground" },
- working: { label: "Working", color: "text-success", dot: "bg-success" },
- blocked: { label: "Blocked", color: "text-warning", dot: "bg-warning" },
- error: { label: "Error", color: "text-destructive", dot: "bg-destructive" },
- offline: { label: "Offline", color: "text-muted-foreground/50", dot: "bg-muted-foreground/40" },
-};
-
export const taskStatusConfig: Record<string, { label: string; icon: typeof CheckCircle2; color: string }> = {
queued: { label: "Queued", icon: Clock, color: "text-muted-foreground" },
dispatched: { label: "Dispatched", icon: Play, color: "text-info" },
diff --git a/packages/views/agents/index.ts b/packages/views/agents/index.ts
index 5477f4bb96..486547b34f 100644
--- a/packages/views/agents/index.ts
+++ b/packages/views/agents/index.ts
@@ -1 +1 @@
-export { AgentsPage } from "./components";
+export { AgentsPage, AgentDetailPage } from "./components";
diff --git a/packages/views/agents/presence.ts b/packages/views/agents/presence.ts
new file mode 100644
index 0000000000..f54b65df57
--- /dev/null
+++ b/packages/views/agents/presence.ts
@@ -0,0 +1,131 @@
+import {
+ AlertCircle,
+ CheckCircle2,
+ CircleDot,
+ CircleSlash,
+ Loader2,
+ PauseCircle,
+ PlugZap,
+ XCircle,
+ type LucideIcon,
+} from "lucide-react";
+import type { AgentAvailability, LastTaskState } from "@multica/core/agents";
+import type { TaskFailureReason } from "@multica/core/types";
+
+// Visual mapping for the two presence dimensions, kept in matching shape
+// so consumers can pick which to render. The two are independent — the
+// dot reads only from availabilityConfig, the last-task chip reads only
+// from taskStateConfig.
+//
+// Color tokens map to project semantic tokens (no hardcoded Tailwind colors):
+//
+// AVAILABILITY (drives the dot everywhere a dot appears):
+// online → success (green)
+// unstable → warning (amber) — pairs with the runtime card's amber
+// offline → muted-foreground (gray)
+//
+// LAST TASK STATE (drives the optional last-task chip on focused surfaces):
+// running → brand (blue) has activity
+// completed → success (green) all good
+// failed → destructive (red)
+// cancelled → muted (gray)
+// idle → muted (gray) no history
+//
+// Critically: `failed` colour appears ONLY in the last-task chip, never
+// on the dot. A runtime-healthy agent whose last task failed shows a
+// green dot + a red "Failed" chip — the dot stops being sticky-red.
+
+export interface AvailabilityVisual {
+ label: string;
+ // Background fill for the dot indicator.
+ dotClass: string;
+ // Foreground colour for the label text alongside the dot.
+ textClass: string;
+ // Icon used in larger badge contexts (detail header, hover card).
+ icon: LucideIcon;
+}
+
+export const availabilityConfig: Record<AgentAvailability, AvailabilityVisual> = {
+ online: {
+ label: "Online",
+ dotClass: "bg-success",
+ textClass: "text-success",
+ icon: CircleDot,
+ },
+ unstable: {
+ label: "Unstable",
+ dotClass: "bg-warning",
+ textClass: "text-warning",
+ icon: PlugZap,
+ },
+ offline: {
+ label: "Offline",
+ dotClass: "bg-muted-foreground/40",
+ textClass: "text-muted-foreground",
+ icon: CircleSlash,
+ },
+};
+
+// Order used by availability filter chips so colours read in a natural
+// progression rather than alphabetical.
+export const availabilityOrder: AgentAvailability[] = [
+ "online",
+ "unstable",
+ "offline",
+];
+
+export interface TaskStateVisual {
+ label: string;
+ // Foreground colour for icon + label text.
+ textClass: string;
+ // Icon used inline.
+ icon: LucideIcon;
+}
+
+export const taskStateConfig: Record<LastTaskState, TaskStateVisual> = {
+ running: {
+ label: "Running",
+ textClass: "text-brand",
+ icon: Loader2,
+ },
+ completed: {
+ label: "Completed",
+ textClass: "text-success",
+ icon: CheckCircle2,
+ },
+ failed: {
+ label: "Failed",
+ textClass: "text-destructive",
+ icon: XCircle,
+ },
+ cancelled: {
+ label: "Cancelled",
+ textClass: "text-muted-foreground",
+ icon: PauseCircle,
+ },
+ idle: {
+ label: "Idle",
+ textClass: "text-muted-foreground",
+ icon: AlertCircle,
+ },
+};
+
+// Order used by last-run filter chips. Actionable signals first
+// (running / failed) before passive ones (idle / cancelled).
+export const lastTaskOrder: LastTaskState[] = [
+ "running",
+ "failed",
+ "completed",
+ "cancelled",
+ "idle",
+];
+
+// Human-readable copy for the back-end task failure reason enum. Surfaced
+// in the hover card and detail header when lastTask === "failed".
+export const failureReasonLabel: Record<TaskFailureReason, string> = {
+ agent_error: "Agent execution error",
+ timeout: "Task timed out",
+ runtime_offline: "Daemon offline",
+ runtime_recovery: "Daemon restarted",
+ manual: "Cancelled by user",
+};
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index a35c8b4849..57f972616d 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -379,8 +379,8 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
<div>
<label className="text-xs text-muted-foreground">Agent</label>
<div className="mt-1 flex items-center gap-2">
- <ActorAvatar actorType="agent" actorId={autopilot.assignee_id} size={20} />
- <span>{getActorName("agent", autopilot.assignee_id)}</span>
+ <ActorAvatar actorType="agent" actorId={autopilot.assignee_id} size={20} enableHoverCard showStatusDot />
+ <span className="cursor-pointer">{getActorName("agent", autopilot.assignee_id)}</span>
</div>
</div>
<div>
diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsx
index 30e09aeb05..afea38d0eb 100644
--- a/packages/views/autopilots/components/autopilot-dialog.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.tsx
@@ -570,7 +570,7 @@ function AgentSection({
actorType="agent"
actorId={selectedId}
size={28}
- disableHoverCard
+ showStatusDot
/>
) : (
<span className="inline-flex size-7 items-center justify-center rounded-full bg-muted text-muted-foreground">
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index f65c640937..949795ca99 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -141,7 +141,7 @@ function AutopilotRow({ autopilot }: { autopilot: Autopilot }) {
{/* Agent */}
<span className="flex w-32 items-center gap-1.5 shrink-0">
- <ActorAvatar actorType="agent" actorId={autopilot.assignee_id} size={18} />
+ <ActorAvatar actorType="agent" actorId={autopilot.assignee_id} size={18} enableHoverCard />
<span className="truncate text-xs text-muted-foreground">
{getActorName("agent", autopilot.assignee_id)}
</span>
diff --git a/packages/views/autopilots/components/pickers/agent-picker.tsx b/packages/views/autopilots/components/pickers/agent-picker.tsx
index f295595a22..b4b42a1e59 100644
--- a/packages/views/autopilots/components/pickers/agent-picker.tsx
+++ b/packages/views/autopilots/components/pickers/agent-picker.tsx
@@ -52,7 +52,7 @@ export function AgentPicker({
<>
{selected ? (
<>
- <ActorAvatar actorType="agent" actorId={selected.id} size={16} disableHoverCard />
+ <ActorAvatar actorType="agent" actorId={selected.id} size={16} showStatusDot />
<span className="truncate">{selected.name}</span>
</>
) : (
@@ -77,7 +77,7 @@ export function AgentPicker({
setOpen(false);
}}
>
- <ActorAvatar actorType="agent" actorId={a.id} size={16} disableHoverCard />
+ <ActorAvatar actorType="agent" actorId={a.id} size={16} showStatusDot />
<span className="truncate">{a.name}</span>
</PickerItem>
))
diff --git a/packages/views/common/actor-avatar.tsx b/packages/views/common/actor-avatar.tsx
index fc1e2e8b04..72e51e1f40 100644
--- a/packages/views/common/actor-avatar.tsx
+++ b/packages/views/common/actor-avatar.tsx
@@ -8,15 +8,31 @@ import {
HoverCardContent,
} from "@multica/ui/components/ui/hover-card";
import { useActorName } from "@multica/core/workspace/hooks";
+import { useAgentPresenceDetail } from "@multica/core/agents";
+import { useCurrentWorkspace } from "@multica/core/paths";
import { AgentProfileCard } from "../agents/components/agent-profile-card";
+import { MemberProfileCard } from "../members/member-profile-card";
+import { availabilityConfig } from "../agents/presence";
interface ActorAvatarProps {
actorType: string;
actorId: string;
size?: number;
className?: string;
- /** Disable the hover-card preview (e.g. when the avatar is itself the page subject). */
- disableHoverCard?: boolean;
+ /**
+ * Wrap the avatar in a hover-card preview on dwell. Use for "who is this?"
+ * surfaces — comment authors, list rows, subscriber chips. Independent of
+ * `showStatusDot`: a surface can have one, both, or neither.
+ */
+ enableHoverCard?: boolean;
+ /**
+ * Overlay an agent-presence dot at the avatar's bottom-right. Use at
+ * decision moments (picker rows, current-assignee display, agent-centric
+ * surfaces). Has no effect for non-agent actors. Independent of
+ * `enableHoverCard` so picker rows can show the dot without nesting a
+ * popover inside the dropdown.
+ */
+ showStatusDot?: boolean;
}
const FOCUSABLE_ANCESTOR_SELECTOR =
@@ -27,7 +43,8 @@ export function ActorAvatar({
actorId,
size,
className,
- disableHoverCard,
+ enableHoverCard,
+ showStatusDot,
}: ActorAvatarProps) {
const { getActorName, getActorInitials, getActorAvatarUrl } = useActorName();
const avatar = (
@@ -41,11 +58,52 @@ export function ActorAvatar({
/>
);
- if (disableHoverCard || actorType !== "agent") {
- return avatar;
+ // Optional presence dot overlay. Only meaningful for agents — members have
+ // no presence backbone. Wrapping unconditionally with relative inline-flex
+ // would create extra DOM for every avatar; we only wrap when a dot is asked
+ // for.
+ const wrapDot = showStatusDot && actorType === "agent";
+ const dotted = wrapDot ? (
+ <span className="relative inline-flex">
+ {avatar}
+ <AgentStatusDot agentId={actorId} size={size} />
+ </span>
+ ) : (
+ avatar
+ );
+
+ if (!enableHoverCard) {
+ return dotted;
+ }
+ if (actorType === "agent") {
+ return <AgentAvatarHoverCard agentId={actorId}>{dotted}</AgentAvatarHoverCard>;
+ }
+ if (actorType === "member") {
+ return <MemberAvatarHoverCard userId={actorId}>{dotted}</MemberAvatarHoverCard>;
}
+ return dotted;
+}
+
+// Small presence indicator overlaid on the bottom-right of an agent avatar.
+// Only renders on hover-enabled surfaces so dense decorative chips (e.g. the
+// 14 px owner sub-avatar in agents-list rows) stay visually clean. The dot
+// scales with the avatar size — anything ≥24 px gets the standard 8 px dot,
+// smaller avatars use a 6 px dot so the indicator doesn't overwhelm them.
+function AgentStatusDot({ agentId, size }: { agentId: string; size?: number }) {
+ const ws = useCurrentWorkspace();
+ const detail = useAgentPresenceDetail(ws?.id, agentId);
+ if (detail === "loading") return null;
+
+ const { dotClass, label } = availabilityConfig[detail.availability];
+ const dotSize = (size ?? 24) >= 24 ? "h-1.5 w-1.5" : "h-1 w-1";
- return <AgentAvatarHoverCard agentId={actorId}>{avatar}</AgentAvatarHoverCard>;
+ return (
+ <span
+ aria-label={`Status: ${label}`}
+ title={label}
+ className={`absolute bottom-0 right-0 rounded-full ring-1 ring-background ${dotClass} ${dotSize}`}
+ />
+ );
}
/**
@@ -60,6 +118,37 @@ function AgentAvatarHoverCard({
}: {
agentId: string;
children: React.ReactNode;
+}) {
+ return (
+ <ActorAvatarHoverCardShell content={<AgentProfileCard agentId={agentId} />}>
+ {children}
+ </ActorAvatarHoverCardShell>
+ );
+}
+
+function MemberAvatarHoverCard({
+ userId,
+ children,
+}: {
+ userId: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <ActorAvatarHoverCardShell content={<MemberProfileCard userId={userId} />}>
+ {children}
+ </ActorAvatarHoverCardShell>
+ );
+}
+
+// Common chrome shared between agent and member hover cards. Keeps focus
+// behaviour and width consistent so the two surfaces feel structurally
+// parallel — content varies, frame doesn't.
+function ActorAvatarHoverCardShell({
+ content,
+ children,
+}: {
+ content: React.ReactNode;
+ children: React.ReactNode;
}) {
const triggerRef = useRef<HTMLSpanElement>(null);
const [standalone, setStandalone] = useState(false);
@@ -78,14 +167,14 @@ function AgentAvatarHoverCard({
tabIndex={standalone ? 0 : -1}
className={
standalone
- ? "inline-flex rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- : "inline-flex"
+ ? "inline-flex cursor-pointer rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ : "inline-flex cursor-pointer"
}
>
{children}
</HoverCardTrigger>
<HoverCardContent align="start" className="w-72">
- <AgentProfileCard agentId={agentId} />
+ {content}
</HoverCardContent>
</HoverCard>
);
diff --git a/packages/views/common/prop-row.tsx b/packages/views/common/prop-row.tsx
new file mode 100644
index 0000000000..4bc8cca65d
--- /dev/null
+++ b/packages/views/common/prop-row.tsx
@@ -0,0 +1,45 @@
+import type { ReactNode } from "react";
+
+/**
+ * Two-column property row used in detail-page sidebars: a fixed-width muted
+ * label on the left and a flexible value on the right.
+ *
+ * `interactive` (default `true`) controls whether the row gets a hover
+ * highlight. Most rows wrap a Picker/Popover trigger and are clickable
+ * anywhere across the row, so the highlight tells users "this is one
+ * target". Read-only rows (Owner / Created / Updated) should pass
+ * `interactive={false}` so they don't pretend to be clickable when they
+ * aren't.
+ *
+ * Used by:
+ * - issue detail sidebar (Status / Priority / Assignee / …)
+ * - agent detail inspector (Runtime / Model / Visibility / …)
+ *
+ * Width of the label is intentionally narrow (`w-16` = 64px) so even
+ * 320px-wide sidebars (agent inspector) leave reasonable room for the
+ * value column.
+ */
+export function PropRow({
+ label,
+ children,
+ interactive = true,
+}: {
+ label: string;
+ children: ReactNode;
+ interactive?: boolean;
+}) {
+ return (
+ <div
+ className={`-mx-2 flex min-h-8 items-center gap-2 rounded-md px-2 ${
+ interactive ? "transition-colors hover:bg-accent/50" : ""
+ }`}
+ >
+ <span className="w-16 shrink-0 text-xs text-muted-foreground">
+ {label}
+ </span>
+ <div className="flex min-w-0 flex-1 items-center gap-1.5 truncate text-xs">
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
similarity index 97%
rename from packages/views/issues/components/agent-transcript-dialog.tsx
rename to packages/views/common/task-transcript/agent-transcript-dialog.tsx
index fa4cb57b0f..25d6e8731c 100644
--- a/packages/views/issues/components/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -29,21 +29,11 @@ import {
DropdownMenuCheckboxItem,
DropdownMenuItem,
} from "@multica/ui/components/ui/dropdown-menu";
-import { ActorAvatar } from "../../common/actor-avatar";
+import { ActorAvatar } from "../actor-avatar";
import { api } from "@multica/core/api";
import type { AgentTask, Agent, AgentRuntime } from "@multica/core/types/agent";
-import { redactSecrets } from "../utils/redact";
-
-// ─── Types ─────────────────────────────────────────────────────────────────
-
-interface TimelineItem {
- seq: number;
- type: "tool_use" | "tool_result" | "thinking" | "text" | "error";
- tool?: string;
- content?: string;
- input?: Record<string, unknown>;
- output?: string;
-}
+import { redactSecrets } from "./redact";
+import type { TimelineItem } from "./build-timeline";
interface AgentTranscriptDialogProps {
open: boolean;
diff --git a/packages/views/common/task-transcript/build-timeline.ts b/packages/views/common/task-transcript/build-timeline.ts
new file mode 100644
index 0000000000..d0d97ba4f1
--- /dev/null
+++ b/packages/views/common/task-transcript/build-timeline.ts
@@ -0,0 +1,28 @@
+import type { TaskMessagePayload } from "@multica/core/types/events";
+import { redactSecrets } from "./redact";
+
+/** A unified timeline entry: tool calls, thinking, text, and errors in chronological order. */
+export interface TimelineItem {
+ seq: number;
+ type: "tool_use" | "tool_result" | "thinking" | "text" | "error";
+ tool?: string;
+ content?: string;
+ input?: Record<string, unknown>;
+ output?: string;
+}
+
+/** Build a chronologically ordered timeline from raw task messages. */
+export function buildTimeline(msgs: TaskMessagePayload[]): TimelineItem[] {
+ const items: TimelineItem[] = [];
+ for (const msg of msgs) {
+ items.push({
+ seq: msg.seq,
+ type: msg.type,
+ tool: msg.tool,
+ content: msg.content ? redactSecrets(msg.content) : msg.content,
+ input: msg.input,
+ output: msg.output ? redactSecrets(msg.output) : msg.output,
+ });
+ }
+ return items.sort((a, b) => a.seq - b.seq);
+}
diff --git a/packages/views/common/task-transcript/index.ts b/packages/views/common/task-transcript/index.ts
new file mode 100644
index 0000000000..51353104b4
--- /dev/null
+++ b/packages/views/common/task-transcript/index.ts
@@ -0,0 +1,4 @@
+export { AgentTranscriptDialog } from "./agent-transcript-dialog";
+export { TranscriptButton } from "./transcript-button";
+export { buildTimeline, type TimelineItem } from "./build-timeline";
+export { redactSecrets } from "./redact";
diff --git a/packages/views/issues/utils/redact.test.ts b/packages/views/common/task-transcript/redact.test.ts
similarity index 100%
rename from packages/views/issues/utils/redact.test.ts
rename to packages/views/common/task-transcript/redact.test.ts
diff --git a/packages/views/issues/utils/redact.ts b/packages/views/common/task-transcript/redact.ts
similarity index 100%
rename from packages/views/issues/utils/redact.ts
rename to packages/views/common/task-transcript/redact.ts
diff --git a/packages/views/common/task-transcript/transcript-button.tsx b/packages/views/common/task-transcript/transcript-button.tsx
new file mode 100644
index 0000000000..dea626be73
--- /dev/null
+++ b/packages/views/common/task-transcript/transcript-button.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { Loader2, ScrollText } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { api } from "@multica/core/api";
+import type { AgentTask } from "@multica/core/types/agent";
+import { AgentTranscriptDialog } from "./agent-transcript-dialog";
+import { buildTimeline, type TimelineItem } from "./build-timeline";
+
+interface TranscriptButtonProps {
+ task: AgentTask;
+ agentName: string;
+ /**
+ * Pre-loaded timeline. When provided the button skips the fetch and opens
+ * the dialog immediately — used by the live card where `items` already
+ * accumulate via WS. Omit for terminal tasks; the button will fetch via
+ * `api.listTaskMessages` on the first click and cache the result.
+ */
+ items?: TimelineItem[];
+ isLive?: boolean;
+ className?: string;
+ title?: string;
+}
+
+/**
+ * Compact icon-button that opens the full transcript dialog. Used on any
+ * surface that lists agent tasks (issue activity card, agent detail
+ * activity tab). Owns its own dialog state and lazy-load — the parent
+ * just drops it in.
+ */
+export function TranscriptButton({
+ task,
+ agentName,
+ items: providedItems,
+ isLive = false,
+ className,
+ title = "View transcript",
+}: TranscriptButtonProps) {
+ const [open, setOpen] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [loadedItems, setLoadedItems] = useState<TimelineItem[] | null>(null);
+
+ // Live mode: parent owns the timeline, we just render it.
+ // Lazy mode: we fetch once and cache.
+ const items = providedItems ?? loadedItems ?? [];
+
+ const handleClick = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (providedItems !== undefined || loadedItems !== null) {
+ setOpen(true);
+ return;
+ }
+ setLoading(true);
+ api
+ .listTaskMessages(task.id)
+ .then((msgs) => {
+ setLoadedItems(buildTimeline(msgs));
+ setOpen(true);
+ })
+ .catch((err) => {
+ console.error(err);
+ setLoadedItems([]);
+ setOpen(true);
+ })
+ .finally(() => setLoading(false));
+ },
+ [providedItems, loadedItems, task.id],
+ );
+
+ return (
+ <>
+ <Tooltip>
+ <TooltipTrigger
+ render={<button type="button" />}
+ onClick={handleClick}
+ disabled={loading}
+ aria-label={title}
+ className={cn(
+ "flex items-center justify-center rounded p-1 text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors disabled:opacity-50",
+ className,
+ )}
+ >
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <ScrollText className="h-3.5 w-3.5" />
+ )}
+ </TooltipTrigger>
+ <TooltipContent>{title}</TooltipContent>
+ </Tooltip>
+
+ {open && (
+ <AgentTranscriptDialog
+ open={open}
+ onOpenChange={setOpen}
+ task={task}
+ items={items}
+ agentName={agentName}
+ isLive={isLive}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/views/editor/content-editor.css b/packages/views/editor/content-editor.css
index bd08a15b36..6380da8f40 100644
--- a/packages/views/editor/content-editor.css
+++ b/packages/views/editor/content-editor.css
@@ -1,5 +1,3 @@
-@import "katex/dist/katex.min.css";
-
/*
* ContentEditor typography — ProseMirror styles using shadcn design tokens.
*
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 7cc4cc86f3..a7340ff19c 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -43,6 +43,7 @@ import { preprocessMarkdown } from "./utils/preprocess";
import { openLink, isMentionHref } from "./utils/link-handler";
import { EditorBubbleMenu } from "./bubble-menu";
import { useLinkHover, LinkHoverCard } from "./link-hover-card";
+import "katex/dist/katex.min.css";
import "./content-editor.css";
// ---------------------------------------------------------------------------
@@ -81,6 +82,12 @@ interface ContentEditorProps {
* under this ID and replaces the selection with a mention link.
*/
currentIssueId?: string;
+ /**
+ * When true, the @mention extension is not registered. Use for editors
+ * where mentioning members/agents has no business meaning (e.g. agent
+ * system prompts, where the content is fed to an LLM as plain text).
+ */
+ disableMentions?: boolean;
}
interface ContentEditorRef {
@@ -111,6 +118,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
showBubbleMenu = true,
submitOnEnter = false,
currentIssueId,
+ disableMentions = false,
},
ref,
) {
@@ -155,6 +163,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onSubmitRef,
onUploadFileRef,
submitOnEnter,
+ disableMentions,
}),
onUpdate: ({ editor: ed }) => {
if (!onUpdateRef.current) return;
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index cc82594e36..d6ca55da45 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -90,6 +90,14 @@ export interface EditorExtensionsOptions {
>;
/** When true, bare Enter also submits (chat-style). Default false. */
submitOnEnter?: boolean;
+ /**
+ * When true, the @mention extension is not registered at all. Use for
+ * editors where mentioning members/agents has no business meaning (e.g.
+ * agent system prompts) — typing `@` becomes inert and any pre-existing
+ * `[@user](mention://...)` markdown renders as plain text instead of being
+ * parsed into a mention node.
+ */
+ disableMentions?: boolean;
}
export function createEditorExtensions(
@@ -122,10 +130,16 @@ export function createEditorExtensions(
// 3-space indent so nested ordered lists survive CommonMark in ReadonlyContent.
Markdown.configure({ indentation: { style: "space", size: 3 } }),
FileCardExtension,
- BaseMentionExtension.configure({
- HTMLAttributes: { class: "mention" },
- ...(editable && options.queryClient ? { suggestion: createMentionSuggestion(options.queryClient) } : {}),
- }),
+ ...(options.disableMentions
+ ? []
+ : [
+ BaseMentionExtension.configure({
+ HTMLAttributes: { class: "mention" },
+ ...(editable && options.queryClient
+ ? { suggestion: createMentionSuggestion(options.queryClient) }
+ : {}),
+ }),
+ ]),
];
if (editable) {
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 6252a6fdc1..ca4140f37f 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -310,6 +310,7 @@ function MentionRow({
actorType={item.type === "all" ? "member" : item.type}
actorId={item.id}
size={20}
+ showStatusDot
/>
<span className="truncate font-medium">{item.label}</span>
{item.type === "agent" && (
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index f3db6fab0b..e1b9f6047a 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -40,6 +40,7 @@ import { ImageLightbox } from "./extensions/image-view";
import { useLinkHover, LinkHoverCard } from "./link-hover-card";
import { openLink, isMentionHref } from "./utils/link-handler";
import { preprocessMarkdown } from "./utils/preprocess";
+import "katex/dist/katex.min.css";
import "./content-editor.css";
// ---------------------------------------------------------------------------
diff --git a/packages/views/issues/components/agent-live-card.tsx b/packages/views/issues/components/agent-live-card.tsx
index dd58721115..a4dcdb6cb4 100644
--- a/packages/views/issues/components/agent-live-card.tsx
+++ b/packages/views/issues/components/agent-live-card.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
-import { Bot, ChevronRight, ChevronDown, Loader2, ArrowDown, Brain, AlertCircle, Clock, CheckCircle2, XCircle, Square, Maximize2 } from "lucide-react";
+import { Bot, ChevronRight, ChevronDown, Loader2, ArrowDown, Brain, AlertCircle, Clock, CheckCircle2, XCircle, Square } from "lucide-react";
import { api } from "@multica/core/api";
import { useWSEvent } from "@multica/core/realtime";
import type { TaskMessagePayload, TaskCompletedPayload, TaskFailedPayload, TaskCancelledPayload } from "@multica/core/types/events";
@@ -11,20 +11,12 @@ import { toast } from "sonner";
import { ActorAvatar } from "../../common/actor-avatar";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@multica/ui/components/ui/collapsible";
import { useActorName } from "@multica/core/workspace/hooks";
-import { redactSecrets } from "../utils/redact";
-import { AgentTranscriptDialog } from "./agent-transcript-dialog";
-
-// ─── Shared types & helpers ─────────────────────────────────────────────────
-
-/** A unified timeline entry: tool calls, thinking, text, and errors in chronological order. */
-interface TimelineItem {
- seq: number;
- type: "tool_use" | "tool_result" | "thinking" | "text" | "error";
- tool?: string;
- content?: string;
- input?: Record<string, unknown>;
- output?: string;
-}
+import {
+ TranscriptButton,
+ buildTimeline,
+ redactSecrets,
+ type TimelineItem,
+} from "../../common/task-transcript";
function formatElapsed(startedAt: string): string {
const elapsed = Date.now() - new Date(startedAt).getTime();
@@ -80,22 +72,6 @@ function getToolSummary(item: TimelineItem): string {
return "";
}
-/** Build a chronologically ordered timeline from raw messages. */
-function buildTimeline(msgs: TaskMessagePayload[]): TimelineItem[] {
- const items: TimelineItem[] = [];
- for (const msg of msgs) {
- items.push({
- seq: msg.seq,
- type: msg.type,
- tool: msg.tool,
- content: msg.content ? redactSecrets(msg.content) : msg.content,
- input: msg.input,
- output: msg.output ? redactSecrets(msg.output) : msg.output,
- });
- }
- return items.sort((a, b) => a.seq - b.seq);
-}
-
// ─── Per-task state ─────────────────────────────────────────────────────────
interface TaskState {
@@ -274,7 +250,6 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv
const [open, setOpen] = useState(false);
const [autoScroll, setAutoScroll] = useState(true);
const [cancelling, setCancelling] = useState(false);
- const [transcriptOpen, setTranscriptOpen] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
// Elapsed time
@@ -333,7 +308,7 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv
}}
>
{task.agent_id ? (
- <ActorAvatar actorType="agent" actorId={task.agent_id} size={20} />
+ <ActorAvatar actorType="agent" actorId={task.agent_id} size={20} enableHoverCard showStatusDot />
) : (
<div className="flex items-center justify-center h-5 w-5 rounded-full shrink-0 bg-info/10 text-info">
<Bot className="h-3 w-3" />
@@ -341,20 +316,20 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv
)}
<div className="flex items-center gap-1.5 text-xs min-w-0">
<Loader2 className="h-3 w-3 animate-spin text-info shrink-0" />
- <span className="font-medium text-foreground truncate">{agentName} is working</span>
+ <span className="cursor-pointer font-medium text-foreground truncate">{agentName} is working</span>
<span className="text-muted-foreground tabular-nums shrink-0">{elapsed}</span>
{toolCount > 0 && (
<span className="text-muted-foreground shrink-0">{toolCount} tools</span>
)}
</div>
<div className="ml-auto flex items-center gap-1 shrink-0">
- <button
- onClick={(e) => { e.stopPropagation(); setTranscriptOpen(true); }}
- className="flex items-center justify-center rounded p-1 text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors"
- title="Expand transcript"
- >
- <Maximize2 className="h-3 w-3" />
- </button>
+ <TranscriptButton
+ task={task}
+ agentName={agentName}
+ items={items}
+ isLive
+ title="View transcript"
+ />
<button
onClick={(e) => { e.stopPropagation(); handleCancel(); }}
disabled={cancelling}
@@ -412,15 +387,6 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv
</div>
</div>
- {/* Fullscreen transcript dialog */}
- <AgentTranscriptDialog
- open={transcriptOpen}
- onOpenChange={setTranscriptOpen}
- task={task}
- items={items}
- agentName={agentName}
- isLive
- />
</div>
);
}
@@ -493,7 +459,6 @@ function TaskRunEntry({ task }: { task: AgentTask }) {
const { getActorName } = useActorName();
const [open, setOpen] = useState(false);
const [items, setItems] = useState<TimelineItem[] | null>(null);
- const [transcriptOpen, setTranscriptOpen] = useState(false);
const loadMessages = useCallback(() => {
if (items !== null) return; // already loaded
@@ -509,6 +474,8 @@ function TaskRunEntry({ task }: { task: AgentTask }) {
if (open) loadMessages();
}, [open, loadMessages]);
+ const agentName = task.agent_id ? getActorName("agent", task.agent_id) : "Agent";
+
const duration = task.started_at && task.completed_at
? formatDuration(task.started_at, task.completed_at)
: null;
@@ -529,33 +496,12 @@ function TaskRunEntry({ task }: { task: AgentTask }) {
<span className={cn("ml-auto capitalize", task.status === "completed" ? "text-success" : "text-destructive")}>
{task.status}
</span>
- <span
- role="button"
- tabIndex={0}
- onClick={(e) => {
- e.stopPropagation();
- // Load messages before opening the transcript dialog
- if (items === null) {
- api.listTaskMessages(task.id).then((msgs) => {
- setItems(buildTimeline(msgs));
- setTranscriptOpen(true);
- }).catch(console.error);
- } else {
- setTranscriptOpen(true);
- }
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.preventDefault();
- e.stopPropagation();
- e.currentTarget.click();
- }
- }}
- className="flex items-center justify-center rounded p-0.5 text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors cursor-pointer"
- title="Expand transcript"
- >
- <Maximize2 className="h-3 w-3" />
- </span>
+ <TranscriptButton
+ task={task}
+ agentName={agentName}
+ items={items ?? undefined}
+ title="View transcript"
+ />
</CollapsibleTrigger>
<CollapsibleContent>
<div className="ml-5 mt-1 max-h-64 overflow-y-auto rounded border bg-muted/30 px-3 py-2 space-y-0.5">
@@ -573,17 +519,6 @@ function TaskRunEntry({ task }: { task: AgentTask }) {
)}
</div>
</CollapsibleContent>
-
- {/* Fullscreen transcript dialog */}
- {items !== null && (
- <AgentTranscriptDialog
- open={transcriptOpen}
- onOpenChange={setTranscriptOpen}
- task={task}
- items={items}
- agentName={task.agent_id ? getActorName("agent", task.agent_id) : "Agent"}
- />
- )}
</Collapsible>
);
}
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index b0a39ef3b2..5cd23565bb 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -137,6 +137,7 @@ export const BoardCardContent = memo(function BoardCardContent({
actorType={issue.assignee_type!}
actorId={issue.assignee_id!}
size={22}
+ enableHoverCard
/>
}
/>
@@ -146,6 +147,7 @@ export const BoardCardContent = memo(function BoardCardContent({
actorType={issue.assignee_type!}
actorId={issue.assignee_id!}
size={22}
+ enableHoverCard
/>
))}
{showPriority &&
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 179a35bbef..fc10520a2a 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -213,8 +213,8 @@ function CommentRow({
return (
<div className={`py-3${isTemp ? " opacity-60" : ""}`}>
<div className="flex items-center gap-2.5">
- <ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size={24} />
- <span className="text-sm font-medium">
+ <ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size={24} enableHoverCard showStatusDot />
+ <span className="cursor-pointer text-sm font-medium">
{getActorName(entry.actor_type, entry.actor_id)}
</span>
<Tooltip>
@@ -417,8 +417,8 @@ function CommentCard({
<CollapsibleTrigger className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
<ChevronRight className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-90")} />
</CollapsibleTrigger>
- <ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size={24} />
- <span className="shrink-0 text-sm font-medium">
+ <ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size={24} enableHoverCard showStatusDot />
+ <span className="shrink-0 cursor-pointer text-sm font-medium">
{getActorName(entry.actor_type, entry.actor_id)}
</span>
<Tooltip>
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 775b3b719e..60de4c7c79 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -34,6 +34,7 @@ import { Checkbox } from "@multica/ui/components/ui/checkbox";
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@multica/ui/components/ui/command";
import { AvatarGroup, AvatarGroupCount } from "@multica/ui/components/ui/avatar";
import { ActorAvatar } from "../../common/actor-avatar";
+import { PropRow } from "../../common/prop-row";
import type { IssueStatus, IssuePriority, TimelineEntry } from "@multica/core/types";
import { STATUS_CONFIG, PRIORITY_CONFIG } from "@multica/core/issues/config";
import { StatusIcon, PriorityIcon, StatusPicker, PriorityPicker, DueDatePicker, AssigneePicker, LabelPicker } from ".";
@@ -129,28 +130,6 @@ function formatTokenCount(n: number): string {
return String(n);
}
-// ---------------------------------------------------------------------------
-// Property row
-// ---------------------------------------------------------------------------
-
-function PropRow({
- label,
- children,
-}: {
- label: string;
- children: React.ReactNode;
-}) {
- return (
- <div className="flex min-h-8 items-center gap-2 rounded-md px-2 -mx-2 hover:bg-accent/50 transition-colors">
- <span className="w-16 shrink-0 text-xs text-muted-foreground">{label}</span>
- <div className="flex min-w-0 flex-1 items-center gap-1.5 text-xs truncate">
- {children}
- </div>
- </div>
- );
-}
-
-
// ---------------------------------------------------------------------------
// Props
// ---------------------------------------------------------------------------
@@ -448,8 +427,8 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
</button>
{detailsOpen && <div className="space-y-0.5 pl-2">
<PropRow label="Created by">
- <ActorAvatar actorType={issue.creator_type} actorId={issue.creator_id} size={18} />
- <span className="truncate">{getActorName(issue.creator_type, issue.creator_id)}</span>
+ <ActorAvatar actorType={issue.creator_type} actorId={issue.creator_id} size={18} enableHoverCard />
+ <span className="cursor-pointer truncate">{getActorName(issue.creator_type, issue.creator_id)}</span>
</PropRow>
<PropRow label="Created">
<span className="text-muted-foreground">{shortDate(issue.created_at)}</span>
@@ -749,6 +728,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
actorId={child.assignee_id}
size={20}
className="shrink-0"
+ enableHoverCard
/>
) : (
<span
@@ -790,6 +770,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
actorType={sub.user_type}
actorId={sub.user_id}
size={24}
+ enableHoverCard
/>
))}
{subscribers.length > 4 && (
@@ -839,7 +820,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
className="flex items-center gap-2.5"
>
<Checkbox checked={isSubbed} className="pointer-events-none" />
- <ActorAvatar actorType="agent" actorId={a.id} size={22} />
+ <ActorAvatar actorType="agent" actorId={a.id} size={22} showStatusDot />
<span className="truncate flex-1">{a.name}</span>
</CommandItem>
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 520f59b6a9..8d196ba8e0 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -274,7 +274,7 @@ function ActorSubContent({
className={FILTER_ITEM_CLASS}
>
<HoverCheck checked={checked} />
- <ActorAvatar actorType="agent" actorId={a.id} size={18} />
+ <ActorAvatar actorType="agent" actorId={a.id} size={18} showStatusDot />
<span className="truncate">{a.name}</span>
{count > 0 && (
<span className="ml-auto text-xs text-muted-foreground">
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index 8dd3b81b01..9f29c8cd02 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -120,6 +120,7 @@ export const ListRow = memo(function ListRow({
actorType={issue.assignee_type!}
actorId={issue.assignee_id!}
size={20}
+ enableHoverCard
/>
)}
</AppLink>
diff --git a/packages/views/issues/components/pickers/assignee-picker.tsx b/packages/views/issues/components/pickers/assignee-picker.tsx
index 78b89eed28..ac08381483 100644
--- a/packages/views/issues/components/pickers/assignee-picker.tsx
+++ b/packages/views/issues/components/pickers/assignee-picker.tsx
@@ -99,7 +99,7 @@ export function AssigneePicker({
trigger={
customTrigger ? customTrigger : assigneeType && assigneeId ? (
<>
- <ActorAvatar actorType={assigneeType} actorId={assigneeId} size={18} disableHoverCard />
+ <ActorAvatar actorType={assigneeType} actorId={assigneeId} size={18} enableHoverCard showStatusDot />
<span className="truncate">{triggerLabel}</span>
</>
) : (
@@ -162,7 +162,7 @@ export function AssigneePicker({
setOpen(false);
}}
>
- <ActorAvatar actorType="agent" actorId={a.id} size={18} disableHoverCard />
+ <ActorAvatar actorType="agent" actorId={a.id} size={18} showStatusDot />
<span className={allowed ? "" : "text-muted-foreground"}>{a.name}</span>
{a.visibility === "private" && (
<Lock className="ml-auto h-3 w-3 text-muted-foreground" />
diff --git a/packages/views/issues/components/pickers/property-picker.tsx b/packages/views/issues/components/pickers/property-picker.tsx
index 5481a8b0c0..8dbd926015 100644
--- a/packages/views/issues/components/pickers/property-picker.tsx
+++ b/packages/views/issues/components/pickers/property-picker.tsx
@@ -7,6 +7,11 @@ import {
PopoverTrigger,
PopoverContent,
} from "@multica/ui/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
const HIGHLIGHT_CLASS = "bg-accent";
const ITEM_SELECTOR = "button[data-picker-item]:not(:disabled)";
@@ -25,6 +30,8 @@ export function PropertyPicker({
searchable = false,
searchPlaceholder = "Filter...",
onSearchChange,
+ header,
+ tooltip,
children,
footer,
}: {
@@ -37,6 +44,15 @@ export function PropertyPicker({
searchable?: boolean;
searchPlaceholder?: string;
onSearchChange?: (query: string) => void;
+ /** Custom sticky header rendered above the scrollable list. Use for
+ * filter toggles, search inputs, or any UI that must stay visible while
+ * the list scrolls. The built-in `searchable` input renders just above
+ * this header when both are present. */
+ header?: React.ReactNode;
+ /** Optional design-system tooltip shown when the trigger is hovered while
+ * the popover is closed. Suppressed automatically when the popover is
+ * open (otherwise tooltip + popover would stack on the same anchor). */
+ tooltip?: React.ReactNode;
children: React.ReactNode;
/**
* Optional footer rendered below the listbox. Unlike items rendered as
@@ -48,7 +64,12 @@ export function PropertyPicker({
}) {
const [query, setQuery] = useState("");
const [highlightedIndex, setHighlightedIndex] = useState(-1);
+ const [tooltipHover, setTooltipHover] = useState(false);
const listRef = useRef<HTMLDivElement>(null);
+ // Show the tooltip only while the trigger is hovered AND the popover is
+ // closed — avoids the awkward state where the tooltip floats next to (or
+ // on top of) the popover that just opened on click.
+ const tooltipOpen = !!tooltip && tooltipHover && !open;
const getItems = useCallback(() => {
if (!listRef.current) return [];
@@ -112,14 +133,25 @@ export function PropertyPicker({
[getItems, highlightedIndex],
);
+ const popoverTrigger = (
+ <PopoverTrigger
+ className={triggerRender ? undefined : "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden"}
+ render={triggerRender}
+ >
+ {trigger}
+ </PopoverTrigger>
+ );
+
return (
<Popover open={open} onOpenChange={handleOpenChange}>
- <PopoverTrigger
- className={triggerRender ? undefined : "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden"}
- render={triggerRender}
- >
- {trigger}
- </PopoverTrigger>
+ {tooltip ? (
+ <Tooltip open={tooltipOpen} onOpenChange={setTooltipHover}>
+ <TooltipTrigger render={popoverTrigger} />
+ <TooltipContent side="top">{tooltip}</TooltipContent>
+ </Tooltip>
+ ) : (
+ popoverTrigger
+ )}
<PopoverContent align={align} className={`${width} gap-0 p-0`}>
{searchable && (
<div className="px-2 py-1.5 border-b">
@@ -138,7 +170,8 @@ export function PropertyPicker({
/>
</div>
)}
- <div ref={listRef} className="p-1 max-h-60 overflow-y-auto">{children}</div>
+ {header && <div className="border-b">{header}</div>}
+ <div ref={listRef} className="p-1 max-h-72 overflow-y-auto">{children}</div>
{footer && <div className="border-t p-1">{footer}</div>}
</PopoverContent>
</Popover>
@@ -154,29 +187,51 @@ export function PickerItem({
disabled,
onClick,
hoverClassName,
+ tooltip,
children,
}: {
selected: boolean;
disabled?: boolean;
onClick: () => void;
hoverClassName?: string;
+ /** Design-system tooltip for the row — useful when truncated content needs
+ * the full string, or when the row carries metadata that doesn't fit on
+ * a single line. Wrapped in a real Tooltip component (200ms delay,
+ * styled), not a native `title` attribute. */
+ tooltip?: React.ReactNode;
children: React.ReactNode;
}) {
- return (
+ const button = (
<button
type="button"
data-picker-item
disabled={disabled}
onClick={onClick}
- className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm ${disabled ? "opacity-50 cursor-not-allowed" : hoverClassName ?? "hover:bg-accent"} transition-colors`}
+ className={`flex w-full items-center gap-3 rounded-md px-2 py-1.5 text-sm ${disabled ? "opacity-50 cursor-not-allowed" : hoverClassName ?? "hover:bg-accent"} transition-colors`}
>
{/* min-w-0 lets long children (like truncated label names) shrink
inside the flex row instead of pushing the selected checkmark off
- the right edge. shrink-0 on the Check keeps it visible. */}
+ the right edge. The check column always reserves its 14px slot
+ (visible when selected, invisible otherwise) so unselected rows
+ align with selected rows and the eye doesn't chase a jittery
+ right edge. */}
<span className="flex min-w-0 flex-1 items-center gap-2">{children}</span>
- {selected && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
+ <Check
+ className={`h-3.5 w-3.5 shrink-0 text-muted-foreground ${
+ selected ? "" : "invisible"
+ }`}
+ />
</button>
);
+
+ if (!tooltip) return button;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={button} />
+ <TooltipContent side="top">{tooltip}</TooltipContent>
+ </Tooltip>
+ );
}
// ---------------------------------------------------------------------------
diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsx
index 9ab955e61c..012090c101 100644
--- a/packages/views/layout/dashboard-layout.tsx
+++ b/packages/views/layout/dashboard-layout.tsx
@@ -5,6 +5,7 @@ import { SidebarProvider, SidebarInset } from "@multica/ui/components/ui/sidebar
import { ModalRegistry } from "../modals/registry";
import { AppSidebar } from "./app-sidebar";
import { DashboardGuard } from "./dashboard-guard";
+import { WorkspacePresencePrefetch } from "./workspace-presence-prefetch";
interface DashboardLayoutProps {
children: ReactNode;
@@ -31,6 +32,7 @@ export function DashboardLayout({
}
>
<SidebarProvider className="h-svh">
+ <WorkspacePresencePrefetch />
<AppSidebar searchSlot={searchSlot} />
<SidebarInset className="relative overflow-hidden">
{children}
diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.ts
index 8b8163f4fb..eb29227164 100644
--- a/packages/views/layout/index.ts
+++ b/packages/views/layout/index.ts
@@ -3,3 +3,4 @@ export { DashboardGuard } from "./dashboard-guard";
export { DashboardLayout } from "./dashboard-layout";
export { useDashboardGuard } from "./use-dashboard-guard";
export { WorkspaceLoader } from "./workspace-loader";
+export { WorkspacePresencePrefetch } from "./workspace-presence-prefetch";
diff --git a/packages/views/layout/workspace-presence-prefetch.tsx b/packages/views/layout/workspace-presence-prefetch.tsx
new file mode 100644
index 0000000000..0de8899d71
--- /dev/null
+++ b/packages/views/layout/workspace-presence-prefetch.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useWorkspaceId } from "@multica/core";
+import { useWorkspacePresencePrefetch } from "@multica/core/agents";
+
+// Mount once inside any subtree that's already gated on "workspace resolved"
+// (DashboardLayout on web, WorkspaceRouteLayout on desktop). useWorkspaceId
+// throws when called outside a resolved workspace — the gating in those
+// layouts guarantees this component never sees that state.
+export function WorkspacePresencePrefetch() {
+ const wsId = useWorkspaceId();
+ useWorkspacePresencePrefetch(wsId);
+ return null;
+}
diff --git a/packages/views/members/index.ts b/packages/views/members/index.ts
new file mode 100644
index 0000000000..1b0e5eec5b
--- /dev/null
+++ b/packages/views/members/index.ts
@@ -0,0 +1 @@
+export { MemberProfileCard } from "./member-profile-card";
diff --git a/packages/views/members/member-profile-card.tsx b/packages/views/members/member-profile-card.tsx
new file mode 100644
index 0000000000..e3fbd44163
--- /dev/null
+++ b/packages/views/members/member-profile-card.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import type { Agent, MemberRole } from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core";
+import { agentRunCounts30dOptions } from "@multica/core/agents";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { ActorAvatar } from "../common/actor-avatar";
+import { AppLink } from "../navigation";
+
+interface MemberProfileCardProps {
+ // The User UUID — matches member.user_id and agent.owner_id. We accept user_id
+ // (not member.id) because every existing call site passes user_id (assignee_id,
+ // commenter_id, owner_id are all User UUIDs in the polymorphic actor model).
+ userId: string;
+}
+
+const ROLE_LABEL: Record<MemberRole, string> = {
+ owner: "Owner",
+ admin: "Admin",
+ member: "Member",
+};
+
+// Mirrors AgentProfileCard's structure so the two hover surfaces feel like
+// twins ("agent and human are both first-class team members"). Content is
+// asymmetric on purpose: humans get identity + the AI agents they own; they
+// don't get a status dot because there's no member-presence backbone today
+// and we don't want to fabricate one.
+export function MemberProfileCard({ userId }: MemberProfileCardProps) {
+ const wsId = useWorkspaceId();
+ const { data: members = [], isLoading: membersLoading } = useQuery(
+ memberListOptions(wsId),
+ );
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: runCounts = [] } = useQuery(agentRunCounts30dOptions(wsId));
+
+ const member = members.find((m) => m.user_id === userId);
+
+ if (membersLoading && !member) {
+ return (
+ <div className="flex items-center gap-3">
+ <Skeleton className="h-10 w-10 rounded-full" />
+ <div className="flex-1 space-y-1.5">
+ <Skeleton className="h-4 w-28" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+ );
+ }
+
+ if (!member) {
+ return (
+ <div className="text-xs text-muted-foreground">Member unavailable</div>
+ );
+ }
+
+ const initials = member.name
+ .split(" ")
+ .map((w) => w[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
+
+ // Sort owned agents by 30-day run count (most-used first); break ties on
+ // name for a stable order. Run counts come from the same workspace-wide
+ // query that powers the Agents-list RUNS column — no extra fetch.
+ const runCountById = new Map(runCounts.map((r) => [r.agent_id, r.run_count]));
+ const ownedAgents = agents
+ .filter((a) => a.owner_id === userId && !a.archived_at)
+ .sort((a, b) => {
+ const ra = runCountById.get(a.id) ?? 0;
+ const rb = runCountById.get(b.id) ?? 0;
+ if (ra !== rb) return rb - ra;
+ return a.name.localeCompare(b.name);
+ });
+
+ return (
+ <div className="flex flex-col gap-3 text-left">
+ {/* Header */}
+ <div className="flex items-start gap-3">
+ <ActorAvatarBase
+ name={member.name}
+ initials={initials}
+ avatarUrl={member.avatar_url}
+ size={40}
+ className="rounded-full"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <p className="truncate text-sm font-semibold">{member.name}</p>
+ <RoleBadge role={member.role} />
+ </div>
+ <p className="mt-0.5 truncate text-xs text-muted-foreground">
+ {member.email}
+ </p>
+ </div>
+ </div>
+
+ {/* Owned agents */}
+ {ownedAgents.length > 0 && <OwnedAgentsSection agents={ownedAgents} />}
+ </div>
+ );
+}
+
+function RoleBadge({ role }: { role: MemberRole }) {
+ return (
+ <span className="rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
+ {ROLE_LABEL[role]}
+ </span>
+ );
+}
+
+function OwnedAgentsSection({ agents }: { agents: Agent[] }) {
+ // Top-2 by frequency (parent already sorted), each row links to the agent
+ // detail page. The presence dot is overlaid on the avatar via ActorAvatar's
+ // showStatusDot — `enableHoverCard` deliberately omitted to avoid
+ // popover-in-popover nesting; the click-through covers "want to know more".
+ // AppLink uses the platform navigation adapter so this works on web (Next
+ // router) and desktop (react-router-dom) without per-app branching.
+ const p = useWorkspacePaths();
+ const visible = agents.slice(0, 2);
+ const overflow = agents.length - visible.length;
+
+ return (
+ <div className="flex flex-col gap-1.5 text-xs">
+ <span className="text-muted-foreground">Agents ({agents.length})</span>
+ <div className="flex flex-col gap-0.5">
+ {visible.map((a) => (
+ <AppLink
+ key={a.id}
+ href={p.agentDetail(a.id)}
+ className="group -mx-1 flex cursor-pointer items-start gap-2 rounded-md px-1 py-1 transition-colors hover:bg-accent"
+ >
+ <ActorAvatar
+ actorType="agent"
+ actorId={a.id}
+ size={20}
+ showStatusDot
+ className="mt-0.5 shrink-0 rounded-md"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{a.name}</div>
+ {a.description && (
+ <div className="truncate text-muted-foreground">
+ {a.description}
+ </div>
+ )}
+ </div>
+ <span
+ aria-hidden
+ className="mt-0.5 shrink-0 font-normal text-brand opacity-0 transition-opacity group-hover:opacity-100"
+ >
+ Detail →
+ </span>
+ </AppLink>
+ ))}
+ {overflow > 0 && (
+ <span className="text-muted-foreground">
+ and {overflow} other agent{overflow === 1 ? "" : "s"}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsx
index 2179455d59..8483fcbf67 100644
--- a/packages/views/modals/create-project.tsx
+++ b/packages/views/modals/create-project.tsx
@@ -253,7 +253,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
<PillButton>
{leadType && leadId ? (
<>
- <ActorAvatar actorType={leadType} actorId={leadId} size={16} />
+ <ActorAvatar actorType={leadType} actorId={leadId} size={16} showStatusDot />
<span>{leadLabel}</span>
</>
) : (
@@ -323,7 +323,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
}}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-accent transition-colors"
>
- <ActorAvatar actorType="agent" actorId={a.id} size={16} />
+ <ActorAvatar actorType="agent" actorId={a.id} size={16} showStatusDot />
<span>{a.name}</span>
</button>
))}
diff --git a/packages/views/package.json b/packages/views/package.json
index 619e673704..68abbcf312 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -17,7 +17,7 @@
"./issues/hooks": "./issues/hooks/index.ts",
"./issues/utils/filter": "./issues/utils/filter.ts",
"./issues/utils/sort": "./issues/utils/sort.ts",
- "./issues/utils/redact": "./issues/utils/redact.ts",
+ "./common/task-transcript": "./common/task-transcript/index.ts",
"./projects/components": "./projects/components/index.ts",
"./autopilots/components": "./autopilots/components/index.ts",
"./modals/registry": "./modals/registry.tsx",
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index ade4acfc1b..ce432e21f1 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -377,8 +377,8 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
<button type="button" className="inline-flex items-center gap-1.5 text-xs hover:text-foreground transition-colors">
{project.lead_type && project.lead_id ? (
<>
- <ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={16} />
- <span>{getActorName(project.lead_type, project.lead_id)}</span>
+ <ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={16} enableHoverCard showStatusDot />
+ <span className="cursor-pointer">{getActorName(project.lead_type, project.lead_id)}</span>
</>
) : (
<span className="text-muted-foreground">No lead</span>
@@ -431,7 +431,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
onClick={() => { handleUpdateField({ lead_type: "agent", lead_id: a.id }); setLeadOpen(false); }}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-accent transition-colors"
>
- <ActorAvatar actorType="agent" actorId={a.id} size={16} />
+ <ActorAvatar actorType="agent" actorId={a.id} size={16} showStatusDot />
<span>{a.name}</span>
</button>
))}
diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsx
index 3e5a3b9e32..1c27455ad6 100644
--- a/packages/views/projects/components/projects-page.tsx
+++ b/packages/views/projects/components/projects-page.tsx
@@ -152,7 +152,7 @@ function ProjectRow({ project }: { project: Project }) {
<button type="button" className="flex w-10 items-center justify-center shrink-0 rounded-full hover:ring-2 hover:ring-accent transition-all cursor-pointer">
{project.lead_type && project.lead_id ? (
<Tooltip>
- <TooltipTrigger render={<span><ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={22} /></span>} />
+ <TooltipTrigger render={<span><ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size={22} enableHoverCard /></span>} />
<TooltipContent side="bottom">{getActorName(project.lead_type, project.lead_id)}</TooltipContent>
</Tooltip>
) : (
@@ -206,7 +206,7 @@ function ProjectRow({ project }: { project: Project }) {
onClick={() => { handleUpdate({ lead_type: "agent", lead_id: a.id }); setLeadOpen(false); }}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-accent transition-colors"
>
- <ActorAvatar actorType="agent" actorId={a.id} size={16} />
+ <ActorAvatar actorType="agent" actorId={a.id} size={16} showStatusDot />
<span>{a.name}</span>
</button>
))}
diff --git a/packages/views/runtimes/components/charts/activity-heatmap.tsx b/packages/views/runtimes/components/charts/activity-heatmap.tsx
index 80e86fdd0f..1a4a18d58e 100644
--- a/packages/views/runtimes/components/charts/activity-heatmap.tsx
+++ b/packages/views/runtimes/components/charts/activity-heatmap.tsx
@@ -1,25 +1,58 @@
import { useMemo } from "react";
import type { RuntimeUsage } from "@multica/core/types";
-import { formatTokens } from "../../utils";
+import { estimateCost } from "../../utils";
-const HEATMAP_WEEKS = 13;
-const CELL_SIZE = 11;
-const CELL_GAP = 2;
+// 26 weeks (~6 months) gives the heatmap real presence in the wider chart
+// card and turns "long-view" into a meaningful tab — a 13-week strip looked
+// cramped. Cells at 16px (vs GitHub's 11) keep the calendar-square density
+// readable at this scale.
+const HEATMAP_WEEKS = 26;
+const CELL_SIZE = 16;
+const CELL_GAP = 3;
const DAY_LABELS = ["", "Mon", "", "Wed", "", "Fri", ""];
+const WEEKDAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
+// Cells use the brand-derived chart-1 hue with descending opacity instead
+// of a neutral foreground fade, so the heatmap reads as part of the same
+// visual family as Daily cost (chart-1 stack) rather than a separate
+// monochrome surface. Level 0 stays neutral muted to clearly mean "no
+// activity" (not "very faint activity").
function getHeatmapColor(level: number): string {
if (level === 0) return "var(--color-muted)";
- const opacities = ["25%", "45%", "68%", "90%"];
- return `color-mix(in oklch, var(--color-foreground) ${opacities[level - 1]}, transparent)`;
+ const opacities = ["20%", "45%", "70%", "100%"];
+ return `color-mix(in oklch, var(--color-chart-1) ${opacities[level - 1]}, transparent)`;
+}
+
+function fmtMoney(n: number): string {
+ if (n >= 100) return `$${n.toFixed(0)}`;
+ return `$${n.toFixed(2)}`;
+}
+
+function fmtDate(iso: string): string {
+ return new Date(iso + "T00:00:00").toLocaleString("en", {
+ month: "short",
+ day: "numeric",
+ });
+}
+
+interface Insights {
+ busiestDay: { date: string; cost: number } | null;
+ busyDayName: string | null;
+ busyDayAvg: number;
+ quietDayName: string | null;
+ quietDayAvg: number;
+ totalCost: number;
+ windowDays: number;
}
export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {
- const { cells, monthLabels } = useMemo(() => {
- const dateTokens = new Map<string, number>();
+ const { cells, monthLabels, insights } = useMemo(() => {
+ // Sum priced cost per day. Cost (not tokens) gives the colour scale a
+ // financial meaning that lines up with the rest of the page — a "hot"
+ // square here means the same thing as a tall bar in Daily cost.
+ const dateCost = new Map<string, number>();
for (const u of usage) {
- const total =
- u.input_tokens + u.output_tokens + u.cache_read_tokens + u.cache_write_tokens;
- dateTokens.set(u.date, (dateTokens.get(u.date) ?? 0) + total);
+ dateCost.set(u.date, (dateCost.get(u.date) ?? 0) + estimateCost(u));
}
const today = new Date();
@@ -32,7 +65,7 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {
date: string;
dayOfWeek: number;
week: number;
- tokens: number;
+ cost: number;
}[] = [];
const d = new Date(startDate);
for (let i = 0; i <= startOffset; i++) {
@@ -43,19 +76,17 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {
date: dateStr,
dayOfWeek,
week,
- tokens: dateTokens.get(dateStr) ?? 0,
+ cost: dateCost.get(dateStr) ?? 0,
});
d.setDate(d.getDate() + 1);
}
- const nonZero = allCells
- .filter((c) => c.tokens > 0)
- .map((c) => c.tokens);
+ const nonZero = allCells.filter((c) => c.cost > 0).map((c) => c.cost);
nonZero.sort((a, b) => a - b);
- const getLevel = (tokens: number) => {
- if (tokens === 0) return 0;
+ const getLevel = (cost: number) => {
+ if (cost === 0) return 0;
if (nonZero.length <= 1) return 4;
- const p = nonZero.indexOf(tokens) / (nonZero.length - 1);
+ const p = nonZero.indexOf(cost) / (nonZero.length - 1);
if (p <= 0.25) return 1;
if (p <= 0.5) return 2;
if (p <= 0.75) return 3;
@@ -64,7 +95,7 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {
const cellsWithLevel = allCells.map((c) => ({
...c,
- level: getLevel(c.tokens),
+ level: getLevel(c.cost),
}));
const months: { label: string; week: number }[] = [];
@@ -82,75 +113,192 @@ export function ActivityHeatmap({ usage }: { usage: RuntimeUsage[] }) {
}
}
- return { cells: cellsWithLevel, monthLabels: months };
+ // Insights derived from the same cells so the colour scale, the busiest
+ // square, and the side-panel numbers can never disagree.
+ let busiestDay: { date: string; cost: number } | null = null;
+ let totalCost = 0;
+ const weekdaySum = [0, 0, 0, 0, 0, 0, 0];
+ const weekdayCount = [0, 0, 0, 0, 0, 0, 0];
+ for (const c of allCells) {
+ totalCost += c.cost;
+ weekdaySum[c.dayOfWeek] = (weekdaySum[c.dayOfWeek] ?? 0) + c.cost;
+ weekdayCount[c.dayOfWeek] = (weekdayCount[c.dayOfWeek] ?? 0) + 1;
+ if (c.cost > 0 && (!busiestDay || c.cost > busiestDay.cost)) {
+ busiestDay = { date: c.date, cost: c.cost };
+ }
+ }
+ const weekdayAvg = weekdaySum.map((s, i) => {
+ const count = weekdayCount[i] ?? 0;
+ return count > 0 ? s / count : 0;
+ });
+ let busyDayName: string | null = null;
+ let busyDayAvg = 0;
+ let quietDayName: string | null = null;
+ let quietDayAvg = Number.POSITIVE_INFINITY;
+ weekdayAvg.forEach((avg, i) => {
+ const name = WEEKDAY_NAMES[i] ?? "";
+ if (avg > busyDayAvg) {
+ busyDayAvg = avg;
+ busyDayName = name;
+ }
+ if (avg < quietDayAvg) {
+ quietDayAvg = avg;
+ quietDayName = name;
+ }
+ });
+ if (quietDayAvg === Number.POSITIVE_INFINITY) quietDayAvg = 0;
+ // When the window has no spend at all, the busy / quiet weekday picks
+ // are noise (every weekday averaged to 0). Suppress them.
+ if (totalCost === 0) {
+ busyDayName = null;
+ quietDayName = null;
+ }
+
+ const insights: Insights = {
+ busiestDay,
+ busyDayName,
+ busyDayAvg,
+ quietDayName,
+ quietDayAvg,
+ totalCost,
+ windowDays: allCells.length,
+ };
+
+ return { cells: cellsWithLevel, monthLabels: months, insights };
}, [usage]);
const labelWidth = 28;
const svgWidth = labelWidth + HEATMAP_WEEKS * (CELL_SIZE + CELL_GAP);
const svgHeight = 14 + 7 * (CELL_SIZE + CELL_GAP);
+ // Vertical stack: heatmap centered up top, insights as a 4-cell stat
+ // strip below (separated by a hairline). Stacking guarantees the parent
+ // card width is decided entirely by its own grid cell — never by the
+ // SVG's intrinsic 249px or by the insight labels — and switching to /
+ // from this tab no longer changes the card's apparent width.
return (
- <div className="rounded-lg border p-4">
- <h4 className="text-xs font-medium text-muted-foreground mb-3">Activity</h4>
- <div className="overflow-x-auto">
- <svg width={svgWidth} height={svgHeight} className="block">
- {monthLabels.map((m) => (
- <text
- key={`${m.label}-${m.week}`}
- x={labelWidth + m.week * (CELL_SIZE + CELL_GAP)}
- y={10}
- className="fill-muted-foreground"
- fontSize={9}
- >
- {m.label}
- </text>
- ))}
- {DAY_LABELS.map((label, i) =>
- label ? (
+ <div className="space-y-4">
+ <div className="flex flex-col items-center gap-2">
+ <div className="overflow-x-auto">
+ <svg width={svgWidth} height={svgHeight} className="block">
+ {monthLabels.map((m) => (
<text
- key={i}
- x={0}
- y={14 + i * (CELL_SIZE + CELL_GAP) + CELL_SIZE - 1}
+ key={`${m.label}-${m.week}`}
+ x={labelWidth + m.week * (CELL_SIZE + CELL_GAP)}
+ y={10}
className="fill-muted-foreground"
fontSize={9}
>
- {label}
+ {m.label}
</text>
- ) : null,
- )}
- {cells.map((c) => (
- <rect
- key={c.date}
- x={labelWidth + c.week * (CELL_SIZE + CELL_GAP)}
- y={14 + c.dayOfWeek * (CELL_SIZE + CELL_GAP)}
- width={CELL_SIZE}
- height={CELL_SIZE}
- rx={2}
- fill={getHeatmapColor(c.level)}
- className="transition-colors"
- >
- <title>
- {c.date}:{" "}
- {c.tokens > 0
- ? formatTokens(c.tokens) + " tokens"
- : "No activity"}
- </title>
- </rect>
+ ))}
+ {DAY_LABELS.map((label, i) =>
+ label ? (
+ <text
+ key={i}
+ x={0}
+ y={14 + i * (CELL_SIZE + CELL_GAP) + CELL_SIZE - 1}
+ className="fill-muted-foreground"
+ fontSize={9}
+ >
+ {label}
+ </text>
+ ) : null,
+ )}
+ {cells.map((c) => (
+ <rect
+ key={c.date}
+ x={labelWidth + c.week * (CELL_SIZE + CELL_GAP)}
+ y={14 + c.dayOfWeek * (CELL_SIZE + CELL_GAP)}
+ width={CELL_SIZE}
+ height={CELL_SIZE}
+ rx={3}
+ fill={getHeatmapColor(c.level)}
+ className="transition-colors"
+ >
+ <title>
+ {c.date}:{" "}
+ {c.cost > 0 ? `$${c.cost.toFixed(2)}` : "No activity"}
+ </title>
+ </rect>
+ ))}
+ </svg>
+ </div>
+ <div className="flex items-center gap-1 text-[10px] text-muted-foreground">
+ <span>Less</span>
+ {[0, 1, 2, 3, 4].map((level) => (
+ <div
+ key={level}
+ className="h-[10px] w-[10px] rounded-[2px]"
+ style={{ backgroundColor: getHeatmapColor(level) }}
+ />
))}
- </svg>
- </div>
- {/* Legend */}
- <div className="mt-2 flex items-center justify-end gap-1 text-[10px] text-muted-foreground">
- <span>Less</span>
- {[0, 1, 2, 3, 4].map((level) => (
- <div
- key={level}
- className="h-[10px] w-[10px] rounded-[2px]"
- style={{ backgroundColor: getHeatmapColor(level) }}
- />
- ))}
- <span>More</span>
+ <span>More</span>
+ </div>
</div>
+
+ <InsightsRow insights={insights} />
+ </div>
+ );
+}
+
+// Horizontal stat strip beneath the heatmap. Mirrors the page-top KPI
+// hero pattern (label → big value → sub) but at smaller scale to stay
+// secondary. 4 columns on desktop, 2 on narrow screens.
+function InsightsRow({ insights }: { insights: Insights }) {
+ const {
+ busiestDay,
+ busyDayName,
+ busyDayAvg,
+ quietDayName,
+ quietDayAvg,
+ totalCost,
+ windowDays,
+ } = insights;
+ return (
+ <dl className="grid grid-cols-2 gap-x-4 gap-y-3 border-t pt-3 sm:grid-cols-4">
+ <Insight
+ label="Busiest day"
+ value={busiestDay ? fmtDate(busiestDay.date) : "—"}
+ sub={busiestDay ? fmtMoney(busiestDay.cost) : null}
+ />
+ <Insight
+ label="Most active weekday"
+ value={busyDayName ?? "—"}
+ sub={busyDayName ? `avg ${fmtMoney(busyDayAvg)}` : null}
+ />
+ <Insight
+ label="Quietest weekday"
+ value={quietDayName ?? "—"}
+ sub={quietDayName ? `avg ${fmtMoney(quietDayAvg)}` : null}
+ />
+ <Insight label={`${windowDays}-day total`} value={fmtMoney(totalCost)} />
+ </dl>
+ );
+}
+
+function Insight({
+ label,
+ value,
+ sub,
+}: {
+ label: string;
+ value: string;
+ sub?: string | null;
+}) {
+ return (
+ <div className="min-w-0">
+ <dt className="truncate text-[11px] uppercase tracking-wider text-muted-foreground">
+ {label}
+ </dt>
+ <dd className="mt-0.5 truncate text-sm font-medium tabular-nums">
+ {value}
+ {sub != null && (
+ <span className="ml-1.5 text-xs font-normal text-muted-foreground">
+ {sub}
+ </span>
+ )}
+ </dd>
</div>
);
}
diff --git a/packages/views/runtimes/components/charts/daily-cost-chart.tsx b/packages/views/runtimes/components/charts/daily-cost-chart.tsx
index 82796dffa8..6257166188 100644
--- a/packages/views/runtimes/components/charts/daily-cost-chart.tsx
+++ b/packages/views/runtimes/components/charts/daily-cost-chart.tsx
@@ -11,47 +11,78 @@ import {
ChartTooltipContent,
type ChartConfig,
} from "@multica/ui/components/ui/chart";
-import type { DailyCostData } from "../../utils";
+import type { DailyCostStackData } from "../../utils";
-const costChartConfig = {
- cost: { label: "Cost", color: "var(--color-chart-1)" },
+// Three-segment stack (input / output / cache write) — keeps the user's
+// attention on what's actually driving spend. Cache reads are excluded
+// because their per-token rate is two orders of magnitude smaller and
+// would be visually invisible in a stack; we surface their *savings*
+// separately as a KPI.
+//
+// Series → CSS chart token: stack reads bottom-up as chart-1 (deepest brand
+// blue, "input") → chart-2 (mid) → chart-3 (lightest, "cache write"), so the
+// visual depth maps directly to "primary cost driver → secondary".
+export const costStackConfig = {
+ input: { label: "Input", color: "var(--chart-1)" },
+ output: { label: "Output", color: "var(--chart-2)" },
+ cacheWrite: { label: "Cache write", color: "var(--chart-3)" },
} satisfies ChartConfig;
-export function DailyCostChart({ data }: { data: DailyCostData[] }) {
- if (data.every((d) => d.cost === 0)) return null;
-
+export function DailyCostChart({ data }: { data: DailyCostStackData[] }) {
+ // No internal empty-state — the parent decides what to show in place of
+ // the chart (often a diagnostic explaining *why* there's no cost). Letting
+ // recharts render an empty axis would be both ugly and uninformative.
return (
- <div className="rounded-lg border p-4">
- <h4 className="text-xs font-medium text-muted-foreground mb-3">Daily Estimated Cost</h4>
- <ChartContainer config={costChartConfig} className="aspect-[2.5/1] w-full">
- <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
- <CartesianGrid vertical={false} />
- <XAxis
- dataKey="label"
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- interval="preserveStartEnd"
- />
- <YAxis
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- tickFormatter={(v: number) => `$${v}`}
- width={50}
- />
- <ChartTooltip
- content={
- <ChartTooltipContent
- formatter={(value) =>
- typeof value === "number" ? `$${value.toFixed(2)}` : String(value)
- }
- />
- }
- />
- <Bar dataKey="cost" fill="var(--color-cost)" radius={[3, 3, 0, 0]} />
- </BarChart>
- </ChartContainer>
- </div>
+ <ChartContainer config={costStackConfig} className="aspect-[3/1] w-full">
+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey="label"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ tickFormatter={(v: number) => `$${v}`}
+ width={50}
+ />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ formatter={(value, name) =>
+ typeof value === "number"
+ ? `$${value.toFixed(2)} ${name}`
+ : `${value} ${name}`
+ }
+ />
+ }
+ />
+ {/* Legend is intentionally rendered by the parent (in the chart card
+ header, top-right) so the chart body stays clean and gets the full
+ vertical real estate. */}
+ <Bar
+ dataKey="input"
+ stackId="cost"
+ fill="var(--color-input)"
+ radius={[0, 0, 0, 0]}
+ />
+ <Bar
+ dataKey="output"
+ stackId="cost"
+ fill="var(--color-output)"
+ radius={[0, 0, 0, 0]}
+ />
+ <Bar
+ dataKey="cacheWrite"
+ stackId="cost"
+ fill="var(--color-cacheWrite)"
+ radius={[3, 3, 0, 0]}
+ />
+ </BarChart>
+ </ChartContainer>
);
}
diff --git a/packages/views/runtimes/components/charts/daily-token-chart.tsx b/packages/views/runtimes/components/charts/daily-token-chart.tsx
deleted file mode 100644
index 239247d8c8..0000000000
--- a/packages/views/runtimes/components/charts/daily-token-chart.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { useMemo } from "react";
-import {
- AreaChart,
- Area,
- XAxis,
- YAxis,
- CartesianGrid,
- Tooltip,
-} from "recharts";
-import {
- ChartContainer,
- type ChartConfig,
-} from "@multica/ui/components/ui/chart";
-import type { DailyTokenData } from "../../utils";
-import { formatTokens } from "../../utils";
-
-const tokenChartConfig = {
- total: { label: "Total", color: "var(--color-chart-1)" },
-} satisfies ChartConfig;
-
-type DailyTokenRow = DailyTokenData & { total: number };
-
-function computeNiceTicks(data: DailyTokenRow[], tickCount = 5): number[] {
- const maxTotal = data.reduce(
- (max, d) => (d.total > max ? d.total : max),
- 0,
- );
- if (maxTotal === 0) return [0];
-
- const rawStep = maxTotal / (tickCount - 1);
- const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)));
- const niceSteps = [1, 2, 2.5, 5, 10];
- const niceStep =
- magnitude * (niceSteps.find((s) => s * magnitude >= rawStep) ?? 10);
-
- const ticks: number[] = [];
- for (let i = 0; i < tickCount; i++) {
- ticks.push(niceStep * i);
- }
- if ((ticks[ticks.length - 1] ?? 0) < maxTotal) {
- ticks.push(niceStep * tickCount);
- }
- return ticks;
-}
-
-function TokenTooltipContent({
- active,
- payload,
- label,
-}: {
- active?: boolean;
- payload?: Array<{ payload: DailyTokenRow }>;
- label?: string;
-}) {
- if (!active || !payload?.length) return null;
- const row = payload[0]!.payload;
-
- const items = [
- { label: "Input", value: row.input },
- { label: "Output", value: row.output },
- { label: "Cache Read", value: row.cacheRead },
- { label: "Cache Write", value: row.cacheWrite },
- ];
-
- return (
- <div className="rounded-lg border border-border/50 bg-background px-3 py-2 text-xs shadow-xl">
- <div className="font-medium mb-1.5">{label}</div>
- <div className="grid gap-1">
- {items.map((item) => (
- <div
- key={item.label}
- className="flex items-center justify-between gap-6"
- >
- <span className="text-muted-foreground">{item.label}</span>
- <span className="font-mono font-medium tabular-nums">
- {formatTokens(item.value)}
- </span>
- </div>
- ))}
- <div className="flex items-center justify-between gap-6 border-t pt-1 mt-0.5 font-medium">
- <span>Total</span>
- <span className="font-mono tabular-nums">
- {formatTokens(row.total)}
- </span>
- </div>
- </div>
- </div>
- );
-}
-
-export function DailyTokenChart({ data }: { data: DailyTokenData[] }) {
- const chartData = useMemo<DailyTokenRow[]>(
- () =>
- data.map((d) => ({
- ...d,
- total: d.input + d.output + d.cacheRead + d.cacheWrite,
- })),
- [data],
- );
- const ticks = useMemo(() => computeNiceTicks(chartData), [chartData]);
- const yMax = ticks[ticks.length - 1] ?? 0;
-
- return (
- <div className="rounded-lg border p-4">
- <h4 className="text-xs font-medium text-muted-foreground mb-3">
- Daily Token Usage
- </h4>
- <ChartContainer
- config={tokenChartConfig}
- className="aspect-[2.5/1] w-full"
- >
- <AreaChart
- data={chartData}
- margin={{ left: 0, right: 0, top: 4, bottom: 0 }}
- >
- <CartesianGrid vertical={false} />
- <XAxis
- dataKey="label"
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- interval="preserveStartEnd"
- />
- <YAxis
- type="number"
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- tickFormatter={(v: number) => formatTokens(v)}
- width={65}
- domain={[0, yMax]}
- ticks={ticks}
- />
- <Tooltip content={<TokenTooltipContent />} />
- <Area
- type="monotone"
- dataKey="total"
- stroke="var(--color-total)"
- fill="var(--color-total)"
- fillOpacity={0.3}
- />
- </AreaChart>
- </ChartContainer>
- </div>
- );
-}
diff --git a/packages/views/runtimes/components/charts/hourly-activity-chart.tsx b/packages/views/runtimes/components/charts/hourly-activity-chart.tsx
index 64d67224d6..c4061e4250 100644
--- a/packages/views/runtimes/components/charts/hourly-activity-chart.tsx
+++ b/packages/views/runtimes/components/charts/hourly-activity-chart.tsx
@@ -1,5 +1,4 @@
-import { useState, useEffect, useMemo } from "react";
-import { BarChart3 } from "lucide-react";
+import { useMemo } from "react";
import {
BarChart,
Bar,
@@ -13,73 +12,66 @@ import {
ChartTooltipContent,
type ChartConfig,
} from "@multica/ui/components/ui/chart";
-import { api } from "@multica/core/api";
-import type { RuntimeHourlyActivity } from "@multica/core/types";
+// Hour-of-day cost. The "WHEN" tab in the runtime detail uses this to show
+// "during what hours of the day did this runtime spend money", which is
+// fundamentally different from "how much per calendar day". Data is fed in
+// by the parent (single orchestrator pattern) — this component is dumb.
const hourlyChartConfig = {
- count: { label: "Tasks", color: "var(--color-chart-2)" },
+ cost: { label: "Cost", color: "var(--color-chart-1)" },
} satisfies ChartConfig;
-export function HourlyActivityChart({ runtimeId }: { runtimeId: string }) {
- const [data, setData] = useState<RuntimeHourlyActivity[]>([]);
- const [loading, setLoading] = useState(true);
-
- useEffect(() => {
- setLoading(true);
- api
- .getRuntimeTaskActivity(runtimeId)
- .then(setData)
- .catch(() => setData([]))
- .finally(() => setLoading(false));
- }, [runtimeId]);
+export interface HourlyCostPoint {
+ hour: number;
+ cost: number;
+}
+export function HourlyActivityChart({ data }: { data: HourlyCostPoint[] }) {
+ // Always render 24 buckets so the X axis is continuous. The parent passes
+ // pre-aggregated server data which may omit hours with zero activity;
+ // we fill those in with $0 here so visual gaps are intentional ("nothing
+ // ran at 03:00") rather than missing data.
const chartData = useMemo(() => {
- const map = new Map(data.map((d) => [d.hour, d.count]));
+ const map = new Map(data.map((d) => [d.hour, d.cost]));
return Array.from({ length: 24 }, (_, i) => ({
hour: i,
label: `${i.toString().padStart(2, "0")}:00`,
- count: map.get(i) ?? 0,
+ cost: map.get(i) ?? 0,
}));
}, [data]);
- const hasData = chartData.some((d) => d.count > 0);
-
return (
- <div className="rounded-lg border p-4">
- <h4 className="text-xs font-medium text-muted-foreground mb-3">Hourly Distribution</h4>
- {loading ? (
- <div className="flex h-[140px] items-center justify-center text-xs text-muted-foreground">
- Loading...
- </div>
- ) : !hasData ? (
- <div className="flex h-[140px] flex-col items-center justify-center">
- <BarChart3 className="h-5 w-5 text-muted-foreground/40" />
- <p className="mt-2 text-xs text-muted-foreground">No task data yet</p>
- </div>
- ) : (
- <ChartContainer config={hourlyChartConfig} className="aspect-[2.5/1] w-full">
- <BarChart data={chartData} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
- <CartesianGrid vertical={false} />
- <XAxis
- dataKey="label"
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- interval={2}
- fontSize={10}
- />
- <YAxis
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- width={30}
- allowDecimals={false}
+ <ChartContainer config={hourlyChartConfig} className="aspect-[3/1] w-full">
+ <BarChart data={chartData} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey="label"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ interval={2}
+ fontSize={10}
+ />
+ <YAxis
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ tickFormatter={(v: number) => `$${v}`}
+ width={40}
+ />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ formatter={(value) =>
+ typeof value === "number"
+ ? `$${value.toFixed(2)}`
+ : String(value)
+ }
/>
- <ChartTooltip content={<ChartTooltipContent />} />
- <Bar dataKey="count" fill="var(--color-count)" radius={[2, 2, 0, 0]} />
- </BarChart>
- </ChartContainer>
- )}
- </div>
+ }
+ />
+ <Bar dataKey="cost" fill="var(--color-cost)" radius={[2, 2, 0, 0]} />
+ </BarChart>
+ </ChartContainer>
);
}
diff --git a/packages/views/runtimes/components/charts/index.ts b/packages/views/runtimes/components/charts/index.ts
index cc1ec80a7a..5184df2941 100644
--- a/packages/views/runtimes/components/charts/index.ts
+++ b/packages/views/runtimes/components/charts/index.ts
@@ -1,5 +1,3 @@
-export { DailyTokenChart } from "./daily-token-chart";
-export { DailyCostChart } from "./daily-cost-chart";
-export { ModelDistributionChart } from "./model-distribution-chart";
+export { DailyCostChart, costStackConfig } from "./daily-cost-chart";
export { ActivityHeatmap } from "./activity-heatmap";
export { HourlyActivityChart } from "./hourly-activity-chart";
diff --git a/packages/views/runtimes/components/charts/model-distribution-chart.tsx b/packages/views/runtimes/components/charts/model-distribution-chart.tsx
deleted file mode 100644
index ddfc397c3e..0000000000
--- a/packages/views/runtimes/components/charts/model-distribution-chart.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { PieChart, Pie, Cell, Label } from "recharts";
-import {
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
- type ChartConfig,
-} from "@multica/ui/components/ui/chart";
-import type { ModelDistribution } from "../../utils";
-import { formatTokens } from "../../utils";
-
-const MODEL_COLORS = [
- "var(--color-chart-1)",
- "var(--color-chart-2)",
- "var(--color-chart-3)",
- "var(--color-chart-4)",
- "var(--color-chart-5)",
-];
-
-export function ModelDistributionChart({ data }: { data: ModelDistribution[] }) {
- if (data.length === 0) return null;
-
- const totalTokens = data.reduce((sum, d) => sum + d.tokens, 0);
- const chartConfig = Object.fromEntries(
- data.map((d, i) => [
- d.model,
- { label: d.model, color: MODEL_COLORS[i % MODEL_COLORS.length] },
- ]),
- ) satisfies ChartConfig;
-
- return (
- <div className="rounded-lg border p-4">
- <h4 className="text-xs font-medium text-muted-foreground mb-3">Token Usage by Model</h4>
- <ChartContainer config={chartConfig} className="mx-auto aspect-square max-h-[200px]">
- <PieChart>
- <ChartTooltip
- content={
- <ChartTooltipContent
- formatter={(value) =>
- typeof value === "number" ? formatTokens(value) : String(value)
- }
- nameKey="model"
- />
- }
- />
- <Pie
- data={data}
- dataKey="tokens"
- nameKey="model"
- innerRadius={50}
- outerRadius={80}
- paddingAngle={2}
- >
- {data.map((entry, i) => (
- <Cell
- key={entry.model}
- fill={MODEL_COLORS[i % MODEL_COLORS.length]}
- />
- ))}
- <Label
- content={({ viewBox }) => {
- if (viewBox && "cx" in viewBox && "cy" in viewBox) {
- return (
- <text x={viewBox.cx} y={viewBox.cy} textAnchor="middle" dominantBaseline="middle">
- <tspan x={viewBox.cx} y={viewBox.cy} className="fill-foreground text-lg font-bold">
- {formatTokens(totalTokens)}
- </tspan>
- <tspan x={viewBox.cx} y={(viewBox.cy ?? 0) + 18} className="fill-muted-foreground text-xs">
- tokens
- </tspan>
- </text>
- );
- }
- return null;
- }}
- />
- </Pie>
- </PieChart>
- </ChartContainer>
- {/* Model legend with cost */}
- <div className="mt-3 space-y-1.5">
- {data.map((d, i) => (
- <div key={d.model} className="flex items-center justify-between text-xs">
- <div className="flex items-center gap-2 min-w-0">
- <div
- className="h-2 w-2 shrink-0 rounded-full"
- style={{ backgroundColor: MODEL_COLORS[i % MODEL_COLORS.length] }}
- />
- <span className="truncate font-mono">{d.model}</span>
- </div>
- <div className="flex items-center gap-3 shrink-0 text-muted-foreground tabular-nums">
- <span>{formatTokens(d.tokens)}</span>
- {d.cost > 0 && <span>${d.cost.toFixed(2)}</span>}
- </div>
- </div>
- ))}
- </div>
- </div>
- );
-}
diff --git a/packages/views/runtimes/components/index.ts b/packages/views/runtimes/components/index.ts
index de77d9b4ce..4534a4c14e 100644
--- a/packages/views/runtimes/components/index.ts
+++ b/packages/views/runtimes/components/index.ts
@@ -1 +1,2 @@
export { default as RuntimesPage } from "./runtimes-page";
+export { RuntimeDetailPage } from "./runtime-detail-page";
diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsx
new file mode 100644
index 0000000000..fc23482109
--- /dev/null
+++ b/packages/views/runtimes/components/runtime-detail-page.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { Server } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { RuntimeDetail } from "./runtime-detail";
+
+/**
+ * Routed entry for `/{slug}/runtimes/{id}`. Reads the workspace runtime list
+ * from cache (the list page already populated it), finds the matching
+ * runtime, and renders the shared detail surface. We deliberately avoid
+ * adding a per-runtime fetch endpoint — the list query is already keyed
+ * per-workspace and is the source of truth for membership; reading from it
+ * keeps cache invariants simple (one cache, one update path).
+ */
+export function RuntimeDetailPage({ runtimeId }: { runtimeId: string }) {
+ const wsId = useWorkspaceId();
+ const { data: runtimes, isLoading } = useQuery(runtimeListOptions(wsId));
+
+ if (isLoading) {
+ return (
+ <div className="flex h-full flex-col p-6">
+ <Skeleton className="h-12 w-1/2" />
+ <div className="mt-6 grid grid-cols-3 gap-3">
+ <Skeleton className="h-20 rounded-lg" />
+ <Skeleton className="h-20 rounded-lg" />
+ <Skeleton className="h-20 rounded-lg" />
+ </div>
+ <Skeleton className="mt-4 h-48 w-full rounded-lg" />
+ </div>
+ );
+ }
+
+ const runtime = runtimes?.find((r) => r.id === runtimeId);
+ if (!runtime) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
+ <Server className="h-10 w-10 text-muted-foreground/30" />
+ <p className="mt-3 text-sm">Runtime not found</p>
+ <p className="mt-1 text-xs text-muted-foreground/70">
+ It may have been deleted or you may not have access.
+ </p>
+ </div>
+ );
+ }
+
+ return <RuntimeDetail runtime={runtime} />;
+}
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index dec1ad22ee..3cdee55734 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -1,14 +1,26 @@
"use client";
-import { useState } from "react";
-import { Trash2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import {
+ ArrowLeft,
+ Trash2,
+ ChevronRight,
+ Cpu,
+ Lock,
+} from "lucide-react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
-import type { AgentRuntime } from "@multica/core/types";
+import type { AgentRuntime, Agent, MemberWithUser } from "@multica/core/types";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
+import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
import { useDeleteRuntime } from "@multica/core/runtimes/mutations";
+import { deriveRuntimeHealth } from "@multica/core/runtimes";
+import {
+ type AgentPresenceDetail,
+ useWorkspacePresenceMap,
+} from "@multica/core/agents";
+import { useWorkspacePaths } from "@multica/core/paths";
import { Button } from "@multica/ui/components/ui/button";
import {
AlertDialog,
@@ -20,9 +32,16 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "../../common/actor-avatar";
+import { AppLink } from "../../navigation";
+import { availabilityConfig, taskStateConfig } from "../../agents/presence";
import { formatLastSeen } from "../utils";
-import { StatusBadge, InfoField } from "./shared";
+import { HealthBadge } from "./shared";
import { ProviderLogo } from "./provider-logo";
import { UpdateSection } from "./update-section";
import { UsageSection } from "./usage-section";
@@ -49,6 +68,26 @@ function getLaunchedBy(metadata: Record<string, unknown>): string | null {
return null;
}
+function shortDaemonId(id: string | null): string | null {
+ if (!id) return null;
+ if (id.length <= 10) return id;
+ return `${id.slice(0, 6)}··${id.slice(-2)}`;
+}
+
+// 30s tick keeps derived runtime health honest as time-based windows
+// (recently_lost → offline → about_to_gc) cross thresholds without any new
+// query data arriving. Agent presence has no time windows anymore, so it
+// doesn't need this — but useWorkspacePresenceMap is the dependency we
+// already mounted on this page, and that's wired to query data, not `now`.
+function useNowTick(intervalMs = 30_000): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), intervalMs);
+ return () => clearInterval(id);
+ }, [intervalMs]);
+ return now;
+}
+
export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
const cliVersion =
runtime.runtime_mode === "local" ? getCliVersion(runtime.metadata) : null;
@@ -57,17 +96,20 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
const user = useAuthStore((s) => s.user);
const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
const deleteMutation = useDeleteRuntime(wsId);
+ const now = useNowTick();
const [deleteOpen, setDeleteOpen] = useState(false);
- // Resolve owner info
+ const health = deriveRuntimeHealth(runtime, now);
const ownerMember = runtime.owner_id
? members.find((m) => m.user_id === runtime.owner_id) ?? null
: null;
- // Permission check for delete
const currentMember = user
? members.find((m) => m.user_id === user.id)
: null;
@@ -77,6 +119,8 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
const isRuntimeOwner = user && runtime.owner_id === user.id;
const canDelete = isAdmin || isRuntimeOwner;
+ const servingAgents = agents.filter((a) => a.runtime_id === runtime.id);
+
const handleDelete = () => {
deleteMutation.mutate(runtime.id, {
onSuccess: () => {
@@ -89,112 +133,88 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
});
};
+ const daemonShort = shortDaemonId(runtime.daemon_id);
+ const lastSeen = formatLastSeen(runtime.last_seen_at);
+
return (
<div className="flex h-full flex-col">
- {/* Header */}
- <div className="flex h-12 shrink-0 items-center justify-between border-b px-4">
- <div className="flex min-w-0 items-center gap-2">
- <div className="flex h-7 w-7 shrink-0 items-center justify-center">
- <ProviderLogo provider={runtime.provider} className="h-5 w-5" />
- </div>
- <div className="min-w-0">
- <h2 className="text-sm font-semibold truncate">{runtime.name}</h2>
- </div>
- </div>
- <div className="flex items-center gap-2">
- <StatusBadge status={runtime.status} />
+ {/* Topbar — back link + breadcrumb + right-side actions. Mirrors the
+ skill-detail-page topbar so users build one mental model for
+ "go back to the index" across the dashboard. */}
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-3">
+ <Button
+ variant="ghost"
+ size="xs"
+ render={<AppLink href={paths.runtimes()} />}
+ >
+ <ArrowLeft className="h-3 w-3" />
+ All runtimes
+ </Button>
+ <ChevronRight className="h-3 w-3 text-muted-foreground" />
+ <span className="truncate font-mono text-xs text-foreground">
+ {runtime.name}
+ </span>
+ <div className="ml-auto flex items-center gap-2">
+ {!canDelete && (
+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
+ <Lock className="h-3 w-3" />
+ Read-only
+ </span>
+ )}
{canDelete && (
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7 text-muted-foreground hover:text-destructive"
- onClick={() => setDeleteOpen(true)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setDeleteOpen(true)}
+ className="text-muted-foreground hover:text-destructive"
+ aria-label="Delete runtime"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ }
+ />
+ <TooltipContent>Delete runtime</TooltipContent>
+ </Tooltip>
)}
</div>
</div>
- {/* Content */}
- <div className="flex-1 overflow-y-auto p-6 space-y-6">
- {/* Info grid */}
- <div className="grid grid-cols-2 gap-4">
- <InfoField label="Runtime Mode" value={runtime.runtime_mode} />
- <InfoField label="Provider" value={runtime.provider} />
- <InfoField label="Status" value={runtime.status} />
- <InfoField
- label="Last Seen"
- value={formatLastSeen(runtime.last_seen_at)}
- />
- {ownerMember && (
- <div>
- <div className="text-xs text-muted-foreground mb-1">Owner</div>
- <div className="flex items-center gap-2">
- <ActorAvatar
- actorType="member"
- actorId={ownerMember.user_id}
- size={20}
- />
- <span className="text-sm">{ownerMember.name}</span>
- </div>
- </div>
- )}
- {runtime.device_info && (
- <InfoField label="Device" value={runtime.device_info} />
- )}
- {runtime.daemon_id && (
- <InfoField label="Daemon ID" value={runtime.daemon_id} mono />
- )}
- </div>
-
- {/* CLI Version & Update */}
- {runtime.runtime_mode === "local" && (
- <div>
- <h3 className="text-xs font-medium text-muted-foreground mb-3">
- CLI Version
- </h3>
- <UpdateSection
- runtimeId={runtime.id}
- currentVersion={cliVersion}
- isOnline={runtime.status === "online"}
- launchedBy={launchedBy}
+ {/* Body — single scroll container that owns the Hero card AND the
+ analytic blocks below. Putting Hero inside the scroll (instead of
+ pinning it under the topbar) means the scroll bar starts at the
+ page boundary rather than mid-content; the topbar stays sticky on
+ its own because it's navigation, not data. */}
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ <div className="grid grid-cols-1 gap-4 p-6 lg:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="min-w-0 space-y-5">
+ <HeroCard
+ runtime={runtime}
+ health={health}
+ lastSeen={lastSeen}
+ ownerMember={ownerMember}
+ cliVersion={cliVersion}
+ daemonShort={daemonShort}
/>
+ <UsageSection runtimeId={runtime.id} />
</div>
- )}
- {/* Usage */}
- <div>
- <h3 className="text-xs font-medium text-muted-foreground mb-3">
- Token Usage
- </h3>
- <UsageSection runtimeId={runtime.id} />
- </div>
-
- {/* Metadata */}
- {runtime.metadata && Object.keys(runtime.metadata).length > 0 && (
- <div>
- <h3 className="text-xs font-medium text-muted-foreground mb-2">
- Metadata
- </h3>
- <div className="rounded-lg border bg-muted/30 p-3">
- <pre className="text-xs font-mono whitespace-pre-wrap break-all">
- {JSON.stringify(runtime.metadata, null, 2)}
- </pre>
- </div>
+ {/* Right rail: serving agents + diagnostics */}
+ <div className="space-y-4">
+ <ServingAgentsCard
+ agents={servingAgents}
+ presenceMap={presenceMap}
+ />
+ <DiagnosticsCard
+ runtime={runtime}
+ cliVersion={cliVersion}
+ launchedBy={launchedBy}
+ canDelete={!!canDelete}
+ onDelete={() => setDeleteOpen(true)}
+ />
</div>
- )}
-
- {/* Timestamps */}
- <div className="grid grid-cols-2 gap-4 border-t pt-4">
- <InfoField
- label="Created"
- value={new Date(runtime.created_at).toLocaleString()}
- />
- <InfoField
- label="Updated"
- value={new Date(runtime.updated_at).toLocaleString()}
- />
</div>
</div>
@@ -222,3 +242,280 @@ export function RuntimeDetail({ runtime }: { runtime: AgentRuntime }) {
</div>
);
}
+
+// `device_info` arrives as a single composite string the daemon assembles
+// (e.g. "host.local · 2.1.121 (Claude Code)"). Splitting on the first
+// " · " gives us a hostname half + a runtime-version half so each can be
+// labelled separately in the Hero card. Older runtimes that report just a
+// hostname still work — `runtime` is undefined in that case.
+function parseDeviceInfo(raw: string): { hostname: string; runtime?: string } {
+ const idx = raw.indexOf(" · ");
+ if (idx < 0) return { hostname: raw };
+ return {
+ hostname: raw.slice(0, idx),
+ runtime: raw.slice(idx + 3),
+ };
+}
+
+function HeroCard({
+ runtime,
+ health,
+ lastSeen,
+ ownerMember,
+ cliVersion,
+ daemonShort,
+}: {
+ runtime: AgentRuntime;
+ health: ReturnType<typeof deriveRuntimeHealth>;
+ lastSeen: string;
+ ownerMember: MemberWithUser | null;
+ cliVersion: string | null;
+ daemonShort: string | null;
+}) {
+ const [showDetails, setShowDetails] = useState(false);
+ const device = runtime.device_info ? parseDeviceInfo(runtime.device_info) : null;
+ const hasTechDetails = !!cliVersion || !!daemonShort;
+
+ return (
+ <div className="rounded-lg border bg-card">
+ {/* Identity row — provider logo, name, status badge, last seen. */}
+ <div className="flex items-start gap-3 border-b p-4">
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-card">
+ <ProviderLogo provider={runtime.provider} className="h-5 w-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <h2 className="truncate text-base font-semibold tracking-tight">
+ {runtime.name}
+ </h2>
+ <HealthBadge health={health} />
+ <span className="text-xs text-muted-foreground">
+ last seen {lastSeen}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* User-visible facts — Owner / Device / Runtime, each labelled.
+ Replaces the older dense `·`-separated meta strip that mixed
+ everything (including dev-only IDs) at the same visual weight. */}
+ <dl className="grid grid-cols-1 divide-y sm:grid-cols-3 sm:divide-x sm:divide-y-0">
+ <Fact label="Owner">
+ {ownerMember ? (
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ <ActorAvatar
+ actorType="member"
+ actorId={ownerMember.user_id}
+ size={18}
+ enableHoverCard
+ />
+ <span className="cursor-pointer truncate text-sm">{ownerMember.name}</span>
+ </span>
+ ) : (
+ <span className="text-sm text-muted-foreground">—</span>
+ )}
+ </Fact>
+ <Fact label="Device">
+ {device?.hostname ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="block truncate font-mono text-xs">
+ {device.hostname}
+ </span>
+ }
+ />
+ <TooltipContent>{device.hostname}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="text-sm text-muted-foreground">—</span>
+ )}
+ </Fact>
+ <Fact label="Runtime">
+ <span className="block truncate text-sm">
+ {device?.runtime ?? (
+ <span className="capitalize">{runtime.provider}</span>
+ )}
+ </span>
+ </Fact>
+ </dl>
+
+ {/* Diagnostic IDs — multica CLI git hash + truncated daemon UUID.
+ Only useful when filing an issue or reading logs; folded by
+ default so they don't compete with the user-visible facts above. */}
+ {hasTechDetails && (
+ <div className="border-t">
+ <button
+ type="button"
+ onClick={() => setShowDetails((v) => !v)}
+ className="flex w-full items-center gap-1 px-4 py-2 text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ChevronRight
+ className={`h-3 w-3 transition-transform ${
+ showDetails ? "rotate-90" : ""
+ }`}
+ />
+ Technical details
+ </button>
+ {showDetails && (
+ <dl className="grid grid-cols-1 gap-y-2 border-t bg-muted/30 px-4 py-3 sm:grid-cols-2">
+ {cliVersion && (
+ <Fact label="Daemon CLI" mono compact>
+ {cliVersion}
+ </Fact>
+ )}
+ {daemonShort && (
+ <Fact label="Daemon ID" mono compact>
+ {daemonShort}
+ </Fact>
+ )}
+ </dl>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Fact({
+ label,
+ children,
+ mono,
+ compact,
+}: {
+ label: string;
+ children: React.ReactNode;
+ mono?: boolean;
+ compact?: boolean;
+}) {
+ return (
+ <div className={`min-w-0 ${compact ? "" : "px-4 py-3"}`}>
+ <dt className="text-[11px] uppercase tracking-wider text-muted-foreground">
+ {label}
+ </dt>
+ <dd className={`mt-1 ${mono ? "font-mono text-xs" : ""}`}>{children}</dd>
+ </div>
+ );
+}
+
+function ServingAgentsCard({
+ agents,
+ presenceMap,
+}: {
+ agents: Agent[];
+ presenceMap: Map<string, AgentPresenceDetail>;
+}) {
+ return (
+ <div className="rounded-lg border">
+ <div className="flex items-center justify-between border-b px-4 py-2.5">
+ <span className="text-xs font-semibold">Serving</span>
+ <span className="text-xs text-muted-foreground">
+ {agents.length} agent{agents.length === 1 ? "" : "s"}
+ </span>
+ </div>
+ {agents.length === 0 ? (
+ <div className="flex flex-col items-center px-4 py-6 text-center">
+ <Cpu className="h-5 w-5 text-muted-foreground/40" />
+ <p className="mt-2 text-xs text-muted-foreground">
+ No agents are bound to this runtime yet.
+ </p>
+ </div>
+ ) : (
+ <div className="divide-y">
+ {agents.map((agent) => {
+ const detail = presenceMap.get(agent.id);
+ const av = detail
+ ? availabilityConfig[detail.availability]
+ : availabilityConfig.offline;
+ const ts = detail ? taskStateConfig[detail.lastTask] : null;
+ const running = detail?.runningCount ?? 0;
+ const queued = detail?.queuedCount ?? 0;
+ return (
+ <div
+ key={agent.id}
+ className="flex items-center gap-2 px-4 py-2"
+ >
+ <ActorAvatar actorType="agent" actorId={agent.id} size={20} enableHoverCard showStatusDot />
+ <div className="min-w-0 flex-1">
+ <div className="cursor-pointer truncate text-xs font-medium">
+ {agent.name}
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs">
+ <span className="inline-flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} />
+ <span className={av.textClass}>{av.label}</span>
+ </span>
+ {ts && detail && detail.lastTask !== "idle" && (
+ <span className={`inline-flex items-center gap-1 ${ts.textClass}`}>
+ <span className="text-muted-foreground">·</span>
+ <ts.icon className="h-3 w-3" />
+ {ts.label}
+ {running > 0 && (
+ <span className="text-muted-foreground">· {running} running</span>
+ )}
+ {queued > 0 && (
+ <span className="text-muted-foreground">· {queued} queued</span>
+ )}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function DiagnosticsCard({
+ runtime,
+ cliVersion,
+ launchedBy,
+ canDelete,
+ onDelete,
+}: {
+ runtime: AgentRuntime;
+ cliVersion: string | null;
+ launchedBy: string | null;
+ canDelete: boolean;
+ onDelete: () => void;
+}) {
+ const isLocal = runtime.runtime_mode === "local";
+ return (
+ <div className="rounded-lg border">
+ <div className="border-b px-4 py-2.5">
+ <span className="text-xs font-semibold">Diagnostics</span>
+ </div>
+ <div className="space-y-3 p-4">
+ {isLocal && (
+ <div>
+ <div className="mb-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
+ CLI
+ </div>
+ <UpdateSection
+ runtimeId={runtime.id}
+ currentVersion={cliVersion}
+ isOnline={runtime.status === "online"}
+ launchedBy={launchedBy}
+ />
+ </div>
+ )}
+ {canDelete && (
+ <div className={isLocal ? "border-t pt-3" : ""}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 w-full justify-start gap-2 text-destructive hover:bg-destructive/10 hover:text-destructive"
+ onClick={onDelete}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ Delete runtime
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index e095c39379..ee6237baca 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -1,256 +1,672 @@
-import { Server, ArrowUpCircle, ChevronDown, Check, Loader2 } from "lucide-react";
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import {
+ ArrowUpCircle,
+ MoreHorizontal,
+ Trash2,
+ Cloud,
+ Monitor,
+} from "lucide-react";
+import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
-import type { AgentRuntime, MemberWithUser } from "@multica/core/types";
+import type { AgentRuntime, AgentTask, Agent, MemberWithUser } from "@multica/core/types";
+import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
-import { memberListOptions } from "@multica/core/workspace/queries";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import {
+ deriveRuntimeHealth,
+ runtimeUsageOptions,
+ latestCliVersionOptions,
+} from "@multica/core/runtimes";
+import { useDeleteRuntime } from "@multica/core/runtimes/mutations";
+import { agentTaskSnapshotOptions } from "@multica/core/agents";
+import { paths, useWorkspaceSlug } from "@multica/core/paths";
+import { AppLink } from "../../navigation";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuSeparator,
} from "@multica/ui/components/ui/dropdown-menu";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { PageHeader } from "../../layout/page-header";
-import { ProviderLogo } from "./provider-logo";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import { HealthIcon, healthLabel } from "./shared";
+import {
+ formatLastSeen,
+ computeCostInWindow,
+ pctChange,
+ isVersionNewer,
+} from "../utils";
+
+// ---------------------------------------------------------------------------
+// Per-runtime workload snapshot — agent IDs serving this runtime (drives the
+// avatar stack; .length doubles as the agent count) plus task counts split
+// by status. Built once per render off the workspace-wide
+// agents / agent-task-snapshot caches; filtered locally — zero extra requests.
+// ---------------------------------------------------------------------------
+
+interface RuntimeWorkload {
+ agentIds: string[];
+ runningCount: number;
+ queuedCount: number;
+}
+
+const EMPTY_WORKLOAD: RuntimeWorkload = {
+ agentIds: [],
+ runningCount: 0,
+ queuedCount: 0,
+};
+
+function buildWorkloadIndex(
+ agents: Agent[],
+ tasks: AgentTask[],
+): Map<string, RuntimeWorkload> {
+ const result = new Map<string, RuntimeWorkload>();
+ const agentToRuntime = new Map<string, string>();
+
+ for (const a of agents) {
+ if (!a.runtime_id) continue;
+ agentToRuntime.set(a.id, a.runtime_id);
+ const entry =
+ result.get(a.runtime_id) ?? {
+ agentIds: [],
+ runningCount: 0,
+ queuedCount: 0,
+ };
+ entry.agentIds.push(a.id);
+ result.set(a.runtime_id, entry);
+ }
+ for (const t of tasks) {
+ const rid = agentToRuntime.get(t.agent_id);
+ if (!rid) continue;
+ const entry = result.get(rid);
+ if (!entry) continue;
+ if (t.status === "running") entry.runningCount += 1;
+ else if (t.status === "queued" || t.status === "dispatched")
+ entry.queuedCount += 1;
+ }
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// Grid template. Two variants because the Owner column only earns its keep
+// in workspaces with multiple runtime owners — single-owner workspaces just
+// see an entire column of identical avatars, which is noise. We pick at
+// list-mount time and pass the chosen template down so the header and every
+// row stay byte-identically aligned.
+//
+// Leading-visual columns are dedicated tracks so header labels sit on the
+// same x as the row text, with no per-cell padding hacks. Same pattern as
+// Agents (avatar) and Skills (source icon).
+//
+// Width choices (left → right):
+// IconBox: 2rem — 32px Cloud / Monitor mode badge
+// Runtime: minmax(0,1fr) — primary, fills remainder, truncates first
+// HealthIcon: 0.875rem — 12px wifi-style icon
+// Health: minmax(0,1fr) — text label, can shrink + truncate at
+// narrow widths so it never overlaps the
+// Runtime column. ("Recently lost · 2m
+// 14s ago" is the worst case; the long
+// suffix truncates first.)
+// Owner: 2rem — single 18px avatar (multi-owner only)
+// Agents: 6rem — 3 avatars overlapped + "+N" pill
+// Active: 5rem — "2 +5q" worst case, right-aligned
+// Cost: 7rem — "$879.00" + "↑18%" stacked, right-aligned
+// CLI: 8rem — "Desktop · v0.2.17" worst case
+// Kebab: 2.5rem — icon button
+//
+// Switched Health from a fixed 9.5rem to minmax(0,1fr) so it competes
+// fairly with Runtime under width pressure. The previous fixed-width
+// reservation guaranteed the worst-case copy fit, but at intermediate
+// viewports the Runtime column was squeezed below its content width and
+// overflowed visually.
+// ---------------------------------------------------------------------------
+
+const GRID_WITH_OWNER =
+ "grid items-center gap-4 " +
+ "grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_2rem_2.5rem] " +
+ "md:grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_2rem_6rem_5rem_7rem_2.5rem] " +
+ "lg:grid-cols-[2rem_minmax(0,1.2fr)_0.875rem_minmax(0,1fr)_2rem_6rem_5rem_7rem_8rem_2.5rem]";
+
+const GRID_NO_OWNER =
+ "grid items-center gap-4 " +
+ "grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_2.5rem] " +
+ "md:grid-cols-[2rem_minmax(0,1fr)_0.875rem_minmax(0,1fr)_6rem_5rem_7rem_2.5rem] " +
+ "lg:grid-cols-[2rem_minmax(0,1.2fr)_0.875rem_minmax(0,1fr)_6rem_5rem_7rem_8rem_2.5rem]";
+
+export function RuntimeList({
+ runtimes,
+ updatableIds,
+ now,
+}: {
+ runtimes: AgentRuntime[];
+ // Kept on the API surface for callers (currently a noop here — the CLI
+ // column re-derives from `metadata.cli_version` + the GitHub-release query
+ // so per-row state is co-located. Removing it would break the page-level
+ // wrapper that still computes the set; left in place to avoid scope creep.)
+ updatableIds?: Set<string>;
+ now: number;
+}) {
+ // Kept to avoid an unused-prop lint; the data path is now per-row.
+ void updatableIds;
+
+ const wsId = useWorkspaceId();
+ const slug = useWorkspaceSlug();
+ const user = useAuthStore((s) => s.user);
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const currentMember = user
+ ? members.find((m) => m.user_id === user.id)
+ : null;
+ const isAdmin = currentMember
+ ? currentMember.role === "owner" || currentMember.role === "admin"
+ : false;
+ // Snapshot also includes each agent's latest terminal task; the workload
+ // index iterates by status and only counts active ones, so terminal rows
+ // are silently ignored.
+ const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));
+ const { data: latestCliVersion = null } = useQuery(latestCliVersionOptions());
+
+ const workloadIndex = useMemo(
+ () => buildWorkloadIndex(agents, snapshot),
+ [agents, snapshot],
+ );
+ const memberById = useMemo(() => {
+ const map = new Map<string, MemberWithUser>();
+ for (const m of members) map.set(m.user_id, m);
+ return map;
+ }, [members]);
+
+ // Owner column only earns its space when the page actually has multiple
+ // distinct owners; otherwise it's a column of identical avatars.
+ const showOwner = useMemo(() => {
+ const owners = new Set<string>();
+ for (const r of runtimes) {
+ if (r.owner_id) owners.add(r.owner_id);
+ }
+ return owners.size > 1;
+ }, [runtimes]);
+
+ const gridClass = showOwner ? GRID_WITH_OWNER : GRID_NO_OWNER;
-type RuntimeFilter = "mine" | "all";
+ const scrollRef = useRef<HTMLDivElement | null>(null);
+ const fadeStyle = useScrollFade(scrollRef);
-function RuntimeListItem({
+ return (
+ <div
+ ref={scrollRef}
+ style={fadeStyle}
+ className="flex-1 min-h-0 overflow-y-auto"
+ >
+ <div
+ role="row"
+ className={`${gridClass} sticky top-0 z-10 border-b bg-muted/30 px-4 py-2 text-xs font-medium uppercase tracking-wider text-muted-foreground backdrop-blur`}
+ >
+ {/* Icon-box leading slot — empty in header so "Runtime" aligns with
+ the row's name text rather than the mode-badge edge. */}
+ <span aria-hidden />
+ <span>Runtime</span>
+ {/* Health-dot leading slot — empty in header so "Health" aligns
+ with the row's status text rather than the dot edge. */}
+ <span aria-hidden />
+ <span>Health</span>
+ {showOwner && <span className="hidden md:block">Owner</span>}
+ <span className="hidden md:block">Agents</span>
+ <span className="hidden text-right md:block">Active</span>
+ <span className="hidden text-right md:block">Cost · 7d</span>
+ <span className="hidden lg:block">CLI</span>
+ <span aria-label="Actions" />
+ </div>
+ {runtimes.map((runtime) => (
+ <RuntimeRow
+ key={runtime.id}
+ runtime={runtime}
+ now={now}
+ gridClass={gridClass}
+ showOwner={showOwner}
+ workload={workloadIndex.get(runtime.id) ?? EMPTY_WORKLOAD}
+ ownerMember={
+ runtime.owner_id ? memberById.get(runtime.owner_id) ?? null : null
+ }
+ latestCliVersion={latestCliVersion}
+ href={slug ? paths.workspace(slug).runtimeDetail(runtime.id) : "#"}
+ wsId={wsId}
+ canDelete={
+ isAdmin || (!!user && runtime.owner_id === user.id)
+ }
+ />
+ ))}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Backend formats `runtime.name` as `"<base> (<hostname>)"` (e.g.
+// "Claude (qingnaiyuandebijibendiannao-8.local)"). Every runtime on the same
+// machine repeats the same hostname suffix, so it carries near-zero scan
+// value once the eye has seen it on the first row — yet it dominates the
+// column width by character count. Split it so the base name stays
+// emphasised and the hostname renders muted + truncates first when the cell
+// is tight. Falls back to the raw name when the format doesn't match.
+// ---------------------------------------------------------------------------
+
+function splitRuntimeName(name: string): {
+ base: string;
+ hostname: string | null;
+} {
+ const m = name.match(/^(.+?)\s+\(([^)]+)\)$/);
+ if (!m || !m[1] || !m[2]) return { base: name, hostname: null };
+ return { base: m[1], hostname: m[2] };
+}
+
+function RuntimeRow({
runtime,
- isSelected,
+ now,
+ gridClass,
+ showOwner,
+ workload,
ownerMember,
- hasUpdate,
- onClick,
+ latestCliVersion,
+ href,
+ wsId,
+ canDelete,
}: {
runtime: AgentRuntime;
- isSelected: boolean;
+ now: number;
+ gridClass: string;
+ showOwner: boolean;
+ workload: RuntimeWorkload;
ownerMember: MemberWithUser | null;
- hasUpdate: boolean;
- onClick: () => void;
+ latestCliVersion: string | null;
+ href: string;
+ wsId: string;
+ canDelete: boolean;
}) {
+ const health = deriveRuntimeHealth(runtime, now);
+ const lastSeen = formatLastSeen(runtime.last_seen_at);
+ const { base: baseName, hostname } = splitRuntimeName(runtime.name);
+ const isOffline = health === "offline" || health === "about_to_gc";
+
+ // Per-row cost fetch reuses the SAME cache key as the runtime-detail page
+ // (`runtimeUsageOptions(rid, 180)`). On cold load that's N parallel
+ // requests, but every one of them populates the same cache the detail
+ // page reads — so clicking a row to drill in is instant.
+ const { data: usage = [] } = useQuery(runtimeUsageOptions(runtime.id, 180));
+
+ const cost7d = useMemo(() => computeCostInWindow(usage, 7), [usage]);
+ const costPrev7d = useMemo(() => computeCostInWindow(usage, 7, 7), [usage]);
+ const costDelta = pctChange(cost7d, costPrev7d);
+
return (
- <button
- onClick={onClick}
- className={`flex w-full items-center gap-3 px-4 py-3 text-left transition-colors ${
- isSelected ? "bg-accent" : "hover:bg-accent/50"
- }`}
+ <AppLink
+ href={href}
+ className={`${gridClass} group border-b px-4 py-3 text-sm transition-colors last:border-b-0 hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none`}
>
- <div className="flex h-8 w-8 shrink-0 items-center justify-center">
- <ProviderLogo provider={runtime.provider} className="h-5 w-5" />
+ {/* MODE BADGE — leading column so the "Runtime" header aligns with the
+ name text rather than the badge edge. */}
+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-card">
+ {runtime.runtime_mode === "cloud" ? (
+ <Cloud className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <Monitor className="h-4 w-4 text-muted-foreground" />
+ )}
</div>
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">{runtime.name}</div>
- <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
+
+ {/* RUNTIME — base name + (hostname). Both can truncate at narrow
+ widths so the cell never overflows into the adjacent Health
+ column. The base name takes precedence (truncate later) by
+ virtue of being the first child; the hostname (more disposable)
+ shrinks first. Provider lives in the right-side CLI column. */}
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="min-w-0 truncate text-sm font-medium">{baseName}</span>
+ {hostname && (
+ <span className="min-w-0 truncate text-xs text-muted-foreground/70">
+ ({hostname})
+ </span>
+ )}
+ </div>
+
+ {/* HEALTH icon — wifi-style indicator carries both shape (Wifi / WifiOff)
+ and colour (success / warning / muted / destructive) for the four
+ health buckets. Leading column for the same alignment reason as
+ the icon-box on the left. */}
+ <HealthIcon health={health} />
+
+ {/* HEALTH label — last_seen folded in only when it carries information
+ (everything except the always-"Just now" online case). */}
+ <span className="min-w-0 truncate text-sm">
+ {healthLabel(health)}
+ {health !== "online" && runtime.last_seen_at && (
+ <span className="text-muted-foreground"> · {lastSeen}</span>
+ )}
+ </span>
+
+ {/* OWNER — small avatar only; name lives in the hover card. Conditional
+ on the workspace having more than one distinct owner. */}
+ {showOwner && (
+ <div className="hidden md:flex">
{ownerMember ? (
- <>
- <ActorAvatar
- actorType="member"
- actorId={ownerMember.user_id}
- size={14}
- />
- <span className="truncate">{ownerMember.name}</span>
- </>
+ <ActorAvatar
+ actorType="member"
+ actorId={ownerMember.user_id}
+ size={18}
+ />
) : (
- <span className="truncate">{runtime.runtime_mode}</span>
+ <span className="text-xs text-muted-foreground/50">—</span>
)}
</div>
+ )}
+
+ {/* AGENTS — avatar stack (3 + "+N"). */}
+ <div className="hidden md:block">
+ <AgentStack agentIds={workload.agentIds} />
</div>
- <div className="flex items-center gap-1.5 shrink-0">
- {hasUpdate && (
- <span title="Update available">
- <ArrowUpCircle className="h-3.5 w-3.5 text-info" />
- </span>
- )}
- <div
- className={`h-2 w-2 rounded-full ${
- runtime.status === "online" ? "bg-success" : "bg-muted-foreground/40"
- }`}
+
+ {/* ACTIVE — running count is the headline (brand colour) when active;
+ queued count piggy-backs as a smaller "+Nq" suffix when non-zero.
+ Offline runtimes show "—" instead of "0" because zero on an offline
+ row is a tautology, not information. */}
+ <div className="hidden text-right md:block">
+ <ActiveCell
+ running={workload.runningCount}
+ queued={workload.queuedCount}
+ offline={isOffline}
/>
</div>
- </button>
+
+ {/* COST · 7D — main number + trend delta stacked. The 7d window is
+ fixed (vs the period selector on the detail page) so the column
+ stays comparable across rows. */}
+ <div className="hidden text-right md:block">
+ <CostCell cost={cost7d} delta={costDelta} hasData={usage.length > 0} />
+ </div>
+
+ {/* CLI — source badge + version + ↑ marker if behind. Pure status,
+ no clickable upgrade button — the actual upgrade lives on the
+ detail page where polling/error state has room to breathe. */}
+ <div className="hidden lg:block">
+ <CliCell runtime={runtime} latestCliVersion={latestCliVersion} />
+ </div>
+
+ {/* ⋯ menu */}
+ <div className="flex justify-end">
+ <RowMenu runtime={runtime} wsId={wsId} canDelete={canDelete} />
+ </div>
+ </AppLink>
);
}
-export function RuntimeList({
- runtimes,
- selectedId,
- onSelect,
- filter,
- onFilterChange,
- ownerFilter,
- onOwnerFilterChange,
- updatableIds,
- bootstrapping,
+function ActiveCell({
+ running,
+ queued,
+ offline,
}: {
- runtimes: AgentRuntime[];
- selectedId: string;
- onSelect: (id: string) => void;
- filter: RuntimeFilter;
- onFilterChange: (filter: RuntimeFilter) => void;
- ownerFilter: string | null;
- onOwnerFilterChange: (ownerId: string | null) => void;
- updatableIds?: Set<string>;
- /**
- * When true and no runtimes are visible, the empty state renders a
- * "starting" indicator instead of the static "register a runtime"
- * hint. The desktop shell sets this while its bundled daemon is
- * still booting / registering — without the hint, users see a
- * misleading "no runtimes" message during the few seconds between
- * page load and daemon registration. Web leaves this undefined.
- */
- bootstrapping?: boolean;
+ running: number;
+ queued: number;
+ offline: boolean;
}) {
- const wsId = useWorkspaceId();
- const { data: members = [] } = useQuery(memberListOptions(wsId));
+ if (offline) {
+ return <span className="text-xs text-muted-foreground/50">—</span>;
+ }
+ if (running === 0 && queued === 0) {
+ return <span className="text-sm text-muted-foreground">0</span>;
+ }
+ return (
+ <div className="flex items-center justify-end gap-1.5 text-sm tabular-nums">
+ {running > 0 ? (
+ <>
+ <span className="h-1.5 w-1.5 rounded-full bg-brand" />
+ <span className="text-brand">{running}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">0</span>
+ )}
+ {queued > 0 && (
+ <span className="text-xs text-warning">+{queued}q</span>
+ )}
+ </div>
+ );
+}
- const getOwnerMember = (ownerId: string | null) => {
- if (!ownerId) return null;
- return members.find((m) => m.user_id === ownerId) ?? null;
- };
+function CostCell({
+ cost,
+ delta,
+ hasData,
+}: {
+ cost: number;
+ delta: number | null;
+ hasData: boolean;
+}) {
+ if (!hasData) {
+ return <span className="text-xs text-muted-foreground/50">—</span>;
+ }
+ const fmt = cost >= 100 ? `$${cost.toFixed(0)}` : `$${cost.toFixed(2)}`;
+ // Tone choice: rising cost is a "watch out" signal (warning), falling is
+ // good news (success), no comparable prior is silent.
+ const deltaTone =
+ delta == null
+ ? "text-muted-foreground"
+ : delta > 0
+ ? "text-warning"
+ : delta < 0
+ ? "text-success"
+ : "text-muted-foreground";
+ const deltaLabel =
+ delta == null
+ ? null
+ : delta === 0
+ ? "flat"
+ : `${delta > 0 ? "↑" : "↓"}${Math.abs(delta)}%`;
+ return (
+ <div className="flex flex-col items-end leading-tight">
+ <span className="text-sm font-medium tabular-nums">{fmt}</span>
+ {deltaLabel && (
+ <span className={`text-[11px] tabular-nums ${deltaTone}`}>
+ {deltaLabel}
+ </span>
+ )}
+ </div>
+ );
+}
- // Get unique owners from runtimes for filter dropdown
- const uniqueOwners = filter === "all"
- ? Array.from(new Set(runtimes.map((r) => r.owner_id).filter(Boolean) as string[]))
- .map((id) => members.find((m) => m.user_id === id))
- .filter(Boolean) as MemberWithUser[]
- : [];
-
- // Count runtimes per owner
- const ownerCounts = new Map<string, number>();
- for (const r of runtimes) {
- if (r.owner_id) ownerCounts.set(r.owner_id, (ownerCounts.get(r.owner_id) ?? 0) + 1);
+function CliCell({
+ runtime,
+ latestCliVersion,
+}: {
+ runtime: AgentRuntime;
+ latestCliVersion: string | null;
+}) {
+ if (runtime.runtime_mode === "cloud") {
+ return <span className="text-xs text-muted-foreground/50">—</span>;
}
+ const meta = runtime.metadata as Record<string, unknown> | null;
+ const cliVersion =
+ meta && typeof meta.cli_version === "string" ? meta.cli_version : null;
+ const launchedBy =
+ meta && typeof meta.launched_by === "string" ? meta.launched_by : null;
+ const isManaged = launchedBy === "desktop";
- // Apply client-side owner filter when in "all" mode
- const filteredRuntimes = filter === "all" && ownerFilter
- ? runtimes.filter((r) => r.owner_id === ownerFilter)
- : runtimes;
+ if (!cliVersion) {
+ return <span className="text-xs text-muted-foreground/50">—</span>;
+ }
- const selectedOwner = ownerFilter ? getOwnerMember(ownerFilter) : null;
+ // Desktop-managed daemons can never self-update from this page (the
+ // Electron app ships and replaces the binary), so the "↑" upgrade marker
+ // would be a lie — suppress it regardless of version comparison.
+ const hasUpdate =
+ !isManaged &&
+ !!latestCliVersion &&
+ isVersionNewer(latestCliVersion, cliVersion);
return (
- <div className="overflow-y-auto h-full border-r">
- <PageHeader className="justify-between">
- <h1 className="text-sm font-semibold">Runtimes</h1>
- <span className="text-xs text-muted-foreground">
- {filteredRuntimes.filter((r) => r.status === "online").length}/
- {filteredRuntimes.length} online
+ <div className="flex min-w-0 items-center gap-1 text-xs">
+ {isManaged && (
+ <span className="shrink-0 rounded-sm bg-muted px-1 py-0.5 text-[10px] font-medium text-muted-foreground">
+ Desktop
</span>
- </PageHeader>
-
- {/* Filter bar */}
- <div className="flex items-center justify-between border-b px-4 py-2">
- {/* Scope toggle */}
- <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">
- <button
- onClick={() => { onFilterChange("mine"); onOwnerFilterChange(null); }}
- className={`rounded px-2.5 py-1 text-xs font-medium transition-colors ${
- filter === "mine"
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground"
- }`}
- >
- Mine
- </button>
- <button
- onClick={() => { onFilterChange("all"); onOwnerFilterChange(null); }}
- className={`rounded px-2.5 py-1 text-xs font-medium transition-colors ${
- filter === "all"
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground"
- }`}
- >
- All
- </button>
- </div>
-
- {/* Owner dropdown (only in All mode with multiple owners) */}
- {filter === "all" && uniqueOwners.length > 1 && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <button className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground hover:bg-accent" />
- }
- >
- {selectedOwner ? (
- <>
- <ActorAvatar actorType="member" actorId={selectedOwner.user_id} size={16} />
- <span className="max-w-20 truncate">{selectedOwner.name}</span>
- </>
- ) : (
- <span>Owner</span>
- )}
- <ChevronDown className="h-3 w-3 opacity-50" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-48">
- <DropdownMenuItem
- onClick={() => onOwnerFilterChange(null)}
- className="flex items-center justify-between"
- >
- <span className="text-xs">All owners</span>
- {!ownerFilter && <Check className="h-3.5 w-3.5 text-foreground" />}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- {uniqueOwners.map((m) => (
- <DropdownMenuItem
- key={m.user_id}
- onClick={() => onOwnerFilterChange(ownerFilter === m.user_id ? null : m.user_id)}
- className="flex items-center justify-between"
- >
- <div className="flex items-center gap-2 min-w-0">
- <ActorAvatar actorType="member" actorId={m.user_id} size={18} />
- <span className="text-xs truncate">{m.name}</span>
- <span className="text-xs text-muted-foreground">{ownerCounts.get(m.user_id) ?? 0}</span>
- </div>
- {ownerFilter === m.user_id && <Check className="h-3.5 w-3.5 shrink-0 text-foreground" />}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </div>
+ )}
+ <span
+ className={`min-w-0 truncate font-mono ${
+ hasUpdate ? "text-warning" : "text-muted-foreground"
+ }`}
+ >
+ {cliVersion}
+ </span>
+ {hasUpdate && latestCliVersion && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <ArrowUpCircle
+ className="h-3 w-3 shrink-0 text-warning"
+ aria-label="Update available"
+ />
+ }
+ />
+ <TooltipContent>
+ Update available: {latestCliVersion}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
- {filteredRuntimes.length === 0 ? (
- bootstrapping ? (
- <div className="flex flex-col items-center justify-center px-4 py-12">
- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground/60" />
- <p className="mt-3 text-sm text-muted-foreground">
- Starting local runtime…
- </p>
- <p className="mt-1 text-xs text-muted-foreground text-center">
- This usually takes a few seconds.
- </p>
- </div>
- ) : (
- <div className="flex flex-col items-center justify-center px-4 py-12">
- <Server className="h-8 w-8 text-muted-foreground/40" />
- <p className="mt-3 text-sm text-muted-foreground">
- {filter === "mine" ? "No runtimes owned by you" : ownerFilter ? "No runtimes for this owner" : "No runtimes registered"}
- </p>
- <p className="mt-1 text-xs text-muted-foreground text-center">
- Run{" "}
- <code className="rounded bg-muted px-1 py-0.5">
- multica daemon start
- </code>{" "}
- to register a local runtime.
- </p>
- </div>
- )
- ) : (
- <div className="divide-y">
- {filteredRuntimes.map((runtime) => (
- <RuntimeListItem
- key={runtime.id}
- runtime={runtime}
- isSelected={runtime.id === selectedId}
- ownerMember={getOwnerMember(runtime.owner_id)}
- hasUpdate={updatableIds?.has(runtime.id) ?? false}
- onClick={() => onSelect(runtime.id)}
- />
- ))}
- </div>
+// Stacks up to 3 agent avatars, then a "+N" pill if more bind to this
+// runtime. Each avatar uses the wrapping ActorAvatar so hover automatically
+// surfaces AgentProfileCard — same hover affordance Agents/Skills already
+// use, no per-row extra wiring.
+function AgentStack({ agentIds }: { agentIds: string[] }) {
+ if (agentIds.length === 0) {
+ return <span className="text-xs text-muted-foreground/50">—</span>;
+ }
+ const visible = agentIds.slice(0, 3);
+ const extra = agentIds.length - visible.length;
+ return (
+ <div className="flex items-center -space-x-1.5">
+ {visible.map((id) => (
+ <span
+ key={id}
+ className="inline-flex rounded-full ring-2 ring-background"
+ >
+ <ActorAvatar actorType="agent" actorId={id} size={22} enableHoverCard />
+ </span>
+ ))}
+ {extra > 0 && (
+ <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground ring-2 ring-background">
+ +{extra}
+ </span>
)}
</div>
);
}
+
+function RowMenu({
+ runtime,
+ wsId,
+ canDelete,
+}: {
+ runtime: AgentRuntime;
+ wsId: string;
+ canDelete: boolean;
+}) {
+ const deleteMutation = useDeleteRuntime(wsId);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+
+ if (!canDelete) {
+ // Keep the grid cell occupied so column alignment doesn't shift between
+ // rows the user can act on and rows they can't.
+ return <span aria-hidden />;
+ }
+
+ const handleDelete = () => {
+ deleteMutation.mutate(runtime.id, {
+ onSuccess: () => {
+ toast.success("Runtime deleted");
+ setDeleteOpen(false);
+ },
+ onError: (e) => {
+ toast.error(
+ e instanceof Error ? e.message : "Failed to delete runtime",
+ );
+ },
+ });
+ };
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Row actions"
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ />
+ }
+ >
+ <MoreHorizontal className="h-4 w-4 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-40"
+ // Prevent the row's anchor navigation from firing if a click on a
+ // menu item somehow bubbles back through the portal.
+ onClick={(e) => e.stopPropagation()}
+ >
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteOpen(true)}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <AlertDialog
+ open={deleteOpen}
+ onOpenChange={(v) => {
+ if (deleteMutation.isPending) return;
+ setDeleteOpen(v);
+ }}
+ >
+ <AlertDialogContent onClick={(e) => e.stopPropagation()}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete Runtime</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete &ldquo;{runtime.name}&rdquo;? This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={handleDelete}
+ disabled={deleteMutation.isPending}
+ >
+ {deleteMutation.isPending ? "Deleting..." : "Delete"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsx
index da948bd9b0..34bc25feb5 100644
--- a/packages/views/runtimes/components/runtimes-page.tsx
+++ b/packages/views/runtimes/components/runtimes-page.tsx
@@ -1,144 +1,514 @@
"use client";
-import React, { useState, useCallback } from "react";
-import { Server } from "lucide-react";
-import { useDefaultLayout } from "react-resizable-panels";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { Search, Server } from "lucide-react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
-} from "@multica/ui/components/ui/resizable";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { runtimeListOptions, runtimeKeys } from "@multica/core/runtimes/queries";
import { useUpdatableRuntimeIds } from "@multica/core/runtimes/hooks";
+import { deriveRuntimeHealth } from "@multica/core/runtimes";
import { useWSEvent } from "@multica/core/realtime";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { PageHeader } from "../../layout/page-header";
import { RuntimeList } from "./runtime-list";
-import { RuntimeDetail } from "./runtime-detail";
type RuntimeFilter = "mine" | "all";
+type HealthFilter = "all" | "online" | "recently_lost" | "offline" | "about_to_gc";
+
+const HEALTH_ORDER: HealthFilter[] = [
+ "all",
+ "online",
+ "recently_lost",
+ "offline",
+ "about_to_gc",
+];
+
+// Single source of truth for the 4-state chip visuals + tooltip copy.
+// Thresholds come from `deriveRuntimeHealth`: 45s heartbeat window (server
+// sweeper), 5 min "recently lost" cutoff, 6 day "about_to_gc" trigger,
+// 7 day hard GC. Wording leans on what the user should *do*, not the
+// internals of the sweeper — those live in the redesign doc.
+const HEALTH_CHIP: Record<
+ Exclude<HealthFilter, "all">,
+ { label: string; dot: string; description: string }
+> = {
+ online: {
+ label: "Online",
+ dot: "bg-success",
+ description: "Heartbeat received in the last 45s. Ready to dispatch tasks.",
+ },
+ recently_lost: {
+ label: "Recently lost",
+ dot: "bg-warning",
+ description: "Lost contact under 5 minutes ago — often a brief network blip.",
+ },
+ offline: {
+ label: "Offline",
+ dot: "bg-muted-foreground/40",
+ description: "No heartbeat for 5+ minutes. Restart the daemon or investigate the host.",
+ },
+ about_to_gc: {
+ label: "About to GC",
+ dot: "bg-destructive",
+ description: "Offline 6+ days. Auto-deleted at 7 days unless it reconnects.",
+ },
+};
interface RuntimesPageProps {
- /** Desktop-only slot rendered above the runtime list (e.g. local daemon card) */
+ /** Desktop-only slot rendered above the runtimes table (e.g. local daemon card) */
topSlot?: React.ReactNode;
/**
* Desktop-only signal: the bundled daemon is still booting / hasn't
- * registered with the server yet. Forwarded to RuntimeList so its
- * empty state shows a "starting" indicator instead of the static
- * "register a runtime" hint during the boot window. Web omits this.
+ * registered with the server yet. Forwarded so the empty state can show
+ * a "starting" indicator instead of the static "register a runtime" hint
+ * during the boot window. Web omits this.
*/
bootstrapping?: boolean;
}
-export default function RuntimesPage({ topSlot, bootstrapping }: RuntimesPageProps = {}) {
+// Re-render every 30s so derived health (recently_lost → offline transitions)
+// catches up even when no underlying query data has changed.
+function useNowTick(intervalMs = 30_000): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), intervalMs);
+ return () => clearInterval(id);
+ }, [intervalMs]);
+ return now;
+}
+
+export function RuntimesPage({ topSlot, bootstrapping }: RuntimesPageProps = {}) {
const isLoading = useAuthStore((s) => s.isLoading);
const wsId = useWorkspaceId();
const qc = useQueryClient();
- const [filter, setFilter] = useState<RuntimeFilter>("mine");
- const [ownerFilter, setOwnerFilter] = useState<string | null>(null);
- const [selectedId, setSelectedId] = useState("");
-
- const ownerParam = filter === "mine" ? "me" as const : undefined;
- const { data: runtimes = [], isLoading: fetching } = useQuery(runtimeListOptions(wsId, ownerParam));
+ const [scope, setScope] = useState<RuntimeFilter>("mine");
+ const [healthFilter, setHealthFilter] = useState<HealthFilter>("all");
+ const [search, setSearch] = useState("");
- const { defaultLayout, onLayoutChanged } = useDefaultLayout({
- id: "multica_runtimes_layout",
- });
+ // One unified cache per workspace: scope (Mine/All) is a view filter, not
+ // a fetch dimension. Splitting on owner used to give us two TanStack cache
+ // slots holding independent snapshots of the same runtime — switching scope
+ // surfaced stale `last_seen_at` from whichever slot was older.
+ const { data: runtimes = [], isLoading: fetching } = useQuery(
+ runtimeListOptions(wsId),
+ );
+ const currentUserId = useAuthStore((s) => s.user?.id);
- // Re-fetch on daemon register/deregister events.
const handleDaemonEvent = useCallback(() => {
qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
}, [qc, wsId]);
-
useWSEvent("daemon:register", handleDaemonEvent);
+
const updatableIds = useUpdatableRuntimeIds(wsId);
+ const now = useNowTick();
- // Auto-select first runtime if nothing selected
- const effectiveSelectedId = selectedId && runtimes.some((r) => r.id === selectedId)
- ? selectedId
- : runtimes[0]?.id ?? "";
- const selected = runtimes.find((r) => r.id === effectiveSelectedId) ?? null;
+ // Apply scope first, then everything downstream (health counts, list filter)
+ // operates on the post-scope set — so chip counts and filter results stay
+ // consistent with what the user sees.
+ const scopedRuntimes = useMemo(() => {
+ if (scope !== "mine") return runtimes;
+ if (!currentUserId) return [];
+ return runtimes.filter((r) => r.owner_id === currentUserId);
+ }, [runtimes, scope, currentUserId]);
- if (isLoading || fetching) {
- return (
- <div className="flex flex-1 min-h-0">
- {/* List skeleton */}
- <div className="w-72 border-r">
- <div className="flex h-12 items-center justify-between border-b px-4">
- <Skeleton className="h-4 w-20" />
- </div>
- <div className="divide-y">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3 px-4 py-3">
- <Skeleton className="h-5 w-5 rounded" />
- <div className="flex-1 space-y-1.5">
- <Skeleton className="h-4 w-28" />
- <Skeleton className="h-3 w-20" />
- </div>
- </div>
- ))}
- </div>
- </div>
- {/* Detail skeleton */}
- <div className="flex-1 p-6 space-y-6">
- <div className="flex items-center gap-3">
- <Skeleton className="h-5 w-5 rounded" />
- <Skeleton className="h-5 w-32" />
+ const healthCounts = useMemo(() => {
+ const counts: Record<Exclude<HealthFilter, "all">, number> = {
+ online: 0,
+ recently_lost: 0,
+ offline: 0,
+ about_to_gc: 0,
+ };
+ for (const r of scopedRuntimes) {
+ counts[deriveRuntimeHealth(r, now)] += 1;
+ }
+ return counts;
+ }, [scopedRuntimes, now]);
+
+ const filtered = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ return scopedRuntimes.filter((r) => {
+ if (healthFilter !== "all") {
+ if (deriveRuntimeHealth(r, now) !== healthFilter) return false;
+ }
+ if (q) {
+ const haystack = `${r.name} ${r.provider} ${r.device_info ?? ""}`.toLowerCase();
+ if (!haystack.includes(q)) return false;
+ }
+ return true;
+ });
+ }, [scopedRuntimes, healthFilter, search, now]);
+
+ if (isLoading || fetching) return <RuntimesPageSkeleton />;
+
+ const totalCount = runtimes.length;
+ const scopedTotal = scopedRuntimes.length;
+ const showEmpty = totalCount === 0 && !bootstrapping;
+
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <PageHeaderBar totalCount={totalCount} />
+
+ <div className="flex flex-1 min-h-0 flex-col gap-4 p-6">
+ {topSlot}
+
+ {showEmpty ? (
+ <div className="flex flex-1 items-center justify-center">
+ <EmptyState />
</div>
- <div className="space-y-3">
- {Array.from({ length: 3 }).map((_, i) => (
- <Skeleton key={i} className="h-16 w-full rounded-lg" />
- ))}
+ ) : (
+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border bg-background">
+ <CardToolbar
+ search={search}
+ setSearch={setSearch}
+ scope={scope}
+ setScope={setScope}
+ />
+ <FilterChipsRow
+ healthFilter={healthFilter}
+ setHealthFilter={setHealthFilter}
+ healthCounts={healthCounts}
+ total={scopedTotal}
+ />
+ {filtered.length === 0 ? (
+ <NoMatchesState search={search} healthFilter={healthFilter} scope={scope} bootstrapping={bootstrapping} />
+ ) : (
+ <RuntimeList
+ runtimes={filtered}
+ updatableIds={updatableIds}
+ now={now}
+ />
+ )}
</div>
- </div>
+ )}
</div>
- );
- }
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Header bar — minimal: only icon + title + count, matching Skills.
+// Page-level actions (Search, scope, filter) live in the card below.
+// ---------------------------------------------------------------------------
+function PageHeaderBar({ totalCount }: { totalCount: number }) {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- {topSlot}
- <ResizablePanelGroup
- orientation="horizontal"
- className="flex-1 min-h-0"
- defaultLayout={defaultLayout}
- onLayoutChanged={onLayoutChanged}
+ <PageHeader className="px-5">
+ <div className="flex items-center gap-2">
+ <Server className="h-4 w-4 text-muted-foreground" />
+ <h1 className="text-sm font-medium">Runtimes</h1>
+ {totalCount > 0 && (
+ <span className="font-mono text-xs tabular-nums text-muted-foreground/70">
+ {totalCount}
+ </span>
+ )}
+ {/* Tagline sits right next to the title — same flex group, single
+ sentence + docs link. Hidden below md so it never collides with
+ the title on narrow screens. */}
+ <p className="ml-2 hidden text-xs text-muted-foreground md:block">
+ Machines and cloud workers running CLI sessions for your agents.{" "}
+ <a
+ href="https://multica.ai/docs/runtimes"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline decoration-muted-foreground/30 underline-offset-4 transition-colors hover:text-foreground"
+ >
+ Learn more →
+ </a>
+ </p>
+ </div>
+ </PageHeader>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Intro block — sits between the page header and the table card. Mirrors
+// Skills' two-paragraph pattern: a one-liner plus a brand-accented callout
+// pinning down a single non-obvious fact about the surface.
+// ---------------------------------------------------------------------------
+
+
+// ---------------------------------------------------------------------------
+// Card toolbar — search + scope toggle + live indicator. Skills puts its
+// search and filter buttons here; we follow the same convention so the card
+// owns its own interactions.
+// ---------------------------------------------------------------------------
+
+function CardToolbar({
+ search,
+ setSearch,
+ scope,
+ setScope,
+}: {
+ search: string;
+ setSearch: (v: string) => void;
+ scope: RuntimeFilter;
+ setScope: (v: RuntimeFilter) => void;
+}) {
+ return (
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search runtimes…"
+ className="h-8 w-64 pl-8 text-sm"
+ />
+ </div>
+ <ScopeSegment value={scope} onChange={setScope} />
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <div className="ml-auto inline-flex cursor-default select-none items-center gap-1.5 text-xs text-muted-foreground">
+ <span className="relative inline-flex h-2 w-2 items-center justify-center">
+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-success/60" />
+ <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-success" />
+ </span>
+ Live
+ </div>
+ }
+ />
+ <TooltipContent side="top">
+ Real-time updates · offline detection up to 75s
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ );
+}
+
+function ScopeSegment({
+ value,
+ onChange,
+}: {
+ value: RuntimeFilter;
+ onChange: (v: RuntimeFilter) => void;
+}) {
+ // Mine first — that's the default selection and the more frequent
+ // scope (your own runtimes), so it lives in the leading slot. Mirrors
+ // the Agents page convention.
+ return (
+ <div className="flex items-center gap-0.5 rounded-md bg-muted p-0.5">
+ <button
+ onClick={() => onChange("mine")}
+ className={`rounded px-2.5 py-1 text-xs font-medium transition-colors ${
+ value === "mine"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ Mine
+ </button>
+ <button
+ onClick={() => onChange("all")}
+ className={`rounded px-2.5 py-1 text-xs font-medium transition-colors ${
+ value === "all"
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
>
- <ResizablePanel
- id="list"
- defaultSize={280}
- minSize={240}
- maxSize={400}
- groupResizeBehavior="preserve-pixel-size"
- >
- <RuntimeList
- runtimes={runtimes}
- selectedId={effectiveSelectedId}
- onSelect={setSelectedId}
- filter={filter}
- onFilterChange={setFilter}
- ownerFilter={ownerFilter}
- onOwnerFilterChange={setOwnerFilter}
- updatableIds={updatableIds}
- bootstrapping={bootstrapping}
+ All
+ </button>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Filter chips — 4 health states + "All", each with a tooltip explaining
+// what the state actually means in operational terms. Counts come from the
+// pre-filter set so users can see "what would happen" before clicking.
+// ---------------------------------------------------------------------------
+
+function FilterChipsRow({
+ healthFilter,
+ setHealthFilter,
+ healthCounts,
+ total,
+}: {
+ healthFilter: HealthFilter;
+ setHealthFilter: (v: HealthFilter) => void;
+ healthCounts: Record<Exclude<HealthFilter, "all">, number>;
+ total: number;
+}) {
+ return (
+ <div className="flex shrink-0 items-center gap-2 border-b px-4 py-2.5">
+ {HEALTH_ORDER.map((key) => {
+ const count = key === "all" ? total : healthCounts[key];
+ const visual = key === "all" ? null : HEALTH_CHIP[key];
+ const description =
+ key === "all" ? "All runtimes in this view" : visual!.description;
+ return (
+ <HealthChip
+ key={key}
+ active={healthFilter === key}
+ onClick={() => setHealthFilter(key)}
+ label={visual?.label ?? "All"}
+ count={count}
+ dotClass={visual?.dot}
+ description={description}
/>
- </ResizablePanel>
+ );
+ })}
+ </div>
+ );
+}
- <ResizableHandle />
+// Mirrors Agents' `PresenceChip` — same `Button outline + size sm` shell so
+// any future polish to the chip token cascades to both surfaces. The active
+// state uses `bg-accent text-accent-foreground hover:bg-accent/80`, matching
+// Skills' filter chip selection.
+function HealthChip({
+ active,
+ onClick,
+ label,
+ count,
+ dotClass,
+ description,
+}: {
+ active: boolean;
+ onClick: () => void;
+ label: string;
+ count: number;
+ dotClass?: string;
+ description: string;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={onClick}
+ className={
+ active
+ ? "bg-accent text-accent-foreground hover:bg-accent/80"
+ : "text-muted-foreground"
+ }
+ >
+ {dotClass && (
+ <span className={`h-1.5 w-1.5 rounded-full ${dotClass}`} />
+ )}
+ <span>{label}</span>
+ <span className="font-mono tabular-nums text-muted-foreground/70">
+ {count}
+ </span>
+ </Button>
+ }
+ />
+ <TooltipContent side="top">{description}</TooltipContent>
+ </Tooltip>
+ );
+}
- <ResizablePanel id="detail" minSize="50%">
- {selected ? (
- <RuntimeDetail key={selected.id} runtime={selected} />
- ) : (
- <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
- <Server className="h-10 w-10 text-muted-foreground/30" />
- <p className="mt-3 text-sm">Select a runtime to view details</p>
- </div>
- )}
- </ResizablePanel>
- </ResizablePanelGroup>
+// ---------------------------------------------------------------------------
+// Empty state — shown when zero runtimes have ever registered in this
+// workspace. Different from "filter matches nothing" (NoMatchesState).
+// ---------------------------------------------------------------------------
+
+function EmptyState() {
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center px-6 py-16 text-center">
+ <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
+ <Server className="h-6 w-6 text-muted-foreground" />
+ </div>
+ <h2 className="mt-4 text-base font-semibold">No runtimes yet</h2>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">
+ Runtimes register automatically when a daemon connects. Run{" "}
+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">
+ multica daemon start
+ </code>{" "}
+ on your machine, or invite a teammate whose daemon is already running.
+ </p>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// No matches state — runtimes exist but the current filter combination
+// hides all of them. Keeps the user oriented by reflecting *which* filters
+// are in play.
+// ---------------------------------------------------------------------------
+
+function NoMatchesState({
+ search,
+ healthFilter,
+ scope,
+ bootstrapping,
+}: {
+ search: string;
+ healthFilter: HealthFilter;
+ scope: RuntimeFilter;
+ bootstrapping?: boolean;
+}) {
+ if (bootstrapping) {
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center gap-2 px-4 py-16 text-center">
+ <Server className="h-8 w-8 animate-pulse text-muted-foreground/40" />
+ <p className="text-sm text-muted-foreground">Starting local runtime…</p>
+ <p className="max-w-xs text-xs text-muted-foreground/70">
+ This usually takes a few seconds. Your daemon is registering with the workspace.
+ </p>
+ </div>
+ );
+ }
+
+ const hasSearch = search.length > 0;
+ const hasHealthFilter = healthFilter !== "all";
+ const hasScope = scope === "mine";
+
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center gap-2 px-4 py-16 text-center text-muted-foreground">
+ <Search className="h-8 w-8 text-muted-foreground/40" />
+ <p className="text-sm">No matches</p>
+ <p className="max-w-xs text-xs">
+ {hasSearch
+ ? `No runtimes match "${search}"${hasHealthFilter || hasScope ? " in this filter" : ""}.`
+ : "No runtimes match this filter."}{" "}
+ Try widening the scope or clearing filters.
+ </p>
</div>
);
}
+
+// ---------------------------------------------------------------------------
+// Loading skeleton — laid out the same as the real page (header + intro
+// + card) so the layout doesn't jump on first paint.
+// ---------------------------------------------------------------------------
+
+function RuntimesPageSkeleton() {
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <PageHeader className="justify-between px-5">
+ <Skeleton className="h-4 w-24" />
+ </PageHeader>
+ <div className="flex flex-1 min-h-0 flex-col gap-4 p-6">
+ <div className="space-y-3 pl-4">
+ <Skeleton className="h-5 w-full max-w-2xl rounded-md" />
+ <Skeleton className="h-14 w-full max-w-3xl rounded-md" />
+ </div>
+ <div className="flex flex-1 min-h-0 flex-col overflow-hidden rounded-lg border">
+ <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
+ <Skeleton className="h-8 w-64 rounded-md" />
+ <Skeleton className="h-7 w-20 rounded-md" />
+ </div>
+ <div className="space-y-2 p-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-14 w-full rounded-md" />
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default RuntimesPage;
+export type { RuntimesPageProps };
diff --git a/packages/views/runtimes/components/shared.tsx b/packages/views/runtimes/components/shared.tsx
index eb0be228d8..9909aae628 100644
--- a/packages/views/runtimes/components/shared.tsx
+++ b/packages/views/runtimes/components/shared.tsx
@@ -1,5 +1,7 @@
-import { Monitor, Cloud, Wifi, WifiOff } from "lucide-react";
+import { Cloud, Monitor, Wifi, WifiHigh, WifiOff } from "lucide-react";
import { Badge } from "@multica/ui/components/ui/badge";
+import type { RuntimeHealth } from "@multica/core/runtimes";
+import { ProviderLogo } from "./provider-logo";
export function RuntimeModeIcon({ mode }: { mode: string }) {
return mode === "cloud" ? (
@@ -9,19 +11,123 @@ export function RuntimeModeIcon({ mode }: { mode: string }) {
);
}
-export function StatusBadge({ status }: { status: string }) {
- const isOnline = status === "online";
+// Compact provider tag: small logo square + provider name. Used in dense
+// list rows to identify which CLI / model provider a runtime is wired to.
+export function ProviderChip({ provider }: { provider: string }) {
return (
- <Badge
- variant="secondary"
- className={isOnline ? "bg-success/10 text-success" : ""}
- >
- {isOnline ? (
- <Wifi className="h-3 w-3" />
- ) : (
- <WifiOff className="h-3 w-3" />
- )}
- {isOnline ? "Online" : "Offline"}
+ <span className="inline-flex items-center gap-1 rounded-md border bg-muted/40 px-1.5 py-0.5 text-xs font-medium text-muted-foreground">
+ <ProviderLogo provider={provider} className="h-3 w-3" />
+ <span className="capitalize">{provider}</span>
+ </span>
+ );
+}
+
+// Maps each derived 4-state runtime health to a semantic colour class.
+// The mapping intentionally reuses our existing tokens (success/warning/
+// muted-foreground/destructive) instead of introducing runtime-specific
+// colours — keeps the palette small and consistent with Skills.
+const HEALTH_VISUAL: Record<
+ RuntimeHealth,
+ { dot: string; label: string; tone: string }
+> = {
+ online: {
+ dot: "bg-success",
+ label: "Online",
+ tone: "bg-success/10 text-success",
+ },
+ recently_lost: {
+ dot: "bg-warning",
+ label: "Recently lost",
+ tone: "bg-warning/10 text-warning",
+ },
+ offline: {
+ dot: "bg-muted-foreground/40",
+ label: "Offline",
+ tone: "bg-muted text-muted-foreground",
+ },
+ about_to_gc: {
+ dot: "bg-destructive",
+ label: "About to GC",
+ tone: "bg-destructive/10 text-destructive",
+ },
+};
+
+export function HealthDot({
+ health,
+ className = "",
+}: {
+ health: RuntimeHealth | "loading";
+ className?: string;
+}) {
+ if (health === "loading") {
+ return (
+ <span
+ className={`inline-block h-2 w-2 rounded-full bg-muted ${className}`}
+ />
+ );
+ }
+ return (
+ <span
+ className={`inline-block h-2 w-2 rounded-full ${HEALTH_VISUAL[health].dot} ${className}`}
+ />
+ );
+}
+
+// Wifi-style runtime health indicator. The icon shape carries the rough
+// state ("can it talk to us?") and the colour carries severity. Used
+// wherever a richer signal than the bare dot is appropriate (agent
+// hover-card runtime row, runtime list health column).
+//
+// online → Wifi (full bars, success)
+// recently_lost → WifiHigh (fewer bars, warning) — transient hiccup
+// offline → WifiOff (slashed, muted) — long unreachable
+// about_to_gc → WifiOff (slashed, destructive) — sweeper coming
+const HEALTH_ICON: Record<
+ RuntimeHealth,
+ { Icon: typeof Wifi; tone: string }
+> = {
+ online: { Icon: Wifi, tone: "text-success" },
+ recently_lost: { Icon: WifiHigh, tone: "text-warning" },
+ offline: { Icon: WifiOff, tone: "text-muted-foreground" },
+ about_to_gc: { Icon: WifiOff, tone: "text-destructive" },
+};
+
+export function HealthIcon({
+ health,
+ className = "h-3 w-3",
+}: {
+ health: RuntimeHealth | "loading";
+ className?: string;
+}) {
+ if (health === "loading") {
+ return <Wifi className={`${className} text-muted-foreground/40`} />;
+ }
+ const { Icon, tone } = HEALTH_ICON[health];
+ return <Icon className={`${className} ${tone}`} />;
+}
+
+export function healthLabel(health: RuntimeHealth | "loading"): string {
+ if (health === "loading") return "—";
+ return HEALTH_VISUAL[health].label;
+}
+
+export function HealthBadge({
+ health,
+}: {
+ health: RuntimeHealth | "loading";
+}) {
+ if (health === "loading") {
+ return (
+ <Badge variant="secondary" className="bg-muted text-muted-foreground">
+ —
+ </Badge>
+ );
+ }
+ const v = HEALTH_VISUAL[health];
+ return (
+ <Badge variant="secondary" className={v.tone}>
+ <span className={`h-1.5 w-1.5 rounded-full ${v.dot}`} />
+ {v.label}
</Badge>
);
}
@@ -55,3 +161,40 @@ export function TokenCard({ label, value }: { label: string; value: string }) {
</div>
);
}
+
+// KPI tile used in the Runtime detail "story numbers" row. The big number
+// is the visual anchor of the whole left column — sized large enough that
+// it dominates over the chart hierarchy below it. Label sits as a small
+// caps eyebrow; hint is a thin caption beneath the number for deltas /
+// ratios / savings context.
+export function KpiCard({
+ label,
+ value,
+ hint,
+ accent,
+}: {
+ label: string;
+ value: string;
+ hint?: React.ReactNode;
+ accent?: "brand" | "success" | "default";
+}) {
+ const valueClass =
+ accent === "brand"
+ ? "text-brand"
+ : accent === "success"
+ ? "text-success"
+ : "";
+ return (
+ <div className="flex flex-col gap-2 p-5">
+ <div className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
+ {label}
+ </div>
+ <div className={`text-3xl font-semibold leading-none tabular-nums ${valueClass}`}>
+ {value}
+ </div>
+ {hint != null && (
+ <div className="text-xs text-muted-foreground">{hint}</div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsx
index 56a4d92308..8ae968e0ae 100644
--- a/packages/views/runtimes/components/usage-section.tsx
+++ b/packages/views/runtimes/components/usage-section.tsx
@@ -1,20 +1,41 @@
"use client";
-import { useState, useEffect } from "react";
-import { BarChart3 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { BarChart3, ChevronRight } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { agentListOptions } from "@multica/core/workspace/queries";
import type { RuntimeUsage } from "@multica/core/types";
-import { api } from "@multica/core/api";
-import { formatTokens, estimateCost, aggregateByDate } from "../utils";
-import { TokenCard } from "./shared";
import {
- ActivityHeatmap,
- HourlyActivityChart,
- DailyTokenChart,
+ runtimeUsageOptions,
+ runtimeUsageByAgentOptions,
+ runtimeUsageByHourOptions,
+} from "@multica/core/runtimes/queries";
+import {
+ formatTokens,
+ estimateCost,
+ estimateCacheSavings,
+ aggregateByDate,
+ aggregateCostByAgent,
+ aggregateCostByModel,
+ aggregateCostByHour,
+ collectUnmappedModels,
+ pctChange,
+ type CostByKey,
+} from "../utils";
+import { KpiCard } from "./shared";
+import { ActorAvatar } from "../../common/actor-avatar";
+import {
DailyCostChart,
- ModelDistributionChart,
+ HourlyActivityChart,
+ ActivityHeatmap,
+ costStackConfig,
} from "./charts";
+// Single source of truth for the period selector. KPIs, the When-chart, the
+// Cost-by tabs, and the CSV export all read from the same `days` value so
+// the labels ("· 30D") and the data slice never disagree.
const TIME_RANGES = [
{ label: "7d", days: 7 },
{ label: "30d", days: 30 },
@@ -23,166 +44,625 @@ const TIME_RANGES = [
type TimeRange = (typeof TIME_RANGES)[number]["days"];
+// ---------------------------------------------------------------------------
+// Local segmented control. shadcn's Tabs is wired for full tab pages with
+// keyboard nav and ARIA semantics that a compact toolbar pill doesn't need.
+// Visual: light-grey track + white "raised" active pill.
+// ---------------------------------------------------------------------------
+
+function Segmented<T extends string | number>({
+ value,
+ onChange,
+ options,
+ disabled,
+}: {
+ value: T;
+ onChange: (v: T) => void;
+ options: readonly { label: string; value: T }[];
+ disabled?: boolean;
+}) {
+ return (
+ <div
+ className={`inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5 ${
+ disabled ? "opacity-50" : ""
+ }`}
+ >
+ {options.map((o) => (
+ <button
+ key={String(o.value)}
+ type="button"
+ disabled={disabled}
+ onClick={() => onChange(o.value)}
+ className={`rounded-sm px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed ${
+ o.value === value
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {o.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function fmtMoney(n: number): string {
+ if (n >= 100) return `$${n.toFixed(0)}`;
+ return `$${n.toFixed(2)}`;
+}
+
+// ---------------------------------------------------------------------------
+// Top-level orchestrator. Owns the time window, fetches a 180-day usage
+// cache once, slices it into "current" / "prior" windows for delta math,
+// and threads everything into the four visual blocks below.
+//
+// 180 days (vs the older 90) is sized for the Heatmap tab — it shows 26
+// weeks (~6 months) so the long view actually looks long. The 7d/30d/90d
+// period selector slices client-side; the prior-window delta on the Cost
+// KPI also benefits from having extra history available.
+// ---------------------------------------------------------------------------
+
export function UsageSection({ runtimeId }: { runtimeId: string }) {
- const [usage, setUsage] = useState<RuntimeUsage[]>([]);
- const [loading, setLoading] = useState(true);
+ const { data: usage = [], isLoading: loading } = useQuery(
+ runtimeUsageOptions(runtimeId, 180),
+ );
const [days, setDays] = useState<TimeRange>(30);
- useEffect(() => {
- setLoading(true);
- api
- .getRuntimeUsage(runtimeId, { days: 90 }) // always fetch 90d, filter client-side
- .then(setUsage)
- .catch(() => setUsage([]))
- .finally(() => setLoading(false));
- }, [runtimeId]);
+ if (loading) return <UsageSkeleton />;
+ if (usage.length === 0) return <UsageEmpty />;
- if (loading) {
- return (
- <div className="space-y-4">
- <div className="flex items-center gap-1">
- {Array.from({ length: 3 }).map((_, i) => (
- <Skeleton key={i} className="h-8 w-12 rounded-md" />
- ))}
- </div>
- <div className="grid grid-cols-4 gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-16 rounded-lg" />
- ))}
- </div>
- <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
- <Skeleton className="h-64 rounded-lg" />
- <Skeleton className="h-64 rounded-lg" />
- </div>
+ // Slice the cached 90-day window into the user's selected sub-window AND
+ // the immediately prior window of equal length. The KPI delta ("+18% vs
+ // prev") then compares like-for-like ranges instead of "this period vs
+ // all of history".
+ const { filtered, prevFiltered } = sliceWindow(usage, days);
+ const totals = computeTotals(filtered);
+ const prevTotals = computeTotals(prevFiltered);
+
+ const tokensTotal =
+ totals.input + totals.output + totals.cacheRead + totals.cacheWrite;
+ const cacheableTokens = totals.input + totals.cacheRead;
+ const cacheHitRate =
+ cacheableTokens > 0 ? Math.round((totals.cacheRead / cacheableTokens) * 100) : 0;
+
+ const costDelta = pctChange(totals.cost, prevTotals.cost);
+
+ return (
+ <div className="space-y-5">
+ {/* Page-wide period selector. Lives at the top because it controls
+ basically everything below: the KPI numbers and labels, the daily
+ / hourly chart windows, and the cost-by aggregations. The Heatmap
+ tab is the only sub-view that ignores it (always shows 90d), and
+ its tab disables this control to telegraph that. */}
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs uppercase tracking-wider text-muted-foreground">
+ Period
+ </span>
+ <Segmented
+ value={days}
+ onChange={setDays}
+ options={TIME_RANGES.map((r) => ({
+ label: r.label,
+ value: r.days,
+ }))}
+ />
</div>
- );
- }
- if (usage.length === 0) {
- return (
- <div className="flex flex-col items-center rounded-lg border border-dashed py-6">
- <BarChart3 className="h-5 w-5 text-muted-foreground/40" />
- <p className="mt-2 text-xs text-muted-foreground">No usage data yet</p>
+ {/* Layer 1 — KPI hero. One outer card, three columns separated by a
+ divider; the big numbers carry the visual weight of the page. */}
+ <div className="grid grid-cols-3 divide-x rounded-lg border bg-card">
+ <KpiCard
+ label={`Cost · ${days}D`}
+ value={fmtMoney(totals.cost)}
+ hint={
+ costDelta == null ? undefined : (
+ <span
+ className={
+ costDelta > 0
+ ? "text-warning"
+ : costDelta < 0
+ ? "text-success"
+ : ""
+ }
+ >
+ {costDelta > 0 ? "+" : ""}
+ {costDelta}% vs prev
+ </span>
+ )
+ }
+ />
+ <KpiCard
+ label={`Cache savings · ${days}D`}
+ value={fmtMoney(totals.cacheSavings)}
+ accent={totals.cacheSavings > 0 ? "success" : "default"}
+ hint={
+ <span>
+ {cacheHitRate}% hit · {formatTokens(totals.cacheRead)} reads
+ </span>
+ }
+ />
+ <KpiCard
+ label={`Tokens · ${days}D`}
+ value={formatTokens(tokensTotal)}
+ hint={
+ <span>
+ in {formatTokens(totals.input)} · out {formatTokens(totals.output)}
+ </span>
+ }
+ />
</div>
- );
- }
- // Filter by selected time range
- const cutoffDate = new Date();
- cutoffDate.setDate(cutoffDate.getDate() - days);
- const cutoff = cutoffDate.toISOString().slice(0, 10);
- const filtered = usage.filter((u) => u.date >= cutoff);
+ {/* Layer 2 — WHEN chart. Three tabs for three independent time
+ dimensions: by-date (Daily), by-hour-of-day (Hourly), by-calendar
+ (Heatmap). The period selector lives at the page top — this card
+ only owns the tab switch and chart legend. */}
+ <WhenChart
+ runtimeId={runtimeId}
+ usage={usage}
+ filtered={filtered}
+ days={days}
+ />
- // Compute totals
- const totals = filtered.reduce(
- (acc, u) => ({
- input: acc.input + u.input_tokens,
- output: acc.output + u.output_tokens,
- cacheRead: acc.cacheRead + u.cache_read_tokens,
- cacheWrite: acc.cacheWrite + u.cache_write_tokens,
- cost: acc.cost + estimateCost(u),
- }),
- { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
+ {/* Layer 3 — WHO/WHAT burned the spend. By-hour was dropped — that
+ dimension lives in the WHEN chart now. */}
+ <CostByBlock runtimeId={runtimeId} days={days} usage={filtered} />
+
+ {/* Layer 4 — Folded raw view. Hourly and Heatmap used to live here;
+ they were promoted into the WHEN chart's tabs, leaving only the
+ breakdown table behind. */}
+ <FoldedRow usage={filtered} />
+ </div>
);
+}
- const { dailyTokens, dailyCost, modelDist } = aggregateByDate(filtered);
+// ---------------------------------------------------------------------------
+// WhenChart — answers "WHEN was this runtime spending money?" along three
+// independent time dimensions. Owning the tab state here (rather than
+// downstream) means the period selector and chart legend can live in the
+// same header row and stay in sync with whichever tab is active.
+// ---------------------------------------------------------------------------
- // Group by date for the table
- const byDate = new Map<string, RuntimeUsage[]>();
- for (const u of filtered) {
- const existing = byDate.get(u.date) ?? [];
- existing.push(u);
- byDate.set(u.date, existing);
- }
+type WhenTab = "daily" | "hourly" | "heatmap";
+
+function WhenChart({
+ runtimeId,
+ usage,
+ filtered,
+ days,
+}: {
+ runtimeId: string;
+ usage: RuntimeUsage[];
+ filtered: RuntimeUsage[];
+ days: TimeRange;
+}) {
+ const [tab, setTab] = useState<WhenTab>("daily");
+
+ // Lazy-fetch hourly cost — only needed when its tab is active. Daily and
+ // heatmap derive from the already-cached 90d usage prop.
+ const { data: byHourRows = [] } = useQuery({
+ ...runtimeUsageByHourOptions(runtimeId, days),
+ enabled: tab === "hourly",
+ });
+
+ const { dailyCostStack } = useMemo(() => aggregateByDate(filtered), [filtered]);
+ const hourlyCost = useMemo(
+ () =>
+ aggregateCostByHour(byHourRows).map((row) => ({
+ hour: Number(row.key),
+ cost: row.cost,
+ })),
+ [byHourRows],
+ );
return (
- <div className="space-y-4">
- {/* Time range selector */}
- <div className="flex items-center gap-1">
- {TIME_RANGES.map((range) => (
- <button
- key={range.days}
- onClick={() => setDays(range.days)}
- className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
- days === range.days
- ? "bg-primary text-primary-foreground"
- : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
- }`}
- >
- {range.label}
- </button>
- ))}
+ <div className="rounded-lg border bg-card p-4">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-3">
+ <h4 className="text-sm font-semibold">When this runtime spent</h4>
+ <Segmented
+ value={tab}
+ onChange={setTab}
+ options={
+ [
+ { label: "Daily", value: "daily" },
+ { label: "Hourly", value: "hourly" },
+ { label: "Heatmap", value: "heatmap" },
+ ] as const
+ }
+ />
+ </div>
+ {tab !== "heatmap" && <ChartLegend />}
</div>
- {/* Summary cards */}
- <div className="grid grid-cols-4 gap-3">
- <TokenCard label="Input" value={formatTokens(totals.input)} />
- <TokenCard label="Output" value={formatTokens(totals.output)} />
- <TokenCard label="Cache Read" value={formatTokens(totals.cacheRead)} />
- <TokenCard label="Cache Write" value={formatTokens(totals.cacheWrite)} />
+ {/* Heatmap intentionally ignores the page period selector and always
+ shows the full 13-week window (a 7-day heatmap is just a row of
+ squares; the long view is the whole point). */}
+ {tab === "heatmap" && (
+ <p className="mb-2 text-center text-xs text-muted-foreground">
+ Last 26 weeks · daily $ intensity (period selector ignored here)
+ </p>
+ )}
+
+ {/* Stable canvas — every tab fits inside the same min-height so
+ switching never collapses or stretches the card vertically (and
+ the right-rail / lower sections never reflow as a side effect). */}
+ <div className="min-h-[260px]">
+ {tab === "daily" && <DailyTab data={dailyCostStack} usage={filtered} />}
+ {tab === "hourly" && <HourlyTab data={hourlyCost} usage={filtered} />}
+ {tab === "heatmap" && <ActivityHeatmap usage={usage} />}
</div>
+ </div>
+ );
+}
- {totals.cost > 0 && (
- <div className="rounded-lg border bg-muted/30 px-3 py-2">
- <span className="text-xs text-muted-foreground">
- Estimated cost ({days}d):{" "}
- </span>
- <span className="text-sm font-semibold">
- ${totals.cost.toFixed(2)}
- </span>
- </div>
+function DailyTab({
+ data,
+ usage,
+}: {
+ data: { total: number }[];
+ usage: RuntimeUsage[];
+}) {
+ const totalCost = data.reduce((s, d) => s + d.total, 0);
+ if (totalCost === 0) return <EmptyChartState usage={usage} />;
+ return <DailyCostChart data={data as Parameters<typeof DailyCostChart>[0]["data"]} />;
+}
+
+function HourlyTab({
+ data,
+ usage,
+}: {
+ data: { hour: number; cost: number }[];
+ usage: RuntimeUsage[];
+}) {
+ const totalCost = data.reduce((s, d) => s + d.cost, 0);
+ if (totalCost === 0) return <EmptyChartState usage={usage} />;
+ return <HourlyActivityChart data={data} />;
+}
+
+// ---------------------------------------------------------------------------
+// EmptyChartState — drop-in replacement for "the chart would render empty".
+// Two cases worth distinguishing:
+// 1. No tokens at all → "no usage" (genuinely nothing happened).
+// 2. Tokens present but cost is $0 → almost always means the model name
+// reported by the daemon isn't in our pricing table. List the offenders
+// so a developer can update MODEL_PRICING in one go.
+// ---------------------------------------------------------------------------
+
+function EmptyChartState({ usage }: { usage: RuntimeUsage[] }) {
+ const hasTokens = usage.some(
+ (u) =>
+ u.input_tokens + u.output_tokens + u.cache_read_tokens + u.cache_write_tokens >
+ 0,
+ );
+ const unmapped = collectUnmappedModels(usage);
+
+ return (
+ <div className="flex aspect-[3/1] flex-col items-center justify-center gap-2 rounded-md border border-dashed bg-muted/20 p-6 text-center">
+ <BarChart3 className="h-5 w-5 text-muted-foreground/50" />
+ {!hasTokens ? (
+ <p className="text-xs text-muted-foreground">
+ No usage in this period.
+ </p>
+ ) : unmapped.length > 0 ? (
+ <>
+ <p className="text-xs text-muted-foreground">
+ Tokens recorded but pricing missing for:
+ </p>
+ <p className="font-mono text-[11px] text-foreground">
+ {unmapped.join(", ")}
+ </p>
+ <p className="text-[11px] text-muted-foreground/70">
+ Add to MODEL_PRICING in packages/views/runtimes/utils.ts
+ </p>
+ </>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Tokens recorded but cost calculation returned $0.
+ </p>
)}
+ </div>
+ );
+}
- {/* Heatmap + Hourly */}
- <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
- <ActivityHeatmap usage={usage} />
- <HourlyActivityChart runtimeId={runtimeId} />
- </div>
+// ---------------------------------------------------------------------------
+// Chart legend — three coloured dots + labels, rendered in WhenChart's
+// header so the chart body keeps its full vertical real estate.
+// ---------------------------------------------------------------------------
- {/* Token & Cost charts */}
- <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
- <DailyTokenChart data={dailyTokens} />
- <DailyCostChart data={dailyCost} />
- </div>
+function ChartLegend() {
+ const items = [
+ { label: costStackConfig.input.label, color: "var(--color-chart-1)" },
+ { label: costStackConfig.output.label, color: "var(--color-chart-2)" },
+ { label: costStackConfig.cacheWrite.label, color: "var(--color-chart-3)" },
+ ];
+ return (
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ {items.map((it) => (
+ <span key={it.label} className="inline-flex items-center gap-1.5">
+ <span
+ className="h-2 w-2 rounded-sm"
+ style={{ background: it.color }}
+ />
+ {it.label}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Cost-by block: two-tab attribution view. By-hour was removed — that
+// dimension lives in the WhenChart's "Hourly" tab, which is more legible
+// as a 24-bucket bar than as a sorted list.
+// ---------------------------------------------------------------------------
- <ModelDistributionChart data={modelDist} />
-
- {/* Daily breakdown table */}
- <div className="rounded-lg border">
- <div className="grid grid-cols-[100px_1fr_80px_80px_80px_80px] gap-2 border-b px-3 py-2 text-xs font-medium text-muted-foreground">
- <div>Date</div>
- <div>Model</div>
- <div className="text-right">Input</div>
- <div className="text-right">Output</div>
- <div className="text-right">Cache R</div>
- <div className="text-right">Cache W</div>
+function CostByBlock({
+ runtimeId,
+ days,
+ usage,
+}: {
+ runtimeId: string;
+ days: number;
+ usage: RuntimeUsage[];
+}) {
+ const [tab, setTab] = useState<"agent" | "model">("agent");
+
+ // by-agent is server-side aggregation (fetched lazily on tab activation).
+ // by-model derives from the daily cache the parent already has — free.
+ const { data: byAgentRows = [] } = useQuery({
+ ...runtimeUsageByAgentOptions(runtimeId, days),
+ enabled: tab === "agent",
+ });
+
+ const wsId = useWorkspaceId();
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+
+ const byAgent = useMemo(() => aggregateCostByAgent(byAgentRows), [byAgentRows]);
+ const byModel = useMemo(() => aggregateCostByModel(usage), [usage]);
+
+ const caption =
+ tab === "agent"
+ ? `${byAgent.length} agent${byAgent.length === 1 ? "" : "s"} on this runtime`
+ : `${byModel.length} model${byModel.length === 1 ? "" : "s"} used`;
+
+ return (
+ <div>
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b pb-3">
+ <div className="flex items-center gap-3">
+ <h4 className="text-sm font-semibold">Cost by {tab}</h4>
+ <Segmented
+ value={tab}
+ onChange={setTab}
+ options={
+ [
+ { label: "By agent", value: "agent" },
+ { label: "By model", value: "model" },
+ ] as const
+ }
+ />
</div>
- <div className="max-h-64 overflow-y-auto divide-y">
- {[...byDate.entries()].map(([date, rows]) =>
- rows.map((row, i) => (
- <div
- key={`${date}-${row.model}-${i}`}
- className="grid grid-cols-[100px_1fr_80px_80px_80px_80px] gap-2 px-3 py-1.5 text-xs"
- >
- <div className="text-muted-foreground">{date}</div>
- <div className="truncate font-mono">{row.model}</div>
- <div className="text-right tabular-nums">
- {formatTokens(row.input_tokens)}
- </div>
- <div className="text-right tabular-nums">
- {formatTokens(row.output_tokens)}
- </div>
- <div className="text-right tabular-nums">
- {formatTokens(row.cache_read_tokens)}
- </div>
- <div className="text-right tabular-nums">
- {formatTokens(row.cache_write_tokens)}
+ <span className="text-xs text-muted-foreground">{caption}</span>
+ </div>
+ <div className="pt-4">
+ {tab === "agent" && (
+ <CostByList
+ rows={byAgent}
+ renderKey={(key) => {
+ const agent = agents.find((a) => a.id === key);
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <ActorAvatar actorType="agent" actorId={key} size={22} enableHoverCard />
+ <span className="cursor-pointer truncate text-sm font-medium">
+ {agent?.name ?? key}
+ </span>
</div>
- </div>
- )),
- )}
+ );
+ }}
+ />
+ )}
+ {tab === "model" && (
+ <CostByList
+ rows={byModel}
+ renderKey={(key) => (
+ <span className="truncate font-mono text-xs text-foreground">
+ {key}
+ </span>
+ )}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+// Generic horizontal-bar list shared by both Cost-by tabs. Each row scales
+// its bar relative to the heaviest row in the set, so the visual ranking
+// is always 0..max and the biggest spender visually fills the column.
+function CostByList({
+ rows,
+ renderKey,
+ emptyHint = "No usage in this period.",
+}: {
+ rows: CostByKey[];
+ renderKey: (key: string) => React.ReactNode;
+ emptyHint?: string;
+}) {
+ if (rows.length === 0) {
+ return (
+ <p className="py-4 text-center text-xs text-muted-foreground">
+ {emptyHint}
+ </p>
+ );
+ }
+ const maxCost = rows.reduce((m, r) => Math.max(m, r.cost), 0);
+ return (
+ <div className="space-y-2">
+ {rows.map((row) => {
+ const pct = maxCost > 0 ? (row.cost / maxCost) * 100 : 0;
+ return (
+ <div
+ key={row.key}
+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)_5rem_5rem] items-center gap-3 py-1"
+ >
+ <div className="min-w-0">{renderKey(row.key)}</div>
+ <div className="relative h-2 overflow-hidden rounded-full bg-muted">
+ <div
+ className="h-full rounded-full bg-chart-1"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <div className="text-right text-xs tabular-nums text-muted-foreground">
+ {formatTokens(row.tokens)}
+ </div>
+ <div className="text-right text-sm font-medium tabular-nums">
+ ${row.cost.toFixed(2)}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Folded row — single chevron-toggle link revealing the raw breakdown
+// table. Hourly distribution and Activity heatmap used to live here; both
+// were promoted to WhenChart tabs, leaving only the table behind.
+// ---------------------------------------------------------------------------
+
+function FoldedRow({ usage }: { usage: RuntimeUsage[] }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <div className="border-t pt-3">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ChevronRight
+ className={`h-3 w-3 transition-transform ${open ? "rotate-90" : ""}`}
+ />
+ Daily breakdown table
+ </button>
+ {open && (
+ <div className="mt-3 rounded-md border p-4">
+ <DailyBreakdownTable usage={usage} />
</div>
+ )}
+ </div>
+ );
+}
+
+function DailyBreakdownTable({ usage }: { usage: RuntimeUsage[] }) {
+ const byDate = new Map<string, RuntimeUsage[]>();
+ for (const u of usage) {
+ const existing = byDate.get(u.date) ?? [];
+ existing.push(u);
+ byDate.set(u.date, existing);
+ }
+ return (
+ <div className="rounded-lg border">
+ <div className="grid grid-cols-[100px_1fr_80px_80px_80px_80px] gap-2 border-b px-3 py-2 text-xs font-medium text-muted-foreground">
+ <div>Date</div>
+ <div>Model</div>
+ <div className="text-right">Input</div>
+ <div className="text-right">Output</div>
+ <div className="text-right">Cache R</div>
+ <div className="text-right">Cache W</div>
+ </div>
+ <div className="max-h-64 overflow-y-auto divide-y">
+ {[...byDate.entries()].map(([date, rows]) =>
+ rows.map((row, i) => (
+ <div
+ key={`${date}-${row.model}-${i}`}
+ className="grid grid-cols-[100px_1fr_80px_80px_80px_80px] gap-2 px-3 py-1.5 text-xs"
+ >
+ <div className="text-muted-foreground">{date}</div>
+ <div className="truncate font-mono">{row.model}</div>
+ <div className="text-right tabular-nums">
+ {formatTokens(row.input_tokens)}
+ </div>
+ <div className="text-right tabular-nums">
+ {formatTokens(row.output_tokens)}
+ </div>
+ <div className="text-right tabular-nums">
+ {formatTokens(row.cache_read_tokens)}
+ </div>
+ <div className="text-right tabular-nums">
+ {formatTokens(row.cache_write_tokens)}
+ </div>
+ </div>
+ )),
+ )}
</div>
</div>
);
}
+
+// ---------------------------------------------------------------------------
+// Loading + empty states
+// ---------------------------------------------------------------------------
+
+function UsageSkeleton() {
+ return (
+ <div className="space-y-5">
+ <Skeleton className="h-28 rounded-lg" />
+ <Skeleton className="h-56 rounded-lg" />
+ <Skeleton className="h-32" />
+ </div>
+ );
+}
+
+function UsageEmpty() {
+ return (
+ <div className="flex flex-col items-center rounded-lg border border-dashed py-8">
+ <BarChart3 className="h-5 w-5 text-muted-foreground/40" />
+ <p className="mt-2 text-xs text-muted-foreground">No usage data yet</p>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function sliceWindow(usage: RuntimeUsage[], days: number) {
+ const now = new Date();
+ const cutoffCurrent = new Date(now);
+ cutoffCurrent.setDate(cutoffCurrent.getDate() - days);
+ const cutoffPrev = new Date(now);
+ cutoffPrev.setDate(cutoffPrev.getDate() - days * 2);
+ const isoCurrent = cutoffCurrent.toISOString().slice(0, 10);
+ const isoPrev = cutoffPrev.toISOString().slice(0, 10);
+
+ return {
+ filtered: usage.filter((u) => u.date >= isoCurrent),
+ prevFiltered: usage.filter(
+ (u) => u.date >= isoPrev && u.date < isoCurrent,
+ ),
+ };
+}
+
+interface UsageTotals {
+ input: number;
+ output: number;
+ cacheRead: number;
+ cacheWrite: number;
+ cost: number;
+ cacheSavings: number;
+}
+
+function computeTotals(rows: RuntimeUsage[]): UsageTotals {
+ return rows.reduce<UsageTotals>(
+ (acc, u) => ({
+ input: acc.input + u.input_tokens,
+ output: acc.output + u.output_tokens,
+ cacheRead: acc.cacheRead + u.cache_read_tokens,
+ cacheWrite: acc.cacheWrite + u.cache_write_tokens,
+ cost: acc.cost + estimateCost(u),
+ cacheSavings: acc.cacheSavings + estimateCacheSavings(u),
+ }),
+ { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, cacheSavings: 0 },
+ );
+}
+
diff --git a/packages/views/runtimes/index.ts b/packages/views/runtimes/index.ts
index 5fa5b0bf99..c534b94c43 100644
--- a/packages/views/runtimes/index.ts
+++ b/packages/views/runtimes/index.ts
@@ -1 +1 @@
-export { RuntimesPage } from "./components";
+export { RuntimesPage, RuntimeDetailPage } from "./components";
diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.ts
index 63218b6817..6175ed080c 100644
--- a/packages/views/runtimes/utils.ts
+++ b/packages/views/runtimes/utils.ts
@@ -1,16 +1,101 @@
-import type { RuntimeUsage } from "@multica/core/types";
+import type {
+ RuntimeUsage,
+ RuntimeUsageByAgent,
+ RuntimeUsageByHour,
+} from "@multica/core/types";
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
+// Compound-unit relative timestamp ("2m 14s ago", "1d 4h ago", "6d 19h ago")
+// — gives the user enough precision to tell "just lost" from "long lost"
+// at a glance without forcing them to mouse-over for a full timestamp.
export function formatLastSeen(lastSeenAt: string | null): string {
if (!lastSeenAt) return "Never";
- const diff = Date.now() - new Date(lastSeenAt).getTime();
- if (diff < 60_000) return "Just now";
- if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
- if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
- return `${Math.floor(diff / 86_400_000)}d ago`;
+ const diffMs = Date.now() - new Date(lastSeenAt).getTime();
+ if (diffMs < 5_000) return "Just now";
+
+ const seconds = Math.floor(diffMs / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (minutes < 1) return `${seconds}s ago`;
+ if (hours < 1) {
+ const s = seconds % 60;
+ return s > 0 ? `${minutes}m ${s}s ago` : `${minutes}m ago`;
+ }
+ if (days < 1) {
+ const m = minutes % 60;
+ return m > 0 ? `${hours}h ${m}m ago` : `${hours}h ago`;
+ }
+ const h = hours % 24;
+ return h > 0 ? `${days}d ${h}h ago` : `${days}d ago`;
+}
+
+// Turns the back-end's `device_info` string ("MacBook-Pro · darwin-amd64",
+// "some-host · linux-amd64") into something humans recognise. We don't have
+// hardware model or geo data on the wire today, so we settle for an OS-aware
+// rewrite of the GOOS/GOARCH suffix while preserving the hostname.
+export function formatDeviceInfo(raw: string | null): string | null {
+ if (!raw) return null;
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ return trimmed
+ .split(" · ")
+ .map((part) => prettifyOsArch(part))
+ .join(" · ");
+}
+
+function prettifyOsArch(part: string): string {
+ const lower = part.toLowerCase();
+ // Pattern: <os>-<arch>; e.g. darwin-amd64, linux-arm64, windows-amd64.
+ const match = lower.match(/^(darwin|linux|windows|freebsd|openbsd|netbsd)-(amd64|arm64|386|arm)$/);
+ if (!match) return part;
+ const os = match[1] ?? "";
+ const arch = match[2] ?? "";
+ const osLabel = OS_LABEL[os] ?? os;
+ const archLabel = ARCH_LABEL[arch] ?? arch;
+ return `${osLabel} (${archLabel})`;
+}
+
+const OS_LABEL: Record<string, string> = {
+ darwin: "macOS",
+ linux: "Linux",
+ windows: "Windows",
+ freebsd: "FreeBSD",
+ openbsd: "OpenBSD",
+ netbsd: "NetBSD",
+};
+
+const ARCH_LABEL: Record<string, string> = {
+ amd64: "x86_64",
+ arm64: "arm64",
+ "386": "x86",
+ arm: "arm",
+};
+
+// Strip leading "v" from version strings — GitHub releases ship `v0.2.17`,
+// daemon metadata reports `0.2.15`; normalising lets us compare both.
+function stripVersionPrefix(v: string): string {
+ return v.replace(/^v/, "");
+}
+
+// True iff `latest` is strictly newer than `current` by dotted-numeric
+// comparison. Non-numeric / missing segments compare as 0 ("0.2" < "0.2.1").
+// Used by the runtime-list CLI column to decide whether to surface the ↑
+// marker; same logic also lives inline in update-section.tsx for now.
+export function isVersionNewer(latest: string, current: string): boolean {
+ const l = stripVersionPrefix(latest).split(".").map(Number);
+ const c = stripVersionPrefix(current).split(".").map(Number);
+ for (let i = 0; i < Math.max(l.length, c.length); i++) {
+ const lv = l[i] ?? 0;
+ const cv = c[i] ?? 0;
+ if (lv > cv) return true;
+ if (lv < cv) return false;
+ }
+ return false;
}
export function formatTokens(n: number): string {
@@ -29,31 +114,91 @@ export function formatTokens(n: number): string {
// Cost estimation
// ---------------------------------------------------------------------------
-// Pricing per million tokens (USD)
+// Pricing per million tokens (USD). Sourced from
+// https://platform.claude.com/docs/en/about-claude/pricing — keep in sync
+// when Anthropic releases new models or adjusts prices. cacheWrite reflects
+// the 5-minute cache TTL (1.25× input); the daemon reports
+// cache_creation_input_tokens without TTL metadata, so 5m is the safest /
+// cheapest assumption (matches the API default).
+//
+// Iteration order matters: the resolver's startsWith() fallback walks this
+// object in insertion order, so MORE SPECIFIC keys (e.g. claude-sonnet-4-5)
+// must precede SHORTER prefixes (e.g. claude-sonnet-4) of the same family.
const MODEL_PRICING: Record<
string,
{ input: number; output: number; cacheRead: number; cacheWrite: number }
> = {
- "claude-haiku-4-5": { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 },
- "claude-sonnet-4-5": { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
- "claude-sonnet-4-6": { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
- "claude-opus-4-5": { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
- "claude-opus-4-6": { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
+ // -- Current generation (4.5+ — Opus dropped from 15/75 to 5/25 here) --
+ "claude-haiku-4-5": { input: 1, output: 5, cacheRead: 0.10, cacheWrite: 1.25 },
+ "claude-sonnet-4-5": { input: 3, output: 15, cacheRead: 0.30, cacheWrite: 3.75 },
+ "claude-sonnet-4-6": { input: 3, output: 15, cacheRead: 0.30, cacheWrite: 3.75 },
+ "claude-opus-4-5": { input: 5, output: 25, cacheRead: 0.50, cacheWrite: 6.25 },
+ "claude-opus-4-6": { input: 5, output: 25, cacheRead: 0.50, cacheWrite: 6.25 },
+ "claude-opus-4-7": { input: 5, output: 25, cacheRead: 0.50, cacheWrite: 6.25 },
+
+ // -- Pre-4.5 Opus (legacy, still served at original price tier) --
+ "claude-opus-4-1": { input: 15, output: 75, cacheRead: 1.50, cacheWrite: 18.75 },
+ "claude-opus-4": { input: 15, output: 75, cacheRead: 1.50, cacheWrite: 18.75 },
+
+ // -- Sonnet 4.0 (deprecated; same price as the 4.x family) --
+ "claude-sonnet-4": { input: 3, output: 15, cacheRead: 0.30, cacheWrite: 3.75 },
+
+ // -- Older Haiku tier (defensive entry for the rare runtime still on it) --
+ "claude-haiku-3-5": { input: 0.80, output: 4, cacheRead: 0.08, cacheWrite: 1.00 },
};
-export function estimateCost(usage: RuntimeUsage): number {
- const model = usage.model;
- let pricing = MODEL_PRICING[model];
- if (!pricing) {
- for (const [key, p] of Object.entries(MODEL_PRICING)) {
- if (model.startsWith(key)) {
- pricing = p;
- break;
- }
- }
+// Resolve a model string to its pricing tier. Two layers of fallback so the
+// daemon-reported model name doesn't have to match the keys exactly:
+// 1. Exact match.
+// 2. Strip a trailing date / "latest" tag (Claude Code typically reports
+// `claude-sonnet-4-5-20250929` — the date is volatile, the family is
+// what we price). Try exact match again on the stripped name.
+// 3. startsWith on either the raw or stripped name.
+// Anything that misses all three is genuinely unknown; we return undefined
+// so callers can distinguish "$0 spend" from "spent but model not priced".
+function resolvePricing(model: string) {
+ if (!model) return undefined;
+ if (MODEL_PRICING[model]) return MODEL_PRICING[model];
+
+ const stripped = model.replace(/-(20\d{6}|latest)$/, "");
+ if (stripped !== model && MODEL_PRICING[stripped]) return MODEL_PRICING[stripped];
+
+ for (const [key, p] of Object.entries(MODEL_PRICING)) {
+ if (model.startsWith(key) || stripped.startsWith(key)) return p;
}
- if (!pricing) return 0;
+ return undefined;
+}
+
+// Cheap predicate for the empty-state diagnostic: which model strings in a
+// usage batch failed pricing resolution. Useful when the user is staring at
+// "$0.00 / 2M tokens" and wants to know why.
+export function isModelPriced(model: string): boolean {
+ return resolvePricing(model) !== undefined;
+}
+// Returns the unique, sorted list of model strings present in `rows` that
+// don't resolve to a price. Empty when everything's priced or there are no
+// rows.
+export function collectUnmappedModels(rows: readonly Priceable[]): string[] {
+ const set = new Set<string>();
+ for (const r of rows) {
+ if (r.model && !isModelPriced(r.model)) set.add(r.model);
+ }
+ return [...set].sort();
+}
+
+// Anything carrying per-model token totals can be priced — RuntimeUsage,
+// RuntimeUsageByAgent, RuntimeUsageByHour all share this shape on purpose
+// (the back-end keeps the model dimension specifically so the client can
+// run this calculation for any aggregation axis).
+type Priceable = Pick<
+ RuntimeUsage,
+ "model" | "input_tokens" | "output_tokens" | "cache_read_tokens" | "cache_write_tokens"
+>;
+
+export function estimateCost(usage: Priceable): number {
+ const pricing = resolvePricing(usage.model);
+ if (!pricing) return 0;
return (
(usage.input_tokens * pricing.input +
usage.output_tokens * pricing.output +
@@ -63,6 +208,37 @@ export function estimateCost(usage: RuntimeUsage): number {
);
}
+export interface CostBreakdown {
+ input: number;
+ output: number;
+ cacheRead: number;
+ cacheWrite: number;
+}
+
+export function estimateCostBreakdown(usage: Priceable): CostBreakdown {
+ const pricing = resolvePricing(usage.model);
+ if (!pricing) {
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
+ }
+ return {
+ input: (usage.input_tokens * pricing.input) / 1_000_000,
+ output: (usage.output_tokens * pricing.output) / 1_000_000,
+ cacheRead: (usage.cache_read_tokens * pricing.cacheRead) / 1_000_000,
+ cacheWrite: (usage.cache_write_tokens * pricing.cacheWrite) / 1_000_000,
+ };
+}
+
+// Cache savings: what cache *reads* would have cost at full input pricing
+// minus what they actually cost at the discounted cache-hit rate. This is a
+// reconstruction of "money the cache saved you", not real-world spend.
+export function estimateCacheSavings(usage: Priceable): number {
+ const pricing = resolvePricing(usage.model);
+ if (!pricing) return 0;
+ const wouldHaveCost = (usage.cache_read_tokens * pricing.input) / 1_000_000;
+ const actualCost = (usage.cache_read_tokens * pricing.cacheRead) / 1_000_000;
+ return wouldHaveCost - actualCost;
+}
+
// ---------------------------------------------------------------------------
// Data aggregation
// ---------------------------------------------------------------------------
@@ -82,6 +258,18 @@ export interface DailyCostData {
cost: number;
}
+// Stacked variant — splits the daily $ figure into the three components that
+// drive billing (cache reads excluded; their cost is tracked separately as
+// "savings" since they're typically dominated by the cached-input discount).
+export interface DailyCostStackData {
+ date: string;
+ label: string;
+ input: number;
+ output: number;
+ cacheWrite: number;
+ total: number;
+}
+
export interface ModelDistribution {
model: string;
tokens: number;
@@ -91,10 +279,15 @@ export interface ModelDistribution {
export function aggregateByDate(usage: RuntimeUsage[]): {
dailyTokens: DailyTokenData[];
dailyCost: DailyCostData[];
+ dailyCostStack: DailyCostStackData[];
modelDist: ModelDistribution[];
} {
const dateMap = new Map<string, Omit<DailyTokenData, "label">>();
const costMap = new Map<string, number>();
+ const stackMap = new Map<
+ string,
+ { input: number; output: number; cacheWrite: number }
+ >();
const modelMap = new Map<string, { tokens: number; cost: number }>();
for (const u of usage) {
@@ -114,6 +307,17 @@ export function aggregateByDate(usage: RuntimeUsage[]): {
const dayCost = (costMap.get(u.date) ?? 0) + estimateCost(u);
costMap.set(u.date, dayCost);
+ const breakdown = estimateCostBreakdown(u);
+ const stack = stackMap.get(u.date) ?? {
+ input: 0,
+ output: 0,
+ cacheWrite: 0,
+ };
+ stack.input += breakdown.input;
+ stack.output += breakdown.output;
+ stack.cacheWrite += breakdown.cacheWrite;
+ stackMap.set(u.date, stack);
+
const modelName = u.model || u.provider;
const m = modelMap.get(modelName) ?? { tokens: 0, cost: 0 };
m.tokens +=
@@ -139,9 +343,132 @@ export function aggregateByDate(usage: RuntimeUsage[]): {
cost: Math.round(cost * 100) / 100,
}));
+ const dailyCostStack = [...stackMap.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([date, s]) => {
+ const round = (n: number) => Math.round(n * 100) / 100;
+ const input = round(s.input);
+ const output = round(s.output);
+ const cacheWrite = round(s.cacheWrite);
+ return {
+ date,
+ label: formatLabel(date),
+ input,
+ output,
+ cacheWrite,
+ total: round(input + output + cacheWrite),
+ };
+ });
+
const modelDist = [...modelMap.entries()]
.map(([model, data]) => ({ model, ...data }))
.sort((a, b) => b.tokens - a.tokens);
- return { dailyTokens, dailyCost, modelDist };
+ return { dailyTokens, dailyCost, dailyCostStack, modelDist };
+}
+
+// ---------------------------------------------------------------------------
+// Cost-by-X aggregations
+//
+// All three "Cost by …" tabs share the same shape: a sorted list of rows
+// where each row carries a key (agent name, model name, or hour-of-day),
+// total tokens and total cost. The chart / list components are oblivious
+// to which axis they're rendering — they just see {key, tokens, cost}.
+// ---------------------------------------------------------------------------
+
+export interface CostByKey {
+ key: string;
+ tokens: number;
+ cost: number;
+ taskCount: number;
+}
+
+// Per-(agent, model) rows → per-agent totals. Cost is summed across all
+// models for that agent, then the list is sorted by cost desc so the
+// heaviest-spending agent appears first.
+export function aggregateCostByAgent(rows: RuntimeUsageByAgent[]): CostByKey[] {
+ const map = new Map<string, CostByKey>();
+ for (const r of rows) {
+ const entry = map.get(r.agent_id) ?? {
+ key: r.agent_id,
+ tokens: 0,
+ cost: 0,
+ taskCount: 0,
+ };
+ entry.tokens +=
+ r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens;
+ entry.cost += estimateCost(r);
+ entry.taskCount += r.task_count;
+ map.set(r.agent_id, entry);
+ }
+ return [...map.values()].sort((a, b) => b.cost - a.cost);
+}
+
+// Per-(date, model) rows → per-model totals (the "By model" tab reuses the
+// daily-grain data we already cache, so no extra request is needed).
+export function aggregateCostByModel(rows: RuntimeUsage[]): CostByKey[] {
+ const map = new Map<string, CostByKey>();
+ for (const r of rows) {
+ const key = r.model || r.provider || "unknown";
+ const entry = map.get(key) ?? { key, tokens: 0, cost: 0, taskCount: 0 };
+ entry.tokens +=
+ r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens;
+ entry.cost += estimateCost(r);
+ map.set(key, entry);
+ }
+ return [...map.values()].sort((a, b) => b.cost - a.cost);
+}
+
+// Per-(hour, model) rows → 24 fixed buckets (0..23). Hours with no activity
+// stay in the list as empty rows so the bar chart axis stays continuous.
+export function aggregateCostByHour(rows: RuntimeUsageByHour[]): CostByKey[] {
+ const buckets = new Map<number, CostByKey>();
+ for (let h = 0; h < 24; h++) {
+ buckets.set(h, { key: String(h), tokens: 0, cost: 0, taskCount: 0 });
+ }
+ for (const r of rows) {
+ const entry = buckets.get(r.hour);
+ if (!entry) continue;
+ entry.tokens +=
+ r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens;
+ entry.cost += estimateCost(r);
+ entry.taskCount += r.task_count;
+ }
+ return [...buckets.values()];
+}
+
+// "Cost · 30D" KPI hint: percentage delta vs. the immediately prior window
+// of equal length. Returns null when there's no comparable prior data
+// (caller renders nothing rather than a misleading "+∞%").
+// Sum of estimated cost over the trailing window
+// [today − offsetDays − daysBack, today − offsetDays).
+// `offsetDays = 0, daysBack = 7` → last 7 days.
+// `offsetDays = 7, daysBack = 7` → the 7 days *before* the last 7 (the
+// "previous" window for the runtime-list ↑/↓ delta).
+//
+// Walks the same daily-grain `RuntimeUsage` rows that `aggregateByDate` uses,
+// so the runtime-list cost stays consistent with the runtime-detail KPIs
+// (and crucially, hits the same TanStack Query cache key).
+export function computeCostInWindow(
+ rows: readonly RuntimeUsage[],
+ daysBack: number,
+ offsetDays: number = 0,
+): number {
+ const now = new Date();
+ const end = new Date(now);
+ end.setDate(now.getDate() - offsetDays);
+ const start = new Date(now);
+ start.setDate(now.getDate() - offsetDays - daysBack);
+ const isoEnd = end.toISOString().slice(0, 10);
+ const isoStart = start.toISOString().slice(0, 10);
+ let total = 0;
+ for (const r of rows) {
+ if (r.date >= isoStart && r.date < isoEnd) total += estimateCost(r);
+ }
+ return total;
+}
+
+export function pctChange(current: number, previous: number): number | null {
+ if (previous <= 0) return null;
+ return Math.round(((current - previous) / previous) * 100);
}
diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsx
index 5cfcd62c01..cf8d86f3ce 100644
--- a/packages/views/skills/components/skills-page.tsx
+++ b/packages/views/skills/components/skills-page.tsx
@@ -82,26 +82,29 @@ function SourceCell({
label = "From Skills.sh";
}
+ // Two grid cells: leading icon track, then the text block. The icon needs
+ // `self-start` + a 1-line top inset so it lands on the top text row instead
+ // of the cell's vertical middle (the cell is 2-line when `creator` exists).
return (
- <div className="min-w-0">
- {/* `flex min-w-0` (NOT inline-flex) so truncate on the inner span fires
- when the label is longer than the grid cell. */}
- <div className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
- {icon}
- <span className="min-w-0 truncate">{label}</span>
- </div>
- {creator && (
- <div className="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
- <ActorAvatar
- name={creator.name}
- initials={creator.name.slice(0, 2).toUpperCase()}
- avatarUrl={creator.avatar_url}
- size={14}
- />
- <span className="min-w-0 truncate">by {creator.name}</span>
+ <>
+ <span className="self-start pt-[3px] text-muted-foreground">{icon}</span>
+ <div className="min-w-0">
+ <div className="min-w-0 truncate text-xs text-muted-foreground">
+ {label}
</div>
- )}
- </div>
+ {creator && (
+ <div className="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
+ <ActorAvatar
+ name={creator.name}
+ initials={creator.name.slice(0, 2).toUpperCase()}
+ avatarUrl={creator.avatar_url}
+ size={14}
+ />
+ <span className="min-w-0 truncate">by {creator.name}</span>
+ </div>
+ )}
+ </div>
+ </>
);
}
@@ -148,8 +151,24 @@ function AgentAssignees({ agents }: { agents: Agent[] }) {
// Row + header
// ---------------------------------------------------------------------------
+// Source column has a leading 12px icon (HardDrive / Download / Pencil) that
+// would otherwise push its text 18px right of the column header, so we extract
+// the icon into its own 0.875rem track. `<SourceCell>` returns two cells (icon
+// + body) and the header inserts a placeholder cell to match.
+//
+// Same pattern as Agents (avatar) and Runtimes (icon-box, Health dot) — header
+// label and row primary text share the same x without per-column padding hacks.
+// Responsive column strategy:
+// <md → Name + Used by + Chevron (drop Source / Updated to free room)
+// md+ → adds Source · Added by + Updated
+// Source icon leading slot (0.875rem) is part of the Source group, hidden
+// together at <md. Each visible column uses minmax(0,…fr) so it can shrink
+// and the cell content (with min-w-0 + truncate) trims gracefully instead
+// of overflowing into adjacent cells.
const ROW_GRID =
- "grid grid-cols-[minmax(0,1.6fr)_minmax(0,0.8fr)_minmax(0,1.2fr)_minmax(0,6rem)_auto] items-center gap-4";
+ "grid items-center gap-4 " +
+ "grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_auto] " +
+ "md:grid-cols-[minmax(0,1.6fr)_minmax(0,0.8fr)_0.875rem_minmax(0,1.2fr)_minmax(0,6rem)_auto]";
function SkillRow({
skill,
@@ -204,8 +223,12 @@ function SkillRow({
<div className="min-w-0">
<AgentAssignees agents={agents} />
</div>
- <SourceCell skill={skill} creator={creator} runtime={runtime} />
- <div className="min-w-0 whitespace-nowrap text-xs text-muted-foreground">
+ {/* Source group (icon + label) — md+. The icon is its own grid cell
+ for header alignment; both hide together at <md. */}
+ <span className="hidden md:contents">
+ <SourceCell skill={skill} creator={creator} runtime={runtime} />
+ </span>
+ <div className="hidden min-w-0 whitespace-nowrap text-xs text-muted-foreground md:block">
{timeAgo(skill.updated_at)}
</div>
<ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-muted-foreground" />
@@ -220,8 +243,12 @@ function ListColumnHeader() {
>
<span>Name</span>
<span>Used by</span>
- <span>Source · Added by</span>
- <span>Updated</span>
+ {/* Source icon leading slot — empty in header so the label below
+ aligns with the row's "From X" / "Created manually" text.
+ Hidden together with the Source label at <md. */}
+ <span aria-hidden className="hidden md:block" />
+ <span className="hidden md:block">Source · Added by</span>
+ <span className="hidden md:block">Updated</span>
<span className="w-4" />
</div>
);
@@ -260,6 +287,19 @@ function PageHeaderBar({
{totalCount}
</span>
)}
+ {/* Tagline next to the title — single sentence + docs link. Hidden
+ below md so it never collides with the title on narrow screens. */}
+ <p className="ml-2 hidden text-xs text-muted-foreground md:block">
+ Instructions any agent in this workspace can use.{" "}
+ <a
+ href="https://multica.ai/docs/skills"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline decoration-muted-foreground/30 underline-offset-4 transition-colors hover:text-foreground"
+ >
+ Learn more →
+ </a>
+ </p>
</div>
<Button type="button" size="sm" onClick={onCreate}>
<Plus className="h-3 w-3" />
@@ -507,35 +547,10 @@ export default function SkillsPage() {
</div>
)}
- {/* Page body — padding here keeps the card from touching the chrome,
- and `gap-4` separates the intro block from the table card. */}
+ {/* Page body — padding here keeps the card from touching the chrome.
+ The "what is a skill" tagline now lives in the page header (right
+ of the title); body starts directly with the table card. */}
<div className="flex flex-1 min-h-0 flex-col gap-4 p-6">
- {!showEmpty && (
- <div className="space-y-3 pl-4">
- <p className="text-base text-foreground">
- Instructions any agent in this workspace can use.{" "}
- <a
- href="https://multica.ai/docs/skills"
- target="_blank"
- rel="noopener noreferrer"
- className="text-xs text-muted-foreground underline decoration-muted-foreground/30 underline-offset-4 transition-colors hover:text-foreground"
- >
- Learn more about Skills →
- </a>
- </p>
- <div className="max-w-3xl rounded-r-md border-l-2 border-l-brand bg-brand/5 px-4 py-3 text-xs leading-relaxed text-muted-foreground">
- <span className="font-medium text-foreground">
- Shared with your workspace.
- </span>{" "}
- Anyone can create a skill, import one from a URL, or copy one
- from their local runtime — and every agent can use it.{" "}
- <span className="font-semibold text-brand">
- Local runtime skills stay private until you copy one here.
- </span>
- </div>
- </div>
- )}
-
{showEmpty ? (
<div className="flex flex-1 items-center justify-center">
<EmptyState onCreate={() => setCreateOpen(true)} />
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index c60e5acf20..b2a9d9e631 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -384,6 +384,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Put("/", h.UpdateAgent)
r.Post("/archive", h.ArchiveAgent)
r.Post("/restore", h.RestoreAgent)
+ r.Post("/cancel-tasks", h.CancelAgentTasks)
r.Get("/tasks", h.ListAgentTasks)
r.Get("/skills", h.ListAgentSkills)
r.Put("/skills", h.SetAgentSkills)
@@ -416,6 +417,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.ListAgentRuntimes)
r.Route("/{runtimeId}", func(r chi.Router) {
r.Get("/usage", h.GetRuntimeUsage)
+ r.Get("/usage/by-agent", h.GetRuntimeUsageByAgent)
+ r.Get("/usage/by-hour", h.GetRuntimeUsageByHour)
r.Get("/activity", h.GetRuntimeTaskActivity)
r.Post("/update", h.InitiateUpdate)
r.Get("/update/{updateId}", h.GetUpdate)
@@ -432,6 +435,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Tasks (user-facing, with ownership check)
r.Post("/api/tasks/{taskId}/cancel", h.CancelTaskByUser)
+ // Workspace-wide agent task snapshot for presence derivation:
+ // every active task + each agent's most recent terminal task.
+ r.Get("/api/agent-task-snapshot", h.ListWorkspaceAgentTaskSnapshot)
+
+ // Workspace-wide daily agent activity (last 30d, anchored on
+ // completed_at). Backs the Agents-list sparkline (trailing 7d
+ // slice) AND the agent detail "Last 30 days" panel.
+ r.Get("/api/agent-activity-30d", h.GetWorkspaceAgentActivity30d)
+
+ // Workspace-wide 30-day run counts per agent for the Agents-list RUNS column.
+ r.Get("/api/agent-run-counts", h.GetWorkspaceAgentRunCounts)
+
r.Route("/api/chat/sessions", func(r chi.Router) {
r.Post("/", h.CreateChatSession)
r.Get("/", h.ListChatSessions)
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 656dae5290..9950802339 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -649,8 +649,11 @@ func (h *Handler) ArchiveAgent(w http.ResponseWriter, r *http.Request) {
return
}
- // Cancel all pending/active tasks for this agent.
- if err := h.Queries.CancelAgentTasksByAgent(r.Context(), agent.ID); err != nil {
+ // Cancel all pending/active tasks for this agent. Discard the returned
+ // rows here — the agent:archived event below already triggers a full
+ // active-tasks invalidation on every connected client, so per-task
+ // task:cancelled events would be redundant noise.
+ if _, err := h.Queries.CancelAgentTasksByAgent(r.Context(), agent.ID); err != nil {
slog.Warn("cancel agent tasks on archive failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
}
@@ -692,6 +695,44 @@ func (h *Handler) RestoreAgent(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+// CancelAgentTasks bulk-cancels every active task (queued/dispatched/running)
+// belonging to an agent. Powers the agents-list "Cancel all tasks" row
+// action. Same permission gate as archive (canManageAgent — owner or
+// workspace admin/owner). Each cancelled row triggers a task:cancelled WS
+// event so connected clients clear their live cards immediately.
+//
+// Note: a `running` task on the daemon side won't actually halt for up to
+// ~5 seconds (daemon polls GetTaskStatus on that interval). The DB row is
+// marked cancelled instantly, but the child process keeps going briefly;
+// see daemon/daemon.go:919-942 for the polling loop. Surface this in the
+// confirm-dialog copy so users aren't surprised by trailing transcript
+// lines.
+type cancelAgentTasksResponse struct {
+ Cancelled int `json:"cancelled"`
+}
+
+func (h *Handler) CancelAgentTasks(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ agent, ok := h.loadAgentForUser(w, r, id)
+ if !ok {
+ return
+ }
+ if !h.canManageAgent(w, r, agent) {
+ return
+ }
+
+ cancelled, err := h.TaskService.CancelTasksForAgent(r.Context(), parseUUID(id))
+ if err != nil {
+ slog.Warn("cancel agent tasks failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
+ writeError(w, http.StatusInternalServerError, "failed to cancel tasks")
+ return
+ }
+
+ slog.Info("agent tasks cancelled",
+ append(logger.RequestAttrs(r), "agent_id", id, "count", len(cancelled))...)
+ writeJSON(w, http.StatusOK, cancelAgentTasksResponse{Cancelled: len(cancelled)})
+}
+
func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
agent, ok := h.loadAgentForUser(w, r, id)
@@ -712,3 +753,105 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+
+// AgentActivityBucket is one day-bucketed throughput sample for the
+// Agents-list ACTIVITY sparkline. bucket_at is midnight UTC of the day.
+type AgentActivityBucket struct {
+ AgentID string `json:"agent_id"`
+ BucketAt string `json:"bucket_at"`
+ TaskCount int32 `json:"task_count"`
+ FailedCount int32 `json:"failed_count"`
+}
+
+// AgentRunCount is the trailing-30-day total task run count per agent,
+// powering the Agents-list RUNS column.
+type AgentRunCount struct {
+ AgentID string `json:"agent_id"`
+ RunCount int32 `json:"run_count"`
+}
+
+// GetWorkspaceAgentRunCounts returns 30-day total run counts for every
+// agent in the workspace. Same single-fetch pattern as live-tasks /
+// activity to keep the Agents list cheap regardless of agent count.
+func (h *Handler) GetWorkspaceAgentRunCounts(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ return
+ }
+
+ rows, err := h.Queries.GetWorkspaceAgentRunCounts(r.Context(), parseUUID(workspaceID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to get agent run counts")
+ return
+ }
+
+ resp := make([]AgentRunCount, len(rows))
+ for i, row := range rows {
+ resp[i] = AgentRunCount{
+ AgentID: uuidToString(row.AgentID),
+ RunCount: row.RunCount,
+ }
+ }
+
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// GetWorkspaceAgentActivity30d returns per-agent daily task counts for the
+// last 30 days, anchored on completed_at. Single workspace-wide read backs
+// both the Agents list sparkline (uses the trailing 7 buckets) and the
+// agent detail "Last 30 days" panel (uses all 30) — one fetch is cheaper
+// than two. Front-end fills missing days with zero; the back-end omits
+// empty buckets to keep the response small.
+func (h *Handler) GetWorkspaceAgentActivity30d(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ return
+ }
+
+ rows, err := h.Queries.GetWorkspaceAgentActivity30d(r.Context(), parseUUID(workspaceID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to get agent activity")
+ return
+ }
+
+ resp := make([]AgentActivityBucket, len(rows))
+ for i, row := range rows {
+ resp[i] = AgentActivityBucket{
+ AgentID: uuidToString(row.AgentID),
+ BucketAt: timestampToString(row.Bucket),
+ TaskCount: row.TaskCount,
+ FailedCount: row.FailedCount,
+ }
+ }
+
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// ListWorkspaceAgentTaskSnapshot returns the task data the front-end needs to
+// derive each agent's presence: every active task (queued/dispatched/running)
+// plus each agent's most recent OUTCOME task (completed/failed only). Cancelled
+// tasks are excluded from the outcome half by design — cancel is a procedural
+// signal ("attempt aborted"), not an outcome, so it must not mask a prior
+// failure. The front-end picks "active wins, else latest outcome"; a failed
+// outcome stays sticky until the user starts a new task or one succeeds.
+// Per-agent filtering happens in the front-end against this workspace-wide
+// snapshot.
+func (h *Handler) ListWorkspaceAgentTaskSnapshot(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ return
+ }
+
+ tasks, err := h.Queries.ListWorkspaceAgentTaskSnapshot(r.Context(), parseUUID(workspaceID))
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent task snapshot")
+ return
+ }
+
+ resp := make([]AgentTaskResponse, len(tasks))
+ for i, t := range tasks {
+ resp[i] = taskToResponse(t)
+ }
+
+ writeJSON(w, http.StatusOK, resp)
+}
diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.go
index d777067027..53c92b1158 100644
--- a/server/internal/handler/agent_test.go
+++ b/server/internal/handler/agent_test.go
@@ -8,6 +8,138 @@ import (
"testing"
)
+// TestListWorkspaceAgentTaskSnapshot covers the agent presence snapshot endpoint:
+// every active task (queued/dispatched/running) PLUS each agent's most recent
+// OUTCOME task (completed/failed only). Cancelled tasks are excluded by design
+// from the outcome half — they're a procedural signal, not an outcome, and
+// must NOT mask a prior failure.
+//
+// The fixtures cover every branch the SQL must classify:
+// - actives are always returned, no dedup
+// - outcomes are deduped to "latest per agent" by completed_at
+// - the OLD 2-minute window must be irrelevant (a 5-minute-old failure is
+// still returned if it's the latest outcome)
+// - cancelled rows are NEVER returned, even when they are temporally newer
+// than a failure — this is what keeps the failed signal sticky after the
+// user cancels their queued retry
+func TestListWorkspaceAgentTaskSnapshot(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ // Three agents so we can verify per-agent semantics independently.
+ agentA := createHandlerTestAgent(t, "snapshot-agent-a", []byte(`{}`))
+ agentB := createHandlerTestAgent(t, "snapshot-agent-b", []byte(`{}`))
+ agentC := createHandlerTestAgent(t, "snapshot-agent-c", []byte(`{}`))
+
+ type taskFixture struct {
+ agentID string
+ status string
+ completedAt string // SQL expression; "" for NULL
+ label string
+ }
+ fixtures := []taskFixture{
+ // Agent A — actives + a newer completed supersedes an older failed.
+ {agentA, "queued", "", "A.queued"},
+ {agentA, "dispatched", "", "A.dispatched"},
+ {agentA, "running", "", "A.running"},
+ {agentA, "failed", "now() - interval '10 minutes'", "A.old_failed"},
+ {agentA, "completed", "now() - interval '30 seconds'", "A.latest_completed"},
+
+ // Agent B — old failure with no later outcome stays visible (no
+ // time window).
+ {agentB, "failed", "now() - interval '5 minutes'", "B.stale_failed_kept"},
+
+ // Agent C — failure followed by a NEWER cancelled. The cancelled
+ // must be skipped by the SQL filter so the failure remains visible.
+ // This is the scenario where a user fails, then cancels their
+ // queued retry to debug.
+ {agentC, "failed", "now() - interval '5 minutes'", "C.failure"},
+ {agentC, "cancelled", "now() - interval '30 seconds'", "C.newer_cancelled_must_be_ignored"},
+ }
+
+ insertedIDs := make([]string, 0, len(fixtures))
+ for _, f := range fixtures {
+ var id string
+ var query string
+ if f.completedAt == "" {
+ query = `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority)
+ VALUES ($1, $2, $3, 0) RETURNING id`
+ } else {
+ query = `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, completed_at)
+ VALUES ($1, $2, $3, 0, ` + f.completedAt + `) RETURNING id`
+ }
+ if err := testPool.QueryRow(ctx, query, f.agentID, testRuntimeID, f.status).Scan(&id); err != nil {
+ t.Fatalf("insert %s: %v", f.label, err)
+ }
+ insertedIDs = append(insertedIDs, id)
+ }
+ t.Cleanup(func() {
+ for _, id := range insertedIDs {
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, id)
+ }
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodGet, "/api/agent-task-snapshot", nil)
+ testHandler.ListWorkspaceAgentTaskSnapshot(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListWorkspaceAgentTaskSnapshot: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var tasks []AgentTaskResponse
+ if err := json.NewDecoder(w.Body).Decode(&tasks); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+
+ // Per-agent breakdown so leftover tasks from other tests in this package
+ // don't pollute the assertions.
+ type key struct{ agent, status string }
+ counts := map[key]int{}
+ for _, task := range tasks {
+ if task.AgentID != agentA && task.AgentID != agentB && task.AgentID != agentC {
+ continue
+ }
+ counts[key{task.AgentID, task.Status}]++
+ }
+
+ wantCounts := map[key]int{
+ // Agent A: 3 actives + the latest outcome (completed). The older
+ // failed must be excluded by DISTINCT ON.
+ {agentA, "queued"}: 1,
+ {agentA, "dispatched"}: 1,
+ {agentA, "running"}: 1,
+ {agentA, "completed"}: 1,
+ // Agent B: just the failed outcome.
+ {agentB, "failed"}: 1,
+ // Agent C: the failed outcome must survive the temporally newer
+ // cancellation — that's the whole point of excluding cancelled
+ // from the outcome half.
+ {agentC, "failed"}: 1,
+ }
+ for k, expected := range wantCounts {
+ if got := counts[k]; got != expected {
+ t.Errorf("agent=%s status=%s: expected %d, got %d", k.agent, k.status, expected, got)
+ }
+ }
+
+ // The OLD failed terminal on agent A must be excluded.
+ if counts[key{agentA, "failed"}] != 0 {
+ t.Errorf("agent A old failed must be superseded by newer completed; got %d", counts[key{agentA, "failed"}])
+ }
+
+ // No cancelled row may ever appear in the snapshot — they're filtered at
+ // SQL level so the front-end's "cancel doesn't mask failure" rule lands
+ // without any front-end logic.
+ for _, agentID := range []string{agentA, agentB, agentC} {
+ if counts[key{agentID, "cancelled"}] != 0 {
+ t.Errorf("agent %s: cancelled rows must be excluded from snapshot; got %d",
+ agentID, counts[key{agentID, "cancelled"}])
+ }
+ }
+}
+
func TestCreateAgent_RejectsDuplicateName(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 0ee1be8533..ca06225247 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -160,6 +160,117 @@ func (h *Handler) GetRuntimeTaskActivity(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, resp)
}
+// RuntimeUsageByAgentResponse is one (agent, model) row of "Cost by agent".
+// Model stays on the wire because cost is computed client-side from a model
+// pricing table, intentionally not stored server-side so pricing changes
+// don't require a back-fill. The client groups by agent_id and sums.
+type RuntimeUsageByAgentResponse struct {
+ AgentID string `json:"agent_id"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheReadTokens int64 `json:"cache_read_tokens"`
+ CacheWriteTokens int64 `json:"cache_write_tokens"`
+ TaskCount int32 `json:"task_count"`
+}
+
+// GetRuntimeUsageByAgent returns per-agent token aggregates for a runtime
+// since the cutoff window. Drives the runtime-detail "Cost by agent" tab.
+func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), parseUUID(runtimeID))
+ if err != nil {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ return
+ }
+
+ if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
+ return
+ }
+
+ since := parseSinceParam(r, 30)
+
+ rows, err := h.Queries.ListRuntimeUsageByAgent(r.Context(), db.ListRuntimeUsageByAgentParams{
+ RuntimeID: parseUUID(runtimeID),
+ Since: since,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list usage by agent")
+ return
+ }
+
+ resp := make([]RuntimeUsageByAgentResponse, len(rows))
+ for i, row := range rows {
+ resp[i] = RuntimeUsageByAgentResponse{
+ AgentID: uuidToString(row.AgentID),
+ Model: row.Model,
+ InputTokens: row.InputTokens,
+ OutputTokens: row.OutputTokens,
+ CacheReadTokens: row.CacheReadTokens,
+ CacheWriteTokens: row.CacheWriteTokens,
+ TaskCount: row.TaskCount,
+ }
+ }
+
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// RuntimeUsageByHourResponse is one (hour, model) row. Hours with zero
+// activity are omitted by the SQL — clients fill the gap to render a
+// continuous 0..23 axis. Model is preserved for client-side cost math.
+type RuntimeUsageByHourResponse struct {
+ Hour int `json:"hour"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheReadTokens int64 `json:"cache_read_tokens"`
+ CacheWriteTokens int64 `json:"cache_write_tokens"`
+ TaskCount int32 `json:"task_count"`
+}
+
+// GetRuntimeUsageByHour returns hourly (0..23) token aggregates for a
+// runtime since the cutoff window. Drives the "By hour" tab.
+func (h *Handler) GetRuntimeUsageByHour(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+
+ rt, err := h.Queries.GetAgentRuntime(r.Context(), parseUUID(runtimeID))
+ if err != nil {
+ writeError(w, http.StatusNotFound, "runtime not found")
+ return
+ }
+
+ if _, ok := h.requireWorkspaceMember(w, r, uuidToString(rt.WorkspaceID), "runtime not found"); !ok {
+ return
+ }
+
+ since := parseSinceParam(r, 30)
+
+ rows, err := h.Queries.GetRuntimeUsageByHour(r.Context(), db.GetRuntimeUsageByHourParams{
+ RuntimeID: parseUUID(runtimeID),
+ Since: since,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to get usage by hour")
+ return
+ }
+
+ resp := make([]RuntimeUsageByHourResponse, len(rows))
+ for i, row := range rows {
+ resp[i] = RuntimeUsageByHourResponse{
+ Hour: int(row.Hour),
+ Model: row.Model,
+ InputTokens: row.InputTokens,
+ OutputTokens: row.OutputTokens,
+ CacheReadTokens: row.CacheReadTokens,
+ CacheWriteTokens: row.CacheWriteTokens,
+ TaskCount: row.TaskCount,
+ }
+ }
+
+ writeJSON(w, http.StatusOK, resp)
+}
+
// GetWorkspaceUsageByDay returns daily token usage aggregated by model for the workspace.
func (h *Handler) GetWorkspaceUsageByDay(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 09cfb3efd2..4ce05812b7 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -173,6 +173,27 @@ func (s *TaskService) CancelTasksForIssue(ctx context.Context, issueID pgtype.UU
return nil
}
+// CancelTasksForAgent cancels every active task belonging to an agent
+// (queued + dispatched + running), reconciles the agent's status, and
+// broadcasts task:cancelled events. Used by the agent-level "Cancel all
+// tasks" action — same shape as CancelTasksForIssue but scoped on agent_id.
+//
+// Returns the cancelled rows so callers can report counts / log them.
+func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
+ cancelled, err := s.Queries.CancelAgentTasksByAgent(ctx, agentID)
+ if err != nil {
+ return nil, err
+ }
+ for _, t := range cancelled {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ }
+ // Reconcile once after the loop — agent transitions from
+ // working→available based on remaining task counts, no need to call
+ // per row (the rows we just cancelled all belong to the same agent).
+ s.ReconcileAgentStatus(ctx, agentID)
+ return cancelled, nil
+}
+
// CancelTasksByTriggerComment cancels active tasks whose trigger is the given
// comment. Called from DeleteComment so an agent does not run with the
// now-deleted content already embedded in its prompt. Must be invoked BEFORE
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 923950afbc..868b36a7f3 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -89,15 +89,60 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
return i, err
}
-const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :exec
+const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
-SET status = 'cancelled'
+SET status = 'cancelled', completed_at = now()
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running')
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at
`
-func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, cancelAgentTasksByAgent, agentID)
- return err
+// Bulk-cancel every active (queued/dispatched/running) task for an agent.
+// Returns the affected rows so callers can broadcast task:cancelled events.
+// Mirrors the shape of CancelAgentTasksByIssue / CancelAgentTasksByIssueAndAgent
+// (also :many + RETURNING + completed_at) so the three sibling cancel paths
+// behave consistently.
+func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelAgentTasksByAgent, agentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
}
const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
@@ -872,6 +917,107 @@ func (q *Queries) GetLastTaskSession(ctx context.Context, arg GetLastTaskSession
return i, err
}
+const getWorkspaceAgentActivity30d = `-- name: GetWorkspaceAgentActivity30d :many
+SELECT
+ atq.agent_id,
+ DATE_TRUNC('day', atq.completed_at)::timestamptz AS bucket,
+ COUNT(*)::int AS task_count,
+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count
+FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+WHERE a.workspace_id = $1
+ AND atq.completed_at IS NOT NULL
+ AND atq.completed_at > now() - INTERVAL '30 days'
+GROUP BY atq.agent_id, bucket
+ORDER BY atq.agent_id, bucket
+`
+
+type GetWorkspaceAgentActivity30dRow struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ Bucket pgtype.Timestamptz `json:"bucket"`
+ TaskCount int32 `json:"task_count"`
+ FailedCount int32 `json:"failed_count"`
+}
+
+// Returns per-agent daily activity buckets for the last 30 days. Single
+// workspace-wide read backs both surfaces:
+// - Agents list ACTIVITY column — uses only the trailing 7 buckets
+// - Agent detail "Last 30 days" panel — uses the full 30
+//
+// 30 days contains 7 days, so one fetch + a client-side .slice(-7) wins
+// over fetching twice. Days with no completion produce no row; the
+// front-end zero-fills.
+//
+// Anchored on completed_at (not created_at) because the sparkline answers
+// "what did this agent produce?" not "what was queued at it?". A task that's
+// still in flight has no completed_at and contributes nothing here — that's
+// correct: in-flight tasks are surfaced via the live presence indicator,
+// not the historical trend.
+func (q *Queries) GetWorkspaceAgentActivity30d(ctx context.Context, workspaceID pgtype.UUID) ([]GetWorkspaceAgentActivity30dRow, error) {
+ rows, err := q.db.Query(ctx, getWorkspaceAgentActivity30d, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []GetWorkspaceAgentActivity30dRow{}
+ for rows.Next() {
+ var i GetWorkspaceAgentActivity30dRow
+ if err := rows.Scan(
+ &i.AgentID,
+ &i.Bucket,
+ &i.TaskCount,
+ &i.FailedCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const getWorkspaceAgentRunCounts = `-- name: GetWorkspaceAgentRunCounts :many
+SELECT
+ atq.agent_id,
+ COUNT(*)::int AS run_count
+FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+WHERE a.workspace_id = $1
+ AND atq.created_at > now() - INTERVAL '30 days'
+GROUP BY atq.agent_id
+`
+
+type GetWorkspaceAgentRunCountsRow struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ RunCount int32 `json:"run_count"`
+}
+
+// Total task runs per agent over the trailing 30 days, used by the Agents
+// list RUNS column. 30-day window keeps the count meaningful (a long-dormant
+// agent shouldn't show "5,420 runs from 2 years ago") and keeps the scan
+// bounded as the workspace ages.
+func (q *Queries) GetWorkspaceAgentRunCounts(ctx context.Context, workspaceID pgtype.UUID) ([]GetWorkspaceAgentRunCountsRow, error) {
+ rows, err := q.db.Query(ctx, getWorkspaceAgentRunCounts, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []GetWorkspaceAgentRunCountsRow{}
+ for rows.Next() {
+ var i GetWorkspaceAgentRunCountsRow
+ if err := rows.Scan(&i.AgentID, &i.RunCount); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const hasActiveTaskForIssue = `-- name: HasActiveTaskForIssue :one
SELECT count(*) > 0 AS has_active FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')
@@ -1216,6 +1362,86 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
return items, nil
}
+const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.last_heartbeat_at FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+WHERE a.workspace_id = $1
+ AND atq.status IN ('queued', 'dispatched', 'running')
+
+UNION ALL
+
+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.last_heartbeat_at FROM (
+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.last_heartbeat_at
+ FROM agent_task_queue atq
+ JOIN agent a ON a.id = atq.agent_id
+ WHERE a.workspace_id = $1
+ AND atq.status IN ('completed', 'failed')
+ ORDER BY atq.agent_id, atq.completed_at DESC NULLS LAST
+) t
+`
+
+// Returns the tasks needed to derive each agent's current presence:
+// - All active tasks (queued / dispatched / running) — for working signal + counts
+// - Each agent's most recent OUTCOME task (completed / failed) — for sticky
+// failed signal
+//
+// The front-end picks "active wins, else latest outcome" — see derive-presence.ts.
+//
+// Cancelled tasks are excluded from the outcome half on purpose: cancel is a
+// procedural signal ("attempt aborted"), not an outcome. It tells us nothing
+// about whether the agent works, so it must NOT be allowed to mask a prior
+// failure. Concretely: if an agent fails and then the user cancels the queued
+// retry (or the parent issue closes and cascades cancels), the failed signal
+// has to stay red. Only a real success (completed) or a fresh attempt (active)
+// clears it.
+//
+// No UI windows in SQL: stickiness is decided by "is the latest outcome a
+// failure?", not a 2-minute clock. JOINs agent because agent_task_queue has
+// no workspace_id column.
+func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, listWorkspaceAgentTaskSnapshot, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const recoverOrphanedTasksForRuntime = `-- name: RecoverOrphanedTasksForRuntime :many
UPDATE agent_task_queue
SET status = 'failed',
diff --git a/server/pkg/db/generated/runtime_usage.sql.go b/server/pkg/db/generated/runtime_usage.sql.go
index eee0280fc9..e5646914ef 100644
--- a/server/pkg/db/generated/runtime_usage.sql.go
+++ b/server/pkg/db/generated/runtime_usage.sql.go
@@ -44,6 +44,71 @@ func (q *Queries) GetRuntimeTaskHourlyActivity(ctx context.Context, runtimeID pg
return items, nil
}
+const getRuntimeUsageByHour = `-- name: GetRuntimeUsageByHour :many
+SELECT
+ EXTRACT(HOUR FROM tu.created_at)::int AS hour,
+ tu.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(DISTINCT tu.task_id)::int AS task_count
+FROM task_usage tu
+JOIN agent_task_queue atq ON atq.id = tu.task_id
+WHERE atq.runtime_id = $1
+ AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
+GROUP BY EXTRACT(HOUR FROM tu.created_at), tu.model
+ORDER BY hour, tu.model
+`
+
+type GetRuntimeUsageByHourParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+type GetRuntimeUsageByHourRow struct {
+ Hour int32 `json:"hour"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheReadTokens int64 `json:"cache_read_tokens"`
+ CacheWriteTokens int64 `json:"cache_write_tokens"`
+ TaskCount int32 `json:"task_count"`
+}
+
+// Per-(hour, model) token aggregates (hour ∈ 0..23) for a runtime since a
+// cutoff. Powers the "By hour" tab — shows when in the day this runtime is
+// doing real work, with model preserved for client-side cost calculation
+// (same reason as ListRuntimeUsageByAgent above). Hours with zero activity
+// are omitted; the client fills the 24-bucket axis.
+func (q *Queries) GetRuntimeUsageByHour(ctx context.Context, arg GetRuntimeUsageByHourParams) ([]GetRuntimeUsageByHourRow, error) {
+ rows, err := q.db.Query(ctx, getRuntimeUsageByHour, arg.RuntimeID, arg.Since)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []GetRuntimeUsageByHourRow{}
+ for rows.Next() {
+ var i GetRuntimeUsageByHourRow
+ if err := rows.Scan(
+ &i.Hour,
+ &i.Model,
+ &i.InputTokens,
+ &i.OutputTokens,
+ &i.CacheReadTokens,
+ &i.CacheWriteTokens,
+ &i.TaskCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listRuntimeUsage = `-- name: ListRuntimeUsage :many
SELECT
DATE(tu.created_at) AS date,
@@ -107,3 +172,69 @@ func (q *Queries) ListRuntimeUsage(ctx context.Context, arg ListRuntimeUsagePara
}
return items, nil
}
+
+const listRuntimeUsageByAgent = `-- name: ListRuntimeUsageByAgent :many
+SELECT
+ atq.agent_id,
+ tu.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(DISTINCT tu.task_id)::int AS task_count
+FROM task_usage tu
+JOIN agent_task_queue atq ON atq.id = tu.task_id
+WHERE atq.runtime_id = $1
+ AND tu.created_at >= DATE_TRUNC('day', $2::timestamptz)
+GROUP BY atq.agent_id, tu.model
+ORDER BY atq.agent_id, tu.model
+`
+
+type ListRuntimeUsageByAgentParams struct {
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+type ListRuntimeUsageByAgentRow struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CacheReadTokens int64 `json:"cache_read_tokens"`
+ CacheWriteTokens int64 `json:"cache_write_tokens"`
+ TaskCount int32 `json:"task_count"`
+}
+
+// Per-(agent, model) token aggregates for a runtime since a cutoff. Powers
+// the runtime-detail "Cost by agent" tab. task_usage only carries task_id,
+// so we join the queue to expose agent_id. The model dimension is kept on
+// purpose: cost is computed client-side from a per-model pricing table, so
+// collapsing models server-side would erase the information needed to do
+// that arithmetic. The client groups by agent_id and sums cost per agent.
+func (q *Queries) ListRuntimeUsageByAgent(ctx context.Context, arg ListRuntimeUsageByAgentParams) ([]ListRuntimeUsageByAgentRow, error) {
+ rows, err := q.db.Query(ctx, listRuntimeUsageByAgent, arg.RuntimeID, arg.Since)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListRuntimeUsageByAgentRow{}
+ for rows.Next() {
+ var i ListRuntimeUsageByAgentRow
+ if err := rows.Scan(
+ &i.AgentID,
+ &i.Model,
+ &i.InputTokens,
+ &i.OutputTokens,
+ &i.CacheReadTokens,
+ &i.CacheWriteTokens,
+ &i.TaskCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index f07e7571de..cb37db08f7 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -110,10 +110,16 @@ SET status = 'cancelled', completed_at = now()
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')
RETURNING *;
--- name: CancelAgentTasksByAgent :exec
+-- name: CancelAgentTasksByAgent :many
+-- Bulk-cancel every active (queued/dispatched/running) task for an agent.
+-- Returns the affected rows so callers can broadcast task:cancelled events.
+-- Mirrors the shape of CancelAgentTasksByIssue / CancelAgentTasksByIssueAndAgent
+-- (also :many + RETURNING + completed_at) so the three sibling cancel paths
+-- behave consistently.
UPDATE agent_task_queue
-SET status = 'cancelled'
-WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running');
+SET status = 'cancelled', completed_at = now()
+WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running')
+RETURNING *;
-- name: CancelAgentTasksByTriggerComment :many
-- Cancels active tasks whose trigger is the given comment. Called when a
@@ -277,6 +283,81 @@ SELECT * FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('dispatched', 'running')
ORDER BY created_at DESC;
+-- name: GetWorkspaceAgentRunCounts :many
+-- Total task runs per agent over the trailing 30 days, used by the Agents
+-- list RUNS column. 30-day window keeps the count meaningful (a long-dormant
+-- agent shouldn't show "5,420 runs from 2 years ago") and keeps the scan
+-- bounded as the workspace ages.
+SELECT
+ atq.agent_id,
+ COUNT(*)::int AS run_count
+FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+WHERE a.workspace_id = $1
+ AND atq.created_at > now() - INTERVAL '30 days'
+GROUP BY atq.agent_id;
+
+-- name: GetWorkspaceAgentActivity30d :many
+-- Returns per-agent daily activity buckets for the last 30 days. Single
+-- workspace-wide read backs both surfaces:
+-- - Agents list ACTIVITY column — uses only the trailing 7 buckets
+-- - Agent detail "Last 30 days" panel — uses the full 30
+-- 30 days contains 7 days, so one fetch + a client-side .slice(-7) wins
+-- over fetching twice. Days with no completion produce no row; the
+-- front-end zero-fills.
+--
+-- Anchored on completed_at (not created_at) because the sparkline answers
+-- "what did this agent produce?" not "what was queued at it?". A task that's
+-- still in flight has no completed_at and contributes nothing here — that's
+-- correct: in-flight tasks are surfaced via the live presence indicator,
+-- not the historical trend.
+SELECT
+ atq.agent_id,
+ DATE_TRUNC('day', atq.completed_at)::timestamptz AS bucket,
+ COUNT(*)::int AS task_count,
+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count
+FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+WHERE a.workspace_id = $1
+ AND atq.completed_at IS NOT NULL
+ AND atq.completed_at > now() - INTERVAL '30 days'
+GROUP BY atq.agent_id, bucket
+ORDER BY atq.agent_id, bucket;
+
+-- name: ListWorkspaceAgentTaskSnapshot :many
+-- Returns the tasks needed to derive each agent's current presence:
+-- - All active tasks (queued / dispatched / running) — for working signal + counts
+-- - Each agent's most recent OUTCOME task (completed / failed) — for sticky
+-- failed signal
+-- The front-end picks "active wins, else latest outcome" — see derive-presence.ts.
+--
+-- Cancelled tasks are excluded from the outcome half on purpose: cancel is a
+-- procedural signal ("attempt aborted"), not an outcome. It tells us nothing
+-- about whether the agent works, so it must NOT be allowed to mask a prior
+-- failure. Concretely: if an agent fails and then the user cancels the queued
+-- retry (or the parent issue closes and cascades cancels), the failed signal
+-- has to stay red. Only a real success (completed) or a fresh attempt (active)
+-- clears it.
+--
+-- No UI windows in SQL: stickiness is decided by "is the latest outcome a
+-- failure?", not a 2-minute clock. JOINs agent because agent_task_queue has
+-- no workspace_id column.
+SELECT atq.* FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+WHERE a.workspace_id = $1
+ AND atq.status IN ('queued', 'dispatched', 'running')
+
+UNION ALL
+
+SELECT t.* FROM (
+ SELECT DISTINCT ON (atq.agent_id) atq.*
+ FROM agent_task_queue atq
+ JOIN agent a ON a.id = atq.agent_id
+ WHERE a.workspace_id = $1
+ AND atq.status IN ('completed', 'failed')
+ ORDER BY atq.agent_id, atq.completed_at DESC NULLS LAST
+) t;
+
-- name: ListTasksByIssue :many
SELECT * FROM agent_task_queue
WHERE issue_id = $1
diff --git a/server/pkg/db/queries/runtime_usage.sql b/server/pkg/db/queries/runtime_usage.sql
index cdbddd7503..1ee16793ff 100644
--- a/server/pkg/db/queries/runtime_usage.sql
+++ b/server/pkg/db/queries/runtime_usage.sql
@@ -24,3 +24,46 @@ FROM agent_task_queue
WHERE runtime_id = $1 AND started_at IS NOT NULL
GROUP BY hour
ORDER BY hour;
+
+-- name: ListRuntimeUsageByAgent :many
+-- Per-(agent, model) token aggregates for a runtime since a cutoff. Powers
+-- the runtime-detail "Cost by agent" tab. task_usage only carries task_id,
+-- so we join the queue to expose agent_id. The model dimension is kept on
+-- purpose: cost is computed client-side from a per-model pricing table, so
+-- collapsing models server-side would erase the information needed to do
+-- that arithmetic. The client groups by agent_id and sums cost per agent.
+SELECT
+ atq.agent_id,
+ tu.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(DISTINCT tu.task_id)::int AS task_count
+FROM task_usage tu
+JOIN agent_task_queue atq ON atq.id = tu.task_id
+WHERE atq.runtime_id = $1
+ AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
+GROUP BY atq.agent_id, tu.model
+ORDER BY atq.agent_id, tu.model;
+
+-- name: GetRuntimeUsageByHour :many
+-- Per-(hour, model) token aggregates (hour ∈ 0..23) for a runtime since a
+-- cutoff. Powers the "By hour" tab — shows when in the day this runtime is
+-- doing real work, with model preserved for client-side cost calculation
+-- (same reason as ListRuntimeUsageByAgent above). Hours with zero activity
+-- are omitted; the client fills the 24-bucket axis.
+SELECT
+ EXTRACT(HOUR FROM tu.created_at)::int AS hour,
+ tu.model,
+ SUM(tu.input_tokens)::bigint AS input_tokens,
+ SUM(tu.output_tokens)::bigint AS output_tokens,
+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,
+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,
+ COUNT(DISTINCT tu.task_id)::int AS task_count
+FROM task_usage tu
+JOIN agent_task_queue atq ON atq.id = tu.task_id
+WHERE atq.runtime_id = $1
+ AND tu.created_at >= DATE_TRUNC('day', @since::timestamptz)
+GROUP BY EXTRACT(HOUR FROM tu.created_at), tu.model
+ORDER BY hour, tu.model;