The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(ui): add streamlined navigation foundation (#12746)
scotttong597fd63b6177
diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.tsindex 66a71b46b5..bd934c1703 100644--- a/packages/shared/src/feature-catalog.ts+++ b/packages/shared/src/feature-catalog.ts@@ -81,6 +81,14 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalogcloudDefault: true,selfHostedDefault: true,},+ enableStreamlinedUi: {+ title: "Streamlined UI",+ description:+ "Use the streamlined application shell, shared task collections, focused task detail layout, contextual navigation, and simplified main sidebar.",+ tier: "preference",+ cloudDefault: true,+ selfHostedDefault: true,+ },enableApps: {title: "Apps (compatibility)",description:diff --git a/packages/shared/src/types/instance.ts b/packages/shared/src/types/instance.tsindex 376171e669..fd49cb880d 100644--- a/packages/shared/src/types/instance.ts+++ b/packages/shared/src/types/instance.ts@@ -54,6 +54,12 @@ export interface InstanceExperimentalSettings {enableManagedSandboxOnly: boolean;enableIsolatedWorkspaces: boolean;enableStreamlinedLeftNavigation: boolean;+ /**+ * Use the streamlined shell, navigation, and contextual-sidebar experience.+ * Missing legacy values default on; the retired left-navigation preference+ * remains separate so an old opt-out cannot disable the broader UI.+ */+ enableStreamlinedUi: boolean;/** @deprecated Compatibility key only. Apps is always enabled. */enableApps: boolean;enablePipelines: boolean;diff --git a/packages/shared/src/validators/instance.test.ts b/packages/shared/src/validators/instance.test.tsindex 16ea3336ab..d6a1564356 100644--- a/packages/shared/src/validators/instance.test.ts+++ b/packages/shared/src/validators/instance.test.ts@@ -5,6 +5,13 @@ import {} from "./instance.js";describe("instance experimental settings validators", () => {+ it("defaults the streamlined UI on and accepts an explicit patch", () => {+ expect(instanceExperimentalSettingsSchema.parse({}).enableStreamlinedUi).toBe(true);+ expect(+ patchInstanceExperimentalSettingsSchema.parse({ enableStreamlinedUi: false }),+ ).toEqual({ enableStreamlinedUi: false });+ });+it("defaults the server info debug view off", () => {const settings = instanceExperimentalSettingsSchema.parse({});diff --git a/packages/shared/src/validators/instance.ts b/packages/shared/src/validators/instance.tsindex 6a392d3f0d..a23c361574 100644--- a/packages/shared/src/validators/instance.ts+++ b/packages/shared/src/validators/instance.ts@@ -45,6 +45,7 @@ export const instanceExperimentalSettingsSchema = z.object({enableManagedSandboxOnly: z.boolean().default(false),enableIsolatedWorkspaces: z.boolean().default(false),enableStreamlinedLeftNavigation: z.boolean().default(true),+ enableStreamlinedUi: z.boolean().default(true),// Deprecated compatibility key. Apps is a standard product surface and is// always enabled; this remains accepted so older stored rows and managed// configs continue to load during upgrades.diff --git a/server/src/__tests__/instance-settings-routes.test.ts b/server/src/__tests__/instance-settings-routes.test.tsindex 455fbeb4fc..4c5bc17579 100644--- a/server/src/__tests__/instance-settings-routes.test.ts+++ b/server/src/__tests__/instance-settings-routes.test.ts@@ -270,6 +270,24 @@ describe("instance settings routes", () => {.expect(404);});+ it("accepts the instance-wide Streamlined UI preference", async () => {+ const app = await createApp({+ type: "board",+ userId: "local-board",+ source: "local_implicit",+ isInstanceAdmin: true,+ });++ await request(app)+ .patch("/api/instance/settings/experimental")+ .send({ enableStreamlinedUi: false })+ .expect(200);++ expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({+ enableStreamlinedUi: false,+ });+ });+it("strips server-managed worktree run execution fields before updating experimental settings", async () => {const app = await createApp({type: "board",diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.tsindex 569fb6685b..475a2fdd5a 100644--- a/server/src/__tests__/instance-settings-service.test.ts+++ b/server/src/__tests__/instance-settings-service.test.ts@@ -29,6 +29,7 @@ describe("instance settings service", () => {enableManagedSandboxOnly: false,enableIsolatedWorkspaces: true,enableStreamlinedLeftNavigation: true,+ enableStreamlinedUi: true,enableApps: true,enableConferenceRoomChat: false,enableClassicTaskInterface: false,@@ -59,6 +60,15 @@ describe("instance settings service", () => {});});+ it("defaults streamlined UI on without inheriting the retired navigation preference", () => {+ expect(normalizeExperimentalSettings(undefined).enableStreamlinedUi).toBe(true);+ expect(normalizeExperimentalSettings({}).enableStreamlinedUi).toBe(true);+ expect(+ normalizeExperimentalSettings({ enableStreamlinedLeftNavigation: false }).enableStreamlinedUi,+ ).toBe(true);+ expect(normalizeExperimentalSettings({ enableStreamlinedUi: false }).enableStreamlinedUi).toBe(false);+ });+it("keeps Apps on for empty, legacy, and explicitly disabled stored settings", () => {expect(normalizeExperimentalSettings(undefined).enableApps).toBe(true);expect(normalizeExperimentalSettings({}).enableApps).toBe(true);diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.tsindex d590dde57e..b695455612 100644--- a/server/src/services/instance-settings.ts+++ b/server/src/services/instance-settings.ts@@ -224,6 +224,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimentaenableManagedSandboxOnly: parsed.data.enableManagedSandboxOnly ?? false,enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false,enableStreamlinedLeftNavigation: parsed.data.enableStreamlinedLeftNavigation ?? true,+ enableStreamlinedUi: parsed.data.enableStreamlinedUi ?? true,// Apps graduated from Experimental. Ignore historical off values while// continuing to accept the compatibility key in stored settings.enableApps: true,@@ -262,6 +263,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimentaenableManagedSandboxOnly: false,enableIsolatedWorkspaces: false,enableStreamlinedLeftNavigation: true,+ enableStreamlinedUi: true,enableApps: true,enablePipelines: false,enableCases: false,diff --git a/tests/e2e/apps-dark-mode-shots.spec.ts b/tests/e2e/apps-dark-mode-shots.spec.tsindex f1a5282569..bbc1de02f7 100644--- a/tests/e2e/apps-dark-mode-shots.spec.ts+++ b/tests/e2e/apps-dark-mode-shots.spec.ts@@ -161,7 +161,7 @@ test.describe.serial("dark-mode Apps surfaces", () => {await expect(page.locator('a[href$="/apps/advanced/gateways"]', { hasText: "Gateways" })).toHaveCount(0);await expect(page.locator('a[href$="/apps/advanced/profiles"]', { hasText: "Profiles" })).toHaveCount(0);await expect(page.locator('a[href$="/apps/advanced/audit"]', { hasText: "Activity" })).toHaveCount(0);- await expect(page.locator('a[href$="/activity"]', { hasText: "Activity" })).toBeVisible();+ await expect(page.locator('a[href$="/activity"]', { hasText: "Audit" })).toBeVisible();await expect(page.getByRole("link", { name: "Applications", exact: true })).toHaveCount(0);// Apps section lives in the same sidebar now.await expect(page.locator('a[href$="/apps"]', { hasText: "Connectors" })).toBeVisible();diff --git a/tests/e2e/sidebar-takeover.spec.ts b/tests/e2e/sidebar-takeover.spec.tsindex ffbfa746ba..af55e6fff8 100644--- a/tests/e2e/sidebar-takeover.spec.ts+++ b/tests/e2e/sidebar-takeover.spec.ts@@ -1,37 +1,20 @@import { test, expect, request as pwRequest, type APIRequestContext } from "@playwright/test";/**- * E2E: Sidebar takeover model (PAP-10695).+ * E2E: contextual sidebar companion model.*- * Takeover routes (company settings, plugin `routeSidebar`) no longer *replace*- * the main app sidebar. Instead the host collapses the app `<Sidebar/>` to its- * 64px rail (still peek-able) and renders the contextual sidebar in a second- * pane → `[ app rail ][ secondary ~240px ][ content ]`.+ * Contextual routes render their navigation beside the stable global sidebar.+ * The global company navigation and account menu remain available, and leaving+ * the surface restores the user's global sidebar preference.*- * These specs assert the rail + secondary pane coexist on a company settings- * route, and that an explicit user pin (expanded) wins over the route-driven- * collapse (pin precedence).- *- * The plugin `routeSidebar` half of this behavior shares the exact same Layout- * code path (one `secondarySidebar`/`hasSecondarySidebar` resolver drives both- * company-settings and plugin routes) and is covered by the unit tests in- * `ui/src/components/Layout.test.tsx`. A live plugin-route e2e requires the- * `plugin-llm-wiki` plugin to be installed in the throwaway e2e instance, which- * is out of scope for this default local_trusted run; visual QA of both panes- * is delegated to the QA child issue.+ * Plugin route sidebars share the same Layout path. A live plugin-route test+ * requires a plugin fixture, so that branch remains covered by Layout tests.*/const PORT = Number(process.env.PAPERCLIP_E2E_PORT ?? 3199);const BASE_URL = `http://127.0.0.1:${PORT}`;const COMPANY_NAME_PREFIX = "E2E-SidebarTakeover";const COLLAPSED_STORAGE_KEY = "paperclip.sidebar.collapsed";--// The sidebar header's "Collapse sidebar" toggle only renders when the app-// sidebar is expanded (pinned, desktop, not takeover-locked); in the collapsed-// rail and on takeover routes it is hidden. Its presence/absence is therefore-// a stable proxy for the app sidebar's collapsed state (see Sidebar.tsx).-// (Previously "Open search", but the header search icon moved into the nav,-// where it renders in the rail too.)const APP_SIDEBAR_EXPANDED_MARKER = "Collapse sidebar";async function createCompany(board: APIRequestContext): Promise<{ id: string; prefix: string }> {@@ -53,7 +36,7 @@ async function createCompany(board: APIRequestContext): Promise<{ id: string; pr};}-test.describe("Sidebar takeover (collapse + secondary pane)", () => {+test.describe("Contextual sidebar companion", () => {let board: APIRequestContext;let companyId: string;let prefix: string;@@ -71,93 +54,59 @@ test.describe("Sidebar takeover (collapse + secondary pane)", () => {});test.beforeEach(async ({ page }) => {- // Start each test from a clean (unpinned) sidebar state so the route-driven- // collapse is the only thing acting on it.await page.addInitScript((key) => {window.localStorage.removeItem(key);+ window.sessionStorage.clear();}, COLLAPSED_STORAGE_KEY);});- test("collapses the app sidebar to its rail and shows the settings sidebar beside it", async ({ page }) => {+ test("shows Settings beside the global navigation", async ({ page }) => {await page.goto(`/${prefix}/company/settings`);- // The contextual (secondary) pane is present...- const secondary = page.locator("[data-secondary-sidebar]");- await expect(secondary).toBeVisible();- await expect(secondary).toHaveCount(1);+ const contextual = page.locator('[data-contextual-sidebar="settings"]');+ await expect(contextual).toBeVisible();+ await expect(contextual).toHaveCount(1);+ await expect(page.locator("[data-secondary-sidebar]")).toHaveCount(1);- // ...and it is ~240px wide (w-60), distinct from the 64px app rail.- const secondaryBox = await secondary.boundingBox();- expect(secondaryBox).not.toBeNull();- expect(secondaryBox!.width).toBeGreaterThan(180);+ await expect(contextual.getByRole("link", { name: "General" })).toBeVisible();+ await expect(contextual.getByText("Environments", { exact: true })).toBeVisible();+ await expect(page.getByRole("button", { name: "Back from Settings" })).toBeVisible();+ await expect(page.getByRole("button", { name: "Open account menu" })).toBeVisible();- // The app sidebar is NOT replaced — its company nav still renders...await expect(page.getByRole("link", { name: "Dashboard" })).toBeVisible();-- // ...but it is collapsed to its rail: the expanded-only "Open search"- // header control is hidden.await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toHaveCount(0);});- test("renders the secondary pane nav labels at full width despite the app rail collapse", async ({ page }) => {- // Regression (PAP-10700): the secondary pane is 240px wide, but its- // SidebarNavItem children read the *global* collapsed state and used to- // render icon-only (label `w-0 text-transparent`), making the settings nav- // unreadable in the default takeover state. The pane must force full labels.+ test("renders contextual labels at full width", async ({ page }) => {await page.goto(`/${prefix}/company/settings`);- const secondary = page.locator("[data-secondary-sidebar]");- await expect(secondary).toBeVisible();-- // App sidebar is collapsed to its rail (default unpinned takeover state)...- await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toHaveCount(0);-- // ...yet a settings nav label renders at its full text width, not clipped to- // zero. "Environments" is unique to the company-settings nav.- const envLabel = secondary.getByText("Environments", { exact: true });+ const contextual = page.locator('[data-contextual-sidebar="settings"]');+ const envLabel = contextual.getByText("Environments", { exact: true });await expect(envLabel).toBeVisible();const labelBox = await envLabel.boundingBox();expect(labelBox).not.toBeNull();expect(labelBox!.width).toBeGreaterThan(20);});- test("settings force-collapse overrides an expanded pin without mutating it", async ({ page }) => {- // User has pinned the sidebar expanded ("0"). Company settings is a hard- // secondary-sidebar takeover route, so forceCollapsed wins while the route is- // active (force > pin > route request > default) but must not mutate the pin.- await page.addInitScript(- ({ key }) => {- window.localStorage.setItem(key, "0");- },- { key: COLLAPSED_STORAGE_KEY },- );-+ test("keeps the retired collapse control absent across contextual navigation", async ({ page }) => {await page.goto(`/${prefix}/company/settings`);-- // Secondary pane still shows on the takeover route.- await expect(page.locator("[data-secondary-sidebar]")).toBeVisible();-- // The app sidebar is hard-collapsed despite the stored expanded pin.+ await expect(page.locator('[data-contextual-sidebar="settings"]')).toBeVisible();+ await expect(page.getByRole("link", { name: "Dashboard" })).toBeVisible();await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toHaveCount(0);await page.goto(`/${prefix}/dashboard`);- // Leaving the takeover route clears the force and restores the user's- // persisted expanded pin.- await expect(page.locator("[data-secondary-sidebar]")).toHaveCount(0);- await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toBeVisible();+ await expect(page.locator("[data-contextual-sidebar]")).toHaveCount(0);+ await expect(page.getByRole("link", { name: "Dashboard" })).toBeVisible();+ await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toHaveCount(0);});- test("leaving the takeover route removes the secondary pane and restores the sidebar", async ({ page }) => {+ test("uses Dashboard as the safe fallback for a direct Settings link", async ({ page }) => {await page.goto(`/${prefix}/company/settings`);- await expect(page.locator("[data-secondary-sidebar]")).toBeVisible();- await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toHaveCount(0);-- // Navigate to a plain (non-takeover) route.- await page.goto(`/${prefix}/dashboard`);+ await page.getByRole("button", { name: "Back from Settings" }).click();- // No secondary pane, and the app sidebar is no longer force-collapsed.- await expect(page.locator("[data-secondary-sidebar]")).toHaveCount(0);- await expect(page.getByLabel(APP_SIDEBAR_EXPANDED_MARKER)).toBeVisible();+ await expect(page).toHaveURL(new RegExp(`/${prefix}/dashboard$`));+ await expect(page.locator("[data-contextual-sidebar]")).toHaveCount(0);+ await expect(page.getByRole("link", { name: "Dashboard" })).toBeVisible();});});diff --git a/ui/src/components/AgentContextualSidebar.test.tsx b/ui/src/components/AgentContextualSidebar.test.tsxnew file mode 100644index 0000000000..f95068b2a3--- /dev/null+++ b/ui/src/components/AgentContextualSidebar.test.tsx@@ -0,0 +1,58 @@+// @vitest-environment jsdom++import { renderToStaticMarkup } from "react-dom/server";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router-dom";+import { describe, expect, it, vi } from "vitest";+import { AgentContextualSidebar } from "./AgentContextualSidebar";++vi.mock("@/context/CompanyContext", () => ({+ useCompany: () => ({ selectedCompanyId: "company-1" }),+}));++vi.mock("./ContextualSidebarFrame", () => ({+ ContextualSidebarFrame: ({+ title,+ showHeader,+ className,+ children,+ }: {+ title: string;+ showHeader?: boolean;+ className?: string;+ children: React.ReactNode;+ }) => (+ <aside data-title={title} data-show-header={String(showHeader)} className={className}>+ {children}+ </aside>+ ),+}));++vi.mock("./SidebarNavItem", () => ({+ SidebarNavItem: ({ to, label }: { to: string; label: string }) => <a href={to}>{label}</a>,+}));++describe("AgentContextualSidebar", () => {+ it("renders local definition/runtime/governance links and scoped Audit links", () => {+ const queryClient = new QueryClient();+ const markup = renderToStaticMarkup(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter initialEntries={["/agents/codexcoder/runtime"]}>+ <AgentContextualSidebar agentRef="codexcoder" agentId="agent-1" agentName="Codex Coder" />+ </MemoryRouter>+ </QueryClientProvider>,+ );++ expect(markup).toContain("Codex Coder");+ expect(markup).toContain('data-show-header="false"');+ expect(markup).toContain("border-r border-border bg-background");+ expect(markup).toContain('data-slot="contextual-sidebar-nav"');+ expect(markup).toContain('href="/agents/codexcoder/overview"');+ expect(markup).toContain('href="/agents/codexcoder/permissions"');+ expect(markup).toContain('href="/agents/codexcoder/api-keys"');+ expect(markup).toContain('href="/activity?mode=agents&agentId=agent-1"');+ expect(markup).toContain('href="/activity/runs?agentId=agent-1"');+ expect(markup).toContain("Harness / Runtime");+ expect(markup).toContain("Permissions / Trust");+ });+});diff --git a/ui/src/components/AgentContextualSidebar.tsx b/ui/src/components/AgentContextualSidebar.tsxnew file mode 100644index 0000000000..41b7489e66--- /dev/null+++ b/ui/src/components/AgentContextualSidebar.tsx@@ -0,0 +1,131 @@+import { useQuery } from "@tanstack/react-query";+import {+ Activity,+ BadgeDollarSign,+ BookOpenText,+ History,+ KeyRound,+ Library,+ PlayCircle,+ ReceiptText,+ Settings2,+ ShieldCheck,+ Sparkles,+ Wrench,+} from "lucide-react";+import { agentsApi } from "@/api/agents";+import { useCompany } from "@/context/CompanyContext";+import { queryKeys } from "@/lib/queryKeys";+import { ContextualSidebarFrame } from "./ContextualSidebarFrame";+import { SidebarNavItem } from "./SidebarNavItem";+import { contextualSidebarStyles } from "./contextual-sidebar-styles";+import {+ AGENT_DETAIL_NAVIGATION,+ agentDetailHref,+ agentScopedAuditHref,+ type AgentLocalDetailView,+} from "@/pages/agent-detail-navigation";++const localIcons = {+ overview: Sparkles,+ instructions: BookOpenText,+ skills: Library,+ runtime: Settings2,+ secrets: ShieldCheck,+ tools: Wrench,+ permissions: ShieldCheck,+ "api-keys": KeyRound,+ revisions: History,+} satisfies Record<AgentLocalDetailView, typeof Sparkles>;++const auditItems = [+ { section: "activity", label: "Activity", icon: Activity },+ { section: "runs", label: "Runs", icon: PlayCircle },+ { section: "costs", label: "Costs", icon: ReceiptText },+ { section: "budgets", label: "Budgets", icon: BadgeDollarSign },+] as const;++export function AgentContextualSidebar({+ agentRef,+ agentId,+ agentName,+}: {+ agentRef: string;+ agentId?: string;+ agentName?: string;+}) {+ const { selectedCompanyId } = useCompany();+ const shouldResolveAgent = !agentId || !agentName;+ const { data: resolvedAgent } = useQuery({+ queryKey: [...queryKeys.agents.detail(agentRef), selectedCompanyId ?? null, "contextual-sidebar"],+ queryFn: () => agentsApi.get(agentRef, selectedCompanyId ?? undefined),+ enabled: shouldResolveAgent && Boolean(agentRef && selectedCompanyId),+ });+ const resolvedId = agentId ?? resolvedAgent?.id;+ const resolvedName = agentName ?? resolvedAgent?.name ?? "Agent";++ return (+ <ContextualSidebarFrame+ surface="agent"+ title={resolvedName}+ fallbackTo="/agents/all"+ showHeader={false}+ className="border-r border-border bg-background"+ >+ <nav+ aria-label={`${resolvedName} navigation`}+ data-slot="contextual-sidebar-nav"+ className={contextualSidebarStyles.nav}+ >+ {AGENT_DETAIL_NAVIGATION.map((section) => (+ <div+ key={section.label}+ data-slot="contextual-sidebar-section"+ className={contextualSidebarStyles.section}+ >+ <p+ data-slot="contextual-sidebar-section-label"+ className={contextualSidebarStyles.sectionLabel}+ >+ {section.label}+ </p>+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>+ {section.items.map((item) => {+ const href = agentDetailHref(agentRef, item.value);+ return (+ <SidebarNavItem+ key={item.value}+ to={href}+ label={item.label}+ icon={localIcons[item.value]}+ />+ );+ })}+ </div>+ </div>+ ))}++ <div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>+ <p+ data-slot="contextual-sidebar-section-label"+ className={contextualSidebarStyles.sectionLabel}+ >+ Audit+ </p>+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>+ {resolvedId ? auditItems.map((item) => (+ <SidebarNavItem+ key={item.section}+ to={agentScopedAuditHref(resolvedId, item.section)}+ label={item.label}+ icon={item.icon}+ />+ )) : (+ <p className="px-2 py-1.5 text-xs text-muted-foreground">Loading audit links…</p>+ )}+ </div>+ </div>+ </nav>+ </ContextualSidebarFrame>+ );+}diff --git a/ui/src/components/AppConnectionSidebar.production.tsx b/ui/src/components/AppConnectionSidebar.production.tsxnew file mode 100644index 0000000000..8c2cb02e66--- /dev/null+++ b/ui/src/components/AppConnectionSidebar.production.tsx@@ -0,0 +1,154 @@+import { ChevronLeft } from "lucide-react";+import { useQuery } from "@tanstack/react-query";+import { humanizeConnectionDisplayName } from "@paperclipai/shared";+import type { ToolApplication, ToolConnection } from "@paperclipai/shared";+import { Link } from "@/lib/router";+import { toolsApi } from "@/api/tools";+import { useCompany } from "@/context/CompanyContext";+import { useSidebar } from "@/context/SidebarContext";+import { queryKeys } from "@/lib/queryKeys";+import {+ APP_TABS,+ CONNECTED_ONLY_APP_TABS,+ appApplicationTabHref,+ appTabHref,+ type AppTabKey,+} from "@/pages/apps/app-tabs";+import { AppLogo } from "@/pages/apps/AppLogo";+import {+ appDefinitionLogoUrl,+ appDefinitionName,+ appDefinitionSlug,+ type AppGalleryDisplayEntry,+} from "@/pages/apps/app-definition-display";+import { SidebarNavItem } from "./SidebarNavItem.production";++type AppDetailSidebarProps =+ | { kind: "connection"; connectionId: string }+ | { kind: "application"; applicationId: string };++export function AppDetailSidebar(props: AppDetailSidebarProps) {+ const { selectedCompanyId } = useCompany();+ const { isMobile, setSidebarOpen } = useSidebar();++ const connectionQuery = useQuery({+ queryKey: queryKeys.tools.connection(props.kind === "connection" ? props.connectionId : "__none__"),+ queryFn: () => toolsApi.getConnection(props.kind === "connection" ? props.connectionId : ""),+ enabled: props.kind === "connection" && !!props.connectionId,+ });+ const applicationsQuery = useQuery({+ queryKey: queryKeys.tools.applications(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listApplications(selectedCompanyId!),+ enabled: props.kind === "application" && !!selectedCompanyId,+ });+ const connectionsQuery = useQuery({+ queryKey: queryKeys.tools.connections(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listConnections(selectedCompanyId!),+ enabled: props.kind === "application" && !!selectedCompanyId,+ });+ const galleryQuery = useQuery({+ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listGallery(selectedCompanyId!),+ enabled: !!selectedCompanyId,+ });+ const attentionQuery = useQuery({+ queryKey: queryKeys.apps.attention(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listAppsAttention(selectedCompanyId!),+ enabled: !!selectedCompanyId,+ refetchInterval: 30_000,+ });++ const connection = connectionQuery.data;+ const application = props.kind === "application"+ ? (applicationsQuery.data?.applications ?? []).find((app) => app.id === props.applicationId)+ : null;+ const appConnections = props.kind === "application"+ ? (connectionsQuery.data?.connections ?? []).filter((candidate) => candidate.applicationId === props.applicationId)+ : [];+ const previousConnection = latestArchivedConnection(appConnections);+ const appName = connection ? humanizeConnectionDisplayName(connection) : application?.name ?? "App";+ const logoEntry = galleryEntryFor(+ (galleryQuery.data?.apps ?? []) as AppGalleryDisplayEntry[],+ connection,+ application ?? undefined,+ );+ const reviewConnectionId = connection?.id ?? previousConnection?.id ?? null;+ const attentionItem = reviewConnectionId+ ? attentionQuery.data?.apps.find((app) => app.connection.id === reviewConnectionId)+ : null;+ const reviewCount =+ (attentionItem?.pendingActionRequestCount ?? 0) ++ ((attentionItem?.quarantinedCatalogEntryCount ?? 0) > 0 ? 1 : 0);++ return (+ <aside className="flex h-full min-h-0 w-full flex-col border-r border-border bg-background">+ <div className="flex shrink-0 flex-col gap-3 px-3 py-3">+ <Link+ to="/apps/connections"+ onClick={() => {+ if (isMobile) setSidebarOpen(false);+ }}+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"+ >+ <ChevronLeft className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">All apps</span>+ </Link>+ <div className="flex min-w-0 items-center gap-2 px-2 py-1">+ <AppLogo name={appName} logoUrl={appDefinitionLogoUrl(logoEntry)} size={28} />+ <span className="flex-1 truncate text-sm font-bold text-foreground">{appName}</span>+ </div>+ </div>++ <nav className="scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-3 py-2">+ <div className="flex flex-col gap-0.5">+ {APP_TABS.filter(+ (tab) => props.kind === "connection" || !CONNECTED_ONLY_APP_TABS.has(tab.key),+ ).map((tab) => (+ <SidebarNavItem+ key={tab.key}+ to={tabHref(props, tab.key)}+ label={tab.label}+ icon={tab.icon}+ end+ badge={tab.key === "review" && reviewCount > 0 ? reviewCount : undefined}+ badgeTone="danger"+ badgeLabel="needing review"+ />+ ))}+ </div>+ </nav>+ </aside>+ );+}++function tabHref(props: AppDetailSidebarProps, tab: AppTabKey): string {+ return props.kind === "connection"+ ? appTabHref(props.connectionId, tab)+ : appApplicationTabHref(props.applicationId, tab);+}++function galleryEntryFor(+ apps: AppGalleryDisplayEntry[],+ connection: ToolConnection | undefined,+ application: ToolApplication | undefined,+): AppGalleryDisplayEntry | null {+ if (application?.applicationKey) {+ const keyed = apps.find((app) => appDefinitionSlug(app) === application.applicationKey);+ if (keyed) return keyed;+ }+ const name = (connection?.name ?? application?.name)?.toLowerCase();+ if (!name) return null;+ return apps.find((app) => appDefinitionName(app).toLowerCase() === name) ??+ apps.find((app) => appDefinitionSlug(app) === name) ??+ null;+}++function latestArchivedConnection(connections: ToolConnection[]): ToolConnection | null {+ const archived = connections.filter((connection) => connection.status === "archived");+ if (archived.length === 0) return null;+ return archived.reduce((latest, connection) => {+ const latestTime = new Date(latest.updatedAt ?? latest.createdAt ?? 0).getTime();+ const connectionTime = new Date(connection.updatedAt ?? connection.createdAt ?? 0).getTime();+ return connectionTime > latestTime ? connection : latest;+ });+}diff --git a/ui/src/components/AppsSidebar.production.tsx b/ui/src/components/AppsSidebar.production.tsxnew file mode 100644index 0000000000..d3f09d355d--- /dev/null+++ b/ui/src/components/AppsSidebar.production.tsx@@ -0,0 +1,92 @@+import { ChevronLeft, AppWindow, Store, ShieldQuestion } from "lucide-react";+import { Link } from "@/lib/router";+import { useCompany } from "@/context/CompanyContext";+import { useSidebar } from "@/context/SidebarContext";+import { DEVELOPER_TABS, advancedTabHref, isExperimentalToolTab } from "@/pages/tools/tool-tabs";+import { useSmokeLabEnabled } from "@/hooks/useSmokeLabEnabled";+import { useReviewCount } from "@/pages/apps/useReviewCount";+import { SidebarNavItem } from "./SidebarNavItem.production";++/**+ * Secondary sidebar for the prosumer Apps area (PAP-10856; three-door IA+ * PAP-13254 / U3).+ *+ * ← Back · APPS: Browse / Review (n)+ * DEVELOPER: Connections / Gateways / Profiles / Rules / Health / Activity+ *+ * "Browse" is the store and "Review" holds decisions waiting on the user's+ * OK. Connection management lives with the Developer tools.+ * "Needs attention" is no longer a door: health/error triage folds into+ * Connections as a status filter + banner, so approvals are never buried+ * behind an error label. The Developer section was folded in from the retired+ * ToolsSidebar (PAP-10915) so the whole Apps area shares one sidebar; a+ * one-line caption frames who it's for (Finding A). "Run your own" and "Paste a+ * config" moved out of the sidebar into rows on the Connect-an-app page+ * (PAP-10922).+ */+export function AppsSidebar() {+ const { selectedCompany } = useCompany();+ const { isMobile, setSidebarOpen } = useSidebar();++ const reviewCount = useReviewCount();+ const { enabled: smokeLabEnabled } = useSmokeLabEnabled();+ const developerTabs = DEVELOPER_TABS.filter(+ (tab) => !isExperimentalToolTab(tab.key) || smokeLabEnabled,+ );++ return (+ <aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">+ <div className="flex flex-col gap-1 px-3 py-3 shrink-0">+ <Link+ to="/dashboard"+ onClick={() => {+ if (isMobile) setSidebarOpen(false);+ }}+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"+ >+ <ChevronLeft className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">{selectedCompany?.name ?? "Company"}</span>+ </Link>+ <div className="flex items-center gap-2 px-2 py-1">+ <AppWindow className="h-4 w-4 text-muted-foreground shrink-0" />+ <span className="flex-1 truncate text-sm font-bold text-foreground">Apps</span>+ </div>+ </div>++ <nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2">+ <div className="px-3 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">+ Apps+ </div>+ <div className="flex flex-col gap-0.5">+ <SidebarNavItem to="/apps" label="Browse" icon={Store} end />+ <SidebarNavItem+ to="/apps/review"+ label="Review"+ icon={ShieldQuestion}+ badge={reviewCount > 0 ? reviewCount : undefined}+ badgeTone="warning"+ badgeLabel="waiting for your OK"+ />+ </div>+ <div className="px-3 pb-1 pt-4 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">+ Developer+ </div>+ <p className="px-3 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70">+ Advanced setup for developers. Most teams never open this.+ </p>+ <div className="flex flex-col gap-0.5">+ <SidebarNavItem to="/apps/connections" label="Connections" icon={AppWindow} end />+ {developerTabs.map((tab) => (+ <SidebarNavItem+ key={tab.key}+ to={advancedTabHref(tab.key)}+ label={tab.label}+ icon={tab.icon}+ end+ />+ ))}+ </div>+ </nav>+ </aside>+ );+}diff --git a/ui/src/components/AppsSidebar.test.tsx b/ui/src/components/AppsSidebar.test.tsxindex 84ea1cabf7..2f5c5fc29d 100644--- a/ui/src/components/AppsSidebar.test.tsx+++ b/ui/src/components/AppsSidebar.test.tsx@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { AppsSidebar } from "./AppsSidebar";+import { contextualSidebarStyles } from "./contextual-sidebar-styles";const sidebarNavItemMock = vi.hoisted(() => vi.fn());const mockToolsApi = vi.hoisted(() => ({@@ -97,7 +98,7 @@ describe("AppsSidebar", () => {vi.clearAllMocks();});- it("renders the consolidated connector and review doors without retired developer links", async () => {+ it("renders the consolidated connector and review doors without a redundant contextual heading", async () => {const root = createRoot(container);const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },@@ -112,7 +113,7 @@ describe("AppsSidebar", () => {});await flushReact();- expect(container.textContent).toContain("Apps");+ expect(container.textContent).not.toContain("Apps");expect(container.textContent).not.toContain("Developer");expect(container.textContent).not.toContain("Advanced setup for developers");expect(container.textContent).not.toContain("Most teams");@@ -152,6 +153,14 @@ describe("AppsSidebar", () => {expect(sidebarNavItemMock).not.toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/advanced/audit" }),);+ expect(container.querySelector('[data-slot="contextual-sidebar-nav"]')?.className).toBe(+ contextualSidebarStyles.nav,+ );+ expect(+ Array.from(container.querySelectorAll('[data-slot="contextual-sidebar-group"]')).every(+ (group) => group.className === contextualSidebarStyles.group,+ ),+ ).toBe(true);await act(async () => {root.unmount();diff --git a/ui/src/components/AppsSidebar.tsx b/ui/src/components/AppsSidebar.tsxindex 4e48641984..269eed5690 100644--- a/ui/src/components/AppsSidebar.tsx+++ b/ui/src/components/AppsSidebar.tsx@@ -1,25 +1,18 @@-import { ChevronLeft, AppWindow, Store, ShieldQuestion } from "lucide-react";-import { Link } from "@/lib/router";-import { useCompany } from "@/context/CompanyContext";-import { useSidebar } from "@/context/SidebarContext";+import { Store, ShieldQuestion } from "lucide-react";import { DEVELOPER_TABS, advancedTabHref, isExperimentalToolTab } from "@/pages/tools/tool-tabs";import { useSmokeLabEnabled } from "@/hooks/useSmokeLabEnabled";import { useReviewCount } from "@/pages/apps/useReviewCount";import { SidebarNavItem } from "./SidebarNavItem";+import { contextualSidebarStyles } from "./contextual-sidebar-styles";/*** Secondary sidebar for the Apps area.*- * ← Back · APPS: Connectors / Review (n)- *- * The landing page combines connector discovery, account management, and- * connection health. Review keeps governed actions waiting on the user's OK.- * Advanced developer surfaces remain hidden unless one is explicitly enabled.+ * Connectors combines discovery, account management, and connection health.+ * Review keeps governed actions waiting on the user's approval. Advanced+ * developer surfaces remain hidden unless one is explicitly enabled.*/export function AppsSidebar() {- const { selectedCompany } = useCompany();- const { isMobile, setSidebarOpen } = useSidebar();-const reviewCount = useReviewCount();const { enabled: smokeLabEnabled } = useSmokeLabEnabled();const developerTabs = DEVELOPER_TABS.filter((tab) => {@@ -31,28 +24,12 @@ export function AppsSidebar() {return (<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">- <div className="flex flex-col gap-1 px-3 py-3 shrink-0">- <Link- to="/dashboard"- onClick={() => {- if (isMobile) setSidebarOpen(false);- }}- className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"- >- <ChevronLeft className="h-3.5 w-3.5 shrink-0" />- <span className="truncate">{selectedCompany?.name ?? "Organization"}</span>- </Link>- <div className="flex items-center gap-2 px-2 py-1">- <AppWindow className="h-4 w-4 text-muted-foreground shrink-0" />- <span className="flex-1 truncate text-sm font-bold text-foreground">Apps</span>- </div>- </div>-- <nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2">- <div className="px-3 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">- Apps- </div>- <div className="flex flex-col gap-0.5">+ <nav+ aria-label="Apps"+ data-slot="contextual-sidebar-nav"+ className={contextualSidebarStyles.nav}+ >+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}><SidebarNavItem to="/apps" label="Connectors" icon={Store} end /><SidebarNavItemto="/apps/review"@@ -64,14 +41,20 @@ export function AppsSidebar() {/></div>{developerTabs.length > 0 ? (- <>- <div className="px-3 pb-1 pt-4 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">+ <div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>+ <div+ data-slot="contextual-sidebar-section-label"+ className={contextualSidebarStyles.sectionLabel}+ >Developer</div>- <p className="px-3 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70">+ <p+ data-slot="contextual-sidebar-section-description"+ className={contextualSidebarStyles.sectionDescription}+ >Advanced setup for developers.</p>- <div className="flex flex-col gap-0.5">+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>{developerTabs.map((tab) => (<SidebarNavItemkey={tab.key}@@ -82,7 +65,7 @@ export function AppsSidebar() {/>))}</div>- </>+ </div>) : null}</nav></aside>diff --git a/ui/src/components/BreadcrumbBar.production.tsx b/ui/src/components/BreadcrumbBar.production.tsxnew file mode 100644index 0000000000..3bb3407efe--- /dev/null+++ b/ui/src/components/BreadcrumbBar.production.tsx@@ -0,0 +1,160 @@+import { Link } from "@/lib/router";+import { Menu } from "lucide-react";+import { useBreadcrumbs } from "../context/BreadcrumbContext";+import { useSidebar } from "../context/SidebarContext";+import { useCompany } from "../context/CompanyContext";+import { Button } from "@/components/ui/button";+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+ BreadcrumbPage,+ BreadcrumbSeparator,+} from "@/components/ui/breadcrumb";+import { Fragment, useMemo } from "react";+import { PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";+import { PluginLauncherOutlet, usePluginLaunchers } from "@/plugins/launchers";++type GlobalToolbarContext = { companyId: string | null; companyPrefix: string | null };++/** Task identifier rendered in gray monospace between the glyph and the title. */+function CrumbIdentifier({ identifier }: { identifier?: string }) {+ if (!identifier) return null;+ return <span className="shrink-0 font-mono text-muted-foreground">{identifier}</span>;+}++function GlobalToolbar({ context }: { context: GlobalToolbarContext }) {+ const { slots } = usePluginSlots({ slotTypes: ["globalToolbarButton"], companyId: context.companyId });+ const { launchers } = usePluginLaunchers({ placementZones: ["globalToolbarButton"], companyId: context.companyId, enabled: !!context.companyId });+ return (+ <div className="ml-auto flex shrink-0 items-center gap-1 pl-2 empty:hidden">+ {slots.length > 0 ? (+ <PluginSlotOutlet slotTypes={["globalToolbarButton"]} context={context} className="flex items-center gap-1" />+ ) : null}+ {launchers.length > 0 ? (+ <PluginLauncherOutlet placementZones={["globalToolbarButton"]} context={context} className="flex items-center gap-1" />+ ) : null}+ </div>+ );+}++export function BreadcrumbBar() {+ const { breadcrumbs, mobileToolbar } = useBreadcrumbs();+ const { toggleSidebar, isMobile } = useSidebar();+ const { selectedCompanyId, selectedCompany } = useCompany();++ const globalToolbarSlotContext = useMemo(+ () => ({+ companyId: selectedCompanyId ?? null,+ companyPrefix: selectedCompany?.issuePrefix ?? null,+ }),+ [selectedCompanyId, selectedCompany?.issuePrefix],+ );++ const globalToolbarSlots = <GlobalToolbar context={globalToolbarSlotContext} />;++ if (isMobile && mobileToolbar) {+ return (+ <div className="border-b border-border px-2 h-12 shrink-0 flex items-center">+ {mobileToolbar}+ </div>+ );+ }++ if (breadcrumbs.length === 0) {+ return (+ <div className="border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end">+ {globalToolbarSlots}+ </div>+ );+ }++ const menuButton = isMobile && (+ <Button+ variant="ghost"+ size="icon-sm"+ className="mr-2 shrink-0"+ onClick={toggleSidebar}+ aria-label="Open sidebar"+ >+ <Menu className="h-5 w-5" />+ </Button>+ );++ // Single breadcrumb = page title (uppercase)+ if (breadcrumbs.length === 1) {+ return (+ <div className="border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center">+ {menuButton}+ <div className="min-w-0 overflow-hidden flex-1">+ {breadcrumbs[0].leading || breadcrumbs[0].identifier ? (+ <h1 className="flex items-center gap-1.5 text-sm font-semibold uppercase tracking-wider">+ {breadcrumbs[0].leading && (+ <span className="flex shrink-0 items-center">{breadcrumbs[0].leading}</span>+ )}+ <CrumbIdentifier identifier={breadcrumbs[0].identifier} />+ <span className="truncate">{breadcrumbs[0].label}</span>+ </h1>+ ) : (+ <h1 className="text-sm font-semibold uppercase tracking-wider truncate">+ {breadcrumbs[0].label}+ </h1>+ )}+ </div>+ {globalToolbarSlots}+ </div>+ );+ }++ // Multiple breadcrumbs = breadcrumb trail+ return (+ <div className="border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center">+ {menuButton}+ <div className="min-w-0 overflow-hidden flex-1">+ <Breadcrumb className="min-w-0 overflow-hidden">+ <BreadcrumbList className="flex-nowrap">+ {breadcrumbs.map((crumb, i) => {+ const isLast = i === breadcrumbs.length - 1;+ return (+ <Fragment key={i}>+ {i > 0 && <BreadcrumbSeparator />}+ <BreadcrumbItem className={isLast ? "min-w-0" : "shrink-0"}>+ {isLast || !crumb.href ? (+ crumb.leading || crumb.identifier ? (+ <BreadcrumbPage className="flex min-w-0 items-center gap-1.5">+ {crumb.leading && (+ <span className="flex shrink-0 items-center">{crumb.leading}</span>+ )}+ <CrumbIdentifier identifier={crumb.identifier} />+ <span className="truncate">{crumb.label}</span>+ </BreadcrumbPage>+ ) : (+ <BreadcrumbPage className="truncate">{crumb.label}</BreadcrumbPage>+ )+ ) : (+ <BreadcrumbLink asChild>+ {crumb.leading || crumb.identifier ? (+ <Link to={crumb.href} className="flex items-center gap-1.5">+ {crumb.leading && (+ <span className="flex shrink-0 items-center">{crumb.leading}</span>+ )}+ <CrumbIdentifier identifier={crumb.identifier} />+ <span className="truncate">{crumb.label}</span>+ </Link>+ ) : (+ <Link to={crumb.href}>{crumb.label}</Link>+ )}+ </BreadcrumbLink>+ )}+ </BreadcrumbItem>+ </Fragment>+ );+ })}+ </BreadcrumbList>+ </Breadcrumb>+ </div>+ {globalToolbarSlots}+ </div>+ );+}diff --git a/ui/src/components/BreadcrumbBar.test.tsx b/ui/src/components/BreadcrumbBar.test.tsxindex 373f742905..e002a40539 100644--- a/ui/src/components/BreadcrumbBar.test.tsx+++ b/ui/src/components/BreadcrumbBar.test.tsx@@ -7,17 +7,26 @@ import { BreadcrumbProvider, useBreadcrumbs } from "../context/BreadcrumbContextimport { BreadcrumbBar } from "./BreadcrumbBar";vi.mock("@/lib/router", () => ({- Link: ({ children, to }: { children: ReactNode; to: string }) => (- <a href={to}>{children}</a>+ Link: ({ children, className, to }: { children: ReactNode; className?: string; to: string }) => (+ <a className={className} href={to}>{children}</a>),}));vi.mock("../context/SidebarContext", () => ({- useSidebar: () => ({ isMobile: false, toggleSidebar: vi.fn() }),+ useSidebar: () => ({+ collapsed: false,+ isMobile: false,+ toggleCollapsed: vi.fn(),+ toggleSidebar: vi.fn(),+ }),}));vi.mock("../context/CompanyContext", () => ({- useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { issuePrefix: "PAP" } }),+ useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { issuePrefix: "TES" } }),+}));++vi.mock("../context/PanelContext", () => ({+ usePanel: () => ({ panelVisible: true, togglePanelVisible: vi.fn() }),}));vi.mock("@/plugins/slots", () => ({@@ -30,25 +39,59 @@ vi.mock("@/plugins/launchers", () => ({PluginLauncherOutlet: () => null,}));-function TaskBreadcrumbs({ onOpen }: { onOpen: () => void }) {- const { setBreadcrumbs, setBreadcrumbToolbar } = useBreadcrumbs();+function TaskBreadcrumbs({+ onOpen,+ panelControl,+ taskDetailLayout = false,+ identifier = "PAP-16679",+}: {+ onOpen?: () => void;+ panelControl?: { open: boolean; onToggle: () => void };+ taskDetailLayout?: boolean;+ identifier?: string;+}) {+ const {+ setBreadcrumbs,+ setBreadcrumbToolbar,+ setBreadcrumbPanelControl,+ } = useBreadcrumbs();useEffect(() => {setBreadcrumbs([- { label: "Tasks", href: "/tasks" },- { label: "Keep the panel launcher available", identifier: "PAP-16679" },+ { label: "Tasks", href: "/issues" },+ {+ label: "Hire your first engineer and create a hiring plan",+ identifier,+ leading: "status",+ },]);setBreadcrumbToolbar(- <button type="button" aria-label="Show task side panel" onClick={onOpen}>- Show panel- </button>,+ onOpen ? (+ <button type="button" aria-label="Show task side panel" onClick={onOpen}>+ Show panel+ </button>+ ) : null,);- return () => setBreadcrumbToolbar(null);- }, [onOpen, setBreadcrumbToolbar, setBreadcrumbs]);+ setBreadcrumbPanelControl(panelControl ?? null);+ return () => {+ setBreadcrumbToolbar(null);+ setBreadcrumbPanelControl(null);+ };+ }, [+ identifier,+ onOpen,+ panelControl,+ setBreadcrumbPanelControl,+ setBreadcrumbToolbar,+ setBreadcrumbs,+ ]);- return <BreadcrumbBar />;+ return <BreadcrumbBar taskDetailLayout={taskDetailLayout} />;}+// eslint-disable-next-line @typescript-eslint/no-explicit-any+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;+describe("BreadcrumbBar", () => {let container: HTMLDivElement;let root: Root;@@ -78,9 +121,103 @@ describe("BreadcrumbBar", () => {'button[aria-label="Show task side panel"]',);expect(launcher).not.toBeNull();- expect(launcher?.closest(".h-12")?.textContent).toContain("PAP-16679");+ expect(launcher?.closest(".h-\\(--sz-60px\\)")?.textContent).toContain("PAP-16679");act(() => launcher?.click());expect(onOpen).toHaveBeenCalledOnce();});++ it("appends the task identifier to the task title in the task-detail header", async () => {+ await act(async () => {+ root.render(+ <BreadcrumbProvider>+ <TaskBreadcrumbs taskDetailLayout identifier="TES-1" />+ </BreadcrumbProvider>,+ );+ });++ const identifier = container.querySelector('[data-slot="task-title-identifier"]');+ expect(identifier).toBeTruthy();+ expect(identifier?.className).not.toContain("absolute");+ expect(identifier?.closest(".relative")?.className).toContain("border-b");+ expect(identifier?.closest(".relative")?.className).toContain("border-border");+ expect(identifier?.closest(".relative")?.className).toContain("h-(--sz-60px)");++ const title = Array.from(container.querySelectorAll("span"))+ .find((element) => element.textContent === "Hire your first engineer and create a hiring plan");+ const tasksLink = container.querySelector<HTMLAnchorElement>('a[href="/issues"]');+ const header = tasksLink?.closest(".relative");+ expect(header?.classList).toContain("px-4");+ expect(header?.classList).toContain("md:px-6");+ expect(header?.classList).not.toContain("px-3");+ expect(tasksLink?.classList).toContain("font-semibold");+ expect(tasksLink?.classList).toContain("tracking-wider");+ expect(tasksLink?.classList).toContain("text-muted-foreground");+ expect(tasksLink?.classList).toContain("hover:text-foreground");+ expect(tasksLink?.classList).not.toContain("font-bold");+ expect(title?.className).toContain("truncate");+ expect(title?.nextElementSibling).toBe(identifier);+ expect(identifier?.textContent).toBe("TES-1");+ });++ it("styles the root crumb as an uppercase muted header on every detail view", async () => {+ await act(async () => {+ root.render(+ <BreadcrumbProvider>+ <TaskBreadcrumbs />+ </BreadcrumbProvider>,+ );+ });++ const rootCrumb = container.querySelector<HTMLAnchorElement>('a[href="/issues"]');+ expect(rootCrumb?.classList).toContain("font-semibold");+ expect(rootCrumb?.classList).toContain("uppercase");+ expect(rootCrumb?.classList).toContain("tracking-wider");+ expect(rootCrumb?.classList).toContain("text-muted-foreground");+ expect(rootCrumb?.classList).toContain("hover:text-foreground");+ });++ it("routes the single task-detail panel button through a page override", async () => {+ const onToggle = vi.fn();+ const panelControl = { open: false, onToggle };+ await act(async () => {+ root.render(+ <BreadcrumbProvider>+ <TaskBreadcrumbs taskDetailLayout panelControl={panelControl} />+ </BreadcrumbProvider>,+ );+ });++ const launcher = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show properties"]',+ );+ expect(launcher).not.toBeNull();+ expect(container.querySelector('button[aria-label="Hide properties"]')).toBeNull();++ act(() => launcher?.click());+ expect(onToggle).toHaveBeenCalledOnce();+ });++ it("omits the retired sidebar control and keeps the properties control", async () => {+ await act(async () => {+ root.render(+ <BreadcrumbProvider>+ <TaskBreadcrumbs taskDetailLayout />+ </BreadcrumbProvider>,+ );+ });++ const leftControl = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Collapse sidebar"]',+ );+ const rightControl = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Hide properties"]',+ );++ expect(leftControl).toBeNull();+ expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();+ expect(rightControl?.className).toContain("size-9");+ expect(rightControl?.className).not.toContain("rounded-none");+ expect(rightControl?.className).not.toContain("h-full");+ });});diff --git a/ui/src/components/BreadcrumbBar.tsx b/ui/src/components/BreadcrumbBar.tsxindex b29d24cc89..751bdc7fdd 100644--- a/ui/src/components/BreadcrumbBar.tsx+++ b/ui/src/components/BreadcrumbBar.tsx@@ -1,8 +1,9 @@import { Link } from "@/lib/router";-import { Menu } from "lucide-react";+import { Menu, PanelRightClose, PanelRightOpen } from "lucide-react";import { useBreadcrumbs } from "../context/BreadcrumbContext";import { useSidebar } from "../context/SidebarContext";import { useCompany } from "../context/CompanyContext";+import { usePanel } from "../context/PanelContext";import { Button } from "@/components/ui/button";import {Breadcrumb,@@ -15,13 +16,18 @@ import {import { Fragment, useMemo, type ReactNode } from "react";import { PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";import { PluginLauncherOutlet, usePluginLaunchers } from "@/plugins/launchers";+import { cn } from "../lib/utils";type GlobalToolbarContext = { companyId: string | null; companyPrefix: string | null };-/** Task identifier rendered in gray monospace between the glyph and the title. */+/** Task identifier rendered in gray monospace beside its breadcrumb label. */function CrumbIdentifier({ identifier }: { identifier?: string }) {if (!identifier) return null;- return <span className="shrink-0 font-mono text-muted-foreground">{identifier}</span>;+ return (+ <span data-slot="task-title-identifier" className="shrink-0 font-mono text-muted-foreground">+ {identifier}+ </span>+ );}function GlobalToolbar({@@ -46,10 +52,18 @@ function GlobalToolbar({);}-export function BreadcrumbBar() {- const { breadcrumbs, breadcrumbToolbar, mobileToolbar } = useBreadcrumbs();+export function BreadcrumbBar({ taskDetailLayout = false }: { taskDetailLayout?: boolean }) {+ const {+ breadcrumbs,+ breadcrumbToolbar,+ breadcrumbPanelControl,+ mobileToolbar,+ } = useBreadcrumbs();const { toggleSidebar, isMobile } = useSidebar();+ const { panelVisible, togglePanelVisible } = usePanel();const { selectedCompanyId, selectedCompany } = useCompany();+ const taskPanelOpen = breadcrumbPanelControl?.open ?? panelVisible;+ const toggleTaskPanel = breadcrumbPanelControl?.onToggle ?? togglePanelVisible;const globalToolbarSlotContext = useMemo(() => ({@@ -68,7 +82,7 @@ export function BreadcrumbBar() {if (isMobile && mobileToolbar) {return (- <div className="border-b border-border px-2 h-12 shrink-0 flex items-center">+ <div className="h-(--sz-60px) shrink-0 flex items-center border-b border-border px-2">{mobileToolbar}</div>);@@ -76,7 +90,7 @@ export function BreadcrumbBar() {if (breadcrumbs.length === 0) {return (- <div className="border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end">+ <div className="h-(--sz-60px) shrink-0 flex items-center justify-end border-b border-border px-4 md:px-6">{globalToolbarSlots}</div>);@@ -94,10 +108,72 @@ export function BreadcrumbBar() {</Button>);+ const breadcrumbTrail = (+ <div className="min-w-0 overflow-hidden flex-1">+ <Breadcrumb className="min-w-0 overflow-hidden">+ <BreadcrumbList className="flex-nowrap">+ {breadcrumbs.map((crumb, i) => {+ const isLast = i === breadcrumbs.length - 1;+ return (+ <Fragment key={i}>+ {i > 0 && <BreadcrumbSeparator />}+ <BreadcrumbItem className={isLast ? "min-w-0" : "shrink-0"}>+ {isLast || !crumb.href ? (+ crumb.leading || crumb.identifier ? (+ <BreadcrumbPage className="flex min-w-0 items-center gap-1.5">+ {crumb.leading && (+ <span className="flex shrink-0 items-center">{crumb.leading}</span>+ )}+ {!taskDetailLayout ? <CrumbIdentifier identifier={crumb.identifier} /> : null}+ <span className="min-w-0 truncate">{crumb.label}</span>+ {taskDetailLayout && isLast ? <CrumbIdentifier identifier={crumb.identifier} /> : null}+ </BreadcrumbPage>+ ) : (+ <BreadcrumbPage className="truncate">{crumb.label}</BreadcrumbPage>+ )+ ) : (+ <BreadcrumbLink asChild>+ {crumb.leading || crumb.identifier ? (+ <Link+ to={crumb.href}+ className={cn(+ "flex min-w-0 items-center gap-1.5",+ i === 0 && "font-semibold uppercase tracking-wider text-muted-foreground hover:text-foreground",+ )}+ >+ {crumb.leading && (+ <span className="flex shrink-0 items-center">{crumb.leading}</span>+ )}+ {!taskDetailLayout ? <CrumbIdentifier identifier={crumb.identifier} /> : null}+ <span className="min-w-0 truncate">{crumb.label}</span>+ {taskDetailLayout && isLast ? <CrumbIdentifier identifier={crumb.identifier} /> : null}+ </Link>+ ) : (+ <Link+ to={crumb.href}+ className={cn(+ "min-w-0 truncate",+ i === 0 && "font-semibold uppercase tracking-wider text-muted-foreground hover:text-foreground",+ )}+ >+ {crumb.label}+ </Link>+ )}+ </BreadcrumbLink>+ )}+ </BreadcrumbItem>+ </Fragment>+ );+ })}+ </BreadcrumbList>+ </Breadcrumb>+ </div>+ );+// Single breadcrumb = page title (uppercase)if (breadcrumbs.length === 1) {return (- <div className="border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center">+ <div className="h-(--sz-60px) shrink-0 flex items-center border-b border-border px-4 md:px-6">{menuButton}<div className="min-w-0 overflow-hidden flex-1">{breadcrumbs[0].leading || breadcrumbs[0].identifier ? (@@ -121,52 +197,27 @@ export function BreadcrumbBar() {// Multiple breadcrumbs = breadcrumb trailreturn (- <div className="border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center">+ <div+ className={cn(+ "relative h-(--sz-60px) shrink-0 flex items-center border-b border-border",+ "px-4 md:px-6",+ )}+ >{menuButton}- <div className="min-w-0 overflow-hidden flex-1">- <Breadcrumb className="min-w-0 overflow-hidden">- <BreadcrumbList className="flex-nowrap">- {breadcrumbs.map((crumb, i) => {- const isLast = i === breadcrumbs.length - 1;- return (- <Fragment key={i}>- {i > 0 && <BreadcrumbSeparator />}- <BreadcrumbItem className={isLast ? "min-w-0" : "shrink-0"}>- {isLast || !crumb.href ? (- crumb.leading || crumb.identifier ? (- <BreadcrumbPage className="flex min-w-0 items-center gap-1.5">- {crumb.leading && (- <span className="flex shrink-0 items-center">{crumb.leading}</span>- )}- <CrumbIdentifier identifier={crumb.identifier} />- <span className="truncate">{crumb.label}</span>- </BreadcrumbPage>- ) : (- <BreadcrumbPage className="truncate">{crumb.label}</BreadcrumbPage>- )- ) : (- <BreadcrumbLink asChild>- {crumb.leading || crumb.identifier ? (- <Link to={crumb.href} className="flex items-center gap-1.5">- {crumb.leading && (- <span className="flex shrink-0 items-center">{crumb.leading}</span>- )}- <CrumbIdentifier identifier={crumb.identifier} />- <span className="truncate">{crumb.label}</span>- </Link>- ) : (- <Link to={crumb.href}>{crumb.label}</Link>- )}- </BreadcrumbLink>- )}- </BreadcrumbItem>- </Fragment>- );- })}- </BreadcrumbList>- </Breadcrumb>- </div>+ {breadcrumbTrail}{globalToolbarSlots}+ {taskDetailLayout ? (+ <Button+ variant="ghost"+ size="icon-sm"+ className="ml-5 size-9 shrink-0 text-muted-foreground"+ onClick={toggleTaskPanel}+ aria-label={taskPanelOpen ? "Hide properties" : "Show properties"}+ title={taskPanelOpen ? "Hide properties" : "Show properties"}+ >+ {taskPanelOpen ? <PanelRightClose className="h-4 w-4" /> : <PanelRightOpen className="h-4 w-4" />}+ </Button>+ ) : null}</div>);}diff --git a/ui/src/components/CompanySettingsSidebar.production.tsx b/ui/src/components/CompanySettingsSidebar.production.tsxnew file mode 100644index 0000000000..4080d1afff--- /dev/null+++ b/ui/src/components/CompanySettingsSidebar.production.tsx@@ -0,0 +1,214 @@+import { useQuery } from "@tanstack/react-query";+import {+ ChevronLeft,+ Clock3,+ Cpu,+ Download,+ FlaskConical,+ KeyRound,+ MailPlus,+ MonitorCog,+ Puzzle,+ Shield,+ SlidersHorizontal,+ Upload,+ UserRoundPen,+ Users,+} from "lucide-react";+import type { PluginRecord } from "@paperclipai/shared";+import { sidebarBadgesApi } from "@/api/sidebarBadges";+import { pluginsApi } from "@/api/plugins";+import { ApiError } from "@/api/client";+import { Link, NavLink } from "@/lib/router";+import { INSTANCE_SETTINGS_PATH_PREFIX } from "@/lib/instance-settings";+import { SIDEBAR_SCROLL_RESET_STATE } from "@/lib/navigation-scroll";+import { queryKeys } from "@/lib/queryKeys";+import { useCompany } from "@/context/CompanyContext";+import { useSidebar } from "@/context/SidebarContext";+import { useCloudInstance } from "@/hooks/useCloudInstance";+import { useHiddenSettings } from "@/hooks/useHiddenSettings";+import { usePluginSlots } from "@/plugins/slots";+import { SidebarNavItem } from "./SidebarNavItem.production";++/**+ * Sandbox-provider-only plugins (e.g. E2B, exe.dev, Modal) have no per-plugin+ * settings page, so a sidebar entry would lead nowhere useful. Filter them out+ * here. Plugins that mix a sandbox provider with other contributions still+ * appear.+ */+function isSandboxProviderOnly(plugin: PluginRecord): boolean {+ const drivers = plugin.manifestJson.environmentDrivers ?? [];+ if (drivers.length === 0) return false;+ return drivers.every((d) => d.kind === "sandbox_provider");+}++export function CompanySettingsSidebar() {+ const { selectedCompany, selectedCompanyId } = useCompany();+ const { isMobile, setSidebarOpen } = useSidebar();+ const { hidden: hiddenSettings } = useHiddenSettings();+ const showPage = (pageKey: string) => !hiddenSettings.has(pageKey);+ const showPlugins = showPage("instance.plugins");+ // Import is floored server-side on cloud-managed instances (403 cloud_managed), so the+ // nav entry is hidden rather than dead-ending. Export stays available.+ const isCloud = Boolean(useCloudInstance());+ const { slots: companySettingsPluginSlots } = usePluginSlots({+ slotTypes: ["companySettingsPage"],+ companyId: selectedCompanyId,+ enabled: !!selectedCompanyId,+ });+ const { data: badges } = useQuery({+ queryKey: selectedCompanyId+ ? queryKeys.sidebarBadges(selectedCompanyId)+ : ["sidebar-badges", "__disabled__"] as const,+ queryFn: async () => {+ try {+ return await sidebarBadgesApi.get(selectedCompanyId!);+ } catch (error) {+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {+ return null;+ }+ throw error;+ }+ },+ enabled: !!selectedCompanyId,+ retry: false,+ refetchInterval: 15_000,+ });+ const { data: plugins } = useQuery({+ queryKey: queryKeys.plugins.all,+ queryFn: () => pluginsApi.list(),+ // The listing only feeds the per-plugin subtree below; skip it when the+ // operator hides the Plugins surface.+ enabled: showPlugins,+ });+ const sidebarPlugins = (plugins ?? []).filter((plugin) => !isSandboxProviderOnly(plugin));++ return (+ <aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">+ <div className="flex flex-col gap-1 px-3 py-3 shrink-0">+ <Link+ to="/dashboard"+ onClick={() => {+ if (isMobile) setSidebarOpen(false);+ }}+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"+ >+ <ChevronLeft className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">{selectedCompany?.name ?? "Company"}</span>+ </Link>+ </div>++ <nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2">+ <div className="flex flex-col gap-0.5">+ <SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end />+ {showPage("instance.profile") && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`}+ label="Profile"+ icon={UserRoundPen}+ end+ />+ )}+ {showPage("company.members") && (+ <SidebarNavItem+ to="/company/settings/members"+ label="Members"+ icon={Users}+ badge={badges?.joinRequests ?? 0}+ end+ />+ )}+ {companySettingsPluginSlots+ .filter((slot) => slot.routePath)+ .map((slot) => (+ <SidebarNavItem+ key={`${slot.pluginKey}:${slot.id}`}+ to={`/company/settings/${slot.routePath}`}+ label={slot.displayName}+ icon={Puzzle}+ end+ />+ ))}+ {showPage("company.invites") && (+ <SidebarNavItem to="/company/settings/invites" label="Invites" icon={MailPlus} end />+ )}+ {showPage("company.secrets") && (+ <SidebarNavItem to="/company/settings/secrets" label="Secrets" icon={KeyRound} end />+ )}+ {showPage("instance.environments") && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`}+ label="Environments"+ icon={MonitorCog}+ end+ />+ )}+ {showPage("instance.access") && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}+ label="Access"+ icon={Shield}+ end+ />+ )}+ {showPage("instance.heartbeats") && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/heartbeats`}+ label="Heartbeats"+ icon={Clock3}+ end+ />+ )}+ {showPage("company.export") && (+ <SidebarNavItem to="/company/export" label="Export" icon={Download} />+ )}+ {!isCloud && showPage("company.import") && (+ <SidebarNavItem to="/company/import" label="Import" icon={Upload} end />+ )}+ {showPage("instance.experimental") && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`}+ label="Experimental"+ icon={FlaskConical}+ />+ )}+ {showPlugins && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`}+ label="Plugins"+ icon={Puzzle}+ />+ )}+ {showPlugins && sidebarPlugins.length > 0 ? (+ <div className="ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3">+ {sidebarPlugins.map((plugin) => (+ <NavLink+ key={plugin.id}+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins/${plugin.id}`}+ state={SIDEBAR_SCROLL_RESET_STATE}+ className={({ isActive }) =>+ [+ "rounded-md px-2 py-1.5 text-xs transition-colors",+ isActive+ ? "bg-accent text-foreground"+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",+ ].join(" ")+ }+ >+ {plugin.manifestJson.displayName ?? plugin.packageName}+ </NavLink>+ ))}+ </div>+ ) : null}+ {showPage("instance.adapters") && (+ <SidebarNavItem+ to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`}+ label="Adapters"+ icon={Cpu}+ />+ )}+ </div>+ </nav>+ </aside>+ );+}diff --git a/ui/src/components/CompanySettingsSidebar.test.tsx b/ui/src/components/CompanySettingsSidebar.test.tsxindex 96c1551260..0fde10d0ce 100644--- a/ui/src/components/CompanySettingsSidebar.test.tsx+++ b/ui/src/components/CompanySettingsSidebar.test.tsx@@ -16,6 +16,7 @@ const mockPluginsApi = vi.hoisted(() => ({const mockUsePluginSlots = vi.hoisted(() => vi.fn());vi.mock("@/lib/router", () => ({+ useNavigate: () => vi.fn(),Link: ({children,to,@@ -41,7 +42,7 @@ vi.mock("@/lib/router", () => ({vi.mock("@/context/CompanyContext", () => ({useCompany: () => ({selectedCompanyId: "company-1",- selectedCompany: { id: "company-1", name: "Paperclip" },+ selectedCompany: { id: "company-1", issuePrefix: "PAP", name: "Paperclip" },}),}));@@ -53,6 +54,7 @@ vi.mock("@/context/SidebarContext", () => ({}));vi.mock("./SidebarNavItem", () => ({+ SidebarNavExpandedProvider: ({ children }: { children: React.ReactNode }) => children,SidebarNavItem: (props: {to: string;label: string;diff --git a/ui/src/components/CompanySettingsSidebar.tsx b/ui/src/components/CompanySettingsSidebar.tsxindex f7c1977602..43887f56db 100644--- a/ui/src/components/CompanySettingsSidebar.tsx+++ b/ui/src/components/CompanySettingsSidebar.tsx@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";import {- ChevronLeft,Cpu,Download,FlaskConical,@@ -17,16 +16,16 @@ import type { PluginRecord } from "@paperclipai/shared";import { sidebarBadgesApi } from "@/api/sidebarBadges";import { pluginsApi } from "@/api/plugins";import { ApiError } from "@/api/client";-import { Link, NavLink } from "@/lib/router";+import { NavLink } from "@/lib/router";import { INSTANCE_SETTINGS_PATH_PREFIX } from "@/lib/instance-settings";import { SIDEBAR_SCROLL_RESET_STATE } from "@/lib/navigation-scroll";import { queryKeys } from "@/lib/queryKeys";import { useCompany } from "@/context/CompanyContext";-import { useSidebar } from "@/context/SidebarContext";import { useCloudInstance } from "@/hooks/useCloudInstance";import { useHiddenSettings } from "@/hooks/useHiddenSettings";import { usePluginSlots } from "@/plugins/slots";import { SidebarNavItem } from "./SidebarNavItem";+import { ContextualSidebarFrame } from "./ContextualSidebarFrame";/*** Sandbox-provider-only plugins (e.g. E2B, exe.dev, Modal) have no per-plugin@@ -41,8 +40,7 @@ function isSandboxProviderOnly(plugin: PluginRecord): boolean {}export function CompanySettingsSidebar() {- const { selectedCompany, selectedCompanyId } = useCompany();- const { isMobile, setSidebarOpen } = useSidebar();+ const { selectedCompanyId } = useCompany();const { hidden: hiddenSettings } = useHiddenSettings();const showPage = (pageKey: string) => !hiddenSettings.has(pageKey);const showPlugins = showPage("instance.plugins");@@ -82,20 +80,7 @@ export function CompanySettingsSidebar() {const sidebarPlugins = (plugins ?? []).filter((plugin) => !isSandboxProviderOnly(plugin));return (- <aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">- <div className="flex flex-col gap-1 px-3 py-3 shrink-0">- <Link- to="/dashboard"- onClick={() => {- if (isMobile) setSidebarOpen(false);- }}- className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"- >- <ChevronLeft className="h-3.5 w-3.5 shrink-0" />- <span className="truncate">{selectedCompany?.name ?? "Organization"}</span>- </Link>- </div>-+ <ContextualSidebarFrame surface="settings" title="Settings" icon={SlidersHorizontal}><nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2"><div className="flex flex-col gap-0.5"><SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end />@@ -196,6 +181,6 @@ export function CompanySettingsSidebar() {)}</div></nav>- </aside>+ </ContextualSidebarFrame>);}diff --git a/ui/src/components/ContextualSidebarFrame.test.tsx b/ui/src/components/ContextualSidebarFrame.test.tsxnew file mode 100644index 0000000000..c196847551--- /dev/null+++ b/ui/src/components/ContextualSidebarFrame.test.tsx@@ -0,0 +1,90 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Settings } from "lucide-react";+import { ContextualSidebarFrame } from "./ContextualSidebarFrame";+import { rememberContextualSidebarOrigin } from "@/lib/shell-navigation";++const mockNavigate = vi.hoisted(() => vi.fn());++vi.mock("@/lib/router", () => ({ useNavigate: () => mockNavigate }));+vi.mock("@/context/CompanyContext", () => ({+ useCompany: () => ({ selectedCompany: { name: "Paperclip", issuePrefix: "PAP" } }),+}));+vi.mock("@/context/SidebarContext", () => ({+ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn(), collapsed: true, peeking: false }),+}));++// eslint-disable-next-line @typescript-eslint/no-explicit-any+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;++describe("ContextualSidebarFrame", () => {+ let container: HTMLDivElement;++ beforeEach(() => {+ window.sessionStorage.clear();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ container.remove();+ vi.clearAllMocks();+ });++ function render() {+ const root = createRoot(container);+ act(() => {+ root.render(+ <ContextualSidebarFrame surface="settings" title="Settings" icon={Settings}>+ <nav>Settings links</nav>+ </ContextualSidebarFrame>,+ );+ });+ return root;+ }++ it("renders the contextual identity and uses a safe fallback", () => {+ const root = render();+ expect(container.textContent).toContain("Paperclip");+ expect(container.textContent).toContain("Settings");++ act(() => {+ container.querySelector<HTMLButtonElement>('button[aria-label="Back from Settings"]')?.click();+ });+ expect(mockNavigate).toHaveBeenCalledWith("/dashboard");+ act(() => root.unmount());+ });++ it("returns to the same-company route that opened the contextual surface", () => {+ rememberContextualSidebarOrigin({+ surface: "settings",+ companyPrefix: "PAP",+ previousPathname: "/PAP/issues/task-1",+ });+ const root = render();++ act(() => {+ container.querySelector<HTMLButtonElement>('button[aria-label="Back from Settings"]')?.click();+ });+ expect(mockNavigate).toHaveBeenCalledWith("/PAP/issues/task-1");+ act(() => root.unmount());+ });++ it("can omit contextual identity when the breadcrumb already provides it", () => {+ const root = createRoot(container);+ act(() => {+ root.render(+ <ContextualSidebarFrame surface="skills" title="Skills" showHeader={false}>+ <nav>Skill links</nav>+ </ContextualSidebarFrame>,+ );+ });++ expect(container.textContent).toBe("Skill links");+ expect(container.querySelector('[aria-label="Back from Skills"]')).toBeNull();+ act(() => root.unmount());+ });+});diff --git a/ui/src/components/ContextualSidebarFrame.tsx b/ui/src/components/ContextualSidebarFrame.tsxnew file mode 100644index 0000000000..f7a48968a0--- /dev/null+++ b/ui/src/components/ContextualSidebarFrame.tsx@@ -0,0 +1,70 @@+import { ChevronLeft, type LucideIcon } from "lucide-react";+import type { ReactNode } from "react";+import { useCompany } from "@/context/CompanyContext";+import { useSidebar } from "@/context/SidebarContext";+import { useNavigate } from "@/lib/router";+import {+ readContextualSidebarOrigin,+ type ContextualSidebarSurface,+} from "@/lib/shell-navigation";+import { cn } from "@/lib/utils";+import { SidebarNavExpandedProvider } from "./SidebarNavItem";++export function ContextualSidebarFrame({+ surface,+ title,+ icon: Icon,+ fallbackTo = "/dashboard",+ showHeader = true,+ className,+ children,+}: {+ surface: ContextualSidebarSurface;+ title: string;+ icon?: LucideIcon;+ fallbackTo?: string;+ showHeader?: boolean;+ className?: string;+ children: ReactNode;+}) {+ const navigate = useNavigate();+ const { selectedCompany } = useCompany();+ const { isMobile, setSidebarOpen } = useSidebar();++ function goBack() {+ navigate(readContextualSidebarOrigin({+ surface,+ companyPrefix: selectedCompany?.issuePrefix,+ fallbackTo,+ }));+ if (isMobile) setSidebarOpen(false);+ }++ return (+ <SidebarNavExpandedProvider>+ <aside+ data-contextual-sidebar={surface}+ className={cn("flex h-full min-h-0 w-full flex-col bg-muted", className)}+ >+ {showHeader ? (+ <div className="flex shrink-0 flex-col gap-1 px-3 py-3">+ <button+ type="button"+ onClick={goBack}+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs text-muted-foreground transition-colors hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={`Back from ${title}`}+ >+ <ChevronLeft className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />+ <span className="truncate">{selectedCompany?.name ?? "Organization"}</span>+ </button>+ <div className="flex min-w-0 items-center gap-2 px-2 py-1">+ {Icon ? <Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" /> : null}+ <span className="min-w-0 flex-1 truncate text-sm font-bold text-foreground">{title}</span>+ </div>+ </div>+ ) : null}+ {children}+ </aside>+ </SidebarNavExpandedProvider>+ );+}diff --git a/ui/src/components/Layout.test.tsx b/ui/src/components/Layout.test.tsxindex 5596289aea..bd04975db9 100644--- a/ui/src/components/Layout.test.tsx+++ b/ui/src/components/Layout.test.tsx@@ -586,6 +586,9 @@ describe("Layout", () => {expect(container.textContent).toContain("Apps sidebar");expect(container.textContent).toContain("Main company nav");expect(mockSetForceCollapsed).toHaveBeenCalledWith(true);+ const secondaryRail = container.querySelector("[data-secondary-sidebar]");+ expect(secondaryRail?.classList.contains("w-60")).toBe(true);+ expect(secondaryRail?.classList.contains("shrink-0")).toBe(true);await act(async () => {root.unmount();diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsxindex 898f715955..43004ed114 100644--- a/ui/src/components/Layout.tsx+++ b/ui/src/components/Layout.tsx@@ -643,7 +643,7 @@ export function Layout() {)}{!isMobile && hasSecondarySidebar ? (- <SecondarySidebar>{secondarySidebar}</SecondarySidebar>+ <SecondarySidebar className="w-60 shrink-0">{secondarySidebar}</SecondarySidebar>) : null}<div className={cn("flex min-w-0 flex-col", isMobile ? "w-full" : "h-full flex-1")}>diff --git a/ui/src/components/RequestCollapsedSidebar.test.tsx b/ui/src/components/RequestCollapsedSidebar.test.tsxindex 0e1d0339e3..dc065e9663 100644--- a/ui/src/components/RequestCollapsedSidebar.test.tsx+++ b/ui/src/components/RequestCollapsedSidebar.test.tsx@@ -9,8 +9,6 @@ import { RequestCollapsedSidebar } from "./RequestCollapsedSidebar";// eslint-disable-next-line @typescript-eslint/no-explicit-any(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;-const COLLAPSED_STORAGE_KEY = "paperclip.sidebar.collapsed";-let capturedValue: ReturnType<typeof useSidebar> | null = null;function Capture() {@@ -82,25 +80,24 @@ describe("RequestCollapsedSidebar", () => {localStorage.clear();});- it("requests collapsed while mounted when there is no user pin", async () => {+ it("records the legacy route request without collapsing the global navigation", async () => {active = await render(true);expect(capturedValue?.routeRequestsCollapsed).toBe(true);- expect(capturedValue?.collapsed).toBe(true);+ expect(capturedValue?.collapsed).toBe(false);});- it("lets an explicit user pin override the route request", async () => {+ it("keeps the global navigation expanded when old pin APIs are called", async () => {active = await render(true);- expect(capturedValue?.collapsed).toBe(true);+ expect(capturedValue?.collapsed).toBe(false);- // User explicitly pins expanded — must win over the route's request.- flushSync(() => capturedValue?.setCollapsed(false));+ flushSync(() => capturedValue?.setCollapsed(true));expect(capturedValue?.routeRequestsCollapsed).toBe(true);expect(capturedValue?.collapsed).toBe(false);});it("clears the request on unmount, restoring the global default", async () => {active = await render(true);- expect(capturedValue?.collapsed).toBe(true);+ expect(capturedValue?.collapsed).toBe(false);// Navigate away: the route (and its <RequestCollapsedSidebar/>) unmounts.flushSync(() => active!.root.render(<Harness onRoute={false} />));@@ -109,15 +106,14 @@ describe("RequestCollapsedSidebar", () => {expect(capturedValue?.collapsed).toBe(false);});- it("keeps a user pin after navigating away (pin persists, request cleared)", async () => {+ it("clears the request without persisting a retired collapsed pin", async () => {active = await render(true);flushSync(() => capturedValue?.setCollapsed(true));- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("1");+ expect(localStorage.getItem("paperclip.sidebar.collapsed")).toBeNull();flushSync(() => active!.root.render(<Harness onRoute={false} />));await flushReact();- // Route request gone, but the explicit collapsed pin still applies.expect(capturedValue?.routeRequestsCollapsed).toBe(false);- expect(capturedValue?.collapsed).toBe(true);+ expect(capturedValue?.collapsed).toBe(false);});});diff --git a/ui/src/components/RequestCollapsedSidebar.tsx b/ui/src/components/RequestCollapsedSidebar.tsxindex 259de29a4e..7d2d7f67d1 100644--- a/ui/src/components/RequestCollapsedSidebar.tsx+++ b/ui/src/components/RequestCollapsedSidebar.tsx@@ -2,14 +2,10 @@ import { useEffect } from "react";import { useSidebar } from "../context/SidebarContext";/**- * Effect-only component (renders nothing). While mounted, it asks the app- * sidebar to default to **collapsed** (still peek-able) — the generic- * "this route brings its own sidebar, keep the app one out of the way" case.- *- * Precedence is enforced by {@link SidebarContext}: an explicit user pin- * (collapsed *or* expanded) always wins over this route request. When the- * component unmounts — e.g. navigating away from the route that rendered it —- * the cleanup clears the request and the global default is restored.+ * Back-compat effect for routes that previously requested the app sidebar's+ * retired icon rail. The request remains observable to older integrations,+ * but {@link SidebarContext} keeps the global navigation expanded. Cleanup+ * still clears the request when the route unmounts.** Drop it anywhere inside a route's element tree:*diff --git a/ui/src/components/RoutineContextualSidebar.test.tsx b/ui/src/components/RoutineContextualSidebar.test.tsxnew file mode 100644index 0000000000..a58163a50d--- /dev/null+++ b/ui/src/components/RoutineContextualSidebar.test.tsx@@ -0,0 +1,116 @@+// @vitest-environment jsdom++import type { ReactNode } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ RoutineContextualSidebar,+ resolveRoutineDetailDestination,+ routineActivityAuditHref,+ routineDetailHref,+ routineRunsAuditHref,+} from "./RoutineContextualSidebar";++vi.mock("@/lib/router", () => ({+ useParams: () => ({ routineId: "routine-route" }),+}));++vi.mock("@/api/routines", () => ({+ routinesApi: { get: vi.fn() },+}));++vi.mock("./ContextualSidebarFrame", () => ({+ ContextualSidebarFrame: ({+ surface,+ title,+ fallbackTo,+ showHeader,+ className,+ children,+ }: {+ surface: string;+ title: string;+ fallbackTo: string;+ showHeader?: boolean;+ className?: string;+ children: ReactNode;+ }) => (+ <aside+ className={className}+ data-surface={surface}+ data-title={title}+ data-fallback={fallbackTo}+ data-show-header={String(showHeader)}+ >+ {children}+ </aside>+ ),+}));++vi.mock("./SidebarNavItem", () => ({+ SidebarNavItem: ({ to, label }: { to: string; label: string }) => <a href={to}>{label}</a>,+}));++describe("routine contextual navigation", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ });++ afterEach(() => {+ flushSync(() => root.unmount());+ container.remove();+ });++ it("builds stable detail and scoped Audit destinations", () => {+ expect(routineDetailHref("routine-1")).toBe("/routines/routine-1/overview");+ expect(routineDetailHref("routine-1", "triggers")).toBe("/routines/routine-1/triggers");+ expect(routineRunsAuditHref("routine-1")).toBe(+ "/activity/runs?entityType=routine&entityId=routine-1",+ );+ expect(routineActivityAuditHref("routine-1")).toBe(+ "/activity?entityType=routine&entityId=routine-1",+ );+ });++ it("defaults and redirects legacy operation routes without remembering a prior section", () => {+ expect(resolveRoutineDetailDestination({ routineId: "routine-1" }))+ .toBe("/routines/routine-1/overview");+ expect(resolveRoutineDetailDestination({ routineId: "routine-1", section: "unknown" }))+ .toBe("/routines/routine-1/overview");+ expect(resolveRoutineDetailDestination({ routineId: "routine-1", section: "runs" }))+ .toBe("/activity/runs?entityType=routine&entityId=routine-1");+ expect(resolveRoutineDetailDestination({ routineId: "routine-1", legacyTab: "activity" }))+ .toBe("/activity?entityType=routine&entityId=routine-1");+ });++ it("renders the routine contextual sidebar with configuration and Audit links", () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ flushSync(() => root.render(+ <QueryClientProvider client={queryClient}>+ <RoutineContextualSidebar routineId="routine-1" title="Weekly release review" />+ </QueryClientProvider>,+ ));++ const frame = container.querySelector("aside");+ expect(frame?.getAttribute("data-surface")).toBe("routine");+ expect(frame?.getAttribute("data-title")).toBe("Weekly release review");+ expect(frame?.getAttribute("data-fallback")).toBe("/routines");+ expect(frame?.getAttribute("data-show-header")).toBe("false");+ expect(frame?.classList).toContain("bg-background");+ expect(frame?.classList).toContain("border-r");+ expect(container.querySelector('a[href="/routines/routine-1/overview"]')?.textContent).toBe("Overview");+ expect(container.querySelector('a[href="/routines/routine-1/triggers"]')?.textContent).toBe("Schedule");+ 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();+ expect(container.textContent).not.toContain("History");+ });+});diff --git a/ui/src/components/RoutineContextualSidebar.tsx b/ui/src/components/RoutineContextualSidebar.tsxnew file mode 100644index 0000000000..46e80fd9ba--- /dev/null+++ b/ui/src/components/RoutineContextualSidebar.tsx@@ -0,0 +1,140 @@+import { useQuery } from "@tanstack/react-query";+import {+ Activity,+ Braces,+ CalendarClock,+ KeyRound,+ LayoutDashboard,+ Play,+ Repeat,+ Send,+ type LucideIcon,+} from "lucide-react";+import { routinesApi } from "@/api/routines";+import { queryKeys } from "@/lib/queryKeys";+import { useParams } from "@/lib/router";+import {+ auditSectionHref,+ routineAuditHref,+} from "@/pages/audit/audit-navigation";+import { ContextualSidebarFrame } from "./ContextualSidebarFrame";+import { SidebarNavItem } from "./SidebarNavItem";++export const ROUTINE_DETAIL_VIEWS = [+ "overview",+ "triggers",+ "variables",+ "delivery",+ "secrets",+ "history",+] as const;++export type RoutineDetailView = (typeof ROUTINE_DETAIL_VIEWS)[number];++export type RoutineContextualNavItem = {+ view: Exclude<RoutineDetailView, "history">;+ label: string;+ icon: LucideIcon;+};++export const ROUTINE_CONTEXTUAL_NAV_ITEMS: readonly RoutineContextualNavItem[] = [+ { view: "overview", label: "Overview", icon: LayoutDashboard },+ { view: "triggers", label: "Schedule", icon: CalendarClock },+ { view: "variables", label: "Variables", icon: Braces },+ { view: "delivery", label: "Delivery", icon: Send },+ { view: "secrets", label: "Secrets", icon: KeyRound },+];++export function isRoutineDetailView(value: string | null | undefined): value is RoutineDetailView {+ return ROUTINE_DETAIL_VIEWS.includes(value as RoutineDetailView);+}++export function routineDetailHref(routineId: string, view: RoutineDetailView = "overview") {+ return `/routines/${routineId}/${view}`;+}++export function routineRunsAuditHref(routineId: string) {+ return auditSectionHref("runs", {+ entityType: "routine",+ entityId: routineId,+ });+}++export function routineActivityAuditHref(routineId: string) {+ return routineAuditHref(routineId);+}++/**+ * Canonical landing/legacy resolver used by the page and available to the+ * shell. Detail configuration stays local; immutable operational history+ * lives in scoped Audit.+ */+export function resolveRoutineDetailDestination(input: {+ routineId: string;+ section?: string | null;+ legacyTab?: string | null;+}) {+ const requested = input.legacyTab ?? input.section;+ if (requested === "runs") return routineRunsAuditHref(input.routineId);+ if (requested === "activity") return routineActivityAuditHref(input.routineId);+ if (isRoutineDetailView(requested)) return routineDetailHref(input.routineId, requested);+ return routineDetailHref(input.routineId, "overview");+}++export function RoutineContextualSidebar({+ routineId: routineIdProp,+ title,+}: {+ routineId?: string;+ title?: string;+} = {}) {+ const params = useParams<{ routineId?: string }>();+ const routineId = routineIdProp ?? params.routineId ?? "";+ const { data: routine } = useQuery({+ queryKey: queryKeys.routines.detail(routineId),+ queryFn: () => routinesApi.get(routineId),+ enabled: Boolean(routineId && !title),+ });+ const frameTitle = title ?? routine?.title ?? "Routine";++ return (+ <ContextualSidebarFrame+ surface="routine"+ title={frameTitle}+ icon={Repeat}+ fallbackTo="/routines"+ showHeader={false}+ className="border-r border-border bg-background"+ >+ <nav className="min-h-0 flex-1 overflow-y-auto px-3 py-2" aria-label="Routine navigation">+ <div className="flex flex-col gap-0.5">+ {ROUTINE_CONTEXTUAL_NAV_ITEMS.map((item) => (+ <SidebarNavItem+ key={item.view}+ to={routineDetailHref(routineId, item.view)}+ label={item.label}+ icon={item.icon}+ end+ />+ ))}+ </div>++ <p className="px-4 pb-1 pt-5 text-(length:--text-nano) font-mono font-medium uppercase tracking-widest text-muted-foreground/60">+ Audit+ </p>+ <div className="flex flex-col gap-0.5">+ <SidebarNavItem+ to={routineRunsAuditHref(routineId)}+ label="Runs"+ icon={Play}+ />+ <SidebarNavItem+ to={routineActivityAuditHref(routineId)}+ label="Activity"+ icon={Activity}+ />+ </div>+ </nav>+ </ContextualSidebarFrame>+ );+}diff --git a/ui/src/components/SecondarySidebar.production.tsx b/ui/src/components/SecondarySidebar.production.tsxnew file mode 100644index 0000000000..ae295bf59d--- /dev/null+++ b/ui/src/components/SecondarySidebar.production.tsx@@ -0,0 +1,39 @@+import { type ReactNode } from "react";+import { cn } from "@/lib/utils";+import { SidebarNavExpandedProvider } from "./SidebarNavItem.production";++/**+ * Fixed-width contextual pane that sits between the collapsed app rail and the+ * main content on takeover routes (company settings, plugin `routeSidebar`).+ *+ * The takeover model (PAP-10695) no longer *replaces* the app `<Sidebar/>`:+ * the host collapses it to its 64px rail (still peek-able) and renders the+ * contextual sidebar here, yielding `[ rail 64px ][ secondary ~240px ][ content ]`.+ *+ * It is a dumb container — fixed `w-60`, full-height, non-shrinking, with a+ * right border and its own vertical scroll — so callers just drop the+ * contextual nav (or a plugin slot mount) inside as `children`.+ *+ * Because the pane is always 240px wide it forces the full-label presentation+ * on any `SidebarNavItem` inside it, so the contextual nav stays readable even+ * while the app sidebar is collapsed to its rail (PAP-10700).+ */+export function SecondarySidebar({+ children,+ className,+}: {+ children: ReactNode;+ className?: string;+}) {+ return (+ <div+ data-secondary-sidebar=""+ className={cn(+ "h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",+ className,+ )}+ >+ <SidebarNavExpandedProvider>{children}</SidebarNavExpandedProvider>+ </div>+ );+}diff --git a/ui/src/components/SecondarySidebar.tsx b/ui/src/components/SecondarySidebar.tsxindex 20b41c17dc..a8cb196fbc 100644--- a/ui/src/components/SecondarySidebar.tsx+++ b/ui/src/components/SecondarySidebar.tsx@@ -3,20 +3,9 @@ import { cn } from "@/lib/utils";import { SidebarNavExpandedProvider } from "./SidebarNavItem";/**- * Fixed-width contextual pane that sits between the collapsed app rail and the- * main content on takeover routes (company settings, plugin `routeSidebar`).- *- * The takeover model (PAP-10695) no longer *replaces* the app `<Sidebar/>`:- * the host collapses it to its 64px rail (still peek-able) and renders the- * contextual sidebar here, yielding `[ rail 64px ][ secondary ~240px ][ content ]`.- *- * It is a dumb container — fixed `w-60`, full-height, non-shrinking, with a- * right border and its own vertical scroll — so callers just drop the- * contextual nav (or a plugin slot mount) inside as `children`.- *- * Because the pane is always 240px wide it forces the full-label presentation- * on any `SidebarNavItem` inside it, so the contextual nav stays readable even- * while the app sidebar is collapsed to its rail (PAP-10700).+ * Content adapter for a contextual sidebar. Depending on the route, Layout+ * either places it inside the primary SidebarShell or mounts it as an adjacent+ * secondary rail.*/export function SecondarySidebar({children,@@ -29,7 +18,7 @@ export function SecondarySidebar({<divdata-secondary-sidebar=""className={cn(- "h-full w-60 shrink-0 overflow-y-auto border-r border-border bg-background",+ "h-full w-full min-w-0 overflow-hidden",className,)}>diff --git a/ui/src/components/Sidebar.production.tsx b/ui/src/components/Sidebar.production.tsxnew file mode 100644index 0000000000..771a142767--- /dev/null+++ b/ui/src/components/Sidebar.production.tsx@@ -0,0 +1,251 @@+import {+ Inbox,+ ListChecks,+ CircleDot,+ Target,+ LayoutDashboard,+ DollarSign,+ History,+ Search,+ SquarePen,+ Network,+ Boxes,+ Repeat,+ Layers,+ GitBranch,+ Package,+ Settings,+ FolderOpen,+ AppWindow,+ MessagesSquare,+ GanttChartSquare,+ LayoutGrid,+} from "lucide-react";+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { SidebarSection } from "./SidebarSection";+import { SidebarNavItem } from "./SidebarNavItem.production";+import { SidebarAgents } from "./SidebarAgents.production";+import { SidebarProjects } from "./SidebarProjects";+import { SidebarStarredProjects } from "./SidebarStarredProjects.production";+import { useDialogActions } from "../context/DialogContext";+import { useCompany } from "../context/CompanyContext";+import { useSidebar } from "../context/SidebarContext";+import { attentionApi } from "../api/attention";+import { heartbeatsApi } from "../api/heartbeats";+import { instanceSettingsApi } from "../api/instanceSettings";+import { queryKeys } from "../lib/queryKeys";+import { attentionBadgeCount } from "../lib/attention";+import { useInboxBadge } from "../hooks/useInboxBadge";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";+import { PluginSlotOutlet } from "@/plugins/slots";+import { PluginLauncherOutlet } from "@/plugins/launchers";+import { SidebarCompanyMenu } from "./SidebarCompanyMenu.production";++export function Sidebar() {+ const { openNewIssue } = useDialogActions();+ // Every labeled section is collapsible (session-scoped, default open) —+ // one policy across static nav groups and the data-driven sections.+ const [workOpen, setWorkOpen] = useState(true);+ const [companyOpen, setCompanyOpen] = useState(true);+ const { selectedCompanyId, selectedCompany } = useCompany();+ const { collapsed, peeking } = useSidebar();+ const rail = collapsed && !peeking;+ const inboxBadge = useInboxBadge(selectedCompanyId);+ const { data: experimentalSettings } = useQuery({+ queryKey: queryKeys.instance.experimentalSettings,+ queryFn: () => instanceSettingsApi.getExperimental(),+ });+ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,+ enabled: !!selectedCompanyId,+ // Event-sourced via LiveUpdatesProvider (GitHub issue 9627) + reconnect reconcile — no+ // interval poll needed. Polling here also re-armed React Query's timer on+ // every live-event cache write, a major source of steady-state churn.+ 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);+ const liveRunCount = liveRuns?.length ?? 0;+ const showWorkspacesLink = experimentalSettings?.enableIsolatedWorkspaces === true;+ const showApps = experimentalSettings?.enableApps === true;+ const showPipelines = experimentalSettings?.enablePipelines === true;+ const showStatusCards = experimentalSettings?.enableStatusCards === true;+ const goalsLinkPending = experimentalSettings === undefined;+ const showGoalsLink = experimentalSettings?.enableGoalsSidebarLink === true;+ // Decisions (attention home) is an experimental surface (PAP-13481): the nav+ // item is hidden entirely until the flag is enabled (same no-flash pattern as+ // showWorkspacesLink — it defaults hidden, so no placeholder is needed).+ const showDecisions = experimentalSettings?.enableDecisions === true;+ const { data: attentionFeed } = useQuery({+ queryKey: queryKeys.attention(selectedCompanyId!),+ queryFn: () => attentionApi.list(selectedCompanyId!),+ enabled: !!selectedCompanyId && showDecisions,+ refetchInterval: 60_000,+ });+ const attentionCount = attentionBadgeCount(attentionFeed);+ const showCases = experimentalSettings?.enableCases === true;+ // Streamlined left navigation (top-level Projects link + starred children) is+ // now the standard product sidebar (PAP-12472). The former experimental+ // opt-out was retired; classic per-project collapsible mode is no longer+ // user-selectable. Kept as a constant so the classic branch below stays as a+ // documented reference until it is fully removed. Routes are unaffected.+ const streamlined = true;+ // Conference Room Chat flag (PAP-136/PAP-137): the Conference Room nav item+ // is a new surface, hidden entirely while the flag is off (same no-flash+ // pattern as showWorkspacesLink above).+ const conferenceRoomChatEnabled = experimentalSettings?.enableConferenceRoomChat === true;++ const pluginContext = {+ companyId: selectedCompanyId,+ companyPrefix: selectedCompany?.issuePrefix ?? null,+ };++ return (+ <aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">+ {/* Top bar: company name, aligned with top sections and borderless.+ Search deliberately does NOT live here:+ the header's spare width goes to the workspace/organization name,+ which is the user's orientation anchor and truncates otherwise.+ Search is the first nav item below instead. */}+ <div className="flex items-center gap-1 px-3 h-12 shrink-0">+ <SidebarCompanyMenu />+ </div>++ <nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2">+ <div className="flex flex-col gap-0.5">+ {/* New Task button aligned with nav items */}+ {(() => {+ const newTaskButton = (+ <button+ onClick={() => openNewIssue()}+ data-slot="icon-button"+ aria-label={rail ? "New Task" : undefined}+ className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors"+ >+ <SquarePen className="h-4 w-4 shrink-0" />+ <span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "truncate"}>New Task</span>+ </button>+ );+ return rail ? (+ <Tooltip>+ <TooltipTrigger asChild>{newTaskButton}</TooltipTrigger>+ <TooltipContent side="right">New Task</TooltipContent>+ </Tooltip>+ ) : (+ newTaskButton+ );+ })()}+ {/* Search moved out of the header so the workspace name keeps the+ width; a nav row also keeps search reachable from the+ collapsed rail, where the old header icon was dropped entirely.+ Cmd/Ctrl+K remains the keyboard path (command palette). */}+ <SidebarNavItem to="/search" label="Search" icon={Search} />+ <SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />+ <SidebarNavItem+ to="/inbox"+ label="Inbox"+ icon={Inbox}+ badge={inboxBadge.inbox}+ badgeLabel="unread"+ badgeTone={inboxBadge.failedRuns > 0 ? "danger" : "default"}+ alert={inboxBadge.failedRuns > 0}+ />+ {showDecisions ? (+ <SidebarNavItem+ to="/decisions"+ label="Decisions"+ icon={ListChecks}+ badge={attentionCount}+ badgeLabel="decisions"+ />+ ) : null}+ {showStatusCards ? (+ <SidebarNavItem to="/status" label="Status" icon={LayoutGrid} textBadge="beta" />+ ) : null}+ {conferenceRoomChatEnabled ? (+ <SidebarNavItem to="/board-chat" label="Conference Room" icon={MessagesSquare} />+ ) : null}+ </div>++ <SidebarSection label="Work" collapsible={{ open: workOpen, onOpenChange: setWorkOpen }}>+ <SidebarNavItem to="/issues" label="Tasks" icon={CircleDot} />+ {showCases ? (+ <SidebarNavItem to="/cases" label="Cases" icon={Layers} textBadge="beta" />+ ) : null}+ <SidebarNavItem to="/routines" label="Routines" icon={Repeat} />+ {showPipelines ? (+ <SidebarNavItem to="/pipelines" label="Pipelines" icon={GitBranch} />+ ) : null}+ {showGoalsLink ? (+ <SidebarNavItem to="/goals" label="Goals" icon={Target} />+ ) : goalsLinkPending ? (+ <div+ data-testid="sidebar-goals-placeholder"+ className="h-8 pointer-coarse:h-7"+ aria-hidden="true"+ />+ ) : null}+ <SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} />+ <SidebarNavItem to="/skills" label="Skills" icon={Boxes} />+ {showWorkspacesLink ? (+ <SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} />+ ) : null}+ {streamlined ? (+ <>+ <SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} />+ <SidebarStarredProjects />+ </>+ ) : null}+ <PluginSlotOutlet+ slotTypes={["sidebar"]}+ context={pluginContext}+ className="flex flex-col gap-0.5"+ itemClassName="text-(length:--text-compact) font-medium"+ missingBehavior="placeholder"+ />+ <PluginLauncherOutlet+ placementZones={["sidebar"]}+ context={pluginContext}+ className="flex flex-col gap-0.5"+ itemClassName="text-(length:--text-compact) font-medium"+ />+ </SidebarSection>++ {/* Classic mode restores the per-project collapsible below Work. */}+ {streamlined ? null : <SidebarProjects />}++ <SidebarAgents streamlined={streamlined} />++ <SidebarSection label="Company" collapsible={{ open: companyOpen, onOpenChange: setCompanyOpen }}>+ <SidebarNavItem to="/org" label="Org" icon={Network} />+ {showApps ? <SidebarNavItem to="/apps" label="Apps" icon={AppWindow} /> : null}+ <SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} />+ <SidebarNavItem to="/costs" label="Costs" icon={DollarSign} />+ {/* One entry — /audit merged into the rich Activity feed (PAP-16302). */}+ <SidebarNavItem to="/activity" label="Activity" icon={History} />+ <SidebarNavItem to="/company/settings" label="Settings" icon={Settings} />+ </SidebarSection>++ <PluginSlotOutlet+ slotTypes={["sidebarPanel"]}+ context={pluginContext}+ className="flex flex-col gap-3"+ itemClassName="rounded-lg border border-border p-3"+ missingBehavior="placeholder"+ />+ </nav>+ </aside>+ );+}diff --git a/ui/src/components/Sidebar.test.tsx b/ui/src/components/Sidebar.test.tsxindex d13dc1aa6b..f075408a3e 100644--- a/ui/src/components/Sidebar.test.tsx+++ b/ui/src/components/Sidebar.test.tsx@@ -100,18 +100,24 @@ vi.mock("./SidebarCompanyMenu", () => ({vi.mock("./SidebarAgents", () => ({SidebarAgents: ({ streamlined }: { streamlined?: boolean }) => (- <div data-testid="sidebar-agents" data-streamlined={String(streamlined)} />+ <div data-testid="sidebar-agents" data-streamlined={String(streamlined)}>+ Active agents+ </div>),}));vi.mock("./SidebarProjects", () => ({- SidebarProjects: () => <div data-testid="sidebar-projects">Projects collapsible</div>,+ SidebarProjects: () => <div data-testid="sidebar-projects">Classic projects</div>,}));vi.mock("./SidebarStarredProjects", () => ({SidebarStarredProjects: () => <div data-testid="sidebar-starred-projects" />,}));+vi.mock("./SidebarRecentTasks", () => ({+ SidebarRecentTasks: () => <div data-testid="sidebar-recent-tasks">Recent Tasks</div>,+}));+async function flushReact() {for (let index = 0; index < 5; index += 1) {await Promise.resolve();@@ -150,6 +156,7 @@ describe("Sidebar", () => {mockAttentionApi.list.mockResolvedValue({ items: [] });mockSidebar.isMobile = false;mockSidebar.collapsed = false;+ mockSidebar.collapseLocked = false;mockSidebar.peeking = false;});@@ -159,6 +166,21 @@ describe("Sidebar", () => {vi.clearAllMocks();});+ it("keeps the default sidebar edge borderless", async () => {+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });+ const root = await renderSidebar();++ const sidebar = container.querySelector("aside");+ expect(sidebar?.classList).not.toContain("border-r");+ expect(sidebar?.classList).not.toContain("border-border");+ expect(sidebar?.classList).toContain("bg-border/50");+ expect(sidebar?.classList).toContain("dark:bg-muted");++ flushSync(() => {+ root.unmount();+ });+ });+it("shows Search as a nav item instead of a header icon", async () => {// The header's spare width goes to the workspace name (which otherwise// truncates at ~78px), so search lives in the nav list — still@@ -201,7 +223,7 @@ describe("Sidebar", () => {});});- it("streamlined (flag ON): keeps Task wording, top-level Projects link, no per-project collapsible", async () => {+ it("uses the simplified work navigation with one Agents destination", async () => {mockInstanceSettingsApi.getExperimental.mockResolvedValue({enableIsolatedWorkspaces: false,enableStreamlinedLeftNavigation: true,@@ -217,34 +239,35 @@ describe("Sidebar", () => {const projectsLink = [...container.querySelectorAll("nav a")].find((a) => a.textContent?.trim() === "Projects");expect(projectsLink?.getAttribute("href")).toBe("/projects");-- expect(container.querySelector('[data-testid="sidebar-projects"]')).toBeNull();- expect(- container.querySelector('[data-testid="sidebar-agents"]')?.getAttribute("data-streamlined"),- ).toBe("true");+ const agentLinks = [...container.querySelectorAll('a[href="/agents"]')];+ expect(agentLinks).toHaveLength(1);+ expect([...container.querySelectorAll('a[href="/activity"]')]).toHaveLength(1);+ expect(navLabels).toContain("Audit");+ expect(navLabels).not.toContain("Settings");+ expect(navLabels).not.toContain("Activity");+ expect(navLabels).not.toContain("Costs");+ expect(container.querySelector('[data-testid="sidebar-recent-tasks"]')).not.toBeNull();flushSync(() => {root.unmount();});});- it("defaults to streamlined navigation while experimental settings are loading", async () => {+ it("keeps the simplified navigation while experimental settings are loading", async () => {mockInstanceSettingsApi.getExperimental.mockImplementation(() => new Promise(() => {}));const root = await renderSidebar();const navLabels = [...container.querySelectorAll("nav a")].map((a) => a.textContent?.trim());expect(navLabels).toContain("Projects");- expect(container.querySelector('[data-testid="sidebar-projects"]')).toBeNull();- expect(- container.querySelector('[data-testid="sidebar-agents"]')?.getAttribute("data-streamlined"),- ).toBe("true");+ expect(navLabels).toContain("Agents");+ expect(container.textContent).not.toContain("Organization");flushSync(() => {root.unmount();});});- it("streamlined is now standard: a stale enableStreamlinedLeftNavigation=false opt-out is ignored", async () => {+ it("ignores the retired streamlined navigation opt-out", async () => {// PAP-12472 retired the experimental opt-out; the streamlined sidebar is the// only path, so an old `false` setting no longer restores classic mode.mockInstanceSettingsApi.getExperimental.mockResolvedValue({@@ -257,11 +280,44 @@ describe("Sidebar", () => {expect(navLabels).toContain("Tasks");// Top-level Projects link + starred children stay, per-project collapsible gone.expect(navLabels).toContain("Projects");- expect(container.querySelector('[data-testid="sidebar-projects"]')).toBeNull();expect(container.querySelector('[data-testid="sidebar-starred-projects"]')).not.toBeNull();- expect(- container.querySelector('[data-testid="sidebar-agents"]')?.getAttribute("data-streamlined"),- ).toBe("true");+ expect(navLabels).toContain("Agents");++ flushSync(() => {+ root.unmount();+ });+ });++ it("restores legacy agent and organization navigation when Streamlined UI is off", async () => {+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({+ enableStreamlinedUi: false,+ enableApps: true,+ });+ const root = await renderSidebar();++ const labels = [...container.querySelectorAll("nav a")].map((anchor) => anchor.textContent?.trim());+ expect(container.querySelector('[data-testid="sidebar-recent-tasks"]')).toBeNull();+ expect(container.querySelector('[data-testid="sidebar-projects"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="sidebar-agents"]')?.getAttribute("data-streamlined")).toBe("undefined");+ expect(container.textContent).toContain("Organization");+ expect(labels).toEqual(expect.arrayContaining(["Org", "Apps", "Timeline", "Costs", "Activity", "Settings"]));+ expect(labels).not.toContain("Audit");+ expect(labels).not.toContain("Projects");+ expect(container.querySelector('a[href="/agents"]')).toBeNull();+ expect(container.querySelector("aside")?.classList).toContain("border-r");++ flushSync(() => {+ root.unmount();+ });+ });++ it("locks the legacy collapse control while a secondary sidebar forces the rail", async () => {+ mockSidebar.collapseLocked = true;+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableStreamlinedUi: false });+ const root = await renderSidebar();++ expect(container.querySelector('button[aria-label="Collapse sidebar"]')).toBeNull();+ expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();flushSync(() => {root.unmount();@@ -336,25 +392,25 @@ describe("Sidebar", () => {});});- it("shows Skills directly below Artifacts in Work", async () => {- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });+ it("groups and orders the streamlined Work and Org navigation", async () => {+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({+ enableIsolatedWorkspaces: false,+ enableApps: true,+ });const root = await renderSidebar();- const artifactsLink = [...container.querySelectorAll("a")].find(- (anchor) => anchor.textContent === "Artifacts",- );- expect(artifactsLink?.getAttribute("href")).toBe("/artifacts");-- const navText = container.querySelector("nav")?.textContent ?? "";- expect(navText).toContain("Artifacts");- expect(navText).toContain("Skills");- expect(navText.indexOf("Artifacts")).toBeLessThan(navText.indexOf("Skills"));-const sections = [...container.querySelectorAll("nav > div")];const workSection = sections.find((section) => section.textContent?.startsWith("Work"));- const companySection = sections.find((section) => section.textContent?.startsWith("Organization"));- expect(workSection?.textContent).toContain("Skills");- expect(companySection?.textContent).not.toContain("Skills");+ const orgSection = sections.find((section) => section.textContent?.startsWith("Org"));+ const labels = (section: Element | undefined) => [...(section?.querySelectorAll("a") ?? [])]+ .map((anchor) => anchor.textContent?.trim());++ expect(labels(workSection)).toEqual(["Tasks", "Projects", "Routines", "Artifacts"]);+ expect(labels(orgSection)).toEqual(["Agents", "Skills", "Apps", "Audit"]);+ expect(sections.indexOf(workSection!)).toBeLessThan(sections.indexOf(orgSection!));+ expect(+ workSection?.querySelector('a[href="/issues"] svg')?.classList.contains("lucide-circle-check"),+ ).toBe(true);flushSync(() => {root.unmount();@@ -398,25 +454,22 @@ describe("Sidebar", () => {expect(link?.getAttribute("href")).toBe("/goals");const navText = container.querySelector("nav")?.textContent ?? "";- expect(navText.indexOf("Goals")).toBeLessThan(navText.indexOf("Artifacts"));+ expect(navText.indexOf("Artifacts")).toBeLessThan(navText.indexOf("Goals"));flushSync(() => {root.unmount();});});- it("places Timeline in the Company section", async () => {+ it("keeps Timeline out of the global navigation", async () => {mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });const root = await renderSidebar();const sections = [...container.querySelectorAll("nav > div")];const workSection = sections.find((section) => section.textContent?.startsWith("Work"));- const companySection = sections.find((section) => section.textContent?.startsWith("Organization"));+ expect(workSection?.textContent).toContain("Projects");expect(workSection?.textContent).not.toContain("Timeline");- expect(companySection?.textContent).toContain("Timeline");-- const timelineLink = [...container.querySelectorAll("a")].find((anchor) => anchor.textContent === "Timeline");- expect(timelineLink?.getAttribute("href")).toBe("/timeline");+ expect(container.querySelector('a[href="/timeline"]')).toBeNull();flushSync(() => {root.unmount();@@ -479,7 +532,7 @@ describe("Sidebar", () => {});});- it("always shows Apps at the bottom of the Work section", async () => {+ it("always shows Apps in the Org section", async () => {mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableApps: false });const root = await renderSidebar();@@ -487,10 +540,10 @@ describe("Sidebar", () => {const link = links.find((anchor) => anchor.textContent === "Apps");expect(link?.getAttribute("href")).toBe("/apps");expect(links.findIndex((anchor) => anchor.textContent === "Apps")).toBeGreaterThan(- links.findIndex((anchor) => anchor.textContent === "Projects"),+ links.findIndex((anchor) => anchor.textContent === "Skills"),);expect(links.findIndex((anchor) => anchor.textContent === "Apps")).toBeLessThan(- links.findIndex((anchor) => anchor.textContent === "Org"),+ links.findIndex((anchor) => anchor.textContent === "Audit"),);flushSync(() => {@@ -536,80 +589,14 @@ describe("Sidebar", () => {});});- it("header toggle collapses an expanded sidebar (aria-expanded reflects state)", async () => {- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });- const root = await renderSidebar();-- const toggle = container.querySelector<HTMLButtonElement>('button[aria-label="Collapse sidebar"]');- expect(toggle).not.toBeNull();- expect(toggle?.getAttribute("aria-expanded")).toBe("true");-- flushSync(() => {- toggle?.click();- });- expect(mockSidebar.toggleCollapsed).toHaveBeenCalledTimes(1);-- flushSync(() => {- root.unmount();- });- });-- it("hides the expand/collapse toggle while a secondary sidebar locks the rail", async () => {- // A secondary sidebar forces the rail; the user must not be able to expand- // the primary while it is shown (PAP-10694).+ it("does not render a global navigation collapse affordance", async () => {mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });- mockSidebar.collapseLocked = true;const root = await renderSidebar();expect(container.querySelector('button[aria-label="Collapse sidebar"]')).toBeNull();expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();-- mockSidebar.collapseLocked = false;- flushSync(() => {- root.unmount();- });- });-- it("keeps the collapsed rail top bar to just the company logo (no clipped toggle)", async () => {- // In the narrow rail the collapse toggle doesn't fit beside the logo and- // would overflow/clip, shoving the logo out of the icon column (PAP-10676), so- // it is dropped in the rail. Expansion stays reachable via hover-peek + Pin- // and Cmd/Ctrl+B. The toggle returns as soon as the panel is expanded or- // peeking (covered by the other top-bar tests).- mockSidebar.collapsed = true;- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });- const root = await renderSidebar();-- expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();- // The company menu (company switcher / logo) is still present in the rail.+ expect(container.querySelector('button[aria-label="Keep sidebar expanded"]')).toBeNull();expect(container.textContent).toContain("Company menu");- // Search survives the rail as an icon-only nav item — the old- // header icon was dropped entirely here, leaving the rail with no visible- // search affordance.- const railSearchLink = [...container.querySelectorAll("nav a")]- .find((anchor) => anchor.getAttribute("href") === "/search");- expect(railSearchLink).toBeTruthy();-- flushSync(() => {- root.unmount();- });- });-- it("peek header shows a pin that promotes the peek to pinned-expanded", async () => {- mockSidebar.collapsed = true;- mockSidebar.peeking = true;- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });- const root = await renderSidebar();-- // The collapse toggle is replaced by the pin while peeking.- expect(container.querySelector('button[aria-label="Expand sidebar"]')).toBeNull();- const pin = container.querySelector<HTMLButtonElement>('button[aria-label="Keep sidebar expanded"]');- expect(pin).not.toBeNull();-- flushSync(() => {- pin?.click();- });- expect(mockSidebar.setCollapsed).toHaveBeenCalledWith(false);flushSync(() => {root.unmount();diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsxindex 2281375062..298fdd96d0 100644--- a/ui/src/components/Sidebar.tsx+++ b/ui/src/components/Sidebar.tsx@@ -1,7 +1,7 @@import {Inbox,ListChecks,- CircleDot,+ CircleCheck,Target,LayoutDashboard,DollarSign,@@ -16,13 +16,11 @@ import {Package,Settings,FolderOpen,- PanelLeftClose,- PanelLeftOpen,- Pin,AppWindow,MessagesSquare,GanttChartSquare,LayoutGrid,+ Users,} from "lucide-react";import { useState } from "react";import { useQuery } from "@tanstack/react-query";@@ -31,6 +29,7 @@ import { SidebarNavItem } from "./SidebarNavItem";import { SidebarAgents } from "./SidebarAgents";import { SidebarProjects } from "./SidebarProjects";import { SidebarStarredProjects } from "./SidebarStarredProjects";+import { SidebarRecentTasks } from "./SidebarRecentTasks";import { useDialogActions } from "../context/DialogContext";import { useCompany } from "../context/CompanyContext";import { useSidebar } from "../context/SidebarContext";@@ -40,8 +39,8 @@ import { instanceSettingsApi } from "../api/instanceSettings";import { queryKeys } from "../lib/queryKeys";import { attentionBadgeCount } from "../lib/attention";import { useInboxBadge } from "../hooks/useInboxBadge";+import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";-import { Button } from "@/components/ui/button";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";import { PluginSlotOutlet } from "@/plugins/slots";@@ -53,9 +52,10 @@ export function Sidebar() {// Every labeled section is collapsible (session-scoped, default open) —// one policy across static nav groups and the data-driven sections.const [workOpen, setWorkOpen] = useState(true);- const [companyOpen, setCompanyOpen] = useState(true);+ const [organizationOpen, setOrganizationOpen] = useState(true);const { selectedCompanyId, selectedCompany } = useCompany();- const { isMobile, collapsed, collapseLocked, peeking, toggleCollapsed, setCollapsed } = useSidebar();+ const { collapsed, peeking } = useSidebar();+ const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();const rail = collapsed && !peeking;const inboxBadge = useInboxBadge(selectedCompanyId);const { data: experimentalSettings } = useQuery({@@ -82,6 +82,9 @@ export function Sidebar() {});usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);const liveRunCount = liveRuns?.length ?? 0;+ const liveIssueIds = new Set(+ (liveRuns ?? []).flatMap((run) => run.issueId ? [run.issueId] : []),+ );const showWorkspacesLink = experimentalSettings?.enableIsolatedWorkspaces === true;const showPipelines = experimentalSettings?.enablePipelines === true;const showStatusCards = experimentalSettings?.enableStatusCards === true;@@ -99,12 +102,6 @@ export function Sidebar() {});const attentionCount = attentionBadgeCount(attentionFeed);const showCases = experimentalSettings?.enableCases === true;- // Streamlined left navigation (top-level Projects link + starred children) is- // now the standard product sidebar (PAP-12472). The former experimental- // opt-out was retired; classic per-project collapsible mode is no longer- // user-selectable. Kept as a constant so the classic branch below stays as a- // documented reference until it is fully removed. Routes are unaffected.- const streamlined = true;// Conference Room Chat flag (PAP-136/PAP-137): the Conference Room nav item// is a new surface, hidden entirely while the flag is off (same no-flash// pattern as showWorkspacesLink above).@@ -116,55 +113,21 @@ export function Sidebar() {};return (- <aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">- {/* Top bar: Company name (bold) + collapse control — aligned with top- sections (no visible border). Search deliberately does NOT live here:+ <aside+ className={cn(+ "w-full h-full min-h-0 flex flex-col",+ streamlinedUiEnabled+ ? "bg-border/50 dark:bg-muted"+ : "border-r border-border bg-background",+ )}+ >+ {/* Top bar: company name, aligned with top sections and borderless.+ Search deliberately does NOT live here:the header's spare width goes to the workspace/organization name,which is the user's orientation anchor and truncates otherwise.Search is the first nav item below instead. */}- <div className="flex items-center gap-1 px-3 h-12 shrink-0">+ <div className="flex h-(--sz-60px) shrink-0 items-center gap-1 px-3"><SidebarCompanyMenu />- {/* In the collapsed rail the toggle doesn't fit beside the logo —- keeping it would overflow the 64px rail and squeeze the logo out of- alignment with the icon column below it. It returns as- soon as the panel is expanded (pinned) or peeking. Expansion in the- rail is still reachable via hover-peek + Pin and Cmd/Ctrl+B. */}- {!rail ? (- <>- {/* Desktop-only collapse/expand affordance. While peeking (hover flyout- over the collapsed rail) it becomes a Pin that promotes the peek to a- pinned-expanded sidebar; otherwise it toggles the pinned rail. Mobile- uses the off-canvas drawer, so this control is hidden there. It is- also hidden while a secondary sidebar forces the rail (collapseLocked):- the user cannot expand the primary while a secondary sidebar is shown. */}- {!isMobile && !collapseLocked ? (- peeking ? (- <Button- variant="ghost"- size="icon-sm"- className="text-muted-foreground shrink-0"- aria-label="Keep sidebar expanded"- title="Keep sidebar expanded"- onClick={() => setCollapsed(false)}- >- <Pin className="h-4 w-4" />- </Button>- ) : (- <Button- variant="ghost"- size="icon-sm"- className="text-muted-foreground shrink-0"- aria-expanded={!collapsed}- aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}- title={collapsed ? "Expand sidebar" : "Collapse sidebar"}- onClick={() => toggleCollapsed()}- >- {collapsed ? <PanelLeftOpen className="h-4 w-4" /> : <PanelLeftClose className="h-4 w-4" />}- </Button>- )- ) : null}- </>- ) : null}</div><nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2">@@ -176,7 +139,10 @@ export function Sidebar() {onClick={() => openNewIssue()}data-slot="icon-button"aria-label={rail ? "New Task" : undefined}- className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors"+ className={cn(+ "flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:text-foreground transition-colors",+ streamlinedUiEnabled ? "hover:bg-background" : "hover:bg-accent/50",+ )}><SquarePen className="h-4 w-4 shrink-0" /><span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "truncate"}>New Task</span>@@ -224,11 +190,18 @@ export function Sidebar() {</div><SidebarSection label="Work" collapsible={{ open: workOpen, onOpenChange: setWorkOpen }}>- <SidebarNavItem to="/issues" label="Tasks" icon={CircleDot} />+ <SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} />+ {streamlinedUiEnabled ? (+ <>+ <SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} />+ <SidebarStarredProjects />+ </>+ ) : null}+ <SidebarNavItem to="/routines" label="Routines" icon={Repeat} />+ <SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} />{showCases ? (<SidebarNavItem to="/cases" label="Cases" icon={Layers} textBadge="beta" />) : null}- <SidebarNavItem to="/routines" label="Routines" icon={Repeat} />{showPipelines ? (<SidebarNavItem to="/pipelines" label="Pipelines" icon={GitBranch} />) : null}@@ -241,17 +214,9 @@ export function Sidebar() {aria-hidden="true"/>) : null}- <SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} />- <SidebarNavItem to="/skills" label="Skills" icon={Boxes} />{showWorkspacesLink ? (<SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} />) : null}- {streamlined ? (- <>- <SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} />- <SidebarStarredProjects />- </>- ) : null}<PluginSlotOutletslotTypes={["sidebar"]}context={pluginContext}@@ -265,22 +230,39 @@ export function Sidebar() {className="flex flex-col gap-0.5"itemClassName="text-(length:--text-compact) font-medium"/>- <SidebarNavItem to="/apps" label="Apps" icon={AppWindow} /></SidebarSection>- {/* Classic mode restores the per-project collapsible below Work. */}- {streamlined ? null : <SidebarProjects />}-- <SidebarAgents streamlined={streamlined} />+ {streamlinedUiEnabled ? (+ <SidebarSection+ label="Org"+ collapsible={{ open: organizationOpen, onOpenChange: setOrganizationOpen }}+ >+ <SidebarNavItem to="/agents" label="Agents" icon={Users} />+ <SidebarNavItem to="/skills" label="Skills" icon={Boxes} />+ <SidebarNavItem to="/apps" label="Apps" icon={AppWindow} />+ <SidebarNavItem to="/activity" label="Audit" icon={History} />+ </SidebarSection>+ ) : null}- <SidebarSection label="Organization" collapsible={{ open: companyOpen, onOpenChange: setCompanyOpen }}>- <SidebarNavItem to="/org" label="Org" icon={Network} />- <SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} />- <SidebarNavItem to="/costs" label="Costs" icon={DollarSign} />- {/* One entry — /audit merged into the rich Activity feed (PAP-16302). */}- <SidebarNavItem to="/activity" label="Activity" icon={History} />- <SidebarNavItem to="/company/settings" label="Settings" icon={Settings} />- </SidebarSection>+ {streamlinedUiEnabled ? (+ <SidebarRecentTasks companyId={selectedCompanyId} liveIssueIds={liveIssueIds} />+ ) : (+ <>+ <SidebarProjects />+ <SidebarAgents />+ <SidebarSection+ label="Organization"+ collapsible={{ open: organizationOpen, onOpenChange: setOrganizationOpen }}+ >+ <SidebarNavItem to="/org" label="Org" icon={Network} />+ <SidebarNavItem to="/apps" label="Apps" icon={AppWindow} />+ <SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} />+ <SidebarNavItem to="/costs" label="Costs" icon={DollarSign} />+ <SidebarNavItem to="/activity" label="Activity" icon={History} />+ <SidebarNavItem to="/company/settings" label="Settings" icon={Settings} />+ </SidebarSection>+ </>+ )}<PluginSlotOutletslotTypes={["sidebarPanel"]}diff --git a/ui/src/components/SidebarAccountMenu.production.tsx b/ui/src/components/SidebarAccountMenu.production.tsxnew file mode 100644index 0000000000..be58276d8a--- /dev/null+++ b/ui/src/components/SidebarAccountMenu.production.tsx@@ -0,0 +1,286 @@+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ BookOpen,+ LogOut,+ Megaphone,+ type LucideIcon,+ UserRound,+ UserRoundPen,+} from "lucide-react";+import type { DeploymentMode, ServerGitInfo } from "@paperclipai/shared";+import { Link } from "@/lib/router";+import { authApi } from "@/api/auth";+import { queryKeys } from "@/lib/queryKeys";+import { useSignOut } from "@/hooks/useSignOut";+import { useSidebar } from "../context/SidebarContext";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";+import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";+import { ThemeToggle } from "./ThemeToggle";+import { SidebarServerInfo } from "./SidebarServerInfo";+import { Badge } from "@/components/ui/badge";++const PROFILE_SETTINGS_PATH = "/company/settings/instance/profile";+const DOCS_URL = "https://docs.paperclip.ing/";+const FEEDBACK_URL = "https://paperclip.ing/feedback";+const SOURCE_REPOSITORY_URL = "https://github.com/paperclipai/paperclip";+const SOURCE_VERSION_RE = /\+\d+\.git\.([0-9a-f]{7,40})(?:\.dirty)?$/i;++interface SidebarAccountMenuProps {+ deploymentMode?: DeploymentMode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ serverGit?: ServerGitInfo;+ version?: string | null;+}++interface MenuActionProps {+ label: string;+ description: string;+ icon: LucideIcon;+ onClick?: () => void;+ href?: string;+ external?: boolean;+}++function deriveInitials(name: string) {+ const parts = name.trim().split(/\s+/).filter(Boolean);+ if (parts.length >= 2) {+ return `${parts[0]?.[0] ?? ""}${parts[parts.length - 1]?.[0] ?? ""}`.toUpperCase();+ }+ return name.slice(0, 2).toUpperCase();+}++function deriveUserSlug(name: string | null | undefined, email: string | null | undefined, id: string | null | undefined) {+ const candidates = [name, email?.split("@")[0], email, id];+ for (const candidate of candidates) {+ const slug = candidate+ ?.trim()+ .toLowerCase()+ .replace(/['"]/g, "")+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "");+ if (slug) return slug;+ }+ return "me";+}++function sourceVersionSha(version: string): string | null {+ const sourceVersion = version.match(SOURCE_VERSION_RE);+ return sourceVersion?.[1] ?? null;+}++function MenuAction({ label, description, icon: Icon, onClick, href, external = false }: MenuActionProps) {+ const className =+ "flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60";++ const content = (+ <>+ <span className="mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground">+ <Icon className="size-4" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-sm font-medium text-foreground">{label}</span>+ <span className="block text-xs text-muted-foreground">{description}</span>+ </span>+ </>+ );++ if (href) {+ if (external) {+ return (+ <a href={href} target="_blank" rel="noreferrer" className={className} onClick={onClick}>+ {content}+ </a>+ );+ }++ return (+ <Link to={href} className={className} onClick={onClick}>+ {content}+ </Link>+ );+ }++ return (+ <button type="button" className={className} onClick={onClick}>+ {content}+ </button>+ );+}++export function SidebarAccountMenu({+ deploymentMode,+ open: controlledOpen,+ onOpenChange,+ serverGit,+ version,+}: SidebarAccountMenuProps) {+ const [internalOpen, setInternalOpen] = useState(false);+ const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();+ const rail = collapsed && !peeking;+ const open = controlledOpen ?? internalOpen;+ const setOpen = onOpenChange ?? setInternalOpen;+ const { data: session } = useQuery({+ queryKey: queryKeys.auth.session,+ queryFn: () => authApi.getSession(),+ retry: false,+ });++ const signOutMutation = useSignOut({ onSignedOut: closeNavigationChrome });++ const displayName = session?.user.name?.trim() || "Board";+ const secondaryLabel =+ session?.user.email?.trim() || (deploymentMode === "authenticated" ? "Signed in" : "Local workspace board");+ const accountBadge = deploymentMode === "authenticated" ? "Account" : "Local";+ const initials = deriveInitials(displayName);+ const profileHref = `/u/${deriveUserSlug(session?.user.name, session?.user.email, session?.user.id)}`;+ const sourceSha = version ? sourceVersionSha(version) : null;+ const sourceFullSha =+ sourceSha && serverGit?.available && serverGit.fullSha.toLowerCase().startsWith(sourceSha.toLowerCase())+ ? serverGit.fullSha+ : sourceSha;+ const sourceBranch = sourceSha && serverGit?.available ? serverGit.branchName : null;++ function closeNavigationChrome() {+ setOpen(false);+ if (isMobile) setSidebarOpen(false);+ }++ function handleSignOut() {+ signOutMutation.mutate();+ }++ return (+ <div className="border-t border-r border-border bg-background px-3 py-2">+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground"+ aria-label="Open account menu"+ >+ <Avatar size="sm">+ {session?.user.image ? <AvatarImage src={session.user.image} alt={displayName} /> : null}+ <AvatarFallback>{initials}</AvatarFallback>+ </Avatar>+ <span className={cn("min-w-0 flex-1 truncate", rail && SIDEBAR_RAIL_HIDDEN_LABEL)}>{displayName}</span>+ </button>+ </PopoverTrigger>+ <PopoverContent+ side="top"+ align="start"+ sideOffset={10}+ className="w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl"+ >+ <div className="h-24 bg-(image:--gradient-extract-25)" />+ <div className="-mt-8 px-4 pb-4">+ <div className="flex items-start gap-3">+ <div className="rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm">+ <Avatar size="lg">+ {session?.user.image ? <AvatarImage src={session.user.image} alt={displayName} /> : null}+ <AvatarFallback>{initials}</AvatarFallback>+ </Avatar>+ </div>+ <div className="min-w-0 flex-1 pt-1">+ <div className="flex items-center gap-2">+ <h2 className="truncate text-base font-semibold text-foreground">{displayName}</h2>+ <Badge variant="ghost" className="bg-accent text-(length:--text-nano) font-semibold uppercase tracking-wide text-muted-foreground">+ {accountBadge}+ </Badge>+ </div>+ <p className="truncate text-sm text-muted-foreground">{secondaryLabel}</p>+ {sourceSha && sourceFullSha ? (+ <div className="mt-1 text-xs text-muted-foreground">+ {sourceBranch ? (+ <a+ href={`${SOURCE_REPOSITORY_URL}/tree/${encodeURIComponent(sourceBranch)}`}+ target="_blank"+ rel="noreferrer"+ className="block truncate transition-colors hover:text-foreground"+ >+ {sourceBranch}+ </a>+ ) : null}+ <p>+ Paperclip{" "}+ <a+ href={`${SOURCE_REPOSITORY_URL}/commit/${sourceFullSha}`}+ target="_blank"+ rel="noreferrer"+ className="transition-colors hover:text-foreground"+ >+ {sourceSha.slice(0, 7)}+ </a>+ </p>+ </div>+ ) : version ? (+ <p className="mt-1 text-xs text-muted-foreground">Paperclip v{version}</p>+ ) : null}+ </div>+ </div>++ <div className="mt-4 space-y-1">+ <MenuAction+ label="View profile"+ description="Open your activity, task, and usage ledger."+ icon={UserRound}+ href={profileHref}+ onClick={closeNavigationChrome}+ />+ <MenuAction+ label="Edit profile"+ description="Update your display name and avatar."+ icon={UserRoundPen}+ href={PROFILE_SETTINGS_PATH}+ onClick={closeNavigationChrome}+ />+ <MenuAction+ label="Documentation"+ description="Open Paperclip docs in a new tab."+ icon={BookOpen}+ href={DOCS_URL}+ external+ onClick={() => setOpen(false)}+ />+ <MenuAction+ label="Feedback"+ description="Share feedback or report an issue."+ icon={Megaphone}+ href={FEEDBACK_URL}+ external+ onClick={() => setOpen(false)}+ />+ <ThemeToggle variant="menu-action" onAfterToggle={() => setOpen(false)} />+ {deploymentMode === "authenticated" ? (+ <button+ type="button"+ className={cn(+ "flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",+ signOutMutation.isPending && "cursor-not-allowed opacity-60",+ )}+ onClick={handleSignOut}+ disabled={signOutMutation.isPending}+ >+ <span className="mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground">+ <LogOut className="size-4" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-sm font-medium text-foreground">+ {signOutMutation.isPending ? "Signing out..." : "Sign out"}+ </span>+ <span className="block text-xs text-muted-foreground">+ End this browser session.+ </span>+ </span>+ </button>+ ) : null}+ <SidebarServerInfo />+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ );+}diff --git a/ui/src/components/SidebarAccountMenu.test.tsx b/ui/src/components/SidebarAccountMenu.test.tsxindex de2da8d8ea..de0ccedeb2 100644--- a/ui/src/components/SidebarAccountMenu.test.tsx+++ b/ui/src/components/SidebarAccountMenu.test.tsx@@ -100,6 +100,29 @@ describe("SidebarAccountMenu", () => {vi.clearAllMocks();});+ it("shares the nav background without separator borders", async () => {+ const root = createRoot(container);+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });++ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <SidebarAccountMenu deploymentMode="local_trusted" />+ </QueryClientProvider>,+ );+ });+ await flushReact();++ const accountSurface = container.firstElementChild;+ expect(accountSurface?.className).toContain("bg-border/50");+ expect(accountSurface?.className).toContain("dark:bg-muted");+ expect(accountSurface?.className).not.toContain("border-t");+ expect(accountSurface?.className).not.toContain("border-r");+ expect(accountSurface?.className).not.toContain("border-border");++ await act(async () => root.unmount());+ });+it("keeps authenticated self-hosted sign-out on the local auth flow", async () => {const root = createRoot(container);const queryClient = new QueryClient({@@ -135,6 +158,7 @@ describe("SidebarAccountMenu", () => {await flushReact();expect(document.body.textContent).toContain("Edit profile");+ expect(document.body.textContent).toContain("Settings");expect(document.body.textContent).not.toContain("Instance settings");expect(document.body.textContent).toContain("Documentation");expect(document.body.textContent).toContain("Feedback");@@ -157,6 +181,7 @@ describe("SidebarAccountMenu", () => {expect(document.body.querySelector('[data-slot="popover-content"]')?.className).toContain("w-(--sz-277px)");expect(document.body.querySelector('a[href="/company/settings/instance/profile"]')).not.toBeNull();+ expect(document.body.querySelector('a[href="/company/settings"]')).not.toBeNull();const signOutButton = Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent?.includes("Sign out"),diff --git a/ui/src/components/SidebarAccountMenu.tsx b/ui/src/components/SidebarAccountMenu.tsxindex be58276d8a..5b15ea6088 100644--- a/ui/src/components/SidebarAccountMenu.tsx+++ b/ui/src/components/SidebarAccountMenu.tsx@@ -4,6 +4,7 @@ import {BookOpen,LogOut,Megaphone,+ Settings,type LucideIcon,UserRound,UserRoundPen,@@ -33,6 +34,8 @@ interface SidebarAccountMenuProps {onOpenChange?: (open: boolean) => void;serverGit?: ServerGitInfo;version?: string | null;+ /** Contextual navigation occupies a full sidebar even if the saved global nav mode is collapsed. */+ forceExpanded?: boolean;}interface MenuActionProps {@@ -116,10 +119,11 @@ export function SidebarAccountMenu({onOpenChange,serverGit,version,+ forceExpanded = false,}: SidebarAccountMenuProps) {const [internalOpen, setInternalOpen] = useState(false);const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();- const rail = collapsed && !peeking;+ const rail = collapsed && !peeking && !forceExpanded;const open = controlledOpen ?? internalOpen;const setOpen = onOpenChange ?? setInternalOpen;const { data: session } = useQuery({@@ -153,7 +157,7 @@ export function SidebarAccountMenu({}return (- <div className="border-t border-r border-border bg-background px-3 py-2">+ <div className="bg-border/50 px-3 py-2 dark:bg-muted"><Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><button@@ -222,6 +226,13 @@ export function SidebarAccountMenu({</div><div className="mt-4 space-y-1">+ <MenuAction+ label="Settings"+ description="Manage company and instance settings."+ icon={Settings}+ href="/company/settings"+ onClick={closeNavigationChrome}+ /><MenuActionlabel="View profile"description="Open your activity, task, and usage ledger."diff --git a/ui/src/components/SidebarAgents.production.tsx b/ui/src/components/SidebarAgents.production.tsxnew file mode 100644index 0000000000..028c8de32a--- /dev/null+++ b/ui/src/components/SidebarAgents.production.tsx@@ -0,0 +1,683 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Link, useLocation } from "@/lib/router";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ MoreHorizontal,+ Loader2,+ LogOut,+ PauseCircle,+ Pencil,+ PlayCircle,+ Plus,+ Star,+ Users,+ AlertTriangle,+} from "lucide-react";+import { useCompany } from "../context/CompanyContext";+import { useDialogActions } from "../context/DialogContext";+import { useSidebar } from "../context/SidebarContext";+import { useToastActions } from "../context/ToastContext";+import { agentsApi } from "../api/agents";+import { builtInAgentsApi, type BuiltInAgentStatus } from "../api/builtInAgents";+import { BuiltInLifecycleChip } from "./BuiltInAgentBadges";+import { authApi } from "../api/auth";+import { heartbeatsApi } from "../api/heartbeats";+import { instanceSettingsApi } from "../api/instanceSettings";+import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";+import { queryKeys } from "../lib/queryKeys";+import { cn, agentRouteRef, agentUrl, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";+import { useAgentOrder } from "../hooks/useAgentOrder";+import {+ isStarred,+ resourceMembershipState,+ starredResourceIds,+ useResourceMembershipMutation,+ useResourceMemberships,+} from "../hooks/useResourceMemberships";+import { usePublishSharedQueryData, useSharedPollingQuery } from "../hooks/useSharedPolling";+import {+ AGENT_SORT_MODE_UPDATED_EVENT,+ getAgentSortModeStorageKey,+ readAgentSortMode,+ type AgentSortModeUpdatedDetail,+ type AgentSidebarSortMode,+ writeAgentSortMode,+} from "../lib/agent-order";+import { AgentIcon } from "./AgentIconPicker";+import { BudgetSidebarMarker } from "./BudgetSidebarMarker";+import { SidebarNavItem } from "./SidebarNavItem.production";+import { SidebarSection, type SidebarSectionRadioChoice } from "./SidebarSection";+import { StarToggle } from "./StarToggle";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import type { Agent } from "@paperclipai/shared";++/**+ * When no agent is running, the sidebar falls back to showing at most this many+ * recently-active agents plus a "See all agents" link (IA Phase 5).+ */+const RECENT_AGENT_LIMIT = 3;+const LIVE_AGENT_LINGER_MS = 120_000;++const AGENT_SORT_CHOICES: SidebarSectionRadioChoice[] = [+ { value: "top", label: "Top" },+ { value: "alphabetical", label: "Alphabetical" },+ { value: "recent", label: "Recent" },+];++function agentTimestamp(agent: Agent, field: "lastHeartbeatAt" | "updatedAt" | "createdAt"): number {+ const raw = agent[field];+ if (!raw) return 0;+ const time = new Date(raw).getTime();+ return Number.isFinite(time) ? time : 0;+}++function sortAgents(agents: Agent[], sortMode: AgentSidebarSortMode): Agent[] {+ if (sortMode === "top") return agents;+ const sorted = [...agents];+ if (sortMode === "alphabetical") {+ sorted.sort((left, right) => left.name.localeCompare(right.name, undefined, { sensitivity: "base" }));+ return sorted;+ }+ sorted.sort((left, right) => {+ const heartbeatDiff = agentTimestamp(right, "lastHeartbeatAt") - agentTimestamp(left, "lastHeartbeatAt");+ if (heartbeatDiff !== 0) return heartbeatDiff;++ const updatedDiff = agentTimestamp(right, "updatedAt") - agentTimestamp(left, "updatedAt");+ if (updatedDiff !== 0) return updatedDiff;++ const createdDiff = agentTimestamp(right, "createdAt") - agentTimestamp(left, "createdAt");+ return createdDiff !== 0+ ? createdDiff+ : left.name.localeCompare(right.name, undefined, { sensitivity: "base" });+ });+ return sorted;+}++// Sidebar star reveals with the agent row's own group, not the shared group.+const AGENT_STAR_ROW_REVEAL =+ "opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";++function SidebarAgentItem({+ activeAgentId,+ activeTab,+ agent,+ disabled,+ isMobile,+ leaving,+ onLeaveAgent,+ onPauseResume,+ rail,+ runCount,+ setSidebarOpen,+ builtInStatus,+ starred = false,+ onToggleStar,+ starPending = false,+}: {+ activeAgentId: string | null;+ activeTab: string | null;+ agent: Agent;+ disabled: boolean;+ isMobile: boolean;+ leaving: boolean;+ onLeaveAgent: (agent: Agent) => void;+ onPauseResume: (agent: Agent, action: "pause" | "resume") => void;+ rail: boolean;+ runCount: number;+ setSidebarOpen: (open: boolean) => void;+ builtInStatus?: BuiltInAgentStatus;+ starred?: boolean;+ onToggleStar?: (agent: Agent, starred: boolean) => void;+ starPending?: boolean;+}) {+ const routeRef = agentRouteRef(agent);+ const href = activeTab ? `${agentUrl(agent)}/${activeTab}` : agentUrl(agent);+ const editHref = `${agentUrl(agent)}/configuration`;+ const isActive = activeAgentId === routeRef;+ const isPaused = agent.status === "paused";+ const isBudgetPaused = isPaused && agent.pauseReason === "budget";+ const hasInvalidOrgChain = agent.orgChainHealth?.status === "invalid_org_chain";+ const pauseResumeLabel = isPaused ? "Resume agent" : "Pause agent";+ const pauseResumeDisabled = disabled || agent.status === "pending_approval" || isBudgetPaused || (isPaused && hasInvalidOrgChain);+ const pauseResumeDisabledLabel = disabled+ ? "Updating..."+ : isBudgetPaused+ ? "Budget paused"+ : isPaused && hasInvalidOrgChain+ ? "Invalid org chain"+ : pauseResumeLabel;+ const showBuiltInLifecycle = builtInStatus === "needs_setup" || builtInStatus === "pending_approval";+ const trailingLabel = [+ showBuiltInLifecycle ? `Built-in agent ${builtInStatus.replace(/_/g, " ")}` : null,+ hasInvalidOrgChain ? "Invalid reporting chain" : null,+ ].filter(Boolean).join(", ") || undefined;++ // C11 (DECISION-SHEET.md): the row itself is a SidebarNavItem, so agent rows+ // share the nav-row chrome (type, active state, rail tooltip, live dot).+ const navItem = (+ <SidebarNavItem+ to={href}+ label={agent.name}+ iconNode={<AgentIcon icon={agent.icon} className="shrink-0 h-4 w-4" />}+ active={isActive}+ liveCount={runCount}+ labelClassName={showBuiltInLifecycle ? "min-w-(--sz-4_5rem) flex-initial" : undefined}+ className={cn(+ "min-w-0 flex-1",+ // Reserve room for the hover ⋯ menu; starred rows widen it for the+ // inline unstar star.+ starred && !isMobile ? "pr-14" : "pr-8",+ )}+ trailing={+ showBuiltInLifecycle || hasInvalidOrgChain ? (+ <span className="ml-1 flex shrink-0 items-center gap-1">+ {showBuiltInLifecycle ? <BuiltInLifecycleChip status={builtInStatus} compact /> : null}+ {hasInvalidOrgChain ? (+ <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-amber-500" aria-label="Invalid reporting chain" />+ ) : null}+ </span>+ ) : undefined+ }+ trailingLabel={trailingLabel}+ liveAccessory={+ agent.pauseReason === "budget" ? <BudgetSidebarMarker title="Agent paused by budget" /> : undefined+ }+ />+ );++ // Rail: the star/menu overlays are hidden, so render the nav item bare (it+ // supplies its own rail tooltip) and let it fill the column like every other+ // rail row.+ if (rail) return navItem;++ return (+ <div className="group/agent relative flex items-center">+ {navItem}++ {starred && !isMobile && onToggleStar ? (+ // Desktop: quiet inline unstar, left of the ⋯ menu, revealed on hover/focus.+ <span className="absolute right-10 top-1/2 -translate-y-1/2">+ <StarToggle+ size="row"+ quiet+ starred+ pending={starPending}+ resourceName={agent.name}+ onToggle={() => onToggleStar(agent, false)}+ revealClassName={AGENT_STAR_ROW_REVEAL}+ />+ </span>+ ) : null}++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ className={cn(+ "absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",+ isMobile+ ? "opacity-100"+ : "pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100",+ )}+ aria-label={`Open actions for ${agent.name}`}+ >+ <MoreHorizontal className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ {onToggleStar ? (+ <>+ <DropdownMenuItem+ onClick={() => {+ if (starPending) return;+ onToggleStar(agent, !starred);+ }}+ disabled={starPending}+ >+ {starPending ? (+ <Loader2 className="size-4 motion-safe:animate-spin" />+ ) : (+ <Star className={cn("size-4", starred && "fill-amber-500 text-amber-500")} />+ )}+ <span>{starred ? "Remove from starred" : "Star agent"}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ ) : null}+ <DropdownMenuItem asChild>+ <Link+ to={editHref}+ onClick={() => {+ if (isMobile) setSidebarOpen(false);+ }}+ >+ <Pencil className="size-4" />+ <span>Edit agent</span>+ </Link>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ if (pauseResumeDisabled) return;+ onPauseResume(agent, isPaused ? "resume" : "pause");+ }}+ disabled={pauseResumeDisabled}+ title={isBudgetPaused ? "Agent was paused by budget limits" : undefined}+ >+ {isPaused ? <PlayCircle className="size-4" /> : <PauseCircle className="size-4" />}+ <span>{pauseResumeDisabledLabel}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ if (leaving) return;+ onLeaveAgent(agent);+ }}+ disabled={leaving}+ >+ {leaving ? <Loader2 className="size-4 motion-safe:animate-spin" /> : <LogOut className="size-4" />}+ <span>{leaving ? "Leaving..." : "Leave agent"}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++export function SidebarAgents({ streamlined = false }: { streamlined?: boolean } = {}) {+ const [open, setOpen] = useState(true);+ const [pendingAgentIds, setPendingAgentIds] = useState<Set<string>>(() => new Set());+ const [liveLingerVersion, setLiveLingerVersion] = useState(0);+ const lastSeenLiveAtRef = useRef<Map<string, number>>(new Map());+ const queryClient = useQueryClient();+ const { selectedCompanyId } = useCompany();+ const { openNewAgent } = useDialogActions();+ const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();+ const rail = collapsed && !peeking;+ const { pushToast } = useToastActions();+ const location = useLocation();++ const { data: agents } = useQuery({+ queryKey: queryKeys.agents.list(selectedCompanyId!),+ queryFn: () => agentsApi.list(selectedCompanyId!),+ enabled: !!selectedCompanyId,+ });+ const { data: experimentalSettings } = useQuery({+ queryKey: queryKeys.instance.experimentalSettings,+ queryFn: () => instanceSettingsApi.getExperimental(),+ enabled: !!selectedCompanyId,+ });+ const builtInAgentsEnabled = experimentalSettings?.enableBuiltInAgents === true;+ const { data: builtInAgents } = useQuery({+ queryKey: queryKeys.builtInAgents.list(selectedCompanyId!),+ queryFn: () => builtInAgentsApi.list(selectedCompanyId!),+ enabled: !!selectedCompanyId && builtInAgentsEnabled,+ });+ const builtInStatusByAgentId = useMemo(() => {+ const map = new Map<string, BuiltInAgentStatus>();+ if (!builtInAgentsEnabled) return map;+ for (const entry of builtInAgents ?? []) {+ if (entry.agentId) map.set(entry.agentId, entry.status);+ }+ return map;+ }, [builtInAgents, builtInAgentsEnabled]);+ const { data: session } = useQuery({+ queryKey: queryKeys.auth.session,+ queryFn: () => authApi.getSession(),+ });+ const membershipsQuery = useResourceMemberships(selectedCompanyId);+ const membershipMutation = useResourceMembershipMutation(selectedCompanyId);++ const liveRunsQueryKey = queryKeys.liveRuns(selectedCompanyId!);+ const sharedLiveRuns = useSharedPollingQuery({+ companyId: selectedCompanyId,+ resourceKey: "live-runs",+ queryKey: liveRunsQueryKey,+ enabled: !!selectedCompanyId,+ // Event-sourced via LiveUpdatesProvider (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);++ const liveCountByAgent = useMemo(() => {+ const counts = new Map<string, number>();+ for (const run of liveRuns ?? []) {+ counts.set(run.agentId, (counts.get(run.agentId) ?? 0) + 1);+ }+ return counts;+ }, [liveRuns]);+ const liveAgentIds = useMemo(() => {+ const ids = new Set<string>();+ for (const [agentId, count] of liveCountByAgent) {+ if (count > 0) ids.add(agentId);+ }+ return ids;+ }, [liveCountByAgent]);++ const visibleAgents = useMemo(() => {+ const filtered = (agents ?? []).filter(+ (a: Agent) =>+ a.status !== "terminated" &&+ (+ !membershipsQuery.isSuccess ||+ resourceMembershipState(membershipsQuery.data, "agent", a.id) !== "left"+ )+ );+ return filtered;+ }, [agents, membershipsQuery.data, membershipsQuery.isSuccess]);+ const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;+ const sortModeStorageKey = useMemo(() => {+ if (!selectedCompanyId) return null;+ return getAgentSortModeStorageKey(selectedCompanyId, currentUserId);+ }, [currentUserId, selectedCompanyId]);+ const [sortMode, setSortMode] = useState<AgentSidebarSortMode>(() => {+ if (!sortModeStorageKey) return "top";+ return readAgentSortMode(sortModeStorageKey);+ });+ const { orderedAgents } = useAgentOrder({+ agents: visibleAgents,+ companyId: selectedCompanyId,+ userId: currentUserId,+ });+ const sortedAgents = useMemo(+ () => sortAgents(orderedAgents, sortMode),+ [orderedAgents, sortMode],+ );+ const sortedAgentIdSet = useMemo(+ () => new Set(sortedAgents.map((agent: Agent) => agent.id)),+ [sortedAgents],+ );++ useEffect(() => {+ const now = Date.now();+ for (const agentId of liveAgentIds) {+ lastSeenLiveAtRef.current.set(agentId, now);+ }+ for (const agentId of lastSeenLiveAtRef.current.keys()) {+ if (!sortedAgentIdSet.has(agentId)) {+ lastSeenLiveAtRef.current.delete(agentId);+ }+ }+ }, [liveAgentIds, sortedAgentIdSet]);++ // IA Phase 5 (streamlined): if any agent has a live run, show only those+ // active agents. Agents that just stopped running linger briefly so clustered+ // run boundaries do not make rows pop out and the section does not immediately+ // swap to the recent fallback during short all-idle gaps. Otherwise fall back+ // to up to RECENT_AGENT_LIMIT agents. Either way a "See all agents" link is+ // shown so the full list is always reachable.+ // Classic mode (PAP-89, flag OFF) restores the show-all behavior.+ const runningAgents = useMemo(() => {+ const nowForLiveLinger = Date.now();+ const lastSeenLiveAtByAgent = lastSeenLiveAtRef.current;+ return sortedAgents.filter((agent: Agent) => {+ if ((liveCountByAgent.get(agent.id) ?? 0) > 0) return true;+ const lastSeenLiveAt = lastSeenLiveAtByAgent.get(agent.id);+ return lastSeenLiveAt !== undefined && nowForLiveLinger - lastSeenLiveAt <= LIVE_AGENT_LINGER_MS;+ });+ }, [liveCountByAgent, liveLingerVersion, sortedAgents]);+ const hasActiveAgents = runningAgents.length > 0;+ const displayedAgents = !streamlined+ ? sortedAgents+ : hasActiveAgents+ ? runningAgents+ : sortedAgents.slice(0, RECENT_AGENT_LIMIT);+ // Always expose "See all agents" whenever the displayed list is a subset of all+ // agents, so users never lose the entry point to the full list. In classic mode+ // every agent is already shown, so the link is unnecessary.+ const showSeeAllLink = streamlined && sortedAgents.length > 0;++ const agentMatch = location.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/);+ const activeAgentId = agentMatch?.[1] ?? null;+ const activeTab = agentMatch?.[2] ?? null;++ useEffect(() => {+ if (!sortModeStorageKey) {+ setSortMode("top");+ return;+ }+ setSortMode(readAgentSortMode(sortModeStorageKey));+ }, [sortModeStorageKey]);++ useEffect(() => {+ if (!sortModeStorageKey) return;++ const onStorage = (event: StorageEvent) => {+ if (event.key !== sortModeStorageKey) return;+ setSortMode(readAgentSortMode(sortModeStorageKey));+ };+ const onCustomEvent = (event: Event) => {+ const detail = (event as CustomEvent<AgentSortModeUpdatedDetail>).detail;+ if (!detail || detail.storageKey !== sortModeStorageKey) return;+ setSortMode(detail.sortMode);+ };++ window.addEventListener("storage", onStorage);+ window.addEventListener(AGENT_SORT_MODE_UPDATED_EVENT, onCustomEvent);+ return () => {+ window.removeEventListener("storage", onStorage);+ window.removeEventListener(AGENT_SORT_MODE_UPDATED_EVENT, onCustomEvent);+ };+ }, [sortModeStorageKey]);++ useEffect(() => {+ if (!streamlined) return;++ const now = Date.now();+ let nextExpiryAt: number | null = null;+ for (const agent of sortedAgents) {+ if ((liveCountByAgent.get(agent.id) ?? 0) > 0) continue;+ const lastSeenLiveAt = lastSeenLiveAtRef.current.get(agent.id);+ if (lastSeenLiveAt === undefined) continue;+ const expiresAt = lastSeenLiveAt + LIVE_AGENT_LINGER_MS;+ if (expiresAt < now) continue;+ nextExpiryAt = nextExpiryAt === null ? expiresAt : Math.min(nextExpiryAt, expiresAt);+ }+ if (nextExpiryAt === null) return;++ const timeoutId = window.setTimeout(() => {+ setLiveLingerVersion((version) => version + 1);+ }, Math.max(0, nextExpiryAt - now + 1));++ return () => {+ window.clearTimeout(timeoutId);+ };+ }, [streamlined, sortedAgents, liveCountByAgent, liveLingerVersion]);++ const persistSortMode = useCallback(+ (value: string) => {+ const nextSortMode: AgentSidebarSortMode =+ value === "alphabetical" || value === "recent" ? value : "top";+ setSortMode(nextSortMode);+ if (sortModeStorageKey) {+ writeAgentSortMode(sortModeStorageKey, nextSortMode);+ }+ },+ [sortModeStorageKey],+ );++ const pauseResumeAgent = useMutation({+ mutationFn: ({ agent, action }: { agent: Agent; action: "pause" | "resume" }) =>+ action === "pause"+ ? agentsApi.pause(agent.id, selectedCompanyId ?? undefined)+ : agentsApi.resume(agent.id, selectedCompanyId ?? undefined),+ onMutate: ({ agent }) => {+ setPendingAgentIds((current) => {+ const next = new Set(current);+ next.add(agent.id);+ return next;+ });+ },+ onSuccess: async (_agent, { agent, action }) => {+ if (selectedCompanyId) {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId) }),+ queryClient.invalidateQueries({ queryKey: queryKeys.liveRuns(selectedCompanyId) }),+ queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(selectedCompanyId) }),+ ]);+ }+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) }),+ queryClient.invalidateQueries({ queryKey: queryKeys.agents.detail(agentRouteRef(agent)) }),+ ]);+ pushToast({+ title: action === "pause" ? "Agent paused" : "Agent resumed",+ body: agent.name,+ tone: "success",+ });+ },+ onError: (error, { agent, action }) => {+ pushToast({+ title: action === "pause" ? "Could not pause agent" : "Could not resume agent",+ body: error instanceof Error ? error.message : agent.name,+ tone: "error",+ });+ },+ onSettled: (_data, _error, { agent }) => {+ setPendingAgentIds((current) => {+ const next = new Set(current);+ next.delete(agent.id);+ return next;+ });+ },+ });++ const leaveAgent = useCallback(+ (agent: Agent) => membershipMutation.mutate({+ resourceType: "agent",+ resourceId: agent.id,+ resourceName: agent.name,+ state: "left",+ }),+ [membershipMutation],+ );+ const agentLeaving = useCallback(+ (agent: Agent) =>+ membershipMutation.isPending &&+ membershipMutation.variables?.resourceType === "agent" &&+ membershipMutation.variables.resourceId === agent.id,+ [membershipMutation.isPending, membershipMutation.variables],+ );++ const toggleStarAgent = useCallback(+ (agent: Agent, starred: boolean) => membershipMutation.mutate({+ resourceType: "agent",+ resourceId: agent.id,+ resourceName: agent.name,+ starred,+ }),+ [membershipMutation],+ );+ const agentStarPending = useCallback(+ (agent: Agent) =>+ membershipMutation.isPending &&+ membershipMutation.variables?.resourceType === "agent" &&+ membershipMutation.variables.resourceId === agent.id &&+ membershipMutation.variables.starred !== undefined,+ [membershipMutation.isPending, membershipMutation.variables],+ );++ // Starred agents pin to the top of the section (name order), and are deduped+ // out of the active/recent subset so no agent appears twice.+ const starredAgentIdSet = useMemo(+ () => new Set(starredResourceIds(membershipsQuery.data, "agent")),+ [membershipsQuery.data],+ );+ const starredAgents = useMemo(+ () => sortAgents(visibleAgents.filter((agent: Agent) => starredAgentIdSet.has(agent.id)), "alphabetical"),+ [visibleAgents, starredAgentIdSet],+ );+ const dedupedDisplayedAgents = useMemo(+ () => displayedAgents.filter((agent: Agent) => !starredAgentIdSet.has(agent.id)),+ [displayedAgents, starredAgentIdSet],+ );++ const renderAgentRow = (agent: Agent, isStarredRow: boolean) => (+ <SidebarAgentItem+ key={agent.id}+ activeAgentId={activeAgentId}+ activeTab={activeTab}+ agent={agent}+ disabled={pendingAgentIds.has(agent.id)}+ isMobile={isMobile}+ leaving={agentLeaving(agent)}+ onLeaveAgent={leaveAgent}+ onPauseResume={(targetAgent, action) => pauseResumeAgent.mutate({ agent: targetAgent, action })}+ rail={rail}+ runCount={liveCountByAgent.get(agent.id) ?? 0}+ setSidebarOpen={setSidebarOpen}+ builtInStatus={builtInStatusByAgentId.get(agent.id)}+ starred={isStarredRow || isStarred(membershipsQuery.data, "agent", agent.id)}+ onToggleStar={toggleStarAgent}+ starPending={agentStarPending(agent)}+ />+ );++ return (+ <SidebarSection+ label="Agents"+ collapsible={{ open, onOpenChange: setOpen }}+ headerAction={{+ ariaLabel: "New agent",+ icon: Plus,+ onClick: openNewAgent,+ }}+ menu={{+ ariaLabel: "Agents section actions",+ actions: [+ { type: "item", label: "Browse agents", icon: Users, href: "/agents/all" },+ { type: "separator" },+ ],+ radioLabel: "Agent sort",+ radioChoices: AGENT_SORT_CHOICES,+ radioValue: sortMode,+ onRadioValueChange: persistSortMode,+ }}+ >+ {starredAgents.map((agent: Agent) => renderAgentRow(agent, true))}+ {dedupedDisplayedAgents.map((agent: Agent) => renderAgentRow(agent, false))}+ {showSeeAllLink && (() => {+ // Deliberately NOT a SidebarNavItem: this is a quiet muted affordance+ // (plain Link) that must not adopt nav-row active-route highlighting.+ const seeAllLink = (+ <Link+ to="/agents/all"+ state={SIDEBAR_SCROLL_RESET_STATE}+ aria-label={rail ? "See all agents" : undefined}+ onClick={() => {+ if (isMobile) setSidebarOpen(false);+ }}+ className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"+ >+ <Users className="shrink-0 h-4 w-4" />+ <span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : undefined}>See all agents</span>+ </Link>+ );+ return rail ? (+ <Tooltip>+ <TooltipTrigger asChild>{seeAllLink}</TooltipTrigger>+ <TooltipContent side="right">See all agents</TooltipContent>+ </Tooltip>+ ) : (+ seeAllLink+ );+ })()}+ </SidebarSection>+ );+}diff --git a/ui/src/components/SidebarAgents.tsx b/ui/src/components/SidebarAgents.tsxindex 14eca32d88..efaa3b387d 100644--- a/ui/src/components/SidebarAgents.tsx+++ b/ui/src/components/SidebarAgents.tsx@@ -663,7 +663,7 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }onClick={() => {if (isMobile) setSidebarOpen(false);}}- className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"+ className="flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-background hover:text-foreground"><Users className="shrink-0 h-4 w-4" /><span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : undefined}>See all agents</span>diff --git a/ui/src/components/SidebarCompanyMenu.production.tsx b/ui/src/components/SidebarCompanyMenu.production.tsxnew file mode 100644index 0000000000..8d2a50a2e3--- /dev/null+++ b/ui/src/components/SidebarCompanyMenu.production.tsx@@ -0,0 +1,513 @@+import { useCallback, useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ Check,+ ChevronsUpDown,+ GripVertical,+ LogOut,+ Plus,+ RefreshCw,+ UserPlus,+} from "lucide-react";+import {+ DndContext,+ MouseSensor,+ TouchSensor,+ closestCenter,+ type DragEndEvent,+ useSensor,+ useSensors,+} from "@dnd-kit/core";+import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import type { Company } from "@paperclipai/shared";+import { Link, useLocation, useNavigate } from "@/lib/router";+import { authApi } from "@/api/auth";+import { cloudApi, type CloudStackSummary } from "@/api/cloud";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { useCompany } from "@/context/CompanyContext";+import { useDialogActions } from "@/context/DialogContext";+import { useCloudInstance } from "@/hooks/useCloudInstance";+import { useCompanyOrder } from "@/hooks/useCompanyOrder";+import { useSignOut } from "@/hooks/useSignOut";+import { navigateTopLevel } from "@/lib/browserNavigation";+import { cloudStackCreateUrl, cloudStackEnterUrl } from "@/lib/cloudLinks";+import { queryKeys } from "@/lib/queryKeys";+import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";+import { useSidebar } from "../context/SidebarContext";+import { CompanyPatternIcon } from "./CompanyPatternIcon";++interface SidebarCompanyMenuProps {+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}++const WORKSPACE_ICON_CLASS = "size-5 shrink-0 rounded-md text-(length:--text-micro)";+const WORKSPACE_BADGE_CLASS =+ "shrink-0 rounded bg-muted px-1.5 py-0.5 font-mono text-(length:--text-nano) text-muted-foreground";++function WorkspaceIcon({ company }: { company: Company }) {+ return (+ <CompanyPatternIcon+ companyName={company.name}+ logoUrl={company.logoUrl}+ className={WORKSPACE_ICON_CLASS}+ />+ );+}++/**+ * Cloud stacks have no hot-linkable icon URL in the portfolio payload, so v1+ * renders the same deterministic monogram treatment cloud's own portfolio page+ * uses — seeded by the display name, never fetched.+ */+function StackIcon({ displayName }: { displayName: string }) {+ return <CompanyPatternIcon companyName={displayName} className={WORKSPACE_ICON_CLASS} />;+}++/**+ * The switcher trigger on a Cloud instance. A Cloud tenant holds exactly one+ * company and the harness pushes the stack's uploaded workspace icon into+ * that company's branding, so the company logo is the stack logo here.+ * The stack rows keep the monogram treatment above.+ */+function CurrentStackIcon({+ displayName,+ company,+}: {+ displayName: string;+ company: Company | null;+}) {+ return (+ <CompanyPatternIcon+ companyName={displayName}+ logoUrl={company?.logoUrl}+ className={WORKSPACE_ICON_CLASS}+ />+ );+}++function CloudStackItem({+ stack,+ isSelected,+ onSelect,+}: {+ stack: CloudStackSummary;+ isSelected: boolean;+ onSelect: (stack: CloudStackSummary) => void;+}) {+ return (+ <DropdownMenuItem+ onSelect={() => onSelect(stack)}+ className={cn("min-w-0 gap-2 py-2", isSelected && "bg-accent text-accent-foreground")}+ >+ <StackIcon displayName={stack.displayName} />+ <span className="min-w-0 flex-1 truncate" title={stack.displayName}>+ {stack.displayName}+ </span>+ {/* Company badges are 3-4 character issue prefixes, but stack slugs are+ user-chosen and can be long enough to truncate the name to a single+ letter — the name is the primary identifier, so the badge yields. */}+ <span className={cn(WORKSPACE_BADGE_CLASS, "max-w-24 truncate")} title={stack.stackSlug}>+ {stack.stackSlug}+ </span>+ {isSelected ? <Check className="size-4 shrink-0 text-muted-foreground" /> : null}+ </DropdownMenuItem>+ );+}++function SortableCompanyItem({+ company,+ isEditing,+ isSelected,+ onSelect,+}: {+ company: Company;+ isEditing: boolean;+ isSelected: boolean;+ onSelect: (company: Company) => void;+}) {+ const {+ attributes,+ listeners,+ setActivatorNodeRef,+ setNodeRef,+ transform,+ transition,+ isDragging,+ } = useSortable({ id: company.id, disabled: !isEditing });++ return (+ <DropdownMenuItem+ ref={setNodeRef}+ style={{+ transform: CSS.Transform.toString(transform),+ transition,+ zIndex: isDragging ? 10 : undefined,+ }}+ onSelect={(event) => {+ if (isEditing) {+ event.preventDefault();+ return;+ }+ onSelect(company);+ }}+ className={cn(+ "min-w-0 gap-2 py-2",+ isEditing && "cursor-grab",+ isDragging && "opacity-80",+ isSelected && "bg-accent text-accent-foreground",+ )}+ >+ <WorkspaceIcon company={company} />+ <span className="min-w-0 flex-1 truncate">{company.name}</span>+ {isEditing ? (+ <button+ type="button"+ ref={setActivatorNodeRef}+ aria-label={`Reorder ${company.name}`}+ className="inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-(length:--rad-2) focus-visible:ring-ring"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ {...attributes}+ {...listeners}+ >+ <GripVertical className="size-4" aria-hidden="true" />+ </button>+ ) : (+ <>+ <span className={WORKSPACE_BADGE_CLASS}>{company.issuePrefix}</span>+ {isSelected ? <Check className="size-4 text-muted-foreground" /> : null}+ </>+ )}+ </DropdownMenuItem>+ );+}++export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: SidebarCompanyMenuProps = {}) {+ const [internalOpen, setInternalOpen] = useState(false);+ const [isEditingOrder, setIsEditingOrder] = useState(false);+ const { companies, selectedCompany, setSelectedCompanyId, companyListUnavailable, retryCompanies } =+ useCompany();+ const { openOnboarding } = useDialogActions();+ const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();+ const rail = collapsed && !peeking;+ const location = useLocation();+ const navigate = useNavigate();+ const open = controlledOpen ?? internalOpen;+ const setOpen = onOpenChange ?? setInternalOpen;+ const sensors = useSensors(+ useSensor(MouseSensor, {+ activationConstraint: { distance: 8 },+ }),+ useSensor(TouchSensor, {+ activationConstraint: { delay: 180, tolerance: 6 },+ }),+ );+ const sidebarCompanies = useMemo(+ () => companies.filter((company) => company.status !== "archived"),+ [companies],+ );+ const { data: session } = useQuery({+ queryKey: queryKeys.auth.session,+ queryFn: () => authApi.getSession(),+ retry: false,+ });+ const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;+ const { orderedCompanies, persistOrder } = useCompanyOrder({+ companies: sidebarCompanies,+ userId: currentUserId,+ });++ // In Paperclip Cloud the switcher lists the signed-in user's stacks+ // (organizations) instead of the instance's companies: a cloud instance holds+ // exactly one company, and switching means leaving this tenant host entirely.+ const cloud = useCloudInstance();+ const isCloud = Boolean(cloud);+ const cloudBaseUrl = cloud?.cloudBaseUrl ?? null;+ const stacksQuery = useQuery({+ queryKey: queryKeys.cloud.stacks,+ queryFn: () => cloudApi.listStacks(),+ enabled: isCloud,+ staleTime: 30_000,+ retry: false,+ });+ const stacks = stacksQuery.data?.stacks ?? [];+ const currentStack = isCloud+ ? stacks.find((stack) => stack.isCurrent)+ ?? stacks.find((stack) => Boolean(cloud?.stackSlug) && stack.stackSlug === cloud?.stackSlug)+ ?? null+ : null;+ const createStackUrl = isCloud ? cloudStackCreateUrl(cloudBaseUrl) : null;+ const switcherNoun = isCloud ? "organization" : "company";+ // The one name the chrome shows for "where am I": the stack in cloud, the+ // company when self-hosted.+ const currentName = isCloud+ ? currentStack?.displayName ?? cloud?.stackDisplayName ?? cloud?.stackSlug ?? null+ : selectedCompany?.name ?? null;++ const signOutMutation = useSignOut({ onSignedOut: closeNavigationChrome });++ function handleOpenChange(nextOpen: boolean) {+ if (!nextOpen) setIsEditingOrder(false);+ setOpen(nextOpen);+ }++ function closeNavigationChrome() {+ setOpen(false);+ setIsEditingOrder(false);+ if (isMobile) setSidebarOpen(false);+ }++ function selectCompany(company: Company) {+ const pathPrefix = location.pathname.split("/")[1]?.toUpperCase();+ const isCompanyRoute = sidebarCompanies.some((sidebarCompany) => (+ sidebarCompany.issuePrefix.toUpperCase() === pathPrefix+ ));+ const shouldLeaveCurrentRoute = company.id !== selectedCompany?.id+ && (location.pathname.startsWith("/instance/") || isCompanyRoute);++ setSelectedCompanyId(company.id);+ setOpen(false);+ if (isMobile) setSidebarOpen(false);+ if (shouldLeaveCurrentRoute) {+ navigate(`/${company.issuePrefix}/dashboard`);+ }+ }++ /**+ * Switching stacks is a full top-level navigation, not client routing: the+ * cloud entry-code handoff authenticates the user for the target stack and+ * wakes it if it is asleep before landing on its own tenant host.+ */+ function selectStack(stack: CloudStackSummary) {+ setOpen(false);+ if (isMobile) setSidebarOpen(false);+ if (stack.stackSlug === currentStack?.stackSlug) return;+ const target = cloudStackEnterUrl(cloudBaseUrl, stack.stackSlug);+ if (!target) return;+ navigateTopLevel(target);+ }++ function addCompany() {+ setOpen(false);+ if (isMobile) setSidebarOpen(false);+ // Cloud creates organizations in the cloud app; the in-app company wizard+ // is unreachable there (POST /companies is a 403 floor on managed stacks).+ if (isCloud) {+ if (createStackUrl) navigateTopLevel(createStackUrl);+ return;+ }+ // Skip the front-door "how would you like to get started?" choice and land+ // directly on "Name your organization" — this entry point is unambiguously+ // "create a new company" (PAP-431).+ openOnboarding({ initialStep: 1 });+ }++ const handleDragEnd = useCallback(+ (event: DragEndEvent) => {+ const { active, over } = event;+ if (!over || active.id === over.id) return;++ const ids = orderedCompanies.map((company) => company.id);+ const oldIndex = ids.indexOf(active.id as string);+ const newIndex = ids.indexOf(over.id as string);+ if (oldIndex === -1 || newIndex === -1) return;++ persistOrder(arrayMove(ids, oldIndex, newIndex));+ },+ [orderedCompanies, persistOrder],+ );++ return (+ <DropdownMenu open={open} onOpenChange={handleOpenChange}>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ // The nav icon column sits at nav px-3 + item mx-2 + item px-2.+ // Match that inset with wrapper px-3 + trigger px-4. Override the+ // Button's direct-SVG padding too so the expanded chevron cannot pull+ // the avatar four pixels left of the nav icons.+ // `min-w-0` on every link of the flex chain (button → label row → label)+ // is what lets the name truncate: a flex item's default `min-width:auto`+ // floors it at its content width, so without it a long name widens the+ // trigger past the sidebar and pushes the chevron out of bounds. Company+ // names were short in practice; cloud stack names are user-chosen.+ className="h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50"+ aria-label={+ currentName+ ? `Open ${currentName} ${switcherNoun} switcher`+ : `Open ${switcherNoun} switcher`+ }+ >+ <span className="flex min-w-0 flex-1 items-center gap-2">+ {isCloud+ ? currentName ? <CurrentStackIcon displayName={currentName} company={selectedCompany} /> : null+ : selectedCompany ? <WorkspaceIcon company={selectedCompany} /> : null}+ {/* The header has room for ~110px of name beside the collapse+ control (~142px on mobile, which hides it) — search moved to+ the nav to buy that width. A name that still+ truncates stays hover-recoverable via title. */}+ <span+ className={cn(+ "min-w-0 truncate text-sm font-bold text-foreground",+ rail && SIDEBAR_RAIL_HIDDEN_LABEL,+ )}+ title={currentName ?? undefined}+ >+ {currentName ?? (isCloud ? "Select organization" : "Select company")}+ </span>+ </span>+ {!rail && <ChevronsUpDown className="size-3.5 shrink-0 text-muted-foreground" />}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={8} className="w-64 p-1">+ <div className="flex items-center justify-between gap-2 px-2 py-1.5">+ <DropdownMenuLabel className="p-0 text-(length:--text-micro) font-semibold uppercase text-muted-foreground">+ {isCloud ? "Switch organization" : "Switch company"}+ </DropdownMenuLabel>+ {/* Stack order is owned by cloud's own portfolio in v1, so the+ drag-to-reorder affordance stays self-hosted-only. */}+ {isCloud ? null : (+ <button+ type="button"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsEditingOrder((current) => !current);+ }}+ className="rounded px-1.5 py-0.5 text-(length:--text-micro) font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ {isEditingOrder ? "Done" : "Edit"}+ </button>+ )}+ </div>+ <div className="max-h-96 overflow-y-auto">+ {isCloud ? (+ <>+ {stacks.map((stack) => (+ <CloudStackItem+ key={stack.stackSlug}+ stack={stack}+ isSelected={stack.stackSlug === currentStack?.stackSlug}+ onSelect={selectStack}+ />+ ))}+ {stacks.length === 0 ? (+ <DropdownMenuItem disabled>+ {stacksQuery.isLoading+ ? "Loading organizations..."+ : stacksQuery.isError+ ? "Could not load organizations"+ : "No organizations"}+ </DropdownMenuItem>+ ) : null}+ </>+ ) : (+ <>+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={orderedCompanies.map((company) => company.id)}+ strategy={verticalListSortingStrategy}+ >+ {orderedCompanies.map((company) => (+ <SortableCompanyItem+ key={company.id}+ company={company}+ isEditing={isEditingOrder}+ isSelected={company.id === selectedCompany?.id}+ onSelect={selectCompany}+ />+ ))}+ </SortableContext>+ </DndContext>+ {orderedCompanies.length === 0 ? (+ // "No companies" is a claim about the account. After a failed+ // list request it is one we cannot make, and this menu is the+ // only place the customer can act on it — say what happened and+ // offer the way back.+ companyListUnavailable ? (+ <>+ <DropdownMenuItem disabled>Couldn't load companies</DropdownMenuItem>+ <DropdownMenuItem+ onSelect={(event) => {+ // Keep the menu open so the result of the retry is visible.+ event.preventDefault();+ void retryCompanies();+ }}+ >+ <RefreshCw className="h-4 w-4 mr-2" />+ Try again+ </DropdownMenuItem>+ </>+ ) : (+ <DropdownMenuItem disabled>No companies</DropdownMenuItem>+ )+ ) : null}+ </>+ )}+ </div>+ <DropdownMenuSeparator />+ {/* A cloud instance without a configured cloud origin has nowhere to+ send the user, so the row (and its separator) drop out entirely. */}+ {isCloud && !createStackUrl ? null : (+ <>+ <DropdownMenuItem+ onClick={addCompany}+ className="gap-2 py-2 text-muted-foreground"+ disabled={isEditingOrder}+ >+ <Plus className="size-4" />+ <span>Create new organization...</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem asChild disabled={isEditingOrder}>+ <Link+ to="/company/settings/invites"+ onClick={(event) => {+ if (isEditingOrder) {+ event.preventDefault();+ return;+ }+ closeNavigationChrome();+ }}+ >+ <UserPlus className="size-4" />+ <span className="truncate">+ {currentName ? `Invite people to ${currentName}` : "Invite people"}+ </span>+ </Link>+ </DropdownMenuItem>+ {session?.session ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => signOutMutation.mutate()}+ disabled={isEditingOrder || signOutMutation.isPending}+ >+ <LogOut className="size-4" />+ <span>{signOutMutation.isPending ? "Signing out..." : "Sign out"}</span>+ </DropdownMenuItem>+ </>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/ui/src/components/SidebarCompanyMenu.test.tsx b/ui/src/components/SidebarCompanyMenu.test.tsxindex 0d4ef924be..133cfea4ab 100644--- a/ui/src/components/SidebarCompanyMenu.test.tsx+++ b/ui/src/components/SidebarCompanyMenu.test.tsx@@ -293,6 +293,11 @@ describe("SidebarCompanyMenu", () => {const trigger = container.querySelector('button[aria-label="Open Acme Labs organization switcher"]');expect(trigger).not.toBeNull();+ expect(trigger?.classList).toContain("px-4");+ expect(trigger?.classList).toContain("has-[>svg]:px-4");+ expect(trigger?.classList).toContain("hover:bg-background");+ expect(trigger?.classList).toContain("hover:text-foreground");+ expect(trigger?.classList).toContain("dark:hover:bg-background");act(() => {trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));diff --git a/ui/src/components/SidebarCompanyMenu.tsx b/ui/src/components/SidebarCompanyMenu.tsxindex 238f240bbf..4b492d1fc2 100644--- a/ui/src/components/SidebarCompanyMenu.tsx+++ b/ui/src/components/SidebarCompanyMenu.tsx@@ -343,17 +343,16 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb<DropdownMenuTrigger asChild><Buttonvariant="ghost"- // `px-3` (not px-2) so the logo's left edge lines up with the nav icon- // column (nav px-3 + item px-3) and, crucially, stays put between states:- // the Button's default size adds `has-[>svg]:px-3`, so with the chevron- // svg present (expanded) it was already 12px but without it (rail) it fell- // back to 8px — a 4px horizontal jump on collapse (PAP-10676).+ // The nav icon column sits at nav px-3 + item mx-2 + item px-2.+ // Match that inset with wrapper px-3 + trigger px-4. Override the+ // Button's direct-SVG padding too so the expanded chevron cannot pull+ // the avatar four pixels left of the nav icons.// `min-w-0` on every link of the flex chain (button → label row → label)// is what lets the name truncate: a flex item's default `min-width:auto`// floors it at its content width, so without it a long name widens the// trigger past the sidebar and pushes the chevron out of bounds. Company// names were short in practice; cloud stack names are user-chosen.- className="h-9 min-w-0 flex-1 justify-start gap-2 px-3 text-left"+ className="h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-background hover:text-foreground has-[>svg]:px-4 dark:hover:bg-background"aria-label={currentName? `Open ${currentName} ${switcherNoun} switcher`diff --git a/ui/src/components/SidebarNavItem.production.tsx b/ui/src/components/SidebarNavItem.production.tsxnew file mode 100644index 0000000000..c7034179c8--- /dev/null+++ b/ui/src/components/SidebarNavItem.production.tsx@@ -0,0 +1,226 @@+import { createContext, useContext, type ReactNode } from "react";+import { NavLink } from "@/lib/router";+import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";+import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";+import { useSidebar } from "../context/SidebarContext";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import type { LucideIcon } from "lucide-react";+import { Badge } from "@/components/ui/badge";++/**+ * Forces the full-label (non-rail) presentation for any `SidebarNavItem`+ * rendered beneath it, regardless of the global `useSidebar().collapsed` state.+ *+ * Takeover routes (PAP-10695) collapse the app `<Sidebar/>` to its 64px rail+ * and render the contextual nav in a fixed 240px `SecondarySidebar`. That pane+ * is always wide enough for labels, but its `SidebarNavItem` children still+ * read the *global* `collapsed=true` and would otherwise render icon-only —+ * leaving the settings nav unreadable (PAP-10700). Wrapping the pane in this+ * provider decouples its items from the global rail collapse.+ */+const SidebarNavExpandedContext = createContext(false);++export function SidebarNavExpandedProvider({ children }: { children: ReactNode }) {+ return (+ <SidebarNavExpandedContext.Provider value={true}>+ {children}+ </SidebarNavExpandedContext.Provider>+ );+}++export function useSidebarNavExpanded() {+ return useContext(SidebarNavExpandedContext);+}++interface SidebarNavItemProps {+ to: string;+ label: string;+ icon?: LucideIcon;+ /**+ * Pre-rendered icon element for rows whose icon isn't a plain Lucide+ * component (e.g. the agent rows' `AgentIcon`). Takes precedence over `icon`;+ * the caller owns its sizing/color classes.+ */+ iconNode?: ReactNode;+ end?: boolean;+ className?: string;+ labelClassName?: string;+ badge?: number;+ badgeTone?: "default" | "danger" | "warning";+ /**+ * Accessible noun for the numeric badge when collapsed to the rail, where the+ * count is rendered as a dot (e.g. `badgeLabel="unread"` → "Inbox, 28 unread").+ */+ badgeLabel?: string;+ textBadge?: string;+ textBadgeTone?: "default" | "amber";+ alert?: boolean;+ liveCount?: number;+ /**+ * Overrides NavLink's own route matching for rows whose active state is+ * computed externally (agent rows match `/agents/:ref` across tab suffixes).+ */+ active?: boolean;+ /** Rendered after the label, before the right-aligned status cluster. */+ trailing?: ReactNode;+ /** Accessible text for `trailing` status content, surfaced in the collapsed rail (where `trailing` is hidden). */+ trailingLabel?: string;+ /** Rendered inside the right-aligned status cluster, before the live dot. */+ liveAccessory?: ReactNode;+}++export function SidebarNavItem({+ to,+ label,+ icon: Icon,+ iconNode,+ end,+ className,+ labelClassName,+ badge,+ badgeTone = "default",+ badgeLabel,+ textBadge,+ textBadgeTone = "default",+ alert = false,+ liveCount,+ active,+ trailing,+ trailingLabel,+ liveAccessory,+}: SidebarNavItemProps) {+ const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();+ // A fixed-width contextual pane (SecondarySidebar) forces full labels even+ // when the global app sidebar is collapsed to its rail (PAP-10700).+ const forceExpanded = useSidebarNavExpanded();+ // The icon-only rail presentation only applies when pinned collapsed and not+ // peeking; a peek/expanded panel — or an expanded contextual pane — restores+ // the full label + badge.+ const rail = collapsed && !peeking && !forceExpanded;++ const hasBadge = badge != null && badge > 0;+ const hasLive = liveCount != null && liveCount > 0;++ // Accessible text equivalent for the collapsed dot indicator. The visible+ // label is `sr-only` in the rail, so the count must be surfaced here.+ const railStatusText = hasLive+ ? `${liveCount} live`+ : hasBadge+ ? `${badge}${badgeLabel ? ` ${badgeLabel}` : ""}`+ : alert+ ? "attention needed"+ : undefined;+ const railAriaLabel = !rail || (!railStatusText && !trailingLabel)+ ? undefined+ : `${label}${railStatusText ? `, ${railStatusText}` : ""}${trailingLabel ? `, ${trailingLabel}` : ""}`;++ const link = (+ <NavLink+ to={to}+ state={SIDEBAR_SCROLL_RESET_STATE}+ end={end}+ aria-label={railAriaLabel}+ onClick={() => { if (isMobile) setSidebarOpen(false); }}+ className={({ isActive }) =>+ cn(+ // One rhythm and one inset pill highlight: mx-2 floats the row off+ // the sidebar edges, rounded-lg matches the card anchor, px-2 gives+ // the icon breathing room inside the pill. Rows with hover menus+ // (agents/projects) reserve extra right padding via className.+ "flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",+ (active ?? isActive)+ ? "bg-accent text-foreground"+ : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",+ className,+ )+ }+ >+ <span className="relative shrink-0">+ {iconNode ?? (Icon ? <Icon className="h-4 w-4" /> : null)}+ {alert && (+ <span className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)" aria-hidden="true" />+ )}+ {/* Collapsed rail: numeric badge / live count collapse to a dot on the+ icon. The icon markup is untouched so it stays pixel-aligned. */}+ {rail && !alert && hasLive && (+ <span className="absolute -right-0.5 -top-0.5 flex h-2 w-2" aria-hidden="true">+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />+ <span className="relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)" />+ </span>+ )}+ {rail && !alert && !hasLive && hasBadge && (+ <span+ className={cn(+ "absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",+ badgeTone === "danger"+ ? "bg-red-600"+ : badgeTone === "warning"+ ? "bg-amber-500"+ : "bg-primary",+ )}+ aria-hidden="true"+ />+ )}+ </span>+ <span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</span>+ {!rail && trailing}+ {!rail && textBadge && (+ <Badge variant="ghost"+ className={cn(+ "ml-auto px-1.5 text-(length:--text-nano) leading-none",+ textBadgeTone === "amber"+ ? "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"+ : "bg-muted text-muted-foreground",+ )}+ >+ {textBadge}+ </Badge>+ )}+ {!rail && (hasLive || liveAccessory) && (+ <span className="ml-auto flex items-center gap-1.5">+ {liveAccessory}+ {hasLive && (+ <>+ <span className="relative flex h-2 w-2">+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400" />+ </span>+ <span className="text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400">{liveCount} live</span>+ </>+ )}+ </span>+ )}+ {!rail && hasBadge && (+ <Badge variant="ghost"+ className={cn(+ "ml-auto px-1.5 leading-none",+ badgeTone === "danger"+ ? "bg-red-600/90 text-red-50"+ : badgeTone === "warning"+ ? "bg-amber-500/90 text-amber-50"+ : "bg-primary text-primary-foreground",+ )}+ >+ {badge}+ </Badge>+ )}+ </NavLink>+ );++ if (!rail) return link;++ // The tooltip wraps a plain block element rather than the NavLink directly:+ // Radix `asChild` (Slot) drops React Router's *function* className, which would+ // strip `flex` off the <a> and render it as a block — the in-flow label would+ // then stack under the icon and the row would grow. Anchoring the tooltip to a+ // wrapper keeps the <a> rendering normally (flex), so the row stays 1:1 with+ // the expanded state and the icon never moves (PAP-10676).+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div>{link}</div>+ </TooltipTrigger>+ <TooltipContent side="right">{label}</TooltipContent>+ </Tooltip>+ );+}diff --git a/ui/src/components/SidebarNavItem.test.tsx b/ui/src/components/SidebarNavItem.test.tsxindex cd99a274cc..a45849f08a 100644--- a/ui/src/components/SidebarNavItem.test.tsx+++ b/ui/src/components/SidebarNavItem.test.tsx@@ -82,6 +82,36 @@ describe("SidebarNavItem", () => {expect(link().getAttribute("aria-label")).toBeNull();});+ it("outlines icon alert badges with the streamlined sidebar surface", () => {+ render(<SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} alert />);++ const alertBadge = container.querySelector('[data-slot="sidebar-icon-alert-badge"]');+ expect(alertBadge).not.toBeNull();+ expect(classTokens(alertBadge)).toContain("shadow-(--shadow-sidebar-icon-badge)");+ expect(classTokens(alertBadge)).not.toContain("shadow-(--shadow-extract-12)");+ });++ it("omits the icon slot when an item has no icon", () => {+ render(<SidebarNavItem to="/issues/one" label="Recent task" />);++ expect(link().querySelector('[data-slot="sidebar-nav-icon"]')).toBeNull();+ expect(link().firstElementChild?.textContent).toBe("Recent task");+ });++ it("uses the Paper nav surface for the active item", () => {+ render(<SidebarNavItem to="/issues" label="Tasks" icon={Inbox} active />);++ expect(classTokens(link())).toContain("bg-background");+ expect(classTokens(link())).not.toContain("bg-accent");+ });++ it("uses the active nav surface for hover", () => {+ render(<SidebarNavItem to="/issues" label="Tasks" icon={Inbox} />);++ expect(classTokens(link())).toContain("hover:bg-background");+ expect(classTokens(link())).not.toContain("hover:bg-accent/50");+ });+it("clips the label (kept in flow for 1:1 row height) and collapses the badge to a dot in the rail", () => {sidebarState.collapsed = true;render(<SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} badge={28} badgeLabel="unread" />);@@ -135,9 +165,9 @@ describe("SidebarNavItem", () => {});it("forces the full label inside an expanded contextual pane even when globally collapsed", () => {- // The takeover model collapses the global sidebar (collapsed=true) while the- // 240px SecondarySidebar still needs readable labels (PAP-10700). The- // provider must override the global rail collapse.+ // The takeover preserves the user's saved global collapse preference while+ // replacing its contents. The provider keeps the contextual navigation+ // readable without changing that preference.sidebarState.collapsed = true;render(<SidebarNavExpandedProvider>diff --git a/ui/src/components/SidebarNavItem.tsx b/ui/src/components/SidebarNavItem.tsxindex c7034179c8..52b1db3a31 100644--- a/ui/src/components/SidebarNavItem.tsx+++ b/ui/src/components/SidebarNavItem.tsx@@ -11,12 +11,10 @@ import { Badge } from "@/components/ui/badge";* Forces the full-label (non-rail) presentation for any `SidebarNavItem`* rendered beneath it, regardless of the global `useSidebar().collapsed` state.*- * Takeover routes (PAP-10695) collapse the app `<Sidebar/>` to its 64px rail- * and render the contextual nav in a fixed 240px `SecondarySidebar`. That pane- * is always wide enough for labels, but its `SidebarNavItem` children still- * read the *global* `collapsed=true` and would otherwise render icon-only —- * leaving the settings nav unreadable (PAP-10700). Wrapping the pane in this- * provider decouples its items from the global rail collapse.+ * Contextual takeover routes replace the global navigation inside the same+ * sidebar shell. The user's saved global collapse preference can still be+ * `collapsed=true`, so this provider keeps contextual navigation readable+ * without mutating that preference.*/const SidebarNavExpandedContext = createContext(false);@@ -90,16 +88,17 @@ export function SidebarNavItem({liveAccessory,}: SidebarNavItemProps) {const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();- // A fixed-width contextual pane (SecondarySidebar) forces full labels even- // when the global app sidebar is collapsed to its rail (PAP-10700).+ // A contextual takeover forces full labels even when the saved global app+ // sidebar preference is collapsed.const forceExpanded = useSidebarNavExpanded();// The icon-only rail presentation only applies when pinned collapsed and not- // peeking; a peek/expanded panel — or an expanded contextual pane — restores+ // peeking; a peek/expanded panel — or a contextual takeover — restores// the full label + badge.const rail = collapsed && !peeking && !forceExpanded;const hasBadge = badge != null && badge > 0;const hasLive = liveCount != null && liveCount > 0;+ const showIconSlot = Boolean(iconNode || Icon || alert || (rail && (hasLive || hasBadge)));// Accessible text equivalent for the collapsed dot indicator. The visible// label is `sr-only` in the rail, so the count must be surfaced here.@@ -129,39 +128,45 @@ export function SidebarNavItem({// (agents/projects) reserve extra right padding via className."flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",(active ?? isActive)- ? "bg-accent text-foreground"- : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",+ ? "bg-background text-foreground"+ : "text-foreground/80 hover:bg-background hover:text-foreground",className,)}>- <span className="relative shrink-0">- {iconNode ?? (Icon ? <Icon className="h-4 w-4" /> : null)}- {alert && (- <span className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)" aria-hidden="true" />- )}- {/* Collapsed rail: numeric badge / live count collapse to a dot on the- icon. The icon markup is untouched so it stays pixel-aligned. */}- {rail && !alert && hasLive && (- <span className="absolute -right-0.5 -top-0.5 flex h-2 w-2" aria-hidden="true">- <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />- <span className="relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)" />- </span>- )}- {rail && !alert && !hasLive && hasBadge && (- <span- className={cn(- "absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",- badgeTone === "danger"- ? "bg-red-600"- : badgeTone === "warning"- ? "bg-amber-500"- : "bg-primary",- )}- aria-hidden="true"- />- )}- </span>+ {showIconSlot ? (+ <span data-slot="sidebar-nav-icon" className="relative shrink-0">+ {iconNode ?? (Icon ? <Icon className="h-4 w-4" /> : null)}+ {alert && (+ <span+ data-slot="sidebar-icon-alert-badge"+ className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-sidebar-icon-badge)"+ aria-hidden="true"+ />+ )}+ {/* Collapsed rail: numeric badge / live count collapse to a dot on the+ icon. The icon markup is untouched so it stays pixel-aligned. */}+ {rail && !alert && hasLive && (+ <span className="absolute -right-0.5 -top-0.5 flex h-2 w-2" aria-hidden="true">+ <span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75" />+ <span className="relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-sidebar-icon-badge)" />+ </span>+ )}+ {rail && !alert && !hasLive && hasBadge && (+ <span+ className={cn(+ "absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-sidebar-icon-badge)",+ badgeTone === "danger"+ ? "bg-red-600"+ : badgeTone === "warning"+ ? "bg-amber-500"+ : "bg-primary",+ )}+ aria-hidden="true"+ />+ )}+ </span>+ ) : null}<span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : cn("min-w-0 flex-1 truncate", labelClassName)}>{label}</span>{!rail && trailing}{!rail && textBadge && (diff --git a/ui/src/components/SidebarProjects.tsx b/ui/src/components/SidebarProjects.tsxindex 2a7abdeb2d..697f1dcfe4 100644--- a/ui/src/components/SidebarProjects.tsx+++ b/ui/src/components/SidebarProjects.tsx@@ -140,8 +140,8 @@ function ProjectItem({className={cn("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pr-8 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",activeProjectRef === routeRef || activeProjectRef === project.id- ? "bg-accent text-foreground"- : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",+ ? "bg-background text-foreground"+ : "text-foreground/80 hover:bg-background hover:text-foreground",)}><ProjectTile color={project.color ?? null} icon={project.icon ?? null} size="xs" />diff --git a/ui/src/components/SidebarRecentTasks.test.tsx b/ui/src/components/SidebarRecentTasks.test.tsxnew file mode 100644index 0000000000..8c572ba865--- /dev/null+++ b/ui/src/components/SidebarRecentTasks.test.tsx@@ -0,0 +1,188 @@+// @vitest-environment jsdom++import { act, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import { SidebarRecentTasks } from "./SidebarRecentTasks";+import {+ getRecentTasksStorageKey,+ readRecentTasks,+ recordRecentTask,+} from "@/lib/recent-tasks";++const mockAuthApi = vi.hoisted(() => ({ getSession: vi.fn() }));+const mockIssuesApi = vi.hoisted(() => ({ get: vi.fn() }));++vi.mock("@/api/auth", () => ({ authApi: mockAuthApi }));+vi.mock("@/api/issues", () => ({ issuesApi: mockIssuesApi }));+vi.mock("@/lib/router", () => ({+ NavLink: ({ children, to, className, ...props }: {+ children: ReactNode;+ to: string;+ className?: string | ((state: { isActive: boolean }) => string);+ }) => (+ <a+ href={to}+ className={typeof className === "function" ? className({ isActive: false }) : className}+ {...props}+ >+ {children}+ </a>+ ),+}));+vi.mock("@/context/SidebarContext", () => ({+ useSidebar: () => ({+ collapsed: false,+ peeking: false,+ isMobile: false,+ setSidebarOpen: vi.fn(),+ }),+}));++// eslint-disable-next-line @typescript-eslint/no-explicit-any+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;++describe("SidebarRecentTasks", () => {+ let container: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ window.localStorage.clear();+ mockIssuesApi.get.mockReset();+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ mockAuthApi.getSession.mockResolvedValue({+ session: { id: "session-1", userId: "user-1" },+ user: { id: "user-1", name: "Board", email: "[email protected]", image: null },+ });+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.clearAllMocks();+ });++ async function render() {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <TooltipProvider>+ <SidebarRecentTasks companyId="company-1" liveIssueIds={new Set(["issue-1"])} />+ </TooltipProvider>+ </QueryClientProvider>,+ );+ });+ await act(async () => {+ for (let index = 0; index < 5; index += 1) {+ await Promise.resolve();+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ }+ });+ return queryClient;+ }++ it("renders a compact empty state", async () => {+ await render();+ expect(container.textContent).toContain("Recent Tasks");+ expect(container.textContent).toContain("Open or create a task");+ });++ it("renders refreshed task text and live state without shifting for a status icon", async () => {+ recordRecentTask({+ id: "issue-1",+ companyId: "company-1",+ title: "Initial title",+ identifier: "PAP-1",+ status: "todo",+ updatedAt: new Date(1),+ }, "user-1");+ mockIssuesApi.get.mockResolvedValue({+ id: "issue-1",+ companyId: "company-1",+ title: "Refreshed title",+ identifier: "PAP-1",+ status: "in_progress",+ hiddenAt: null,+ updatedAt: new Date(2),+ });++ const queryClient = await render();+ await act(async () => {+ for (let index = 0; index < 5; index += 1) {+ await Promise.resolve();+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ }+ });++ const link = container.querySelector('a[href="/issues/issue-1"]');+ expect(mockIssuesApi.get).toHaveBeenCalledWith("issue-1");+ expect(queryClient.getQueryData(["issues", "detail", "issue-1"])).toMatchObject({+ title: "Refreshed title",+ });+ expect(link?.textContent).toContain("Refreshed title");+ expect(link?.textContent).toContain("1 live");+ expect(link?.querySelector('[aria-label="In Progress"]')).toBeNull();+ expect(link?.querySelector('[data-slot="recent-task-icon-spacer"]')).toBeNull();+ expect(link?.querySelector('[data-slot="sidebar-nav-icon"]')).toBeNull();+ expect(link?.firstElementChild?.textContent).toBe("Refreshed title");+ });++ it("synchronizes recent tasks written by another tab", async () => {+ mockIssuesApi.get.mockImplementation(() => new Promise(() => {}));+ await render();+ const storageKey = getRecentTasksStorageKey("company-1", "user-1");+ const entries = [{+ id: "issue-2",+ companyId: "company-1",+ title: "Cross-tab task",+ identifier: "PAP-2",+ status: "todo" as const,+ recordedAt: 2,+ }];++ await act(async () => {+ window.localStorage.setItem(storageKey, JSON.stringify(entries));+ window.dispatchEvent(new StorageEvent("storage", { key: storageKey }));+ await Promise.resolve();+ });++ expect(container.querySelector('a[href="/issues/issue-2"]')?.textContent).toContain("Cross-tab task");+ });++ it("prunes tasks that become hidden", async () => {+ recordRecentTask({+ id: "issue-hidden",+ companyId: "company-1",+ title: "Hidden task",+ identifier: "PAP-3",+ status: "todo",+ updatedAt: new Date(3),+ }, "user-1");+ mockIssuesApi.get.mockResolvedValue({+ id: "issue-hidden",+ companyId: "company-1",+ title: "Hidden task",+ identifier: "PAP-3",+ status: "todo",+ hiddenAt: new Date(),+ updatedAt: new Date(4),+ });++ await render();+ await act(async () => {+ await Promise.resolve();+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ });++ expect(container.querySelector('a[href="/issues/issue-hidden"]')).toBeNull();+ expect(readRecentTasks(+ getRecentTasksStorageKey("company-1", "user-1"),+ "company-1",+ )).toEqual([]);+ });+});diff --git a/ui/src/components/SidebarRecentTasks.tsx b/ui/src/components/SidebarRecentTasks.tsxnew file mode 100644index 0000000000..449251bbc4--- /dev/null+++ b/ui/src/components/SidebarRecentTasks.tsx@@ -0,0 +1,69 @@+import { useQuery } from "@tanstack/react-query";+import { authApi } from "@/api/auth";+import { queryKeys } from "@/lib/queryKeys";+import { useRecentTasks } from "@/hooks/useRecentTasks";+import { useSidebar } from "@/context/SidebarContext";+import { SidebarSection } from "./SidebarSection";+import { SidebarNavItem } from "./SidebarNavItem";++export function SidebarRecentTasks({+ companyId,+ liveIssueIds,+}: {+ companyId: string | null | undefined;+ liveIssueIds: ReadonlySet<string>;+}) {+ const { collapsed, peeking } = useSidebar();+ const rail = collapsed && !peeking;+ const { data: session, isPending } = useQuery({+ queryKey: queryKeys.auth.session,+ queryFn: () => authApi.getSession(),+ retry: false,+ });++ if (!companyId || isPending) return null;++ const userId = session?.user?.id ?? session?.session?.userId ?? null;+ return (+ <RecentTasksList+ key={`${companyId}:${userId ?? "__local_board__"}`}+ companyId={companyId}+ userId={userId}+ liveIssueIds={liveIssueIds}+ rail={rail}+ />+ );+}++function RecentTasksList({+ companyId,+ userId,+ liveIssueIds,+ rail,+}: {+ companyId: string;+ userId: string | null;+ liveIssueIds: ReadonlySet<string>;+ rail: boolean;+}) {+ const { entries } = useRecentTasks({ companyId, userId });++ if (rail && entries.length === 0) return null;++ return (+ <SidebarSection label="Recent Tasks">+ {entries.length === 0 ? (+ <p className="mx-3 px-2 py-1 text-(length:--text-micro) leading-snug text-muted-foreground/70">+ Open or create a task to keep it close at hand.+ </p>+ ) : entries.map((entry) => (+ <SidebarNavItem+ key={entry.id}+ to={`/issues/${entry.id}`}+ label={entry.title}+ liveCount={liveIssueIds.has(entry.id) ? 1 : undefined}+ />+ ))}+ </SidebarSection>+ );+}diff --git a/ui/src/components/SidebarShell.production.tsx b/ui/src/components/SidebarShell.production.tsxnew file mode 100644index 0000000000..5d70676160--- /dev/null+++ b/ui/src/components/SidebarShell.production.tsx@@ -0,0 +1,244 @@+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type FocusEventHandler,+ type KeyboardEvent,+ type MouseEventHandler,+ type PointerEvent,+ type ReactNode,+} from "react";+import { cn } from "@/lib/utils";++const DEFAULT_SIDEBAR_WIDTH = 240;+const MIN_SIDEBAR_WIDTH = 208;+const MAX_SIDEBAR_WIDTH = 420;+const SIDEBAR_WIDTH_STEP = 16;++// Collapsed icon rail. Width is chosen so the icon is *centered* in the rail,+// which keeps the active/hover highlight symmetric around it (PAP-10676):+// the icon's left edge sits at nav px-3 (12) + item px-3 (12) = 24px, so a+// matching 24px trailing margin (12 item px-3 + 12 nav px-3) yields+// 24 + 16 (icon) + 24 = 64. The icon's left edge is unchanged from the expanded+// layout, so icons stay pixel-identical across states.+export const SIDEBAR_RAIL_WIDTH = 64;++function clampSidebarWidth(width: number) {+ return Math.min(MAX_SIDEBAR_WIDTH, Math.max(MIN_SIDEBAR_WIDTH, width));+}++function readStoredSidebarWidth(storageKey: string) {+ if (typeof window === "undefined") return DEFAULT_SIDEBAR_WIDTH;++ try {+ const stored = window.localStorage.getItem(storageKey);+ if (!stored) return DEFAULT_SIDEBAR_WIDTH;+ const parsed = Number.parseInt(stored, 10);+ if (!Number.isFinite(parsed)) return DEFAULT_SIDEBAR_WIDTH;+ return clampSidebarWidth(parsed);+ } catch {+ return DEFAULT_SIDEBAR_WIDTH;+ }+}++function writeStoredSidebarWidth(storageKey: string, width: number) {+ if (typeof window === "undefined") return;++ try {+ window.localStorage.setItem(storageKey, String(clampSidebarWidth(width)));+ } catch {+ // Storage can be unavailable in private contexts; resizing should still work.+ }+}++type SidebarShellProps = {+ children: ReactNode;+ /** Whether the sidebar occupies space at all (mobile back-compat / hidden). */+ open: boolean;+ /** Pinned collapsed (rail) mode. Desktop-only; the caller gates this. */+ collapsed?: boolean;+ /** Ephemeral hover/focus peek. Only meaningful while collapsed. */+ peeking?: boolean;+ resizable?: boolean;+ storageKey?: string;+ className?: string;+ /** Forwarded to the overlay panel so Layout can wire peek triggers. */+ onPanelMouseEnter?: MouseEventHandler<HTMLDivElement>;+ onPanelMouseLeave?: MouseEventHandler<HTMLDivElement>;+ onPanelFocusCapture?: FocusEventHandler<HTMLDivElement>;+ onPanelBlurCapture?: FocusEventHandler<HTMLDivElement>;+};++/**+ * Layout shell for the desktop sidebar. Owns the persisted expanded width and+ * renders two layers:+ * - an in-flow spacer that reserves `reservedWidth` (rail when collapsed,+ * expanded width otherwise) so content to the right only reflows on pin, and+ * - an absolutely-positioned panel of `panelWidth` (rail at rest, expanded+ * while peeking) that overlays content — with shadow/raised z-index — when it+ * is wider than the reserved spacer.+ *+ * The icon-alignment guarantee comes for free: collapsing is a pure width+ * change with `overflow-hidden` clipping the labels; item padding/icon markup+ * are never touched, so the left-aligned icon stays pixel-identical.+ *+ * Opening/closing is intentionally instant (no width transition): the pin toggle+ * and peek snap between rail and expanded widths so the content never appears to+ * slide. Resizing the drag handle is likewise direct.+ */+export function SidebarShell({+ children,+ open,+ collapsed = false,+ peeking = false,+ resizable = false,+ storageKey = "paperclip.sidebar.width",+ className,+ onPanelMouseEnter,+ onPanelMouseLeave,+ onPanelFocusCapture,+ onPanelBlurCapture,+}: SidebarShellProps) {+ const [width, setWidth] = useState(() => readStoredSidebarWidth(storageKey));+ const [isResizing, setIsResizing] = useState(false);+ const widthRef = useRef(width);+ const dragState = useRef<{ startX: number; startWidth: number } | null>(null);++ useEffect(() => {+ const storedWidth = readStoredSidebarWidth(storageKey);+ widthRef.current = storedWidth;+ setWidth(storedWidth);+ }, [storageKey]);++ // Unified width function (plan §5): one code path for every pinned state.+ const expandedWidth = open ? width : 0;+ const reservedWidth = !open ? 0 : collapsed ? SIDEBAR_RAIL_WIDTH : expandedWidth;+ const panelWidth = !open ? 0 : collapsed && !peeking ? SIDEBAR_RAIL_WIDTH : expandedWidth;+ const isOverlay = panelWidth > reservedWidth;++ // The drag handle can only resize the expanded width, so it is disabled while+ // collapsed (the rail width is a fixed constant, not user-resizable).+ const canResize = resizable && open && !collapsed;++ const reservedStyle = useMemo(+ () => ({ width: `${reservedWidth}px` }),+ [reservedWidth],+ );+ const panelStyle = useMemo(+ () => ({ width: `${panelWidth}px` }),+ [panelWidth],+ );++ const commitWidth = useCallback(+ (nextWidth: number) => {+ const clamped = clampSidebarWidth(nextWidth);+ widthRef.current = clamped;+ setWidth(clamped);+ writeStoredSidebarWidth(storageKey, clamped);+ },+ [storageKey],+ );++ const handlePointerDown = useCallback(+ (event: PointerEvent<HTMLDivElement>) => {+ if (!canResize) return;++ event.preventDefault();+ event.currentTarget.setPointerCapture(event.pointerId);+ dragState.current = { startX: event.clientX, startWidth: widthRef.current };+ setIsResizing(true);+ },+ [canResize],+ );++ const handlePointerMove = useCallback(+ (event: PointerEvent<HTMLDivElement>) => {+ if (!dragState.current) return;++ const nextWidth = dragState.current.startWidth + event.clientX - dragState.current.startX;+ const clamped = clampSidebarWidth(nextWidth);+ widthRef.current = clamped;+ setWidth(clamped);+ },+ [],+ );++ const endResize = useCallback(() => {+ if (!dragState.current) return;++ dragState.current = null;+ setIsResizing(false);+ writeStoredSidebarWidth(storageKey, widthRef.current);+ }, [storageKey]);++ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ if (!canResize) return;++ if (event.key === "ArrowLeft") {+ event.preventDefault();+ commitWidth(width - SIDEBAR_WIDTH_STEP);+ } else if (event.key === "ArrowRight") {+ event.preventDefault();+ commitWidth(width + SIDEBAR_WIDTH_STEP);+ } else if (event.key === "Home") {+ event.preventDefault();+ commitWidth(MIN_SIDEBAR_WIDTH);+ } else if (event.key === "End") {+ event.preventDefault();+ commitWidth(MAX_SIDEBAR_WIDTH);+ }+ },+ [canResize, commitWidth, width],+ );++ return (+ <div className={cn("relative h-full shrink-0", className)} style={reservedStyle}>+ <div+ className={cn(+ "absolute inset-y-0 left-0 flex flex-col overflow-hidden",+ // Open/close is instant (PAP-10676): no width transition so the rail and+ // expanded states snap without any sliding motion.+ // Overlay styling only while the panel is wider than its reserved+ // spacer (i.e. peeking) so it floats above content without reflow.+ isOverlay+ ? "z-30 border-r border-border bg-background shadow-lg"+ : "z-0",+ )}+ style={panelStyle}+ data-sidebar-overlay={isOverlay ? "" : undefined}+ onMouseEnter={onPanelMouseEnter}+ onMouseLeave={onPanelMouseLeave}+ onFocusCapture={onPanelFocusCapture}+ onBlurCapture={onPanelBlurCapture}+ >+ {children}+ {canResize ? (+ <div+ role="separator"+ aria-label="Resize sidebar"+ aria-orientation="vertical"+ aria-valuemin={MIN_SIDEBAR_WIDTH}+ aria-valuemax={MAX_SIDEBAR_WIDTH}+ aria-valuenow={width}+ tabIndex={0}+ className={cn(+ "absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none",+ "before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors",+ "hover:before:bg-border focus-visible:before:bg-ring",+ isResizing && "before:bg-ring",+ )}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={endResize}+ onPointerCancel={endResize}+ onLostPointerCapture={endResize}+ onKeyDown={handleKeyDown}+ />+ ) : null}+ </div>+ </div>+ );+}diff --git a/ui/src/components/SidebarShell.test.tsx b/ui/src/components/SidebarShell.test.tsxindex f15a1ab596..b4571b8195 100644--- a/ui/src/components/SidebarShell.test.tsx+++ b/ui/src/components/SidebarShell.test.tsx@@ -88,6 +88,27 @@ describe("SidebarShell", () => {expect(window.localStorage.getItem("test.sidebar.width")).toBe("320");});+ it("matches the properties panel resize-grip hover treatment", () => {+ act(() => {+ root.render(+ <SidebarShell open resizable storageKey="test.sidebar.width">+ <div>Sidebar</div>+ </SidebarShell>,+ );+ });++ const separator = handle();+ const indicator = separator?.firstElementChild as HTMLDivElement | null;++ expect(separator?.parentElement).toBe(spacer());+ expect(separator?.className).toContain("group");+ expect(separator?.style.right).toBe("-4px");+ expect(separator?.style.width).toBe("8px");+ expect(indicator?.className).toContain("w-0.5");+ expect(indicator?.className).toContain("group-hover:bg-ring");+ expect(indicator?.className).toContain("group-focus-visible:bg-ring");+ });+it("supports keyboard resizing and clamps to the configured bounds", () => {act(() => {root.render(diff --git a/ui/src/components/SidebarShell.tsx b/ui/src/components/SidebarShell.tsxindex 5d70676160..9834434c0b 100644--- a/ui/src/components/SidebarShell.tsx+++ b/ui/src/components/SidebarShell.tsx@@ -215,30 +215,36 @@ export function SidebarShell({onBlurCapture={onPanelBlurCapture}>{children}- {canResize ? (+ </div>+ {canResize ? (+ <div+ role="separator"+ aria-label="Resize sidebar"+ aria-orientation="vertical"+ aria-valuemin={MIN_SIDEBAR_WIDTH}+ aria-valuemax={MAX_SIDEBAR_WIDTH}+ aria-valuenow={width}+ tabIndex={0}+ data-dragging={isResizing ? "" : undefined}+ className="group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none"+ style={{ right: -4, width: 8 }}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={endResize}+ onPointerCancel={endResize}+ onLostPointerCapture={endResize}+ onKeyDown={handleKeyDown}+ ><div- role="separator"- aria-label="Resize sidebar"- aria-orientation="vertical"- aria-valuemin={MIN_SIDEBAR_WIDTH}- aria-valuemax={MAX_SIDEBAR_WIDTH}- aria-valuenow={width}- tabIndex={0}className={cn(- "absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none",- "before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors",- "hover:before:bg-border focus-visible:before:bg-ring",- isResizing && "before:bg-ring",+ "mx-auto h-full w-0.5 transition-colors",+ isResizing+ ? "bg-ring"+ : "bg-transparent group-hover:bg-ring group-focus-visible:bg-ring",)}- onPointerDown={handlePointerDown}- onPointerMove={handlePointerMove}- onPointerUp={endResize}- onPointerCancel={endResize}- onLostPointerCapture={endResize}- onKeyDown={handleKeyDown}/>- ) : null}- </div>+ </div>+ ) : null}</div>);}diff --git a/ui/src/components/SidebarStarredProjects.production.tsx b/ui/src/components/SidebarStarredProjects.production.tsxnew file mode 100644index 0000000000..264be97716--- /dev/null+++ b/ui/src/components/SidebarStarredProjects.production.tsx@@ -0,0 +1,218 @@+import { useCallback, useMemo } from "react";+import { NavLink, useLocation } from "@/lib/router";+import { useQuery } from "@tanstack/react-query";+import { Loader2, LogOut, MoreHorizontal, Star } from "lucide-react";+import { useCompany } from "../context/CompanyContext";+import { useSidebar } from "../context/SidebarContext";+import { projectsApi } from "../api/projects";+import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";+import { queryKeys } from "../lib/queryKeys";+import { cn, projectRouteRef, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";+import {+ isStarred,+ starredResourceIds,+ useResourceMembershipMutation,+ useResourceMemberships,+} from "../hooks/useResourceMemberships";+import { BudgetSidebarMarker } from "./BudgetSidebarMarker";+import { ProjectTile } from "./ProjectTile";+import { StarToggle } from "./StarToggle";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import type { Project } from "@paperclipai/shared";++// Sidebar star reveals with the row's own group, not the shared unnamed group.+const STAR_ROW_REVEAL =+ "opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";++/**+ * Compact starred-project children rendered directly below the top-level+ * `Projects` nav row in the streamlined sidebar. Starring/unstarring itself+ * happens from browse/detail surfaces; here we only ever *remove* a star+ * (plus the existing leave affordance). Archived projects are filtered out+ * server-side, so a stale star never resurrects a hidden project.+ */+export function SidebarStarredProjects() {+ const { selectedCompanyId } = useCompany();+ const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();+ const rail = collapsed && !peeking;+ const location = useLocation();++ const { data: projects } = useQuery({+ queryKey: queryKeys.projects.list(selectedCompanyId!),+ queryFn: () => projectsApi.list(selectedCompanyId!),+ enabled: !!selectedCompanyId,+ });+ const membershipsQuery = useResourceMemberships(selectedCompanyId);+ const membershipMutation = useResourceMembershipMutation(selectedCompanyId);++ const projectMatch = location.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/);+ const activeProjectRef = projectMatch?.[1] ?? null;++ const starredProjects = useMemo(() => {+ if (!membershipsQuery.isSuccess) return [];+ const starredIds = new Set(starredResourceIds(membershipsQuery.data, "project"));+ if (starredIds.size === 0) return [];+ const byId = new Map((projects ?? []).map((project: Project) => [project.id, project]));+ return Array.from(starredIds)+ .map((id) => byId.get(id))+ .filter((project): project is Project => !!project)+ .sort((left, right) =>+ left.name.localeCompare(right.name, undefined, { sensitivity: "base" }),+ );+ }, [membershipsQuery.data, membershipsQuery.isSuccess, projects]);++ const unstar = useCallback(+ (project: Project) => membershipMutation.mutate({+ resourceType: "project",+ resourceId: project.id,+ resourceName: project.name,+ starred: false,+ }),+ [membershipMutation],+ );+ const leave = useCallback(+ (project: Project) => membershipMutation.mutate({+ resourceType: "project",+ resourceId: project.id,+ resourceName: project.name,+ state: "left",+ }),+ [membershipMutation],+ );+ const pendingFor = useCallback(+ (project: Project) =>+ membershipMutation.isPending &&+ membershipMutation.variables?.resourceType === "project" &&+ membershipMutation.variables.resourceId === project.id,+ [membershipMutation.isPending, membershipMutation.variables],+ );++ // Don't render anything until memberships load — no skeleton flash in the nav.+ if (!membershipsQuery.isSuccess) return null;++ // Empty starred groups should not add a placeholder row or extra sidebar spacing.+ if (starredProjects.length === 0) {+ return null;+ }++ return (+ <div className="flex flex-col gap-0.5" aria-label="Starred projects">+ {starredProjects.map((project) => {+ const routeRef = projectRouteRef(project);+ const isActive = activeProjectRef === routeRef || activeProjectRef === project.id;+ const pending = pendingFor(project);+ const unstarPending = pending && membershipMutation.variables?.starred === false;+ const leavePending = pending && membershipMutation.variables?.state === "left";+ const starred = isStarred(membershipsQuery.data, "project", project.id);++ const link = (+ <NavLink+ to={`/projects/${routeRef}/issues`}+ state={SIDEBAR_SCROLL_RESET_STATE}+ onClick={() => {+ if (isMobile) setSidebarOpen(false);+ }}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",+ !rail && "pl-6",+ isActive+ ? "bg-accent text-foreground"+ : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",+ )}+ >+ <ProjectTile color={project.color ?? null} icon={project.icon ?? null} size="xs" />+ <span className={rail ? SIDEBAR_RAIL_HIDDEN_LABEL : "flex-1 truncate"}>{project.name}</span>+ {!rail && project.pauseReason === "budget" ? (+ <BudgetSidebarMarker title="Project paused by budget" />+ ) : null}+ </NavLink>+ );++ return (+ <div key={project.id} className="group/starred-project relative flex items-center">+ {rail ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="min-w-0 flex-1">{link}</div>+ </TooltipTrigger>+ <TooltipContent side="right">{project.name}</TooltipContent>+ </Tooltip>+ ) : (+ link+ )}++ {!rail && !isMobile ? (+ // Desktop: quiet inline unstar revealed on hover/focus.+ <span className="absolute right-3 top-1/2 -translate-y-1/2">+ <StarToggle+ size="row"+ quiet+ starred={starred}+ pending={unstarPending}+ resourceName={project.name}+ onToggle={() => unstar(project)}+ revealClassName={STAR_ROW_REVEAL}+ />+ </span>+ ) : null}++ {!rail && isMobile ? (+ // Touch: explicit ⋯ menu (no hover). Star action + separated Leave.+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ className="absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100"+ aria-label={`Open actions for ${project.name}`}+ >+ <MoreHorizontal className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuItem+ onClick={() => {+ if (pending) return;+ unstar(project);+ }}+ disabled={pending}+ >+ {unstarPending ? (+ <Loader2 className="size-4 motion-safe:animate-spin" />+ ) : (+ <Star className="size-4 fill-amber-500 text-amber-500" />+ )}+ <span>Remove from starred</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ if (pending) return;+ leave(project);+ }}+ disabled={pending}+ >+ {leavePending ? (+ <Loader2 className="size-4 motion-safe:animate-spin" />+ ) : (+ <LogOut className="size-4" />+ )}+ <span>Leave project</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : null}+ </div>+ );+ })}+ </div>+ );+}diff --git a/ui/src/components/SidebarStarredProjects.tsx b/ui/src/components/SidebarStarredProjects.tsxindex 264be97716..3e00980641 100644--- a/ui/src/components/SidebarStarredProjects.tsx+++ b/ui/src/components/SidebarStarredProjects.tsx@@ -124,8 +124,8 @@ export function SidebarStarredProjects() {"flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!rail && "pl-6",isActive- ? "bg-accent text-foreground"- : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",+ ? "bg-background text-foreground"+ : "text-foreground/80 hover:bg-background hover:text-foreground",)}><ProjectTile color={project.color ?? null} icon={project.icon ?? null} size="xs" />diff --git a/ui/src/components/SkillsContextualSidebar.test.tsx b/ui/src/components/SkillsContextualSidebar.test.tsxnew file mode 100644index 0000000000..f5df38493e--- /dev/null+++ b/ui/src/components/SkillsContextualSidebar.test.tsx@@ -0,0 +1,115 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SkillsContextualSidebar } from "./SkillsContextualSidebar";+import { contextualSidebarStyles } from "./contextual-sidebar-styles";++const sidebarNavItemMock = vi.hoisted(() => vi.fn());+const mockLocation = vi.hoisted(() => ({ pathname: "/PAP/skills", search: "" }));++vi.mock("@/lib/router", () => ({+ useLocation: () => mockLocation,+ useNavigate: () => vi.fn(),+}));+vi.mock("@/context/CompanyContext", () => ({+ useCompany: () => ({ selectedCompany: { name: "Paperclip", issuePrefix: "PAP" } }),+}));+vi.mock("@/context/SidebarContext", () => ({+ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }),+}));+vi.mock("./SidebarNavItem", () => ({+ SidebarNavExpandedProvider: ({ children }: { children: React.ReactNode }) => children,+ SidebarNavItem: (props: { to: string; label: string; active?: boolean }) => {+ sidebarNavItemMock(props);+ return <a href={props.to} aria-current={props.active ? "page" : undefined}>{props.label}</a>;+ },+}));++// eslint-disable-next-line @typescript-eslint/no-explicit-any+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;++describe("SkillsContextualSidebar", () => {+ let container: HTMLDivElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ mockLocation.pathname = "/PAP/skills";+ mockLocation.search = "";+ });++ afterEach(() => {+ container.remove();+ vi.clearAllMocks();+ });++ function render() {+ const root = createRoot(container);+ act(() => root.render(<SkillsContextualSidebar />));+ return root;+ }++ it("keeps Installed, Discover, and authored My Skills visible together", () => {+ const root = render();++ expect(container.textContent).toContain("Installed");+ expect(container.textContent).toContain("Discover");+ expect(container.textContent).toContain("My Skills");+ expect(container.textContent).toContain("Skills you create, edit, and test.");+ expect(container.textContent).not.toContain("Paperclip");+ expect(container.querySelector('[aria-label="Back from Skills"]')).toBeNull();+ expect(container.querySelector('[aria-current="page"]')?.textContent).toBe("Installed");++ act(() => root.unmount());+ });++ it("uses the shared contextual-navigation spacing and type contract", () => {+ const root = render();++ expect(container.querySelector('[data-slot="contextual-sidebar-nav"]')?.className).toBe(+ contextualSidebarStyles.nav,+ );+ expect(container.querySelector('[data-slot="contextual-sidebar-section"]')?.className).toBe(+ contextualSidebarStyles.section,+ );+ expect(container.querySelector('[data-slot="contextual-sidebar-section-label"]')?.className).toBe(+ contextualSidebarStyles.sectionLabel,+ );+ expect(container.querySelector('[data-slot="contextual-sidebar-section-description"]')?.className).toBe(+ contextualSidebarStyles.sectionDescription,+ );+ expect(+ Array.from(container.querySelectorAll('[data-slot="contextual-sidebar-group"]')).every(+ (group) => group.className === contextualSidebarStyles.group,+ ),+ ).toBe(true);++ act(() => root.unmount());+ });++ it("activates Discover for old catalog links without changing the navigation", () => {+ mockLocation.search = "?tab=bundled";+ const root = render();++ expect(container.querySelector('[aria-current="page"]')?.textContent).toBe("Discover");+ expect(sidebarNavItemMock.mock.calls.map(([props]) => props.to)).toEqual([+ "/skills",+ "/skills?tab=discover",+ "/skills/studio",+ ]);++ act(() => root.unmount());+ });++ it("activates My Skills throughout Studio", () => {+ mockLocation.pathname = "/PAP/skills/studio/skill-1";+ mockLocation.search = "?tab=files";+ const root = render();++ expect(container.querySelector('[aria-current="page"]')?.textContent).toBe("My Skills");++ act(() => root.unmount());+ });+});diff --git a/ui/src/components/SkillsContextualSidebar.tsx b/ui/src/components/SkillsContextualSidebar.tsxnew file mode 100644index 0000000000..6773374eff--- /dev/null+++ b/ui/src/components/SkillsContextualSidebar.tsx@@ -0,0 +1,79 @@+import { Compass, Library, PencilRuler } from "lucide-react";+import { useLocation } from "@/lib/router";+import {+ resolveSkillsNavigationView,+ SKILLS_NAVIGATION_HREFS,+} from "@/pages/skills/skills-navigation";+import { ContextualSidebarFrame } from "./ContextualSidebarFrame";+import { SidebarNavItem } from "./SidebarNavItem";+import { contextualSidebarStyles } from "./contextual-sidebar-styles";++export {+ resolveSkillsDiscoveryView,+ resolveSkillsNavigationView,+ SKILLS_NAVIGATION_HREFS,+ withSkillsDiscoveryView,+ type SkillsNavigationView,+} from "@/pages/skills/skills-navigation";++export function SkillsContextualSidebar() {+ const location = useLocation();+ const activeView = resolveSkillsNavigationView(location.pathname, location.search);++ return (+ <ContextualSidebarFrame+ surface="skills"+ title="Skills"+ icon={Library}+ fallbackTo="/dashboard"+ showHeader={false}+ className="border-r border-border bg-background"+ >+ <nav+ aria-label="Skills"+ data-slot="contextual-sidebar-nav"+ className={contextualSidebarStyles.nav}+ >+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>+ <SidebarNavItem+ to={SKILLS_NAVIGATION_HREFS.installed}+ label="Installed"+ icon={Library}+ active={activeView === "installed"}+ end+ />+ <SidebarNavItem+ to={SKILLS_NAVIGATION_HREFS.discover}+ label="Discover"+ icon={Compass}+ active={activeView === "discover"}+ end+ />+ </div>++ <div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>+ <div+ data-slot="contextual-sidebar-section-label"+ className={contextualSidebarStyles.sectionLabel}+ >+ Author+ </div>+ <p+ data-slot="contextual-sidebar-section-description"+ className={contextualSidebarStyles.sectionDescription}+ >+ Skills you create, edit, and test.+ </p>+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>+ <SidebarNavItem+ to={SKILLS_NAVIGATION_HREFS.authored}+ label="My Skills"+ icon={PencilRuler}+ active={activeView === "authored"}+ />+ </div>+ </div>+ </nav>+ </ContextualSidebarFrame>+ );+}diff --git a/ui/src/components/contextual-sidebar-styles.ts b/ui/src/components/contextual-sidebar-styles.tsnew file mode 100644index 0000000000..3b05540f59--- /dev/null+++ b/ui/src/components/contextual-sidebar-styles.ts@@ -0,0 +1,15 @@+/**+ * Shared visual contract for the Skills and Apps contextual navigation rails.+ *+ * Keep these surfaces on the same token-backed spacing and typography so their+ * navigation hierarchy cannot drift as either area evolves.+ */+export const contextualSidebarStyles = {+ nav: "flex min-h-0 flex-1 flex-col overflow-y-auto scrollbar-auto-hide px-3 py-2",+ group: "flex flex-col gap-0.5",+ section: "mt-4 border-t border-border pt-3",+ sectionLabel:+ "px-2 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",+ sectionDescription:+ "px-4 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70",+} as const;diff --git a/ui/src/context/BreadcrumbContext.tsx b/ui/src/context/BreadcrumbContext.tsxindex c3b8a79b82..73900d5d99 100644--- a/ui/src/context/BreadcrumbContext.tsx+++ b/ui/src/context/BreadcrumbContext.tsx@@ -23,10 +23,17 @@ interface BreadcrumbContextValue {setBreadcrumbs: (crumbs: Breadcrumb[]) => void;breadcrumbToolbar: ReactNode | null;setBreadcrumbToolbar: (node: ReactNode | null) => void;+ breadcrumbPanelControl: BreadcrumbPanelControl | null;+ setBreadcrumbPanelControl: (control: BreadcrumbPanelControl | null) => void;mobileToolbar: ReactNode | null;setMobileToolbar: (node: ReactNode | null) => void;}+export interface BreadcrumbPanelControl {+ open: boolean;+ onToggle: () => void;+}+interface BreadcrumbProviderProps {children: ReactNode;companyName?: string | null;@@ -62,6 +69,8 @@ export function buildDocumentTitle(breadcrumbs: Breadcrumb[], companyName?: striexport function BreadcrumbProvider({ children, companyName }: BreadcrumbProviderProps) {const [breadcrumbs, setBreadcrumbsState] = useState<Breadcrumb[]>([]);const [breadcrumbToolbar, setBreadcrumbToolbarState] = useState<ReactNode | null>(null);+ const [breadcrumbPanelControl, setBreadcrumbPanelControlState] =+ useState<BreadcrumbPanelControl | null>(null);const [mobileToolbar, setMobileToolbarState] = useState<ReactNode | null>(null);const setBreadcrumbs = useCallback((crumbs: Breadcrumb[]) => {@@ -76,6 +85,10 @@ export function BreadcrumbProvider({ children, companyName }: BreadcrumbProvidersetBreadcrumbToolbarState(node);}, []);+ const setBreadcrumbPanelControl = useCallback((control: BreadcrumbPanelControl | null) => {+ setBreadcrumbPanelControlState(control);+ }, []);+useEffect(() => {document.title = buildDocumentTitle(breadcrumbs, companyName);}, [breadcrumbs, companyName]);@@ -87,6 +100,8 @@ export function BreadcrumbProvider({ children, companyName }: BreadcrumbProvidersetBreadcrumbs,breadcrumbToolbar,setBreadcrumbToolbar,+ breadcrumbPanelControl,+ setBreadcrumbPanelControl,mobileToolbar,setMobileToolbar,}}diff --git a/ui/src/context/SidebarContext.test.tsx b/ui/src/context/SidebarContext.test.tsxindex 630f55cc48..b7ae80046d 100644--- a/ui/src/context/SidebarContext.test.tsx+++ b/ui/src/context/SidebarContext.test.tsx@@ -8,25 +8,6 @@ import { SidebarProvider, useSidebar } from "./SidebarContext";// eslint-disable-next-line @typescript-eslint/no-explicit-any(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;-const COLLAPSED_STORAGE_KEY = "paperclip.sidebar.collapsed";--// Mutable media state driving the matchMedia mock.-const mediaState = { mobile: false, hoverFine: true };--function act(callback: () => void) {- flushSync(callback);-}--function setViewport({ mobile, hoverFine }: { mobile?: boolean; hoverFine?: boolean }) {- if (typeof mobile === "boolean") mediaState.mobile = mobile;- if (typeof hoverFine === "boolean") mediaState.hoverFine = hoverFine;- Object.defineProperty(window, "innerWidth", {- configurable: true,- writable: true,- value: mediaState.mobile ? 500 : 1280,- });-}-let capturedValue: ReturnType<typeof useSidebar> | null = null;function Capture() {@@ -34,6 +15,10 @@ function Capture() {return null;}+function act(callback: () => void) {+ flushSync(callback);+}+function renderProvider(): { root: Root; host: HTMLDivElement } {const host = document.createElement("div");document.body.appendChild(host);@@ -53,25 +38,26 @@ describe("SidebarContext", () => {beforeEach(() => {localStorage.clear();+ localStorage.setItem("paperclip.sidebar.collapsed", "1");capturedValue = null;- setViewport({ mobile: false, hoverFine: true });+ Object.defineProperty(window, "innerWidth", {+ configurable: true,+ writable: true,+ value: 1280,+ });Object.defineProperty(window, "matchMedia", {configurable: true,writable: true,- value: vi.fn().mockImplementation((query: string) => {- const isHoverQuery = query.includes("(hover: hover)");- const matches = isHoverQuery ? mediaState.hoverFine : mediaState.mobile;- return {- matches,- media: query,- onchange: null,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- addListener: vi.fn(),- removeListener: vi.fn(),- dispatchEvent: vi.fn(),- };- }),+ value: vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),});});@@ -84,219 +70,42 @@ describe("SidebarContext", () => {localStorage.clear();});- describe("precedence: user pin > route request > default", () => {- it("defaults to expanded (collapsed=false) with no pin and no route request", () => {- active = renderProvider();- expect(capturedValue?.collapsed).toBe(false);- });-- it("uses the route request when there is no user pin", () => {- active = renderProvider();- act(() => capturedValue?.setRouteRequestsCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);- });-- it("lets an explicit user pin override the route request", () => {- active = renderProvider();- act(() => capturedValue?.setRouteRequestsCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);-- // User pins expanded — this must win over the route's collapse request.- act(() => capturedValue?.setCollapsed(false));- expect(capturedValue?.collapsed).toBe(false);-- // And pinning collapsed wins too.- act(() => capturedValue?.setCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);- });-- it("toggleCollapsed flips the effective mode and records a pin", () => {- active = renderProvider();- expect(capturedValue?.collapsed).toBe(false);+ it("keeps the global navigation expanded even when legacy collapsed state exists", () => {+ active = renderProvider();- act(() => capturedValue?.toggleCollapsed());- expect(capturedValue?.collapsed).toBe(true);- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("1");-- act(() => capturedValue?.toggleCollapsed());- expect(capturedValue?.collapsed).toBe(false);- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("0");- });-- it("toggleCollapsed pins expanded when only a route request is active", () => {- active = renderProvider();- act(() => capturedValue?.setRouteRequestsCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);-- // Effective is collapsed (via route); toggling should flip to expanded.- act(() => capturedValue?.toggleCollapsed());- expect(capturedValue?.collapsed).toBe(false);- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("0");- });+ expect(capturedValue?.collapsed).toBe(false);+ expect(capturedValue?.collapseLocked).toBe(false);+ expect(capturedValue?.peeking).toBe(false);});- describe("forced collapse (secondary sidebar): overrides the pin, preserves preference", () => {- it("forces collapsed even when the user pinned expanded, without mutating the pin", () => {- active = renderProvider();- // User prefers expanded site-wide.- act(() => capturedValue?.setCollapsed(false));- expect(capturedValue?.collapsed).toBe(false);- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("0");+ it("keeps the legacy collapse API inert", () => {+ active = renderProvider();- // Entering a secondary-sidebar route forces the rail and locks it.- act(() => capturedValue?.setForceCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);- expect(capturedValue?.collapseLocked).toBe(true);- // The persisted preference is untouched.- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("0");- });-- it("restores the user's preference when the force is cleared (leaving the route)", () => {- active = renderProvider();- act(() => capturedValue?.setCollapsed(false));- act(() => capturedValue?.setForceCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);-- // Navigating away clears the force; the expanded preference returns.- act(() => capturedValue?.setForceCollapsed(false));- expect(capturedValue?.collapsed).toBe(false);- expect(capturedValue?.collapseLocked).toBe(false);- });+ act(() => capturedValue?.setCollapsed(true));+ act(() => capturedValue?.toggleCollapsed());+ act(() => capturedValue?.setForceCollapsed(true));+ act(() => capturedValue?.setPeeking(true));- it("locks the toggle while forced: toggleCollapsed is a no-op and never writes the pin", () => {- active = renderProvider();- act(() => capturedValue?.setCollapsed(false));- act(() => capturedValue?.setForceCollapsed(true));-- act(() => capturedValue?.toggleCollapsed());- expect(capturedValue?.collapsed).toBe(true); // still forced- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("0"); // pin unchanged- });-- it("never forces or locks on mobile", () => {- setViewport({ mobile: true });- active = renderProvider();- act(() => capturedValue?.setForceCollapsed(true));- expect(capturedValue?.collapsed).toBe(false);- expect(capturedValue?.collapseLocked).toBe(false);- });+ expect(capturedValue?.collapsed).toBe(false);+ expect(capturedValue?.collapseLocked).toBe(false);+ expect(capturedValue?.peeking).toBe(false);});- describe("persistence round-trip", () => {- it("writes '1'/'0' to localStorage on setCollapsed", () => {- active = renderProvider();- act(() => capturedValue?.setCollapsed(true));- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("1");- act(() => capturedValue?.setCollapsed(false));- expect(localStorage.getItem(COLLAPSED_STORAGE_KEY)).toBe("0");- });+ it("tracks route requests for compatibility without collapsing the navigation", () => {+ active = renderProvider();- it("reads the persisted pin synchronously on first paint (no flash)", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- active = renderProvider();- // Collapsed is already true on the very first captured render.- expect(capturedValue?.collapsed).toBe(true);- });+ act(() => capturedValue?.setRouteRequestsCollapsed(true));- it("treats a missing/garbage value as unpinned", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "yes");- active = renderProvider();- expect(capturedValue?.collapsed).toBe(false);- // Unpinned, so a route request still applies.- act(() => capturedValue?.setRouteRequestsCollapsed(true));- expect(capturedValue?.collapsed).toBe(true);- });+ expect(capturedValue?.routeRequestsCollapsed).toBe(true);+ expect(capturedValue?.collapsed).toBe(false);});- describe("mobile gating", () => {- it("never reports collapsed on mobile even with a collapsed pin", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- setViewport({ mobile: true });- active = renderProvider();- expect(capturedValue?.isMobile).toBe(true);- expect(capturedValue?.collapsed).toBe(false);- });+ it("retains sidebarOpen and toggleSidebar for the mobile drawer", () => {+ active = renderProvider();+ const initial = capturedValue?.sidebarOpen;- it("never reports peeking on mobile", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- setViewport({ mobile: true });- active = renderProvider();- act(() => capturedValue?.setPeeking(true));- expect(capturedValue?.peeking).toBe(false);- });- });+ act(() => capturedValue?.toggleSidebar());- describe("peek gating", () => {- it("peeks when collapsed on a hover-capable pointer", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- setViewport({ mobile: false, hoverFine: true });- active = renderProvider();- expect(capturedValue?.collapsed).toBe(true);- act(() => capturedValue?.setPeeking(true));- expect(capturedValue?.peeking).toBe(true);- });-- it("does not peek when expanded", () => {- setViewport({ mobile: false, hoverFine: true });- active = renderProvider();- expect(capturedValue?.collapsed).toBe(false);- act(() => capturedValue?.setPeeking(true));- expect(capturedValue?.peeking).toBe(false);- });-- it("does not peek on a coarse/non-hover pointer", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- setViewport({ mobile: false, hoverFine: false });- active = renderProvider();- expect(capturedValue?.collapsed).toBe(true);- act(() => capturedValue?.setPeeking(true));- expect(capturedValue?.peeking).toBe(false);- });-- // iPadOS Safari keeps the hover/pointer media query false even with a- // trackpad attached (PAP-10725); a real cursor still emits "mouse" pointer- // events, which must unlock peek at runtime.- it("peeks once a mouse-type pointer event is seen (iPad + trackpad)", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- setViewport({ mobile: false, hoverFine: false });- active = renderProvider();- expect(capturedValue?.collapsed).toBe(true);-- // No cursor seen yet → peek stays gated despite the media query.- act(() => capturedValue?.setPeeking(true));- expect(capturedValue?.peeking).toBe(false);-- // A trackpad/mouse moves: a "mouse" pointer event unlocks peek.- act(() => {- const e = new Event("pointermove");- (e as unknown as { pointerType: string }).pointerType = "mouse";- window.dispatchEvent(e);- });- expect(capturedValue?.peeking).toBe(true);- });-- it("ignores touch pointer events (touch-only stays gated)", () => {- localStorage.setItem(COLLAPSED_STORAGE_KEY, "1");- setViewport({ mobile: false, hoverFine: false });- active = renderProvider();-- act(() => capturedValue?.setPeeking(true));- act(() => {- const e = new Event("pointerover");- (e as unknown as { pointerType: string }).pointerType = "touch";- window.dispatchEvent(e);- });- expect(capturedValue?.peeking).toBe(false);- });- });-- describe("back-compat", () => {- it("retains sidebarOpen/toggleSidebar for the drawer", () => {- active = renderProvider();- const initial = capturedValue?.sidebarOpen;- expect(typeof initial).toBe("boolean");- act(() => capturedValue?.toggleSidebar());- expect(capturedValue?.sidebarOpen).toBe(!initial);- });+ expect(capturedValue?.sidebarOpen).toBe(!initial);});});diff --git a/ui/src/context/SidebarContext.tsx b/ui/src/context/SidebarContext.tsxindex d24c065b32..2cfde402ef 100644--- a/ui/src/context/SidebarContext.tsx+++ b/ui/src/context/SidebarContext.tsx@@ -14,27 +14,20 @@ interface SidebarContextValue {setSidebarOpen: (open: boolean) => void;toggleSidebar: () => void;isMobile: boolean;- // Pinned desktop mode: expanded | collapsed. Desktop-only.+ // Back-compat collapse API. The global navigation is permanently expanded;+ // these values remain for callers that have not removed old requests.collapsed: boolean;setCollapsed: (next: boolean) => void;toggleCollapsed: () => void;- // True while a secondary sidebar forces the rail: the collapse is locked, so- // the expand/toggle affordance must be hidden/inert. Desktop-only.+ // Retained compatibility value; always false now that the rail is retired.collapseLocked: boolean;- // Ephemeral peek (hover flyout). Only meaningful on desktop, collapsed,- // hover-capable pointer. Never persisted.+ // Retained compatibility value; the retired rail can no longer peek.peeking: boolean;setPeeking: (next: boolean) => void;- // Hard, ephemeral collapse forced by an active secondary sidebar (settings,- // plugin `routeSidebar`, …). HIGHER precedence than the user pin — the rule- // is "a secondary sidebar always collapses the primary" — but it never- // mutates the persisted pin, so leaving the route restores the preference.- // Wired by Layout (PAP-10694).+ // Legacy requests remain observable without affecting the global nav.forceCollapsed: boolean;setForceCollapsed: (next: boolean) => void;- // Route-requested collapse: a route may *default* the app sidebar to- // collapsed. LOWER precedence than an explicit user pin. Wired by routes via- // RequestCollapsedSidebar.+ // Route-requested collapse retained for integration compatibility.routeRequestsCollapsed: boolean;setRouteRequestsCollapsed: (next: boolean) => void;}@@ -42,62 +35,13 @@ interface SidebarContextValue {const SidebarContext = createContext<SidebarContextValue | null>(null);const MOBILE_BREAKPOINT = 768;-const COLLAPSED_STORAGE_KEY = "paperclip.sidebar.collapsed";-const PEEK_POINTER_QUERY = "(hover: hover) and (pointer: fine)";--// Tri-state read of the persisted user pin:-// true → pinned collapsed ("1")-// false → pinned expanded ("0")-// null → no pin (fall through to route request, then global default)-// Read synchronously in the state initializer so first paint matches the-// persisted mode (mirrors the `paperclip.sidebar.width` pattern in-// ResizableSidebarPane and avoids an expand→collapse flash).-function readStoredCollapsed(): boolean | null {- if (typeof window === "undefined") return null;-- try {- const stored = window.localStorage.getItem(COLLAPSED_STORAGE_KEY);- if (stored === "1") return true;- if (stored === "0") return false;- return null;- } catch {- return null;- }-}--function writeStoredCollapsed(value: boolean) {- if (typeof window === "undefined") return;-- try {- window.localStorage.setItem(COLLAPSED_STORAGE_KEY, value ? "1" : "0");- } catch {- // Storage can be unavailable in private contexts; pinning should still- // work for the current session.- }-}--function readPointerCanPeek(): boolean {- if (typeof window === "undefined" || typeof window.matchMedia !== "function") {- return false;- }-- try {- return window.matchMedia(PEEK_POINTER_QUERY).matches;- } catch {- return false;- }-}export function SidebarProvider({ children }: { children: ReactNode }) {const [isMobile, setIsMobile] = useState(() => window.innerWidth < MOBILE_BREAKPOINT);const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth >= MOBILE_BREAKPOINT);- // `null` = unpinned; an explicit user pin takes precedence over route request.- const [userCollapsed, setUserCollapsed] = useState<boolean | null>(() => readStoredCollapsed());const [routeRequestsCollapsed, setRouteRequestsCollapsed] = useState(false);const [forceCollapsed, setForceCollapsed] = useState(false);- const [rawPeeking, setRawPeeking] = useState(false);- const [pointerCanPeek, setPointerCanPeek] = useState(() => readPointerCanPeek());useEffect(() => {const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);@@ -109,67 +53,14 @@ export function SidebarProvider({ children }: { children: ReactNode }) {return () => mql.removeEventListener("change", onChange);}, []);- useEffect(() => {- if (typeof window.matchMedia !== "function") return;- const mql = window.matchMedia(PEEK_POINTER_QUERY);- // Latch on only — see the runtime detection below for why this never flips- // back to false.- const onChange = (e: MediaQueryListEvent) => {- if (e.matches) setPointerCanPeek(true);- };- mql.addEventListener("change", onChange);- return () => mql.removeEventListener("change", onChange);- }, []);-- // iPadOS Safari does not flip the `(hover: hover) and (pointer: fine)` media- // query when a trackpad/mouse is attached, so the query above stays false even- // though a real cursor is driving the UI — and hover-peek never triggers- // (PAP-10725). Detect a fine pointer at runtime instead: a genuine- // mouse/trackpad emits pointer events with `pointerType: "mouse"`, whereas- // touch reports "touch" and the Pencil reports "pen", so this never enables on- // touch-only input. Treat peek capability as a one-way latch — once a cursor- // has been seen we keep peek available for the session.- useEffect(() => {- if (pointerCanPeek || typeof window.PointerEvent !== "function") return;- const onPointer = (e: PointerEvent) => {- if (e.pointerType === "mouse") setPointerCanPeek(true);- };- window.addEventListener("pointerover", onPointer, { passive: true });- window.addEventListener("pointermove", onPointer, { passive: true });- return () => {- window.removeEventListener("pointerover", onPointer);- window.removeEventListener("pointermove", onPointer);- };- }, [pointerCanPeek]);-- // Precedence (highest wins): forced (active secondary sidebar) > explicit user- // pin > route request > default expanded. The force is ephemeral and never- // touches the persisted pin, so dropping it restores the user's preference.- const pinnedOrRequested = userCollapsed !== null ? userCollapsed : routeRequestsCollapsed;- const desktopCollapsed = forceCollapsed || pinnedOrRequested;- // Collapsed/peek are desktop-only; mobile always uses the drawer. The user- // pin is preserved across the breakpoint and reapplies on the desktop side.- const collapsed = isMobile ? false : desktopCollapsed;- // While forced, the pin is locked: the expand/toggle affordance is inert.- const collapseLocked = !isMobile && forceCollapsed;- // Peek only applies when collapsed on a hover-capable pointer.- const peeking = rawPeeking && collapsed && pointerCanPeek;-- const setCollapsed = useCallback((next: boolean) => {- setUserCollapsed(next);- writeStoredCollapsed(next);- }, []);-- const toggleCollapsed = useCallback(() => {- // While a secondary sidebar forces the rail, the toggle is locked: it must- // neither expand the rail nor mutate the persisted preference.- if (forceCollapsed) return;- setCollapsed(!pinnedOrRequested);- }, [forceCollapsed, pinnedOrRequested, setCollapsed]);-- const setPeeking = useCallback((next: boolean) => {- setRawPeeking(next);- }, []);+ // The icon rail has been retired. Keep the old API inert so routes and+ // plugins compiled against it cannot collapse the global navigation.+ const collapsed = false;+ const collapseLocked = false;+ const peeking = false;+ const setCollapsed = useCallback((_next: boolean) => {}, []);+ const toggleCollapsed = useCallback(() => {}, []);+ const setPeeking = useCallback((_next: boolean) => {}, []);const toggleSidebar = useCallback(() => setSidebarOpen((v) => !v), []);diff --git a/ui/src/hooks/useRecentTasks.ts b/ui/src/hooks/useRecentTasks.tsnew file mode 100644index 0000000000..5fe3156498--- /dev/null+++ b/ui/src/hooks/useRecentTasks.ts@@ -0,0 +1,112 @@+import { useEffect, useMemo, useState } from "react";+import { useQueries } from "@tanstack/react-query";+import type { Issue } from "@paperclipai/shared";+import { ApiError } from "@/api/client";+import { issuesApi } from "@/api/issues";+import { queryKeys } from "@/lib/queryKeys";+import {+ RECENT_TASKS_UPDATED_EVENT,+ getRecentTasksStorageKey,+ pruneRecentTasks,+ readRecentTasks,+ updateRecentTaskSnapshots,+ type RecentTaskEntry,+} from "@/lib/recent-tasks";++type RecentTasksUpdatedDetail = {+ storageKey: string;+ entries: RecentTaskEntry[];+};++export function useRecentTasks({+ companyId,+ userId,+}: {+ companyId: string | null | undefined;+ userId: string | null | undefined;+}) {+ const storageKey = useMemo(+ () => companyId ? getRecentTasksStorageKey(companyId, userId) : null,+ [companyId, userId],+ );+ const [entries, setEntries] = useState<RecentTaskEntry[]>(() => (+ storageKey && companyId ? readRecentTasks(storageKey, companyId) : []+ ));++ useEffect(() => {+ setEntries(storageKey && companyId ? readRecentTasks(storageKey, companyId) : []);+ }, [companyId, storageKey]);++ useEffect(() => {+ if (!storageKey || !companyId) return;++ const sync = () => setEntries(readRecentTasks(storageKey, companyId));+ const onStorage = (event: StorageEvent) => {+ if (event.key === storageKey) sync();+ };+ const onRecentTasksUpdated = (event: Event) => {+ const detail = (event as CustomEvent<RecentTasksUpdatedDetail>).detail;+ if (detail?.storageKey === storageKey) setEntries(detail.entries);+ };++ window.addEventListener("storage", onStorage);+ window.addEventListener(RECENT_TASKS_UPDATED_EVENT, onRecentTasksUpdated);+ return () => {+ window.removeEventListener("storage", onStorage);+ window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, onRecentTasksUpdated);+ };+ }, [companyId, storageKey]);++ const detailQueries = useQueries({+ queries: entries.map((entry) => ({+ queryKey: queryKeys.issues.detail(entry.id),+ queryFn: () => issuesApi.get(entry.id),+ retry: false,+ staleTime: 30_000,+ })),+ });++ const refreshedEntries = entries.map((entry, index) => {+ const issue = detailQueries[index]?.data;+ if (!issue || issue.companyId !== companyId || issue.hiddenAt) return entry;+ return {+ ...entry,+ title: issue.title,+ identifier: issue.identifier,+ status: issue.status,+ };+ });+ const queryRevision = detailQueries+ .map((query) => `${query.dataUpdatedAt}:${query.errorUpdatedAt}:${query.status}`)+ .join("|");++ useEffect(() => {+ if (!storageKey || !companyId || detailQueries.length === 0) return;++ const resolvedIssues: Issue[] = [];+ const removeIds = new Set<string>();+ detailQueries.forEach((query, index) => {+ const entry = entries[index];+ if (!entry) return;+ if (query.data) {+ if (query.data.companyId !== companyId || query.data.hiddenAt) {+ removeIds.add(entry.id);+ } else {+ resolvedIssues.push(query.data);+ }+ } else if (query.error instanceof ApiError && [403, 404].includes(query.error.status)) {+ removeIds.add(entry.id);+ }+ });++ updateRecentTaskSnapshots(storageKey, companyId, resolvedIssues);+ pruneRecentTasks(storageKey, companyId, removeIds);+ // queryRevision is the stable notification boundary for the useQueries result array.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [companyId, entries, queryRevision, storageKey]);++ return {+ entries: refreshedEntries,+ storageKey,+ };+}diff --git a/ui/src/hooks/useStreamlinedUiEnabled.test.tsx b/ui/src/hooks/useStreamlinedUiEnabled.test.tsxnew file mode 100644index 0000000000..5d11efcdee--- /dev/null+++ b/ui/src/hooks/useStreamlinedUiEnabled.test.tsx@@ -0,0 +1,82 @@+// @vitest-environment jsdom++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createRoot, type Root } from "react-dom/client";+import { flushSync } from "react-dom";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ resolveStreamlinedUiEnabled,+ useStreamlinedUiEnabled,+} from "./useStreamlinedUiEnabled";++const mockInstanceSettingsApi = vi.hoisted(() => ({+ getExperimental: vi.fn(),+}));++vi.mock("@/api/instanceSettings", () => ({+ instanceSettingsApi: mockInstanceSettingsApi,+}));++function Probe() {+ const state = useStreamlinedUiEnabled();+ return <output>{`${state.enabled}:${state.loaded}`}</output>;+}++async function flushReact() {+ for (let index = 0; index < 5; index += 1) {+ await Promise.resolve();+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ }+ flushSync(() => {});+}++describe("useStreamlinedUiEnabled", () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement("div");+ document.body.appendChild(host);+ root = createRoot(host);+ });++ afterEach(() => {+ flushSync(() => root.unmount());+ host.remove();+ vi.clearAllMocks();+ });++ it("fails open for missing settings and loading state", () => {+ expect(resolveStreamlinedUiEnabled(undefined)).toBe(true);+ expect(resolveStreamlinedUiEnabled(null)).toBe(true);++ mockInstanceSettingsApi.getExperimental.mockImplementation(() => new Promise(() => {}));+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ flushSync(() => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <Probe />+ </QueryClientProvider>,+ );+ });++ expect(host.textContent).toBe("true:false");+ });++ it("uses the legacy shell only for an explicit false value", async () => {+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableStreamlinedUi: false });+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ flushSync(() => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <Probe />+ </QueryClientProvider>,+ );+ });+ await flushReact();++ expect(host.textContent).toBe("false:true");+ expect(resolveStreamlinedUiEnabled({ enableStreamlinedUi: true })).toBe(true);+ expect(resolveStreamlinedUiEnabled({ enableStreamlinedUi: false })).toBe(false);+ });+});diff --git a/ui/src/hooks/useStreamlinedUiEnabled.ts b/ui/src/hooks/useStreamlinedUiEnabled.tsnew file mode 100644index 0000000000..8689d92bd8--- /dev/null+++ b/ui/src/hooks/useStreamlinedUiEnabled.ts@@ -0,0 +1,44 @@+import { useContext } from "react";+import { QueryClient, QueryClientContext, useQuery } from "@tanstack/react-query";+import type { InstanceExperimentalSettings } from "@paperclipai/shared";+import { instanceSettingsApi } from "@/api/instanceSettings";+import { queryKeys } from "@/lib/queryKeys";++export function resolveStreamlinedUiEnabled(+ settings:+ | Pick<InstanceExperimentalSettings, "enableStreamlinedUi">+ | null+ | undefined,+): boolean {+ return settings?.enableStreamlinedUi !== false;+}++let detachedClient: QueryClient | null = null;+function getDetachedClient(): QueryClient {+ detachedClient ??= new QueryClient();+ return detachedClient;+}++/**+ * The streamlined shell is the default experience. Missing legacy values,+ * loading states, and read failures all fail open so the app never flashes or+ * falls back to the legacy shell unless an instance explicitly opts out.+ */+export function useStreamlinedUiEnabled(): { enabled: boolean; loaded: boolean } {+ const contextClient = useContext(QueryClientContext);+ const query = useQuery(+ {+ queryKey: queryKeys.instance.experimentalSettings,+ queryFn: () => instanceSettingsApi.getExperimental(),+ enabled: contextClient != null,+ },+ contextClient ?? getDetachedClient(),+ );++ if (!contextClient) return { enabled: true, loaded: true };++ return {+ enabled: resolveStreamlinedUiEnabled(query.data),+ loaded: query.isFetched,+ };+}diff --git a/ui/src/index.css b/ui/src/index.cssindex 208e0e3905..2721a5cccf 100644--- a/ui/src/index.css+++ b/ui/src/index.css@@ -154,6 +154,16 @@--agent-10a: #f2d95f;--agent-10b: #4fbcba;+ /* Onboarding mascot artwork (brand-fixed, theme-independent). Keeping the+ SVG palette in the token layer preserves the source asset while allowing+ components to remain token-only. */+ --pill-guy-eye: #060606;+ --pill-guy-dormant-top: #626262;+ --pill-guy-dormant-bottom: #101010;+ --pill-guy-tuft: #2d200d;+ --pill-guy-alive-top: #3028aa;+ --pill-guy-alive-bottom: #ff0000;+/* Status colors — one base hue per status, consumed by the agent / taskstatus chips and the task status icons. Mode-independent: the `.status-chip`,`.status-fill` and inline icon helpers derive the light vs dark@@ -266,18 +276,25 @@/* Portable side-panel geometry and hierarchy. These stay centralized sotask, project, agent, and future hosts render the same Codex-like chrome. */- --side-panel-header-height: var(--sz-48px);+ --side-panel-header-height: var(--sz-60px);--side-panel-tab-height: var(--sz-30px);+ --side-panel-streamlined-tab-min-width: var(--sz-72px);+ --side-panel-streamlined-tab-max-width: var(--sz-160px);+ --side-panel-tab-edge-fade-width: var(--sz-32px);--side-panel-tab-label-max-width: var(--sz-100px);--side-panel-tab-label-expanded-max-width: calc(var(--side-panel-tab-label-max-width) + var(--sz-18px));- --side-panel-tab-label-fade-width: var(--sz-18px);+ --side-panel-tab-label-fade-width: var(--sz-32px);--side-panel-tab-radius: var(--radius-xl);--side-panel-control-radius: var(--radius-xl);--side-panel-launcher-width: var(--sz-320px);--side-panel-bg: var(--background);--side-panel-fg: var(--foreground);+ --streamlined-task-detail-bg: var(--background);--side-panel-tab-active-bg: color-mix(in oklab, var(--accent) 88%, var(--background));--side-panel-tab-hover-bg: color-mix(in oklab, var(--accent) 58%, transparent);+ --radius-task-composer: 16px;+ --shadow-task-composer: 0 2px 8px -2px color-mix(in oklab, var(--foreground) 7%, transparent),+ 0 12px 32px -8px color-mix(in oklab, var(--foreground) 12%, transparent);/* Composer mode-chip hues (v5–v7 decisions): agent + plan reuse the taskstatus hues; ask is the v5 blue. Consumed as `--sc` seeds through the@@ -302,6 +319,7 @@/* Redesigned chat-shell column cap (phase 2c): one token caps the pagewrapper, thread body, and pinned composer so they widen in lockstep. */--tc-shell-max-w: 60rem;+ --sz-66px: 66px;/* Active-turn status island and its checklist overlay. */--sz-turn-status-island: min(100%, 42rem);@@ -316,10 +334,11 @@}.dark {- --background: oklch(0.145 0 0);+ --background: oklch(0.205 0 0);--foreground: oklch(0.985 0 0);- --side-panel-bg: rgb(10 10 10);+ --side-panel-bg: var(--background);--side-panel-fg: oklch(0.985 0 0);+ --streamlined-task-detail-bg: var(--background);--card: oklch(0.205 0 0);--card-foreground: oklch(0.985 0 0);--popover: oklch(0.205 0 0);@@ -375,6 +394,11 @@--status-task-icon-cancelled: #9a958a;}+.streamlined-task-detail-surface {+ --side-panel-bg: var(--streamlined-task-detail-bg);+ background-color: var(--streamlined-task-detail-bg);+}+::highlight(paperclip-doc-annotation-open) {background-color: transparent;color: inherit;@@ -562,6 +586,61 @@#main-content:has([data-task-chat-shell]) {scrollbar-gutter: auto;}++/* Paper task-detail properties rhythm: values share the 12px label scale and+ each section gets a full 24px breathing interval before the next heading. */+.task-detail-properties [data-property-section="true"] {+ padding-bottom: calc(var(--spacing) * 6);+}++.task-detail-properties [data-property-value="true"],+.task-detail-properties [data-property-value="true"] .text-sm {+ font-size: var(--text-xs);+ line-height: var(--text-xs--line-height);+}++/* The generic line-tab variant deliberately keeps active tabs transparent.+ The task-detail sidebar uses a filled active tab instead; the pane slot ID+ gives this contextual treatment enough specificity without affecting other+ line-tab surfaces. */+#properties-pane-header-slot .task-detail-pane-tab[data-state="active"] {+ background-color: var(--muted);+}++/* Codex-style pane tabs soften clipped labels into the tab surface. The mask+ stays on the label itself so short names remain visually untouched. */+.task-detail-pane-tab-label {+ -webkit-mask-image: linear-gradient(+ to right,+ var(--foreground) 0,+ var(--foreground) calc(100% - calc(var(--spacing) * 4)),+ transparent 100%+ );+ mask-image: linear-gradient(+ to right,+ var(--foreground) 0,+ var(--foreground) calc(100% - calc(var(--spacing) * 4)),+ transparent 100%+ );+}++/* Keep continuation tabs readable as they pass beneath the fixed add control.+ The mask is enabled only while content remains beyond the right edge. */+.side-panel-tabs-scroll[data-scroll-end-fade="true"] {+ -webkit-mask-image: linear-gradient(+ to right,+ var(--foreground) 0,+ var(--foreground) calc(100% - var(--side-panel-tab-edge-fade-width)),+ transparent 100%+ );+ mask-image: linear-gradient(+ to right,+ var(--foreground) 0,+ var(--foreground) calc(100% - var(--side-panel-tab-edge-fade-width)),+ transparent 100%+ );+}+/* Light mode scrollbar on hover */.scrollbar-auto-hide:hover {scrollbar-color: oklch(0.7 0 0) transparent;@@ -795,7 +874,14 @@transition-duration: var(--motion-side-panel-tab);transition-timing-function: var(--motion-ease-standard);}-.side-panel-tab-label-fade {+.side-panel-tab-close-motion {+ transition-property: color, background-color, border-color, box-shadow, transform;+ transition-duration: var(--motion-side-panel-tab);+ transition-timing-function: var(--motion-ease-standard);+}+.side-panel-tab-label-fade,+.side-panel-tab-label-close-fade[data-truncated="true"],+[data-appearance="streamlined-task"]:is(:hover, :focus-within) .side-panel-tab-label-close-fade {-webkit-mask-image: linear-gradient(to right, black calc(100% - var(--side-panel-tab-label-fade-width)), transparent);mask-image: linear-gradient(to right, black calc(100% - var(--side-panel-tab-label-fade-width)), transparent);-webkit-mask-repeat: no-repeat;@@ -816,7 +902,8 @@.tc-turn-metrics,.tc-line-scroll-inner,.tc-pane-glide,- .side-panel-tab-motion { transition: none; }+ .side-panel-tab-motion,+ .side-panel-tab-close-motion { transition: none; }/* The pill keyframes carry the X-centering; with animation:none restore it. */.tc-scroll-pill-in,.tc-scroll-pill-out { transform: translate(-50%, 0); }@@ -2396,7 +2483,8 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {--shadow-extract-9: 0 18px 42px rgba(15,23,42,0.06); /* Extracted from ui/src/components/IssueThreadInteractionCard.tsx (shadow-[0_18px_42px_rgba(15,23,42,0.06)]). */--shadow-extract-10: 0 1px 0 1px var(--border); /* Extracted from ui/src/components/KeyboardShortcutsCheatsheet.tsx; corrected for full-color semantic tokens. */--shadow-extract-11: 0 18px 50px rgba(37,99,235,0.08); /* LiveRunWidget.tsx glow. Gallery feedback r2: liveness glow recolored cyan->status blue (value edit, site unchanged; originally extracted as rgba(6,182,212,0.08)). */- --shadow-extract-12: 0 0 0 2px var(--background); /* Extracted from ui/src/components/SidebarNavItem.tsx; corrected for full-color semantic tokens. */+ --shadow-extract-12: 0 0 0 2px var(--background); /* Production sidebar icon-badge outline. */+ --shadow-sidebar-icon-badge: 0 0 0 2px var(--muted); /* Streamlined sidebar icon-badge outline; matches the sidebar surface. */--shadow-extract-13: 0 0 0 3px rgba(245,158,11,0.18); /* Extracted from ui/src/components/environment-variables-editor/index.tsx (shadow-[0_0_0_3px_rgba(245,158,11,0.18)]). */--shadow-extract-14: 0 0 12px rgba(37,99,235,0.08); /* AgentDetail.tsx live-card glow. Gallery feedback r2: liveness glow recolored cyan->status blue (value edit, site unchanged; originally extracted as rgba(6,182,212,0.08)). */--shadow-extract-18: 0 18px 44px -28px rgba(0,0,0,0.45); /* Extracted from ui/src/pages/ProfileSettings.tsx (shadow-[0_18px_44px_-28px_rgba(0,0,0,0.45)]). */diff --git a/ui/src/lib/queryKeys.test.ts b/ui/src/lib/queryKeys.test.tsindex 243f3cca96..652053c848 100644--- a/ui/src/lib/queryKeys.test.ts+++ b/ui/src/lib/queryKeys.test.ts@@ -19,3 +19,17 @@ describe("project query keys", () => {expect(queryKeys.projects.all("company-1")).toEqual(["projects", "company-1"]);});});++describe("audit query keys", () => {+ it("separates entity-scoped activity from the unscoped feed", () => {+ const unscoped = queryKeys.audit.agentActions("company-1", { actorScope: "all" });+ const routine = queryKeys.audit.agentActions("company-1", {+ actorScope: "all",+ entityType: "routine",+ entityId: "routine-1",+ });++ expect(routine).not.toEqual(unscoped);+ expect(routine).toContain("routine-1");+ });+});diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.tsindex 00d3db2be6..3ce435a550 100644--- a/ui/src/lib/queryKeys.ts+++ b/ui/src/lib/queryKeys.ts@@ -96,6 +96,8 @@ export const queryKeys = {] as const,},audit: {+ runs: (companyId: string, agentId?: string | null) =>+ ["audit", companyId, "runs", agentId ?? "__all"] as const,agentActions: (companyId: string,filters: {@@ -104,6 +106,7 @@ export const queryKeys = {responsibleUserId?: string | null;runId?: string | null;entityType?: string | null;+ entityId?: string | null;action?: string | null;from?: string | null;to?: string | null;@@ -119,6 +122,7 @@ export const queryKeys = {filters.responsibleUserId ?? "__all",filters.runId ?? "__all",filters.entityType ?? "__all",+ filters.entityId ?? "__all",filters.action ?? "__all",filters.actorType ?? "__all",filters.from ?? "",diff --git a/ui/src/lib/recent-tasks.test.ts b/ui/src/lib/recent-tasks.test.tsnew file mode 100644index 0000000000..ae64c38d75--- /dev/null+++ b/ui/src/lib/recent-tasks.test.ts@@ -0,0 +1,94 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ RECENT_TASKS_LIMIT,+ RECENT_TASKS_UPDATED_EVENT,+ getRecentTasksStorageKey,+ pruneRecentTasks,+ readRecentTasks,+ recordRecentTask,+ updateRecentTaskSnapshots,+} from "./recent-tasks";++const issue = (id: string, companyId = "company-1") => ({+ id,+ companyId,+ title: `Task ${id}`,+ identifier: `PAP-${id}`,+ status: "todo" as const,+ updatedAt: new Date(0),+});++describe("recent task persistence", () => {+ beforeEach(() => window.localStorage.clear());++ it("is account and company scoped", () => {+ expect(getRecentTasksStorageKey("company-1", "user-1")).not.toBe(+ getRecentTasksStorageKey("company-1", "user-2"),+ );+ expect(getRecentTasksStorageKey("company-1", "user-1")).not.toBe(+ getRecentTasksStorageKey("company-2", "user-1"),+ );+ });++ it("deduplicates, only promotes newer activity, and stays bounded", () => {+ for (let index = 0; index < RECENT_TASKS_LIMIT + 2; index += 1) {+ recordRecentTask(issue(String(index)), "user-1", index);+ }+ recordRecentTask(issue("4"), "user-1", 4);++ let entries = readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1");+ expect(entries[0]?.id).toBe("6");++ recordRecentTask(issue("4"), "user-1", 99);++ entries = readRecentTasks(getRecentTasksStorageKey("company-1", "user-1"), "company-1");+ expect(entries).toHaveLength(RECENT_TASKS_LIMIT);+ expect(entries[0]?.id).toBe("4");+ expect(entries.filter((entry) => entry.id === "4")).toHaveLength(1);+ });++ it("publishes same-tab updates", () => {+ const listener = vi.fn();+ window.addEventListener(RECENT_TASKS_UPDATED_EVENT, listener);+ recordRecentTask(issue("1"), "user-1");+ expect(listener).toHaveBeenCalledOnce();+ listener.mockClear();+ recordRecentTask(issue("1"), "user-1");+ expect(listener).not.toHaveBeenCalled();+ window.removeEventListener(RECENT_TASKS_UPDATED_EVENT, listener);+ });++ it("prunes unavailable tasks and refreshes stored snapshots", () => {+ recordRecentTask(issue("1"), "user-1", 1);+ recordRecentTask(issue("2"), "user-1", 2);+ const storageKey = getRecentTasksStorageKey("company-1", "user-1");++ updateRecentTaskSnapshots(storageKey, "company-1", [{+ ...issue("2"),+ title: "Updated task",+ status: "in_progress",+ updatedAt: new Date(3),+ }]);+ pruneRecentTasks(storageKey, "company-1", new Set(["1"]));++ expect(readRecentTasks(storageKey, "company-1")).toEqual([+ expect.objectContaining({+ id: "2",+ title: "Updated task",+ status: "in_progress",+ recordedAt: 3,+ }),+ ]);+ });++ it("ignores malformed and cross-company entries", () => {+ const storageKey = getRecentTasksStorageKey("company-1", "user-1");+ window.localStorage.setItem(storageKey, JSON.stringify([+ issue("other", "company-2"),+ { nonsense: true },+ ]));+ expect(readRecentTasks(storageKey, "company-1")).toEqual([]);+ });+});diff --git a/ui/src/lib/recent-tasks.ts b/ui/src/lib/recent-tasks.tsnew file mode 100644index 0000000000..6308eeb2ac--- /dev/null+++ b/ui/src/lib/recent-tasks.ts@@ -0,0 +1,155 @@+import type { Issue, IssueStatus } from "@paperclipai/shared";++export const RECENT_TASKS_LIMIT = 5;+export const RECENT_TASKS_UPDATED_EVENT = "paperclip:recent-tasks-updated";++export interface RecentTaskEntry {+ id: string;+ companyId: string;+ title: string;+ identifier: string | null;+ status: IssueStatus;+ recordedAt: number;+}++interface RecentTasksUpdatedDetail {+ storageKey: string;+ entries: RecentTaskEntry[];+}++export function getRecentTasksStorageKey(companyId: string, userId: string | null | undefined) {+ return `paperclip.recentTasks:${companyId}:${userId ?? "__local_board__"}`;+}++function isRecentTaskEntry(value: unknown, companyId: string): value is RecentTaskEntry {+ if (!value || typeof value !== "object") return false;+ const entry = value as Partial<RecentTaskEntry>;+ return entry.companyId === companyId+ && typeof entry.id === "string"+ && entry.id.length > 0+ && typeof entry.title === "string"+ && (entry.identifier === null || typeof entry.identifier === "string")+ && typeof entry.status === "string"+ && typeof entry.recordedAt === "number"+ && Number.isFinite(entry.recordedAt);+}++export function readRecentTasks(storageKey: string, companyId: string): RecentTaskEntry[] {+ if (typeof window === "undefined") return [];+ try {+ const parsed = JSON.parse(window.localStorage.getItem(storageKey) ?? "[]") as unknown;+ if (!Array.isArray(parsed)) return [];+ return normalizeRecentTasks(+ parsed.filter((entry): entry is RecentTaskEntry => isRecentTaskEntry(entry, companyId)),+ );+ } catch {+ return [];+ }+}++function normalizeRecentTasks(entries: RecentTaskEntry[]) {+ const seen = new Set<string>();+ return [...entries]+ .sort((left, right) => right.recordedAt - left.recordedAt)+ .filter((entry) => {+ if (seen.has(entry.id)) return false;+ seen.add(entry.id);+ return true;+ })+ .slice(0, RECENT_TASKS_LIMIT);+}++function publishRecentTasks(storageKey: string, entries: RecentTaskEntry[]) {+ if (typeof window === "undefined") return;+ window.dispatchEvent(new CustomEvent<RecentTasksUpdatedDetail>(RECENT_TASKS_UPDATED_EVENT, {+ detail: { storageKey, entries },+ }));+}++export function writeRecentTasks(storageKey: string, entries: RecentTaskEntry[]) {+ if (typeof window === "undefined") return;+ const bounded = normalizeRecentTasks(entries);+ try {+ window.localStorage.setItem(storageKey, JSON.stringify(bounded));+ } catch {+ // The in-tab event still keeps mounted navigation current for this session.+ }+ publishRecentTasks(storageKey, bounded);+}++export function recordRecentTask(+ issue: Pick<Issue, "id" | "companyId" | "title" | "identifier" | "status" | "updatedAt">,+ userId: string | null | undefined,+ recordedAt = new Date(issue.updatedAt).getTime(),+) {+ const storageKey = getRecentTasksStorageKey(issue.companyId, userId);+ const current = readRecentTasks(storageKey, issue.companyId);+ const existing = current.find((candidate) => candidate.id === issue.id);+ const activityAt = Number.isFinite(recordedAt)+ ? recordedAt+ : existing?.recordedAt ?? Date.now();+ const entry: RecentTaskEntry = {+ id: issue.id,+ companyId: issue.companyId,+ title: issue.title,+ identifier: issue.identifier,+ status: issue.status,+ recordedAt: activityAt,+ };+ if (+ existing+ && existing.title === entry.title+ && existing.identifier === entry.identifier+ && existing.status === entry.status+ && existing.recordedAt === entry.recordedAt+ ) return;++ writeRecentTasks(+ storageKey,+ existing+ ? current.map((candidate) => candidate.id === issue.id ? entry : candidate)+ : [entry, ...current],+ );+}++export function pruneRecentTasks(+ storageKey: string,+ companyId: string,+ removeIds: ReadonlySet<string>,+) {+ if (removeIds.size === 0) return;+ const current = readRecentTasks(storageKey, companyId);+ const next = current.filter((entry) => !removeIds.has(entry.id));+ if (next.length !== current.length) writeRecentTasks(storageKey, next);+}++export function updateRecentTaskSnapshots(+ storageKey: string,+ companyId: string,+ issues: ReadonlyArray<Pick<Issue, "id" | "companyId" | "title" | "identifier" | "status" | "updatedAt">>,+) {+ const issueById = new Map(issues.map((issue) => [issue.id, issue]));+ const current = readRecentTasks(storageKey, companyId);+ let changed = false;+ const next = current.map((entry) => {+ const issue = issueById.get(entry.id);+ if (!issue || issue.companyId !== companyId) return entry;+ const activityAt = new Date(issue.updatedAt).getTime();+ const nextRecordedAt = Number.isFinite(activityAt) ? activityAt : entry.recordedAt;+ if (+ issue.title === entry.title+ && issue.identifier === entry.identifier+ && issue.status === entry.status+ && nextRecordedAt === entry.recordedAt+ ) return entry;+ changed = true;+ return {+ ...entry,+ title: issue.title,+ identifier: issue.identifier,+ status: issue.status,+ recordedAt: nextRecordedAt,+ };+ });+ if (changed) writeRecentTasks(storageKey, next);+}diff --git a/ui/src/lib/shell-navigation.test.ts b/ui/src/lib/shell-navigation.test.tsnew file mode 100644index 0000000000..648626adc6--- /dev/null+++ b/ui/src/lib/shell-navigation.test.ts@@ -0,0 +1,85 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it } from "vitest";+import {+ classifyShellRoute,+ getCompanyPathSegments,+ readContextualSidebarOrigin,+ rememberContextualSidebarOrigin,+} from "./shell-navigation";++describe("shell navigation", () => {+ beforeEach(() => window.sessionStorage.clear());++ it("classifies task detail independently from list routes", () => {+ expect(classifyShellRoute("/PAP/issues", "PAP").isTaskDetail).toBe(false);+ expect(classifyShellRoute("/PAP/issues/task-1", "PAP").isTaskDetail).toBe(true);+ });++ it("classifies the built-in contextual surfaces", () => {+ expect(classifyShellRoute("/PAP/company/settings/secrets", "PAP").builtInContextualSurface).toBe("settings");+ expect(classifyShellRoute("/PAP/company/export", "PAP").builtInContextualSurface).toBe("settings");+ expect(classifyShellRoute("/PAP/apps/connections", "PAP").builtInContextualSurface).toBe("apps");+ expect(classifyShellRoute("/PAP/tools/runtime", "PAP").builtInContextualSurface).toBe("apps");+ expect(classifyShellRoute("/PAP/agents/agent-1/instructions", "PAP").builtInContextualSurface).toBe("agent");+ expect(classifyShellRoute("/PAP/agents/agent-1/runs/run-1", "PAP").builtInContextualSurface).toBe("agent");+ expect(classifyShellRoute("/PAP/routines/routine-1/overview", "PAP").builtInContextualSurface).toBe("routine");+ expect(classifyShellRoute("/PAP/skills", "PAP").builtInContextualSurface).toBe("skills");+ expect(classifyShellRoute("/PAP/skills/studio/skill-1", "PAP").builtInContextualSurface).toBe("skills");+ });++ it("keeps Agent and Routine collection routes in the global shell", () => {+ for (const pathname of [+ "/PAP/agents",+ "/PAP/agents/all",+ "/PAP/agents/active",+ "/PAP/agents/paused",+ "/PAP/agents/error",+ "/PAP/agents/builtin",+ "/PAP/agents/new",+ "/PAP/routines",+ ]) {+ expect(classifyShellRoute(pathname, "PAP").builtInContextualSurface).toBeNull();+ }+ });++ it("rejects a different company prefix", () => {+ expect(getCompanyPathSegments("/OTHER/issues/task-1", "PAP")).toEqual([]);+ });++ it("remembers only safe same-company origins", () => {+ rememberContextualSidebarOrigin({+ surface: "settings",+ companyPrefix: "PAP",+ previousPathname: "/PAP/issues/task-1",+ });+ expect(readContextualSidebarOrigin({+ surface: "settings",+ companyPrefix: "PAP",+ fallbackTo: "/dashboard",+ })).toBe("/PAP/issues/task-1");++ rememberContextualSidebarOrigin({+ surface: "settings",+ companyPrefix: "PAP",+ previousPathname: "/OTHER/dashboard",+ });+ expect(readContextualSidebarOrigin({+ surface: "settings",+ companyPrefix: "PAP",+ fallbackTo: "/dashboard",+ })).toBe("/PAP/issues/task-1");+ });++ it("falls back when storage contains an unsafe path", () => {+ window.sessionStorage.setItem(+ "paperclip.contextualSidebar.origin:PAP:settings",+ "/OTHER/company/settings",+ );+ expect(readContextualSidebarOrigin({+ surface: "settings",+ companyPrefix: "PAP",+ fallbackTo: "/dashboard",+ })).toBe("/dashboard");+ });+});diff --git a/ui/src/lib/shell-navigation.ts b/ui/src/lib/shell-navigation.tsnew file mode 100644index 0000000000..b615f019bf--- /dev/null+++ b/ui/src/lib/shell-navigation.ts@@ -0,0 +1,106 @@+export type ContextualSidebarSurface =+ | "settings"+ | "apps"+ | "agent"+ | "routine"+ | "skills"+ | `plugin:${string}`;++export interface ShellRouteClassification {+ companySegments: string[];+ isTaskDetail: boolean;+ builtInContextualSurface: Exclude<ContextualSidebarSurface, `plugin:${string}`> | null;+}++const CONTEXTUAL_ORIGIN_KEY_PREFIX = "paperclip.contextualSidebar.origin";++export function getCompanyPathSegments(pathname: string, companyPrefix: string | undefined): string[] {+ if (!companyPrefix) return [];+ const segments = pathname.split("/").filter(Boolean);+ if (segments.length < 2) return [];+ if (segments[0]?.toUpperCase() !== companyPrefix.toUpperCase()) return [];+ return segments.slice(1);+}++export function classifyShellRoute(+ pathname: string,+ companyPrefix: string | undefined,+): ShellRouteClassification {+ const companySegments = getCompanyPathSegments(pathname, companyPrefix);+ const root = companySegments[0]?.toLowerCase();+ const isCompanySettings = root === "company" && ["settings", "export", "import"].includes(+ companySegments[1]?.toLowerCase() ?? "",+ );+ const agentSegment = companySegments[1]?.toLowerCase();+ const isAgentDetail = root === "agents"+ && Boolean(agentSegment)+ && agentSegment !== "new"+ && !["all", "active", "paused", "error", "builtin"].includes(agentSegment ?? "");+ const isRoutineDetail = root === "routines" && companySegments.length >= 2;+ const isSkillsSurface = root === "skills";++ return {+ companySegments,+ isTaskDetail: root === "issues" && companySegments.length >= 2,+ builtInContextualSurface: isCompanySettings+ ? "settings"+ : root === "apps" || root === "tools"+ ? "apps"+ : isAgentDetail+ ? "agent"+ : isRoutineDetail+ ? "routine"+ : isSkillsSurface+ ? "skills"+ : null,+ };+}++function contextualOriginStorageKey(surface: ContextualSidebarSurface, companyPrefix: string) {+ return `${CONTEXTUAL_ORIGIN_KEY_PREFIX}:${companyPrefix.toUpperCase()}:${surface}`;+}++function isCompanyPath(pathname: string, companyPrefix: string) {+ const first = pathname.split("/").filter(Boolean)[0];+ return first?.toUpperCase() === companyPrefix.toUpperCase();+}++export function rememberContextualSidebarOrigin({+ surface,+ companyPrefix,+ previousPathname,+}: {+ surface: ContextualSidebarSurface;+ companyPrefix: string;+ previousPathname: string;+}) {+ if (typeof window === "undefined" || !isCompanyPath(previousPathname, companyPrefix)) return;++ try {+ window.sessionStorage.setItem(+ contextualOriginStorageKey(surface, companyPrefix),+ previousPathname,+ );+ } catch {+ // Navigation still has a deterministic fallback when storage is unavailable.+ }+}++export function readContextualSidebarOrigin({+ surface,+ companyPrefix,+ fallbackTo,+}: {+ surface: ContextualSidebarSurface;+ companyPrefix: string | null | undefined;+ fallbackTo: string;+}) {+ if (typeof window === "undefined" || !companyPrefix) return fallbackTo;++ try {+ const stored = window.sessionStorage.getItem(contextualOriginStorageKey(surface, companyPrefix));+ return stored && isCompanyPath(stored, companyPrefix) ? stored : fallbackTo;+ } catch {+ return fallbackTo;+ }+}diff --git a/ui/src/pages/InstanceExperimentalSettings.test.tsx b/ui/src/pages/InstanceExperimentalSettings.test.tsxindex d5f5566906..1006159fa1 100644--- a/ui/src/pages/InstanceExperimentalSettings.test.tsx+++ b/ui/src/pages/InstanceExperimentalSettings.test.tsx@@ -43,7 +43,9 @@ async function flushReact() {const CONFERENCE_TOGGLE_SELECTOR ='button[aria-label="Toggle conference room chat experimental setting"]';const STREAMLINED_TOGGLE_SELECTOR =- 'button[aria-label="Toggle streamlined left navigation experimental setting"]';+ 'button[aria-label="Toggle Streamlined UI experimental setting"]';+const TASK_WATCHDOGS_TOGGLE_SELECTOR =+ 'button[aria-label="Toggle task watchdogs experimental setting"]';const CLASSIC_TASK_INTERFACE_TOGGLE_SELECTOR ='button[aria-label="Toggle classic task interface experimental setting"]';const GOALS_SIDEBAR_LINK_TOGGLE_SELECTOR =@@ -72,6 +74,7 @@ function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload {enableManagedSandboxOnly: false,enableIsolatedWorkspaces: false,enableStreamlinedLeftNavigation: true,+ enableStreamlinedUi: true,enableApps: true,enablePipelines: false,enableCases: false,@@ -224,13 +227,30 @@ describe("InstanceExperimentalSettings — Conference Room Chat card (PAP-11233)expect(mockInstanceSettingsApi.updateExperimental).not.toHaveBeenCalled();});- it("no longer renders the Streamlined Left Navigation toggle (opt-out retired, PAP-12472)", async () => {+ it("renders and patches the Streamlined UI experimental toggle on and off", async () => {await renderPage();- const headings = [...container.querySelectorAll("section h2")].map((h) => h.textContent);- expect(headings).not.toContain("Streamlined Left Navigation Bar");- expect(container.querySelector(STREAMLINED_TOGGLE_SELECTOR)).toBeNull();- expect(mockInstanceSettingsApi.updateExperimental).not.toHaveBeenCalled();+ expect(container.textContent).toContain("Streamlined UI");+ expect(container.textContent).toContain(+ "Use the simplified main sidebar, shared Tasks and Inbox presentation, focused task detail layout, and contextual navigation across Agents, Routines, Skills, and Settings.",+ );++ const toggle = container.querySelector<HTMLButtonElement>(STREAMLINED_TOGGLE_SELECTOR);+ expect(toggle?.getAttribute("aria-checked")).toBe("true");++ await act(() => toggle?.click());+ await flushReact();+ expect(mockInstanceSettingsApi.updateExperimental).toHaveBeenLastCalledWith({+ enableStreamlinedUi: false,+ });+ expect(toggle?.getAttribute("aria-checked")).toBe("false");++ await act(() => toggle?.click());+ await flushReact();+ expect(mockInstanceSettingsApi.updateExperimental).toHaveBeenLastCalledWith({+ enableStreamlinedUi: true,+ });+ expect(toggle?.getAttribute("aria-checked")).toBe("true");});it("does not render a Task Watchdogs toggle because watchdogs are always enabled", async () => {diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsxindex cfa91e8080..9efacbd95e 100644--- a/ui/src/pages/InstanceExperimentalSettings.tsx+++ b/ui/src/pages/InstanceExperimentalSettings.tsx@@ -205,6 +205,7 @@ export function InstanceExperimentalSettings() {const enableIsolatedWorkspaces = experimentalQuery.data?.enableIsolatedWorkspaces === true;// Streamlined left navigation is now the standard sidebar (PAP-12472); the// experimental opt-out was retired, so it no longer surfaces a toggle here.+ const enableStreamlinedUi = experimentalQuery.data?.enableStreamlinedUi !== false;const enableConferenceRoomChat = experimentalQuery.data?.enableConferenceRoomChat === true;const enableClassicTaskInterface = experimentalQuery.data?.enableClassicTaskInterface === true;const enableIssuePlanDecompositions =@@ -420,6 +421,18 @@ export function InstanceExperimentalSettings() {ariaLabel="Toggle status cards experimental setting"/>+ <ExperimentalToggleCard+ title="Streamlined UI"+ description="Use the simplified main sidebar, shared Tasks and Inbox presentation, focused task detail layout, and contextual navigation across Agents, Routines, Skills, and Settings."+ footnote="Turning this off restores the legacy shell and navigation. Task and page data are unchanged."+ checked={enableStreamlinedUi}+ onCheckedChange={(checked) => toggleMutation.mutate({ enableStreamlinedUi: checked })}+ disabled={toggleMutation.isPending}+ settingKey="enableStreamlinedUi"+ managed={managedKeys.enableStreamlinedUi}+ ariaLabel="Toggle Streamlined UI experimental setting"+ />+<ExperimentalToggleCardtitle="Summaries"description="Show Summarizer-generated status slots on project and workspace pages, with on-demand refresh and revision history. Existing summary data is kept when this is disabled."diff --git a/ui/src/pages/agent-detail-navigation.test.ts b/ui/src/pages/agent-detail-navigation.test.tsnew file mode 100644index 0000000000..ce63a023a4--- /dev/null+++ b/ui/src/pages/agent-detail-navigation.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";+import {+ AGENT_DETAIL_NAVIGATION,+ agentDetailHref,+ agentLegacyAuditSection,+ agentScopedAuditHref,+ parseAgentDetailView,+} from "./agent-detail-navigation";++describe("agent detail navigation", () => {+ it("exposes the complete local information architecture", () => {+ expect(AGENT_DETAIL_NAVIGATION.flatMap((section) => section.items.map((item) => item.value))).toEqual([+ "overview",+ "instructions",+ "skills",+ "runtime",+ "secrets",+ "tools",+ "permissions",+ "api-keys",+ "revisions",+ ]);+ });++ it("canonicalizes legacy local paths", () => {+ expect(parseAgentDetailView("dashboard")).toBe("overview");+ expect(parseAgentDetailView("configuration")).toBe("runtime");+ expect(parseAgentDetailView("prompts")).toBe("instructions");+ expect(agentDetailHref("codexcoder", "permissions")).toBe("/agents/codexcoder/permissions");+ });++ it("maps legacy operational pages into scoped Audit sections", () => {+ expect(agentLegacyAuditSection("runs")).toBe("runs");+ expect(agentLegacyAuditSection("audit")).toBe("activity");+ expect(agentLegacyAuditSection("budget")).toBe("budgets");+ expect(agentScopedAuditHref("agent-1", "activity")).toBe("/activity?mode=agents&agentId=agent-1");+ expect(agentScopedAuditHref("agent-1", "costs")).toBe("/activity/costs?agentId=agent-1");+ });+});diff --git a/ui/src/pages/agent-detail-navigation.ts b/ui/src/pages/agent-detail-navigation.tsnew file mode 100644index 0000000000..e06ae44ac9--- /dev/null+++ b/ui/src/pages/agent-detail-navigation.ts@@ -0,0 +1,76 @@+import { auditSectionHref, type AuditSection } from "./audit/audit-navigation";++export type AgentDetailView =+ | "overview"+ | "instructions"+ | "skills"+ | "runtime"+ | "secrets"+ | "tools"+ | "permissions"+ | "api-keys"+ | "revisions"+ | "run-detail";++export type AgentLocalDetailView = Exclude<AgentDetailView, "run-detail">;++export const AGENT_DETAIL_NAVIGATION: ReadonlyArray<{+ label: string;+ items: ReadonlyArray<{ value: AgentLocalDetailView; label: string }>;+}> = [+ {+ label: "Agent",+ items: [+ { value: "overview", label: "Overview" },+ { value: "instructions", label: "Instructions" },+ { value: "skills", label: "Skills" },+ ],+ },+ {+ label: "Runtime",+ items: [+ { value: "runtime", label: "Harness / Runtime" },+ { value: "secrets", label: "Secrets" },+ { value: "tools", label: "Tools" },+ ],+ },+ {+ label: "Governance",+ items: [+ { value: "permissions", label: "Permissions / Trust" },+ { value: "api-keys", label: "API Keys" },+ { value: "revisions", label: "Revisions" },+ ],+ },+] as const;++export function parseAgentDetailView(value: string | null): AgentLocalDetailView {+ if (value === "instructions" || value === "prompts") return "instructions";+ if (value === "skills") return "skills";+ if (value === "runtime" || value === "configure" || value === "configuration") return "runtime";+ if (value === "secrets") return "secrets";+ if (value === "tools") return "tools";+ if (value === "permissions" || value === "trust") return "permissions";+ if (value === "api-keys" || value === "keys") return "api-keys";+ if (value === "revisions" || value === "history") return "revisions";+ return "overview";+}++export function agentDetailHref(agentRef: string, view: AgentLocalDetailView = "overview") {+ return `/agents/${agentRef}/${view}`;+}++export function agentLegacyAuditSection(value: string | null): AuditSection | null {+ if (value === "runs") return "runs";+ if (value === "audit" || value === "activity") return "activity";+ if (value === "cost" || value === "costs") return "costs";+ if (value === "budget" || value === "budgets") return "budgets";+ return null;+}++export function agentScopedAuditHref(agentId: string, section: AuditSection) {+ return auditSectionHref(section, {+ mode: section === "activity" ? "agents" : undefined,+ agentId,+ });+}diff --git a/ui/src/pages/audit/audit-navigation.test.ts b/ui/src/pages/audit/audit-navigation.test.tsnew file mode 100644index 0000000000..009659a67e--- /dev/null+++ b/ui/src/pages/audit/audit-navigation.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import {+ agentAuditHref,+ auditScopeFromSearchParams,+ auditSectionHref,+ routineAuditHref,+ runAuditHref,+} from "./audit-navigation";++describe("audit navigation", () => {+ it("builds stable section routes", () => {+ expect(auditSectionHref("activity")).toBe("/activity");+ expect(auditSectionHref("runs")).toBe("/activity/runs");+ expect(auditSectionHref("costs")).toBe("/activity/costs");+ expect(auditSectionHref("budgets")).toBe("/activity/budgets");+ expect(auditSectionHref("timeline")).toBe("/activity/timeline");+ });++ it("provides agent, routine, and run scoped links", () => {+ expect(agentAuditHref("agent-1")).toBe("/activity?mode=agents&agentId=agent-1");+ expect(agentAuditHref("agent-1", "runs")).toBe("/activity/runs?agentId=agent-1");+ expect(routineAuditHref("routine-1")).toBe(+ "/activity?entityType=routine&entityId=routine-1",+ );+ expect(runAuditHref("run-1", "agent-1")).toBe(+ "/activity?mode=agents&agentId=agent-1&runId=run-1",+ );+ });++ it("reads supported scope parameters without treating arbitrary query data as filters", () => {+ expect(auditScopeFromSearchParams(new URLSearchParams(+ "mode=agents&agentId=agent-1&entityType=routine&entityId=routine-1&ignored=yes",+ ))).toEqual({+ mode: "agents",+ agentId: "agent-1",+ runId: null,+ entityType: "routine",+ entityId: "routine-1",+ });+ });+});diff --git a/ui/src/pages/audit/audit-navigation.ts b/ui/src/pages/audit/audit-navigation.tsnew file mode 100644index 0000000000..8562295ea5--- /dev/null+++ b/ui/src/pages/audit/audit-navigation.ts@@ -0,0 +1,64 @@+export type AuditSection = "activity" | "runs" | "costs" | "budgets" | "timeline";++export const AUDIT_SECTIONS: ReadonlyArray<{+ value: AuditSection;+ label: string;+ href: string;+}> = [+ { value: "activity", label: "Activity", href: "/activity" },+ { value: "runs", label: "Runs", href: "/activity/runs" },+ { value: "costs", label: "Costs", href: "/activity/costs" },+ { value: "budgets", label: "Budgets", href: "/activity/budgets" },+ { value: "timeline", label: "Timeline", href: "/activity/timeline" },+];++export interface AuditLinkScope {+ mode?: "all" | "agents";+ agentId?: string | null;+ runId?: string | null;+ entityType?: string | null;+ entityId?: string | null;+}++export function auditSectionHref(section: AuditSection, scope: AuditLinkScope = {}) {+ const base = AUDIT_SECTIONS.find((candidate) => candidate.value === section)?.href ?? "/activity";+ const search = new URLSearchParams();+ if (scope.mode === "agents") search.set("mode", "agents");+ if (scope.agentId) search.set("agentId", scope.agentId);+ if (scope.runId) search.set("runId", scope.runId);+ if (scope.entityType) search.set("entityType", scope.entityType);+ if (scope.entityId) search.set("entityId", scope.entityId);+ const query = search.toString();+ return query ? `${base}?${query}` : base;+}++/** Link target for an agent's attributed activity or company-wide run history. */+export function agentAuditHref(agentId: string, section: "activity" | "runs" = "activity") {+ return auditSectionHref(section, {+ mode: section === "activity" ? "agents" : undefined,+ agentId,+ });+}++/** Link target for the immutable activity recorded directly against a routine. */+export function routineAuditHref(routineId: string) {+ return auditSectionHref("activity", {+ entityType: "routine",+ entityId: routineId,+ });+}++/** Link target for the attributed activity behind a specific run. */+export function runAuditHref(runId: string, agentId?: string | null) {+ return auditSectionHref("activity", { mode: "agents", runId, agentId });+}++export function auditScopeFromSearchParams(searchParams: URLSearchParams): AuditLinkScope {+ return {+ mode: searchParams.get("mode") === "agents" ? "agents" : "all",+ agentId: searchParams.get("agentId"),+ runId: searchParams.get("runId"),+ entityType: searchParams.get("entityType"),+ entityId: searchParams.get("entityId"),+ };+}diff --git a/ui/src/pages/skills/skills-navigation.test.ts b/ui/src/pages/skills/skills-navigation.test.tsnew file mode 100644index 0000000000..e9e781ae48--- /dev/null+++ b/ui/src/pages/skills/skills-navigation.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import {+ resolveSkillsDiscoveryView,+ resolveSkillsNavigationView,+ SKILLS_NAVIGATION_HREFS,+ withSkillsDiscoveryView,+} from "./skills-navigation";++describe("skills navigation", () => {+ it("defaults to Installed and exposes stable canonical hrefs", () => {+ expect(resolveSkillsDiscoveryView(null)).toBe("installed");+ expect(resolveSkillsNavigationView("/PAP/skills", "")).toBe("installed");+ expect(SKILLS_NAVIGATION_HREFS).toEqual({+ installed: "/skills",+ discover: "/skills?tab=discover",+ authored: "/skills/studio",+ });+ });++ it.each(["discover", "all", "catalog", "bundled"])(+ "maps the legacy %s tab to Discover",+ (tab) => {+ expect(resolveSkillsDiscoveryView(tab)).toBe("discover");+ expect(resolveSkillsNavigationView("/PAP/skills", `?tab=${tab}`)).toBe("discover");+ },+ );++ it("treats catalog detail links as Discover and Studio routes as My Skills", () => {+ expect(resolveSkillsNavigationView("/PAP/skills", "?catalog=skill-1")).toBe("discover");+ expect(resolveSkillsNavigationView("/PAP/skills", "?view=catalog")).toBe("discover");+ expect(resolveSkillsNavigationView("/PAP/skills/studio/skill-1", "?tab=files")).toBe("authored");+ });++ it("canonicalizes view changes without carrying incompatible filters", () => {+ expect(withSkillsDiscoveryView(+ new URLSearchParams("tab=catalog&folder=my&category=writing&source=bundled"),+ "discover",+ ).toString()).toBe("tab=discover&source=bundled");++ expect(withSkillsDiscoveryView(+ new URLSearchParams("tab=discover&folder=my&source=external"),+ "installed",+ ).toString()).toBe("folder=my&source=external");+ });+});diff --git a/ui/src/pages/skills/skills-navigation.ts b/ui/src/pages/skills/skills-navigation.tsnew file mode 100644index 0000000000..c905f82877--- /dev/null+++ b/ui/src/pages/skills/skills-navigation.ts@@ -0,0 +1,41 @@+export type SkillsNavigationView = "installed" | "discover" | "authored";++export const SKILLS_NAVIGATION_HREFS: Record<SkillsNavigationView, string> = {+ installed: "/skills",+ discover: "/skills?tab=discover",+ authored: "/skills/studio",+};++export function resolveSkillsDiscoveryView(tabParam: string | null): Exclude<SkillsNavigationView, "authored"> {+ // Preserve old discovery links while presenting one canonical Discover view.+ return ["discover", "all", "catalog", "bundled"].includes(tabParam ?? "")+ ? "discover"+ : "installed";+}++export function withSkillsDiscoveryView(+ current: URLSearchParams,+ view: Exclude<SkillsNavigationView, "authored">,+): URLSearchParams {+ const params = new URLSearchParams(current);+ if (view === "installed") params.delete("tab");+ else params.set("tab", "discover");+ params.delete("view");+ params.delete("category");+ if (view !== "installed") params.delete("folder");+ return params;+}++export function resolveSkillsNavigationView(+ pathname: string,+ search: string | URLSearchParams = "",+): SkillsNavigationView {+ const segments = pathname.split("/").filter(Boolean);+ const skillsIndex = segments.findIndex((segment) => segment.toLowerCase() === "skills");+ const skillsRoute = skillsIndex >= 0 ? segments.slice(skillsIndex + 1) : [];+ if (skillsRoute[0]?.toLowerCase() === "studio") return "authored";++ const params = typeof search === "string" ? new URLSearchParams(search) : search;+ if (params.has("catalog") || params.get("view") === "catalog") return "discover";+ return resolveSkillsDiscoveryView(params.get("tab"));+}