Skip to content

The open-source app everyone uses to manage agents at work

feat(ui): refine streamlined workspace surfaces (#12747)

scotttongb1f4910ee577
diff --git a/ui/src/App.activity-routing.test.tsx b/ui/src/App.activity-routing.test.tsx
index 88c1e3c8c7..c1adf64c58 100644
--- a/ui/src/App.activity-routing.test.tsx
+++ b/ui/src/App.activity-routing.test.tsx
@@ -69,6 +69,13 @@ vi.mock("./pages/audit/CompanyActivity", () => ({
},
}));
+vi.mock("./pages/audit/AuditHub", () => ({
+ AuditHub: ({ section }: { section: string }) => {
+ const location = useLocation();
+ return <div>{`AUDIT_${section.toUpperCase()}@${location.pathname}${location.search}`}</div>;
+ },
+}));
+
vi.mock("./pages/Issues", () => ({
Issues: () => {
const location = useLocation();
@@ -152,6 +159,18 @@ describe("App Activity routing (PAP-16302)", () => {
flushSync(() => root.unmount());
});
+ it("serves organization and entity-scoped run history beneath Activity", async () => {
+ const root = renderAppAt(
+ container,
+ "/PAP/activity/runs?entityType=routine&entityId=routine-1",
+ );
+ await waitForRoute(
+ container,
+ "AUDIT_RUNS@/PAP/activity/runs?entityType=routine&entityId=routine-1",
+ );
+ flushSync(() => root.unmount());
+ });
+
it("redirects /:company/audit to Activity with the agent-actions mode preset", async () => {
const root = renderAppAt(container, "/PAP/audit");
await waitForRoute(container, "ACTIVITY_PAGE@/PAP/activity?mode=agents");
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 803188021c..147b6a4645 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -50,6 +50,7 @@ import { Approvals } from "./pages/Approvals";
import { ApprovalDetail } from "./pages/ApprovalDetail";
import { Costs } from "./pages/Costs";
import { CompanyActivity } from "./pages/audit/CompanyActivity";
+import { AuditHub } from "./pages/audit/AuditHub";
import { Inbox } from "./pages/Inbox";
import { WhatNeedsMe } from "./pages/WhatNeedsMe";
import { DecisionQueuePage } from "./pages/DecisionQueuePage";
@@ -325,6 +326,10 @@ function boardRoutes() {
<Route path="approvals/:approvalId" element={<ApprovalDetail />} />
<Route path="costs" element={<Costs />} />
<Route path="activity" element={<CompanyActivity />} />
+ <Route path="activity/runs" element={<AuditHub section="runs" />} />
+ <Route path="activity/costs" element={<AuditHub section="costs" />} />
+ <Route path="activity/budgets" element={<AuditHub section="budgets" />} />
+ <Route path="activity/timeline" element={<AuditHub section="timeline" />} />
{/* `/audit` merged into the single Activity page (PAP-16302). Existing deep
links keep working, preset to the agent-actions scope. */}
<Route path="audit" element={<Navigate to="/activity?mode=agents" replace />} />
diff --git a/ui/src/components/CollectionToolbar.test.tsx b/ui/src/components/CollectionToolbar.test.tsx
new file mode 100644
index 0000000000..61866ed7dd
--- /dev/null
+++ b/ui/src/components/CollectionToolbar.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import { afterEach, describe, expect, it } from "vitest";
+import { CollectionToolbar } from "./CollectionToolbar";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("CollectionToolbar", () => {
+ let container: HTMLDivElement | null = null;
+ let root: ReturnType<typeof createRoot> | null = null;
+
+ afterEach(() => {
+ if (root) flushSync(() => root?.unmount());
+ container?.remove();
+ root = null;
+ container = null;
+ });
+
+ it("keeps collection controls in stable semantic slots", () => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ flushSync(() => {
+ root?.render(
+ <CollectionToolbar
+ ariaLabel="Task list controls"
+ context={<span>Mine</span>}
+ search={<input aria-label="Search tasks" />}
+ controls={<button type="button">Filter</button>}
+ actions={<button type="button">New task</button>}
+ feedback={<span>Status: active</span>}
+ />,
+ );
+ });
+
+ const toolbar = container.querySelector('[role="toolbar"]');
+ expect(toolbar?.getAttribute("aria-label")).toBe("Task list controls");
+ expect(toolbar?.querySelector('[data-slot="collection-toolbar-context"]')?.textContent).toBe("Mine");
+ expect(toolbar?.querySelector('[data-slot="collection-toolbar-search"] input')).not.toBeNull();
+ expect(toolbar?.querySelector('[data-slot="collection-toolbar-controls"]')?.textContent).toBe("Filter");
+ expect(toolbar?.querySelector('[data-slot="collection-toolbar-actions"]')?.textContent).toBe("New task");
+ expect(toolbar?.querySelector('[data-slot="collection-toolbar-feedback"]')?.textContent).toBe("Status: active");
+ });
+
+ it("omits empty optional slots", () => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ flushSync(() => root?.render(<CollectionToolbar search={<span>Search</span>} />));
+
+ expect(container.querySelector('[data-slot="collection-toolbar-context"]')).toBeNull();
+ expect(container.querySelector('[data-slot="collection-toolbar-controls"]')).toBeNull();
+ expect(container.querySelector('[data-slot="collection-toolbar-actions"]')).toBeNull();
+ expect(container.querySelector('[data-slot="collection-toolbar-feedback"]')).toBeNull();
+ });
+});
diff --git a/ui/src/components/CollectionToolbar.tsx b/ui/src/components/CollectionToolbar.tsx
new file mode 100644
index 0000000000..d38369dd05
--- /dev/null
+++ b/ui/src/components/CollectionToolbar.tsx
@@ -0,0 +1,75 @@
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+export interface CollectionToolbarProps {
+ /** Primary context such as tabs, a view title, or a result count. */
+ context?: ReactNode;
+ /** The collection's canonical search control. */
+ search?: ReactNode;
+ /** Filter, sort, column, density, and view controls. */
+ controls?: ReactNode;
+ /** Collection-specific actions such as create or bulk operations. */
+ actions?: ReactNode;
+ /** Optional second row for active-filter chips or selection feedback. */
+ feedback?: ReactNode;
+ className?: string;
+ ariaLabel?: string;
+}
+
+/**
+ * Presentation-only shell for list and board controls.
+ *
+ * State, queries, and control behavior stay with the consuming surface. Keeping
+ * this component slot-based lets Inbox, Tasks, routine runs, and scoped task
+ * lists share geometry without coupling their data models.
+ */
+export function CollectionToolbar({
+ context,
+ search,
+ controls,
+ actions,
+ feedback,
+ className,
+ ariaLabel = "Collection controls",
+}: CollectionToolbarProps) {
+ return (
+ <div
+ data-slot="collection-toolbar"
+ className={cn("flex flex-col gap-2", className)}
+ role="toolbar"
+ aria-label={ariaLabel}
+ >
+ <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center">
+ {context ? (
+ <div data-slot="collection-toolbar-context" className="min-w-0 shrink-0">
+ {context}
+ </div>
+ ) : null}
+ {search ? (
+ <div data-slot="collection-toolbar-search" className="min-w-0 flex-1">
+ {search}
+ </div>
+ ) : null}
+ {(controls || actions) ? (
+ <div className="flex min-w-0 flex-wrap items-center gap-1 sm:ml-auto sm:flex-nowrap">
+ {controls ? (
+ <div data-slot="collection-toolbar-controls" className="flex min-w-0 flex-wrap items-center gap-1">
+ {controls}
+ </div>
+ ) : null}
+ {actions ? (
+ <div data-slot="collection-toolbar-actions" className="flex shrink-0 items-center gap-1">
+ {actions}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ {feedback ? (
+ <div data-slot="collection-toolbar-feedback" className="min-w-0">
+ {feedback}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/ui/src/components/IssueRow.test.tsx b/ui/src/components/IssueRow.test.tsx
index b31dfeca8f..a319063502 100644
--- a/ui/src/components/IssueRow.test.tsx
+++ b/ui/src/components/IssueRow.test.tsx
@@ -122,6 +122,159 @@ describe("IssueRow", () => {
});
});
+ it("uses stable canonical identifier and timestamp columns at the trailing edge", () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <IssueRow
+ issue={createIssue({ identifier: "PAP-42", title: "Canonical task" })}
+ presentation="task"
+ metadata={<span>Live</span>}
+ actions={<button type="button">More</button>}
+ trailingMeta="Updated now"
+ />,
+ );
+ });
+
+ const row = container.querySelector('[data-slot="task-row"]');
+ const leading = row?.querySelector('[data-slot="task-row-leading"]');
+ const title = row?.querySelector('[data-slot="task-row-title"]');
+ const metadata = row?.querySelector('[data-slot="task-row-metadata"]');
+ const identifier = row?.querySelector('[data-slot="task-row-identifier"]');
+ const timestamp = row?.querySelector('[data-slot="task-row-timestamp"]');
+ const actions = row?.querySelector('[data-slot="task-row-actions"]');
+ const link = row?.querySelector('[data-inbox-issue-link]');
+
+ expect(leading?.querySelector("svg")).not.toBeNull();
+ expect(title?.textContent).toContain("Canonical task");
+ expect(metadata?.textContent).toBe("Live");
+ expect(identifier?.textContent).toBe("PAP-42");
+ expect(timestamp?.textContent).toBe("Updated now");
+ expect(actions?.textContent).toBe("More");
+ expect(identifier?.className).toContain("w-20");
+ expect(timestamp?.className).toContain("w-24");
+ if (!link || !metadata || !identifier || !timestamp || !actions) throw new Error("Expected canonical task row slots");
+ expect(link.contains(actions)).toBe(false);
+ expect(metadata.compareDocumentPosition(actions) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(actions.compareDocumentPosition(identifier) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(identifier.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(timestamp.nextElementSibling).toBeNull();
+
+ act(() => root.unmount());
+ });
+
+ it("keeps the canonical archive action within the shared task-row height", () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <IssueRow
+ issue={createIssue()}
+ presentation="task"
+ onArchive={() => undefined}
+ />,
+ );
+ });
+
+ const archiveButton = container.querySelector<HTMLButtonElement>('button[aria-label="Archive"]');
+ expect(archiveButton?.className).toContain("h-5");
+ expect(archiveButton?.className).toContain("py-0");
+ expect(archiveButton?.className).not.toContain("py-1");
+
+ act(() => root.unmount());
+ });
+
+ it("preserves the legacy archive action density", () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(<IssueRow issue={createIssue()} onArchive={() => undefined} />);
+ });
+
+ const archiveButton = container.querySelector<HTMLButtonElement>('button[aria-label="Archive"]');
+ expect(archiveButton?.className).toContain("py-1");
+ expect(archiveButton?.className).not.toContain("h-5");
+
+ act(() => root.unmount());
+ });
+
+ it("emphasizes unread canonical titles and overlays the accessible mark-read control", () => {
+ const root = createRoot(container);
+ const onMarkRead = vi.fn();
+ act(() => {
+ root.render(
+ <IssueRow
+ issue={createIssue()}
+ presentation="task"
+ unreadState="visible"
+ onMarkRead={onMarkRead}
+ />,
+ );
+ });
+
+ const row = container.querySelector('[data-slot="task-row"]');
+ const title = row?.querySelector('[data-slot="task-row-title"]');
+ const unreadSlot = row?.querySelector('[data-testid="issue-row-unread-slot"]');
+ const markReadButton = unreadSlot?.querySelector<HTMLButtonElement>('button[aria-label="Mark as read"]');
+ expect(row?.getAttribute("data-unread")).toBe("true");
+ expect(title?.className).toContain("font-semibold");
+ expect(unreadSlot).not.toBeNull();
+ expect(unreadSlot?.className).toContain("absolute");
+ expect(markReadButton).not.toBeNull();
+ expect(markReadButton?.closest("a")).toBeNull();
+
+ act(() => markReadButton?.click());
+ expect(onMarkRead).toHaveBeenCalledTimes(1);
+
+ act(() => root.unmount());
+ });
+
+ it("keeps canonical leading geometry independent of unread state", () => {
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <>
+ <IssueRow issue={createIssue({ id: "read" })} presentation="task" unreadState="hidden" />
+ <IssueRow issue={createIssue({ id: "plain" })} presentation="task" />
+ </>,
+ );
+ });
+
+ const rows = Array.from(container.querySelectorAll('[data-slot="task-row"]'));
+ const unreadSlot = rows[0]?.querySelector('[data-testid="issue-row-unread-slot"]');
+ expect(rows).toHaveLength(2);
+ expect(rows[0]?.className).toBe(rows[1]?.className);
+ expect(unreadSlot).not.toBeNull();
+ expect(unreadSlot?.className).toContain("absolute");
+ expect(unreadSlot?.querySelector('button[aria-label="Mark as read"]')).toBeNull();
+ expect(rows[1]?.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull();
+
+ act(() => root.unmount());
+ });
+
+ it("preserves task-tree indentation slots in the canonical layout", () => {
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <IssueRow
+ issue={createIssue()}
+ presentation="task"
+ treeGuides={2}
+ chevronInGuide
+ leadingControl={<button type="button">Expand</button>}
+ />,
+ );
+ });
+
+ expect(container.querySelectorAll('[data-slot="task-row-tree-guide"]')).toHaveLength(2);
+ expect(container.querySelector('[data-slot="task-row-leading"]')?.textContent).toContain("Expand");
+ for (const connector of container.querySelectorAll('[data-slot="task-row-tree-connector"]')) {
+ expect(connector.className).toContain("left-7");
+ }
+ act(() => root.unmount());
+ });
+
it("keeps editable row controls keyboard-accessible and outside the navigation link", () => {
const root = createRoot(container);
@@ -509,6 +662,19 @@ describe("IssueRow", () => {
});
});
+ it("never renders a horizontal divider in canonical task presentation", () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(<IssueRow issue={createIssue()} presentation="task" showDivider />);
+ });
+
+ const row = container.querySelector('[data-slot="task-row"]');
+ expect(row?.className).not.toContain("border-b");
+
+ act(() => root.unmount());
+ });
+
it("keeps the hover wash on the row root while the overlay link stays a bare positioning layer", () => {
const root = createRoot(container);
@@ -620,6 +786,34 @@ describe("IssueRow", () => {
expect(label).not.toContain("next try");
});
+ it.each(["task", "legacy"] as const)(
+ "places the recovery chip immediately after the title in %s list rows",
+ (presentation) => {
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <IssueRow
+ issue={recoveryIssue(at(-5 * 60_000))}
+ presentation={presentation}
+ />,
+ );
+ });
+
+ const titleCluster = container.querySelector('[data-slot="task-row-title-cluster"]');
+ const title = titleCluster?.querySelector('[data-slot="task-row-title"]');
+ const chip = titleCluster?.querySelector('[data-testid="issue-row-recovery-indicator"]');
+ expect(titleCluster).not.toBeNull();
+ expect(title).not.toBeNull();
+ expect(chip).not.toBeNull();
+ if (!title || !chip) throw new Error("Expected the title and recovery chip");
+ expect(title.compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+
+ act(() => {
+ root.unmount();
+ });
+ },
+ );
+
it("stays calm when the overdue attempt is a verified live run", () => {
const chip = renderChip(
recoveryIssue(at(-5 * 60_000), {
diff --git a/ui/src/components/IssueRow.tsx b/ui/src/components/IssueRow.tsx
index b383670cc3..4f5f01c52d 100644
--- a/ui/src/components/IssueRow.tsx
+++ b/ui/src/components/IssueRow.tsx
@@ -24,12 +24,25 @@ import { hasAssignedBacklogBlocker } from "../lib/issue-blockers";
import { ExternalObjectStatusSummary } from "./ExternalObjectStatusSummary";
import { Badge } from "@/components/ui/badge";
-type UnreadState = "hidden" | "visible" | "fading";
+export type IssueRowUnreadState = "hidden" | "visible" | "fading";
+export type IssueRowPresentation = "legacy" | "task";
-interface IssueRowProps {
+export interface IssueRowProps {
issue: Issue;
issueLinkState?: unknown;
selected?: boolean;
+ /** Opt-in canonical collection layout. Legacy remains the default until each surface migrates. */
+ presentation?: IssueRowPresentation;
+ /** Interactive disclosure or selection control before the canonical status glyph. */
+ leadingControl?: ReactNode;
+ /** Optional status override; defaults to the task's shared StatusIcon. */
+ statusSlot?: ReactNode;
+ /** Stable metadata slot before the task's optional collection columns. */
+ metadata?: ReactNode;
+ /** Stable interactive action slot before the identifier and timestamp columns. */
+ actions?: ReactNode;
+ /** Controls the canonical trailing identifier without affecting legacy layouts. */
+ showIdentifier?: boolean;
mobileLeading?: ReactNode;
desktopMetaLeading?: ReactNode;
desktopLeadingSpacer?: boolean;
@@ -47,7 +60,7 @@ interface IssueRowProps {
checklistCurrentStep?: boolean;
checklistDependencyChips?: ReactNode;
checklistRowId?: string;
- unreadState?: UnreadState | null;
+ unreadState?: IssueRowUnreadState | null;
onMarkRead?: () => void;
onArchive?: () => void;
archiveDisabled?: boolean;
@@ -57,21 +70,22 @@ interface IssueRowProps {
/** Ancestor levels; renders that many vertical tree-guide slots (desktop). */
treeGuides?: number;
/**
- * This row has its own collapse chevron sitting in the innermost guide
- * column (a nested parent). Breaks the guide line there so the chevron is
- * not crossed out by it.
+ * This nested row has its own collapse chevron aligned with the innermost
+ * guide. Breaks the guide line there so the chevron is not crossed out.
*/
chevronInGuide?: boolean;
- /** Opt in to a bottom divider on this row (default off; used by views that intentionally keep separators). */
+ /** Legacy-only opt in to a bottom divider; canonical task rows stay divider-free. */
showDivider?: boolean;
}
export function InboxArchiveButton({
onArchive,
disabled,
+ compact = false,
}: {
onArchive: () => void;
disabled?: boolean;
+ compact?: boolean;
}) {
return (
<button
@@ -89,7 +103,10 @@ export function InboxArchiveButton({
onArchive();
}}
disabled={disabled}
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover:opacity-100 focus-visible:opacity-100 disabled:pointer-events-none disabled:opacity-30"
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover:opacity-100 focus-visible:opacity-100 disabled:pointer-events-none disabled:opacity-30",
+ compact ? "h-5 py-0" : "py-1",
+ )}
aria-label="Archive"
>
<Archive className="h-3.5 w-3.5" />
@@ -102,6 +119,12 @@ export function IssueRow({
issue,
issueLinkState,
selected = false,
+ presentation = "legacy",
+ leadingControl,
+ statusSlot,
+ metadata,
+ actions,
+ showIdentifier = true,
mobileLeading,
desktopMetaLeading,
desktopLeadingSpacer = false,
@@ -127,10 +150,9 @@ export function IssueRow({
}: IssueRowProps) {
const issuePathId = issue.identifier ?? issue.id;
const identifier = issue.identifier ?? issue.id.slice(0, 8);
- // A row participates in the unread system whenever `unreadState` is supplied
- // (inbox rows). It then reserves a fixed leading dot slot on all rows — read
- // and unread alike — so the mark-read dot sits in the far-left gutter without
- // shifting content, matching the sibling non-issue inbox rows.
+ // A row participates in the unread system whenever `unreadState` is supplied.
+ // Canonical rows overlay this affordance in their shared gutter, while legacy
+ // inbox rows retain their reserved slot until that presentation is migrated.
const showUnreadSlot = unreadState != null;
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
const unreadDotButton = (
@@ -202,6 +224,134 @@ export function IssueRow({
</Badge>
) : null;
+ if (presentation === "task") {
+ const isUnread = unreadState === "visible" || unreadState === "fading";
+ return (
+ <div
+ onMouseEnter={onMouseEnter}
+ data-slot="task-row"
+ data-unread={isUnread ? "true" : undefined}
+ className={cn(
+ "group relative flex min-w-0 items-start gap-2 rounded-lg py-2.5 pl-4 pr-2 text-sm no-underline text-inherit sm:items-center sm:py-2",
+ "[&_button]:relative [&_button]:z-10",
+ selected ? "bg-accent/50 hover:bg-accent/50" : "hover:bg-accent/50",
+ checklistCurrentStep && "bg-primary/5",
+ className,
+ )}
+ >
+ <Link
+ to={createIssueDetailPath(issuePathId)}
+ state={detailState}
+ disableIssueQuicklook
+ issuePrefetch={issue}
+ data-inbox-issue-link
+ id={checklistRowId}
+ aria-current={checklistCurrentStep ? "step" : undefined}
+ onClickCapture={() => rememberIssueDetailLocationState(issuePathId, detailState)}
+ className="absolute inset-0 rounded-lg no-underline text-inherit focus-visible:z-10 focus-visible:outline-none focus-visible:ring-(length:--rad-3) focus-visible:ring-ring"
+ >
+ <span className="sr-only">Open {identifier}: {issue.title}</span>
+ </Link>
+
+ {showUnreadSlot ? (
+ <span
+ data-testid="issue-row-unread-slot"
+ className="absolute left-0 top-3 inline-flex h-4 w-4 items-center justify-center sm:top-1/2 sm:-translate-y-1/2"
+ >
+ {showUnreadDot ? unreadDotButton : null}
+ </span>
+ ) : null}
+
+ <span data-slot="task-row-leading" className="flex shrink-0 items-center gap-1 pt-px sm:pt-0">
+ {treeGuides > 0
+ ? Array.from({ length: treeGuides }, (_, level) => {
+ const gapForChevron = chevronInGuide && level === treeGuides - 1;
+ return (
+ <span
+ key={`task-guide-${level}`}
+ data-slot="task-row-tree-guide"
+ aria-hidden="true"
+ className="relative hidden w-4 shrink-0 self-stretch sm:block"
+ >
+ <span
+ data-slot="task-row-tree-connector"
+ className="absolute -inset-y-3 left-7 w-px bg-background"
+ >
+ {gapForChevron ? (
+ <span className="absolute inset-0 flex flex-col">
+ <span className="flex-1 bg-border" />
+ <span className="h-3.5 shrink-0" />
+ <span className="flex-1 bg-border" />
+ </span>
+ ) : (
+ <span className="absolute inset-0 bg-border" />
+ )}
+ </span>
+ </span>
+ );
+ })
+ : null}
+ {leadingControl}
+ {statusSlot ?? (
+ <StatusIcon
+ status={issue.status}
+ blockerAttention={issue.blockerAttention}
+ size="md"
+ className={selectedStatusClass}
+ />
+ )}
+ {productivityReviewIndicator}
+ {parkedBlockerIndicator}
+ </span>
+
+ <span className="flex min-w-0 flex-1 flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
+ <span data-slot="task-row-title-cluster" className="flex min-w-0 flex-1 items-start gap-1.5 sm:items-center">
+ <span
+ data-slot="task-row-title"
+ className={cn(
+ "min-w-0 line-clamp-2 text-sm sm:truncate sm:line-clamp-none",
+ isUnread && "font-semibold",
+ titleClassName,
+ )}
+ >
+ {issue.title}{titleSuffix}
+ </span>
+ {recoveryIndicator}
+ </span>
+ {checklistDependencyChips ? (
+ <span className="flex flex-wrap gap-1">{checklistDependencyChips}</span>
+ ) : null}
+ {mobileMeta ? (
+ <span className="text-xs text-muted-foreground sm:hidden">{mobileMeta}</span>
+ ) : null}
+ </span>
+
+ <span
+ data-slot="task-row-trailing"
+ className="ml-auto hidden min-w-0 shrink-0 items-center gap-2 sm:flex"
+ >
+ {externalObjectSummary ? (
+ <ExternalObjectStatusSummary summary={externalObjectSummary} compact />
+ ) : null}
+ {metadata ? <span data-slot="task-row-metadata" className="min-w-0">{metadata}</span> : null}
+ {desktopTrailing}
+ {actions ? <span data-slot="task-row-actions" className="flex shrink-0 items-center gap-1">{actions}</span> : null}
+ {onArchive ? <InboxArchiveButton onArchive={onArchive} disabled={archiveDisabled} compact /> : null}
+ {showIdentifier ? (
+ <span data-slot="task-row-identifier" className="w-20 shrink-0 text-right font-mono text-xs text-muted-foreground">
+ {identifier}
+ </span>
+ ) : null}
+ {trailingMeta ? (
+ <span data-slot="task-row-timestamp" className="w-24 shrink-0 truncate text-right text-xs text-muted-foreground">
+ {trailingMeta}
+ </span>
+ ) : null}
+ </span>
+ </div>
+ );
+ }
+
return (
<div
onMouseEnter={onMouseEnter}
@@ -243,11 +393,16 @@ export function IssueRow({
{mobileLeading ?? <StatusIcon status={issue.status} blockerAttention={issue.blockerAttention} size="md" className={selectedStatusClass} />}
{productivityReviewIndicator}
{parkedBlockerIndicator}
- {recoveryIndicator}
</span>
<span className="flex min-w-0 flex-1 flex-col gap-1 sm:contents">
- <span className={cn("line-clamp-2 text-sm sm:order-2 sm:min-w-0 sm:flex-1 sm:truncate sm:line-clamp-none", titleClassName)}>
- {issue.title}{titleSuffix}
+ <span data-slot="task-row-title-cluster" className="flex min-w-0 items-start gap-1.5 sm:order-2 sm:flex-1 sm:items-center">
+ <span
+ data-slot="task-row-title"
+ className={cn("min-w-0 line-clamp-2 text-sm sm:truncate sm:line-clamp-none", titleClassName)}
+ >
+ {issue.title}{titleSuffix}
+ </span>
+ {recoveryIndicator}
</span>
{checklistDependencyChips ? (
<span className="flex flex-wrap gap-1 sm:order-3 sm:ml-(--sz-calc-13)">
@@ -317,7 +472,6 @@ export function IssueRow({
{identifier}
</span>
{parkedBlockerIndicator}
- {recoveryIndicator}
</>
)}
{mobileMeta ? (
@@ -377,7 +531,7 @@ function renderRecoveryChip(
role="status"
aria-label={detail ? `${label} — ${detail}` : label}
className={cn(
- "ml-1.5 gap-0.5 text-(length:--text-nano)",
+ "shrink-0 gap-0.5 text-(length:--text-nano)",
tone.className,
selected ? "!border-muted-foreground !text-muted-foreground" : null,
)}
diff --git a/ui/src/components/KeyboardShortcutsCheatsheet.test.tsx b/ui/src/components/KeyboardShortcutsCheatsheet.test.tsx
index b27b3831c1..92622d8e14 100644
--- a/ui/src/components/KeyboardShortcutsCheatsheet.test.tsx
+++ b/ui/src/components/KeyboardShortcutsCheatsheet.test.tsx
@@ -18,24 +18,16 @@ describe("KeyboardShortcutsCheatsheet", () => {
document.body.innerHTML = "";
});
- it("lists the re-pointed Cmd/Ctrl+B sidebar collapse shortcut as a chord", () => {
+ it("does not advertise the retired sidebar collapse shortcut", () => {
const root = createRoot(container);
flushSync(() => {
root.render(<KeyboardShortcutsCheatsheetContent />);
});
- // The collapse/expand row exists with its label.
const row = [...container.querySelectorAll("span")].find(
(node) => node.textContent?.trim() === "Collapse or expand sidebar",
)?.parentElement;
- expect(row).toBeTruthy();
-
- // Rendered as a "+" chord (B + a Cmd/Ctrl cap), not a "then" sequence.
- const caps = [...(row?.querySelectorAll("kbd") ?? [])].map((kbd) => kbd.textContent);
- expect(caps).toContain("B");
- expect(caps.some((cap) => cap === "⌘" || cap === "Ctrl")).toBe(true);
- expect(row?.textContent).toContain("+");
- expect(row?.textContent).not.toContain("then");
+ expect(row).toBeUndefined();
flushSync(() => {
root.unmount();
diff --git a/ui/src/components/KeyboardShortcutsCheatsheet.tsx b/ui/src/components/KeyboardShortcutsCheatsheet.tsx
index 9acd0289a5..210c9f302f 100644
--- a/ui/src/components/KeyboardShortcutsCheatsheet.tsx
+++ b/ui/src/components/KeyboardShortcutsCheatsheet.tsx
@@ -8,17 +8,6 @@ interface ShortcutEntry {
combo?: boolean;
}
-// Platform-appropriate label for the Cmd/Ctrl modifier so the cheatsheet shows
-// the same key the user actually presses (re-pointed in the collapsible sidebar
-// work — Cmd/Ctrl+B toggles the rail).
-function getPlatformLabel() {
- if (typeof navigator === "undefined") return "";
- const nav = navigator as Navigator & { userAgentData?: { platform?: string } };
- return nav.userAgentData?.platform || navigator.userAgent || "";
-}
-
-const META_KEY = /Mac|iPhone|iPad|iPod/.test(getPlatformLabel()) ? "⌘" : "Ctrl";
-
interface ShortcutSection {
title: string;
shortcuts: ShortcutEntry[];
@@ -66,7 +55,6 @@ const sections: ShortcutSection[] = [
{ keys: ["/"], label: "Search current page or quick search" },
{ keys: ["c"], label: "New task" },
{ keys: ["["], label: "Toggle sidebar" },
- { keys: [META_KEY, "B"], label: "Collapse or expand sidebar", combo: true },
{ keys: ["]"], label: "Toggle panel" },
{ keys: ["?"], label: "Show keyboard shortcuts" },
],
diff --git a/ui/src/components/RoutineOverview.test.tsx b/ui/src/components/RoutineOverview.test.tsx
new file mode 100644
index 0000000000..6045a147b2
--- /dev/null
+++ b/ui/src/components/RoutineOverview.test.tsx
@@ -0,0 +1,203 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import type { RoutineDetail, RoutineRunSummary } from "@paperclipai/shared";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RoutineDetailContext, type RoutineDetailContextValue } from "./routine-sections/context";
+import {
+ RoutineOverview,
+ routineRunIssue,
+ summarizeRoutineSchedule,
+} from "./RoutineOverview";
+
+const issueRowRender = vi.hoisted(() => vi.fn());
+
+vi.mock("@/components/IssueRow", () => ({
+ IssueRow: (props: { issue: { title: string }; presentation?: string }) => {
+ issueRowRender(props);
+ return <div data-slot="task-row">{props.issue.title}</div>;
+ },
+}));
+
+vi.mock("@/components/MarkdownBody", () => ({
+ MarkdownBody: ({ children }: { children: string }) => <div data-testid="markdown">{children}</div>,
+}));
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+}));
+
+const triggeredAt = new Date("2026-08-31T16:00:00.000Z");
+const run: RoutineRunSummary = {
+ id: "run-1",
+ companyId: "company-1",
+ routineId: "routine-1",
+ triggerId: "trigger-1",
+ source: "schedule",
+ status: "succeeded",
+ triggeredAt,
+ idempotencyKey: null,
+ triggerPayload: null,
+ dispatchFingerprint: null,
+ linkedIssueId: "issue-1",
+ coalescedIntoRunId: null,
+ failureReason: null,
+ completedAt: triggeredAt,
+ createdAt: triggeredAt,
+ updatedAt: triggeredAt,
+ trigger: { id: "trigger-1", kind: "schedule", label: "weekday" },
+ linkedIssue: {
+ id: "issue-1",
+ identifier: "PAP-42",
+ title: "Prepare the release digest",
+ status: "done",
+ priority: "high",
+ updatedAt: triggeredAt,
+ },
+};
+
+const routine = {
+ id: "routine-1",
+ companyId: "company-1",
+ projectId: "project-1",
+ folderId: null,
+ goalId: null,
+ parentIssueId: null,
+ title: "Weekly release review",
+ description: "Summarize **release readiness** for the operator.",
+ assigneeAgentId: "agent-1",
+ priority: "medium",
+ status: "active",
+ concurrencyPolicy: "coalesce_if_active",
+ catchUpPolicy: "skip_missed",
+ activityGatePolicy: "always",
+ activityGateScope: "company",
+ variables: [],
+ env: { PRIVATE_TOKEN: { type: "secret_ref", secretId: "secret-1" } },
+ latestRevisionId: "revision-1",
+ latestRevisionNumber: 1,
+ createdByAgentId: null,
+ createdByUserId: null,
+ responsibleUserId: null,
+ updatedByAgentId: null,
+ updatedByUserId: null,
+ lastTriggeredAt: triggeredAt,
+ lastEnqueuedAt: triggeredAt,
+ createdAt: triggeredAt,
+ updatedAt: triggeredAt,
+ project: null,
+ assignee: { id: "agent-1", name: "Release Manager", role: "manager", title: null, urlKey: "release-manager" },
+ parentIssue: null,
+ triggers: [{
+ id: "trigger-1",
+ companyId: "company-1",
+ routineId: "routine-1",
+ kind: "schedule",
+ label: "weekday",
+ enabled: true,
+ cronExpression: "0 9 * * 1-5",
+ timezone: "America/Los_Angeles",
+ nextRunAt: new Date("2026-09-01T16:00:00.000Z"),
+ lastFiredAt: triggeredAt,
+ publicId: null,
+ secretId: null,
+ signingMode: null,
+ replayWindowSec: null,
+ lastRotatedAt: null,
+ lastResult: "succeeded",
+ createdByAgentId: null,
+ createdByUserId: null,
+ updatedByAgentId: null,
+ updatedByUserId: null,
+ createdAt: triggeredAt,
+ updatedAt: triggeredAt,
+ }],
+ recentRuns: [run],
+ activeIssue: null,
+} as RoutineDetail;
+
+function contextFixture(): RoutineDetailContextValue {
+ return {
+ routine,
+ routineId: routine.id,
+ companyId: routine.companyId,
+ routineRuns: [run],
+ currentAssignee: {
+ id: "agent-1",
+ name: "Release Manager",
+ urlKey: "release-manager",
+ },
+ hasLiveRun: false,
+ } as RoutineDetailContextValue;
+}
+
+describe("RoutineOverview", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ issueRowRender.mockClear();
+ vi.spyOn(Date, "now").mockReturnValue(new Date("2026-08-31T17:00:00.000Z").getTime());
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ flushSync(() => root.unmount());
+ container.remove();
+ vi.restoreAllMocks();
+ });
+
+ it("summarizes enabled schedules and their next run", () => {
+ expect(summarizeRoutineSchedule(routine.triggers)).toMatchObject({
+ label: "1 active schedule",
+ detail: "0 9 * * 1-5 · America/Los_Angeles",
+ nextRunAt: new Date("2026-09-01T16:00:00.000Z"),
+ });
+ expect(summarizeRoutineSchedule([{ ...routine.triggers[0]!, enabled: false }])).toEqual({
+ label: "No active schedule",
+ detail: "Manual runs only",
+ nextRunAt: null,
+ });
+ });
+
+ it("adapts compact run tasks to the canonical task presentation", () => {
+ const issue = routineRunIssue(run.linkedIssue!, run, "company-1", "project-1");
+ expect(issue).toMatchObject({
+ id: "issue-1",
+ companyId: "company-1",
+ projectId: "project-1",
+ status: "done",
+ priority: "high",
+ originKind: "routine_execution",
+ originId: "routine-1",
+ originRunId: "run-1",
+ });
+ });
+
+ it("shows operational facts, readable description, agent, and recent task rows without secrets", () => {
+ flushSync(() => root.render(
+ <RoutineDetailContext.Provider value={contextFixture()}>
+ <RoutineOverview />
+ </RoutineDetailContext.Provider>,
+ ));
+
+ expect(container.textContent).toContain("1 active schedule");
+ expect(container.textContent).toContain("Next run");
+ expect(container.textContent).toContain("Release Manager");
+ expect(container.textContent).toContain("Summarize **release readiness** for the operator.");
+ expect(container.textContent).toContain("Prepare the release digest");
+ expect(container.textContent).not.toContain("PRIVATE_TOKEN");
+ expect(container.textContent).not.toContain("secret-1");
+ expect(issueRowRender).toHaveBeenCalledWith(expect.objectContaining({ presentation: "task" }));
+ expect(container.querySelector('a[href="/activity/runs?entityType=routine&entityId=routine-1"]'))
+ .not.toBeNull();
+ expect(container.querySelector('a[href="/activity?entityType=routine&entityId=routine-1"]'))
+ .not.toBeNull();
+ });
+});
diff --git a/ui/src/components/RoutineOverview.tsx b/ui/src/components/RoutineOverview.tsx
new file mode 100644
index 0000000000..671fdd6860
--- /dev/null
+++ b/ui/src/components/RoutineOverview.tsx
@@ -0,0 +1,249 @@
+import type {
+ Issue,
+ IssuePriority,
+ IssueStatus,
+ RoutineRunSummary,
+ RoutineTrigger,
+} from "@paperclipai/shared";
+import { ISSUE_PRIORITIES, ISSUE_STATUSES } from "@paperclipai/shared";
+import { CalendarClock, Clock3, Play, Repeat, UserRound } from "lucide-react";
+import { IssueRow } from "@/components/IssueRow";
+import { MarkdownBody } from "@/components/MarkdownBody";
+import { StatusBadge } from "@/components/StatusBadge";
+import { Button } from "@/components/ui/button";
+import { createIssueDetailLocationState } from "@/lib/issueDetailBreadcrumb";
+import { Link } from "@/lib/router";
+import {
+ routineActivityAuditHref,
+ routineDetailHref,
+ routineRunsAuditHref,
+} from "./RoutineContextualSidebar";
+import { useRoutineDetail } from "./routine-sections/context";
+
+export type RoutineScheduleSummary = {
+ label: string;
+ detail: string;
+ nextRunAt: Date | null;
+};
+
+export function formatRoutineTimestamp(value: Date | string) {
+ return new Date(value).toLocaleString(undefined, {
+ dateStyle: "medium",
+ timeStyle: "short",
+ });
+}
+
+export function summarizeRoutineSchedule(triggers: RoutineTrigger[]): RoutineScheduleSummary {
+ const schedules = triggers.filter((trigger) => trigger.kind === "schedule" && trigger.enabled);
+ const nextRunAt = schedules
+ .map((trigger) => trigger.nextRunAt ? new Date(trigger.nextRunAt) : null)
+ .filter((value): value is Date => value !== null && Number.isFinite(value.getTime()))
+ .sort((left, right) => left.getTime() - right.getTime())[0] ?? null;
+
+ if (schedules.length === 0) {
+ return { label: "No active schedule", detail: "Manual runs only", nextRunAt: null };
+ }
+
+ const first = schedules[0]!;
+ return {
+ label: schedules.length === 1 ? "1 active schedule" : `${schedules.length} active schedules`,
+ detail: first.cronExpression
+ ? `${first.cronExpression}${first.timezone ? ` · ${first.timezone}` : ""}`
+ : first.label ?? "Scheduled trigger",
+ nextRunAt,
+ };
+}
+
+function normalizeIssueStatus(value: string): IssueStatus {
+ return ISSUE_STATUSES.includes(value as IssueStatus) ? value as IssueStatus : "todo";
+}
+
+function normalizeIssuePriority(value: string): IssuePriority {
+ return ISSUE_PRIORITIES.includes(value as IssuePriority) ? value as IssuePriority : "medium";
+}
+
+/** Display-only adapter for the canonical task row; run summaries intentionally carry compact task data. */
+export function routineRunIssue(
+ summary: NonNullable<RoutineRunSummary["linkedIssue"]>,
+ run: RoutineRunSummary,
+ companyId: string,
+ projectId: string | null,
+): Issue {
+ return {
+ ...summary,
+ companyId,
+ projectId,
+ projectWorkspaceId: null,
+ goalId: null,
+ parentId: null,
+ description: null,
+ status: normalizeIssueStatus(summary.status),
+ workMode: "standard",
+ priority: normalizeIssuePriority(summary.priority),
+ reviewPolicy: null,
+ assigneeAgentId: null,
+ assigneeUserId: null,
+ checkoutRunId: null,
+ executionRunId: null,
+ executionAgentNameKey: null,
+ executionLockedAt: null,
+ createdByAgentId: null,
+ createdByUserId: null,
+ responsibleUserId: null,
+ issueNumber: null,
+ originKind: "routine_execution",
+ originId: run.routineId,
+ originRunId: run.id,
+ requestDepth: 0,
+ billingCode: null,
+ assigneeAdapterOverrides: null,
+ executionWorkspaceId: null,
+ executionWorkspacePreference: null,
+ executionWorkspaceSettings: null,
+ startedAt: null,
+ completedAt: null,
+ cancelledAt: null,
+ hiddenAt: null,
+ createdAt: run.triggeredAt,
+ };
+}
+
+function OverviewFact({
+ icon: Icon,
+ label,
+ value,
+ detail,
+}: {
+ icon: typeof Clock3;
+ label: string;
+ value: React.ReactNode;
+ detail?: React.ReactNode;
+}) {
+ return (
+ <div className="flex min-w-0 flex-col gap-1 rounded-lg border border-border p-3">
+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <Icon className="h-3.5 w-3.5" aria-hidden="true" />
+ <span>{label}</span>
+ </div>
+ <div className="min-w-0 text-sm font-medium text-foreground">{value}</div>
+ {detail ? <div className="min-w-0 text-xs text-muted-foreground">{detail}</div> : null}
+ </div>
+ );
+}
+
+export function RoutineOverview() {
+ const { routine, routineRuns, currentAssignee, hasLiveRun } = useRoutineDetail();
+ const schedule = summarizeRoutineSchedule(routine.triggers);
+ const sortedRuns = [...(routineRuns ?? [])].sort(
+ (left, right) => new Date(right.triggeredAt).getTime() - new Date(left.triggeredAt).getTime(),
+ );
+ const lastRun = sortedRuns[0] ?? null;
+ const recentRuns = sortedRuns.slice(0, 5);
+ const detailOrigin = createIssueDetailLocationState(
+ routine.title,
+ routineDetailHref(routine.id),
+ "issues",
+ );
+ const automationState = routine.status === "archived"
+ ? "archived"
+ : !routine.assigneeAgentId
+ ? "draft"
+ : routine.status;
+
+ return (
+ <div className="flex flex-col gap-6" data-routine-overview-mode="read">
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
+ <OverviewFact
+ icon={Repeat}
+ label="State"
+ value={<StatusBadge status={automationState} />}
+ detail={hasLiveRun ? "A run is active now" : "No active run"}
+ />
+ <OverviewFact
+ icon={CalendarClock}
+ label="Schedule"
+ value={schedule.label}
+ detail={<span className="font-mono">{schedule.detail}</span>}
+ />
+ <OverviewFact
+ icon={Clock3}
+ label="Next run"
+ value={schedule.nextRunAt ? formatRoutineTimestamp(schedule.nextRunAt) : "Not scheduled"}
+ detail={schedule.nextRunAt ? "Scheduled" : "Add or enable a schedule"}
+ />
+ <OverviewFact
+ icon={Play}
+ label="Last run"
+ value={lastRun ? <StatusBadge status={lastRun.status} /> : "No runs yet"}
+ detail={lastRun ? formatRoutineTimestamp(lastRun.triggeredAt) : "Run manually or wait for the schedule"}
+ />
+ </div>
+
+ <section className="flex flex-col gap-2" aria-labelledby="routine-agent-heading">
+ <h2 id="routine-agent-heading" className="text-sm font-semibold">Default agent</h2>
+ {currentAssignee ? (
+ <Link
+ to={`/agents/${currentAssignee.urlKey ?? currentAssignee.id}`}
+ className="flex w-fit items-center gap-2 rounded-md text-sm font-medium hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <UserRound className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
+ {currentAssignee.name}
+ </Link>
+ ) : (
+ <p className="text-sm text-muted-foreground">No default agent. Automatic triggers remain paused.</p>
+ )}
+ </section>
+
+ <section className="flex flex-col gap-2" aria-labelledby="routine-description-heading">
+ <h2 id="routine-description-heading" className="text-sm font-semibold">Description</h2>
+ {routine.description?.trim() ? (
+ <MarkdownBody className="text-sm text-foreground" linkIssueReferences>
+ {routine.description}
+ </MarkdownBody>
+ ) : (
+ <p className="text-sm text-muted-foreground">No description yet.</p>
+ )}
+ </section>
+
+ <section className="flex flex-col gap-2" aria-labelledby="routine-recent-runs-heading">
+ <div className="flex items-center justify-between gap-3">
+ <h2 id="routine-recent-runs-heading" className="text-sm font-semibold">Recent runs</h2>
+ <Button variant="ghost" size="sm" asChild>
+ <Link to={routineRunsAuditHref(routine.id)}>View all runs</Link>
+ </Button>
+ </div>
+ {recentRuns.length === 0 ? (
+ <p className="py-6 text-center text-sm text-muted-foreground">
+ No runs yet. Run the routine now or wait for its schedule.
+ </p>
+ ) : (
+ <div className="flex flex-col gap-0.5">
+ {recentRuns.map((run) => run.linkedIssue ? (
+ <IssueRow
+ key={run.id}
+ issue={routineRunIssue(run.linkedIssue, run, routine.companyId, routine.projectId)}
+ issueLinkState={detailOrigin}
+ presentation="task"
+ metadata={(
+ <span className="flex items-center gap-2">
+ <StatusBadge status={run.status} />
+ <span className="font-mono text-xs text-muted-foreground">{formatRoutineTimestamp(run.triggeredAt)}</span>
+ </span>
+ )}
+ />
+ ) : (
+ <div key={run.id} className="flex min-w-0 items-center gap-2 rounded-lg px-2 py-2 text-sm">
+ <StatusBadge status={run.status} />
+ <span className="min-w-0 flex-1 truncate">{run.trigger?.label ?? "Routine run"}</span>
+ <span className="shrink-0 font-mono text-xs text-muted-foreground">{formatRoutineTimestamp(run.triggeredAt)}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ <Button variant="link" size="sm" className="w-fit px-0" asChild>
+ <Link to={routineActivityAuditHref(routine.id)}>View routine activity</Link>
+ </Button>
+ </section>
+ </div>
+ );
+}
diff --git a/ui/src/components/onboarding/PillGuy.tsx b/ui/src/components/onboarding/PillGuy.tsx
index 588cfac87f..73a01b44cc 100644
--- a/ui/src/components/onboarding/PillGuy.tsx
+++ b/ui/src/components/onboarding/PillGuy.tsx
@@ -34,8 +34,8 @@ function DormantPill() {
<svg viewBox="0 0 100 93" fill="none" aria-hidden className="size-full">
<path d={BODY_PATH} fill={`url(#${DORMANT_GRADIENT_ID})`} />
{/* Closed eyes: the same rounded rects as the open pair, flattened. */}
- <rect x="75.9199" y="66.3047" width="9" height="4" rx="2" fill="#060606" />
- <rect x="28.9199" y="66.3047" width="9" height="4" rx="2" fill="#060606" />
+ <rect x="75.9199" y="66.3047" width="9" height="4" rx="2" fill="var(--pill-guy-eye)" />
+ <rect x="28.9199" y="66.3047" width="9" height="4" rx="2" fill="var(--pill-guy-eye)" />
<defs>
<linearGradient
id={DORMANT_GRADIENT_ID}
@@ -45,8 +45,8 @@ function DormantPill() {
y2="107.486"
gradientUnits="userSpaceOnUse"
>
- <stop stopColor="#626262" />
- <stop offset="1" stopColor="#101010" />
+ <stop stopColor="var(--pill-guy-dormant-top)" />
+ <stop offset="1" stopColor="var(--pill-guy-dormant-bottom)" />
</linearGradient>
</defs>
</svg>
@@ -57,9 +57,9 @@ function AlivePill() {
return (
<svg viewBox="0 0 100 93" fill="none" aria-hidden className="size-full">
<path d={BODY_PATH} fill={`url(#${ALIVE_GRADIENT_ID})`} />
- <rect x="76.1406" y="63.1328" width="8.87072" height="10.3492" rx="4.43536" fill="#060606" />
- <rect x="28.8301" y="63.1328" width="8.87072" height="10.3492" rx="4.43536" fill="#060606" />
- <path d={TUFT_PATH} fill="#2D200D" />
+ <rect x="76.1406" y="63.1328" width="8.87072" height="10.3492" rx="4.43536" fill="var(--pill-guy-eye)" />
+ <rect x="28.8301" y="63.1328" width="8.87072" height="10.3492" rx="4.43536" fill="var(--pill-guy-eye)" />
+ <path d={TUFT_PATH} fill="var(--pill-guy-tuft)" />
<defs>
<linearGradient
id={ALIVE_GRADIENT_ID}
@@ -69,8 +69,8 @@ function AlivePill() {
y2="107.486"
gradientUnits="userSpaceOnUse"
>
- <stop stopColor="#3028AA" />
- <stop offset="1" stopColor="#FF0000" />
+ <stop stopColor="var(--pill-guy-alive-top)" />
+ <stop offset="1" stopColor="var(--pill-guy-alive-bottom)" />
</linearGradient>
</defs>
</svg>
diff --git a/ui/src/components/routine-sections/editable-sections.production.tsx b/ui/src/components/routine-sections/editable-sections.production.tsx
new file mode 100644
index 0000000000..49e79c2522
--- /dev/null
+++ b/ui/src/components/routine-sections/editable-sections.production.tsx
@@ -0,0 +1,859 @@
+import { useEffect, useMemo, useState } from "react";
+import {
+ ArrowRight,
+ Braces,
+ Clock3,
+ Edit3,
+ KeyRound,
+ Play,
+ Plus,
+ X,
+} from "lucide-react";
+import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { RadioCardGroup } from "@/components/ui/radio-card";
+import { cn } from "@/lib/utils";
+import { nextCronFires, previewFirePolicies } from "../../lib/cron-fires";
+import { timeAgo } from "../../lib/timeAgo";
+import { EmptyState } from "../EmptyState";
+import { InlineEntitySelector } from "../InlineEntitySelector";
+import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "../IssueDocumentAnnotations";
+import { AgentIcon } from "../AgentIconPicker";
+import { MarkdownEditor } from "../MarkdownEditor";
+import { ScheduleEditor, getScheduleCronValidation } from "../ScheduleEditor";
+import { RoutineVariablesEditor, RoutineVariablesHint } from "../RoutineVariablesEditor";
+import { RoutineTriggerCard } from "../RoutineTriggerCard";
+import { EnvironmentVariablesEditor } from "../environment-variables-editor";
+import { createDefaultNewTrigger, useRoutineDetail } from "./context";
+import type { EnvBinding, RoutineDetail as RoutineDetailType } from "@paperclipai/shared";
+
+const concurrencyPolicyOptions = [
+ {
+ value: "coalesce_if_active",
+ title: "Coalesce if active",
+ description: "Keep one follow-up run queued while an active run is still working.",
+ },
+ {
+ value: "always_enqueue",
+ title: "Always enqueue",
+ description: "Queue every trigger occurrence, even if several runs stack up.",
+ },
+ {
+ value: "skip_if_active",
+ title: "Skip if active",
+ description: "Drop overlapping trigger occurrences while the routine is already active.",
+ },
+];
+
+const catchUpPolicyOptions = [
+ {
+ value: "skip_missed",
+ title: "Skip missed",
+ description: "Ignore schedule windows that were missed while paused.",
+ },
+ {
+ value: "enqueue_missed_with_cap",
+ title: "Enqueue missed with cap",
+ description: "Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap.",
+ },
+];
+
+const activityGatePolicyOptions = [
+ {
+ value: "always",
+ title: "Run on every scheduled tick",
+ description: "Fire on the schedule no matter what — the default behavior.",
+ },
+ {
+ value: "require_external_activity",
+ title: "Skip when there's been no activity since the last run",
+ description:
+ "On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens.",
+ },
+];
+
+const activityGateScopeOptions = [
+ {
+ value: "company",
+ title: "Company-wide",
+ description: "Any activity across the company counts as a reason to run.",
+ },
+ {
+ value: "project",
+ title: "This project",
+ description: "Only activity in the routine's project counts as a reason to run.",
+ },
+];
+
+const triggerKinds = ["schedule", "webhook"];
+const signingModes = ["bearer", "hmac_sha256", "github_hmac", "none"];
+const signingModeDescriptions: Record<string, string> = {
+ bearer: "Expect a shared bearer token in the Authorization header.",
+ hmac_sha256: "Expect an HMAC SHA-256 signature over the request using the shared secret.",
+ github_hmac: "Accept GitHub-style X-Hub-Signature-256 header (HMAC over raw body, no timestamp).",
+ none: "No authentication — the webhook URL itself acts as a shared secret.",
+};
+const SIGNING_MODES_WITHOUT_REPLAY_WINDOW = new Set(["github_hmac", "none"]);
+
+export function OverviewSection({
+ defaultDescriptionAnnotationsOpen = false,
+}: {
+ defaultDescriptionAnnotationsOpen?: boolean;
+} = {}) {
+ const ctx = useRoutineDetail();
+ const {
+ routine,
+ editDraft,
+ setEditDraft,
+ assigneeOptions,
+ projectOptions,
+ recentAssigneeIds,
+ recentProjectIds,
+ agentById,
+ projectById,
+ currentAssignee,
+ currentProject,
+ mentionOptions,
+ assigneeSelectorRef,
+ projectSelectorRef,
+ descriptionEditorRef,
+ routineRuns,
+ activity,
+ saveRoutine,
+ saveConflict,
+ isSectionDirty,
+ navigateToSection,
+ } = ctx;
+ const [descriptionAnnotationsOpen, setDescriptionAnnotationsOpen] = useState(defaultDescriptionAnnotationsOpen);
+
+ const activeTriggers = routine.triggers.length;
+ const nextFire = useMemo(() => {
+ const upcoming = routine.triggers
+ .filter((trigger) => trigger.kind === "schedule" && trigger.nextRunAt)
+ .map((trigger) => new Date(trigger.nextRunAt as Date))
+ .sort((a, b) => a.getTime() - b.getTime())[0];
+ return upcoming ? upcoming.toLocaleString() : null;
+ }, [routine.triggers]);
+ const boundSecrets = editDraft.env ? Object.keys(editDraft.env).length : 0;
+ const lastRun = (routineRuns ?? [])[0] ?? null;
+ const recentActivity = (activity ?? []).slice(0, 5);
+
+ return (
+ <div className="space-y-6">
+ {/* Assignment row */}
+ <div className="overflow-x-auto overscroll-x-contain">
+ <div className="inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap">
+ <span>For</span>
+ <InlineEntitySelector
+ ref={assigneeSelectorRef}
+ value={editDraft.assigneeAgentId}
+ options={assigneeOptions}
+ recentOptionIds={recentAssigneeIds}
+ placeholder="Responsible"
+ noneLabel="No responsible"
+ searchPlaceholder="Search responsible..."
+ emptyMessage="No responsible found."
+ onChange={(assigneeAgentId) =>
+ setEditDraft((current) => ({ ...current, assigneeAgentId }))
+ }
+ onConfirm={() => {
+ if (editDraft.projectId) {
+ descriptionEditorRef.current?.focus();
+ } else {
+ projectSelectorRef.current?.focus();
+ }
+ }}
+ renderTriggerValue={(option) =>
+ option ? (
+ currentAssignee ? (
+ <>
+ <AgentIcon icon={currentAssignee.icon} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{option.label}</span>
+ </>
+ ) : (
+ <span className="truncate">{option.label}</span>
+ )
+ ) : (
+ <span className="text-muted-foreground">Responsible</span>
+ )
+ }
+ renderOption={(option) => {
+ if (!option.id) return <span className="truncate">{option.label}</span>;
+ const assignee = agentById.get(option.id);
+ return (
+ <>
+ {assignee ? (
+ <AgentIcon icon={assignee.icon} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ ) : null}
+ <span className="truncate">{option.label}</span>
+ </>
+ );
+ }}
+ />
+ <span>in</span>
+ <InlineEntitySelector
+ ref={projectSelectorRef}
+ value={editDraft.projectId}
+ options={projectOptions}
+ recentOptionIds={recentProjectIds}
+ placeholder="Project"
+ noneLabel="No project"
+ searchPlaceholder="Search projects..."
+ emptyMessage="No projects found."
+ onChange={(projectId) => setEditDraft((current) => ({ ...current, projectId }))}
+ onConfirm={() => descriptionEditorRef.current?.focus()}
+ renderTriggerValue={(option) =>
+ option && currentProject ? (
+ <>
+ <span
+ className="h-3.5 w-3.5 shrink-0 rounded-sm"
+ style={{ backgroundColor: currentProject.color ?? "var(--project-none)" }}
+ />
+ <span className="truncate">{option.label}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">Project</span>
+ )
+ }
+ renderOption={(option) => {
+ if (!option.id) return <span className="truncate">{option.label}</span>;
+ const project = projectById.get(option.id);
+ return (
+ <>
+ <span
+ className="h-3.5 w-3.5 shrink-0 rounded-sm"
+ style={{ backgroundColor: project?.color ?? "var(--project-none)" }}
+ />
+ <span className="truncate">{option.label}</span>
+ </>
+ );
+ }}
+ />
+ </div>
+ </div>
+
+ {!routine.assigneeAgentId ? (
+ <div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200">
+ Default agent required. This routine can stay as a draft and still run manually, but
+ automation stays paused until you assign a default agent.
+ </div>
+ ) : null}
+
+ {/* Instructions */}
+ <div className="space-y-2">
+ <div className="flex items-center justify-end">
+ {routine.descriptionDocument ? (
+ <DocumentAnnotationsCountChip
+ issueId={routine.id}
+ docKey="description"
+ target={{ kind: "routine", routineId: routine.id, documentKey: "description" }}
+ panelOpen={descriptionAnnotationsOpen}
+ onToggle={() => setDescriptionAnnotationsOpen((open) => !open)}
+ />
+ ) : null}
+ </div>
+ {routine.descriptionDocument ? (
+ <IssueDocumentAnnotations
+ issueId={routine.id}
+ doc={routine.descriptionDocument}
+ target={{ kind: "routine", routineId: routine.id, documentKey: "description" }}
+ bodyMarkdown={editDraft.description}
+ draftDirty={isSectionDirty("overview") || saveRoutine.isPending}
+ draftConflicted={saveConflict}
+ historicalPreview={false}
+ locationHash={typeof window === "undefined" ? "" : window.location.hash}
+ panelOpen={descriptionAnnotationsOpen}
+ onPanelOpenChange={setDescriptionAnnotationsOpen}
+ >
+ <MarkdownEditor
+ ref={descriptionEditorRef}
+ value={editDraft.description}
+ onChange={(description) => setEditDraft((current) => ({ ...current, description }))}
+ placeholder="Add instructions..."
+ bordered={false}
+ contentClassName="min-h-(--sz-120px) text-sm leading-7"
+ mentions={mentionOptions}
+ onSubmit={() => {
+ if (!saveRoutine.isPending && editDraft.title.trim()) {
+ saveRoutine.mutate();
+ }
+ }}
+ />
+ </IssueDocumentAnnotations>
+ ) : (
+ <MarkdownEditor
+ ref={descriptionEditorRef}
+ value={editDraft.description}
+ onChange={(description) => setEditDraft((current) => ({ ...current, description }))}
+ placeholder="Add instructions..."
+ bordered={false}
+ contentClassName="min-h-(--sz-120px) text-sm leading-7"
+ mentions={mentionOptions}
+ onSubmit={() => {
+ if (!saveRoutine.isPending && editDraft.title.trim()) {
+ saveRoutine.mutate();
+ }
+ }}
+ />
+ )}
+ </div>
+
+ {/* Variables peek */}
+ <div className="space-y-3">
+ <RoutineVariablesHint />
+ <RoutineVariablesEditor
+ title={editDraft.title}
+ description={editDraft.description}
+ value={editDraft.variables}
+ onChange={(variables) => setEditDraft((current) => ({ ...current, variables }))}
+ />
+ </div>
+
+ {/* Summary cards */}
+ <div className="grid gap-3 sm:grid-cols-3">
+ <SummaryCard
+ icon={Clock3}
+ label="Triggers"
+ value={activeTriggers === 0 ? "None" : `${activeTriggers} active`}
+ hint={nextFire ? `Next fire ${nextFire}` : "No schedule"}
+ to={() => navigateToSection("triggers")}
+ ariaLabel={`${activeTriggers} triggers. Open triggers.`}
+ />
+ <SummaryCard
+ icon={KeyRound}
+ label="Secrets"
+ value={boundSecrets === 0 ? "None" : `${boundSecrets} bound`}
+ hint="Manage bound secrets"
+ to={() => navigateToSection("secrets")}
+ ariaLabel={`${boundSecrets} secrets bound. Open secrets.`}
+ />
+ <SummaryCard
+ icon={Play}
+ label="Last run"
+ value={lastRun ? lastRun.status.replaceAll("_", " ") : "No runs"}
+ hint={lastRun ? timeAgo(lastRun.triggeredAt) : "Trigger a run"}
+ to={() => navigateToSection("runs")}
+ ariaLabel={lastRun ? `Last run ${lastRun.status}. Open runs.` : "No runs. Open runs."}
+ />
+ </div>
+
+ {/* Recent activity */}
+ <div className="space-y-2">
+ <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ Recent activity
+ </p>
+ {recentActivity.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No activity yet.</p>
+ ) : (
+ <div className="divide-y divide-border/60">
+ {recentActivity.map((event) => (
+ <div key={event.id} className="flex items-center gap-2 py-1.5 text-xs">
+ <Badge variant="outline" className="shrink-0 font-mono">
+ {event.action}
+ </Badge>
+ <span className="min-w-0 flex-1 truncate text-muted-foreground">
+ {event.details && Object.keys(event.details).length > 0
+ ? Object.keys(event.details).slice(0, 3).join(" · ")
+ : ""}
+ </span>
+ <span className="shrink-0 text-muted-foreground/60">{timeAgo(event.createdAt)}</span>
+ </div>
+ ))}
+ <button
+ type="button"
+ onClick={() => navigateToSection("activity")}
+ className="flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground"
+ >
+ View all activity <ArrowRight className="h-3 w-3" />
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function SummaryCard({
+ icon: Icon,
+ label,
+ value,
+ hint,
+ to,
+ ariaLabel,
+}: {
+ icon: typeof Clock3;
+ label: string;
+ value: string;
+ hint: string;
+ to: () => void;
+ ariaLabel: string;
+}) {
+ return (
+ <button type="button" onClick={to} aria-label={ariaLabel} className="text-left">
+ <Card className="gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30">
+ <CardContent className="space-y-1 p-0">
+ <div className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground">
+ <Icon className="h-3.5 w-3.5" />
+ {label}
+ <ArrowRight className="ml-auto h-3.5 w-3.5 text-muted-foreground/60" />
+ </div>
+ <p className="text-lg font-semibold">{value}</p>
+ <p className="text-xs text-muted-foreground">{hint}</p>
+ </CardContent>
+ </Card>
+ </button>
+ );
+}
+
+export function TriggersSection() {
+ const ctx = useRoutineDetail();
+ const { routine, newTrigger, setNewTrigger, createTrigger, updateTrigger, deleteTrigger, rotateTrigger } = ctx;
+ const [addOpen, setAddOpen] = useState(false);
+ const [newScheduleEditorValid, setNewScheduleEditorValid] = useState(true);
+ const newScheduleValidation = useMemo(
+ () => newTrigger.kind === "schedule" ? getScheduleCronValidation(newTrigger.cronExpression) : null,
+ [newTrigger.cronExpression, newTrigger.kind],
+ );
+ const addDisabled =
+ createTrigger.isPending ||
+ (newScheduleValidation ? !newScheduleValidation.valid || !newScheduleEditorValid : false);
+
+ useEffect(() => {
+ if (newTrigger.kind !== "schedule") setNewScheduleEditorValid(true);
+ }, [newTrigger.kind]);
+
+ return (
+ <div className="space-y-4">
+ {/* Add-trigger drawer header (§3.2) */}
+ <div className="flex items-center justify-between">
+ <p className="text-sm font-medium text-muted-foreground">
+ {routine.triggers.length === 0
+ ? "No triggers yet"
+ : `${routine.triggers.length} trigger${routine.triggers.length === 1 ? "" : "s"}`}
+ </p>
+ <Button
+ size="sm"
+ variant={addOpen ? "secondary" : "default"}
+ onClick={() => setAddOpen((open) => !open)}
+ aria-expanded={addOpen}
+ >
+ {addOpen ? (
+ <>
+ <X className="mr-1.5 h-3.5 w-3.5" />
+ Cancel
+ </>
+ ) : (
+ <>
+ <Plus className="mr-1.5 h-3.5 w-3.5" />
+ New trigger
+ </>
+ )}
+ </Button>
+ </div>
+
+ {/* Add trigger form — expand-on-click drawer */}
+ {addOpen ? (
+ <div className="space-y-3 rounded-lg border border-border p-4">
+ <p className="text-sm font-medium">Add trigger</p>
+ <div className="grid gap-3 md:grid-cols-2">
+ <div className="space-y-1.5">
+ <Label className="text-xs">Kind</Label>
+ <Select
+ value={newTrigger.kind}
+ onValueChange={(kind) => setNewTrigger((current) => ({ ...current, kind }))}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {triggerKinds.map((kind) => (
+ <SelectItem key={kind} value={kind} disabled={kind === "webhook"}>
+ {kind}
+ {kind === "webhook" ? " — COMING SOON" : ""}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {newTrigger.kind === "schedule" && (
+ <div className="space-y-1.5 md:col-span-2">
+ <Label className="text-xs">Schedule</Label>
+ <ScheduleEditor
+ value={newTrigger.cronExpression}
+ onChange={(cronExpression) =>
+ setNewTrigger((current) => ({ ...current, cronExpression }))
+ }
+ onValidityChange={setNewScheduleEditorValid}
+ />
+ </div>
+ )}
+ {newTrigger.kind === "webhook" && (
+ <>
+ <div className="space-y-1.5">
+ <Label className="text-xs">Signing mode</Label>
+ <Select
+ value={newTrigger.signingMode}
+ onValueChange={(signingMode) =>
+ setNewTrigger((current) => ({ ...current, signingMode }))
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {signingModes.map((mode) => (
+ <SelectItem key={mode} value={mode}>
+ {mode}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">
+ {signingModeDescriptions[newTrigger.signingMode]}
+ </p>
+ </div>
+ {!SIGNING_MODES_WITHOUT_REPLAY_WINDOW.has(newTrigger.signingMode) && (
+ <div className="space-y-1.5">
+ <Label className="text-xs">Replay window (seconds)</Label>
+ <Input
+ value={newTrigger.replayWindowSec}
+ onChange={(event) =>
+ setNewTrigger((current) => ({ ...current, replayWindowSec: event.target.value }))
+ }
+ />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ <div className="flex items-center justify-end gap-2">
+ <Button size="sm" variant="ghost" onClick={() => setAddOpen(false)}>
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ onClick={() =>
+ createTrigger.mutate(undefined, {
+ onSuccess: () => {
+ setNewTrigger(createDefaultNewTrigger());
+ setAddOpen(false);
+ },
+ })
+ }
+ disabled={addDisabled}
+ >
+ {createTrigger.isPending ? "Adding..." : "Add trigger"}
+ </Button>
+ </div>
+ </div>
+ ) : null}
+
+ {/* Existing triggers */}
+ {routine.triggers.length === 0 ? (
+ <EmptyState
+ icon={Clock3}
+ message="No triggers yet."
+ action="Add a schedule"
+ onAction={() => setAddOpen(true)}
+ />
+ ) : (
+ <div className="space-y-3">
+ {routine.triggers.map((trigger) => (
+ <RoutineTriggerCard
+ key={trigger.id}
+ trigger={trigger}
+ onSave={(id, patch) => updateTrigger.mutate({ id, patch })}
+ onRotate={(id) => rotateTrigger.mutate(id)}
+ onDelete={(id) => deleteTrigger.mutate(id)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function VariablesSection() {
+ const ctx = useRoutineDetail();
+ const { editDraft, setEditDraft, navigateToSection } = ctx;
+ const hasVariables = editDraft.variables.length > 0;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs">
+ <span className="flex-1 text-muted-foreground">
+ Variables are auto-detected from <code className="font-mono">{"{{placeholders}}"}</code> in
+ the title &amp; instructions. The variable name is read-only — rename by editing the
+ placeholder.
+ </span>
+ <Button variant="secondary" size="sm" onClick={() => navigateToSection("overview")}>
+ <Edit3 className="mr-1.5 h-3.5 w-3.5" />
+ Edit instructions
+ </Button>
+ </div>
+
+ {hasVariables ? (
+ <RoutineVariablesEditor
+ title={editDraft.title}
+ description={editDraft.description}
+ value={editDraft.variables}
+ onChange={(variables) => setEditDraft((current) => ({ ...current, variables }))}
+ />
+ ) : (
+ <EmptyState
+ icon={Braces}
+ message="No variables yet. Add a {{placeholder}} in the title or instructions to create one."
+ action="Edit instructions"
+ onAction={() => navigateToSection("overview")}
+ />
+ )}
+ </div>
+ );
+}
+
+export function SecretsSection() {
+ const ctx = useRoutineDetail();
+ const { editDraft, setEditDraft, availableSecrets, createSecret, secretMessage, copySecretValue } = ctx;
+
+ // Project/company-scoped secrets that already see real usage, surfaced as
+ // quick-bind chips (§3.4). Ranked by reference count then recency.
+ const recentlyUsedSecrets = useMemo(
+ () =>
+ [...availableSecrets]
+ .filter((secret) => secret.status === "active")
+ .sort((a, b) => {
+ const refDelta = (b.referenceCount ?? 0) - (a.referenceCount ?? 0);
+ if (refDelta !== 0) return refDelta;
+ return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
+ })
+ .slice(0, 8),
+ [availableSecrets],
+ );
+
+ return (
+ <div className="space-y-4">
+ <div className="rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground">
+ Routine secrets apply to every task this routine creates. They override matching keys in
+ project and agent env. <span className="font-mono">PAPERCLIP_*</span> names are reserved.
+ </div>
+
+ {secretMessage ? (
+ <div className="space-y-3 rounded-lg border border-blue-500/30 bg-blue-500/5 p-4 text-sm">
+ <div>
+ <p className="font-medium">{secretMessage.title}</p>
+ <p className="text-xs text-muted-foreground">
+ Save this now. Paperclip will not show the secret value again.
+ </p>
+ </div>
+ <div className="space-y-3">
+ {secretMessage.entries.map((entry, index) => (
+ <div key={`${entry.webhookUrl}-${index}`} className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Input value={entry.webhookUrl} readOnly className="flex-1" />
+ <Button variant="outline" size="sm" onClick={() => copySecretValue("Webhook URL", entry.webhookUrl)}>
+ URL
+ </Button>
+ </div>
+ <div className="flex items-center gap-2">
+ <Input value={entry.webhookSecret} readOnly className="flex-1" />
+ <Button variant="outline" size="sm" onClick={() => copySecretValue("Webhook secret", entry.webhookSecret)}>
+ Secret
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ <EnvironmentVariablesEditor
+ value={(editDraft.env ?? {}) as Record<string, EnvBinding>}
+ secrets={availableSecrets}
+ recentlyUsedSecrets={recentlyUsedSecrets}
+ onCreateSecret={async (name, value) => createSecret.mutateAsync({ name, value })}
+ onChange={(env) => setEditDraft((current) => ({ ...current, env: env ?? null }))}
+ />
+ </div>
+ );
+}
+
+export function DeliverySection() {
+ const ctx = useRoutineDetail();
+ const { editDraft, setEditDraft, routine } = ctx;
+
+ // The activity gate only affects schedule ticks (webhook/manual/API fires are
+ // themselves activity and always run), so the control is only meaningful for
+ // routines that have a schedule trigger. Disable — rather than hide — it
+ // elsewhere so the capability stays discoverable.
+ const hasScheduleTrigger = routine.triggers.some((trigger) => trigger.kind === "schedule");
+ const gateEnabled = editDraft.activityGatePolicy === "require_external_activity";
+
+ return (
+ <div className="space-y-6">
+ <div className="space-y-3">
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
+ Concurrency
+ </p>
+ <RadioCardGroup
+ ariaLabel="Concurrency policy"
+ value={editDraft.concurrencyPolicy}
+ onValueChange={(concurrencyPolicy) =>
+ setEditDraft((current) => ({ ...current, concurrencyPolicy }))
+ }
+ options={concurrencyPolicyOptions}
+ />
+ </div>
+ <div className="space-y-3">
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
+ Catch-up
+ </p>
+ <RadioCardGroup
+ ariaLabel="Catch-up policy"
+ value={editDraft.catchUpPolicy}
+ onValueChange={(catchUpPolicy) =>
+ setEditDraft((current) => ({ ...current, catchUpPolicy }))
+ }
+ options={catchUpPolicyOptions}
+ />
+ </div>
+ <div className="space-y-3">
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
+ Advanced run policy
+ </p>
+ <RadioCardGroup
+ ariaLabel="Advanced run policy"
+ value={editDraft.activityGatePolicy}
+ onValueChange={(activityGatePolicy) =>
+ setEditDraft((current) => ({ ...current, activityGatePolicy }))
+ }
+ options={activityGatePolicyOptions}
+ disabled={!hasScheduleTrigger}
+ />
+ {!hasScheduleTrigger ? (
+ <p className="text-xs text-muted-foreground">
+ Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always
+ run.
+ </p>
+ ) : gateEnabled ? (
+ <div className="space-y-2 rounded-lg border border-border p-3">
+ <Label className="text-xs font-medium">Activity scope</Label>
+ <RadioCardGroup
+ ariaLabel="Activity gate scope"
+ value={editDraft.activityGateScope}
+ onValueChange={(activityGateScope) =>
+ setEditDraft((current) => ({ ...current, activityGateScope }))
+ }
+ options={activityGateScopeOptions}
+ />
+ </div>
+ ) : null}
+ </div>
+ <NextFiresPreview
+ triggers={routine.triggers}
+ concurrencyPolicy={editDraft.concurrencyPolicy}
+ />
+ </div>
+ );
+}
+
+const dispositionToneClass: Record<string, string> = {
+ queued: "text-emerald-600 dark:text-emerald-400",
+ coalesced: "text-amber-600 dark:text-amber-400",
+ skipped: "text-muted-foreground",
+};
+
+/**
+ * "Next 5 fires" preview (§3.5) — the strongest "what does this policy mean?"
+ * surface. Picks the soonest-firing schedule trigger, computes its next fires
+ * client-side, and annotates each with how the chosen concurrency policy would
+ * treat it.
+ */
+function NextFiresPreview({
+ triggers,
+ concurrencyPolicy,
+}: {
+ triggers: RoutineDetailType["triggers"];
+ concurrencyPolicy: string;
+}) {
+ const preview = useMemo(() => {
+ const schedule = triggers
+ .filter((trigger) => trigger.kind === "schedule" && trigger.enabled && trigger.cronExpression)
+ .map((trigger) => {
+ const fires = nextCronFires(trigger.cronExpression, 5, {
+ timeZone: trigger.timezone ?? "UTC",
+ });
+ return { trigger, fires };
+ })
+ .filter((entry) => entry.fires.length > 0)
+ .sort((a, b) => a.fires[0]!.getTime() - b.fires[0]!.getTime())[0];
+ if (!schedule) return null;
+ return {
+ timeZone: schedule.trigger.timezone ?? "UTC",
+ entries: previewFirePolicies(schedule.fires, concurrencyPolicy),
+ };
+ }, [triggers, concurrencyPolicy]);
+
+ return (
+ <div className="space-y-3">
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">
+ Next 5 fires
+ </p>
+ {preview ? (
+ <>
+ <div className="space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs">
+ {preview.entries.map((entry, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <span className="text-muted-foreground/40">·</span>
+ <span className="tabular-nums">{formatFireTime(entry.at, preview.timeZone)}</span>
+ <ArrowRight className="h-3 w-3 shrink-0 text-muted-foreground/50" />
+ <span className={cn("font-medium", dispositionToneClass[entry.disposition])}>
+ {entry.label}
+ </span>
+ {entry.note ? (
+ <span className="truncate text-muted-foreground/60">({entry.note})</span>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ <p className="text-(length:--text-micro) text-muted-foreground/60">
+ Preview assumes the previous run is still in flight when the next fires. Times shown in{" "}
+ {preview.timeZone}.
+ </p>
+ </>
+ ) : (
+ <p className="rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground">
+ No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy
+ treats upcoming fires.
+ </p>
+ )}
+ </div>
+ );
+}
+
+function formatFireTime(date: Date, timeZone: string): string {
+ try {
+ return new Intl.DateTimeFormat(undefined, {
+ timeZone,
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ hourCycle: "h23",
+ })
+ .format(date)
+ .replace(",", "");
+ } catch {
+ return date.toISOString();
+ }
+}
diff --git a/ui/src/components/routine-sections/editable-sections.tsx b/ui/src/components/routine-sections/editable-sections.tsx
index a80ff3d4ba..4321a3ec44 100644
--- a/ui/src/components/routine-sections/editable-sections.tsx
+++ b/ui/src/components/routine-sections/editable-sections.tsx
@@ -4,7 +4,6 @@ import {
Braces,
Clock3,
Edit3,
- KeyRound,
Play,
Plus,
X,
@@ -144,7 +143,6 @@ export function OverviewSection({
.sort((a, b) => a.getTime() - b.getTime())[0];
return upcoming ? upcoming.toLocaleString() : null;
}, [routine.triggers]);
- const boundSecrets = editDraft.env ? Object.keys(editDraft.env).length : 0;
const lastRun = (routineRuns ?? [])[0] ?? null;
const recentActivity = (activity ?? []).slice(0, 5);
@@ -320,7 +318,7 @@ export function OverviewSection({
</div>
{/* Summary cards */}
- <div className="grid gap-3 sm:grid-cols-3">
+ <div className="grid gap-3 sm:grid-cols-2">
<SummaryCard
icon={Clock3}
label="Triggers"
@@ -329,14 +327,6 @@ export function OverviewSection({
to={() => navigateToSection("triggers")}
ariaLabel={`${activeTriggers} triggers. Open triggers.`}
/>
- <SummaryCard
- icon={KeyRound}
- label="Secrets"
- value={boundSecrets === 0 ? "None" : `${boundSecrets} bound`}
- hint="Manage bound secrets"
- to={() => navigateToSection("secrets")}
- ariaLabel={`${boundSecrets} secrets bound. Open secrets.`}
- />
<SummaryCard
icon={Play}
label="Last run"
diff --git a/ui/src/pages/AgentDetail.instructions.test.tsx b/ui/src/pages/AgentDetail.instructions.test.tsx
index 1d3ab7b8ee..bd33d7c435 100644
--- a/ui/src/pages/AgentDetail.instructions.test.tsx
+++ b/ui/src/pages/AgentDetail.instructions.test.tsx
@@ -78,6 +78,10 @@ vi.mock("../components/MarkdownEditor", () => ({
},
}));
+vi.mock("../components/MarkdownBody", () => ({
+ MarkdownBody: ({ children }: { children: string }) => <div data-testid="markdown-body">{children}</div>,
+}));
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
@@ -279,6 +283,13 @@ describe("PromptsTab instruction editor", () => {
await flushReact();
}
+ async function selectInstructionMode(mode: "Read" | "Edit" | "Raw") {
+ await act(async () => {
+ buttonByText(container, mode.toLowerCase()).click();
+ });
+ await flushReact();
+ }
+
it("uses server markdown metadata for extensionless files and saves MarkdownEditor drafts", async () => {
const summary = makeSummary("AGENTS", "AGENTS", {
language: "markdown",
@@ -289,6 +300,13 @@ describe("PromptsTab instruction editor", () => {
{ AGENTS: makeDetail(summary, "# Current") },
);
+ await waitFor(() => {
+ expect(container.querySelector('[data-testid="markdown-body"]')?.textContent).toBe("# Current");
+ });
+ await selectInstructionMode("Raw");
+ expect(container.querySelector('[data-testid="instructions-raw-source"]')?.textContent?.trim()).toBe("# Current");
+ await selectInstructionMode("Edit");
+
const editor = await waitFor(() => {
const candidate = container.querySelector<HTMLTextAreaElement>('[data-testid="markdown-editor"]');
expect(candidate).not.toBeNull();
@@ -330,6 +348,7 @@ describe("PromptsTab instruction editor", () => {
{ "AGENTS.md": makeDetail(summary, "# Current") },
{ onDirtyChange },
);
+ await selectInstructionMode("Edit");
const editorProps = await waitFor(() => {
const latest = markdownEditorRenderMock.mock.calls.at(-1)?.[0] as
@@ -364,6 +383,7 @@ describe("PromptsTab instruction editor", () => {
onCancelActionChange: (next) => { cancelAction = next; },
},
);
+ await selectInstructionMode("Edit");
const editor = await waitFor(() => {
const candidate = container.querySelector<HTMLTextAreaElement>('[data-testid="markdown-editor"]');
@@ -401,6 +421,7 @@ describe("PromptsTab instruction editor", () => {
{ "settings.json": makeDetail(summary, "{\n \"ok\": true\n}") },
);
+ await selectInstructionMode("Edit");
await waitFor(() => {
expect(container.querySelector<HTMLTextAreaElement>('textarea[placeholder="File contents"]')).not.toBeNull();
});
@@ -417,6 +438,7 @@ describe("PromptsTab instruction editor", () => {
buttonByText(container, "Create").click();
});
+ await selectInstructionMode("Edit");
await waitFor(() => {
expect(container.querySelector('[data-testid="markdown-editor"]')).not.toBeNull();
});
@@ -433,6 +455,7 @@ describe("PromptsTab instruction editor", () => {
{ "FALLBACK.md": makeDetail(summary, "# Fallback", { markdown: undefined }) },
);
+ await selectInstructionMode("Edit");
await waitFor(() => {
expect(container.querySelector("[data-testid=\"markdown-editor\"]")).not.toBeNull();
expect(markdownEditorRenderMock).toHaveBeenLastCalledWith(expect.objectContaining({
@@ -451,6 +474,7 @@ describe("PromptsTab instruction editor", () => {
{ "NOTES.md": makeDetail(summary, "raw instructions") },
);
+ await selectInstructionMode("Edit");
await waitFor(() => {
expect(container.querySelector('[data-testid="markdown-editor"]')).toBeNull();
expect(container.querySelector<HTMLTextAreaElement>('textarea[placeholder="File contents"]')?.value).toBe("raw instructions");
diff --git a/ui/src/pages/AgentDetail.production.tsx b/ui/src/pages/AgentDetail.production.tsx
new file mode 100644
index 0000000000..6bc2a0ce0e
--- /dev/null
+++ b/ui/src/pages/AgentDetail.production.tsx
@@ -0,0 +1,4516 @@
+import { useCallback, useEffect, useMemo, useState, useRef } from "react";
+import { useParams, useNavigate, Link, Navigate, useBeforeUnload, type NavigateFunction } from "@/lib/router";
+import { useQuery, useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import {
+ agentsApi,
+ type AgentKey,
+ type ClaudeLoginResult,
+ type AgentPermissionUpdate,
+} from "../api/agents";
+import { builtInAgentsApi, type BuiltInManagedResourceKind } from "../api/builtInAgents";
+import { companySkillsApi } from "../api/companySkills";
+import { budgetsApi } from "../api/budgets";
+import { heartbeatsApi } from "../api/heartbeats";
+import { instanceSettingsApi } from "../api/instanceSettings";
+import { ApiError } from "../api/client";
+import { ChartCard, RunActivityChart, PriorityChart, IssueStatusChart, SuccessRateChart } from "../components/ActivityCharts";
+import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
+import { activityApi } from "../api/activity";
+import { accessApi } from "../api/access";
+import { issuesApi } from "../api/issues";
+import { projectsApi } from "../api/projects";
+import { usePanel } from "../context/PanelContext";
+import { useSidebar } from "../context/SidebarContext";
+import { useCompany } from "../context/CompanyContext";
+import { useToastActions } from "../context/ToastContext";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { queryKeys } from "../lib/queryKeys";
+import { copyTextToClipboard } from "../lib/clipboard";
+import { AgentSkillsTab } from "./agent-skills/AgentSkillsTab";
+import { AgentConfigForm } from "../components/AgentConfigForm";
+import { PageTabBar } from "../components/PageTabBar";
+import { adapterLabels, roleLabels, help } from "../components/agent-config-primitives";
+import { ToggleSwitch } from "@/components/ui/toggle-switch";
+import { useAdapterCapabilities } from "@/adapters/use-adapter-capabilities";
+import { redactCommandText as redactCommandSecretText } from "@paperclipai/adapter-utils";
+import { MarkdownEditor } from "../components/MarkdownEditor";
+import { assetsApi } from "../api/assets";
+import { toolsApi } from "../api/tools";
+import { getUIAdapter, buildTranscript, onAdapterChange } from "../adapters";
+import { StatusBadge } from "../components/StatusBadge";
+import { MarkdownBody } from "../components/MarkdownBody";
+import { CopyText } from "../components/CopyText";
+import { EntityRow } from "../components/EntityRow";
+import { StatusGlyph } from "../components/StatusGlyph";
+import { MembershipAction } from "../components/MembershipAction";
+import { StarToggle } from "../components/StarToggle";
+import { Identity } from "../components/Identity";
+import { AuditFeed } from "./audit/AuditFeed.production";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { AgentActionButtons } from "../components/AgentActionButtons";
+import { InlineBanner } from "../components/InlineBanner";
+import { BuiltInBundlePanel } from "../components/BuiltInBundlePanel";
+import { ConfigureBuiltInAgentModal } from "../components/ConfigureBuiltInAgentModal";
+import { BudgetPolicyCard } from "../components/BudgetPolicyCard";
+import { TrustPresetSection } from "../components/TrustPresetSection";
+import { FileTree, buildFileTree } from "../components/FileTree";
+import { ScrollToBottom } from "../components/ScrollToBottom";
+import { SourceResolvedFoldCallout } from "../components/SourceResolvedFoldCallout";
+import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";
+import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
+import { buildSameOriginWebSocketUrl } from "../lib/websocket-url";
+import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";
+import { cn } from "../lib/utils";
+import { describeRunRetryState } from "../lib/runRetryState";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tabs } from "@/components/ui/tabs";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ CheckCircle2,
+ XCircle,
+ Clock,
+ Timer,
+ Loader2,
+ Slash,
+ RotateCcw,
+ Plus,
+ Key,
+ Eye,
+ EyeOff,
+ Copy,
+ ChevronRight,
+ ChevronDown,
+ ArrowLeft,
+ HelpCircle,
+ FolderOpen,
+ AlertTriangle,
+} from "lucide-react";
+import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "@/components/ui/collapsible";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { Input } from "@/components/ui/input";
+import { AgentIcon, AgentIconPicker } from "../components/AgentIconPicker";
+import { RunTranscriptView, type TranscriptMode } from "../components/transcript/RunTranscriptView";
+import { AgentToolsTab } from "./AgentToolsTab";
+import {
+ appendCapped,
+ LIVE_TRANSCRIPT_RENDER_LIMIT,
+ MAX_LIVE_EVENTS,
+ MAX_LIVE_LOG_LINES,
+} from "../lib/live-log-buffer";
+import {
+ isUuidLike,
+ type Agent,
+ type AgentDetail as AgentDetailRecord,
+ type BudgetPolicySummary,
+ type HeartbeatRun,
+ type HeartbeatRunEvent,
+ type AgentRuntimeState,
+ type LiveEvent,
+ type WorkspaceOperation,
+ isResponsibleUserDenialCode,
+ responsibleUserLabel,
+} from "@paperclipai/shared";
+import { ResponsibleUserDenialNotice } from "../components/ResponsibleUserDenialNotice";
+import { RunWorkspaceRecoverySurface } from "../components/RunWorkspaceRecoverySurface";
+import { buildPermissionsForTrustPreset, getTrustPreset } from "../lib/trust-policy-ui";
+import { redactHomePathUserSegments, redactHomePathUserSegmentsInValue } from "@paperclipai/adapter-utils";
+import { agentRouteRef } from "../lib/utils";
+import {
+ isStarred,
+ resourceMembershipState,
+ useResourceMembershipMutation,
+ useResourceMemberships,
+} from "../hooks/useResourceMemberships";
+import { Badge } from "@/components/ui/badge";
+
+const runStatusIcons: Record<string, { icon: typeof CheckCircle2; color: string }> = {
+ succeeded: { icon: CheckCircle2, color: "text-green-600 dark:text-green-400" },
+ failed: { icon: XCircle, color: "text-red-600 dark:text-red-400" },
+ running: { icon: Loader2, color: "text-blue-600 dark:text-blue-400" }, // Gallery feedback r1: running = status blue, not cyan.
+ queued: { icon: Clock, color: "text-yellow-600 dark:text-yellow-400" },
+ scheduled_retry: { icon: Clock, color: "text-sky-600 dark:text-sky-400" },
+ timed_out: { icon: Timer, color: "text-orange-600 dark:text-orange-400" },
+ cancelled: { icon: Slash, color: "text-neutral-500 dark:text-neutral-400" },
+};
+
+const RUN_LOG_PAGE_BYTES = 256_000;
+
+const REDACTED_ENV_VALUE = "***REDACTED***";
+const SECRET_ENV_KEY_RE =
+ /(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i;
+const COMMAND_ENV_KEY_RE = /(^command$|^cmd$|command[-_]?line|resolved[-_]?command|PAPERCLIP_RESOLVED_COMMAND)/i;
+const JWT_VALUE_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/;
+
+function formatOrgChainHealthPath(agent: AgentDetailRecord) {
+ return agent.orgChainHealth?.fullChain
+ .map((entry) => `${entry.name}${entry.status !== "active" && entry.status !== "idle" ? ` (${entry.status})` : ""}`)
+ .join(" -> ") ?? agent.name;
+}
+
+function redactPathText(value: string, censorUsernameInLogs: boolean) {
+ return redactHomePathUserSegments(value, { enabled: censorUsernameInLogs });
+}
+
+function redactPathValue<T>(value: T, censorUsernameInLogs: boolean): T {
+ return redactHomePathUserSegmentsInValue(value, { enabled: censorUsernameInLogs });
+}
+
+function redactCommandText(value: string, censorUsernameInLogs: boolean): string {
+ return redactPathText(redactCommandSecretText(value, REDACTED_ENV_VALUE), censorUsernameInLogs);
+}
+
+function shouldRedactSecretValue(key: string, value: unknown): boolean {
+ if (SECRET_ENV_KEY_RE.test(key)) return true;
+ if (typeof value !== "string") return false;
+ return JWT_VALUE_RE.test(value);
+}
+
+function redactEnvValue(key: string, value: unknown, censorUsernameInLogs: boolean): string {
+ if (
+ typeof value === "object" &&
+ value !== null &&
+ !Array.isArray(value) &&
+ (value as { type?: unknown }).type === "secret_ref"
+ ) {
+ return "***SECRET_REF***";
+ }
+ if (shouldRedactSecretValue(key, value)) return REDACTED_ENV_VALUE;
+ if (value === null || value === undefined) return "";
+ if (typeof value === "string" && COMMAND_ENV_KEY_RE.test(key)) return redactCommandText(value, censorUsernameInLogs);
+ if (typeof value === "string") return redactPathText(value, censorUsernameInLogs);
+ try {
+ return JSON.stringify(redactPathValue(value, censorUsernameInLogs));
+ } catch {
+ return redactPathText(String(value), censorUsernameInLogs);
+ }
+}
+
+function isMarkdown(pathValue: string) {
+ return pathValue.toLowerCase().endsWith(".md");
+}
+
+function shouldUseMarkdownInstructionsEditor(input: {
+ selectedFileExists: boolean;
+ selectedPath: string;
+ detail?: { markdown?: boolean } | null;
+ summary?: { markdown?: boolean } | null;
+}) {
+ const metadataMarkdown = input.detail?.markdown ?? input.summary?.markdown;
+ if (typeof metadataMarkdown === "boolean") return metadataMarkdown;
+ return isMarkdown(input.selectedPath);
+}
+
+function formatEnvForDisplay(envValue: unknown, censorUsernameInLogs: boolean): string {
+ const env = asRecord(envValue);
+ if (!env) return "<unable-to-parse>";
+
+ const keys = Object.keys(env);
+ if (keys.length === 0) return "<empty>";
+
+ return keys
+ .sort()
+ .map((key) => `${key}=${redactEnvValue(key, env[key], censorUsernameInLogs)}`)
+ .join("\n");
+}
+
+const sourceLabels: Record<string, string> = {
+ timer: "Timer",
+ assignment: "Assignment",
+ on_demand: "On-demand",
+ automation: "Automation",
+};
+
+const LIVE_SCROLL_BOTTOM_TOLERANCE_PX = 32;
+type ScrollContainer = Window | HTMLElement;
+
+function isWindowContainer(container: ScrollContainer): container is Window {
+ return container === window;
+}
+
+function isElementScrollContainer(element: HTMLElement): boolean {
+ const overflowY = window.getComputedStyle(element).overflowY;
+ return overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay";
+}
+
+function findScrollContainer(anchor: HTMLElement | null): ScrollContainer {
+ let parent = anchor?.parentElement ?? null;
+ while (parent) {
+ if (isElementScrollContainer(parent)) return parent;
+ parent = parent.parentElement;
+ }
+ return window;
+}
+
+function readScrollMetrics(container: ScrollContainer): { scrollHeight: number; distanceFromBottom: number } {
+ if (isWindowContainer(container)) {
+ const pageHeight = Math.max(
+ document.documentElement.scrollHeight,
+ document.body.scrollHeight,
+ );
+ const viewportBottom = window.scrollY + window.innerHeight;
+ return {
+ scrollHeight: pageHeight,
+ distanceFromBottom: Math.max(0, pageHeight - viewportBottom),
+ };
+ }
+
+ const viewportBottom = container.scrollTop + container.clientHeight;
+ return {
+ scrollHeight: container.scrollHeight,
+ distanceFromBottom: Math.max(0, container.scrollHeight - viewportBottom),
+ };
+}
+
+function scrollToContainerBottom(container: ScrollContainer, behavior: ScrollBehavior = "auto") {
+ if (isWindowContainer(container)) {
+ const pageHeight = Math.max(
+ document.documentElement.scrollHeight,
+ document.body.scrollHeight,
+ );
+ window.scrollTo({ top: pageHeight, behavior });
+ return;
+ }
+
+ container.scrollTo({ top: container.scrollHeight, behavior });
+}
+
+type AgentDetailView = "dashboard" | "instructions" | "configuration" | "secrets" | "skills" | "tools" | "runs" | "audit" | "budget";
+
+export const AGENT_DETAIL_TABS: ReadonlyArray<{ value: AgentDetailView; label: string }> = [
+ { value: "dashboard", label: "Dashboard" },
+ { value: "instructions", label: "Instructions" },
+ { value: "skills", label: "Skills" },
+ { value: "configuration", label: "Configuration" },
+ { value: "secrets", label: "Secrets" },
+ { value: "tools", label: "Tools" },
+ { value: "runs", label: "Runs" },
+ { value: "audit", label: "Audit" },
+ { value: "budget", label: "Budget" },
+];
+
+export const DISCARD_AGENT_CONFIG_CHANGES_MESSAGE = "Discard unsaved agent configuration changes?";
+
+export function confirmAgentConfigNavigation(
+ dirty: boolean,
+ confirm: (message: string) => boolean = (message) =>
+ typeof window === "undefined" || window.confirm(message),
+): boolean {
+ return !dirty || confirm(DISCARD_AGENT_CONFIG_CHANGES_MESSAGE);
+}
+
+export function agentConfigHistoryRestoreDelta(currentIndex: unknown, nextIndex: unknown): number | null {
+ if (typeof currentIndex !== "number" || typeof nextIndex !== "number") return null;
+ const delta = currentIndex - nextIndex;
+ return delta === 0 ? null : delta;
+}
+
+export function restoreAgentConfigHistoryEntry(
+ history: Pick<History, "go" | "pushState">,
+ currentEntry: { index: unknown; state: unknown; url: string },
+ nextIndex: unknown,
+): boolean {
+ const restoreDelta = agentConfigHistoryRestoreDelta(currentEntry.index, nextIndex);
+ if (restoreDelta === null) {
+ // Some legacy URL-cleanup paths erased React Router's history index. A
+ // fresh copy of the guarded entry is the only safe way to return without
+ // letting Router consume the unindexed destination and discard the form.
+ history.pushState(currentEntry.state, "", currentEntry.url);
+ return false;
+ }
+
+ history.go(restoreDelta);
+ return true;
+}
+
+export function parseAgentDetailView(value: string | null): AgentDetailView {
+ if (value === "instructions" || value === "prompts") return "instructions";
+ if (value === "configure" || value === "configuration") return "configuration";
+ if (value === "secrets") return "secrets";
+ if (value === "skills") return "skills";
+ if (value === "tools") return "tools";
+ if (value === "budget") return "budget";
+ if (value === "audit") return "audit";
+ if (value === "runs") return value;
+ return "dashboard";
+}
+
+function usageNumber(usage: Record<string, unknown> | null, ...keys: string[]) {
+ if (!usage) return 0;
+ for (const key of keys) {
+ const value = usage[key];
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ }
+ return 0;
+}
+
+function setsEqual<T>(left: Set<T>, right: Set<T>) {
+ if (left.size !== right.size) return false;
+ for (const value of left) {
+ if (!right.has(value)) return false;
+ }
+ return true;
+}
+
+function runMetrics(run: HeartbeatRun) {
+ const usage = (run.usageJson ?? null) as Record<string, unknown> | null;
+ const result = (run.resultJson ?? null) as Record<string, unknown> | null;
+ const input = usageNumber(usage, "inputTokens", "input_tokens");
+ const output = usageNumber(usage, "outputTokens", "output_tokens");
+ const cached = usageNumber(
+ usage,
+ "cachedInputTokens",
+ "cached_input_tokens",
+ "cache_read_input_tokens",
+ );
+ const cost =
+ visibleRunCostUsd(usage, result);
+ const provider = asNonEmptyString(usage?.provider) ?? null;
+ const model = asNonEmptyString(usage?.model) ?? null;
+ return {
+ input,
+ output,
+ cached,
+ cost,
+ totalTokens: input + output,
+ provider,
+ model,
+ };
+}
+
+export type RunLogChunk = {
+ ts: string;
+ stream: "stdout" | "stderr" | "system";
+ chunk: string;
+};
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
+}
+
+function asNonEmptyString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+export function buildHeartbeatProgressLogLine(
+ payload: Record<string, unknown>,
+ fallbackTimestamp: string,
+): RunLogChunk | null {
+ const message = asNonEmptyString(payload.message);
+ if (!message) return null;
+ const phase = asNonEmptyString(payload.phase);
+ const ts = asNonEmptyString(payload.updatedAt) ?? fallbackTimestamp;
+ const chunk = phase ? `[${phase}] ${message}` : message;
+ return { ts, stream: "system", chunk };
+}
+
+export function heartbeatProgressLogLineKey(line: RunLogChunk): string {
+ return `${line.ts}\u0000${line.stream}\u0000${line.chunk}`;
+}
+
+export function shouldPollRunShellLog(status: HeartbeatRun["status"]): boolean {
+ return status === "running";
+}
+
+export function runDetailRefetchIntervalMs(status: HeartbeatRun["status"]): 5000 | 15000 | false {
+ if (status === "queued") return 5000;
+ if (status === "running") return 15000;
+ return false;
+}
+
+export function RunInvocationCard({
+ payload,
+ censorUsernameInLogs,
+}: {
+ payload: Record<string, unknown>;
+ censorUsernameInLogs: boolean;
+}) {
+ const rawCommandLine = [
+ typeof payload.command === "string" ? payload.command : null,
+ ...(Array.isArray(payload.commandArgs)
+ ? payload.commandArgs.filter((value): value is string => typeof value === "string")
+ : []),
+ ]
+ .filter((value): value is string => Boolean(value))
+ .join(" ");
+ const commandLine = rawCommandLine ? redactCommandText(rawCommandLine, censorUsernameInLogs) : "";
+
+ const hasAdvancedDetails =
+ commandLine.length > 0
+ || (Array.isArray(payload.commandNotes) && payload.commandNotes.length > 0)
+ || payload.prompt !== undefined
+ || payload.context !== undefined
+ || payload.env !== undefined;
+
+ return (
+ <div className="rounded-lg border border-border bg-background/60 p-3 space-y-2">
+ <div className="text-xs font-medium text-muted-foreground">Invocation</div>
+ {typeof payload.adapterType === "string" && (
+ <div className="text-xs"><span className="text-muted-foreground">Adapter: </span>{payload.adapterType}</div>
+ )}
+ {typeof payload.cwd === "string" && (
+ <div className="text-xs break-all"><span className="text-muted-foreground">Working dir: </span><span className="font-mono">{payload.cwd}</span></div>
+ )}
+ {hasAdvancedDetails && (
+ <Collapsible>
+ <CollapsibleTrigger className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors group">
+ <ChevronRight className="h-3 w-3 transition-transform group-data-[state=open]:rotate-90" />
+ Details
+ </CollapsibleTrigger>
+ <CollapsibleContent className="pt-2 space-y-2">
+ {commandLine && (
+ <div className="text-xs break-all">
+ <span className="text-muted-foreground">Command: </span>
+ <span className="font-mono">{commandLine}</span>
+ </div>
+ )}
+ {Array.isArray(payload.commandNotes) && payload.commandNotes.length > 0 && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">Command notes</div>
+ <ul className="list-disc pl-5 space-y-1">
+ {payload.commandNotes
+ .filter((value): value is string => typeof value === "string" && value.trim().length > 0)
+ .map((note, idx) => (
+ <li key={`${idx}-${note}`} className="text-xs break-all font-mono">
+ {note}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {payload.prompt !== undefined && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">Prompt</div>
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap">
+ {typeof payload.prompt === "string"
+ ? redactPathText(payload.prompt, censorUsernameInLogs)
+ : JSON.stringify(redactPathValue(payload.prompt, censorUsernameInLogs), null, 2)}
+ </pre>
+ </div>
+ )}
+ {payload.context !== undefined && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">Context</div>
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap">
+ {JSON.stringify(redactPathValue(payload.context, censorUsernameInLogs), null, 2)}
+ </pre>
+ </div>
+ )}
+ {payload.env !== undefined && (
+ <div>
+ <div className="text-xs text-muted-foreground mb-1">Environment</div>
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap font-mono">
+ {formatEnvForDisplay(payload.env, censorUsernameInLogs)}
+ </pre>
+ </div>
+ )}
+ </CollapsibleContent>
+ </Collapsible>
+ )}
+ </div>
+ );
+}
+
+function parseStoredLogContent(content: string): RunLogChunk[] {
+ const parsed: RunLogChunk[] = [];
+ for (const line of content.split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ const raw = JSON.parse(trimmed) as { ts?: unknown; stream?: unknown; chunk?: unknown };
+ const stream =
+ raw.stream === "stderr" || raw.stream === "system" ? raw.stream : "stdout";
+ const chunk = typeof raw.chunk === "string" ? raw.chunk : "";
+ const ts = typeof raw.ts === "string" ? raw.ts : new Date().toISOString();
+ if (!chunk) continue;
+ parsed.push({ ts, stream, chunk });
+ } catch {
+ // Ignore malformed log lines.
+ }
+ }
+ return parsed;
+}
+
+function workspaceOperationPhaseLabel(phase: WorkspaceOperation["phase"]) {
+ switch (phase) {
+ case "worktree_prepare":
+ return "Worktree setup";
+ case "workspace_config_freshness":
+ return "Config freshness";
+ case "workspace_provision":
+ return "Provision";
+ case "workspace_teardown":
+ return "Teardown";
+ case "worktree_cleanup":
+ return "Worktree cleanup";
+ default:
+ return phase;
+ }
+}
+
+function workspaceOperationStatusTone(status: WorkspaceOperation["status"]) {
+ switch (status) {
+ case "succeeded":
+ return "border-green-500/20 bg-green-500/10 text-green-700 dark:text-green-300";
+ case "failed":
+ return "border-red-500/20 bg-red-500/10 text-red-700 dark:text-red-300";
+ case "running":
+ return "border-blue-500/20 bg-blue-500/10 text-blue-700 dark:text-blue-300";
+ case "skipped":
+ return "border-yellow-500/20 bg-yellow-500/10 text-yellow-700 dark:text-yellow-300";
+ default:
+ return "border-border bg-muted/40 text-muted-foreground";
+ }
+}
+
+function WorkspaceOperationStatusBadge({ status }: { status: WorkspaceOperation["status"] }) {
+ return (
+ <Badge variant="outline"
+ className={cn(
+ "text-(length:--text-micro) capitalize",
+ workspaceOperationStatusTone(status),
+ )}
+ >
+ {status.replace("_", " ")}
+ </Badge>
+ );
+}
+
+function WorkspaceOperationLogViewer({
+ operation,
+ censorUsernameInLogs,
+}: {
+ operation: WorkspaceOperation;
+ censorUsernameInLogs: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const { data: logData, isLoading, error } = useQuery({
+ queryKey: ["workspace-operation-log", operation.id],
+ queryFn: () => heartbeatsApi.workspaceOperationLog(operation.id),
+ enabled: open && Boolean(operation.logRef),
+ refetchInterval: open && operation.status === "running" ? 2000 : false,
+ });
+
+ const chunks = useMemo(
+ () => (logData?.content ? parseStoredLogContent(logData.content) : []),
+ [logData?.content],
+ );
+
+ return (
+ <div className="space-y-2">
+ <button
+ type="button"
+ className="text-(length:--text-micro) text-muted-foreground underline underline-offset-2 hover:text-foreground"
+ onClick={() => setOpen((value) => !value)}
+ >
+ {open ? "Hide full log" : "Show full log"}
+ </button>
+ {open && (
+ <div className="rounded-md border border-border bg-background/70 p-2">
+ {isLoading && <div className="text-xs text-muted-foreground">Loading log...</div>}
+ {error && (
+ <div className="text-xs text-destructive">
+ {error instanceof Error ? error.message : "Failed to load workspace operation log"}
+ </div>
+ )}
+ {!isLoading && !error && chunks.length === 0 && (
+ <div className="text-xs text-muted-foreground">No persisted log lines.</div>
+ )}
+ {chunks.length > 0 && (
+ <div className="max-h-64 overflow-y-auto rounded bg-neutral-100 p-2 font-mono text-xs dark:bg-neutral-950">
+ {chunks.map((chunk, index) => (
+ <div key={`${chunk.ts}-${index}`} className="flex gap-2">
+ <span className="shrink-0 text-neutral-500">
+ {new Date(chunk.ts).toLocaleTimeString("en-US", { hour12: false })}
+ </span>
+ <span
+ className={cn(
+ "shrink-0 w-14",
+ chunk.stream === "stderr"
+ ? "text-red-600 dark:text-red-300"
+ : chunk.stream === "system"
+ ? "text-blue-600 dark:text-blue-300"
+ : "text-muted-foreground",
+ )}
+ >
+ [{chunk.stream}]
+ </span>
+ <span className="whitespace-pre-wrap break-all">{redactPathText(chunk.chunk, censorUsernameInLogs)}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function WorkspaceOperationsSection({
+ operations,
+ censorUsernameInLogs,
+}: {
+ operations: WorkspaceOperation[];
+ censorUsernameInLogs: boolean;
+}) {
+ if (operations.length === 0) return null;
+
+ return (
+ <div className="rounded-lg border border-border bg-background/60 p-3 space-y-3">
+ <div className="text-xs font-medium text-muted-foreground">
+ Workspace ({operations.length})
+ </div>
+ <div className="space-y-3">
+ {operations.map((operation) => {
+ const metadata = asRecord(operation.metadata);
+ return (
+ <div key={operation.id} className="rounded-md border border-border/70 bg-background/70 p-3 space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="text-sm font-medium">{workspaceOperationPhaseLabel(operation.phase)}</div>
+ <WorkspaceOperationStatusBadge status={operation.status} />
+ <div className="text-(length:--text-micro) text-muted-foreground">
+ {relativeTime(operation.startedAt)}
+ {operation.finishedAt && ` to ${relativeTime(operation.finishedAt)}`}
+ </div>
+ </div>
+ {operation.command && (
+ <div className="text-xs break-all">
+ <span className="text-muted-foreground">Command: </span>
+ <span className="font-mono">{operation.command}</span>
+ </div>
+ )}
+ {operation.cwd && (
+ <div className="text-xs break-all">
+ <span className="text-muted-foreground">Working dir: </span>
+ <span className="font-mono">{operation.cwd}</span>
+ </div>
+ )}
+ {(asNonEmptyString(metadata?.branchName)
+ || asNonEmptyString(metadata?.baseRef)
+ || asNonEmptyString(metadata?.worktreePath)
+ || asNonEmptyString(metadata?.repoRoot)
+ || asNonEmptyString(metadata?.cleanupAction)) && (
+ <div className="grid gap-1 text-xs sm:grid-cols-2">
+ {asNonEmptyString(metadata?.branchName) && (
+ <div><span className="text-muted-foreground">Branch: </span><span className="font-mono">{metadata?.branchName as string}</span></div>
+ )}
+ {asNonEmptyString(metadata?.baseRef) && (
+ <div><span className="text-muted-foreground">Base ref: </span><span className="font-mono">{metadata?.baseRef as string}</span></div>
+ )}
+ {asNonEmptyString(metadata?.worktreePath) && (
+ <div className="break-all"><span className="text-muted-foreground">Worktree: </span><span className="font-mono">{metadata?.worktreePath as string}</span></div>
+ )}
+ {asNonEmptyString(metadata?.repoRoot) && (
+ <div className="break-all"><span className="text-muted-foreground">Repo root: </span><span className="font-mono">{metadata?.repoRoot as string}</span></div>
+ )}
+ {asNonEmptyString(metadata?.cleanupAction) && (
+ <div><span className="text-muted-foreground">Cleanup: </span><span className="font-mono">{metadata?.cleanupAction as string}</span></div>
+ )}
+ </div>
+ )}
+ {typeof metadata?.created === "boolean" && (
+ <div className="text-xs text-muted-foreground">
+ {metadata.created ? "Created by this run" : "Reused existing workspace"}
+ </div>
+ )}
+ {operation.stderrExcerpt && operation.stderrExcerpt.trim() && (
+ <div>
+ <div className="mb-1 text-xs text-red-700 dark:text-red-300">stderr excerpt</div>
+ <pre className="rounded-md bg-red-50 p-2 text-xs whitespace-pre-wrap break-all text-red-800 dark:bg-neutral-950 dark:text-red-100">
+ {redactPathText(operation.stderrExcerpt, censorUsernameInLogs)}
+ </pre>
+ </div>
+ )}
+ {operation.stdoutExcerpt && operation.stdoutExcerpt.trim() && (
+ <div>
+ <div className="mb-1 text-xs text-muted-foreground">stdout excerpt</div>
+ <pre className="rounded-md bg-neutral-100 p-2 text-xs whitespace-pre-wrap break-all dark:bg-neutral-950">
+ {redactPathText(operation.stdoutExcerpt, censorUsernameInLogs)}
+ </pre>
+ </div>
+ )}
+ {operation.logRef && (
+ <WorkspaceOperationLogViewer
+ operation={operation}
+ censorUsernameInLogs={censorUsernameInLogs}
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+export function AgentDetail() {
+ const { companyPrefix, agentId, tab: urlTab, runId: urlRunId } = useParams<{
+ companyPrefix?: string;
+ agentId: string;
+ tab?: string;
+ runId?: string;
+ }>();
+ const { companies, selectedCompanyId, setSelectedCompanyId } = useCompany();
+ const { closePanel } = usePanel();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const [actionError, setActionError] = useState<string | null>(null);
+ const [dismissedLeftAgentIds, setDismissedLeftAgentIds] = useState<Set<string>>(() => new Set());
+ const activeView = urlRunId ? "runs" as AgentDetailView : parseAgentDetailView(urlTab ?? null);
+ const needsDashboardData = activeView === "dashboard";
+ const needsRunData = activeView === "runs" || Boolean(urlRunId);
+ const shouldLoadHeartbeats = needsDashboardData || needsRunData;
+ const [configDirty, setConfigDirty] = useState(false);
+ const [configSaving, setConfigSaving] = useState(false);
+ const saveConfigActionRef = useRef<(() => void) | null>(null);
+ const cancelConfigActionRef = useRef<(() => void) | null>(null);
+ const { isMobile } = useSidebar();
+ const routeAgentRef = agentId ?? "";
+ const routeCompanyId = useMemo(() => {
+ if (!companyPrefix) return null;
+ const requestedPrefix = companyPrefix.toUpperCase();
+ return companies.find((company) => company.issuePrefix.toUpperCase() === requestedPrefix)?.id ?? null;
+ }, [companies, companyPrefix]);
+ const lookupCompanyId = routeCompanyId ?? selectedCompanyId ?? undefined;
+ const canFetchAgent = routeAgentRef.length > 0 && (isUuidLike(routeAgentRef) || Boolean(lookupCompanyId));
+ const setSaveConfigAction = useCallback((fn: (() => void) | null) => { saveConfigActionRef.current = fn; }, []);
+ const setCancelConfigAction = useCallback((fn: (() => void) | null) => { cancelConfigActionRef.current = fn; }, []);
+ const prepareAgentNavigation = useCallback(() => {
+ return confirmAgentConfigNavigation(configDirty);
+ }, [configDirty]);
+
+ const { data: agent, isLoading, error } = useQuery<AgentDetailRecord>({
+ queryKey: [...queryKeys.agents.detail(routeAgentRef), lookupCompanyId ?? null],
+ queryFn: () => agentsApi.get(routeAgentRef, lookupCompanyId),
+ enabled: canFetchAgent,
+ });
+ const resolvedCompanyId = agent?.companyId ?? selectedCompanyId;
+ const canonicalAgentRef = agent ? agentRouteRef(agent) : routeAgentRef;
+ const agentLookupRef = agent?.id ?? routeAgentRef;
+ const resolvedAgentId = agent?.id ?? null;
+ const membershipsQuery = useResourceMemberships(resolvedCompanyId);
+ const membershipMutation = useResourceMembershipMutation(resolvedCompanyId);
+ const agentMembershipState = resolvedAgentId
+ ? resourceMembershipState(membershipsQuery.data, "agent", resolvedAgentId)
+ : "joined";
+
+ const { data: experimentalSettings } = useQuery({
+ queryKey: queryKeys.instance.experimentalSettings,
+ queryFn: () => instanceSettingsApi.getExperimental(),
+ enabled: !!resolvedCompanyId,
+ });
+ const builtInAgentsEnabled = experimentalSettings?.enableBuiltInAgents === true;
+ const { data: builtInStates } = useQuery({
+ queryKey: queryKeys.builtInAgents.list(resolvedCompanyId!),
+ queryFn: () => builtInAgentsApi.list(resolvedCompanyId!),
+ enabled: !!resolvedCompanyId && builtInAgentsEnabled,
+ });
+ const builtInState = builtInAgentsEnabled
+ ? builtInStates?.find((entry) => entry.agentId === resolvedAgentId) ?? null
+ : null;
+ const builtInFeatureLabel = builtInState
+ ? builtInState.definition.featureKeys
+ .map((key) => key.charAt(0).toUpperCase() + key.slice(1))
+ .join(", ")
+ : "";
+ const invalidateBuiltIn = useCallback(() => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.builtInAgents.list(resolvedCompanyId!) });
+ if (resolvedAgentId) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(resolvedAgentId) });
+ }
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(routeAgentRef) });
+ }, [queryClient, resolvedCompanyId, resolvedAgentId, routeAgentRef]);
+
+ const resetBuiltIn = useMutation({
+ mutationFn: () => builtInAgentsApi.reset(resolvedCompanyId!, builtInState!.definition.key),
+ onSuccess: invalidateBuiltIn,
+ });
+
+ const [showBuiltInConfigure, setShowBuiltInConfigure] = useState(false);
+ const resetBuiltInResource = useMutation({
+ mutationFn: (kind: BuiltInManagedResourceKind) =>
+ builtInAgentsApi.reset(resolvedCompanyId!, builtInState!.definition.key, [kind]),
+ onSuccess: invalidateBuiltIn,
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to update bundle resource");
+ },
+ });
+ const runBuiltInRoutine = useMutation({
+ mutationFn: (routineKey: string) =>
+ builtInAgentsApi.runRoutine(resolvedCompanyId!, builtInState!.definition.key, routineKey),
+ onSuccess: invalidateBuiltIn,
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to run built-in routine");
+ },
+ });
+ const enableBuiltInSchedule = useMutation({
+ mutationFn: (routineKey: string) =>
+ builtInAgentsApi.enableRoutineSchedule(resolvedCompanyId!, builtInState!.definition.key, routineKey),
+ onSuccess: invalidateBuiltIn,
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to enable routine schedule");
+ },
+ });
+ const disableBuiltInSchedule = useMutation({
+ mutationFn: (routineKey: string) =>
+ builtInAgentsApi.disableRoutineSchedule(resolvedCompanyId!, builtInState!.definition.key, routineKey),
+ onSuccess: invalidateBuiltIn,
+ onError: (error) => {
+ setActionError(error instanceof Error ? error.message : "Failed to disable routine schedule");
+ },
+ });
+ const builtInRoutineActionPending =
+ runBuiltInRoutine.isPending
+ ? "run"
+ : enableBuiltInSchedule.isPending
+ ? "enable"
+ : disableBuiltInSchedule.isPending
+ ? "disable"
+ : null;
+
+ const { data: runtimeState } = useQuery({
+ queryKey: queryKeys.agents.runtimeState(resolvedAgentId ?? routeAgentRef),
+ queryFn: () => agentsApi.runtimeState(resolvedAgentId!, resolvedCompanyId ?? undefined),
+ enabled: Boolean(resolvedAgentId) && needsDashboardData,
+ });
+
+ const { data: heartbeats } = useQuery({
+ queryKey: queryKeys.heartbeats(resolvedCompanyId!, agent?.id ?? undefined),
+ queryFn: () => heartbeatsApi.list(resolvedCompanyId!, agent?.id ?? undefined),
+ enabled: !!resolvedCompanyId && !!agent?.id && shouldLoadHeartbeats,
+ });
+
+ const { data: allIssues } = useQuery({
+ queryKey: [...queryKeys.issues.list(resolvedCompanyId!), "participant-agent", resolvedAgentId ?? "__none__"],
+ queryFn: () => issuesApi.list(resolvedCompanyId!, { participantAgentId: resolvedAgentId! }),
+ enabled: !!resolvedCompanyId && !!resolvedAgentId && needsDashboardData,
+ });
+
+ const { data: allAgents } = useQuery({
+ queryKey: queryKeys.agents.list(resolvedCompanyId!),
+ queryFn: () => agentsApi.list(resolvedCompanyId!),
+ enabled: !!resolvedCompanyId && needsDashboardData,
+ });
+
+ const { data: budgetOverview } = useQuery({
+ queryKey: queryKeys.budgets.overview(resolvedCompanyId ?? "__none__"),
+ queryFn: () => budgetsApi.overview(resolvedCompanyId!),
+ enabled: !!resolvedCompanyId,
+ refetchInterval: 30_000,
+ staleTime: 5_000,
+ });
+
+ const assignedIssues = (allIssues ?? [])
+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
+ const reportsToAgent = (allAgents ?? []).find((a) => a.id === agent?.reportsTo);
+ const directReports = (allAgents ?? []).filter((a) => a.reportsTo === agent?.id && a.status !== "terminated");
+ const agentBudgetSummary = useMemo(() => {
+ const matched = budgetOverview?.policies.find(
+ (policy) => policy.scopeType === "agent" && policy.scopeId === (agent?.id ?? routeAgentRef),
+ );
+ if (matched) return matched;
+ const budgetMonthlyCents = agent?.budgetMonthlyCents ?? 0;
+ const spentMonthlyCents = agent?.spentMonthlyCents ?? 0;
+ return {
+ policyId: "",
+ companyId: resolvedCompanyId ?? "",
+ scopeType: "agent",
+ scopeId: agent?.id ?? routeAgentRef,
+ scopeName: agent?.name ?? "Agent",
+ metric: "billed_cents",
+ windowKind: "calendar_month_utc",
+ amount: budgetMonthlyCents,
+ observedAmount: spentMonthlyCents,
+ remainingAmount: Math.max(0, budgetMonthlyCents - spentMonthlyCents),
+ utilizationPercent:
+ budgetMonthlyCents > 0 ? Number(((spentMonthlyCents / budgetMonthlyCents) * 100).toFixed(2)) : 0,
+ warnPercent: 80,
+ hardStopEnabled: true,
+ notifyEnabled: true,
+ isActive: budgetMonthlyCents > 0,
+ status: budgetMonthlyCents > 0 && spentMonthlyCents >= budgetMonthlyCents ? "hard_stop" : "ok",
+ paused: agent?.status === "paused",
+ pauseReason: agent?.pauseReason ?? null,
+ windowStart: new Date(),
+ windowEnd: new Date(),
+ } satisfies BudgetPolicySummary;
+ }, [agent, budgetOverview?.policies, resolvedCompanyId, routeAgentRef]);
+ const mobileLiveRun = useMemo(
+ () => (heartbeats ?? []).find((r) => r.status === "running" || r.status === "queued") ?? null,
+ [heartbeats],
+ );
+
+ useEffect(() => {
+ if (!agent) return;
+ if (urlRunId) {
+ if (routeAgentRef !== canonicalAgentRef) {
+ navigate(`/agents/${canonicalAgentRef}/runs/${urlRunId}`, { replace: true });
+ }
+ return;
+ }
+ const canonicalTab =
+ activeView === "instructions"
+ ? "instructions"
+ : activeView === "configuration"
+ ? "configuration"
+ : activeView === "secrets"
+ ? "secrets"
+ : activeView === "skills"
+ ? "skills"
+ : activeView === "tools"
+ ? "tools"
+ : activeView === "runs"
+ ? "runs"
+ : activeView === "audit"
+ ? "audit"
+ : activeView === "budget"
+ ? "budget"
+ : "dashboard";
+ if (routeAgentRef !== canonicalAgentRef || urlTab !== canonicalTab) {
+ navigate(`/agents/${canonicalAgentRef}/${canonicalTab}`, { replace: true });
+ return;
+ }
+ }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, navigate]);
+
+ useEffect(() => {
+ if (!agent?.companyId || agent.companyId === selectedCompanyId) return;
+ setSelectedCompanyId(agent.companyId, { source: "route_sync" });
+ }, [agent?.companyId, selectedCompanyId, setSelectedCompanyId]);
+
+ // Invoke / pause / resume / terminate / duplicate / reset live in the shared
+ // AgentActionButtons component. The detail header keeps only "approve" here,
+ // which is surfaced via the pending-approval banner below.
+ const agentAction = useMutation({
+ mutationFn: async (action: "approve") => {
+ if (!agentLookupRef) return Promise.reject(new Error("No agent reference"));
+ if (action === "approve") {
+ return agentsApi.approve(agentLookupRef, resolvedCompanyId ?? undefined);
+ }
+ },
+ onSuccess: () => {
+ setActionError(null);
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(routeAgentRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentLookupRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.runtimeState(agentLookupRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.taskSessions(agentLookupRef) });
+ if (resolvedCompanyId) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(resolvedCompanyId) });
+ if (agent?.id) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(resolvedCompanyId, agent.id) });
+ }
+ }
+ },
+ onError: (err) => {
+ setActionError(err instanceof Error ? err.message : "Action failed");
+ },
+ });
+
+ const budgetMutation = useMutation({
+ mutationFn: (amount: number) =>
+ budgetsApi.upsertPolicy(resolvedCompanyId!, {
+ scopeType: "agent",
+ scopeId: agent?.id ?? routeAgentRef,
+ amount,
+ windowKind: "calendar_month_utc",
+ }),
+ onSuccess: () => {
+ if (!resolvedCompanyId) return;
+ queryClient.invalidateQueries({ queryKey: queryKeys.budgets.overview(resolvedCompanyId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(routeAgentRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentLookupRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(resolvedCompanyId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(resolvedCompanyId) });
+ },
+ });
+
+ const updateIcon = useMutation({
+ mutationFn: (icon: string) => agentsApi.update(agentLookupRef, { icon }, resolvedCompanyId ?? undefined),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(routeAgentRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentLookupRef) });
+ if (resolvedCompanyId) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(resolvedCompanyId) });
+ }
+ },
+ });
+
+ const updatePermissions = useMutation({
+ mutationFn: (permissions: AgentPermissionUpdate) =>
+ agentsApi.updatePermissions(agentLookupRef, permissions, resolvedCompanyId ?? undefined),
+ onSuccess: () => {
+ setActionError(null);
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(routeAgentRef) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentLookupRef) });
+ if (resolvedCompanyId) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(resolvedCompanyId) });
+ }
+ },
+ onError: (err) => {
+ setActionError(err instanceof Error ? err.message : "Failed to update permissions");
+ },
+ });
+
+ useEffect(() => {
+ const crumbs: { label: string; href?: string }[] = [
+ { label: "Agents", href: "/agents" },
+ ];
+ const agentName = agent?.name ?? routeAgentRef ?? "Agent";
+ if (activeView === "dashboard" && !urlRunId) {
+ crumbs.push({ label: agentName });
+ } else {
+ crumbs.push({ label: agentName, href: `/agents/${canonicalAgentRef}/dashboard` });
+ if (urlRunId) {
+ crumbs.push({ label: "Runs", href: `/agents/${canonicalAgentRef}/runs` });
+ crumbs.push({ label: `Run ${urlRunId.slice(0, 8)}` });
+ } else if (activeView === "instructions") {
+ crumbs.push({ label: "Instructions" });
+ } else if (activeView === "configuration") {
+ crumbs.push({ label: "Configuration" });
+ } else if (activeView === "secrets") {
+ crumbs.push({ label: "Secrets" });
+ // } else if (activeView === "skills") { // TODO: bring back later
+ // crumbs.push({ label: "Skills" });
+ } else if (activeView === "tools") {
+ crumbs.push({ label: "Tools" });
+ } else if (activeView === "runs") {
+ crumbs.push({ label: "Runs" });
+ } else if (activeView === "budget") {
+ crumbs.push({ label: "Budget" });
+ } else {
+ crumbs.push({ label: "Dashboard" });
+ }
+ }
+ setBreadcrumbs(crumbs);
+ }, [setBreadcrumbs, agent, routeAgentRef, canonicalAgentRef, activeView, urlRunId]);
+
+ useEffect(() => {
+ closePanel();
+ return () => closePanel();
+ }, [closePanel]);
+
+ useEffect(() => {
+ if (!resolvedAgentId || agentMembershipState !== "joined") return;
+ setDismissedLeftAgentIds((current) => {
+ if (!current.has(resolvedAgentId)) return current;
+ const next = new Set(current);
+ next.delete(resolvedAgentId);
+ return next;
+ });
+ }, [resolvedAgentId, agentMembershipState]);
+
+ useBeforeUnload(
+ useCallback((event) => {
+ if (!configDirty) return;
+ event.preventDefault();
+ event.returnValue = "";
+ }, [configDirty]),
+ );
+
+ useEffect(() => {
+ if (!configDirty) return;
+
+ function handleDocumentClick(event: MouseEvent) {
+ if (
+ event.defaultPrevented ||
+ event.button !== 0 ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey
+ ) {
+ return;
+ }
+ const target = event.target;
+ if (!(target instanceof Element)) return;
+ const anchor = target.closest("a[href]");
+ if (!(anchor instanceof HTMLAnchorElement)) return;
+ if (anchor.target && anchor.target !== "_self") return;
+
+ const nextUrl = new URL(anchor.href, window.location.href);
+ const currentUrl = new URL(window.location.href);
+ if (nextUrl.origin !== currentUrl.origin) return;
+ if (
+ nextUrl.pathname === currentUrl.pathname &&
+ nextUrl.search === currentUrl.search &&
+ nextUrl.hash === currentUrl.hash
+ ) {
+ return;
+ }
+ if (prepareAgentNavigation()) return;
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ document.addEventListener("click", handleDocumentClick, true);
+ return () => document.removeEventListener("click", handleDocumentClick, true);
+ }, [configDirty, prepareAgentNavigation]);
+
+ useEffect(() => {
+ if (!configDirty) return;
+
+ // BrowserRouter updates after popstate. Run first in the capture phase so a
+ // rejected Back/Forward navigation can be restored before React Router
+ // consumes it and unmounts the route-backed form.
+ const currentEntry = {
+ index: window.history.state?.idx,
+ state: window.history.state,
+ url: window.location.href,
+ };
+ let restoring = false;
+
+ function handlePopState(event: PopStateEvent) {
+ if (restoring) {
+ restoring = false;
+ return;
+ }
+
+ if (prepareAgentNavigation()) return;
+
+ event.stopImmediatePropagation();
+ restoring = restoreAgentConfigHistoryEntry(window.history, currentEntry, event.state?.idx);
+ }
+
+ window.addEventListener("popstate", handlePopState, true);
+ return () => window.removeEventListener("popstate", handlePopState, true);
+ }, [configDirty, prepareAgentNavigation]);
+
+ if (isLoading) return <PageSkeleton variant="detail" />;
+ if (error) return <p className="text-sm text-destructive">{error.message}</p>;
+ if (!agent) return null;
+ if (!urlRunId && !urlTab) {
+ return <Navigate to={`/agents/${canonicalAgentRef}/dashboard`} replace />;
+ }
+ const isPendingApproval = agent.status === "pending_approval";
+ const hasInvalidOrgChain = agent.orgChainHealth?.status === "invalid_org_chain";
+ const pausedEscalationWarning = !hasInvalidOrgChain ? agent.orgChainHealth?.escalationWarning ?? null : null;
+ const showConfigActionBar = (
+ activeView === "configuration" || activeView === "instructions" || activeView === "secrets"
+ ) && (configDirty || configSaving);
+ const showLeftAgentNotice = agentMembershipState === "left" && !dismissedLeftAgentIds.has(agent.id);
+ const agentMembershipPending =
+ membershipMutation.isPending &&
+ membershipMutation.variables?.resourceType === "agent" &&
+ membershipMutation.variables.resourceId === agent.id;
+ const agentStarred = isStarred(membershipsQuery.data, "agent", agent.id);
+ const agentStarPending = agentMembershipPending && membershipMutation.variables?.starred !== undefined;
+ const agentJoinLeavePending = agentMembershipPending && membershipMutation.variables?.starred === undefined;
+
+ function handleAgentTabChange(value: string) {
+ if (value === activeView || !prepareAgentNavigation()) return;
+ navigate(`/agents/${canonicalAgentRef}/${value}`);
+ }
+
+ return (
+ <div className={cn("space-y-6", isMobile && showConfigActionBar && "pb-24")}>
+ {showLeftAgentNotice ? (
+ <div className="flex items-center gap-3 border border-yellow-300/35 bg-yellow-300/10 px-3 py-2 text-sm text-yellow-900 dark:text-yellow-100">
+ <p className="min-w-0 flex-1">
+ You left this agent. It no longer appears in your sidebar.
+ </p>
+ <MembershipAction
+ compact
+ state="left"
+ pending={agentJoinLeavePending}
+ pendingState={agentJoinLeavePending ? membershipMutation.variables?.state : null}
+ resourceName={agent.name}
+ onJoin={() => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: agent.id,
+ resourceName: agent.name,
+ state: "joined",
+ })}
+ onLeave={() => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: agent.id,
+ resourceName: agent.name,
+ state: "left",
+ })}
+ />
+ <button
+ type="button"
+ className="h-6 w-6 shrink-0 text-yellow-900/70 hover:text-yellow-900 dark:text-yellow-100/70 dark:hover:text-yellow-100"
+ aria-label="Dismiss agent membership notice"
+ onClick={() => setDismissedLeftAgentIds((current) => new Set(current).add(agent.id))}
+ >
+ ×
+ </button>
+ </div>
+ ) : null}
+ {pausedEscalationWarning ? (
+ <div className="flex items-start gap-3 border border-amber-300/35 bg-amber-300/10 px-3 py-2 text-sm text-amber-900 dark:text-amber-100">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <div className="min-w-0 space-y-1">
+ <p className="font-medium">Escalation path is paused</p>
+ <p className="text-amber-900/90 dark:text-amber-100/90">{pausedEscalationWarning}</p>
+ </div>
+ </div>
+ ) : null}
+ {hasInvalidOrgChain ? (
+ <div className="flex items-start gap-3 border border-amber-300/35 bg-amber-300/10 px-3 py-2 text-sm text-amber-900 dark:text-amber-100">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <div className="min-w-0 space-y-1">
+ <p className="font-medium">Invalid reporting chain</p>
+ <p className="text-amber-900/90 dark:text-amber-100/90">
+ {agent.name} cannot accept tasks or start runs until its reporting chain is repaired.
+ </p>
+ <p className="break-words font-mono text-xs text-amber-900/80 dark:text-amber-100/80">
+ {formatOrgChainHealthPath(agent)}
+ </p>
+ {agent.orgChainHealth?.repairGuidance ? (
+ <p className="text-amber-900/85 dark:text-amber-100/85">{agent.orgChainHealth.repairGuidance}</p>
+ ) : (
+ <p className="text-amber-900/85 dark:text-amber-100/85">
+ Assign this agent to an active manager/root, or explicitly pause or terminate the affected agent/subtree.
+ </p>
+ )}
+ </div>
+ </div>
+ ) : null}
+ {/* Header */}
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-3 min-w-0">
+ <AgentIconPicker
+ value={agent.icon}
+ onChange={(icon) => updateIcon.mutate(icon)}
+ >
+ <button className="shrink-0 flex items-center justify-center h-12 w-12 rounded-lg bg-accent hover:bg-accent/80 transition-colors">
+ <AgentIcon icon={agent.icon} className="h-6 w-6" />
+ </button>
+ </AgentIconPicker>
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <h2 className="text-2xl font-bold truncate">{agent.name}</h2>
+ </div>
+ <p className="text-sm text-muted-foreground truncate">
+ {roleLabels[agent.role] ?? agent.role}
+ {agent.title ? ` - ${agent.title}` : ""}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ <StarToggle
+ size="button"
+ starred={agentStarred}
+ pending={agentStarPending}
+ resourceName={agent.name}
+ onToggle={(next) => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: agent.id,
+ resourceName: agent.name,
+ starred: next,
+ })}
+ />
+ <AgentActionButtons
+ agent={agent}
+ companyId={resolvedCompanyId}
+ assignLabel="Assign Task"
+ runLabel="Run Heartbeat"
+ actionsDisabled={agentAction.isPending}
+ workActionsDisabled={hasInvalidOrgChain}
+ workActionsDisabledReason="Repair this agent's reporting chain before assigning tasks or starting runs"
+ hasPendingNavigationChanges={configDirty}
+ onBeforeNavigate={prepareAgentNavigation}
+ onActionError={setActionError}
+ onTerminateSuccess={() => navigate("/agents/all", { replace: true })}
+ hideTerminate={Boolean(builtInState)}
+ pauseConfirm={
+ builtInState
+ ? {
+ title: `Pause the ${builtInState.definition.displayName}?`,
+ description: (
+ <>
+ {builtInFeatureLabel} depends on this agent. While paused,{" "}
+ {builtInFeatureLabel.toLowerCase()} generation is skipped and the{" "}
+ {builtInFeatureLabel} page shows a warning.
+ </>
+ ),
+ }
+ : undefined
+ }
+ >
+ {mobileLiveRun && (
+ <Link
+ to={`/agents/${canonicalAgentRef}/runs/${mobileLiveRun.id}`}
+ className="sm:hidden flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-blue-500/10 hover:bg-blue-500/20 transition-colors no-underline"
+ >
+ <span className="relative flex h-2 w-2">
+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500" />
+ </span>
+ <span className="text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400">Live</span>
+ </Link>
+ )}
+ </AgentActionButtons>
+ </div>
+ </div>
+
+ {builtInState && (
+ <InlineBanner
+ tone="info"
+ title="Built-in agent"
+ actions={
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => resetBuiltIn.mutate()}
+ disabled={resetBuiltIn.isPending}
+ >
+ {resetBuiltIn.isPending ? "Resetting…" : "Reset to defaults"}
+ </Button>
+ }
+ >
+ Ships with Paperclip and powers <strong>{builtInFeatureLabel}</strong>. Configure it like
+ any agent — model, instructions, budget. It can be paused but not deleted; pausing it
+ pauses {builtInFeatureLabel}.
+ </InlineBanner>
+ )}
+
+ {builtInState?.definition.bundle && (
+ <BuiltInBundlePanel
+ state={builtInState}
+ agentRef={canonicalAgentRef}
+ onConfigure={() => setShowBuiltInConfigure(true)}
+ onResetResource={(kind) => resetBuiltInResource.mutate(kind)}
+ onRunRoutine={(routineKey) => runBuiltInRoutine.mutate(routineKey)}
+ onEnableSchedule={(routineKey) => enableBuiltInSchedule.mutate(routineKey)}
+ onDisableSchedule={(routineKey) => disableBuiltInSchedule.mutate(routineKey)}
+ resettingResource={resetBuiltInResource.isPending ? resetBuiltInResource.variables ?? null : null}
+ routineActionPending={builtInRoutineActionPending}
+ />
+ )}
+
+ {builtInState && resolvedCompanyId && (
+ <ConfigureBuiltInAgentModal
+ companyId={resolvedCompanyId}
+ state={builtInState}
+ open={showBuiltInConfigure}
+ onOpenChange={setShowBuiltInConfigure}
+ onConfigured={() => {
+ setShowBuiltInConfigure(false);
+ invalidateBuiltIn();
+ }}
+ />
+ )}
+
+ {!urlRunId && (
+ <Tabs
+ value={activeView}
+ onValueChange={handleAgentTabChange}
+ >
+ <PageTabBar
+ items={AGENT_DETAIL_TABS}
+ value={activeView}
+ onValueChange={handleAgentTabChange}
+ />
+ </Tabs>
+ )}
+
+ {actionError && <p className="text-sm text-destructive">{actionError}</p>}
+ {isPendingApproval && (
+ <div className="flex flex-wrap items-center gap-3 rounded-md border border-amber-300/60 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-400/40 dark:bg-amber-950/30 dark:text-amber-200">
+ <span>This agent is pending board approval and cannot be invoked yet.</span>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => agentAction.mutate("approve")}
+ disabled={agentAction.isPending}
+ >
+ <CheckCircle2 className="h-3.5 w-3.5 sm:mr-1" />
+ <span>Approve agent</span>
+ </Button>
+ </div>
+ )}
+
+ {/* Floating Save/Cancel (desktop) */}
+ {!isMobile && showConfigActionBar && (
+ <div className="fixed bottom-6 right-6 z-30">
+ <div className="flex items-center gap-2 bg-background/90 backdrop-blur-sm border border-border rounded-lg px-3 py-1.5 shadow-lg">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => cancelConfigActionRef.current?.()}
+ disabled={configSaving}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => saveConfigActionRef.current?.()}
+ disabled={configSaving}
+ >
+ {configSaving ? "Saving…" : "Save"}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* Mobile bottom Save/Cancel bar */}
+ {isMobile && showConfigActionBar && (
+ <div className="fixed inset-x-0 bottom-0 z-30 border-t border-border bg-background/95 backdrop-blur-sm">
+ <div
+ className="flex items-center justify-end gap-2 px-3 py-2"
+ style={{ paddingBottom: "max(env(safe-area-inset-bottom), 0.5rem)" }}
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => cancelConfigActionRef.current?.()}
+ disabled={configSaving}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => saveConfigActionRef.current?.()}
+ disabled={configSaving}
+ >
+ {configSaving ? "Saving…" : "Save"}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* View content */}
+ {activeView === "dashboard" && (
+ <AgentOverview
+ agent={agent}
+ runs={heartbeats ?? []}
+ assignedIssues={assignedIssues}
+ runtimeState={runtimeState}
+ agentId={agent.id}
+ agentRouteId={canonicalAgentRef}
+ />
+ )}
+
+ {activeView === "instructions" && (
+ <PromptsTab
+ agent={agent}
+ companyId={resolvedCompanyId ?? undefined}
+ onDirtyChange={setConfigDirty}
+ onSaveActionChange={setSaveConfigAction}
+ onCancelActionChange={setCancelConfigAction}
+ onSavingChange={setConfigSaving}
+ />
+ )}
+
+ {activeView === "configuration" && (
+ <AgentConfigurePage
+ agent={agent}
+ agentId={agent.id}
+ companyId={resolvedCompanyId ?? undefined}
+ onDirtyChange={setConfigDirty}
+ onSaveActionChange={setSaveConfigAction}
+ onCancelActionChange={setCancelConfigAction}
+ onSavingChange={setConfigSaving}
+ updatePermissions={updatePermissions}
+ />
+ )}
+
+ {activeView === "secrets" && (
+ <div className="max-w-3xl">
+ <ConfigurationTab
+ agent={agent}
+ companyId={resolvedCompanyId ?? undefined}
+ onDirtyChange={setConfigDirty}
+ onSaveActionChange={setSaveConfigAction}
+ onCancelActionChange={setCancelConfigAction}
+ onSavingChange={setConfigSaving}
+ updatePermissions={updatePermissions}
+ content="secrets"
+ />
+ </div>
+ )}
+
+ {activeView === "skills" && (
+ <AgentSkillsTab
+ agent={agent}
+ companyId={resolvedCompanyId ?? undefined}
+ />
+ )}
+
+ {activeView === "tools" && resolvedCompanyId && (
+ <AgentToolsTab agent={agent} companyId={resolvedCompanyId} />
+ )}
+
+ {activeView === "runs" && (
+ <RunsTab
+ runs={heartbeats ?? []}
+ companyId={resolvedCompanyId!}
+ agentId={agent.id}
+ agentRouteId={canonicalAgentRef}
+ selectedRunId={urlRunId ?? null}
+ adapterType={agent.adapterType}
+ adapterConfig={agent.adapterConfig}
+ />
+ )}
+
+ {activeView === "audit" && resolvedCompanyId ? (
+ <AuditFeed companyId={resolvedCompanyId} lockedAgentId={agent.id} hideHeader />
+ ) : null}
+
+ {activeView === "budget" && resolvedCompanyId ? (
+ <div className="max-w-3xl">
+ <BudgetPolicyCard
+ summary={agentBudgetSummary}
+ isSaving={budgetMutation.isPending}
+ onSave={(amount) => budgetMutation.mutate(amount)}
+ variant="plain"
+ />
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+/* ---- Helper components ---- */
+
+function SummaryRow({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="flex items-center justify-between">
+ <span className="text-muted-foreground text-xs">{label}</span>
+ <div className="flex items-center gap-1">{children}</div>
+ </div>
+ );
+}
+
+export type LatestRunIssue = { id: string; title: string; status: string; identifier?: string | null };
+
+/**
+ * The id of the issue a run works on, read from its context snapshot. Newer
+ * snapshots use `issueId`; older ones use `taskId`. Returns undefined for pure
+ * timer heartbeats that carry no task reference.
+ */
+export function getRunSnapshotIssueId(
+ run: Pick<HeartbeatRun, "contextSnapshot">,
+): string | undefined {
+ const ctx = run.contextSnapshot as Record<string, unknown> | null;
+ const issueId = ctx?.issueId ?? ctx?.taskId;
+ return issueId ? String(issueId) : undefined;
+}
+
+/**
+ * Resolve the Live Run section's two navigation destinations and the task (if
+ * any) the run works on. The run→task link lives in the run's context snapshot
+ * (`issueId`, falling back to `taskId` for older snapshots); the `HeartbeatRun`
+ * itself doesn't carry the issue id. The heading always links to the run detail
+ * page; the running row links to the task detail page when the snapshot resolves
+ * to a known issue, otherwise falls back to the run detail page (pure timer
+ * heartbeats or an issue that can't be resolved).
+ */
+export function resolveLatestRunNavigation(
+ run: Pick<HeartbeatRun, "id" | "contextSnapshot">,
+ agentId: string,
+ issuesById: Map<string, LatestRunIssue>,
+): { task: LatestRunIssue | undefined; runHref: string; rowHref: string } {
+ const issueId = getRunSnapshotIssueId(run);
+ const task = issueId ? issuesById.get(issueId) : undefined;
+ const runHref = `/agents/${agentId}/runs/${run.id}`;
+ const rowHref = task ? `/issues/${task.identifier ?? task.id}` : runHref;
+ return { task, runHref, rowHref };
+}
+
+function LatestRunCard({
+ runs,
+ agentId,
+ issuesById,
+}: {
+ runs: HeartbeatRun[];
+ agentId: string;
+ issuesById: Map<string, LatestRunIssue>;
+}) {
+ const sorted = useMemo(
+ () =>
+ [...runs].sort(
+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
+ ),
+ [runs]
+ );
+
+ const liveRun = sorted.find((r) => r.status === "running" || r.status === "queued");
+ const run = liveRun ?? sorted[0];
+
+ // The assigned-issues list this card resolves against is bounded (server page
+ // limit), so a live run can reference a valid issue that isn't on the loaded
+ // page. When the snapshot points at an issue we don't already have, fetch it
+ // directly so the running row always links to the task rather than falling
+ // back to run metadata. `enabled` keeps this a no-op for the common case.
+ const snapshotIssueId = run ? getRunSnapshotIssueId(run) : undefined;
+ const needsFallbackFetch = !!snapshotIssueId && !issuesById.has(snapshotIssueId);
+ const { data: fallbackIssue } = useQuery({
+ queryKey: queryKeys.issues.detail(snapshotIssueId ?? "__none__"),
+ queryFn: () => issuesApi.get(snapshotIssueId as string),
+ enabled: needsFallbackFetch,
+ staleTime: 30_000,
+ });
+
+ const summaryRaw = run
+ ? run.resultJson
+ ? String((run.resultJson as Record<string, unknown>).summary ?? (run.resultJson as Record<string, unknown>).result ?? "")
+ : run.error ?? ""
+ : "";
+
+ // Extract a clean 2-3 line excerpt: first non-empty, non-header, non-list-mark lines
+ const summary = useMemo(() => {
+ if (!summaryRaw) return "";
+ const lines = summaryRaw
+ .replace(/^#{1,6}\s+/gm, "")
+ .split("\n")
+ .map((l) => l.trim())
+ .filter((l) => l.length > 0 && !l.startsWith("---") && !l.startsWith("|") && !l.startsWith("```") && !/^[-*>]/.test(l) && !/^\d+\./.test(l));
+ const excerpt: string[] = [];
+ let chars = 0;
+ for (const line of lines) {
+ if (excerpt.length >= 3 || chars + line.length > 280) break;
+ excerpt.push(line);
+ chars += line.length;
+ }
+ return excerpt.join(" ");
+ }, [summaryRaw]);
+
+ if (!run) return null;
+
+ const isLive = run.status === "running" || run.status === "queued";
+ // Fold any directly-fetched fallback issue into the lookup, keyed by the same
+ // snapshot id used to resolve the row so it hits regardless of id-vs-slug.
+ const effectiveIssuesById =
+ fallbackIssue && snapshotIssueId
+ ? new Map(issuesById).set(snapshotIssueId, {
+ id: fallbackIssue.id,
+ title: fallbackIssue.title,
+ status: fallbackIssue.status,
+ identifier: fallbackIssue.identifier,
+ })
+ : issuesById;
+ const { task, runHref, rowHref } = resolveLatestRunNavigation(run, agentId, effectiveIssuesById);
+ const statusInfo = runStatusIcons[run.status] ?? { icon: Clock, color: "text-neutral-400" };
+ const StatusIcon = statusInfo.icon;
+
+ return (
+ <div className="space-y-3">
+ <div className="flex w-full items-center justify-between">
+ <Link
+ to={runHref}
+ className="no-underline"
+ >
+ <h3 className="flex items-center gap-2 text-sm font-medium transition-colors hover:text-foreground">
+ {isLive && (
+ <span className="relative flex h-2 w-2">
+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500" />
+ </span>
+ )}
+ <span>{isLive ? "Live Run" : "Latest Run"}</span>
+ <span className="font-mono text-xs font-normal text-muted-foreground">
+ &middot; {run.id.slice(0, 8)}
+ </span>
+ </h3>
+ </Link>
+ </div>
+
+ <Link
+ to={rowHref}
+ className={cn(
+ "block border rounded-lg p-4 space-y-2 w-full no-underline transition-colors hover:bg-muted/50 cursor-pointer",
+ isLive ? "border-blue-500/30 shadow-(--shadow-extract-14)" : "border-border"
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <StatusIcon className={cn("h-3.5 w-3.5", statusInfo.color, run.status === "running" && "animate-spin")} />
+ <StatusBadge status={run.status} />
+ {task ? (
+ <>
+ <StatusGlyph status={task.status} size="sm" />
+ <span className="font-mono text-xs text-muted-foreground">
+ {task.identifier ?? task.id.slice(0, 8)}
+ </span>
+ <span className="truncate text-xs">{task.title}</span>
+ </>
+ ) : (
+ <>
+ <span className="font-mono text-xs text-muted-foreground">{run.id.slice(0, 8)}</span>
+ <Badge variant="ghost" className={cn(
+ "px-1.5 text-(length:--text-nano)",
+ run.invocationSource === "timer" ? "bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"
+ : run.invocationSource === "assignment" ? "bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300"
+ : run.invocationSource === "on_demand" ? "bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300"
+ : "bg-muted text-muted-foreground"
+ )}>
+ {sourceLabels[run.invocationSource] ?? run.invocationSource}
+ </Badge>
+ </>
+ )}
+ <span className="ml-auto text-xs text-muted-foreground">{relativeTime(run.createdAt)}</span>
+ </div>
+
+ {summary && (
+ <div className="overflow-hidden max-h-16">
+ <MarkdownBody className="[&>*:first-child]:mt-0 [&>*:last-child]:mb-0">{summary}</MarkdownBody>
+ </div>
+ )}
+ </Link>
+ </div>
+ );
+}
+
+/* ---- Agent Overview (main single-page view) ---- */
+
+function AgentOverview({
+ agent,
+ runs,
+ assignedIssues,
+ runtimeState,
+ agentId,
+ agentRouteId,
+}: {
+ agent: AgentDetailRecord;
+ runs: HeartbeatRun[];
+ assignedIssues: { id: string; title: string; status: string; priority: string; identifier?: string | null; createdAt: Date }[];
+ runtimeState?: AgentRuntimeState;
+ agentId: string;
+ agentRouteId: string;
+}) {
+ const issuesById = useMemo(() => {
+ const map = new Map<string, (typeof assignedIssues)[number]>();
+ for (const issue of assignedIssues) map.set(issue.id, issue);
+ return map;
+ }, [assignedIssues]);
+
+ return (
+ <div className="space-y-8">
+ {/* Latest Run */}
+ <LatestRunCard runs={runs} agentId={agentRouteId} issuesById={issuesById} />
+
+ {/* Charts */}
+ <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
+ <ChartCard title="Run Activity" subtitle="Last 14 days">
+ <RunActivityChart runs={runs} />
+ </ChartCard>
+ {/* PAP-411: "Tasks by Priority" chart hidden behind SHOW_TASK_PRIORITY_UI. */}
+ {SHOW_TASK_PRIORITY_UI && (
+ <ChartCard title="Tasks by Priority" subtitle="Last 14 days">
+ <PriorityChart issues={assignedIssues} />
+ </ChartCard>
+ )}
+ <ChartCard title="Tasks by Status" subtitle="Last 14 days">
+ <IssueStatusChart issues={assignedIssues} />
+ </ChartCard>
+ <ChartCard title="Success Rate" subtitle="Last 14 days">
+ <SuccessRateChart runs={runs} />
+ </ChartCard>
+ </div>
+
+ {/* Recent Issues */}
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium">Recent Tasks</h3>
+ <Link
+ to={`/issues?participantAgentId=${agentId}`}
+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"
+ >
+ See All &rarr;
+ </Link>
+ </div>
+ {assignedIssues.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No recent tasks.</p>
+ ) : (
+ <div className="border border-border rounded-lg">
+ {assignedIssues.slice(0, 10).map((issue) => (
+ <EntityRow
+ key={issue.id}
+ identifier={issue.identifier ?? issue.id.slice(0, 8)}
+ title={issue.title}
+ to={`/issues/${issue.identifier ?? issue.id}`}
+ trailing={<StatusBadge status={issue.status} />}
+ />
+ ))}
+ {assignedIssues.length > 10 && (
+ <div className="px-3 py-2 text-xs text-muted-foreground text-center border-t border-border">
+ +{assignedIssues.length - 10} more tasks
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Costs */}
+ <div className="space-y-3">
+ <h3 className="text-sm font-medium">Costs</h3>
+ <CostsSection runtimeState={runtimeState} runs={runs} />
+ </div>
+ </div>
+ );
+}
+
+/* ---- Costs Section (inline) ---- */
+
+function CostsSection({
+ runtimeState,
+ runs,
+}: {
+ runtimeState?: AgentRuntimeState;
+ runs: HeartbeatRun[];
+}) {
+ const runsWithCost = runs
+ .filter((r) => {
+ const metrics = runMetrics(r);
+ return metrics.cost > 0 || metrics.input > 0 || metrics.output > 0 || metrics.cached > 0;
+ })
+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
+
+ return (
+ <div className="space-y-4">
+ {runtimeState && (
+ <div className="border border-border rounded-lg p-4">
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4 tabular-nums">
+ <div>
+ <span className="text-xs text-muted-foreground block">Input tokens</span>
+ <span className="text-lg font-semibold">{formatTokens(runtimeState.totalInputTokens)}</span>
+ </div>
+ <div>
+ <span className="text-xs text-muted-foreground block">Output tokens</span>
+ <span className="text-lg font-semibold">{formatTokens(runtimeState.totalOutputTokens)}</span>
+ </div>
+ <div>
+ <span className="text-xs text-muted-foreground block">Cached tokens</span>
+ <span className="text-lg font-semibold">{formatTokens(runtimeState.totalCachedInputTokens)}</span>
+ </div>
+ <div>
+ <span className="text-xs text-muted-foreground block">Total cost</span>
+ <span className="text-lg font-semibold">{formatCents(runtimeState.totalCostCents)}</span>
+ </div>
+ </div>
+ </div>
+ )}
+ {runsWithCost.length > 0 && (
+ <div className="border border-border rounded-lg overflow-hidden">
+ <table className="w-full text-xs">
+ <thead>
+ <tr className="border-b border-border bg-accent/20">
+ <th scope="col" className="text-left px-3 py-2 font-medium text-muted-foreground">Date</th>
+ <th scope="col" className="text-left px-3 py-2 font-medium text-muted-foreground">Run</th>
+ <th scope="col" className="text-right px-3 py-2 font-medium text-muted-foreground">Input</th>
+ <th scope="col" className="text-right px-3 py-2 font-medium text-muted-foreground">Output</th>
+ <th scope="col" className="text-right px-3 py-2 font-medium text-muted-foreground">Cost</th>
+ </tr>
+ </thead>
+ <tbody>
+ {runsWithCost.slice(0, 10).map((run) => {
+ const metrics = runMetrics(run);
+ return (
+ <tr key={run.id} className="border-b border-border last:border-b-0">
+ <td className="px-3 py-2">{formatDate(run.createdAt)}</td>
+ <td className="px-3 py-2 font-mono">{run.id.slice(0, 8)}</td>
+ <td className="px-3 py-2 text-right tabular-nums">{formatTokens(metrics.input)}</td>
+ <td className="px-3 py-2 text-right tabular-nums">{formatTokens(metrics.output)}</td>
+ <td className="px-3 py-2 text-right tabular-nums">
+ {metrics.cost > 0
+ ? `$${metrics.cost.toFixed(4)}`
+ : "-"
+ }
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---- Agent Configure Page ---- */
+
+/**
+ * Agent detail URLs use a name-derived key, so updates that change the agent's
+ * name (a rename or a config-revision rollback) can invalidate the reference
+ * currently in the URL. When that happens, refetching the old reference would
+ * 404 with "Agent not found". Instead, drop the stale cached queries and
+ * replace the URL with the new canonical reference. Returns true when a
+ * redirect happened.
+ */
+export function syncAgentRouteAfterRename(
+ queryClient: QueryClient,
+ navigate: NavigateFunction,
+ previous: { id: string; urlKey?: string | null; name?: string | null },
+ updated: { id: string; urlKey?: string | null; name?: string | null },
+ tab: string,
+): boolean {
+ const previousRef = agentRouteRef(previous);
+ const nextRef = agentRouteRef(updated);
+ if (nextRef === previousRef) return false;
+ queryClient.removeQueries({ queryKey: queryKeys.agents.detail(previousRef) });
+ navigate(`/agents/${nextRef}/${tab}`, { replace: true });
+ return true;
+}
+
+function AgentConfigurePage({
+ agent,
+ agentId,
+ companyId,
+ onDirtyChange,
+ onSaveActionChange,
+ onCancelActionChange,
+ onSavingChange,
+ updatePermissions,
+}: {
+ agent: AgentDetailRecord;
+ agentId: string;
+ companyId?: string;
+ onDirtyChange: (dirty: boolean) => void;
+ onSaveActionChange: (save: (() => void) | null) => void;
+ onCancelActionChange: (cancel: (() => void) | null) => void;
+ onSavingChange: (saving: boolean) => void;
+ updatePermissions: { mutate: (permissions: AgentPermissionUpdate) => void; isPending: boolean };
+}) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const { tab: urlTab } = useParams<{ tab?: string }>();
+ const [revisionsOpen, setRevisionsOpen] = useState(false);
+
+ const { data: configRevisions } = useQuery({
+ queryKey: queryKeys.agents.configRevisions(agent.id),
+ queryFn: () => agentsApi.listConfigRevisions(agent.id, companyId),
+ });
+
+ const rollbackConfig = useMutation({
+ mutationFn: (revisionId: string) => agentsApi.rollbackConfigRevision(agent.id, revisionId, companyId),
+ onSuccess: (updated) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.configRevisions(agent.id) });
+ if (!syncAgentRouteAfterRename(queryClient, navigate, agent, updated, urlTab ?? "configuration")) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) });
+ }
+ },
+ });
+
+ return (
+ <div className="max-w-3xl space-y-6">
+ <ConfigurationTab
+ agent={agent}
+ onDirtyChange={onDirtyChange}
+ onSaveActionChange={onSaveActionChange}
+ onCancelActionChange={onCancelActionChange}
+ onSavingChange={onSavingChange}
+ updatePermissions={updatePermissions}
+ companyId={companyId}
+ hidePromptTemplate
+ hideInstructionsFile
+ />
+ <div>
+ <h3 className="text-sm font-medium mb-3">API Keys</h3>
+ <KeysTab agentId={agentId} companyId={companyId} />
+ </div>
+
+ {/* Configuration Revisions — collapsible at the bottom */}
+ <div>
+ <button
+ className="flex items-center gap-2 text-sm font-medium hover:text-foreground transition-colors"
+ onClick={() => setRevisionsOpen((v) => !v)}
+ >
+ {revisionsOpen
+ ? <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
+ : <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
+ }
+ Configuration Revisions
+ <span className="text-xs font-normal text-muted-foreground">{configRevisions?.length ?? 0}</span>
+ </button>
+ {revisionsOpen && (
+ <div className="mt-3">
+ {(configRevisions ?? []).length === 0 ? (
+ <p className="text-sm text-muted-foreground">No configuration revisions yet.</p>
+ ) : (
+ <div className="space-y-2">
+ {(configRevisions ?? []).slice(0, 10).map((revision) => (
+ <div key={revision.id} className="border border-border/70 rounded-md p-3 space-y-2">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-xs text-muted-foreground">
+ <span className="font-mono">{revision.id.slice(0, 8)}</span>
+ <span className="mx-1">·</span>
+ <span>{formatDate(revision.createdAt)}</span>
+ <span className="mx-1">·</span>
+ <span>{revision.source}</span>
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7 px-2.5 text-xs"
+ onClick={() => rollbackConfig.mutate(revision.id)}
+ disabled={rollbackConfig.isPending}
+ >
+ Restore
+ </Button>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Changed:{" "}
+ {revision.changedKeys.length > 0 ? revision.changedKeys.join(", ") : "no tracked changes"}
+ </p>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/* ---- Configuration Tab ---- */
+
+function ConfigurationTab({
+ agent,
+ companyId,
+ onDirtyChange,
+ onSaveActionChange,
+ onCancelActionChange,
+ onSavingChange,
+ updatePermissions,
+ hidePromptTemplate,
+ hideInstructionsFile,
+ content = "configuration",
+}: {
+ agent: AgentDetailRecord;
+ companyId?: string;
+ onDirtyChange: (dirty: boolean) => void;
+ onSaveActionChange: (save: (() => void) | null) => void;
+ onCancelActionChange: (cancel: (() => void) | null) => void;
+ onSavingChange: (saving: boolean) => void;
+ updatePermissions: { mutate: (permissions: AgentPermissionUpdate) => void; isPending: boolean };
+ hidePromptTemplate?: boolean;
+ hideInstructionsFile?: boolean;
+ content?: "configuration" | "secrets";
+}) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const { tab: urlTab } = useParams<{ tab?: string }>();
+ const { pushToast } = useToastActions();
+ const [awaitingRefreshAfterSave, setAwaitingRefreshAfterSave] = useState(false);
+ const lastAgentRef = useRef(agent);
+
+ const { data: adapterModels } = useQuery({
+ queryKey:
+ companyId
+ ? queryKeys.agents.adapterModels(companyId, agent.adapterType)
+ : ["agents", "none", "adapter-models", agent.adapterType],
+ queryFn: () => agentsApi.adapterModels(companyId!, agent.adapterType),
+ enabled: Boolean(companyId) && content === "configuration",
+ });
+
+ const lowTrustSelected = getTrustPreset(agent.permissions) === "low_trust_review";
+
+ const { data: boundaryProjects, isLoading: boundaryProjectsLoading } = useQuery({
+ queryKey: companyId ? queryKeys.projects.list(companyId) : ["projects", "__low-trust-disabled"],
+ queryFn: () => projectsApi.list(companyId!),
+ enabled: Boolean(companyId && lowTrustSelected) && content === "configuration",
+ });
+
+ const { data: boundaryIssues, isLoading: boundaryIssuesLoading } = useQuery({
+ queryKey: companyId
+ ? [...queryKeys.issues.list(companyId), "low-trust-boundary-candidates"]
+ : ["issues", "__low-trust-disabled"],
+ queryFn: () => issuesApi.list(companyId!, { limit: 100, sortField: "updated", sortDir: "desc" }),
+ enabled: Boolean(companyId && lowTrustSelected) && content === "configuration",
+ });
+
+ const updateAgent = useMutation({
+ mutationFn: (data: Record<string, unknown>) => agentsApi.update(agent.id, data, companyId),
+ onMutate: () => {
+ setAwaitingRefreshAfterSave(true);
+ },
+ onSuccess: (updated) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.configRevisions(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(agent.companyId) });
+ if (!syncAgentRouteAfterRename(queryClient, navigate, agent, updated, urlTab ?? content)) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) });
+ }
+ pushToast({ title: "Agent saved", tone: "success" });
+ },
+ onError: (err) => {
+ setAwaitingRefreshAfterSave(false);
+ const message =
+ err instanceof ApiError
+ ? err.message
+ : err instanceof Error
+ ? err.message
+ : "Could not save agent";
+ pushToast({ title: "Save failed", body: message, tone: "error" });
+ },
+ });
+
+ useEffect(() => {
+ if (awaitingRefreshAfterSave && agent !== lastAgentRef.current) {
+ setAwaitingRefreshAfterSave(false);
+ }
+ lastAgentRef.current = agent;
+ }, [agent, awaitingRefreshAfterSave]);
+ const isConfigSaving = updateAgent.isPending || awaitingRefreshAfterSave;
+
+ useEffect(() => {
+ onSavingChange(isConfigSaving);
+ }, [onSavingChange, isConfigSaving]);
+
+ const canCreateAgents = Boolean(agent.permissions?.canCreateAgents);
+ const canCreateSkills = agent.permissions?.canCreateSkills !== false;
+ const canAssignTasks = Boolean(agent.access?.canAssignTasks);
+ const taskAssignSource = agent.access?.taskAssignSource ?? "none";
+ const taskAssignLocked = agent.role === "ceo" || canCreateAgents;
+ const taskAssignHint =
+ taskAssignSource === "ceo_role"
+ ? "Enabled automatically for CEO agents."
+ : taskAssignSource === "agent_creator"
+ ? "Enabled automatically while this agent can create new agents."
+ : taskAssignSource === "explicit_grant"
+ ? "Enabled via explicit company permission grant."
+ : taskAssignSource === "simple_default"
+ ? "Enabled by simple company-wide task assignment defaults."
+ : "Disabled unless explicitly granted.";
+
+ return (
+ <div className="space-y-6">
+ <AgentConfigForm
+ mode="edit"
+ agent={agent}
+ onSave={(patch) => updateAgent.mutateAsync(patch)}
+ isSaving={isConfigSaving}
+ adapterModels={adapterModels}
+ onDirtyChange={onDirtyChange}
+ onSaveActionChange={onSaveActionChange}
+ onCancelActionChange={onCancelActionChange}
+ hideInlineSave
+ hidePromptTemplate={hidePromptTemplate}
+ hideInstructionsFile={hideInstructionsFile}
+ content={content}
+ sectionLayout="cards"
+ />
+ {content === "configuration" ? (
+ <p className="text-xs text-muted-foreground">
+ Saved adapter config affects the next run. Active runs keep the config they started with, and config changes may start a fresh adapter session.
+ </p>
+ ) : null}
+
+ {content === "configuration" ? <TrustPresetSection
+ permissions={agent.permissions}
+ disabled={updatePermissions.isPending}
+ companyId={companyId}
+ projectCandidates={(boundaryProjects ?? []).map((project) => ({
+ id: project.id,
+ label: project.name,
+ }))}
+ issueCandidates={(boundaryIssues ?? []).map((issue) => ({
+ id: issue.id,
+ label: `${issue.identifier ?? issue.id.slice(0, 8)} · ${issue.title}`,
+ }))}
+ candidatesLoading={boundaryProjectsLoading || boundaryIssuesLoading}
+ onChange={(nextPermissions) =>
+ updatePermissions.mutate({
+ canCreateAgents,
+ canCreateSkills,
+ canAssignTasks,
+ ...buildPermissionsForTrustPreset(nextPermissions, nextPermissions.trustPreset === "low_trust_review" ? "low_trust_review" : "standard"),
+ })
+ }
+ /> : null}
+
+ {content === "configuration" ? <div>
+ <h3 className="text-sm font-medium mb-3">Permissions</h3>
+ <div className="border border-border rounded-lg p-4 space-y-4">
+ <div className="flex items-center justify-between gap-4 text-sm">
+ <div className="space-y-1">
+ <div>Can create new agents</div>
+ <p className="text-xs text-muted-foreground">
+ Lets this agent create or hire agents. This also grants task assignment authority.
+ </p>
+ </div>
+ <ToggleSwitch
+ checked={canCreateAgents}
+ onCheckedChange={() =>
+ updatePermissions.mutate({
+ canCreateAgents: !canCreateAgents,
+ canCreateSkills,
+ canAssignTasks: !canCreateAgents ? true : canAssignTasks,
+ })
+ }
+ disabled={updatePermissions.isPending}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-4 text-sm">
+ <div className="space-y-1">
+ <div>Can create/import skills</div>
+ <p className="text-xs text-muted-foreground">
+ Lets this agent install, import, create, and scan company skills without creating agents.
+ </p>
+ </div>
+ <ToggleSwitch
+ checked={canCreateSkills}
+ onCheckedChange={() =>
+ updatePermissions.mutate({
+ canCreateAgents,
+ canCreateSkills: !canCreateSkills,
+ canAssignTasks,
+ })
+ }
+ disabled={updatePermissions.isPending}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-4 text-sm">
+ <div className="space-y-1">
+ <div>Can assign tasks</div>
+ <p className="text-xs text-muted-foreground">
+ {taskAssignHint}
+ </p>
+ </div>
+ <ToggleSwitch
+ checked={canAssignTasks}
+ onCheckedChange={() =>
+ updatePermissions.mutate({
+ canCreateAgents,
+ canCreateSkills,
+ canAssignTasks: !canAssignTasks,
+ })
+ }
+ disabled={updatePermissions.isPending || taskAssignLocked}
+ />
+ </div>
+ </div>
+ </div> : null}
+ </div>
+ );
+}
+
+/* ---- Prompts Tab ---- */
+
+export function PromptsTab({
+ agent,
+ companyId,
+ onDirtyChange,
+ onSaveActionChange,
+ onCancelActionChange,
+ onSavingChange,
+}: {
+ agent: Agent;
+ companyId?: string;
+ onDirtyChange: (dirty: boolean) => void;
+ onSaveActionChange: (save: (() => void) | null) => void;
+ onCancelActionChange: (cancel: (() => void) | null) => void;
+ onSavingChange: (saving: boolean) => void;
+}) {
+ const queryClient = useQueryClient();
+ const { selectedCompanyId } = useCompany();
+ const { isMobile } = useSidebar();
+ const [selectedFile, setSelectedFile] = useState<string>("AGENTS.md");
+ const [showFilePanel, setShowFilePanel] = useState(false);
+ const [draft, setDraft] = useState<string | null>(null);
+ const [bundleDraft, setBundleDraft] = useState<{
+ mode: "managed" | "external";
+ rootPath: string;
+ entryFile: string;
+ } | null>(null);
+ const [newFilePath, setNewFilePath] = useState("");
+ const [showNewFileInput, setShowNewFileInput] = useState(false);
+ const [pendingFiles, setPendingFiles] = useState<string[]>([]);
+ const [expandedDirs, setExpandedDirs] = useState<Set<string>>(new Set());
+ const [filePanelWidth, setFilePanelWidth] = useState(260);
+ const [instructionPaneWidth, setInstructionPaneWidth] = useState<number | null>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [awaitingRefresh, setAwaitingRefresh] = useState(false);
+ const lastFileVersionRef = useRef<string | null>(null);
+ const externalBundleRef = useRef<{
+ rootPath: string;
+ entryFile: string;
+ selectedFile: string;
+ } | null>(null);
+
+ useEffect(() => {
+ setSelectedFile("AGENTS.md");
+ setShowFilePanel(false);
+ setDraft(null);
+ setBundleDraft(null);
+ setNewFilePath("");
+ setShowNewFileInput(false);
+ setPendingFiles([]);
+ setExpandedDirs(new Set());
+ setAwaitingRefresh(false);
+ lastFileVersionRef.current = null;
+ externalBundleRef.current = null;
+ }, [agent.id]);
+
+ const getCapabilities = useAdapterCapabilities();
+ const isLocal = getCapabilities(agent.adapterType).supportsInstructionsBundle;
+
+ const { data: bundle, isLoading: bundleLoading } = useQuery({
+ queryKey: queryKeys.agents.instructionsBundle(agent.id),
+ queryFn: () => agentsApi.instructionsBundle(agent.id, companyId),
+ enabled: Boolean(companyId && isLocal),
+ });
+
+ const persistedMode = bundle?.mode ?? "managed";
+ const persistedRootPath = persistedMode === "managed"
+ ? (bundle?.managedRootPath ?? bundle?.rootPath ?? "")
+ : (bundle?.rootPath ?? "");
+ const currentMode = bundleDraft?.mode ?? persistedMode;
+ const currentEntryFile = bundleDraft?.entryFile ?? bundle?.entryFile ?? "AGENTS.md";
+ const currentRootPath = bundleDraft?.rootPath ?? persistedRootPath;
+ const fileOptions = useMemo(
+ () => bundle?.files.map((file) => file.path) ?? [],
+ [bundle],
+ );
+ const bundleMatchesDraft = Boolean(
+ bundle &&
+ currentMode === persistedMode &&
+ currentEntryFile === bundle.entryFile &&
+ currentRootPath === persistedRootPath,
+ );
+ const visibleFilePaths = useMemo(
+ () => bundleMatchesDraft
+ ? [...new Set([currentEntryFile, ...fileOptions, ...pendingFiles])]
+ : [currentEntryFile, ...pendingFiles],
+ [bundleMatchesDraft, currentEntryFile, fileOptions, pendingFiles],
+ );
+ const fileTree = useMemo(
+ () => buildFileTree(Object.fromEntries(visibleFilePaths.map((filePath) => [filePath, ""]))),
+ [visibleFilePaths],
+ );
+ const selectedOrEntryFile = selectedFile || currentEntryFile;
+ const selectedFileExists = bundleMatchesDraft && fileOptions.includes(selectedOrEntryFile);
+ const selectedFileSummary = bundle?.files.find((file) => file.path === selectedOrEntryFile) ?? null;
+
+ const { data: selectedFileDetail, isLoading: fileLoading } = useQuery({
+ queryKey: queryKeys.agents.instructionsFile(agent.id, selectedOrEntryFile),
+ queryFn: () => agentsApi.instructionsFile(agent.id, selectedOrEntryFile, companyId),
+ enabled: Boolean(companyId && isLocal && selectedFileExists),
+ });
+
+ const updateBundle = useMutation({
+ mutationFn: (data: {
+ mode?: "managed" | "external";
+ rootPath?: string | null;
+ entryFile?: string;
+ clearLegacyPromptTemplate?: boolean;
+ }) => agentsApi.updateInstructionsBundle(agent.id, data, companyId),
+ onMutate: () => setAwaitingRefresh(true),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.instructionsBundle(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) });
+ },
+ onError: () => setAwaitingRefresh(false),
+ });
+
+ const saveFile = useMutation({
+ mutationFn: (data: { path: string; content: string; clearLegacyPromptTemplate?: boolean }) =>
+ agentsApi.saveInstructionsFile(agent.id, data, companyId),
+ onMutate: () => setAwaitingRefresh(true),
+ onSuccess: (_, variables) => {
+ setPendingFiles((prev) => prev.filter((f) => f !== variables.path));
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.instructionsBundle(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.instructionsFile(agent.id, variables.path) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) });
+ },
+ onError: () => setAwaitingRefresh(false),
+ });
+
+ const deleteFile = useMutation({
+ mutationFn: (relativePath: string) => agentsApi.deleteInstructionsFile(agent.id, relativePath, companyId),
+ onMutate: () => setAwaitingRefresh(true),
+ onSuccess: (_, relativePath) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.instructionsBundle(agent.id) });
+ queryClient.removeQueries({ queryKey: queryKeys.agents.instructionsFile(agent.id, relativePath) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) });
+ },
+ onError: () => setAwaitingRefresh(false),
+ });
+
+ const uploadMarkdownImage = useMutation({
+ mutationFn: async ({ file, namespace }: { file: File; namespace: string }) => {
+ if (!selectedCompanyId) throw new Error("Select a company to upload images");
+ return assetsApi.uploadImage(selectedCompanyId, file, namespace);
+ },
+ });
+
+ useEffect(() => {
+ if (!bundle) return;
+ if (!bundleMatchesDraft) {
+ if (selectedFile !== currentEntryFile) setSelectedFile(currentEntryFile);
+ return;
+ }
+ const availablePaths = bundle.files.map((file) => file.path);
+ if (availablePaths.length === 0) {
+ if (selectedFile !== bundle.entryFile) setSelectedFile(bundle.entryFile);
+ return;
+ }
+ if (!availablePaths.includes(selectedFile) && selectedFile !== currentEntryFile && !pendingFiles.includes(selectedFile)) {
+ setSelectedFile(availablePaths.includes(bundle.entryFile) ? bundle.entryFile : availablePaths[0]!);
+ }
+ }, [bundle, bundleMatchesDraft, currentEntryFile, pendingFiles, selectedFile]);
+
+ useEffect(() => {
+ const nextExpanded = new Set<string>();
+ for (const filePath of visibleFilePaths) {
+ const parts = filePath.split("/");
+ let currentPath = "";
+ for (let i = 0; i < parts.length - 1; i++) {
+ currentPath = currentPath ? `${currentPath}/${parts[i]}` : parts[i]!;
+ nextExpanded.add(currentPath);
+ }
+ }
+ setExpandedDirs((current) => (setsEqual(current, nextExpanded) ? current : nextExpanded));
+ }, [visibleFilePaths]);
+
+ useEffect(() => {
+ if (isMobile) {
+ setInstructionPaneWidth(null);
+ return;
+ }
+ const element = containerRef.current;
+ if (!element) return;
+
+ const updateWidth = () => setInstructionPaneWidth(element.getBoundingClientRect().width);
+ updateWidth();
+
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver((entries) => {
+ const entry = entries[0];
+ if (entry) setInstructionPaneWidth(entry.contentRect.width);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [bundleLoading, isMobile, visibleFilePaths.length]);
+
+ useEffect(() => {
+ const versionKey = selectedFileExists && selectedFileDetail
+ ? `${selectedFileDetail.path}:${selectedFileDetail.content}`
+ : `draft:${currentMode}:${currentRootPath}:${selectedOrEntryFile}`;
+ if (awaitingRefresh) {
+ setAwaitingRefresh(false);
+ setBundleDraft(null);
+ setDraft(null);
+ lastFileVersionRef.current = versionKey;
+ return;
+ }
+ if (lastFileVersionRef.current !== versionKey) {
+ setDraft(null);
+ lastFileVersionRef.current = versionKey;
+ }
+ }, [awaitingRefresh, currentMode, currentRootPath, selectedFileDetail, selectedFileExists, selectedOrEntryFile]);
+
+ useEffect(() => {
+ if (!bundle) return;
+ setBundleDraft((current) => {
+ if (current) return current;
+ return {
+ mode: persistedMode,
+ rootPath: persistedRootPath,
+ entryFile: bundle.entryFile,
+ };
+ });
+ }, [bundle, persistedMode, persistedRootPath]);
+
+ useEffect(() => {
+ if (!bundle || currentMode !== "external") return;
+ externalBundleRef.current = {
+ rootPath: currentRootPath,
+ entryFile: currentEntryFile,
+ selectedFile: selectedOrEntryFile,
+ };
+ }, [bundle, currentEntryFile, currentMode, currentRootPath, selectedOrEntryFile]);
+
+ const currentContent = selectedFileExists ? (selectedFileDetail?.content ?? "") : "";
+ const displayValue = draft ?? currentContent;
+ const useMarkdownEditor = shouldUseMarkdownInstructionsEditor({
+ selectedFileExists,
+ selectedPath: selectedOrEntryFile,
+ detail: selectedFileDetail,
+ summary: selectedFileSummary,
+ });
+ const bundleDirty = Boolean(
+ bundleDraft &&
+ (
+ bundleDraft.mode !== persistedMode ||
+ bundleDraft.rootPath !== persistedRootPath ||
+ bundleDraft.entryFile !== (bundle?.entryFile ?? "AGENTS.md")
+ ),
+ );
+ const fileDirty = draft !== null && draft !== currentContent;
+ const isDirty = bundleDirty || fileDirty;
+ const isSaving = updateBundle.isPending || saveFile.isPending || deleteFile.isPending || awaitingRefresh;
+
+ useEffect(() => { onSavingChange(isSaving); }, [onSavingChange, isSaving]);
+ useEffect(() => { onDirtyChange(isDirty); }, [onDirtyChange, isDirty]);
+
+ useEffect(() => {
+ onSaveActionChange(isDirty ? () => {
+ const save = async () => {
+ const shouldClearLegacy =
+ Boolean(bundle?.legacyPromptTemplateActive) || Boolean(bundle?.legacyBootstrapPromptTemplateActive);
+ if (bundleDirty && bundleDraft) {
+ await updateBundle.mutateAsync({
+ mode: bundleDraft.mode,
+ rootPath: bundleDraft.mode === "external" ? bundleDraft.rootPath : null,
+ entryFile: bundleDraft.entryFile,
+ });
+ }
+ if (fileDirty) {
+ await saveFile.mutateAsync({
+ path: selectedOrEntryFile,
+ content: displayValue,
+ clearLegacyPromptTemplate: shouldClearLegacy,
+ });
+ }
+ };
+ void save().catch(() => undefined);
+ } : null);
+ }, [
+ bundle,
+ bundleDirty,
+ bundleDraft,
+ displayValue,
+ fileDirty,
+ isDirty,
+ onSaveActionChange,
+ saveFile,
+ selectedOrEntryFile,
+ updateBundle,
+ ]);
+
+ useEffect(() => {
+ onCancelActionChange(isDirty ? () => {
+ setDraft(null);
+ if (bundle) {
+ setBundleDraft({
+ mode: persistedMode,
+ rootPath: persistedRootPath,
+ entryFile: bundle.entryFile,
+ });
+ }
+ } : null);
+ }, [bundle, isDirty, onCancelActionChange, persistedMode, persistedRootPath]);
+
+ const handleSeparatorDrag = useCallback((event: React.MouseEvent) => {
+ event.preventDefault();
+ const startX = event.clientX;
+ const startWidth = filePanelWidth;
+ const onMouseMove = (moveEvent: MouseEvent) => {
+ const delta = moveEvent.clientX - startX;
+ const next = Math.max(180, Math.min(500, startWidth + delta));
+ setFilePanelWidth(next);
+ };
+ const onMouseUp = () => {
+ document.removeEventListener("mousemove", onMouseMove);
+ document.removeEventListener("mouseup", onMouseUp);
+ document.body.style.cursor = "";
+ document.body.style.userSelect = "";
+ };
+ document.addEventListener("mousemove", onMouseMove);
+ document.addEventListener("mouseup", onMouseUp);
+ document.body.style.cursor = "col-resize";
+ document.body.style.userSelect = "none";
+ }, [filePanelWidth]);
+
+ const instructionsSideBySide =
+ !isMobile && instructionPaneWidth !== null && instructionPaneWidth >= filePanelWidth + 520;
+
+ if (!isLocal) {
+ return (
+ <div className="max-w-3xl">
+ <p className="text-sm text-muted-foreground">
+ Instructions bundles are only available for local adapters.
+ </p>
+ </div>
+ );
+ }
+
+ if (bundleLoading && !bundle) {
+ return <PromptsTabSkeleton />;
+ }
+
+ return (
+ <div className="space-y-6">
+ {(bundle?.warnings ?? []).length > 0 && (
+ <div className="space-y-2">
+ {(bundle?.warnings ?? []).map((warning) => (
+ <div key={warning} className="rounded-md border border-sky-500/25 bg-sky-500/10 px-3 py-2 text-xs text-sky-900 dark:text-sky-100">
+ {warning}
+ </div>
+ ))}
+ </div>
+ )}
+ <p className="text-xs text-muted-foreground">
+ Saved instructions affect the next run. Active runs keep the instructions they started with, and instruction changes may start a fresh adapter session.
+ </p>
+
+ <Collapsible defaultOpen={currentMode === "external"}>
+ <CollapsibleTrigger className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors group">
+ <ChevronRight className="h-3 w-3 transition-transform group-data-[state=open]:rotate-90" />
+ Advanced
+ </CollapsibleTrigger>
+ <CollapsibleContent className="pt-4 pb-6">
+ <TooltipProvider>
+ <div className="grid gap-x-6 gap-y-4 md:grid-cols-(--gtc-18)">
+ <label className="space-y-1.5 min-w-0">
+ <span className="text-xs font-medium text-muted-foreground flex items-center gap-1">
+ Mode
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-3 w-3 text-muted-foreground cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent side="right" sideOffset={4}>
+ Managed: Paperclip stores and serves the instructions bundle. External: you provide a path on disk where the instructions live.
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant={currentMode === "managed" ? "default" : "outline"}
+ onClick={() => {
+ if (currentMode === "external") {
+ externalBundleRef.current = {
+ rootPath: currentRootPath,
+ entryFile: currentEntryFile,
+ selectedFile: selectedOrEntryFile,
+ };
+ }
+ const nextEntryFile = currentEntryFile || "AGENTS.md";
+ setBundleDraft({
+ mode: "managed",
+ rootPath: bundle?.managedRootPath ?? currentRootPath,
+ entryFile: nextEntryFile,
+ });
+ setSelectedFile(nextEntryFile);
+ }}
+ >
+ Managed
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant={currentMode === "external" ? "default" : "outline"}
+ onClick={() => {
+ const externalBundle = externalBundleRef.current;
+ const nextEntryFile = externalBundle?.entryFile ?? currentEntryFile ?? "AGENTS.md";
+ setBundleDraft({
+ mode: "external",
+ rootPath: externalBundle?.rootPath ?? (bundle?.mode === "external" ? (bundle.rootPath ?? "") : ""),
+ entryFile: nextEntryFile,
+ });
+ setSelectedFile(externalBundle?.selectedFile ?? nextEntryFile);
+ }}
+ >
+ External
+ </Button>
+ </div>
+ </label>
+ <label className="space-y-1.5 min-w-0">
+ <span className="text-xs font-medium text-muted-foreground flex items-center gap-1">
+ Root path
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-3 w-3 text-muted-foreground cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent side="right" sideOffset={4}>
+ The absolute directory on disk where the instructions bundle lives. In managed mode this is set by Paperclip automatically.
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ {currentMode === "managed" ? (
+ <div className="flex items-center gap-1.5 font-mono text-xs text-muted-foreground pt-1.5">
+ <span className="min-w-0 truncate" title={currentRootPath || undefined}>{currentRootPath || "(managed)"}</span>
+ {currentRootPath && (
+ <CopyText text={currentRootPath} className="shrink-0">
+ <Copy className="h-3.5 w-3.5" />
+ </CopyText>
+ )}
+ </div>
+ ) : (
+ <div className="flex items-center gap-1.5">
+ <Input
+ value={currentRootPath}
+ onChange={(event) => {
+ const nextRootPath = event.target.value;
+ externalBundleRef.current = {
+ rootPath: nextRootPath,
+ entryFile: currentEntryFile,
+ selectedFile: selectedOrEntryFile,
+ };
+ setBundleDraft({
+ mode: "external",
+ rootPath: nextRootPath,
+ entryFile: currentEntryFile,
+ });
+ }}
+ className="font-mono text-sm"
+ placeholder="/absolute/path/to/agent/prompts"
+ />
+ {currentRootPath && (
+ <CopyText text={currentRootPath} className="shrink-0">
+ <Copy className="h-3.5 w-3.5" />
+ </CopyText>
+ )}
+ </div>
+ )}
+ </label>
+ <label className="space-y-1.5">
+ <span className="text-xs font-medium text-muted-foreground flex items-center gap-1">
+ Entry file
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-3 w-3 text-muted-foreground cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent side="right" sideOffset={4}>
+ The main file the agent reads first when loading instructions. Defaults to AGENTS.md.
+ </TooltipContent>
+ </Tooltip>
+ </span>
+ <Input
+ value={currentEntryFile}
+ onChange={(event) => {
+ const nextEntryFile = event.target.value || "AGENTS.md";
+ const nextSelectedFile = selectedOrEntryFile === currentEntryFile
+ ? nextEntryFile
+ : selectedOrEntryFile;
+ if (currentMode === "external") {
+ externalBundleRef.current = {
+ rootPath: currentRootPath,
+ entryFile: nextEntryFile,
+ selectedFile: nextSelectedFile,
+ };
+ }
+ if (selectedOrEntryFile === currentEntryFile) setSelectedFile(nextEntryFile);
+ setBundleDraft({
+ mode: currentMode,
+ rootPath: currentRootPath,
+ entryFile: nextEntryFile,
+ });
+ }}
+ className="font-mono text-sm"
+ />
+ </label>
+ </div>
+ </TooltipProvider>
+ </CollapsibleContent>
+ </Collapsible>
+
+ <div
+ ref={containerRef}
+ className="grid min-w-0 gap-3"
+ style={
+ instructionsSideBySide
+ ? { gridTemplateColumns: `${filePanelWidth}px 0.5rem minmax(0, 1fr)` }
+ : undefined
+ }
+ >
+ <div className={cn(
+ "min-w-0 w-full border border-border rounded-lg p-3 space-y-3",
+ isMobile && showFilePanel && "block",
+ isMobile && !showFilePanel && "hidden",
+ )}>
+ <div className="flex items-center justify-between">
+ <h4 className="text-sm font-medium">Files</h4>
+ <div className="flex items-center gap-1">
+ {!showNewFileInput && (
+ <Button
+ type="button"
+ size="icon"
+ variant="outline"
+ className="h-7 w-7"
+ onClick={() => setShowNewFileInput(true)}
+ >
+ +
+ </Button>
+ )}
+ {isMobile && (
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="h-7 w-7"
+ onClick={() => setShowFilePanel(false)}
+ >
+ ✕
+ </Button>
+ )}
+ </div>
+ </div>
+ {showNewFileInput && (
+ <div className="space-y-2">
+ <Input
+ value={newFilePath}
+ onChange={(event) => setNewFilePath(event.target.value)}
+ placeholder="TOOLS.md"
+ className="font-mono text-sm"
+ autoFocus
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ setShowNewFileInput(false);
+ setNewFilePath("");
+ }
+ }}
+ />
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="default"
+ className="flex-1"
+ disabled={!newFilePath.trim() || newFilePath.includes("..")}
+ onClick={() => {
+ const candidate = newFilePath.trim();
+ if (!candidate || candidate.includes("..")) return;
+ setPendingFiles((prev) => prev.includes(candidate) ? prev : [...prev, candidate]);
+ setSelectedFile(candidate);
+ setDraft("");
+ setNewFilePath("");
+ setShowNewFileInput(false);
+ }}
+ >
+ Create
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="flex-1"
+ onClick={() => {
+ setShowNewFileInput(false);
+ setNewFilePath("");
+ }}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )}
+ <FileTree
+ nodes={fileTree}
+ selectedFile={selectedOrEntryFile}
+ expandedDirs={expandedDirs}
+ checkedFiles={new Set()}
+ onToggleDir={(dirPath) => setExpandedDirs((current) => {
+ const next = new Set(current);
+ if (next.has(dirPath)) next.delete(dirPath);
+ else next.add(dirPath);
+ return next;
+ })}
+ onSelectFile={(filePath) => {
+ setSelectedFile(filePath);
+ if (!fileOptions.includes(filePath)) setDraft("");
+ if (isMobile) setShowFilePanel(false);
+ }}
+ onToggleCheck={() => {}}
+ showCheckboxes={false}
+ wrapLabels
+ renderFileExtra={(node) => {
+ const file = bundle?.files.find((entry) => entry.path === node.path);
+ if (!file) return null;
+ if (file.deprecated) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="ml-3 shrink-0 rounded border border-amber-500/40 bg-amber-500/10 text-amber-800 dark:text-amber-200 px-1.5 py-0.5 text-(length:--text-nano) uppercase tracking-wide cursor-help">
+ virtual file
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="right" sideOffset={4}>
+ Legacy inline prompt — this deprecated virtual file preserves the old promptTemplate content
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+ return (
+ <span className="ml-3 shrink-0 rounded border border-border text-muted-foreground px-1.5 py-0.5 text-(length:--text-nano) uppercase tracking-wide">
+ {file.isEntryFile ? "entry" : `${file.size}b`}
+ </span>
+ );
+ }}
+ />
+ </div>
+
+ {/* Draggable separator */}
+ {instructionsSideBySide && (
+ <div
+ className="w-1 cursor-col-resize rounded transition-colors hover:bg-border active:bg-primary/50"
+ onMouseDown={handleSeparatorDrag}
+ />
+ )}
+
+ <div className={cn("min-w-0 w-full overflow-hidden border border-border rounded-lg p-4 space-y-3", isMobile && showFilePanel && "hidden")}>
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2 min-w-0">
+ {isMobile && (
+ <Button
+ type="button"
+ size="icon"
+ variant="outline"
+ className="h-7 w-7 shrink-0"
+ onClick={() => setShowFilePanel(true)}
+ >
+ <FolderOpen className="h-3.5 w-3.5" />
+ </Button>
+ )}
+ <div className="min-w-0">
+ <h4 className="text-sm font-medium font-mono truncate">{selectedOrEntryFile}</h4>
+ <p className="text-xs text-muted-foreground">
+ {selectedFileExists
+ ? selectedFileSummary?.deprecated
+ ? "Deprecated virtual file"
+ : `${selectedFileDetail?.language ?? "text"} file`
+ : "New file in this bundle"}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ {!fileLoading && (
+ <CopyText
+ text={displayValue}
+ ariaLabel="Copy instructions file as markdown"
+ title="Copy as markdown"
+ copiedLabel="Copied"
+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-muted-foreground hover:bg-accent hover:text-foreground"
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </CopyText>
+ )}
+ {selectedFileExists && !selectedFileSummary?.deprecated && selectedOrEntryFile !== currentEntryFile && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ if (confirm(`Delete ${selectedOrEntryFile}?`)) {
+ deleteFile.mutate(selectedOrEntryFile, {
+ onSuccess: () => {
+ setSelectedFile(currentEntryFile);
+ setDraft(null);
+ },
+ });
+ }
+ }}
+ disabled={deleteFile.isPending}
+ >
+ Delete
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {selectedFileExists && fileLoading && !selectedFileDetail ? (
+ <PromptEditorSkeleton />
+ ) : useMarkdownEditor ? (
+ <MarkdownEditor
+ key={selectedOrEntryFile}
+ value={displayValue}
+ onChange={(value) => setDraft(value ?? "")}
+ placeholder="# Agent instructions"
+ className="min-w-0 overflow-hidden"
+ contentClassName="min-h-(--sz-420px) max-w-full break-words text-sm leading-7"
+ imageUploadHandler={async (file) => {
+ const namespace = `agents/${agent.id}/instructions/${selectedOrEntryFile.replaceAll("/", "-")}`;
+ const asset = await uploadMarkdownImage.mutateAsync({ file, namespace });
+ return asset.contentPath;
+ }}
+ />
+ ) : (
+ <textarea
+ value={displayValue}
+ onChange={(event) => setDraft(event.target.value)}
+ className="min-h-(--sz-420px) w-full min-w-0 rounded-md border border-border bg-transparent px-3 py-2 font-mono text-sm outline-none"
+ placeholder="File contents"
+ />
+ )}
+ </div>
+ </div>
+
+ </div>
+ );
+}
+
+function PromptsTabSkeleton() {
+ return (
+ <div className="max-w-5xl space-y-4">
+ <div className="rounded-lg border border-border p-4 space-y-4">
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-4 w-(--sz-30rem) max-w-full" />
+ </div>
+ <Skeleton className="h-4 w-16" />
+ </div>
+ <div className="grid gap-3 md:grid-cols-3">
+ {Array.from({ length: 3 }).map((_, index) => (
+ <div key={index} className="space-y-2">
+ <Skeleton className="h-3 w-20" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="grid gap-4 lg:grid-cols-(--gtc-19)">
+ <div className="rounded-lg border border-border p-3 space-y-3">
+ <div className="flex items-center justify-between">
+ <Skeleton className="h-4 w-12" />
+ <Skeleton className="h-8 w-16" />
+ </div>
+ <Skeleton className="h-10 w-full" />
+ <div className="space-y-2">
+ {Array.from({ length: 5 }).map((_, index) => (
+ <Skeleton key={index} className="h-9 w-full rounded-none" />
+ ))}
+ </div>
+ </div>
+ <div className="rounded-lg border border-border p-4 space-y-3">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-48" />
+ <Skeleton className="h-3 w-28" />
+ </div>
+ <PromptEditorSkeleton />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function PromptEditorSkeleton() {
+ return (
+ <div className="space-y-3">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-(--sz-420px) w-full" />
+ </div>
+ );
+}
+
+/* ---- Runs Tab ---- */
+
+function RunListItem({ run, isSelected, agentId }: { run: HeartbeatRun; isSelected: boolean; agentId: string }) {
+ const statusInfo = runStatusIcons[run.status] ?? { icon: Clock, color: "text-neutral-400" };
+ const StatusIcon = statusInfo.icon;
+ const metrics = runMetrics(run);
+ const summary = run.resultJson
+ ? String((run.resultJson as Record<string, unknown>).summary ?? (run.resultJson as Record<string, unknown>).result ?? "")
+ : run.error ?? "";
+ const sourceResolvedFold = readSourceResolvedWatchdogFold(run.resultJson);
+
+ return (
+ <Link
+ to={isSelected ? `/agents/${agentId}/runs` : `/agents/${agentId}/runs/${run.id}`}
+ className={cn(
+ "flex flex-col gap-1 w-full px-3 py-2.5 text-left border-b border-border last:border-b-0 transition-colors no-underline text-inherit",
+ isSelected ? "bg-accent/40" : "hover:bg-accent/20",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <StatusIcon className={cn("h-3.5 w-3.5 shrink-0", statusInfo.color, run.status === "running" && "animate-spin")} />
+ <span className="font-mono text-xs text-muted-foreground">
+ {run.id.slice(0, 8)}
+ </span>
+ <Badge variant="ghost" className={cn(
+ "px-1.5 text-(length:--text-nano)",
+ run.invocationSource === "timer" ? "bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"
+ : run.invocationSource === "assignment" ? "bg-violet-100 text-violet-700 dark:bg-violet-900/50 dark:text-violet-300"
+ : run.invocationSource === "on_demand" ? "bg-cyan-100 text-cyan-700 dark:bg-cyan-900/50 dark:text-cyan-300"
+ : "bg-muted text-muted-foreground"
+ )}>
+ {sourceLabels[run.invocationSource] ?? run.invocationSource}
+ </Badge>
+ {sourceResolvedFold ? <SourceResolvedFoldBadge showIcon={false} className="shrink-0 text-(length:--text-nano) py-0" /> : null}
+ <span className="ml-auto text-(length:--text-micro) text-muted-foreground shrink-0">
+ {relativeTime(run.createdAt)}
+ </span>
+ </div>
+ {summary && (
+ <span className="text-xs text-muted-foreground truncate pl-5.5">
+ {summary.slice(0, 60)}
+ </span>
+ )}
+ {(metrics.totalTokens > 0 || metrics.cost > 0) && (
+ <div className="flex items-center gap-2 pl-5.5 text-(length:--text-micro) text-muted-foreground tabular-nums">
+ {metrics.totalTokens > 0 && <span>{formatTokens(metrics.totalTokens)} tok</span>}
+ {metrics.cost > 0 && <span>${metrics.cost.toFixed(3)}</span>}
+ </div>
+ )}
+ </Link>
+ );
+}
+
+function RunsTab({
+ runs,
+ companyId,
+ agentId,
+ agentRouteId,
+ selectedRunId,
+ adapterType,
+ adapterConfig,
+}: {
+ runs: HeartbeatRun[];
+ companyId: string;
+ agentId: string;
+ agentRouteId: string;
+ selectedRunId: string | null;
+ adapterType: string;
+ adapterConfig: Record<string, unknown>;
+}) {
+ const { isMobile } = useSidebar();
+
+ if (runs.length === 0) {
+ return <p className="text-sm text-muted-foreground">No runs yet.</p>;
+ }
+
+ // Sort by created descending
+ const sorted = [...runs].sort(
+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
+ );
+
+ // On mobile, don't auto-select so the list shows first; on desktop, auto-select latest
+ const effectiveRunId = isMobile ? selectedRunId : (selectedRunId ?? sorted[0]?.id ?? null);
+ const selectedRun = sorted.find((r) => r.id === effectiveRunId) ?? null;
+
+ // Mobile: show either run list OR run detail with back button
+ if (isMobile) {
+ if (selectedRun) {
+ return (
+ <div className="space-y-3 min-w-0 overflow-x-hidden">
+ <Link
+ to={`/agents/${agentRouteId}/runs`}
+ className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors no-underline"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ Back to runs
+ </Link>
+ <RunDetail key={selectedRun.id} run={selectedRun} agentRouteId={agentRouteId} adapterType={adapterType} adapterConfig={adapterConfig} />
+ </div>
+ );
+ }
+ return (
+ <div className="border border-border rounded-lg overflow-x-hidden">
+ {sorted.map((run) => (
+ <RunListItem key={run.id} run={run} isSelected={false} agentId={agentRouteId} />
+ ))}
+ </div>
+ );
+ }
+
+ // Desktop: side-by-side layout
+ return (
+ <div className="flex gap-0">
+ {/* Left: run list — border stretches full height, content sticks */}
+ <div className={cn(
+ "shrink-0 border border-border rounded-lg",
+ selectedRun ? "w-72" : "w-full",
+ )}>
+ <div className="sticky top-4 overflow-y-auto" style={{ maxHeight: "calc(100vh - 2rem)" }}>
+ {sorted.map((run) => (
+ <RunListItem key={run.id} run={run} isSelected={run.id === effectiveRunId} agentId={agentRouteId} />
+ ))}
+ </div>
+ </div>
+
+ {/* Right: run detail — natural height, page scrolls */}
+ {selectedRun && (
+ <div className="flex-1 min-w-0 pl-4">
+ <RunDetail key={selectedRun.id} run={selectedRun} agentRouteId={agentRouteId} adapterType={adapterType} adapterConfig={adapterConfig} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---- Run Detail (expanded) ---- */
+
+function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }: { run: HeartbeatRun; agentRouteId: string; adapterType: string; adapterConfig: Record<string, unknown> }) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const { data: hydratedRun } = useQuery({
+ queryKey: queryKeys.runDetail(initialRun.id),
+ queryFn: () => heartbeatsApi.get(initialRun.id),
+ enabled: Boolean(initialRun.id),
+ refetchInterval: (query) => runDetailRefetchIntervalMs(
+ (query.state.data ?? initialRun).status,
+ ),
+ });
+ const run = hydratedRun ?? initialRun;
+ const metrics = runMetrics(run);
+ const { data: userDirectory } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(run.companyId),
+ queryFn: () => accessApi.listUserDirectory(run.companyId),
+ enabled: Boolean(run.companyId && run.responsibleUserId),
+ retry: false,
+ });
+ const responsibleUserName = useMemo(() => {
+ if (!run.responsibleUserId) return null;
+ const entry = userDirectory?.users.find(
+ (candidate) => candidate.principalId === run.responsibleUserId,
+ );
+ return entry?.user?.name ?? entry?.user?.email ?? null;
+ }, [run.responsibleUserId, userDirectory]);
+ const responsibleDenialCode = isResponsibleUserDenialCode(run.errorCode) ? run.errorCode : null;
+ const [sessionOpen, setSessionOpen] = useState(false);
+ const [claudeLoginResult, setClaudeLoginResult] = useState<ClaudeLoginResult | null>(null);
+
+ useEffect(() => {
+ setClaudeLoginResult(null);
+ }, [run.id]);
+
+ const cancelRun = useMutation({
+ mutationFn: () => heartbeatsApi.cancel(run.id),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(run.companyId, run.agentId) });
+ },
+ });
+ const canResumeLostRun = run.errorCode === "process_lost" && run.status === "failed";
+ const resumePayload = useMemo(() => {
+ const payload: Record<string, unknown> = {
+ resumeFromRunId: run.id,
+ };
+ const context = asRecord(run.contextSnapshot);
+ if (!context) return payload;
+ const issueId = asNonEmptyString(context.issueId);
+ const taskId = asNonEmptyString(context.taskId);
+ const taskKey = asNonEmptyString(context.taskKey);
+ const commentId = asNonEmptyString(context.wakeCommentId) ?? asNonEmptyString(context.commentId);
+ if (issueId) payload.issueId = issueId;
+ if (taskId) payload.taskId = taskId;
+ if (taskKey) payload.taskKey = taskKey;
+ if (commentId) payload.commentId = commentId;
+ return payload;
+ }, [run.contextSnapshot, run.id]);
+ const resumeRun = useMutation({
+ mutationFn: async () => {
+ const result = await agentsApi.wakeup(run.agentId, {
+ source: "on_demand",
+ triggerDetail: "manual",
+ reason: "resume_process_lost_run",
+ payload: resumePayload,
+ }, run.companyId);
+ if (!("id" in result)) {
+ throw new Error(result.message ?? "Resume request was skipped.");
+ }
+ return result;
+ },
+ onSuccess: (resumedRun) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(run.companyId, run.agentId) });
+ navigate(`/agents/${agentRouteId}/runs/${resumedRun.id}`);
+ },
+ });
+
+ const canRetryRun = run.status === "failed" || run.status === "timed_out";
+ const retryPayload = useMemo(() => {
+ const payload: Record<string, unknown> = {};
+ const context = asRecord(run.contextSnapshot);
+ if (!context) return payload;
+ const issueId = asNonEmptyString(context.issueId);
+ const taskId = asNonEmptyString(context.taskId);
+ const taskKey = asNonEmptyString(context.taskKey);
+ if (issueId) payload.issueId = issueId;
+ if (taskId) payload.taskId = taskId;
+ if (taskKey) payload.taskKey = taskKey;
+ return payload;
+ }, [run.contextSnapshot]);
+ const retryRun = useMutation({
+ mutationFn: async () => {
+ const result = await agentsApi.wakeup(run.agentId, {
+ source: "on_demand",
+ triggerDetail: "manual",
+ reason: "retry_failed_run",
+ payload: retryPayload,
+ }, run.companyId);
+ if (!("id" in result)) {
+ throw new Error(result.message ?? "Retry was skipped.");
+ }
+ return result;
+ },
+ onSuccess: (newRun) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(run.companyId, run.agentId) });
+ navigate(`/agents/${agentRouteId}/runs/${newRun.id}`);
+ },
+ });
+
+ const { data: touchedIssues } = useQuery({
+ queryKey: queryKeys.runIssues(run.id),
+ queryFn: () => activityApi.issuesForRun(run.id),
+ });
+ const touchedIssueIds = useMemo(
+ () => Array.from(new Set((touchedIssues ?? []).map((issue) => issue.issueId))),
+ [touchedIssues],
+ );
+
+ const clearSessionsForTouchedIssues = useMutation({
+ mutationFn: async () => {
+ if (touchedIssueIds.length === 0) return 0;
+ await Promise.all(touchedIssueIds.map((issueId) => agentsApi.resetSession(run.agentId, issueId, run.companyId)));
+ return touchedIssueIds.length;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.runtimeState(run.agentId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.taskSessions(run.agentId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.runIssues(run.id) });
+ },
+ });
+
+ const runClaudeLogin = useMutation({
+ mutationFn: () => agentsApi.loginWithClaude(run.agentId, run.companyId),
+ onSuccess: (data) => {
+ setClaudeLoginResult(data);
+ },
+ });
+
+ const isRunning = run.status === "running" && !!run.startedAt && !run.finishedAt;
+ const [elapsedSec, setElapsedSec] = useState<number>(() => {
+ if (!run.startedAt) return 0;
+ return Math.max(0, Math.round((Date.now() - new Date(run.startedAt).getTime()) / 1000));
+ });
+
+ useEffect(() => {
+ if (!isRunning || !run.startedAt) return;
+ const startMs = new Date(run.startedAt).getTime();
+ setElapsedSec(Math.max(0, Math.round((Date.now() - startMs) / 1000)));
+ const id = setInterval(() => {
+ setElapsedSec(Math.max(0, Math.round((Date.now() - startMs) / 1000)));
+ }, 1000);
+ return () => clearInterval(id);
+ }, [isRunning, run.startedAt]);
+
+ const timeFormat: Intl.DateTimeFormatOptions = { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false };
+ const startTime = run.startedAt ? new Date(run.startedAt).toLocaleTimeString("en-US", timeFormat) : null;
+ const endTime = run.finishedAt ? new Date(run.finishedAt).toLocaleTimeString("en-US", timeFormat) : null;
+ const durationSec = run.startedAt && run.finishedAt
+ ? Math.round((new Date(run.finishedAt).getTime() - new Date(run.startedAt).getTime()) / 1000)
+ : null;
+ const displayDurationSec = durationSec ?? (isRunning ? elapsedSec : null);
+ const hasMetrics = metrics.input > 0 || metrics.output > 0 || metrics.cached > 0 || metrics.cost > 0;
+ const hasSession = !!(run.sessionIdBefore || run.sessionIdAfter);
+ const sessionChanged = run.sessionIdBefore && run.sessionIdAfter && run.sessionIdBefore !== run.sessionIdAfter;
+ const sessionId = run.sessionIdAfter || run.sessionIdBefore;
+ const hasNonZeroExit = run.exitCode !== null && run.exitCode !== 0;
+ const retryState = describeRunRetryState(run);
+
+ return (
+ <div className="space-y-4 min-w-0">
+ {/* Workspace-validation recovery: surfaces the recovery card when this run was declined over a
+ git workspace it could not validate, wired to the same reconcile / repair / re-issue /
+ break-glass handlers as the task detail page. */}
+ <RunWorkspaceRecoverySurface run={run} />
+ {/* Run summary card */}
+ <div className="border border-border rounded-lg overflow-hidden">
+ <div className="flex flex-col sm:flex-row">
+ {/* Left column: status + timing */}
+ <div className="flex-1 p-4 space-y-3">
+ <div className="flex items-center gap-2">
+ <StatusBadge status={run.status} />
+ {(run.status === "running" || run.status === "queued") && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive hover:text-destructive text-xs h-6 px-2"
+ onClick={() => cancelRun.mutate()}
+ disabled={cancelRun.isPending}
+ >
+ {cancelRun.isPending ? "Cancelling…" : "Cancel"}
+ </Button>
+ )}
+ {canResumeLostRun && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs h-6 px-2"
+ onClick={() => resumeRun.mutate()}
+ disabled={resumeRun.isPending}
+ >
+ <RotateCcw className="h-3.5 w-3.5 mr-1" />
+ {resumeRun.isPending ? "Resuming…" : "Resume"}
+ </Button>
+ )}
+ {canRetryRun && !canResumeLostRun && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs h-6 px-2"
+ onClick={() => retryRun.mutate()}
+ disabled={retryRun.isPending}
+ >
+ <RotateCcw className="h-3.5 w-3.5 mr-1" />
+ {retryRun.isPending ? "Retrying…" : "Retry"}
+ </Button>
+ )}
+ </div>
+ {/* Adapter type · provider · model */}
+ {(() => {
+ const displayProvider = metrics.provider
+ ?? asNonEmptyString(adapterConfig?.provider);
+ const displayModel = metrics.model
+ ?? asNonEmptyString(adapterConfig?.model);
+ if (!adapterType && !displayProvider && !displayModel) return null;
+ return (
+ <div className="text-(length:--text-micro) text-muted-foreground font-mono flex items-center gap-1.5 flex-wrap">
+ {adapterType && (
+ <span className="bg-muted rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium uppercase tracking-wide">{adapterType.replace(/_/g, " ")}</span>
+ )}
+ {displayProvider && displayModel && (
+ <span>{displayProvider}/{displayModel}</span>
+ )}
+ {!displayProvider && displayModel && (
+ <span>{displayModel}</span>
+ )}
+ </div>
+ );
+ })()}
+ {run.responsibleUserId && (
+ <div
+ data-testid="run-detail-on-behalf-of"
+ className="text-xs text-muted-foreground"
+ >
+ On behalf of{" "}
+ <span className="text-foreground">
+ {responsibleUserName ?? responsibleUserLabel(null)}
+ </span>
+ </div>
+ )}
+ {resumeRun.isError && (
+ <div className="text-xs text-destructive">
+ {resumeRun.error instanceof Error ? resumeRun.error.message : "Failed to resume run"}
+ </div>
+ )}
+ {retryRun.isError && (
+ <div className="text-xs text-destructive">
+ {retryRun.error instanceof Error ? retryRun.error.message : "Failed to retry run"}
+ </div>
+ )}
+ {startTime && (
+ <div className="space-y-0.5">
+ <div className="text-sm font-mono">
+ {startTime}
+ {endTime && <span className="text-muted-foreground"> &rarr; </span>}
+ {endTime}
+ </div>
+ <div className="text-(length:--text-micro) text-muted-foreground">
+ {relativeTime(run.startedAt!)}
+ {run.finishedAt && <> &rarr; {relativeTime(run.finishedAt)}</>}
+ </div>
+ {displayDurationSec !== null && (
+ <div className="text-xs text-muted-foreground">
+ Duration: {displayDurationSec >= 60 ? `${Math.floor(displayDurationSec / 60)}m ${displayDurationSec % 60}s` : `${displayDurationSec}s`}
+ </div>
+ )}
+ </div>
+ )}
+ {run.error && (
+ <div className="text-xs">
+ <span className="text-red-600 dark:text-red-400">{run.error}</span>
+ {run.errorCode && <span className="text-muted-foreground ml-1">({run.errorCode})</span>}
+ </div>
+ )}
+ {run.errorCode === "claude_auth_required" && adapterType === "claude_local" && (
+ <div className="space-y-2">
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={() => runClaudeLogin.mutate()}
+ disabled={runClaudeLogin.isPending}
+ >
+ {runClaudeLogin.isPending ? "Running claude login..." : "Login to Claude Code"}
+ </Button>
+ {runClaudeLogin.isError && (
+ <p className="text-xs text-destructive">
+ {runClaudeLogin.error instanceof Error
+ ? runClaudeLogin.error.message
+ : "Failed to run Claude login"}
+ </p>
+ )}
+ {claudeLoginResult?.loginUrl && (
+ <p className="text-xs">
+ Login URL:
+ <a
+ href={claudeLoginResult.loginUrl}
+ className="text-blue-600 underline underline-offset-2 ml-1 break-all dark:text-blue-400"
+ target="_blank"
+ rel="noreferrer"
+ >
+ {claudeLoginResult.loginUrl}
+ </a>
+ </p>
+ )}
+ {claudeLoginResult && (
+ <>
+ {!!claudeLoginResult.stdout && (
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap">
+ {claudeLoginResult.stdout}
+ </pre>
+ )}
+ {!!claudeLoginResult.stderr && (
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap">
+ {claudeLoginResult.stderr}
+ </pre>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ {responsibleDenialCode && (
+ <ResponsibleUserDenialNotice
+ code={responsibleDenialCode}
+ userName={responsibleUserName}
+ />
+ )}
+ {hasNonZeroExit && (
+ <div className="text-xs text-red-600 dark:text-red-400">
+ Exit code {run.exitCode}
+ {run.signal && <span className="text-muted-foreground ml-1">(signal: {run.signal})</span>}
+ </div>
+ )}
+ {retryState && (
+ <div className="rounded-md border border-border/70 bg-accent/20 px-3 py-2 text-xs leading-5">
+ <div className="flex flex-wrap items-center gap-2">
+ <span
+ className={cn(
+ "rounded-md border px-1.5 py-0.5 text-(length:--text-micro) font-medium",
+ retryState.tone,
+ )}
+ >
+ {retryState.badgeLabel}
+ </span>
+ {retryState.retryOfRunId ? (
+ <Link
+ to={`/agents/${agentRouteId}/runs/${retryState.retryOfRunId}`}
+ className="font-mono text-foreground hover:underline"
+ >
+ {retryState.retryOfRunId.slice(0, 8)}
+ </Link>
+ ) : null}
+ </div>
+ {retryState.detail ? <p className="mt-2 text-muted-foreground">{retryState.detail}</p> : null}
+ {retryState.secondary ? <p className="text-muted-foreground">{retryState.secondary}</p> : null}
+ </div>
+ )}
+ </div>
+
+ {/* Right column: metrics */}
+ {hasMetrics && (
+ <div className="border-t sm:border-t-0 sm:border-l border-border p-4 grid grid-cols-2 gap-x-4 sm:gap-x-8 gap-y-3 content-center tabular-nums">
+ <div>
+ <div className="text-xs text-muted-foreground">Input</div>
+ <div className="text-sm font-medium font-mono">{formatTokens(metrics.input)}</div>
+ </div>
+ <div>
+ <div className="text-xs text-muted-foreground">Output</div>
+ <div className="text-sm font-medium font-mono">{formatTokens(metrics.output)}</div>
+ </div>
+ <div>
+ <div className="text-xs text-muted-foreground">Cached</div>
+ <div className="text-sm font-medium font-mono">{formatTokens(metrics.cached)}</div>
+ </div>
+ <div>
+ <div className="text-xs text-muted-foreground">Cost</div>
+ <div className="text-sm font-medium font-mono">{metrics.cost > 0 ? `$${metrics.cost.toFixed(4)}` : "-"}</div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Collapsible session row */}
+ {hasSession && (
+ <div className="border-t border-border">
+ <button
+ className="flex items-center gap-1.5 w-full px-4 py-2 text-xs text-muted-foreground hover:text-foreground transition-colors"
+ onClick={() => setSessionOpen((v) => !v)}
+ >
+ <ChevronRight className={cn("h-3 w-3 transition-transform", sessionOpen && "rotate-90")} />
+ Session
+ {sessionChanged && <span className="text-yellow-400 ml-1">(changed)</span>}
+ </button>
+ {sessionOpen && (
+ <div className="px-4 pb-3 space-y-1 text-xs">
+ {run.sessionIdBefore && (
+ <div className="flex items-center gap-2">
+ <span className="text-muted-foreground w-12">{sessionChanged ? "Before" : "ID"}</span>
+ <CopyText text={run.sessionIdBefore} className="font-mono" />
+ </div>
+ )}
+ {sessionChanged && run.sessionIdAfter && (
+ <div className="flex items-center gap-2">
+ <span className="text-muted-foreground w-12">After</span>
+ <CopyText text={run.sessionIdAfter} className="font-mono" />
+ </div>
+ )}
+ {touchedIssueIds.length > 0 && (
+ <div className="pt-1">
+ <button
+ type="button"
+ className="text-(length:--text-micro) text-muted-foreground underline underline-offset-2 hover:text-foreground disabled:opacity-60"
+ disabled={clearSessionsForTouchedIssues.isPending}
+ onClick={() => {
+ const issueCount = touchedIssueIds.length;
+ const confirmed = window.confirm(
+ `Clear session for ${issueCount} issue${issueCount === 1 ? "" : "s"} touched by this run?`,
+ );
+ if (!confirmed) return;
+ clearSessionsForTouchedIssues.mutate();
+ }}
+ >
+ {clearSessionsForTouchedIssues.isPending
+ ? "clearing session..."
+ : "clear session for these tasks"}
+ </button>
+ {clearSessionsForTouchedIssues.isError && (
+ <p className="text-(length:--text-micro) text-destructive mt-1">
+ {clearSessionsForTouchedIssues.error instanceof Error
+ ? clearSessionsForTouchedIssues.error.message
+ : "Failed to clear sessions"}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Issues touched by this run */}
+ {touchedIssues && touchedIssues.length > 0 && (
+ <div className="space-y-2">
+ <span className="text-xs font-medium text-muted-foreground">Tasks Touched ({touchedIssues.length})</span>
+ <div className="border border-border rounded-lg divide-y divide-border">
+ {touchedIssues.map((issue) => (
+ <Link
+ key={issue.issueId}
+ to={`/issues/${issue.identifier ?? issue.issueId}`}
+ className="flex items-center justify-between w-full px-3 py-2 text-xs hover:bg-accent/20 transition-colors text-left no-underline text-inherit"
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <StatusBadge status={issue.status} />
+ <span className="truncate">{issue.title}</span>
+ </div>
+ <span className="font-mono text-muted-foreground shrink-0 ml-2">{issue.identifier ?? issue.issueId.slice(0, 8)}</span>
+ </Link>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* stderr excerpt for failed runs */}
+ {run.stderrExcerpt && (
+ <div className="space-y-1">
+ <span className="text-xs font-medium text-red-600 dark:text-red-400">stderr</span>
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap">{run.stderrExcerpt}</pre>
+ </div>
+ )}
+
+ {/* stdout excerpt when no log is available */}
+ {run.stdoutExcerpt && !run.logRef && (
+ <div className="space-y-1">
+ <span className="text-xs font-medium text-muted-foreground">stdout</span>
+ <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap">{run.stdoutExcerpt}</pre>
+ </div>
+ )}
+
+ {(() => {
+ const fold = readSourceResolvedWatchdogFold(run.resultJson);
+ if (!fold) return null;
+ if (run.status === "failed" || run.status === "timed_out") return null;
+ return <SourceResolvedFoldCallout fold={fold} finalizedAt={run.finishedAt} />;
+ })()}
+
+ {/* Log viewer */}
+ <LogViewer run={run} adapterType={adapterType} />
+ <ScrollToBottom />
+ </div>
+ );
+}
+
+/* ---- Log Viewer ---- */
+
+function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType: string }) {
+ const [events, setEvents] = useState<HeartbeatRunEvent[]>([]);
+ const [logLines, setLogLines] = useState<Array<{ ts: string; stream: "stdout" | "stderr" | "system"; chunk: string }>>([]);
+ const [loading, setLoading] = useState(true);
+ const [logLoading, setLogLoading] = useState(!!run.logRef);
+ const [logError, setLogError] = useState<string | null>(null);
+ const [logOffset, setLogOffset] = useState(0);
+ const [hasMoreLog, setHasMoreLog] = useState(false);
+ const [loadingMoreLog, setLoadingMoreLog] = useState(false);
+ const [isFollowing, setIsFollowing] = useState(false);
+ const [isStreamingConnected, setIsStreamingConnected] = useState(false);
+ const [transcriptMode, setTranscriptMode] = useState<TranscriptMode>("nice");
+ const logEndRef = useRef<HTMLDivElement>(null);
+ const pendingLogLineRef = useRef("");
+ const seenProgressLogLineKeysRef = useRef<Set<string>>(new Set());
+ const scrollContainerRef = useRef<ScrollContainer | null>(null);
+ const isFollowingRef = useRef(false);
+ const lastMetricsRef = useRef<{ scrollHeight: number; distanceFromBottom: number }>({
+ scrollHeight: 0,
+ distanceFromBottom: Number.POSITIVE_INFINITY,
+ });
+ const isLive = run.status === "running" || run.status === "queued";
+ const shouldPollShellLog = shouldPollRunShellLog(run.status);
+ const { data: workspaceOperations = [] } = useQuery({
+ queryKey: queryKeys.runWorkspaceOperations(run.id),
+ queryFn: () => heartbeatsApi.workspaceOperations(run.id),
+ refetchInterval: isLive ? 2000 : false,
+ });
+
+ function isRunLogUnavailable(err: unknown): boolean {
+ return err instanceof ApiError && err.status === 404;
+ }
+
+ function appendLogContent(content: string, finalize = false) {
+ if (!content && !finalize) return;
+ const combined = `${pendingLogLineRef.current}${content}`;
+ const split = combined.split("\n");
+ pendingLogLineRef.current = split.pop() ?? "";
+ if (finalize && pendingLogLineRef.current) {
+ split.push(pendingLogLineRef.current);
+ pendingLogLineRef.current = "";
+ }
+
+ const parsed: Array<{ ts: string; stream: "stdout" | "stderr" | "system"; chunk: string }> = [];
+ for (const line of split) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ const raw = JSON.parse(trimmed) as { ts?: unknown; stream?: unknown; chunk?: unknown };
+ const stream =
+ raw.stream === "stderr" || raw.stream === "system" ? raw.stream : "stdout";
+ const chunk = typeof raw.chunk === "string" ? raw.chunk : "";
+ const ts = typeof raw.ts === "string" ? raw.ts : new Date().toISOString();
+ if (!chunk) continue;
+ parsed.push({ ts, stream, chunk });
+ } catch {
+ // ignore malformed lines
+ }
+ }
+
+ if (parsed.length > 0) {
+ // Live runs stream forever, so cap the retained tail. Terminated runs are
+ // paginated by the user via "Load more log" and keep their full history.
+ setLogLines((prev) =>
+ isLive ? appendCapped(prev, parsed, MAX_LIVE_LOG_LINES) : [...prev, ...parsed],
+ );
+ }
+ }
+
+ // Fetch events
+ const { data: initialEvents } = useQuery({
+ queryKey: ["run-events", run.id],
+ queryFn: () => heartbeatsApi.events(run.id, 0, 200),
+ });
+
+ useEffect(() => {
+ if (initialEvents) {
+ setEvents(initialEvents);
+ setLoading(false);
+ }
+ }, [initialEvents]);
+
+ const getScrollContainer = useCallback((): ScrollContainer => {
+ if (scrollContainerRef.current) return scrollContainerRef.current;
+ const container = findScrollContainer(logEndRef.current);
+ scrollContainerRef.current = container;
+ return container;
+ }, []);
+
+ const updateFollowingState = useCallback(() => {
+ const container = getScrollContainer();
+ const metrics = readScrollMetrics(container);
+ lastMetricsRef.current = metrics;
+ const nearBottom = metrics.distanceFromBottom <= LIVE_SCROLL_BOTTOM_TOLERANCE_PX;
+ isFollowingRef.current = nearBottom;
+ setIsFollowing((prev) => (prev === nearBottom ? prev : nearBottom));
+ }, [getScrollContainer]);
+
+ useEffect(() => {
+ scrollContainerRef.current = null;
+ lastMetricsRef.current = {
+ scrollHeight: 0,
+ distanceFromBottom: Number.POSITIVE_INFINITY,
+ };
+
+ if (!isLive) {
+ isFollowingRef.current = false;
+ setIsFollowing(false);
+ return;
+ }
+
+ updateFollowingState();
+ }, [isLive, run.id, updateFollowingState]);
+
+ useEffect(() => {
+ if (!isLive) return;
+ const container = getScrollContainer();
+ updateFollowingState();
+
+ if (container === window) {
+ window.addEventListener("scroll", updateFollowingState, { passive: true });
+ } else {
+ container.addEventListener("scroll", updateFollowingState, { passive: true });
+ }
+ window.addEventListener("resize", updateFollowingState);
+ return () => {
+ if (container === window) {
+ window.removeEventListener("scroll", updateFollowingState);
+ } else {
+ container.removeEventListener("scroll", updateFollowingState);
+ }
+ window.removeEventListener("resize", updateFollowingState);
+ };
+ }, [isLive, run.id, getScrollContainer, updateFollowingState]);
+
+ // Auto-scroll only for live runs when following
+ useEffect(() => {
+ if (!isLive || !isFollowingRef.current) return;
+
+ const container = getScrollContainer();
+ const previous = lastMetricsRef.current;
+ const current = readScrollMetrics(container);
+ const growth = Math.max(0, current.scrollHeight - previous.scrollHeight);
+ const expectedDistance = previous.distanceFromBottom + growth;
+ const movedAwayBy = current.distanceFromBottom - expectedDistance;
+
+ // If user moved away from bottom between updates, release auto-follow immediately.
+ if (movedAwayBy > LIVE_SCROLL_BOTTOM_TOLERANCE_PX) {
+ isFollowingRef.current = false;
+ setIsFollowing(false);
+ lastMetricsRef.current = current;
+ return;
+ }
+
+ scrollToContainerBottom(container, "auto");
+ const after = readScrollMetrics(container);
+ lastMetricsRef.current = after;
+ if (!isFollowingRef.current) {
+ isFollowingRef.current = true;
+ }
+ setIsFollowing((prev) => (prev ? prev : true));
+ }, [events.length, logLines.length, isLive, getScrollContainer]);
+
+ // Fetch persisted shell log
+ useEffect(() => {
+ let cancelled = false;
+ pendingLogLineRef.current = "";
+ seenProgressLogLineKeysRef.current = new Set();
+ setLogLines([]);
+ setLogOffset(0);
+ setHasMoreLog(false);
+ setLoadingMoreLog(false);
+ setLogError(null);
+
+ if (!run.logRef && !shouldPollShellLog) {
+ setLogLoading(false);
+ return () => {
+ cancelled = true;
+ };
+ }
+
+ setLogLoading(true);
+ const load = async () => {
+ try {
+ const result = await heartbeatsApi.log(run.id, 0, RUN_LOG_PAGE_BYTES);
+ if (cancelled) return;
+ appendLogContent(result.content, result.nextOffset === undefined);
+ const next = result.nextOffset ?? result.content.length;
+ setLogOffset(next);
+ setHasMoreLog(!shouldPollShellLog && result.nextOffset !== undefined);
+ } catch (err) {
+ if (!cancelled) {
+ if (shouldPollShellLog && isRunLogUnavailable(err)) {
+ setLogLoading(false);
+ return;
+ }
+ setLogError(err instanceof Error ? err.message : "Failed to load run log");
+ }
+ } finally {
+ if (!cancelled) setLogLoading(false);
+ }
+ };
+
+ void load();
+ return () => {
+ cancelled = true;
+ };
+ }, [run.id, run.logRef, run.logBytes, shouldPollShellLog]);
+
+ async function loadMorePersistedLog() {
+ if (loadingMoreLog || !hasMoreLog) return;
+ setLoadingMoreLog(true);
+ setLogError(null);
+ try {
+ const result = await heartbeatsApi.log(run.id, logOffset, RUN_LOG_PAGE_BYTES);
+ appendLogContent(result.content, result.nextOffset === undefined);
+ const next = result.nextOffset ?? logOffset + result.content.length;
+ setLogOffset(next);
+ setHasMoreLog(result.nextOffset !== undefined);
+ } catch (err) {
+ setLogError(err instanceof Error ? err.message : "Failed to load more run log");
+ } finally {
+ setLoadingMoreLog(false);
+ }
+ }
+
+ // Poll for live updates
+ useEffect(() => {
+ if (!isLive || isStreamingConnected) return;
+ const interval = setInterval(async () => {
+ const maxSeq = events.length > 0 ? Math.max(...events.map((e) => e.seq)) : 0;
+ try {
+ const newEvents = await heartbeatsApi.events(run.id, maxSeq, 100);
+ if (newEvents.length > 0) {
+ setEvents((prev) => appendCapped(prev, newEvents, MAX_LIVE_EVENTS));
+ }
+ } catch {
+ // ignore polling errors
+ }
+ }, 2000);
+ return () => clearInterval(interval);
+ }, [run.id, isLive, isStreamingConnected, events]);
+
+ // Poll shell log for running runs
+ useEffect(() => {
+ if (!shouldPollShellLog || isStreamingConnected) return;
+ const interval = setInterval(async () => {
+ try {
+ const result = await heartbeatsApi.log(run.id, logOffset, 256_000);
+ if (result.content) {
+ appendLogContent(result.content, result.nextOffset === undefined);
+ }
+ if (result.nextOffset !== undefined) {
+ setLogOffset(result.nextOffset);
+ } else if (result.content.length > 0) {
+ setLogOffset((prev) => prev + result.content.length);
+ }
+ } catch (err) {
+ if (isRunLogUnavailable(err)) return;
+ // ignore polling errors
+ }
+ }, 2000);
+ return () => clearInterval(interval);
+ }, [run.id, shouldPollShellLog, isStreamingConnected, logOffset]);
+
+ // Stream live updates from websocket (primary path for running runs).
+ useEffect(() => {
+ if (!isLive) return;
+
+ let closed = false;
+ let reconnectTimer: number | null = null;
+ let socket: WebSocket | null = null;
+
+ const scheduleReconnect = () => {
+ if (closed) return;
+ reconnectTimer = window.setTimeout(connect, 1500);
+ };
+
+ const connect = () => {
+ if (closed) return;
+ const url = buildSameOriginWebSocketUrl(
+ `/api/companies/${encodeURIComponent(run.companyId)}/events/ws`,
+ );
+ socket = new WebSocket(url);
+
+ socket.onopen = () => {
+ setIsStreamingConnected(true);
+ };
+
+ socket.onmessage = (message) => {
+ const rawMessage = typeof message.data === "string" ? message.data : "";
+ if (!rawMessage) return;
+
+ let event: LiveEvent;
+ try {
+ event = JSON.parse(rawMessage) as LiveEvent;
+ } catch {
+ return;
+ }
+
+ if (event.companyId !== run.companyId) return;
+ const payload = asRecord(event.payload);
+ const eventRunId = asNonEmptyString(payload?.runId);
+ if (!payload || eventRunId !== run.id) return;
+
+ if (event.type === "heartbeat.run.log") {
+ const chunk = typeof payload.chunk === "string" ? payload.chunk : "";
+ if (!chunk) return;
+ const streamRaw = asNonEmptyString(payload.stream);
+ const stream = streamRaw === "stderr" || streamRaw === "system" ? streamRaw : "stdout";
+ const ts = asNonEmptyString((payload as Record<string, unknown>).ts) ?? event.createdAt;
+ setLogLines((prev) => appendCapped(prev, [{ ts, stream, chunk }], MAX_LIVE_LOG_LINES));
+ return;
+ }
+
+ if (event.type === "heartbeat.run.progress") {
+ const line = buildHeartbeatProgressLogLine(payload, event.createdAt);
+ if (!line) return;
+ const key = heartbeatProgressLogLineKey(line);
+ if (seenProgressLogLineKeysRef.current.has(key)) return;
+ seenProgressLogLineKeysRef.current.add(key);
+ setLogLines((prev) => appendCapped(prev, [line], MAX_LIVE_LOG_LINES));
+ return;
+ }
+
+ if (event.type !== "heartbeat.run.event") return;
+
+ const seq = typeof payload.seq === "number" ? payload.seq : null;
+ if (seq === null || !Number.isFinite(seq)) return;
+
+ const streamRaw = asNonEmptyString(payload.stream);
+ const stream =
+ streamRaw === "stdout" || streamRaw === "stderr" || streamRaw === "system"
+ ? streamRaw
+ : null;
+ const levelRaw = asNonEmptyString(payload.level);
+ const level =
+ levelRaw === "info" || levelRaw === "warn" || levelRaw === "error"
+ ? levelRaw
+ : null;
+
+ const liveEvent: HeartbeatRunEvent = {
+ id: seq,
+ companyId: run.companyId,
+ runId: run.id,
+ agentId: run.agentId,
+ seq,
+ eventType: asNonEmptyString(payload.eventType) ?? "event",
+ stream,
+ level,
+ color: asNonEmptyString(payload.color),
+ message: asNonEmptyString(payload.message),
+ payload: asRecord(payload.payload),
+ createdAt: new Date(event.createdAt),
+ };
+
+ setEvents((prev) => {
+ if (prev.some((existing) => existing.seq === seq)) return prev;
+ return appendCapped(prev, [liveEvent], MAX_LIVE_EVENTS);
+ });
+ };
+
+ socket.onerror = () => {
+ socket?.close();
+ };
+
+ socket.onclose = () => {
+ setIsStreamingConnected(false);
+ scheduleReconnect();
+ };
+ };
+
+ connect();
+
+ return () => {
+ closed = true;
+ setIsStreamingConnected(false);
+ if (reconnectTimer !== null) window.clearTimeout(reconnectTimer);
+ if (socket) {
+ socket.onopen = null;
+ socket.onmessage = null;
+ socket.onerror = null;
+ socket.onclose = null;
+ socket.close(1000, "run_detail_unmount");
+ }
+ };
+ }, [isLive, run.companyId, run.id, run.agentId]);
+
+ const censorUsernameInLogs = useQuery({
+ queryKey: queryKeys.instance.generalSettings,
+ queryFn: () => instanceSettingsApi.getGeneral(),
+ }).data?.censorUsernameInLogs === true;
+
+ const adapterInvokePayload = useMemo(() => {
+ const evt = events.find((e) => e.eventType === "adapter.invoke");
+ return redactPathValue(asRecord(evt?.payload ?? null), censorUsernameInLogs);
+ }, [censorUsernameInLogs, events]);
+
+ // NOTE: adapter is NOT memoized because external adapters replace their
+ // parseStdoutLine asynchronously after dynamic parser loading. Memoizing
+ // on adapterType alone would stale the transcript with the fallback parser.
+ // We subscribe to adapter registry changes to force transcript recomputation.
+ const [parserTick, setParserTick] = useState(0);
+ const adapter = getUIAdapter(adapterType);
+
+ useEffect(() => {
+ return onAdapterChange(() => setParserTick((t) => t + 1));
+ }, []);
+
+ const transcript = useMemo(
+ () => buildTranscript(logLines, adapter, { censorUsernameInLogs }),
+ [adapter, censorUsernameInLogs, logLines, parserTick],
+ );
+ const toolDecisionLookup = useQuery({
+ queryKey: queryKeys.tools.runDecisions(run.companyId, run.id),
+ queryFn: () => toolsApi.getRunDecisionLookup(run.companyId, run.id),
+ enabled: Boolean(run.companyId && run.id),
+ refetchInterval: isLive ? 3000 : false,
+ staleTime: isLive ? 1000 : 30_000,
+ });
+
+ useEffect(() => {
+ setTranscriptMode("nice");
+ }, [run.id]);
+
+ if (loading && logLoading) {
+ return <p className="text-xs text-muted-foreground">Loading run logs...</p>;
+ }
+
+ if (events.length === 0 && logLines.length === 0 && !logError) {
+ return <p className="text-xs text-muted-foreground">No log events.</p>;
+ }
+
+ const levelColors: Record<string, string> = {
+ info: "text-foreground",
+ warn: "text-yellow-600 dark:text-yellow-400",
+ error: "text-red-600 dark:text-red-400",
+ };
+
+ const streamColors: Record<string, string> = {
+ stdout: "text-foreground",
+ stderr: "text-red-600 dark:text-red-300",
+ system: "text-blue-600 dark:text-blue-300",
+ };
+
+ return (
+ <div className="space-y-3">
+ <WorkspaceOperationsSection
+ operations={workspaceOperations}
+ censorUsernameInLogs={censorUsernameInLogs}
+ />
+ {adapterInvokePayload && (
+ <RunInvocationCard payload={adapterInvokePayload} censorUsernameInLogs={censorUsernameInLogs} />
+ )}
+
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-muted-foreground">
+ Transcript ({transcript.length})
+ </span>
+ <div className="flex items-center gap-2">
+ <div className="inline-flex rounded-lg border border-border/70 bg-background/70 p-0.5">
+ {(["nice", "raw"] as const).map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ className={cn(
+ "rounded-md px-2.5 py-1 text-(length:--text-micro) font-medium capitalize transition-colors",
+ transcriptMode === mode
+ ? "bg-accent text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ onClick={() => setTranscriptMode(mode)}
+ >
+ {mode}
+ </button>
+ ))}
+ </div>
+ {isLive && !isFollowing && (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => {
+ const container = getScrollContainer();
+ isFollowingRef.current = true;
+ setIsFollowing(true);
+ scrollToContainerBottom(container, "auto");
+ lastMetricsRef.current = readScrollMetrics(container);
+ }}
+ >
+ Jump to live
+ </Button>
+ )}
+ {isLive && (
+ <span className="flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400">
+ <span className="relative flex h-2 w-2">
+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500" />
+ </span>
+ Live
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="max-h-(--sz-38rem) overflow-y-auto rounded-2xl border border-border/70 bg-background/40 p-3 sm:p-4">
+ <RunTranscriptView
+ entries={transcript}
+ toolDecisions={toolDecisionLookup.data?.decisions ?? []}
+ mode={transcriptMode}
+ streaming={isLive}
+ limit={isLive ? LIVE_TRANSCRIPT_RENDER_LIMIT : undefined}
+ emptyMessage={run.logRef ? "Waiting for transcript..." : "No persisted transcript for this run."}
+ />
+ {hasMoreLog && (
+ <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-border/60 pt-3">
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ onClick={loadMorePersistedLog}
+ disabled={loadingMoreLog}
+ >
+ {loadingMoreLog ? "Loading..." : "Load more log"}
+ </Button>
+ <span className="text-xs text-muted-foreground">
+ Showing the first {Math.round(logOffset / 1024).toLocaleString("en-US")} KB
+ {typeof run.logBytes === "number" && run.logBytes > 0
+ ? ` of ${Math.round(run.logBytes / 1024).toLocaleString("en-US")} KB`
+ : ""}
+ </span>
+ </div>
+ )}
+ {logError && (
+ <div className="mt-3 rounded-xl border border-red-500/20 bg-red-500/[0.06] px-3 py-2 text-xs text-red-700 dark:text-red-300">
+ {logError}
+ </div>
+ )}
+ <div ref={logEndRef} />
+ </div>
+
+ {(run.status === "failed" || run.status === "timed_out") && (
+ <div className="rounded-lg border border-red-300 dark:border-red-500/30 bg-red-50 dark:bg-red-950/20 p-3 space-y-2">
+ <div className="text-xs font-medium text-red-700 dark:text-red-300">Failure details</div>
+ {run.error && (
+ <div className="text-xs text-red-600 dark:text-red-200">
+ <span className="text-red-700 dark:text-red-300">Error: </span>
+ {redactPathText(run.error, censorUsernameInLogs)}
+ </div>
+ )}
+ {run.stderrExcerpt && run.stderrExcerpt.trim() && (
+ <div>
+ <div className="text-xs text-red-700 dark:text-red-300 mb-1">stderr excerpt</div>
+ <pre className="bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100">
+ {redactPathText(run.stderrExcerpt, censorUsernameInLogs)}
+ </pre>
+ </div>
+ )}
+ {run.resultJson && (
+ <div>
+ <div className="text-xs text-red-700 dark:text-red-300 mb-1">adapter result JSON</div>
+ <pre className="bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100">
+ {JSON.stringify(redactPathValue(run.resultJson, censorUsernameInLogs), null, 2)}
+ </pre>
+ </div>
+ )}
+ {run.stdoutExcerpt && run.stdoutExcerpt.trim() && !run.resultJson && (
+ <div>
+ <div className="text-xs text-red-700 dark:text-red-300 mb-1">stdout excerpt</div>
+ <pre className="bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100">
+ {redactPathText(run.stdoutExcerpt, censorUsernameInLogs)}
+ </pre>
+ </div>
+ )}
+ </div>
+ )}
+
+ {events.length > 0 && (
+ <div>
+ <div className="mb-2 text-xs font-medium text-muted-foreground">Events ({events.length})</div>
+ <div className="bg-neutral-100 dark:bg-neutral-950 rounded-lg p-3 font-mono text-xs space-y-0.5">
+ {events.map((evt) => {
+ const color = evt.color
+ ?? (evt.level ? levelColors[evt.level] : null)
+ ?? (evt.stream ? streamColors[evt.stream] : null)
+ ?? "text-foreground";
+
+ return (
+ <div key={evt.id} className="flex gap-2">
+ <span className="text-neutral-400 dark:text-neutral-600 shrink-0 select-none w-16">
+ {new Date(evt.createdAt).toLocaleTimeString("en-US", { hour12: false })}
+ </span>
+ <span className={cn("shrink-0 w-14", evt.stream ? (streamColors[evt.stream] ?? "text-neutral-500") : "text-neutral-500")}>
+ {evt.stream ? `[${evt.stream}]` : ""}
+ </span>
+ <span className={cn("break-all", color)}>
+ {evt.message
+ ? redactPathText(evt.message, censorUsernameInLogs)
+ : evt.payload
+ ? JSON.stringify(redactPathValue(evt.payload, censorUsernameInLogs))
+ : ""}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---- Keys Tab ---- */
+
+function KeysTab({ agentId, companyId }: { agentId: string; companyId?: string }) {
+ const queryClient = useQueryClient();
+ const { pushToast } = useToastActions();
+ const [newKeyName, setNewKeyName] = useState("");
+ const [newToken, setNewToken] = useState<string | null>(null);
+ const [tokenVisible, setTokenVisible] = useState(false);
+ const [copied, setCopied] = useState(false);
+
+ const { data: keys, isLoading } = useQuery({
+ queryKey: queryKeys.agents.keys(agentId),
+ queryFn: () => agentsApi.listKeys(agentId, companyId),
+ });
+
+ const createKey = useMutation({
+ mutationFn: () => agentsApi.createKey(agentId, newKeyName.trim() || "Default", companyId),
+ onSuccess: (data) => {
+ setNewToken(data.token);
+ setTokenVisible(true);
+ setNewKeyName("");
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.keys(agentId) });
+ },
+ });
+
+ const revokeKey = useMutation({
+ mutationFn: (keyId: string) => agentsApi.revokeKey(agentId, keyId, companyId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.keys(agentId) });
+ },
+ });
+
+ function copyToken() {
+ if (!newToken) return;
+ void copyTextToClipboard(newToken)
+ .then(() => {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ })
+ .catch(() => {
+ pushToast({ title: "Copy failed", body: "Clipboard access is unavailable.", tone: "error" });
+ });
+ }
+
+ const activeKeys = (keys ?? []).filter((k: AgentKey) => !k.revokedAt);
+ const revokedKeys = (keys ?? []).filter((k: AgentKey) => k.revokedAt);
+
+ return (
+ <div className="space-y-6">
+ {/* New token banner */}
+ {newToken && (
+ <div className="border border-yellow-300 dark:border-yellow-600/40 bg-yellow-50 dark:bg-yellow-500/5 rounded-lg p-4 space-y-2">
+ <p className="text-sm font-medium text-yellow-700 dark:text-yellow-400">
+ API key created — copy it now, it will not be shown again.
+ </p>
+ <div className="flex items-center gap-2">
+ <code className="flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate">
+ {tokenVisible ? newToken : newToken.replace(/./g, "•")}
+ </code>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setTokenVisible((v) => !v)}
+ title={tokenVisible ? "Hide" : "Show"}
+ >
+ {tokenVisible ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={copyToken}
+ title="Copy"
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </Button>
+ {copied && <span className="text-xs text-green-400">Copied!</span>}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground text-xs"
+ onClick={() => setNewToken(null)}
+ >
+ Dismiss
+ </Button>
+ </div>
+ )}
+
+ {/* Create new key */}
+ <div className="border border-border rounded-lg p-4 space-y-3">
+ <h3 className="text-xs font-medium text-muted-foreground flex items-center gap-2">
+ <Key className="h-3.5 w-3.5" />
+ Create API Key
+ </h3>
+ <p className="text-xs text-muted-foreground">
+ API keys allow this agent to authenticate calls to the Paperclip server.
+ </p>
+ <div className="flex items-center gap-2">
+ <Input
+ placeholder="Key name (e.g. production)"
+ value={newKeyName}
+ onChange={(e) => setNewKeyName(e.target.value)}
+ className="h-8 text-sm"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") createKey.mutate();
+ }}
+ />
+ <Button
+ size="sm"
+ onClick={() => createKey.mutate()}
+ disabled={createKey.isPending}
+ >
+ <Plus className="h-3.5 w-3.5 mr-1" />
+ Create
+ </Button>
+ </div>
+ </div>
+
+ {/* Active keys */}
+ {isLoading && <p className="text-sm text-muted-foreground">Loading keys...</p>}
+
+ {!isLoading && activeKeys.length === 0 && !newToken && (
+ <p className="text-sm text-muted-foreground">No active API keys.</p>
+ )}
+
+ {activeKeys.length > 0 && (
+ <div>
+ <h3 className="text-xs font-medium text-muted-foreground mb-2">
+ Active Keys
+ </h3>
+ <div className="border border-border rounded-lg divide-y divide-border">
+ {activeKeys.map((key: AgentKey) => (
+ <div key={key.id} className="flex items-center justify-between px-4 py-2.5">
+ <div>
+ <span className="text-sm font-medium">{key.name}</span>
+ <span className="text-xs text-muted-foreground ml-3">
+ Created {formatDate(key.createdAt)}
+ </span>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive hover:text-destructive text-xs"
+ onClick={() => revokeKey.mutate(key.id)}
+ disabled={revokeKey.isPending}
+ >
+ Revoke
+ </Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Revoked keys */}
+ {revokedKeys.length > 0 && (
+ <div>
+ <h3 className="text-xs font-medium text-muted-foreground mb-2">
+ Revoked Keys
+ </h3>
+ <div className="border border-border rounded-lg divide-y divide-border opacity-50">
+ {revokedKeys.map((key: AgentKey) => (
+ <div key={key.id} className="flex items-center justify-between px-4 py-2.5">
+ <div>
+ <span className="text-sm line-through">{key.name}</span>
+ <span className="text-xs text-muted-foreground ml-3">
+ Revoked {key.revokedAt ? formatDate(key.revokedAt) : ""}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx
index 54c0dd3bbd..e439bf62c5 100644
--- a/ui/src/pages/AgentDetail.tsx
+++ b/ui/src/pages/AgentDetail.tsx
@@ -9,12 +9,9 @@ import {
} from "../api/agents";
import { builtInAgentsApi, type BuiltInManagedResourceKind } from "../api/builtInAgents";
import { companySkillsApi } from "../api/companySkills";
-import { budgetsApi } from "../api/budgets";
import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
import { ApiError } from "../api/client";
-import { ChartCard, RunActivityChart, PriorityChart, IssueStatusChart, SuccessRateChart } from "../components/ActivityCharts";
-import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
import { activityApi } from "../api/activity";
import { accessApi } from "../api/access";
import { issuesApi } from "../api/issues";
@@ -28,10 +25,10 @@ import { queryKeys } from "../lib/queryKeys";
import { copyTextToClipboard } from "../lib/clipboard";
import { AgentSkillsTab } from "./agent-skills/AgentSkillsTab";
import { AgentConfigForm } from "../components/AgentConfigForm";
-import { PageTabBar } from "../components/PageTabBar";
import { adapterLabels, roleLabels, help } from "../components/agent-config-primitives";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { useAdapterCapabilities } from "@/adapters/use-adapter-capabilities";
+import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import { redactCommandText as redactCommandSecretText } from "@paperclipai/adapter-utils";
import { MarkdownEditor } from "../components/MarkdownEditor";
import { assetsApi } from "../api/assets";
@@ -40,18 +37,16 @@ import { getUIAdapter, buildTranscript, onAdapterChange } from "../adapters";
import { StatusBadge } from "../components/StatusBadge";
import { MarkdownBody } from "../components/MarkdownBody";
import { CopyText } from "../components/CopyText";
-import { EntityRow } from "../components/EntityRow";
+import { IssueRow } from "../components/IssueRow";
import { StatusGlyph } from "../components/StatusGlyph";
import { MembershipAction } from "../components/MembershipAction";
import { StarToggle } from "../components/StarToggle";
import { Identity } from "../components/Identity";
-import { AuditFeed } from "./audit/AuditFeed";
import { PageSkeleton } from "../components/PageSkeleton";
import { AgentActionButtons } from "../components/AgentActionButtons";
import { InlineBanner } from "../components/InlineBanner";
import { BuiltInBundlePanel } from "../components/BuiltInBundlePanel";
import { ConfigureBuiltInAgentModal } from "../components/ConfigureBuiltInAgentModal";
-import { BudgetPolicyCard } from "../components/BudgetPolicyCard";
import { TrustPresetSection } from "../components/TrustPresetSection";
import { FileTree, buildFileTree } from "../components/FileTree";
import { ScrollToBottom } from "../components/ScrollToBottom";
@@ -59,12 +54,14 @@ import { SourceResolvedFoldCallout } from "../components/SourceResolvedFoldCallo
import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";
import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
import { buildSameOriginWebSocketUrl } from "../lib/websocket-url";
-import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";
+import { formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";
import { cn } from "../lib/utils";
import { describeRunRetryState } from "../lib/runRetryState";
import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
import { Tabs } from "@/components/ui/tabs";
+import { PageTabBar } from "../components/PageTabBar";
+import { AuditFeed } from "./audit/AuditFeed";
+import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
CheckCircle2,
@@ -102,10 +99,10 @@ import {
isUuidLike,
type Agent,
type AgentDetail as AgentDetailRecord,
- type BudgetPolicySummary,
type HeartbeatRun,
type HeartbeatRunEvent,
type AgentRuntimeState,
+ type Issue,
type LiveEvent,
type WorkspaceOperation,
isResponsibleUserDenialCode,
@@ -129,6 +126,14 @@ import {
useResourceMemberships,
} from "../hooks/useResourceMemberships";
import { Badge } from "@/components/ui/badge";
+import {
+ AGENT_DETAIL_NAVIGATION,
+ agentDetailHref,
+ agentLegacyAuditSection,
+ agentScopedAuditHref,
+ parseAgentDetailView,
+ type AgentDetailView,
+} from "./agent-detail-navigation";
const runStatusIcons: Record<string, { icon: typeof CheckCircle2; color: string }> = {
succeeded: { icon: CheckCircle2, color: "text-green-600 dark:text-green-400" },
@@ -281,9 +286,10 @@ function scrollToContainerBottom(container: ScrollContainer, behavior: ScrollBeh
container.scrollTo({ top: container.scrollHeight, behavior });
}
-type AgentDetailView = "dashboard" | "instructions" | "configuration" | "secrets" | "skills" | "tools" | "runs" | "audit" | "budget";
+/** @deprecated Use AGENT_DETAIL_NAVIGATION for contextual navigation. */
+export const AGENT_DETAIL_TABS = AGENT_DETAIL_NAVIGATION.flatMap((section) => section.items);
-export const AGENT_DETAIL_TABS: ReadonlyArray<{ value: AgentDetailView; label: string }> = [
+const LEGACY_AGENT_DETAIL_TABS = [
{ value: "dashboard", label: "Dashboard" },
{ value: "instructions", label: "Instructions" },
{ value: "skills", label: "Skills" },
@@ -293,7 +299,7 @@ export const AGENT_DETAIL_TABS: ReadonlyArray<{ value: AgentDetailView; label: s
{ value: "runs", label: "Runs" },
{ value: "audit", label: "Audit" },
{ value: "budget", label: "Budget" },
-];
+] as const;
export const DISCARD_AGENT_CONFIG_CHANGES_MESSAGE = "Discard unsaved agent configuration changes?";
@@ -329,17 +335,7 @@ export function restoreAgentConfigHistoryEntry(
return true;
}
-export function parseAgentDetailView(value: string | null): AgentDetailView {
- if (value === "instructions" || value === "prompts") return "instructions";
- if (value === "configure" || value === "configuration") return "configuration";
- if (value === "secrets") return "secrets";
- if (value === "skills") return "skills";
- if (value === "tools") return "tools";
- if (value === "budget") return "budget";
- if (value === "audit") return "audit";
- if (value === "runs") return value;
- return "dashboard";
-}
+export { agentDetailHref, agentScopedAuditHref, parseAgentDetailView };
function usageNumber(usage: Record<string, unknown> | null, ...keys: string[]) {
if (!usage) return 0;
@@ -764,12 +760,27 @@ export function AgentDetail() {
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
const navigate = useNavigate();
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const [actionError, setActionError] = useState<string | null>(null);
const [dismissedLeftAgentIds, setDismissedLeftAgentIds] = useState<Set<string>>(() => new Set());
- const activeView = urlRunId ? "runs" as AgentDetailView : parseAgentDetailView(urlTab ?? null);
- const needsDashboardData = activeView === "dashboard";
- const needsRunData = activeView === "runs" || Boolean(urlRunId);
- const shouldLoadHeartbeats = needsDashboardData || needsRunData;
+ const activeView: AgentDetailView = urlRunId ? "run-detail" : parseAgentDetailView(urlTab ?? null);
+ const legacyAuditSection = !urlRunId ? agentLegacyAuditSection(urlTab ?? null) : null;
+ const legacyView = urlRunId
+ ? "runs"
+ : legacyAuditSection === "runs"
+ ? "runs"
+ : legacyAuditSection === "activity"
+ ? "audit"
+ : legacyAuditSection === "costs" || legacyAuditSection === "budgets"
+ ? "budget"
+ : activeView === "overview"
+ ? "dashboard"
+ : activeView === "runtime"
+ ? "configuration"
+ : activeView;
+ const needsOverviewData = activeView === "overview";
+ const needsRunData = activeView === "run-detail";
+ const shouldLoadHeartbeats = needsOverviewData || needsRunData;
const [configDirty, setConfigDirty] = useState(false);
const [configSaving, setConfigSaving] = useState(false);
const saveConfigActionRef = useRef<(() => void) | null>(null);
@@ -788,7 +799,6 @@ export function AgentDetail() {
const prepareAgentNavigation = useCallback(() => {
return confirmAgentConfigNavigation(configDirty);
}, [configDirty]);
-
const { data: agent, isLoading, error } = useQuery<AgentDetailRecord>({
queryKey: [...queryKeys.agents.detail(routeAgentRef), lookupCompanyId ?? null],
queryFn: () => agentsApi.get(routeAgentRef, lookupCompanyId),
@@ -796,6 +806,10 @@ export function AgentDetail() {
});
const resolvedCompanyId = agent?.companyId ?? selectedCompanyId;
const canonicalAgentRef = agent ? agentRouteRef(agent) : routeAgentRef;
+ const handleLegacyTabChange = useCallback((next: string) => {
+ if (!prepareAgentNavigation()) return;
+ navigate(`/agents/${canonicalAgentRef || routeAgentRef}/${next}`);
+ }, [canonicalAgentRef, navigate, prepareAgentNavigation, routeAgentRef]);
const agentLookupRef = agent?.id ?? routeAgentRef;
const resolvedAgentId = agent?.id ?? null;
const { data: boardAccess } = useQuery({
@@ -889,7 +903,7 @@ export function AgentDetail() {
const { data: runtimeState } = useQuery({
queryKey: queryKeys.agents.runtimeState(resolvedAgentId ?? routeAgentRef),
queryFn: () => agentsApi.runtimeState(resolvedAgentId!, resolvedCompanyId ?? undefined),
- enabled: Boolean(resolvedAgentId) && needsDashboardData,
+ enabled: Boolean(resolvedAgentId) && needsOverviewData,
});
const { data: heartbeats } = useQuery({
@@ -901,58 +915,37 @@ export function AgentDetail() {
const { data: allIssues } = useQuery({
queryKey: [...queryKeys.issues.list(resolvedCompanyId!), "participant-agent", resolvedAgentId ?? "__none__"],
queryFn: () => issuesApi.list(resolvedCompanyId!, { participantAgentId: resolvedAgentId! }),
- enabled: !!resolvedCompanyId && !!resolvedAgentId && needsDashboardData,
+ enabled: !!resolvedCompanyId && !!resolvedAgentId && needsOverviewData,
});
const { data: allAgents } = useQuery({
queryKey: queryKeys.agents.list(resolvedCompanyId!),
queryFn: () => agentsApi.list(resolvedCompanyId!),
- enabled: !!resolvedCompanyId && needsDashboardData,
+ enabled: !!resolvedCompanyId && needsOverviewData,
});
- const { data: budgetOverview } = useQuery({
- queryKey: queryKeys.budgets.overview(resolvedCompanyId ?? "__none__"),
- queryFn: () => budgetsApi.overview(resolvedCompanyId!),
- enabled: !!resolvedCompanyId,
- refetchInterval: 30_000,
- staleTime: 5_000,
+ const { data: skillSnapshot } = useQuery({
+ queryKey: queryKeys.agents.skills(resolvedAgentId ?? "__none__"),
+ queryFn: () => agentsApi.skills(resolvedAgentId!, resolvedCompanyId ?? undefined),
+ enabled: Boolean(resolvedCompanyId && resolvedAgentId && needsOverviewData),
});
- const assignedIssues = (allIssues ?? [])
- .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
+ const { data: overviewCompanySkills } = useQuery({
+ queryKey: queryKeys.companySkills.list(resolvedCompanyId ?? "__none__"),
+ queryFn: () => companySkillsApi.list(resolvedCompanyId!),
+ enabled: Boolean(resolvedCompanyId && needsOverviewData),
+ });
+
+ const assignedIssues = useMemo(
+ () => [...(allIssues ?? [])].sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()),
+ [allIssues],
+ );
const reportsToAgent = (allAgents ?? []).find((a) => a.id === agent?.reportsTo);
const directReports = (allAgents ?? []).filter((a) => a.reportsTo === agent?.id && a.status !== "terminated");
- const agentBudgetSummary = useMemo(() => {
- const matched = budgetOverview?.policies.find(
- (policy) => policy.scopeType === "agent" && policy.scopeId === (agent?.id ?? routeAgentRef),
- );
- if (matched) return matched;
- const budgetMonthlyCents = agent?.budgetMonthlyCents ?? 0;
- const spentMonthlyCents = agent?.spentMonthlyCents ?? 0;
- return {
- policyId: "",
- companyId: resolvedCompanyId ?? "",
- scopeType: "agent",
- scopeId: agent?.id ?? routeAgentRef,
- scopeName: agent?.name ?? "Agent",
- metric: "billed_cents",
- windowKind: "calendar_month_utc",
- amount: budgetMonthlyCents,
- observedAmount: spentMonthlyCents,
- remainingAmount: Math.max(0, budgetMonthlyCents - spentMonthlyCents),
- utilizationPercent:
- budgetMonthlyCents > 0 ? Number(((spentMonthlyCents / budgetMonthlyCents) * 100).toFixed(2)) : 0,
- warnPercent: 80,
- hardStopEnabled: true,
- notifyEnabled: true,
- isActive: budgetMonthlyCents > 0,
- status: budgetMonthlyCents > 0 && spentMonthlyCents >= budgetMonthlyCents ? "hard_stop" : "ok",
- paused: agent?.status === "paused",
- pauseReason: agent?.pauseReason ?? null,
- windowStart: new Date(),
- windowEnd: new Date(),
- } satisfies BudgetPolicySummary;
- }, [agent, budgetOverview?.policies, resolvedCompanyId, routeAgentRef]);
+ const overviewSkillNames = useMemo(() => {
+ const namesByKey = new Map((overviewCompanySkills ?? []).map((skill) => [skill.key, skill.name]));
+ return (skillSnapshot?.desiredSkills ?? []).map((key) => namesByKey.get(key) ?? key);
+ }, [overviewCompanySkills, skillSnapshot?.desiredSkills]);
const mobileLiveRun = useMemo(
() => (heartbeats ?? []).find((r) => r.status === "running" || r.status === "queued") ?? null,
[heartbeats],
@@ -966,29 +959,19 @@ export function AgentDetail() {
}
return;
}
- const canonicalTab =
- activeView === "instructions"
- ? "instructions"
- : activeView === "configuration"
- ? "configuration"
- : activeView === "secrets"
- ? "secrets"
- : activeView === "skills"
- ? "skills"
- : activeView === "tools"
- ? "tools"
- : activeView === "runs"
- ? "runs"
- : activeView === "audit"
- ? "audit"
- : activeView === "budget"
- ? "budget"
- : "dashboard";
+ if (!streamlinedUiEnabled) {
+ if (routeAgentRef !== canonicalAgentRef) {
+ navigate(`/agents/${canonicalAgentRef}/${urlTab ?? "dashboard"}`, { replace: true });
+ }
+ return;
+ }
+ if (legacyAuditSection) return;
+ const canonicalTab = activeView === "run-detail" ? "overview" : activeView;
if (routeAgentRef !== canonicalAgentRef || urlTab !== canonicalTab) {
- navigate(`/agents/${canonicalAgentRef}/${canonicalTab}`, { replace: true });
+ navigate(agentDetailHref(canonicalAgentRef, canonicalTab), { replace: true });
return;
}
- }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, navigate]);
+ }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate, streamlinedUiEnabled]);
useEffect(() => {
if (!agent?.companyId || agent.companyId === selectedCompanyId) return;
@@ -1023,24 +1006,6 @@ export function AgentDetail() {
},
});
- const budgetMutation = useMutation({
- mutationFn: (amount: number) =>
- budgetsApi.upsertPolicy(resolvedCompanyId!, {
- scopeType: "agent",
- scopeId: agent?.id ?? routeAgentRef,
- amount,
- windowKind: "calendar_month_utc",
- }),
- onSuccess: () => {
- if (!resolvedCompanyId) return;
- queryClient.invalidateQueries({ queryKey: queryKeys.budgets.overview(resolvedCompanyId) });
- queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(routeAgentRef) });
- queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentLookupRef) });
- queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(resolvedCompanyId) });
- queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(resolvedCompanyId) });
- },
- });
-
const updateIcon = useMutation({
mutationFn: (icon: string) => agentsApi.update(agentLookupRef, { icon }, resolvedCompanyId ?? undefined),
onSuccess: () => {
@@ -1073,29 +1038,18 @@ export function AgentDetail() {
{ label: "Agents", href: "/agents" },
];
const agentName = agent?.name ?? routeAgentRef ?? "Agent";
- if (activeView === "dashboard" && !urlRunId) {
+ if (activeView === "overview" && !urlRunId) {
crumbs.push({ label: agentName });
} else {
- crumbs.push({ label: agentName, href: `/agents/${canonicalAgentRef}/dashboard` });
+ crumbs.push({ label: agentName, href: agentDetailHref(canonicalAgentRef) });
if (urlRunId) {
- crumbs.push({ label: "Runs", href: `/agents/${canonicalAgentRef}/runs` });
+ crumbs.push({ label: "Runs", href: agent?.id ? agentScopedAuditHref(agent.id, "runs") : undefined });
crumbs.push({ label: `Run ${urlRunId.slice(0, 8)}` });
- } else if (activeView === "instructions") {
- crumbs.push({ label: "Instructions" });
- } else if (activeView === "configuration") {
- crumbs.push({ label: "Configuration" });
- } else if (activeView === "secrets") {
- crumbs.push({ label: "Secrets" });
- // } else if (activeView === "skills") { // TODO: bring back later
- // crumbs.push({ label: "Skills" });
- } else if (activeView === "tools") {
- crumbs.push({ label: "Tools" });
- } else if (activeView === "runs") {
- crumbs.push({ label: "Runs" });
- } else if (activeView === "budget") {
- crumbs.push({ label: "Budget" });
} else {
- crumbs.push({ label: "Dashboard" });
+ const item = AGENT_DETAIL_NAVIGATION
+ .flatMap((section) => section.items)
+ .find((candidate) => candidate.value === activeView);
+ crumbs.push({ label: item?.label ?? "Overview" });
}
}
setBreadcrumbs(crumbs);
@@ -1195,14 +1149,17 @@ export function AgentDetail() {
if (isLoading) return <PageSkeleton variant="detail" />;
if (error) return <p className="text-sm text-destructive">{error.message}</p>;
if (!agent) return null;
+ if (streamlinedUiEnabled && !urlRunId && legacyAuditSection) {
+ return <Navigate to={agentScopedAuditHref(agent.id, legacyAuditSection)} replace />;
+ }
if (!urlRunId && !urlTab) {
- return <Navigate to={`/agents/${canonicalAgentRef}/dashboard`} replace />;
+ return <Navigate to={streamlinedUiEnabled ? agentDetailHref(canonicalAgentRef) : `/agents/${canonicalAgentRef}/dashboard`} replace />;
}
const isPendingApproval = agent.status === "pending_approval";
const hasInvalidOrgChain = agent.orgChainHealth?.status === "invalid_org_chain";
const pausedEscalationWarning = !hasInvalidOrgChain ? agent.orgChainHealth?.escalationWarning ?? null : null;
const showConfigActionBar = (
- activeView === "configuration" || activeView === "instructions" || activeView === "secrets"
+ activeView === "runtime" || activeView === "instructions" || activeView === "secrets"
) && (configDirty || configSaving);
const showLeftAgentNotice = agentMembershipState === "left" && !dismissedLeftAgentIds.has(agent.id);
const agentMembershipPending =
@@ -1213,11 +1170,6 @@ export function AgentDetail() {
const agentStarPending = agentMembershipPending && membershipMutation.variables?.starred !== undefined;
const agentJoinLeavePending = agentMembershipPending && membershipMutation.variables?.starred === undefined;
- function handleAgentTabChange(value: string) {
- if (value === activeView || !prepareAgentNavigation()) return;
- navigate(`/agents/${canonicalAgentRef}/${value}`);
- }
-
return (
<div className={cn("space-y-6", isMobile && showConfigActionBar && "pb-24")}>
{showLeftAgentNotice ? (
@@ -1296,7 +1248,7 @@ export function AgentDetail() {
</button>
</AgentIconPicker>
<div className="min-w-0">
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center justify-end gap-2">
<h2 className="text-2xl font-bold truncate">{agent.name}</h2>
</div>
<p className="text-sm text-muted-foreground truncate">
@@ -1411,18 +1363,15 @@ export function AgentDetail() {
/>
)}
- {!urlRunId && (
- <Tabs
- value={activeView}
- onValueChange={handleAgentTabChange}
- >
+ {!streamlinedUiEnabled && !urlRunId ? (
+ <Tabs value={legacyView} onValueChange={handleLegacyTabChange}>
<PageTabBar
- items={AGENT_DETAIL_TABS}
- value={activeView}
- onValueChange={handleAgentTabChange}
+ items={LEGACY_AGENT_DETAIL_TABS}
+ value={legacyView}
+ onValueChange={handleLegacyTabChange}
/>
</Tabs>
- )}
+ ) : null}
{actionError && <p className="text-sm text-destructive">{actionError}</p>}
{isPendingApproval && (
@@ -1490,13 +1439,15 @@ export function AgentDetail() {
)}
{/* View content */}
- {activeView === "dashboard" && (
+ {activeView === "overview" && (streamlinedUiEnabled || !legacyAuditSection) && (
<AgentOverview
agent={agent}
runs={heartbeats ?? []}
assignedIssues={assignedIssues}
runtimeState={runtimeState}
- agentId={agent.id}
+ reportsToAgent={reportsToAgent}
+ directReportCount={directReports.length}
+ skillNames={overviewSkillNames}
agentRouteId={canonicalAgentRef}
/>
)}
@@ -1512,18 +1463,22 @@ export function AgentDetail() {
/>
)}
- {activeView === "configuration" && (
- <AgentConfigurePage
- agent={agent}
- agentId={agent.id}
- companyId={resolvedCompanyId ?? undefined}
- onDirtyChange={setConfigDirty}
- onSaveActionChange={setSaveConfigAction}
- onCancelActionChange={setCancelConfigAction}
- onSavingChange={setConfigSaving}
- updatePermissions={updatePermissions}
- canConfigureProviderTrace={canUseProviderTrace}
- />
+ {activeView === "runtime" && (
+ <div className="max-w-3xl">
+ <ConfigurationTab
+ agent={agent}
+ companyId={resolvedCompanyId ?? undefined}
+ onDirtyChange={setConfigDirty}
+ onSaveActionChange={setSaveConfigAction}
+ onCancelActionChange={setCancelConfigAction}
+ onSavingChange={setConfigSaving}
+ updatePermissions={updatePermissions}
+ canConfigureProviderTrace={canUseProviderTrace}
+ content="runtime"
+ hidePromptTemplate
+ hideInstructionsFile
+ />
+ </div>
)}
{activeView === "secrets" && (
@@ -1552,7 +1507,32 @@ export function AgentDetail() {
<AgentToolsTab agent={agent} companyId={resolvedCompanyId} />
)}
- {activeView === "runs" && (
+ {activeView === "permissions" && (
+ <div className="max-w-3xl">
+ <ConfigurationTab
+ agent={agent}
+ companyId={resolvedCompanyId ?? undefined}
+ onDirtyChange={setConfigDirty}
+ onSaveActionChange={setSaveConfigAction}
+ onCancelActionChange={setCancelConfigAction}
+ onSavingChange={setConfigSaving}
+ updatePermissions={updatePermissions}
+ content="permissions"
+ />
+ </div>
+ )}
+
+ {activeView === "api-keys" && (
+ <div className="max-w-3xl">
+ <KeysTab agentId={agent.id} companyId={resolvedCompanyId ?? undefined} />
+ </div>
+ )}
+
+ {activeView === "revisions" && (
+ <AgentRevisionsTab agent={agent} companyId={resolvedCompanyId ?? undefined} />
+ )}
+
+ {activeView === "run-detail" && (
<RunsTab
runs={heartbeats ?? []}
companyId={resolvedCompanyId!}
@@ -1564,18 +1544,31 @@ export function AgentDetail() {
/>
)}
- {activeView === "audit" && resolvedCompanyId ? (
- <AuditFeed companyId={resolvedCompanyId} lockedAgentId={agent.id} hideHeader />
+ {!streamlinedUiEnabled && legacyAuditSection === "runs" && (
+ <RunsTab
+ runs={heartbeats ?? []}
+ companyId={resolvedCompanyId!}
+ agentId={agent.id}
+ agentRouteId={canonicalAgentRef}
+ selectedRunId={null}
+ adapterType={agent.adapterType}
+ adapterConfig={agent.adapterConfig}
+ />
+ )}
+
+ {!streamlinedUiEnabled && legacyAuditSection === "activity" && resolvedCompanyId ? (
+ <AuditFeed companyId={resolvedCompanyId} lockedAgentId={agent.id} />
) : null}
- {activeView === "budget" && resolvedCompanyId ? (
- <div className="max-w-3xl">
- <BudgetPolicyCard
- summary={agentBudgetSummary}
- isSaving={budgetMutation.isPending}
- onSave={(amount) => budgetMutation.mutate(amount)}
- variant="plain"
- />
+ {!streamlinedUiEnabled && (legacyAuditSection === "costs" || legacyAuditSection === "budgets") ? (
+ <div className="space-y-3">
+ <h3 className="text-lg font-semibold">Agent budget</h3>
+ <p className="text-sm text-muted-foreground">
+ Review this agent&apos;s budget policy and spend in the organization costs view.
+ </p>
+ <Button variant="outline" asChild>
+ <Link to="/costs">Open costs and budgets</Link>
+ </Button>
</div>
) : null}
</div>
@@ -1772,21 +1765,25 @@ function LatestRunCard({
);
}
-/* ---- Agent Overview (main single-page view) ---- */
+/* ---- Agent Overview ---- */
-function AgentOverview({
+export function AgentOverview({
agent,
runs,
assignedIssues,
runtimeState,
- agentId,
+ reportsToAgent,
+ directReportCount,
+ skillNames,
agentRouteId,
}: {
agent: AgentDetailRecord;
runs: HeartbeatRun[];
- assignedIssues: { id: string; title: string; status: string; priority: string; identifier?: string | null; createdAt: Date }[];
+ assignedIssues: Issue[];
runtimeState?: AgentRuntimeState;
- agentId: string;
+ reportsToAgent?: Agent;
+ directReportCount: number;
+ skillNames: string[];
agentRouteId: string;
}) {
const issuesById = useMemo(() => {
@@ -1794,37 +1791,81 @@ function AgentOverview({
for (const issue of assignedIssues) map.set(issue.id, issue);
return map;
}, [assignedIssues]);
+ const configuredModel = asNonEmptyString(agent.adapterConfig?.model)
+ ?? asNonEmptyString(agent.adapterConfig?.modelName)
+ ?? asNonEmptyString(agent.runtimeConfig?.model)
+ ?? "Adapter default";
+ const lastRun = runs[0] ?? null;
return (
- <div className="space-y-8">
- {/* Latest Run */}
+ <div className="space-y-6">
<LatestRunCard runs={runs} agentId={agentRouteId} issuesById={issuesById} />
- {/* Charts */}
- <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
- <ChartCard title="Run Activity" subtitle="Last 14 days">
- <RunActivityChart runs={runs} />
- </ChartCard>
- {/* PAP-411: "Tasks by Priority" chart hidden behind SHOW_TASK_PRIORITY_UI. */}
- {SHOW_TASK_PRIORITY_UI && (
- <ChartCard title="Tasks by Priority" subtitle="Last 14 days">
- <PriorityChart issues={assignedIssues} />
- </ChartCard>
- )}
- <ChartCard title="Tasks by Status" subtitle="Last 14 days">
- <IssueStatusChart issues={assignedIssues} />
- </ChartCard>
- <ChartCard title="Success Rate" subtitle="Last 14 days">
- <SuccessRateChart runs={runs} />
- </ChartCard>
+ <div className="grid gap-4 md:grid-cols-2">
+ <section className="rounded-lg border border-border p-4" aria-labelledby="agent-identity-heading">
+ <div className="mb-4 flex items-center justify-between gap-3">
+ <h3 id="agent-identity-heading" className="text-sm font-medium">Identity</h3>
+ <StatusBadge status={agent.status} />
+ </div>
+ <div className="space-y-3">
+ <SummaryRow label="Role"><span className="text-sm">{roleLabels[agent.role] ?? agent.role}</span></SummaryRow>
+ <SummaryRow label="Title"><span className="text-sm">{agent.title ?? "Not set"}</span></SummaryRow>
+ <SummaryRow label="Reports to">
+ {reportsToAgent ? (
+ <Link className="text-sm hover:underline" to={agentDetailHref(agentRouteRef(reportsToAgent))}>
+ {reportsToAgent.name}
+ </Link>
+ ) : <span className="text-sm">Board</span>}
+ </SummaryRow>
+ <SummaryRow label="Direct reports"><span className="text-sm tabular-nums">{directReportCount}</span></SummaryRow>
+ </div>
+ </section>
+
+ <section className="rounded-lg border border-border p-4" aria-labelledby="agent-runtime-heading">
+ <div className="mb-4 flex items-center justify-between gap-3">
+ <h3 id="agent-runtime-heading" className="text-sm font-medium">Harness / Runtime</h3>
+ <Link className="text-xs text-muted-foreground hover:text-foreground" to={agentDetailHref(agentRouteId, "runtime")}>Configure</Link>
+ </div>
+ <div className="space-y-3">
+ <SummaryRow label="Adapter"><span className="text-sm">{adapterLabels[agent.adapterType] ?? agent.adapterType}</span></SummaryRow>
+ <SummaryRow label="Model"><span className="max-w-64 truncate text-sm font-mono">{configuredModel}</span></SummaryRow>
+ <SummaryRow label="Session"><span className="max-w-64 truncate text-sm font-mono">{runtimeState?.sessionDisplayId ?? runtimeState?.sessionId ?? "No session"}</span></SummaryRow>
+ <SummaryRow label="Last run">
+ <span className="text-sm">{lastRun ? `${lastRun.status} · ${relativeTime(lastRun.createdAt)}` : "No runs"}</span>
+ </SummaryRow>
+ </div>
+ </section>
+
+ <section className="rounded-lg border border-border p-4" aria-labelledby="agent-capabilities-heading">
+ <h3 id="agent-capabilities-heading" className="mb-3 text-sm font-medium">Capabilities</h3>
+ {agent.capabilities?.trim() ? (
+ <MarkdownBody className="text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">{agent.capabilities}</MarkdownBody>
+ ) : (
+ <p className="text-sm text-muted-foreground">No capability summary has been added.</p>
+ )}
+ </section>
+
+ <section className="rounded-lg border border-border p-4" aria-labelledby="agent-skills-heading">
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <h3 id="agent-skills-heading" className="text-sm font-medium">Skills</h3>
+ <Link className="text-xs text-muted-foreground hover:text-foreground" to={agentDetailHref(agentRouteId, "skills")}>Manage</Link>
+ </div>
+ {skillNames.length > 0 ? (
+ <div className="flex flex-wrap gap-2">
+ {skillNames.slice(0, 8).map((skill) => <Badge key={skill} variant="secondary">{skill}</Badge>)}
+ {skillNames.length > 8 ? <Badge variant="outline">+{skillNames.length - 8} more</Badge> : null}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">No skills enabled.</p>
+ )}
+ </section>
</div>
- {/* Recent Issues */}
- <div className="space-y-3">
+ <section className="space-y-3" aria-labelledby="agent-recent-tasks-heading">
<div className="flex items-center justify-between">
- <h3 className="text-sm font-medium">Recent Tasks</h3>
+ <h3 id="agent-recent-tasks-heading" className="text-sm font-medium">Recent Tasks</h3>
<Link
- to={`/issues?participantAgentId=${agentId}`}
+ to={`/issues?participantAgentId=${agent.id}`}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
See All &rarr;
@@ -1833,108 +1874,39 @@ function AgentOverview({
{assignedIssues.length === 0 ? (
<p className="text-sm text-muted-foreground">No recent tasks.</p>
) : (
- <div className="border border-border rounded-lg">
- {assignedIssues.slice(0, 10).map((issue) => (
- <EntityRow
+ <div className="overflow-hidden rounded-lg border border-border">
+ {assignedIssues.slice(0, 6).map((issue) => (
+ <IssueRow
key={issue.id}
- identifier={issue.identifier ?? issue.id.slice(0, 8)}
- title={issue.title}
- to={`/issues/${issue.identifier ?? issue.id}`}
- trailing={<StatusBadge status={issue.status} />}
+ issue={issue}
+ presentation="task"
+ metadata={<span className="text-xs text-muted-foreground">{relativeTime(issue.updatedAt)}</span>}
+ showDivider
/>
))}
- {assignedIssues.length > 10 && (
- <div className="px-3 py-2 text-xs text-muted-foreground text-center border-t border-border">
- +{assignedIssues.length - 10} more tasks
+ {assignedIssues.length > 6 && (
+ <div className="border-t border-border px-3 py-2 text-center text-xs text-muted-foreground">
+ +{assignedIssues.length - 6} more tasks
</div>
)}
</div>
)}
- </div>
-
- {/* Costs */}
- <div className="space-y-3">
- <h3 className="text-sm font-medium">Costs</h3>
- <CostsSection runtimeState={runtimeState} runs={runs} />
- </div>
- </div>
- );
-}
-
-/* ---- Costs Section (inline) ---- */
-
-function CostsSection({
- runtimeState,
- runs,
-}: {
- runtimeState?: AgentRuntimeState;
- runs: HeartbeatRun[];
-}) {
- const runsWithCost = runs
- .filter((r) => {
- const metrics = runMetrics(r);
- return metrics.cost > 0 || metrics.input > 0 || metrics.output > 0 || metrics.cached > 0;
- })
- .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
-
- return (
- <div className="space-y-4">
- {runtimeState && (
- <div className="border border-border rounded-lg p-4">
- <div className="grid grid-cols-2 md:grid-cols-4 gap-4 tabular-nums">
- <div>
- <span className="text-xs text-muted-foreground block">Input tokens</span>
- <span className="text-lg font-semibold">{formatTokens(runtimeState.totalInputTokens)}</span>
- </div>
- <div>
- <span className="text-xs text-muted-foreground block">Output tokens</span>
- <span className="text-lg font-semibold">{formatTokens(runtimeState.totalOutputTokens)}</span>
- </div>
- <div>
- <span className="text-xs text-muted-foreground block">Cached tokens</span>
- <span className="text-lg font-semibold">{formatTokens(runtimeState.totalCachedInputTokens)}</span>
- </div>
- <div>
- <span className="text-xs text-muted-foreground block">Total cost</span>
- <span className="text-lg font-semibold">{formatCents(runtimeState.totalCostCents)}</span>
- </div>
- </div>
- </div>
- )}
- {runsWithCost.length > 0 && (
- <div className="border border-border rounded-lg overflow-hidden">
- <table className="w-full text-xs">
- <thead>
- <tr className="border-b border-border bg-accent/20">
- <th scope="col" className="text-left px-3 py-2 font-medium text-muted-foreground">Date</th>
- <th scope="col" className="text-left px-3 py-2 font-medium text-muted-foreground">Run</th>
- <th scope="col" className="text-right px-3 py-2 font-medium text-muted-foreground">Input</th>
- <th scope="col" className="text-right px-3 py-2 font-medium text-muted-foreground">Output</th>
- <th scope="col" className="text-right px-3 py-2 font-medium text-muted-foreground">Cost</th>
- </tr>
- </thead>
- <tbody>
- {runsWithCost.slice(0, 10).map((run) => {
- const metrics = runMetrics(run);
- return (
- <tr key={run.id} className="border-b border-border last:border-b-0">
- <td className="px-3 py-2">{formatDate(run.createdAt)}</td>
- <td className="px-3 py-2 font-mono">{run.id.slice(0, 8)}</td>
- <td className="px-3 py-2 text-right tabular-nums">{formatTokens(metrics.input)}</td>
- <td className="px-3 py-2 text-right tabular-nums">{formatTokens(metrics.output)}</td>
- <td className="px-3 py-2 text-right tabular-nums">
- {metrics.cost > 0
- ? `$${metrics.cost.toFixed(4)}`
- : "-"
- }
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
+ </section>
+
+ <section className="space-y-3" aria-labelledby="agent-audit-links-heading">
+ <h3 id="agent-audit-links-heading" className="text-sm font-medium">Audit</h3>
+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
+ {(["activity", "runs", "costs", "budgets"] as const).map((section) => (
+ <Link
+ key={section}
+ to={agentScopedAuditHref(agent.id, section)}
+ className="rounded-lg border border-border px-3 py-2 text-sm font-medium capitalize hover:bg-accent"
+ >
+ {section}
+ </Link>
+ ))}
</div>
- )}
+ </section>
</div>
);
}
@@ -1964,31 +1936,15 @@ export function syncAgentRouteAfterRename(
return true;
}
-function AgentConfigurePage({
+function AgentRevisionsTab({
agent,
- agentId,
companyId,
- onDirtyChange,
- onSaveActionChange,
- onCancelActionChange,
- onSavingChange,
- updatePermissions,
- canConfigureProviderTrace,
}: {
agent: AgentDetailRecord;
- agentId: string;
companyId?: string;
- onDirtyChange: (dirty: boolean) => void;
- onSaveActionChange: (save: (() => void) | null) => void;
- onCancelActionChange: (cancel: (() => void) | null) => void;
- onSavingChange: (saving: boolean) => void;
- updatePermissions: { mutate: (permissions: AgentPermissionUpdate) => void; isPending: boolean };
- canConfigureProviderTrace: boolean;
}) {
const queryClient = useQueryClient();
const navigate = useNavigate();
- const { tab: urlTab } = useParams<{ tab?: string }>();
- const [revisionsOpen, setRevisionsOpen] = useState(false);
const { data: configRevisions } = useQuery({
queryKey: queryKeys.agents.configRevisions(agent.id),
@@ -2000,81 +1956,48 @@ function AgentConfigurePage({
onSuccess: (updated) => {
queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) });
queryClient.invalidateQueries({ queryKey: queryKeys.agents.configRevisions(agent.id) });
- if (!syncAgentRouteAfterRename(queryClient, navigate, agent, updated, urlTab ?? "configuration")) {
+ if (!syncAgentRouteAfterRename(queryClient, navigate, agent, updated, "revisions")) {
queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) });
}
},
});
return (
- <div className="max-w-3xl space-y-6">
- <ConfigurationTab
- agent={agent}
- onDirtyChange={onDirtyChange}
- onSaveActionChange={onSaveActionChange}
- onCancelActionChange={onCancelActionChange}
- onSavingChange={onSavingChange}
- updatePermissions={updatePermissions}
- companyId={companyId}
- hidePromptTemplate
- hideInstructionsFile
- canConfigureProviderTrace={canConfigureProviderTrace}
- />
- <div>
- <h3 className="text-sm font-medium mb-3">API Keys</h3>
- <KeysTab agentId={agentId} companyId={companyId} />
+ <div className="max-w-3xl space-y-3">
+ <div className="flex items-baseline justify-between gap-3">
+ <h3 className="text-sm font-medium">Configuration Revisions</h3>
+ <span className="text-xs text-muted-foreground">{configRevisions?.length ?? 0} total</span>
</div>
-
- {/* Configuration Revisions — collapsible at the bottom */}
- <div>
- <button
- className="flex items-center gap-2 text-sm font-medium hover:text-foreground transition-colors"
- onClick={() => setRevisionsOpen((v) => !v)}
- >
- {revisionsOpen
- ? <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
- : <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
- }
- Configuration Revisions
- <span className="text-xs font-normal text-muted-foreground">{configRevisions?.length ?? 0}</span>
- </button>
- {revisionsOpen && (
- <div className="mt-3">
- {(configRevisions ?? []).length === 0 ? (
- <p className="text-sm text-muted-foreground">No configuration revisions yet.</p>
- ) : (
- <div className="space-y-2">
- {(configRevisions ?? []).slice(0, 10).map((revision) => (
- <div key={revision.id} className="border border-border/70 rounded-md p-3 space-y-2">
- <div className="flex items-center justify-between gap-3">
- <div className="text-xs text-muted-foreground">
- <span className="font-mono">{revision.id.slice(0, 8)}</span>
- <span className="mx-1">·</span>
- <span>{formatDate(revision.createdAt)}</span>
- <span className="mx-1">·</span>
- <span>{revision.source}</span>
- </div>
- <Button
- size="sm"
- variant="outline"
- className="h-7 px-2.5 text-xs"
- onClick={() => rollbackConfig.mutate(revision.id)}
- disabled={rollbackConfig.isPending}
- >
- Restore
- </Button>
- </div>
- <p className="text-xs text-muted-foreground">
- Changed:{" "}
- {revision.changedKeys.length > 0 ? revision.changedKeys.join(", ") : "no tracked changes"}
- </p>
- </div>
- ))}
+ {(configRevisions ?? []).length === 0 ? (
+ <p className="text-sm text-muted-foreground">No configuration revisions yet.</p>
+ ) : (
+ <div className="space-y-2">
+ {(configRevisions ?? []).map((revision) => (
+ <div key={revision.id} className="space-y-2 rounded-md border border-border p-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-xs text-muted-foreground">
+ <span className="font-mono">{revision.id.slice(0, 8)}</span>
+ <span className="mx-1">·</span>
+ <span>{formatDate(revision.createdAt)}</span>
+ <span className="mx-1">·</span>
+ <span>{revision.source}</span>
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => rollbackConfig.mutate(revision.id)}
+ disabled={rollbackConfig.isPending}
+ >
+ Restore
+ </Button>
</div>
- )}
- </div>
- )}
- </div>
+ <p className="text-xs text-muted-foreground">
+ Changed: {revision.changedKeys.length > 0 ? revision.changedKeys.join(", ") : "no tracked changes"}
+ </p>
+ </div>
+ ))}
+ </div>
+ )}
</div>
);
}
@@ -2091,7 +2014,7 @@ function ConfigurationTab({
updatePermissions,
hidePromptTemplate,
hideInstructionsFile,
- content = "configuration",
+ content = "runtime",
canConfigureProviderTrace = false,
}: {
agent: AgentDetailRecord;
@@ -2103,7 +2026,7 @@ function ConfigurationTab({
updatePermissions: { mutate: (permissions: AgentPermissionUpdate) => void; isPending: boolean };
hidePromptTemplate?: boolean;
hideInstructionsFile?: boolean;
- content?: "configuration" | "secrets";
+ content?: "runtime" | "permissions" | "secrets";
canConfigureProviderTrace?: boolean;
}) {
const queryClient = useQueryClient();
@@ -2119,7 +2042,7 @@ function ConfigurationTab({
? queryKeys.agents.adapterModels(companyId, agent.adapterType)
: ["agents", "none", "adapter-models", agent.adapterType],
queryFn: () => agentsApi.adapterModels(companyId!, agent.adapterType),
- enabled: Boolean(companyId) && content === "configuration",
+ enabled: Boolean(companyId) && content === "runtime",
});
const lowTrustSelected = getTrustPreset(agent.permissions) === "low_trust_review";
@@ -2127,7 +2050,7 @@ function ConfigurationTab({
const { data: boundaryProjects, isLoading: boundaryProjectsLoading } = useQuery({
queryKey: companyId ? queryKeys.projects.list(companyId) : ["projects", "__low-trust-disabled"],
queryFn: () => projectsApi.list(companyId!),
- enabled: Boolean(companyId && lowTrustSelected) && content === "configuration",
+ enabled: Boolean(companyId && lowTrustSelected) && content === "permissions",
});
const { data: boundaryIssues, isLoading: boundaryIssuesLoading } = useQuery({
@@ -2135,7 +2058,7 @@ function ConfigurationTab({
? [...queryKeys.issues.list(companyId), "low-trust-boundary-candidates"]
: ["issues", "__low-trust-disabled"],
queryFn: () => issuesApi.list(companyId!, { limit: 100, sortField: "updated", sortDir: "desc" }),
- enabled: Boolean(companyId && lowTrustSelected) && content === "configuration",
+ enabled: Boolean(companyId && lowTrustSelected) && content === "permissions",
});
const updateAgent = useMutation({
@@ -2170,12 +2093,19 @@ function ConfigurationTab({
}
lastAgentRef.current = agent;
}, [agent, awaitingRefreshAfterSave]);
- const isConfigSaving = updateAgent.isPending || awaitingRefreshAfterSave;
+ const isConfigSaving = content !== "permissions" && (updateAgent.isPending || awaitingRefreshAfterSave);
useEffect(() => {
onSavingChange(isConfigSaving);
}, [onSavingChange, isConfigSaving]);
+ useEffect(() => {
+ if (content !== "permissions") return;
+ onDirtyChange(false);
+ onSaveActionChange(null);
+ onCancelActionChange(null);
+ }, [content, onCancelActionChange, onDirtyChange, onSaveActionChange]);
+
const canCreateAgents = Boolean(agent.permissions?.canCreateAgents);
const canCreateSkills = agent.permissions?.canCreateSkills !== false;
const canAssignTasks = Boolean(agent.access?.canAssignTasks);
@@ -2194,7 +2124,7 @@ function ConfigurationTab({
return (
<div className="space-y-6">
- <AgentConfigForm
+ {content !== "permissions" ? <AgentConfigForm
mode="edit"
agent={agent}
onSave={(patch) => updateAgent.mutateAsync(patch)}
@@ -2206,17 +2136,17 @@ function ConfigurationTab({
hideInlineSave
hidePromptTemplate={hidePromptTemplate}
hideInstructionsFile={hideInstructionsFile}
- content={content}
+ content={content === "runtime" ? "configuration" : "secrets"}
sectionLayout="cards"
canConfigureProviderTrace={canConfigureProviderTrace}
- />
- {content === "configuration" ? (
+ /> : null}
+ {content === "runtime" ? (
<p className="text-xs text-muted-foreground">
Saved adapter config affects the next run. Active runs keep the config they started with, and config changes may start a fresh adapter session.
</p>
) : null}
- {content === "configuration" ? <TrustPresetSection
+ {content === "permissions" ? <TrustPresetSection
permissions={agent.permissions}
disabled={updatePermissions.isPending}
companyId={companyId}
@@ -2239,7 +2169,7 @@ function ConfigurationTab({
}
/> : null}
- {content === "configuration" ? <div>
+ {content === "permissions" ? <div>
<h3 className="text-sm font-medium mb-3">Permissions</h3>
<div className="border border-border rounded-lg p-4 space-y-4">
<div className="flex items-center justify-between gap-4 text-sm">
@@ -2326,6 +2256,7 @@ export function PromptsTab({
const { selectedCompanyId } = useCompany();
const { isMobile } = useSidebar();
const [selectedFile, setSelectedFileState] = useState<string>("AGENTS.md");
+ const [instructionMode, setInstructionMode] = useState<"read" | "edit" | "raw">("read");
const [showFilePanel, setShowFilePanel] = useState(false);
const [draft, setDraft] = useState<string | null>(null);
const [bundleDraft, setBundleDraft] = useState<{
@@ -2362,6 +2293,7 @@ export function PromptsTab({
useEffect(() => {
editorInteractedRef.current = false;
setSelectedFile("AGENTS.md");
+ setInstructionMode("read");
setShowFilePanel(false);
setDraft(null);
setBundleDraft(null);
@@ -2952,6 +2884,7 @@ export function PromptsTab({
})}
onSelectFile={(filePath) => {
setSelectedFile(filePath);
+ setInstructionMode("read");
if (!fileOptions.includes(filePath)) setDraft("");
if (isMobile) setShowFilePanel(false);
}}
@@ -3018,6 +2951,21 @@ export function PromptsTab({
</div>
</div>
<div className="flex items-center gap-2">
+ <div className="flex items-center rounded-md border border-border p-0.5" role="group" aria-label="Instruction file view">
+ {(["read", "edit", "raw"] as const).map((mode) => (
+ <Button
+ key={mode}
+ type="button"
+ size="sm"
+ variant={instructionMode === mode ? "secondary" : "ghost"}
+ className="capitalize"
+ aria-pressed={instructionMode === mode}
+ onClick={() => setInstructionMode(mode)}
+ >
+ {mode}
+ </Button>
+ ))}
+ </div>
{!fileLoading && (
<CopyText
text={displayValue}
@@ -3054,6 +3002,27 @@ export function PromptsTab({
{selectedFileExists && fileLoading && !selectedFileDetail ? (
<PromptEditorSkeleton />
+ ) : instructionMode === "read" ? (
+ <div className="min-h-(--sz-420px) rounded-md border border-border bg-background p-4">
+ {displayValue.trim() ? (
+ useMarkdownEditor ? (
+ <MarkdownBody className="max-w-none text-sm leading-7 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
+ {displayValue}
+ </MarkdownBody>
+ ) : (
+ <pre className="whitespace-pre-wrap break-words font-sans text-sm leading-7">{displayValue}</pre>
+ )
+ ) : (
+ <p className="text-sm text-muted-foreground">This instruction file is empty.</p>
+ )}
+ </div>
+ ) : instructionMode === "raw" ? (
+ <pre
+ data-testid="instructions-raw-source"
+ className="min-h-(--sz-420px) overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-muted p-4 font-mono text-sm leading-7"
+ >
+ {displayValue}
+ </pre>
) : useMarkdownEditor ? (
<div
onBeforeInputCapture={markEditorInteracted}
@@ -3082,6 +3051,7 @@ export function PromptsTab({
</div>
) : (
<textarea
+ aria-label="Instruction file editor"
value={displayValue}
onChange={(event) => setDraft(event.target.value)}
className="min-h-(--sz-420px) w-full min-w-0 rounded-md border border-border bg-transparent px-3 py-2 font-mono text-sm outline-none"
diff --git a/ui/src/pages/AgentOverview.test.tsx b/ui/src/pages/AgentOverview.test.tsx
new file mode 100644
index 0000000000..7149a65788
--- /dev/null
+++ b/ui/src/pages/AgentOverview.test.tsx
@@ -0,0 +1,78 @@
+// @vitest-environment jsdom
+
+import { renderToStaticMarkup } from "react-dom/server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { AgentDetail, AgentRuntimeState, HeartbeatRun, Issue } from "@paperclipai/shared";
+import { describe, expect, it, vi } from "vitest";
+import { AgentOverview } from "./AgentDetail";
+
+vi.mock("@/lib/router", async () => {
+ const actual = await vi.importActual<typeof import("react-router-dom")>("react-router-dom");
+ return {
+ ...actual,
+ Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+ };
+});
+
+vi.mock("../components/MarkdownBody", () => ({
+ MarkdownBody: ({ children }: { children: string }) => <div>{children}</div>,
+}));
+
+describe("AgentOverview", () => {
+ it("prioritizes identity, capability, runtime, skills, tasks, and scoped Audit entry points", () => {
+ const agent = {
+ id: "agent-1",
+ companyId: "company-1",
+ name: "Codex Coder",
+ urlKey: "codexcoder",
+ role: "engineer",
+ title: "Product engineer",
+ status: "active",
+ reportsTo: null,
+ capabilities: "Builds and verifies product changes.",
+ adapterType: "codex_local",
+ adapterConfig: { model: "gpt-5.6-sol" },
+ runtimeConfig: {},
+ chainOfCommand: [],
+ access: { canAssignTasks: true, taskAssignSource: "explicit_grant", membership: null, grants: [] },
+ } as unknown as AgentDetail;
+ const issue = {
+ id: "issue-1",
+ companyId: "company-1",
+ identifier: "PAP-42",
+ title: "Simplify agent information architecture",
+ status: "in_progress",
+ priority: "high",
+ updatedAt: new Date("2026-08-31T12:00:00Z"),
+ } as unknown as Issue;
+ const runtime = {
+ sessionDisplayId: "codex-session-42",
+ } as unknown as AgentRuntimeState;
+
+ const markup = renderToStaticMarkup(
+ <QueryClientProvider client={new QueryClient()}>
+ <AgentOverview
+ agent={agent}
+ runs={[] as HeartbeatRun[]}
+ assignedIssues={[issue]}
+ runtimeState={runtime}
+ directReportCount={2}
+ skillNames={["Design Guide", "Check PR"]}
+ agentRouteId="codexcoder"
+ />
+ </QueryClientProvider>,
+ );
+
+ expect(markup).toContain("Identity");
+ expect(markup).toContain("Capabilities");
+ expect(markup).toContain("Harness / Runtime");
+ expect(markup).toContain("Design Guide");
+ expect(markup).toContain("Simplify agent information architecture");
+ expect(markup).toContain("PAP-42");
+ expect(markup).toContain('href="/activity/costs?agentId=agent-1"');
+ expect(markup).not.toContain("Run Activity");
+ expect(markup).not.toContain("Tasks by Status");
+ });
+});
diff --git a/ui/src/pages/Agents.production.tsx b/ui/src/pages/Agents.production.tsx
new file mode 100644
index 0000000000..8e519f538b
--- /dev/null
+++ b/ui/src/pages/Agents.production.tsx
@@ -0,0 +1,874 @@
+import { useState, useEffect, useMemo, lazy, Suspense } from "react";
+import { Link, useNavigate, useLocation } from "@/lib/router";
+import { useQuery } from "@tanstack/react-query";
+import { agentsApi, type OrgNode } from "../api/agents";
+import { builtInAgentsApi, type BuiltInAgentState } from "../api/builtInAgents";
+import { environmentsApi } from "../api/environments";
+import { heartbeatsApi } from "../api/heartbeats";
+import { instanceSettingsApi } from "../api/instanceSettings";
+import { useCompany } from "../context/CompanyContext";
+import { useDialogActions } from "../context/DialogContext";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useSidebar } from "../context/SidebarContext";
+import { queryKeys } from "../lib/queryKeys";
+import { isPlatformManagedEnvironment } from "../lib/managed-sandbox-environment";
+import { AgentStatusBadge, AgentStatusCapsule } from "../components/StatusBadge";
+import { AgentActionButtons } from "../components/AgentActionButtons";
+import { MembershipAction } from "../components/MembershipAction";
+import { StarToggle } from "../components/StarToggle";
+import { EntityRow } from "../components/EntityRow";
+import { BuiltInLifecycleChip } from "../components/BuiltInAgentBadges";
+import { EmptyState } from "../components/EmptyState";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { relativeTime, cn, agentRouteRef, agentUrl } from "../lib/utils";
+import { PageTabBar } from "../components/PageTabBar";
+import { Tabs } from "@/components/ui/tabs";
+import { Button } from "@/components/ui/button";
+import { AlertTriangle, Bot, Plus, List, GitBranch } from "lucide-react";
+import { AGENT_ROLE_LABELS, type Agent, type Environment, type EnvironmentCapabilities } from "@paperclipai/shared";
+import {
+ isStarred,
+ resourceMembershipState,
+ useResourceMembershipMutation,
+ useResourceMemberships,
+} from "../hooks/useResourceMemberships";
+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
+
+import { getAdapterLabel } from "../adapters/adapter-display-registry";
+
+const roleLabels = AGENT_ROLE_LABELS as Record<string, string>;
+
+// Lazy-loaded so the roster page doesn't statically pull in the full
+// AgentConfigForm module graph (the modal reuses its adapter/model pickers).
+const ConfigureBuiltInAgentModal = lazy(() =>
+ import("../components/ConfigureBuiltInAgentModal").then((m) => ({
+ default: m.ConfigureBuiltInAgentModal,
+ })),
+);
+
+export const AGENT_FILTER_TABS = ["all", "active", "paused", "error", "builtin"] as const;
+type FilterTab = (typeof AGENT_FILTER_TABS)[number];
+
+const AGENT_FILTER_TAB_ITEMS: { value: FilterTab; label: string }[] = [
+ { value: "all", label: "All" },
+ { value: "active", label: "Active" },
+ { value: "paused", label: "Paused" },
+ { value: "error", label: "Error" },
+ { value: "builtin", label: "Built-in" },
+];
+
+function isFilterTab(value: string): value is FilterTab {
+ return (AGENT_FILTER_TABS as readonly string[]).includes(value);
+}
+
+interface EnvironmentDescriptor {
+ label: string;
+ detail: string;
+ title: string;
+}
+
+const localEnvironmentDescriptor: EnvironmentDescriptor = {
+ label: "Local",
+ detail: "Paperclip host",
+ title: "Local - Paperclip host",
+};
+
+const loadingEnvironmentDescriptor: EnvironmentDescriptor = {
+ label: "—",
+ detail: "Loading environment",
+ title: "Loading environment",
+};
+
+// Agents in these states never appear in the agents list — `terminated` is
+// hidden like an archived company, and `pending_approval` is a hiring gate that
+// lives in the task thread, not an agent run state (PAP-75).
+const HIDDEN_AGENT_STATUSES = new Set(["terminated", "pending_approval"]);
+
+function matchesFilter(status: string, tab: FilterTab): boolean {
+ if (tab === "all") return true;
+ if (tab === "active") return status === "active" || status === "running" || status === "idle";
+ if (tab === "paused") return status === "paused";
+ if (tab === "error") return status === "error";
+ return true;
+}
+
+function filterAgents(agents: Agent[], tab: FilterTab, builtInAgentIds: Set<string>): Agent[] {
+ return agents
+ .filter((a) => {
+ if (HIDDEN_AGENT_STATUSES.has(a.status)) return false;
+ // The `builtin` filter keys on the built-in marker, not agent status.
+ if (tab === "builtin") return builtInAgentIds.has(a.id);
+ return matchesFilter(a.status, tab);
+ })
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+function getConfiguredModel(agent: Agent): string | null {
+ const value = agent.adapterConfig?.model;
+ if (typeof value !== "string") return null;
+ const model = value.trim();
+ return model.length > 0 ? model : null;
+}
+
+function formatEnvironmentDriver(driver: Environment["driver"]): string {
+ if (driver === "ssh") return "SSH";
+ return driver.charAt(0).toUpperCase() + driver.slice(1);
+}
+
+function getSandboxProviderLabel(
+ environment: Environment,
+ capabilities?: EnvironmentCapabilities | null,
+): string {
+ const provider = typeof environment.config.provider === "string"
+ ? environment.config.provider.trim()
+ : "";
+ if (!provider) return "Sandbox";
+ return capabilities?.sandboxProviders?.[provider]?.displayName ?? provider;
+}
+
+function describeEnvironment(
+ environment: Environment,
+ capabilities?: EnvironmentCapabilities | null,
+): EnvironmentDescriptor {
+ const detail = isPlatformManagedEnvironment(environment)
+ ? "Managed by Paperclip"
+ : environment.driver === "sandbox"
+ ? `${getSandboxProviderLabel(environment, capabilities)} sandbox provider`
+ : environment.driver === "local"
+ ? "Paperclip host"
+ : formatEnvironmentDriver(environment.driver);
+
+ return {
+ label: environment.name,
+ detail,
+ title: `${environment.name} - ${detail}`,
+ };
+}
+
+function describeMissingEnvironment(environmentId: string): EnvironmentDescriptor {
+ return {
+ label: "Unknown environment",
+ detail: environmentId.slice(0, 8),
+ title: `Unknown environment - ${environmentId}`,
+ };
+}
+
+function resolveAgentEnvironment(
+ agent: Agent,
+ environmentsById: Map<string, Environment>,
+ instanceDefaultEnvironmentId: string | null,
+ capabilities?: EnvironmentCapabilities | null,
+): EnvironmentDescriptor {
+ const environmentId = agent.defaultEnvironmentId ?? instanceDefaultEnvironmentId;
+ if (!environmentId) return localEnvironmentDescriptor;
+ const environment = environmentsById.get(environmentId);
+ return environment
+ ? describeEnvironment(environment, capabilities)
+ : describeMissingEnvironment(environmentId);
+}
+
+function filterOrgTree(nodes: OrgNode[], tab: FilterTab, builtInAgentIds: Set<string>): OrgNode[] {
+ return nodes
+ .reduce<OrgNode[]>((acc, node) => {
+ const filteredReports = filterOrgTree(node.reports, tab, builtInAgentIds);
+ // Hidden agents (terminated / pending_approval) never render as a row, but
+ // any visible reports are promoted so the tree doesn't lose live agents.
+ if (HIDDEN_AGENT_STATUSES.has(node.status)) {
+ acc.push(...filteredReports);
+ return acc;
+ }
+ const nodeMatches = tab === "builtin"
+ ? builtInAgentIds.has(node.id)
+ : matchesFilter(node.status, tab);
+ if (nodeMatches || filteredReports.length > 0) {
+ acc.push({ ...node, reports: filteredReports });
+ }
+ return acc;
+ }, [])
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export function Agents() {
+ const { selectedCompanyId } = useCompany();
+ const { openNewAgent } = useDialogActions();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const { isMobile } = useSidebar();
+ const pathSegment = location.pathname.split("/").pop() ?? "all";
+ const requestedTab: FilterTab = isFilterTab(pathSegment) ? pathSegment : "all";
+ const [view, setView] = useState<"list" | "org">("org");
+ const forceListView = isMobile;
+ const effectiveView: "list" | "org" = forceListView ? "list" : view;
+
+ const { data: instanceSettings } = useQuery({
+ queryKey: queryKeys.instance.settings,
+ queryFn: () => instanceSettingsApi.get(),
+ enabled: !!selectedCompanyId,
+ });
+ const builtInAgentsEnabled = instanceSettings?.experimental.enableBuiltInAgents === true;
+ const tab: FilterTab = requestedTab === "builtin" && !builtInAgentsEnabled ? "all" : requestedTab;
+ const visibleTabItems = useMemo(
+ () => AGENT_FILTER_TAB_ITEMS.filter((item) => item.value !== "builtin" || builtInAgentsEnabled),
+ [builtInAgentsEnabled],
+ );
+
+ const { data: builtInAgents } = useQuery({
+ queryKey: queryKeys.builtInAgents.list(selectedCompanyId!),
+ queryFn: () => builtInAgentsApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId && builtInAgentsEnabled,
+ });
+ const builtInByAgentId = useMemo(() => {
+ const map = new Map<string, BuiltInAgentState>();
+ if (!builtInAgentsEnabled) return map;
+ for (const entry of builtInAgents ?? []) {
+ if (entry.agentId) map.set(entry.agentId, entry);
+ }
+ return map;
+ }, [builtInAgents, builtInAgentsEnabled]);
+ const builtInAgentIds = useMemo(() => new Set(builtInByAgentId.keys()), [builtInByAgentId]);
+ const [configureState, setConfigureState] = useState<BuiltInAgentState | null>(null);
+
+ const { data: agents, isLoading, error } = useQuery({
+ queryKey: queryKeys.agents.list(selectedCompanyId!),
+ queryFn: () => agentsApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+
+ const { data: orgTree } = useQuery({
+ queryKey: queryKeys.org(selectedCompanyId!),
+ queryFn: () => agentsApi.org(selectedCompanyId!),
+ enabled: !!selectedCompanyId && effectiveView === "org",
+ });
+
+ const environmentsEnabled = instanceSettings?.experimental.enableEnvironments === true;
+
+ const { data: environments } = useQuery({
+ queryKey: queryKeys.environments.list(selectedCompanyId!),
+ queryFn: () => environmentsApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId && environmentsEnabled,
+ });
+
+ const { data: environmentCapabilities } = useQuery({
+ queryKey: queryKeys.environments.capabilities(selectedCompanyId!),
+ queryFn: () => environmentsApi.capabilities(selectedCompanyId!),
+ enabled: !!selectedCompanyId && environmentsEnabled,
+ });
+
+ const runsQueryKey = [...queryKeys.liveRuns(selectedCompanyId!), "agents-page"] as const;
+ const sharedRuns = useSharedPollingQuery({
+ companyId: selectedCompanyId,
+ resourceKey: "live-runs:agents-page",
+ queryKey: runsQueryKey,
+ enabled: !!selectedCompanyId,
+ refetchInterval: 15_000,
+ leaderOnly: true,
+ });
+ const { data: runs, dataUpdatedAt: runsUpdatedAt } = useQuery({
+ queryKey: runsQueryKey,
+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),
+ enabled: sharedRuns.enabled,
+ refetchInterval: sharedRuns.refetchInterval,
+ });
+ usePublishSharedQueryData(sharedRuns, runs, runsUpdatedAt);
+ const membershipsQuery = useResourceMemberships(selectedCompanyId);
+ const membershipMutation = useResourceMembershipMutation(selectedCompanyId);
+
+ // Map agentId -> first live run + live run count
+ const liveRunByAgent = useMemo(() => {
+ const map = new Map<string, { runId: string; liveCount: number }>();
+ for (const r of runs ?? []) {
+ if (r.status !== "running" && r.status !== "queued") continue;
+ const existing = map.get(r.agentId);
+ if (existing) {
+ existing.liveCount += 1;
+ continue;
+ }
+ map.set(r.agentId, { runId: r.id, liveCount: 1 });
+ }
+ return map;
+ }, [runs]);
+
+ const agentMap = useMemo(() => {
+ const map = new Map<string, Agent>();
+ for (const a of agents ?? []) map.set(a.id, a);
+ return map;
+ }, [agents]);
+
+ const environmentsById = useMemo(() => {
+ const map = new Map<string, Environment>();
+ for (const environment of environments ?? []) map.set(environment.id, environment);
+ return map;
+ }, [environments]);
+
+ const environmentByAgentId = useMemo(() => {
+ const map = new Map<string, EnvironmentDescriptor>();
+ for (const agent of agents ?? []) {
+ map.set(
+ agent.id,
+ resolveAgentEnvironment(
+ agent,
+ environmentsById,
+ instanceSettings?.defaultEnvironmentId ?? null,
+ environmentCapabilities,
+ ),
+ );
+ }
+ return map;
+ }, [agents, environmentsById, environmentCapabilities, instanceSettings?.defaultEnvironmentId]);
+
+ useEffect(() => {
+ setBreadcrumbs([{ label: "Agents" }]);
+ }, [setBreadcrumbs]);
+
+ useEffect(() => {
+ if (selectedCompanyId && requestedTab === "builtin" && instanceSettings && !builtInAgentsEnabled) {
+ navigate("/agents/all", { replace: true });
+ }
+ }, [builtInAgentsEnabled, instanceSettings, navigate, requestedTab, selectedCompanyId]);
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={Bot} message="Select a company to view agents." />;
+ }
+
+ if (isLoading) {
+ return <PageSkeleton variant="list" />;
+ }
+
+ const filtered = filterAgents(agents ?? [], tab, builtInAgentIds);
+ const filteredOrg = filterOrgTree(orgTree ?? [], tab, builtInAgentIds);
+ const environmentDataLoading = environmentsEnabled && environments === undefined;
+ const showEnvironmentColumn = environmentsEnabled && (environments === undefined || environments.length > 1);
+ const resolveRenderedEnvironment = (agentId: string) => (
+ environmentDataLoading
+ ? loadingEnvironmentDescriptor
+ : environmentByAgentId.get(agentId) ?? localEnvironmentDescriptor
+ );
+
+ const renderAgentRow = (agent: Agent) => {
+ const hasInvalidOrgChain = agent.orgChainHealth?.status === "invalid_org_chain";
+ const agentPending =
+ membershipMutation.isPending &&
+ membershipMutation.variables?.resourceType === "agent" &&
+ membershipMutation.variables.resourceId === agent.id;
+ const agentStarPending = agentPending && membershipMutation.variables?.starred !== undefined;
+ const agentJoinLeavePending = agentPending && membershipMutation.variables?.starred === undefined;
+ const agentStarred = isStarred(membershipsQuery.data, "agent", agent.id);
+ const builtInState = builtInByAgentId.get(agent.id);
+ const showBuiltInLifecycle = builtInState?.status === "needs_setup" || builtInState?.status === "pending_approval";
+ // Lifecycle chip + inline `Set up`. Rendered inline in
+ // `meta` at xl (where there's room and the meta columns align) and on a
+ // dedicated full-width line beneath the name below xl, so the chips never
+ // starve the name — the row's primary identifier — at narrow widths.
+ const builtInCluster = builtInState && showBuiltInLifecycle ? (
+ <>
+ <BuiltInLifecycleChip status={builtInState.status} />
+ {builtInState.status === "needs_setup" && (
+ <span
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => setConfigureState(builtInState)}
+ >
+ Set up
+ </Button>
+ </span>
+ )}
+ </>
+ ) : null;
+ return (
+ <EntityRow
+ key={agent.id}
+ title={agent.name}
+ // Fixed (truncating) title width at xl so the `meta` group starts at a
+ // constant x on every row — that's what makes the model + timestamp
+ // columns line up vertically. Below xl the meta columns are hidden, so
+ // the title flexes instead: a fixed width there let the shrink-0
+ // trailing actions squeeze the name to zero width on mobile.
+ titleClassName="flex-1 xl:flex-none xl:w-56"
+ titleTextClassName="whitespace-normal break-words xl:truncate xl:whitespace-nowrap"
+ subtitleClassName="whitespace-normal break-words xl:truncate xl:whitespace-nowrap"
+ subtitle={`${roleLabels[agent.role] ?? agent.role}${agent.title ? ` - ${agent.title}` : ""}`}
+ to={agentUrl(agent)}
+ className={cn(
+ "group",
+ agent.pausedAt && tab !== "paused" ? "opacity-50" : "",
+ resourceMembershipState(membershipsQuery.data, "agent", agent.id) === "left" ? "sm:text-foreground/55" : "",
+ )}
+ leading={hasInvalidOrgChain ? (
+ <AlertTriangle className="h-3.5 w-3.5 text-amber-500" aria-label="Invalid reporting chain" />
+ ) : (
+ <AgentStatusCapsule status={agent.status} />
+ )}
+ secondaryRow={
+ builtInCluster ? (
+ <div className="xl:hidden flex flex-wrap items-center gap-1.5">
+ {builtInCluster}
+ </div>
+ ) : undefined
+ }
+ meta={
+ <div className="flex items-center gap-3">
+ {builtInCluster && (
+ <div className="hidden xl:flex items-center gap-1.5">
+ {builtInCluster}
+ </div>
+ )}
+ <div className="hidden xl:flex items-center gap-3">
+ <AgentMetaColumns
+ agent={agent}
+ environment={resolveRenderedEnvironment(agent.id)}
+ showEnvironment={showEnvironmentColumn}
+ />
+ </div>
+ </div>
+ }
+ metaSpacerClassName="hidden xl:block"
+ trailing={
+ <div className="flex items-center gap-3">
+ <div className="hidden sm:flex items-center gap-3">
+ {liveRunByAgent.has(agent.id) && (
+ <LiveRunIndicator
+ agentRef={agentRouteRef(agent)}
+ runId={liveRunByAgent.get(agent.id)!.runId}
+ liveCount={liveRunByAgent.get(agent.id)!.liveCount}
+ />
+ )}
+ <span className="w-20 flex justify-end">
+ <AgentStatusBadge status={agent.status} />
+ </span>
+ {/* Row actions mirror the agent detail page; stop the click
+ from bubbling to the row link so buttons don't navigate.
+ Hidden on mobile so the agent name keeps room to render. */}
+ <div
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <AgentActionButtons
+ agent={agent}
+ companyId={selectedCompanyId}
+ runLabel="Run Heartbeat"
+ showStatus={false}
+ />
+ </div>
+ <StarToggle
+ size="row"
+ starred={agentStarred}
+ pending={agentStarPending}
+ resourceName={agent.name}
+ onToggle={(next) => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: agent.id,
+ resourceName: agent.name,
+ starred: next,
+ })}
+ />
+ </div>
+ <MembershipAction
+ state={resourceMembershipState(membershipsQuery.data, "agent", agent.id)}
+ pending={agentJoinLeavePending}
+ pendingState={agentJoinLeavePending ? membershipMutation.variables?.state ?? null : null}
+ resourceName={agent.name}
+ onJoin={() => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: agent.id,
+ resourceName: agent.name,
+ state: "joined",
+ })}
+ onLeave={() => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: agent.id,
+ resourceName: agent.name,
+ state: "left",
+ })}
+ />
+ </div>
+ }
+ />
+ );
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <Tabs value={tab} onValueChange={(v) => navigate(`/agents/${v}`)}>
+ <PageTabBar
+ items={visibleTabItems}
+ value={tab}
+ onValueChange={(v) => navigate(`/agents/${v}`)}
+ />
+ </Tabs>
+ <div className="flex items-center gap-2">
+ {/* View toggle */}
+ {!forceListView && (
+ <div className="flex items-center border border-border" role="group" aria-label="View mode">
+ <button
+ className={cn(
+ "p-1.5 transition-colors",
+ effectiveView === "list" ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"
+ )}
+ onClick={() => setView("list")}
+ title="List view"
+ aria-label="List view"
+ aria-pressed={effectiveView === "list"}
+ >
+ <List className="h-3.5 w-3.5" />
+ </button>
+ <button
+ className={cn(
+ "p-1.5 transition-colors",
+ effectiveView === "org" ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"
+ )}
+ onClick={() => setView("org")}
+ title="Org chart view"
+ aria-label="Org chart view"
+ aria-pressed={effectiveView === "org"}
+ >
+ <GitBranch className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ )}
+ <Button size="sm" variant="outline" onClick={openNewAgent}>
+ <Plus className="h-3.5 w-3.5 mr-1.5" />
+ New Agent
+ </Button>
+ </div>
+ </div>
+
+ {filtered.length > 0 && (
+ <p className="text-xs text-muted-foreground">{filtered.length} agent{filtered.length !== 1 ? "s" : ""}</p>
+ )}
+
+ {error && <p className="text-sm text-destructive">{error.message}</p>}
+
+ {agents && agents.length === 0 && (
+ <EmptyState
+ icon={Bot}
+ message="Create your first agent to get started."
+ action="New Agent"
+ onAction={openNewAgent}
+ />
+ )}
+
+ {/* List view */}
+ {effectiveView === "list" && filtered.length > 0 && (
+ <div>
+ {filtered.map(renderAgentRow)}
+ </div>
+ )}
+
+ {effectiveView === "list" && agents && agents.length > 0 && filtered.length === 0 && (
+ <p className="text-sm text-muted-foreground text-center py-8">
+ No agents match the selected status.
+ </p>
+ )}
+
+ {/* Org chart view */}
+ {effectiveView === "org" && filteredOrg.length > 0 && (
+ <div className="py-1">
+ {filteredOrg.map((node) => (
+ <OrgTreeNode
+ key={node.id}
+ node={node}
+ depth={0}
+ agentMap={agentMap}
+ liveRunByAgent={liveRunByAgent}
+ environmentByAgentId={environmentByAgentId}
+ environmentDataLoading={environmentDataLoading}
+ showEnvironment={showEnvironmentColumn}
+ tab={tab}
+ memberships={membershipsQuery.data}
+ membershipMutation={membershipMutation}
+ builtInByAgentId={builtInByAgentId}
+ onConfigureBuiltIn={setConfigureState}
+ />
+ ))}
+ </div>
+ )}
+
+ {effectiveView === "org" && orgTree && orgTree.length > 0 && filteredOrg.length === 0 && (
+ <p className="text-sm text-muted-foreground text-center py-8">
+ No agents match the selected status.
+ </p>
+ )}
+
+ {effectiveView === "org" && orgTree && orgTree.length === 0 && (
+ <p className="text-sm text-muted-foreground text-center py-8">
+ No organizational hierarchy defined.
+ </p>
+ )}
+ {configureState && selectedCompanyId && (
+ <Suspense fallback={null}>
+ <ConfigureBuiltInAgentModal
+ companyId={selectedCompanyId}
+ state={configureState}
+ open={configureState !== null}
+ onOpenChange={(open) => {
+ if (!open) setConfigureState(null);
+ }}
+ />
+ </Suspense>
+ )}
+ </div>
+ );
+}
+
+function OrgTreeNode({
+ node,
+ depth,
+ agentMap,
+ liveRunByAgent,
+ environmentByAgentId,
+ environmentDataLoading,
+ showEnvironment,
+ tab,
+ memberships,
+ membershipMutation,
+ builtInByAgentId,
+ onConfigureBuiltIn,
+}: {
+ node: OrgNode;
+ depth: number;
+ agentMap: Map<string, Agent>;
+ liveRunByAgent: Map<string, { runId: string; liveCount: number }>;
+ environmentByAgentId: Map<string, EnvironmentDescriptor>;
+ environmentDataLoading: boolean;
+ showEnvironment: boolean;
+ tab: FilterTab;
+ memberships: ReturnType<typeof useResourceMemberships>["data"];
+ membershipMutation: ReturnType<typeof useResourceMembershipMutation>;
+ builtInByAgentId: Map<string, BuiltInAgentState>;
+ onConfigureBuiltIn: (state: BuiltInAgentState) => void;
+}) {
+ const agent = agentMap.get(node.id);
+ const builtInState = builtInByAgentId.get(node.id);
+ const showBuiltInLifecycle = builtInState?.status === "needs_setup" || builtInState?.status === "pending_approval";
+ const hasInvalidOrgChain = Boolean(agent && agent.orgChainHealth?.status === "invalid_org_chain");
+ const membershipState = resourceMembershipState(memberships, "agent", node.id);
+ const pending = membershipMutation.isPending &&
+ membershipMutation.variables?.resourceType === "agent" &&
+ membershipMutation.variables.resourceId === node.id;
+ const starPending = pending && membershipMutation.variables?.starred !== undefined;
+ const joinLeavePending = pending && membershipMutation.variables?.starred === undefined;
+ const starred = isStarred(memberships, "agent", node.id);
+
+ return (
+ <div style={{ paddingLeft: depth * 24 }}>
+ <Link
+ to={agent ? agentUrl(agent) : `/agents/${node.id}`}
+ className={cn(
+ "group flex items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent/50 transition-colors w-full text-left no-underline text-inherit",
+ agent?.pausedAt && tab !== "paused" && "opacity-50",
+ membershipState === "left" && "sm:text-foreground/55",
+ )}
+ >
+ {hasInvalidOrgChain ? (
+ <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-amber-500" aria-label="Invalid reporting chain" />
+ ) : (
+ <AgentStatusCapsule status={node.status} />
+ )}
+ <div className="flex-1 min-w-0 flex flex-wrap items-center gap-2">
+ {/* Name floor + `truncate` keeps the primary identifier readable; the
+ cluster wraps to a second line under pressure instead of starving
+ the name at narrow widths. */}
+ <div className="min-w-(--sz-7rem) truncate">
+ <span className="text-sm font-medium">{node.name}</span>
+ <span className="text-xs text-muted-foreground ml-2">
+ {roleLabels[node.role] ?? node.role}
+ {agent?.title ? ` - ${agent.title}` : ""}
+ </span>
+ </div>
+ {builtInState && showBuiltInLifecycle && (
+ <div className="flex items-center gap-1.5 shrink-0">
+ <BuiltInLifecycleChip status={builtInState.status} />
+ {builtInState.status === "needs_setup" && (
+ <span
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <Button size="xs" variant="outline" onClick={() => onConfigureBuiltIn(builtInState)}>
+ Set up
+ </Button>
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-3 shrink-0">
+ <span className="sm:hidden">
+ {liveRunByAgent.has(node.id) ? (
+ <LiveRunIndicator
+ agentRef={agent ? agentRouteRef(agent) : node.id}
+ runId={liveRunByAgent.get(node.id)!.runId}
+ liveCount={liveRunByAgent.get(node.id)!.liveCount}
+ />
+ ) : (
+ <AgentStatusBadge status={node.status} />
+ )}
+ </span>
+ <div className="hidden sm:flex items-center gap-3">
+ {liveRunByAgent.has(node.id) && (
+ <LiveRunIndicator
+ agentRef={agent ? agentRouteRef(agent) : node.id}
+ runId={liveRunByAgent.get(node.id)!.runId}
+ liveCount={liveRunByAgent.get(node.id)!.liveCount}
+ />
+ )}
+ {agent && (
+ <div className="hidden xl:flex items-center gap-3">
+ <AgentMetaColumns
+ agent={agent}
+ environment={
+ environmentDataLoading
+ ? loadingEnvironmentDescriptor
+ : environmentByAgentId.get(agent.id) ?? localEnvironmentDescriptor
+ }
+ showEnvironment={showEnvironment}
+ />
+ </div>
+ )}
+ <span className="w-20 flex justify-end">
+ <AgentStatusBadge status={node.status} />
+ </span>
+ </div>
+ <MembershipAction
+ state={membershipState}
+ pending={joinLeavePending}
+ pendingState={joinLeavePending ? membershipMutation.variables?.state : null}
+ resourceName={node.name}
+ onJoin={() => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: node.id,
+ resourceName: node.name,
+ state: "joined",
+ })}
+ onLeave={() => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: node.id,
+ resourceName: node.name,
+ state: "left",
+ })}
+ />
+ <div className="hidden sm:flex items-center gap-3">
+ <StarToggle
+ size="row"
+ starred={starred}
+ pending={starPending}
+ resourceName={node.name}
+ onToggle={(next) => membershipMutation.mutate({
+ resourceType: "agent",
+ resourceId: node.id,
+ resourceName: node.name,
+ starred: next,
+ })}
+ />
+ </div>
+ </div>
+ </Link>
+ {node.reports && node.reports.length > 0 && (
+ <div className="border-l border-border ml-4">
+ {node.reports.map((child) => (
+ <OrgTreeNode
+ key={child.id}
+ node={child}
+ depth={depth + 1}
+ agentMap={agentMap}
+ liveRunByAgent={liveRunByAgent}
+ environmentByAgentId={environmentByAgentId}
+ environmentDataLoading={environmentDataLoading}
+ showEnvironment={showEnvironment}
+ tab={tab}
+ memberships={memberships}
+ membershipMutation={membershipMutation}
+ builtInByAgentId={builtInByAgentId}
+ onConfigureBuiltIn={onConfigureBuiltIn}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Provider/model + heartbeat columns shared by the list and org views. The
+ * model and adapter label share one fixed-width cell, each line truncating with
+ * an ellipsis so a long model id can never overlap the heartbeat column. The
+ * heartbeat is single-line (`whitespace-nowrap`) and wide enough for a full
+ * date like "Apr 30, 2026".
+ */
+function AgentMetaColumns({
+ agent,
+ environment,
+ showEnvironment,
+}: {
+ agent: Agent;
+ environment: EnvironmentDescriptor;
+ showEnvironment: boolean;
+}) {
+ const model = getConfiguredModel(agent);
+ const adapterLabel = getAdapterLabel(agent.adapterType);
+ return (
+ <>
+ <div className="w-44 min-w-0 leading-tight">
+ <div
+ className="truncate font-mono text-xs text-muted-foreground"
+ title={model ?? undefined}
+ >
+ {model ?? "—"}
+ </div>
+ <div className="truncate font-mono text-(length:--text-micro) text-muted-foreground/70" title={adapterLabel}>
+ {adapterLabel}
+ </div>
+ </div>
+ {showEnvironment && (
+ <div className="w-44 min-w-0 leading-tight">
+ <div className="truncate text-xs text-muted-foreground" title={environment.title}>
+ {environment.label}
+ </div>
+ <div className="truncate text-(length:--text-micro) text-muted-foreground/70">
+ {environment.detail}
+ </div>
+ </div>
+ )}
+ <span className="w-24 whitespace-nowrap text-right text-xs text-muted-foreground">
+ {agent.lastHeartbeatAt ? relativeTime(agent.lastHeartbeatAt) : "—"}
+ </span>
+ </>
+ );
+}
+
+function LiveRunIndicator({
+ agentRef,
+ runId,
+ liveCount,
+}: {
+ agentRef: string;
+ runId: string;
+ liveCount: number;
+}) {
+ return (
+ <Link
+ to={`/agents/${agentRef}/runs/${runId}`}
+ className="flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-blue-500/10 hover:bg-blue-500/20 transition-colors no-underline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <span className="relative flex h-2 w-2">
+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500" />
+ </span>
+ <span className="text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400">
+ Live{liveCount > 1 ? ` (${liveCount})` : ""}
+ </span>
+ </Link>
+ );
+}
diff --git a/ui/src/pages/Agents.test.tsx b/ui/src/pages/Agents.test.tsx
index 8f44fa835d..524022db9b 100644
--- a/ui/src/pages/Agents.test.tsx
+++ b/ui/src/pages/Agents.test.tsx
@@ -381,6 +381,54 @@ describe("Agents", () => {
expect(heartbeatCell?.textContent).not.toContain("\n");
});
+ it("switches between the preserved list and the interactive org chart with icon buttons", async () => {
+ root = createRoot(container);
+ await act(async () => {
+ root!.render(
+ <QueryClientProvider client={queryClient}>
+ <ToastProvider>
+ <Agents />
+ </ToastProvider>
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ const listToggle = container.querySelector<HTMLButtonElement>('button[aria-label="List view"]');
+ const orgToggle = container.querySelector<HTMLButtonElement>('button[aria-label="Org chart view"]');
+ expect(listToggle?.getAttribute("aria-pressed")).toBe("true");
+ expect(orgToggle?.getAttribute("aria-pressed")).toBe("false");
+ expect(orgToggle?.querySelector(".lucide-network")).not.toBeNull();
+ expect(orgToggle?.querySelector(".lucide-git-branch")).toBeNull();
+ expect(container.querySelector('[data-testid="org-chart-viewport"]')).toBeNull();
+
+ await act(async () => {
+ orgToggle?.click();
+ });
+ await flushReact();
+ await flushReact();
+
+ expect(mockAgentsApi.org).toHaveBeenCalledWith("company-1");
+ expect(orgToggle?.getAttribute("aria-pressed")).toBe("true");
+ const orgViewport = container.querySelector('[data-testid="org-chart-viewport"]');
+ expect(orgViewport).not.toBeNull();
+ expect(orgViewport?.parentElement?.classList.contains("flex-1")).toBe(true);
+ expect(orgViewport?.parentElement?.classList.contains("md:min-h-0")).toBe(true);
+ expect(orgViewport?.parentElement?.classList.contains("h-(--sz-calc-38)")).toBe(false);
+ expect(orgViewport?.parentElement?.parentElement?.classList.contains("h-full")).toBe(true);
+ expect(orgViewport?.parentElement?.parentElement?.classList.contains("min-h-0")).toBe(true);
+ expect(container.querySelector('[aria-label="Zoom in"]')).not.toBeNull();
+ expect(container.querySelector('[aria-label="Zoom out"]')).not.toBeNull();
+ expect(container.querySelector('[aria-label="Fit chart to screen"]')).not.toBeNull();
+
+ await act(async () => {
+ listToggle?.click();
+ });
+ await flushReact();
+ expect(container.querySelector('[data-testid="org-chart-viewport"]')).toBeNull();
+ expect(container.textContent).toContain("gpt-5.4");
+ });
+
it("gives mobile agent names the full row width after the leading status indicator", async () => {
mockSidebarState.isMobile = true;
mockResourceMembershipsApi.listMine.mockResolvedValue({
@@ -901,7 +949,7 @@ describe("Agents", () => {
await flushReact();
await flushReact();
- // Switch from the default org view to the list view.
+ // Keep the list view selected before checking its aligned metadata columns.
const listToggle = Array.from(container.querySelectorAll("button")).find(
(btn) => btn.querySelector("svg.lucide-list"),
);
@@ -938,7 +986,7 @@ describe("Agents", () => {
await flushReact();
await flushReact();
- // Org view (default).
+ // List view (default).
const orgAction = container.querySelector('[aria-label="Leave Alpha"]');
const orgStar = container.querySelector('[aria-label="Star Alpha"]');
expect(orgAction).not.toBeNull();
@@ -946,7 +994,7 @@ describe("Agents", () => {
expect(orgAction?.closest(".hidden")).toBeNull();
expect(orgStar?.closest(".hidden")).not.toBeNull();
- // List view.
+ // List view remains stable after explicitly selecting it.
const listToggle = Array.from(container.querySelectorAll("button")).find(
(btn) => btn.querySelector("svg.lucide-list"),
);
diff --git a/ui/src/pages/Agents.tsx b/ui/src/pages/Agents.tsx
index 33394acaf9..a4dbcc6660 100644
--- a/ui/src/pages/Agents.tsx
+++ b/ui/src/pages/Agents.tsx
@@ -11,6 +11,7 @@ import { useCompany } from "../context/CompanyContext";
import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useSidebar } from "../context/SidebarContext";
+import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import { queryKeys } from "../lib/queryKeys";
import { isPlatformManagedEnvironment } from "../lib/managed-sandbox-environment";
import { AgentStatusBadge, AgentStatusCapsule } from "../components/StatusBadge";
@@ -21,11 +22,12 @@ import { EntityRow } from "../components/EntityRow";
import { BuiltInLifecycleChip } from "../components/BuiltInAgentBadges";
import { EmptyState } from "../components/EmptyState";
import { PageSkeleton } from "../components/PageSkeleton";
+import { OrgChart } from "./OrgChart";
import { relativeTime, cn, agentRouteRef, agentUrl } from "../lib/utils";
import { PageTabBar } from "../components/PageTabBar";
import { Tabs } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
-import { AlertTriangle, Bot, Plus, List, GitBranch } from "lucide-react";
+import { AlertTriangle, Bot, Plus, List, Network } from "lucide-react";
import { AGENT_ROLE_LABELS, type Agent, type Environment, type EnvironmentCapabilities } from "@paperclipai/shared";
import {
isStarred,
@@ -189,18 +191,26 @@ function filterOrgTree(nodes: OrgNode[], tab: FilterTab, builtInAgentIds: Set<st
.sort((a, b) => a.name.localeCompare(b.name));
}
-export function Agents() {
+export type AgentsView = "list" | "org";
+
+export function Agents({ initialView = "list" }: { initialView?: AgentsView } = {}) {
const { selectedCompanyId } = useCompany();
const { openNewAgent } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const navigate = useNavigate();
const location = useLocation();
const { isMobile } = useSidebar();
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const pathSegment = location.pathname.split("/").pop() ?? "all";
const requestedTab: FilterTab = isFilterTab(pathSegment) ? pathSegment : "all";
- const [view, setView] = useState<"list" | "org">("org");
- const forceListView = isMobile;
- const effectiveView: "list" | "org" = forceListView ? "list" : view;
+ const [view, setView] = useState<AgentsView>(() => streamlinedUiEnabled ? initialView : "org");
+ const forceListView = !streamlinedUiEnabled && isMobile;
+ const effectiveView: AgentsView = forceListView ? "list" : view;
+
+ useEffect(() => {
+ setView(streamlinedUiEnabled ? initialView : "org");
+ }, [initialView, streamlinedUiEnabled]);
+
const { data: boardAccess } = useQuery({
queryKey: queryKeys.access.currentBoardAccess,
queryFn: () => accessApi.getCurrentBoardAccess(),
@@ -298,12 +308,6 @@ export function Agents() {
return map;
}, [runs]);
- const agentMap = useMemo(() => {
- const map = new Map<string, Agent>();
- for (const a of agents ?? []) map.set(a.id, a);
- return map;
- }, [agents]);
-
const environmentsById = useMemo(() => {
const map = new Map<string, Environment>();
for (const environment of environments ?? []) map.set(environment.id, environment);
@@ -506,7 +510,11 @@ export function Agents() {
};
return (
- <div className="space-y-4">
+ <div className={cn(
+ effectiveView === "org"
+ ? "flex h-full min-h-0 flex-col gap-4"
+ : "space-y-4",
+ )}>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Tabs value={tab} onValueChange={(v) => navigate(`/agents/${v}`)}>
<PageTabBar
@@ -516,35 +524,32 @@ export function Agents() {
/>
</Tabs>
<div className="flex items-center gap-2">
- {/* View toggle */}
- {!forceListView && (
- <div className="flex items-center border border-border" role="group" aria-label="View mode">
- <button
- className={cn(
- "p-1.5 transition-colors",
- effectiveView === "list" ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"
- )}
+ {!forceListView ? <div className="flex items-center overflow-hidden rounded-md border border-border" role="group" aria-label="Agent view">
+ <Button
+ type="button"
+ size="icon-sm"
+ variant={effectiveView === "list" ? "secondary" : "ghost"}
+ className="rounded-none"
onClick={() => setView("list")}
title="List view"
aria-label="List view"
aria-pressed={effectiveView === "list"}
>
<List className="h-3.5 w-3.5" />
- </button>
- <button
- className={cn(
- "p-1.5 transition-colors",
- effectiveView === "org" ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50"
- )}
+ </Button>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant={effectiveView === "org" ? "secondary" : "ghost"}
+ className="rounded-none border-l border-border"
onClick={() => setView("org")}
title="Org chart view"
aria-label="Org chart view"
aria-pressed={effectiveView === "org"}
>
- <GitBranch className="h-3.5 w-3.5" />
- </button>
- </div>
- )}
+ <Network className="h-3.5 w-3.5" />
+ </Button>
+ </div> : null}
<Button size="sm" variant="outline" onClick={openNewAgent}>
<Plus className="h-3.5 w-3.5 mr-1.5" />
New Agent
@@ -582,25 +587,7 @@ export function Agents() {
{/* Org chart view */}
{effectiveView === "org" && filteredOrg.length > 0 && (
- <div className="py-1">
- {filteredOrg.map((node) => (
- <OrgTreeNode
- key={node.id}
- node={node}
- depth={0}
- agentMap={agentMap}
- liveRunByAgent={liveRunByAgent}
- environmentByAgentId={environmentByAgentId}
- environmentDataLoading={environmentDataLoading}
- showEnvironment={showEnvironmentColumn}
- tab={tab}
- memberships={membershipsQuery.data}
- membershipMutation={membershipMutation}
- builtInByAgentId={builtInByAgentId}
- onConfigureBuiltIn={setConfigureState}
- />
- ))}
- </div>
+ <OrgChart embedded orgTree={filteredOrg} agents={agents ?? []} />
)}
{effectiveView === "org" && orgTree && orgTree.length > 0 && filteredOrg.length === 0 && (
diff --git a/ui/src/pages/CompanySkills.production.tsx b/ui/src/pages/CompanySkills.production.tsx
new file mode 100644
index 0000000000..0711bbddad
--- /dev/null
+++ b/ui/src/pages/CompanySkills.production.tsx
@@ -0,0 +1,5626 @@
+import { useEffect, useMemo, useRef, useState, type SVGProps } from "react";
+import { Link, useNavigate, useParams, useSearchParams } from "@/lib/router";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type {
+ AgentDesiredSkillEntry,
+ Agent,
+ CatalogSkill,
+ CatalogSkillFileDetail,
+ CatalogSkillSource,
+ CompanySkillCompatibility,
+ CompanySkillCreateRequest,
+ CompanySkillDetail,
+ CompanySkillFileDetail,
+ CompanySkillFileInventoryEntry,
+ CompanySkillListItem,
+ CompanySkillProjectScanResult,
+ CompanySkillSharingScope,
+ CompanySkillSourceBadge,
+ CompanySkillTrustLevel,
+ CompanySkillUpdateRequest,
+ CompanySkillUpdateStatus,
+ CompanySkillVersion,
+} from "@paperclipai/shared";
+import { companySkillsApi } from "../api/companySkills";
+import { foldersApi } from "../api/folders";
+import { agentsApi } from "../api/agents";
+import { useCompany } from "../context/CompanyContext";
+import { useBreadcrumbs, type Breadcrumb } from "../context/BreadcrumbContext";
+import { useToastActions } from "../context/ToastContext";
+import { queryKeys } from "../lib/queryKeys";
+import { copyTextToClipboard } from "../lib/clipboard";
+import { EmptyState } from "../components/EmptyState";
+import { MarkdownBody } from "../components/MarkdownBody";
+import { MarkdownEditor } from "../components/MarkdownEditor";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { CopyText } from "../components/CopyText";
+import { Identity } from "../components/Identity";
+import { AgentIcon } from "../components/AgentIconPicker";
+import { AgentMultiSelect } from "../components/AgentMultiSelect";
+import { useAdapterCapabilities } from "../adapters/use-adapter-capabilities";
+import {
+ SkillPolicyDenialNotice,
+ useSkillPolicyDenial,
+} from "@/components/skill-studio/SkillPolicySurfaces";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { buildLineDiff, type DiffRow } from "../lib/line-diff";
+import { cn, relativeTime } from "../lib/utils";
+import { resolveSkillSummaryText } from "../lib/company-skill-summary";
+import {
+ parseSkillRoute,
+ skillRoute,
+ skillStudioNewRoute,
+ skillStudioRoute,
+ withRouteSkill,
+ resolveSkillRouteToken,
+ type CompanySkillRouteSubject,
+} from "../lib/company-skill-routes";
+import {
+ SKILL_CREATE_ACCENTS,
+ buildBlankSkillDraft,
+ buildForkSkillDraft,
+ defaultSkillMarkdown,
+ normalizeSkillDraftSlug,
+ skillAccentColor,
+ skillCreateDraftToPayload,
+ splitCategoryDraft,
+ type SkillCreateDraft,
+} from "../lib/skill-create";
+import { SkillCardIcon } from "../components/SkillCardIcon";
+import { ImportSkillsFromProjectDialog } from "./skills/ImportSkillsFromProjectDialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import { Badge } from "@/components/ui/badge";
+import {
+ AllUnfiledBanner,
+ BulkBar,
+ DeleteFolderDialog,
+ FolderChip,
+ FolderFormDialog,
+ FolderSwatch,
+ MobileFolderSheet,
+ MoveToMenu,
+ folderSearchValue,
+ normalizeFolderSelection,
+ type FolderSelection,
+} from "../components/folders/FolderControls";
+import {
+ FolderBreadcrumb,
+ MoveToFolderDialog,
+ SkillFolderRail,
+ folderBreadcrumbTrail,
+ reservedRootLabel,
+ isBundledFolder,
+ skillFolderDisplayPath,
+ skillFolderPathDisplayFallback,
+ subtreeFolderIds,
+ treeFromResult,
+} from "../components/folders/SkillFolderTree";
+import {
+ AlertTriangle,
+ ArrowUpCircle,
+ Boxes,
+ Check,
+ ChevronDown,
+ ChevronLeft,
+ ChevronRight,
+ Code2,
+ Download,
+ Eye,
+ Filter,
+ FileCode2,
+ FileText,
+ Folder,
+ FolderInput,
+ FolderOpen,
+ FolderSearch,
+ GitFork,
+ Globe,
+ HelpCircle,
+ LayoutGrid,
+ Link2,
+ Lock,
+ ExternalLink,
+ FlaskConical,
+ MoreHorizontal,
+ Paperclip,
+ Pause,
+ Pencil,
+ Pin,
+ Plus,
+ Copy,
+ RefreshCw,
+ Save,
+ Search,
+ Settings,
+ ShieldCheck,
+ Star,
+ Trash2,
+ Users,
+ Hash,
+ History,
+ X,
+ XOctagon,
+} from "lucide-react";
+import { GithubIcon } from "../components/icons/github-icon";
+import type { FolderListItem, FolderListResult } from "@paperclipai/shared";
+
+type SkillTreeNode = {
+ name: string;
+ path: string | null;
+ kind: "dir" | "file";
+ fileKind?: CompanySkillFileInventoryEntry["kind"];
+ children: SkillTreeNode[];
+};
+
+const SKILL_TREE_BASE_INDENT = 16;
+const SKILL_TREE_STEP_INDENT = 24;
+const SKILL_TREE_ROW_HEIGHT_CLASS = "min-h-9";
+
+function VercelMark(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
+ <path d="M12 4 21 19H3z" />
+ </svg>
+ );
+}
+
+function stripFrontmatter(markdown: string) {
+ const normalized = markdown.replace(/\r\n/g, "\n");
+ if (!normalized.startsWith("---\n")) return normalized.trim();
+ const closing = normalized.indexOf("\n---\n", 4);
+ if (closing < 0) return normalized.trim();
+ return normalized.slice(closing + 5).trim();
+}
+
+function splitFrontmatter(markdown: string): { frontmatter: string | null; body: string } {
+ const normalized = markdown.replace(/\r\n/g, "\n");
+ if (!normalized.startsWith("---\n")) {
+ return { frontmatter: null, body: normalized };
+ }
+ const closing = normalized.indexOf("\n---\n", 4);
+ if (closing < 0) {
+ return { frontmatter: null, body: normalized };
+ }
+ return {
+ frontmatter: normalized.slice(4, closing).trim(),
+ body: normalized.slice(closing + 5).trimStart(),
+ };
+}
+
+function mergeFrontmatter(markdown: string, body: string) {
+ const parsed = splitFrontmatter(markdown);
+ if (!parsed.frontmatter) return body;
+ return ["---", parsed.frontmatter, "---", "", body].join("\n");
+}
+
+function buildTree(entries: CompanySkillFileInventoryEntry[]) {
+ const root: SkillTreeNode = { name: "", path: null, kind: "dir", children: [] };
+
+ for (const entry of entries) {
+ const segments = entry.path.split("/").filter(Boolean);
+ let current = root;
+ let currentPath = "";
+ for (const [index, segment] of segments.entries()) {
+ currentPath = currentPath ? `${currentPath}/${segment}` : segment;
+ const isLeaf = index === segments.length - 1;
+ let next = current.children.find((child) => child.name === segment);
+ if (!next) {
+ next = {
+ name: segment,
+ path: isLeaf ? entry.path : currentPath,
+ kind: isLeaf ? "file" : "dir",
+ fileKind: isLeaf ? entry.kind : undefined,
+ children: [],
+ };
+ current.children.push(next);
+ }
+ current = next;
+ }
+ }
+
+ function sortNode(node: SkillTreeNode) {
+ node.children.sort((left, right) => {
+ if (left.kind !== right.kind) return left.kind === "dir" ? -1 : 1;
+ if (left.name === "SKILL.md") return -1;
+ if (right.name === "SKILL.md") return 1;
+ return left.name.localeCompare(right.name);
+ });
+ node.children.forEach(sortNode);
+ }
+
+ sortNode(root);
+ return root.children;
+}
+
+function sourceMeta(sourceBadge: CompanySkillSourceBadge, sourceLabel: string | null) {
+ const normalizedLabel = sourceLabel?.toLowerCase() ?? "";
+ const isSkillsShManaged =
+ normalizedLabel.includes("skills.sh") || normalizedLabel.includes("vercel-labs/skills");
+
+ switch (sourceBadge) {
+ case "skills_sh":
+ return { icon: VercelMark, label: sourceLabel ?? "skills.sh", managedLabel: "skills.sh managed" };
+ case "github":
+ return isSkillsShManaged
+ ? { icon: VercelMark, label: sourceLabel ?? "skills.sh", managedLabel: "skills.sh managed" }
+ : { icon: GithubIcon, label: sourceLabel ?? "GitHub", managedLabel: "GitHub managed" };
+ case "url":
+ return { icon: Link2, label: sourceLabel ?? "URL", managedLabel: "URL managed" };
+ case "local":
+ return { icon: Folder, label: sourceLabel ?? "Folder", managedLabel: "Folder managed" };
+ case "paperclip":
+ return { icon: Paperclip, label: sourceLabel ?? "Paperclip", managedLabel: "Paperclip managed" };
+ default:
+ return { icon: Boxes, label: sourceLabel ?? "Catalog", managedLabel: "Catalog managed" };
+ }
+}
+
+function shortRef(ref: string | null | undefined) {
+ if (!ref) return null;
+ return ref.slice(0, 7);
+}
+
+function middleTruncate(value: string, maxLength = 72) {
+ if (value.length <= maxLength) return value;
+ const edgeLength = Math.floor((maxLength - 3) / 2);
+ return `${value.slice(0, edgeLength)}...${value.slice(value.length - edgeLength)}`;
+}
+
+function formatProjectScanSummary(result: CompanySkillProjectScanResult) {
+ const parts = [
+ `${result.discovered} found`,
+ `${result.imported.length} imported`,
+ `${result.updated.length} updated`,
+ ];
+ if (result.conflicts.length > 0) parts.push(`${result.conflicts.length} conflicts`);
+ if (result.skipped.length > 0) parts.push(`${result.skipped.length} skipped`);
+ return `${parts.join(", ")} across ${result.scannedWorkspaces} workspace${result.scannedWorkspaces === 1 ? "" : "s"}.`;
+}
+
+function fileIcon(kind: CompanySkillFileInventoryEntry["kind"]) {
+ if (kind === "script" || kind === "reference") return FileCode2;
+ return FileText;
+}
+
+function catalogSkillRoute(catalogRef: string) {
+ return `/skills?view=catalog&catalog=${encodeURIComponent(catalogRef)}`;
+}
+
+function parentDirectoryPaths(filePath: string) {
+ const segments = filePath.split("/").filter(Boolean);
+ const parents: string[] = [];
+ for (let index = 0; index < segments.length - 1; index += 1) {
+ parents.push(segments.slice(0, index + 1).join("/"));
+ }
+ return parents;
+}
+
+type SourceFilter = "all" | "company" | "bundled" | "optional" | "external";
+
+const SOURCE_FILTER_LABELS: Record<SourceFilter, string> = {
+ all: "All",
+ company: "Company",
+ bundled: "Bundled",
+ optional: "Optional",
+ external: "External",
+};
+
+function readonlyMetadataValue(metadata: Record<string, unknown> | null | undefined, key: string): string | null {
+ if (!metadata || typeof metadata !== "object") return null;
+ const raw = (metadata as Record<string, unknown>)[key];
+ if (typeof raw !== "string") return null;
+ const trimmed = raw.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function readonlyMetadataKind(metadata: Record<string, unknown> | null | undefined): "bundled" | "optional" | null {
+ const value = readonlyMetadataValue(metadata, "sourceKind") ?? readonlyMetadataValue(metadata, "catalogKind");
+ if (value === "bundled") return "bundled";
+ if (value === "optional") return "optional";
+ return null;
+}
+
+function classifySource(skill: {
+ sourceBadge: CompanySkillSourceBadge;
+ sourceType: string;
+ catalogKind?: "bundled" | "optional" | null;
+ metadata?: Record<string, unknown> | null;
+}): SourceFilter {
+ if (skill.sourceBadge === "paperclip") return "company";
+ if (skill.sourceType === "local_path" && !skill.sourceBadge.toString().includes("github")) {
+ return "company";
+ }
+ if (skill.sourceType === "catalog" || skill.sourceBadge === "catalog") {
+ const kind = skill.catalogKind ?? readonlyMetadataKind(skill.metadata);
+ if (kind === "bundled") return "bundled";
+ if (kind === "optional") return "optional";
+ return "company";
+ }
+ if (skill.sourceBadge === "github" || skill.sourceBadge === "skills_sh" || skill.sourceBadge === "url" || skill.sourceBadge === "local") {
+ return "external";
+ }
+ return "company";
+}
+
+function SourceFilterMenu({
+ counts,
+ value,
+ onChange,
+}: {
+ counts: Record<SourceFilter, number>;
+ value: SourceFilter;
+ onChange: (next: SourceFilter) => void;
+}) {
+ const filters: SourceFilter[] = ["all", "company", "bundled", "optional", "external"];
+ const activeFilterCount = value === "all" ? 0 : 1;
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={cn("relative shrink-0", activeFilterCount > 0 && "text-blue-600 dark:text-blue-400")}
+ title={activeFilterCount > 0 ? `Filters: ${activeFilterCount}` : "Filter"}
+ >
+ <Filter className="h-3.5 w-3.5" />
+ {activeFilterCount > 0 ? (
+ <span className="absolute -right-0.5 -top-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-blue-600 text-(length:--text-nano) font-bold text-white">
+ {activeFilterCount}
+ </span>
+ ) : null}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-48">
+ <DropdownMenuLabel>Source</DropdownMenuLabel>
+ <DropdownMenuRadioGroup value={value} onValueChange={(next) => onChange(next as SourceFilter)}>
+ {filters.map((filter) => (
+ <DropdownMenuRadioItem key={filter} value={filter}>
+ <span>{SOURCE_FILTER_LABELS[filter]}</span>
+ <span className="ml-auto text-xs text-muted-foreground">{counts[filter] ?? 0}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function CatalogFilterMenu({
+ kindFilter,
+ categoryFilter,
+ categories,
+ onKindChange,
+ onCategoryChange,
+}: {
+ kindFilter: "all" | "bundled" | "optional";
+ categoryFilter: string;
+ categories: string[];
+ onKindChange: (next: "all" | "bundled" | "optional") => void;
+ onCategoryChange: (next: string) => void;
+}) {
+ const activeFilterCount = (kindFilter === "all" ? 0 : 1) + (categoryFilter ? 1 : 0);
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={cn("relative shrink-0", activeFilterCount > 0 && "text-blue-600 dark:text-blue-400")}
+ title={activeFilterCount > 0 ? `Filters: ${activeFilterCount}` : "Filter"}
+ >
+ <Filter className="h-3.5 w-3.5" />
+ {activeFilterCount > 0 ? (
+ <span className="absolute -right-0.5 -top-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-blue-600 text-(length:--text-nano) font-bold text-white">
+ {activeFilterCount}
+ </span>
+ ) : null}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="max-h-(--sz-calc-32) w-56 overflow-y-auto">
+ <DropdownMenuLabel>Type</DropdownMenuLabel>
+ <DropdownMenuRadioGroup value={kindFilter} onValueChange={(next) => onKindChange(next as "all" | "bundled" | "optional")}>
+ <DropdownMenuRadioItem value="all">All</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="bundled">Bundled</DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="optional">Optional</DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel>Category</DropdownMenuLabel>
+ <DropdownMenuRadioGroup value={categoryFilter || "__all__"} onValueChange={(next) => onCategoryChange(next === "__all__" ? "" : next)}>
+ <DropdownMenuRadioItem value="__all__">All categories</DropdownMenuRadioItem>
+ {categories.map((category) => (
+ <DropdownMenuRadioItem key={category} value={category}>
+ {category}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function TrustChip({ level }: { level: CompanySkillTrustLevel }) {
+ const map = {
+ markdown_only: {
+ icon: ShieldCheck,
+ label: "Markdown only",
+ tooltip: "Text only — no scripts, no binaries, no assets.",
+ className: "border-border bg-muted/40 text-muted-foreground",
+ },
+ assets: {
+ icon: Folder,
+ label: "Includes assets",
+ tooltip: "Ships images, fonts, or other non-script files.",
+ className: "border-cyan-500/30 bg-cyan-500/10 text-cyan-800 dark:text-cyan-200",
+ },
+ scripts_executables: {
+ icon: AlertTriangle,
+ label: "Includes scripts",
+ tooltip: "Ships executable scripts. Review before installing.",
+ className: "border-amber-500/40 bg-amber-500/10 text-amber-800 dark:text-amber-200",
+ },
+ } as const;
+ const config = map[level] ?? map.markdown_only;
+ const Icon = config.icon;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="outline" className={cn("text-(length:--text-micro)", config.className)}>
+ <Icon className="h-3 w-3" aria-hidden="true" />
+ {config.label}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{config.tooltip}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+function CompatChip({ compatibility }: { compatibility: CompanySkillCompatibility }) {
+ if (compatibility === "compatible") return null;
+ const map = {
+ unknown: {
+ icon: HelpCircle,
+ label: "Unknown format",
+ tooltip: "Paperclip could not validate this skill as Agent Skills markdown. Install at your own risk.",
+ className: "border-yellow-500/40 bg-yellow-500/10 text-yellow-800 dark:text-yellow-200",
+ },
+ invalid: {
+ icon: XOctagon,
+ label: "Invalid",
+ tooltip: "This skill cannot be installed — content is not valid Agent Skills markdown.",
+ className: "border-destructive/40 bg-destructive/10 text-destructive",
+ },
+ } as const;
+ const config = map[compatibility];
+ const Icon = config.icon;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="outline" className={cn("text-(length:--text-micro)", config.className)}>
+ <Icon className="h-3 w-3" aria-hidden="true" />
+ {config.label}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>{config.tooltip}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+function ProvenanceBadge({ packageName, packageVersion }: { packageName: string | null; packageVersion: string | null }) {
+ if (!packageName) return null;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1 rounded border border-border bg-muted/30 px-1.5 py-0.5 font-mono text-(length:--text-nano) text-muted-foreground">
+ <Boxes className="h-3 w-3" aria-hidden="true" />
+ <span>{packageName}{packageVersion ? ` v${packageVersion}` : ""}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Installed from the app-shipped skills catalog. Provenance is signed by package version and content hash.</TooltipContent>
+ </Tooltip>
+ );
+}
+
+function formatBytes(bytes: number) {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+// ---------------------------------------------------------------------------
+// Skills Store discovery grid (PAP-10879)
+// ---------------------------------------------------------------------------
+
+export type DiscoveryTab = "all" | "installed" | "catalog" | "bundled";
+
+const DISCOVERY_TABS: DiscoveryTab[] = ["all", "installed", "catalog", "bundled"];
+
+export function resolveDiscoveryTab(tabParam: string | null): DiscoveryTab {
+ return DISCOVERY_TABS.includes(tabParam as DiscoveryTab)
+ ? (tabParam as DiscoveryTab)
+ : "installed";
+}
+
+export function withDiscoveryTab(current: URLSearchParams, tab: DiscoveryTab): URLSearchParams {
+ const params = new URLSearchParams(current);
+ if (tab === "installed") params.delete("tab");
+ else params.set("tab", tab);
+ params.delete("category");
+ if (tab !== "installed") params.delete("folder");
+ return params;
+}
+
+export function skillDetailBreadcrumbs(
+ detail: Pick<CompanySkillDetail, "name" | "folderId">,
+ folderResult: FolderListResult | null | undefined,
+): Breadcrumb[] {
+ const trail = detail.folderId
+ ? folderBreadcrumbTrail(treeFromResult(folderResult), detail.folderId)
+ : [];
+ return [
+ { label: "Skills", href: "/skills" },
+ ...trail.map((folder, index) => ({
+ label: index === 0 ? reservedRootLabel(folder) : folder.name,
+ href: `/skills?folder=${encodeURIComponent(folder.id)}`,
+ })),
+ { label: detail.name },
+ ];
+}
+
+type DiscoverySort = "agents" | "stars" | "forks" | "recent" | "alphabetical";
+
+const DISCOVERY_SORT_LABELS: Record<DiscoverySort, string> = {
+ agents: "Most agents",
+ stars: "Most stars",
+ forks: "Most forks",
+ recent: "Recently updated",
+ alphabetical: "Alphabetical",
+};
+const DISCOVERY_SORTS: DiscoverySort[] = ["agents", "stars", "forks", "recent", "alphabetical"];
+
+export type DiscoveryCard = {
+ key: string;
+ skillId: string | null;
+ folderId?: string | null;
+ catalogRef: string | null;
+ name: string;
+ slug: string;
+ author: string;
+ version: string | null;
+ tagline: string | null;
+ description: string | null;
+ categories: string[];
+ iconUrl: string | null;
+ color: string | null;
+ starCount: number;
+ agentCount: number;
+ forkCount: number;
+ installed: boolean;
+ required: boolean;
+ forkedFrom: boolean;
+ updatedAt: number;
+ sourceBadge?: CompanySkillSourceBadge | null;
+ sourceLabel?: string | null;
+};
+
+export { SkillCardIcon } from "../components/SkillCardIcon";
+
+function discoveryVersionLabel(skill: {
+ packageVersion: string | null;
+ sourceRef: string | null;
+}, required: boolean): string | null {
+ if (skill.packageVersion) return `v${skill.packageVersion}`;
+ if (required) return "core";
+ if (skill.sourceRef) return shortRef(skill.sourceRef);
+ return null;
+}
+
+function uniqueCategories(values: (string | null | undefined)[]): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const value of values) {
+ const slug = value?.trim();
+ if (!slug || seen.has(slug)) continue;
+ seen.add(slug);
+ out.push(slug);
+ }
+ return out;
+}
+
+function categorySetKey(categories: string[]) {
+ return [...categories].sort().join(",");
+}
+
+function skillSettingsToastBody(skill: Pick<CompanySkillDetail, "categories" | "sharingScope">) {
+ const sharing = skill.sharingScope === "private" ? "Sharing: private" : "Sharing: company";
+ const categories = skill.categories.length ? `Categories: ${skill.categories.join(", ")}` : "Categories: none";
+ return `${sharing} | ${categories}`;
+}
+
+// Merge installed company skills and the install catalog into one card model.
+// Installed skills win on dedup (they carry the richer social-proof metadata);
+// catalog-only skills fill in the rest of the discoverable surface.
+function buildDiscoveryCards(
+ installed: CompanySkillListItem[],
+ catalog: CatalogSkill[],
+): DiscoveryCard[] {
+ const catalogByKey = new Map(catalog.map((entry) => [entry.key, entry]));
+ const cards: DiscoveryCard[] = [];
+ const installedKeys = new Set<string>();
+
+ for (const skill of installed) {
+ installedKeys.add(skill.key);
+ const catalogMatch = catalogByKey.get(skill.key) ?? null;
+ const required = skill.catalogKind === "bundled" || catalogMatch?.kind === "bundled";
+ cards.push({
+ key: skill.key,
+ skillId: skill.id,
+ folderId: skill.folderId ?? null,
+ catalogRef: catalogMatch ? catalogMatch.id : null,
+ name: skill.name,
+ slug: skill.slug,
+ author: skill.authorName ?? skill.sourceLabel ?? "you",
+ version: discoveryVersionLabel(skill, required),
+ tagline: skill.tagline ?? null,
+ description: skill.description ?? null,
+ categories: uniqueCategories([...(skill.categories ?? []), catalogMatch?.category]),
+ iconUrl: skill.iconUrl,
+ color: skill.color,
+ starCount: skill.starCount ?? 0,
+ agentCount: skill.attachedAgentCount ?? 0,
+ forkCount: skill.forkCount ?? 0,
+ installed: true,
+ required,
+ forkedFrom: Boolean(skill.forkedFromSkillId),
+ updatedAt: new Date(skill.updatedAt).getTime() || 0,
+ sourceBadge: skill.sourceBadge,
+ sourceLabel: skill.sourceLabel,
+ });
+ }
+
+ for (const entry of catalog) {
+ if (installedKeys.has(entry.key)) continue;
+ const required = entry.kind === "bundled";
+ cards.push({
+ key: entry.key,
+ skillId: null,
+ folderId: null,
+ catalogRef: entry.id,
+ name: entry.name,
+ slug: entry.slug,
+ author: entry.packageName ?? "Paperclip",
+ version: discoveryVersionLabel({ packageVersion: entry.packageVersion ?? null, sourceRef: null }, required),
+ tagline: null,
+ description: entry.description,
+ categories: uniqueCategories([entry.category, ...(entry.tags ?? [])]),
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: false,
+ required,
+ forkedFrom: false,
+ updatedAt: 0,
+ sourceBadge: "catalog",
+ sourceLabel: entry.packageName ?? "Catalog",
+ });
+ }
+
+ return cards;
+}
+
+function cardsForTab(cards: DiscoveryCard[], tab: DiscoveryTab): DiscoveryCard[] {
+ switch (tab) {
+ case "installed":
+ return cards.filter((card) => card.installed);
+ case "catalog":
+ return cards.filter((card) => card.catalogRef != null);
+ case "bundled":
+ return cards.filter((card) => card.required);
+ case "all":
+ default:
+ return cards;
+ }
+}
+
+function sortDiscoveryCards(cards: DiscoveryCard[], sort: DiscoverySort, demoteRequired: boolean): DiscoveryCard[] {
+ const byName = (a: DiscoveryCard, b: DiscoveryCard) => a.name.localeCompare(b.name);
+ const sorted = [...cards].sort((a, b) => {
+ // Bundled/required skills are demoted out of discovery rankings (except on
+ // the Bundled tab, where they are the whole point).
+ if (demoteRequired && a.required !== b.required) return a.required ? 1 : -1;
+ switch (sort) {
+ case "stars":
+ return b.starCount - a.starCount || byName(a, b);
+ case "forks":
+ return b.forkCount - a.forkCount || byName(a, b);
+ case "recent":
+ return b.updatedAt - a.updatedAt || byName(a, b);
+ case "alphabetical":
+ return byName(a, b);
+ case "agents":
+ default:
+ return b.agentCount - a.agentCount || byName(a, b);
+ }
+ });
+ return sorted;
+}
+
+function discoveryMatchesSearch(card: DiscoveryCard, query: string): boolean {
+ if (!query) return true;
+ const haystack = [
+ card.name,
+ card.slug,
+ card.author,
+ card.tagline ?? "",
+ card.description ?? "",
+ card.categories.join(" "),
+ ].join(" ").toLowerCase();
+ return haystack.includes(query.toLowerCase());
+}
+
+function SkillStat({ icon: Icon, value }: { icon: typeof Star; value: string }) {
+ return (
+ <span className="inline-flex items-center gap-1">
+ <Icon className="h-3 w-3" aria-hidden="true" />
+ {value}
+ </span>
+ );
+}
+
+function SkillCategoryChip({ label }: { label: string }) {
+ return (
+ <Badge variant="outline" className="border-border bg-muted/40 text-(length:--text-nano) capitalize text-muted-foreground">
+ {label}
+ </Badge>
+ );
+}
+
+function SkillCard({
+ card,
+ folders,
+ selected = false,
+ selectMode = false,
+ showFolderBadge = false,
+ onOpen,
+ onSelectChange,
+ onMove,
+ onCreateFolderAndMove,
+ onOpenMove,
+}: {
+ card: DiscoveryCard;
+ folders?: FolderListItem[];
+ selected?: boolean;
+ selectMode?: boolean;
+ /** Show the card's folder so search results reveal where an item lives (user story 5). */
+ showFolderBadge?: boolean;
+ onOpen: (card: DiscoveryCard) => void;
+ onSelectChange?: (card: DiscoveryCard, selected: boolean) => void;
+ onMove?: (card: DiscoveryCard, folderId: string | null) => void;
+ onCreateFolderAndMove?: (card: DiscoveryCard) => void;
+ onOpenMove?: (card: DiscoveryCard) => void;
+}) {
+ const badgeFolder = showFolderBadge && card.installed
+ ? (card.folderId ? folders?.find((folder) => folder.id === card.folderId) ?? null : null)
+ : undefined;
+ const cardFolder = card.folderId ? folders?.find((folder) => folder.id === card.folderId) ?? null : null;
+ const canMove = card.installed
+ && !card.required
+ && !(cardFolder && isBundledFolder(cardFolder));
+ return (
+ <div
+ onClick={() => onOpen(card)}
+ onKeyDown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onOpen(card);
+ }
+ }}
+ role="button"
+ tabIndex={0}
+ className={cn(
+ // Quiet interactive-card affordance (DECISION-SHEET: one recipe for
+ // clickable cards): pointer cursor, border darkens, slight lift.
+ "group flex h-full min-h-(--sz-11_5rem) flex-col rounded-lg border border-border bg-card p-4 text-left cursor-pointer transition-colors hover:border-foreground/20 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ card.required && "bg-muted/30",
+ )}
+ >
+ <div className="flex items-start gap-3">
+ {selectMode && canMove ? (
+ <input
+ type="checkbox"
+ className="mt-1 h-4 w-4 rounded border-border"
+ checked={selected}
+ aria-label={`Select ${card.name}`}
+ onClick={(event) => event.stopPropagation()}
+ onChange={(event) => onSelectChange?.(card, event.target.checked)}
+ />
+ ) : null}
+ <SkillCardIcon card={card} />
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-mono text-sm font-medium text-foreground">{card.name}</div>
+ <div className="truncate text-xs text-muted-foreground">
+ by {card.author}{card.version ? ` · ${card.version}` : ""}
+ </div>
+ {badgeFolder !== undefined ? (
+ <div className="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
+ <FolderSwatch color={badgeFolder?.color} className="h-2 w-2" />
+ <span className="truncate">{badgeFolder ? badgeFolder.name : "Unfiled"}</span>
+ </div>
+ ) : null}
+ </div>
+ {/* Where the skill came from (PAP-10907 E); native title gives a hover hint. */}
+ {(() => {
+ const meta = sourceMeta(card.sourceBadge ?? "catalog", card.sourceLabel ?? null);
+ const SourceIcon = meta.icon;
+ return (
+ <span className="shrink-0 text-muted-foreground" title={`From ${meta.label}`} aria-label={`From ${meta.label}`}>
+ <SourceIcon className="h-3.5 w-3.5" aria-hidden="true" />
+ </span>
+ );
+ })()}
+ {canMove && folders && onMove && onCreateFolderAndMove ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="-mr-1 -mt-1 opacity-70 group-hover:opacity-100"
+ aria-label={`More actions for ${card.name}`}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" onClick={(event) => event.stopPropagation()}>
+ {onOpenMove ? (
+ <>
+ <DropdownMenuItem onSelect={() => onOpenMove(card)}>
+ <FolderInput className="h-3.5 w-3.5" />
+ Move to folder…
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ ) : null}
+ <MoveToMenu
+ folders={folders}
+ currentFolderId={card.folderId}
+ onMove={(folderId) => onMove(card, folderId)}
+ onCreateAndMove={() => onCreateFolderAndMove(card)}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ </div>
+
+ {card.forkedFrom ? (
+ <div className="mt-2 inline-flex items-center gap-1 text-(length:--text-micro) text-muted-foreground">
+ <GitFork className="h-3 w-3" aria-hidden="true" />
+ Forked
+ </div>
+ ) : null}
+
+ {/* Always reserve two lines so cards line up even without a description. */}
+ <p className="mt-2 line-clamp-2 min-h-8 text-xs text-muted-foreground">
+ {resolveSkillSummaryText({
+ tagline: card.tagline,
+ description: card.description,
+ key: card.key,
+ name: card.name,
+ }) ?? ""}
+ </p>
+
+ <div className="mt-auto pt-3">
+ {/* Stats: installed agents · stars · forks — stars/forks only when > 0. */}
+ <div className="flex items-center gap-2 text-(length:--text-micro) text-muted-foreground">
+ <span>{card.agentCount} {card.agentCount === 1 ? "agent" : "agents"}</span>
+ {card.starCount > 0 ? (
+ <>
+ <span aria-hidden="true">·</span>
+ <SkillStat icon={Star} value={String(card.starCount)} />
+ </>
+ ) : null}
+ {card.forkCount > 0 ? (
+ <>
+ <span aria-hidden="true">·</span>
+ <SkillStat icon={GitFork} value={String(card.forkCount)} />
+ </>
+ ) : null}
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-1">
+ {card.installed ? (
+ <Badge variant="outline" className="border-emerald-500/30 bg-emerald-500/10 text-(length:--text-nano) text-emerald-700 dark:text-emerald-300">
+ Installed
+ </Badge>
+ ) : null}
+ {card.categories.slice(0, 2).map((category) => (
+ <SkillCategoryChip key={category} label={category} />
+ ))}
+ {card.required ? (
+ <Badge variant="outline" className="ml-auto border-border bg-muted/60 text-(length:--text-nano) text-muted-foreground">
+ <Lock className="h-3 w-3" aria-hidden="true" />
+ Bundled
+ </Badge>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export type DiscoveryCategory = { slug: string; count: number };
+
+function CategoryNav({
+ categories,
+ total,
+ active,
+ onSelect,
+}: {
+ categories: DiscoveryCategory[];
+ total: number;
+ active: string | null;
+ onSelect: (slug: string | null) => void;
+}) {
+ return (
+ <nav className="flex flex-col gap-0.5 px-2">
+ <button
+ type="button"
+ onClick={() => onSelect(null)}
+ className={cn(
+ "flex items-center justify-between rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-accent/40",
+ active == null ? "bg-accent/60 font-medium text-foreground" : "text-muted-foreground",
+ )}
+ >
+ <span>All</span>
+ <span className="text-xs text-muted-foreground">{total}</span>
+ </button>
+ {categories.map((category) => (
+ <button
+ key={category.slug}
+ type="button"
+ onClick={() => onSelect(category.slug)}
+ className={cn(
+ "flex items-center justify-between rounded-md px-2 py-1.5 text-sm capitalize transition-colors hover:bg-accent/40",
+ active === category.slug ? "bg-accent/60 font-medium text-foreground" : "text-muted-foreground",
+ )}
+ >
+ <span className="truncate">{category.slug}</span>
+ <span className="ml-2 shrink-0 text-xs text-muted-foreground">{category.count}</span>
+ </button>
+ ))}
+ </nav>
+ );
+}
+
+export function DiscoveryGrid({
+ tab,
+ tabCounts,
+ onTabChange,
+ categories,
+ categoryTotal,
+ activeCategory,
+ onCategoryChange,
+ search,
+ onSearchChange,
+ sort,
+ onSortChange,
+ cards,
+ onOpenCard,
+ loading,
+ error,
+ totalCount,
+ onCreate,
+ onImport,
+ onImportFromProject,
+ onBrowseCatalog,
+ onScan,
+ scanPending,
+ scanStatus,
+ folderResult,
+ folderSelection = "all",
+ foldersLoading = false,
+ selectMode = false,
+ selectedSkillIds = [],
+ onFolderSelect,
+ onCreateFolder,
+ onRenameFolder,
+ onEditFolder,
+ onMoveFolder,
+ onDeleteFolder,
+ onToggleSelectMode,
+ onSelectCard,
+ onMoveCard,
+ onCreateFolderAndMoveCard,
+ onMoveSelected,
+ onCreateFolderAndMoveSelected,
+ onClearSelected,
+ onOpenMobileFolders,
+ onCreateFolderIn,
+ onEnsureMyFolder,
+ onOpenMoveCard,
+ folderNudgeStorageKey,
+}: {
+ tab: DiscoveryTab;
+ tabCounts: Record<DiscoveryTab, number>;
+ onTabChange: (tab: DiscoveryTab) => void;
+ categories: DiscoveryCategory[];
+ categoryTotal: number;
+ activeCategory: string | null;
+ onCategoryChange: (slug: string | null) => void;
+ search: string;
+ onSearchChange: (value: string) => void;
+ sort: DiscoverySort;
+ onSortChange: (sort: DiscoverySort) => void;
+ cards: DiscoveryCard[];
+ onOpenCard: (card: DiscoveryCard) => void;
+ loading: boolean;
+ error: string | null;
+ totalCount: number;
+ onCreate: () => void;
+ onImport: () => void;
+ onImportFromProject: () => void;
+ onBrowseCatalog: () => void;
+ onScan: (projectId?: string) => void;
+ scanPending: boolean;
+ scanStatus: string | null;
+ folderResult?: FolderListResult | null;
+ folderSelection?: FolderSelection;
+ foldersLoading?: boolean;
+ selectMode?: boolean;
+ selectedSkillIds?: string[];
+ onFolderSelect?: (selection: FolderSelection) => void;
+ onCreateFolder?: () => void;
+ onRenameFolder?: (folder: FolderListItem, name: string) => void;
+ onEditFolder?: (folder: FolderListItem) => void;
+ onMoveFolder?: (folder: FolderListItem, destination: "my" | "company") => void;
+ onDeleteFolder?: (folder: FolderListItem) => void;
+ onToggleSelectMode?: () => void;
+ onSelectCard?: (card: DiscoveryCard, selected: boolean) => void;
+ onMoveCard?: (card: DiscoveryCard, folderId: string | null) => void;
+ onCreateFolderAndMoveCard?: (card: DiscoveryCard) => void;
+ onMoveSelected?: (folderId: string | null) => void;
+ onCreateFolderAndMoveSelected?: () => void;
+ onClearSelected?: () => void;
+ onOpenMobileFolders?: () => void;
+ /** Create a folder under `parentId` (null = top level), used by the tree rail. */
+ onCreateFolderIn?: (parentId: string | null) => void;
+ /** Provision the caller's personal "My Skills" root on demand. */
+ onEnsureMyFolder?: () => void;
+ /** Open the rich move-to-folder dialog for a single card. */
+ onOpenMoveCard?: (card: DiscoveryCard) => void;
+ /** When set and no folders exist yet, show the dismissible all-unfiled nudge (ux-spec §6.3). */
+ folderNudgeStorageKey?: string;
+}) {
+ // Source filter (github / skills.sh / local / …) lives in the grid so it
+ // narrows whatever the parent already filtered by tab/category/search (PAP-10907 E).
+ const [sourceBadgeFilter, setSourceBadgeFilter] = useState<string>("all");
+ const availableSources = useMemo(() => {
+ const set = new Set<string>();
+ for (const card of cards) if (card.sourceBadge) set.add(card.sourceBadge);
+ return Array.from(set).sort();
+ }, [cards]);
+ useEffect(() => {
+ if (sourceBadgeFilter !== "all" && !availableSources.includes(sourceBadgeFilter)) {
+ setSourceBadgeFilter("all");
+ }
+ }, [availableSources, sourceBadgeFilter]);
+ const sourceFilteredCards = useMemo(
+ () => (sourceBadgeFilter === "all" ? cards : cards.filter((card) => card.sourceBadge === sourceBadgeFilter)),
+ [cards, sourceBadgeFilter],
+ );
+ const sourceFilterActive = sourceBadgeFilter !== "all";
+ const folderActionsReady = Boolean(
+ onCreateFolderIn && onRenameFolder && onEditFolder && onMoveFolder && onDeleteFolder,
+ );
+ // The nested folder tree owns the left rail whenever folders (reserved roots
+ // or user folders) exist for the installed view.
+ const showFolderRail = Boolean(
+ folderResult && folderResult.folders.length > 0 && onFolderSelect && folderActionsReady,
+ );
+ const activeProjectFolder = useMemo(() => {
+ if (!folderResult || folderSelection === "all" || folderSelection === "unfiled") return null;
+ const folder = folderResult.folders.find((candidate) => candidate.id === folderSelection);
+ return folder?.systemKey?.startsWith("project:") ? folder : null;
+ }, [folderResult, folderSelection]);
+ const activeProjectId = activeProjectFolder?.systemKey?.slice("project:".length) || null;
+
+ return (
+ // On desktop the store is bounded to the viewport so the category sidebar
+ // and the results pane each scroll independently (PAP-10907). Mobile keeps
+ // the natural page flow.
+ <div className="flex min-h-(--sz-calc-30) md:h-(--sz-calc-33) md:min-h-0 md:overflow-hidden">
+ {showFolderRail ? (
+ <div className="hidden shrink-0 pl-4 pt-4 md:block">
+ <SkillFolderRail
+ result={folderResult}
+ selection={folderSelection}
+ loading={foldersLoading}
+ tags={categories}
+ activeTag={activeCategory}
+ onSelect={onFolderSelect!}
+ onSelectTag={onCategoryChange}
+ onCreateFolder={onCreateFolderIn!}
+ onRenameFolder={onRenameFolder!}
+ onEditFolder={onEditFolder!}
+ onMoveFolder={onMoveFolder!}
+ onDeleteFolder={onDeleteFolder!}
+ onEnsureMyFolder={onEnsureMyFolder}
+ />
+ </div>
+ ) : null}
+ {/* Secondary category sidebar — the main app nav collapses to a rail while
+ this is present (handled in Layout). */}
+ <aside className={cn("hidden w-60 shrink-0 flex-col overflow-hidden border-r border-border md:flex", showFolderRail && "md:hidden")}>
+ <div className="border-b border-border px-4 py-4">
+ <h2 className="text-sm font-semibold text-foreground">Skills Store</h2>
+ <p className="text-xs text-muted-foreground">Discover, install, fork, share</p>
+ </div>
+ <div className="px-4 pb-1 pt-3 text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">
+ Categories
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto pb-4">
+ <CategoryNav
+ categories={categories}
+ total={categoryTotal}
+ active={activeCategory}
+ onSelect={onCategoryChange}
+ />
+ </div>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
+ {/* Search + sort + actions */}
+ <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-3">
+ <div className="flex h-9 min-w-(--sz-12rem) flex-1 items-center gap-2 rounded-md border border-border px-2.5">
+ <Search className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <input
+ value={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ placeholder="Search skills, authors, categories…"
+ className="h-full w-full bg-transparent text-base outline-none placeholder:text-muted-foreground sm:text-sm"
+ />
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm">
+ <span className="text-muted-foreground">Sort</span>
+ <span className="ml-1.5">{DISCOVERY_SORT_LABELS[sort]}</span>
+ <ChevronDown className="ml-1 h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuRadioGroup value={sort} onValueChange={(value) => onSortChange(value as DiscoverySort)}>
+ {DISCOVERY_SORTS.map((option) => (
+ <DropdownMenuRadioItem key={option} value={option}>
+ {DISCOVERY_SORT_LABELS[option]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {availableSources.length > 1 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm">
+ <span className="text-muted-foreground">Source</span>
+ <span className="ml-1.5 capitalize">
+ {sourceBadgeFilter === "all" ? "All" : sourceMeta(sourceBadgeFilter as CompanySkillSourceBadge, null).label}
+ </span>
+ <ChevronDown className="ml-1 h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuRadioGroup value={sourceBadgeFilter} onValueChange={setSourceBadgeFilter}>
+ <DropdownMenuRadioItem value="all">All sources</DropdownMenuRadioItem>
+ {availableSources.map((badge) => (
+ <DropdownMenuRadioItem key={badge} value={badge}>
+ {sourceMeta(badge as CompanySkillSourceBadge, null).label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => onScan()}
+ disabled={scanPending}
+ aria-label="Scan project workspaces for skills"
+ title="Scan project workspaces for skills"
+ >
+ <RefreshCw className={cn("h-4 w-4", scanPending && "animate-spin")} />
+ </Button>
+ <Button asChild variant="outline" size="sm">
+ <Link to="/skills/studio">
+ <FlaskConical className="h-3.5 w-3.5" />
+ Studio
+ </Link>
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button size="sm" variant="default">
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ New
+ <ChevronDown className="ml-1 h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={onCreate}>
+ <Pencil className="mr-2 h-4 w-4" />
+ Create new skill
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onBrowseCatalog}>
+ <Boxes className="mr-2 h-4 w-4" />
+ Browse catalog
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onImport}>
+ <Globe className="mr-2 h-4 w-4" />
+ Import from path or URL
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={onImportFromProject}>
+ <FolderSearch className="mr-2 h-4 w-4" />
+ Import skills from project
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {folderResult && onFolderSelect ? (
+ <div className="w-full md:hidden">
+ <FolderChip
+ result={folderResult}
+ selection={folderSelection}
+ allLabel="All skills"
+ onClick={onOpenMobileFolders ?? (() => undefined)}
+ />
+ </div>
+ ) : null}
+ {onCreateFolder && !showFolderRail ? (
+ <Button variant="outline" size="sm" onClick={onCreateFolder}>
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ New folder
+ </Button>
+ ) : null}
+ {onToggleSelectMode ? (
+ <Button variant="ghost" size="sm" onClick={onToggleSelectMode}>
+ {selectMode ? "Done" : "Select"}
+ </Button>
+ ) : null}
+ </div>
+
+ {/* Mobile category selector (sidebar is hidden below md) */}
+ {categories.length > 0 ? (
+ <div className="border-b border-border px-4 py-2 md:hidden">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm" className="w-full justify-between">
+ <span className="capitalize">{activeCategory ?? "All categories"}</span>
+ <ChevronDown className="h-3.5 w-3.5" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="max-h-72 overflow-auto">
+ <DropdownMenuRadioGroup
+ value={activeCategory ?? "__all__"}
+ onValueChange={(value) => onCategoryChange(value === "__all__" ? null : value)}
+ >
+ <DropdownMenuRadioItem value="__all__">All ({categoryTotal})</DropdownMenuRadioItem>
+ {categories.map((category) => (
+ <DropdownMenuRadioItem key={category.slug} value={category.slug} className="capitalize">
+ {category.slug} ({category.count})
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ) : null}
+
+ {/* Tab strip — Bundled/required lives at the end */}
+ <div className="border-b border-border px-4">
+ <Tabs value={tab} onValueChange={(value) => onTabChange(value as DiscoveryTab)}>
+ <TabsList variant="line" className="p-0">
+ <TabsTrigger value="all" className="px-3">
+ <span>All</span>
+ <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.all}</span>
+ </TabsTrigger>
+ <TabsTrigger value="installed" className="px-3">
+ <span>Installed</span>
+ <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.installed}</span>
+ </TabsTrigger>
+ <TabsTrigger value="catalog" className="px-3">
+ <span>Catalog</span>
+ <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.catalog}</span>
+ </TabsTrigger>
+ <TabsTrigger value="bundled" className="px-3">
+ <span>Bundled</span>
+ <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.bundled}</span>
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+
+ {/* Grid body */}
+ <div className="min-h-0 flex-1 overflow-auto p-4">
+ {scanStatus ? <p className="mb-3 text-xs text-muted-foreground">{scanStatus}</p> : null}
+ {showFolderRail && onFolderSelect ? (
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <FolderBreadcrumb result={folderResult} selection={folderSelection} onSelect={onFolderSelect} />
+ {activeProjectFolder && activeProjectId ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onScan(activeProjectId)}
+ disabled={scanPending}
+ aria-label={`Refresh ${activeProjectFolder.name} project skills`}
+ title={`Refresh skills from ${activeProjectFolder.name}`}
+ >
+ <RefreshCw className={cn("h-3.5 w-3.5", scanPending && "animate-spin")} />
+ Refresh
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+ {folderNudgeStorageKey && onCreateFolder && folderResult && folderResult.folders.length === 0 && !loading && cards.length > 0 ? (
+ <AllUnfiledBanner
+ storageKey={folderNudgeStorageKey}
+ itemLabelPlural="skills"
+ onCreateFolder={onCreateFolder}
+ />
+ ) : null}
+ {selectMode && onMoveSelected && onCreateFolderAndMoveSelected && onClearSelected ? (
+ <div className="mb-3">
+ <BulkBar
+ selectedCount={selectedSkillIds.length}
+ folders={folderResult?.folders ?? []}
+ onMove={onMoveSelected}
+ onCreateAndMove={onCreateFolderAndMoveSelected}
+ onClear={onClearSelected}
+ onDone={onToggleSelectMode ?? onClearSelected}
+ />
+ </div>
+ ) : null}
+ {loading ? (
+ <PageSkeleton variant="list" />
+ ) : error ? (
+ <div className="py-6 text-sm text-destructive">{error}</div>
+ ) : sourceFilteredCards.length === 0 ? (
+ <div className="py-12">
+ <EmptyState
+ icon={LayoutGrid}
+ message={
+ totalCount === 0
+ ? "No skills yet. Create one or install from the catalog."
+ : search || activeCategory || sourceFilterActive
+ ? "No skills match your filters."
+ : "No skills in this tab yet."
+ }
+ />
+ {totalCount === 0 ? (
+ <div className="mt-3 flex flex-col items-center gap-2">
+ <Button size="sm" onClick={onBrowseCatalog}>
+ <Boxes className="mr-1.5 h-3.5 w-3.5" /> Browse catalog
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onCreate}>
+ Create a skill
+ </Button>
+ </div>
+ ) : (search || activeCategory || sourceFilterActive) ? (
+ <div className="mt-3 flex justify-center">
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ onSearchChange("");
+ onCategoryChange(null);
+ setSourceBadgeFilter("all");
+ }}
+ >
+ Clear filters
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ ) : (
+ <>
+ <p className="mb-3 text-xs text-muted-foreground">
+ {sourceFilteredCards.length} {sourceFilteredCards.length === 1 ? "skill" : "skills"}
+ {activeCategory ? <span className="capitalize"> · {activeCategory}</span> : null}
+ </p>
+ <div className="grid gap-3 [grid-template-columns:repeat(auto-fill,minmax(19rem,1fr))]">
+ {sourceFilteredCards.map((card) => (
+ <SkillCard
+ key={card.key}
+ card={card}
+ folders={folderResult?.folders}
+ selected={selectedSkillIds.includes(card.skillId ?? "")}
+ selectMode={selectMode}
+ showFolderBadge={Boolean(folderResult && search.trim())}
+ onOpen={onOpenCard}
+ onSelectChange={onSelectCard}
+ onMove={onMoveCard}
+ onCreateFolderAndMove={onCreateFolderAndMoveCard}
+ onOpenMove={onOpenMoveCard}
+ />
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function NewSkillWizard({
+ initialDraft,
+ onCreate,
+ isPending,
+ error,
+ onCancel,
+}: {
+ initialDraft: SkillCreateDraft;
+ onCreate: (payload: CompanySkillCreateRequest) => void;
+ isPending: boolean;
+ error: string | null;
+ onCancel: () => void;
+}) {
+ const [step, setStep] = useState(0);
+ const [draft, setDraft] = useState<SkillCreateDraft>(initialDraft);
+ const [slugDirty, setSlugDirty] = useState(initialDraft.slug.trim().length > 0);
+ const categoryDraft = draft.categories.join(", ");
+ const steps = ["Basics", "Design", "Content", "Review"];
+
+ useEffect(() => {
+ setStep(0);
+ setDraft(initialDraft);
+ setSlugDirty(initialDraft.slug.trim().length > 0);
+ }, [initialDraft]);
+
+ function patchDraft(patch: Partial<SkillCreateDraft>) {
+ setDraft((current) => ({ ...current, ...patch }));
+ }
+
+ const nameValid = draft.name.trim().length > 0;
+ const effectiveSlug = draft.slug.trim() || normalizeSkillDraftSlug(draft.name);
+ function submit() {
+ onCreate(skillCreateDraftToPayload(draft));
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 border-b border-border pb-3">
+ {steps.map((label, index) => (
+ <button
+ key={label}
+ type="button"
+ onClick={() => setStep(index)}
+ className={cn(
+ "rounded-md px-2 py-1 text-xs",
+ step === index ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {draft.forkedFromName ? (
+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
+ <GitFork className="h-3.5 w-3.5" />
+ Forking {draft.forkedFromName}
+ </div>
+ ) : null}
+
+ {step === 0 ? (
+ <div className="space-y-3">
+ <Input
+ value={draft.name}
+ onChange={(event) => {
+ const nextName = event.target.value;
+ patchDraft({
+ name: nextName,
+ slug: slugDirty ? draft.slug : normalizeSkillDraftSlug(nextName),
+ markdown: draft.markdown === defaultSkillMarkdown(draft.name, draft.tagline)
+ ? defaultSkillMarkdown(nextName, draft.tagline)
+ : draft.markdown,
+ });
+ }}
+ placeholder="Skill name"
+ className="h-9"
+ />
+ <Input
+ value={draft.slug}
+ onChange={(event) => {
+ const nextSlug = normalizeSkillDraftSlug(event.target.value);
+ setSlugDirty(nextSlug.length > 0);
+ patchDraft({ slug: nextSlug });
+ }}
+ placeholder="skill-shortname"
+ className="h-9 font-mono"
+ />
+ <Textarea
+ value={draft.tagline}
+ onChange={(event) => {
+ const nextTagline = event.target.value;
+ patchDraft({
+ tagline: nextTagline,
+ description: draft.description ? draft.description : nextTagline,
+ markdown: draft.markdown === defaultSkillMarkdown(draft.name, draft.tagline)
+ ? defaultSkillMarkdown(draft.name, nextTagline)
+ : draft.markdown,
+ });
+ }}
+ placeholder="One-line promise for the skill"
+ className="min-h-20"
+ />
+ </div>
+ ) : step === 1 ? (
+ <div className="space-y-4">
+ <div className="flex items-center gap-3">
+ <SkillCardIcon
+ size={48}
+ card={{
+ key: effectiveSlug || draft.name || "new-skill",
+ name: draft.name || "New Skill",
+ slug: effectiveSlug || "skill",
+ iconUrl: null,
+ color: draft.color,
+ }}
+ />
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">{draft.name || "New Skill"}</div>
+ <div className="truncate text-xs text-muted-foreground">{draft.tagline || "No tagline yet."}</div>
+ </div>
+ </div>
+ <div>
+ <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-muted-foreground">Color</label>
+ <div className="flex flex-wrap gap-2">
+ {SKILL_CREATE_ACCENTS.map((color) => (
+ <button
+ key={color}
+ type="button"
+ onClick={() => patchDraft({ color })}
+ className={cn(
+ "h-7 w-7 rounded-md border",
+ draft.color === color ? "border-foreground" : "border-border",
+ )}
+ style={{ backgroundColor: color }}
+ aria-label={`Use ${color}`}
+ />
+ ))}
+ <Input
+ value={draft.color}
+ onChange={(event) => patchDraft({ color: event.target.value })}
+ className="h-7 w-28 font-mono text-xs"
+ />
+ </div>
+ </div>
+ <div>
+ <label className="mb-2 block text-xs font-medium uppercase tracking-wide text-muted-foreground">Categories</label>
+ <Input
+ value={categoryDraft}
+ onChange={(event) => patchDraft({ categories: splitCategoryDraft(event.target.value) })}
+ placeholder="engineering, review, memory"
+ className="h-9"
+ />
+ </div>
+ </div>
+ ) : step === 2 ? (
+ <div className="space-y-2">
+ <Textarea
+ value={draft.markdown}
+ onChange={(event) => patchDraft({ markdown: event.target.value })}
+ className="h-(--sz-calc-34) resize-y font-mono text-xs"
+ />
+ </div>
+ ) : (
+ <div className="space-y-4 text-sm">
+ <div className="grid grid-cols-(--gtc-26) gap-y-2">
+ <span className="text-muted-foreground">Name</span>
+ <span>{draft.name || "Untitled"}</span>
+ <span className="text-muted-foreground">Slug</span>
+ <span className="font-mono">{effectiveSlug || "skill"}</span>
+ <span className="text-muted-foreground">Scope</span>
+ <span>{draft.sharingScope === "private" ? "Private" : "Company"}</span>
+ <span className="text-muted-foreground">Categories</span>
+ <span>{draft.categories.length ? draft.categories.join(", ") : "none"}</span>
+ </div>
+ <div className="space-y-2">
+ <label className="block text-xs font-medium uppercase tracking-wide text-muted-foreground">Sharing</label>
+ <div className="grid gap-2 sm:grid-cols-3">
+ {(["company", "private"] as const).map((scope) => (
+ <button
+ key={scope}
+ type="button"
+ onClick={() => patchDraft({ sharingScope: scope })}
+ className={cn(
+ "rounded-md border px-3 py-2 text-left text-sm",
+ draft.sharingScope === scope ? "border-foreground bg-accent/50" : "border-border",
+ )}
+ >
+ <span className="block font-medium">{scope === "company" ? "Company" : "Private"}</span>
+ <span className="mt-1 block text-xs text-muted-foreground">
+ {scope === "company" ? "Visible inside this company." : "Only visible in your library."}
+ </span>
+ </button>
+ ))}
+ <button
+ type="button"
+ disabled
+ className="rounded-md border border-dashed border-border px-3 py-2 text-left text-sm text-muted-foreground"
+ >
+ <span className="block font-medium">Public link</span>
+ <span className="mt-1 block text-xs">Coming later.</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {error ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ {error}
+ </div>
+ ) : null}
+
+ <div className="flex items-center justify-between gap-2 border-t border-border pt-3">
+ <Button variant="ghost" size="sm" onClick={onCancel} disabled={isPending}>
+ Cancel
+ </Button>
+ <div className="flex items-center gap-2">
+ <Button variant="ghost" size="sm" onClick={() => setStep((value) => Math.max(0, value - 1))} disabled={isPending || step === 0}>
+ Back
+ </Button>
+ {step < steps.length - 1 ? (
+ <Button size="sm" onClick={() => setStep((value) => Math.min(steps.length - 1, value + 1))} disabled={!nameValid}>
+ Next
+ </Button>
+ ) : (
+ <Button size="sm" onClick={submit} disabled={isPending || !nameValid}>
+ {isPending ? "Creating..." : draft.forkedFromSkillId ? "Create fork" : "Create skill"}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function CatalogList({
+ skills,
+ kindFilter,
+ categoryFilter,
+ catalogFilter,
+ installedByKey,
+ selectedCatalogRef,
+ selectedPath,
+ expandedSkillId,
+ expandedDirs,
+ onSelect,
+ onSelectPath,
+ onToggleSkill,
+ onToggleDir,
+}: {
+ skills: CatalogSkill[];
+ kindFilter: "all" | "bundled" | "optional";
+ categoryFilter: string;
+ catalogFilter: string;
+ installedByKey: Map<string, CompanySkillListItem>;
+ selectedCatalogRef: string | null;
+ selectedPath: string;
+ expandedSkillId: string | null;
+ expandedDirs: Record<string, Set<string>>;
+ onSelect: (catalogRef: string) => void;
+ onSelectPath: (catalogRef: string, path: string) => void;
+ onToggleSkill: (catalogRef: string) => void;
+ onToggleDir: (catalogRef: string, path: string) => void;
+}) {
+ const lowered = catalogFilter.trim().toLowerCase();
+ const filtered = skills.filter((skill) => {
+ if (kindFilter !== "all" && skill.kind !== kindFilter) return false;
+ if (categoryFilter && skill.category !== categoryFilter) return false;
+ if (!lowered) return true;
+ const haystack = `${skill.name} ${skill.slug} ${skill.key} ${skill.description} ${skill.category} ${skill.tags.join(" ")} ${skill.recommendedForRoles.join(" ")}`.toLowerCase();
+ return haystack.includes(lowered);
+ });
+
+ if (filtered.length === 0) {
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No catalog skills match this filter.
+ </div>
+ );
+ }
+
+ const available = filtered.filter((skill) => !installedByKey.has(skill.key));
+ const installed = filtered.filter((skill) => installedByKey.has(skill.key));
+ const bundled = available.filter((skill) => skill.kind === "bundled");
+ const optional = available.filter((skill) => skill.kind === "optional");
+
+ function renderRow(skill: CatalogSkill) {
+ const isSelected = selectedCatalogRef === skill.id || selectedCatalogRef === skill.key;
+ const expanded = expandedSkillId === skill.id;
+ const tree = buildTree(skill.files.map((file) => ({
+ path: file.path,
+ kind: file.kind,
+ })));
+ return (
+ <div key={skill.id} className="border-b border-border">
+ <div
+ className={cn(
+ "group grid grid-cols-(--gtc-3) items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
+ isSelected && "text-foreground",
+ )}
+ >
+ <Link
+ to={catalogSkillRoute(skill.id)}
+ className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
+ onClick={() => onSelect(skill.id)}
+ >
+ <span className="flex min-w-0 items-center gap-2 self-center">
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
+ <Boxes className={cn("h-3.5 w-3.5", skill.kind === "optional" && "opacity-70")} aria-hidden="true" />
+ </span>
+ <span className="min-w-0 overflow-hidden text-(length:--text-compact) font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
+ {skill.name}
+ </span>
+ </span>
+ </Link>
+ <button
+ type="button"
+ className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-(--tp-background-color-color-opacity) hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => onToggleSkill(skill.id)}
+ aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ <div
+ aria-hidden={!expanded}
+ className={cn(
+ "grid overflow-hidden transition-(--tp-grid-template-rows-opacity) duration-200 ease-(--e-cubic-bezier-0_16-1-0_3-1)",
+ expanded ? "grid-rows-(--gtr-2) opacity-100" : "grid-rows-(--gtr-3) opacity-0",
+ )}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <SkillTree
+ nodes={tree}
+ skillId={skill.id}
+ selectedPath={isSelected ? selectedPath : "SKILL.md"}
+ expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
+ onToggleDir={(path) => onToggleDir(skill.id, path)}
+ onSelectPath={(path) => onSelectPath(skill.id, path)}
+ fileHref={(skillId) => catalogSkillRoute(skillId)}
+ depth={1}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ {bundled.length > 0 && kindFilter !== "optional" ? (
+ <div>
+ <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Bundled · {bundled.length}
+ </div>
+ {bundled.map(renderRow)}
+ </div>
+ ) : null}
+ {optional.length > 0 && kindFilter !== "bundled" ? (
+ <div>
+ <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Optional · {optional.length}
+ </div>
+ {optional.map(renderRow)}
+ </div>
+ ) : null}
+ {installed.length > 0 ? (
+ <div>
+ <div className="border-b border-border bg-background px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
+ Installed · {installed.length}
+ </div>
+ {installed.map(renderRow)}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function CatalogDetailPane({
+ skill,
+ packageName,
+ packageVersion,
+ installedSkill,
+ installedSkillId,
+ fileQuery,
+ selectedPath,
+ onInstall,
+ onUpdate,
+ onOpenInstalled,
+ loadingPrimaryAction,
+}: {
+ skill: CatalogSkill | null;
+ packageName: string | null;
+ packageVersion: string | null;
+ installedSkill: CompanySkillListItem | null;
+ installedSkillId: string | null;
+ fileQuery: { data: CatalogSkillFileDetail | undefined; isLoading: boolean; error: unknown };
+ selectedPath: string;
+ onInstall: () => void;
+ onUpdate: () => void;
+ onOpenInstalled: (skillId: string) => void;
+ loadingPrimaryAction: boolean;
+}) {
+ if (!skill) {
+ return <EmptyState icon={Boxes} message="Select a catalog skill to inspect." />;
+ }
+
+ const installedHash = installedSkill?.originHash ?? null;
+ const hashOutOfSync = Boolean(installedSkill && installedHash && installedHash !== skill.contentHash);
+ const isInstalled = Boolean(installedSkill);
+
+ let cta: React.ReactNode;
+ if (skill.compatibility === "invalid") {
+ cta = (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button disabled>
+ <Download className="mr-1.5 h-3.5 w-3.5" />
+ Install skill
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>This skill cannot be installed — its content is not valid Agent Skills markdown.</TooltipContent>
+ </Tooltip>
+ );
+ } else if (!isInstalled) {
+ cta = (
+ <Button onClick={onInstall} disabled={loadingPrimaryAction}>
+ {skill.trustLevel === "scripts_executables" ? <AlertTriangle className="mr-1.5 h-3.5 w-3.5" /> : <Download className="mr-1.5 h-3.5 w-3.5" />}
+ {loadingPrimaryAction ? "Preparing..." : "Install skill in this organization"}
+ </Button>
+ );
+ } else if (hashOutOfSync) {
+ cta = (
+ <Button onClick={onUpdate} disabled={loadingPrimaryAction} className="border-amber-500/40 bg-amber-500/20 text-amber-900 dark:text-amber-100 hover:bg-amber-500/30">
+ <ArrowUpCircle className="mr-1.5 h-3.5 w-3.5" />
+ Update from catalog
+ </Button>
+ );
+ } else {
+ cta = (
+ <Button variant="ghost" onClick={() => installedSkillId && onOpenInstalled(installedSkillId)}>
+ <Check className="mr-1.5 h-3.5 w-3.5" />
+ Installed · Open in library
+ </Button>
+ );
+ }
+
+ const body = fileQuery.data?.markdown ? stripFrontmatter(fileQuery.data.content) : fileQuery.data?.content ?? "";
+
+ return (
+ <div className="min-w-0">
+ <div className="border-b border-border px-5 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h1 className="flex items-center gap-2 truncate text-2xl font-semibold">
+ <Boxes className={cn("h-5 w-5 shrink-0 text-muted-foreground", skill.kind === "optional" && "opacity-70")} aria-hidden="true" />
+ {skill.name}
+ </h1>
+ <p className="mt-2 max-w-3xl text-sm text-muted-foreground">{skill.description}</p>
+ <div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span className="rounded border border-border bg-muted/40 px-1.5 py-0.5 uppercase tracking-wide">{skill.kind}</span>
+ <span>·</span>
+ <span>{skill.category}</span>
+ <span>·</span>
+ <ProvenanceBadge packageName={packageName} packageVersion={packageVersion} />
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">{cta}</div>
+ </div>
+
+ <div className="mt-4 flex flex-wrap items-center gap-2 border-t border-border pt-4">
+ <TrustChip level={skill.trustLevel} />
+ <CompatChip compatibility={skill.compatibility} />
+ {hashOutOfSync ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="outline" className="border-amber-500/40 bg-amber-500/10 text-(length:--text-micro) text-amber-800 dark:text-amber-200">
+ <ArrowUpCircle className="h-3 w-3" aria-hidden="true" />
+ Update available
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>Catalog content hash has changed since this skill was installed.</TooltipContent>
+ </Tooltip>
+ ) : null}
+ {skill.requires.length > 0 ? (
+ <Badge variant="outline" className="border-border bg-muted/40 text-(length:--text-micro) text-muted-foreground">
+ Requires: {skill.requires.join(", ")}
+ </Badge>
+ ) : null}
+ {skill.recommendedForRoles.length > 0 ? (
+ <Badge variant="outline" className="border-border bg-muted/40 text-(length:--text-micro) text-muted-foreground">
+ Roles: {skill.recommendedForRoles.join(" · ")}
+ </Badge>
+ ) : null}
+ {skill.tags.length > 0 ? (
+ <Badge variant="outline" className="border-border bg-muted/40 text-(length:--text-micro) text-muted-foreground">
+ Tags: {skill.tags.join(" · ")}
+ </Badge>
+ ) : null}
+ </div>
+
+ <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span className="uppercase tracking-(--tracking-caps)">Key</span>
+ <span className="font-mono">{skill.key}</span>
+ <span className="uppercase tracking-(--tracking-caps)">·</span>
+ <span className="uppercase tracking-(--tracking-caps)">Hash</span>
+ <span className="font-mono">{skill.contentHash.slice(0, 24)}…</span>
+ <CopyText
+ text={skill.contentHash}
+ copiedLabel="Copied hash"
+ ariaLabel="Copy content hash"
+ title="Copy content hash"
+ className="inline-flex h-6 w-6 items-center justify-center rounded-sm border border-border text-muted-foreground hover:bg-accent hover:text-foreground"
+ >
+ <Copy className="h-3 w-3" />
+ </CopyText>
+ </div>
+ </div>
+
+ <div className="border-b border-border px-5 py-3">
+ <div className="truncate font-mono text-sm">{selectedPath}</div>
+ </div>
+
+ <div className="min-h-(--sz-400px) px-5 py-5">
+ {fileQuery.isLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : fileQuery.error ? (
+ <div className="text-sm text-destructive">{fileQuery.error instanceof Error ? fileQuery.error.message : "Failed to load file"}</div>
+ ) : !fileQuery.data ? (
+ <div className="text-sm text-muted-foreground">Select a file to inspect.</div>
+ ) : fileQuery.data.markdown ? (
+ <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody>
+ ) : (
+ <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground">
+ <code>{fileQuery.data.content}</code>
+ </pre>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// Installing only adds a skill to the company library; an agent can use it only
+// once it is also enabled for that agent. Pre-select every agent that can
+// receive the skill so "install" defaults to a state where the skill is
+// actually usable, instead of a library row no agent has.
+export function defaultInstallAgentSelection(
+ agents: Array<Pick<AttachAgentOption, "id" | "supportsSkills" | "required">>,
+): Set<string> {
+ return new Set(agents.filter((agent) => agent.supportsSkills && !agent.required).map((agent) => agent.id));
+}
+
+export function InstallPreviewDialog({
+ open,
+ onOpenChange,
+ skill,
+ packageName,
+ packageVersion,
+ conflict,
+ defaultSlug,
+ defaultForce,
+ defaultAction,
+ agents,
+ isPending,
+ error,
+ onConfirm,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ skill: CatalogSkill | null;
+ packageName: string | null;
+ packageVersion: string | null;
+ conflict: CompanySkillListItem | null;
+ defaultSlug: string | null;
+ defaultForce: boolean;
+ defaultAction: "install" | "update" | "replace";
+ agents: AttachAgentOption[];
+ isPending: boolean;
+ error: string | null;
+ onConfirm: (input: { slug: string | null; force: boolean; agentIds: string[] }) => void;
+}) {
+ const [slug, setSlug] = useState<string>("");
+ const [force, setForce] = useState(false);
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [selectedAgentIds, setSelectedAgentIds] = useState<Set<string>>(new Set());
+ // Whether the user changed the agent selection this open. Until then the
+ // selection keeps tracking the default: the agents query may resolve after
+ // the dialog opens, and a one-shot seed would freeze an empty selection and
+ // install the skill for nobody.
+ const [selectionTouched, setSelectionTouched] = useState(false);
+ const wasOpenRef = useRef(false);
+
+ useEffect(() => {
+ if (!open) return;
+ setSlug(defaultSlug ?? "");
+ setForce(defaultForce);
+ setAdvancedOpen(defaultAction === "replace" || defaultForce);
+ }, [open, defaultSlug, defaultForce, defaultAction]);
+
+ useEffect(() => {
+ if (open && !wasOpenRef.current) setSelectionTouched(false);
+ wasOpenRef.current = open;
+ }, [open]);
+
+ // Track the default selection while the dialog is open and untouched; the
+ // user's first change takes over and background refetches never clobber it.
+ useEffect(() => {
+ if (!open || selectionTouched) return;
+ setSelectedAgentIds(defaultAction === "install" ? defaultInstallAgentSelection(agents) : new Set());
+ }, [open, selectionTouched, defaultAction, agents]);
+
+ if (!skill) return null;
+
+ let confirmLabel = "Install skill";
+ let confirmVariant: "default" | "destructive" = "default";
+ if (defaultAction === "update") {
+ confirmLabel = "Install update";
+ } else if (defaultAction === "replace") {
+ confirmLabel = "Replace existing skill";
+ confirmVariant = "destructive";
+ }
+ if (isPending) confirmLabel = "Installing…";
+
+ return (
+ <Dialog open={open} onOpenChange={(value) => (!isPending ? onOpenChange(value) : null)}>
+ <DialogContent className="sm:max-w-2xl" showCloseButton={!isPending}>
+ <DialogHeader>
+ <DialogTitle>
+ {defaultAction === "update" ? "Update" : defaultAction === "replace" ? "Replace" : "Install"} · {skill.name}
+ </DialogTitle>
+ <DialogDescription>
+ <span className="capitalize">{skill.kind}</span> · {skill.category}
+ {packageName ? <> · {packageName}{packageVersion ? ` v${packageVersion}` : ""}</> : null}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 text-sm">
+ <div className="rounded-md border border-border p-3">
+ <div className="grid grid-cols-(--gtc-26) gap-y-2 text-xs">
+ <div className="text-muted-foreground">Trust</div>
+ <div className="flex items-center gap-2">
+ <TrustChip level={skill.trustLevel} />
+ {skill.trustLevel === "markdown_only" ? (
+ <span className="text-muted-foreground">Safe</span>
+ ) : skill.trustLevel === "scripts_executables" ? (
+ <span className="text-amber-800 dark:text-amber-200">Review required</span>
+ ) : (
+ <span className="text-muted-foreground">Non-script assets</span>
+ )}
+ </div>
+ <div className="text-muted-foreground">Compatibility</div>
+ <div className="flex items-center gap-2">
+ {skill.compatibility === "compatible" ? (
+ <span className="inline-flex items-center gap-1 text-muted-foreground">
+ <Check className="h-3 w-3" aria-hidden="true" />
+ Compatible
+ </span>
+ ) : (
+ <CompatChip compatibility={skill.compatibility} />
+ )}
+ </div>
+ <div className="text-muted-foreground">Requires</div>
+ <div className="text-foreground">{skill.requires.length === 0 ? "none" : skill.requires.join(", ")}</div>
+ <div className="text-muted-foreground">Roles</div>
+ <div className="text-foreground">{skill.recommendedForRoles.length === 0 ? "any" : skill.recommendedForRoles.join(" · ")}</div>
+ <div className="text-muted-foreground">Provenance</div>
+ <div className="min-w-0">
+ <div className="truncate">{packageName ?? "—"}{packageVersion ? ` v${packageVersion}` : ""}</div>
+ <div className="truncate font-mono text-(length:--text-micro) text-muted-foreground">{skill.contentHash}</div>
+ </div>
+ </div>
+ </div>
+
+ <div className="rounded-md border border-border">
+ <div className="border-b border-border px-3 py-2 text-xs uppercase tracking-wide text-muted-foreground">
+ Files ({skill.files.length})
+ </div>
+ <div className="max-h-48 overflow-y-auto">
+ {skill.files.map((file) => (
+ <div key={file.path} className="grid grid-cols-(--gtc-27) items-center gap-x-3 border-b border-border/50 px-3 py-1.5 text-xs last:border-b-0">
+ <span className="truncate font-mono text-muted-foreground">{file.path}</span>
+ <span className="rounded border border-border bg-muted/40 px-1 py-0.5 text-(length:--text-nano) uppercase text-muted-foreground">{file.kind}</span>
+ <span className="text-(length:--text-micro) text-muted-foreground">{formatBytes(file.sizeBytes)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {conflict ? (
+ <div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-800 dark:text-amber-200">
+ An existing skill with key <span className="font-mono">{conflict.key}</span> is installed (
+ {conflict.sourceLabel ?? conflict.sourceType}). Installing will {defaultAction === "update" ? "overwrite the catalog content" : "replace the existing skill"}.
+ </div>
+ ) : null}
+
+ {defaultAction === "install" ? (
+ <div className="rounded-md border border-border p-3">
+ <div className="mb-1 text-xs uppercase tracking-wide text-muted-foreground">Enable for agents</div>
+ <p className="mb-2 text-xs text-muted-foreground">
+ Installing adds the skill to the company library. Agents can only use it once it is enabled for them.
+ </p>
+ <AgentMultiSelect
+ agents={agents}
+ selectedAgentIds={selectedAgentIds}
+ onChange={(next) => {
+ setSelectionTouched(true);
+ setSelectedAgentIds(next);
+ }}
+ showSelectionPreview={false}
+ emptyMessage="No agents in this company support skills yet."
+ isAgentDisabled={(agent) => {
+ const option = agent as AttachAgentOption;
+ return option.required || !option.supportsSkills;
+ }}
+ getDescription={(agent) => {
+ const option = agent as AttachAgentOption;
+ return `${option.adapterType}${option.required ? " · required" : ""}${!option.supportsSkills ? " · skills not supported" : ""}`;
+ }}
+ />
+ </div>
+ ) : null}
+
+ <button
+ type="button"
+ onClick={() => setAdvancedOpen((value) => !value)}
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
+ >
+ {advancedOpen ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
+ Advanced
+ </button>
+ {advancedOpen ? (
+ <div className="space-y-3 rounded-md border border-border p-3 text-xs">
+ <div>
+ <label className="mb-1 block uppercase tracking-wide text-muted-foreground">Slug override</label>
+ <Input value={slug} onChange={(event) => setSlug(event.target.value)} placeholder={defaultSlug ?? skill.slug} className="h-8" />
+ </div>
+ <label className="flex items-center gap-2">
+ <Checkbox checked={force} onCheckedChange={(value) => setForce(Boolean(value))} />
+ <span>Force replace existing same-key skill</span>
+ </label>
+ </div>
+ ) : null}
+
+ {error ? (
+ <div className="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">
+ {error}
+ </div>
+ ) : null}
+ </div>
+
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={isPending}>
+ Cancel
+ </Button>
+ <Button
+ variant={confirmVariant}
+ onClick={() =>
+ onConfirm({
+ slug: slug.trim().length > 0 ? slug.trim() : null,
+ force,
+ agentIds: defaultAction === "install" ? Array.from(selectedAgentIds) : [],
+ })
+ }
+ disabled={isPending}
+ >
+ {confirmLabel}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+type AttachAgentOption = {
+ id: string;
+ name: string;
+ adapterType: string;
+ supportsSkills: boolean;
+ required: boolean;
+ icon: string | null;
+ paused: boolean;
+};
+
+function AttachAgentsPopover({
+ agents,
+ attachedAgentIds,
+ versions,
+ selectedVersionId,
+ pending,
+ onSubmit,
+ fullWidth = false,
+}: {
+ agents: AttachAgentOption[];
+ attachedAgentIds: string[];
+ versions: CompanySkillVersion[];
+ selectedVersionId: string | null;
+ pending: boolean;
+ onSubmit: (nextIds: string[], versionId: string | null) => void;
+ fullWidth?: boolean;
+}) {
+ const [draftVersionId, setDraftVersionId] = useState<string | null>(selectedVersionId);
+ const attachedIds = useMemo(() => new Set(attachedAgentIds), [attachedAgentIds]);
+ const eligible = agents.filter((agent) => agent.supportsSkills);
+ const sortedVersions = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+
+ return (
+ <AgentMultiSelect
+ agents={agents}
+ selectedAgentIds={attachedIds}
+ onSave={(nextIds) => onSubmit(Array.from(nextIds), draftVersionId)}
+ pending={pending}
+ triggerLabel="Add to agent"
+ triggerIcon={<Plus className="mr-1.5 h-3.5 w-3.5" />}
+ triggerVariant="default"
+ triggerSize="sm"
+ triggerFullWidth={fullWidth}
+ triggerClassName={cn(fullWidth && "w-full")}
+ contentAlign="end"
+ showSelectionPreview={false}
+ onOpenChange={(open) => {
+ if (open) setDraftVersionId(selectedVersionId);
+ }}
+ headerContent={sortedVersions.length > 0 ? (
+ <div className="mt-2 flex items-center gap-2 text-xs">
+ <span className="shrink-0 text-muted-foreground">Version</span>
+ <select
+ value={draftVersionId ?? "__latest__"}
+ onChange={(event) => setDraftVersionId(event.target.value === "__latest__" ? null : event.target.value)}
+ className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-xs text-foreground"
+ >
+ <option value="__latest__">Latest</option>
+ {sortedVersions.map((version) => (
+ <option key={version.id} value={version.id}>
+ v{version.revisionNumber}{version.label ? ` · ${version.label}` : ""}
+ </option>
+ ))}
+ </select>
+ </div>
+ ) : null}
+ emptyMessage={eligible.length === 0 ? "No agents in this company support skills yet." : "No agents yet."}
+ isAgentDisabled={(agent) => {
+ const option = agent as AttachAgentOption;
+ return option.required || !option.supportsSkills;
+ }}
+ getDescription={(agent) => {
+ const option = agent as AttachAgentOption;
+ return `${option.adapterType}${option.required ? " · required" : ""}${!option.supportsSkills ? " · skills not supported" : ""}`;
+ }}
+ renderNameSuffix={(agent) => (agent as AttachAgentOption).paused ? (
+ <Badge variant="outline" className="[&>svg]:size-2.5 border-amber-500/30 bg-amber-500/10 px-1.5 text-(length:--text-nano) uppercase tracking-wide text-amber-500">
+ <Pause className="h-2.5 w-2.5" aria-hidden="true" />
+ Paused
+ </Badge>
+ ) : null}
+ />
+ );
+}
+
+function SkillTree({
+ nodes,
+ skillId,
+ selectedPath,
+ expandedDirs,
+ onToggleDir,
+ onSelectPath,
+ fileHref = (currentSkillId, path) => skillRoute(currentSkillId, path),
+ depth = 0,
+}: {
+ nodes: SkillTreeNode[];
+ skillId: string;
+ selectedPath: string;
+ expandedDirs: Set<string>;
+ onToggleDir: (path: string) => void;
+ onSelectPath: (path: string) => void;
+ fileHref?: (skillId: string, path?: string | null) => string;
+ depth?: number;
+}) {
+ return (
+ <div>
+ {nodes.map((node) => {
+ const expanded = node.kind === "dir" && node.path ? expandedDirs.has(node.path) : false;
+ if (node.kind === "dir") {
+ return (
+ <div key={node.path ?? node.name}>
+ <div
+ className={cn(
+ "group grid w-full grid-cols-(--gtc-3) items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",
+ SKILL_TREE_ROW_HEIGHT_CLASS,
+ )}
+ >
+ <button
+ type="button"
+ className="flex min-w-0 items-center gap-2 py-1 text-left"
+ style={{ paddingLeft: `${SKILL_TREE_BASE_INDENT + depth * SKILL_TREE_STEP_INDENT}px` }}
+ onClick={() => node.path && onToggleDir(node.path)}
+ >
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">
+ {expanded ? <FolderOpen className="h-3.5 w-3.5" /> : <Folder className="h-3.5 w-3.5" />}
+ </span>
+ <span className="truncate">{node.name}</span>
+ </button>
+ <button
+ type="button"
+ className="flex h-9 w-9 items-center justify-center self-center rounded-sm text-muted-foreground opacity-70 transition-(--tp-background-color-color-opacity) hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => node.path && onToggleDir(node.path)}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ {expanded && (
+ <SkillTree
+ nodes={node.children}
+ skillId={skillId}
+ selectedPath={selectedPath}
+ expandedDirs={expandedDirs}
+ onToggleDir={onToggleDir}
+ onSelectPath={onSelectPath}
+ fileHref={fileHref}
+ depth={depth + 1}
+ />
+ )}
+ </div>
+ );
+ }
+
+ const FileIcon = fileIcon(node.fileKind ?? "other");
+ return (
+ <Link
+ key={node.path ?? node.name}
+ className={cn(
+ "flex w-full items-center gap-2 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",
+ SKILL_TREE_ROW_HEIGHT_CLASS,
+ node.path === selectedPath && "text-foreground",
+ )}
+ style={{ paddingInlineStart: `${SKILL_TREE_BASE_INDENT + depth * SKILL_TREE_STEP_INDENT}px` }}
+ to={fileHref(skillId, node.path)}
+ onClick={() => node.path && onSelectPath(node.path)}
+ >
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">
+ <FileIcon className="h-3.5 w-3.5" />
+ </span>
+ <span className="truncate">{node.name}</span>
+ </Link>
+ );
+ })}
+ </div>
+ );
+}
+
+function SkillList({
+ skills,
+ selectedSkillId,
+ skillFilter,
+ sourceFilter,
+ expandedSkillId,
+ expandedDirs,
+ selectedPaths,
+ onToggleSkill,
+ onToggleDir,
+ onSelectSkill,
+ onSelectPath,
+ onClearFilters,
+}: {
+ skills: CompanySkillListItem[];
+ selectedSkillId: string | null;
+ skillFilter: string;
+ sourceFilter: SourceFilter;
+ expandedSkillId: string | null;
+ expandedDirs: Record<string, Set<string>>;
+ selectedPaths: Record<string, string>;
+ onToggleSkill: (skillId: string) => void;
+ onToggleDir: (skillId: string, path: string) => void;
+ onSelectSkill: (skillId: string) => void;
+ onSelectPath: (skillId: string, path: string) => void;
+ onClearFilters: () => void;
+}) {
+ const filteredSkills = skills.filter((skill) => {
+ const haystack = `${skill.name} ${skill.key} ${skill.slug} ${skill.sourceLabel ?? ""}`.toLowerCase();
+ if (!haystack.includes(skillFilter.toLowerCase())) return false;
+ if (sourceFilter === "all") return true;
+ const skillSource = classifySource(skill);
+ return skillSource === sourceFilter;
+ });
+
+ if (filteredSkills.length === 0) {
+ if (sourceFilter !== "all" && skills.length > 0) {
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No {SOURCE_FILTER_LABELS[sourceFilter].toLowerCase()} skills installed.{" "}
+ <button type="button" className="text-foreground underline" onClick={onClearFilters}>
+ Clear filter
+ </button>
+ </div>
+ );
+ }
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No skills match this filter.
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ {filteredSkills.map((skill) => {
+ const expanded = expandedSkillId === skill.id;
+ const tree = buildTree(skill.fileInventory);
+ const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
+ const SourceIcon = source.icon;
+
+ return (
+ <div key={skill.id} className="border-b border-border">
+ <div
+ className={cn(
+ "group grid grid-cols-(--gtc-3) items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
+ skill.id === selectedSkillId && "text-foreground",
+ )}
+ >
+ <Link
+ to={skillRoute(skill, skills)}
+ className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
+ onClick={() => onSelectSkill(skill.id)}
+ >
+ <span className="flex min-w-0 items-center gap-2 self-center">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
+ <SourceIcon className="h-3.5 w-3.5" />
+ <span className="sr-only">{source.managedLabel}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top">{source.managedLabel}</TooltipContent>
+ </Tooltip>
+ <span className="min-w-0 overflow-hidden text-(length:--text-compact) font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
+ {skill.name}
+ </span>
+ </span>
+ </Link>
+ <button
+ type="button"
+ className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-(--tp-background-color-color-opacity) hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => onToggleSkill(skill.id)}
+ aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ <div
+ aria-hidden={!expanded}
+ className={cn(
+ "grid overflow-hidden transition-(--tp-grid-template-rows-opacity) duration-200 ease-(--e-cubic-bezier-0_16-1-0_3-1)",
+ expanded ? "grid-rows-(--gtr-2) opacity-100" : "grid-rows-(--gtr-3) opacity-0",
+ )}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <SkillTree
+ nodes={tree}
+ skillId={skill.id}
+ selectedPath={selectedPaths[skill.id] ?? "SKILL.md"}
+ expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
+ onToggleDir={(path) => onToggleDir(skill.id, path)}
+ onSelectPath={(path) => onSelectPath(skill.id, path)}
+ fileHref={(_, path) => skillRoute(skill, skills, path)}
+ depth={1}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+type SkillDetailTab = "overview" | "files" | "versions" | "agents";
+
+const SKILL_DETAIL_TABS: Array<{ value: SkillDetailTab; label: string; icon: typeof FileText }> = [
+ { value: "overview", label: "Overview", icon: FileText },
+ { value: "files", label: "Files", icon: FolderOpen },
+ { value: "versions", label: "Versions", icon: History },
+ { value: "agents", label: "Agents", icon: Users },
+];
+
+function currentVersionSelection(detail: CompanySkillDetail | null | undefined) {
+ const selected = detail?.usedByAgents.find((agent) => agent.versionId)?.versionId;
+ return selected ?? null;
+}
+
+function versionLabel(version: CompanySkillVersion | null | undefined) {
+ if (!version) return "Latest";
+ return `v${version.revisionNumber}${version.label ? ` · ${version.label}` : ""}`;
+}
+
+export function getSkillVersionDiffSelection(versions: CompanySkillVersion[], targetVersionId?: string | null) {
+ const sorted = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+ const right = targetVersionId
+ ? sorted.find((version) => version.id === targetVersionId) ?? null
+ : sorted[0] ?? null;
+ if (!right) return { leftVersionId: null, rightVersionId: null };
+
+ const left = sorted.find((version) => version.revisionNumber < right.revisionNumber) ?? null;
+ return {
+ leftVersionId: left?.id ?? null,
+ rightVersionId: right.id,
+ };
+}
+
+function SkillVersionDiffDialog({
+ open,
+ onOpenChange,
+ versions,
+ leftVersionId,
+ rightVersionId,
+ onLeftVersionChange,
+ onRightVersionChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ versions: CompanySkillVersion[];
+ leftVersionId: string | null;
+ rightVersionId: string | null;
+ onLeftVersionChange: (id: string | null) => void;
+ onRightVersionChange: (id: string | null) => void;
+}) {
+ const sorted = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+ const left = sorted.find((version) => version.id === leftVersionId) ?? null;
+ const right = sorted.find((version) => version.id === rightVersionId) ?? null;
+ const allPaths = useMemo(() => {
+ const paths = new Set<string>();
+ for (const file of left?.fileInventory ?? []) paths.add(file.path);
+ for (const file of right?.fileInventory ?? []) paths.add(file.path);
+ return Array.from(paths).sort((a, b) => {
+ if (a === "SKILL.md") return -1;
+ if (b === "SKILL.md") return 1;
+ return a.localeCompare(b);
+ });
+ }, [left, right]);
+ const [selectedPath, setSelectedPath] = useState("SKILL.md");
+ const effectivePath = allPaths.includes(selectedPath) ? selectedPath : allPaths[0] ?? "SKILL.md";
+ const leftFile = left?.fileInventory.find((file) => file.path === effectivePath);
+ const rightFile = right?.fileInventory.find((file) => file.path === effectivePath);
+ const diffRows = useMemo(
+ () => buildLineDiff(leftFile?.content ?? "", rightFile?.content ?? ""),
+ [leftFile?.content, rightFile?.content],
+ );
+ const lineClassesByKind: Record<DiffRow["kind"], string> = {
+ context: "bg-transparent",
+ removed: "bg-red-500/10 text-red-900 dark:text-red-100",
+ added: "bg-green-500/10 text-green-900 dark:text-green-100",
+ };
+ const markerByKind: Record<DiffRow["kind"], string> = {
+ context: " ",
+ removed: "-",
+ added: "+",
+ };
+
+ useEffect(() => {
+ if (open && allPaths.length > 0 && !allPaths.includes(selectedPath)) {
+ setSelectedPath(allPaths[0]!);
+ }
+ }, [allPaths, open, selectedPath]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-(--sz-85vh) w-full !max-w-(--pct-90) flex-col overflow-hidden">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <DialogHeader className="shrink-0">
+ <DialogTitle>Diff · skill files</DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-wrap items-center gap-3 text-xs">
+ <label className="flex items-center gap-2">
+ <Badge variant="outline" className="border-red-500/30 bg-red-500/10 uppercase tracking-wider text-red-400">Old</Badge>
+ <select
+ value={leftVersionId ?? ""}
+ onChange={(event) => onLeftVersionChange(event.target.value || null)}
+ className="h-8 w-44 rounded-md border border-border bg-background px-2 text-xs"
+ >
+ <option value="">Initial</option>
+ {sorted.map((version) => (
+ <option key={version.id} value={version.id}>{versionLabel(version)}</option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-2">
+ <Badge variant="outline" className="border-green-500/30 bg-green-500/10 uppercase tracking-wider text-green-400">New</Badge>
+ <select
+ value={right?.id ?? ""}
+ onChange={(event) => onRightVersionChange(event.target.value || null)}
+ className="h-8 w-44 rounded-md border border-border bg-background px-2 text-xs"
+ >
+ {sorted.map((version) => (
+ <option key={version.id} value={version.id}>{versionLabel(version)}</option>
+ ))}
+ </select>
+ </label>
+ </div>
+ </div>
+ <div className="flex min-h-0 flex-1 gap-3">
+ <aside className="hidden w-56 shrink-0 overflow-auto border-r border-border pr-3 md:block">
+ {allPaths.map((path) => (
+ <button
+ key={path}
+ type="button"
+ onClick={() => setSelectedPath(path)}
+ className={cn(
+ "flex w-full items-center gap-2 px-2 py-1.5 text-left font-mono text-xs text-muted-foreground hover:bg-accent/40 hover:text-foreground",
+ effectivePath === path && "bg-accent/50 text-foreground",
+ )}
+ >
+ <FileText className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">{path}</span>
+ </button>
+ ))}
+ </aside>
+ <div className="min-w-0 flex-1 overflow-auto rounded-md border border-border text-xs">
+ {!right ? (
+ <div className="p-6 text-center text-sm text-muted-foreground">Select a version to compare.</div>
+ ) : left?.id === right.id ? (
+ <div className="p-6 text-center text-sm text-muted-foreground">Both sides are the same version.</div>
+ ) : (
+ <div className="font-mono text-xs leading-6">
+ <div className="grid grid-cols-(--gtc-1) border-b border-border/60 bg-muted/30 px-3 py-2 text-(length:--text-micro) uppercase tracking-wide text-muted-foreground">
+ <span>Old</span>
+ <span>New</span>
+ <span />
+ <span>{effectivePath}</span>
+ </div>
+ {diffRows.map((row, index) => (
+ <div
+ key={`${row.kind}-${index}-${row.oldLineNumber ?? "x"}-${row.newLineNumber ?? "x"}`}
+ className={cn("grid grid-cols-(--gtc-1) gap-0 border-b border-border/30 px-3", lineClassesByKind[row.kind])}
+ >
+ <span className="select-none border-r border-border/30 pr-3 text-right text-muted-foreground">{row.oldLineNumber ?? ""}</span>
+ <span className="select-none border-r border-border/30 px-3 text-right text-muted-foreground">{row.newLineNumber ?? ""}</span>
+ <span className="select-none px-3 text-center text-muted-foreground">{markerByKind[row.kind]}</span>
+ <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit">{row.text.length > 0 ? row.text : " "}</pre>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/**
+ * Canonical-path block for the skill detail (wireframe screen 5): the folder
+ * location is a first-class element with Copy and Move actions. The `skill://`
+ * link and skill id survive folder moves, so the path is presentational.
+ */
+function SkillLocationCard({
+ folderPath,
+ onMove,
+}: {
+ folderPath: string | null | undefined;
+ onMove?: () => void;
+}) {
+ const [copied, setCopied] = useState(false);
+ const canonical = folderPath && folderPath.length > 0 ? folderPath : "Unfiled";
+ return (
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Location</div>
+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/30 px-2.5 py-1.5">
+ <FolderOpen className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground" title={canonical}>{canonical}</span>
+ </div>
+ <div className="mt-2 flex items-center gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ void copyTextToClipboard(canonical)
+ .then(() => {
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ })
+ .catch(() => {});
+ }}
+ >
+ <Copy className="mr-1.5 h-3.5 w-3.5" />
+ {copied ? "Copied" : "Copy path"}
+ </Button>
+ {onMove ? (
+ <Button size="sm" variant="outline" onClick={onMove}>
+ <FolderInput className="mr-1.5 h-3.5 w-3.5" />
+ Move
+ </Button>
+ ) : null}
+ </div>
+ </section>
+ );
+}
+
+/**
+ * Inline tags editor for the skill detail. Tags are the skill's `categories[]`
+ * presented as first-class chips — there is no separate "tags" field.
+ */
+function SkillTagsEditor({
+ categories,
+ pending,
+ onSave,
+}: {
+ categories: string[];
+ pending: boolean;
+ onSave: (categories: string[]) => void;
+}) {
+ const [draft, setDraft] = useState("");
+ function addTag(raw: string) {
+ const tag = raw.trim().toLowerCase();
+ if (!tag || categories.includes(tag)) {
+ setDraft("");
+ return;
+ }
+ onSave([...categories, tag]);
+ setDraft("");
+ }
+ return (
+ <section>
+ <div className="mb-2 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ <Hash className="h-3 w-3" />
+ Tags
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ {categories.map((tag) => (
+ <span
+ key={tag}
+ className="inline-flex items-center gap-1 rounded-full border border-border bg-accent/40 px-2 py-0.5 text-xs text-foreground"
+ >
+ {tag}
+ <button
+ type="button"
+ aria-label={`Remove tag ${tag}`}
+ disabled={pending}
+ onClick={() => onSave(categories.filter((entry) => entry !== tag))}
+ className="text-muted-foreground hover:text-foreground disabled:opacity-50"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ {categories.length === 0 ? (
+ <span className="text-xs text-muted-foreground">No tags yet.</span>
+ ) : null}
+ </div>
+ <Input
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ addTag(draft);
+ }
+ }}
+ onBlur={() => draft.trim() && addTag(draft)}
+ placeholder="Add a tag…"
+ disabled={pending}
+ className="mt-2 h-8 text-sm"
+ />
+ </section>
+ );
+}
+
+export function SkillDetailPage({
+ detail,
+ folderDisplayPath,
+ catalogSource,
+ routeSkills,
+ loading,
+ activeTab,
+ onTabChange,
+ selectedPath,
+ file,
+ fileLoading,
+ viewMode,
+ editMode,
+ draft,
+ setViewMode,
+ setEditMode,
+ setDraft,
+ onSave,
+ savePending,
+ versions,
+ versionsLoading,
+ attachAgents,
+ onSubmitAttach,
+ attachPending,
+ expandedDirs,
+ onToggleDir,
+ onSelectPath,
+ updateStatus,
+ updateStatusLoading,
+ onCheckUpdates,
+ checkUpdatesPending,
+ onInstallUpdate,
+ installUpdatePending,
+ onToggleStar,
+ starPending,
+ onFork,
+ onUpdateSettings,
+ updateSettingsPending,
+ onMoveToFolder,
+ onDelete,
+ deletePending,
+ studioHref,
+}: {
+ detail: CompanySkillDetail | null | undefined;
+ folderDisplayPath?: string | null;
+ catalogSource?: CatalogSkillSource | null;
+ routeSkills?: CompanySkillRouteSubject[];
+ loading: boolean;
+ activeTab: SkillDetailTab;
+ onTabChange: (tab: SkillDetailTab) => void;
+ selectedPath: string;
+ file: CompanySkillFileDetail | null | undefined;
+ fileLoading: boolean;
+ viewMode: "preview" | "code";
+ editMode: boolean;
+ draft: string;
+ setViewMode: (mode: "preview" | "code") => void;
+ setEditMode: (value: boolean) => void;
+ setDraft: (value: string) => void;
+ onSave: () => void;
+ savePending: boolean;
+ versions: CompanySkillVersion[];
+ versionsLoading: boolean;
+ attachAgents: AttachAgentOption[];
+ onSubmitAttach: (ids: string[], versionId: string | null) => void;
+ attachPending: boolean;
+ expandedDirs: Set<string>;
+ onToggleDir: (path: string) => void;
+ onSelectPath: (path: string) => void;
+ updateStatus: CompanySkillUpdateStatus | null | undefined;
+ updateStatusLoading: boolean;
+ onCheckUpdates: () => void;
+ checkUpdatesPending: boolean;
+ onInstallUpdate: () => void;
+ installUpdatePending: boolean;
+ onToggleStar: () => void;
+ starPending: boolean;
+ onFork: () => void;
+ onUpdateSettings: (payload: Pick<CompanySkillUpdateRequest, "categories" | "sharingScope">) => void;
+ updateSettingsPending: boolean;
+ /** Open the rich move-to-folder dialog for this skill. */
+ onMoveToFolder?: () => void;
+ onDelete: () => void;
+ deletePending: boolean;
+ studioHref?: string;
+}) {
+ const [diffOpen, setDiffOpen] = useState(false);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ const [settingsSharingScope, setSettingsSharingScope] = useState<Exclude<CompanySkillSharingScope, "public_link">>("company");
+ const [settingsCategoryDraft, setSettingsCategoryDraft] = useState("");
+ // Top-level description is clamped to four lines; "View all" expands it. We
+ // only surface the toggle when the text actually overflows the clamp.
+ const descriptionRef = useRef<HTMLParagraphElement | null>(null);
+ const [descExpanded, setDescExpanded] = useState(false);
+ const [descClamped, setDescClamped] = useState(false);
+ useEffect(() => {
+ const el = descriptionRef.current;
+ if (!el || descExpanded) return;
+ setDescClamped(el.scrollHeight - el.clientHeight > 1);
+ }, [detail?.description, detail?.tagline, detail?.id, descExpanded]);
+ useEffect(() => {
+ setDescExpanded(false);
+ }, [detail?.id]);
+ useEffect(() => {
+ if (!detail || settingsOpen) return;
+ setSettingsSharingScope(detail.sharingScope === "public_link" ? "company" : detail.sharingScope);
+ setSettingsCategoryDraft(detail.categories.join(", "));
+ }, [detail, settingsOpen]);
+ const sortedVersions = [...versions].sort((a, b) => b.revisionNumber - a.revisionNumber);
+ const [leftVersionId, setLeftVersionId] = useState<string | null>(null);
+ const [rightVersionId, setRightVersionId] = useState<string | null>(null);
+
+ function openVersionDiff(targetVersionId?: string | null) {
+ const selection = getSkillVersionDiffSelection(sortedVersions, targetVersionId);
+ setLeftVersionId(selection.leftVersionId);
+ setRightVersionId(selection.rightVersionId);
+ setDiffOpen(Boolean(selection.rightVersionId));
+ }
+
+ // Track unsaved edits so we can float a save bar and warn before the page is
+ // unloaded with a dirty draft (PAP-10907 J).
+ const savedFileContent = file?.content ?? "";
+ const isDirty = editMode && Boolean(file?.editable) && draft !== savedFileContent;
+ useEffect(() => {
+ if (!isDirty) return;
+ const handler = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ event.returnValue = "";
+ };
+ window.addEventListener("beforeunload", handler);
+ return () => window.removeEventListener("beforeunload", handler);
+ }, [isDirty]);
+
+ if (!detail) {
+ return loading ? <PageSkeleton variant="detail" /> : <EmptyState icon={Boxes} message="Skill not found." />;
+ }
+
+ const skill = detail;
+ const resolvedStudioHref = studioHref ?? skillStudioRoute(skill.id);
+ const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
+ const SourceIcon = source.icon;
+ const body = file?.markdown ? stripFrontmatter(file.content) : file?.content ?? "";
+ const currentPin = shortRef(skill.sourceRef);
+ const latestPin = shortRef(updateStatus?.latestRef);
+ const selectedVersion = versions.find((version) => version.id === currentVersionSelection(skill)) ?? null;
+ const subtitleText = resolveSkillSummaryText(skill) ?? source.label;
+ const settingsCategories = splitCategoryDraft(settingsCategoryDraft);
+ const settingsCategoriesDirty = categorySetKey(settingsCategories) !== categorySetKey(skill.categories);
+ const settingsSharingDirty = settingsSharingScope !== (skill.sharingScope === "public_link" ? "company" : skill.sharingScope);
+ const settingsDirty = settingsCategoriesDirty || settingsSharingDirty;
+ // Look up the richer agent record (icon, paused) for agents using this skill.
+ const attachAgentMetaById = new Map(attachAgents.map((agent) => [agent.id, agent]));
+
+ // Sidebar provenance: prefer the rich upstream attribution from the catalog
+ // entry (GitHub owner/repo/path with a real link). Catalog-installed skills
+ // only persist a local staging path, so without this they'd show a long,
+ // unhelpful filesystem path (PAP-10907).
+ const githubSource = catalogSource && catalogSource.type === "github" ? catalogSource : null;
+ const githubLabel = githubSource
+ ? githubSource.hostname === "github.com"
+ ? "GitHub"
+ : githubSource.hostname
+ : null;
+ const githubRepoText = githubSource
+ ? `${githubSource.owner}/${githubSource.repo}${githubSource.path ? `/${githubSource.path}` : ""}`
+ : null;
+ const githubHref = githubSource
+ ? githubSource.url
+ ?? `https://${githubSource.hostname}/${githubSource.owner}/${githubSource.repo}/tree/${githubSource.ref}/${githubSource.path}`.replace(/\/$/, "")
+ : null;
+ // Fallback for non-catalog skills: the recorded locator/path wraps inside
+ // the narrow sidebar instead of widening the page.
+ const sourceLocatorText = skill.sourcePath || skill.sourceLocator || null;
+ const sourceHref =
+ skill.homepageUrl
+ ?? (sourceLocatorText && /^(https?:\/\/|[\w.-]+\.[a-z]{2,}\/)/i.test(sourceLocatorText)
+ ? sourceLocatorText.startsWith("http")
+ ? sourceLocatorText
+ : `https://${sourceLocatorText}`
+ : null);
+
+ function renderFilesBody() {
+ return (
+ <div className="grid min-h-(--sz-560px) gap-0 lg:grid-cols-(--gtc-28)">
+ <aside className="border-b border-border pb-3 lg:border-b-0 lg:border-r lg:pb-0 lg:pr-3">
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Files</div>
+ <SkillTree
+ nodes={buildTree(skill.fileInventory)}
+ skillId={skill.id}
+ selectedPath={selectedPath}
+ expandedDirs={expandedDirs}
+ onToggleDir={onToggleDir}
+ onSelectPath={onSelectPath}
+ fileHref={(_, path) => skillRoute(skill, routeSkills ?? [skill], path)}
+ />
+ </aside>
+ <section className="min-w-0 lg:pl-5">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3 border-b border-border pb-3">
+ <div className="min-w-0 truncate font-mono text-sm">{file?.path ?? selectedPath}</div>
+ <div className="flex items-center gap-2">
+ {file?.markdown && !editMode ? (
+ <div className="flex items-center border border-border">
+ <button
+ className={cn("px-3 py-1.5 text-sm", viewMode === "preview" ? "text-foreground" : "text-muted-foreground")}
+ onClick={() => setViewMode("preview")}
+ >
+ <span className="flex items-center gap-1.5"><Eye className="h-3.5 w-3.5" /> View</span>
+ </button>
+ <button
+ className={cn("border-l border-border px-3 py-1.5 text-sm", viewMode === "code" ? "text-foreground" : "text-muted-foreground")}
+ onClick={() => setViewMode("code")}
+ >
+ <span className="flex items-center gap-1.5"><Code2 className="h-3.5 w-3.5" /> Code</span>
+ </button>
+ </div>
+ ) : null}
+ {skill.editable && file?.editable ? (
+ editMode ? (
+ <>
+ <Button variant="ghost" size="sm" onClick={() => setEditMode(false)} disabled={savePending}>Cancel</Button>
+ <Button size="sm" onClick={onSave} disabled={savePending}>
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {savePending ? "Saving..." : "Save"}
+ </Button>
+ </>
+ ) : (
+ <Button variant="ghost" size="sm" onClick={() => setEditMode(true)}>
+ <Pencil className="mr-1.5 h-3.5 w-3.5" /> Edit
+ </Button>
+ )
+ ) : !skill.editable ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onFork}
+ title={skill.editableReason ?? "Fork this skill to edit it."}
+ >
+ <GitFork className="mr-1.5 h-3.5 w-3.5" />
+ Fork
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ {fileLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : !file ? (
+ <div className="text-sm text-muted-foreground">Select a file to inspect.</div>
+ ) : editMode && file.editable ? (
+ file.markdown ? (
+ <MarkdownEditor value={draft} onChange={setDraft} bordered={false} className="min-h-(--sz-520px)" />
+ ) : (
+ <Textarea
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ className="min-h-(--sz-520px) rounded-none border-0 bg-transparent px-0 py-0 font-mono text-sm shadow-none focus-visible:ring-0"
+ />
+ )
+ ) : file.markdown && viewMode === "preview" ? (
+ <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody>
+ ) : (
+ <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground">
+ <code>{file.content}</code>
+ </pre>
+ )}
+ </section>
+ </div>
+ );
+ }
+
+ function renderOverviewBody() {
+ return (
+ <div className="space-y-6">
+ <section>
+ <h2 className="mb-2 text-sm font-medium">About</h2>
+ {fileLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : file?.markdown ? (
+ <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body || skill.description || "No overview yet."}</MarkdownBody>
+ ) : (
+ <p className="text-sm text-muted-foreground">{skill.description ?? "No overview yet."}</p>
+ )}
+ </section>
+ <section className="grid min-w-0 gap-3 text-sm sm:grid-cols-2">
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Key</div>
+ <div className="mt-1 truncate font-mono">{skill.key}</div>
+ </div>
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Source</div>
+ <div className="mt-1 min-w-0 [overflow-wrap:anywhere]">{sourceLocatorText ?? source.label}</div>
+ </div>
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Version</div>
+ <div className="mt-1">{versionLabel(skill.currentVersion ?? null)}</div>
+ </div>
+ <div className="min-w-0 border-b border-border py-2">
+ <div className="text-xs text-muted-foreground">Mode</div>
+ <div className="mt-1 flex flex-wrap items-center gap-2">
+ {skill.editable ? (
+ "Editable"
+ ) : (
+ <>
+ <span>Read only</span>
+ <Button type="button" variant="outline" size="xs" onClick={onFork}>
+ <GitFork className="mr-1 h-3 w-3" />
+ Fork
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ </section>
+ </div>
+ );
+ }
+
+ function renderVersionsBody() {
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-sm text-muted-foreground">
+ {versionsLoading ? "Loading versions..." : `${versions.length} ${versions.length === 1 ? "version" : "versions"}`}
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => openVersionDiff()}
+ disabled={sortedVersions.length < 2}
+ >
+ <History className="mr-1.5 h-3.5 w-3.5" /> Compare
+ </Button>
+ </div>
+ <div className="border-y border-border">
+ {versionsLoading ? (
+ <PageSkeleton variant="list" />
+ ) : sortedVersions.length === 0 ? (
+ <div className="py-6 text-sm text-muted-foreground">No saved versions yet.</div>
+ ) : (
+ sortedVersions.map((version) => (
+ <div key={version.id} className="grid gap-2 border-b border-border px-0 py-3 text-sm last:border-b-0 sm:grid-cols-(--gtc-13)">
+ <div className="min-w-0">
+ <div className="font-medium">{versionLabel(version)}</div>
+ <div className="mt-1 text-xs text-muted-foreground">
+ {relativeTime(version.createdAt)} · {version.fileInventory.length} files
+ </div>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => openVersionDiff(version.id)}
+ >
+ View diff
+ </Button>
+ </div>
+ ))
+ )}
+ </div>
+ <SkillVersionDiffDialog
+ open={diffOpen}
+ onOpenChange={setDiffOpen}
+ versions={sortedVersions}
+ leftVersionId={leftVersionId}
+ rightVersionId={rightVersionId}
+ onLeftVersionChange={setLeftVersionId}
+ onRightVersionChange={setRightVersionId}
+ />
+ </div>
+ );
+ }
+
+ function renderAgentsBody() {
+ // Only the agents actually using this skill are listed (PAP-10907); the
+ // multi-selector behind "Add to agent" is where you attach more.
+ const attached = skill.usedByAgents;
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm text-muted-foreground">
+ {attached.length} {attached.length === 1 ? "agent" : "agents"} attached
+ {selectedVersion ? ` · ${versionLabel(selectedVersion)}` : " · Latest"}
+ </p>
+ <AttachAgentsPopover
+ agents={attachAgents}
+ attachedAgentIds={attached.map((agent) => agent.id)}
+ versions={versions}
+ selectedVersionId={currentVersionSelection(skill)}
+ pending={attachPending}
+ onSubmit={onSubmitAttach}
+ />
+ </div>
+ {attached.length === 0 ? (
+ <div className="rounded-md border border-dashed border-border py-8 text-center text-sm text-muted-foreground">
+ No agents are using this skill yet. Use “Add to agent” to attach it.
+ </div>
+ ) : (
+ <div className="border-y border-border">
+ {attached.map((agent) => {
+ const meta = attachAgentMetaById.get(agent.id);
+ return (
+ <div key={agent.id} className="flex items-center gap-3 border-b border-border py-3 text-sm last:border-b-0">
+ <AgentIcon icon={meta?.icon ?? null} className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span className="truncate font-medium">{agent.name}</span>
+ {meta?.paused ? (
+ <Badge variant="outline" className="[&>svg]:size-2.5 border-amber-500/30 bg-amber-500/10 px-1.5 text-(length:--text-nano) uppercase tracking-wide text-amber-500">
+ <Pause className="h-2.5 w-2.5" aria-hidden="true" />
+ Paused
+ </Badge>
+ ) : null}
+ </div>
+ <div className="mt-0.5 text-xs text-muted-foreground">{agent.adapterType}</div>
+ </div>
+ <Link
+ to={`/agents/${agent.urlKey}/skills`}
+ className="shrink-0 text-xs text-muted-foreground no-underline hover:text-foreground"
+ >
+ View
+ </Link>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ const tabBody = activeTab === "files"
+ ? renderFilesBody()
+ : activeTab === "versions"
+ ? renderVersionsBody()
+ : activeTab === "agents"
+ ? renderAgentsBody()
+ : renderOverviewBody();
+
+ return (
+ <div className="min-h-(--sz-calc-30)">
+ <div className="border-b border-border px-4 py-5">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-start gap-3">
+ <SkillCardIcon
+ card={{
+ key: detail.key,
+ name: detail.name,
+ slug: detail.slug,
+ iconUrl: detail.iconUrl,
+ color: detail.color,
+ }}
+ size={44}
+ />
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <h1 className="truncate text-2xl font-semibold">{detail.name}</h1>
+ {/* Source icon sits right after the title; the tooltip names
+ where the skill was installed from (PAP-10907). */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground"
+ aria-label={`Installed from ${source.label}`}
+ >
+ <SourceIcon className="h-4 w-4" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Installed from {source.label}</TooltipContent>
+ </Tooltip>
+ </div>
+ {/* GitHub-style "by" attribution sits directly under the title. */}
+ {detail.authorName ? (
+ <p className="mt-0.5 text-sm text-muted-foreground">
+ by <span className="text-foreground">{detail.authorName}</span>
+ </p>
+ ) : null}
+ {subtitleText ? (
+ <div className="mt-1 max-w-2xl">
+ <p
+ ref={descriptionRef}
+ className={cn(
+ "text-sm text-muted-foreground",
+ !descExpanded && "line-clamp-4",
+ )}
+ >
+ {subtitleText}
+ </p>
+ {descClamped ? (
+ <button
+ type="button"
+ onClick={() => setDescExpanded((value) => !value)}
+ className="mt-0.5 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {descExpanded ? "Show less" : "View all"}
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ {detail.categories.slice(0, 4).map((category) => (
+ <SkillCategoryChip key={category} label={category} />
+ ))}
+ </div>
+ </div>
+ {/* GitHub-style social proof, top-right: installs · stars · fork.
+ "Installs" counts agents that currently have this skill attached
+ (PAP-10907); stars and fork are interactive. */}
+ <div className="flex flex-wrap items-center justify-end gap-1">
+ <Button variant="outline" size="sm" asChild>
+ <Link to={resolvedStudioHref}>
+ <FlaskConical className="mr-1.5 h-3.5 w-3.5" />
+ Open in Studio
+ </Link>
+ </Button>
+ <div className="flex items-center overflow-hidden rounded-md border border-border">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs text-muted-foreground">
+ <Download className="h-3.5 w-3.5" aria-hidden="true" />
+ <span className="font-medium text-foreground">{detail.attachedAgentCount}</span>
+ <span className="hidden sm:inline">{detail.attachedAgentCount === 1 ? "install" : "installs"}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Agents in this company that currently have this skill installed.</TooltipContent>
+ </Tooltip>
+ <button
+ type="button"
+ onClick={onToggleStar}
+ disabled={starPending}
+ className="inline-flex items-center gap-1.5 border-l border-border px-2.5 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground disabled:opacity-50"
+ title={detail.starredByCurrentActor ? "Unstar this skill" : "Star this skill"}
+ >
+ <Star className={cn("h-3.5 w-3.5", detail.starredByCurrentActor && "fill-current text-yellow-400")} />
+ <span className="hidden sm:inline">{detail.starredByCurrentActor ? "Starred" : "Star"}</span>
+ <span className="font-medium text-foreground">{detail.starCount}</span>
+ </button>
+ <button
+ type="button"
+ onClick={onFork}
+ className="inline-flex items-center gap-1.5 border-l border-border px-2.5 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
+ title="Fork this skill"
+ >
+ <GitFork className="h-3.5 w-3.5" />
+ <span className="hidden sm:inline">Fork</span>
+ <span className="font-medium text-foreground">{detail.forkCount}</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="grid gap-6 px-4 py-4 xl:grid-cols-(--gtc-29)">
+ <main className="min-w-0">
+ <Tabs value={activeTab} onValueChange={(value) => onTabChange(value as SkillDetailTab)}>
+ {/* Underlined tab strip: the bottom padding keeps the active-tab
+ underline inside the horizontal-scroll clip box (PAP-10907). */}
+ <TabsList variant="line" className="mb-5 w-full max-w-full justify-start overflow-x-auto border-b border-border p-0 pb-1.5 [scrollbar-width:none]">
+ {SKILL_DETAIL_TABS.map((tab) => {
+ const Icon = tab.icon;
+ return (
+ <TabsTrigger key={tab.value} value={tab.value} className="px-3">
+ <Icon className="mr-1.5 h-3.5 w-3.5" />
+ {tab.label}
+ </TabsTrigger>
+ );
+ })}
+ </TabsList>
+ </Tabs>
+ {tabBody}
+ </main>
+
+ <aside className="min-w-0 space-y-6 border-t border-border pt-4 xl:border-l xl:border-t-0 xl:pl-5 xl:pt-0">
+ <SkillLocationCard
+ folderPath={folderDisplayPath ?? skillFolderPathDisplayFallback(detail.folderPath)}
+ onMove={onMoveToFolder}
+ />
+ <SkillTagsEditor
+ categories={detail.categories}
+ pending={updateSettingsPending}
+ onSave={(categories) => onUpdateSettings({ categories, sharingScope: detail.sharingScope === "public_link" ? "company" : detail.sharingScope })}
+ />
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Agents</div>
+ <div className="space-y-3">
+ {/* Big primary action opens the agent multi-selector (PAP-10907). */}
+ <AttachAgentsPopover
+ agents={attachAgents}
+ attachedAgentIds={detail.usedByAgents.map((agent) => agent.id)}
+ versions={versions}
+ selectedVersionId={currentVersionSelection(detail)}
+ pending={attachPending}
+ onSubmit={onSubmitAttach}
+ fullWidth
+ />
+ {detail.usedByAgents.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No agents attached yet.</p>
+ ) : (
+ <div className="space-y-0.5">
+ {/* Preview up to three attached agents, then summarise the rest. */}
+ {detail.usedByAgents.slice(0, 3).map((agent) => {
+ const meta = attachAgentMetaById.get(agent.id);
+ return (
+ <Link
+ key={agent.id}
+ to={`/agents/${agent.urlKey}/skills`}
+ className="flex items-center gap-2 rounded-md px-1.5 py-1 text-sm no-underline hover:bg-accent/40"
+ >
+ <AgentIcon icon={meta?.icon ?? null} className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate text-foreground">{agent.name}</span>
+ {meta?.paused ? (
+ <Pause className="h-3 w-3 shrink-0 text-amber-500" aria-label="Paused" />
+ ) : null}
+ </Link>
+ );
+ })}
+ {detail.usedByAgents.length > 3 ? (
+ <p className="px-1.5 pt-0.5 text-xs text-muted-foreground">
+ and {detail.usedByAgents.length - 3} more
+ </p>
+ ) : null}
+ </div>
+ )}
+ </div>
+ </section>
+
+ {/* Provenance: where this skill came from, with org/path linked when
+ available. Bundled/catalog skills surface their source label too
+ (PAP-10907). */}
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Source</div>
+ {githubSource ? (
+ <div className="flex items-start gap-2 text-sm">
+ <GithubIcon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <div className="min-w-0">
+ <div className="text-foreground">{githubLabel}</div>
+ <a
+ href={githubHref ?? undefined}
+ target="_blank"
+ rel="noreferrer"
+ title={githubRepoText ?? undefined}
+ className="mt-0.5 flex max-w-full items-start gap-1 text-xs text-muted-foreground no-underline transition-colors [overflow-wrap:anywhere] hover:text-foreground"
+ >
+ <span className="min-w-0 [overflow-wrap:anywhere]">{githubRepoText}</span>
+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />
+ </a>
+ <div className="mt-0.5 truncate font-mono text-(length:--text-micro) text-muted-foreground" title={githubSource.commit}>
+ {githubSource.ref}
+ {githubSource.commit ? ` · ${githubSource.commit.slice(0, 7)}` : ""}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="flex items-start gap-2 text-sm">
+ <SourceIcon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <div className="min-w-0">
+ <div className="text-foreground">{source.label}</div>
+ {sourceLocatorText ? (
+ sourceHref ? (
+ <a
+ href={sourceHref}
+ target="_blank"
+ rel="noreferrer"
+ title={sourceLocatorText ?? undefined}
+ className="mt-0.5 flex max-w-full items-start gap-1 text-xs text-muted-foreground no-underline transition-colors [overflow-wrap:anywhere] hover:text-foreground"
+ >
+ <span className="min-w-0 [overflow-wrap:anywhere]">{sourceLocatorText}</span>
+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden="true" />
+ </a>
+ ) : (
+ <div className="mt-0.5 min-w-0 text-xs text-muted-foreground [overflow-wrap:anywhere]" title={sourceLocatorText ?? undefined}>
+ {sourceLocatorText}
+ </div>
+ )
+ ) : (
+ <div className="mt-0.5 text-xs text-muted-foreground">{source.managedLabel}</div>
+ )}
+ </div>
+ </div>
+ )}
+ </section>
+
+ {/* Revision / update controls sit under Agents, above the config gear
+ (PAP-10907 F). Only GitHub-sourced skills can pull updates. */}
+ {detail.sourceType === "github" ? (
+ <section>
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Updates</div>
+ <div className="space-y-2">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Pin className="h-3.5 w-3.5 shrink-0" aria-label="Pinned source revision" />
+ </TooltipTrigger>
+ <TooltipContent>Pinned source revision</TooltipContent>
+ </Tooltip>
+ <span className="truncate font-mono text-foreground">{currentPin ?? "untracked"}</span>
+ </div>
+ <Button variant="outline" size="sm" className="w-full" onClick={onCheckUpdates} disabled={checkUpdatesPending || updateStatusLoading}>
+ <RefreshCw className={cn("mr-1.5 h-3.5 w-3.5", (checkUpdatesPending || updateStatusLoading) && "animate-spin")} />
+ Check for updates
+ </Button>
+ {updateStatus?.supported && updateStatus.hasUpdate ? (
+ <Button size="sm" className="w-full" onClick={onInstallUpdate} disabled={installUpdatePending}>
+ <ArrowUpCircle className={cn("mr-1.5 h-3.5 w-3.5", installUpdatePending && "animate-spin")} />
+ Install update{latestPin ? ` ${latestPin}` : ""}
+ </Button>
+ ) : updateStatus?.supported && !updateStatus.hasUpdate && !updateStatusLoading ? (
+ <p className="text-xs text-muted-foreground">Up to date.</p>
+ ) : null}
+ </div>
+ </section>
+ ) : null}
+
+ {/* Config lives behind a gear; sharing + danger zone open in a modal
+ (PAP-10907 A). */}
+ <section>
+ <button
+ type="button"
+ onClick={() => {
+ setSettingsSharingScope(detail.sharingScope === "public_link" ? "company" : detail.sharingScope);
+ setSettingsCategoryDraft(detail.categories.join(", "));
+ setSettingsOpen(true);
+ }}
+ className="flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm text-muted-foreground transition-colors hover:bg-accent/30 hover:text-foreground"
+ >
+ <Settings className="h-4 w-4 shrink-0" />
+ <span className="flex-1">Settings</span>
+ </button>
+ </section>
+ </aside>
+ </div>
+
+ {/* Floating save bar: stays visible while a file edit is dirty so the
+ unsaved state is obvious (PAP-10907 J). */}
+ {isDirty ? (
+ <div className="fixed bottom-6 left-1/2 z-40 flex -translate-x-1/2 items-center gap-3 rounded-full border border-border bg-background/95 px-4 py-2 shadow-lg backdrop-blur">
+ <span className="text-sm text-muted-foreground">Unsaved changes</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setDraft(savedFileContent);
+ setEditMode(false);
+ }}
+ disabled={savePending}
+ >
+ Discard
+ </Button>
+ <Button size="sm" onClick={onSave} disabled={savePending}>
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {savePending ? "Saving…" : "Save changes"}
+ </Button>
+ </div>
+ ) : null}
+ <Dialog open={settingsOpen} onOpenChange={setSettingsOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Skill settings</DialogTitle>
+ <DialogDescription>Manage how {detail.name} is grouped and shared.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-5">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Categories</label>
+ <Input
+ value={settingsCategoryDraft}
+ onChange={(event) => setSettingsCategoryDraft(event.target.value)}
+ placeholder="engineering, review, memory"
+ className="h-9"
+ disabled={updateSettingsPending}
+ />
+ <p className="text-xs text-muted-foreground">Separate categories with commas. Leave empty to clear categories.</p>
+ </div>
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Sharing</label>
+ <select
+ value={settingsSharingScope}
+ onChange={(event) => setSettingsSharingScope(event.target.value as Exclude<CompanySkillSharingScope, "public_link">)}
+ disabled={updateSettingsPending}
+ className="h-9 w-full rounded-md border border-border bg-background px-2 text-sm text-foreground"
+ >
+ <option value="company">Company — visible inside this company</option>
+ <option value="private">Private — only visible in your library</option>
+ </select>
+ <p className="text-xs text-muted-foreground">Public link sharing is coming later.</p>
+ </div>
+ <div className="flex justify-end gap-2 border-t border-border pt-4">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setSettingsSharingScope(skill.sharingScope === "public_link" ? "company" : skill.sharingScope);
+ setSettingsCategoryDraft(skill.categories.join(", "));
+ }}
+ disabled={!settingsDirty || updateSettingsPending}
+ >
+ Reset
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={() => onUpdateSettings({ sharingScope: settingsSharingScope, categories: settingsCategories })}
+ disabled={!settingsDirty || updateSettingsPending}
+ >
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {updateSettingsPending ? "Saving…" : "Save settings"}
+ </Button>
+ </div>
+ {detail.editable ? (
+ <div className="rounded-md border border-destructive/40 p-3">
+ <div className="text-xs font-semibold uppercase tracking-wide text-destructive">Danger zone</div>
+ <div className="mt-2 flex items-center justify-between gap-3">
+ <p className="min-w-0 text-xs text-muted-foreground">Remove this skill from the company library.</p>
+ <Button
+ variant="destructive"
+ size="sm"
+ className="shrink-0"
+ onClick={onDelete}
+ disabled={deletePending}
+ title={detail.usedByAgents.length > 0 ? "Detach this skill from all agents before removing it." : undefined}
+ >
+ <Trash2 className="mr-1.5 h-3.5 w-3.5" />
+ {deletePending ? "Removing…" : "Remove"}
+ </Button>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+function SkillPane({
+ loading,
+ detail,
+ file,
+ fileLoading,
+ updateStatus,
+ updateStatusLoading,
+ viewMode,
+ editMode,
+ draft,
+ setViewMode,
+ setEditMode,
+ setDraft,
+ onCheckUpdates,
+ checkUpdatesPending,
+ onInstallUpdate,
+ installUpdatePending,
+ onDelete,
+ deletePending,
+ onSave,
+ savePending,
+ attachAgents,
+ versions,
+ onSubmitAttach,
+ attachPending,
+}: {
+ loading: boolean;
+ detail: CompanySkillDetail | null | undefined;
+ file: CompanySkillFileDetail | null | undefined;
+ fileLoading: boolean;
+ updateStatus: CompanySkillUpdateStatus | null | undefined;
+ updateStatusLoading: boolean;
+ viewMode: "preview" | "code";
+ editMode: boolean;
+ draft: string;
+ setViewMode: (mode: "preview" | "code") => void;
+ setEditMode: (value: boolean) => void;
+ setDraft: (value: string) => void;
+ onCheckUpdates: () => void;
+ checkUpdatesPending: boolean;
+ onInstallUpdate: () => void;
+ installUpdatePending: boolean;
+ onDelete: () => void;
+ deletePending: boolean;
+ onSave: () => void;
+ savePending: boolean;
+ attachAgents: AttachAgentOption[];
+ versions: CompanySkillVersion[];
+ onSubmitAttach: (ids: string[], versionId: string | null) => void;
+ attachPending: boolean;
+}) {
+ if (!detail) {
+ if (loading) {
+ return <PageSkeleton variant="detail" />;
+ }
+ return (
+ <EmptyState
+ icon={Boxes}
+ message="Select a skill to inspect its files."
+ />
+ );
+ }
+
+ const source = sourceMeta(detail.sourceBadge, detail.sourceLabel);
+ const SourceIcon = source.icon;
+ const usedBy = detail.usedByAgents;
+ const body = file?.markdown ? stripFrontmatter(file.content) : file?.content ?? "";
+ const currentPin = shortRef(detail.sourceRef);
+ const latestPin = shortRef(updateStatus?.latestRef);
+ const displaySourcePath = detail.sourcePath ? middleTruncate(detail.sourcePath) : null;
+ const removeBlocked = usedBy.length > 0;
+ const removeDisabledReason = removeBlocked
+ ? "Detach this skill from all agents before removing it."
+ : null;
+
+ return (
+ <div className="min-w-0">
+ <div className="border-b border-border px-5 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h1 className="flex items-center gap-2 truncate text-2xl font-semibold">
+ <SourceIcon className="h-5 w-5 shrink-0 text-muted-foreground" />
+ {detail.name}
+ </h1>
+ {detail.description && (
+ <p className="mt-2 max-w-3xl text-sm text-muted-foreground">{detail.description}</p>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <Button variant="outline" size="sm" asChild>
+ <Link to={skillStudioRoute(detail.id)}>
+ <FlaskConical className="mr-1.5 h-3.5 w-3.5" />
+ Open in Studio
+ </Link>
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onDelete}
+ disabled={deletePending}
+ title={removeDisabledReason ?? undefined}
+ >
+ <Trash2 className="mr-1.5 h-3.5 w-3.5" />
+ {deletePending ? "Removing..." : "Remove"}
+ </Button>
+ {detail.editable ? (
+ <button
+ className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
+ onClick={() => setEditMode(!editMode)}
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ {editMode ? "Stop editing" : "Edit"}
+ </button>
+ ) : (
+ <div className="text-sm text-muted-foreground">{detail.editableReason}</div>
+ )}
+ </div>
+ </div>
+
+ <div className="mt-4 space-y-3 border-t border-border pt-4 text-sm">
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">Source</span>
+ <span className="flex min-w-0 items-center gap-2">
+ <SourceIcon className="h-3.5 w-3.5 text-muted-foreground" />
+ {detail.sourcePath && displaySourcePath ? (
+ <>
+ <span
+ className="block min-w-0 max-w-(--sz-calc-35) truncate font-mono text-xs text-muted-foreground"
+ title={detail.sourcePath}
+ >
+ {displaySourcePath}
+ </span>
+ <CopyText
+ text={detail.sourcePath}
+ copiedLabel="Copied path"
+ ariaLabel="Copy source path"
+ title="Copy source path"
+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-sm border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </CopyText>
+ </>
+ ) : (
+ <span className="truncate">{source.label}</span>
+ )}
+ </span>
+ </div>
+ {detail.sourceType === "github" && (
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">Pin</span>
+ <span className="font-mono text-xs">{currentPin ?? "untracked"}</span>
+ {updateStatus?.trackingRef && (
+ <span className="text-xs text-muted-foreground">tracking {updateStatus.trackingRef}</span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onCheckUpdates}
+ disabled={checkUpdatesPending || updateStatusLoading}
+ >
+ <RefreshCw className={cn("mr-1.5 h-3.5 w-3.5", (checkUpdatesPending || updateStatusLoading) && "animate-spin")} />
+ Check for updates
+ </Button>
+ {updateStatus?.supported && updateStatus.hasUpdate && (
+ <Button
+ size="sm"
+ onClick={onInstallUpdate}
+ disabled={installUpdatePending}
+ >
+ <RefreshCw className={cn("mr-1.5 h-3.5 w-3.5", installUpdatePending && "animate-spin")} />
+ Install update{latestPin ? ` ${latestPin}` : ""}
+ </Button>
+ )}
+ {updateStatus?.supported && !updateStatus.hasUpdate && !updateStatusLoading && (
+ <span className="text-xs text-muted-foreground">Up to date</span>
+ )}
+ {!updateStatus?.supported && updateStatus?.reason && (
+ <span className="text-xs text-muted-foreground">{updateStatus.reason}</span>
+ )}
+ </div>
+ )}
+ <div className="flex items-center gap-2">
+ <span className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">Key</span>
+ <span className="font-mono text-xs">{detail.key}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">Mode</span>
+ <span>{detail.editable ? "Editable" : "Read only"}</span>
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">Trust</span>
+ <TrustChip level={detail.trustLevel} />
+ <CompatChip compatibility={detail.compatibility} />
+ {readonlyMetadataValue(detail.metadata, "userModifiedAt") ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="outline" className="border-violet-500/40 bg-violet-500/10 text-(length:--text-micro) text-violet-200">
+ <Pencil className="h-3 w-3" aria-hidden="true" />
+ Locally modified
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>You have edited this skill after installing. Updates from the catalog will overwrite your changes.</TooltipContent>
+ </Tooltip>
+ ) : null}
+ {(() => {
+ const packageName = readonlyMetadataValue(detail.metadata, "originPackageName") ?? readonlyMetadataValue(detail.metadata, "catalogPackageName");
+ const packageVersion = readonlyMetadataValue(detail.metadata, "originVersion") ?? readonlyMetadataValue(detail.metadata, "catalogPackageVersion");
+ return <ProvenanceBadge packageName={packageName} packageVersion={packageVersion} />;
+ })()}
+ </div>
+ <div className="flex flex-wrap items-start gap-x-3 gap-y-2">
+ <div className="flex items-center gap-2">
+ <span className="text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-muted-foreground">Used by</span>
+ <AttachAgentsPopover
+ agents={attachAgents}
+ attachedAgentIds={usedBy.map((agent) => agent.id)}
+ versions={versions}
+ selectedVersionId={usedBy.find((agent) => agent.versionId)?.versionId ?? null}
+ pending={attachPending}
+ onSubmit={onSubmitAttach}
+ />
+ </div>
+ {usedBy.length === 0 ? (
+ <span className="text-muted-foreground">No agents attached</span>
+ ) : (
+ <div className="grid w-full grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {usedBy.map((agent) => (
+ <Link
+ key={agent.id}
+ to={`/agents/${agent.urlKey}/skills`}
+ className="group rounded-md border border-transparent p-2 no-underline hover:border-border hover:bg-accent/40"
+ >
+ <Identity name={agent.name} size="sm" />
+ </Link>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="border-b border-border px-5 py-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-0">
+ <div className="truncate font-mono text-sm">{file?.path ?? "SKILL.md"}</div>
+ </div>
+ <div className="flex items-center gap-2">
+ {file?.markdown && !editMode && (
+ <div className="flex items-center border border-border">
+ <button
+ className={cn("px-3 py-1.5 text-sm", viewMode === "preview" && "text-foreground", viewMode !== "preview" && "text-muted-foreground")}
+ onClick={() => setViewMode("preview")}
+ >
+ <span className="flex items-center gap-1.5">
+ <Eye className="h-3.5 w-3.5" />
+ View
+ </span>
+ </button>
+ <button
+ className={cn("border-l border-border px-3 py-1.5 text-sm", viewMode === "code" && "text-foreground", viewMode !== "code" && "text-muted-foreground")}
+ onClick={() => setViewMode("code")}
+ >
+ <span className="flex items-center gap-1.5">
+ <Code2 className="h-3.5 w-3.5" />
+ Code
+ </span>
+ </button>
+ </div>
+ )}
+ {editMode && file?.editable && (
+ <>
+ <Button variant="ghost" size="sm" onClick={() => setEditMode(false)} disabled={savePending}>
+ Cancel
+ </Button>
+ <Button size="sm" onClick={onSave} disabled={savePending}>
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {savePending ? "Saving..." : "Save"}
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="min-h-(--sz-560px) px-5 py-5">
+ {fileLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : !file ? (
+ <div className="text-sm text-muted-foreground">Select a file to inspect.</div>
+ ) : editMode && file.editable ? (
+ file.markdown ? (
+ <MarkdownEditor
+ value={draft}
+ onChange={setDraft}
+ bordered={false}
+ className="min-h-(--sz-520px)"
+ />
+ ) : (
+ <Textarea
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ className="min-h-(--sz-520px) rounded-none border-0 bg-transparent px-0 py-0 font-mono text-sm shadow-none focus-visible:ring-0"
+ />
+ )
+ ) : file.markdown && viewMode === "preview" ? (
+ <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody>
+ ) : (
+ <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground">
+ <code>{file.content}</code>
+ </pre>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export function CompanySkills() {
+ const { "*": routePath } = useParams<{ "*": string }>();
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const { pushToast } = useToastActions();
+ const adapterCaps = useAdapterCapabilities();
+ const policyDenial = useSkillPolicyDenial();
+ // Route a failed skill mutation to the persistent policy banner when it is an
+ // explicit-policy (State B) or platform-safety (State C) denial; otherwise keep
+ // the existing transient error toast. This is the core "actionable denial only
+ // for real restrictions" behavior from §9.10 (PAP-13865).
+ const reportSkillError = (error: unknown, title: string, fallbackBody: string, actionLabel?: string) => {
+ if (policyDenial.capture(error, actionLabel)) return;
+ pushToast({
+ tone: "error",
+ title,
+ body: error instanceof Error && error.message ? error.message : fallbackBody,
+ });
+ };
+ const [skillFilter, setSkillFilter] = useState("");
+ const [source, setSource] = useState("");
+ const [emptySourceHelpOpen, setEmptySourceHelpOpen] = useState(false);
+ const [expandedSkillId, setExpandedSkillId] = useState<string | null>(null);
+ const [expandedDirs, setExpandedDirs] = useState<Record<string, Set<string>>>({});
+ const [viewMode, setViewMode] = useState<"preview" | "code">("preview");
+ const [editMode, setEditMode] = useState(false);
+ const [draft, setDraft] = useState("");
+ const [displayedDetail, setDisplayedDetail] = useState<CompanySkillDetail | null>(null);
+ const [displayedFile, setDisplayedFile] = useState<CompanySkillFileDetail | null>(null);
+ const [scanStatusMessage, setScanStatusMessage] = useState<string | null>(null);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const [deleteTargetSkillId, setDeleteTargetSkillId] = useState<string | null>(null);
+ const [deleteTargetDetail, setDeleteTargetDetail] = useState<CompanySkillDetail | null>(null);
+ const [catalogFilter, setCatalogFilter] = useState("");
+ const [catalogKindFilter, setCatalogKindFilter] = useState<"all" | "bundled" | "optional">("all");
+ const [catalogCategoryFilter, setCatalogCategoryFilter] = useState<string>("");
+ const [catalogSelectedPath, setCatalogSelectedPath] = useState<string>("SKILL.md");
+ const [expandedCatalogSkillId, setExpandedCatalogSkillId] = useState<string | null>(null);
+ const [expandedCatalogDirs, setExpandedCatalogDirs] = useState<Record<string, Set<string>>>({});
+ const [installDialogState, setInstallDialogState] = useState<{
+ open: boolean;
+ catalogSkill: CatalogSkill | null;
+ conflict: CompanySkillListItem | null;
+ defaultSlug: string | null;
+ defaultForce: boolean;
+ defaultAction: "install" | "update" | "replace";
+ error: string | null;
+ }>({ open: false, catalogSkill: null, conflict: null, defaultSlug: null, defaultForce: false, defaultAction: "install", error: null });
+ const [discoverySearch, setDiscoverySearch] = useState("");
+ const [discoverySort, setDiscoverySort] = useState<DiscoverySort>("agents");
+ const [createError, setCreateError] = useState<string | null>(null);
+ const [importDialogOpen, setImportDialogOpen] = useState(false);
+ const [importFromProjectOpen, setImportFromProjectOpen] = useState(false);
+ const [folderDialogOpen, setFolderDialogOpen] = useState(false);
+ const [folderDialogTarget, setFolderDialogTarget] = useState<FolderListItem | null>(null);
+ const [folderDialogParentId, setFolderDialogParentId] = useState<string | null>(null);
+ const [deleteFolderTarget, setDeleteFolderTarget] = useState<FolderListItem | null>(null);
+ const [mobileFoldersOpen, setMobileFoldersOpen] = useState(false);
+ // Rich move-to-folder dialog (tree picker + inline new-folder + path preview).
+ const [moveDialog, setMoveDialog] = useState<
+ { skillIds: string[]; title: string; subtitle: string | null; currentFolderId: string | null } | null
+ >(null);
+ const [selectMode, setSelectMode] = useState(false);
+ const [selectedSkillIds, setSelectedSkillIds] = useState<string[]>([]);
+ const [moveAfterCreateSkillIds, setMoveAfterCreateSkillIds] = useState<string[]>([]);
+ const parsedRoute = useMemo(() => parseSkillRoute(routePath), [routePath]);
+ const isStudioNew = routePath === "studio/new";
+ const routeSkillToken = isStudioNew ? null : parsedRoute.skillToken;
+ const selectedPath = parsedRoute.filePath;
+ const viewParam = searchParams.get("view");
+ const activeView: "installed" | "catalog" = viewParam === "catalog" ? "catalog" : "installed";
+ const sourceFilterParam = searchParams.get("source") ?? "all";
+ const sourceFilter: SourceFilter = (["all", "company", "bundled", "optional", "external"] as SourceFilter[]).includes(sourceFilterParam as SourceFilter)
+ ? (sourceFilterParam as SourceFilter)
+ : "all";
+ const selectedCatalogRef = searchParams.get("catalog");
+ const tabParam = searchParams.get("tab");
+ const discoveryTab = resolveDiscoveryTab(tabParam);
+ const detailTab: SkillDetailTab = (["overview", "files", "versions", "agents"] as SkillDetailTab[]).includes(tabParam as SkillDetailTab)
+ ? (tabParam as SkillDetailTab)
+ : parsedRoute.hasExplicitFilePath || selectedPath !== "SKILL.md"
+ ? "files"
+ : "overview";
+ const discoveryCategory = searchParams.get("category");
+ const studioForkFromId = isStudioNew ? searchParams.get("forkFrom")?.trim() || null : null;
+ const studioNewFolderId = isStudioNew ? searchParams.get("folderId")?.trim() || null : null;
+ // Discovery grid owns `/skills` whenever no specific skill or catalog entry is
+ // selected; selecting either drops into the existing master/detail surfaces.
+ const isDiscovery = !isStudioNew && !routeSkillToken && !selectedCatalogRef;
+ const folderSelection = normalizeFolderSelection(searchParams.get("folder"));
+
+ function setDiscoveryTab(tab: DiscoveryTab) {
+ setSearchParams((current) => withDiscoveryTab(current, tab));
+ }
+
+ function setFolderSelection(selection: FolderSelection) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ params.set("tab", "installed");
+ params.delete("category");
+ const value = folderSearchValue(selection);
+ if (value) params.set("folder", value);
+ else params.delete("folder");
+ return params;
+ });
+ }
+
+ function openCreateFolder(moveSkillIds: string[] = [], parentId: string | null = null) {
+ setMoveAfterCreateSkillIds(moveSkillIds);
+ setFolderDialogTarget(null);
+ setFolderDialogParentId(parentId);
+ setFolderDialogOpen(true);
+ }
+
+ function setDetailTab(tab: SkillDetailTab) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (tab === "overview") params.delete("tab");
+ else params.set("tab", tab);
+ return params;
+ });
+ }
+
+ function setDiscoveryCategory(slug: string | null) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (slug) params.set("category", slug);
+ else params.delete("category");
+ return params;
+ });
+ }
+
+ function setSourceFilter(next: SourceFilter) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (next === "all") params.delete("source");
+ else params.set("source", next);
+ return params;
+ });
+ }
+
+ function selectCatalog(catalogRef: string | null, path = "SKILL.md") {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (catalogRef) params.set("catalog", catalogRef);
+ else params.delete("catalog");
+ return params;
+ });
+ setCatalogSelectedPath(path);
+ }
+
+ useEffect(() => {
+ if (!isStudioNew) return;
+ setCreateError(null);
+ }, [isStudioNew, studioForkFromId]);
+
+ // The old split catalog view no longer exists — catalog/bundled skills now open
+ // as a regular full page keyed by `?catalog=<ref>`. Strip the legacy `view`
+ // param so stale `?view=catalog` deep links land on the new surface (PAP-10907).
+ useEffect(() => {
+ if (!searchParams.has("view")) return;
+ setSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete("view");
+ return next;
+ },
+ { replace: true },
+ );
+ }, [searchParams, setSearchParams]);
+
+ const skillsQuery = useQuery({
+ queryKey: queryKeys.companySkills.list(selectedCompanyId ?? ""),
+ queryFn: () => companySkillsApi.list(selectedCompanyId!),
+ enabled: Boolean(selectedCompanyId),
+ });
+ const skillFoldersQuery = useQuery({
+ queryKey: queryKeys.folders.list(selectedCompanyId ?? "", "skill"),
+ queryFn: () => foldersApi.list(selectedCompanyId!, "skill"),
+ enabled: Boolean(selectedCompanyId && ((isDiscovery && discoveryTab === "installed") || routeSkillToken)),
+ });
+
+ const installedSkills = skillsQuery.data ?? [];
+ const routeResolution = useMemo(
+ () => resolveSkillRouteToken(routeSkillToken, installedSkills),
+ [routeSkillToken, installedSkills],
+ );
+
+ // At `/skills` root the discovery grid is shown, so we no longer auto-select
+ // the first skill; a skill is only "selected" once it is in the route.
+ const selectedSkillId = routeResolution.skill?.id ?? null;
+
+ const detailQuery = useQuery({
+ queryKey: queryKeys.companySkills.detail(selectedCompanyId ?? "", selectedSkillId ?? ""),
+ queryFn: () => companySkillsApi.detail(selectedCompanyId!, selectedSkillId!),
+ enabled: Boolean(selectedCompanyId && selectedSkillId),
+ });
+
+ const fileQuery = useQuery({
+ queryKey: queryKeys.companySkills.file(selectedCompanyId ?? "", selectedSkillId ?? "", selectedPath),
+ queryFn: () => companySkillsApi.file(selectedCompanyId!, selectedSkillId!, selectedPath),
+ enabled: Boolean(selectedCompanyId && selectedSkillId && selectedPath),
+ });
+
+ const versionsQuery = useQuery({
+ queryKey: queryKeys.companySkills.versions(selectedCompanyId ?? "", selectedSkillId ?? ""),
+ queryFn: () => companySkillsApi.versions(selectedCompanyId!, selectedSkillId!),
+ enabled: Boolean(selectedCompanyId && selectedSkillId),
+ });
+
+ const studioForkDetailQuery = useQuery({
+ queryKey: queryKeys.companySkills.detail(selectedCompanyId ?? "", studioForkFromId ?? ""),
+ queryFn: () => companySkillsApi.detail(selectedCompanyId!, studioForkFromId!),
+ enabled: Boolean(selectedCompanyId && isStudioNew && studioForkFromId),
+ });
+
+ const studioDraft = useMemo(() => {
+ if (!isStudioNew) return buildBlankSkillDraft();
+ const base = studioForkFromId
+ ? (studioForkDetailQuery.data ? buildForkSkillDraft(studioForkDetailQuery.data) : buildBlankSkillDraft())
+ : buildBlankSkillDraft();
+ // New skills created from a folder context (e.g. My Skills) default their
+ // destination folder to that folder (PAP-14038).
+ return studioNewFolderId ? { ...base, folderId: studioNewFolderId } : base;
+ }, [isStudioNew, studioForkDetailQuery.data, studioForkFromId, studioNewFolderId]);
+
+ // The writable folder to seed a new skill into when creating from the browser.
+ const defaultNewSkillFolderId = useMemo(() => {
+ if (folderSelection === "all" || folderSelection === "unfiled") return null;
+ const model = treeFromResult(skillFoldersQuery.data);
+ const folder = model.byId.get(folderSelection);
+ if (!folder) return null;
+ // Never seed into read-only reserved subtrees (Bundled / Projects).
+ if (folder.path === "bundled" || folder.path.startsWith("bundled/")) return null;
+ if (folder.path === "projects" || folder.path.startsWith("projects/")) return null;
+ return folder.id;
+ }, [folderSelection, skillFoldersQuery.data]);
+
+ const updateStatusQuery = useQuery({
+ queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId ?? "", selectedSkillId ?? ""),
+ queryFn: () => companySkillsApi.updateStatus(selectedCompanyId!, selectedSkillId!),
+ enabled: Boolean(
+ selectedCompanyId
+ && selectedSkillId
+ && (detailQuery.data?.sourceType === "github" || displayedDetail?.sourceType === "github"),
+ ),
+ staleTime: 60_000,
+ });
+
+ useEffect(() => {
+ if (!routeResolution.skill || !routeResolution.shouldRedirect || skillsQuery.isLoading) return;
+ const search = searchParams.toString();
+ navigate(
+ {
+ pathname: skillRoute(routeResolution.skill, installedSkills, selectedPath),
+ search: search ? `?${search}` : "",
+ },
+ { replace: true },
+ );
+ }, [installedSkills, navigate, routeResolution, searchParams, selectedPath, skillsQuery.isLoading]);
+
+ useEffect(() => {
+ setExpandedSkillId(selectedSkillId);
+ }, [selectedSkillId]);
+
+ useEffect(() => {
+ if (!selectedSkillId || selectedPath === "SKILL.md") return;
+ const parents = parentDirectoryPaths(selectedPath);
+ if (parents.length === 0) return;
+ setExpandedDirs((current) => {
+ const next = new Set(current[selectedSkillId] ?? []);
+ let changed = false;
+ for (const parent of parents) {
+ if (!next.has(parent)) {
+ next.add(parent);
+ changed = true;
+ }
+ }
+ return changed ? { ...current, [selectedSkillId]: next } : current;
+ });
+ }, [selectedPath, selectedSkillId]);
+
+ useEffect(() => {
+ setEditMode(false);
+ }, [selectedSkillId, selectedPath]);
+
+ useEffect(() => {
+ if (detailQuery.data) {
+ setDisplayedDetail(detailQuery.data);
+ }
+ }, [detailQuery.data]);
+
+ useEffect(() => {
+ if (fileQuery.data) {
+ setDisplayedFile(fileQuery.data);
+ setDraft(fileQuery.data.markdown ? splitFrontmatter(fileQuery.data.content).body : fileQuery.data.content);
+ }
+ }, [fileQuery.data]);
+
+ useEffect(() => {
+ if (selectedSkillId) return;
+ setDisplayedDetail(null);
+ setDisplayedFile(null);
+ }, [selectedSkillId]);
+
+ const activeDetail = detailQuery.data ?? displayedDetail;
+ useEffect(() => {
+ setBreadcrumbs([
+ { label: "Skills", href: "/skills" },
+ ...(isStudioNew
+ ? [{ label: studioForkFromId ? "Fork skill" : "New skill" }]
+ : activeDetail
+ ? skillDetailBreadcrumbs(activeDetail, skillFoldersQuery.data).slice(1)
+ : routeSkillToken
+ ? [{ label: "Detail" }]
+ : []),
+ ]);
+ }, [activeDetail, isStudioNew, routeSkillToken, setBreadcrumbs, skillFoldersQuery.data, studioForkFromId]);
+ const activeFile = fileQuery.data ?? displayedFile;
+
+ function routeForSkill(skill: CompanySkillRouteSubject, path?: string | null) {
+ return skillRoute(skill, withRouteSkill(installedSkills, skill), path);
+ }
+
+ function routeForSkillId(skillId: string, path?: string | null) {
+ const skill = installedSkills.find((entry) => entry.id === skillId)
+ ?? (activeDetail?.id === skillId ? activeDetail : null);
+ return skill ? routeForSkill(skill, path) : skillRoute(skillId, path);
+ }
+
+ function openDeleteDialog() {
+ setDeleteTargetSkillId(selectedSkillId);
+ setDeleteTargetDetail(activeDetail ?? null);
+ setDeleteOpen(true);
+ }
+
+ function closeDeleteDialog(open: boolean) {
+ setDeleteOpen(open);
+ if (!open) {
+ setDeleteTargetSkillId(null);
+ setDeleteTargetDetail(null);
+ }
+ }
+
+ const importSkill = useMutation({
+ mutationFn: (importSource: string) => companySkillsApi.importFromSource(selectedCompanyId!, importSource),
+ onSuccess: async (result) => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
+ if (result.imported[0]) navigate(routeForSkill(result.imported[0]));
+ pushToast({
+ tone: "success",
+ title: "Skills imported",
+ body: `${result.imported.length} skill${result.imported.length === 1 ? "" : "s"} added.`,
+ });
+ if (result.warnings[0]) {
+ pushToast({ tone: "warn", title: "Import warnings", body: result.warnings[0] });
+ }
+ setSource("");
+ },
+ onError: (error) => {
+ reportSkillError(error, "Skill import failed", "Failed to import skill source.", "Importing skills");
+ },
+ });
+
+ const scanProjects = useMutation({
+ mutationFn: (projectId?: string) => companySkillsApi.scanProjects(
+ selectedCompanyId!,
+ projectId ? { projectIds: [projectId] } : {},
+ ),
+ onMutate: (projectId) => {
+ setScanStatusMessage(
+ projectId ? "Refreshing project skills..." : "Scanning project workspaces for skills...",
+ );
+ },
+ onSuccess: async (result) => {
+ setScanStatusMessage("Refreshing skills list...");
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") }),
+ ]);
+ const summary = formatProjectScanSummary(result);
+ setScanStatusMessage(summary);
+ pushToast({
+ tone: "success",
+ title: "Project skill scan complete",
+ body: summary,
+ });
+ if (result.conflicts[0]) {
+ pushToast({
+ tone: "warn",
+ title: "Skill conflicts found",
+ body: result.conflicts[0].reason,
+ });
+ } else if (result.warnings[0]) {
+ pushToast({
+ tone: "warn",
+ title: "Scan warnings",
+ body: result.warnings[0],
+ });
+ }
+ },
+ onError: (error) => {
+ setScanStatusMessage(null);
+ reportSkillError(error, "Project skill scan failed", "Failed to scan project workspaces.", "Scanning projects for skills");
+ },
+ });
+
+
+ const createSkill = useMutation({
+ mutationFn: (payload: CompanySkillCreateRequest) => companySkillsApi.create(selectedCompanyId!, payload),
+ onSuccess: async (skill) => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
+ navigate(routeForSkill(skill));
+ setCreateError(null);
+ pushToast({
+ tone: "success",
+ title: skill.forkedFromSkillId ? "Skill fork created" : "Skill created",
+ body: `${skill.name} is now editable in the Paperclip workspace.`,
+ });
+ },
+ onError: (error) => {
+ const message = error instanceof Error ? error.message : "Failed to create skill.";
+ setCreateError(message);
+ reportSkillError(error, "Skill creation failed", "Failed to create skill.", "Creating a skill");
+ },
+ });
+
+ const saveFile = useMutation({
+ mutationFn: () => companySkillsApi.updateFile(
+ selectedCompanyId!,
+ selectedSkillId!,
+ selectedPath,
+ activeFile?.markdown ? mergeFrontmatter(activeFile.content, draft) : draft,
+ ),
+ onSuccess: async (result) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, selectedSkillId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.file(selectedCompanyId!, selectedSkillId!, selectedPath) }),
+ ]);
+ setDraft(result.markdown ? splitFrontmatter(result.content).body : result.content);
+ setEditMode(false);
+ pushToast({
+ tone: "success",
+ title: "Skill saved",
+ body: result.path,
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Save failed",
+ body: error instanceof Error ? error.message : "Failed to save skill file.",
+ });
+ },
+ });
+
+ const toggleStar = useMutation({
+ mutationFn: () => {
+ if (!activeDetail) throw new Error("Select a skill first.");
+ return activeDetail.starredByCurrentActor
+ ? companySkillsApi.unstar(selectedCompanyId!, activeDetail.id)
+ : companySkillsApi.star(selectedCompanyId!, activeDetail.id);
+ },
+ onSuccess: async () => {
+ if (!activeDetail) return;
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, activeDetail.id) }),
+ ]);
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Star failed",
+ body: error instanceof Error ? error.message : "Failed to update star.",
+ });
+ },
+ });
+
+ const updateSkillSettings = useMutation({
+ mutationFn: (payload: { skillId: string; updates: Pick<CompanySkillUpdateRequest, "categories" | "sharingScope"> }) =>
+ companySkillsApi.update(selectedCompanyId!, payload.skillId, payload.updates),
+ onSuccess: async (skill) => {
+ queryClient.setQueryData<CompanySkillDetail | undefined>(
+ queryKeys.companySkills.detail(selectedCompanyId!, skill.id),
+ (current) => current ? { ...current, ...skill } : current,
+ );
+ queryClient.setQueryData<CompanySkillListItem[] | undefined>(
+ queryKeys.companySkills.list(selectedCompanyId!),
+ (current) => current?.map((entry) => entry.id === skill.id ? { ...entry, ...skill } : entry),
+ );
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, skill.id) }),
+ ]);
+ pushToast({ tone: "success", title: "Skill settings updated", body: skillSettingsToastBody(skill) });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Skill settings update failed",
+ body: error instanceof Error ? error.message : "Failed to update skill settings.",
+ });
+ },
+ });
+
+ const installUpdate = useMutation({
+ mutationFn: () => companySkillsApi.installUpdate(selectedCompanyId!, selectedSkillId!),
+ onSuccess: async (skill) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, selectedSkillId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId!, selectedSkillId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.file(selectedCompanyId!, selectedSkillId!, selectedPath) }),
+ ]);
+ navigate(routeForSkill(skill, selectedPath));
+ pushToast({
+ tone: "success",
+ title: "Skill updated",
+ body: skill.sourceRef ? `Pinned to ${shortRef(skill.sourceRef)}` : skill.name,
+ });
+ },
+ onError: (error) => {
+ reportSkillError(error, "Update failed", "Failed to install skill update.", "Updating this skill");
+ },
+ });
+
+ const catalogListQuery = useQuery({
+ queryKey: queryKeys.companySkills.catalog(),
+ queryFn: () => companySkillsApi.catalogList(),
+ enabled: Boolean(selectedCompanyId),
+ staleTime: 60_000,
+ });
+
+ const catalogDetailQuery = useQuery({
+ queryKey: queryKeys.companySkills.catalogDetail(selectedCatalogRef ?? ""),
+ queryFn: () => companySkillsApi.catalogDetail(selectedCatalogRef!),
+ enabled: Boolean(selectedCompanyId && selectedCatalogRef),
+ staleTime: 60_000,
+ });
+
+ const catalogFileQuery = useQuery({
+ queryKey: queryKeys.companySkills.catalogFile(selectedCatalogRef ?? "", catalogSelectedPath),
+ queryFn: () => companySkillsApi.catalogFile(selectedCatalogRef!, catalogSelectedPath),
+ enabled: Boolean(selectedCompanyId && selectedCatalogRef && catalogSelectedPath),
+ staleTime: 60_000,
+ });
+
+ const agentsQuery = useQuery({
+ queryKey: queryKeys.agents.list(selectedCompanyId ?? ""),
+ queryFn: () => agentsApi.list(selectedCompanyId!),
+ enabled: Boolean(selectedCompanyId),
+ });
+
+ const installedByKey = useMemo(
+ () => new Map(installedSkills.map((skill) => [skill.key, skill])),
+ [installedSkills],
+ );
+ const catalogCategories = useMemo(() => {
+ const set = new Set<string>();
+ for (const skill of catalogListQuery.data ?? []) set.add(skill.category);
+ return Array.from(set).sort();
+ }, [catalogListQuery.data]);
+
+ // --- Discovery grid derived data (PAP-10879) ---
+ const discoveryCards = useMemo(
+ () => buildDiscoveryCards(installedSkills, catalogListQuery.data ?? []),
+ [installedSkills, catalogListQuery.data],
+ );
+ const discoveryTabCounts = useMemo(() => ({
+ all: discoveryCards.length,
+ installed: discoveryCards.filter((card) => card.installed).length,
+ catalog: discoveryCards.filter((card) => card.catalogRef != null).length,
+ bundled: discoveryCards.filter((card) => card.required).length,
+ }), [discoveryCards]);
+ const discoveryTabCards = useMemo(
+ () => cardsForTab(discoveryCards, discoveryTab),
+ [discoveryCards, discoveryTab],
+ );
+ const discoveryCategoryCounts = useMemo<DiscoveryCategory[]>(() => {
+ const counts = new Map<string, number>();
+ for (const card of discoveryTabCards) {
+ for (const category of card.categories) {
+ counts.set(category, (counts.get(category) ?? 0) + 1);
+ }
+ }
+ return Array.from(counts.entries())
+ .map(([slug, count]) => ({ slug, count }))
+ .sort((a, b) => b.count - a.count || a.slug.localeCompare(b.slug));
+ }, [discoveryTabCards]);
+ const discoverySearchActive = discoverySearch.trim().length > 0;
+ // Selecting a folder shows its whole subtree (folder + descendants), matching
+ // the folder-browser model. `null` means no subtree constraint (All/Unfiled).
+ const folderSubtreeIds = useMemo(() => {
+ if (folderSelection === "all" || folderSelection === "unfiled") return null;
+ const model = treeFromResult(skillFoldersQuery.data);
+ if (!model.byId.has(folderSelection)) return null;
+ return subtreeFolderIds(model, folderSelection);
+ }, [folderSelection, skillFoldersQuery.data]);
+ const visibleDiscoveryCards = useMemo(() => {
+ const filtered = discoveryTabCards.filter((card) => {
+ if (discoveryCategory && !card.categories.includes(discoveryCategory)) return false;
+ // Search spans all folders (user story 5): the folder filter only
+ // narrows when the user is browsing, never when searching.
+ if (discoveryTab === "installed" && !discoverySearchActive) {
+ if (folderSelection === "unfiled" && card.folderId) return false;
+ if (folderSubtreeIds && (!card.folderId || !folderSubtreeIds.has(card.folderId))) return false;
+ }
+ return discoveryMatchesSearch(card, discoverySearch.trim());
+ });
+ return sortDiscoveryCards(filtered, discoverySort, discoveryTab !== "bundled");
+ }, [discoveryTabCards, discoveryCategory, discoverySearch, discoverySearchActive, discoverySort, discoveryTab, folderSelection, folderSubtreeIds]);
+
+ const selectedCatalogSkill = catalogDetailQuery.data
+ ?? (catalogListQuery.data ?? []).find((entry) => entry.id === selectedCatalogRef || entry.key === selectedCatalogRef)
+ ?? null;
+
+ useEffect(() => {
+ setExpandedCatalogSkillId(selectedCatalogSkill?.id ?? null);
+ }, [selectedCatalogSkill?.id]);
+
+ useEffect(() => {
+ if (!selectedCatalogSkill || catalogSelectedPath === "SKILL.md") return;
+ const parents = parentDirectoryPaths(catalogSelectedPath);
+ if (parents.length === 0) return;
+ setExpandedCatalogDirs((current) => {
+ const next = new Set(current[selectedCatalogSkill.id] ?? []);
+ let changed = false;
+ for (const parent of parents) {
+ if (!next.has(parent)) {
+ next.add(parent);
+ changed = true;
+ }
+ }
+ return changed ? { ...current, [selectedCatalogSkill.id]: next } : current;
+ });
+ }, [catalogSelectedPath, selectedCatalogSkill]);
+
+ const sourceCounts = useMemo<Record<SourceFilter, number>>(() => {
+ const counts: Record<SourceFilter, number> = { all: installedSkills.length, company: 0, bundled: 0, optional: 0, external: 0 };
+ for (const skill of installedSkills) {
+ const cls = classifySource(skill);
+ counts[cls] += 1;
+ }
+ return counts;
+ }, [installedSkills]);
+ const installCatalog = useMutation({
+ mutationFn: (payload: { catalogSkillId: string; slug: string | null; force: boolean; agentIds: string[] }) =>
+ companySkillsApi.installCatalog(selectedCompanyId!, {
+ catalogSkillId: payload.catalogSkillId,
+ slug: payload.slug,
+ force: payload.force,
+ }),
+ onSuccess: async (result, payload) => {
+ // Enable the skill for the agents chosen in the install dialog before any
+ // invalidation, so the refetched skill detail already reflects the
+ // attachments. Mode "add" appends to each agent's desired set without
+ // clobbering concurrent edits. A per-agent failure must not fail the
+ // install itself — the skill is in the library either way.
+ const enableTargets = result.action === "created" ? payload.agentIds : [];
+ let enabledCount = 0;
+ let enableFailures = 0;
+ for (const agentId of enableTargets) {
+ try {
+ await agentsApi.syncSkills(agentId, [{ key: result.skill.key, versionId: null }], "add", selectedCompanyId ?? undefined);
+ enabledCount += 1;
+ } catch {
+ enableFailures += 1;
+ }
+ }
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, result.skill.id) }),
+ ]);
+ setInstallDialogState((current) => ({ ...current, open: false, error: null }));
+ pushToast({
+ tone: "success",
+ title: result.action === "created" ? "Skill installed" : result.action === "updated" ? "Skill updated" : "Skill is up to date",
+ body: result.action === "created"
+ ? enabledCount > 0
+ ? `${result.skill.name} — enabled for ${enabledCount} agent${enabledCount === 1 ? "" : "s"}.`
+ : `${result.skill.name} is in the library but not enabled for any agent yet. Use "Add to agent" to enable it.`
+ : result.skill.name,
+ });
+ if (enableFailures > 0) {
+ pushToast({
+ tone: "warn",
+ title: "Skill installed, but enabling failed",
+ body: `Could not enable ${result.skill.name} for ${enableFailures} agent${enableFailures === 1 ? "" : "s"}. Use "Add to agent" on the skill page.`,
+ });
+ }
+ if (result.warnings[0]) {
+ pushToast({ tone: "warn", title: "Install warnings", body: result.warnings[0] });
+ }
+ if (result.action === "created") {
+ navigate(routeForSkill(result.skill));
+ }
+ },
+ onError: (error) => {
+ const message = error instanceof Error ? error.message : "Failed to install catalog skill.";
+ setInstallDialogState((current) => ({ ...current, error: message }));
+ // Also surface explicit-policy / platform denials in the persistent banner
+ // so the reason stays visible after the dialog closes.
+ policyDenial.capture(error, "Installing this skill");
+ },
+ });
+ const createFolder = useMutation({
+ mutationFn: (payload: { name: string; color: string | null }) =>
+ foldersApi.create(selectedCompanyId!, { kind: "skill", parentId: folderDialogParentId, ...payload }),
+ onSuccess: async (folder) => {
+ setFolderDialogOpen(false);
+ setFolderDialogTarget(null);
+ setFolderDialogParentId(null);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") });
+ if (moveAfterCreateSkillIds.length > 0) {
+ const ids = moveAfterCreateSkillIds;
+ setMoveAfterCreateSkillIds([]);
+ try {
+ await Promise.all(ids.map((itemId) =>
+ foldersApi.moveItem(selectedCompanyId!, { kind: "skill", itemId, folderId: folder.id })
+ ));
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") }),
+ ]);
+ } catch (moveError) {
+ pushToast({
+ tone: "error",
+ title: "Folder created, move failed",
+ body: moveError instanceof Error ? moveError.message : "Failed to move the selected skills.",
+ });
+ return;
+ }
+ } else {
+ setFolderSelection(folder.id);
+ }
+ pushToast({ tone: "success", title: "Folder created", body: folder.name });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Folder save failed",
+ body: error instanceof Error ? error.message : "Failed to save folder.",
+ });
+ },
+ });
+ const updateFolder = useMutation({
+ mutationFn: ({ folderId, payload }: { folderId: string; payload: { name?: string; color?: string | null } }) =>
+ foldersApi.update(selectedCompanyId!, folderId, payload),
+ onSuccess: async () => {
+ setFolderDialogOpen(false);
+ setFolderDialogTarget(null);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Folder save failed",
+ body: error instanceof Error ? error.message : "Failed to update folder.",
+ });
+ },
+ });
+ const moveFolder = useMutation({
+ mutationFn: ({ folderId, parentId }: { folderId: string; parentId: string | null }) =>
+ foldersApi.moveFolder(selectedCompanyId!, folderId, { parentId, position: 0 }),
+ onSuccess: async (folder) => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") });
+ setFolderSelection(folder.id);
+ pushToast({
+ tone: "success",
+ title: "Folder moved",
+ body: skillFolderPathDisplayFallback(folder.path) ?? folder.name,
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Folder move failed",
+ body: error instanceof Error ? error.message : "Failed to move folder.",
+ });
+ },
+ });
+ const deleteFolder = useMutation({
+ mutationFn: (folderId: string) => foldersApi.delete(selectedCompanyId!, folderId),
+ onSuccess: async (_, folderId) => {
+ if (folderSelection === folderId) setFolderSelection("all");
+ setDeleteFolderTarget(null);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") }),
+ ]);
+ pushToast({ tone: "success", title: "Folder deleted", body: "Skills moved to Unfiled." });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Folder delete failed",
+ body: error instanceof Error ? error.message : "Failed to delete folder.",
+ });
+ },
+ });
+ const moveSkillToFolder = useMutation({
+ mutationFn: ({ itemId, folderId }: { itemId: string; folderId: string | null }) =>
+ foldersApi.moveItem(selectedCompanyId!, { kind: "skill", itemId, folderId }),
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") }),
+ ]);
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Move failed",
+ body: error instanceof Error ? error.message : "Failed to move skill.",
+ });
+ },
+ });
+
+ async function moveSelectedSkills(folderId: string | null) {
+ const ids = selectedSkillIds;
+ if (ids.length === 0) return;
+ try {
+ await Promise.all(ids.map((itemId) => foldersApi.moveItem(selectedCompanyId!, { kind: "skill", itemId, folderId })));
+ setSelectedSkillIds([]);
+ setSelectMode(false);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") }),
+ ]);
+ pushToast({ tone: "success", title: "Skills moved", body: `${ids.length} skill${ids.length === 1 ? "" : "s"} filed.` });
+ } catch (moveError) {
+ pushToast({
+ tone: "error",
+ title: "Failed to move skills",
+ body: moveError instanceof Error ? moveError.message : "Failed to move the selected skills.",
+ });
+ }
+ }
+
+ // Provision the signed-in user's personal "My Skills" root, then select it.
+ const ensureMyFolder = useMutation({
+ mutationFn: () => foldersApi.ensureMy(selectedCompanyId!),
+ onSuccess: async (folder) => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") });
+ setFolderSelection(folder.id);
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Couldn't open My Skills",
+ body: error instanceof Error ? error.message : "Failed to create your personal folder.",
+ });
+ },
+ });
+
+ async function openNewSkill() {
+ const model = treeFromResult(skillFoldersQuery.data);
+ const selectedFolder = folderSelection === "all" || folderSelection === "unfiled"
+ ? null
+ : model.byId.get(folderSelection) ?? null;
+ if (selectedFolder?.systemKey === "my") {
+ try {
+ const personalFolder = await ensureMyFolder.mutateAsync();
+ navigate(skillStudioNewRoute(null, personalFolder.id));
+ } catch {
+ return;
+ }
+ return;
+ }
+ navigate(skillStudioNewRoute(null, defaultNewSkillFolderId));
+ }
+
+ async function openCreateFolderIn(parentId: string | null) {
+ const parent = parentId ? treeFromResult(skillFoldersQuery.data).byId.get(parentId) : null;
+ if (parent?.systemKey === "my") {
+ try {
+ const personalFolder = await ensureMyFolder.mutateAsync();
+ openCreateFolder([], personalFolder.id);
+ } catch {
+ return;
+ }
+ return;
+ }
+ openCreateFolder([], parentId);
+ }
+
+ async function moveFolderBetweenScopes(folder: FolderListItem, destination: "my" | "company") {
+ if (destination === "company") {
+ moveFolder.mutate({ folderId: folder.id, parentId: null });
+ return;
+ }
+ try {
+ const personalFolder = await ensureMyFolder.mutateAsync();
+ moveFolder.mutate({ folderId: folder.id, parentId: personalFolder.id });
+ } catch {
+ return;
+ }
+ }
+
+ // Inline folder creation used by the move dialog's "New folder inside…" affordance.
+ async function createFolderInline(parentId: string | null, name: string): Promise<string | null> {
+ try {
+ const folder = await foldersApi.create(selectedCompanyId!, { kind: "skill", parentId, name, color: null });
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") });
+ return folder.id;
+ } catch (error) {
+ pushToast({
+ tone: "error",
+ title: "Folder create failed",
+ body: error instanceof Error ? error.message : "Failed to create folder.",
+ });
+ return null;
+ }
+ }
+
+ // Commit a move initiated from the rich move-to-folder dialog.
+ async function performDialogMove(folderId: string | null) {
+ if (!moveDialog) return;
+ const ids = moveDialog.skillIds;
+ try {
+ await Promise.all(ids.map((itemId) => foldersApi.moveItem(selectedCompanyId!, { kind: "skill", itemId, folderId })));
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "skill") }),
+ ...ids.map((itemId) =>
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, itemId) }),
+ ),
+ ]);
+ setMoveDialog(null);
+ setSelectedSkillIds([]);
+ setSelectMode(false);
+ pushToast({
+ tone: "success",
+ title: ids.length === 1 ? "Skill moved" : "Skills moved",
+ body: folderId
+ ? `Filed under ${skillFolderResult?.folders.find((folder) => folder.id === folderId)?.name ?? "folder"}.`
+ : "Moved to Unfiled.",
+ });
+ } catch (moveError) {
+ pushToast({
+ tone: "error",
+ title: "Move failed",
+ body: moveError instanceof Error ? moveError.message : "Failed to move.",
+ });
+ }
+ }
+
+ const eligibleAgentsForAttach = useMemo(() => {
+ const data = agentsQuery.data ?? [];
+ return data.map((agent: Agent) => {
+ const caps = adapterCaps(agent.adapterType);
+ const requiredKeys: string[] = [];
+ const usedSet = new Set((activeDetail?.usedByAgents ?? []).map((entry) => entry.id));
+ const isRequired = false; // detection currently lives server-side; default false until detail surfaces required state
+ return {
+ id: agent.id,
+ name: agent.name,
+ adapterType: agent.adapterType,
+ supportsSkills: Boolean(caps.supportsSkills),
+ required: isRequired,
+ icon: agent.icon,
+ paused: agent.status === "paused" || agent.pausedAt != null,
+ attached: usedSet.has(agent.id),
+ requiredKeys,
+ };
+ });
+ }, [agentsQuery.data, adapterCaps, activeDetail]);
+
+ const attachAgentsMutation = useMutation({
+ mutationFn: async (input: { agentId: string; desiredSkills: Array<string | AgentDesiredSkillEntry> }) => {
+ return agentsApi.syncSkills(input.agentId, input.desiredSkills, "replace", selectedCompanyId ?? undefined);
+ },
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, selectedSkillId ?? "") }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.versions(selectedCompanyId!, selectedSkillId ?? "") }),
+ ]);
+ },
+ });
+
+ async function handleAttachSubmit(nextAgentIds: string[], versionId: string | null = null) {
+ if (!activeDetail) return;
+ const skillKey = activeDetail.key;
+ const targetSet = new Set(nextAgentIds);
+ const current = (activeDetail.usedByAgents ?? []).map((entry) => entry.id);
+ const currentSet = new Set(current);
+ const currentVersionByAgent = new Map(
+ (activeDetail.usedByAgents ?? []).map((entry) => [entry.id, entry.versionId ?? null]),
+ );
+ const toAdd = nextAgentIds.filter((id) => !currentSet.has(id));
+ const toRemove = current.filter((id) => !targetSet.has(id));
+ const toUpdateVersion = nextAgentIds.filter((id) =>
+ currentSet.has(id) && (currentVersionByAgent.get(id) ?? null) !== versionId,
+ );
+ const affected = new Set<string>([...toAdd, ...toRemove, ...toUpdateVersion]);
+ if (affected.size === 0) {
+ return;
+ }
+ try {
+ for (const agentId of affected) {
+ const snapshot = await agentsApi.skills(agentId, selectedCompanyId ?? undefined);
+ const currentEntries: AgentDesiredSkillEntry[] = (snapshot.desiredSkillEntries ?? snapshot.desiredSkills.map((key) => ({ key, versionId: null })))
+ .filter((entry) => entry.key !== skillKey);
+ if (targetSet.has(agentId)) {
+ currentEntries.push({ key: skillKey, versionId });
+ }
+ await attachAgentsMutation.mutateAsync({ agentId, desiredSkills: currentEntries });
+ }
+ pushToast({ tone: "success", title: "Agents updated", body: `${nextAgentIds.length} agent(s) attached.` });
+ } catch (error) {
+ pushToast({ tone: "error", title: "Update failed", body: error instanceof Error ? error.message : "Failed to update agent skills." });
+ }
+ }
+
+ function openInstallDialog(catalogSkill: CatalogSkill) {
+ const existing = installedByKey.get(catalogSkill.key) ?? null;
+ const installedHash = existing?.originHash ?? null;
+ const action: "install" | "update" | "replace" = existing
+ ? installedHash && installedHash !== catalogSkill.contentHash
+ ? "update"
+ : existing.sourceType !== "catalog"
+ ? "replace"
+ : "update"
+ : "install";
+ setInstallDialogState({
+ open: true,
+ catalogSkill,
+ conflict: existing,
+ defaultSlug: existing?.slug ?? catalogSkill.slug,
+ defaultForce: action === "replace",
+ defaultAction: action,
+ error: null,
+ });
+ }
+
+ const deleteSkill = useMutation({
+ mutationFn: () => companySkillsApi.delete(selectedCompanyId!, deleteTargetSkillId!),
+ onSuccess: async (skill) => {
+ closeDeleteDialog(false);
+ setDisplayedDetail(null);
+ setDisplayedFile(null);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ ...(deleteTargetSkillId ? [
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, deleteTargetSkillId) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId!, deleteTargetSkillId) }),
+ ] : []),
+ ...(deleteTargetSkillId ? [
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.companySkills.file(selectedCompanyId!, deleteTargetSkillId, selectedPath),
+ }),
+ ] : []),
+ ]);
+ await queryClient.refetchQueries({
+ queryKey: queryKeys.companySkills.list(selectedCompanyId!),
+ type: "active",
+ });
+ navigate("/skills", { replace: true });
+ pushToast({
+ tone: "success",
+ title: "Skill removed",
+ body: `${skill.name} was removed from the company skill library.`,
+ });
+ },
+ onError: (error) => {
+ reportSkillError(error, "Remove failed", "Failed to remove skill.", "Removing this skill");
+ },
+ });
+
+ const skillFolderResult = skillFoldersQuery.data ?? null;
+ const showInstalledFolders = isDiscovery && discoveryTab === "installed";
+ // Rail counts reflect the current category/search scope, never the folder
+ // filter itself (ux-spec §5.3).
+ const railSkillFolderResult = useMemo(() => {
+ if (!skillFolderResult || discoveryTab !== "installed") return skillFolderResult;
+ const scoped = discoveryTabCards.filter((card) => {
+ if (discoveryCategory && !card.categories.includes(discoveryCategory)) return false;
+ return discoveryMatchesSearch(card, discoverySearch.trim());
+ });
+ const direct = new Map<string, number>();
+ let unfiled = 0;
+ for (const card of scoped) {
+ if (card.folderId) direct.set(card.folderId, (direct.get(card.folderId) ?? 0) + 1);
+ else unfiled += 1;
+ }
+ // Roll direct counts up through the tree so a collapsed parent reflects the
+ // number of skills anywhere in its subtree, not just its own level.
+ const model = treeFromResult(skillFolderResult);
+ return {
+ ...skillFolderResult,
+ allCount: scoped.length,
+ unfiledCount: unfiled,
+ folders: skillFolderResult.folders.map((folder) => {
+ let itemCount = 0;
+ for (const id of subtreeFolderIds(model, folder.id)) itemCount += direct.get(id) ?? 0;
+ return { ...folder, itemCount };
+ }),
+ };
+ }, [skillFolderResult, discoveryTab, discoveryTabCards, discoveryCategory, discoverySearch]);
+ const activeSkillFolderDisplayPath = useMemo(
+ () => skillFolderDisplayPath(treeFromResult(skillFolderResult), activeDetail?.folderId),
+ [skillFolderResult, activeDetail?.folderId],
+ );
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={Boxes} message="Select a company to manage skills." />;
+ }
+
+ function handleAddSkillSource() {
+ const trimmedSource = source.trim();
+ if (trimmedSource.length === 0) {
+ setEmptySourceHelpOpen(true);
+ return;
+ }
+ importSkill.mutate(trimmedSource);
+ }
+
+ // Opening a card stays inside the new store and always lands on a regular full
+ // page: installed skills go to their detail route; catalog/bundled/optional
+ // skills open the standalone catalog page (no modal, no legacy split view).
+ function openDiscoveryCard(card: DiscoveryCard) {
+ if (card.skillId) {
+ navigate(routeForSkillId(card.skillId));
+ return;
+ }
+ if (card.catalogRef) {
+ selectCatalog(card.catalogRef);
+ }
+ }
+
+ // "Back to store" returns to the discovery grid while keeping the tab /
+ // category / source filters the user arrived with (PAP-10907).
+ const backToStoreParams = new URLSearchParams(searchParams);
+ backToStoreParams.delete("catalog");
+ const backToStoreParamString = backToStoreParams.toString();
+ const backToStoreHref = backToStoreParamString ? `/skills?${backToStoreParamString}` : "/skills";
+
+ // Surface the upstream catalog source (GitHub owner/repo/path) on the installed
+ // skill detail, matched by canonical key (PAP-10907).
+ const catalogSourceForDetail = activeDetail
+ ? (catalogListQuery.data ?? []).find((entry) => entry.key === activeDetail.key)?.source ?? null
+ : null;
+ const studioBackHref = studioForkDetailQuery.data ? routeForSkill(studioForkDetailQuery.data) : "/skills";
+ const studioTitle = studioForkFromId ? "Fork skill" : "Create a new skill";
+ const studioDescription = studioForkFromId
+ ? "Review the fork metadata and create an editable company copy."
+ : "Create an editable company skill in the Paperclip workspace.";
+ return (
+ <>
+ {policyDenial.denial ? (
+ <div className="px-4 pt-4">
+ <SkillPolicyDenialNotice denial={policyDenial.denial} onDismiss={policyDenial.reset} />
+ </div>
+ ) : null}
+ <Dialog open={deleteOpen} onOpenChange={closeDeleteDialog}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Remove skill</DialogTitle>
+ <DialogDescription>
+ Remove this skill from the company library. If any agents still use it, removal will be blocked until it is detached.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3 text-sm">
+ <p>
+ {deleteTargetDetail
+ ? `You are about to remove ${deleteTargetDetail.name}.`
+ : "You are about to remove this skill."}
+ </p>
+ {deleteTargetDetail?.usedByAgents?.length ? (
+ <div className="rounded-md border border-border px-3 py-3 text-muted-foreground">
+ Currently used by {deleteTargetDetail.usedByAgents.map((agent) => agent.name).join(", ")}.
+ </div>
+ ) : null}
+ {(deleteTargetDetail?.usedByAgents.length ?? 0) > 0 ? (
+ <p className="text-muted-foreground">
+ Detach this skill from all agents to enable removal.
+ </p>
+ ) : null}
+ </div>
+ <DialogFooter>
+ {(deleteTargetDetail?.usedByAgents.length ?? 0) > 0 ? (
+ <Button variant="ghost" onClick={() => closeDeleteDialog(false)}>
+ Close
+ </Button>
+ ) : (
+ <>
+ <Button variant="ghost" onClick={() => closeDeleteDialog(false)} disabled={deleteSkill.isPending}>
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => deleteSkill.mutate()}
+ disabled={deleteSkill.isPending || !deleteTargetSkillId}
+ >
+ {deleteSkill.isPending ? "Removing..." : "Remove skill"}
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog open={emptySourceHelpOpen} onOpenChange={setEmptySourceHelpOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Add a skill source</DialogTitle>
+ <DialogDescription>
+ Paste a local path, GitHub URL, or `skills.sh` command into the field first.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3 text-sm">
+ <a
+ href="https://skills.sh"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Browse skills.sh</span>
+ <span className="mt-1 block text-muted-foreground">
+ Find install commands and paste one here.
+ </span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ <a
+ href="https://github.com/search?q=SKILL.md&type=code"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Search GitHub</span>
+ <span className="mt-1 block text-muted-foreground">
+ Look for repositories with `SKILL.md`, then paste the repo URL here.
+ </span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ </div>
+ <DialogFooter showCloseButton />
+ </DialogContent>
+ </Dialog>
+
+ <InstallPreviewDialog
+ open={installDialogState.open}
+ onOpenChange={(open) => setInstallDialogState((current) => ({ ...current, open, error: open ? current.error : null }))}
+ skill={installDialogState.catalogSkill}
+ packageName={installDialogState.catalogSkill?.packageName ?? installDialogState.conflict?.packageName ?? null}
+ packageVersion={installDialogState.catalogSkill?.packageVersion ?? installDialogState.conflict?.packageVersion ?? null}
+ conflict={installDialogState.conflict}
+ defaultSlug={installDialogState.defaultSlug}
+ defaultForce={installDialogState.defaultForce}
+ defaultAction={installDialogState.defaultAction}
+ agents={eligibleAgentsForAttach}
+ isPending={installCatalog.isPending}
+ error={installDialogState.error}
+ onConfirm={({ slug, force, agentIds }) => {
+ if (!installDialogState.catalogSkill) return;
+ installCatalog.mutate({
+ catalogSkillId: installDialogState.catalogSkill.id,
+ slug,
+ force,
+ agentIds,
+ });
+ }}
+ />
+
+ <Dialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Import a skill</DialogTitle>
+ <DialogDescription>
+ Paste a local path, GitHub URL, or `skills.sh` command to import a skill into this company.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3">
+ <div className="flex items-center gap-2 border-b border-border pb-2">
+ <Input
+ value={source}
+ onChange={(event) => setSource(event.target.value)}
+ placeholder="Paste path, GitHub URL, or skills.sh command"
+ className="h-9 rounded-none border-0 px-0 shadow-none focus-visible:ring-0"
+ />
+ <Button size="sm" onClick={handleAddSkillSource} disabled={importSkill.isPending}>
+ {importSkill.isPending ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Import"}
+ </Button>
+ </div>
+ <a
+ href="https://skills.sh"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-sm text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Browse skills.sh</span>
+ <span className="mt-1 block text-muted-foreground">Find install commands and paste one here.</span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ <a
+ href="https://github.com/search?q=SKILL.md&type=code"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-sm text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Search GitHub</span>
+ <span className="mt-1 block text-muted-foreground">Look for repositories with `SKILL.md`, then paste the repo URL.</span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {selectedCompanyId ? (
+ <ImportSkillsFromProjectDialog
+ open={importFromProjectOpen}
+ onOpenChange={setImportFromProjectOpen}
+ companyId={selectedCompanyId}
+ onImportFromPath={() => {
+ setImportFromProjectOpen(false);
+ setImportDialogOpen(true);
+ }}
+ />
+ ) : null}
+ <FolderFormDialog
+ open={folderDialogOpen}
+ kind="skill"
+ folder={folderDialogTarget}
+ pending={createFolder.isPending || updateFolder.isPending}
+ onOpenChange={(open) => {
+ setFolderDialogOpen(open);
+ if (!open) setFolderDialogParentId(null);
+ }}
+ onSubmit={(payload) => {
+ if (folderDialogTarget) updateFolder.mutate({ folderId: folderDialogTarget.id, payload });
+ else createFolder.mutate(payload);
+ }}
+ />
+ <DeleteFolderDialog
+ open={deleteFolderTarget !== null}
+ folder={deleteFolderTarget}
+ itemLabelPlural="skills"
+ pending={deleteFolder.isPending}
+ onOpenChange={(open) => {
+ if (!open) setDeleteFolderTarget(null);
+ }}
+ onConfirm={() => {
+ if (deleteFolderTarget) deleteFolder.mutate(deleteFolderTarget.id);
+ }}
+ />
+ <MobileFolderSheet
+ open={mobileFoldersOpen}
+ onOpenChange={setMobileFoldersOpen}
+ result={railSkillFolderResult}
+ selection={folderSelection}
+ allLabel="All skills"
+ itemLabelPlural="Skills"
+ onSelect={setFolderSelection}
+ onCreate={() => openCreateFolder()}
+ />
+ <MoveToFolderDialog
+ open={moveDialog !== null}
+ onOpenChange={(open) => {
+ if (!open) setMoveDialog(null);
+ }}
+ result={railSkillFolderResult}
+ title={moveDialog?.title ?? "Move to folder"}
+ subtitle={moveDialog?.subtitle ?? null}
+ currentFolderId={moveDialog?.currentFolderId ?? null}
+ onMove={(folderId) => void performDialogMove(folderId)}
+ onCreateFolder={createFolderInline}
+ />
+
+ {isStudioNew ? (
+ <div className="min-h-(--sz-calc-30)">
+ <div className="border-b border-border px-4 py-5">
+ <Link
+ to={studioBackHref}
+ className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted-foreground no-underline transition-colors hover:text-foreground"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ Back
+ </Link>
+ <h1 className="text-2xl font-semibold">{studioTitle}</h1>
+ <p className="mt-1 max-w-2xl text-sm text-muted-foreground">{studioDescription}</p>
+ </div>
+ <div className="px-4 py-4">
+ <div className="max-w-3xl">
+ {studioForkFromId && studioForkDetailQuery.isLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : studioForkFromId && !studioForkDetailQuery.data ? (
+ <EmptyState icon={Boxes} message="Fork source skill not found." />
+ ) : (
+ <NewSkillWizard
+ initialDraft={studioDraft}
+ onCreate={(payload) => createSkill.mutate(payload)}
+ isPending={createSkill.isPending}
+ error={createError}
+ onCancel={() => navigate(studioBackHref)}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ ) : isDiscovery ? (
+ <DiscoveryGrid
+ tab={discoveryTab}
+ tabCounts={discoveryTabCounts}
+ onTabChange={setDiscoveryTab}
+ categories={discoveryCategoryCounts}
+ categoryTotal={discoveryTabCards.length}
+ activeCategory={discoveryCategory}
+ onCategoryChange={setDiscoveryCategory}
+ search={discoverySearch}
+ onSearchChange={setDiscoverySearch}
+ sort={discoverySort}
+ onSortChange={setDiscoverySort}
+ cards={visibleDiscoveryCards}
+ onOpenCard={openDiscoveryCard}
+ loading={skillsQuery.isLoading || catalogListQuery.isLoading}
+ error={skillsQuery.error?.message ?? catalogListQuery.error?.message ?? null}
+ totalCount={discoveryCards.length}
+ onCreate={() => void openNewSkill()}
+ onImport={() => setImportDialogOpen(true)}
+ onImportFromProject={() => setImportFromProjectOpen(true)}
+ onBrowseCatalog={() => setDiscoveryTab("catalog")}
+ onScan={(projectId) => scanProjects.mutate(projectId)}
+ scanPending={scanProjects.isPending}
+ scanStatus={scanStatusMessage}
+ folderResult={showInstalledFolders ? railSkillFolderResult : null}
+ folderSelection={folderSelection}
+ foldersLoading={skillFoldersQuery.isLoading}
+ selectMode={showInstalledFolders && selectMode}
+ selectedSkillIds={selectedSkillIds}
+ onFolderSelect={showInstalledFolders ? setFolderSelection : undefined}
+ onOpenMobileFolders={showInstalledFolders ? () => setMobileFoldersOpen(true) : undefined}
+ onCreateFolder={showInstalledFolders ? () => openCreateFolder() : undefined}
+ onCreateFolderIn={showInstalledFolders ? (parentId) => void openCreateFolderIn(parentId) : undefined}
+ onEnsureMyFolder={showInstalledFolders ? () => ensureMyFolder.mutate() : undefined}
+ onOpenMoveCard={showInstalledFolders ? (card) => {
+ if (!card.skillId) return;
+ setMoveDialog({
+ skillIds: [card.skillId],
+ title: `Move "${card.name}"`,
+ subtitle: "Choose a destination folder.",
+ currentFolderId: card.folderId ?? null,
+ });
+ } : undefined}
+ onRenameFolder={showInstalledFolders ? (folder, name) => updateFolder.mutate({ folderId: folder.id, payload: { name } }) : undefined}
+ onEditFolder={showInstalledFolders ? (folder) => {
+ setFolderDialogTarget(folder);
+ setFolderDialogOpen(true);
+ } : undefined}
+ onMoveFolder={showInstalledFolders ? (folder, destination) => void moveFolderBetweenScopes(folder, destination) : undefined}
+ onDeleteFolder={showInstalledFolders ? setDeleteFolderTarget : undefined}
+ onToggleSelectMode={showInstalledFolders ? () => {
+ setSelectMode((current) => !current);
+ if (selectMode) setSelectedSkillIds([]);
+ } : undefined}
+ onSelectCard={showInstalledFolders ? (card, selected) => {
+ if (!card.skillId) return;
+ setSelectedSkillIds((current) =>
+ selected
+ ? Array.from(new Set([...current, card.skillId!]))
+ : current.filter((id) => id !== card.skillId)
+ );
+ } : undefined}
+ onMoveCard={showInstalledFolders ? (card, folderId) => {
+ if (!card.skillId) return;
+ const skillId = card.skillId;
+ const previousFolderId = card.folderId ?? null;
+ moveSkillToFolder.mutate({ itemId: skillId, folderId });
+ pushToast({
+ tone: "success",
+ title: "Skill moved",
+ body: folderId
+ ? `Moved "${card.name}" to ${skillFolderResult?.folders.find((folder) => folder.id === folderId)?.name ?? "folder"}.`
+ : `Moved "${card.name}" to Unfiled.`,
+ action: {
+ label: "Undo",
+ onClick: () => moveSkillToFolder.mutate({ itemId: skillId, folderId: previousFolderId }),
+ },
+ });
+ } : undefined}
+ onCreateFolderAndMoveCard={showInstalledFolders ? (card) => {
+ if (card.skillId) openCreateFolder([card.skillId]);
+ } : undefined}
+ onMoveSelected={showInstalledFolders ? (folderId) => void moveSelectedSkills(folderId) : undefined}
+ onCreateFolderAndMoveSelected={showInstalledFolders ? () => openCreateFolder(selectedSkillIds) : undefined}
+ onClearSelected={showInstalledFolders ? () => setSelectedSkillIds([]) : undefined}
+ folderNudgeStorageKey={showInstalledFolders ? `paperclip:skills-folder-nudge:${selectedCompanyId ?? "none"}` : undefined}
+ />
+ ) : activeView === "installed" && selectedSkillId ? (
+ <SkillDetailPage
+ detail={activeDetail}
+ folderDisplayPath={activeSkillFolderDisplayPath}
+ catalogSource={catalogSourceForDetail}
+ routeSkills={installedSkills}
+ loading={skillsQuery.isLoading || detailQuery.isLoading}
+ activeTab={detailTab}
+ onTabChange={setDetailTab}
+ selectedPath={selectedPath}
+ file={activeFile}
+ fileLoading={fileQuery.isLoading && !activeFile}
+ viewMode={viewMode}
+ editMode={editMode}
+ draft={draft}
+ setViewMode={setViewMode}
+ setEditMode={setEditMode}
+ setDraft={setDraft}
+ onSave={() => saveFile.mutate()}
+ savePending={saveFile.isPending}
+ versions={versionsQuery.data ?? []}
+ versionsLoading={versionsQuery.isLoading}
+ attachAgents={eligibleAgentsForAttach}
+ onSubmitAttach={handleAttachSubmit}
+ attachPending={attachAgentsMutation.isPending}
+ expandedDirs={expandedDirs[selectedSkillId] ?? new Set<string>()}
+ onToggleDir={(path) => {
+ setExpandedDirs((current) => {
+ const next = new Set(current[selectedSkillId] ?? []);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return { ...current, [selectedSkillId]: next };
+ });
+ }}
+ onSelectPath={(path) => {
+ setDetailTab("files");
+ navigate(routeForSkillId(selectedSkillId, path));
+ }}
+ updateStatus={updateStatusQuery.data}
+ updateStatusLoading={updateStatusQuery.isLoading}
+ onCheckUpdates={() => {
+ void updateStatusQuery.refetch();
+ }}
+ checkUpdatesPending={updateStatusQuery.isFetching}
+ onInstallUpdate={() => installUpdate.mutate()}
+ installUpdatePending={installUpdate.isPending}
+ onToggleStar={() => toggleStar.mutate()}
+ starPending={toggleStar.isPending}
+ onFork={() => activeDetail && navigate(skillStudioNewRoute(activeDetail.id))}
+ onUpdateSettings={(updates) => activeDetail && updateSkillSettings.mutate({ skillId: activeDetail.id, updates })}
+ onMoveToFolder={activeDetail ? () => setMoveDialog({
+ skillIds: [activeDetail.id],
+ title: `Move "${activeDetail.name}"`,
+ subtitle: "Choose a destination folder.",
+ currentFolderId: activeDetail.folderId ?? null,
+ }) : undefined}
+ updateSettingsPending={updateSkillSettings.isPending}
+ onDelete={openDeleteDialog}
+ deletePending={deleteSkill.isPending}
+ studioHref={skillStudioRoute(selectedSkillId)}
+ />
+ ) : selectedCatalogRef ? (
+ // Catalog / optional / bundled skills open as a regular full page in the
+ // new store — no modal, no legacy split view (PAP-10907).
+ <div className="min-h-(--sz-calc-30)">
+ <div className="border-b border-border px-4 py-3">
+ <Link
+ to={backToStoreHref}
+ className="inline-flex items-center gap-1.5 text-sm text-muted-foreground no-underline transition-colors hover:text-foreground"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ Back to store
+ </Link>
+ </div>
+ {catalogListQuery.isLoading || catalogDetailQuery.isLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : !selectedCatalogSkill ? (
+ <EmptyState icon={Boxes} message="Catalog skill not found." />
+ ) : (
+ <div className="grid gap-0 xl:grid-cols-(--gtc-30)">
+ <aside className="border-b border-border px-3 py-4 xl:border-b-0 xl:border-r">
+ <div className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Files</div>
+ <SkillTree
+ nodes={buildTree(selectedCatalogSkill.files.map((file) => ({ path: file.path, kind: file.kind })))}
+ skillId={selectedCatalogSkill.id}
+ selectedPath={catalogSelectedPath}
+ expandedDirs={expandedCatalogDirs[selectedCatalogSkill.id] ?? new Set<string>()}
+ onToggleDir={(path) =>
+ setExpandedCatalogDirs((current) => {
+ const next = new Set(current[selectedCatalogSkill.id] ?? []);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return { ...current, [selectedCatalogSkill.id]: next };
+ })
+ }
+ onSelectPath={(path) => setCatalogSelectedPath(path)}
+ fileHref={() => `/skills?catalog=${encodeURIComponent(selectedCatalogRef)}`}
+ />
+ </aside>
+ <div className="min-w-0">
+ <CatalogDetailPane
+ skill={selectedCatalogSkill}
+ packageName={selectedCatalogSkill.packageName ?? installedByKey.get(selectedCatalogSkill.key)?.packageName ?? null}
+ packageVersion={selectedCatalogSkill.packageVersion ?? installedByKey.get(selectedCatalogSkill.key)?.packageVersion ?? null}
+ installedSkill={installedByKey.get(selectedCatalogSkill.key) ?? null}
+ installedSkillId={installedByKey.get(selectedCatalogSkill.key)?.id ?? null}
+ fileQuery={catalogFileQuery}
+ selectedPath={catalogSelectedPath}
+ onInstall={() => openInstallDialog(selectedCatalogSkill)}
+ onUpdate={() => openInstallDialog(selectedCatalogSkill)}
+ onOpenInstalled={(skillId) => navigate(routeForSkillId(skillId))}
+ loadingPrimaryAction={installCatalog.isPending}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="min-h-(--sz-calc-30)">
+ {skillsQuery.isLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : (
+ <EmptyState icon={Boxes} message="Skill not found." />
+ )}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/ui/src/pages/CompanySkills.test.tsx b/ui/src/pages/CompanySkills.test.tsx
index cabcb1a4c6..11147e97e7 100644
--- a/ui/src/pages/CompanySkills.test.tsx
+++ b/ui/src/pages/CompanySkills.test.tsx
@@ -3,12 +3,13 @@
import type { ComponentProps, ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
-import type { CatalogSkill, CompanySkillDetail, CompanySkillVersion, FolderListResult } from "@paperclipai/shared";
+import type { CatalogSkill, CompanySkillDetail, CompanySkillListItem, CompanySkillVersion, FolderListResult } from "@paperclipai/shared";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
DiscoveryGrid,
InstallPreviewDialog,
SkillDetailPage,
+ buildDiscoveryCards,
defaultInstallAgentSelection,
getSkillVersionDiffSelection,
resolveDiscoveryTab,
@@ -250,9 +251,7 @@ async function renderDiscoveryGrid(props: Partial<ComponentProps<typeof Discover
await act(async () => {
root?.render(
<DiscoveryGrid
- tab="all"
- tabCounts={{ all: 0, installed: 0, catalog: 0, bundled: 0 }}
- onTabChange={vi.fn()}
+ tab="installed"
categories={[]}
categoryTotal={0}
activeCategory={null}
@@ -269,7 +268,7 @@ async function renderDiscoveryGrid(props: Partial<ComponentProps<typeof Discover
onCreate={vi.fn()}
onImport={vi.fn()}
onImportFromProject={vi.fn()}
- onBrowseCatalog={vi.fn()}
+ onBrowseDiscover={vi.fn()}
onScan={vi.fn()}
scanPending={false}
scanStatus={null}
@@ -376,14 +375,66 @@ describe("getSkillVersionDiffSelection", () => {
});
});
-describe("DiscoveryGrid Studio entry points", () => {
- it("links the header Studio button to Skill Studio", async () => {
- const node = await renderDiscoveryGrid();
- const studioLink = Array.from(node.querySelectorAll("a")).find((link) =>
- link.textContent?.includes("Studio"),
- );
+describe("DiscoveryGrid IA presentation", () => {
+ it("makes the search scope explicit for Installed and Discover", async () => {
+ let node = await renderDiscoveryGrid({ tab: "installed" });
+ expect(node.querySelector('input[aria-label="Search installed skills"]')).not.toBeNull();
- expect(studioLink?.getAttribute("href")).toBe("/skills/studio");
+ root?.unmount();
+ container?.remove();
+ root = null;
+ container = null;
+
+ node = await renderDiscoveryGrid({ tab: "discover" });
+ expect(node.querySelector('input[aria-label="Search discoverable skills"]')).not.toBeNull();
+ expect(node.textContent).not.toContain("Catalog");
+ });
+
+ it("distinguishes installation from agent enablement on cards", async () => {
+ const installedCard = {
+ key: "installed",
+ skillId: "skill-installed",
+ catalogRef: null,
+ name: "Installed Skill",
+ slug: "installed",
+ author: "Paperclip",
+ version: null,
+ tagline: null,
+ description: null,
+ categories: [],
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ agentCount: 0,
+ forkCount: 0,
+ installed: true,
+ required: false,
+ forkedFrom: false,
+ updatedAt: 0,
+ sourceBadge: "local" as const,
+ sourceLabel: "Local workspace",
+ };
+ const availableCard = {
+ ...installedCard,
+ key: "available",
+ skillId: null,
+ catalogRef: "catalog-available",
+ name: "Available Skill",
+ slug: "available",
+ installed: false,
+ sourceBadge: "catalog" as const,
+ sourceLabel: "Paperclip catalog",
+ };
+ const node = await renderDiscoveryGrid({
+ tab: "discover",
+ cards: [installedCard, availableCard],
+ totalCount: 2,
+ });
+
+ expect(node.textContent).toContain("Not enabled for any agents");
+ expect(node.textContent).toContain("Available to install");
+ expect(node.textContent).toContain("Local workspace");
+ expect(node.textContent).toContain("Paperclip catalog");
});
it("uses the create callback from the New menu and empty state", async () => {
@@ -396,6 +447,17 @@ describe("DiscoveryGrid Studio entry points", () => {
expect(onCreate).toHaveBeenCalledTimes(2);
});
+ it("uses one Discover action instead of Catalog or Bundled navigation", async () => {
+ const onBrowseDiscover = vi.fn();
+ const node = await renderDiscoveryGrid({ onBrowseDiscover });
+
+ await click(buttonsNamed(node, "Discover skills")[0] as HTMLButtonElement);
+
+ expect(onBrowseDiscover).toHaveBeenCalledOnce();
+ expect(node.textContent).not.toContain("Browse catalog");
+ expect(node.textContent).not.toContain("Bundled tab");
+ });
+
it("keeps folder creation in the compact rail control", async () => {
const props = projectFolderGridProps();
const node = await renderDiscoveryGrid(props);
@@ -410,6 +472,29 @@ describe("DiscoveryGrid Studio entry points", () => {
expect(props.onCreateFolder).not.toHaveBeenCalled();
});
+ it("removes category and folder browse rails while keeping search available", async () => {
+ const node = await renderDiscoveryGrid({
+ ...projectFolderGridProps(),
+ categories: [{ slug: "design", count: 1 }],
+ categoryTotal: 1,
+ showBrowseRails: false,
+ });
+
+ expect(node.querySelector('nav[aria-label="Skill folders"]')).toBeNull();
+ expect(node.querySelector("aside")).toBeNull();
+ expect(node.textContent).not.toContain("Browse by category");
+ expect(node.querySelector('input[aria-label="Search installed skills"]')).not.toBeNull();
+ });
+
+ it("omits bulk selection when its entry point is not supplied", async () => {
+ const node = await renderDiscoveryGrid({
+ ...projectFolderGridProps(),
+ onToggleSelectMode: undefined,
+ });
+
+ expect(buttonsNamed(node, "Select")).toHaveLength(0);
+ });
+
it("keeps folder creation available when no folder rail exists", async () => {
const onCreateFolder = vi.fn();
const node = await renderDiscoveryGrid({
@@ -548,18 +633,77 @@ describe("DiscoveryGrid Studio entry points", () => {
describe("skills discovery tab routing", () => {
it("opens the folder-first installed view when the URL has no tab", () => {
expect(resolveDiscoveryTab(null)).toBe("installed");
- expect(resolveDiscoveryTab("all")).toBe("all");
+ expect(resolveDiscoveryTab("all")).toBe("discover");
+ expect(resolveDiscoveryTab("catalog")).toBe("discover");
+ expect(resolveDiscoveryTab("bundled")).toBe("discover");
});
- it("keeps All explicit and makes Installed the canonical default URL", () => {
- const allParams = withDiscoveryTab(new URLSearchParams("folder=my&category=writing"), "all");
- expect(allParams.toString()).toBe("tab=all");
+ it("uses Discover as the only explicit discovery URL and Installed as the default", () => {
+ const discoverParams = withDiscoveryTab(new URLSearchParams("folder=my&category=writing"), "discover");
+ expect(discoverParams.toString()).toBe("tab=discover");
const installedParams = withDiscoveryTab(new URLSearchParams("tab=all&folder=my"), "installed");
expect(installedParams.toString()).toBe("folder=my");
});
});
+describe("skills discovery card reconciliation", () => {
+ it("renders one installed card when installed and catalog data share a key", () => {
+ const installed = {
+ id: "installed-new",
+ key: "PaperclipAI/Review",
+ name: "Review",
+ slug: "review",
+ updatedAt: new Date("2026-08-30T00:00:00Z"),
+ folderId: null,
+ authorName: "Paperclip",
+ packageVersion: "2.0.0",
+ sourceRef: null,
+ tagline: null,
+ description: "Installed copy",
+ categories: [],
+ iconUrl: null,
+ color: null,
+ starCount: 0,
+ attachedAgentCount: 2,
+ forkCount: 0,
+ catalogKind: "optional",
+ forkedFromSkillId: null,
+ sourceBadge: "catalog",
+ sourceLabel: "Paperclip",
+ } as unknown as CompanySkillListItem;
+ const olderDuplicate = {
+ ...installed,
+ id: "installed-old",
+ key: "paperclipai/review",
+ updatedAt: new Date("2026-08-01T00:00:00Z"),
+ } as CompanySkillListItem;
+ const catalog = {
+ id: "catalog-review",
+ key: "paperclipai/review",
+ name: "Review",
+ slug: "review",
+ kind: "optional",
+ category: "quality",
+ description: "Catalog copy",
+ packageName: "Paperclip",
+ packageVersion: "2.0.0",
+ tags: [],
+ } as unknown as CatalogSkill;
+
+ const cards = buildDiscoveryCards([olderDuplicate, installed], [catalog, { ...catalog, id: "catalog-duplicate" }]);
+
+ expect(cards).toHaveLength(1);
+ expect(cards[0]).toMatchObject({
+ skillId: "installed-new",
+ catalogRef: "catalog-review",
+ installed: true,
+ agentCount: 2,
+ sourceKind: "optional",
+ });
+ });
+});
+
describe("skill detail breadcrumbs", () => {
it("links each folder ancestor back to the installed folder view", () => {
const folders: FolderListResult = {
diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx
index 6440e73a9c..1ac354a807 100644
--- a/ui/src/pages/CompanySkills.tsx
+++ b/ui/src/pages/CompanySkills.tsx
@@ -38,6 +38,7 @@ import { Identity } from "../components/Identity";
import { AgentIcon } from "../components/AgentIconPicker";
import { AgentMultiSelect } from "../components/AgentMultiSelect";
import { useAdapterCapabilities } from "../adapters/use-adapter-capabilities";
+import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import {
SkillPolicyDenialNotice,
useSkillPolicyDenial,
@@ -75,6 +76,10 @@ import {
resolveSkillRouteToken,
type CompanySkillRouteSubject,
} from "../lib/company-skill-routes";
+import {
+ resolveSkillsDiscoveryView,
+ withSkillsDiscoveryView,
+} from "./skills/skills-navigation";
import {
SKILL_CREATE_ACCENTS,
buildBlankSkillDraft,
@@ -126,6 +131,7 @@ import {
ChevronLeft,
ChevronRight,
Code2,
+ Compass,
Download,
Eye,
Filter,
@@ -552,23 +558,14 @@ function formatBytes(bytes: number) {
// Skills Store discovery grid (PAP-10879)
// ---------------------------------------------------------------------------
-export type DiscoveryTab = "all" | "installed" | "catalog" | "bundled";
-
-const DISCOVERY_TABS: DiscoveryTab[] = ["all", "installed", "catalog", "bundled"];
+export type DiscoveryTab = "installed" | "discover";
export function resolveDiscoveryTab(tabParam: string | null): DiscoveryTab {
- return DISCOVERY_TABS.includes(tabParam as DiscoveryTab)
- ? (tabParam as DiscoveryTab)
- : "installed";
+ return resolveSkillsDiscoveryView(tabParam);
}
export function withDiscoveryTab(current: URLSearchParams, tab: DiscoveryTab): URLSearchParams {
- const params = new URLSearchParams(current);
- if (tab === "installed") params.delete("tab");
- else params.set("tab", tab);
- params.delete("category");
- if (tab !== "installed") params.delete("folder");
- return params;
+ return withSkillsDiscoveryView(current, tab);
}
export function skillDetailBreadcrumbs(
@@ -623,6 +620,7 @@ export type DiscoveryCard = {
updatedAt: number;
sourceBadge?: CompanySkillSourceBadge | null;
sourceLabel?: string | null;
+ sourceKind?: "bundled" | "optional" | null;
};
export { SkillCardIcon } from "../components/SkillCardIcon";
@@ -662,17 +660,36 @@ function skillSettingsToastBody(skill: Pick<CompanySkillDetail, "categories" | "
// Merge installed company skills and the install catalog into one card model.
// Installed skills win on dedup (they carry the richer social-proof metadata);
// catalog-only skills fill in the rest of the discoverable surface.
-function buildDiscoveryCards(
+function discoveryCardIdentity(key: string): string {
+ return key.trim().toLowerCase();
+}
+
+export function buildDiscoveryCards(
installed: CompanySkillListItem[],
catalog: CatalogSkill[],
): DiscoveryCard[] {
- const catalogByKey = new Map(catalog.map((entry) => [entry.key, entry]));
+ const installedByKey = new Map<string, CompanySkillListItem>();
+ for (const skill of installed) {
+ const identity = discoveryCardIdentity(skill.key);
+ const existing = installedByKey.get(identity);
+ if (!existing || new Date(skill.updatedAt).getTime() > new Date(existing.updatedAt).getTime()) {
+ installedByKey.set(identity, skill);
+ }
+ }
+
+ const catalogByKey = new Map<string, CatalogSkill>();
+ for (const entry of catalog) {
+ const identity = discoveryCardIdentity(entry.key);
+ if (!catalogByKey.has(identity)) catalogByKey.set(identity, entry);
+ }
+
const cards: DiscoveryCard[] = [];
const installedKeys = new Set<string>();
- for (const skill of installed) {
- installedKeys.add(skill.key);
- const catalogMatch = catalogByKey.get(skill.key) ?? null;
+ for (const skill of installedByKey.values()) {
+ const identity = discoveryCardIdentity(skill.key);
+ installedKeys.add(identity);
+ const catalogMatch = catalogByKey.get(identity) ?? null;
const required = skill.catalogKind === "bundled" || catalogMatch?.kind === "bundled";
cards.push({
key: skill.key,
@@ -697,11 +714,12 @@ function buildDiscoveryCards(
updatedAt: new Date(skill.updatedAt).getTime() || 0,
sourceBadge: skill.sourceBadge,
sourceLabel: skill.sourceLabel,
+ sourceKind: skill.catalogKind ?? catalogMatch?.kind ?? null,
});
}
- for (const entry of catalog) {
- if (installedKeys.has(entry.key)) continue;
+ for (const [identity, entry] of catalogByKey) {
+ if (installedKeys.has(identity)) continue;
const required = entry.kind === "bundled";
cards.push({
key: entry.key,
@@ -726,6 +744,7 @@ function buildDiscoveryCards(
updatedAt: 0,
sourceBadge: "catalog",
sourceLabel: entry.packageName ?? "Catalog",
+ sourceKind: entry.kind,
});
}
@@ -733,17 +752,7 @@ function buildDiscoveryCards(
}
function cardsForTab(cards: DiscoveryCard[], tab: DiscoveryTab): DiscoveryCard[] {
- switch (tab) {
- case "installed":
- return cards.filter((card) => card.installed);
- case "catalog":
- return cards.filter((card) => card.catalogRef != null);
- case "bundled":
- return cards.filter((card) => card.required);
- case "all":
- default:
- return cards;
- }
+ return tab === "installed" ? cards.filter((card) => card.installed) : cards;
}
function sortDiscoveryCards(cards: DiscoveryCard[], sort: DiscoverySort, demoteRequired: boolean): DiscoveryCard[] {
@@ -823,6 +832,8 @@ function SkillCard({
onCreateFolderAndMove?: (card: DiscoveryCard) => void;
onOpenMove?: (card: DiscoveryCard) => void;
}) {
+ const source = sourceMeta(card.sourceBadge ?? "catalog", card.sourceLabel ?? null);
+ const SourceIcon = source.icon;
const badgeFolder = showFolderBadge && card.installed
? (card.folderId ? folders?.find((folder) => folder.id === card.folderId) ?? null : null)
: undefined;
@@ -873,16 +884,6 @@ function SkillCard({
</div>
) : null}
</div>
- {/* Where the skill came from (PAP-10907 E); native title gives a hover hint. */}
- {(() => {
- const meta = sourceMeta(card.sourceBadge ?? "catalog", card.sourceLabel ?? null);
- const SourceIcon = meta.icon;
- return (
- <span className="shrink-0 text-muted-foreground" title={`From ${meta.label}`} aria-label={`From ${meta.label}`}>
- <SourceIcon className="h-3.5 w-3.5" aria-hidden="true" />
- </span>
- );
- })()}
{canMove && folders && onMove && onCreateFolderAndMove ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -935,9 +936,15 @@ function SkillCard({
</p>
<div className="mt-auto pt-3">
- {/* Stats: installed agents · stars · forks — stars/forks only when > 0. */}
+ {/* Installation and agent enablement are separate states. */}
<div className="flex items-center gap-2 text-(length:--text-micro) text-muted-foreground">
- <span>{card.agentCount} {card.agentCount === 1 ? "agent" : "agents"}</span>
+ <span>
+ {card.installed
+ ? card.agentCount > 0
+ ? `Enabled for ${card.agentCount} ${card.agentCount === 1 ? "agent" : "agents"}`
+ : "Not enabled for any agents"
+ : "Available to install"}
+ </span>
{card.starCount > 0 ? (
<>
<span aria-hidden="true">·</span>
@@ -953,10 +960,14 @@ function SkillCard({
</div>
<div className="mt-2 flex flex-wrap items-center gap-1">
{card.installed ? (
- <Badge variant="outline" className="border-emerald-500/30 bg-emerald-500/10 text-(length:--text-nano) text-emerald-700 dark:text-emerald-300">
+ <Badge variant="secondary" className="text-(length:--text-nano)">
Installed
</Badge>
) : null}
+ <Badge variant="outline" className="max-w-full text-(length:--text-nano) text-muted-foreground">
+ <SourceIcon className="h-3 w-3" aria-hidden="true" />
+ <span className="truncate">{source.label}</span>
+ </Badge>
{card.categories.slice(0, 2).map((category) => (
<SkillCategoryChip key={category} label={category} />
))}
@@ -965,6 +976,10 @@ function SkillCard({
<Lock className="h-3 w-3" aria-hidden="true" />
Bundled
</Badge>
+ ) : card.sourceKind === "optional" ? (
+ <Badge variant="outline" className="ml-auto text-(length:--text-nano) text-muted-foreground">
+ Optional
+ </Badge>
) : null}
</div>
</div>
@@ -1018,8 +1033,6 @@ function CategoryNav({
export function DiscoveryGrid({
tab,
- tabCounts,
- onTabChange,
categories,
categoryTotal,
activeCategory,
@@ -1036,7 +1049,7 @@ export function DiscoveryGrid({
onCreate,
onImport,
onImportFromProject,
- onBrowseCatalog,
+ onBrowseDiscover,
onScan,
scanPending,
scanStatus,
@@ -1063,10 +1076,9 @@ export function DiscoveryGrid({
onEnsureMyFolder,
onOpenMoveCard,
folderNudgeStorageKey,
+ showBrowseRails = true,
}: {
tab: DiscoveryTab;
- tabCounts: Record<DiscoveryTab, number>;
- onTabChange: (tab: DiscoveryTab) => void;
categories: DiscoveryCategory[];
categoryTotal: number;
activeCategory: string | null;
@@ -1083,7 +1095,7 @@ export function DiscoveryGrid({
onCreate: () => void;
onImport: () => void;
onImportFromProject: () => void;
- onBrowseCatalog: () => void;
+ onBrowseDiscover: () => void;
onScan: (projectId?: string) => void;
scanPending: boolean;
scanStatus: string | null;
@@ -1114,22 +1126,43 @@ export function DiscoveryGrid({
onOpenMoveCard?: (card: DiscoveryCard) => void;
/** When set and no folders exist yet, show the dismissible all-unfiled nudge (ux-spec §6.3). */
folderNudgeStorageKey?: string;
+ /** Category/folder navigation stays available in production, but the Streamlined UI relies on search and scrolling. */
+ showBrowseRails?: boolean;
}) {
+ const installedView = tab === "installed";
+ const viewTitle = installedView ? "Installed skills" : "Discover skills";
+ const viewDescription = installedView
+ ? "Skills available to this organization."
+ : "Browse skills from every available source.";
+ const searchLabel = installedView ? "Search installed skills" : "Search discoverable skills";
// Source filter (github / skills.sh / local / …) lives in the grid so it
// narrows whatever the parent already filtered by tab/category/search (PAP-10907 E).
const [sourceBadgeFilter, setSourceBadgeFilter] = useState<string>("all");
const availableSources = useMemo(() => {
- const set = new Set<string>();
- for (const card of cards) if (card.sourceBadge) set.add(card.sourceBadge);
- return Array.from(set).sort();
+ const facets = new Map<string, string>();
+ for (const card of cards) {
+ if (card.sourceKind) {
+ facets.set(`kind:${card.sourceKind}`, card.sourceKind === "bundled" ? "Bundled" : "Optional");
+ }
+ if (card.sourceBadge) {
+ facets.set(`badge:${card.sourceBadge}`, sourceMeta(card.sourceBadge, null).label);
+ }
+ }
+ return Array.from(facets, ([value, label]) => ({ value, label }))
+ .sort((left, right) => left.label.localeCompare(right.label));
}, [cards]);
useEffect(() => {
- if (sourceBadgeFilter !== "all" && !availableSources.includes(sourceBadgeFilter)) {
+ if (sourceBadgeFilter !== "all" && !availableSources.some((source) => source.value === sourceBadgeFilter)) {
setSourceBadgeFilter("all");
}
}, [availableSources, sourceBadgeFilter]);
const sourceFilteredCards = useMemo(
- () => (sourceBadgeFilter === "all" ? cards : cards.filter((card) => card.sourceBadge === sourceBadgeFilter)),
+ () => sourceBadgeFilter === "all"
+ ? cards
+ : cards.filter((card) => {
+ const [facet, value] = sourceBadgeFilter.split(":", 2);
+ return facet === "kind" ? card.sourceKind === value : card.sourceBadge === value;
+ }),
[cards, sourceBadgeFilter],
);
const sourceFilterActive = sourceBadgeFilter !== "all";
@@ -1139,7 +1172,7 @@ export function DiscoveryGrid({
// The nested folder tree owns the left rail whenever folders (reserved roots
// or user folders) exist for the installed view.
const showFolderRail = Boolean(
- folderResult && folderResult.folders.length > 0 && onFolderSelect && folderActionsReady,
+ showBrowseRails && folderResult && folderResult.folders.length > 0 && onFolderSelect && folderActionsReady,
);
const activeProjectFolder = useMemo(() => {
if (!folderResult || folderSelection === "all" || folderSelection === "unfiled") return null;
@@ -1172,35 +1205,42 @@ export function DiscoveryGrid({
/>
</div>
) : null}
- {/* Secondary category sidebar — the main app nav collapses to a rail while
- this is present (handled in Layout). */}
- <aside className={cn("hidden w-60 shrink-0 flex-col overflow-hidden border-r border-border md:flex", showFolderRail && "md:hidden")}>
- <div className="border-b border-border px-4 py-4">
- <h2 className="text-sm font-semibold text-foreground">Skills Store</h2>
- <p className="text-xs text-muted-foreground">Discover, install, fork, share</p>
- </div>
- <div className="px-4 pb-1 pt-3 text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">
- Categories
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto pb-4">
- <CategoryNav
- categories={categories}
- total={categoryTotal}
- active={activeCategory}
- onSelect={onCategoryChange}
- />
- </div>
- </aside>
+ {showBrowseRails ? (
+ <aside className={cn("hidden w-60 shrink-0 flex-col overflow-hidden border-r border-border md:flex", showFolderRail && "md:hidden")}>
+ <div className="border-b border-border px-4 py-4">
+ <h2 className="text-sm font-semibold text-foreground">Browse by category</h2>
+ <p className="text-xs text-muted-foreground">
+ Filter {installedView ? "installed" : "discoverable"} skills.
+ </p>
+ </div>
+ <div className="px-4 pb-1 pt-3 text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground">
+ Categories
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto pb-4">
+ <CategoryNav
+ categories={categories}
+ total={categoryTotal}
+ active={activeCategory}
+ onSelect={onCategoryChange}
+ />
+ </div>
+ </aside>
+ ) : null}
<div className="flex min-w-0 flex-1 flex-col overflow-hidden">
{/* Search + sort + actions */}
<div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-3">
+ <div className="w-full">
+ <h1 className="text-lg font-semibold text-foreground">{viewTitle}</h1>
+ <p className="text-xs text-muted-foreground">{viewDescription}</p>
+ </div>
<div className="flex h-9 min-w-(--sz-12rem) flex-1 items-center gap-2 rounded-md border border-border px-2.5">
<Search className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<input
value={search}
onChange={(event) => onSearchChange(event.target.value)}
- placeholder="Search skills, authors, categories…"
+ aria-label={searchLabel}
+ placeholder={`${searchLabel}…`}
className="h-full w-full bg-transparent text-base outline-none placeholder:text-muted-foreground sm:text-sm"
/>
</div>
@@ -1227,8 +1267,10 @@ export function DiscoveryGrid({
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<span className="text-muted-foreground">Source</span>
- <span className="ml-1.5 capitalize">
- {sourceBadgeFilter === "all" ? "All" : sourceMeta(sourceBadgeFilter as CompanySkillSourceBadge, null).label}
+ <span className="ml-1.5">
+ {sourceBadgeFilter === "all"
+ ? "All"
+ : availableSources.find((source) => source.value === sourceBadgeFilter)?.label ?? "All"}
</span>
<ChevronDown className="ml-1 h-3.5 w-3.5" />
</Button>
@@ -1236,9 +1278,9 @@ export function DiscoveryGrid({
<DropdownMenuContent align="end">
<DropdownMenuRadioGroup value={sourceBadgeFilter} onValueChange={setSourceBadgeFilter}>
<DropdownMenuRadioItem value="all">All sources</DropdownMenuRadioItem>
- {availableSources.map((badge) => (
- <DropdownMenuRadioItem key={badge} value={badge}>
- {sourceMeta(badge as CompanySkillSourceBadge, null).label}
+ {availableSources.map((source) => (
+ <DropdownMenuRadioItem key={source.value} value={source.value}>
+ {source.label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
@@ -1255,12 +1297,6 @@ export function DiscoveryGrid({
>
<RefreshCw className={cn("h-4 w-4", scanPending && "animate-spin")} />
</Button>
- <Button asChild variant="outline" size="sm">
- <Link to="/skills/studio">
- <FlaskConical className="h-3.5 w-3.5" />
- Studio
- </Link>
- </Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm" variant="default">
@@ -1274,9 +1310,9 @@ export function DiscoveryGrid({
<Pencil className="mr-2 h-4 w-4" />
Create new skill
</DropdownMenuItem>
- <DropdownMenuItem onSelect={onBrowseCatalog}>
- <Boxes className="mr-2 h-4 w-4" />
- Browse catalog
+ <DropdownMenuItem onSelect={onBrowseDiscover}>
+ <Compass className="mr-2 h-4 w-4" />
+ Discover skills
</DropdownMenuItem>
<DropdownMenuItem onSelect={onImport}>
<Globe className="mr-2 h-4 w-4" />
@@ -1288,7 +1324,7 @@ export function DiscoveryGrid({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- {folderResult && onFolderSelect ? (
+ {showBrowseRails && folderResult && onFolderSelect ? (
<div className="w-full md:hidden">
<FolderChip
result={folderResult}
@@ -1312,7 +1348,7 @@ export function DiscoveryGrid({
</div>
{/* Mobile category selector (sidebar is hidden below md) */}
- {categories.length > 0 ? (
+ {showBrowseRails && categories.length > 0 ? (
<div className="border-b border-border px-4 py-2 md:hidden">
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -1338,30 +1374,6 @@ export function DiscoveryGrid({
</div>
) : null}
- {/* Tab strip — Bundled/required lives at the end */}
- <div className="border-b border-border px-4">
- <Tabs value={tab} onValueChange={(value) => onTabChange(value as DiscoveryTab)}>
- <TabsList variant="line" className="p-0">
- <TabsTrigger value="all" className="px-3">
- <span>All</span>
- <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.all}</span>
- </TabsTrigger>
- <TabsTrigger value="installed" className="px-3">
- <span>Installed</span>
- <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.installed}</span>
- </TabsTrigger>
- <TabsTrigger value="catalog" className="px-3">
- <span>Catalog</span>
- <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.catalog}</span>
- </TabsTrigger>
- <TabsTrigger value="bundled" className="px-3">
- <span>Bundled</span>
- <span className="ml-1.5 text-(length:--text-micro) text-muted-foreground">{tabCounts.bundled}</span>
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
-
{/* Grid body */}
<div className="min-h-0 flex-1 overflow-auto p-4">
{scanStatus ? <p className="mb-3 text-xs text-muted-foreground">{scanStatus}</p> : null}
@@ -1412,17 +1424,21 @@ export function DiscoveryGrid({
icon={LayoutGrid}
message={
totalCount === 0
- ? "No skills yet. Create one or install from the catalog."
+ ? installedView
+ ? "No installed skills yet. Discover a skill or create one."
+ : "No skills are available to discover yet."
: search || activeCategory || sourceFilterActive
? "No skills match your filters."
- : "No skills in this tab yet."
+ : "No skills in this view yet."
}
/>
{totalCount === 0 ? (
<div className="mt-3 flex flex-col items-center gap-2">
- <Button size="sm" onClick={onBrowseCatalog}>
- <Boxes className="mr-1.5 h-3.5 w-3.5" /> Browse catalog
- </Button>
+ {installedView ? (
+ <Button size="sm" onClick={onBrowseDiscover}>
+ <Compass className="mr-1.5 h-3.5 w-3.5" /> Discover skills
+ </Button>
+ ) : null}
<Button size="sm" variant="ghost" onClick={onCreate}>
Create a skill
</Button>
@@ -4005,6 +4021,7 @@ export function CompanySkills() {
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToastActions();
const adapterCaps = useAdapterCapabilities();
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const policyDenial = useSkillPolicyDenial();
// Route a failed skill mutation to the persistent policy banner when it is an
// explicit-policy (State B) or platform-safety (State C) denial; otherwise keep
@@ -4076,7 +4093,17 @@ export function CompanySkills() {
: "all";
const selectedCatalogRef = searchParams.get("catalog");
const tabParam = searchParams.get("tab");
- const discoveryTab = resolveDiscoveryTab(tabParam);
+ const discoveryTab = resolveDiscoveryTab(tabParam ?? (viewParam === "catalog" ? "catalog" : null));
+ const legacyDiscoveryTab = (["all", "installed", "catalog", "bundled"] as const).includes(
+ tabParam as "all" | "installed" | "catalog" | "bundled",
+ )
+ ? (tabParam as "all" | "installed" | "catalog" | "bundled")
+ : "installed";
+ const effectiveDiscoveryTab: DiscoveryTab = streamlinedUiEnabled
+ ? discoveryTab
+ : legacyDiscoveryTab === "installed"
+ ? "installed"
+ : "discover";
const detailTab: SkillDetailTab = (["overview", "files", "versions", "agents"] as SkillDetailTab[]).includes(tabParam as SkillDetailTab)
? (tabParam as SkillDetailTab)
: parsedRoute.hasExplicitFilePath || selectedPath !== "SKILL.md"
@@ -4089,11 +4116,25 @@ export function CompanySkills() {
// selected; selecting either drops into the existing master/detail surfaces.
const isDiscovery = !isStudioNew && !routeSkillToken && !selectedCatalogRef;
const folderSelection = normalizeFolderSelection(searchParams.get("folder"));
+ const browseRailsEnabled = !streamlinedUiEnabled;
+ const visibleDiscoveryCategory = browseRailsEnabled ? discoveryCategory : null;
+ const visibleFolderSelection: FolderSelection = browseRailsEnabled ? folderSelection : "all";
function setDiscoveryTab(tab: DiscoveryTab) {
setSearchParams((current) => withDiscoveryTab(current, tab));
}
+ function setLegacyDiscoveryTab(tab: "all" | "installed" | "catalog" | "bundled") {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ if (tab === "installed") params.delete("tab");
+ else params.set("tab", tab);
+ params.delete("category");
+ if (tab !== "installed") params.delete("folder");
+ return params;
+ });
+ }
+
function setFolderSelection(selection: FolderSelection) {
setSearchParams((current) => {
const params = new URLSearchParams(current);
@@ -4155,20 +4196,36 @@ export function CompanySkills() {
setCreateError(null);
}, [isStudioNew, studioForkFromId]);
- // The old split catalog view no longer exists — catalog/bundled skills now open
- // as a regular full page keyed by `?catalog=<ref>`. Strip the legacy `view`
- // param so stale `?view=catalog` deep links land on the new surface (PAP-10907).
+ // Canonicalize the old split-view and multi-tab URLs into the single Discover
+ // destination while keeping every stale deep link useful.
useEffect(() => {
- if (!searchParams.has("view")) return;
+ if (!streamlinedUiEnabled) return;
+ const legacyTab = searchParams.get("tab");
+ const hasLegacyDiscoveryTab = isDiscovery && ["all", "catalog", "bundled"].includes(legacyTab ?? "");
+ const hasRetiredBrowseFilter = isDiscovery && (searchParams.has("category") || searchParams.has("folder"));
+ if (!searchParams.has("view") && !hasLegacyDiscoveryTab && !hasRetiredBrowseFilter) return;
setSearchParams(
(current) => {
const next = new URLSearchParams(current);
+ if (hasLegacyDiscoveryTab || (next.get("view") === "catalog" && !next.has("tab"))) {
+ next.set("tab", "discover");
+ }
next.delete("view");
+ if (isDiscovery) {
+ next.delete("category");
+ next.delete("folder");
+ }
return next;
},
{ replace: true },
);
- }, [searchParams, setSearchParams]);
+ }, [isDiscovery, searchParams, setSearchParams, streamlinedUiEnabled]);
+
+ useEffect(() => {
+ if (!streamlinedUiEnabled) return;
+ setSelectMode(false);
+ setSelectedSkillIds([]);
+ }, [streamlinedUiEnabled]);
const skillsQuery = useQuery({
queryKey: queryKeys.companySkills.list(selectedCompanyId ?? ""),
@@ -4178,7 +4235,7 @@ export function CompanySkills() {
const skillFoldersQuery = useQuery({
queryKey: queryKeys.folders.list(selectedCompanyId ?? "", "skill"),
queryFn: () => foldersApi.list(selectedCompanyId!, "skill"),
- enabled: Boolean(selectedCompanyId && ((isDiscovery && discoveryTab === "installed") || routeSkillToken)),
+ enabled: Boolean(selectedCompanyId && ((isDiscovery && effectiveDiscoveryTab === "installed") || routeSkillToken)),
});
const installedSkills = skillsQuery.data ?? [];
@@ -4227,15 +4284,15 @@ export function CompanySkills() {
// The writable folder to seed a new skill into when creating from the browser.
const defaultNewSkillFolderId = useMemo(() => {
- if (folderSelection === "all" || folderSelection === "unfiled") return null;
+ if (visibleFolderSelection === "all" || visibleFolderSelection === "unfiled") return null;
const model = treeFromResult(skillFoldersQuery.data);
- const folder = model.byId.get(folderSelection);
+ const folder = model.byId.get(visibleFolderSelection);
if (!folder) return null;
// Never seed into read-only reserved subtrees (Bundled / Projects).
if (folder.path === "bundled" || folder.path.startsWith("bundled/")) return null;
if (folder.path === "projects" || folder.path.startsWith("projects/")) return null;
return folder.id;
- }, [folderSelection, skillFoldersQuery.data]);
+ }, [skillFoldersQuery.data, visibleFolderSelection]);
const updateStatusQuery = useQuery({
queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId ?? "", selectedSkillId ?? ""),
@@ -4569,15 +4626,15 @@ export function CompanySkills() {
() => buildDiscoveryCards(installedSkills, catalogListQuery.data ?? []),
[installedSkills, catalogListQuery.data],
);
- const discoveryTabCounts = useMemo(() => ({
- all: discoveryCards.length,
- installed: discoveryCards.filter((card) => card.installed).length,
- catalog: discoveryCards.filter((card) => card.catalogRef != null).length,
- bundled: discoveryCards.filter((card) => card.required).length,
- }), [discoveryCards]);
const discoveryTabCards = useMemo(
- () => cardsForTab(discoveryCards, discoveryTab),
- [discoveryCards, discoveryTab],
+ () => {
+ if (streamlinedUiEnabled) return cardsForTab(discoveryCards, discoveryTab);
+ if (legacyDiscoveryTab === "installed") return discoveryCards.filter((card) => card.installed);
+ if (legacyDiscoveryTab === "catalog") return discoveryCards.filter((card) => card.catalogRef != null);
+ if (legacyDiscoveryTab === "bundled") return discoveryCards.filter((card) => card.required);
+ return discoveryCards;
+ },
+ [discoveryCards, discoveryTab, legacyDiscoveryTab, streamlinedUiEnabled],
);
const discoveryCategoryCounts = useMemo<DiscoveryCategory[]>(() => {
const counts = new Map<string, number>();
@@ -4594,24 +4651,24 @@ export function CompanySkills() {
// Selecting a folder shows its whole subtree (folder + descendants), matching
// the folder-browser model. `null` means no subtree constraint (All/Unfiled).
const folderSubtreeIds = useMemo(() => {
- if (folderSelection === "all" || folderSelection === "unfiled") return null;
+ if (visibleFolderSelection === "all" || visibleFolderSelection === "unfiled") return null;
const model = treeFromResult(skillFoldersQuery.data);
- if (!model.byId.has(folderSelection)) return null;
- return subtreeFolderIds(model, folderSelection);
- }, [folderSelection, skillFoldersQuery.data]);
+ if (!model.byId.has(visibleFolderSelection)) return null;
+ return subtreeFolderIds(model, visibleFolderSelection);
+ }, [skillFoldersQuery.data, visibleFolderSelection]);
const visibleDiscoveryCards = useMemo(() => {
const filtered = discoveryTabCards.filter((card) => {
- if (discoveryCategory && !card.categories.includes(discoveryCategory)) return false;
+ if (visibleDiscoveryCategory && !card.categories.includes(visibleDiscoveryCategory)) return false;
// Search spans all folders (user story 5): the folder filter only
// narrows when the user is browsing, never when searching.
- if (discoveryTab === "installed" && !discoverySearchActive) {
- if (folderSelection === "unfiled" && card.folderId) return false;
+ if (effectiveDiscoveryTab === "installed" && !discoverySearchActive) {
+ if (visibleFolderSelection === "unfiled" && card.folderId) return false;
if (folderSubtreeIds && (!card.folderId || !folderSubtreeIds.has(card.folderId))) return false;
}
return discoveryMatchesSearch(card, discoverySearch.trim());
});
- return sortDiscoveryCards(filtered, discoverySort, discoveryTab !== "bundled");
- }, [discoveryTabCards, discoveryCategory, discoverySearch, discoverySearchActive, discoverySort, discoveryTab, folderSelection, folderSubtreeIds]);
+ return sortDiscoveryCards(filtered, discoverySort, effectiveDiscoveryTab === "discover");
+ }, [discoverySearch, discoverySearchActive, discoverySort, discoveryTabCards, effectiveDiscoveryTab, folderSubtreeIds, visibleDiscoveryCategory, visibleFolderSelection]);
const selectedCatalogSkill = catalogDetailQuery.data
?? (catalogListQuery.data ?? []).find((entry) => entry.id === selectedCatalogRef || entry.key === selectedCatalogRef)
@@ -4858,9 +4915,9 @@ export function CompanySkills() {
async function openNewSkill() {
const model = treeFromResult(skillFoldersQuery.data);
- const selectedFolder = folderSelection === "all" || folderSelection === "unfiled"
+ const selectedFolder = visibleFolderSelection === "all" || visibleFolderSelection === "unfiled"
? null
- : model.byId.get(folderSelection) ?? null;
+ : model.byId.get(visibleFolderSelection) ?? null;
if (selectedFolder?.systemKey === "my") {
try {
const personalFolder = await ensureMyFolder.mutateAsync();
@@ -5072,13 +5129,14 @@ export function CompanySkills() {
});
const skillFolderResult = skillFoldersQuery.data ?? null;
- const showInstalledFolders = isDiscovery && discoveryTab === "installed";
+ const showInstalledFolders = isDiscovery && effectiveDiscoveryTab === "installed";
+ const showInstalledBulkSelection = showInstalledFolders && !streamlinedUiEnabled;
// Rail counts reflect the current category/search scope, never the folder
// filter itself (ux-spec §5.3).
const railSkillFolderResult = useMemo(() => {
- if (!skillFolderResult || discoveryTab !== "installed") return skillFolderResult;
+ if (!skillFolderResult || effectiveDiscoveryTab !== "installed") return skillFolderResult;
const scoped = discoveryTabCards.filter((card) => {
- if (discoveryCategory && !card.categories.includes(discoveryCategory)) return false;
+ if (visibleDiscoveryCategory && !card.categories.includes(visibleDiscoveryCategory)) return false;
return discoveryMatchesSearch(card, discoverySearch.trim());
});
const direct = new Map<string, number>();
@@ -5100,7 +5158,7 @@ export function CompanySkills() {
return { ...folder, itemCount };
}),
};
- }, [skillFolderResult, discoveryTab, discoveryTabCards, discoveryCategory, discoverySearch]);
+ }, [discoverySearch, discoveryTabCards, effectiveDiscoveryTab, skillFolderResult, visibleDiscoveryCategory]);
const activeSkillFolderDisplayPath = useMemo(
() => skillFolderDisplayPath(treeFromResult(skillFolderResult), activeDetail?.folderId),
[skillFolderResult, activeDetail?.folderId],
@@ -5410,13 +5468,24 @@ export function CompanySkills() {
</div>
</div>
) : isDiscovery ? (
+ <>
+ {!streamlinedUiEnabled ? (
+ <div className="px-4 pt-4">
+ <Tabs value={legacyDiscoveryTab} onValueChange={(value) => setLegacyDiscoveryTab(value as "all" | "installed" | "catalog" | "bundled")}>
+ <TabsList variant="line" aria-label="Skills view">
+ <TabsTrigger value="all">All</TabsTrigger>
+ <TabsTrigger value="installed">Installed</TabsTrigger>
+ <TabsTrigger value="catalog">Catalog</TabsTrigger>
+ <TabsTrigger value="bundled">Bundled</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+ ) : null}
<DiscoveryGrid
- tab={discoveryTab}
- tabCounts={discoveryTabCounts}
- onTabChange={setDiscoveryTab}
+ tab={effectiveDiscoveryTab}
categories={discoveryCategoryCounts}
categoryTotal={discoveryTabCards.length}
- activeCategory={discoveryCategory}
+ activeCategory={visibleDiscoveryCategory}
onCategoryChange={setDiscoveryCategory}
search={discoverySearch}
onSearchChange={setDiscoverySearch}
@@ -5426,19 +5495,19 @@ export function CompanySkills() {
onOpenCard={openDiscoveryCard}
loading={skillsQuery.isLoading || catalogListQuery.isLoading}
error={skillsQuery.error?.message ?? catalogListQuery.error?.message ?? null}
- totalCount={discoveryCards.length}
+ totalCount={discoveryTabCards.length}
onCreate={() => void openNewSkill()}
onImport={() => setImportDialogOpen(true)}
onImportFromProject={() => setImportFromProjectOpen(true)}
- onBrowseCatalog={() => setDiscoveryTab("catalog")}
+ onBrowseDiscover={() => streamlinedUiEnabled ? setDiscoveryTab("discover") : setLegacyDiscoveryTab("catalog")}
onScan={(projectId) => scanProjects.mutate(projectId)}
scanPending={scanProjects.isPending}
scanStatus={scanStatusMessage}
folderResult={showInstalledFolders ? railSkillFolderResult : null}
- folderSelection={folderSelection}
+ folderSelection={visibleFolderSelection}
foldersLoading={skillFoldersQuery.isLoading}
- selectMode={showInstalledFolders && selectMode}
- selectedSkillIds={selectedSkillIds}
+ selectMode={showInstalledBulkSelection && selectMode}
+ selectedSkillIds={showInstalledBulkSelection ? selectedSkillIds : []}
onFolderSelect={showInstalledFolders ? setFolderSelection : undefined}
onOpenMobileFolders={showInstalledFolders ? () => setMobileFoldersOpen(true) : undefined}
onCreateFolder={showInstalledFolders ? () => openCreateFolder() : undefined}
@@ -5460,11 +5529,11 @@ export function CompanySkills() {
} : undefined}
onMoveFolder={showInstalledFolders ? (folder, destination) => void moveFolderBetweenScopes(folder, destination) : undefined}
onDeleteFolder={showInstalledFolders ? setDeleteFolderTarget : undefined}
- onToggleSelectMode={showInstalledFolders ? () => {
+ onToggleSelectMode={showInstalledBulkSelection ? () => {
setSelectMode((current) => !current);
if (selectMode) setSelectedSkillIds([]);
} : undefined}
- onSelectCard={showInstalledFolders ? (card, selected) => {
+ onSelectCard={showInstalledBulkSelection ? (card, selected) => {
if (!card.skillId) return;
setSelectedSkillIds((current) =>
selected
@@ -5492,11 +5561,13 @@ export function CompanySkills() {
onCreateFolderAndMoveCard={showInstalledFolders ? (card) => {
if (card.skillId) openCreateFolder([card.skillId]);
} : undefined}
- onMoveSelected={showInstalledFolders ? (folderId) => void moveSelectedSkills(folderId) : undefined}
- onCreateFolderAndMoveSelected={showInstalledFolders ? () => openCreateFolder(selectedSkillIds) : undefined}
- onClearSelected={showInstalledFolders ? () => setSelectedSkillIds([]) : undefined}
+ onMoveSelected={showInstalledBulkSelection ? (folderId) => void moveSelectedSkills(folderId) : undefined}
+ onCreateFolderAndMoveSelected={showInstalledBulkSelection ? () => openCreateFolder(selectedSkillIds) : undefined}
+ onClearSelected={showInstalledBulkSelection ? () => setSelectedSkillIds([]) : undefined}
folderNudgeStorageKey={showInstalledFolders ? `paperclip:skills-folder-nudge:${selectedCompanyId ?? "none"}` : undefined}
+ showBrowseRails={browseRailsEnabled}
/>
+ </>
) : activeView === "installed" && selectedSkillId ? (
<SkillDetailPage
detail={activeDetail}
diff --git a/ui/src/pages/Costs.production.tsx b/ui/src/pages/Costs.production.tsx
new file mode 100644
index 0000000000..a314c5ffb6
--- /dev/null
+++ b/ui/src/pages/Costs.production.tsx
@@ -0,0 +1,1103 @@
+import { useEffect, useMemo, useRef, useState, type ComponentType } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import type {
+ BudgetPolicySummary,
+ CostByAgentModel,
+ CostByBiller,
+ CostByProviderModel,
+ CostWindowSpendRow,
+ FinanceEvent,
+ QuotaWindow,
+} from "@paperclipai/shared";
+import { ArrowDownLeft, ArrowUpRight, ChevronDown, ChevronRight, Coins, DollarSign, ReceiptText } from "lucide-react";
+import { budgetsApi } from "../api/budgets";
+import { costsApi } from "../api/costs";
+import { BillerSpendCard } from "../components/BillerSpendCard";
+import { BudgetIncidentCard } from "../components/BudgetIncidentCard";
+import { BudgetPolicyCard } from "../components/BudgetPolicyCard";
+import { EmptyState } from "../components/EmptyState";
+import { FinanceBillerCard } from "../components/FinanceBillerCard";
+import { FinanceKindCard } from "../components/FinanceKindCard";
+import { FinanceTimelineCard } from "../components/FinanceTimelineCard";
+import { Identity } from "../components/Identity";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { PageTabBar } from "../components/PageTabBar";
+import { ProviderQuotaCard } from "../components/ProviderQuotaCard";
+import { StatusBadge } from "../components/StatusBadge";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useCompany } from "../context/CompanyContext";
+import { useDateRange, PRESET_KEYS, PRESET_LABELS } from "../hooks/useDateRange";
+import { queryKeys } from "../lib/queryKeys";
+import { billingTypeDisplayName, cn, formatCents, formatTokens, providerDisplayName } from "../lib/utils";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+
+const NO_COMPANY = "__none__";
+
+function currentWeekRange(): { from: string; to: string } {
+ const now = new Date();
+ const day = now.getDay();
+ const diffToMon = day === 0 ? -6 : 1 - day;
+ const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate() + diffToMon, 0, 0, 0, 0);
+ const sun = new Date(mon.getFullYear(), mon.getMonth(), mon.getDate() + 6, 23, 59, 59, 999);
+ return { from: mon.toISOString(), to: sun.toISOString() };
+}
+
+function ProviderTabLabel({ provider, rows }: { provider: string; rows: CostByProviderModel[] }) {
+ const totalTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0);
+ const totalCost = rows.reduce((sum, row) => sum + row.costCents, 0);
+ return (
+ <span className="flex items-center gap-1.5">
+ <span>{providerDisplayName(provider)}</span>
+ <span className="font-mono text-xs text-muted-foreground">{formatTokens(totalTokens)}</span>
+ <span className="text-xs text-muted-foreground">{formatCents(totalCost)}</span>
+ </span>
+ );
+}
+
+function BillerTabLabel({ biller, rows }: { biller: string; rows: CostByBiller[] }) {
+ const totalTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0);
+ const totalCost = rows.reduce((sum, row) => sum + row.costCents, 0);
+ return (
+ <span className="flex items-center gap-1.5">
+ <span>{providerDisplayName(biller)}</span>
+ <span className="font-mono text-xs text-muted-foreground">{formatTokens(totalTokens)}</span>
+ <span className="text-xs text-muted-foreground">{formatCents(totalCost)}</span>
+ </span>
+ );
+}
+
+function MetricTile({
+ label,
+ value,
+ subtitle,
+ icon: Icon,
+}: {
+ label: string;
+ value: string;
+ subtitle: string;
+ icon: ComponentType<{ className?: string }>;
+}) {
+ return (
+ <Card className="block p-4">
+ <div className="flex items-center justify-between gap-3">
+ <div className="min-w-0">
+ <div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">{label}</div>
+ <div className="mt-2 text-2xl font-semibold tabular-nums">{value}</div>
+ <div className="mt-1 text-xs leading-5 text-muted-foreground">{subtitle}</div>
+ </div>
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border">
+ <Icon className="h-4 w-4 text-muted-foreground" />
+ </div>
+ </div>
+ </Card>
+ );
+}
+
+function FinanceSummaryCard({
+ debitCents,
+ creditCents,
+ netCents,
+ estimatedDebitCents,
+ eventCount,
+}: {
+ debitCents: number;
+ creditCents: number;
+ netCents: number;
+ estimatedDebitCents: number;
+ eventCount: number;
+}) {
+ return (
+ <Card>
+ <CardHeader className="px-5 pt-5 pb-2">
+ <CardTitle className="text-base">Finance ledger</CardTitle>
+ <CardDescription>
+ Account-level charges that do not map to a single inference request.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4">
+ <MetricTile
+ label="Debits"
+ value={formatCents(debitCents)}
+ subtitle={`${eventCount} total event${eventCount === 1 ? "" : "s"} in range`}
+ icon={ArrowUpRight}
+ />
+ <MetricTile
+ label="Credits"
+ value={formatCents(creditCents)}
+ subtitle="Refunds, offsets, and credit returns"
+ icon={ArrowDownLeft}
+ />
+ <MetricTile
+ label="Net"
+ value={formatCents(netCents)}
+ subtitle="Debit minus credit for the selected period"
+ icon={ReceiptText}
+ />
+ <MetricTile
+ label="Estimated"
+ value={formatCents(estimatedDebitCents)}
+ subtitle="Estimated debits that are not yet invoice-authoritative"
+ icon={Coins}
+ />
+ </CardContent>
+ </Card>
+ );
+}
+
+export function Costs() {
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const queryClient = useQueryClient();
+
+ const [mainTab, setMainTab] = useState<"overview" | "budgets" | "providers" | "billers" | "finance">("overview");
+ const [activeProvider, setActiveProvider] = useState("all");
+ const [activeBiller, setActiveBiller] = useState("all");
+
+ const {
+ preset,
+ setPreset,
+ customFrom,
+ setCustomFrom,
+ customTo,
+ setCustomTo,
+ from,
+ to,
+ customReady,
+ } = useDateRange();
+
+ useEffect(() => {
+ setBreadcrumbs([{ label: "Costs" }]);
+ }, [setBreadcrumbs]);
+
+ const [today, setToday] = useState(() => new Date().toDateString());
+ const todayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(() => {
+ const schedule = () => {
+ const now = new Date();
+ const ms = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime() - now.getTime();
+ todayTimerRef.current = setTimeout(() => {
+ setToday(new Date().toDateString());
+ schedule();
+ }, ms);
+ };
+ schedule();
+ return () => {
+ if (todayTimerRef.current != null) clearTimeout(todayTimerRef.current);
+ };
+ }, []);
+
+ const weekRange = useMemo(() => currentWeekRange(), [today]);
+ const companyId = selectedCompanyId ?? NO_COMPANY;
+
+ const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({
+ queryKey: queryKeys.budgets.overview(companyId),
+ queryFn: () => budgetsApi.overview(companyId),
+ enabled: !!selectedCompanyId && customReady,
+ refetchInterval: 30_000,
+ staleTime: 5_000,
+ });
+
+ const invalidateBudgetViews = () => {
+ if (!selectedCompanyId) return;
+ queryClient.invalidateQueries({ queryKey: queryKeys.budgets.overview(selectedCompanyId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(selectedCompanyId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.projects.all(selectedCompanyId) });
+ };
+
+ const policyMutation = useMutation({
+ mutationFn: (input: {
+ scopeType: BudgetPolicySummary["scopeType"];
+ scopeId: string;
+ amount: number;
+ windowKind: BudgetPolicySummary["windowKind"];
+ }) =>
+ budgetsApi.upsertPolicy(companyId, {
+ scopeType: input.scopeType,
+ scopeId: input.scopeId,
+ amount: input.amount,
+ windowKind: input.windowKind,
+ }),
+ onSuccess: invalidateBudgetViews,
+ });
+
+ const incidentMutation = useMutation({
+ mutationFn: (input: { incidentId: string; action: "keep_paused" | "raise_budget_and_resume"; amount?: number }) =>
+ budgetsApi.resolveIncident(companyId, input.incidentId, input),
+ onSuccess: invalidateBudgetViews,
+ });
+
+ const { data: spendData, isLoading: spendLoading, error: spendError } = useQuery({
+ queryKey: queryKeys.costs(companyId, from || undefined, to || undefined),
+ queryFn: async () => {
+ const [summary, byAgent, byProject, byAgentModel] = await Promise.all([
+ costsApi.summary(companyId, from || undefined, to || undefined),
+ costsApi.byAgent(companyId, from || undefined, to || undefined),
+ costsApi.byProject(companyId, from || undefined, to || undefined),
+ costsApi.byAgentModel(companyId, from || undefined, to || undefined),
+ ]);
+ return { summary, byAgent, byProject, byAgentModel };
+ },
+ enabled: !!selectedCompanyId && customReady,
+ });
+
+ const { data: financeData, isLoading: financeLoading, error: financeError } = useQuery({
+ queryKey: [
+ queryKeys.financeSummary(companyId, from || undefined, to || undefined),
+ queryKeys.financeByBiller(companyId, from || undefined, to || undefined),
+ queryKeys.financeByKind(companyId, from || undefined, to || undefined),
+ queryKeys.financeEvents(companyId, from || undefined, to || undefined, 18),
+ ],
+ queryFn: async () => {
+ const [summary, byBiller, byKind, events] = await Promise.all([
+ costsApi.financeSummary(companyId, from || undefined, to || undefined),
+ costsApi.financeByBiller(companyId, from || undefined, to || undefined),
+ costsApi.financeByKind(companyId, from || undefined, to || undefined),
+ costsApi.financeEvents(companyId, from || undefined, to || undefined, 18),
+ ]);
+ return { summary, byBiller, byKind, events };
+ },
+ enabled: !!selectedCompanyId && customReady,
+ });
+
+ const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());
+ useEffect(() => {
+ setExpandedAgents(new Set());
+ }, [companyId, from, to]);
+
+ function toggleAgent(agentId: string) {
+ setExpandedAgents((prev) => {
+ const next = new Set(prev);
+ if (next.has(agentId)) next.delete(agentId);
+ else next.add(agentId);
+ return next;
+ });
+ }
+
+ const agentModelRows = useMemo(() => {
+ const map = new Map<string, CostByAgentModel[]>();
+ for (const row of spendData?.byAgentModel ?? []) {
+ const rows = map.get(row.agentId) ?? [];
+ rows.push(row);
+ map.set(row.agentId, rows);
+ }
+ for (const [agentId, rows] of map) {
+ map.set(agentId, rows.slice().sort((a, b) => b.costCents - a.costCents));
+ }
+ return map;
+ }, [spendData?.byAgentModel]);
+
+ const { data: providerData } = useQuery({
+ queryKey: queryKeys.usageByProvider(companyId, from || undefined, to || undefined),
+ queryFn: () => costsApi.byProvider(companyId, from || undefined, to || undefined),
+ enabled: !!selectedCompanyId && customReady && (mainTab === "providers" || mainTab === "billers"),
+ refetchInterval: 30_000,
+ staleTime: 10_000,
+ });
+
+ const { data: billerData } = useQuery({
+ queryKey: queryKeys.usageByBiller(companyId, from || undefined, to || undefined),
+ queryFn: () => costsApi.byBiller(companyId, from || undefined, to || undefined),
+ enabled: !!selectedCompanyId && customReady && mainTab === "billers",
+ refetchInterval: 30_000,
+ staleTime: 10_000,
+ });
+
+ const { data: weekData } = useQuery({
+ queryKey: queryKeys.usageByProvider(companyId, weekRange.from, weekRange.to),
+ queryFn: () => costsApi.byProvider(companyId, weekRange.from, weekRange.to),
+ enabled: !!selectedCompanyId && (mainTab === "providers" || mainTab === "billers"),
+ refetchInterval: 30_000,
+ staleTime: 10_000,
+ });
+
+ const { data: weekBillerData } = useQuery({
+ queryKey: queryKeys.usageByBiller(companyId, weekRange.from, weekRange.to),
+ queryFn: () => costsApi.byBiller(companyId, weekRange.from, weekRange.to),
+ enabled: !!selectedCompanyId && mainTab === "billers",
+ refetchInterval: 30_000,
+ staleTime: 10_000,
+ });
+
+ const { data: windowData } = useQuery({
+ queryKey: queryKeys.usageWindowSpend(companyId),
+ queryFn: () => costsApi.windowSpend(companyId),
+ enabled: !!selectedCompanyId && mainTab === "providers",
+ refetchInterval: 30_000,
+ staleTime: 10_000,
+ });
+
+ const { data: quotaData, isLoading: quotaLoading } = useQuery({
+ queryKey: queryKeys.usageQuotaWindows(companyId),
+ queryFn: () => costsApi.quotaWindows(companyId),
+ enabled: !!selectedCompanyId && mainTab === "providers",
+ refetchInterval: 300_000,
+ staleTime: 60_000,
+ });
+
+ const byProvider = useMemo(() => {
+ const map = new Map<string, CostByProviderModel[]>();
+ for (const row of providerData ?? []) {
+ const rows = map.get(row.provider) ?? [];
+ rows.push(row);
+ map.set(row.provider, rows);
+ }
+ return map;
+ }, [providerData]);
+
+ const byBiller = useMemo(() => {
+ const map = new Map<string, CostByBiller[]>();
+ for (const row of billerData ?? []) {
+ const rows = map.get(row.biller) ?? [];
+ rows.push(row);
+ map.set(row.biller, rows);
+ }
+ return map;
+ }, [billerData]);
+
+ const weekSpendByProvider = useMemo(() => {
+ const map = new Map<string, number>();
+ for (const row of weekData ?? []) {
+ map.set(row.provider, (map.get(row.provider) ?? 0) + row.costCents);
+ }
+ return map;
+ }, [weekData]);
+
+ const weekSpendByBiller = useMemo(() => {
+ const map = new Map<string, number>();
+ for (const row of weekBillerData ?? []) {
+ map.set(row.biller, (map.get(row.biller) ?? 0) + row.costCents);
+ }
+ return map;
+ }, [weekBillerData]);
+
+ const windowSpendByProvider = useMemo(() => {
+ const map = new Map<string, CostWindowSpendRow[]>();
+ for (const row of windowData ?? []) {
+ const rows = map.get(row.provider) ?? [];
+ rows.push(row);
+ map.set(row.provider, rows);
+ }
+ return map;
+ }, [windowData]);
+
+ const quotaWindowsByProvider = useMemo(() => {
+ const map = new Map<string, QuotaWindow[]>();
+ for (const result of quotaData ?? []) {
+ if (result.ok && result.windows.length > 0) {
+ map.set(result.provider, result.windows);
+ }
+ }
+ return map;
+ }, [quotaData]);
+
+ const quotaErrorsByProvider = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const result of quotaData ?? []) {
+ if (!result.ok && result.error) map.set(result.provider, result.error);
+ }
+ return map;
+ }, [quotaData]);
+
+ const quotaSourcesByProvider = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const result of quotaData ?? []) {
+ if (typeof result.source === "string" && result.source.length > 0) {
+ map.set(result.provider, result.source);
+ }
+ }
+ return map;
+ }, [quotaData]);
+
+ const deficitNotchByProvider = useMemo(() => {
+ const map = new Map<string, boolean>();
+ if (preset !== "mtd") return map;
+ const budget = spendData?.summary.budgetCents ?? 0;
+ if (budget <= 0) return map;
+ const totalSpend = spendData?.summary.spendCents ?? 0;
+ const now = new Date();
+ const daysElapsed = now.getDate();
+ const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
+ for (const [providerKey, rows] of byProvider) {
+ const providerCostCents = rows.reduce((sum, row) => sum + row.costCents, 0);
+ const providerShare = totalSpend > 0 ? providerCostCents / totalSpend : 0;
+ const providerBudget = budget * providerShare;
+ if (providerBudget <= 0) {
+ map.set(providerKey, false);
+ continue;
+ }
+ const burnRate = providerCostCents / Math.max(daysElapsed, 1);
+ map.set(providerKey, providerCostCents + burnRate * (daysInMonth - daysElapsed) > providerBudget);
+ }
+ return map;
+ }, [preset, spendData, byProvider]);
+
+ const providers = useMemo(() => Array.from(byProvider.keys()), [byProvider]);
+ const billers = useMemo(() => Array.from(byBiller.keys()), [byBiller]);
+
+ const effectiveProvider =
+ activeProvider === "all" || providers.includes(activeProvider) ? activeProvider : "all";
+ useEffect(() => {
+ if (effectiveProvider !== activeProvider) setActiveProvider("all");
+ }, [effectiveProvider, activeProvider]);
+
+ const effectiveBiller =
+ activeBiller === "all" || billers.includes(activeBiller) ? activeBiller : "all";
+ useEffect(() => {
+ if (effectiveBiller !== activeBiller) setActiveBiller("all");
+ }, [effectiveBiller, activeBiller]);
+
+ const providerTabItems = useMemo(() => {
+ const providerKeys = Array.from(byProvider.keys());
+ const allTokens = providerKeys.reduce(
+ (sum, provider) => sum + (byProvider.get(provider)?.reduce((acc, row) => acc + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0) ?? 0),
+ 0,
+ );
+ const allCents = providerKeys.reduce(
+ (sum, provider) => sum + (byProvider.get(provider)?.reduce((acc, row) => acc + row.costCents, 0) ?? 0),
+ 0,
+ );
+ return [
+ {
+ value: "all",
+ label: (
+ <span className="flex items-center gap-1.5">
+ <span>All providers</span>
+ {providerKeys.length > 0 ? (
+ <>
+ <span className="font-mono text-xs text-muted-foreground">{formatTokens(allTokens)}</span>
+ <span className="text-xs text-muted-foreground">{formatCents(allCents)}</span>
+ </>
+ ) : null}
+ </span>
+ ),
+ },
+ ...providerKeys.map((provider) => ({
+ value: provider,
+ label: <ProviderTabLabel provider={provider} rows={byProvider.get(provider) ?? []} />,
+ })),
+ ];
+ }, [byProvider]);
+
+ const billerTabItems = useMemo(() => {
+ const billerKeys = Array.from(byBiller.keys());
+ const allTokens = billerKeys.reduce(
+ (sum, biller) => sum + (byBiller.get(biller)?.reduce((acc, row) => acc + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0) ?? 0),
+ 0,
+ );
+ const allCents = billerKeys.reduce(
+ (sum, biller) => sum + (byBiller.get(biller)?.reduce((acc, row) => acc + row.costCents, 0) ?? 0),
+ 0,
+ );
+ return [
+ {
+ value: "all",
+ label: (
+ <span className="flex items-center gap-1.5">
+ <span>All billers</span>
+ {billerKeys.length > 0 ? (
+ <>
+ <span className="font-mono text-xs text-muted-foreground">{formatTokens(allTokens)}</span>
+ <span className="text-xs text-muted-foreground">{formatCents(allCents)}</span>
+ </>
+ ) : null}
+ </span>
+ ),
+ },
+ ...billerKeys.map((biller) => ({
+ value: biller,
+ label: <BillerTabLabel biller={biller} rows={byBiller.get(biller) ?? []} />,
+ })),
+ ];
+ }, [byBiller]);
+
+ const inferenceTokenTotal =
+ (spendData?.byAgent ?? []).reduce(
+ (sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens,
+ 0,
+ );
+
+ const topFinanceEvents = (financeData?.events ?? []) as FinanceEvent[];
+ const budgetPolicies = budgetData?.policies ?? [];
+ const activeBudgetIncidents = budgetData?.activeIncidents ?? [];
+ const budgetPoliciesByScope = useMemo(() => ({
+ company: budgetPolicies.filter((policy) => policy.scopeType === "company"),
+ agent: budgetPolicies.filter((policy) => policy.scopeType === "agent"),
+ project: budgetPolicies.filter((policy) => policy.scopeType === "project"),
+ }), [budgetPolicies]);
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={DollarSign} message="Select a company to view costs." />;
+ }
+
+ const showCustomPrompt = preset === "custom" && !customReady;
+ const showOverviewLoading = (spendLoading || financeLoading) && customReady;
+ const overviewError = spendError ?? financeError;
+
+ return (
+ <div className="space-y-6">
+ <div className="space-y-5">
+ <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
+ <div>
+ <h1 className="text-3xl font-semibold tracking-tight">Costs</h1>
+ <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">
+ Inference spend, platform fees, credits, and live quota windows.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ {PRESET_KEYS.map((key) => (
+ <Button
+ key={key}
+ variant={preset === key ? "secondary" : "ghost"}
+ size="sm"
+ onClick={() => setPreset(key)}
+ aria-pressed={preset === key}
+ >
+ {PRESET_LABELS[key]}
+ </Button>
+ ))}
+ </div>
+ </div>
+
+ {preset === "custom" ? (
+ <div className="flex flex-wrap items-center gap-2 border border-border p-3">
+ <input
+ type="date"
+ value={customFrom}
+ onChange={(event) => setCustomFrom(event.target.value)}
+ className="h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"
+ />
+ <span className="text-sm text-muted-foreground">to</span>
+ <input
+ type="date"
+ value={customTo}
+ onChange={(event) => setCustomTo(event.target.value)}
+ className="h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"
+ />
+ </div>
+ ) : null}
+
+ <div className="grid gap-3 lg:grid-cols-4">
+ <MetricTile
+ label="Inference spend"
+ value={formatCents(spendData?.summary.spendCents ?? 0)}
+ subtitle={`${formatTokens(inferenceTokenTotal)} tokens across request-scoped events`}
+ icon={DollarSign}
+ />
+ <MetricTile
+ label="Budget"
+ value={activeBudgetIncidents.length > 0 ? String(activeBudgetIncidents.length) : (
+ spendData?.summary.budgetCents && spendData.summary.budgetCents > 0
+ ? `${spendData.summary.utilizationPercent}%`
+ : "Open"
+ )}
+ subtitle={
+ activeBudgetIncidents.length > 0
+ ? `${budgetData?.pausedAgentCount ?? 0} agents paused · ${budgetData?.pausedProjectCount ?? 0} projects paused`
+ : spendData?.summary.budgetCents && spendData.summary.budgetCents > 0
+ ? `${formatCents(spendData.summary.spendCents)} of ${formatCents(spendData.summary.budgetCents)}`
+ : "No monthly cap configured"
+ }
+ icon={Coins}
+ />
+ <MetricTile
+ label="Finance net"
+ value={formatCents(financeData?.summary.netCents ?? 0)}
+ subtitle={`${formatCents(financeData?.summary.debitCents ?? 0)} debits · ${formatCents(financeData?.summary.creditCents ?? 0)} credits`}
+ icon={ReceiptText}
+ />
+ <MetricTile
+ label="Finance events"
+ value={String(financeData?.summary.eventCount ?? 0)}
+ subtitle={`${formatCents(financeData?.summary.estimatedDebitCents ?? 0)} estimated in range`}
+ icon={ArrowUpRight}
+ />
+ </div>
+ </div>
+
+ <Tabs value={mainTab} onValueChange={(value) => setMainTab(value as typeof mainTab)}>
+ <TabsList variant="line" className="justify-start">
+ <TabsTrigger value="overview">Overview</TabsTrigger>
+ <TabsTrigger value="budgets">Budgets</TabsTrigger>
+ <TabsTrigger value="providers">Providers</TabsTrigger>
+ <TabsTrigger value="billers">Billers</TabsTrigger>
+ <TabsTrigger value="finance">Finance</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="overview" className="mt-4 space-y-4">
+ {showCustomPrompt ? (
+ <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>
+ ) : showOverviewLoading ? (
+ <PageSkeleton variant="costs" />
+ ) : overviewError ? (
+ <p className="text-sm text-destructive">{(overviewError as Error).message}</p>
+ ) : (
+ <>
+ {activeBudgetIncidents.length > 0 ? (
+ <div className="grid gap-4 xl:grid-cols-2">
+ {activeBudgetIncidents.slice(0, 2).map((incident) => (
+ <BudgetIncidentCard
+ key={incident.id}
+ incident={incident}
+ isMutating={incidentMutation.isPending}
+ onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })}
+ onRaiseAndResume={(amount) =>
+ incidentMutation.mutate({
+ incidentId: incident.id,
+ action: "raise_budget_and_resume",
+ amount,
+ })}
+ />
+ ))}
+ </div>
+ ) : null}
+
+ <div className="grid gap-4 xl:grid-cols-(--gtc-31)">
+ <Card>
+ <CardHeader className="px-5 pt-5 pb-2">
+ <CardTitle className="text-base">Inference ledger</CardTitle>
+ <CardDescription>
+ Request-scoped inference spend for the selected period.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4 px-5 pb-5 pt-2">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <div>
+ <div className="text-3xl font-semibold tabular-nums">
+ {formatCents(spendData?.summary.spendCents ?? 0)}
+ </div>
+ <div className="mt-1 text-sm text-muted-foreground">
+ {spendData?.summary.budgetCents && spendData.summary.budgetCents > 0
+ ? `Budget ${formatCents(spendData.summary.budgetCents)}`
+ : "Unlimited budget"}
+ </div>
+ </div>
+ <div className="border border-border px-4 py-3 text-right">
+ <div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">usage</div>
+ <div className="mt-1 text-lg font-medium tabular-nums">
+ {formatTokens(inferenceTokenTotal)}
+ </div>
+ </div>
+ </div>
+ {spendData?.summary.budgetCents && spendData.summary.budgetCents > 0 ? (
+ <div className="space-y-2">
+ <div className="h-2 overflow-hidden bg-muted">
+ <div
+ className={cn(
+ "h-full transition-(--tp-width-background-color) duration-150",
+ spendData.summary.utilizationPercent > 90
+ ? "bg-(--status-task-blocked)"
+ : spendData.summary.utilizationPercent > 70
+ ? "bg-(--status-task-todo)"
+ : "bg-(--status-task-done)",
+ )}
+ style={{ width: `${Math.min(100, spendData.summary.utilizationPercent)}%` }}
+ />
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {spendData.summary.utilizationPercent}% of monthly budget consumed in this range.
+ </div>
+ </div>
+ ) : null}
+ </CardContent>
+ </Card>
+
+ <FinanceSummaryCard
+ debitCents={financeData?.summary.debitCents ?? 0}
+ creditCents={financeData?.summary.creditCents ?? 0}
+ netCents={financeData?.summary.netCents ?? 0}
+ estimatedDebitCents={financeData?.summary.estimatedDebitCents ?? 0}
+ eventCount={financeData?.summary.eventCount ?? 0}
+ />
+ </div>
+
+ <div className="grid gap-4 xl:grid-cols-(--gtc-32)">
+ <Card>
+ <CardHeader className="px-5 pt-5 pb-2">
+ <CardTitle className="text-base">By agent</CardTitle>
+ <CardDescription>What each agent consumed in the selected period.</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-2 px-5 pb-5 pt-2">
+ {(spendData?.byAgent.length ?? 0) === 0 ? (
+ <p className="text-sm text-muted-foreground">No cost events yet.</p>
+ ) : (
+ spendData?.byAgent.map((row) => {
+ const modelRows = agentModelRows.get(row.agentId) ?? [];
+ const isExpanded = expandedAgents.has(row.agentId);
+ const hasBreakdown = modelRows.length > 0;
+ return (
+ <div key={row.agentId} className="border border-border px-4 py-3">
+ <div
+ className={cn("flex items-start justify-between gap-3", hasBreakdown ? "cursor-pointer select-none" : "")}
+ onClick={() => hasBreakdown && toggleAgent(row.agentId)}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ {hasBreakdown ? (
+ isExpanded
+ ? <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />
+ : <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />
+ ) : (
+ <span className="h-3 w-3 shrink-0" />
+ )}
+ <Identity name={row.agentName ?? row.agentId} size="sm" />
+ {row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}
+ </div>
+ <div className="text-right text-sm tabular-nums">
+ <div className="font-medium">{formatCents(row.costCents)}</div>
+ <div className="text-xs text-muted-foreground">
+ in {formatTokens(row.inputTokens + row.cachedInputTokens)} · out {formatTokens(row.outputTokens)}
+ </div>
+ {(row.apiRunCount > 0 || row.subscriptionRunCount > 0) ? (
+ <div className="text-xs text-muted-foreground">
+ {row.apiRunCount > 0 ? `${row.apiRunCount} api` : "0 api"}
+ {" · "}
+ {row.subscriptionRunCount > 0
+ ? `${row.subscriptionRunCount} subscription`
+ : "0 subscription"}
+ </div>
+ ) : null}
+ </div>
+ </div>
+
+ {isExpanded && modelRows.length > 0 ? (
+ <div className="mt-3 space-y-2 border-l border-border pl-4">
+ {modelRows.map((modelRow) => {
+ const sharePct = row.costCents > 0 ? Math.round((modelRow.costCents / row.costCents) * 100) : 0;
+ return (
+ <div
+ key={`${modelRow.provider}:${modelRow.model}:${modelRow.billingType}`}
+ className="flex items-start justify-between gap-3 text-xs"
+ >
+ <div className="min-w-0">
+ <div className="truncate font-medium text-foreground">
+ {providerDisplayName(modelRow.provider)}
+ <span className="mx-1 text-border">/</span>
+ <span className="font-mono">{modelRow.model}</span>
+ </div>
+ <div className="truncate text-muted-foreground">
+ {providerDisplayName(modelRow.biller)} · {billingTypeDisplayName(modelRow.billingType)}
+ </div>
+ </div>
+ <div className="text-right tabular-nums">
+ <div className="font-medium">
+ {formatCents(modelRow.costCents)}
+ <span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>
+ </div>
+ <div className="text-muted-foreground">
+ {formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ) : null}
+ </div>
+ );
+ })
+ )}
+ </CardContent>
+ </Card>
+
+ <div className="space-y-4">
+ <Card>
+ <CardHeader className="px-5 pt-5 pb-2">
+ <CardTitle className="text-base">By project</CardTitle>
+ <CardDescription>Run costs attributed through project-linked tasks.</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-2 px-5 pb-5 pt-2">
+ {(spendData?.byProject.length ?? 0) === 0 ? (
+ <p className="text-sm text-muted-foreground">No project-attributed run costs yet.</p>
+ ) : (
+ spendData?.byProject.map((row, index) => (
+ <div
+ key={row.projectId ?? `unattributed-${index}`}
+ className="flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm"
+ >
+ <span className="truncate">{row.projectName ?? row.projectId ?? "Unattributed"}</span>
+ <span className="font-medium tabular-nums">{formatCents(row.costCents)}</span>
+ </div>
+ ))
+ )}
+ </CardContent>
+ </Card>
+
+ <FinanceTimelineCard rows={topFinanceEvents.slice(0, 6)} emptyMessage="No finance events yet. Add account-level charges once biller invoices or credits land." />
+ </div>
+ </div>
+ </>
+ )}
+ </TabsContent>
+
+ <TabsContent value="budgets" className="mt-4 space-y-4">
+ {budgetLoading ? (
+ <PageSkeleton variant="costs" />
+ ) : budgetError ? (
+ <p className="text-sm text-destructive">{(budgetError as Error).message}</p>
+ ) : (
+ <>
+ <Card className="border-border/70 bg-(image:--gradient-extract-2)">
+ <CardHeader className="px-5 pt-5 pb-3">
+ <CardTitle className="text-base">Budget control plane</CardTitle>
+ <CardDescription>
+ Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4">
+ <MetricTile
+ label="Active incidents"
+ value={String(activeBudgetIncidents.length)}
+ subtitle="Open soft or hard threshold crossings"
+ icon={ReceiptText}
+ />
+ <MetricTile
+ label="Pending approvals"
+ value={String(budgetData?.pendingApprovalCount ?? 0)}
+ subtitle="Budget override approvals awaiting board action"
+ icon={ArrowUpRight}
+ />
+ <MetricTile
+ label="Paused agents"
+ value={String(budgetData?.pausedAgentCount ?? 0)}
+ subtitle="Agent heartbeats blocked by budget"
+ icon={Coins}
+ />
+ <MetricTile
+ label="Paused projects"
+ value={String(budgetData?.pausedProjectCount ?? 0)}
+ subtitle="Project execution blocked by budget"
+ icon={DollarSign}
+ />
+ </CardContent>
+ </Card>
+
+ {activeBudgetIncidents.length > 0 ? (
+ <div className="space-y-3">
+ <div>
+ <h2 className="text-lg font-semibold">Active incidents</h2>
+ <p className="text-sm text-muted-foreground">
+ Resolve hard stops here by raising the budget or explicitly keeping the scope paused.
+ </p>
+ </div>
+ <div className="grid gap-4 xl:grid-cols-2">
+ {activeBudgetIncidents.map((incident) => (
+ <BudgetIncidentCard
+ key={incident.id}
+ incident={incident}
+ isMutating={incidentMutation.isPending}
+ onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })}
+ onRaiseAndResume={(amount) =>
+ incidentMutation.mutate({
+ incidentId: incident.id,
+ action: "raise_budget_and_resume",
+ amount,
+ })}
+ />
+ ))}
+ </div>
+ </div>
+ ) : null}
+
+ <div className="space-y-5">
+ {(["company", "agent", "project"] as const).map((scopeType) => {
+ const rows = budgetPoliciesByScope[scopeType];
+ if (rows.length === 0) return null;
+ return (
+ <section key={scopeType} className="space-y-3">
+ <div>
+ <h2 className="text-lg font-semibold capitalize">{scopeType} budgets</h2>
+ <p className="text-sm text-muted-foreground">
+ {scopeType === "company"
+ ? "Company-wide monthly policy."
+ : scopeType === "agent"
+ ? "Recurring monthly spend policies for individual agents."
+ : "Lifetime spend policies for execution-bound projects."}
+ </p>
+ </div>
+ <div className="grid gap-4 xl:grid-cols-2">
+ {rows.map((summary) => (
+ <BudgetPolicyCard
+ key={summary.policyId}
+ summary={summary}
+ isSaving={policyMutation.isPending}
+ onSave={(amount) =>
+ policyMutation.mutate({
+ scopeType: summary.scopeType,
+ scopeId: summary.scopeId,
+ amount,
+ windowKind: summary.windowKind,
+ })}
+ />
+ ))}
+ </div>
+ </section>
+ );
+ })}
+
+ {budgetPolicies.length === 0 ? (
+ <Card>
+ <CardContent className="px-5 py-8 text-sm text-muted-foreground">
+ No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control.
+ </CardContent>
+ </Card>
+ ) : null}
+ </div>
+ </>
+ )}
+ </TabsContent>
+
+ <TabsContent value="providers" className="mt-4 space-y-4">
+ {showCustomPrompt ? (
+ <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>
+ ) : (
+ <>
+ <Tabs value={effectiveProvider} onValueChange={setActiveProvider}>
+ <PageTabBar items={providerTabItems} value={effectiveProvider} />
+
+ <TabsContent value="all" className="mt-4">
+ {providers.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No cost events in this period.</p>
+ ) : (
+ <div className="grid gap-4 md:grid-cols-2">
+ {providers.map((provider) => (
+ <ProviderQuotaCard
+ key={provider}
+ provider={provider}
+ rows={byProvider.get(provider) ?? []}
+ budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}
+ totalCompanySpendCents={spendData?.summary.spendCents ?? 0}
+ weekSpendCents={weekSpendByProvider.get(provider) ?? 0}
+ windowRows={windowSpendByProvider.get(provider) ?? []}
+ showDeficitNotch={deficitNotchByProvider.get(provider) ?? false}
+ quotaWindows={quotaWindowsByProvider.get(provider) ?? []}
+ quotaError={quotaErrorsByProvider.get(provider) ?? null}
+ quotaSource={quotaSourcesByProvider.get(provider) ?? null}
+ quotaLoading={quotaLoading}
+ />
+ ))}
+ </div>
+ )}
+ </TabsContent>
+
+ {providers.map((provider) => (
+ <TabsContent key={provider} value={provider} className="mt-4">
+ <ProviderQuotaCard
+ provider={provider}
+ rows={byProvider.get(provider) ?? []}
+ budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}
+ totalCompanySpendCents={spendData?.summary.spendCents ?? 0}
+ weekSpendCents={weekSpendByProvider.get(provider) ?? 0}
+ windowRows={windowSpendByProvider.get(provider) ?? []}
+ showDeficitNotch={deficitNotchByProvider.get(provider) ?? false}
+ quotaWindows={quotaWindowsByProvider.get(provider) ?? []}
+ quotaError={quotaErrorsByProvider.get(provider) ?? null}
+ quotaSource={quotaSourcesByProvider.get(provider) ?? null}
+ quotaLoading={quotaLoading}
+ />
+ </TabsContent>
+ ))}
+ </Tabs>
+ </>
+ )}
+ </TabsContent>
+
+ <TabsContent value="billers" className="mt-4 space-y-4">
+ {showCustomPrompt ? (
+ <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>
+ ) : (
+ <>
+ <Tabs value={effectiveBiller} onValueChange={setActiveBiller}>
+ <PageTabBar items={billerTabItems} value={effectiveBiller} />
+
+ <TabsContent value="all" className="mt-4">
+ {billers.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No billable events in this period.</p>
+ ) : (
+ <div className="grid gap-4 md:grid-cols-2">
+ {billers.map((biller) => {
+ const row = (byBiller.get(biller) ?? [])[0];
+ if (!row) return null;
+ const providerRows = (providerData ?? []).filter((entry) => entry.biller === biller);
+ return (
+ <BillerSpendCard
+ key={biller}
+ row={row}
+ weekSpendCents={weekSpendByBiller.get(biller) ?? 0}
+ budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}
+ totalCompanySpendCents={spendData?.summary.spendCents ?? 0}
+ providerRows={providerRows}
+ />
+ );
+ })}
+ </div>
+ )}
+ </TabsContent>
+
+ {billers.map((biller) => {
+ const row = (byBiller.get(biller) ?? [])[0];
+ if (!row) return null;
+ const providerRows = (providerData ?? []).filter((entry) => entry.biller === biller);
+ return (
+ <TabsContent key={biller} value={biller} className="mt-4">
+ <BillerSpendCard
+ row={row}
+ weekSpendCents={weekSpendByBiller.get(biller) ?? 0}
+ budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}
+ totalCompanySpendCents={spendData?.summary.spendCents ?? 0}
+ providerRows={providerRows}
+ />
+ </TabsContent>
+ );
+ })}
+ </Tabs>
+ </>
+ )}
+ </TabsContent>
+
+ <TabsContent value="finance" className="mt-4 space-y-4">
+ {showCustomPrompt ? (
+ <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>
+ ) : financeLoading ? (
+ <PageSkeleton variant="costs" />
+ ) : financeError ? (
+ <p className="text-sm text-destructive">{(financeError as Error).message}</p>
+ ) : (
+ <>
+ <FinanceSummaryCard
+ debitCents={financeData?.summary.debitCents ?? 0}
+ creditCents={financeData?.summary.creditCents ?? 0}
+ netCents={financeData?.summary.netCents ?? 0}
+ estimatedDebitCents={financeData?.summary.estimatedDebitCents ?? 0}
+ eventCount={financeData?.summary.eventCount ?? 0}
+ />
+
+ <div className="grid gap-4 xl:grid-cols-(--gtc-33)">
+ <div className="space-y-4">
+ <Card>
+ <CardHeader className="px-5 pt-5 pb-2">
+ <CardTitle className="text-base">By biller</CardTitle>
+ <CardDescription>Account-level financial events grouped by who charged or credited them.</CardDescription>
+ </CardHeader>
+ <CardContent className="grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2">
+ {(financeData?.byBiller.length ?? 0) === 0 ? (
+ <p className="text-sm text-muted-foreground">No finance events yet.</p>
+ ) : (
+ financeData?.byBiller.map((row) => <FinanceBillerCard key={row.biller} row={row} />)
+ )}
+ </CardContent>
+ </Card>
+ <FinanceTimelineCard rows={topFinanceEvents} />
+ </div>
+
+ <FinanceKindCard rows={financeData?.byKind ?? []} />
+ </div>
+ </>
+ )}
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/ui/src/pages/Costs.test.tsx b/ui/src/pages/Costs.test.tsx
new file mode 100644
index 0000000000..04b21bd3c7
--- /dev/null
+++ b/ui/src/pages/Costs.test.tsx
@@ -0,0 +1,92 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Costs } from "./Costs";
+
+const budgetOverviewMock = vi.hoisted(() => vi.fn());
+const setBreadcrumbsMock = vi.hoisted(() => vi.fn());
+const costsApiMocks = vi.hoisted(() => ({
+ summary: vi.fn(),
+ byAgent: vi.fn(),
+ byProject: vi.fn(),
+ byAgentModel: vi.fn(),
+ financeSummary: vi.fn(),
+ financeByBiller: vi.fn(),
+ financeByKind: vi.fn(),
+ financeEvents: vi.fn(),
+ byProvider: vi.fn(),
+ byBiller: vi.fn(),
+ windowSpend: vi.fn(),
+ quotaWindows: vi.fn(),
+}));
+
+vi.mock("../api/budgets", () => ({
+ budgetsApi: {
+ overview: (...args: unknown[]) => budgetOverviewMock(...args),
+ upsertPolicy: vi.fn(),
+ resolveIncident: vi.fn(),
+ },
+}));
+
+vi.mock("../api/costs", () => ({ costsApi: costsApiMocks }));
+
+vi.mock("../context/CompanyContext", () => ({
+ useCompany: () => ({ selectedCompanyId: "company-1" }),
+}));
+
+vi.mock("../context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: setBreadcrumbsMock }),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("Costs embedded Audit surfaces", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ budgetOverviewMock.mockResolvedValue({
+ policies: [],
+ activeIncidents: [],
+ pendingApprovalCount: 0,
+ pausedAgentCount: 0,
+ pausedProjectCount: 0,
+ });
+ });
+
+ afterEach(() => {
+ act(() => root?.unmount());
+ container.remove();
+ vi.clearAllMocks();
+ });
+
+ it("renders a focused Budgets section without duplicate Costs chrome or spend queries", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ root = createRoot(container);
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Costs embedded initialTab="budgets" lockTab />
+ </QueryClientProvider>,
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await vi.waitFor(() => {
+ expect(budgetOverviewMock).toHaveBeenCalledWith("company-1");
+ expect(container.textContent).toContain("Budget control plane");
+ });
+ });
+ expect(container.textContent).not.toContain("Inference spend");
+ expect(container.querySelector('[role="tab"]')).toBeFalsy();
+ expect(setBreadcrumbsMock).not.toHaveBeenCalled();
+ for (const mock of Object.values(costsApiMocks)) expect(mock).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/pages/Costs.tsx b/ui/src/pages/Costs.tsx
index 44206e50fa..c639fd6aef 100644
--- a/ui/src/pages/Costs.tsx
+++ b/ui/src/pages/Costs.tsx
@@ -34,6 +34,17 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
const NO_COMPANY = "__none__";
+export type CostsMainTab = "overview" | "budgets" | "providers" | "billers" | "finance";
+
+export interface CostsProps {
+ /** Render inside Audit without a second page-level title or breadcrumb. */
+ embedded?: boolean;
+ initialTab?: CostsMainTab;
+ /** Pin the surface to one tab (used by Audit > Budgets). */
+ lockTab?: boolean;
+ /** Budgets is a peer Audit section, so omit it from the Costs sub-navigation. */
+ hideBudgetsTab?: boolean;
+}
function currentWeekRange(): { from: string; to: string } {
const now = new Date();
@@ -146,14 +157,20 @@ function FinanceSummaryCard({
);
}
-export function Costs() {
+export function Costs({
+ embedded = false,
+ initialTab = "overview",
+ lockTab = false,
+ hideBudgetsTab = false,
+}: CostsProps = {}) {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
- const [mainTab, setMainTab] = useState<"overview" | "budgets" | "providers" | "billers" | "finance">("overview");
+ const [mainTab, setMainTab] = useState<CostsMainTab>(initialTab);
const [activeProvider, setActiveProvider] = useState("all");
const [activeBiller, setActiveBiller] = useState("all");
+ const showSummaryChrome = !(embedded && lockTab && initialTab === "budgets");
const {
preset,
@@ -168,8 +185,12 @@ export function Costs() {
} = useDateRange();
useEffect(() => {
- setBreadcrumbs([{ label: "Costs" }]);
- }, [setBreadcrumbs]);
+ if (!embedded) setBreadcrumbs([{ label: "Costs" }]);
+ }, [embedded, setBreadcrumbs]);
+
+ useEffect(() => {
+ setMainTab(initialTab);
+ }, [initialTab]);
const [today, setToday] = useState(() => new Date().toDateString());
const todayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -240,7 +261,7 @@ export function Costs() {
]);
return { summary, byAgent, byProject, byAgentModel };
},
- enabled: !!selectedCompanyId && customReady,
+ enabled: !!selectedCompanyId && customReady && showSummaryChrome,
});
const { data: financeData, isLoading: financeLoading, error: financeError } = useQuery({
@@ -259,7 +280,7 @@ export function Costs() {
]);
return { summary, byBiller, byKind, events };
},
- enabled: !!selectedCompanyId && customReady,
+ enabled: !!selectedCompanyId && customReady && showSummaryChrome,
});
const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());
@@ -535,16 +556,20 @@ export function Costs() {
const showCustomPrompt = preset === "custom" && !customReady;
const showOverviewLoading = (spendLoading || financeLoading) && customReady;
const overviewError = spendError ?? financeError;
-
return (
<div className="space-y-6">
- <div className="space-y-5">
+ {showSummaryChrome ? (
+ <div className="space-y-5">
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div>
+ {embedded ? (
+ <h2 className="text-lg font-semibold text-foreground">Costs</h2>
+ ) : (
<h1 className="text-3xl font-semibold tracking-tight">Costs</h1>
- <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">
- Inference spend, platform fees, credits, and live quota windows.
- </p>
+ )}
+ <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">
+ Inference spend, platform fees, credits, and live quota windows.
+ </p>
</div>
<div className="flex flex-wrap items-center gap-2">
@@ -616,16 +641,19 @@ export function Costs() {
icon={ArrowUpRight}
/>
</div>
- </div>
+ </div>
+ ) : null}
<Tabs value={mainTab} onValueChange={(value) => setMainTab(value as typeof mainTab)}>
- <TabsList variant="line" className="justify-start">
- <TabsTrigger value="overview">Overview</TabsTrigger>
- <TabsTrigger value="budgets">Budgets</TabsTrigger>
- <TabsTrigger value="providers">Providers</TabsTrigger>
- <TabsTrigger value="billers">Billers</TabsTrigger>
- <TabsTrigger value="finance">Finance</TabsTrigger>
- </TabsList>
+ {!lockTab ? (
+ <TabsList variant="line" className="justify-start">
+ <TabsTrigger value="overview">Overview</TabsTrigger>
+ {!hideBudgetsTab ? <TabsTrigger value="budgets">Budgets</TabsTrigger> : null}
+ <TabsTrigger value="providers">Providers</TabsTrigger>
+ <TabsTrigger value="billers">Billers</TabsTrigger>
+ <TabsTrigger value="finance">Finance</TabsTrigger>
+ </TabsList>
+ ) : null}
<TabsContent value="overview" className="mt-4 space-y-4">
{showCustomPrompt ? (
diff --git a/ui/src/pages/DesignGuide.tsx b/ui/src/pages/DesignGuide.tsx
index 78da658a08..1dba377a19 100644
--- a/ui/src/pages/DesignGuide.tsx
+++ b/ui/src/pages/DesignGuide.tsx
@@ -149,7 +149,9 @@ import {
pendingConnectionIntentInteraction,
retryConnectionIntentInteraction,
} from "@/fixtures/issueThreadInteractionFixtures";
-import type { CompanySecret, EnvBinding } from "@paperclipai/shared";
+import type { CompanySecret, EnvBinding, Issue } from "@paperclipai/shared";
+import { CollectionToolbar } from "@/components/CollectionToolbar";
+import { IssueRow } from "@/components/IssueRow";
import {
EnvInputsList,
ExternalSourcesList,
@@ -239,6 +241,15 @@ const DESIGN_GUIDE_DEGRADED_OUTPUTS: IssueWorkProduct[] = [
} as IssueWorkProduct,
];
+const DESIGN_GUIDE_TASK = {
+ id: "design-guide-task",
+ identifier: "PAP-427",
+ title: "Reconcile the navigation model across operator surfaces",
+ status: "in_progress",
+ priority: "medium",
+ blockerAttention: false,
+} as unknown as Issue;
+
/* ------------------------------------------------------------------ */
/* Section wrapper */
/* ------------------------------------------------------------------ */
@@ -494,7 +505,8 @@ export function DesignGuide() {
"StatusBadge", "StatusIcon", "PriorityIcon", "EntityRow", "EmptyState", "MetricCard",
"FilterBar", "InlineEditor", "PageSkeleton", "Identity", "CommentThread", "MarkdownEditor",
"PropertiesPanel", "Sidebar", "CommandPalette", "EnvironmentVariablesEditor",
- "InlineBanner", "BuiltInAgentGate", "BuiltInLifecycleChip",
+ "InlineBanner", "BuiltInAgentGate", "BuiltInLifecycleChip", "CollectionToolbar",
+ "IssueRow", "ContextualSidebarFrame",
].map((name) => (
<Badge key={name} variant="ghost" className="font-mono text-(length:--text-nano)">
{name}
@@ -505,6 +517,30 @@ export function DesignGuide() {
</div>
</Section>
+ <Section title="Task Collection">
+ <p className="max-w-prose text-sm text-muted-foreground">
+ CollectionToolbar owns shared geometry while each page owns its state and behavior.
+ The canonical task row is opt-in during migration: status leads, unread work uses
+ title emphasis, metadata remains stable, and the task identifier trails.
+ </p>
+ <CollectionToolbar
+ context={<span className="text-sm font-medium">Recent tasks</span>}
+ search={<Input aria-label="Search task collection example" placeholder="Search tasks..." />}
+ controls={<Button variant="outline" size="sm">Filter</Button>}
+ actions={<Button size="sm">New task</Button>}
+ feedback={<span className="text-xs text-muted-foreground">1 task · Updated newest first</span>}
+ />
+ <div className="overflow-hidden rounded-lg border border-border">
+ <IssueRow
+ issue={DESIGN_GUIDE_TASK}
+ presentation="task"
+ unreadState="visible"
+ metadata={<span className="text-xs text-muted-foreground">Updated 12m ago</span>}
+ actions={<Button variant="ghost" size="xs">More</Button>}
+ />
+ </div>
+ </Section>
+
{/* ============================================================ */}
{/* COLORS */}
{/* ============================================================ */}
diff --git a/ui/src/pages/OrgChart.production.tsx b/ui/src/pages/OrgChart.production.tsx
new file mode 100644
index 0000000000..d394489b43
--- /dev/null
+++ b/ui/src/pages/OrgChart.production.tsx
@@ -0,0 +1,641 @@
+import { useEffect, useRef, useState, useMemo, useCallback } from "react";
+import { Link, useNavigate } from "@/lib/router";
+import { useQuery } from "@tanstack/react-query";
+import { agentsApi, type OrgNode } from "../api/agents";
+import { useCompany } from "../context/CompanyContext";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { queryKeys } from "../lib/queryKeys";
+import { agentUrl } from "../lib/utils";
+import { Card } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { EmptyState } from "../components/EmptyState";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { AgentIcon } from "../components/AgentIconPicker";
+import { Download, Maximize2, Minus, Network, Plus, Upload } from "lucide-react";
+import { AGENT_ROLE_LABELS, type Agent } from "@paperclipai/shared";
+import { useCloudInstance } from "@/hooks/useCloudInstance";
+import { useHiddenSettings } from "@/hooks/useHiddenSettings";
+
+// Layout constants
+const CARD_W = 200;
+const CARD_H = 100;
+const GAP_X = 32;
+const GAP_Y = 80;
+const PADDING = 60;
+const MIN_ZOOM = 0.2;
+const MAX_ZOOM = 2;
+const TOUCH_MOVE_THRESHOLD = 6;
+
+// ── Tree layout types ───────────────────────────────────────────────────
+
+interface LayoutNode {
+ id: string;
+ name: string;
+ role: string;
+ status: string;
+ x: number;
+ y: number;
+ children: LayoutNode[];
+}
+
+interface Point {
+ x: number;
+ y: number;
+}
+
+interface TouchGesture {
+ mode: "pan" | "pinch" | null;
+ startPoint: Point;
+ startPan: Point;
+ startZoom: number;
+ startDistance: number;
+ startCenter: Point;
+ moved: boolean;
+}
+
+// ── Layout algorithm ────────────────────────────────────────────────────
+
+/** Compute the width each subtree needs. */
+function subtreeWidth(node: OrgNode): number {
+ if (node.reports.length === 0) return CARD_W;
+ const childrenW = node.reports.reduce((sum, c) => sum + subtreeWidth(c), 0);
+ const gaps = (node.reports.length - 1) * GAP_X;
+ return Math.max(CARD_W, childrenW + gaps);
+}
+
+/** Recursively assign x,y positions. */
+function layoutTree(node: OrgNode, x: number, y: number): LayoutNode {
+ const totalW = subtreeWidth(node);
+ const layoutChildren: LayoutNode[] = [];
+
+ if (node.reports.length > 0) {
+ const childrenW = node.reports.reduce((sum, c) => sum + subtreeWidth(c), 0);
+ const gaps = (node.reports.length - 1) * GAP_X;
+ let cx = x + (totalW - childrenW - gaps) / 2;
+
+ for (const child of node.reports) {
+ const cw = subtreeWidth(child);
+ layoutChildren.push(layoutTree(child, cx, y + CARD_H + GAP_Y));
+ cx += cw + GAP_X;
+ }
+ }
+
+ return {
+ id: node.id,
+ name: node.name,
+ role: node.role,
+ status: node.status,
+ x: x + (totalW - CARD_W) / 2,
+ y,
+ children: layoutChildren,
+ };
+}
+
+/** Layout all root nodes side by side. */
+function layoutForest(roots: OrgNode[]): LayoutNode[] {
+ if (roots.length === 0) return [];
+
+ const totalW = roots.reduce((sum, r) => sum + subtreeWidth(r), 0);
+ const gaps = (roots.length - 1) * GAP_X;
+ let x = PADDING;
+ const y = PADDING;
+
+ const result: LayoutNode[] = [];
+ for (const root of roots) {
+ const w = subtreeWidth(root);
+ result.push(layoutTree(root, x, y));
+ x += w + GAP_X;
+ }
+
+ // Compute bounds and return
+ return result;
+}
+
+/** Flatten layout tree to list of nodes. */
+function flattenLayout(nodes: LayoutNode[]): LayoutNode[] {
+ const result: LayoutNode[] = [];
+ function walk(n: LayoutNode) {
+ result.push(n);
+ n.children.forEach(walk);
+ }
+ nodes.forEach(walk);
+ return result;
+}
+
+/** Collect all parent→child edges. */
+function collectEdges(nodes: LayoutNode[]): Array<{ parent: LayoutNode; child: LayoutNode }> {
+ const edges: Array<{ parent: LayoutNode; child: LayoutNode }> = [];
+ function walk(n: LayoutNode) {
+ for (const c of n.children) {
+ edges.push({ parent: n, child: c });
+ walk(c);
+ }
+ }
+ nodes.forEach(walk);
+ return edges;
+}
+
+function clampZoom(value: number): number {
+ return Math.min(Math.max(value, MIN_ZOOM), MAX_ZOOM);
+}
+
+function touchPoint(touch: React.Touch): Point {
+ return { x: touch.clientX, y: touch.clientY };
+}
+
+function touchDistance(a: React.Touch, b: React.Touch): number {
+ const dx = a.clientX - b.clientX;
+ const dy = a.clientY - b.clientY;
+ return Math.hypot(dx, dy);
+}
+
+function touchCenter(a: React.Touch, b: React.Touch, container: HTMLDivElement): Point {
+ const rect = container.getBoundingClientRect();
+ return {
+ x: (a.clientX + b.clientX) / 2 - rect.left,
+ y: (a.clientY + b.clientY) / 2 - rect.top,
+ };
+}
+
+// ── Status dot colors (raw hex for SVG) ─────────────────────────────────
+
+import { getAdapterLabel } from "../adapters/adapter-display-registry";
+
+const statusDotColor: Record<string, string> = {
+ running: "var(--hex-22d3ee)",
+ active: "var(--hex-4ade80)",
+ paused: "var(--hex-facc15)",
+ idle: "var(--hex-facc15)",
+ error: "var(--hex-f87171)",
+ terminated: "var(--hex-a3a3a3)",
+};
+const defaultDotColor = "var(--hex-a3a3a3)";
+
+// ── Main component ──────────────────────────────────────────────────────
+
+export function OrgChart() {
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const navigate = useNavigate();
+ // Import is floored server-side on cloud-managed instances (403 cloud_managed), so the
+ // button is hidden rather than dead-ending. Export stays available. Both
+ // buttons also respect the operator-hidden settings registry.
+ const isCloud = Boolean(useCloudInstance());
+ const { hidden: hiddenSettings } = useHiddenSettings();
+ const showImport = !isCloud && !hiddenSettings.has("company.import");
+ const showExport = !hiddenSettings.has("company.export");
+
+ const { data: orgTree, isLoading } = useQuery({
+ queryKey: queryKeys.org(selectedCompanyId!),
+ queryFn: () => agentsApi.org(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+
+ const { data: agents } = useQuery({
+ queryKey: queryKeys.agents.list(selectedCompanyId!),
+ queryFn: () => agentsApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+
+ const agentMap = useMemo(() => {
+ const m = new Map<string, Agent>();
+ for (const a of agents ?? []) m.set(a.id, a);
+ return m;
+ }, [agents]);
+
+ useEffect(() => {
+ setBreadcrumbs([{ label: "Org Chart" }]);
+ }, [setBreadcrumbs]);
+
+ // Layout computation
+ const layout = useMemo(() => layoutForest(orgTree ?? []), [orgTree]);
+ const allNodes = useMemo(() => flattenLayout(layout), [layout]);
+ const edges = useMemo(() => collectEdges(layout), [layout]);
+
+ // Compute SVG bounds
+ const bounds = useMemo(() => {
+ if (allNodes.length === 0) return { width: 800, height: 600 };
+ let maxX = 0, maxY = 0;
+ for (const n of allNodes) {
+ maxX = Math.max(maxX, n.x + CARD_W);
+ maxY = Math.max(maxY, n.y + CARD_H);
+ }
+ return { width: maxX + PADDING, height: maxY + PADDING };
+ }, [allNodes]);
+
+ // Pan & zoom state
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [pan, setPan] = useState({ x: 0, y: 0 });
+ const [zoom, setZoom] = useState(1);
+ const [dragging, setDragging] = useState(false);
+ const dragStart = useRef({ x: 0, y: 0, panX: 0, panY: 0 });
+ const touchGesture = useRef<TouchGesture>({
+ mode: null,
+ startPoint: { x: 0, y: 0 },
+ startPan: { x: 0, y: 0 },
+ startZoom: 1,
+ startDistance: 0,
+ startCenter: { x: 0, y: 0 },
+ moved: false,
+ });
+ const suppressNextCardClick = useRef(false);
+ const suppressClickTimerRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (suppressClickTimerRef.current !== null) {
+ window.clearTimeout(suppressClickTimerRef.current);
+ }
+ };
+ }, []);
+
+ // Center the chart on first load
+ const hasInitialized = useRef(false);
+ useEffect(() => {
+ if (hasInitialized.current || allNodes.length === 0 || !containerRef.current) return;
+ hasInitialized.current = true;
+
+ const container = containerRef.current;
+ const containerW = container.clientWidth;
+ const containerH = container.clientHeight;
+
+ // Fit chart to container
+ const scaleX = (containerW - 40) / bounds.width;
+ const scaleY = (containerH - 40) / bounds.height;
+ const fitZoom = Math.min(scaleX, scaleY, 1);
+
+ const chartW = bounds.width * fitZoom;
+ const chartH = bounds.height * fitZoom;
+
+ setZoom(fitZoom);
+ setPan({
+ x: (containerW - chartW) / 2,
+ y: (containerH - chartH) / 2,
+ });
+ }, [allNodes, bounds]);
+
+ const handleMouseDown = useCallback((e: React.MouseEvent) => {
+ if (e.button !== 0) return;
+ // Don't drag if clicking a card
+ const target = e.target as HTMLElement;
+ if (target.closest("[data-org-card]")) return;
+ setDragging(true);
+ dragStart.current = { x: e.clientX, y: e.clientY, panX: pan.x, panY: pan.y };
+ }, [pan]);
+
+ const handleMouseMove = useCallback((e: React.MouseEvent) => {
+ if (!dragging) return;
+ const dx = e.clientX - dragStart.current.x;
+ const dy = e.clientY - dragStart.current.y;
+ setPan({ x: dragStart.current.panX + dx, y: dragStart.current.panY + dy });
+ }, [dragging]);
+
+ const handleMouseUp = useCallback(() => {
+ setDragging(false);
+ }, []);
+
+ const handleWheel = useCallback((e: React.WheelEvent) => {
+ e.preventDefault();
+ const container = containerRef.current;
+ if (!container) return;
+
+ const rect = container.getBoundingClientRect();
+ const mouseX = e.clientX - rect.left;
+ const mouseY = e.clientY - rect.top;
+
+ const factor = e.deltaY < 0 ? 1.1 : 0.9;
+ const newZoom = clampZoom(zoom * factor);
+
+ // Zoom toward mouse position
+ const scale = newZoom / zoom;
+ setPan({
+ x: mouseX - scale * (mouseX - pan.x),
+ y: mouseY - scale * (mouseY - pan.y),
+ });
+ setZoom(newZoom);
+ }, [zoom, pan]);
+
+ const zoomTowardPoint = useCallback((newZoom: number, point: Point) => {
+ const clampedZoom = clampZoom(newZoom);
+ const scale = clampedZoom / zoom;
+ setPan({
+ x: point.x - scale * (point.x - pan.x),
+ y: point.y - scale * (point.y - pan.y),
+ });
+ setZoom(clampedZoom);
+ }, [zoom, pan]);
+
+ const fitToScreen = useCallback(() => {
+ if (!containerRef.current) return;
+ const cW = containerRef.current.clientWidth;
+ const cH = containerRef.current.clientHeight;
+ const scaleX = (cW - 40) / bounds.width;
+ const scaleY = (cH - 40) / bounds.height;
+ const fitZoom = Math.min(scaleX, scaleY, 1);
+ const chartW = bounds.width * fitZoom;
+ const chartH = bounds.height * fitZoom;
+ setZoom(fitZoom);
+ setPan({ x: (cW - chartW) / 2, y: (cH - chartH) / 2 });
+ }, [bounds]);
+
+ const handleTouchStart = useCallback((e: React.TouchEvent<HTMLDivElement>) => {
+ if (e.touches.length >= 2 && containerRef.current) {
+ const [first, second] = [e.touches[0]!, e.touches[1]!];
+ touchGesture.current = {
+ mode: "pinch",
+ startPoint: { x: 0, y: 0 },
+ startPan: pan,
+ startZoom: zoom,
+ startDistance: touchDistance(first, second),
+ startCenter: touchCenter(first, second, containerRef.current),
+ moved: false,
+ };
+ return;
+ }
+
+ const touch = e.touches[0];
+ if (!touch) return;
+ touchGesture.current = {
+ mode: "pan",
+ startPoint: touchPoint(touch),
+ startPan: pan,
+ startZoom: zoom,
+ startDistance: 0,
+ startCenter: { x: 0, y: 0 },
+ moved: false,
+ };
+ }, [pan, zoom]);
+
+ const handleTouchMove = useCallback((e: React.TouchEvent<HTMLDivElement>) => {
+ const container = containerRef.current;
+ if (!container || !touchGesture.current.mode) return;
+
+ if (e.touches.length >= 2) {
+ const [first, second] = [e.touches[0]!, e.touches[1]!];
+ const distance = touchDistance(first, second);
+ const center = touchCenter(first, second, container);
+
+ if (touchGesture.current.mode !== "pinch" || touchGesture.current.startDistance === 0) {
+ touchGesture.current = {
+ mode: "pinch",
+ startPoint: { x: 0, y: 0 },
+ startPan: pan,
+ startZoom: zoom,
+ startDistance: distance,
+ startCenter: center,
+ moved: false,
+ };
+ return;
+ }
+
+ const gesture = touchGesture.current;
+ const nextZoom = clampZoom(gesture.startZoom * (distance / gesture.startDistance));
+ const scale = nextZoom / gesture.startZoom;
+ const dx = center.x - gesture.startCenter.x;
+ const dy = center.y - gesture.startCenter.y;
+ gesture.moved =
+ gesture.moved ||
+ Math.abs(distance - gesture.startDistance) > TOUCH_MOVE_THRESHOLD ||
+ Math.hypot(dx, dy) > TOUCH_MOVE_THRESHOLD;
+ setZoom(nextZoom);
+ setPan({
+ x: center.x - scale * (gesture.startCenter.x - gesture.startPan.x),
+ y: center.y - scale * (gesture.startCenter.y - gesture.startPan.y),
+ });
+ return;
+ }
+
+ const touch = e.touches[0];
+ if (!touch || touchGesture.current.mode !== "pan") return;
+ const dx = touch.clientX - touchGesture.current.startPoint.x;
+ const dy = touch.clientY - touchGesture.current.startPoint.y;
+ touchGesture.current.moved = touchGesture.current.moved || Math.hypot(dx, dy) > TOUCH_MOVE_THRESHOLD;
+ setPan({
+ x: touchGesture.current.startPan.x + dx,
+ y: touchGesture.current.startPan.y + dy,
+ });
+ }, [pan, zoom]);
+
+ const handleTouchEnd = useCallback(() => {
+ if (touchGesture.current.moved) {
+ suppressNextCardClick.current = true;
+ if (suppressClickTimerRef.current !== null) {
+ window.clearTimeout(suppressClickTimerRef.current);
+ }
+ suppressClickTimerRef.current = window.setTimeout(() => {
+ suppressNextCardClick.current = false;
+ suppressClickTimerRef.current = null;
+ }, 400);
+ }
+ touchGesture.current = {
+ mode: null,
+ startPoint: { x: 0, y: 0 },
+ startPan: pan,
+ startZoom: zoom,
+ startDistance: 0,
+ startCenter: { x: 0, y: 0 },
+ moved: false,
+ };
+ }, [pan, zoom]);
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={Network} message="Select a company to view the org chart." />;
+ }
+
+ if (isLoading) {
+ return <PageSkeleton variant="org-chart" />;
+ }
+
+ if (orgTree && orgTree.length === 0) {
+ return <EmptyState icon={Network} message="No organizational hierarchy defined." />;
+ }
+
+ return (
+ <div className="flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0">
+ <div className="mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2">
+ {showImport && (
+ <Link to="/company/import">
+ <Button variant="outline" size="sm">
+ <Upload className="mr-1.5 h-3.5 w-3.5" />
+ Import company
+ </Button>
+ </Link>
+ )}
+ {showExport && (
+ <Link to="/company/export">
+ <Button variant="outline" size="sm">
+ <Download className="mr-1.5 h-3.5 w-3.5" />
+ Export company
+ </Button>
+ </Link>
+ )}
+ </div>
+ <div
+ ref={containerRef}
+ data-testid="org-chart-viewport"
+ className="w-full flex-1 min-h-0 overflow-hidden relative bg-muted/20 border border-border rounded-lg"
+ style={{
+ cursor: dragging ? "grabbing" : "grab",
+ touchAction: "none",
+ overscrollBehavior: "contain",
+ }}
+ onMouseDown={handleMouseDown}
+ onMouseMove={handleMouseMove}
+ onMouseUp={handleMouseUp}
+ onMouseLeave={handleMouseUp}
+ onWheel={handleWheel}
+ onTouchStart={handleTouchStart}
+ onTouchMove={handleTouchMove}
+ onTouchEnd={handleTouchEnd}
+ onTouchCancel={handleTouchEnd}
+ >
+ {/* Zoom controls */}
+ <div className="absolute top-3 right-3 z-10 flex flex-col gap-1.5">
+ <button
+ className="flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7"
+ onClick={() => {
+ const container = containerRef.current;
+ if (container) {
+ zoomTowardPoint(zoom * 1.2, {
+ x: container.clientWidth / 2,
+ y: container.clientHeight / 2,
+ });
+ }
+ }}
+ title="Zoom in"
+ aria-label="Zoom in"
+ >
+ <Plus className="h-4 w-4 sm:h-3.5 sm:w-3.5" />
+ </button>
+ <button
+ className="flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7"
+ onClick={() => {
+ const container = containerRef.current;
+ if (container) {
+ zoomTowardPoint(zoom * 0.8, {
+ x: container.clientWidth / 2,
+ y: container.clientHeight / 2,
+ });
+ }
+ }}
+ title="Zoom out"
+ aria-label="Zoom out"
+ >
+ <Minus className="h-4 w-4 sm:h-3.5 sm:w-3.5" />
+ </button>
+ <button
+ className="flex size-9 items-center justify-center rounded border border-border bg-background text-(length:--text-nano) transition-colors hover:bg-accent sm:size-7"
+ onClick={fitToScreen}
+ title="Fit to screen"
+ aria-label="Fit chart to screen"
+ >
+ <Maximize2 className="h-4 w-4 sm:h-3.5 sm:w-3.5" />
+ </button>
+ </div>
+
+ {/* SVG layer for edges */}
+ <svg
+ className="absolute inset-0 pointer-events-none"
+ style={{
+ width: "100%",
+ height: "100%",
+ }}
+ >
+ <g transform={`translate(${pan.x}, ${pan.y}) scale(${zoom})`}>
+ {edges.map(({ parent, child }) => {
+ const x1 = parent.x + CARD_W / 2;
+ const y1 = parent.y + CARD_H;
+ const x2 = child.x + CARD_W / 2;
+ const y2 = child.y;
+ const midY = (y1 + y2) / 2;
+
+ return (
+ <path
+ key={`${parent.id}-${child.id}`}
+ d={`M ${x1} ${y1} L ${x1} ${midY} L ${x2} ${midY} L ${x2} ${y2}`}
+ fill="none"
+ stroke="var(--border)"
+ strokeWidth={1.5}
+ />
+ );
+ })}
+ </g>
+ </svg>
+
+ {/* Card layer */}
+ <div
+ data-testid="org-chart-card-layer"
+ className="absolute inset-0"
+ style={{
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
+ transformOrigin: "0 0",
+ }}
+ >
+ {allNodes.map((node) => {
+ const agent = agentMap.get(node.id);
+ const dotColor = statusDotColor[node.status] ?? defaultDotColor;
+
+ return (
+ <Card
+ key={node.id}
+ data-org-card
+ className="block absolute py-0 hover:shadow-md hover:border-foreground/20 transition-(--tp-box-shadow-border-color) duration-150 cursor-pointer select-none"
+ style={{
+ left: node.x,
+ top: node.y,
+ width: CARD_W,
+ minHeight: CARD_H,
+ }}
+ onClick={() => navigate(agent ? agentUrl(agent) : `/agents/${node.id}`)}
+ onClickCapture={(e) => {
+ if (!suppressNextCardClick.current) return;
+ suppressNextCardClick.current = false;
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <div className="flex items-center px-4 py-3 gap-3">
+ {/* Agent icon + status dot */}
+ <div className="relative shrink-0">
+ <div className="w-9 h-9 rounded-full bg-muted flex items-center justify-center">
+ <AgentIcon icon={agent?.icon} className="h-4.5 w-4.5 text-foreground/70" />
+ </div>
+ <span
+ className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-card"
+ style={{ backgroundColor: dotColor }}
+ />
+ </div>
+ {/* Name + role + adapter type */}
+ <div className="flex flex-col items-start min-w-0 flex-1">
+ <span className="text-sm font-semibold text-foreground leading-tight">
+ {node.name}
+ </span>
+ <span className="text-(length:--text-micro) text-muted-foreground leading-tight mt-0.5">
+ {agent?.title ?? roleLabel(node.role)}
+ </span>
+ {agent && (
+ <span className="text-(length:--text-nano) text-muted-foreground/60 font-mono leading-tight mt-1">
+ {getAdapterLabel(agent.adapterType)}
+ </span>
+ )}
+ {agent && agent.capabilities && (
+ <span className="text-(length:--text-nano) text-muted-foreground/80 leading-tight mt-1 line-clamp-2">
+ {agent.capabilities}
+ </span>
+ )}
+ </div>
+ </div>
+ </Card>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const roleLabels: Record<string, string> = AGENT_ROLE_LABELS;
+
+function roleLabel(role: string): string {
+ return roleLabels[role] ?? role;
+}
diff --git a/ui/src/pages/OrgChart.test.tsx b/ui/src/pages/OrgChart.test.tsx
index 36e8238c54..0bc5310df0 100644
--- a/ui/src/pages/OrgChart.test.tsx
+++ b/ui/src/pages/OrgChart.test.tsx
@@ -129,6 +129,8 @@ describe("OrgChart mobile gestures", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
let queryClient: QueryClient;
+ let viewportWidth: number;
+ let viewportHeight: number;
beforeEach(() => {
container = document.createElement("div");
@@ -136,19 +138,21 @@ describe("OrgChart mobile gestures", () => {
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
+ viewportWidth = 360;
+ viewportHeight = 520;
orgMock.mockResolvedValue(orgTree);
listMock.mockResolvedValue(agents);
Object.defineProperty(HTMLElement.prototype, "clientWidth", {
configurable: true,
get() {
- return this.getAttribute("data-testid") === "org-chart-viewport" ? 360 : 0;
+ return this.getAttribute("data-testid") === "org-chart-viewport" ? viewportWidth : 0;
},
});
Object.defineProperty(HTMLElement.prototype, "clientHeight", {
configurable: true,
get() {
- return this.getAttribute("data-testid") === "org-chart-viewport" ? 520 : 0;
+ return this.getAttribute("data-testid") === "org-chart-viewport" ? viewportHeight : 0;
},
});
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function getRect(this: HTMLElement) {
@@ -158,10 +162,10 @@ describe("OrgChart mobile gestures", () => {
y: 0,
left: 0,
top: 0,
- right: 360,
- bottom: 520,
- width: 360,
- height: 520,
+ right: viewportWidth,
+ bottom: viewportHeight,
+ width: viewportWidth,
+ height: viewportHeight,
toJSON: () => ({}),
};
}
@@ -264,6 +268,19 @@ describe("OrgChart mobile gestures", () => {
expect(layer.style.transform).toBe("translate(-45px, 40px) scale(1.5)");
});
+ it("does not produce a negative zoom while the viewport has no usable height", async () => {
+ viewportHeight = 2;
+ const { layer } = await renderOrgChart();
+
+ expect(layer.style.transform).toBe("translate(0px, 0px) scale(1)");
+
+ await act(async () => {
+ (container.querySelector('[aria-label="Fit chart to screen"]') as HTMLButtonElement).click();
+ });
+
+ expect(layer.style.transform).toBe("translate(0px, 0px) scale(1)");
+ });
+
it("shows both portability buttons on self-hosted instances", async () => {
await renderOrgChart();
diff --git a/ui/src/pages/OrgChart.tsx b/ui/src/pages/OrgChart.tsx
index b5c8b47546..1eb8e35ce6 100644
--- a/ui/src/pages/OrgChart.tsx
+++ b/ui/src/pages/OrgChart.tsx
@@ -24,6 +24,7 @@ const GAP_Y = 80;
const PADDING = 60;
const MIN_ZOOM = 0.2;
const MAX_ZOOM = 2;
+const FIT_PADDING = 40;
const TOUCH_MOVE_THRESHOLD = 6;
// ── Tree layout types ───────────────────────────────────────────────────
@@ -139,6 +140,28 @@ function clampZoom(value: number): number {
return Math.min(Math.max(value, MIN_ZOOM), MAX_ZOOM);
}
+function fitChartToViewport(
+ containerWidth: number,
+ containerHeight: number,
+ bounds: { width: number; height: number },
+): { zoom: number; pan: Point } | null {
+ if (containerWidth <= FIT_PADDING || containerHeight <= FIT_PADDING) return null;
+
+ const scaleX = (containerWidth - FIT_PADDING) / bounds.width;
+ const scaleY = (containerHeight - FIT_PADDING) / bounds.height;
+ const zoom = clampZoom(Math.min(scaleX, scaleY, 1));
+ const chartWidth = bounds.width * zoom;
+ const chartHeight = bounds.height * zoom;
+
+ return {
+ zoom,
+ pan: {
+ x: (containerWidth - chartWidth) / 2,
+ y: (containerHeight - chartHeight) / 2,
+ },
+ };
+}
+
function touchPoint(touch: React.Touch): Point {
return { x: touch.clientX, y: touch.clientY };
}
@@ -173,7 +196,16 @@ const defaultDotColor = "var(--hex-a3a3a3)";
// ── Main component ──────────────────────────────────────────────────────
-export function OrgChart() {
+export interface OrgChartProps {
+ /** Pre-filtered tree for embedding the chart in another collection page. */
+ orgTree?: OrgNode[];
+ /** Agent records paired with a pre-filtered embedded tree. */
+ agents?: Agent[];
+ /** Hides page-level actions and breadcrumb ownership. */
+ embedded?: boolean;
+}
+
+export function OrgChart({ orgTree: providedOrgTree, agents: providedAgents, embedded = false }: OrgChartProps = {}) {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const navigate = useNavigate();
@@ -185,17 +217,19 @@ export function OrgChart() {
const showImport = !isCloud && !hiddenSettings.has("company.import");
const showExport = !hiddenSettings.has("company.export");
- const { data: orgTree, isLoading } = useQuery({
+ const { data: queriedOrgTree, isLoading } = useQuery({
queryKey: queryKeys.org(selectedCompanyId!),
queryFn: () => agentsApi.org(selectedCompanyId!),
- enabled: !!selectedCompanyId,
+ enabled: !!selectedCompanyId && providedOrgTree === undefined,
});
- const { data: agents } = useQuery({
+ const { data: queriedAgents } = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
queryFn: () => agentsApi.list(selectedCompanyId!),
- enabled: !!selectedCompanyId,
+ enabled: !!selectedCompanyId && providedAgents === undefined,
});
+ const orgTree = providedOrgTree ?? queriedOrgTree;
+ const agents = providedAgents ?? queriedAgents;
const agentMap = useMemo(() => {
const m = new Map<string, Agent>();
@@ -204,8 +238,8 @@ export function OrgChart() {
}, [agents]);
useEffect(() => {
- setBreadcrumbs([{ label: "Org Chart" }]);
- }, [setBreadcrumbs]);
+ if (!embedded) setBreadcrumbs([{ label: "Org Chart" }]);
+ }, [embedded, setBreadcrumbs]);
// Layout computation
const layout = useMemo(() => layoutForest(orgTree ?? []), [orgTree]);
@@ -252,26 +286,18 @@ export function OrgChart() {
// Center the chart on first load
const hasInitialized = useRef(false);
useEffect(() => {
- if (hasInitialized.current || allNodes.length === 0 || !containerRef.current) return;
- hasInitialized.current = true;
+ hasInitialized.current = false;
+ }, [orgTree]);
+ useEffect(() => {
+ if (hasInitialized.current || allNodes.length === 0 || !containerRef.current) return;
const container = containerRef.current;
- const containerW = container.clientWidth;
- const containerH = container.clientHeight;
-
- // Fit chart to container
- const scaleX = (containerW - 40) / bounds.width;
- const scaleY = (containerH - 40) / bounds.height;
- const fitZoom = Math.min(scaleX, scaleY, 1);
+ const fitted = fitChartToViewport(container.clientWidth, container.clientHeight, bounds);
+ if (!fitted) return;
- const chartW = bounds.width * fitZoom;
- const chartH = bounds.height * fitZoom;
-
- setZoom(fitZoom);
- setPan({
- x: (containerW - chartW) / 2,
- y: (containerH - chartH) / 2,
- });
+ hasInitialized.current = true;
+ setZoom(fitted.zoom);
+ setPan(fitted.pan);
}, [allNodes, bounds]);
const handleMouseDown = useCallback((e: React.MouseEvent) => {
@@ -327,15 +353,15 @@ export function OrgChart() {
const fitToScreen = useCallback(() => {
if (!containerRef.current) return;
- const cW = containerRef.current.clientWidth;
- const cH = containerRef.current.clientHeight;
- const scaleX = (cW - 40) / bounds.width;
- const scaleY = (cH - 40) / bounds.height;
- const fitZoom = Math.min(scaleX, scaleY, 1);
- const chartW = bounds.width * fitZoom;
- const chartH = bounds.height * fitZoom;
- setZoom(fitZoom);
- setPan({ x: (cW - chartW) / 2, y: (cH - chartH) / 2 });
+ const fitted = fitChartToViewport(
+ containerRef.current.clientWidth,
+ containerRef.current.clientHeight,
+ bounds,
+ );
+ if (!fitted) return;
+
+ setZoom(fitted.zoom);
+ setPan(fitted.pan);
}, [bounds]);
const handleTouchStart = useCallback((e: React.TouchEvent<HTMLDivElement>) => {
@@ -442,7 +468,7 @@ export function OrgChart() {
return <EmptyState icon={Network} message="Select an organization to view the org chart." />;
}
- if (isLoading) {
+ if (providedOrgTree === undefined && isLoading) {
return <PageSkeleton variant="org-chart" />;
}
@@ -451,25 +477,31 @@ export function OrgChart() {
}
return (
- <div className="flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0">
- <div className="mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2">
- {showImport && (
+ <div
+ className={embedded
+ ? "flex min-h-(--sz-420px) flex-1 flex-col md:min-h-0"
+ : "flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0"}
+ >
+ {!embedded && (showImport || showExport) ? (
+ <div className="mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2">
+ {showImport ? (
<Link to="/company/import">
<Button variant="outline" size="sm">
<Upload className="mr-1.5 h-3.5 w-3.5" />
Import organization
</Button>
</Link>
- )}
- {showExport && (
+ ) : null}
+ {showExport ? (
<Link to="/company/export">
<Button variant="outline" size="sm">
<Download className="mr-1.5 h-3.5 w-3.5" />
Export organization
</Button>
</Link>
- )}
- </div>
+ ) : null}
+ </div>
+ ) : null}
<div
ref={containerRef}
data-testid="org-chart-viewport"
diff --git a/ui/src/pages/ProjectDetail.test.tsx b/ui/src/pages/ProjectDetail.test.tsx
index 22cca9127a..d4c23b1dbc 100644
--- a/ui/src/pages/ProjectDetail.test.tsx
+++ b/ui/src/pages/ProjectDetail.test.tsx
@@ -246,6 +246,28 @@ describe("ProjectDetail", () => {
});
});
+ it("keeps Timeline out of the project task-list controls", async () => {
+ mockLocation.pathname = "/projects/project-1/issues";
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+ await act(async () => {
+ root = createRoot(container);
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <ProjectDetail />
+ </QueryClientProvider>,
+ );
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+ const props = mockIssuesList.mock.calls.at(-1)?.[0];
+ expect(props).toEqual(expect.objectContaining({ projectId: "project-1" }));
+ expect(props).not.toHaveProperty("projectTimelineHref");
+ });
+
describe("plugin detail-tab deep links", () => {
const PLUGIN_TAB = "plugin:paperclipai.plugin-llm-wiki:project-knowledge";
const knowledgeSlot = {
diff --git a/ui/src/pages/RoutineDetail.production.tsx b/ui/src/pages/RoutineDetail.production.tsx
new file mode 100644
index 0000000000..95c53ab8cd
--- /dev/null
+++ b/ui/src/pages/RoutineDetail.production.tsx
@@ -0,0 +1,926 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Navigate, useNavigate, useParams } from "@/lib/router";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { AlertCircle, Repeat, Sparkles } from "lucide-react";
+import { ApiError } from "../api/client";
+import {
+ routinesApi,
+ type RoutineTriggerResponse,
+ type RotateRoutineTriggerResponse,
+ type RestoreRoutineRevisionResponse,
+} from "../api/routines";
+import { secretsApi } from "../api/secrets";
+import { type RoutineHistoryDirtyFieldDescriptor } from "../components/RoutineHistoryTab";
+import { heartbeatsApi } from "../api/heartbeats";
+import { agentsApi } from "../api/agents";
+import { projectsApi } from "../api/projects";
+import { accessApi } from "../api/access";
+import { useCompany } from "../context/CompanyContext";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useToastActions } from "../context/ToastContext";
+import { queryKeys } from "../lib/queryKeys";
+import { copyTextToClipboard } from "../lib/clipboard";
+import { buildMarkdownMentionOptions } from "../lib/company-members";
+import { ToggleSwitch } from "@/components/ui/toggle-switch";
+import { EmptyState } from "../components/EmptyState";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { type InlineEntityOption } from "../components/InlineEntitySelector";
+import { type MarkdownEditorRef, type MentionOption } from "../components/MarkdownEditor";
+import {
+ RoutineRunVariablesDialog,
+ type RoutineRunDialogSubmitData,
+} from "../components/RoutineRunVariablesDialog";
+import { RunButton } from "../components/AgentActionButtons";
+import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
+import { getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";
+import { Badge } from "@/components/ui/badge";
+import {
+ RoutineSubSidebar,
+ RoutineSectionPicker,
+} from "../components/RoutineSubSidebar";
+import { RoutineSaveBar } from "../components/RoutineSaveBar";
+import {
+ EDITABLE_SECTIONS,
+ ROUTINE_SECTION_KEYS,
+ SECTION_FIELD_KEYS,
+ RoutineDetailContext,
+ createDefaultNewTrigger,
+ type RoutineDetailContextValue,
+ type RoutineEditDraft,
+ type RoutineSectionKey,
+ type SecretMessage,
+} from "../components/routine-sections/context";
+import {
+ OverviewSection,
+ TriggersSection,
+ VariablesSection,
+ SecretsSection,
+ DeliverySection,
+} from "../components/routine-sections/editable-sections.production";
+import {
+ RunsSection,
+ ActivitySection,
+ HistorySection,
+} from "../components/routine-sections/operate-sections";
+import type {
+ RoutineDetail as RoutineDetailType,
+ RoutineEnvConfig,
+ RoutineVariable,
+} from "@paperclipai/shared";
+
+const LAST_SECTION_STORAGE_KEY = "paperclip.routineLastSection";
+
+export function buildRoutineProjectOptions(
+ projects: ReadonlyArray<{ id: string; name: string; description?: string | null; archivedAt?: Date | string | null }>,
+): InlineEntityOption[] {
+ return projects
+ .filter((project) => !project.archivedAt)
+ .map((project) => ({
+ id: project.id,
+ label: project.name,
+ searchText: project.description ?? "",
+ }));
+}
+
+const SECTION_TITLES: Record<RoutineSectionKey, string> = {
+ overview: "Overview",
+ triggers: "Triggers",
+ variables: "Variables",
+ secrets: "Secrets",
+ delivery: "Delivery",
+ runs: "Runs",
+ activity: "Activity",
+ history: "History",
+};
+
+function isRoutineSection(value: string | undefined | null): value is RoutineSectionKey {
+ return value != null && ROUTINE_SECTION_KEYS.includes(value as RoutineSectionKey);
+}
+
+function readLastSection(routineId: string): RoutineSectionKey | null {
+ try {
+ const raw = localStorage.getItem(LAST_SECTION_STORAGE_KEY);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw) as Record<string, string>;
+ const stored = parsed[routineId];
+ return isRoutineSection(stored) ? stored : null;
+ } catch {
+ return null;
+ }
+}
+
+function writeLastSection(routineId: string, section: RoutineSectionKey) {
+ try {
+ const raw = localStorage.getItem(LAST_SECTION_STORAGE_KEY);
+ const parsed = raw ? (JSON.parse(raw) as Record<string, string>) : {};
+ parsed[routineId] = section;
+ localStorage.setItem(LAST_SECTION_STORAGE_KEY, JSON.stringify(parsed));
+ } catch {
+ /* ignore storage failures */
+ }
+}
+
+/** Back-compat: `?tab=x` query param maps to the new section sub-routes. */
+const LEGACY_TAB_TO_SECTION: Record<string, RoutineSectionKey> = {
+ triggers: "triggers",
+ runs: "runs",
+ activity: "activity",
+ secrets: "secrets",
+ history: "history",
+};
+
+function autoResizeTextarea(element: HTMLTextAreaElement | null) {
+ if (!element) return;
+ element.style.height = "auto";
+ element.style.height = `${element.scrollHeight}px`;
+}
+
+function getLocalTimezone(): string {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
+ } catch {
+ return "UTC";
+ }
+}
+
+function buildRoutineMutationPayload(input: RoutineEditDraft) {
+ return {
+ ...input,
+ description: input.description.trim() || null,
+ projectId: input.projectId || null,
+ assigneeAgentId: input.assigneeAgentId || null,
+ env: input.env && Object.keys(input.env).length > 0 ? input.env : null,
+ };
+}
+
+export function RoutineDetail() {
+ const { routineId, section: sectionParam } = useParams<{ routineId: string; section?: string }>();
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const { pushToast } = useToastActions();
+ const hydratedRoutineIdRef = useRef<string | null>(null);
+ const titleInputRef = useRef<HTMLTextAreaElement | null>(null);
+ const descriptionEditorRef = useRef<MarkdownEditorRef>(null);
+ const assigneeSelectorRef = useRef<HTMLButtonElement | null>(null);
+ const projectSelectorRef = useRef<HTMLButtonElement | null>(null);
+ const [secretMessage, setSecretMessage] = useState<SecretMessage | null>(null);
+ const [saveConflict, setSaveConflict] = useState(false);
+ const [runVariablesOpen, setRunVariablesOpen] = useState(false);
+ const [newTrigger, setNewTrigger] = useState(createDefaultNewTrigger);
+ const [editDraft, setEditDraft] = useState<RoutineEditDraft>({
+ title: "",
+ description: "",
+ projectId: "",
+ assigneeAgentId: "",
+ priority: "medium",
+ concurrencyPolicy: "coalesce_if_active",
+ catchUpPolicy: "skip_missed",
+ activityGatePolicy: "always",
+ activityGateScope: "company",
+ variables: [],
+ env: null,
+ });
+
+ const section: RoutineSectionKey = isRoutineSection(sectionParam) ? sectionParam : "overview";
+
+ const navigateToSection = useCallback(
+ (next: RoutineSectionKey, options?: { replace?: boolean }) => {
+ if (!routineId) return;
+ writeLastSection(routineId, next);
+ navigate(`/routines/${routineId}/${next}`, { replace: options?.replace ?? true });
+ },
+ [navigate, routineId],
+ );
+
+ const { data: routine, isLoading, error } = useQuery({
+ queryKey: queryKeys.routines.detail(routineId!),
+ queryFn: () => routinesApi.get(routineId!),
+ enabled: !!routineId,
+ });
+ const activeIssueId = routine?.activeIssue?.id;
+ const { data: liveRuns } = useQuery({
+ queryKey: queryKeys.issues.liveRuns(activeIssueId!),
+ queryFn: () => heartbeatsApi.liveRunsForIssue(activeIssueId!),
+ enabled: !!activeIssueId,
+ refetchInterval: 3000,
+ });
+ const hasLiveRun = (liveRuns ?? []).length > 0;
+ const { data: routineRuns } = useQuery({
+ queryKey: queryKeys.routines.runs(routineId!),
+ queryFn: () => routinesApi.listRuns(routineId!),
+ enabled: !!routineId,
+ refetchInterval: hasLiveRun ? 3000 : false,
+ });
+ const relatedActivityIds = useMemo(
+ () => ({
+ triggerIds: routine?.triggers.map((trigger) => trigger.id) ?? [],
+ runIds: routineRuns?.map((run) => run.id) ?? [],
+ }),
+ [routine?.triggers, routineRuns],
+ );
+ const { data: activity } = useQuery({
+ queryKey: [
+ ...queryKeys.routines.activity(selectedCompanyId!, routineId!),
+ relatedActivityIds.triggerIds.join(","),
+ relatedActivityIds.runIds.join(","),
+ ],
+ queryFn: () => routinesApi.activity(selectedCompanyId!, routineId!, relatedActivityIds),
+ enabled: !!selectedCompanyId && !!routineId && !!routine,
+ });
+ const { data: agents } = useQuery({
+ queryKey: queryKeys.agents.list(selectedCompanyId!),
+ queryFn: () => agentsApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: projects } = useQuery({
+ queryKey: queryKeys.projects.list(selectedCompanyId!, { includeArchived: true }),
+ queryFn: () => projectsApi.list(selectedCompanyId!, { includeArchived: true }),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: availableSecrets = [] } = useQuery({
+ queryKey: selectedCompanyId ? queryKeys.secrets.list(selectedCompanyId) : ["secrets", "none"],
+ queryFn: () => secretsApi.list(selectedCompanyId!),
+ enabled: Boolean(selectedCompanyId),
+ });
+ const createSecret = useMutation({
+ mutationFn: (input: { name: string; value: string }) => {
+ if (!selectedCompanyId) throw new Error("Select a company to create secrets");
+ return secretsApi.create(selectedCompanyId, input);
+ },
+ onSuccess: () => {
+ if (!selectedCompanyId) return;
+ queryClient.invalidateQueries({ queryKey: queryKeys.secrets.list(selectedCompanyId) });
+ },
+ });
+
+ const routineDefaults = useMemo<RoutineEditDraft | null>(
+ () =>
+ routine
+ ? {
+ title: routine.title,
+ description: routine.description ?? "",
+ projectId: routine.projectId ?? "",
+ assigneeAgentId: routine.assigneeAgentId ?? "",
+ priority: routine.priority,
+ concurrencyPolicy: routine.concurrencyPolicy,
+ catchUpPolicy: routine.catchUpPolicy,
+ activityGatePolicy: routine.activityGatePolicy,
+ activityGateScope: routine.activityGateScope,
+ variables: routine.variables,
+ env: routine.env ?? null,
+ }
+ : null,
+ [routine],
+ );
+ const dirtyFields = useMemo<RoutineHistoryDirtyFieldDescriptor[]>(() => {
+ if (!routineDefaults) return [];
+ const result: RoutineHistoryDirtyFieldDescriptor[] = [];
+ if (editDraft.title !== routineDefaults.title) result.push({ key: "title", label: "the title" });
+ if (editDraft.description !== routineDefaults.description) {
+ result.push({ key: "description", label: "the description" });
+ }
+ if (editDraft.projectId !== routineDefaults.projectId) {
+ result.push({ key: "projectId", label: "the project" });
+ }
+ if (editDraft.assigneeAgentId !== routineDefaults.assigneeAgentId) {
+ result.push({ key: "assigneeAgentId", label: "the default agent" });
+ }
+ if (editDraft.priority !== routineDefaults.priority) {
+ result.push({ key: "priority", label: "the priority" });
+ }
+ if (editDraft.concurrencyPolicy !== routineDefaults.concurrencyPolicy) {
+ result.push({ key: "concurrencyPolicy", label: "the concurrency policy" });
+ }
+ if (editDraft.catchUpPolicy !== routineDefaults.catchUpPolicy) {
+ result.push({ key: "catchUpPolicy", label: "the catch-up policy" });
+ }
+ if (editDraft.activityGatePolicy !== routineDefaults.activityGatePolicy) {
+ result.push({ key: "activityGatePolicy", label: "the advanced run policy" });
+ }
+ if (editDraft.activityGateScope !== routineDefaults.activityGateScope) {
+ result.push({ key: "activityGateScope", label: "the activity gate scope" });
+ }
+ if (JSON.stringify(editDraft.variables) !== JSON.stringify(routineDefaults.variables)) {
+ result.push({ key: "variables", label: "the variables" });
+ }
+ if (JSON.stringify(editDraft.env ?? null) !== JSON.stringify(routineDefaults.env ?? null)) {
+ result.push({ key: "env", label: "the secrets" });
+ }
+ return result;
+ }, [editDraft, routineDefaults]);
+ const isEditDirty = dirtyFields.length > 0;
+
+ const sectionDirtyFields = useCallback(
+ (target: RoutineSectionKey) => {
+ const keys = SECTION_FIELD_KEYS[target];
+ if (!keys) return [];
+ return dirtyFields.filter((field) => keys.includes(field.key));
+ },
+ [dirtyFields],
+ );
+ const isSectionDirty = useCallback(
+ (target: RoutineSectionKey) => sectionDirtyFields(target).length > 0,
+ [sectionDirtyFields],
+ );
+ const discardSection = useCallback(
+ (target: RoutineSectionKey) => {
+ if (!routineDefaults) return;
+ const keys = SECTION_FIELD_KEYS[target];
+ if (!keys) return;
+ setEditDraft((current) => {
+ const next = { ...current } as Record<string, unknown>;
+ for (const key of keys) {
+ next[key] = (routineDefaults as Record<string, unknown>)[key];
+ }
+ return next as RoutineEditDraft;
+ });
+ },
+ [routineDefaults],
+ );
+
+ useEffect(() => {
+ if (!routine) return;
+ setBreadcrumbs([{ label: "Routines", href: "/routines" }, { label: routine.title }]);
+ if (!routineDefaults) return;
+ const changedRoutine = hydratedRoutineIdRef.current !== routine.id;
+ if (changedRoutine || !isEditDirty) {
+ setEditDraft(routineDefaults);
+ hydratedRoutineIdRef.current = routine.id;
+ }
+ }, [routine, routineDefaults, isEditDirty, setBreadcrumbs]);
+
+ useEffect(() => {
+ autoResizeTextarea(titleInputRef.current);
+ }, [editDraft.title, routine?.id]);
+
+ // Persist the section the user lands on so a bare /routines/:id remembers it.
+ useEffect(() => {
+ if (routineId && isRoutineSection(sectionParam)) {
+ writeLastSection(routineId, sectionParam);
+ }
+ }, [routineId, sectionParam]);
+
+ const copySecretValue = useCallback(
+ async (label: string, value: string) => {
+ try {
+ await copyTextToClipboard(value);
+ pushToast({ title: `${label} copied`, tone: "success" });
+ } catch (copyError) {
+ pushToast({
+ title: `Failed to copy ${label.toLowerCase()}`,
+ body: copyError instanceof Error ? copyError.message : "Clipboard access was denied.",
+ tone: "error",
+ });
+ }
+ },
+ [pushToast],
+ );
+
+ const saveRoutine = useMutation({
+ mutationFn: () => {
+ const payload = buildRoutineMutationPayload(editDraft);
+ const baseRevisionId = routine?.latestRevisionId ?? null;
+ return routinesApi.update(routineId!, {
+ ...payload,
+ ...(baseRevisionId ? { baseRevisionId } : {}),
+ });
+ },
+ onSuccess: async () => {
+ setSaveConflict(false);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(selectedCompanyId!, routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.revisions(routineId!) }),
+ ]);
+ },
+ onError: (mutationError) => {
+ if (mutationError instanceof ApiError && mutationError.status === 409) {
+ setSaveConflict(true);
+ pushToast({
+ title: "Routine changed",
+ body: "Someone else updated this routine. Reload to see the latest revision.",
+ tone: "warn",
+ });
+ return;
+ }
+ pushToast({
+ title: "Failed to save routine",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not save the routine.",
+ tone: "error",
+ });
+ },
+ });
+
+ const runRoutine = useMutation({
+ mutationFn: (data?: RoutineRunDialogSubmitData) =>
+ routinesApi.run(routineId!, {
+ ...(data?.variables && Object.keys(data.variables).length > 0 ? { variables: data.variables } : {}),
+ ...(data?.assigneeAgentId !== undefined ? { assigneeAgentId: data.assigneeAgentId } : {}),
+ ...(data?.projectId !== undefined ? { projectId: data.projectId } : {}),
+ ...(data?.executionWorkspaceId !== undefined ? { executionWorkspaceId: data.executionWorkspaceId } : {}),
+ ...(data?.executionWorkspacePreference !== undefined
+ ? { executionWorkspacePreference: data.executionWorkspacePreference }
+ : {}),
+ ...(data?.executionWorkspaceSettings !== undefined
+ ? { executionWorkspaceSettings: data.executionWorkspaceSettings }
+ : {}),
+ }),
+ onSuccess: async () => {
+ pushToast({ title: "Routine run started", tone: "success" });
+ setRunVariablesOpen(false);
+ navigateToSection("runs");
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.runs(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(selectedCompanyId!, routineId!) }),
+ ]);
+ },
+ onError: (runError) => {
+ pushToast({
+ title: "Routine run failed",
+ body: runError instanceof Error ? runError.message : "Paperclip could not start the routine run.",
+ tone: "error",
+ });
+ },
+ });
+
+ const updateRoutineStatus = useMutation({
+ mutationFn: (status: string) => routinesApi.update(routineId!, { status }),
+ onSuccess: async (_data, status) => {
+ pushToast({
+ title: "Routine saved",
+ body: status === "paused" ? "Automation paused." : "Automation enabled.",
+ tone: "success",
+ });
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ ]);
+ },
+ onError: (statusError) => {
+ pushToast({
+ title: "Failed to update routine",
+ body: statusError instanceof Error ? statusError.message : "Paperclip could not update the routine.",
+ tone: "error",
+ });
+ },
+ });
+
+ const createTrigger = useMutation({
+ mutationFn: async (): Promise<RoutineTriggerResponse> => {
+ const existingOfKind = (routine?.triggers ?? []).filter((t) => t.kind === newTrigger.kind).length;
+ const autoLabel = existingOfKind > 0 ? `${newTrigger.kind}-${existingOfKind + 1}` : newTrigger.kind;
+ return routinesApi.createTrigger(routineId!, {
+ kind: newTrigger.kind,
+ label: autoLabel,
+ ...(newTrigger.kind === "schedule"
+ ? { cronExpression: newTrigger.cronExpression.trim(), timezone: getLocalTimezone() }
+ : {}),
+ ...(newTrigger.kind === "webhook"
+ ? { signingMode: newTrigger.signingMode, replayWindowSec: Number(newTrigger.replayWindowSec || "300") }
+ : {}),
+ });
+ },
+ onSuccess: async (result) => {
+ if (result.secretMaterial) {
+ setSecretMessage({
+ title: "Webhook trigger created",
+ entries: [{ webhookUrl: result.secretMaterial.webhookUrl, webhookSecret: result.secretMaterial.webhookSecret }],
+ });
+ } else {
+ pushToast({ title: "Trigger added", body: "The routine schedule was saved.", tone: "success" });
+ }
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(selectedCompanyId!, routineId!) }),
+ ]);
+ },
+ onError: (triggerError) => {
+ pushToast({
+ title: "Failed to add trigger",
+ body: triggerError instanceof Error ? triggerError.message : "Paperclip could not create the trigger.",
+ tone: "error",
+ });
+ },
+ });
+
+ const updateTrigger = useMutation({
+ mutationFn: ({ id, patch }: { id: string; patch: Record<string, unknown> }) => routinesApi.updateTrigger(id, patch),
+ onSuccess: async () => {
+ pushToast({ title: "Trigger saved", body: "The routine cadence update was saved.", tone: "success" });
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(selectedCompanyId!, routineId!) }),
+ ]);
+ },
+ onError: (triggerError) => {
+ pushToast({
+ title: "Failed to update trigger",
+ body: triggerError instanceof Error ? triggerError.message : "Paperclip could not update the trigger.",
+ tone: "error",
+ });
+ },
+ });
+
+ const deleteTrigger = useMutation({
+ mutationFn: (id: string) => routinesApi.deleteTrigger(id),
+ onSuccess: async () => {
+ pushToast({ title: "Trigger deleted", tone: "success" });
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(selectedCompanyId!, routineId!) }),
+ ]);
+ },
+ onError: (triggerError) => {
+ pushToast({
+ title: "Failed to delete trigger",
+ body: triggerError instanceof Error ? triggerError.message : "Paperclip could not delete the trigger.",
+ tone: "error",
+ });
+ },
+ });
+
+ const rotateTrigger = useMutation({
+ mutationFn: (id: string): Promise<RotateRoutineTriggerResponse> => routinesApi.rotateTriggerSecret(id),
+ onSuccess: async (result) => {
+ setSecretMessage({
+ title: "Webhook secret rotated",
+ entries: [{ webhookUrl: result.secretMaterial.webhookUrl, webhookSecret: result.secretMaterial.webhookSecret }],
+ });
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.activity(selectedCompanyId!, routineId!) }),
+ ]);
+ },
+ onError: (triggerError) => {
+ pushToast({
+ title: "Failed to rotate webhook secret",
+ body: triggerError instanceof Error ? triggerError.message : "Paperclip could not rotate the webhook secret.",
+ tone: "error",
+ });
+ },
+ });
+
+ const agentById = useMemo(() => new Map((agents ?? []).map((agent) => [agent.id, agent])), [agents]);
+ const projectById = useMemo(() => new Map((projects ?? []).map((project) => [project.id, project])), [projects]);
+ const recentAssigneeIds = useMemo(() => getRecentAssigneeIds(), [routine?.id]);
+ const recentProjectIds = useMemo(() => getRecentProjectIds(), [routine?.id]);
+ const assigneeOptions = useMemo<InlineEntityOption[]>(
+ () =>
+ sortAgentsByRecency(
+ (agents ?? []).filter((agent) => agent.status !== "terminated"),
+ recentAssigneeIds,
+ ).map((agent) => ({
+ id: agent.id,
+ label: agent.name,
+ searchText: `${agent.name} ${agent.role} ${agent.title ?? ""}`,
+ })),
+ [agents, recentAssigneeIds],
+ );
+ const projectOptions = useMemo<InlineEntityOption[]>(
+ () => buildRoutineProjectOptions(projects ?? []),
+ [projects],
+ );
+ const mentionOptions = useMemo<MentionOption[]>(
+ () => buildMarkdownMentionOptions({
+ agents,
+ projects: (projects ?? []).filter((project) => !project.archivedAt),
+ members: companyMembers?.users,
+ }),
+ [agents, companyMembers?.users, projects],
+ );
+
+ // Wrap track-recent side-effects so the section components stay declarative.
+ const setEditDraftTracked: typeof setEditDraft = useCallback((updater) => {
+ setEditDraft((current) => {
+ const next = typeof updater === "function" ? (updater as (c: RoutineEditDraft) => RoutineEditDraft)(current) : updater;
+ if (next.assigneeAgentId && next.assigneeAgentId !== current.assigneeAgentId) {
+ trackRecentAssignee(next.assigneeAgentId);
+ }
+ if (next.projectId && next.projectId !== current.projectId) {
+ trackRecentProject(next.projectId);
+ }
+ return next;
+ });
+ }, []);
+
+ const currentAssignee = editDraft.assigneeAgentId ? agentById.get(editDraft.assigneeAgentId) ?? null : null;
+ const currentProject = editDraft.projectId ? projectById.get(editDraft.projectId) ?? null : null;
+
+ const reloadLatest = useCallback(() => {
+ setSaveConflict(false);
+ if (routineDefaults) setEditDraft(routineDefaults);
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(routineId!) });
+ }, [queryClient, routineDefaults, routineId]);
+
+ const onHistoryRestoreSecretMaterials = useCallback((response: RestoreRoutineRevisionResponse) => {
+ if (response.secretMaterials.length > 0) {
+ setSecretMessage({
+ title:
+ response.secretMaterials.length === 1
+ ? "Webhook trigger restored"
+ : `${response.secretMaterials.length} webhook triggers restored`,
+ entries: response.secretMaterials.map((recreated) => ({
+ webhookUrl: recreated.webhookUrl,
+ webhookSecret: recreated.webhookSecret,
+ })),
+ });
+ }
+ }, []);
+
+ const onHistoryRestored = useCallback(
+ (response: RestoreRoutineRevisionResponse) => {
+ setSaveConflict(false);
+ queryClient.setQueryData<RoutineDetailType | undefined>(
+ queryKeys.routines.detail(routineId!),
+ (prev) =>
+ prev
+ ? {
+ ...prev,
+ ...response.routine,
+ latestRevisionId: response.revision.id,
+ latestRevisionNumber: response.revision.revisionNumber,
+ }
+ : prev,
+ );
+ setEditDraft({
+ title: response.routine.title,
+ description: response.routine.description ?? "",
+ projectId: response.routine.projectId ?? "",
+ assigneeAgentId: response.routine.assigneeAgentId ?? "",
+ priority: response.routine.priority,
+ concurrencyPolicy: response.routine.concurrencyPolicy,
+ catchUpPolicy: response.routine.catchUpPolicy,
+ activityGatePolicy: response.routine.activityGatePolicy,
+ activityGateScope: response.routine.activityGateScope,
+ variables: response.routine.variables as RoutineVariable[],
+ env: (response.routine.env ?? null) as RoutineEnvConfig | null,
+ });
+ hydratedRoutineIdRef.current = response.routine.id;
+ },
+ [queryClient, routineId],
+ );
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={Repeat} message="Select a company to view routines." />;
+ }
+
+ // Back-compat redirect: `?tab=x` → `/routines/:id/x`.
+ const legacyTab = new URLSearchParams(window.location.search).get("tab");
+ if (routineId && legacyTab && LEGACY_TAB_TO_SECTION[legacyTab]) {
+ return <Navigate to={`/routines/${routineId}/${LEGACY_TAB_TO_SECTION[legacyTab]}`} replace />;
+ }
+
+ // Bare /routines/:id → remembered section or overview.
+ if (routineId && !sectionParam) {
+ const landing = readLastSection(routineId) ?? "overview";
+ return <Navigate to={`/routines/${routineId}/${landing}`} replace />;
+ }
+ // Unknown section → overview.
+ if (routineId && sectionParam && !isRoutineSection(sectionParam)) {
+ return <Navigate to={`/routines/${routineId}/overview`} replace />;
+ }
+
+ if (isLoading) {
+ return <PageSkeleton variant="issues-list" />;
+ }
+
+ if (error || !routine || !routineDefaults) {
+ return (
+ <EmptyState
+ icon={AlertCircle}
+ message={error instanceof Error ? error.message : "We couldn't load this routine."}
+ />
+ );
+ }
+
+ const automationEnabled = routine.status === "active";
+ const automationToggleDisabled = updateRoutineStatus.isPending || routine.status === "archived";
+ const automationLabel =
+ routine.status === "archived"
+ ? "Archived"
+ : !routine.assigneeAgentId
+ ? "Draft"
+ : automationEnabled
+ ? "Active"
+ : "Paused";
+ const automationLabelClassName =
+ routine.status === "archived"
+ ? "text-muted-foreground"
+ : automationEnabled
+ ? "text-emerald-400"
+ : "text-muted-foreground";
+
+ const contextValue: RoutineDetailContextValue = {
+ routine,
+ routineId: routineId!,
+ companyId: routine.companyId,
+ editDraft,
+ setEditDraft: setEditDraftTracked,
+ routineDefaults,
+ dirtyFields,
+ isEditDirty,
+ sectionDirtyFields,
+ isSectionDirty,
+ discardSection,
+ saveRoutine,
+ saveConflict,
+ reloadLatest,
+ automationEnabled,
+ automationLabel,
+ automationLabelClassName,
+ automationToggleDisabled,
+ onToggleAutomation: () => {
+ if (!automationEnabled && !routine.assigneeAgentId) {
+ pushToast({
+ title: "Default agent required",
+ body: "Set a default agent before enabling routine automation.",
+ tone: "warn",
+ });
+ return;
+ }
+ updateRoutineStatus.mutate(automationEnabled ? "paused" : "active");
+ },
+ onOpenRunDialog: () => setRunVariablesOpen(true),
+ runRoutinePending: runRoutine.isPending,
+ newTrigger,
+ setNewTrigger,
+ createTrigger,
+ updateTrigger,
+ deleteTrigger,
+ rotateTrigger,
+ secretMessage,
+ setSecretMessage,
+ copySecretValue,
+ availableSecrets,
+ createSecret,
+ agents: agents ?? [],
+ projects: projects ?? [],
+ agentById,
+ projectById,
+ assigneeOptions,
+ projectOptions,
+ recentAssigneeIds,
+ recentProjectIds,
+ mentionOptions,
+ currentAssignee,
+ currentProject,
+ routineRuns,
+ activity,
+ hasLiveRun,
+ activeIssueId,
+ titleInputRef,
+ descriptionEditorRef,
+ assigneeSelectorRef,
+ projectSelectorRef,
+ onHistoryRestoreSecretMaterials,
+ onHistoryRestored,
+ navigateToSection,
+ };
+
+ const isEditableSection = EDITABLE_SECTIONS.includes(section);
+
+ return (
+ <RoutineDetailContext.Provider value={contextValue}>
+ <a
+ href="#routine-section"
+ className="sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-20 focus:rounded focus:bg-background focus:px-3 focus:py-1.5 focus:text-sm"
+ >
+ Skip to section
+ </a>
+
+ {/* Bounded to the main scroll area's height so the header + sub-nav stay
+ fixed and only the section content below scrolls (no page-level
+ scroll, no competing sticky points). */}
+ <div className="-m-4 flex h-full min-h-0 flex-col overflow-hidden md:-m-6">
+ {/* Slim page header — fixed at the top of the routine layout. */}
+ <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <textarea
+ ref={titleInputRef}
+ data-autosize-title
+ className="min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold leading-7 outline-none placeholder:text-muted-foreground/50"
+ placeholder="Routine title"
+ rows={1}
+ value={editDraft.title}
+ onChange={(event) => {
+ setEditDraft((current) => ({ ...current, title: event.target.value }));
+ autoResizeTextarea(event.target);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.metaKey && !event.ctrlKey && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ if (section === "overview") {
+ descriptionEditorRef.current?.focus();
+ } else {
+ navigateToSection("overview");
+ }
+ }
+ }}
+ />
+ {routine.managedByPlugin ? (
+ <Badge variant="outline" className="hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex">
+ <Sparkles className="h-3 w-3" />
+ {routine.managedByPlugin.pluginDisplayName}
+ <span className="font-mono text-(length:--text-nano)">{routine.managedByPlugin.resourceKey}</span>
+ </Badge>
+ ) : null}
+ </div>
+ <div className="ml-auto flex shrink-0 items-center gap-3">
+ <RunButton onClick={() => setRunVariablesOpen(true)} disabled={runRoutine.isPending} />
+ <div className="flex items-center gap-2">
+ <ToggleSwitch
+ size="default"
+ checked={automationEnabled}
+ onCheckedChange={contextValue.onToggleAutomation}
+ disabled={automationToggleDisabled}
+ aria-label={automationEnabled ? "Pause automatic triggers" : "Enable automatic triggers"}
+ />
+ <span className={`text-sm font-medium ${automationLabelClassName}`}>{automationLabel}</span>
+ </div>
+ </div>
+ </header>
+
+ {/* Mobile section picker */}
+ <RoutineSectionPicker
+ activeSection={section}
+ onNavigate={navigateToSection}
+ isSectionDirty={isSectionDirty}
+ />
+
+ <div className="flex min-h-0 flex-1">
+ <RoutineSubSidebar
+ activeSection={section}
+ hrefFor={(target) => `/routines/${routineId}/${target}`}
+ isSectionDirty={isSectionDirty}
+ hasLiveRun={hasLiveRun}
+ onNavigate={(target) => writeLastSection(routineId!, target)}
+ />
+
+ <main
+ id="routine-section"
+ role="main"
+ className="min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-10 md:px-8"
+ >
+ <section
+ aria-labelledby="routine-section-title"
+ className={isEditableSection ? "mx-auto w-full max-w-3xl" : "w-full"}
+ >
+ <h2 id="routine-section-title" className="mb-4 text-lg font-semibold">
+ {SECTION_TITLES[section]}
+ </h2>
+
+ {section === "overview" && <OverviewSection />}
+ {section === "triggers" && <TriggersSection />}
+ {section === "variables" && <VariablesSection />}
+ {section === "secrets" && <SecretsSection />}
+ {section === "delivery" && <DeliverySection />}
+ {section === "runs" && <RunsSection />}
+ {section === "activity" && <ActivitySection />}
+ {section === "history" && <HistorySection />}
+
+ {isEditableSection ? (
+ <RoutineSaveBar
+ dirtyFields={sectionDirtyFields(section)}
+ isSaving={saveRoutine.isPending}
+ saveConflict={saveConflict}
+ onSave={() => {
+ if (!saveRoutine.isPending && editDraft.title.trim()) saveRoutine.mutate();
+ }}
+ onDiscard={() => discardSection(section)}
+ onReload={reloadLatest}
+ />
+ ) : null}
+ </section>
+ </main>
+ </div>
+ </div>
+
+ <RoutineRunVariablesDialog
+ open={runVariablesOpen}
+ onOpenChange={setRunVariablesOpen}
+ companyId={routine.companyId}
+ routineName={routine.title}
+ agents={agents ?? []}
+ projects={projects ?? []}
+ defaultProjectId={routine.projectId}
+ defaultAssigneeAgentId={routine.assigneeAgentId}
+ variables={routine.variables ?? []}
+ isPending={runRoutine.isPending}
+ onSubmit={(data) => runRoutine.mutate(data)}
+ />
+ </RoutineDetailContext.Provider>
+ );
+}
diff --git a/ui/src/pages/RoutineDetail.tsx b/ui/src/pages/RoutineDetail.tsx
index ffaca21049..58ce52aede 100644
--- a/ui/src/pages/RoutineDetail.tsx
+++ b/ui/src/pages/RoutineDetail.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Navigate, useNavigate, useParams } from "@/lib/router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { AlertCircle, Repeat, Sparkles } from "lucide-react";
+import { AlertCircle, History, Pencil, Repeat, Sparkles, X } from "lucide-react";
import { ApiError } from "../api/client";
import {
routinesApi,
@@ -18,6 +18,7 @@ import { accessApi } from "../api/access";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useToastActions } from "../context/ToastContext";
+import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import { queryKeys } from "../lib/queryKeys";
import { copyTextToClipboard } from "../lib/clipboard";
import { buildMarkdownMentionOptions } from "../lib/company-members";
@@ -34,14 +35,17 @@ import { RunButton } from "../components/AgentActionButtons";
import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
import { getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";
import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { RoutineOverview } from "../components/RoutineOverview";
+import { RoutineSectionPicker, RoutineSubSidebar } from "../components/RoutineSubSidebar";
import {
- RoutineSubSidebar,
- RoutineSectionPicker,
-} from "../components/RoutineSubSidebar";
+ isRoutineDetailView,
+ resolveRoutineDetailDestination,
+ routineDetailHref,
+} from "../components/RoutineContextualSidebar";
import { RoutineSaveBar } from "../components/RoutineSaveBar";
import {
EDITABLE_SECTIONS,
- ROUTINE_SECTION_KEYS,
SECTION_FIELD_KEYS,
RoutineDetailContext,
createDefaultNewTrigger,
@@ -58,9 +62,9 @@ import {
DeliverySection,
} from "../components/routine-sections/editable-sections";
import {
- RunsSection,
ActivitySection,
HistorySection,
+ RunsSection,
} from "../components/routine-sections/operate-sections";
import type {
RoutineDetail as RoutineDetailType,
@@ -68,8 +72,6 @@ import type {
RoutineVariable,
} from "@paperclipai/shared";
-const LAST_SECTION_STORAGE_KEY = "paperclip.routineLastSection";
-
export function buildRoutineProjectOptions(
projects: ReadonlyArray<{ id: string; name: string; description?: string | null; archivedAt?: Date | string | null }>,
): InlineEntityOption[] {
@@ -84,49 +86,13 @@ export function buildRoutineProjectOptions(
const SECTION_TITLES: Record<RoutineSectionKey, string> = {
overview: "Overview",
- triggers: "Triggers",
+ triggers: "Schedule",
variables: "Variables",
secrets: "Secrets",
delivery: "Delivery",
runs: "Runs",
activity: "Activity",
- history: "History",
-};
-
-function isRoutineSection(value: string | undefined | null): value is RoutineSectionKey {
- return value != null && ROUTINE_SECTION_KEYS.includes(value as RoutineSectionKey);
-}
-
-function readLastSection(routineId: string): RoutineSectionKey | null {
- try {
- const raw = localStorage.getItem(LAST_SECTION_STORAGE_KEY);
- if (!raw) return null;
- const parsed = JSON.parse(raw) as Record<string, string>;
- const stored = parsed[routineId];
- return isRoutineSection(stored) ? stored : null;
- } catch {
- return null;
- }
-}
-
-function writeLastSection(routineId: string, section: RoutineSectionKey) {
- try {
- const raw = localStorage.getItem(LAST_SECTION_STORAGE_KEY);
- const parsed = raw ? (JSON.parse(raw) as Record<string, string>) : {};
- parsed[routineId] = section;
- localStorage.setItem(LAST_SECTION_STORAGE_KEY, JSON.stringify(parsed));
- } catch {
- /* ignore storage failures */
- }
-}
-
-/** Back-compat: `?tab=x` query param maps to the new section sub-routes. */
-const LEGACY_TAB_TO_SECTION: Record<string, RoutineSectionKey> = {
- triggers: "triggers",
- runs: "runs",
- activity: "activity",
- secrets: "secrets",
- history: "history",
+ history: "Version history",
};
function autoResizeTextarea(element: HTMLTextAreaElement | null) {
@@ -160,6 +126,7 @@ export function RoutineDetail() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const { pushToast } = useToastActions();
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const hydratedRoutineIdRef = useRef<string | null>(null);
const titleInputRef = useRef<HTMLTextAreaElement | null>(null);
const descriptionEditorRef = useRef<MarkdownEditorRef>(null);
@@ -168,6 +135,7 @@ export function RoutineDetail() {
const [secretMessage, setSecretMessage] = useState<SecretMessage | null>(null);
const [saveConflict, setSaveConflict] = useState(false);
const [runVariablesOpen, setRunVariablesOpen] = useState(false);
+ const [overviewEditing, setOverviewEditing] = useState(false);
const [newTrigger, setNewTrigger] = useState(createDefaultNewTrigger);
const [editDraft, setEditDraft] = useState<RoutineEditDraft>({
title: "",
@@ -183,15 +151,25 @@ export function RoutineDetail() {
env: null,
});
- const section: RoutineSectionKey = isRoutineSection(sectionParam) ? sectionParam : "overview";
+ const legacyOperateSection = !streamlinedUiEnabled && (sectionParam === "runs" || sectionParam === "activity")
+ ? sectionParam
+ : null;
+ const section: RoutineSectionKey = legacyOperateSection
+ ?? (isRoutineDetailView(sectionParam) ? sectionParam : "overview");
const navigateToSection = useCallback(
(next: RoutineSectionKey, options?: { replace?: boolean }) => {
if (!routineId) return;
- writeLastSection(routineId, next);
- navigate(`/routines/${routineId}/${next}`, { replace: options?.replace ?? true });
+ if (!streamlinedUiEnabled && (next === "runs" || next === "activity")) {
+ navigate(`/routines/${routineId}/${next}`, { replace: options?.replace ?? true });
+ return;
+ }
+ navigate(
+ resolveRoutineDetailDestination({ routineId, section: next }),
+ { replace: options?.replace ?? true },
+ );
},
- [navigate, routineId],
+ [navigate, routineId, streamlinedUiEnabled],
);
const { data: routine, isLoading, error } = useQuery({
@@ -360,12 +338,9 @@ export function RoutineDetail() {
autoResizeTextarea(titleInputRef.current);
}, [editDraft.title, routine?.id]);
- // Persist the section the user lands on so a bare /routines/:id remembers it.
useEffect(() => {
- if (routineId && isRoutineSection(sectionParam)) {
- writeLastSection(routineId, sectionParam);
- }
- }, [routineId, sectionParam]);
+ if (section !== "overview") setOverviewEditing(false);
+ }, [routineId, section]);
const copySecretValue = useCallback(
async (label: string, value: string) => {
@@ -677,20 +652,15 @@ export function RoutineDetail() {
return <EmptyState icon={Repeat} message="Select an organization to view routines." />;
}
- // Back-compat redirect: `?tab=x` → `/routines/:id/x`.
const legacyTab = new URLSearchParams(window.location.search).get("tab");
- if (routineId && legacyTab && LEGACY_TAB_TO_SECTION[legacyTab]) {
- return <Navigate to={`/routines/${routineId}/${LEGACY_TAB_TO_SECTION[legacyTab]}`} replace />;
- }
-
- // Bare /routines/:id → remembered section or overview.
- if (routineId && !sectionParam) {
- const landing = readLastSection(routineId) ?? "overview";
- return <Navigate to={`/routines/${routineId}/${landing}`} replace />;
- }
- // Unknown section → overview.
- if (routineId && sectionParam && !isRoutineSection(sectionParam)) {
- return <Navigate to={`/routines/${routineId}/overview`} replace />;
+ const validLegacySection = !streamlinedUiEnabled && (sectionParam === "runs" || sectionParam === "activity");
+ if (routineId && (legacyTab || !sectionParam || (!isRoutineDetailView(sectionParam) && !validLegacySection))) {
+ return (
+ <Navigate
+ to={resolveRoutineDetailDestination({ routineId, section: sectionParam, legacyTab })}
+ replace
+ />
+ );
}
if (isLoading) {
@@ -801,35 +771,52 @@ export function RoutineDetail() {
Skip to section
</a>
- {/* Bounded to the main scroll area's height so the header + sub-nav stay
- fixed and only the section content below scrolls (no page-level
- scroll, no competing sticky points). */}
- <div className="-m-4 flex h-full min-h-0 flex-col overflow-hidden md:-m-6">
- {/* Slim page header — fixed at the top of the routine layout. */}
- <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6">
+ {/* The global shell owns routine navigation. This surface keeps one
+ content scroll owner and a compact action header. */}
+ <div className="-m-4 flex h-full min-h-0 overflow-hidden md:-m-6">
+ {!streamlinedUiEnabled ? (
+ <RoutineSubSidebar
+ activeSection={section}
+ hrefFor={(next) => next === "runs" || next === "activity"
+ ? `/routines/${routine.id}/${next}`
+ : routineDetailHref(routine.id, next)}
+ isSectionDirty={isSectionDirty}
+ hasLiveRun={hasLiveRun}
+ onNavigate={navigateToSection}
+ />
+ ) : null}
+ <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
+ {!streamlinedUiEnabled ? (
+ <RoutineSectionPicker
+ activeSection={section}
+ onNavigate={navigateToSection}
+ isSectionDirty={isSectionDirty}
+ />
+ ) : null}
+ <header className="flex min-h-14 shrink-0 flex-wrap items-center gap-3 border-b border-border bg-background px-4 py-2 md:px-6">
<div className="flex min-w-0 flex-1 items-center gap-3">
- <textarea
- ref={titleInputRef}
- data-autosize-title
- className="min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold leading-7 outline-none placeholder:text-muted-foreground/50"
- placeholder="Routine title"
- rows={1}
- value={editDraft.title}
- onChange={(event) => {
- setEditDraft((current) => ({ ...current, title: event.target.value }));
- autoResizeTextarea(event.target);
- }}
- onKeyDown={(event) => {
- if (event.key === "Enter" && !event.metaKey && !event.ctrlKey && !event.nativeEvent.isComposing) {
- event.preventDefault();
- if (section === "overview") {
+ {section === "overview" && overviewEditing ? (
+ <textarea
+ ref={titleInputRef}
+ data-autosize-title
+ className="min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold leading-7 outline-none placeholder:text-muted-foreground/50"
+ placeholder="Routine title"
+ rows={1}
+ value={editDraft.title}
+ onChange={(event) => {
+ setEditDraft((current) => ({ ...current, title: event.target.value }));
+ autoResizeTextarea(event.target);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.metaKey && !event.ctrlKey && !event.nativeEvent.isComposing) {
+ event.preventDefault();
descriptionEditorRef.current?.focus();
- } else {
- navigateToSection("overview");
}
- }
- }}
- />
+ }}
+ />
+ ) : (
+ <h1 className="min-w-0 flex-1 truncate text-xl font-bold">{routine.title}</h1>
+ )}
{routine.managedByPlugin ? (
<Badge variant="outline" className="hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex">
<Sparkles className="h-3 w-3" />
@@ -838,7 +825,45 @@ export function RoutineDetail() {
</Badge>
) : null}
</div>
- <div className="ml-auto flex shrink-0 items-center gap-3">
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ {section === "history" ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => navigate(routineDetailHref(routine.id))}
+ >
+ Back to overview
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => navigate(routineDetailHref(routine.id, "history"))}
+ >
+ <History className="h-3.5 w-3.5" />
+ History
+ </Button>
+ )}
+ {section === "overview" ? (
+ overviewEditing ? (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ discardSection("overview");
+ setOverviewEditing(false);
+ }}
+ >
+ <X className="h-3.5 w-3.5" />
+ Cancel editing
+ </Button>
+ ) : (
+ <Button variant="outline" size="sm" onClick={() => setOverviewEditing(true)}>
+ <Pencil className="h-3.5 w-3.5" />
+ Edit routine
+ </Button>
+ )
+ ) : null}
<RunButton onClick={() => setRunVariablesOpen(true)} disabled={runRoutine.isPending} />
<div className="flex items-center gap-2">
<ToggleSwitch
@@ -853,58 +878,48 @@ export function RoutineDetail() {
</div>
</header>
- {/* Mobile section picker */}
- <RoutineSectionPicker
- activeSection={section}
- onNavigate={navigateToSection}
- isSectionDirty={isSectionDirty}
- />
-
- <div className="flex min-h-0 flex-1">
- <RoutineSubSidebar
- activeSection={section}
- hrefFor={(target) => `/routines/${routineId}/${target}`}
- isSectionDirty={isSectionDirty}
- hasLiveRun={hasLiveRun}
- onNavigate={(target) => writeLastSection(routineId!, target)}
- />
-
- <main
- id="routine-section"
- role="main"
- className="min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-10 md:px-8"
+ <main
+ id="routine-section"
+ role="main"
+ className="min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-8 md:px-8"
+ >
+ <section
+ aria-labelledby="routine-section-title"
+ className={
+ section === "overview" && !overviewEditing
+ ? "mx-auto w-full max-w-5xl"
+ : isEditableSection
+ ? "mx-auto w-full max-w-3xl"
+ : "w-full"
+ }
>
- <section
- aria-labelledby="routine-section-title"
- className={isEditableSection ? "mx-auto w-full max-w-3xl" : "w-full"}
- >
- <h2 id="routine-section-title" className="mb-4 text-lg font-semibold">
- {SECTION_TITLES[section]}
- </h2>
-
- {section === "overview" && <OverviewSection />}
- {section === "triggers" && <TriggersSection />}
- {section === "variables" && <VariablesSection />}
- {section === "secrets" && <SecretsSection />}
- {section === "delivery" && <DeliverySection />}
- {section === "runs" && <RunsSection />}
- {section === "activity" && <ActivitySection />}
- {section === "history" && <HistorySection />}
-
- {isEditableSection ? (
- <RoutineSaveBar
- dirtyFields={sectionDirtyFields(section)}
- isSaving={saveRoutine.isPending}
- saveConflict={saveConflict}
- onSave={() => {
- if (!saveRoutine.isPending && editDraft.title.trim()) saveRoutine.mutate();
- }}
- onDiscard={() => discardSection(section)}
- onReload={reloadLatest}
- />
- ) : null}
- </section>
- </main>
+ <h2 id="routine-section-title" className="mb-4 text-lg font-semibold">
+ {SECTION_TITLES[section]}
+ </h2>
+
+ {section === "overview" && (overviewEditing ? <OverviewSection /> : <RoutineOverview />)}
+ {section === "triggers" && <TriggersSection />}
+ {section === "variables" && <VariablesSection />}
+ {section === "secrets" && <SecretsSection />}
+ {section === "delivery" && <DeliverySection />}
+ {section === "runs" && <RunsSection />}
+ {section === "activity" && <ActivitySection />}
+ {section === "history" && <HistorySection />}
+
+ {isEditableSection && (section !== "overview" || overviewEditing) ? (
+ <RoutineSaveBar
+ dirtyFields={sectionDirtyFields(section)}
+ isSaving={saveRoutine.isPending}
+ saveConflict={saveConflict}
+ onSave={() => {
+ if (!saveRoutine.isPending && editDraft.title.trim()) saveRoutine.mutate();
+ }}
+ onDiscard={() => discardSection(section)}
+ onReload={reloadLatest}
+ />
+ ) : null}
+ </section>
+ </main>
</div>
</div>
diff --git a/ui/src/pages/Routines.production.tsx b/ui/src/pages/Routines.production.tsx
new file mode 100644
index 0000000000..4ec6f10503
--- /dev/null
+++ b/ui/src/pages/Routines.production.tsx
@@ -0,0 +1,1451 @@
+import { startTransition, useEffect, useMemo, useRef, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Link, useNavigate, useSearchParams } from "@/lib/router";
+import { ArrowUpDown, Check, ChevronDown, ChevronRight, Layers, Plus, Repeat } from "lucide-react";
+import { routinesApi } from "../api/routines";
+import { foldersApi } from "../api/folders";
+import { agentsApi } from "../api/agents";
+import { projectsApi } from "../api/projects";
+import { issuesApi } from "../api/issues";
+import { heartbeatsApi } from "../api/heartbeats";
+import { accessApi } from "../api/access";
+import { useCompany } from "../context/CompanyContext";
+import { useBreadcrumbs } from "../context/BreadcrumbContext";
+import { useToastActions } from "../context/ToastContext";
+import { buildMarkdownMentionOptions } from "../lib/company-members";
+import { cn } from "../lib/utils";
+import { queryKeys } from "../lib/queryKeys";
+import { groupBy } from "../lib/groupBy";
+import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";
+import { collectLiveIssueIds } from "../lib/liveIssueIds";
+import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
+import { getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";
+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
+import { EmptyState } from "../components/EmptyState";
+import { IssuesList } from "../components/IssuesList";
+import { PageSkeleton } from "../components/PageSkeleton";
+import { PageTabBar } from "../components/PageTabBar";
+import { AgentIcon } from "../components/AgentIconPicker";
+import { InlineEntitySelector, type InlineEntityOption } from "../components/InlineEntitySelector";
+import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "../components/MarkdownEditor";
+import { RoutineListRow, nextRoutineStatus } from "../components/RoutineList";
+import {
+ RoutineRunVariablesDialog,
+ type RoutineRunDialogSubmitData,
+} from "../components/RoutineRunVariablesDialog";
+import { RoutineVariablesEditor, RoutineVariablesHint } from "../components/RoutineVariablesEditor";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Tabs, TabsContent } from "@/components/ui/tabs";
+import type { RoutineListItem, RoutineVariable } from "@paperclipai/shared";
+import type { FolderListItem } from "@paperclipai/shared";
+import {
+ AllUnfiledBanner,
+ BulkBar,
+ DeleteFolderDialog,
+ FolderChip,
+ FolderFormDialog,
+ FolderRail,
+ FolderSwatch,
+ MobileFolderSheet,
+ MoveToMenu,
+ folderSearchValue,
+ normalizeFolderSelection,
+ selectedFolderFromList,
+ type FolderSelection,
+} from "../components/folders/FolderControls";
+
+const concurrencyPolicies = ["coalesce_if_active", "always_enqueue", "skip_if_active"];
+const catchUpPolicies = ["skip_missed", "enqueue_missed_with_cap"];
+const concurrencyPolicyDescriptions: Record<string, string> = {
+ coalesce_if_active: "If a run is already active, keep just one follow-up run queued.",
+ always_enqueue: "Queue every trigger occurrence, even if the routine is already running.",
+ skip_if_active: "Drop new trigger occurrences while a run is still active.",
+};
+const catchUpPolicyDescriptions: Record<string, string> = {
+ skip_missed: "Ignore windows that were missed while the scheduler or routine was paused.",
+ enqueue_missed_with_cap: "Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap.",
+};
+
+function autoResizeTextarea(element: HTMLTextAreaElement | null) {
+ if (!element) return;
+ element.style.height = "auto";
+ element.style.height = `${element.scrollHeight}px`;
+}
+
+type RoutinesTab = "routines" | "runs";
+type RoutineGroupBy = "folder" | "none" | "project" | "assignee";
+type RoutineSortField = "updated" | "created" | "title" | "lastRun";
+type RoutineSortDir = "asc" | "desc";
+
+type RoutineViewState = {
+ sortField: RoutineSortField;
+ sortDir: RoutineSortDir;
+ groupBy: RoutineGroupBy;
+ collapsedGroups: string[];
+};
+
+type RoutineGroup = {
+ key: string;
+ label: string | null;
+ items: RoutineListItem[];
+};
+
+const builtInRoutineGroupKey = "__built_in_routines";
+
+const defaultRoutineViewState: RoutineViewState = {
+ sortField: "title",
+ sortDir: "asc",
+ groupBy: "folder",
+ collapsedGroups: [],
+};
+
+function getRoutineViewState(key: string): RoutineViewState {
+ try {
+ const raw = localStorage.getItem(key);
+ if (raw) return { ...defaultRoutineViewState, ...JSON.parse(raw) };
+ } catch {
+ // Ignore malformed local state and fall back to defaults.
+ }
+ return { ...defaultRoutineViewState };
+}
+
+function saveRoutineViewState(key: string, state: RoutineViewState) {
+ localStorage.setItem(key, JSON.stringify(state));
+}
+
+function timestampValue(value: Date | string | null | undefined) {
+ if (!value) return Number.NEGATIVE_INFINITY;
+ const timestamp = new Date(value).getTime();
+ return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY;
+}
+
+function compareNullableText(left: string | null | undefined, right: string | null | undefined) {
+ return (left ?? "").localeCompare(right ?? "", undefined, { sensitivity: "base" });
+}
+
+type RoutineFolderGroupMeta = { name: string; position?: number | null };
+
+function buildRoutineMutationPayload(input: {
+ title: string;
+ description: string;
+ projectId: string;
+ folderId: string | null;
+ assigneeAgentId: string;
+ priority: string;
+ concurrencyPolicy: string;
+ catchUpPolicy: string;
+ variables: RoutineVariable[];
+}) {
+ return {
+ ...input,
+ description: input.description.trim() || null,
+ projectId: input.projectId || null,
+ folderId: input.folderId || null,
+ assigneeAgentId: input.assigneeAgentId || null,
+ };
+}
+
+export function buildRoutineGroups(
+ routines: RoutineListItem[],
+ groupByValue: RoutineGroupBy,
+ projectById: Map<string, { name: string }>,
+ agentById: Map<string, { name: string }>,
+ folderById: Map<string, RoutineFolderGroupMeta>,
+): RoutineGroup[] {
+ if (groupByValue === "none") {
+ return [{ key: "__all", label: null, items: routines }];
+ }
+
+ if (groupByValue === "folder") {
+ const groups = groupBy(routines, (routine) => routine.folderId ?? "__unfiled");
+ return Object.keys(groups)
+ .sort((left, right) => {
+ if (left === "__unfiled" || right === "__unfiled") {
+ if (left === right) return 0;
+ return left === "__unfiled" ? 1 : -1;
+ }
+
+ const leftFolder = folderById.get(left);
+ const rightFolder = folderById.get(right);
+ const leftPosition = Number.isFinite(leftFolder?.position) ? leftFolder!.position! : Number.POSITIVE_INFINITY;
+ const rightPosition = Number.isFinite(rightFolder?.position) ? rightFolder!.position! : Number.POSITIVE_INFINITY;
+ const positionCompare = leftPosition - rightPosition;
+ if (positionCompare !== 0) return positionCompare;
+
+ const labelCompare = (leftFolder?.name ?? "Unknown folder").localeCompare(
+ rightFolder?.name ?? "Unknown folder",
+ undefined,
+ { sensitivity: "base" },
+ );
+ return labelCompare || left.localeCompare(right);
+ })
+ .map((key) => ({
+ key,
+ label: key === "__unfiled" ? "Unfiled" : (folderById.get(key)?.name ?? "Unknown folder"),
+ items: groups[key]!,
+ }));
+ }
+
+ if (groupByValue === "project") {
+ const groups = groupBy(routines, (routine) => routine.projectId ?? "__no_project");
+ return Object.keys(groups)
+ .sort((left, right) => {
+ const leftLabel = left === "__no_project" ? "No project" : (projectById.get(left)?.name ?? "Unknown project");
+ const rightLabel = right === "__no_project" ? "No project" : (projectById.get(right)?.name ?? "Unknown project");
+ return leftLabel.localeCompare(rightLabel);
+ })
+ .map((key) => ({
+ key,
+ label: key === "__no_project" ? "No project" : (projectById.get(key)?.name ?? "Unknown project"),
+ items: groups[key]!,
+ }));
+ }
+
+ const groups = groupBy(routines, (routine) => routine.assigneeAgentId ?? "__unassigned");
+ return Object.keys(groups)
+ .sort((left, right) => {
+ const leftLabel = left === "__unassigned" ? "Unassigned" : (agentById.get(left)?.name ?? "Unknown agent");
+ const rightLabel = right === "__unassigned" ? "Unassigned" : (agentById.get(right)?.name ?? "Unknown agent");
+ return leftLabel.localeCompare(rightLabel);
+ })
+ .map((key) => ({
+ key,
+ label: key === "__unassigned" ? "Unassigned" : (agentById.get(key)?.name ?? "Unknown agent"),
+ items: groups[key]!,
+ }));
+}
+
+export function isBuiltInRoutine(routine: Pick<RoutineListItem, "originKind">) {
+ return routine.originKind === "built_in_agent_bundle";
+}
+
+export function buildRoutineSections(
+ routines: RoutineListItem[],
+ groupByValue: RoutineGroupBy,
+ projectById: Map<string, { name: string }>,
+ agentById: Map<string, { name: string }>,
+ folderById: Map<string, { name: string }>,
+): RoutineGroup[] {
+ const builtInRoutines = routines.filter(isBuiltInRoutine);
+ const customRoutines = routines.filter((routine) => !isBuiltInRoutine(routine));
+ const customGroups = buildRoutineGroups(customRoutines, groupByValue, projectById, agentById, folderById)
+ .filter((group) => group.items.length > 0)
+ .map((group) => (
+ builtInRoutines.length > 0 && groupByValue === "none" && group.key === "__all"
+ ? { ...group, label: "Custom routines" }
+ : group
+ ));
+
+ if (builtInRoutines.length === 0) return customGroups;
+
+ return [
+ ...customGroups,
+ {
+ key: builtInRoutineGroupKey,
+ label: "Built-in routines",
+ items: builtInRoutines,
+ },
+ ];
+}
+
+export function sortRoutines(
+ routines: RoutineListItem[],
+ sortField: RoutineSortField,
+ sortDir: RoutineSortDir,
+): RoutineListItem[] {
+ const direction = sortDir === "asc" ? 1 : -1;
+ return [...routines].sort((left, right) => {
+ let result = 0;
+
+ if (sortField === "title") {
+ result = compareNullableText(left.title, right.title);
+ } else if (sortField === "created") {
+ result = timestampValue(left.createdAt) - timestampValue(right.createdAt);
+ } else if (sortField === "lastRun") {
+ result = timestampValue(left.lastRun?.triggeredAt ?? left.lastTriggeredAt) -
+ timestampValue(right.lastRun?.triggeredAt ?? right.lastTriggeredAt);
+ } else {
+ result = timestampValue(left.updatedAt) - timestampValue(right.updatedAt);
+ }
+
+ if (result !== 0) return result * direction;
+ return compareNullableText(left.title, right.title);
+ });
+}
+
+function buildRoutinesTabHref(tab: RoutinesTab) {
+ return tab === "runs" ? "/routines?tab=runs" : "/routines";
+}
+
+function RoutineSectionHeader({
+ label,
+ count,
+ isOpen,
+}: {
+ label: string;
+ count: number;
+ isOpen: boolean;
+}) {
+ return (
+ <div
+ className={`flex items-center gap-2 rounded-lg border border-border px-3 py-2${
+ isOpen ? " mb-1" : ""
+ }`}
+ >
+ <CollapsibleTrigger className="flex items-center gap-1.5">
+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90" />
+ <span className="text-sm font-semibold uppercase tracking-wide">
+ {label}
+ </span>
+ </CollapsibleTrigger>
+ <span className="text-xs text-muted-foreground">
+ {count}
+ </span>
+ </div>
+ );
+}
+
+export function Routines() {
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const { pushToast } = useToastActions();
+ const descriptionEditorRef = useRef<MarkdownEditorRef>(null);
+ const titleInputRef = useRef<HTMLTextAreaElement | null>(null);
+ const assigneeSelectorRef = useRef<HTMLButtonElement | null>(null);
+ const projectSelectorRef = useRef<HTMLButtonElement | null>(null);
+ const [folderDialogOpen, setFolderDialogOpen] = useState(false);
+ const [folderDialogTarget, setFolderDialogTarget] = useState<FolderListItem | null>(null);
+ const [deleteFolderTarget, setDeleteFolderTarget] = useState<FolderListItem | null>(null);
+ const [mobileFoldersOpen, setMobileFoldersOpen] = useState(false);
+ const [selectMode, setSelectMode] = useState(false);
+ const [selectedRoutineIds, setSelectedRoutineIds] = useState<string[]>([]);
+ const [moveAfterCreateIds, setMoveAfterCreateIds] = useState<string[]>([]);
+ const [runningRoutineId, setRunningRoutineId] = useState<string | null>(null);
+ const [statusMutationRoutineId, setStatusMutationRoutineId] = useState<string | null>(null);
+ const [runDialogRoutine, setRunDialogRoutine] = useState<RoutineListItem | null>(null);
+ const [composerOpen, setComposerOpen] = useState(false);
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const activeTab: RoutinesTab = searchParams.get("tab") === "runs" ? "runs" : "routines";
+ const [draft, setDraft] = useState<{
+ title: string;
+ description: string;
+ projectId: string;
+ folderId: string | null;
+ assigneeAgentId: string;
+ priority: string;
+ concurrencyPolicy: string;
+ catchUpPolicy: string;
+ variables: RoutineVariable[];
+ }>({
+ title: "",
+ description: "",
+ projectId: "",
+ folderId: null,
+ assigneeAgentId: "",
+ priority: "medium",
+ concurrencyPolicy: "coalesce_if_active",
+ catchUpPolicy: "skip_missed",
+ variables: [],
+ });
+ const routineViewStateKey = selectedCompanyId
+ ? `paperclip:routines-view:${selectedCompanyId}`
+ : "paperclip:routines-view";
+ const [routineViewState, setRoutineViewState] = useState<RoutineViewState>(() => getRoutineViewState(routineViewStateKey));
+ const folderSelection = normalizeFolderSelection(searchParams.get("folder"));
+
+ useEffect(() => {
+ setBreadcrumbs([{ label: "Routines" }]);
+ }, [setBreadcrumbs]);
+
+ useEffect(() => {
+ setRoutineViewState(getRoutineViewState(routineViewStateKey));
+ }, [routineViewStateKey]);
+
+ const { data: routines, isLoading, error } = useQuery({
+ queryKey: queryKeys.routines.list(selectedCompanyId!),
+ queryFn: () => routinesApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: routineFolders, isLoading: foldersLoading } = useQuery({
+ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine"),
+ queryFn: () => foldersApi.list(selectedCompanyId!, "routine"),
+ enabled: !!selectedCompanyId && activeTab === "routines",
+ });
+ const { data: agents } = useQuery({
+ queryKey: queryKeys.agents.list(selectedCompanyId!),
+ queryFn: () => agentsApi.list(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: projects } = useQuery({
+ queryKey: queryKeys.projects.list(selectedCompanyId!, { includeArchived: true }),
+ queryFn: () => projectsApi.list(selectedCompanyId!, { includeArchived: true }),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
+ const { data: routineExecutionIssues, isLoading: recentRunsLoading, error: recentRunsError } = useQuery({
+ queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"],
+ queryFn: () => issuesApi.list(selectedCompanyId!, { originKind: "routine_execution" }),
+ enabled: !!selectedCompanyId && activeTab === "runs",
+ });
+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);
+ const sharedLiveRuns = useSharedPollingQuery({
+ companyId: selectedCompanyId,
+ resourceKey: "live-runs",
+ queryKey: liveRunsQueryKey,
+ enabled: !!selectedCompanyId && activeTab === "runs",
+ // Event-sourced via LiveUpdatesProvider (GitHub issue 9627); no interval poll needed.
+ refetchInterval: false,
+ leaderOnly: true,
+ });
+ const { data: liveRuns, dataUpdatedAt: liveRunsUpdatedAt } = useQuery({
+ queryKey: liveRunsQueryKey,
+ queryFn: () => heartbeatsApi.liveRunsForCompany(selectedCompanyId!),
+ enabled: sharedLiveRuns.enabled,
+ refetchInterval: sharedLiveRuns.refetchInterval,
+ });
+ usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);
+
+ useEffect(() => {
+ autoResizeTextarea(titleInputRef.current);
+ }, [draft.title, composerOpen]);
+
+ const mentionOptions = useMemo<MentionOption[]>(() => {
+ return buildMarkdownMentionOptions({
+ agents,
+ projects: (projects ?? []).filter((project) => !project.archivedAt),
+ members: companyMembers?.users,
+ });
+ }, [agents, companyMembers?.users, projects]);
+
+ const createRoutine = useMutation({
+ mutationFn: () =>
+ routinesApi.create(selectedCompanyId!, buildRoutineMutationPayload(draft)),
+ onSuccess: async (routine) => {
+ setDraft({
+ title: "",
+ description: "",
+ projectId: "",
+ folderId: null,
+ assigneeAgentId: "",
+ priority: "medium",
+ concurrencyPolicy: "coalesce_if_active",
+ catchUpPolicy: "skip_missed",
+ variables: [],
+ });
+ setComposerOpen(false);
+ setAdvancedOpen(false);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) });
+ pushToast({
+ title: "Routine created",
+ body: routine.assigneeAgentId
+ ? "Add the first trigger to turn it into a live workflow."
+ : "Draft saved. Add a default agent before enabling automation.",
+ tone: "success",
+ });
+ navigate(`/routines/${routine.id}?tab=triggers`);
+ },
+ });
+ const createFolder = useMutation({
+ mutationFn: (payload: { name: string; color: string | null }) =>
+ foldersApi.create(selectedCompanyId!, { kind: "routine", ...payload }),
+ onSuccess: async (folder) => {
+ setFolderDialogOpen(false);
+ setFolderDialogTarget(null);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") });
+ if (moveAfterCreateIds.length > 0) {
+ const ids = moveAfterCreateIds;
+ setMoveAfterCreateIds([]);
+ try {
+ await Promise.all(ids.map((itemId) =>
+ foldersApi.moveItem(selectedCompanyId!, { kind: "routine", itemId, folderId: folder.id })
+ ));
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") }),
+ ]);
+ } catch (moveError) {
+ pushToast({
+ title: "Folder created, move failed",
+ body: moveError instanceof Error ? moveError.message : "Paperclip could not move the selected routines.",
+ tone: "error",
+ });
+ return;
+ }
+ } else {
+ setFolderSelection(folder.id);
+ }
+ pushToast({ title: "Folder created", body: folder.name, tone: "success" });
+ },
+ onError: (mutationError) => {
+ pushToast({
+ title: "Failed to save folder",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not save the folder.",
+ tone: "error",
+ });
+ },
+ });
+ const updateFolder = useMutation({
+ mutationFn: ({ folderId, payload }: { folderId: string; payload: { name?: string; color?: string | null } }) =>
+ foldersApi.update(selectedCompanyId!, folderId, payload),
+ onSuccess: async () => {
+ setFolderDialogOpen(false);
+ setFolderDialogTarget(null);
+ await queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") });
+ },
+ onError: (mutationError) => {
+ pushToast({
+ title: "Folder save failed",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not update the folder.",
+ tone: "error",
+ });
+ },
+ });
+ const deleteFolder = useMutation({
+ mutationFn: (folderId: string) => foldersApi.delete(selectedCompanyId!, folderId),
+ onSuccess: async (_, folderId) => {
+ if (folderSelection === folderId) setFolderSelection("all");
+ setDeleteFolderTarget(null);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") }),
+ ]);
+ pushToast({ title: "Folder deleted", body: "Items moved to Unfiled.", tone: "success" });
+ },
+ onError: (mutationError) => {
+ pushToast({
+ title: "Folder delete failed",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not delete the folder.",
+ tone: "error",
+ });
+ },
+ });
+ const moveRoutineToFolder = useMutation({
+ mutationFn: ({ itemId, folderId }: { itemId: string; folderId: string | null }) =>
+ foldersApi.moveItem(selectedCompanyId!, { kind: "routine", itemId, folderId }),
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") }),
+ ]);
+ },
+ onError: (mutationError) => {
+ pushToast({
+ title: "Move failed",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not move the routine.",
+ tone: "error",
+ });
+ },
+ });
+ const updateIssue = useMutation({
+ mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
+ issuesApi.update(id, data),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"] });
+ },
+ });
+
+ const updateRoutineStatus = useMutation({
+ mutationFn: ({ id, status }: { id: string; status: string }) => routinesApi.update(id, { status }),
+ onMutate: ({ id }) => {
+ setStatusMutationRoutineId(id);
+ },
+ onSuccess: async (_, variables) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(variables.id) }),
+ ]);
+ },
+ onSettled: () => {
+ setStatusMutationRoutineId(null);
+ },
+ onError: (mutationError) => {
+ pushToast({
+ title: "Failed to update routine",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not update the routine.",
+ tone: "error",
+ });
+ },
+ });
+
+ const runRoutine = useMutation({
+ mutationFn: ({ id, data }: { id: string; data?: RoutineRunDialogSubmitData }) => routinesApi.run(id, {
+ ...(data?.variables && Object.keys(data.variables).length > 0 ? { variables: data.variables } : {}),
+ ...(data?.assigneeAgentId !== undefined ? { assigneeAgentId: data.assigneeAgentId } : {}),
+ ...(data?.projectId !== undefined ? { projectId: data.projectId } : {}),
+ ...(data?.executionWorkspaceId !== undefined ? { executionWorkspaceId: data.executionWorkspaceId } : {}),
+ ...(data?.executionWorkspacePreference !== undefined
+ ? { executionWorkspacePreference: data.executionWorkspacePreference }
+ : {}),
+ ...(data?.executionWorkspaceSettings !== undefined
+ ? { executionWorkspaceSettings: data.executionWorkspaceSettings }
+ : {}),
+ }),
+ onMutate: ({ id }) => {
+ setRunningRoutineId(id);
+ },
+ onSuccess: async (_, { id }) => {
+ setRunDialogRoutine(null);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.detail(id) }),
+ ]);
+ },
+ onSettled: () => {
+ setRunningRoutineId(null);
+ },
+ onError: (mutationError) => {
+ pushToast({
+ title: "Routine run failed",
+ body: mutationError instanceof Error ? mutationError.message : "Paperclip could not start the routine run.",
+ tone: "error",
+ });
+ },
+ });
+
+ const recentAssigneeIds = useMemo(() => getRecentAssigneeIds(), [composerOpen]);
+ const recentProjectIds = useMemo(() => getRecentProjectIds(), [composerOpen]);
+ const assigneeOptions = useMemo<InlineEntityOption[]>(
+ () =>
+ sortAgentsByRecency(
+ (agents ?? []).filter((agent) => agent.status !== "terminated"),
+ recentAssigneeIds,
+ ).map((agent) => ({
+ id: agent.id,
+ label: agent.name,
+ searchText: `${agent.name} ${agent.role} ${agent.title ?? ""}`,
+ })),
+ [agents, recentAssigneeIds],
+ );
+ const projectOptions = useMemo<InlineEntityOption[]>(
+ () =>
+ (projects ?? []).filter((project) => !project.archivedAt).map((project) => ({
+ id: project.id,
+ label: project.name,
+ searchText: project.description ?? "",
+ })),
+ [projects],
+ );
+ const agentById = useMemo(
+ () => new Map((agents ?? []).map((agent) => [agent.id, agent])),
+ [agents],
+ );
+ const projectById = useMemo(
+ () => new Map((projects ?? []).map((project) => [project.id, project])),
+ [projects],
+ );
+ const folderById = useMemo(
+ () => new Map((routineFolders?.folders ?? []).map((folder) => [folder.id, folder])),
+ [routineFolders],
+ );
+ const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns, routineExecutionIssues), [liveRuns, routineExecutionIssues]);
+ const visibleRoutines = useMemo(
+ () => (routines ?? []).filter((routine) => routine.status !== "archived"),
+ [routines],
+ );
+ const folderFilteredRoutines = useMemo(() => {
+ if (routineViewState.groupBy !== "folder") return visibleRoutines;
+ if (folderSelection === "all") return visibleRoutines;
+ if (folderSelection === "unfiled") return visibleRoutines.filter((routine) => !routine.folderId);
+ return visibleRoutines.filter((routine) => routine.folderId === folderSelection);
+ }, [folderSelection, routineViewState.groupBy, visibleRoutines]);
+ // Rail counts reflect the page's visible scope (archived hidden), not raw DB
+ // counts (ux-spec §5.3).
+ const railFolderResult = useMemo(() => {
+ if (!routineFolders) return routineFolders;
+ const counts = new Map<string, number>();
+ let unfiled = 0;
+ for (const routine of visibleRoutines) {
+ if (routine.folderId) counts.set(routine.folderId, (counts.get(routine.folderId) ?? 0) + 1);
+ else unfiled += 1;
+ }
+ return {
+ ...routineFolders,
+ allCount: visibleRoutines.length,
+ unfiledCount: unfiled,
+ folders: routineFolders.folders.map((folder) => ({
+ ...folder,
+ itemCount: counts.get(folder.id) ?? 0,
+ })),
+ };
+ }, [routineFolders, visibleRoutines]);
+ const sortedRoutines = useMemo(
+ () => sortRoutines(folderFilteredRoutines, routineViewState.sortField, routineViewState.sortDir),
+ [folderFilteredRoutines, routineViewState.sortDir, routineViewState.sortField],
+ );
+ const routineSections = useMemo(
+ () => buildRoutineSections(sortedRoutines, routineViewState.groupBy, projectById, agentById, folderById),
+ [agentById, folderById, projectById, routineViewState.groupBy, sortedRoutines],
+ );
+ const recentRunsIssueLinkState = useMemo(
+ () =>
+ createIssueDetailLocationState(
+ "Recent Runs",
+ buildRoutinesTabHref("runs"),
+ "issues",
+ ),
+ [],
+ );
+ const currentAssignee = draft.assigneeAgentId ? agentById.get(draft.assigneeAgentId) ?? null : null;
+ const currentProject = draft.projectId ? projectById.get(draft.projectId) ?? null : null;
+ const activeFolder = selectedFolderFromList(routineFolders?.folders ?? [], folderSelection);
+ const hasRoutineFolders = (routineFolders?.folders.length ?? 0) > 0;
+ const showFolderRail = activeTab === "routines" && routineViewState.groupBy === "folder" && hasRoutineFolders;
+
+ function updateRoutineView(patch: Partial<RoutineViewState>) {
+ setRoutineViewState((current) => {
+ const next = { ...current, ...patch };
+ saveRoutineViewState(routineViewStateKey, next);
+ return next;
+ });
+ }
+
+ function handleTabChange(tab: string) {
+ const nextTab = tab === "runs" ? "runs" : "routines";
+ startTransition(() => {
+ navigate(buildRoutinesTabHref(nextTab));
+ });
+ }
+
+ function setFolderSelection(selection: FolderSelection) {
+ setSearchParams((current) => {
+ const params = new URLSearchParams(current);
+ const value = folderSearchValue(selection);
+ if (value) params.set("folder", value);
+ else params.delete("folder");
+ return params;
+ });
+ }
+
+ function openCreateFolder(moveItemIds: string[] = []) {
+ setMoveAfterCreateIds(moveItemIds);
+ setFolderDialogTarget(null);
+ setFolderDialogOpen(true);
+ }
+
+ function openCreateRoutine() {
+ setDraft((current) => ({
+ ...current,
+ folderId: folderSelection === "all" || folderSelection === "unfiled" ? null : folderSelection,
+ }));
+ setComposerOpen(true);
+ }
+
+ async function moveSelectedRoutines(folderId: string | null) {
+ const ids = selectedRoutineIds;
+ if (ids.length === 0) return;
+ try {
+ await Promise.all(ids.map((itemId) => foldersApi.moveItem(selectedCompanyId!, { kind: "routine", itemId, folderId })));
+ setSelectedRoutineIds([]);
+ setSelectMode(false);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.routines.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.folders.list(selectedCompanyId!, "routine") }),
+ ]);
+ pushToast({ title: "Routines moved", body: `${ids.length} routine${ids.length === 1 ? "" : "s"} filed.`, tone: "success" });
+ } catch (moveError) {
+ pushToast({
+ title: "Failed to move routines",
+ body: moveError instanceof Error ? moveError.message : "Paperclip could not move the selected routines.",
+ tone: "error",
+ });
+ }
+ }
+
+ function handleRunNow(routine: RoutineListItem) {
+ setRunDialogRoutine(routine);
+ }
+
+ function handleToggleEnabled(routine: RoutineListItem, enabled: boolean) {
+ if (!enabled && !routine.assigneeAgentId) {
+ pushToast({
+ title: "Default agent required",
+ body: "Set a default agent before enabling routine automation.",
+ tone: "warn",
+ });
+ return;
+ }
+ updateRoutineStatus.mutate({
+ id: routine.id,
+ status: nextRoutineStatus(routine.status, !enabled),
+ });
+ }
+
+ function handleToggleArchived(routine: RoutineListItem) {
+ updateRoutineStatus.mutate({
+ id: routine.id,
+ status: routine.status === "archived" ? "active" : "archived",
+ });
+ }
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={Repeat} message="Select a company to view routines." />;
+ }
+
+ if (isLoading) {
+ return <PageSkeleton variant="issues-list" />;
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
+ <div className="space-y-1">
+ <h1 className="text-2xl font-semibold tracking-tight">
+ Routines
+ </h1>
+ <p className="text-sm text-muted-foreground">
+ Recurring work definitions that materialize into auditable execution tasks.
+ </p>
+ </div>
+ <Button onClick={openCreateRoutine}>
+ <Plus className="mr-2 h-4 w-4" />
+ Create routine
+ </Button>
+ </div>
+
+ <Tabs value={activeTab} onValueChange={handleTabChange}>
+ <PageTabBar
+ align="start"
+ value={activeTab}
+ onValueChange={handleTabChange}
+ items={[
+ { value: "routines", label: "Routines" },
+ { value: "runs", label: "Recent Runs" },
+ ]}
+ />
+ <TabsContent value="routines" className="space-y-4">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm text-muted-foreground">
+ {visibleRoutines.length} routine{visibleRoutines.length === 1 ? "" : "s"}
+ </p>
+ <div className="flex items-center gap-1">
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="sm" className="text-xs" title="Sort">
+ <ArrowUpDown className="h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1" />
+ <span className="hidden sm:inline">Sort</span>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-44 p-0">
+ <div className="p-2 space-y-0.5">
+ {([
+ ["updated", "Updated"],
+ ["created", "Created"],
+ ["lastRun", "Last run"],
+ ["title", "Title"],
+ ] as const).map(([field, label]) => (
+ <button
+ key={field}
+ className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${
+ routineViewState.sortField === field
+ ? "bg-accent/50 text-foreground"
+ : "text-muted-foreground hover:bg-accent/50"
+ }`}
+ onClick={() => {
+ updateRoutineView(
+ routineViewState.sortField === field
+ ? { sortDir: routineViewState.sortDir === "asc" ? "desc" : "asc" }
+ : { sortField: field, sortDir: field === "title" ? "asc" : "desc" },
+ );
+ }}
+ >
+ <span>{label}</span>
+ {routineViewState.sortField === field ? (
+ <span className="text-xs text-muted-foreground">
+ {routineViewState.sortDir === "asc" ? "Asc" : "Desc"}
+ </span>
+ ) : null}
+ </button>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="sm" className="text-xs" title="Group">
+ <Layers className="h-3.5 w-3.5 sm:h-3 sm:w-3 sm:mr-1" />
+ <span className="hidden sm:inline">Group</span>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-44 p-0">
+ <div className="p-2 space-y-0.5">
+ {([
+ ["folder", "Folder"],
+ ["project", "Project"],
+ ["assignee", "Agent"],
+ ["none", "None"],
+ ] as const).map(([value, label]) => (
+ <button
+ key={value}
+ className={`flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm ${
+ routineViewState.groupBy === value
+ ? "bg-accent/50 text-foreground"
+ : "text-muted-foreground hover:bg-accent/50"
+ }`}
+ onClick={() => updateRoutineView({ groupBy: value, collapsedGroups: [] })}
+ >
+ <span>{label}</span>
+ {routineViewState.groupBy === value ? <Check className="h-3.5 w-3.5" /> : null}
+ </button>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ {routineViewState.groupBy === "folder" && !hasRoutineFolders ? (
+ <Button variant="outline" size="sm" onClick={() => openCreateFolder()}>
+ <Plus className="mr-2 h-3.5 w-3.5" />
+ New folder
+ </Button>
+ ) : null}
+ {showFolderRail ? (
+ <Button variant="ghost" size="sm" className="text-xs" onClick={() => setSelectMode((current) => !current)}>
+ {selectMode ? "Done" : "Select"}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ {routineViewState.groupBy === "folder" ? (
+ <div className="md:hidden">
+ <FolderChip
+ result={railFolderResult}
+ selection={folderSelection}
+ allLabel="All routines"
+ onClick={() => setMobileFoldersOpen(true)}
+ />
+ </div>
+ ) : null}
+ </TabsContent>
+ <TabsContent value="runs">
+ <IssuesList
+ issues={routineExecutionIssues ?? []}
+ isLoading={recentRunsLoading}
+ error={recentRunsError as Error | null}
+ agents={agents}
+ projects={projects}
+ liveIssueIds={liveIssueIds}
+ viewStateKey="paperclip:routine-recent-runs-view"
+ issueLinkState={recentRunsIssueLinkState}
+ onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
+ />
+ </TabsContent>
+ </Tabs>
+
+ <Dialog
+ open={composerOpen}
+ onOpenChange={(open) => {
+ if (!createRoutine.isPending) {
+ setComposerOpen(open);
+ }
+ }}
+ >
+ <DialogContent
+ showCloseButton={false}
+ className="flex max-h-(--sz-calc-18) max-w-3xl flex-col gap-0 overflow-hidden p-0"
+ >
+ <div className="shrink-0 flex flex-wrap items-center justify-between gap-3 border-b border-border/60 px-5 py-3">
+ <div>
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">New routine</p>
+ <p className="text-sm text-muted-foreground">
+ Define the recurring work first. Default project and agent are optional for draft routines.
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setComposerOpen(false);
+ setAdvancedOpen(false);
+ }}
+ disabled={createRoutine.isPending}
+ >
+ Cancel
+ </Button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="px-5 pt-5 pb-3">
+ <textarea
+ ref={titleInputRef}
+ className="w-full resize-none overflow-hidden bg-transparent text-xl font-semibold outline-none placeholder:text-muted-foreground/50"
+ placeholder="Routine title"
+ rows={1}
+ value={draft.title}
+ onChange={(event) => {
+ setDraft((current) => ({ ...current, title: event.target.value }));
+ autoResizeTextarea(event.target);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.metaKey && !event.ctrlKey && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ descriptionEditorRef.current?.focus();
+ return;
+ }
+ if (event.key === "Tab" && !event.shiftKey) {
+ event.preventDefault();
+ if (draft.assigneeAgentId) {
+ if (draft.projectId) {
+ descriptionEditorRef.current?.focus();
+ } else {
+ projectSelectorRef.current?.focus();
+ }
+ } else {
+ assigneeSelectorRef.current?.focus();
+ }
+ }
+ }}
+ autoFocus
+ />
+ </div>
+
+ <div className="px-5 pb-3">
+ <div className="overflow-x-auto overscroll-x-contain">
+ <div className="inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap">
+ <span>For</span>
+ <InlineEntitySelector
+ ref={assigneeSelectorRef}
+ value={draft.assigneeAgentId}
+ options={assigneeOptions}
+ recentOptionIds={recentAssigneeIds}
+ placeholder="Responsible"
+ noneLabel="No responsible"
+ searchPlaceholder="Search responsible..."
+ emptyMessage="No responsible found."
+ onChange={(assigneeAgentId) => {
+ if (assigneeAgentId) trackRecentAssignee(assigneeAgentId);
+ setDraft((current) => ({ ...current, assigneeAgentId }));
+ }}
+ onConfirm={() => {
+ if (draft.projectId) {
+ descriptionEditorRef.current?.focus();
+ } else {
+ projectSelectorRef.current?.focus();
+ }
+ }}
+ renderTriggerValue={(option) =>
+ option ? (
+ currentAssignee ? (
+ <>
+ <AgentIcon icon={currentAssignee.icon} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{option.label}</span>
+ </>
+ ) : (
+ <span className="truncate">{option.label}</span>
+ )
+ ) : (
+ <span className="text-muted-foreground">Responsible</span>
+ )
+ }
+ renderOption={(option) => {
+ if (!option.id) return <span className="truncate">{option.label}</span>;
+ const assignee = agentById.get(option.id);
+ return (
+ <>
+ {assignee ? <AgentIcon icon={assignee.icon} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : null}
+ <span className="truncate">{option.label}</span>
+ </>
+ );
+ }}
+ />
+ <span>in</span>
+ <InlineEntitySelector
+ ref={projectSelectorRef}
+ value={draft.projectId}
+ options={projectOptions}
+ recentOptionIds={recentProjectIds}
+ placeholder="Project"
+ noneLabel="No project"
+ searchPlaceholder="Search projects..."
+ emptyMessage="No projects found."
+ onChange={(projectId) => {
+ if (projectId) trackRecentProject(projectId);
+ setDraft((current) => ({ ...current, projectId }));
+ }}
+ onConfirm={() => descriptionEditorRef.current?.focus()}
+ renderTriggerValue={(option) =>
+ option && currentProject ? (
+ <>
+ <span
+ className="h-3.5 w-3.5 shrink-0 rounded-sm"
+ style={{ backgroundColor: currentProject.color ?? "var(--project-none)" }}
+ />
+ <span className="truncate">{option.label}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">Project</span>
+ )
+ }
+ renderOption={(option) => {
+ if (!option.id) return <span className="truncate">{option.label}</span>;
+ const project = projectById.get(option.id);
+ return (
+ <>
+ <span
+ className="h-3.5 w-3.5 shrink-0 rounded-sm"
+ style={{ backgroundColor: project?.color ?? "var(--project-none)" }}
+ />
+ <span className="truncate">{option.label}</span>
+ </>
+ );
+ }}
+ />
+ <span>filed in</span>
+ <Select
+ value={draft.folderId ?? "__unfiled"}
+ onValueChange={(value) => setDraft((current) => ({
+ ...current,
+ folderId: value === "__unfiled" ? null : value,
+ }))}
+ >
+ <SelectTrigger className="h-8 w-auto min-w-32 border-0 bg-muted/50 px-2 shadow-none">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="__unfiled">Unfiled</SelectItem>
+ {(routineFolders?.folders ?? []).map((folder) => (
+ <SelectItem key={folder.id} value={folder.id}>
+ {folder.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ </div>
+
+ <div className="border-t border-border/60 px-5 py-4">
+ <MarkdownEditor
+ ref={descriptionEditorRef}
+ value={draft.description}
+ onChange={(description) => setDraft((current) => ({ ...current, description }))}
+ placeholder="Add instructions..."
+ bordered={false}
+ contentClassName="min-h-(--sz-160px) text-sm text-muted-foreground"
+ mentions={mentionOptions}
+ onSubmit={() => {
+ if (!createRoutine.isPending && draft.title.trim() && draft.projectId && draft.assigneeAgentId) {
+ createRoutine.mutate();
+ }
+ }}
+ />
+ </div>
+
+ <div className="border-t border-border/60 px-5 py-3">
+ <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
+ <CollapsibleTrigger className="flex w-full items-center justify-between text-left">
+ <div>
+ <p className="text-sm font-medium">Advanced delivery settings</p>
+ <p className="text-sm text-muted-foreground">Keep policy controls secondary to the work definition.</p>
+ </div>
+ {advancedOpen ? <ChevronDown className="h-4 w-4 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 text-muted-foreground" />}
+ </CollapsibleTrigger>
+ <CollapsibleContent className="pt-3">
+ <div className="grid gap-4 md:grid-cols-2">
+ <div className="space-y-2">
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">Concurrency</p>
+ <Select
+ value={draft.concurrencyPolicy}
+ onValueChange={(concurrencyPolicy) => setDraft((current) => ({ ...current, concurrencyPolicy }))}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {concurrencyPolicies.map((value) => (
+ <SelectItem key={value} value={value}>{value.replaceAll("_", " ")}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">{concurrencyPolicyDescriptions[draft.concurrencyPolicy]}</p>
+ </div>
+ <div className="space-y-2">
+ <p className="text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground">Catch-up</p>
+ <Select
+ value={draft.catchUpPolicy}
+ onValueChange={(catchUpPolicy) => setDraft((current) => ({ ...current, catchUpPolicy }))}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {catchUpPolicies.map((value) => (
+ <SelectItem key={value} value={value}>{value.replaceAll("_", " ")}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">{catchUpPolicyDescriptions[draft.catchUpPolicy]}</p>
+ </div>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ </div>
+
+ <div className="shrink-0 flex flex-col gap-3 border-t border-border/60 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
+ <div className="text-sm text-muted-foreground">
+ After creation, Paperclip takes you straight to trigger setup. Draft routines stay paused until you add a default agent.
+ </div>
+ <div className="flex flex-col gap-2 sm:items-end">
+ <Button
+ onClick={() => createRoutine.mutate()}
+ disabled={
+ createRoutine.isPending ||
+ !draft.title.trim()
+ }
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ {createRoutine.isPending ? "Creating..." : "Create routine"}
+ </Button>
+ {createRoutine.isError ? (
+ <p className="text-sm text-destructive">
+ {createRoutine.error instanceof Error ? createRoutine.error.message : "Failed to create routine"}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {error ? (
+ <Card>
+ <CardContent className="pt-6 text-sm text-destructive">
+ {error instanceof Error ? error.message : "Failed to load routines"}
+ </CardContent>
+ </Card>
+ ) : null}
+
+ {activeTab === "routines" ? (
+ <div className={cn(showFolderRail && "flex gap-4")}>
+ {showFolderRail ? (
+ <FolderRail
+ result={railFolderResult}
+ selection={folderSelection}
+ allLabel="All routines"
+ itemLabelPlural="routines"
+ loading={foldersLoading}
+ onSelect={setFolderSelection}
+ onCreate={() => openCreateFolder()}
+ onRename={(folder, name) => updateFolder.mutate({ folderId: folder.id, payload: { name } })}
+ onEdit={(folder) => {
+ setFolderDialogTarget(folder);
+ setFolderDialogOpen(true);
+ }}
+ onDelete={setDeleteFolderTarget}
+ />
+ ) : null}
+ <div className="min-w-0 flex-1">
+ {routineViewState.groupBy === "folder" && hasRoutineFolders ? (
+ <div className="mb-3 flex flex-wrap items-center gap-2">
+ {folderSelection === "all" ? <FolderIconHeader label="All routines" count={sortedRoutines.length} /> : (
+ <div className="flex min-w-0 items-center gap-2 text-sm">
+ <FolderSwatch color={activeFolder?.color} />
+ <span className="truncate font-medium">{folderSelection === "unfiled" ? "Unfiled" : activeFolder?.name ?? "Folder"}</span>
+ <span className="text-muted-foreground">{sortedRoutines.length} routine{sortedRoutines.length === 1 ? "" : "s"}</span>
+ </div>
+ )}
+ </div>
+ ) : null}
+ {routineViewState.groupBy === "folder" && !hasRoutineFolders && !foldersLoading && visibleRoutines.length > 0 ? (
+ <AllUnfiledBanner
+ storageKey={`paperclip:routines-folder-nudge:${selectedCompanyId ?? "none"}`}
+ itemLabelPlural="routines"
+ onCreateFolder={() => openCreateFolder()}
+ />
+ ) : null}
+ {selectMode ? (
+ <BulkBar
+ selectedCount={selectedRoutineIds.length}
+ folders={routineFolders?.folders ?? []}
+ onMove={(folderId) => void moveSelectedRoutines(folderId)}
+ onCreateAndMove={() => openCreateFolder(selectedRoutineIds)}
+ onClear={() => setSelectedRoutineIds([])}
+ onDone={() => {
+ setSelectMode(false);
+ setSelectedRoutineIds([]);
+ }}
+ />
+ ) : null}
+ {visibleRoutines.length === 0 ? (
+ <div className="py-12">
+ <EmptyState
+ icon={Repeat}
+ message="No active routines. Use Create routine to define the first recurring workflow."
+ />
+ </div>
+ ) : sortedRoutines.length === 0 ? (
+ <div className="py-12">
+ <EmptyState
+ icon={Repeat}
+ message={folderSelection === "all" ? "No routines match this view." : "This folder is empty."}
+ />
+ {folderSelection !== "all" ? (
+ <div className="mt-3 flex justify-center">
+ <Button size="sm" onClick={openCreateRoutine}>
+ <Plus className="mr-2 h-3.5 w-3.5" />
+ New routine in this folder
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3">
+ {routineSections.map((group) => {
+ const isOpen = !routineViewState.collapsedGroups.includes(group.key);
+ return (
+ <Collapsible
+ key={group.key}
+ open={isOpen}
+ onOpenChange={(open) => {
+ updateRoutineView({
+ collapsedGroups: open
+ ? routineViewState.collapsedGroups.filter((item) => item !== group.key)
+ : [...routineViewState.collapsedGroups, group.key],
+ });
+ }}
+ >
+ {group.label ? (
+ <RoutineSectionHeader
+ label={group.label}
+ count={group.items.length}
+ isOpen={isOpen}
+ />
+ ) : null}
+ <CollapsibleContent>
+ {group.items.map((routine) => (
+ <RoutineListRow
+ key={routine.id}
+ routine={routine}
+ projectById={projectById}
+ agentById={agentById}
+ runningRoutineId={runningRoutineId}
+ statusMutationRoutineId={statusMutationRoutineId}
+ href={`/routines/${routine.id}`}
+ runNowButton
+ divider={false}
+ onRunNow={handleRunNow}
+ onToggleEnabled={handleToggleEnabled}
+ onToggleArchived={handleToggleArchived}
+ selectMode={selectMode}
+ selected={selectedRoutineIds.includes(routine.id)}
+ onSelectChange={(selectedRoutine, selected) => {
+ setSelectedRoutineIds((current) =>
+ selected
+ ? Array.from(new Set([...current, selectedRoutine.id]))
+ : current.filter((id) => id !== selectedRoutine.id)
+ );
+ }}
+ extraMenuItems={
+ <MoveToMenu
+ folders={routineFolders?.folders ?? []}
+ currentFolderId={routine.folderId ?? null}
+ onMove={(folderId) => {
+ const previousFolderId = routine.folderId ?? null;
+ moveRoutineToFolder.mutate({ itemId: routine.id, folderId });
+ pushToast({
+ title: "Routine moved",
+ body: folderId
+ ? `Moved "${routine.title}" to ${routineFolders?.folders.find((folder) => folder.id === folderId)?.name ?? "folder"}.`
+ : `Moved "${routine.title}" to Unfiled.`,
+ tone: "success",
+ action: {
+ label: "Undo",
+ onClick: () => moveRoutineToFolder.mutate({ itemId: routine.id, folderId: previousFolderId }),
+ },
+ });
+ }}
+ onCreateAndMove={() => openCreateFolder([routine.id])}
+ />
+ }
+ />
+ ))}
+ </CollapsibleContent>
+ </Collapsible>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ ) : null}
+
+ <FolderFormDialog
+ open={folderDialogOpen}
+ kind="routine"
+ folder={folderDialogTarget}
+ pending={createFolder.isPending || updateFolder.isPending}
+ onOpenChange={setFolderDialogOpen}
+ onSubmit={(payload) => {
+ if (folderDialogTarget) updateFolder.mutate({ folderId: folderDialogTarget.id, payload });
+ else createFolder.mutate(payload);
+ }}
+ />
+ <DeleteFolderDialog
+ open={deleteFolderTarget !== null}
+ folder={deleteFolderTarget}
+ itemLabelPlural="routines"
+ pending={deleteFolder.isPending}
+ onOpenChange={(open) => {
+ if (!open) setDeleteFolderTarget(null);
+ }}
+ onConfirm={() => {
+ if (deleteFolderTarget) deleteFolder.mutate(deleteFolderTarget.id);
+ }}
+ />
+ <MobileFolderSheet
+ open={mobileFoldersOpen}
+ onOpenChange={setMobileFoldersOpen}
+ result={railFolderResult}
+ selection={folderSelection}
+ allLabel="All routines"
+ itemLabelPlural="Routines"
+ onSelect={setFolderSelection}
+ onCreate={() => openCreateFolder()}
+ />
+
+ <RoutineRunVariablesDialog
+ open={runDialogRoutine !== null}
+ onOpenChange={(next) => {
+ if (!next) setRunDialogRoutine(null);
+ }}
+ companyId={selectedCompanyId}
+ routineName={runDialogRoutine?.title ?? null}
+ agents={agents ?? []}
+ projects={projects ?? []}
+ defaultProjectId={runDialogRoutine?.projectId ?? null}
+ defaultAssigneeAgentId={runDialogRoutine?.assigneeAgentId ?? null}
+ variables={runDialogRoutine?.variables ?? []}
+ isPending={runRoutine.isPending}
+ onSubmit={(data) => {
+ if (!runDialogRoutine) return;
+ runRoutine.mutate({ id: runDialogRoutine.id, data });
+ }}
+ />
+ </div>
+ );
+}
+
+function FolderIconHeader({ label, count }: { label: string; count: number }) {
+ return (
+ <div className="flex min-w-0 items-center gap-2 text-sm">
+ <Repeat className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="truncate font-medium">{label}</span>
+ <span className="text-muted-foreground">{count} routine{count === 1 ? "" : "s"}</span>
+ </div>
+ );
+}
diff --git a/ui/src/pages/Routines.test.tsx b/ui/src/pages/Routines.test.tsx
index fdcea31bef..199839b13c 100644
--- a/ui/src/pages/Routines.test.tsx
+++ b/ui/src/pages/Routines.test.tsx
@@ -29,6 +29,7 @@ const issuesListRenderMock = vi.fn(({ issues }: { issues: Issue[] }) => (
const inlineEntitySelectorRenderMock = vi.fn((props: { options?: Array<{ id: string }> }) => props);
vi.mock("@/lib/router", () => ({
+ Navigate: ({ to }: { to: string }) => <a data-redirect href={to}>Redirect</a>,
Link: ({ to, children, ...props }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string; children: ReactNode }) => (
<a href={to} {...props}>
{children}
@@ -677,8 +678,7 @@ describe("Routines page", () => {
});
}
- const sectionLabels = Array.from(container.querySelectorAll("span"))
- .filter((element) => element.className.includes("uppercase") && element.className.includes("tracking-wide"))
+ const sectionLabels = Array.from(container.querySelectorAll("[data-routine-section-label]"))
.map((element) => element.textContent);
expect(sectionLabels).toEqual(["RPI", "Test", "Unfiled"]);
@@ -1034,13 +1034,9 @@ describe("Routines page", () => {
});
});
- it("shows recent runs through the issues list scoped to routine execution issues", async () => {
+ it("keeps the list focused on routines and links run history to Audit", async () => {
currentSearch = "tab=runs";
routinesListMock.mockResolvedValue([createRoutine({ id: "routine-1" })]);
- issuesListMock.mockResolvedValue([
- createIssue({ id: "issue-1", title: "Routine execution A" }),
- createIssue({ id: "issue-2", title: "Routine execution B", identifier: "PAP-1001", issueNumber: 1001 }),
- ]);
const root = createRoot(container);
const queryClient = new QueryClient({
@@ -1058,13 +1054,9 @@ describe("Routines page", () => {
await flush();
});
- for (let attempts = 0; attempts < 5 && issuesListMock.mock.calls.length === 0; attempts += 1) {
- await act(async () => {
- await flush();
- });
- }
-
- expect(issuesListMock).toHaveBeenCalledWith("company-1", { originKind: "routine_execution" });
+ expect(container.querySelector('a[data-redirect][href="/activity/runs"]'))
+ .not.toBeNull();
+ expect(issuesListMock).not.toHaveBeenCalled();
await act(async () => {
root.unmount();
diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsx
index 1c93762451..e7c03b1542 100644
--- a/ui/src/pages/Routines.tsx
+++ b/ui/src/pages/Routines.tsx
@@ -1,6 +1,6 @@
import { startTransition, useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Link, useNavigate, useSearchParams } from "@/lib/router";
+import { Link, Navigate, useNavigate, useSearchParams } from "@/lib/router";
import { ArrowUpDown, Check, ChevronDown, ChevronRight, Layers, Plus, Repeat } from "lucide-react";
import { routinesApi } from "../api/routines";
import { foldersApi } from "../api/folders";
@@ -20,7 +20,6 @@ import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";
import { collectLiveIssueIds } from "../lib/liveIssueIds";
import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
import { getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";
-import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
import { EmptyState } from "../components/EmptyState";
import { IssuesList } from "../components/IssuesList";
import { PageSkeleton } from "../components/PageSkeleton";
@@ -46,9 +45,13 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
-import { Tabs, TabsContent } from "@/components/ui/tabs";
+import { auditSectionHref } from "./audit/audit-navigation";
+import { routineDetailHref } from "../components/RoutineContextualSidebar";
+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";
+import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
import type { RoutineListItem, RoutineVariable } from "@paperclipai/shared";
import type { FolderListItem } from "@paperclipai/shared";
+import { Tabs } from "@/components/ui/tabs";
import {
AllUnfiledBanner,
BulkBar,
@@ -83,8 +86,8 @@ function autoResizeTextarea(element: HTMLTextAreaElement | null) {
element.style.height = `${element.scrollHeight}px`;
}
-type RoutinesTab = "routines" | "runs";
type RoutineGroupBy = "folder" | "none" | "project" | "assignee";
+type RoutinesTab = "routines" | "runs";
type RoutineSortField = "updated" | "created" | "title" | "lastRun";
type RoutineSortDir = "asc" | "desc";
@@ -284,28 +287,20 @@ export function sortRoutines(
});
}
-function buildRoutinesTabHref(tab: RoutinesTab) {
- return tab === "runs" ? "/routines?tab=runs" : "/routines";
-}
-
function RoutineSectionHeader({
label,
count,
- isOpen,
+ isOpen: _isOpen,
}: {
label: string;
count: number;
isOpen: boolean;
}) {
return (
- <div
- className={`flex items-center gap-2 rounded-lg border border-border px-3 py-2${
- isOpen ? " mb-1" : ""
- }`}
- >
+ <div className="flex items-center gap-2 px-2 py-1.5">
<CollapsibleTrigger className="flex items-center gap-1.5">
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform [[data-state=open]>&]:rotate-90" />
- <span className="text-sm font-semibold uppercase tracking-wide">
+ <span data-routine-section-label className="text-sm font-medium">
{label}
</span>
</CollapsibleTrigger>
@@ -339,7 +334,9 @@ export function Routines() {
const [runDialogRoutine, setRunDialogRoutine] = useState<RoutineListItem | null>(null);
const [composerOpen, setComposerOpen] = useState(false);
const [advancedOpen, setAdvancedOpen] = useState(false);
- const activeTab: RoutinesTab = searchParams.get("tab") === "runs" ? "runs" : "routines";
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
+ const legacyRunsRequested = searchParams.get("tab") === "runs";
+ const activeTab: RoutinesTab = !streamlinedUiEnabled && legacyRunsRequested ? "runs" : "routines";
const [draft, setDraft] = useState<{
title: string;
description: string;
@@ -383,7 +380,7 @@ export function Routines() {
const { data: routineFolders, isLoading: foldersLoading } = useQuery({
queryKey: queryKeys.folders.list(selectedCompanyId!, "routine"),
queryFn: () => foldersApi.list(selectedCompanyId!, "routine"),
- enabled: !!selectedCompanyId && activeTab === "routines",
+ enabled: !!selectedCompanyId,
});
const { data: agents } = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId!),
@@ -403,15 +400,14 @@ export function Routines() {
const { data: routineExecutionIssues, isLoading: recentRunsLoading, error: recentRunsError } = useQuery({
queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"],
queryFn: () => issuesApi.list(selectedCompanyId!, { originKind: "routine_execution" }),
- enabled: !!selectedCompanyId && activeTab === "runs",
+ enabled: !!selectedCompanyId && !streamlinedUiEnabled && activeTab === "runs",
});
const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);
const sharedLiveRuns = useSharedPollingQuery({
companyId: selectedCompanyId,
resourceKey: "live-runs",
queryKey: liveRunsQueryKey,
- enabled: !!selectedCompanyId && activeTab === "runs",
- // Event-sourced via LiveUpdatesProvider (GitHub issue 9627); no interval poll needed.
+ enabled: !!selectedCompanyId && !streamlinedUiEnabled && activeTab === "runs",
refetchInterval: false,
leaderOnly: true,
});
@@ -422,7 +418,6 @@ export function Routines() {
refetchInterval: sharedLiveRuns.refetchInterval,
});
usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);
-
useEffect(() => {
autoResizeTextarea(titleInputRef.current);
}, [draft.title, composerOpen]);
@@ -460,7 +455,7 @@ export function Routines() {
: "Draft saved. Add a default agent before enabling automation.",
tone: "success",
});
- navigate(`/routines/${routine.id}?tab=triggers`);
+ navigate(routineDetailHref(routine.id, "triggers"));
},
});
const createFolder = useMutation({
@@ -554,14 +549,6 @@ export function Routines() {
});
},
});
- const updateIssue = useMutation({
- mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
- issuesApi.update(id, data),
- onSuccess: async () => {
- await queryClient.invalidateQueries({ queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"] });
- },
- });
-
const updateRoutineStatus = useMutation({
mutationFn: ({ id, status }: { id: string; status: string }) => routinesApi.update(id, { status }),
onMutate: ({ id }) => {
@@ -655,11 +642,33 @@ export function Routines() {
() => new Map((routineFolders?.folders ?? []).map((folder) => [folder.id, folder])),
[routineFolders],
);
- const liveIssueIds = useMemo(() => collectLiveIssueIds(liveRuns, routineExecutionIssues), [liveRuns, routineExecutionIssues]);
const visibleRoutines = useMemo(
() => (routines ?? []).filter((routine) => routine.status !== "archived"),
[routines],
);
+ const liveIssueIds = useMemo(
+ () => collectLiveIssueIds(liveRuns, routineExecutionIssues),
+ [liveRuns, routineExecutionIssues],
+ );
+ const recentRunsIssueLinkState = useMemo(
+ () => createIssueDetailLocationState("Recent Runs", "/routines?tab=runs", "issues"),
+ [],
+ );
+ const updateIssue = useMutation({
+ mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) => issuesApi.update(id, data),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"],
+ });
+ },
+ });
+
+ function handleLegacyTabChange(tab: string) {
+ const nextTab: RoutinesTab = tab === "runs" ? "runs" : "routines";
+ startTransition(() => {
+ navigate(nextTab === "runs" ? "/routines?tab=runs" : "/routines");
+ });
+ }
const folderFilteredRoutines = useMemo(() => {
if (routineViewState.groupBy !== "folder") return visibleRoutines;
if (folderSelection === "all") return visibleRoutines;
@@ -694,20 +703,11 @@ export function Routines() {
() => buildRoutineSections(sortedRoutines, routineViewState.groupBy, projectById, agentById, folderById),
[agentById, folderById, projectById, routineViewState.groupBy, sortedRoutines],
);
- const recentRunsIssueLinkState = useMemo(
- () =>
- createIssueDetailLocationState(
- "Recent Runs",
- buildRoutinesTabHref("runs"),
- "issues",
- ),
- [],
- );
const currentAssignee = draft.assigneeAgentId ? agentById.get(draft.assigneeAgentId) ?? null : null;
const currentProject = draft.projectId ? projectById.get(draft.projectId) ?? null : null;
const activeFolder = selectedFolderFromList(routineFolders?.folders ?? [], folderSelection);
const hasRoutineFolders = (routineFolders?.folders.length ?? 0) > 0;
- const showFolderRail = activeTab === "routines" && routineViewState.groupBy === "folder" && hasRoutineFolders;
+ const showFolderRail = routineViewState.groupBy === "folder" && hasRoutineFolders;
function updateRoutineView(patch: Partial<RoutineViewState>) {
setRoutineViewState((current) => {
@@ -717,13 +717,6 @@ export function Routines() {
});
}
- function handleTabChange(tab: string) {
- const nextTab = tab === "runs" ? "runs" : "routines";
- startTransition(() => {
- navigate(buildRoutinesTabHref(nextTab));
- });
- }
-
function setFolderSelection(selection: FolderSelection) {
setSearchParams((current) => {
const params = new URLSearchParams(current);
@@ -799,43 +792,97 @@ export function Routines() {
return <EmptyState icon={Repeat} message="Select an organization to view routines." />;
}
+ if (streamlinedUiEnabled && legacyRunsRequested) {
+ return <Navigate to={auditSectionHref("runs", {})} replace />;
+ }
+
if (isLoading) {
return <PageSkeleton variant="issues-list" />;
}
+ if (!streamlinedUiEnabled && activeTab === "runs") {
+ return (
+ <div className="space-y-6">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
+ <div className="space-y-1">
+ <h1 className="text-2xl font-semibold tracking-tight">Routines</h1>
+ <p className="text-sm text-muted-foreground">
+ Recurring work definitions that materialize into auditable execution tasks.
+ </p>
+ </div>
+ <Button onClick={openCreateRoutine}>
+ <Plus className="mr-2 h-4 w-4" />
+ Create routine
+ </Button>
+ </div>
+ <Tabs value={activeTab} onValueChange={handleLegacyTabChange}>
+ <PageTabBar
+ align="start"
+ value={activeTab}
+ onValueChange={handleLegacyTabChange}
+ items={[
+ { value: "routines", label: "Routines" },
+ { value: "runs", label: "Recent Runs" },
+ ]}
+ />
+ </Tabs>
+ <IssuesList
+ issues={routineExecutionIssues ?? []}
+ isLoading={recentRunsLoading}
+ error={recentRunsError as Error | null}
+ agents={agents}
+ projects={projects}
+ liveIssueIds={liveIssueIds}
+ viewStateKey="paperclip:routine-recent-runs-view"
+ issueLinkState={recentRunsIssueLinkState}
+ onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
+ />
+ </div>
+ );
+ }
+
return (
<div className="space-y-6">
- <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="space-y-1">
- <h1 className="text-2xl font-semibold tracking-tight">
- Routines
- </h1>
+ <h1 className="text-xl font-bold">Routines</h1>
<p className="text-sm text-muted-foreground">
Recurring work definitions that materialize into auditable execution tasks.
</p>
</div>
- <Button onClick={openCreateRoutine}>
- <Plus className="mr-2 h-4 w-4" />
- Create routine
- </Button>
+ <div className="flex items-center gap-2">
+ {streamlinedUiEnabled ? (
+ <Button variant="outline" asChild>
+ <Link to={auditSectionHref("runs", {})}>View all runs</Link>
+ </Button>
+ ) : null}
+ <Button onClick={openCreateRoutine}>
+ <Plus className="mr-2 h-4 w-4" />
+ Create routine
+ </Button>
+ </div>
</div>
- <Tabs value={activeTab} onValueChange={handleTabChange}>
- <PageTabBar
- align="start"
- value={activeTab}
- onValueChange={handleTabChange}
- items={[
- { value: "routines", label: "Routines" },
- { value: "runs", label: "Recent Runs" },
- ]}
- />
- <TabsContent value="routines" className="space-y-4">
- <div className="flex items-center justify-between gap-3">
- <p className="text-sm text-muted-foreground">
- {visibleRoutines.length} routine{visibleRoutines.length === 1 ? "" : "s"}
- </p>
- <div className="flex items-center gap-1">
+ {!streamlinedUiEnabled ? (
+ <Tabs value={activeTab} onValueChange={handleLegacyTabChange}>
+ <PageTabBar
+ align="start"
+ value={activeTab}
+ onValueChange={handleLegacyTabChange}
+ items={[
+ { value: "routines", label: "Routines" },
+ { value: "runs", label: "Recent Runs" },
+ ]}
+ />
+ </Tabs>
+ ) : null}
+
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm text-muted-foreground">
+ {visibleRoutines.length} routine{visibleRoutines.length === 1 ? "" : "s"}
+ </p>
+ <div className="flex items-center gap-1">
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="text-xs" title="Sort">
@@ -919,33 +966,19 @@ export function Routines() {
{selectMode ? "Done" : "Select"}
</Button>
) : null}
- </div>
</div>
- {routineViewState.groupBy === "folder" ? (
- <div className="md:hidden">
- <FolderChip
- result={railFolderResult}
- selection={folderSelection}
- allLabel="All routines"
- onClick={() => setMobileFoldersOpen(true)}
- />
- </div>
- ) : null}
- </TabsContent>
- <TabsContent value="runs">
- <IssuesList
- issues={routineExecutionIssues ?? []}
- isLoading={recentRunsLoading}
- error={recentRunsError as Error | null}
- agents={agents}
- projects={projects}
- liveIssueIds={liveIssueIds}
- viewStateKey="paperclip:routine-recent-runs-view"
- issueLinkState={recentRunsIssueLinkState}
- onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
- />
- </TabsContent>
- </Tabs>
+ </div>
+ {routineViewState.groupBy === "folder" ? (
+ <div className="md:hidden">
+ <FolderChip
+ result={railFolderResult}
+ selection={folderSelection}
+ allLabel="All routines"
+ onClick={() => setMobileFoldersOpen(true)}
+ />
+ </div>
+ ) : null}
+ </div>
<Dialog
open={composerOpen}
@@ -1230,8 +1263,7 @@ export function Routines() {
</Card>
) : null}
- {activeTab === "routines" ? (
- <div className={cn(showFolderRail && "flex gap-4")}>
+ <div className={cn(showFolderRail && "flex gap-4")}>
{showFolderRail ? (
<FolderRail
result={railFolderResult}
@@ -1382,7 +1414,6 @@ export function Routines() {
)}
</div>
</div>
- ) : null}
<FolderFormDialog
open={folderDialogOpen}
diff --git a/ui/src/pages/Timeline.test.tsx b/ui/src/pages/Timeline.test.tsx
index 22d7e32bd6..7236793b88 100644
--- a/ui/src/pages/Timeline.test.tsx
+++ b/ui/src/pages/Timeline.test.tsx
@@ -11,6 +11,7 @@ const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
const mockWorkTimelineApi = vi.hoisted(() => ({
get: vi.fn(),
}));
+const mockLocation = vi.hoisted(() => ({ search: "" }));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-1" }),
@@ -25,7 +26,7 @@ vi.mock("@/api/workTimeline", () => ({
}));
vi.mock("@/lib/router", () => ({
- useLocation: () => ({ pathname: "/PAP/timeline" }),
+ useLocation: () => ({ pathname: "/PAP/timeline", search: mockLocation.search }),
}));
vi.mock("@/components/RequestCollapsedSidebar", () => ({
@@ -130,6 +131,7 @@ describe("Timeline", () => {
defaultOptions: { queries: { retry: false } },
});
mockWorkTimelineApi.get.mockResolvedValue(emptyTimeline);
+ mockLocation.search = "";
});
afterEach(() => {
@@ -156,6 +158,27 @@ describe("Timeline", () => {
expect(container.querySelector('[data-testid="request-collapsed-sidebar"]')).not.toBeNull();
});
+ it("applies project scope from the project Timeline control", async () => {
+ mockLocation.search = "?projectId=11111111-1111-4111-8111-111111111111";
+ root = createRoot(container);
+
+ flushSync(() => {
+ root?.render(
+ <QueryClientProvider client={queryClient}>
+ <Timeline />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ expect(container.textContent).toContain("Project Timeline");
+ expect(mockWorkTimelineApi.get).toHaveBeenCalledWith(
+ "company-1",
+ expect.objectContaining({ projectId: "11111111-1111-4111-8111-111111111111" }),
+ expect.anything(),
+ );
+ });
+
it("renders range controls plus icon zoom controls without the user lens selector or visible-duration readout", async () => {
root = createRoot(container);
diff --git a/ui/src/pages/Timeline.tsx b/ui/src/pages/Timeline.tsx
index 1957742740..125a347ca6 100644
--- a/ui/src/pages/Timeline.tsx
+++ b/ui/src/pages/Timeline.tsx
@@ -30,6 +30,8 @@ import {
} from "@/components/timeline/WorkTimelineChart";
import { formatDuration, TIMELINE_COLORS } from "@/lib/timeline/layout";
import { cn } from "@/lib/utils";
+import { useLocation } from "@/lib/router";
+import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled";
type RangePreset = "today" | "7d" | "30d" | "custom";
const TIMELINE_PAGE_LIMIT = 500;
@@ -302,9 +304,15 @@ function TimelineSummaryStats({
);
}
-export function Timeline() {
+export function Timeline({ embedded = false }: { embedded?: boolean } = {}) {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
+ const location = useLocation();
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
+ const scopedProjectId = useMemo(
+ () => streamlinedUiEnabled ? new URLSearchParams(location.search).get("projectId") || undefined : undefined,
+ [location.search, streamlinedUiEnabled],
+ );
const [zoom, setZoom] = useState<ZoomLevel>("day");
const [zoomScale, setZoomScale] = useState<number | undefined>(undefined);
const zoomTouched = useRef(false);
@@ -313,18 +321,20 @@ export function Timeline() {
const [visibleWindow, setVisibleWindow] = useState<VisibleTimelineWindow | null>(null);
useEffect(() => {
- setBreadcrumbs([{ label: "Timeline" }]);
- }, [setBreadcrumbs]);
+ if (!embedded) {
+ setBreadcrumbs([{ label: scopedProjectId ? "Project Timeline" : "Timeline" }]);
+ }
+ }, [embedded, scopedProjectId, setBreadcrumbs]);
const dateRangeError = rangeError(dateRange);
const params: WorkTimelineParams | null = useMemo(() => {
const window = rangeWindow(dateRange);
if (!window) return null;
- return window;
- }, [dateRange]);
+ return scopedProjectId ? { ...window, projectId: scopedProjectId } : window;
+ }, [dateRange, scopedProjectId]);
const { data, isLoading, error } = useQuery({
- queryKey: [...queryKeys.workTimeline(selectedCompanyId ?? ""), dateRange.fromDate, dateRange.toDate],
+ queryKey: [...queryKeys.workTimeline(selectedCompanyId ?? ""), dateRange.fromDate, dateRange.toDate, scopedProjectId ?? null],
queryFn: ({ signal }) => loadTimelineWindow(selectedCompanyId!, params!, signal),
enabled: !!selectedCompanyId && !!params,
});
@@ -351,7 +361,7 @@ export function Timeline() {
if (!selectedCompanyId) {
return (
<>
- <RequestCollapsedSidebar />
+ {!embedded && <RequestCollapsedSidebar />}
<EmptyState icon={GanttChartSquare} message="Select an organization to view its work timeline." />
</>
);
@@ -360,7 +370,9 @@ export function Timeline() {
const header = (
<div className="flex items-center gap-2">
<GanttChartSquare className="h-6 w-6 text-muted-foreground" />
- <h1 className="text-3xl font-semibold tracking-tight">Work Timeline</h1>
+ <h1 className="text-3xl font-semibold tracking-tight">
+ {scopedProjectId ? "Project Timeline" : "Work Timeline"}
+ </h1>
</div>
);
@@ -463,7 +475,7 @@ export function Timeline() {
return (
<div className="space-y-6">
- <RequestCollapsedSidebar />
+ {!embedded && <RequestCollapsedSidebar />}
{header}
{toolbar}
@@ -491,7 +503,10 @@ export function Timeline() {
{data && !isLoading && !dateRangeError && (
data.spans.length === 0 ? (
<div className="space-y-3">
- <EmptyState icon={GanttChartSquare} message="No activity in this window." />
+ <EmptyState
+ icon={GanttChartSquare}
+ message={scopedProjectId ? "No project activity in this window." : "No activity in this window."}
+ />
<div className="flex flex-wrap items-center justify-end gap-3">
{rangeControls}
</div>
diff --git a/ui/src/pages/audit/AuditFeed.production.tsx b/ui/src/pages/audit/AuditFeed.production.tsx
new file mode 100644
index 0000000000..94426bfcda
--- /dev/null
+++ b/ui/src/pages/audit/AuditFeed.production.tsx
@@ -0,0 +1,655 @@
+import { useEffect, useMemo, useState } from "react";
+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import { Download, ScrollText, ShieldAlert } from "lucide-react";
+import type { Agent } from "@paperclipai/shared";
+import { Link } from "@/lib/router";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { Identity } from "@/components/Identity";
+import { AgentIcon } from "@/components/AgentIconPicker";
+import { cn, relativeTime } from "@/lib/utils";
+import { queryKeys } from "@/lib/queryKeys";
+import { formatActivityVerb } from "@/lib/activity-format";
+import { buildCompanyUserProfileMap, type CompanyUserProfile } from "@/lib/company-members";
+import { auditApi, type AuditActionRecord, type AuditActionFilters } from "@/api/audit";
+import { agentsApi } from "@/api/agents";
+import { accessApi } from "@/api/access";
+import { ApiError } from "@/api/client";
+import { useToastActions } from "@/context/ToastContext";
+
+const PAGE_SIZE = 50;
+const ALL = "__all";
+
+/** Action-domain prefixes offered in the filter (server does a prefix match). */
+const ACTION_DOMAINS: { value: string; label: string }[] = [
+ { value: ALL, label: "All actions" },
+ { value: "issue.", label: "Tasks" },
+ { value: "agent.", label: "Agents" },
+ { value: "heartbeat.", label: "Runs" },
+ { value: "approval.", label: "Approvals" },
+ { value: "project.", label: "Projects" },
+ { value: "goal.", label: "Goals" },
+ { value: "tool_gateway.", label: "Tools" },
+ { value: "cost.", label: "Costs" },
+ { value: "company.", label: "Company" },
+];
+
+/** Entity types offered in the filter (server does an exact match). */
+const ENTITY_TYPES: { value: string; label: string }[] = [
+ { value: ALL, label: "All entities" },
+ { value: "issue", label: "Task" },
+ { value: "agent", label: "Agent" },
+ { value: "project", label: "Project" },
+ { value: "goal", label: "Goal" },
+ { value: "company", label: "Company" },
+];
+
+/**
+ * Which actors the feed covers. `all` is the shared company activity view
+ * (people, agents, and the system); `agents` is the privileged agent-action
+ * audit that carries responsible-person and run attribution.
+ */
+export type AuditFeedMode = "all" | "agents";
+
+export interface AuditFeedProps {
+ companyId: string;
+ /**
+ * When set, the feed is pinned to a single agent (per-agent Audit tab) — the
+ * agent filter is hidden and every query/export carries this agentId.
+ */
+ lockedAgentId?: string;
+ /** Hide the section header/description (the AgentDetail tab supplies its own chrome). */
+ hideHeader?: boolean;
+ /**
+ * Controlled feed mode. Supplying `onModeChange` turns on the mode toggle for
+ * callers that hold `audit:view_agent_actions`; without it the feed stays in
+ * `mode` (or the all-actors default). Ignored when `lockedAgentId` is set.
+ */
+ mode?: AuditFeedMode;
+ onModeChange?: (mode: AuditFeedMode) => void;
+}
+
+function toStartIso(value: string): string | undefined {
+ if (!value) return undefined;
+ const date = new Date(`${value}T00:00:00.000Z`);
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
+}
+
+function toEndIso(value: string): string | undefined {
+ if (!value) return undefined;
+ const date = new Date(`${value}T23:59:59.999Z`);
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
+}
+
+/** Actor avatar + name — agents render their icon glyph, humans their avatar. */
+function AuditActor({
+ record,
+ agentMap,
+ userProfileMap,
+}: {
+ record: AuditActionRecord;
+ agentMap: Map<string, Agent>;
+ userProfileMap: Map<string, CompanyUserProfile>;
+}) {
+ // Agent names are company-readable through the same authorization-filtered
+ // directory used by this page. The basic audit tier strips privileged
+ // attribution (`agentId`) but retains the acting principal (`actorId`), so
+ // use that principal to avoid presenting a trivially joinable identity as
+ // an anonymous "Agent" in the UI.
+ const actorAgentId = record.agentId
+ ?? (record.actorType === "agent" ? record.actorId : null);
+ const agent = actorAgentId ? agentMap.get(actorAgentId) : null;
+ if (agent) {
+ return (
+ <span className="inline-flex min-w-0 items-center gap-1.5" title={agent.name}>
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
+ <AgentIcon icon={agent.icon} className="h-3 w-3" />
+ </span>
+ <span className="truncate font-medium text-foreground">{agent.name}</span>
+ </span>
+ );
+ }
+ if (record.actorType === "user" && record.actorId) {
+ const profile = userProfileMap.get(record.actorId);
+ return (
+ <Identity
+ name={profile?.label ?? "User"}
+ avatarUrl={profile?.image ?? null}
+ size="sm"
+ className="font-medium text-foreground"
+ />
+ );
+ }
+ // Fall back to the actor *type*, never a blanket "System". This still covers
+ // deleted or authorization-filtered agents that are absent from the directory.
+ const label =
+ record.actorType === "plugin"
+ ? "Plugin"
+ : record.actorType === "agent"
+ ? "Agent"
+ : record.actorType === "user"
+ ? "User"
+ : "System";
+ return <Identity name={label} size="sm" className="font-medium text-foreground" />;
+}
+
+/**
+ * The clickable entity node inside the humanized sentence. The verb from
+ * `formatActivityVerb` already encodes the relationship ("commented on",
+ * "created document for", …) and expects the issue reference to follow it, so
+ * this renders the task link (or a document/plain fallback) — never a phrase
+ * that would duplicate the verb.
+ */
+function AuditEntityNode({ record }: { record: AuditActionRecord }) {
+ const { issue, document } = record.entity;
+ const issueRef = issue?.identifier ?? issue?.id ?? null;
+
+ if (issueRef) {
+ return (
+ <Link to={`/issues/${issueRef}`} className="font-medium text-primary hover:underline">
+ {issue?.identifier ? `${issue.identifier}${issue.title ? ` · ${issue.title}` : ""}` : "the task"}
+ </Link>
+ );
+ }
+ if (document) {
+ return <span className="font-medium text-foreground">{document.key}</span>;
+ }
+ // Non-linkable entities (company, agent, goal, …) — show a plain descriptor.
+ return <span className="text-muted-foreground">{record.entityType}</span>;
+}
+
+function AuditRow({
+ record,
+ agentMap,
+ userProfileMap,
+}: {
+ record: AuditActionRecord;
+ agentMap: Map<string, Agent>;
+ userProfileMap: Map<string, CompanyUserProfile>;
+}) {
+ const verb = formatActivityVerb(record.action, record.details, { agentMap, userProfileMap });
+ const responsible = record.responsibleUserId ? userProfileMap.get(record.responsibleUserId) : null;
+ // Suppress the "on behalf of" chip when the human actor *is* the responsible user.
+ const showOnBehalf = Boolean(
+ record.responsibleUserId
+ && !(record.actorType === "user" && record.actorId === record.responsibleUserId),
+ );
+ const responsibleLabel = responsible?.label ?? (record.responsibleUserId ? "a user" : null);
+ const excerpt = record.entity.comment?.excerpt?.trim();
+ // Show the document key only when it isn't already the linked entity node.
+ const documentKey = record.entity.issue && record.entity.document ? record.entity.document.key : null;
+
+ return (
+ <li className="px-4 py-3 text-sm">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 space-y-1">
+ <div className="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-foreground">
+ <AuditActor record={record} agentMap={agentMap} userProfileMap={userProfileMap} />
+ <span className="text-muted-foreground">{verb}</span>
+ <AuditEntityNode record={record} />
+ </div>
+ {excerpt ? (
+ <p className="line-clamp-2 border-l-2 border-border pl-2 text-muted-foreground">
+ “{excerpt}”
+ </p>
+ ) : null}
+ {documentKey ? (
+ <p className="text-xs text-muted-foreground">
+ Document <span className="font-mono text-(length:--text-micro)">{documentKey}</span>
+ </p>
+ ) : null}
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ {showOnBehalf && responsibleLabel ? (
+ <span className="inline-flex items-center rounded-full bg-muted px-2 py-0.5">
+ on behalf of {responsibleLabel}
+ </span>
+ ) : null}
+ {record.runId && record.agentId ? (
+ <Link
+ to={`/agents/${record.agentId}/runs/${record.runId}`}
+ className="text-primary hover:underline"
+ >
+ View run
+ </Link>
+ ) : null}
+ <span className="font-mono text-(length:--text-micro) opacity-70">{record.action}</span>
+ </div>
+ </div>
+ <time
+ className="shrink-0 whitespace-nowrap text-xs text-muted-foreground"
+ dateTime={record.createdAt}
+ title={new Date(record.createdAt).toLocaleString()}
+ >
+ {relativeTime(record.createdAt)}
+ </time>
+ </div>
+ </li>
+ );
+}
+
+/** The permission-denied / upsell state shown when the caller lacks the grant. */
+function AuditUpsell() {
+ return (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-3 py-14 text-center">
+ <ShieldAlert className="h-10 w-10 text-muted-foreground/50" />
+ <div>
+ <p className="text-sm font-medium text-foreground">Agent audit is a Paperclip Enterprise view</p>
+ <p className="mx-auto mt-1 max-w-md text-sm text-muted-foreground">
+ The agent audit log gives you a searchable, exportable record of everything your agents
+ did — every comment, task change, approval, and run — with the responsible person for
+ each action. Ask an administrator to grant you the{" "}
+ <span className="font-mono text-(length:--text-micro)">audit:view_agent_actions</span>{" "}
+ permission to view it.
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+export function AuditFeed({
+ companyId,
+ lockedAgentId,
+ hideHeader,
+ mode,
+ onModeChange,
+}: AuditFeedProps) {
+ const { pushToast } = useToastActions();
+ const [agent, setAgent] = useState<string>(ALL);
+ const [responsibleUser, setResponsibleUser] = useState<string>(ALL);
+ const [actionDomain, setActionDomain] = useState<string>(ALL);
+ const [entityType, setEntityType] = useState<string>(ALL);
+ const [dateFrom, setDateFrom] = useState<string>("");
+ const [dateTo, setDateTo] = useState<string>("");
+ const [exporting, setExporting] = useState(false);
+ const [downgradeRecoveryAttempted, setDowngradeRecoveryAttempted] = useState(false);
+
+ const agents = useQuery({
+ queryKey: queryKeys.agents.list(companyId),
+ queryFn: () => agentsApi.list(companyId),
+ });
+ const userDirectory = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(companyId),
+ queryFn: () => accessApi.listUserDirectory(companyId),
+ retry: false,
+ });
+
+ const agentMap = useMemo(
+ () => new Map((agents.data ?? []).map((a) => [a.id, a])),
+ [agents.data],
+ );
+ const userProfileMap = useMemo(
+ () => buildCompanyUserProfileMap(userDirectory.data?.users),
+ [userDirectory.data],
+ );
+
+ // The per-agent tab keeps the legacy privileged scope because it always
+ // carries an attribution filter and must not silently downgrade to the basic
+ // tier. Everywhere else the mode picks the scope, defaulting to all actors.
+ const resolvedMode: AuditFeedMode = lockedAgentId ? "agents" : mode ?? "all";
+
+ const filters: AuditActionFilters = {
+ actorScope: resolvedMode,
+ agentId: lockedAgentId ?? (agent === ALL ? undefined : agent),
+ responsibleUserId: responsibleUser === ALL ? undefined : responsibleUser,
+ action: actionDomain === ALL ? undefined : actionDomain,
+ entityType: entityType === ALL ? undefined : entityType,
+ from: toStartIso(dateFrom),
+ to: toEndIso(dateTo),
+ };
+
+ const hasActiveFilters = Boolean(
+ (!lockedAgentId && agent !== ALL)
+ || responsibleUser !== ALL
+ || actionDomain !== ALL
+ || entityType !== ALL
+ || dateFrom
+ || dateTo,
+ );
+
+ const feed = useInfiniteQuery({
+ queryKey: queryKeys.audit.agentActions(companyId, {
+ actorScope: filters.actorScope,
+ agentId: filters.agentId,
+ responsibleUserId: filters.responsibleUserId,
+ action: filters.action,
+ entityType: filters.entityType,
+ from: filters.from,
+ to: filters.to,
+ }),
+ queryFn: ({ pageParam }) =>
+ auditApi.listAgentActions(companyId, { ...filters, limit: PAGE_SIZE, cursor: pageParam ?? undefined }),
+ initialPageParam: null as string | null,
+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
+ retry: (count, error) => !(error instanceof ApiError && error.status === 403) && count < 2,
+ });
+
+ const permissionDenied = feed.error instanceof ApiError && feed.error.status === 403;
+ const hasBasicPage = feed.data?.pages.some((page) => page.accessTier === "basic") ?? false;
+ const hasFullPage = feed.data?.pages.some((page) => page.accessTier === "full") ?? false;
+
+ // Once the server answers at the basic tier the caller has lost the permission
+ // that produced the privileged attribution on the pages already in the cache.
+ // Drop those pages rather than rendering revoked "on behalf of" attribution
+ // next to stripped rows — the recovery refetch below may never clear them.
+ const items = useMemo(() => {
+ const pages = feed.data?.pages ?? [];
+ const visible = hasBasicPage ? pages.filter((page) => page.accessTier !== "full") : pages;
+ return visible.flatMap((page) => page.items);
+ }, [feed.data, hasBasicPage]);
+ // Access may be revoked between cursor requests. Treat the least-privileged
+ // page as authoritative until every cached page has been fetched again.
+ const accessTier = hasBasicPage ? "basic" : feed.data?.pages[0]?.accessTier;
+ const hasMixedAccessTiers = hasBasicPage && hasFullPage;
+ const canUseAdvancedControls = lockedAgentId
+ ? true
+ : accessTier === "full";
+ // The recovery refetch below gets one shot. If it does not clear the mixed
+ // pages — it errored, or it somehow came back mixed again — the cache keeps
+ // them, so `hasMixedAccessTiers` would stay true forever. Only call the feed
+ // "recovering" while that attempt is outstanding; once it has settled, fall
+ // through to normal rendering. Otherwise the banner permanently hides the
+ // error state and its "Try again" button, with no way off the page. Falling
+ // through is safe because `items` already excludes the privileged pages, so
+ // an unrecovered cache renders as a plain basic-tier feed.
+ const downgradeRecoveryExhausted = Boolean(
+ hasMixedAccessTiers && downgradeRecoveryAttempted && !feed.isFetching,
+ );
+ const recoveringFromAccessDowngrade = Boolean(
+ !lockedAgentId
+ && !downgradeRecoveryExhausted
+ && ((permissionDenied && hasActiveFilters) || hasMixedAccessTiers),
+ );
+ // A reader without `audit:view_agent_actions` can still land on the
+ // agent-actions mode through an old `/audit` deep link. Drop them into the
+ // shared all-activity feed instead of blocking the whole page with the upsell.
+ const fallingBackToAllActivity = Boolean(
+ permissionDenied && !lockedAgentId && resolvedMode === "agents" && onModeChange,
+ );
+ // The privileged mode is only offered to callers the server already answered
+ // at the full tier — everyone else just gets the basic all-activity feed.
+ const showModeToggle = Boolean(
+ !lockedAgentId
+ && onModeChange
+ && !fallingBackToAllActivity
+ && (resolvedMode === "agents" || accessTier === "full"),
+ );
+
+ useEffect(() => {
+ if (fallingBackToAllActivity) onModeChange?.("all");
+ }, [fallingBackToAllActivity, onModeChange]);
+
+ useEffect(() => {
+ if (!lockedAgentId && (accessTier === "basic" || recoveringFromAccessDowngrade)) {
+ setAgent(ALL);
+ setResponsibleUser(ALL);
+ setActionDomain(ALL);
+ setEntityType(ALL);
+ setDateFrom("");
+ setDateTo("");
+ }
+ }, [accessTier, hasMixedAccessTiers, lockedAgentId, recoveringFromAccessDowngrade]);
+
+ // Recover from a mid-pagination downgrade with exactly one refetch. `feed`
+ // gets a new identity on every render, so an unguarded refetch here re-fires
+ // on each render and hammers the endpoint while the tiers stay mixed.
+ useEffect(() => {
+ if (!hasMixedAccessTiers) {
+ if (downgradeRecoveryAttempted) setDowngradeRecoveryAttempted(false);
+ return;
+ }
+ if (downgradeRecoveryAttempted) return;
+ setDowngradeRecoveryAttempted(true);
+ void feed.refetch();
+ }, [downgradeRecoveryAttempted, feed, hasMixedAccessTiers]);
+
+ const clearFilters = () => {
+ setAgent(ALL);
+ setResponsibleUser(ALL);
+ setActionDomain(ALL);
+ setEntityType(ALL);
+ setDateFrom("");
+ setDateTo("");
+ };
+
+ const handleExport = async () => {
+ setExporting(true);
+ try {
+ const blob = await auditApi.exportAgentActionsCsv(companyId, {
+ actorScope: filters.actorScope,
+ agentId: filters.agentId,
+ responsibleUserId: filters.responsibleUserId,
+ action: filters.action,
+ entityType: filters.entityType,
+ from: filters.from,
+ to: filters.to,
+ });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `${resolvedMode === "agents" ? "agent-audit" : "activity"}-${companyId}.csv`;
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ // Browsers may read blob URLs lazily after click(), so keep the URL alive
+ // long enough for the download to start.
+ window.setTimeout(() => URL.revokeObjectURL(url), 5_000);
+ pushToast({ title: "Audit exported", body: "Your CSV download has started.", tone: "success" });
+ } catch (error) {
+ pushToast({
+ title: "Export failed",
+ body: error instanceof Error ? error.message : "Could not export the audit log.",
+ tone: "error",
+ });
+ } finally {
+ setExporting(false);
+ }
+ };
+
+ if (permissionDenied && !recoveringFromAccessDowngrade && !fallingBackToAllActivity) {
+ return <AuditUpsell />;
+ }
+
+ return (
+ <div className="space-y-4">
+ {!hideHeader ? (
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h1 className="text-lg font-semibold text-foreground">Activity</h1>
+ <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
+ {resolvedMode === "agents"
+ ? "Every recorded agent action, newest first — with the responsible person and run behind each one."
+ : "Everything happening in your company, newest first — people, agents, and the system. Each line is one recorded action."}
+ </p>
+ </div>
+ </div>
+ ) : null}
+
+ {showModeToggle ? (
+ <Tabs value={resolvedMode} onValueChange={(value) => onModeChange?.(value as AuditFeedMode)}>
+ <TabsList aria-label="Activity scope">
+ <TabsTrigger value="all">All activity</TabsTrigger>
+ <TabsTrigger value="agents">Agent actions</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ ) : null}
+
+ {canUseAdvancedControls ? (
+ <div className="flex flex-wrap items-center gap-2">
+ {!lockedAgentId ? (
+ <Select value={agent} onValueChange={setAgent}>
+ <SelectTrigger className="w-40">
+ <SelectValue placeholder="Agent" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All agents</SelectItem>
+ {(agents.data ?? []).map((a) => (
+ <SelectItem key={a.id} value={a.id}>
+ {a.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : null}
+ <Select value={responsibleUser} onValueChange={setResponsibleUser}>
+ {/* Wide enough for "All responsible users" — w-44 truncated it. */}
+ <SelectTrigger className="w-52">
+ <SelectValue placeholder="Responsible user" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All responsible users</SelectItem>
+ {(userDirectory.data?.users ?? []).map((u) => (
+ <SelectItem key={u.principalId} value={u.principalId}>
+ {u.user?.name ?? u.user?.email ?? u.principalId.slice(0, 8)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={actionDomain} onValueChange={setActionDomain}>
+ <SelectTrigger className="w-36">
+ <SelectValue placeholder="Action" />
+ </SelectTrigger>
+ <SelectContent>
+ {ACTION_DOMAINS.map((d) => (
+ <SelectItem key={d.value} value={d.value}>
+ {d.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select value={entityType} onValueChange={setEntityType}>
+ <SelectTrigger className="w-36">
+ <SelectValue placeholder="Entity" />
+ </SelectTrigger>
+ <SelectContent>
+ {ENTITY_TYPES.map((e) => (
+ <SelectItem key={e.value} value={e.value}>
+ {e.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Input
+ type="date"
+ aria-label="From date"
+ value={dateFrom}
+ max={dateTo || undefined}
+ onChange={(e) => setDateFrom(e.target.value)}
+ className="w-36"
+ />
+ <Input
+ type="date"
+ aria-label="To date"
+ value={dateTo}
+ min={dateFrom || undefined}
+ onChange={(e) => setDateTo(e.target.value)}
+ className="w-36"
+ />
+ {hasActiveFilters ? (
+ <Button variant="ghost" size="sm" onClick={clearFilters}>
+ Clear filters
+ </Button>
+ ) : null}
+ <Button
+ variant="outline"
+ size="sm"
+ className="ml-auto"
+ onClick={handleExport}
+ disabled={exporting || feed.isLoading || items.length === 0}
+ >
+ <Download className="mr-1.5 h-4 w-4" />
+ {exporting ? "Exporting…" : "Export CSV"}
+ </Button>
+ </div>
+ ) : null}
+
+ {recoveringFromAccessDowngrade || fallingBackToAllActivity ? (
+ <Card>
+ <CardContent className="py-14 text-center text-sm text-muted-foreground">
+ Refreshing audit access…
+ </CardContent>
+ </Card>
+ ) : feed.isLoading ? (
+ <Card>
+ <CardContent className="py-14 text-center text-sm text-muted-foreground">Loading…</CardContent>
+ </Card>
+ ) : feed.error ? (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-3 py-14 text-center">
+ <p className="text-sm text-muted-foreground">
+ {feed.error instanceof Error ? feed.error.message : "Failed to load the audit log."}
+ </p>
+ <Button variant="outline" size="sm" onClick={() => feed.refetch()}>
+ Try again
+ </Button>
+ </CardContent>
+ </Card>
+ ) : items.length === 0 ? (
+ <Card>
+ <CardContent className="flex flex-col items-center gap-3 py-14 text-center">
+ <ScrollText className="h-10 w-10 text-muted-foreground/40" />
+ <div>
+ <p className="text-sm font-medium text-foreground">
+ {hasActiveFilters ? "No actions match these filters" : "Nothing here yet"}
+ </p>
+ <p className="mt-1 max-w-md text-sm text-muted-foreground">
+ {hasActiveFilters
+ ? "Try a wider date range or different filters."
+ : resolvedMode === "agents"
+ ? "As soon as your agents start doing things, their actions show up here."
+ : "As soon as anyone in your company does something, it shows up here."}
+ </p>
+ </div>
+ {hasActiveFilters ? (
+ <Button variant="outline" size="sm" onClick={clearFilters}>
+ Clear filters
+ </Button>
+ ) : null}
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <CardContent className="px-0 py-0">
+ <ul className={cn("divide-y divide-border")}>
+ {items.map((record) => (
+ <AuditRow
+ key={record.id}
+ record={record}
+ agentMap={agentMap}
+ userProfileMap={userProfileMap}
+ />
+ ))}
+ </ul>
+ </CardContent>
+ </Card>
+ )}
+
+ {feed.hasNextPage ? (
+ <div className="flex justify-center">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => feed.fetchNextPage()}
+ disabled={feed.isFetchingNextPage}
+ >
+ {feed.isFetchingNextPage ? "Loading…" : "Load more"}
+ </Button>
+ </div>
+ ) : null}
+
+ <p className="text-xs text-muted-foreground">
+ Recorded by Paperclip — entries can't be edited. Sensitive values are never stored.
+ </p>
+ </div>
+ );
+}
diff --git a/ui/src/pages/audit/AuditFeed.test.tsx b/ui/src/pages/audit/AuditFeed.test.tsx
index e11f9c3352..70210eb3d1 100644
--- a/ui/src/pages/audit/AuditFeed.test.tsx
+++ b/ui/src/pages/audit/AuditFeed.test.tsx
@@ -109,6 +109,8 @@ describe("AuditFeed", () => {
props: {
companyId?: string;
lockedAgentId?: string;
+ lockedRunId?: string;
+ lockedEntity?: { type: string; id: string; label?: string };
mode?: "all" | "agents";
onModeChange?: (mode: "all" | "agents") => void;
} = {},
@@ -121,6 +123,8 @@ describe("AuditFeed", () => {
<AuditFeed
companyId={props.companyId ?? "company-1"}
lockedAgentId={props.lockedAgentId}
+ lockedRunId={props.lockedRunId}
+ lockedEntity={props.lockedEntity}
mode={props.mode}
onModeChange={props.onModeChange}
/>
@@ -218,12 +222,16 @@ describe("AuditFeed", () => {
expect(container.textContent).not.toContain("All agents");
expect(container.textContent).not.toContain("All responsible users");
expect(container.textContent).not.toContain("Export CSV");
+ expect(container.textContent).toContain("Action");
+ expect(container.textContent).toContain("Entity");
+ expect(container.textContent).toContain("From");
+ expect(container.textContent).toContain("To");
});
it("clears privileged filters and recovers the basic feed after an access downgrade", async () => {
let permissionRevoked = false;
- listAgentActionsMock.mockImplementation((_companyId: string, filters: { from?: string }) => {
- if (permissionRevoked && filters.from) {
+ listAgentActionsMock.mockImplementation((_companyId: string, filters: { agentId?: string }) => {
+ if (permissionRevoked && filters.agentId) {
return Promise.reject(
new ApiError("Missing permission: audit:view_agent_actions", 403, { error: "Missing permission" }),
);
@@ -236,35 +244,27 @@ describe("AuditFeed", () => {
});
await render();
- const fromDate = container.querySelector<HTMLInputElement>('input[aria-label="From date"]');
- expect(fromDate).toBeTruthy();
- const setInputValue = Object.getOwnPropertyDescriptor(
- window.HTMLInputElement.prototype,
- "value",
- )?.set;
- expect(setInputValue).toBeTruthy();
+ permissionRevoked = true;
+ await clickButton("All agents");
+ const fableOption = Array.from(document.body.querySelectorAll<HTMLElement>('[role="option"]'))
+ .find((option) => option.textContent?.trim() === "Fable");
+ expect(fableOption).toBeTruthy();
await act(async () => {
- permissionRevoked = true;
- setInputValue!.call(fromDate, "2026-08-01");
- fromDate!.dispatchEvent(new Event("input", { bubbles: true }));
+ fableOption!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
- // The recovery settles across the 403, the filter reset, and the basic-tier
- // refetch. The privileged filter fires first (from set), then the recovery
- // refetch clears it (from undefined). Wait for that recovery refetch and the
- // dropped filter chrome instead of a fixed flush count.
await waitForCondition(
() =>
- listAgentActionsMock.mock.calls.some(([, filters]) => filters.from)
- && listAgentActionsMock.mock.calls.at(-1)?.[1]?.from === undefined
+ listAgentActionsMock.mock.calls.some(([, filters]) => filters.agentId)
+ && listAgentActionsMock.mock.calls.at(-1)?.[1]?.agentId === undefined
&& !container.textContent?.includes("All agents"),
"the basic feed after the access downgrade",
20_000,
);
- expect(listAgentActionsMock.mock.calls.some(([, filters]) => filters.from)).toBe(true);
+ expect(listAgentActionsMock.mock.calls.some(([, filters]) => filters.agentId)).toBe(true);
await vi.waitFor(() => {
expect(listAgentActionsMock.mock.calls.at(-1)?.[1]).toEqual(
- expect.objectContaining({ actorScope: "all", from: undefined }),
+ expect.objectContaining({ actorScope: "all", agentId: undefined }),
);
expect(container.textContent).toContain("commented on");
expect(container.textContent).not.toContain("Paperclip Enterprise view");
@@ -431,13 +431,13 @@ describe("AuditFeed", () => {
});
await flushReact();
- expect(container.textContent).toContain("All activity");
- expect(container.textContent).toContain("Agent actions");
+ expect(container.textContent).toContain("Activity");
+ expect(container.textContent).toContain("Agent Actions");
expect(listAgentActionsMock.mock.calls[0]?.[1]).toEqual(
expect.objectContaining({ actorScope: "all" }),
);
- await clickTab("Agent actions");
+ await clickTab("Agent Actions");
await flushReact();
expect(listAgentActionsMock.mock.calls.at(-1)?.[1]).toEqual(
@@ -479,8 +479,9 @@ describe("AuditFeed", () => {
listAgentActionsMock.mockResolvedValue({ items: [record()], nextCursor: null, accessTier: "basic" });
await render({ mode: "all", onModeChange: vi.fn() });
- expect(container.querySelector('[role="tab"]')).toBeFalsy();
- expect(container.textContent).not.toContain("Agent actions");
+ const tabs = Array.from(container.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
+ expect(tabs.map((tab) => tab.textContent?.trim())).toEqual(["Activity", "Agent Actions"]);
+ expect(tabs.find((tab) => tab.textContent?.trim() === "Agent Actions")?.disabled).toBe(true);
// The basic feed itself still renders.
expect(container.textContent).toContain("commented on");
});
@@ -506,6 +507,33 @@ describe("AuditFeed", () => {
expect(container.textContent).toContain("Paperclip Enterprise view");
});
+ it("renders a flat activity list with clearly labeled filters", async () => {
+ await render();
+
+ const list = container.querySelector('ul[aria-label="Audit activity"]');
+ expect(list).toBeTruthy();
+ expect(list?.closest('[data-slot="card"]')).toBeFalsy();
+ expect(container.textContent).toContain("Agent");
+ expect(container.textContent).toContain("Responsible user");
+ expect(container.textContent).toContain("Action");
+ expect(container.textContent).toContain("Entity");
+ });
+
+ it("pins run and entity scopes into distinct audit requests", async () => {
+ await render({ lockedRunId: "run-42" });
+ expect(listAgentActionsMock.mock.calls[0]?.[1]).toEqual(
+ expect.objectContaining({ actorScope: "agents", runId: "run-42" }),
+ );
+ expect(container.textContent).toContain("Scoped to run run-42");
+
+ flushSync(() => root.unmount());
+ await render({ lockedEntity: { type: "routine", id: "routine-7", label: "Nightly triage" } });
+ expect(listAgentActionsMock.mock.calls.at(-1)?.[1]).toEqual(
+ expect.objectContaining({ entityType: "routine", entityId: "routine-7" }),
+ );
+ expect(container.textContent).toContain("Scoped to Nightly triage");
+ });
+
it("only offers action domains present in the agent-action feed", async () => {
await render();
diff --git a/ui/src/pages/audit/AuditFeed.tsx b/ui/src/pages/audit/AuditFeed.tsx
index 9726362f5e..cdbf86d008 100644
--- a/ui/src/pages/audit/AuditFeed.tsx
+++ b/ui/src/pages/audit/AuditFeed.tsx
@@ -48,6 +48,8 @@ const ENTITY_TYPES: { value: string; label: string }[] = [
{ value: ALL, label: "All entities" },
{ value: "issue", label: "Task" },
{ value: "agent", label: "Agent" },
+ { value: "heartbeat_run", label: "Run" },
+ { value: "routine", label: "Routine" },
{ value: "project", label: "Project" },
{ value: "goal", label: "Goal" },
{ value: "company", label: "Organization" },
@@ -67,6 +69,10 @@ export interface AuditFeedProps {
* agent filter is hidden and every query/export carries this agentId.
*/
lockedAgentId?: string;
+ /** Pin the feed to one run while preserving the existing run-detail links. */
+ lockedRunId?: string;
+ /** Pin the feed to an entity such as a routine. */
+ lockedEntity?: { type: string; id: string; label?: string };
/** Hide the section header/description (the AgentDetail tab supplies its own chrome). */
hideHeader?: boolean;
/**
@@ -260,6 +266,8 @@ function AuditUpsell() {
export function AuditFeed({
companyId,
lockedAgentId,
+ lockedRunId,
+ lockedEntity,
hideHeader,
mode,
onModeChange,
@@ -296,14 +304,17 @@ export function AuditFeed({
// The per-agent tab keeps the legacy privileged scope because it always
// carries an attribution filter and must not silently downgrade to the basic
// tier. Everywhere else the mode picks the scope, defaulting to all actors.
- const resolvedMode: AuditFeedMode = lockedAgentId ? "agents" : mode ?? "all";
+ const resolvedMode: AuditFeedMode = lockedAgentId || lockedRunId ? "agents" : mode ?? "all";
+ const hasLockedScope = Boolean(lockedAgentId || lockedRunId || lockedEntity);
const filters: AuditActionFilters = {
actorScope: resolvedMode,
agentId: lockedAgentId ?? (agent === ALL ? undefined : agent),
+ runId: lockedRunId,
responsibleUserId: responsibleUser === ALL ? undefined : responsibleUser,
action: actionDomain === ALL ? undefined : actionDomain,
- entityType: entityType === ALL ? undefined : entityType,
+ entityType: lockedEntity?.type ?? (entityType === ALL ? undefined : entityType),
+ entityId: lockedEntity?.id,
from: toStartIso(dateFrom),
to: toEndIso(dateTo),
};
@@ -316,14 +327,19 @@ export function AuditFeed({
|| dateFrom
|| dateTo,
);
+ const hasPrivilegedFilters = Boolean(
+ !hasLockedScope && (agent !== ALL || responsibleUser !== ALL),
+ );
const feed = useInfiniteQuery({
queryKey: queryKeys.audit.agentActions(companyId, {
actorScope: filters.actorScope,
agentId: filters.agentId,
+ runId: filters.runId,
responsibleUserId: filters.responsibleUserId,
action: filters.action,
entityType: filters.entityType,
+ entityId: filters.entityId,
from: filters.from,
to: filters.to,
}),
@@ -351,7 +367,7 @@ export function AuditFeed({
// page as authoritative until every cached page has been fetched again.
const accessTier = hasBasicPage ? "basic" : feed.data?.pages[0]?.accessTier;
const hasMixedAccessTiers = hasBasicPage && hasFullPage;
- const canUseAdvancedControls = lockedAgentId
+ const canUseAdvancedControls = lockedAgentId || lockedRunId
? true
: accessTier === "full";
// The recovery refetch below gets one shot. If it does not clear the mixed
@@ -366,23 +382,22 @@ export function AuditFeed({
hasMixedAccessTiers && downgradeRecoveryAttempted && !feed.isFetching,
);
const recoveringFromAccessDowngrade = Boolean(
- !lockedAgentId
+ !hasLockedScope
&& !downgradeRecoveryExhausted
- && ((permissionDenied && hasActiveFilters) || hasMixedAccessTiers),
+ && ((permissionDenied && hasPrivilegedFilters) || hasMixedAccessTiers),
);
// A reader without `audit:view_agent_actions` can still land on the
// agent-actions mode through an old `/audit` deep link. Drop them into the
// shared all-activity feed instead of blocking the whole page with the upsell.
const fallingBackToAllActivity = Boolean(
- permissionDenied && !lockedAgentId && resolvedMode === "agents" && onModeChange,
+ permissionDenied && !hasLockedScope && resolvedMode === "agents" && onModeChange,
);
- // The privileged mode is only offered to callers the server already answered
- // at the full tier — everyone else just gets the basic all-activity feed.
+ // Keep both modes explicit in the Audit IA. Basic readers can see that Agent
+ // Actions exists, but cannot switch into the privileged scope.
const showModeToggle = Boolean(
- !lockedAgentId
+ !hasLockedScope
&& onModeChange
&& !fallingBackToAllActivity
- && (resolvedMode === "agents" || accessTier === "full"),
);
useEffect(() => {
@@ -390,15 +405,11 @@ export function AuditFeed({
}, [fallingBackToAllActivity, onModeChange]);
useEffect(() => {
- if (!lockedAgentId && (accessTier === "basic" || recoveringFromAccessDowngrade)) {
+ if (!hasLockedScope && (accessTier === "basic" || recoveringFromAccessDowngrade)) {
setAgent(ALL);
setResponsibleUser(ALL);
- setActionDomain(ALL);
- setEntityType(ALL);
- setDateFrom("");
- setDateTo("");
}
- }, [accessTier, hasMixedAccessTiers, lockedAgentId, recoveringFromAccessDowngrade]);
+ }, [accessTier, hasLockedScope, recoveringFromAccessDowngrade]);
// Recover from a mid-pagination downgrade with exactly one refetch. `feed`
// gets a new identity on every render, so an unguarded refetch here re-fires
@@ -428,9 +439,11 @@ export function AuditFeed({
const blob = await auditApi.exportAgentActionsCsv(companyId, {
actorScope: filters.actorScope,
agentId: filters.agentId,
+ runId: filters.runId,
responsibleUserId: filters.responsibleUserId,
action: filters.action,
entityType: filters.entityType,
+ entityId: filters.entityId,
from: filters.from,
to: filters.to,
});
@@ -465,7 +478,7 @@ export function AuditFeed({
{!hideHeader ? (
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
- <h1 className="text-lg font-semibold text-foreground">Activity</h1>
+ <h2 className="text-lg font-semibold text-foreground">Activity</h2>
<p className="mt-1 max-w-2xl text-sm text-muted-foreground">
{resolvedMode === "agents"
? "Every recorded agent action, newest first — with the responsible person and run behind each one."
@@ -478,15 +491,32 @@ export function AuditFeed({
{showModeToggle ? (
<Tabs value={resolvedMode} onValueChange={(value) => onModeChange?.(value as AuditFeedMode)}>
<TabsList aria-label="Activity scope">
- <TabsTrigger value="all">All activity</TabsTrigger>
- <TabsTrigger value="agents">Agent actions</TabsTrigger>
+ <TabsTrigger value="all">Activity</TabsTrigger>
+ <TabsTrigger
+ value="agents"
+ disabled={accessTier === "basic"}
+ title={accessTier === "basic" ? "Agent Actions requires audit access" : undefined}
+ >
+ Agent Actions
+ </TabsTrigger>
</TabsList>
</Tabs>
) : null}
- {canUseAdvancedControls ? (
- <div className="flex flex-wrap items-center gap-2">
- {!lockedAgentId ? (
+ {hasLockedScope ? (
+ <div className="border-y border-border px-1 py-2 text-xs text-muted-foreground">
+ {lockedRunId
+ ? `Scoped to run ${lockedRunId.slice(0, 8)}`
+ : lockedAgentId
+ ? "Scoped to one agent"
+ : `Scoped to ${lockedEntity?.label ?? lockedEntity?.type ?? "entity"}`}
+ </div>
+ ) : null}
+
+ <div className="flex flex-wrap items-end gap-3 border-y border-border py-3">
+ {canUseAdvancedControls && !lockedAgentId && !lockedRunId ? (
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>Agent</span>
<Select value={agent} onValueChange={setAgent}>
<SelectTrigger className="w-40">
<SelectValue placeholder="Agent" />
@@ -500,23 +530,31 @@ export function AuditFeed({
))}
</SelectContent>
</Select>
- ) : null}
- <Select value={responsibleUser} onValueChange={setResponsibleUser}>
- {/* Wide enough for "All responsible users" — w-44 truncated it. */}
- <SelectTrigger className="w-52">
- <SelectValue placeholder="Responsible user" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={ALL}>All responsible users</SelectItem>
- {(userDirectory.data?.users ?? []).map((u) => (
- <SelectItem key={u.principalId} value={u.principalId}>
- {u.user?.name ?? u.user?.email ?? u.principalId.slice(0, 8)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ </label>
+ ) : null}
+ {canUseAdvancedControls ? (
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>Responsible user</span>
+ <Select value={responsibleUser} onValueChange={setResponsibleUser}>
+ {/* Wide enough for "All responsible users" — w-44 truncated it. */}
+ <SelectTrigger className="w-52">
+ <SelectValue placeholder="Responsible user" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All responsible users</SelectItem>
+ {(userDirectory.data?.users ?? []).map((u) => (
+ <SelectItem key={u.principalId} value={u.principalId}>
+ {u.user?.name ?? u.user?.email ?? u.principalId.slice(0, 8)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ ) : null}
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>Action</span>
<Select value={actionDomain} onValueChange={setActionDomain}>
- <SelectTrigger className="w-36">
+ <SelectTrigger className="w-40">
<SelectValue placeholder="Action" />
</SelectTrigger>
<SelectContent>
@@ -527,18 +565,26 @@ export function AuditFeed({
))}
</SelectContent>
</Select>
- <Select value={entityType} onValueChange={setEntityType}>
- <SelectTrigger className="w-36">
- <SelectValue placeholder="Entity" />
- </SelectTrigger>
- <SelectContent>
- {ENTITY_TYPES.map((e) => (
- <SelectItem key={e.value} value={e.value}>
- {e.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ </label>
+ {!lockedEntity ? (
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>Entity</span>
+ <Select value={entityType} onValueChange={setEntityType}>
+ <SelectTrigger className="w-40">
+ <SelectValue placeholder="Entity" />
+ </SelectTrigger>
+ <SelectContent>
+ {ENTITY_TYPES.map((e) => (
+ <SelectItem key={e.value} value={e.value}>
+ {e.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ ) : null}
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>From</span>
<Input
type="date"
aria-label="From date"
@@ -547,6 +593,9 @@ export function AuditFeed({
onChange={(e) => setDateFrom(e.target.value)}
className="w-36"
/>
+ </label>
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>To</span>
<Input
type="date"
aria-label="To date"
@@ -555,11 +604,13 @@ export function AuditFeed({
onChange={(e) => setDateTo(e.target.value)}
className="w-36"
/>
- {hasActiveFilters ? (
- <Button variant="ghost" size="sm" onClick={clearFilters}>
- Clear filters
- </Button>
- ) : null}
+ </label>
+ {hasActiveFilters ? (
+ <Button variant="ghost" size="sm" onClick={clearFilters}>
+ Clear filters
+ </Button>
+ ) : null}
+ {canUseAdvancedControls ? (
<Button
variant="outline"
size="sm"
@@ -570,8 +621,8 @@ export function AuditFeed({
<Download className="mr-1.5 h-4 w-4" />
{exporting ? "Exporting…" : "Export CSV"}
</Button>
- </div>
- ) : null}
+ ) : null}
+ </div>
{recoveringFromAccessDowngrade || fallingBackToAllActivity ? (
<Card>
@@ -618,20 +669,18 @@ export function AuditFeed({
</CardContent>
</Card>
) : (
- <Card>
- <CardContent className="px-0 py-0">
- <ul className={cn("divide-y divide-border")}>
- {items.map((record) => (
- <AuditRow
- key={record.id}
- record={record}
- agentMap={agentMap}
- userProfileMap={userProfileMap}
- />
- ))}
- </ul>
- </CardContent>
- </Card>
+ <div className="border-y border-border">
+ <ul className={cn("divide-y divide-border")} aria-label="Audit activity">
+ {items.map((record) => (
+ <AuditRow
+ key={record.id}
+ record={record}
+ agentMap={agentMap}
+ userProfileMap={userProfileMap}
+ />
+ ))}
+ </ul>
+ </div>
)}
{feed.hasNextPage ? (
diff --git a/ui/src/pages/audit/AuditHub.test.tsx b/ui/src/pages/audit/AuditHub.test.tsx
new file mode 100644
index 0000000000..d1a52650d6
--- /dev/null
+++ b/ui/src/pages/audit/AuditHub.test.tsx
@@ -0,0 +1,170 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AuditHub } from "./AuditHub";
+
+const navigateMock = vi.hoisted(() => vi.fn());
+const setSearchParamsMock = vi.hoisted(() => vi.fn());
+const setBreadcrumbsMock = vi.hoisted(() => vi.fn());
+let currentSearch = "";
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({ selectedCompanyId: "company-1" }),
+}));
+
+vi.mock("@/context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: setBreadcrumbsMock }),
+}));
+
+vi.mock("@/context/SidebarContext", () => ({
+ useSidebar: () => ({ isMobile: false }),
+}));
+
+vi.mock("@/lib/router", () => ({
+ useNavigate: () => navigateMock,
+ useSearchParams: () => [new URLSearchParams(currentSearch), setSearchParamsMock],
+}));
+
+vi.mock("./AuditFeed", () => ({
+ AuditFeed: (props: Record<string, unknown>) => (
+ <div
+ data-testid="audit-feed"
+ data-mode={props.mode}
+ data-agent={props.lockedAgentId}
+ data-run={props.lockedRunId}
+ data-entity={JSON.stringify(props.lockedEntity ?? null)}
+ />
+ ),
+}));
+
+vi.mock("./AuditRuns", () => ({
+ AuditRuns: ({ companyId, routineId }: { companyId: string; routineId?: string }) => (
+ <div data-testid="audit-runs" data-company={companyId} data-routine={routineId} />
+ ),
+}));
+
+vi.mock("./RoutineAuditActivity", () => ({
+ RoutineAuditActivity: ({ companyId, routineId }: { companyId: string; routineId: string }) => (
+ <div data-testid="routine-audit-activity" data-company={companyId} data-routine={routineId} />
+ ),
+}));
+
+vi.mock("@/pages/Costs", () => ({
+ Costs: (props: Record<string, unknown>) => (
+ <div
+ data-testid="audit-costs"
+ data-initial-tab={props.initialTab}
+ data-lock-tab={String(props.lockTab ?? false)}
+ data-hide-budgets={String(props.hideBudgetsTab ?? false)}
+ />
+ ),
+}));
+
+vi.mock("@/pages/Timeline", () => ({
+ Timeline: ({ embedded }: { embedded?: boolean }) => (
+ <div data-testid="audit-timeline" data-embedded={String(embedded ?? false)} />
+ ),
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("AuditHub", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ currentSearch = "";
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ flushSync(() => root?.unmount());
+ container.remove();
+ vi.clearAllMocks();
+ });
+
+ function render(section: "activity" | "runs" | "costs" | "budgets" | "timeline") {
+ root = createRoot(container);
+ flushSync(() => root.render(<AuditHub section={section} />));
+ }
+
+ it("uses one clear section model and passes deep-link scopes to Activity", () => {
+ currentSearch = "mode=agents&agentId=agent-1&runId=run-1";
+ render("activity");
+
+ expect(container.querySelectorAll('[role="tab"]')).toHaveLength(5);
+ expect(container.textContent).toContain("Activity");
+ expect(container.textContent).toContain("Runs");
+ expect(container.textContent).toContain("Costs");
+ expect(container.textContent).toContain("Budgets");
+ expect(container.textContent).toContain("Timeline");
+ const feed = container.querySelector<HTMLElement>('[data-testid="audit-feed"]');
+ expect(feed?.dataset.mode).toBe("agents");
+ expect(feed?.dataset.agent).toBe("agent-1");
+ expect(feed?.dataset.run).toBe("run-1");
+ expect(feed?.dataset.entity).toBe(JSON.stringify(null));
+ expect(setBreadcrumbsMock).toHaveBeenCalledWith([{ label: "Audit" }]);
+ });
+
+ it("uses routine-scoped activity instead of the privileged organization feed", () => {
+ currentSearch = "entityType=routine&entityId=routine-1";
+ render("activity");
+
+ expect(container.querySelector('[data-testid="audit-feed"]')).toBeNull();
+ const activity = container.querySelector<HTMLElement>('[data-testid="routine-audit-activity"]');
+ expect(activity?.dataset.company).toBe("company-1");
+ expect(activity?.dataset.routine).toBe("routine-1");
+ });
+
+ it("passes routine scope to the Runs section", () => {
+ currentSearch = "entityType=routine&entityId=routine-1";
+ render("runs");
+
+ const runs = container.querySelector<HTMLElement>('[data-testid="audit-runs"]');
+ expect(runs?.dataset.company).toBe("company-1");
+ expect(runs?.dataset.routine).toBe("routine-1");
+ });
+
+ it("renders Timeline as the section after Budgets", () => {
+ render("timeline");
+
+ const labels = Array.from(container.querySelectorAll<HTMLElement>('[role="tab"]'))
+ .map((tab) => tab.textContent?.trim());
+ expect(labels).toEqual(["Activity", "Runs", "Costs", "Budgets", "Timeline"]);
+ expect(container.querySelector<HTMLElement>('[data-testid="audit-timeline"]')?.dataset.embedded)
+ .toBe("true");
+ });
+
+ it("renders Costs and Budgets as intentional peer sections", () => {
+ render("budgets");
+ let costs = container.querySelector<HTMLElement>('[data-testid="audit-costs"]');
+ expect(costs?.dataset.initialTab).toBe("budgets");
+ expect(costs?.dataset.lockTab).toBe("true");
+
+ flushSync(() => root.unmount());
+ render("costs");
+ costs = container.querySelector<HTMLElement>('[data-testid="audit-costs"]');
+ expect(costs?.dataset.initialTab).toBe("overview");
+ expect(costs?.dataset.hideBudgets).toBe("true");
+ });
+
+ it("keeps the current entity scope when moving between Audit sections", () => {
+ currentSearch = "entityType=routine&entityId=routine-1";
+ render("activity");
+
+ const runsTab = Array.from(container.querySelectorAll<HTMLElement>('[role="tab"]'))
+ .find((tab) => tab.textContent?.trim() === "Runs");
+ expect(runsTab).toBeTruthy();
+ flushSync(() => {
+ runsTab!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));
+ runsTab!.dispatchEvent(new MouseEvent("click", { bubbles: true, button: 0 }));
+ });
+ expect(navigateMock).toHaveBeenCalledWith(
+ "/activity/runs?entityType=routine&entityId=routine-1",
+ );
+ });
+});
diff --git a/ui/src/pages/audit/AuditHub.tsx b/ui/src/pages/audit/AuditHub.tsx
new file mode 100644
index 0000000000..fda7237d4f
--- /dev/null
+++ b/ui/src/pages/audit/AuditHub.tsx
@@ -0,0 +1,104 @@
+import { useCallback, useEffect } from "react";
+import { History } from "lucide-react";
+import { EmptyState } from "@/components/EmptyState";
+import { PageTabBar } from "@/components/PageTabBar";
+import { Tabs } from "@/components/ui/tabs";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { useCompany } from "@/context/CompanyContext";
+import { useNavigate, useSearchParams } from "@/lib/router";
+import { Costs } from "@/pages/Costs";
+import { Timeline } from "@/pages/Timeline";
+import { AuditFeed, type AuditFeedMode } from "./AuditFeed";
+import { AuditRuns } from "./AuditRuns";
+import { RoutineAuditActivity } from "./RoutineAuditActivity";
+import {
+ AUDIT_SECTIONS,
+ auditScopeFromSearchParams,
+ auditSectionHref,
+ type AuditSection,
+} from "./audit-navigation";
+
+export function AuditHub({ section }: { section: AuditSection }) {
+ const navigate = useNavigate();
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const scope = auditScopeFromSearchParams(searchParams);
+ const mode: AuditFeedMode = scope.mode === "agents" ? "agents" : "all";
+ const routineId = scope.entityType === "routine" ? scope.entityId ?? undefined : undefined;
+
+ useEffect(() => {
+ const current = AUDIT_SECTIONS.find((candidate) => candidate.value === section);
+ setBreadcrumbs([
+ { label: "Audit", href: section === "activity" ? undefined : "/activity" },
+ ...(section === "activity" || !current ? [] : [{ label: current.label }]),
+ ]);
+ }, [section, setBreadcrumbs]);
+
+ const handleModeChange = useCallback(
+ (next: AuditFeedMode) => {
+ setSearchParams(
+ (current) => {
+ const params = new URLSearchParams(current);
+ if (next === "agents") params.set("mode", "agents");
+ else params.delete("mode");
+ return params;
+ },
+ { replace: true },
+ );
+ },
+ [setSearchParams],
+ );
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={History} message="Select an organization to view Audit." />;
+ }
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-3xl font-semibold tracking-tight text-foreground">Audit</h1>
+ <p className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">
+ Review what happened, inspect agent runs, and understand the costs and budget controls
+ behind your organization.
+ </p>
+ </div>
+
+ <Tabs
+ value={section}
+ onValueChange={(value) => {
+ const next = value as AuditSection;
+ navigate(auditSectionHref(next, scope));
+ }}
+ >
+ <PageTabBar items={AUDIT_SECTIONS} value={section} align="start" />
+ </Tabs>
+
+ {section === "activity" && routineId ? (
+ <RoutineAuditActivity companyId={selectedCompanyId} routineId={routineId} />
+ ) : section === "activity" ? (
+ <AuditFeed
+ companyId={selectedCompanyId}
+ hideHeader
+ mode={mode}
+ onModeChange={handleModeChange}
+ lockedAgentId={scope.agentId ?? undefined}
+ lockedRunId={scope.runId ?? undefined}
+ lockedEntity={
+ scope.entityType && scope.entityId
+ ? { type: scope.entityType, id: scope.entityId }
+ : undefined
+ }
+ />
+ ) : section === "runs" ? (
+ <AuditRuns companyId={selectedCompanyId} routineId={routineId} />
+ ) : section === "budgets" ? (
+ <Costs embedded initialTab="budgets" lockTab />
+ ) : section === "timeline" ? (
+ <Timeline embedded />
+ ) : (
+ <Costs embedded initialTab="overview" hideBudgetsTab />
+ )}
+ </div>
+ );
+}
diff --git a/ui/src/pages/audit/AuditRuns.test.tsx b/ui/src/pages/audit/AuditRuns.test.tsx
new file mode 100644
index 0000000000..78c3aeae4b
--- /dev/null
+++ b/ui/src/pages/audit/AuditRuns.test.tsx
@@ -0,0 +1,154 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { HeartbeatRun, RoutineRunSummary } from "@paperclipai/shared";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AuditRuns } from "./AuditRuns";
+
+const listAgentsMock = vi.hoisted(() => vi.fn());
+const listRunsMock = vi.hoisted(() => vi.fn());
+const listRoutineRunsMock = vi.hoisted(() => vi.fn());
+const setSearchParamsMock = vi.hoisted(() => vi.fn());
+let currentSearch = "";
+
+vi.mock("@/api/agents", () => ({
+ agentsApi: { list: (companyId: string) => listAgentsMock(companyId) },
+}));
+
+vi.mock("@/api/heartbeats", () => ({
+ heartbeatsApi: {
+ list: (companyId: string, agentId?: string, limit?: number, options?: unknown) =>
+ listRunsMock(companyId, agentId, limit, options),
+ },
+}));
+
+vi.mock("@/api/routines", () => ({
+ routinesApi: {
+ listRuns: (routineId: string, limit?: number) => listRoutineRunsMock(routineId, limit),
+ },
+}));
+
+vi.mock("@/lib/router", () => ({
+ Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => (
+ <a href={to} {...props}>{children}</a>
+ ),
+ useSearchParams: () => [new URLSearchParams(currentSearch), setSearchParamsMock],
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+function run(overrides: Partial<HeartbeatRun> = {}): HeartbeatRun {
+ return {
+ id: "run-12345678",
+ companyId: "company-1",
+ agentId: "agent-1",
+ invocationSource: "manual",
+ status: "succeeded",
+ startedAt: new Date("2026-08-31T18:00:00.000Z"),
+ finishedAt: new Date("2026-08-31T18:01:05.000Z"),
+ resultJson: { summary: "Reviewed the release checklist" },
+ error: null,
+ createdAt: new Date("2026-08-31T18:00:00.000Z"),
+ ...overrides,
+ } as HeartbeatRun;
+}
+
+function routineRun(overrides: Partial<RoutineRunSummary> = {}): RoutineRunSummary {
+ return {
+ id: "routine-run-1",
+ companyId: "company-1",
+ routineId: "routine-1",
+ triggerId: "trigger-1",
+ source: "schedule",
+ status: "succeeded",
+ triggeredAt: new Date("2026-08-31T18:00:00.000Z"),
+ idempotencyKey: null,
+ triggerPayload: null,
+ dispatchFingerprint: null,
+ linkedIssueId: "issue-1",
+ coalescedIntoRunId: null,
+ failureReason: null,
+ completedAt: new Date("2026-08-31T18:01:05.000Z"),
+ createdAt: new Date("2026-08-31T18:00:00.000Z"),
+ updatedAt: new Date("2026-08-31T18:01:05.000Z"),
+ linkedIssue: { id: "issue-1", identifier: "TES-42", title: "Publish forecast" },
+ trigger: { id: "trigger-1", kind: "schedule", label: "Daily forecast" },
+ ...overrides,
+ } as RoutineRunSummary;
+}
+
+async function flushReact() {
+ for (let index = 0; index < 3; index += 1) {
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ }
+}
+
+describe("AuditRuns", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ currentSearch = "";
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ listAgentsMock.mockResolvedValue([{ id: "agent-1", name: "Fable" }]);
+ listRunsMock.mockResolvedValue([run()]);
+ listRoutineRunsMock.mockResolvedValue([routineRun()]);
+ });
+
+ afterEach(() => {
+ flushSync(() => root?.unmount());
+ container.remove();
+ vi.clearAllMocks();
+ });
+
+ async function render(routineId?: string) {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ root = createRoot(container);
+ flushSync(() => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <AuditRuns companyId="company-1" routineId={routineId} />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+ }
+
+ it("renders a filterable flat run list with existing run-detail links", async () => {
+ await render();
+
+ expect(listRunsMock).toHaveBeenCalledWith("company-1", undefined, 200, { summary: true });
+ expect(container.textContent).toContain("Agent");
+ expect(container.textContent).toContain("Status");
+ expect(container.textContent).toContain("Reviewed the release checklist");
+ expect(container.textContent).toContain("1m 5s");
+ const list = container.querySelector('ul[aria-label="Recent runs"]');
+ expect(list).toBeTruthy();
+ expect(list?.closest('[data-slot="card"]')).toBeFalsy();
+ expect(container.querySelector('a[href="/agents/agent-1/runs/run-12345678"]')).toBeTruthy();
+ });
+
+ it("uses the agent deep-link filter for both the query key and request", async () => {
+ currentSearch = "agentId=agent-1&runStatus=succeeded";
+ await render();
+
+ expect(listRunsMock).toHaveBeenCalledWith("company-1", "agent-1", 200, { summary: true });
+ expect(container.textContent).toContain("Clear filters");
+ });
+
+ it("loads routine runs directly when the Audit scope is a routine", async () => {
+ await render("routine-1");
+
+ expect(listRoutineRunsMock).toHaveBeenCalledWith("routine-1", 200);
+ expect(listAgentsMock).not.toHaveBeenCalled();
+ expect(listRunsMock).not.toHaveBeenCalled();
+ expect(container.textContent).toContain("Publish forecast");
+ expect(container.textContent).toContain("Daily forecast");
+ expect(container.querySelector('a[href="/issues/TES-42"]')).toBeTruthy();
+ });
+});
diff --git a/ui/src/pages/audit/AuditRuns.tsx b/ui/src/pages/audit/AuditRuns.tsx
new file mode 100644
index 0000000000..aada265e42
--- /dev/null
+++ b/ui/src/pages/audit/AuditRuns.tsx
@@ -0,0 +1,312 @@
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { HeartbeatRun, RoutineRunSummary } from "@paperclipai/shared";
+import { Activity, CircleDotDashed } from "lucide-react";
+import { agentsApi } from "@/api/agents";
+import { heartbeatsApi } from "@/api/heartbeats";
+import { routinesApi } from "@/api/routines";
+import { EmptyState } from "@/components/EmptyState";
+import { StatusBadge } from "@/components/StatusBadge";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { queryKeys } from "@/lib/queryKeys";
+import { Link, useSearchParams } from "@/lib/router";
+import { relativeTime } from "@/lib/utils";
+
+const ALL = "__all";
+const RUN_LIMIT = 200;
+
+function runSummary(run: HeartbeatRun) {
+ const result = run.resultJson as { summary?: unknown; result?: unknown } | null;
+ const value = result?.summary ?? result?.result ?? run.error;
+ return typeof value === "string" && value.trim() ? value.trim() : null;
+}
+
+function runDuration(run: HeartbeatRun) {
+ const start = run.startedAt ? new Date(run.startedAt).getTime() : null;
+ const end = run.finishedAt ? new Date(run.finishedAt).getTime() : null;
+ if (start == null || end == null || !Number.isFinite(start) || !Number.isFinite(end)) return null;
+ const seconds = Math.max(0, Math.round((end - start) / 1000));
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ return `${minutes}m ${seconds % 60}s`;
+}
+
+function readableSource(source: string) {
+ return source.replaceAll("_", " ");
+}
+
+function routineRunTitle(run: RoutineRunSummary) {
+ return run.linkedIssue?.title ?? run.trigger?.label ?? "Routine run";
+}
+
+function RoutineScopedRuns({
+ runs,
+ isLoading,
+ error,
+ onRetry,
+}: {
+ runs: RoutineRunSummary[];
+ isLoading: boolean;
+ error: Error | null;
+ onRetry: () => void;
+}) {
+ if (isLoading) {
+ return (
+ <div className="border-y border-border py-14 text-center text-sm text-muted-foreground">
+ Loading routine runs…
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex flex-col items-center gap-3 border-y border-border py-14 text-center">
+ <p className="text-sm text-muted-foreground">{error.message}</p>
+ <Button variant="outline" size="sm" onClick={onRetry}>Try again</Button>
+ </div>
+ );
+ }
+
+ if (runs.length === 0) {
+ return <EmptyState icon={Activity} message="No routine runs yet." />;
+ }
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h2 className="text-lg font-semibold text-foreground">Routine runs</h2>
+ <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
+ Executions created by this routine, newest first.
+ </p>
+ </div>
+ <ul className="divide-y divide-border border-y border-border" aria-label="Routine runs">
+ {runs.map((run) => {
+ const content = (
+ <>
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium text-foreground">{routineRunTitle(run)}</span>
+ <StatusBadge status={run.status} />
+ </div>
+ <p className="mt-1 truncate text-sm text-muted-foreground">
+ {run.trigger?.label ?? readableSource(run.source)}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground sm:justify-end">
+ <span className="capitalize">{readableSource(run.source)}</span>
+ <time dateTime={new Date(run.triggeredAt).toISOString()}>
+ {relativeTime(run.triggeredAt)}
+ </time>
+ </div>
+ </>
+ );
+ const rowClassName = "flex flex-col gap-2 px-1 py-3 text-inherit no-underline transition-colors hover:bg-muted/50 sm:flex-row sm:items-start sm:justify-between sm:px-3";
+ return (
+ <li key={run.id}>
+ {run.linkedIssue ? (
+ <Link to={`/issues/${run.linkedIssue.identifier ?? run.linkedIssue.id}`} className={rowClassName}>
+ {content}
+ </Link>
+ ) : (
+ <div className={rowClassName}>{content}</div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ <p className="text-xs text-muted-foreground">Showing the {RUN_LIMIT} most recent routine runs.</p>
+ </div>
+ );
+}
+
+export function AuditRuns({ companyId, routineId }: { companyId: string; routineId?: string }) {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const agentId = searchParams.get("agentId") ?? ALL;
+ const status = searchParams.get("runStatus") ?? ALL;
+ const agents = useQuery({
+ queryKey: queryKeys.agents.list(companyId),
+ queryFn: () => agentsApi.list(companyId),
+ enabled: !routineId,
+ });
+ const runs = useQuery({
+ queryKey: queryKeys.audit.runs(companyId, agentId === ALL ? null : agentId),
+ queryFn: () =>
+ heartbeatsApi.list(companyId, agentId === ALL ? undefined : agentId, RUN_LIMIT, {
+ summary: true,
+ }),
+ refetchInterval: 15_000,
+ enabled: !routineId,
+ });
+ const routineRuns = useQuery({
+ queryKey: [...queryKeys.routines.runs(routineId ?? ""), "audit"],
+ queryFn: () => routinesApi.listRuns(routineId!, RUN_LIMIT),
+ enabled: Boolean(routineId),
+ refetchInterval: 15_000,
+ });
+ const agentById = useMemo(
+ () => new Map((agents.data ?? []).map((agent) => [agent.id, agent])),
+ [agents.data],
+ );
+ const statuses = useMemo(
+ () => Array.from(new Set((runs.data ?? []).map((run) => run.status))).sort(),
+ [runs.data],
+ );
+ const visibleRuns = useMemo(
+ () => (runs.data ?? []).filter((run) => status === ALL || run.status === status),
+ [runs.data, status],
+ );
+
+ const updateFilter = (key: "agentId" | "runStatus", value: string) => {
+ setSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ if (value === ALL) next.delete(key);
+ else next.set(key, value);
+ return next;
+ },
+ { replace: true },
+ );
+ };
+
+ const clearFilters = () => {
+ setSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete("agentId");
+ next.delete("runStatus");
+ return next;
+ },
+ { replace: true },
+ );
+ };
+
+ if (routineId) {
+ return (
+ <RoutineScopedRuns
+ runs={routineRuns.data ?? []}
+ isLoading={routineRuns.isLoading}
+ error={routineRuns.error instanceof Error ? routineRuns.error : null}
+ onRetry={() => void routineRuns.refetch()}
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h2 className="text-lg font-semibold text-foreground">Runs</h2>
+ <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
+ Recent agent executions across the organization. Open a run to inspect its transcript,
+ output, and task context.
+ </p>
+ </div>
+
+ <div className="flex flex-wrap items-end gap-3 border-y border-border py-3">
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>Agent</span>
+ <Select value={agentId} onValueChange={(value) => updateFilter("agentId", value)}>
+ <SelectTrigger className="w-48">
+ <SelectValue placeholder="All agents" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All agents</SelectItem>
+ {(agents.data ?? []).map((agent) => (
+ <SelectItem key={agent.id} value={agent.id}>
+ {agent.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ <label className="grid gap-1 text-(length:--text-micro) font-medium text-muted-foreground">
+ <span>Status</span>
+ <Select value={status} onValueChange={(value) => updateFilter("runStatus", value)}>
+ <SelectTrigger className="w-40">
+ <SelectValue placeholder="All statuses" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All statuses</SelectItem>
+ {statuses.map((value) => (
+ <SelectItem key={value} value={value}>
+ {readableSource(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </label>
+ {agentId !== ALL || status !== ALL ? (
+ <Button variant="ghost" size="sm" onClick={clearFilters}>
+ Clear filters
+ </Button>
+ ) : null}
+ </div>
+
+ {runs.isLoading ? (
+ <div className="border-y border-border py-14 text-center text-sm text-muted-foreground">
+ Loading runs…
+ </div>
+ ) : runs.error ? (
+ <div className="flex flex-col items-center gap-3 border-y border-border py-14 text-center">
+ <p className="text-sm text-muted-foreground">
+ {runs.error instanceof Error ? runs.error.message : "Failed to load runs."}
+ </p>
+ <Button variant="outline" size="sm" onClick={() => runs.refetch()}>
+ Try again
+ </Button>
+ </div>
+ ) : visibleRuns.length === 0 ? (
+ <EmptyState
+ icon={agentId !== ALL || status !== ALL ? CircleDotDashed : Activity}
+ message={agentId !== ALL || status !== ALL ? "No runs match these filters." : "No runs yet."}
+ />
+ ) : (
+ <ul className="divide-y divide-border border-y border-border" aria-label="Recent runs">
+ {visibleRuns.map((run) => {
+ const agent = agentById.get(run.agentId);
+ const summary = runSummary(run);
+ const duration = runDuration(run);
+ return (
+ <li key={run.id}>
+ <Link
+ to={`/agents/${run.agentId}/runs/${run.id}`}
+ className="flex flex-col gap-2 px-1 py-3 text-inherit no-underline transition-colors hover:bg-muted/50 sm:flex-row sm:items-start sm:justify-between sm:px-3"
+ >
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-medium text-foreground">
+ {agent?.name ?? "Unknown agent"}
+ </span>
+ <span className="font-mono text-(length:--text-micro) text-muted-foreground">
+ {run.id.slice(0, 8)}
+ </span>
+ <StatusBadge status={run.status} />
+ </div>
+ <p className="mt-1 truncate text-sm text-muted-foreground">
+ {summary ?? `${readableSource(run.invocationSource)} run`}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground sm:justify-end">
+ <span className="capitalize">{readableSource(run.invocationSource)}</span>
+ {duration ? <span>{duration}</span> : null}
+ <time dateTime={new Date(run.createdAt).toISOString()}>
+ {relativeTime(run.createdAt)}
+ </time>
+ </div>
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ <p className="text-xs text-muted-foreground">Showing the {RUN_LIMIT} most recent runs.</p>
+ </div>
+ );
+}
diff --git a/ui/src/pages/audit/CompanyActivity.production.tsx b/ui/src/pages/audit/CompanyActivity.production.tsx
new file mode 100644
index 0000000000..cd92a013fa
--- /dev/null
+++ b/ui/src/pages/audit/CompanyActivity.production.tsx
@@ -0,0 +1,49 @@
+import { useCallback, useEffect } from "react";
+import { History } from "lucide-react";
+import { useSearchParams } from "@/lib/router";
+import { useCompany } from "../../context/CompanyContext";
+import { useBreadcrumbs } from "../../context/BreadcrumbContext";
+import { EmptyState } from "../../components/EmptyState";
+import { AuditFeed, type AuditFeedMode } from "./AuditFeed.production";
+
+/**
+ * Company activity page — the single merged surface for `/:company/activity`
+ * (PAP-16302). It replaces both the old 200-row activity list and the separate
+ * `/audit` page: all company readers get the shared all-actors feed, and callers
+ * with `audit:view_agent_actions` can switch to the privileged agent-action
+ * audit. The mode lives in `?mode=` so `/audit` deep links can preset it and
+ * links stay shareable. The server enforces both tiers regardless.
+ */
+export function CompanyActivity() {
+ const { selectedCompanyId } = useCompany();
+ const { setBreadcrumbs } = useBreadcrumbs();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const mode: AuditFeedMode = searchParams.get("mode") === "agents" ? "agents" : "all";
+
+ useEffect(() => {
+ setBreadcrumbs([{ label: "Activity" }]);
+ }, [setBreadcrumbs]);
+
+ const handleModeChange = useCallback(
+ (next: AuditFeedMode) => {
+ setSearchParams(
+ (current) => {
+ const params = new URLSearchParams(current);
+ if (next === "agents") params.set("mode", "agents");
+ else params.delete("mode");
+ return params;
+ },
+ // The mode is a view toggle, not a navigation step — don't stack history
+ // entries the back button has to walk through.
+ { replace: true },
+ );
+ },
+ [setSearchParams],
+ );
+
+ if (!selectedCompanyId) {
+ return <EmptyState icon={History} message="Select a company to view activity." />;
+ }
+
+ return <AuditFeed companyId={selectedCompanyId} mode={mode} onModeChange={handleModeChange} />;
+}
diff --git a/ui/src/pages/audit/CompanyActivity.tsx b/ui/src/pages/audit/CompanyActivity.tsx
index c986ef58c0..7e9d1f8a27 100644
--- a/ui/src/pages/audit/CompanyActivity.tsx
+++ b/ui/src/pages/audit/CompanyActivity.tsx
@@ -3,26 +3,27 @@ import { History } from "lucide-react";
import { useSearchParams } from "@/lib/router";
import { useCompany } from "../../context/CompanyContext";
import { useBreadcrumbs } from "../../context/BreadcrumbContext";
+import { useStreamlinedUiEnabled } from "../../hooks/useStreamlinedUiEnabled";
import { EmptyState } from "../../components/EmptyState";
import { AuditFeed, type AuditFeedMode } from "./AuditFeed";
+import { AuditHub } from "./AuditHub";
/**
- * Company activity page — the single merged surface for `/:company/activity`
- * (PAP-16302). It replaces both the old 200-row activity list and the separate
- * `/audit` page: all company readers get the shared all-actors feed, and callers
- * with `audit:view_agent_actions` can switch to the privileged agent-action
- * audit. The mode lives in `?mode=` so `/audit` deep links can preset it and
- * links stay shareable. The server enforces both tiers regardless.
+ * Canonical `/:company/activity` entrypoint for the Audit hub. It retains the
+ * shared all-actors and privileged Agent Actions modes while Runs, Costs,
+ * Budgets, and Timeline live as peer sections. The mode lives in `?mode=` so `/audit` deep
+ * links can preset it and links stay shareable. The server enforces both tiers.
*/
export function CompanyActivity() {
+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const [searchParams, setSearchParams] = useSearchParams();
const mode: AuditFeedMode = searchParams.get("mode") === "agents" ? "agents" : "all";
useEffect(() => {
- setBreadcrumbs([{ label: "Activity" }]);
- }, [setBreadcrumbs]);
+ if (!streamlinedUiEnabled) setBreadcrumbs([{ label: "Activity" }]);
+ }, [setBreadcrumbs, streamlinedUiEnabled]);
const handleModeChange = useCallback(
(next: AuditFeedMode) => {
@@ -33,14 +34,14 @@ export function CompanyActivity() {
else params.delete("mode");
return params;
},
- // The mode is a view toggle, not a navigation step — don't stack history
- // entries the back button has to walk through.
{ replace: true },
);
},
[setSearchParams],
);
+ if (streamlinedUiEnabled) return <AuditHub section="activity" />;
+
if (!selectedCompanyId) {
return <EmptyState icon={History} message="Select an organization to view activity." />;
}
diff --git a/ui/src/pages/audit/RoutineAuditActivity.test.tsx b/ui/src/pages/audit/RoutineAuditActivity.test.tsx
new file mode 100644
index 0000000000..1ca806cd22
--- /dev/null
+++ b/ui/src/pages/audit/RoutineAuditActivity.test.tsx
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RoutineAuditActivity } from "./RoutineAuditActivity";
+
+const getRoutineMock = vi.hoisted(() => vi.fn());
+const listRoutineRunsMock = vi.hoisted(() => vi.fn());
+const routineActivityMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/api/routines", () => ({
+ routinesApi: {
+ get: (routineId: string) => getRoutineMock(routineId),
+ listRuns: (routineId: string, limit?: number) => listRoutineRunsMock(routineId, limit),
+ activity: (
+ companyId: string,
+ routineId: string,
+ scope: { triggerIds: string[]; runIds: string[] },
+ ) => routineActivityMock(companyId, routineId, scope),
+ },
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+async function flushReact() {
+ for (let index = 0; index < 3; index += 1) {
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ }
+}
+
+describe("RoutineAuditActivity", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ getRoutineMock.mockResolvedValue({ triggers: [{ id: "trigger-1" }, { id: "trigger-2" }] });
+ listRoutineRunsMock.mockResolvedValue([{ id: "run-1" }, { id: "run-2" }]);
+ routineActivityMock.mockResolvedValue([
+ {
+ id: "event-1",
+ action: "routine.run.completed",
+ details: { runId: "run-1" },
+ createdAt: new Date("2026-08-31T18:01:05.000Z"),
+ },
+ ]);
+ });
+
+ afterEach(() => {
+ flushSync(() => root?.unmount());
+ container.remove();
+ vi.clearAllMocks();
+ });
+
+ it("loads activity through the routine endpoint with its trigger and run scope", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ root = createRoot(container);
+ flushSync(() => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <RoutineAuditActivity companyId="company-1" routineId="routine-1" />
+ </QueryClientProvider>,
+ );
+ });
+ await flushReact();
+
+ expect(getRoutineMock).toHaveBeenCalledWith("routine-1");
+ expect(listRoutineRunsMock).toHaveBeenCalledWith("routine-1", 200);
+ expect(routineActivityMock).toHaveBeenCalledWith("company-1", "routine-1", {
+ triggerIds: ["trigger-1", "trigger-2"],
+ runIds: ["run-1", "run-2"],
+ });
+ expect(container.textContent).toContain("routine.run.completed");
+ });
+});
diff --git a/ui/src/pages/audit/RoutineAuditActivity.tsx b/ui/src/pages/audit/RoutineAuditActivity.tsx
new file mode 100644
index 0000000000..ed7a76e1be
--- /dev/null
+++ b/ui/src/pages/audit/RoutineAuditActivity.tsx
@@ -0,0 +1,63 @@
+import { useQuery } from "@tanstack/react-query";
+import { Activity } from "lucide-react";
+import { routinesApi } from "@/api/routines";
+import { EmptyState } from "@/components/EmptyState";
+import { RoutineActivityRow } from "@/components/RoutineActivityRow";
+import { Button } from "@/components/ui/button";
+import { queryKeys } from "@/lib/queryKeys";
+
+export function RoutineAuditActivity({
+ companyId,
+ routineId,
+}: {
+ companyId: string;
+ routineId: string;
+}) {
+ const activity = useQuery({
+ queryKey: [...queryKeys.routines.activity(companyId, routineId), "audit"],
+ queryFn: async () => {
+ const [routine, runs] = await Promise.all([
+ routinesApi.get(routineId),
+ routinesApi.listRuns(routineId, 200),
+ ]);
+ return routinesApi.activity(companyId, routineId, {
+ triggerIds: routine.triggers.map((trigger) => trigger.id),
+ runIds: runs.map((run) => run.id),
+ });
+ },
+ });
+
+ if (activity.isLoading) {
+ return (
+ <div className="border-y border-border py-14 text-center text-sm text-muted-foreground">
+ Loading routine activity…
+ </div>
+ );
+ }
+
+ if (activity.error) {
+ return (
+ <div className="flex flex-col items-center gap-3 border-y border-border py-14 text-center">
+ <p className="text-sm text-muted-foreground">
+ {activity.error instanceof Error ? activity.error.message : "Failed to load routine activity."}
+ </p>
+ <Button variant="outline" size="sm" onClick={() => activity.refetch()}>
+ Try again
+ </Button>
+ </div>
+ );
+ }
+
+ const events = activity.data ?? [];
+ if (events.length === 0) {
+ return <EmptyState icon={Activity} message="No routine activity yet." />;
+ }
+
+ return (
+ <div className="border-y border-border" aria-label="Routine activity">
+ {events.map((event) => (
+ <RoutineActivityRow key={event.id} event={event} />
+ ))}
+ </div>
+ );
+}
diff --git a/ui/storybook/stories/skills-store-discovery.stories.tsx b/ui/storybook/stories/skills-store-discovery.stories.tsx
index 1c92aeacb7..2bcb7c2c98 100644
--- a/ui/storybook/stories/skills-store-discovery.stories.tsx
+++ b/ui/storybook/stories/skills-store-discovery.stories.tsx
@@ -1,9 +1,14 @@
import { useMemo, useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
-import { DiscoveryGrid, type DiscoveryCard, type DiscoveryCategory } from "@/pages/CompanySkills";
+import {
+ DiscoveryGrid,
+ type DiscoveryCard,
+ type DiscoveryCategory,
+ type DiscoveryTab,
+} from "@/pages/CompanySkills";
-type DiscoveryTab = "all" | "installed" | "catalog" | "bundled";
type DiscoverySort = "agents" | "stars" | "forks" | "recent" | "alphabetical";
+const STORY_NOW = new Date("2026-08-31T12:00:00Z").getTime();
const MOCK_CARDS: DiscoveryCard[] = [
{
@@ -25,7 +30,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: false,
forkedFrom: false,
- updatedAt: Date.now() - 2 * 86_400_000,
+ updatedAt: STORY_NOW - 2 * 86_400_000,
sourceBadge: "github",
},
{
@@ -47,7 +52,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: false,
required: false,
forkedFrom: false,
- updatedAt: Date.now() - 5 * 86_400_000,
+ updatedAt: STORY_NOW - 5 * 86_400_000,
sourceBadge: "skills_sh",
},
{
@@ -69,7 +74,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: false,
forkedFrom: false,
- updatedAt: Date.now() - 9 * 86_400_000,
+ updatedAt: STORY_NOW - 9 * 86_400_000,
sourceBadge: "local",
},
{
@@ -91,7 +96,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: false,
forkedFrom: true,
- updatedAt: Date.now() - 1 * 86_400_000,
+ updatedAt: STORY_NOW - 1 * 86_400_000,
sourceBadge: "paperclip",
},
{
@@ -135,7 +140,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: false,
forkedFrom: false,
- updatedAt: Date.now() - 3 * 86_400_000,
+ updatedAt: STORY_NOW - 3 * 86_400_000,
sourceBadge: "github",
},
{
@@ -179,7 +184,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: false,
forkedFrom: false,
- updatedAt: Date.now() - 4 * 86_400_000,
+ updatedAt: STORY_NOW - 4 * 86_400_000,
sourceBadge: "local",
},
{
@@ -201,7 +206,7 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: true,
forkedFrom: false,
- updatedAt: Date.now() - 30 * 86_400_000,
+ updatedAt: STORY_NOW - 30 * 86_400_000,
sourceBadge: "paperclip",
},
{
@@ -223,22 +228,17 @@ const MOCK_CARDS: DiscoveryCard[] = [
installed: true,
required: true,
forkedFrom: false,
- updatedAt: Date.now() - 28 * 86_400_000,
+ updatedAt: STORY_NOW - 28 * 86_400_000,
sourceBadge: "url",
},
];
-const DISCOVERY_TABS: DiscoveryTab[] = ["all", "installed", "catalog", "bundled"];
-
function cardsForTab(cards: DiscoveryCard[], tab: DiscoveryTab): DiscoveryCard[] {
- if (tab === "installed") return cards.filter((c) => c.installed);
- if (tab === "catalog") return cards.filter((c) => c.catalogRef != null);
- if (tab === "bundled") return cards.filter((c) => c.required);
- return cards;
+ return tab === "installed" ? cards.filter((card) => card.installed) : cards;
}
function DiscoveryGridHarness({
- initialTab = "all",
+ initialTab = "installed",
cards = MOCK_CARDS,
}: {
initialTab?: DiscoveryTab;
@@ -264,7 +264,7 @@ function DiscoveryGridHarness({
if (!q) return true;
return `${card.name} ${card.author} ${card.categories.join(" ")}`.toLowerCase().includes(q);
});
- const demote = tab !== "bundled";
+ const demote = tab === "discover";
return [...filtered].sort((a, b) => {
if (demote && a.required !== b.required) return a.required ? 1 : -1;
if (sort === "stars") return b.starCount - a.starCount;
@@ -275,24 +275,9 @@ function DiscoveryGridHarness({
});
}, [tabCards, category, search, sort, tab]);
- const tabCounts = useMemo(
- () => ({
- all: cards.length,
- installed: cards.filter((c) => c.installed).length,
- catalog: cards.filter((c) => c.catalogRef != null).length,
- bundled: cards.filter((c) => c.required).length,
- }),
- [cards],
- ) as Record<DiscoveryTab, number>;
-
return (
<DiscoveryGrid
tab={tab}
- tabCounts={tabCounts}
- onTabChange={(next) => {
- setTab(next);
- setCategory(null);
- }}
categories={categories}
categoryTotal={tabCards.length}
activeCategory={category}
@@ -309,7 +294,10 @@ function DiscoveryGridHarness({
onCreate={() => {}}
onImport={() => {}}
onImportFromProject={() => {}}
- onBrowseCatalog={() => setTab("catalog")}
+ onBrowseDiscover={() => {
+ setTab("discover");
+ setCategory(null);
+ }}
onScan={() => {}}
scanPending={false}
scanStatus={null}
@@ -327,7 +315,6 @@ export default meta;
type Story = StoryObj<typeof DiscoveryGridHarness>;
-export const AllSkills: Story = { args: { initialTab: "all" } };
-export const InstalledTab: Story = { args: { initialTab: "installed" } };
-export const BundledRequiredTab: Story = { args: { initialTab: "bundled" } };
-export const EmptyLibrary: Story = { args: { initialTab: "all", cards: [] } };
+export const Installed: Story = { args: { initialTab: "installed" } };
+export const Discover: Story = { args: { initialTab: "discover" } };
+export const EmptyInstalledLibrary: Story = { args: { initialTab: "installed", cards: [] } };