Skip to content

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

Go

feat(core): multica 1.0 part 1 (MUL-8317) (#9635)

Jiayuan Zhang7c186016a54e
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
index 20ec58eb66..b90e778f9c 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
@@ -8,12 +8,12 @@ import { RESOURCES } from "@multica/views/locales";
// The shell resolves the mocked `getCurrentSlug()` against the workspace list
// before mounting workspace-scoped chrome, so the list has to contain it or
-// the sidebar under test never renders. Gating behaviour itself is covered by
+// the rail under test never renders. Gating behaviour itself is covered by
// desktop-layout.workspace-gate.test.tsx.
const WORKSPACES = [{ id: "ws-1", slug: "acme" }];
// The shell is the only thing under test here, so everything it mounts around
-// the sidebar is stubbed out. What survives is the pair that has to agree:
+// the rail is stubbed out. What survives is the pair that has to agree:
// `WindowToolbar`'s own trigger, and the `hasExternalTrigger` the provider
// publishes to every page header inside the canvas.
vi.mock("@/hooks/use-tab-history", () => ({
@@ -66,15 +66,24 @@ vi.mock("@multica/views/platform", () => ({
}));
vi.mock("@multica/views/layout", () => ({
- AppSidebar: () => null,
+ AppRail: () => null,
+ AppShellProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+ CompactNavSheet: () => null,
GlobalShortcuts: () => null,
NavigationProgress: () => null,
+ NewIssueButton: () => null,
+ SearchButton: () => null,
+ ShellRouteDataPrefetch: ({ children }: { children: ReactNode }) => <>{children}</>,
+ SpacePanel: () => null,
+ // In a panel space the shell's toggleNav is the sidebar toggle.
+ useAppShell: () => ({ toggleNav: useSidebar().toggleSidebar }),
+ useTabPresentation: () => ({ visual: { kind: "icon", icon: "Inbox" }, title: "" }),
+ ResourceLeadingVisual: () => null,
}));
vi.mock("@multica/views/modals/registry", () => ({ ModalRegistry: () => null }));
vi.mock("@multica/views/search", () => ({
SearchCommand: () => null,
- SearchTrigger: () => null,
}));
vi.mock("@multica/views/chat", () => ({ FloatingChat: () => null }));
vi.mock("./tab-bar", () => ({ TabBar: () => null }));
@@ -138,8 +147,8 @@ beforeEach(() => {
describe("DesktopShell sidebar trigger", () => {
// The window toolbar parks a trigger beside the traffic lights that never
// scrolls away, so nothing inside the canvas may add a second one. Desktop
- // windows sit below `xl`, exactly the band where `PageHeader`'s fallback
- // trigger renders, so every page used to stack an identical icon 50px under
+ // windows often sit in the band where `PageHeader`'s fallback trigger
+ // renders, so every page used to stack an identical icon 50px under
// this one — and a third when a list/detail surface brought its own header
// along (MUL-6218).
it("keeps exactly one trigger and tells page headers not to add another", () => {
@@ -150,18 +159,19 @@ describe("DesktopShell sidebar trigger", () => {
"data-external-trigger",
"true",
);
+ // The toolbar floats over the 64px rail; the tabs start past the rest
+ // of it whether or not the panel inside the card is open.
const mainTopBar = container.querySelector('[data-slot="main-top-bar"]');
- expect(mainTopBar).toHaveAttribute("data-sidebar-resize-consumer");
- expect(mainTopBar).toHaveClass("transition-[padding-left]");
- expect(mainTopBar).toHaveStyle({
- paddingLeft:
- "max(0px, calc(200px - var(--sidebar-live-width, var(--sidebar-width))))",
- });
+ expect(mainTopBar).toHaveStyle({ paddingLeft: "136px" });
fireEvent.click(
container.querySelector('[data-slot="sidebar-trigger"]')!,
);
- expect(mainTopBar).toHaveStyle({ paddingLeft: "200px" });
+ expect(getByTestId("page-content")).toHaveAttribute(
+ "data-sidebar-state",
+ "collapsed",
+ );
+ expect(mainTopBar).toHaveStyle({ paddingLeft: "136px" });
expect(queryByRole("status", { name: /loading workspace/i })).toBeNull();
});
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index abf73ff7f4..476602b73a 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -1,5 +1,4 @@
import { useEffect, useRef, useSyncExternalStore } from "react";
-import { motion } from "motion/react";
import { useQuery } from "@tanstack/react-query";
import { cn } from "@multica/ui/lib/utils";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
@@ -13,11 +12,17 @@ import {
} from "@multica/ui/components/ui/sidebar";
import { ModalRegistry } from "@multica/views/modals/registry";
import {
- AppSidebar,
+ AppRail,
+ AppShellProvider,
+ CompactNavSheet,
GlobalShortcuts,
NavigationProgress,
+ NewIssueButton,
+ SearchButton,
+ ShellRouteDataPrefetch,
+ SpacePanel,
} from "@multica/views/layout";
-import { SearchCommand, SearchTrigger } from "@multica/views/search";
+import { SearchCommand } from "@multica/views/search";
import { FloatingChat } from "@multica/views/chat";
import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";
import { workspaceListOptions } from "@multica/core/workspace";
@@ -32,20 +37,18 @@ import {
DesktopNavigationProvider,
routeContentLinkPath,
} from "@/platform/navigation";
+import { useRenderedRouteStore } from "@/stores/rendered-route-store";
import { TabBar } from "./tab-bar";
import { TabContent } from "./tab-content";
import { WindowOverlay } from "./window-overlay";
import { WindowToolbar, WINDOW_TOOLBAR_CLEARANCE } from "./window-toolbar";
const TOP_BAR_HEIGHT_CLASS = "h-10";
-const toolbarMotion = {
- type: "spring",
- stiffness: 420,
- damping: 38,
- mass: 0.8,
-} as const;
+const RAIL_WIDTH = 64;
+const TITLE_BAR_ACTION_CLASS =
+ "flex size-7 items-center justify-center rounded-md text-faint-foreground transition-colors duration-150 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:outline-2 focus-visible:outline-offset-2 [&_svg]:size-4";
-function SidebarTopSpacer() {
+function RailTopSpacer() {
return <div className={cn("shrink-0", TOP_BAR_HEIGHT_CLASS)} />;
}
@@ -64,26 +67,22 @@ function useNativeNavigationGestures() {
}
-// The main area's top bar doubles as a window drag region. When the sidebar
-// is not occupying enough main-flow width, leave the remainder here so tabs
-// do not land beneath the traffic lights / navigation controls. The matching
-// 200ms transition cancels the sidebar gap's movement during toggle; live
-// resize previews disable it through data-sidebar-resize-consumer.
-function MainTopBar({ sidebarMounted }: { sidebarMounted: boolean }) {
- const { state, isCompact } = useSidebar();
- const sidebarHidden = !sidebarMounted || state === "collapsed" || isCompact;
- const toolbarClearance: React.CSSProperties["paddingLeft"] = sidebarHidden
- ? WINDOW_TOOLBAR_CLEARANCE
- : `max(0px, calc(${WINDOW_TOOLBAR_CLEARANCE}px - var(--sidebar-live-width, var(--sidebar-width))))`;
+// The main area's top bar doubles as a window drag region. The window
+// toolbar (traffic lights, history, panel toggle) floats over the rail and
+// the start of this bar, so the tabs start past whatever the rail leaves of
+// its width. New issue and search hold the far end; the tabs give way to
+// them.
+function MainTopBar({ railMounted }: { railMounted: boolean }) {
+ const { isCompact } = useSidebar();
+ const toolbarClearance =
+ railMounted && !isCompact
+ ? WINDOW_TOOLBAR_CLEARANCE - RAIL_WIDTH
+ : WINDOW_TOOLBAR_CLEARANCE;
return (
<header
data-slot="main-top-bar"
- data-sidebar-resize-consumer
- className={cn(
- "relative shrink-0 flex items-center gap-2 transition-[padding-left] duration-200 ease-out motion-reduce:transition-none",
- TOP_BAR_HEIGHT_CLASS,
- )}
+ className={cn("relative shrink-0 flex items-center gap-2", TOP_BAR_HEIGHT_CLASS)}
style={{ paddingLeft: toolbarClearance }}
>
<div
@@ -102,33 +101,48 @@ function MainTopBar({ sidebarMounted }: { sidebarMounted: boolean }) {
>
<TabBar />
</div>
+ {railMounted && (
+ <div
+ data-slot="title-bar-actions"
+ className="relative z-10 ml-auto flex shrink-0 items-center gap-2 pr-3"
+ style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
+ >
+ <NewIssueButton className={TITLE_BAR_ACTION_CLASS} tooltipSide="bottom" />
+ <SearchButton className={TITLE_BAR_ACTION_CLASS} tooltipSide="bottom" />
+ </div>
+ )}
</header>
);
}
-// The canvas hugs the expanded sidebar with a hairline gap. When the sidebar
-// leaves the main flow, the left margin must grow to mirror the fixed mr-2 so
-// the floating canvas sits symmetrically inside the window frame.
+// The content card: the space panel and the tab content share one surface,
+// split by a single hairline. It hugs the rail; without one (compact, or no
+// workspace yet) it mirrors the fixed mr-2 so it sits centred in the frame.
function MainCanvas({
children,
+ railMounted,
showWorkspaceLoading,
}: {
children: React.ReactNode;
+ railMounted: boolean;
showWorkspaceLoading: boolean;
}) {
- const { state, isCompact } = useSidebar();
+ const { isCompact } = useSidebar();
const { t } = useT("layout");
- const sidebarHidden = state === "collapsed" || isCompact;
const loadingLabel = t(($) => $.workspace_loader.loading_workspace);
return (
- <motion.div
- animate={{ marginLeft: sidebarHidden ? 8 : 2 }}
- className="relative flex flex-1 min-h-0 flex-col overflow-hidden mr-2 mb-2 rounded-xl bg-page-canvas ring-1 ring-surface-border shadow-[var(--surface-shadow)]"
- initial={false}
- transition={toolbarMotion}
+ <div
+ data-slot="main-canvas"
+ className={cn(
+ "relative mr-2 mb-2 flex min-h-0 flex-1 flex-row overflow-hidden rounded-xl bg-page-canvas shadow-[var(--surface-shadow)] ring-1 ring-surface-border",
+ railMounted && !isCompact ? "ml-0" : "ml-2",
+ )}
>
- {children}
+ {railMounted && <SpacePanel />}
+ <div className="relative flex min-w-0 flex-1 flex-col overflow-hidden">
+ {children}
+ </div>
{showWorkspaceLoading && (
<div
aria-label={loadingLabel}
@@ -142,7 +156,7 @@ function MainCanvas({
</div>
</div>
)}
- </motion.div>
+ </div>
);
}
@@ -211,7 +225,7 @@ export function DesktopShell() {
// Reactive read of current workspace slug from the platform singleton.
// On first mount, it is null until WorkspaceRouteLayout (inside the tab
- // router) sets it. Once set, the sidebar and other shell-level components
+ // router) sets it. Once set, the rail and other shell-level components
// can resolve workspace-scoped paths via useWorkspacePaths().
const currentSlug = useSyncExternalStore(
subscribeToCurrentSlug,
@@ -239,6 +253,7 @@ export function DesktopShell() {
currentSlug && workspaces.some((w) => w.slug === currentSlug)
? currentSlug
: null;
+ const renderedPathname = useRenderedRouteStore((s) => s.pathname);
return (
<DesktopNavigationProvider>
@@ -246,7 +261,7 @@ export function DesktopShell() {
use useWorkspaceSlug() (nullable) or useRequiredWorkspaceSlug()
(throws). TabContent MUST always render so the tab router can
mount WorkspaceRouteLayout, which calls setCurrentWorkspace()
- to populate the slug. The sidebar gates on the resolved slug
+ to populate the slug. The rail gates on the resolved slug
(see above) to avoid the useRequiredWorkspaceSlug and
useWorkspaceId throws. Zero-workspace users see the
window-level overlay (new-workspace flow) triggered by
@@ -262,30 +277,42 @@ export function DesktopShell() {
{/* hasExternalTrigger: WindowToolbar below parks a SidebarTrigger
beside the traffic lights, where it is always reachable. Page
headers inside the canvas must not add their own fallback one on
- top of it — desktop windows sit below `xl`, exactly where that
+ top of it — desktop windows often sit in the band where that
fallback renders, so every page showed a second identical icon
50px under this one (MUL-6218). */}
<SidebarProvider
hasExternalTrigger
className="flex-1 bg-app-shell [--sidebar-wrapper-fill:var(--app-shell)]"
>
- {slug && <GlobalShortcuts />}
- {slug && <WindowToolbar />}
- {slug && <AppSidebar topSlot={<SidebarTopSpacer />} searchSlot={<SearchTrigger />} />}
- {/* Right side: header + content container */}
- <div className="flex flex-1 min-w-0 flex-col">
- <MainTopBar sidebarMounted={Boolean(slug)} />
- <MainCanvas showWorkspaceLoading={!slug}>
- {/* Same indicator, same anchor as web: DashboardLayout puts it
- at the top of SidebarInset, and MainCanvas is desktop's
- equivalent relative/overflow-hidden content box. Desktop
- used to have no navigation feedback at all — a click just
- froze until the destination committed (MUL-6404). */}
- <NavigationProgress />
- <TabContent />
- {slug && <FloatingChat />}
- </MainCanvas>
- </div>
+ <AppShellProvider renderedPathname={renderedPathname}>
+ <ShellRouteDataPrefetch>
+ {slug && <GlobalShortcuts />}
+ {slug && <WindowToolbar />}
+ {slug && (
+ <AppRail
+ topSlot={<RailTopSpacer />}
+ globalActions={false}
+ className="hidden pt-0 md:flex"
+ />
+ )}
+ {slug && <CompactNavSheet globalActions={false} />}
+ {/* Right side: header + content card */}
+ <div className="flex flex-1 min-w-0 flex-col">
+ <MainTopBar railMounted={Boolean(slug)} />
+ <MainCanvas railMounted={Boolean(slug)} showWorkspaceLoading={!slug}>
+ {/* Same indicator, same anchor as web: DashboardLayout puts
+ it at the top of the content column, and this is
+ desktop's equivalent relative/overflow-hidden box.
+ Desktop used to have no navigation feedback at all — a
+ click just froze until the destination committed
+ (MUL-6404). */}
+ <NavigationProgress />
+ <TabContent />
+ {slug && <FloatingChat />}
+ </MainCanvas>
+ </div>
+ </ShellRouteDataPrefetch>
+ </AppShellProvider>
</SidebarProvider>
</div>
{slug && <ModalRegistry />}
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
index a2770a8d64..abbddb933a 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
@@ -79,9 +79,18 @@ vi.mock("@multica/views/platform", () => ({
// Each workspace-scoped component gets a marker so the assertions can tell
// which of them the shell decided to mount.
vi.mock("@multica/views/layout", () => ({
- AppSidebar: () => <div data-testid="app-sidebar" />,
+ AppRail: () => <div data-testid="app-rail" />,
+ AppShellProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+ CompactNavSheet: () => null,
GlobalShortcuts: () => <div data-testid="global-shortcuts" />,
NavigationProgress: () => <div data-testid="navigation-progress" />,
+ NewIssueButton: () => <div data-testid="title-bar-new-issue" />,
+ SearchButton: () => <div data-testid="title-bar-search" />,
+ ShellRouteDataPrefetch: ({ children }: { children: ReactNode }) => <>{children}</>,
+ SpacePanel: () => <div data-testid="space-panel" />,
+ useAppShell: () => ({ hasPanel: true }),
+ useTabPresentation: () => ({ visual: { kind: "icon", icon: "Inbox" }, title: "" }),
+ ResourceLeadingVisual: () => null,
}));
vi.mock("@multica/views/modals/registry", () => ({
@@ -101,7 +110,6 @@ vi.mock("@multica/views/search", () => ({
}
return <div data-testid="search-command" />;
},
- SearchTrigger: () => null,
}));
vi.mock("@multica/views/chat", () => ({
@@ -152,8 +160,11 @@ describe("DesktopShell workspace gating", () => {
it("mounts workspace-scoped chrome while the slug resolves", () => {
const { queryByRole, queryByTestId } = renderShell();
- expect(queryByTestId("app-sidebar")).not.toBeNull();
+ expect(queryByTestId("app-rail")).not.toBeNull();
+ expect(queryByTestId("space-panel")).not.toBeNull();
expect(queryByTestId("search-command")).not.toBeNull();
+ expect(queryByTestId("title-bar-new-issue")).not.toBeNull();
+ expect(queryByTestId("title-bar-search")).not.toBeNull();
expect(queryByTestId("global-shortcuts")).not.toBeNull();
expect(queryByTestId("modal-registry")).not.toBeNull();
expect(queryByTestId("floating-chat")).not.toBeNull();
@@ -165,7 +176,7 @@ describe("DesktopShell workspace gating", () => {
const { container, getByRole, getByTestId, queryByTestId } = renderShell();
- expect(queryByTestId("app-sidebar")).toBeNull();
+ expect(queryByTestId("app-rail")).toBeNull();
expect(
container.querySelectorAll("[data-slot='sidebar-trigger']"),
).toHaveLength(0);
@@ -185,8 +196,10 @@ describe("DesktopShell workspace gating", () => {
const { queryByTestId } = renderShell();
- expect(queryByTestId("app-sidebar")).toBeNull();
+ expect(queryByTestId("app-rail")).toBeNull();
+ expect(queryByTestId("space-panel")).toBeNull();
expect(queryByTestId("search-command")).toBeNull();
+ expect(queryByTestId("title-bar-new-issue")).toBeNull();
expect(queryByTestId("global-shortcuts")).toBeNull();
expect(queryByTestId("modal-registry")).toBeNull();
expect(queryByTestId("floating-chat")).toBeNull();
@@ -220,7 +233,8 @@ describe("DesktopShell workspace gating", () => {
const { queryByTestId } = renderShell();
- expect(queryByTestId("app-sidebar")).toBeNull();
+ expect(queryByTestId("app-rail")).toBeNull();
expect(queryByTestId("search-command")).toBeNull();
+ expect(queryByTestId("title-bar-new-issue")).toBeNull();
});
});
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx
index 1660660394..9a15dd2d8f 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx
@@ -12,7 +12,6 @@ import { I18nProvider } from "@multica/core/i18n/react";
import type { SupportedLocale } from "@multica/core/i18n";
import { RESOURCES } from "@multica/views/locales";
import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
-import { SIDEBAR_WRAPPER_FILL_CLASS } from "@multica/ui/components/ui/sidebar";
type MockTab = {
id: string;
@@ -271,76 +270,26 @@ describe("TabBar active-tab title persistence", () => {
});
});
-describe("TabBar merged-tab chrome", () => {
- // Keep the fill inside the translucent keyline so the merged border is even.
- it("keeps the active tab's page-canvas fill out from under its keyline", () => {
- const { getByLabelText } = render(<TabBar />);
- const cap = getByLabelText("Issues")
- .closest("[data-tab-frame]")
- ?.querySelector(".rounded-t-lg");
+describe("TabBar pill chrome", () => {
+ const pillOf = (label: string, getByLabelText: (text: string) => HTMLElement) =>
+ getByLabelText(label).closest("[data-tab-frame]")?.querySelector(".rounded-lg");
- expect(cap).toHaveClass(
- "border-surface-border",
+ // The active pill is the content card's material, so it reads as that
+ // card's tab while standing apart from it on the title bar.
+ it("paints the active tab with the content card's surface", () => {
+ const { getByLabelText } = render(<TabBar />);
+ expect(pillOf("Issues", getByLabelText)).toHaveClass(
"bg-page-canvas",
- "bg-clip-padding",
+ "ring-surface-border",
+ "shadow-[var(--surface-shadow)]",
);
});
- // The opaque backing keeps the flare and card keylines from stacking, and has
- // to equal the strip's backdrop at every width. It reads that colour off the
- // sidebar wrapper's published fill rather than naming a token, so no token may
- // appear here or in the gradient — a pinned one is exactly the regression this
- // covers. The wrapper's end of the contract is covered in packages/views.
- it("paints each flare on the sidebar wrapper's own fill", () => {
- const { getByLabelText } = render(<TabBar />);
- const flares = getByLabelText("Issues")
- .closest("[data-tab-frame]")
- ?.querySelectorAll('[style*="radial-gradient"]');
-
- expect(flares).toHaveLength(2);
- for (const flare of flares ?? []) {
- expect(flare).toHaveClass(SIDEBAR_WRAPPER_FILL_CLASS);
- expect(flare.getAttribute("style")).toContain("var(--page-canvas) 10.2px)");
- expect(flare.getAttribute("style")).not.toContain("var(--sidebar)");
- expect(flare.getAttribute("style")).not.toContain("var(--app-shell)");
- expect(flare.className).not.toContain("bg-app-shell");
- expect(flare.className).not.toContain("bg-sidebar");
- }
- });
-
- // A flare overhangs the neighbouring tab by 9px, so the backing above may only
- // cover the arc and the canvas fill: left over the notch it prints a square of
- // strip colour on top of whatever the neighbour draws there, which is how the
- // hover pill lost its corner to a dark bite (MUL-6160). The notch is therefore
- // masked out of the flare entirely, and the mask has to close before the arc's
- // anti-aliasing starts (r - 1.2) or the arc loses the backing it needs.
- it("punches the notch out rather than filling it with strip colour", () => {
+ it("keeps inactive tabs as lighter pills without the card's edge", () => {
const { getByLabelText } = render(<TabBar />);
- const flares = getByLabelText("Issues")
- .closest("[data-tab-frame]")
- ?.querySelectorAll<HTMLElement>('[style*="radial-gradient"]');
-
- expect(flares).toHaveLength(2);
- for (const flare of flares ?? []) {
- const corner = /circle at top (left|right), transparent 8\.8px/.exec(
- flare.style.backgroundImage,
- )?.[1];
- const mask = flare.style.maskImage;
-
- expect(corner).toBeDefined();
- expect(mask).toContain(`radial-gradient(circle at top ${corner}, transparent 8.4px`);
- expect(mask).toMatch(/ 8\.8px\)$/);
- expect(flare.style.getPropertyValue("-webkit-mask-image")).toBe(mask);
- }
- });
-
- it("draws the merged cap only on the active tab", () => {
- const { getByLabelText } = render(<TabBar />);
- expect(
- getByLabelText("Projects")
- .closest("[data-tab-frame]")
- ?.querySelector(".rounded-t-lg"),
- ).toBeNull();
+ const pill = pillOf("Projects", getByLabelText);
+ expect(pill).toHaveClass("bg-page-canvas/50");
+ expect(pill).not.toHaveClass("ring-surface-border");
});
});
@@ -365,7 +314,7 @@ describe("TabBar overflow", () => {
"overflow-y-hidden",
);
expect(getByLabelText("Tab 1").closest("[data-tab-frame]")).toHaveClass(
- "w-40",
+ "w-56",
"min-w-32",
);
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsx
index 2ba6ea24f5..6ea6ce721a 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx
@@ -35,7 +35,6 @@ import {
} from "@multica/ui/components/ui/context-menu";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
-import { SIDEBAR_WRAPPER_FILL_CLASS } from "@multica/ui/components/ui/sidebar";
import { cn } from "@multica/ui/lib/utils";
import { useTabStore, useActiveGroup, type Tab } from "@/stores/tab-store";
import { paths } from "@multica/core/paths";
@@ -49,33 +48,6 @@ import { parseIssueWindowPath } from "../../../shared/issue-window";
const TAB_SCROLL_FADE_SIZE = 24;
const TAB_ENTRY_EASE = [0.22, 1, 0.36, 1] as const;
-// Concave tab flares need an opaque backing beneath translucent border arcs
-// to avoid compositing a second keyline over the content ring. Read that backdrop
-// from SIDEBAR_WRAPPER_FILL_CLASS rather than duplicating the wrapper's fill rule.
-// Mask the transparent notch so the backing cannot paint over a neighboring hover
-// pill, while retaining backing beneath the arc's antialiasing.
-const TAB_FLARE_RADIUS = 10;
-const tabFlareGradient = (side: "left" | "right") => {
- const r = TAB_FLARE_RADIUS;
- return `radial-gradient(circle at top ${side}, transparent ${r - 1.2}px, var(--surface-border) ${r - 0.8}px, var(--surface-border) ${r - 0.2}px, var(--page-canvas) ${r + 0.2}px)`;
-};
-const tabFlareNotchMask = (side: "left" | "right") => {
- const r = TAB_FLARE_RADIUS;
- return `radial-gradient(circle at top ${side}, transparent ${r - 1.6}px, black ${r - 1.2}px)`;
-};
-// The flares are mirror images: the offset overlaps the tab edge by 1px so arc
-// and side border meet, and gradient and mask share the corner the offset picks.
-const tabFlareStyle = (side: "left" | "right"): React.CSSProperties => {
- const overhang = -TAB_FLARE_RADIUS + 1;
- const mask = tabFlareNotchMask(side);
- return {
- ...(side === "left" ? { left: overhang } : { right: overhang }),
- backgroundImage: tabFlareGradient(side),
- maskImage: mask,
- WebkitMaskImage: mask,
- };
-};
-
type TabSnapshot = {
workspaceSlug: string | null;
ids: Set<string>;
@@ -164,7 +136,6 @@ function SortableTabItem({
canCloseOthers,
isNew,
shouldReduceMotion,
- showSeparator,
}: {
tab: Tab;
isActive: boolean;
@@ -177,11 +148,6 @@ function SortableTabItem({
canCloseOthers: boolean;
isNew: boolean;
shouldReduceMotion: boolean;
- /**
- * Hairline on the tab's left edge — hidden next to the active tab, and
- * faded out while either of the two tabs it divides is hovered.
- */
- showSeparator: boolean;
}) {
const { t } = useT("settings");
const setActiveTab = useTabStore((s) => s.setActiveTab);
@@ -296,14 +262,11 @@ function SortableTabItem({
data-tab-entering={isEntering ? "true" : undefined}
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
className={cn(
- // The 36px frame contains a centered 32px content row and a 4px
- // bottom connector. Keep the connector clickable without letting it
- // shift the icon, title, or hover actions below the toolbar center.
- "group relative flex size-full min-w-0 items-center gap-1.5 px-2.5 pb-1 text-caption transition-colors",
+ "group relative flex size-full min-w-0 items-center gap-1.5 px-2.5 text-caption transition-colors",
"select-none cursor-default",
isActive
- ? "font-medium text-foreground"
- : "text-muted-foreground hover:text-sidebar-accent-foreground",
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground",
isDragging && "opacity-60",
)}
>
@@ -347,7 +310,7 @@ function SortableTabItem({
style={style}
data-tab-frame
data-tab-id={tab.id}
- className={cn("h-9 w-40 min-w-32", isActive && "z-10")}
+ className={cn("h-full w-56 min-w-32", isActive && "z-10")}
>
<motion.div
className="group/tab relative size-full"
@@ -356,46 +319,19 @@ function SortableTabItem({
transition={{ duration: isEntering ? 0.18 : 0, ease: TAB_ENTRY_EASE }}
onAnimationComplete={() => setIsEntering(false)}
>
- {isActive ? (
- // Merged-tab chrome: a bordered cap, a borderless base whose fill
- // runs into the content card below (covering its top ring), and two
- // flares whose arcs hand the keyline over to the card's ring. The
- // flares overlap the tab edge by 1px so arc and side border meet.
- <span
- aria-hidden
- className={cn(
- "pointer-events-none absolute inset-0",
- isDragging && "opacity-60",
- )}
- >
- {/* Keep the fill inside the translucent keyline so it matches the
- flare arcs and content card ring. */}
- <span className="absolute inset-x-0 top-0 bottom-2.5 rounded-t-lg border border-b-0 border-surface-border bg-page-canvas bg-clip-padding" />
- <span className="absolute inset-x-0 bottom-0 h-2.5 bg-page-canvas" />
- <span
- className={cn("absolute bottom-0 size-2.5", SIDEBAR_WRAPPER_FILL_CLASS)}
- style={tabFlareStyle("left")}
- />
- <span
- className={cn("absolute bottom-0 size-2.5", SIDEBAR_WRAPPER_FILL_CLASS)}
- style={tabFlareStyle("right")}
- />
- </span>
- ) : (
- <span
- aria-hidden
- className="pointer-events-none absolute inset-x-0.5 top-0 bottom-1 rounded-lg bg-sidebar-accent opacity-0 transition-opacity group-hover/tab:opacity-100"
- />
- )}
- {showSeparator && (
- // Fades in step with the neighbouring hover pill: both use a bare
- // transition-opacity, so the hairline clears exactly as the pill
- // arrives rather than lingering 2px off its rounded edge.
- <span
- aria-hidden
- className="pointer-events-none absolute left-0 top-2 h-4 w-px bg-surface-border transition-opacity group-hover/tab:opacity-0 prev-tab-hover:opacity-0"
- />
- )}
+ {/* Every tab is a pill on the title bar; the active one is made of
+ the content card's own material so it reads as the card's tab
+ without having to join it. */}
+ <span
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-x-0 inset-y-1.5 rounded-lg transition-colors",
+ isActive
+ ? "bg-page-canvas shadow-[var(--surface-shadow)] ring-1 ring-surface-border"
+ : "bg-page-canvas/50 group-hover/tab:bg-page-canvas/80",
+ isDragging && "opacity-60",
+ )}
+ />
<ContextMenu>
<TooltipHint label={tab.pinned ? tabName : undefined} side="bottom">
<ContextMenuTrigger render={tabButton} />
@@ -445,7 +381,7 @@ function SortableTabItem({
{showAddedHighlight && (
<motion.span
aria-hidden
- className="pointer-events-none absolute inset-x-0.5 top-0 bottom-1 rounded-lg bg-primary/10 ring-1 ring-inset ring-primary/20"
+ className="pointer-events-none absolute inset-x-0 inset-y-1.5 rounded-lg bg-primary/10 ring-1 ring-inset ring-primary/20"
initial={{ opacity: shouldReduceMotion ? 0.25 : 0.65 }}
animate={{ opacity: 0 }}
transition={{ duration: shouldReduceMotion ? 0.16 : 0.42 }}
@@ -491,7 +427,7 @@ function NewTabEdgeFeedback({
key={`${signal.tabId}-${signal.sequence}`}
aria-hidden
data-new-tab-edge-feedback="true"
- className="pointer-events-none absolute top-1 bottom-1 right-0 z-20 w-8 rounded-r-lg bg-gradient-to-l from-primary/35 via-primary/10 to-transparent"
+ className="pointer-events-none absolute inset-y-1.5 right-0 z-20 w-8 rounded-r-lg bg-gradient-to-l from-primary/35 via-primary/10 to-transparent"
initial={{
opacity: shouldReduceMotion ? 0.45 : 0,
x: shouldReduceMotion ? 0 : 4,
@@ -646,7 +582,7 @@ export function TabBar() {
};
return (
- <div className="flex h-full w-full min-w-0 max-w-full items-center justify-start gap-0.5 px-2">
+ <div className="flex h-full w-full min-w-0 max-w-full items-center justify-start gap-1.5 px-2">
<div className="relative flex h-full min-w-0 flex-1 items-center">
<DndContext
sensors={sensors}
@@ -654,48 +590,36 @@ export function TabBar() {
modifiers={[restrictToHorizontalAxis, restrictToParentElement]}
onDragEnd={handleDragEnd}
>
- {/* px-4 keeps the active tab's flares inside the scroller's clip
- (overflow clips at the padding box) and clears the content
- card's rounded top-left corner below the first tab. */}
+ {/* px-px keeps the active pill's ring inside the scroller's clip. */}
<div
ref={tabScrollRef}
data-tab-scroll-container
- className="no-scrollbar flex h-full min-w-0 flex-1 items-end overflow-x-auto overflow-y-hidden overscroll-x-contain px-4"
+ className="no-scrollbar flex h-full min-w-0 flex-1 items-center gap-1.5 overflow-x-auto overflow-y-hidden overscroll-x-contain px-px"
style={tabFadeStyle}
>
<SortableContext items={tabIds} strategy={horizontalListSortingStrategy}>
- {tabs.map((tab, index) => {
- const previousTab = index > 0 ? tabs[index - 1] : null;
- return (
- <Fragment key={tab.id}>
- <SortableTabItem
- tab={tab}
- isActive={tab.id === activeTabId}
- isOnly={tabs.length === 1}
- canCloseOthers={tabs.some(
- (candidate) => candidate.id !== tab.id && !candidate.pinned,
- )}
- isNew={addedTabIdSet.has(tab.id)}
- shouldReduceMotion={shouldReduceMotion}
- showSeparator={
- !!previousTab &&
- tab.id !== activeTabId &&
- previousTab.id !== activeTabId &&
- // the pinned-zone divider already separates this pair
- !(previousTab.pinned && !tab.pinned)
- }
- />
- {tab.pinned &&
- index === pinnedCount - 1 &&
- unpinnedCount > 0 && (
- <div
- aria-hidden
- className="mx-1 mb-3 h-4 w-px shrink-0 self-end bg-surface-border"
- />
- )}
- </Fragment>
- );
- })}
+ {tabs.map((tab, index) => (
+ <Fragment key={tab.id}>
+ <SortableTabItem
+ tab={tab}
+ isActive={tab.id === activeTabId}
+ isOnly={tabs.length === 1}
+ canCloseOthers={tabs.some(
+ (candidate) => candidate.id !== tab.id && !candidate.pinned,
+ )}
+ isNew={addedTabIdSet.has(tab.id)}
+ shouldReduceMotion={shouldReduceMotion}
+ />
+ {tab.pinned &&
+ index === pinnedCount - 1 &&
+ unpinnedCount > 0 && (
+ <div
+ aria-hidden
+ className="h-4 w-px shrink-0 bg-surface-border"
+ />
+ )}
+ </Fragment>
+ ))}
</SortableContext>
</div>
</DndContext>
diff --git a/apps/desktop/src/renderer/src/components/tab-content.tsx b/apps/desktop/src/renderer/src/components/tab-content.tsx
index 5f2fb93863..12f4e5d383 100644
--- a/apps/desktop/src/renderer/src/components/tab-content.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-content.tsx
@@ -10,6 +10,7 @@ import {
registerActiveHostElement,
registerCoordinatorQueryClient,
} from "@/platform/tab-coordinator";
+import { initIssueViewTabs } from "@/platform/issue-view-tabs";
/**
* Renders the active tab session through THE single app router
@@ -39,6 +40,7 @@ export function TabContent() {
// is idempotent.
useState(() => {
initTabCoordinator();
+ initIssueViewTabs();
return true;
});
diff --git a/apps/desktop/src/renderer/src/components/window-toolbar.test.tsx b/apps/desktop/src/renderer/src/components/window-toolbar.test.tsx
index bcee6381b4..a66b724def 100644
--- a/apps/desktop/src/renderer/src/components/window-toolbar.test.tsx
+++ b/apps/desktop/src/renderer/src/components/window-toolbar.test.tsx
@@ -19,9 +19,8 @@ const historyState = vi.hoisted(() => ({
goToHistoryIndex: vi.fn(),
}));
-const sidebarState = vi.hoisted(() => ({
- state: "expanded" as "expanded" | "collapsed",
- isCompact: false,
+const shellState = vi.hoisted(() => ({
+ current: { toggleNav: () => {} } as { toggleNav: () => void } | null,
}));
vi.mock("@/hooks/use-tab-history", () => ({
@@ -34,10 +33,10 @@ vi.mock("@multica/views/layout", () => ({
title: fallbackTitle ?? `Title ${url}`,
}),
ResourceLeadingVisual: () => <span aria-hidden />,
+ useAppShell: () => shellState.current,
}));
vi.mock("@multica/ui/components/ui/sidebar", () => ({
- useSidebar: () => sidebarState,
SidebarTrigger: (props: ComponentProps<"button">) => (
<button type="button" aria-label="Toggle sidebar" {...props} />
),
@@ -71,8 +70,7 @@ beforeEach(() => {
historyState.goBack.mockReset();
historyState.goForward.mockReset();
historyState.goToHistoryIndex.mockReset();
- sidebarState.state = "expanded";
- sidebarState.isCompact = false;
+ shellState.current = { toggleNav: vi.fn() };
vi.useFakeTimers();
});
@@ -97,30 +95,36 @@ describe("historyIndicesForMenu", () => {
});
describe("WindowToolbar history controls", () => {
- it("left-aligns the controls past the traffic lights across the expanded sidebar", () => {
+ it("left-aligns the controls past the traffic lights at a fixed width", () => {
render(<WindowToolbar />, { wrapper: I18nWrapper });
const toolbar = document.querySelector('[data-slot="window-toolbar"]');
+ expect(WINDOW_TOOLBAR_CLEARANCE).toBe(200);
expect(toolbar).not.toHaveClass("justify-end");
- expect(toolbar).toHaveStyle({
- paddingLeft: "88px",
- width:
- "max(var(--sidebar-live-width, var(--sidebar-width)), 200px)",
- });
- expect(toolbar).toHaveAttribute("data-sidebar-resize-consumer");
- expect(toolbar).not.toHaveClass("transition-[width]");
+ expect(toolbar).toHaveStyle({ paddingLeft: "88px", width: "200px" });
});
- it("keeps the controls clear of the traffic lights after toggling the sidebar", () => {
- const { rerender } = render(<WindowToolbar />, { wrapper: I18nWrapper });
- sidebarState.state = "collapsed";
- rerender(<WindowToolbar />);
+ it("keeps the controls clear of the traffic lights after toggling the panel", () => {
+ render(<WindowToolbar />, { wrapper: I18nWrapper });
+ fireEvent.click(screen.getByRole("button", { name: "Toggle sidebar" }));
const toolbar = document.querySelector('[data-slot="window-toolbar"]');
- expect(WINDOW_TOOLBAR_CLEARANCE).toBe(200);
expect(toolbar).toHaveStyle({ paddingLeft: "88px", width: "200px" });
});
+ // Inside the shell the toggle routes through toggleNav, which collapses the
+ // space panel or, in Inbox, Chat and Settings, the page's own list column.
+ it("routes the panel toggle through the shell", () => {
+ const toggleNav = vi.fn();
+ shellState.current = { toggleNav };
+ render(<WindowToolbar />, { wrapper: I18nWrapper });
+
+ const toggle = screen.getByRole("button", { name: "Toggle sidebar" });
+ expect(toggle).toBeEnabled();
+ fireEvent.click(toggle);
+ expect(toggleNav).toHaveBeenCalledOnce();
+ });
+
it("orders Back, Forward, then the sidebar toggle with no separate History button", () => {
render(<WindowToolbar />, { wrapper: I18nWrapper });
diff --git a/apps/desktop/src/renderer/src/components/window-toolbar.tsx b/apps/desktop/src/renderer/src/components/window-toolbar.tsx
index 873ad69bbb..e1c47b2970 100644
--- a/apps/desktop/src/renderer/src/components/window-toolbar.tsx
+++ b/apps/desktop/src/renderer/src/components/window-toolbar.tsx
@@ -7,10 +7,7 @@ import {
type PointerEventHandler,
} from "react";
import { ArrowLeft, ArrowRight } from "@multica/ui/icons";
-import {
- SidebarTrigger,
- useSidebar,
-} from "@multica/ui/components/ui/sidebar";
+import { SidebarTrigger } from "@multica/ui/components/ui/sidebar";
import {
DropdownMenu,
DropdownMenuContent,
@@ -26,6 +23,7 @@ import {
import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";
import {
ResourceLeadingVisual,
+ useAppShell,
useTabPresentation,
} from "@multica/views/layout";
import { ActionShortcutKeycaps } from "@multica/views/common/shortcut-keycaps";
@@ -35,9 +33,9 @@ import { browsingHistoryKeyForUrl } from "@/stores/tab-store";
// Controls sit left-aligned just past the macOS traffic lights, which end
// around x=76 with trafficLightPosition { x: 16 }. The clearance covers that
-// inset plus Back, Forward and the sidebar toggle (3 × 28px, 2 × 8px gaps) and
-// a 12px trailing pad, and matches the sidebar's minimum width so the
-// controls always fit inside the expanded sidebar column.
+// inset plus Back, Forward and the panel toggle (3 × 28px, 2 × 8px gaps) and
+// a 12px trailing pad. It spans the rail and the start of the tab bar, which
+// pads itself past it.
const TRAFFIC_LIGHT_CLEARANCE = 88;
export const WINDOW_TOOLBAR_CLEARANCE = 200;
const LONG_PRESS_DURATION_MS = 500;
@@ -179,11 +177,7 @@ function HistoryMenuItem({
export function WindowToolbar() {
const { t } = useT("layout");
- const { state: sidebarState, isCompact } = useSidebar();
- const sidebarHidden = sidebarState === "collapsed" || isCompact;
- const toolbarWidth: React.CSSProperties["width"] = sidebarHidden
- ? WINDOW_TOOLBAR_CLEARANCE
- : `max(var(--sidebar-live-width, var(--sidebar-width)), ${WINDOW_TOOLBAR_CLEARANCE}px)`;
+ const shell = useAppShell();
const {
canGoBack,
canGoForward,
@@ -259,12 +253,11 @@ export function WindowToolbar() {
return (
<div
data-slot="window-toolbar"
- data-sidebar-resize-consumer
className="fixed left-0 top-0 z-30 flex h-10 shrink-0 items-center pr-3"
style={
{
WebkitAppRegion: "drag",
- width: toolbarWidth,
+ width: WINDOW_TOOLBAR_CLEARANCE,
paddingLeft: TRAFFIC_LIGHT_CLEARANCE,
} as React.CSSProperties
}
@@ -367,6 +360,14 @@ export function WindowToolbar() {
<SidebarTrigger
className="size-7 text-faint-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
shortcut={<ActionShortcutKeycaps action="toggleSidebar" />}
+ onClick={
+ shell
+ ? (event) => {
+ event.preventDefault();
+ shell.toggleNav();
+ }
+ : undefined
+ }
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
/>
</div>
diff --git a/apps/desktop/src/renderer/src/globals.css b/apps/desktop/src/renderer/src/globals.css
index 551ede7b84..0bd8e0f48b 100644
--- a/apps/desktop/src/renderer/src/globals.css
+++ b/apps/desktop/src/renderer/src/globals.css
@@ -6,20 +6,6 @@
@custom-variant dark (&:is(.dark *));
-/* Tab strip hairlines sit on each tab's own left edge, so the hairline between
- two tabs belongs to the tab on the right. Hovering the left tab has to fade
- it out as well, which no ancestor-based variant can reach — hence the
- adjacent-sibling selector. The (hover: hover) gate mirrors what Tailwind
- already wraps group-hover in, so both halves of the fade stay in step on
- devices without a pointer. */
-@custom-variant prev-tab-hover {
- @media (hover: hover) {
- [data-tab-frame]:hover + [data-tab-frame] & {
- @slot;
- }
- }
-}
-
/* Font stack: Inter for Latin UI text + system CJK fonts for localized content.
Web app uses the same stack via next/font/google in apps/web/app/layout.tsx —
keep the CJK fallback tail in sync across both files. The Inter primary family
@@ -80,8 +66,3 @@ html[lang="zh-TW"] {
@source "../../../../../packages/core/**/*.{ts,tsx}";
@source "../../../../../packages/views/**/*.{ts,tsx}";
@source "./**/*.tsx";
-
-/* Desktop-specific: override sidebar container padding for traffic light layout */
-[data-slot="sidebar-container"] {
- padding: 0 !important;
-}
diff --git a/apps/desktop/src/renderer/src/pages/project-detail-page.tsx b/apps/desktop/src/renderer/src/pages/project-detail-page.tsx
index 6762de6cc7..7c31d7ba1c 100644
--- a/apps/desktop/src/renderer/src/pages/project-detail-page.tsx
+++ b/apps/desktop/src/renderer/src/pages/project-detail-page.tsx
@@ -4,6 +4,7 @@ import { ProjectDetail } from "@multica/views/projects/components";
import { useWorkspaceId } from "@multica/core/hooks";
import { projectDetailOptions } from "@multica/core/projects/queries";
import { useDocumentTitle } from "@/hooks/use-document-title";
+import { IssueViewUrlSync } from "@/platform/issue-view-tabs";
export function ProjectDetailPage() {
const { id } = useParams<{ id: string }>();
@@ -15,5 +16,9 @@ export function ProjectDetailPage() {
useDocumentTitle(project ? project.title : "Project");
if (!id) return null;
- return <ProjectDetail projectId={id} />;
+ return (
+ <IssueViewUrlSync scope={{ scope_type: "project", scope_id: id }}>
+ <ProjectDetail projectId={id} />
+ </IssueViewUrlSync>
+ );
}
diff --git a/apps/desktop/src/renderer/src/platform/issue-view-tabs.test.tsx b/apps/desktop/src/renderer/src/platform/issue-view-tabs.test.tsx
new file mode 100644
index 0000000000..a67a4bbc3d
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/issue-view-tabs.test.tsx
@@ -0,0 +1,130 @@
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
+import { getActiveTab, useTabStore } from "@/stores/tab-store";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@/stores/window-overlay-store", () => ({
+ useWindowOverlayStore: Object.assign(() => null, { getState: () => ({ overlay: null, open: vi.fn(), close: vi.fn() }) }),
+}));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: Object.assign(() => null, { getState: () => ({ logout: vi.fn() }) }),
+}));
+
+import { DesktopNavigationProvider } from "./navigation";
+import { IssueViewUrlSync, __resetIssueViewTabsForTests, initIssueViewTabs } from "./issue-view-tabs";
+
+const KEY = "ws-1:workspace";
+const WORKSPACE = { scope_type: "workspace" } as const;
+let rendered: (string | null)[] = [];
+
+function Probe() {
+ const view = useActiveIssueViewStore((s) => s.active[KEY] ?? null);
+ rendered.push(view);
+ return <span data-testid="view">{view ?? "none"}</span>;
+}
+
+/** The active tab's page, remounted per tab the way TabContent does. */
+function ActiveIssuesPage() {
+ const tabId = useTabStore((s) => getActiveTab(s)?.id);
+ return (
+ <DesktopNavigationProvider>
+ <IssueViewUrlSync key={tabId} scope={WORKSPACE}>
+ <Probe />
+ </IssueViewUrlSync>
+ </DesktopNavigationProvider>
+ );
+}
+
+const tabs = () => useTabStore.getState().byWorkspace.acme.tabs;
+const activeUrl = () => getActiveTab(useTabStore.getState())!.url;
+const shown = () => screen.getByTestId("view").textContent;
+
+beforeEach(() => {
+ Object.defineProperty(window, "desktopAPI", {
+ configurable: true,
+ value: { runtimeConfig: { ok: true, config: { appUrl: "https://app.example" } } },
+ });
+ __resetIssueViewTabsForTests();
+ useActiveIssueViewStore.setState({ active: {} });
+ useTabStore.getState().reset();
+ useTabStore.getState().switchWorkspace("acme");
+ initIssueViewTabs();
+ rendered = [];
+});
+
+afterEach(() => __resetIssueViewTabsForTests());
+
+describe("desktop issue views per tab", () => {
+ it("opens a cmd+clicked view in its own tab, and each tab keeps its view", () => {
+ useTabStore.getState().navigateActiveSession("/acme/issues?view=a");
+ render(<ActiveIssuesPage />);
+ expect(shown()).toBe("a");
+ const tabA = getActiveTab(useTabStore.getState())!.id;
+
+ act(() => {
+ useTabStore.getState().openTab("/acme/issues?view=b", "B");
+ });
+ expect(tabs()).toHaveLength(2);
+ expect(shown()).toBe("a");
+
+ const tabB = tabs().find((t) => t.id !== tabA)!.id;
+ rendered = [];
+ act(() => useTabStore.getState().setActiveTab(tabB));
+ expect(shown()).toBe("b");
+ expect(rendered).not.toContain("a");
+
+ act(() => useTabStore.getState().setActiveTab(tabA));
+ expect(shown()).toBe("a");
+ act(() => useTabStore.getState().setActiveTab(tabB));
+ expect(shown()).toBe("b");
+ });
+
+ it("shows All issues in a tab opened without a view, whatever another tab has open", () => {
+ useTabStore.getState().navigateActiveSession("/acme/issues?view=a");
+ render(<ActiveIssuesPage />);
+
+ act(() => {
+ useTabStore.getState().openTab("/acme/issues", "Issues", { activate: true });
+ });
+
+ expect(activeUrl()).toBe("/acme/issues");
+ expect(shown()).toBe("none");
+ });
+
+ it("writes view changes back to the tab's URL without adding history", () => {
+ render(<ActiveIssuesPage />);
+ const history = () => getActiveTab(useTabStore.getState())!.history.stack;
+
+ act(() => useActiveIssueViewStore.getState().setActive(KEY, "c"));
+ expect(activeUrl()).toBe("/acme/issues?view=c");
+ act(() => useActiveIssueViewStore.getState().setActive(KEY, null));
+ expect(activeUrl()).toBe("/acme/issues");
+ expect(history()).toEqual(["/acme/issues"]);
+ });
+
+ it("keeps the tab's open view when its page is reached without one", () => {
+ useTabStore.getState().navigateActiveSession("/acme/issues/MUL-1");
+ useActiveIssueViewStore.getState().setActive(KEY, "a");
+ useTabStore.getState().navigateActiveSession("/acme/issues");
+
+ render(<ActiveIssuesPage />);
+
+ expect(shown()).toBe("a");
+ expect(activeUrl()).toBe("/acme/issues?view=a");
+ });
+
+ it("follows the URL back to the entry before a view was opened", () => {
+ render(<ActiveIssuesPage />);
+ act(() => {
+ useActiveIssueViewStore.getState().setActive(KEY, "a");
+ useTabStore.getState().navigateActiveSession("/acme/issues?view=a");
+ });
+ expect(shown()).toBe("a");
+
+ act(() => useTabStore.getState().goBack());
+
+ expect(activeUrl()).toBe("/acme/issues");
+ expect(shown()).toBe("none");
+ });
+});
diff --git a/apps/desktop/src/renderer/src/platform/issue-view-tabs.tsx b/apps/desktop/src/renderer/src/platform/issue-view-tabs.tsx
new file mode 100644
index 0000000000..09187613b6
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/issue-view-tabs.tsx
@@ -0,0 +1,81 @@
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ issueViewContainerKey,
+ useActiveIssueViewStore,
+} from "@multica/core/issue-views/active-view-store";
+import type { IssueViewScope } from "@multica/core/issue-views/queries";
+import { useNavigation } from "@multica/views/navigation";
+import { getActiveTab, useTabStore } from "@/stores/tab-store";
+
+const tabViews = new Map<string, Record<string, string>>();
+let shownTabId: string | null = null;
+let unsubscribe: (() => void) | null = null;
+
+/**
+ * Give every tab its own open views. The active-view store is one map for the
+ * whole window, so it is swapped with the active tab inside the tab store's
+ * subscription — zustand runs it synchronously in `set()`, before React
+ * renders the incoming tab — and each tab's map is parked here meanwhile.
+ * Memory only, like the store: a tab's `?view=` is what survives a restart.
+ */
+export function initIssueViewTabs(): void {
+ if (unsubscribe) return;
+ shownTabId = getActiveTab(useTabStore.getState())?.id ?? null;
+ unsubscribe = useTabStore.subscribe((state) => {
+ const nextId = getActiveTab(state)?.id ?? null;
+ if (nextId === shownTabId) return;
+ if (shownTabId) tabViews.set(shownTabId, useActiveIssueViewStore.getState().active);
+ shownTabId = nextId;
+ const open = new Set(Object.values(state.byWorkspace).flatMap((group) => group.tabs.map((tab) => tab.id)));
+ for (const id of tabViews.keys()) if (!open.has(id)) tabViews.delete(id);
+ useActiveIssueViewStore.setState({ active: (nextId && tabViews.get(nextId)) || {} });
+ });
+}
+
+export function __resetIssueViewTabsForTests(): void {
+ unsubscribe?.();
+ unsubscribe = null;
+ shownTabId = null;
+ tabViews.clear();
+}
+
+/**
+ * Desktop counterpart of web's useIssueViewUrlSync, around a page whose issue
+ * surface can open saved views. The tab's URL wins when the page mounts with
+ * a `?view=` (a cmd+clicked tab, a restored session) and on every later URL
+ * change (back/forward); the store writes back with replace otherwise, so the
+ * URL always names what the tab shows.
+ */
+export function IssueViewUrlSync({ scope, children }: { scope: IssueViewScope; children: React.ReactNode }) {
+ const wsId = useWorkspaceId();
+ const navigation = useNavigation();
+ const containerKey = issueViewContainerKey(wsId, scope);
+ const urlView = navigation.searchParams.get("view");
+ const activeViewId = useActiveIssueViewStore((s) => s.active[containerKey] ?? null);
+ const setActive = useActiveIssueViewStore((s) => s.setActive);
+ const seenUrlView = useRef<string | null | undefined>(undefined);
+ // Until the URL is adopted the store can still hold another surface's view;
+ // rendering against it would mount (and fetch) that view first.
+ const [adopting, setAdopting] = useState(() => urlView !== null && urlView !== activeViewId);
+
+ useLayoutEffect(() => {
+ const mounting = seenUrlView.current === undefined;
+ if (urlView === seenUrlView.current) return;
+ seenUrlView.current = urlView;
+ if (!mounting || urlView) setActive(containerKey, urlView);
+ setAdopting(false);
+ }, [containerKey, urlView, setActive]);
+
+ useEffect(() => {
+ const current = useActiveIssueViewStore.getState().active[containerKey] ?? null;
+ if (current === seenUrlView.current) return;
+ const params = new URLSearchParams(navigation.searchParams);
+ if (current) params.set("view", current);
+ else params.delete("view");
+ const search = params.toString();
+ navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}${navigation.hash}`);
+ }, [activeViewId, containerKey, navigation]);
+
+ return adopting ? null : children;
+}
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index e16c412e7a..8287060724 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -1,5 +1,5 @@
-import { useEffect } from "react";
-import { createMemoryRouter, Outlet, useMatches } from "react-router-dom";
+import { useEffect, useLayoutEffect } from "react";
+import { createMemoryRouter, Outlet, useLocation, useMatches } from "react-router-dom";
import type { RouteObject } from "react-router-dom";
import { IssueDetailPage } from "./pages/issue-detail-page";
import { ProjectDetailPage } from "./pages/project-detail-page";
@@ -28,6 +28,7 @@ import {
import { DesktopChooseRuntimePage } from "./components/desktop-choose-runtime-page";
import { AgentCreatedPage } from "./pages/agent-created-page";
import { SquadsPage, SquadDetailPage as SquadDetailPageView } from "@multica/views/squads/components";
+import { AllViewsPage } from "@multica/views/issue-views";
import { InboxPage } from "@multica/views/inbox";
import { ChatPage } from "@multica/views/chat";
import { SettingsPage } from "@multica/views/settings";
@@ -37,6 +38,11 @@ import { DaemonSettingsTab } from "./components/daemon-settings-tab";
import { UpdatesSettingsTab } from "./components/updates-settings-tab";
import { WorkspaceRouteLayout } from "./components/workspace-route-layout";
import { DesktopRouteErrorPage } from "./components/route-error-page";
+import { IssueViewUrlSync } from "./platform/issue-view-tabs";
+import { useRenderedRouteStore } from "./stores/rendered-route-store";
+
+const WORKSPACE_VIEW_SCOPE = { scope_type: "workspace" } as const;
+const MY_VIEW_SCOPE = { scope_type: "my" } as const;
/**
* Wraps `SettingsPage` so the desktop-only extra tabs can pull their labels
@@ -85,11 +91,25 @@ function TitleSync() {
return null;
}
+/**
+ * Publishes the committed pathname. A layout effect, so the shell's update
+ * lands in the same frame as the page it describes.
+ */
+function RenderedPathnameSync() {
+ const { pathname } = useLocation();
+ const setPathname = useRenderedRouteStore((s) => s.setPathname);
+ useLayoutEffect(() => {
+ setPathname(pathname);
+ }, [pathname, setPathname]);
+ return null;
+}
+
/** Wrapper that renders route children + TitleSync */
function PageShell() {
return (
<>
<TitleSync />
+ <RenderedPathnameSync />
<Outlet />
</>
);
@@ -130,7 +150,11 @@ export const appRoutes: RouteObject[] = [
{ index: true, element: null },
{
path: "issues",
- element: <IssuesPage />,
+ element: (
+ <IssueViewUrlSync scope={WORKSPACE_VIEW_SCOPE}>
+ <IssuesPage />
+ </IssueViewUrlSync>
+ ),
handle: { title: "Issues" },
},
{
@@ -160,7 +184,11 @@ export const appRoutes: RouteObject[] = [
},
{
path: "my-issues",
- element: <MyIssuesPage />,
+ element: (
+ <IssueViewUrlSync scope={MY_VIEW_SCOPE}>
+ <MyIssuesPage />
+ </IssueViewUrlSync>
+ ),
handle: { title: "My Issues" },
},
{
@@ -221,6 +249,7 @@ export const appRoutes: RouteObject[] = [
handle: { title: "Member" },
},
{ path: "squads", element: <SquadsPage />, handle: { title: "Squads" } },
+ { path: "views", element: <AllViewsPage />, handle: { title: "Views" } },
{
path: "squads/:id",
element: <SquadDetailPageView />,
diff --git a/apps/desktop/src/renderer/src/stores/rendered-route-store.ts b/apps/desktop/src/renderer/src/stores/rendered-route-store.ts
new file mode 100644
index 0000000000..cb81764875
--- /dev/null
+++ b/apps/desktop/src/renderer/src/stores/rendered-route-store.ts
@@ -0,0 +1,18 @@
+import { create } from "zustand";
+
+/**
+ * The pathname of the page the router has actually committed. The tab
+ * session URL moves first and the router renders the new page in a
+ * transition, so for a few frames the session already points at the next
+ * page while the previous one is still on screen. Shell chrome that has to
+ * line up with the page (the space panel, list columns) reads this instead.
+ */
+interface RenderedRouteStore {
+ pathname: string | null;
+ setPathname: (pathname: string) => void;
+}
+
+export const useRenderedRouteStore = create<RenderedRouteStore>((set) => ({
+ pathname: null,
+ setPathname: (pathname) => set({ pathname }),
+}));
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
index 3a758856c5..b431b2681a 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
@@ -63,6 +63,20 @@ describe("resourceKeyForUrl", () => {
expect(resourceKeyForUrl("/acme/issues#anchor")).toBe("/acme/issues");
expect(resourceKeyForUrl("/acme/issues?filter=a#x")).toBe("/acme/issues");
});
+
+ it("keeps the saved view a URL opens, and nothing else of its search", () => {
+ expect(resourceKeyForUrl("/acme/issues?view=v1")).toBe("/acme/issues?view=v1");
+ expect(resourceKeyForUrl("/acme/issues?filter=a&view=v1#x")).toBe("/acme/issues?view=v1");
+ expect(resourceKeyForUrl("/acme/issues#view=v1")).toBe("/acme/issues");
+ });
+
+ it("keeps the built-in scope a URL opens, unless a saved view names the list", () => {
+ expect(resourceKeyForUrl("/acme/my-issues?scope=agents")).toBe("/acme/my-issues?scope=agents");
+ expect(resourceKeyForUrl("/acme/my-issues?filter=a&scope=agents#x")).toBe(
+ "/acme/my-issues?scope=agents",
+ );
+ expect(resourceKeyForUrl("/acme/my-issues?scope=agents&view=v1")).toBe("/acme/my-issues?view=v1");
+ });
});
describe("browsingHistoryKeyForUrl", () => {
@@ -266,6 +280,40 @@ describe("useTabStore actions", () => {
expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
});
+ it("openTab of another saved view opens its own tab; the same view focuses it", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.navigateActiveSession("/acme/issues?view=a");
+ const viewA = getActiveTab(useTabStore.getState())!.id;
+
+ const viewB = store.openTab("/acme/issues?view=b", "B");
+ const allIssues = store.openTab("/acme/issues", "Issues");
+ const viewAgain = store.openTab("/acme/issues?view=a&filter=urgent", "A");
+
+ const urls = useTabStore.getState().byWorkspace.acme.tabs.map((t) => t.url);
+ expect(new Set([viewA, viewB, allIssues]).size).toBe(3);
+ expect(viewAgain).toBe(viewA);
+ expect(urls).toEqual(expect.arrayContaining(["/acme/issues?view=a", "/acme/issues?view=b", "/acme/issues"]));
+ });
+
+ it("openTab of My agents' work opens beside My issues; reopening either focuses it", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.navigateActiveSession("/acme/my-issues");
+ const myIssues = getActiveTab(useTabStore.getState())!.id;
+
+ const myAgents = store.openTab("/acme/my-issues?scope=agents", "My agents' work");
+ const myIssuesAgain = store.openTab("/acme/my-issues", "My issues");
+ const myAgentsAgain = store.openTab("/acme/my-issues?scope=agents&filter=urgent", "My agents' work");
+
+ expect(myAgents).not.toBe(myIssues);
+ expect(myIssuesAgain).toBe(myIssues);
+ expect(myAgentsAgain).toBe(myAgents);
+ expect(useTabStore.getState().byWorkspace.acme.tabs.map((t) => t.url)).toEqual(
+ expect.arrayContaining(["/acme/my-issues", "/acme/my-issues?scope=agents"]),
+ );
+ });
+
describe("openTab insertion position (MUL-5860)", () => {
const urls = () =>
useTabStore.getState().byWorkspace.acme.tabs.map((t) => t.url);
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index 251fa9bd63..b545be6e9a 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -309,9 +309,25 @@ export function splitTabUrl(url: string): { pathname: string; suffix: string } {
return { pathname: url.slice(0, cut), suffix: url.slice(cut) };
}
-/** Dedup identity of a tab URL: its pathname (search/hash are view state). */
+/**
+ * Dedup identity of a tab URL: its pathname (search/hash are view state),
+ * plus the list it opens — `?view=` names a saved view and `?scope=` a
+ * built-in one (My agents' work), so cmd+clicking list B from a tab showing
+ * list A must open B, not focus A. A saved view carries its own scope.
+ */
export function resourceKeyForUrl(url: string): string {
- return splitTabUrl(url).pathname;
+ const { pathname, suffix } = splitTabUrl(url);
+ const params = searchParamsOfSuffix(suffix);
+ const view = params.get("view");
+ if (view) return `${pathname}?view=${encodeURIComponent(view)}`;
+ const scope = params.get("scope");
+ return scope ? `${pathname}?scope=${encodeURIComponent(scope)}` : pathname;
+}
+
+function searchParamsOfSuffix(suffix: string): URLSearchParams {
+ if (!suffix.startsWith("?")) return new URLSearchParams();
+ const hashIndex = suffix.indexOf("#");
+ return new URLSearchParams(hashIndex === -1 ? suffix.slice(1) : suffix.slice(1, hashIndex));
}
/**
@@ -330,11 +346,8 @@ function inboxSelectionKeyForUrl(url: string): string | null {
const { pathname, suffix } = splitTabUrl(url);
const segments = pathname.split("/").filter(Boolean);
if (segments.length !== 2 || segments[1] !== "inbox") return null;
- if (!suffix.startsWith("?")) return null;
- const hashIndex = suffix.indexOf("#");
- const search = hashIndex === -1 ? suffix.slice(1) : suffix.slice(1, hashIndex);
- const selectedKey = new URLSearchParams(search).get("issue");
+ const selectedKey = searchParamsOfSuffix(suffix).get("issue");
if (!selectedKey) return null;
return `${pathname}?issue=${encodeURIComponent(selectedKey)}`;
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
index c16ea0a329..95e0e1c212 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/layout.tsx
@@ -3,7 +3,7 @@
import { Suspense } from "react";
import { DashboardLayout } from "@multica/views/layout";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
-import { SearchCommand, SearchTrigger } from "@multica/views/search";
+import { SearchCommand } from "@multica/views/search";
import { FloatingChat } from "@multica/views/chat/floating-chat";
import { WebNotificationBridge } from "@/components/web-notification-bridge";
import { WorkspaceDocumentTitle } from "@/platform/workspace-document-title";
@@ -19,7 +19,6 @@ export default function Layout({ children }: { children: React.ReactNode }) {
</Suspense>
<DashboardLayout
loadingIndicator={<MulticaIcon className="size-6" />}
- searchSlot={<SearchTrigger />}
extra={
<>
<SearchCommand />
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/projects/[id]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/projects/[id]/page.tsx
index 76ea0c2820..8c0e50b653 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/projects/[id]/page.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/projects/[id]/page.tsx
@@ -1,7 +1,14 @@
"use client";
-import { use } from "react";
+import { Suspense, use } from "react";
import { ProjectDetail } from "@multica/views/projects/components";
+import { useIssueViewUrlSync } from "../../../../../platform/use-issue-view-url-sync";
+
+function IssueViewUrlSync({ projectId }: { projectId: string }) {
+ // useSearchParams requires a Suspense boundary in the app router.
+ useIssueViewUrlSync({ scope_type: "project", scope_id: projectId });
+ return null;
+}
export default function ProjectDetailPage({
params,
@@ -9,5 +16,12 @@ export default function ProjectDetailPage({
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
- return <ProjectDetail projectId={id} />;
+ return (
+ <>
+ <Suspense fallback={null}>
+ <IssueViewUrlSync projectId={id} />
+ </Suspense>
+ <ProjectDetail projectId={id} />
+ </>
+ );
}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/views/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/views/page.tsx
new file mode 100644
index 0000000000..e241cf066e
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/views/page.tsx
@@ -0,0 +1 @@
+export { AllViewsPage as default } from "@multica/views/issue-views";
diff --git a/apps/web/config/google-analytics.ts b/apps/web/config/google-analytics.ts
index 762c9e275f..c16785b1e4 100644
--- a/apps/web/config/google-analytics.ts
+++ b/apps/web/config/google-analytics.ts
@@ -89,6 +89,7 @@ const WORKSPACE_SECTIONS = new Set([
"skills",
"squads",
"usage",
+ "views",
]);
/**
diff --git a/e2e/auth.spec.ts b/e2e/auth.spec.ts
index d873aac69c..5e78d8550a 100644
--- a/e2e/auth.spec.ts
+++ b/e2e/auth.spec.ts
@@ -1,5 +1,5 @@
import { test, expect } from "@playwright/test";
-import { createTestApi, loginAsDefault, openWorkspaceMenu, waitForPageText } from "./helpers";
+import { createTestApi, loginAsDefault, openAccountMenu, waitForPageText } from "./helpers";
test.describe("Authentication", () => {
test("login page renders correctly", async ({ page }) => {
@@ -16,7 +16,7 @@ test.describe("Authentication", () => {
const workspaceSlug = await loginAsDefault(page);
await expect(page).toHaveURL(new RegExp(`/${workspaceSlug}/issues$`));
- await expect(page.getByRole("button", { name: "New Issue" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "New Issue" }).first()).toBeVisible();
});
test("unauthenticated user is redirected to /login", async ({ page }) => {
@@ -35,7 +35,7 @@ test.describe("Authentication", () => {
await loginAsDefault(page);
// Open the workspace dropdown menu
- await openWorkspaceMenu(page);
+ await openAccountMenu(page);
await page.getByRole("menuitem", { name: "Log out" }).click();
diff --git a/e2e/helpers.ts b/e2e/helpers.ts
index ecac9e45f4..72dfaa0873 100644
--- a/e2e/helpers.ts
+++ b/e2e/helpers.ts
@@ -8,8 +8,8 @@ const DEFAULT_E2E_EMAIL = `e2e-${E2E_WORKER}-${E2E_RUN_ID}@multica.ai`;
const DEFAULT_E2E_WORKSPACE = `e2e-workspace-${E2E_WORKER}-${E2E_RUN_ID}`;
async function waitForIssuesPage(page: Page) {
- await waitForPageText(page, "New Issue");
- await expect(page.getByRole("button", { name: "New Issue" })).toBeVisible({
+ // The Issues panel's create button is icon-only; its label is the name.
+ await expect(page.getByRole("button", { name: "New Issue" }).first()).toBeVisible({
timeout: 15000,
});
}
@@ -80,11 +80,21 @@ export async function preferManualCreateMode(page: Page) {
await waitForIssuesPage(page);
}
-export async function openWorkspaceMenu(page: Page) {
- // Click the workspace switcher button (has ChevronDown icon)
- const workspaceButton = page.getByRole("button", { name: /E2E Workspace/ }).first();
- await expect(workspaceButton).toBeVisible({ timeout: 15000 });
- await workspaceButton.click();
- // Wait for dropdown to appear
- await expect(page.locator('[class*="popover"]')).toBeVisible();
+/** The app rail: workspace tiles, spaces, and the account menu. */
+export function appRail(page: Page) {
+ return page.getByRole("navigation", { name: "App navigation" });
+}
+
+/** The current workspace's tile in the rail; its accessible name is the workspace name. */
+export function currentWorkspaceTile(page: Page) {
+ return appRail(page)
+ .getByRole("link", { name: /E2E Workspace|Renamed WS/ })
+ .and(page.locator('[aria-current="page"]'));
+}
+
+export async function openAccountMenu(page: Page) {
+ const accountButton = appRail(page).getByRole("button", { name: "Account" });
+ await expect(accountButton).toBeVisible({ timeout: 15000 });
+ await accountButton.click();
+ await expect(page.getByRole("menu")).toBeVisible();
}
diff --git a/e2e/issue-filter-advanced.spec.ts b/e2e/issue-filter-advanced.spec.ts
new file mode 100644
index 0000000000..afa8bf8a01
--- /dev/null
+++ b/e2e/issue-filter-advanced.spec.ts
@@ -0,0 +1,174 @@
+import { expect, test, type Page } from "@playwright/test";
+import { createTestApi, loginAsDefault } from "./helpers";
+import type { TestApiClient } from "./fixtures";
+
+// Menu search, the due-date dimension and advanced mode, end to end: menu or
+// panel → store → table query → SQL. SHOTS_DIR, when set, collects screenshots.
+
+async function visibleIssueTitles(page: Page, titles: string[]) {
+ const present: string[] = [];
+ for (const title of titles) {
+ if (await page.getByText(title, { exact: true }).first().isVisible()) {
+ present.push(title);
+ }
+ }
+ return present.sort();
+}
+
+async function shot(page: Page, name: string) {
+ const dir = process.env.SHOTS_DIR;
+ if (!dir) return;
+ // Let menus and tooltips finish their enter/exit transitions.
+ await page.waitForTimeout(400);
+ await page.screenshot({ path: `${dir}/${name}.png` });
+}
+
+async function closeMenus(page: Page) {
+ await page.keyboard.press("Escape");
+ await page.keyboard.press("Escape");
+}
+
+function localDate(offsetDays: number) {
+ const d = new Date();
+ d.setDate(d.getDate() + offsetDays);
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+}
+
+test.describe("Issue filter: search, due date, advanced", () => {
+ let api: TestApiClient;
+ const suffix = Date.now().toString(36);
+ const urgentLate = `adv urgent late ${suffix}`;
+ const urgentUndated = `adv urgent undated ${suffix}`;
+ const lowLate = `adv low late ${suffix}`;
+ const lowUndated = `adv low undated ${suffix}`;
+ const mediumLate = `adv medium late ${suffix}`;
+ const all = [urgentLate, urgentUndated, lowLate, lowUndated, mediumLate];
+
+ test.beforeEach(async ({ page }) => {
+ api = await createTestApi();
+ const yesterday = localDate(-1);
+ await api.createIssue(urgentLate, { priority: "urgent", due_date: yesterday });
+ await api.createIssue(urgentUndated, { priority: "urgent" });
+ await api.createIssue(lowLate, { priority: "low", due_date: yesterday });
+ await api.createIssue(lowUndated, { priority: "low" });
+ await api.createIssue(mediumLate, { priority: "medium", due_date: yesterday });
+ await loginAsDefault(page);
+ });
+
+ test.afterEach(async () => {
+ await api.cleanup();
+ });
+
+ test("search adds a value as a condition; due date filters by bucket", async ({ page }) => {
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
+
+ await page.getByRole("button", { name: "Filter", exact: true }).click();
+ await page.getByRole("textbox", { name: "Filter by field or value…" }).fill("urg");
+ const urgentRow = page.getByRole("menuitemcheckbox", { name: /Priority\s*is\s*Urgent/ });
+ await expect(urgentRow).toBeVisible();
+ await shot(page, "01-search");
+ await urgentRow.click();
+ await closeMenus(page);
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([urgentLate, urgentUndated].sort());
+
+ await page.getByRole("button", { name: "1 filter" }).click();
+ await page.getByRole("menuitem", { name: /^Due date/ }).click();
+ await page.getByRole("menuitemcheckbox", { name: "Overdue" }).click();
+ await shot(page, "02-due-date");
+ await closeMenus(page);
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([urgentLate]);
+ });
+
+ test("advanced mode ORs inside a group and switches back only when simple can say it", async ({ page }) => {
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
+
+ // Start from a simple filter: due date is overdue.
+ await page.getByRole("button", { name: "Filter", exact: true }).click();
+ await page.getByRole("menuitem", { name: /^Due date/ }).click();
+ await page.getByRole("menuitemcheckbox", { name: "Overdue" }).click();
+ await closeMenus(page);
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([lowLate, mediumLate, urgentLate].sort());
+
+ // Switching carries it over as the first rule.
+ await page.getByRole("button", { name: "1 filter" }).click();
+ await page.getByRole("menuitem", { name: /Switch to advanced filter/ }).click();
+ const panel = page.getByTestId("advanced-filter-panel");
+ await expect(panel).toBeVisible();
+ await expect(panel.getByTestId("advanced-filter-row")).toHaveCount(1);
+ await expect(panel.getByRole("button", { name: "Switch to simple filter" })).toBeEnabled();
+
+ // AND (priority is urgent OR priority is low), as a group.
+ await panel.getByRole("button", { name: "Add condition group" }).click();
+ await page.getByRole("menuitem", { name: "Priority" }).click();
+ const group = panel.getByTestId("advanced-filter-group");
+ await expect(group).toBeVisible();
+ await group.getByRole("button", { name: "Values" }).first().click();
+ await page.getByRole("menuitemcheckbox", { name: "Urgent" }).click();
+ await page.keyboard.press("Escape");
+ await group.getByRole("button", { name: "Add condition" }).click();
+ await page.getByRole("menuitem", { name: "Priority" }).click();
+ await group.getByRole("button", { name: "Values" }).nth(1).click();
+ await page.getByRole("menuitemcheckbox", { name: "Low" }).click();
+ await page.keyboard.press("Escape");
+
+ await expect(panel).toBeVisible();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([lowLate, urgentLate].sort());
+ await expect(panel.getByRole("button", { name: "Switch to simple filter" })).toBeDisabled();
+ await expect(panel.getByText(/Simple filters can't show groups/)).toBeVisible();
+ await shot(page, "03-advanced");
+
+ // The trigger names the mode; the chip bar carries the tree as one chip.
+ await page.keyboard.press("Escape");
+ await expect(panel).toBeHidden();
+ await expect(page.getByRole("button", { name: "Advanced filter" })).toBeVisible();
+ await page.mouse.move(600, 400);
+ await shot(page, "04-advanced-closed");
+
+ // Delete the group: one overdue rule is a simple filter again.
+ await page.getByRole("button", { name: "Advanced filter" }).click();
+ await expect(panel).toBeVisible();
+ await group.getByRole("button", { name: "Condition actions" }).last().click();
+ await page.getByRole("menuitem", { name: "Delete group" }).click();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([lowLate, mediumLate, urgentLate].sort());
+ await panel.getByRole("button", { name: "Switch to simple filter" }).click();
+ await expect(panel).toBeHidden();
+ await expect(page.getByRole("button", { name: "1 filter" })).toBeVisible();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([lowLate, mediumLate, urgentLate].sort());
+ });
+
+ test("custom properties are conditions like any other field", async ({ page }) => {
+ const property = await api.createProperty(`Estimate ${suffix}`, "number");
+ await page.reload();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
+
+ await page.getByRole("button", { name: "Filter", exact: true }).click();
+ await page.getByRole("menuitem", { name: /Switch to advanced filter/ }).click();
+ const panel = page.getByTestId("advanced-filter-panel");
+ await panel.getByRole("button", { name: "Add condition", exact: true }).click();
+ await page.getByRole("menuitem", { name: "Priority" }).click();
+ await panel.getByRole("button", { name: "Values" }).first().click();
+ await page.getByRole("menuitemcheckbox", { name: "Urgent" }).click();
+ await page.keyboard.press("Escape");
+
+ await panel.getByRole("button", { name: "Add condition", exact: true }).click();
+ await expect(page.getByRole("menuitem", { name: property.name })).toBeVisible();
+ await shot(page, "05-advanced-field-picker");
+ await page.getByRole("menuitem", { name: property.name }).click();
+ await panel.getByRole("button", { name: "Values" }).nth(1).click();
+ await page.getByRole("menuitemcheckbox", { name: "No value" }).click();
+ await page.keyboard.press("Escape");
+
+ const rows = panel.getByTestId("advanced-filter-row");
+ await expect(rows).toHaveCount(2);
+ await expect(rows.nth(1)).toContainText(property.name);
+ await expect(panel.getByRole("button", { name: "Add property filter" })).toHaveCount(0);
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([urgentLate, urgentUndated].sort());
+ await shot(page, "06-advanced-properties");
+
+ await panel.getByRole("button", { name: "Clear all" }).click();
+ await expect(rows).toHaveCount(0);
+ await expect(panel.getByRole("button", { name: "Clear all" })).toBeDisabled();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
+ });
+});
diff --git a/e2e/issue-filter-negation.spec.ts b/e2e/issue-filter-negation.spec.ts
new file mode 100644
index 0000000000..7c99165a72
--- /dev/null
+++ b/e2e/issue-filter-negation.spec.ts
@@ -0,0 +1,71 @@
+import { expect, test, type Page } from "@playwright/test";
+import { createTestApi, loginAsDefault } from "./helpers";
+import type { TestApiClient } from "./fixtures";
+
+// "Is not" flips one dimension to its complement. The list surface is
+// server-driven, so this exercises menu → store → table query → SQL predicate.
+
+async function visibleIssueTitles(page: Page, titles: string[]) {
+ const present: string[] = [];
+ for (const title of titles) {
+ if (await page.getByText(title, { exact: true }).first().isVisible()) {
+ present.push(title);
+ }
+ }
+ return present.sort();
+}
+
+async function closeMenus(page: Page) {
+ await page.keyboard.press("Escape");
+ await page.keyboard.press("Escape");
+}
+
+test.describe("Issue filter: is not", () => {
+ let api: TestApiClient;
+ const suffix = Date.now().toString(36);
+ const high = `negate high ${suffix}`;
+ const low = `negate low ${suffix}`;
+ const none = `negate none ${suffix}`;
+ const all = [high, low, none];
+
+ test.beforeEach(async ({ page }) => {
+ api = await createTestApi();
+ await api.createIssue(high, { priority: "high" });
+ await api.createIssue(low, { priority: "low" });
+ await api.createIssue(none);
+ await loginAsDefault(page);
+ });
+
+ test.afterEach(async () => {
+ await api.cleanup();
+ });
+
+ test("excludes the selected values and keeps everything else", async ({ page }) => {
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
+
+ await page.getByRole("button", { name: "Filter", exact: true }).click();
+ await page.getByRole("menuitem", { name: "Priority" }).click();
+ await page.getByRole("menuitemcheckbox", { name: "High" }).click();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([high]);
+
+ // Flipping the operator keeps the selection open and inverts it, issues
+ // without a priority included.
+ await page.getByRole("menuitemradio", { name: "is not" }).click();
+ await expect(page.getByRole("menuitemcheckbox", { name: "High" })).toBeVisible();
+ await closeMenus(page);
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([low, none].sort());
+
+ // The dimension row reads as a sentence: "Priority is not High".
+ await page.getByRole("button", { name: "1 filter" }).click();
+ const row = page.getByRole("menuitem", { name: /^Priority\s*is not\s*High/ });
+ await expect(row).toBeVisible();
+ // An Escape that lands while the menu is still opening is dropped.
+ await expect(async () => {
+ await page.keyboard.press("Escape");
+ await expect(row).toBeHidden({ timeout: 1000 });
+ }).toPass();
+
+ await page.getByRole("button", { name: "Reset" }).click();
+ await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
+ });
+});
diff --git a/e2e/issues.spec.ts b/e2e/issues.spec.ts
index 08ea1d8dca..f0f78a0a6d 100644
--- a/e2e/issues.spec.ts
+++ b/e2e/issues.spec.ts
@@ -136,7 +136,7 @@ test.describe("Issues", () => {
test("can create a new issue", async ({ page }) => {
await preferManualCreateMode(page);
- const newIssueButton = page.getByRole("button", { name: "New Issue" });
+ const newIssueButton = page.getByRole("button", { name: "New Issue" }).first();
await expect(newIssueButton).toBeVisible();
await newIssueButton.click();
@@ -188,7 +188,7 @@ test.describe("Issues", () => {
test("can dismiss issue creation", async ({ page }) => {
await preferManualCreateMode(page);
- await page.getByRole("button", { name: "New Issue" }).click();
+ await page.getByRole("button", { name: "New Issue" }).first().click();
const titleInput = page.getByRole("textbox", { name: "Issue title" });
await expect(titleInput).toBeVisible();
@@ -196,6 +196,6 @@ test.describe("Issues", () => {
await page.keyboard.press("Escape");
await expect(titleInput).not.toBeVisible();
- await expect(page.getByRole("button", { name: "New Issue" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "New Issue" }).first()).toBeVisible();
});
});
diff --git a/e2e/local-search.spec.ts b/e2e/local-search.spec.ts
index 213b7007f0..9ce418f98c 100644
--- a/e2e/local-search.spec.ts
+++ b/e2e/local-search.spec.ts
@@ -1,6 +1,6 @@
import { expect, test, type Page, type Response } from "@playwright/test";
import { TestApiClient } from "./fixtures";
-import { createTestApi, loginAsDefault, openWorkspaceMenu } from "./helpers";
+import { createTestApi, loginAsDefault, openAccountMenu } from "./helpers";
// Web search answers from the local search index once it has synced
// (MUL-7754): results match server search, follow writes made elsewhere, and
@@ -102,7 +102,7 @@ test.describe("Local search index", () => {
await synced;
await expect.poll(() => searchIndexDatabases(page)).toHaveLength(1);
- await openWorkspaceMenu(page);
+ await openAccountMenu(page);
await page.getByRole("menuitem", { name: "Log out" }).click();
await page.waitForURL("**/login", { timeout: 10_000, waitUntil: "domcontentloaded" });
diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts
index 553832e5d8..57f6428ad0 100644
--- a/e2e/navigation.spec.ts
+++ b/e2e/navigation.spec.ts
@@ -1,5 +1,5 @@
import { test, expect } from "@playwright/test";
-import { loginAsDefault, waitForPageText } from "./helpers";
+import { appRail, loginAsDefault, waitForPageText } from "./helpers";
const ROUTE_CHANGE_TIMEOUT = 30000;
@@ -9,26 +9,28 @@ test.describe("Navigation", () => {
await page.waitForLoadState("networkidle");
});
- test("sidebar navigation works", async ({ page }) => {
- await page.getByRole("link", { name: "Inbox" }).click();
+ test("rail navigation works", async ({ page }) => {
+ const rail = appRail(page);
+ await rail.getByRole("link", { name: "Inbox" }).click();
await expect(page).toHaveURL(/\/inbox/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Inbox");
// Each destination renames the browser tab after itself (MUL-6222).
await expect(page).toHaveTitle("Inbox | Multica");
- await page.getByRole("link", { name: "Agents" }).click();
+ // Team lands on its first page, Agents.
+ await rail.getByRole("link", { name: "Team" }).click();
await expect(page).toHaveURL(/\/agents/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Agents");
await expect(page).toHaveTitle("Agents | Multica");
- await page.getByRole("link", { name: "Issues", exact: true }).click();
+ await rail.getByRole("link", { name: "Issues", exact: true }).click();
await expect(page).toHaveURL(/\/issues/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Issues");
await expect(page).toHaveTitle("Issues | Multica");
});
- test("settings page loads via sidebar", async ({ page }) => {
- await page.getByRole("link", { name: "Settings", exact: true }).click();
+ test("settings page loads via the rail", async ({ page }) => {
+ await appRail(page).getByRole("link", { name: "Settings", exact: true }).click();
await expect(page).toHaveURL(/\/settings/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Settings");
@@ -37,7 +39,7 @@ test.describe("Navigation", () => {
});
test("agents page shows agent list", async ({ page }) => {
- await page.getByRole("link", { name: "Agents" }).click();
+ await appRail(page).getByRole("link", { name: "Team" }).click();
await expect(page).toHaveURL(/\/agents/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Agents");
diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts
index 8b8a2feee3..a0f5d22877 100644
--- a/e2e/settings.spec.ts
+++ b/e2e/settings.spec.ts
@@ -1,15 +1,16 @@
import { test, expect } from "@playwright/test";
-import { loginAsDefault, waitForPageText } from "./helpers";
+import { appRail, currentWorkspaceTile, loginAsDefault, waitForPageText } from "./helpers";
test.describe("Settings", () => {
- test("updating workspace name reflects in sidebar immediately", async ({
+ test("updating workspace name reflects in the rail immediately", async ({
page,
}) => {
const workspaceSlug = await loginAsDefault(page);
- // Read the current workspace name from the sidebar
- const sidebarName = page.getByRole("button", { name: /E2E Workspace/ }).first();
- const originalName = (await sidebarName.innerText()).split("\n").pop()?.trim() ?? "E2E Workspace";
+ // Read the current workspace name from its rail tile
+ const tile = currentWorkspaceTile(page);
+ await expect(tile).toBeVisible({ timeout: 15000 });
+ const originalName = (await tile.getAttribute("aria-label")) ?? "E2E Workspace";
await page.goto(`/${workspaceSlug}/settings?tab=workspace`, { waitUntil: "domcontentloaded" });
await waitForPageText(page, "General");
@@ -27,15 +28,15 @@ test.describe("Settings", () => {
await expect(page.getByText("Workspace settings saved").first()).toBeVisible({ timeout: 5000 });
- // Sidebar should reflect the new name WITHOUT page refresh
- await expect(page.getByRole("button", { name: new RegExp(newName) }).first()).toBeVisible();
+ // The rail should reflect the new name WITHOUT page refresh
+ await expect(appRail(page).getByRole("link", { name: newName })).toBeVisible();
// Restore original name so other tests aren't affected
await nameInput.clear();
await nameInput.fill(originalName.trim());
await page.locator("button", { hasText: "Save" }).click();
await expect(page.getByText("Workspace settings saved").first()).toBeVisible({ timeout: 5000 });
- await expect(page.getByRole("button", { name: new RegExp(originalName) }).first()).toBeVisible();
+ await expect(appRail(page).getByRole("link", { name: originalName })).toBeVisible();
});
// Composio connect flow, fully mocked at the network boundary so it runs
diff --git a/packages/core/agents/stores/view-store.test.ts b/packages/core/agents/stores/view-store.test.ts
index c53b617021..eaebe78de2 100644
--- a/packages/core/agents/stores/view-store.test.ts
+++ b/packages/core/agents/stores/view-store.test.ts
@@ -26,7 +26,7 @@ beforeAll(() => {
beforeEach(() => {
localStorage.clear();
- useAgentsViewStore.setState({ scope: "mine", search: "" });
+ useAgentsViewStore.setState({ scope: "mine" });
setCurrentWorkspace(null, null);
});
@@ -226,41 +226,35 @@ describe("useAgentsViewStore", () => {
expect(useAgentsViewStore.getState().hiddenColumns).toEqual(["model"]);
});
- });
- describe("search (session-only)", () => {
- it("keeps the query in the store but never persists it", async () => {
+ it("moves a v1 payload still on the old default to the new default", async () => {
+ localStorage.setItem(
+ "multica_agents_view:acme",
+ JSON.stringify({ state: { hiddenColumns: ["created"] }, version: 1 }),
+ );
+
setCurrentWorkspace("acme", "ws_a");
await flush();
- useAgentsViewStore.getState().setSearch("reviewer");
await flush();
- expect(useAgentsViewStore.getState().search).toBe("reviewer");
- const raw = localStorage.getItem("multica_agents_view:acme");
- expect(raw).not.toBeNull();
- expect(JSON.parse(raw as string).state).not.toHaveProperty("search");
+ expect(useAgentsViewStore.getState().hiddenColumns).toEqual([
+ "owner",
+ "access",
+ "created",
+ ]);
});
- it("clears the query on workspace switch", async () => {
+ it("keeps a customised v1 column choice", async () => {
localStorage.setItem(
- "multica_agents_view:beta",
- JSON.stringify({ state: { scope: "all" }, version: 1 }),
+ "multica_agents_view:acme",
+ JSON.stringify({ state: { hiddenColumns: ["created", "runs"] }, version: 1 }),
);
- setCurrentWorkspace("acme", "ws_a");
- await flush();
- await flush();
- useAgentsViewStore.getState().setSearch("reviewer");
- setCurrentWorkspace("beta", "ws_b");
+ setCurrentWorkspace("acme", "ws_a");
await flush();
await flush();
- expect(useAgentsViewStore.getState().search).toBe("");
- useAgentsViewStore.getState().setSearch("reviewer");
- setCurrentWorkspace("gamma", "ws_c");
- await flush();
- await flush();
- expect(useAgentsViewStore.getState().search).toBe("");
+ expect(useAgentsViewStore.getState().hiddenColumns).toEqual(["created", "runs"]);
});
});
});
diff --git a/packages/core/agents/stores/view-store.ts b/packages/core/agents/stores/view-store.ts
index 73f5208132..6d8396cd7e 100644
--- a/packages/core/agents/stores/view-store.ts
+++ b/packages/core/agents/stores/view-store.ts
@@ -1,20 +1,16 @@
"use client";
-import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
import {
- createWorkspaceAwareStorage,
- registerForWorkspaceRehydration,
-} from "../../platform/workspace-storage";
-import { defaultStorage } from "../../platform/storage";
+ createCollectionViewStore,
+ type CollectionSortDirection,
+ type CollectionViewCore,
+} from "../../collections/view-store";
import type { AccessScope } from "../effective-access";
// View preferences for the agents list page: scope, sort, column visibility,
// and filters. Persisted per workspace, per user/device. Row selection is
// session-scoped on purpose (same rationale as the skills/autopilots view
-// stores). The search query lives here too but is session-only (never
-// persisted): it must survive opening an agent and coming back to the list,
-// yet a stale query restored days later would read as "my agents vanished".
+// stores).
// Scope mixes the ownership lens (mine/all) with the archived lifecycle
// stage. Impure on paper, but the three are mutually exclusive in practice
@@ -27,7 +23,7 @@ export const AGENT_SCOPES: AgentsScope[] = ["mine", "all", "archived"];
export type AgentSortField = "lastActive" | "name" | "runs" | "created";
-export type AgentSortDirection = "asc" | "desc";
+export type AgentSortDirection = CollectionSortDirection;
/** Per-field direction applied when the user switches TO that field. */
export const AGENT_SORT_DEFAULT_DIRECTION: Record<
@@ -78,145 +74,75 @@ export type AgentColumnKey =
| "model"
| "created";
-/** Created is opt-in: hidden until the user enables it. Owner and model are
- * shown by default — comparing which model each agent runs is a core use of
- * the list (GitHub #9500). */
-export const AGENT_DEFAULT_HIDDEN_COLUMNS: AgentColumnKey[] = ["created"];
-
-/** Persist schema version. v0 hid the model column by default; v1 shows it. */
-const AGENT_VIEW_STORE_VERSION = 1;
-
-export interface AgentsViewState {
+/** Model stays on by default — comparing which model each agent runs is a
+ * core use of the list (GitHub #9500). Owner, access and created are opt-in
+ * so the default columns fit a 1280px window without horizontal scrolling;
+ * owner is also constant in the default "mine" scope. */
+export const AGENT_DEFAULT_HIDDEN_COLUMNS: AgentColumnKey[] = [
+ "owner",
+ "access",
+ "created",
+];
+
+/** Persist schema version. v0 hid the model column by default; v1 shows it;
+ * v2 also hides owner and access by default. */
+const AGENT_VIEW_STORE_VERSION = 2;
+
+export interface AgentsViewState
+ extends CollectionViewCore<AgentSortField, AgentColumnKey, AgentListFilters> {
scope: AgentsScope;
- sortField: AgentSortField;
- sortDirection: AgentSortDirection;
- hiddenColumns: AgentColumnKey[];
- filters: AgentListFilters;
- /** Free-text list search. Session-only — excluded from persistence. */
- search: string;
- setSearch: (search: string) => void;
setScope: (scope: AgentsScope) => void;
- /** Header click: toggles direction on the active field, otherwise switches
- * to the field with its default direction. */
- toggleSort: (field: AgentSortField) => void;
- /** Display panel select: switches field (default direction), no toggle. */
- setSortField: (field: AgentSortField) => void;
- setSortDirection: (direction: AgentSortDirection) => void;
- toggleColumn: (key: AgentColumnKey) => void;
- toggleFilter: (key: keyof AgentListFilters, value: string) => void;
- clearFilters: () => void;
}
-const DEFAULTS = {
+export const useAgentsViewStore = createCollectionViewStore<
+ AgentSortField,
+ AgentColumnKey,
+ AgentListFilters,
+ { scope: AgentsScope },
+ { setScope: (scope: AgentsScope) => void }
+>({
+ name: "multica_agents_view",
+ version: AGENT_VIEW_STORE_VERSION,
+ // v0 → v1: model went from hidden-by-default to shown-by-default. Every v0
+ // payload carried "model" in hiddenColumns unless the user had turned it
+ // on, so un-hide it once; the user can re-hide it from the Display panel.
+ // v1 → v2: a payload still on the v1 default (only "created" hidden) moves
+ // to the new default; any other column choice is the user's and stays.
+ // Other persisted prefs pass through untouched.
+ migrate: (persisted, version) => {
+ let p = (persisted ?? {}) as Partial<AgentsViewState>;
+ if (version < 1 && Array.isArray(p.hiddenColumns)) {
+ p = { ...p, hiddenColumns: p.hiddenColumns.filter((k) => k !== "model") };
+ }
+ if (
+ version < 2 &&
+ Array.isArray(p.hiddenColumns) &&
+ p.hiddenColumns.length === 1 &&
+ p.hiddenColumns[0] === "created"
+ ) {
+ p = { ...p, hiddenColumns: [...AGENT_DEFAULT_HIDDEN_COLUMNS] };
+ }
+ return p;
+ },
+ defaultSortField: "lastActive",
+ sortDefaultDirection: AGENT_SORT_DEFAULT_DIRECTION,
+ defaultHiddenColumns: AGENT_DEFAULT_HIDDEN_COLUMNS,
+ emptyFilters: EMPTY_AGENT_FILTERS,
// "mine" is the historical default — most members care about their own
// agents first; admins flip to "all".
- scope: "mine" as AgentsScope,
- sortField: "lastActive" as AgentSortField,
- sortDirection: AGENT_SORT_DEFAULT_DIRECTION.lastActive,
- hiddenColumns: AGENT_DEFAULT_HIDDEN_COLUMNS,
- filters: EMPTY_AGENT_FILTERS,
- search: "",
-};
-
-export const useAgentsViewStore = create<AgentsViewState>()(
- persist(
- (set) => ({
- ...DEFAULTS,
- setSearch: (search) => set({ search }),
- // "Mine" is the clean personal view: entering it clears all filters,
- // so Mine never carries filters. Switching to all/archived leaves
- // filters intact (you can carry "owner = Bob" between them).
- setScope: (scope) =>
- set(scope === "mine" ? { scope, filters: EMPTY_AGENT_FILTERS } : { scope }),
- toggleSort: (field) =>
- set((state) =>
- state.sortField === field
- ? {
- sortDirection: state.sortDirection === "asc" ? "desc" : "asc",
- }
- : {
- sortField: field,
- sortDirection: AGENT_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortField: (field) =>
- set((state) =>
- state.sortField === field
- ? {}
- : {
- sortField: field,
- sortDirection: AGENT_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortDirection: (direction) => set({ sortDirection: direction }),
- toggleColumn: (key) =>
- set((state) => ({
- hiddenColumns: state.hiddenColumns.includes(key)
- ? state.hiddenColumns.filter((k) => k !== key)
- : [...state.hiddenColumns, key],
- })),
- toggleFilter: (key, value) =>
- set((state) => {
- const list = state.filters[key] as string[];
- const next = list.includes(value)
- ? list.filter((v) => v !== value)
- : [...list, value];
- // Applying any filter leaves the clean "mine" view for "all" —
- // Mine is the no-filter mode (see setScope). Archived keeps its
- // own scope (it can carry filters).
- const scope = state.scope === "mine" ? "all" : state.scope;
- return { scope, filters: { ...state.filters, [key]: next } };
- }),
- clearFilters: () => set({ filters: EMPTY_AGENT_FILTERS }),
- }),
- {
- name: "multica_agents_view",
- version: AGENT_VIEW_STORE_VERSION,
- storage: createJSONStorage(() =>
- createWorkspaceAwareStorage(defaultStorage),
+ extraState: { scope: "mine" },
+ // "Mine" is the clean personal view: entering it clears all filters, so
+ // Mine never carries filters. Switching to all/archived leaves filters
+ // intact (you can carry "owner = Bob" between them).
+ extraActions: (set) => ({
+ setScope: (scope) =>
+ set(
+ scope === "mine" ? { scope, filters: EMPTY_AGENT_FILTERS } : { scope },
),
- partialize: (state) => ({
- scope: state.scope,
- sortField: state.sortField,
- sortDirection: state.sortDirection,
- hiddenColumns: state.hiddenColumns,
- filters: state.filters,
- }),
- // v0 → v1: model went from hidden-by-default to shown-by-default.
- // Every v0 payload carried "model" in hiddenColumns unless the user
- // had turned it on, so un-hide it once; the user can re-hide it from
- // the Display panel. Other persisted prefs pass through untouched.
- migrate: (persisted, version) => {
- const p = (persisted ?? {}) as Partial<AgentsViewState>;
- if (version < 1 && Array.isArray(p.hiddenColumns)) {
- return {
- ...p,
- hiddenColumns: p.hiddenColumns.filter((k) => k !== "model"),
- } as AgentsViewState;
- }
- return p as AgentsViewState;
- },
- // On rehydrate, if the new workspace has no persisted value, reset to
- // the defaults instead of leaving the previous workspace's in-memory
- // view state in place. Default merge keeps current state when
- // persisted is undefined, which would leak state across workspaces.
- merge: (persisted, current) => {
- // `search` is session-only and must not leak across workspaces, so
- // every rehydrate (i.e. workspace switch) clears it.
- if (!persisted) return { ...current, ...DEFAULTS };
- const p = persisted as Partial<AgentsViewState>;
- // Deep-merge filters so a payload persisted before a new filter
- // dimension existed (e.g. `owners`) still gets that key's default
- // instead of dropping it to `undefined` and crashing `.length`.
- return {
- ...current,
- ...p,
- filters: { ...EMPTY_AGENT_FILTERS, ...(p.filters ?? {}) },
- search: "",
- };
- },
- },
- ),
-);
-
-registerForWorkspaceRehydration(() => useAgentsViewStore.persist.rehydrate());
+ }),
+ // Applying any filter leaves the clean "mine" view for "all". Archived
+ // keeps its own scope (it can carry filters).
+ onToggleFilter: (state) => ({
+ scope: state.scope === "mine" ? "all" : state.scope,
+ }),
+});
diff --git a/packages/core/autopilots/stores/view-store.ts b/packages/core/autopilots/stores/view-store.ts
index 419bfeaf83..039274b061 100644
--- a/packages/core/autopilots/stores/view-store.ts
+++ b/packages/core/autopilots/stores/view-store.ts
@@ -1,12 +1,10 @@
"use client";
-import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
import {
- createWorkspaceAwareStorage,
- registerForWorkspaceRehydration,
-} from "../../platform/workspace-storage";
-import { defaultStorage } from "../../platform/storage";
+ createCollectionViewStore,
+ type CollectionSortDirection,
+ type CollectionViewCore,
+} from "../../collections/view-store";
// View preferences for the autopilots list page: scope, sort, column
// visibility, and filters. Persisted per workspace (workspace-aware storage),
@@ -26,7 +24,7 @@ export const AUTOPILOT_SCOPES: AutopilotScope[] = ["all", "active", "paused"];
export type AutopilotSortField = "name" | "lastRun" | "nextRun" | "created";
-export type AutopilotSortDirection = "asc" | "desc";
+export type AutopilotSortDirection = CollectionSortDirection;
/** Per-field direction applied when the user switches TO that field. */
export const AUTOPILOT_SORT_DEFAULT_DIRECTION: Record<
@@ -72,105 +70,28 @@ export const AUTOPILOT_DEFAULT_HIDDEN_COLUMNS: AutopilotColumnKey[] = [
"created",
];
-export interface AutopilotsViewState {
+export interface AutopilotsViewState
+ extends CollectionViewCore<
+ AutopilotSortField,
+ AutopilotColumnKey,
+ AutopilotListFilters
+ > {
scope: AutopilotScope;
- sortField: AutopilotSortField;
- sortDirection: AutopilotSortDirection;
- hiddenColumns: AutopilotColumnKey[];
- filters: AutopilotListFilters;
setScope: (scope: AutopilotScope) => void;
- /** Header click: toggles direction on the active field, otherwise switches
- * to the field with its default direction. */
- toggleSort: (field: AutopilotSortField) => void;
- /** Display panel select: switches field (default direction), no toggle. */
- setSortField: (field: AutopilotSortField) => void;
- setSortDirection: (direction: AutopilotSortDirection) => void;
- toggleColumn: (key: AutopilotColumnKey) => void;
- toggleFilter: (key: keyof AutopilotListFilters, value: string) => void;
- clearFilters: () => void;
}
-const DEFAULTS = {
- scope: "all" as AutopilotScope,
- sortField: "lastRun" as AutopilotSortField,
- sortDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION.lastRun,
- hiddenColumns: AUTOPILOT_DEFAULT_HIDDEN_COLUMNS,
- filters: EMPTY_AUTOPILOT_FILTERS,
-};
-
-export const useAutopilotsViewStore = create<AutopilotsViewState>()(
- persist(
- (set) => ({
- ...DEFAULTS,
- setScope: (scope) => set({ scope }),
- toggleSort: (field) =>
- set((state) =>
- state.sortField === field
- ? {
- sortDirection: state.sortDirection === "asc" ? "desc" : "asc",
- }
- : {
- sortField: field,
- sortDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortField: (field) =>
- set((state) =>
- state.sortField === field
- ? {}
- : {
- sortField: field,
- sortDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortDirection: (direction) => set({ sortDirection: direction }),
- toggleColumn: (key) =>
- set((state) => ({
- hiddenColumns: state.hiddenColumns.includes(key)
- ? state.hiddenColumns.filter((k) => k !== key)
- : [...state.hiddenColumns, key],
- })),
- toggleFilter: (key, value) =>
- set((state) => {
- const list = state.filters[key] as string[];
- const next = list.includes(value)
- ? list.filter((v) => v !== value)
- : [...list, value];
- return { filters: { ...state.filters, [key]: next } };
- }),
- clearFilters: () => set({ filters: EMPTY_AUTOPILOT_FILTERS }),
- }),
- {
- name: "multica_autopilots_view",
- storage: createJSONStorage(() =>
- createWorkspaceAwareStorage(defaultStorage),
- ),
- partialize: (state) => ({
- scope: state.scope,
- sortField: state.sortField,
- sortDirection: state.sortDirection,
- hiddenColumns: state.hiddenColumns,
- filters: state.filters,
- }),
- // On rehydrate, if the new workspace has no persisted value, reset to
- // the defaults instead of leaving the previous workspace's in-memory
- // view state in place (same rationale as the skills view store).
- merge: (persisted, current) => {
- if (!persisted) return { ...current, ...DEFAULTS };
- const p = persisted as Partial<AutopilotsViewState>;
- // Deep-merge filters so a payload persisted before a new filter
- // dimension existed still gets that key's default instead of
- // dropping it to undefined (which crashes `.length` reads).
- return {
- ...current,
- ...p,
- filters: { ...EMPTY_AUTOPILOT_FILTERS, ...(p.filters ?? {}) },
- };
- },
- },
- ),
-);
-
-registerForWorkspaceRehydration(() =>
- useAutopilotsViewStore.persist.rehydrate(),
-);
+export const useAutopilotsViewStore = createCollectionViewStore<
+ AutopilotSortField,
+ AutopilotColumnKey,
+ AutopilotListFilters,
+ { scope: AutopilotScope },
+ { setScope: (scope: AutopilotScope) => void }
+>({
+ name: "multica_autopilots_view",
+ defaultSortField: "lastRun",
+ sortDefaultDirection: AUTOPILOT_SORT_DEFAULT_DIRECTION,
+ defaultHiddenColumns: AUTOPILOT_DEFAULT_HIDDEN_COLUMNS,
+ emptyFilters: EMPTY_AUTOPILOT_FILTERS,
+ extraState: { scope: "all" },
+ extraActions: (set) => ({ setScope: (scope) => set({ scope }) }),
+});
diff --git a/packages/core/collections/view-store.ts b/packages/core/collections/view-store.ts
new file mode 100644
index 0000000000..1f5a1e2fb5
--- /dev/null
+++ b/packages/core/collections/view-store.ts
@@ -0,0 +1,202 @@
+"use client";
+
+import { create, type StoreApi } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import {
+ createWorkspaceAwareStorage,
+ registerForWorkspaceRehydration,
+} from "../platform/workspace-storage";
+import { defaultStorage } from "../platform/storage";
+
+// Shared view preferences for the collection list pages (agents, skills,
+// autopilots, projects, squads): sort, column visibility and multi-select
+// filters, persisted per workspace. Row selection stays session-local.
+
+export type CollectionSortDirection = "asc" | "desc";
+
+export type CollectionFilters<F> = { [K in keyof F]: string[] };
+
+export interface CollectionViewCore<
+ Sort extends string,
+ Column extends string,
+ Filters extends CollectionFilters<Filters>,
+> {
+ sortField: Sort;
+ sortDirection: CollectionSortDirection;
+ hiddenColumns: Column[];
+ filters: Filters;
+ /** Header click: toggles direction on the active field, otherwise switches
+ * to the field with its default direction. */
+ toggleSort: (field: Sort) => void;
+ /** Display panel select: switches field (default direction), no toggle. */
+ setSortField: (field: Sort) => void;
+ setSortDirection: (direction: CollectionSortDirection) => void;
+ toggleColumn: (key: Column) => void;
+ toggleFilter: (key: keyof Filters, value: string) => void;
+ clearFilters: () => void;
+}
+
+type StoreSet<S> = StoreApi<S>["setState"];
+type StoreGet<S> = StoreApi<S>["getState"];
+
+export interface CollectionViewStoreOptions<
+ Sort extends string,
+ Column extends string,
+ Filters extends CollectionFilters<Filters>,
+ ExtraState extends object,
+ ExtraActions extends object,
+> {
+ /** Persist key. Changing it orphans every user's saved preferences. */
+ name: string;
+ version?: number;
+ migrate?: (persisted: unknown, version: number) => unknown;
+ defaultSortField: Sort;
+ sortDefaultDirection: Record<Sort, CollectionSortDirection>;
+ defaultHiddenColumns: Column[];
+ emptyFilters: Filters;
+ /** Page-specific persisted state (scope, view mode). */
+ extraState?: ExtraState;
+ extraActions?: (
+ set: StoreSet<
+ CollectionViewCore<Sort, Column, Filters> & ExtraState & ExtraActions
+ >,
+ get: StoreGet<
+ CollectionViewCore<Sort, Column, Filters> & ExtraState & ExtraActions
+ >,
+ ) => ExtraActions;
+ /** Extra state patch applied alongside every filter toggle. */
+ onToggleFilter?: (
+ state: CollectionViewCore<Sort, Column, Filters> & ExtraState,
+ ) => Partial<ExtraState>;
+}
+
+export function createCollectionViewStore<
+ Sort extends string,
+ Column extends string,
+ Filters extends CollectionFilters<Filters>,
+ ExtraState extends object = Record<never, never>,
+ ExtraActions extends object = Record<never, never>,
+>(
+ options: CollectionViewStoreOptions<
+ Sort,
+ Column,
+ Filters,
+ ExtraState,
+ ExtraActions
+ >,
+) {
+ type State = CollectionViewCore<Sort, Column, Filters> &
+ ExtraState &
+ ExtraActions;
+ type Persisted = Pick<
+ State,
+ "sortField" | "sortDirection" | "hiddenColumns" | "filters"
+ > &
+ ExtraState;
+
+ const extraState = (options.extraState ?? {}) as ExtraState;
+ const defaults = {
+ sortField: options.defaultSortField,
+ sortDirection: options.sortDefaultDirection[options.defaultSortField],
+ hiddenColumns: options.defaultHiddenColumns,
+ filters: options.emptyFilters,
+ ...extraState,
+ };
+ const extraKeys = Object.keys(extraState) as (keyof ExtraState)[];
+
+ const store = create<State>()(
+ persist(
+ (set, get) =>
+ ({
+ ...defaults,
+ toggleSort: (field: Sort) =>
+ set((state) =>
+ state.sortField === field
+ ? ({
+ sortDirection:
+ state.sortDirection === "asc" ? "desc" : "asc",
+ } as Partial<State>)
+ : ({
+ sortField: field,
+ sortDirection: options.sortDefaultDirection[field],
+ } as Partial<State>),
+ ),
+ setSortField: (field: Sort) =>
+ set((state) =>
+ state.sortField === field
+ ? {}
+ : ({
+ sortField: field,
+ sortDirection: options.sortDefaultDirection[field],
+ } as Partial<State>),
+ ),
+ setSortDirection: (direction: CollectionSortDirection) =>
+ set({ sortDirection: direction } as Partial<State>),
+ toggleColumn: (key: Column) =>
+ set(
+ (state) =>
+ ({
+ hiddenColumns: state.hiddenColumns.includes(key)
+ ? state.hiddenColumns.filter((k) => k !== key)
+ : [...state.hiddenColumns, key],
+ }) as Partial<State>,
+ ),
+ toggleFilter: (key: keyof Filters, value: string) =>
+ set((state) => {
+ const list = state.filters[key] as string[];
+ const next = list.includes(value)
+ ? list.filter((v) => v !== value)
+ : [...list, value];
+ return {
+ ...options.onToggleFilter?.(state),
+ filters: { ...state.filters, [key]: next },
+ } as Partial<State>;
+ }),
+ clearFilters: () =>
+ set({ filters: options.emptyFilters } as Partial<State>),
+ ...options.extraActions?.(set, get),
+ }) as State,
+ {
+ name: options.name,
+ ...(options.version !== undefined ? { version: options.version } : {}),
+ ...(options.migrate
+ ? {
+ migrate: (persisted: unknown, version: number) =>
+ options.migrate!(persisted, version) as State,
+ }
+ : {}),
+ storage: createJSONStorage(() =>
+ createWorkspaceAwareStorage(defaultStorage),
+ ),
+ partialize: (state): Persisted => {
+ const out = {
+ sortField: state.sortField,
+ sortDirection: state.sortDirection,
+ hiddenColumns: state.hiddenColumns,
+ filters: state.filters,
+ } as Persisted;
+ for (const key of extraKeys) {
+ (out as ExtraState)[key] = (state as ExtraState)[key];
+ }
+ return out;
+ },
+ // A workspace with nothing persisted resets to the defaults instead
+ // of keeping the previous workspace's in-memory state. Filters are
+ // deep-merged so a payload saved before a filter dimension existed
+ // still gets that key's empty default.
+ merge: (persisted, current) => {
+ if (!persisted) return { ...current, ...defaults };
+ const p = persisted as Partial<State>;
+ return {
+ ...current,
+ ...p,
+ filters: { ...options.emptyFilters, ...(p.filters ?? {}) },
+ };
+ },
+ },
+ ),
+ );
+
+ registerForWorkspaceRehydration(() => store.persist.rehydrate());
+ return store;
+}
diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.ts
index d8e6c4d1ec..50c396f2e7 100644
--- a/packages/core/diagnostics/diagnostic-context.ts
+++ b/packages/core/diagnostics/diagnostic-context.ts
@@ -72,6 +72,7 @@ const WORKSPACE_ROUTES: readonly RoutePattern[] = [
["inbox"],
["chat"],
["my-issues"],
+ ["views"],
["usage"],
["billing"],
["runtimes"],
diff --git a/packages/core/issue-statuses/archive.ts b/packages/core/issue-statuses/archive.ts
index 0fb573f9b6..f830ac9a64 100644
--- a/packages/core/issue-statuses/archive.ts
+++ b/packages/core/issue-statuses/archive.ts
@@ -22,7 +22,8 @@ export function createIssueStatusListStore(key: string) {
viewMode: "list", grouping: "status", statusFilters: [key],
priorityFilters: [], assigneeFilters: [], includeNoAssignee: false,
creatorFilters: [], projectFilters: [], includeNoProject: false,
- labelFilters: [], propertyFilters: {}, dateFilter: null,
+ labelFilters: [], relationFilters: [], dueDateFilters: [], negatedFilters: [],
+ propertyFilters: {}, advancedFilter: null, dateFilter: null,
agentRunningFilter: false, showSubIssues: true,
hiddenStatuses: [], listCollapsedStatuses: [],
}));
diff --git a/packages/core/issue-views/active-view-store.ts b/packages/core/issue-views/active-view-store.ts
index 7b77b590c4..671eb81f47 100644
--- a/packages/core/issue-views/active-view-store.ts
+++ b/packages/core/issue-views/active-view-store.ts
@@ -7,8 +7,9 @@ import type { IssueViewScope } from "./queries";
/**
* Which saved view is open on each surface container, keyed by
* `${wsId}:${scope_type}[:${scope_id}]`. Client/view state (zustand per the
- * state rules): NOT persisted — on web the URL `?view=` param is the durable
+ * state rules): NOT persisted — the URL `?view=` param is the durable
* carrier, and resurrecting a deleted view from storage would strand users.
+ * Desktop swaps the whole map with the active tab.
*/
export function issueViewContainerKey(wsId: string, scope: IssueViewScope): string {
return scope.scope_id
@@ -53,6 +54,8 @@ export function lockedDimensionsFromQuery(
}
if (nonEmptyArray(query.projectStatusFilters)) locked.add("projectStatus");
if (nonEmptyArray(query.labelFilters)) locked.add("label");
+ if (nonEmptyArray(query.relationFilters)) locked.add("relation");
+ if (nonEmptyArray(query.dueDateFilters)) locked.add("dueDate");
const propertyFilters = query.propertyFilters;
if (propertyFilters && typeof propertyFilters === "object") {
for (const [id, selected] of Object.entries(propertyFilters as Record<string, unknown>)) {
diff --git a/packages/core/issue-views/baseline.test.ts b/packages/core/issue-views/baseline.test.ts
index 153b988ab9..a95b5ea926 100644
--- a/packages/core/issue-views/baseline.test.ts
+++ b/packages/core/issue-views/baseline.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import { baselineFromQuery } from "./baseline";
+import { baselineFromQuery, issueViewFilterCount } from "./baseline";
import { propertyFilterValueKey } from "../types";
// The property-filter branch of baselineFromQuery: saved-view members must
@@ -85,3 +85,21 @@ describe("baselineFromQuery project status filters", () => {
expect(baseline.raw.projectStatusFilters).toEqual(["in_progress"]);
});
});
+
+describe("issueViewFilterCount", () => {
+ it("counts constrained dimensions, not values", () => {
+ expect(issueViewFilterCount({})).toBe(0);
+ expect(
+ issueViewFilterCount({
+ statusFilters: ["todo", "in_progress"],
+ includeNoAssignee: true,
+ labelFilters: [],
+ propertyFilters: { p1: ["a"], p2: [] },
+ }),
+ ).toBe(3);
+ });
+
+ it("ignores values the store cannot represent", () => {
+ expect(issueViewFilterCount({ priorityFilters: ["bogus"], projectStatusFilters: ["nope"] })).toBe(0);
+ });
+});
diff --git a/packages/core/issue-views/baseline.ts b/packages/core/issue-views/baseline.ts
index af293fae36..82b84273db 100644
--- a/packages/core/issue-views/baseline.ts
+++ b/packages/core/issue-views/baseline.ts
@@ -1,4 +1,16 @@
-import type { ActorFilterValue, FilterSnapshot } from "../issues/stores/view-store";
+import type {
+ ActorFilterValue,
+ FilterSnapshot,
+ IssueRelationFilter,
+ NegatableFilterDimension,
+} from "../issues/stores/view-store";
+import {
+ DUE_DATE_FILTERS,
+ ISSUE_RELATION_FILTERS,
+ NEGATABLE_FILTER_DIMENSIONS,
+ type DueDateFilter,
+} from "../issues/stores/view-store";
+import { countAdvancedConditions, sanitizeAdvancedFilter } from "../issues/stores/filter-tree";
import type { IssuePriority, IssueStatus, ProjectStatus, PropertyFilterValue } from "../types";
import { isKnownPropertyFilterOp, isPropertyOperatorFilter, propertyFilterValueKey } from "../types";
import { PRIORITY_DISPLAY_ORDER } from "../issues/config";
@@ -24,6 +36,10 @@ export interface IssueViewBaseline {
includeNoProject: boolean;
projectStatus: Set<string>;
label: Set<string>;
+ relation: Set<string>;
+ dueDate: Set<string>;
+ /** Dimensions the view saved as "is not". */
+ negated: Set<NegatableFilterDimension>;
/** Property definition id → fixed member keys (`propertyFilterValueKey`). */
property: Map<string, Set<string>>;
/** Enum-sanitized snapshot, safe to hand straight to `resetFiltersTo`. */
@@ -86,6 +102,25 @@ export function baselineFromQuery(query: Record<string, unknown>): IssueViewBase
(s): s is ProjectStatus => (PROJECT_STATUS_ORDER as readonly string[]).includes(s),
);
const labelFilters = stringArray(query.labelFilters);
+ const relationFilters = stringArray(query.relationFilters).filter(
+ (r): r is IssueRelationFilter => (ISSUE_RELATION_FILTERS as readonly string[]).includes(r),
+ );
+ const dueDateFilters = [
+ ...new Set(
+ stringArray(query.dueDateFilters).filter((d): d is DueDateFilter =>
+ (DUE_DATE_FILTERS as readonly string[]).includes(d),
+ ),
+ ),
+ ];
+ const advancedFilter = sanitizeAdvancedFilter(query.advancedFilter);
+ const negatedFilters = [
+ ...new Set(
+ stringArray(query.negatedFilters).filter(
+ (d): d is NegatableFilterDimension =>
+ (NEGATABLE_FILTER_DIMENSIONS as readonly string[]).includes(d),
+ ),
+ ),
+ ];
const includeNoAssignee = query.includeNoAssignee === true;
const includeNoProject = query.includeNoProject === true;
@@ -113,6 +148,9 @@ export function baselineFromQuery(query: Record<string, unknown>): IssueViewBase
includeNoProject,
projectStatus: new Set(projectStatusFilters),
label: new Set(labelFilters),
+ relation: new Set(relationFilters),
+ dueDate: new Set(dueDateFilters),
+ negated: new Set(negatedFilters),
property,
raw: {
statusFilters,
@@ -124,7 +162,31 @@ export function baselineFromQuery(query: Record<string, unknown>): IssueViewBase
includeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters,
+ dueDateFilters,
+ negatedFilters,
propertyFilters,
+ advancedFilter,
},
};
}
+
+/** How many filter dimensions a saved query constrains, for summaries. */
+export function issueViewFilterCount(query: Record<string, unknown>): number {
+ const { raw } = baselineFromQuery(query);
+ return (
+ [
+ raw.statusFilters.length,
+ raw.priorityFilters.length,
+ raw.assigneeFilters.length || raw.includeNoAssignee,
+ raw.creatorFilters.length,
+ raw.projectFilters.length || raw.includeNoProject,
+ raw.projectStatusFilters.length,
+ raw.labelFilters.length,
+ raw.relationFilters.length,
+ raw.dueDateFilters.length,
+ ].filter(Boolean).length +
+ Object.keys(raw.propertyFilters).length +
+ countAdvancedConditions(raw.advancedFilter)
+ );
+}
diff --git a/packages/core/issue-views/definition.test.ts b/packages/core/issue-views/definition.test.ts
new file mode 100644
index 0000000000..a136a0c711
--- /dev/null
+++ b/packages/core/issue-views/definition.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+import { createStore } from "zustand/vanilla";
+import { viewStoreSlice, type IssueViewState } from "../issues/stores/view-store";
+import {
+ isIssueViewModified,
+ issueViewDefinitionFromState,
+ issueViewSeedDefinition,
+ modifiedFilterDimensions,
+} from "./definition";
+
+function liveStateFor(view: { query: Record<string, unknown>; display: Record<string, unknown> }) {
+ const store = createStore<IssueViewState>()(viewStoreSlice);
+ const seed = issueViewSeedDefinition(view);
+ store.setState({ ...seed.query, ...seed.display } as Partial<IssueViewState>);
+ return store;
+}
+
+describe("isIssueViewModified", () => {
+ const view = {
+ query: { statusFilters: ["todo"] },
+ display: { viewMode: "list", sortBy: "priority" },
+ };
+
+ it("reports a freshly opened view as unmodified, even with sparse definitions", () => {
+ expect(isIssueViewModified(view, liveStateFor(view).getState())).toEqual({
+ filters: false,
+ display: false,
+ });
+ });
+
+ it("separates filter edits from display edits", () => {
+ const store = liveStateFor(view);
+ store.setState({ priorityFilters: ["high"] });
+ expect(isIssueViewModified(view, store.getState())).toEqual({ filters: true, display: false });
+ store.setState({ priorityFilters: [], viewMode: "board" });
+ expect(isIssueViewModified(view, store.getState())).toEqual({ filters: false, display: true });
+ });
+
+ it("treats 'is not' on an empty dimension as no change", () => {
+ const store = liveStateFor(view);
+ store.getState().setFilterNegated("label", true);
+ expect(isIssueViewModified(view, store.getState()).filters).toBe(false);
+ store.getState().setFilterNegated("status", true);
+ expect(isIssueViewModified(view, store.getState()).filters).toBe(true);
+ });
+
+ it("round-trips a negated view without reporting it modified", () => {
+ const negatedView = {
+ query: { statusFilters: ["done"], negatedFilters: ["status"], relationFilters: ["assigned"] },
+ display: {},
+ };
+ const store = liveStateFor(negatedView);
+ expect(store.getState().negatedFilters).toEqual(["status"]);
+ expect(isIssueViewModified(negatedView, store.getState()).filters).toBe(false);
+ expect(issueViewDefinitionFromState(store.getState()).query).toMatchObject({
+ negatedFilters: ["status"],
+ relationFilters: ["assigned"],
+ });
+ });
+});
+
+describe("modifiedFilterDimensions", () => {
+ const view = {
+ query: { statusFilters: ["done"], negatedFilters: ["status"], priorityFilters: ["high"] },
+ display: {},
+ };
+
+ it("names the dimensions whose values or relation changed", () => {
+ const store = liveStateFor(view);
+ expect([...modifiedFilterDimensions(view, store.getState())]).toEqual([]);
+ store.getState().toggleRelationFilter("created");
+ store.getState().setFilterNegated("status", false);
+ store.getState().setPropertyFilterValues("prop-1", ["x"]);
+ expect([...modifiedFilterDimensions(view, store.getState())].sort()).toEqual(
+ ["property:prop-1", "relation", "status"],
+ );
+ });
+});
diff --git a/packages/core/issue-views/definition.ts b/packages/core/issue-views/definition.ts
new file mode 100644
index 0000000000..68d1a64ec5
--- /dev/null
+++ b/packages/core/issue-views/definition.ts
@@ -0,0 +1,167 @@
+import { createStore } from "zustand/vanilla";
+import type { IssueView } from "../api/schemas";
+import {
+ effectiveNegatedFilters,
+ filterDimensionHasSelection,
+ mergeViewStatePersisted,
+ NEGATABLE_FILTER_DIMENSIONS,
+ viewStoreSlice,
+ type FilterSnapshot,
+ type IssueViewState,
+ type NegatableFilterDimension,
+} from "../issues/stores/view-store";
+import {
+ advancedFilterSignature,
+ pruneAdvancedFilter,
+ sanitizeAdvancedFilter,
+ simpleFromAdvancedFilter,
+} from "../issues/stores/filter-tree";
+
+/** What a saved view stores: its filters, and the display it opens with. */
+export interface IssueViewDefinition {
+ query: Record<string, unknown>;
+ display: Record<string, unknown>;
+}
+
+export function issueViewDefinitionFromState(state: IssueViewState): IssueViewDefinition {
+ return {
+ query: {
+ statusFilters: state.statusFilters,
+ priorityFilters: state.priorityFilters,
+ assigneeFilters: state.assigneeFilters,
+ includeNoAssignee: state.includeNoAssignee,
+ creatorFilters: state.creatorFilters,
+ projectFilters: state.projectFilters,
+ includeNoProject: state.includeNoProject,
+ projectStatusFilters: state.projectStatusFilters,
+ labelFilters: state.labelFilters,
+ relationFilters: state.relationFilters,
+ dueDateFilters: state.dueDateFilters,
+ negatedFilters: effectiveNegatedFilters(state),
+ propertyFilters: state.propertyFilters,
+ advancedFilter: pruneAdvancedFilter(state.advancedFilter),
+ },
+ display: {
+ showSubIssues: state.showSubIssues,
+ viewMode: state.viewMode,
+ grouping: state.grouping,
+ sortBy: state.sortBy,
+ sortDirection: state.sortDirection,
+ cardProperties: state.cardProperties,
+ cardPropertyIds: state.cardPropertyIds,
+ tableColumns: state.tableColumns,
+ tableGrouping: state.tableGrouping,
+ tableHierarchy: state.tableHierarchy,
+ tableCalculation: state.tableCalculation,
+ swimlaneGrouping: state.swimlaneGrouping,
+ ganttZoom: state.ganttZoom,
+ ganttShowCompleted: state.ganttShowCompleted,
+ },
+ };
+}
+
+/**
+ * The definition a view opens with, sanitized exactly like the surface seed,
+ * so comparing it with live state never reports a fresh view as modified.
+ */
+export function issueViewSeedDefinition(
+ view: Pick<IssueView, "query" | "display">,
+): IssueViewDefinition {
+ const defaults = createStore<IssueViewState>()(viewStoreSlice).getState();
+ return issueViewDefinitionFromState(
+ mergeViewStatePersisted({ ...view.query, ...view.display }, defaults),
+ );
+}
+
+function stableStringify(value: unknown): string {
+ return JSON.stringify(value, (_key, inner: unknown) =>
+ inner && typeof inner === "object" && !Array.isArray(inner)
+ ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => a.localeCompare(b)))
+ : inner,
+ );
+}
+
+const DIMENSION_FIELDS: Record<NegatableFilterDimension, readonly string[]> = {
+ status: ["statusFilters"],
+ priority: ["priorityFilters"],
+ assignee: ["assigneeFilters", "includeNoAssignee"],
+ creator: ["creatorFilters"],
+ project: ["projectFilters", "includeNoProject"],
+ projectStatus: ["projectStatusFilters"],
+ label: ["labelFilters"],
+ relation: ["relationFilters"],
+ dueDate: ["dueDateFilters"],
+};
+
+/**
+ * A query reduced to what it filters, for comparisons. Entering advanced mode
+ * rewrites the same filter as a tree with fresh ids, so a tree simple mode
+ * can say compares as those simple fields, and any other tree by its
+ * id-free signature.
+ */
+function filterMeaning(query: Record<string, unknown>): Record<string, unknown> {
+ const tree = sanitizeAdvancedFilter(query.advancedFilter);
+ if (!tree) return { ...query, advancedFilter: "" };
+ const simple = simpleFromAdvancedFilter(tree);
+ const flatEmpty =
+ NEGATABLE_FILTER_DIMENSIONS.every(
+ (dimension) => !filterDimensionHasSelection(query as unknown as FilterSnapshot, dimension),
+ ) &&
+ Object.values((query.propertyFilters ?? {}) as Record<string, unknown[]>).every(
+ (values) => values.length === 0,
+ );
+ if (simple && flatEmpty) return { ...query, ...simple, advancedFilter: "" };
+ return { ...query, advancedFilter: advancedFilterSignature(tree) };
+}
+
+/** Whether two filter queries select the same issues by construction. */
+export function sameFilterMeaning(
+ a: Record<string, unknown>,
+ b: Record<string, unknown>,
+): boolean {
+ return stableStringify(filterMeaning(a)) === stableStringify(filterMeaning(b));
+}
+
+/**
+ * The filter dimensions (chip keys) whose condition differs from what the
+ * view saves: its values, or its "is" / "is not".
+ */
+export function modifiedFilterDimensions(
+ view: Pick<IssueView, "query" | "display">,
+ state: IssueViewState,
+): Set<string> {
+ const seed = filterMeaning(issueViewSeedDefinition(view).query);
+ const live = filterMeaning(issueViewDefinitionFromState(state).query);
+ const seedNegated = new Set(seed.negatedFilters as NegatableFilterDimension[]);
+ const liveNegated = new Set(live.negatedFilters as NegatableFilterDimension[]);
+ const modified = new Set<string>();
+ for (const dimension of NEGATABLE_FILTER_DIMENSIONS) {
+ const fields = DIMENSION_FIELDS[dimension];
+ const changed =
+ seedNegated.has(dimension) !== liveNegated.has(dimension) ||
+ fields.some((field) => stableStringify(seed[field]) !== stableStringify(live[field]));
+ if (changed) modified.add(dimension);
+ }
+ const seedProperties = (seed.propertyFilters ?? {}) as Record<string, unknown>;
+ const liveProperties = (live.propertyFilters ?? {}) as Record<string, unknown>;
+ for (const id of new Set([...Object.keys(seedProperties), ...Object.keys(liveProperties)])) {
+ if (stableStringify(seedProperties[id] ?? []) !== stableStringify(liveProperties[id] ?? [])) {
+ modified.add(`property:${id}`);
+ }
+ }
+ if (seed.advancedFilter !== live.advancedFilter) modified.add("advanced");
+ return modified;
+}
+
+/** Whether the live state drifted from what the view saves. */
+export function isIssueViewModified(
+ view: Pick<IssueView, "query" | "display">,
+ state: IssueViewState,
+): { filters: boolean; display: boolean } {
+ const seed = issueViewSeedDefinition(view);
+ const live = issueViewDefinitionFromState(state);
+ return {
+ filters: !sameFilterMeaning(seed.query, live.query),
+ display: stableStringify(seed.display) !== stableStringify(live.display),
+ };
+}
diff --git a/packages/core/issue-views/index.ts b/packages/core/issue-views/index.ts
index dc820af97f..a3b680c6ed 100644
--- a/packages/core/issue-views/index.ts
+++ b/packages/core/issue-views/index.ts
@@ -4,3 +4,7 @@ export * from "./active-view-store";
export * from "./use-active-view";
export * from "./baseline";
export * from "./preferences";
+export * from "./sidebar-views";
+export * from "./view-target";
+export * from "./definition";
+export * from "./rename-store";
diff --git a/packages/core/issue-views/mutations.ts b/packages/core/issue-views/mutations.ts
index 1b290cf9cf..135e9712c7 100644
--- a/packages/core/issue-views/mutations.ts
+++ b/packages/core/issue-views/mutations.ts
@@ -26,6 +26,9 @@ export function useCreateIssueView(wsId: string) {
? [...old, created]
: old,
);
+ queryClient.setQueryData<IssueView[]>(issueViewKeys.everywhere(wsId), (old) =>
+ old && !old.some((v) => v.id === created.id) ? [...old, created] : old,
+ );
}
void queryClient.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });
},
diff --git a/packages/core/issue-views/preferences.ts b/packages/core/issue-views/preferences.ts
index dd1f1e9b2f..9db6318754 100644
--- a/packages/core/issue-views/preferences.ts
+++ b/packages/core/issue-views/preferences.ts
@@ -5,6 +5,9 @@ import { api } from "../api";
import type { IssueViewPreference } from "../api/schemas";
import type { IssueViewScope } from "./queries";
+/** A preference container: a view surface, or the user's sidebar list. */
+export type IssueViewPreferenceScope = IssueViewScope | { scope_type: "sidebar"; scope_id?: null };
+
export interface ViewBarPrefs {
hidden: string[];
order: string[];
@@ -14,11 +17,11 @@ export const EMPTY_VIEW_BAR_PREFS: ViewBarPrefs = { hidden: [], order: [] };
export const issueViewPrefKeys = {
all: (wsId: string) => ["issue-view-prefs", wsId] as const,
- scope: (wsId: string, scope: IssueViewScope) =>
+ scope: (wsId: string, scope: IssueViewPreferenceScope) =>
[...issueViewPrefKeys.all(wsId), scope.scope_type, scope.scope_id ?? null] as const,
};
-export function issueViewPreferenceOptions(wsId: string, scope: IssueViewScope) {
+export function issueViewPreferenceOptions(wsId: string, scope: IssueViewPreferenceScope) {
return queryOptions({
queryKey: issueViewPrefKeys.scope(wsId, scope),
queryFn: () => api.getIssueViewPreference(scope),
@@ -31,7 +34,7 @@ export function issueViewPreferenceOptions(wsId: string, scope: IssueViewScope)
* drag-reorder are the canonical optimistic case (locally predictable, same
* screen, trivial rollback).
*/
-export function useUpdateIssueViewPreference(wsId: string, scope: IssueViewScope) {
+export function useUpdateIssueViewPreference(wsId: string, scope: IssueViewPreferenceScope) {
const queryClient = useQueryClient();
const queryKey = issueViewPrefKeys.scope(wsId, scope);
return useMutation({
@@ -43,7 +46,8 @@ export function useUpdateIssueViewPreference(wsId: string, scope: IssueViewScope
const optimistic: IssueViewPreference = {
scope_type: scope.scope_type,
scope_id: scope.scope_id ?? null,
- updated_at: previous?.updated_at ?? "",
+ // Non-empty: an empty updated_at means "never saved" to readers.
+ updated_at: previous?.updated_at || new Date().toISOString(),
prefs: { ...prefs },
};
queryClient.setQueryData<IssueViewPreference>(queryKey, optimistic);
diff --git a/packages/core/issue-views/queries.ts b/packages/core/issue-views/queries.ts
index 9c18cb7ddb..64d50e38d8 100644
--- a/packages/core/issue-views/queries.ts
+++ b/packages/core/issue-views/queries.ts
@@ -13,8 +13,29 @@ export const issueViewKeys = {
[...issueViewKeys.all(wsId), scope.scope_type, scope.scope_id ?? null] as const,
detail: (wsId: string, id: string) =>
[...issueViewKeys.all(wsId), "detail", id] as const,
+ everywhere: (wsId: string) => [...issueViewKeys.all(wsId), "everywhere"] as const,
};
+/** Every view the caller can open, across workspace, my and project scopes. */
+export function issueViewEverywhereOptions(wsId: string) {
+ return queryOptions({
+ queryKey: issueViewKeys.everywhere(wsId),
+ queryFn: async () => {
+ try {
+ return await api.listIssueViews({ scope_type: "all" });
+ } catch {
+ // Backends without the cross-scope list reject scope_type=all.
+ const [workspace, my] = await Promise.all([
+ api.listIssueViews({ scope_type: "workspace" }),
+ api.listIssueViews({ scope_type: "my" }),
+ ]);
+ return [...workspace, ...my];
+ }
+ },
+ enabled: !!wsId,
+ });
+}
+
export function issueViewListOptions(wsId: string, scope: IssueViewScope) {
return queryOptions({
queryKey: issueViewKeys.list(wsId, scope),
diff --git a/packages/core/issue-views/rename-store.ts b/packages/core/issue-views/rename-store.ts
new file mode 100644
index 0000000000..fa541c1c10
--- /dev/null
+++ b/packages/core/issue-views/rename-store.ts
@@ -0,0 +1,22 @@
+"use client";
+
+import { create } from "zustand";
+
+/** Where an inline rename is open: one place at a time, never two inputs. */
+export type IssueViewRenameSurface = "sidebar" | "header";
+
+interface IssueViewRenameState {
+ target: { viewId: string; surface: IssueViewRenameSurface } | null;
+ start: (viewId: string, surface: IssueViewRenameSurface) => void;
+ stop: () => void;
+}
+
+/**
+ * The view whose name is being edited inline. Creating or duplicating a view
+ * opens it here right away so the user names it where it appears.
+ */
+export const useIssueViewRenameStore = create<IssueViewRenameState>((set) => ({
+ target: null,
+ start: (viewId, surface) => set({ target: { viewId, surface } }),
+ stop: () => set({ target: null }),
+}));
diff --git a/packages/core/issue-views/sidebar-views.hook.test.tsx b/packages/core/issue-views/sidebar-views.hook.test.tsx
new file mode 100644
index 0000000000..b682c3ad26
--- /dev/null
+++ b/packages/core/issue-views/sidebar-views.hook.test.tsx
@@ -0,0 +1,75 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClientProvider, type QueryClient } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import type { IssueViewPreference } from "../api/schemas";
+import { createQueryClient } from "../query-client";
+import { useSidebarViews } from "./sidebar-views";
+
+const preference = (order: string[], updated_at = "2026-10-30T00:00:00Z"): IssueViewPreference => ({
+ scope_type: "sidebar",
+ scope_id: null,
+ updated_at,
+ prefs: { hidden: [], order },
+});
+
+describe("useSidebarViews writes", () => {
+ let qc: QueryClient;
+ let putIssueViewPreference: ReturnType<typeof vi.fn>;
+
+ function setup(saved: IssueViewPreference) {
+ putIssueViewPreference = vi.fn(async (body: { prefs: { order: string[] } }) => preference(body.prefs.order));
+ setApiInstance({
+ getIssueViewPreference: vi.fn(async () => saved),
+ // Saved views never arrive: the directory is still loading.
+ listIssueViews: vi.fn(() => new Promise(() => {})),
+ listPins: vi.fn(async () => []),
+ putIssueViewPreference,
+ } as unknown as ApiClient);
+ return renderHook(() => useSidebarViews("ws-1", "me"), {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ ),
+ });
+ }
+
+ beforeEach(() => {
+ qc = createQueryClient();
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("keeps starred views that have not loaded when unstarring a built-in", async () => {
+ const { result } = setup(preference(["builtin:my_issues", "view:a", "builtin:all_issues", "view:b"]));
+ await waitFor(() => expect(result.current.isStarred("view:a")).toBe(true));
+ expect(result.current.viewsPending).toBe(true);
+
+ act(() => result.current.unstar("builtin:all_issues"));
+
+ await waitFor(() => expect(putIssueViewPreference).toHaveBeenCalledTimes(1));
+ expect(putIssueViewPreference.mock.calls[0]![0].prefs.order).toEqual([
+ "builtin:my_issues",
+ "view:a",
+ "view:b",
+ ]);
+ });
+
+ it("does not write a default order before the views behind it have loaded", async () => {
+ const { result } = setup(preference([], ""));
+ await waitFor(() => expect(result.current.isStarred("builtin:all_issues")).toBe(true));
+
+ act(() => result.current.unstar("builtin:all_issues"));
+ act(() => result.current.star("view:a"));
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(putIssueViewPreference).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/issue-views/sidebar-views.test.ts b/packages/core/issue-views/sidebar-views.test.ts
new file mode 100644
index 0000000000..5a782eeb49
--- /dev/null
+++ b/packages/core/issue-views/sidebar-views.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+import type { IssueView } from "../api/schemas";
+import { defaultSidebarViewOrder, reorderSidebarViewOrder, resolveSidebarViewItems } from "./sidebar-views";
+
+const view = (id: string, owner_id: string): IssueView => ({
+ id,
+ owner_id,
+ workspace_id: "ws",
+ name: id,
+ scope_type: "workspace",
+ scope_id: null,
+ scope_variant: null,
+ visibility: "workspace",
+ definition_version: 1,
+ query: {},
+ display: {},
+ revision: 1,
+ created_at: "",
+ updated_at: "",
+});
+
+describe("defaultSidebarViewOrder", () => {
+ it("lists built-ins, own views, then previously pinned views once", () => {
+ const views = [view("a", "me"), view("b", "other"), view("c", "other")];
+ expect(defaultSidebarViewOrder(views, "me", ["c", "a"])).toEqual([
+ "builtin:my_issues",
+ "builtin:my_agents",
+ "builtin:all_issues",
+ "view:a",
+ "view:c",
+ ]);
+ });
+});
+
+describe("resolveSidebarViewItems", () => {
+ it("keeps the saved order and drops unknown or duplicate ids", () => {
+ const items = resolveSidebarViewItems(
+ ["view:b", "builtin:all_issues", "view:gone", "builtin:nope", "view:b"],
+ [view("a", "me"), view("b", "me")],
+ );
+ expect(items.map((item) => item.id)).toEqual(["view:b", "builtin:all_issues"]);
+ expect(items[1]).toMatchObject({ kind: "builtin", key: "all_issues" });
+ });
+});
+
+describe("reorderSidebarViewOrder", () => {
+ it("moves visible ids and keeps unresolved ones in their slots", () => {
+ expect(
+ reorderSidebarViewOrder(
+ ["builtin:my_issues", "view:loading", "view:a", "builtin:all_issues"],
+ ["builtin:all_issues", "builtin:my_issues", "view:a"],
+ ),
+ ).toEqual(["builtin:all_issues", "view:loading", "builtin:my_issues", "view:a"]);
+ });
+
+ it("appends visible ids the stored order did not have", () => {
+ expect(reorderSidebarViewOrder(["view:a", "view:a"], ["view:b", "view:a"])).toEqual(["view:b", "view:a"]);
+ });
+});
diff --git a/packages/core/issue-views/sidebar-views.ts b/packages/core/issue-views/sidebar-views.ts
new file mode 100644
index 0000000000..b85d7bbb07
--- /dev/null
+++ b/packages/core/issue-views/sidebar-views.ts
@@ -0,0 +1,135 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { IssueView } from "../api/schemas";
+import { pinListOptions } from "../pins/queries";
+import type { PinnedItem } from "../types";
+import { issueViewEverywhereOptions } from "./queries";
+import { issueViewPreferenceOptions, useUpdateIssueViewPreference } from "./preferences";
+
+/** The views every workspace has without saving anything. */
+export type BuiltinViewKey = "my_issues" | "my_agents" | "all_issues";
+export const BUILTIN_VIEW_KEYS: readonly BuiltinViewKey[] = ["my_issues", "my_agents", "all_issues"];
+
+export const builtinViewItemId = (key: BuiltinViewKey) => `builtin:${key}`;
+export const savedViewItemId = (viewId: string) => `view:${viewId}`;
+
+export const SIDEBAR_VIEWS_SCOPE = { scope_type: "sidebar" } as const;
+
+export type SidebarViewItem =
+ | { id: string; kind: "builtin"; key: BuiltinViewKey }
+ | { id: string; kind: "view"; view: IssueView };
+
+const EMPTY_VIEWS: IssueView[] = [];
+const EMPTY_PINS: PinnedItem[] = [];
+
+/**
+ * The starred list before the user has arranged it: the built-ins, the
+ * user's own views, then views they had pinned under the old Pinned section.
+ */
+export function defaultSidebarViewOrder(
+ views: readonly IssueView[],
+ userId: string | undefined,
+ pinnedViewIds: readonly string[],
+): string[] {
+ const ids = BUILTIN_VIEW_KEYS.map(builtinViewItemId);
+ for (const view of views) {
+ if (view.owner_id === userId) ids.push(savedViewItemId(view.id));
+ }
+ for (const viewId of pinnedViewIds) {
+ const id = savedViewItemId(viewId);
+ if (!ids.includes(id)) ids.push(id);
+ }
+ return ids;
+}
+
+/** Resolve starred ids to items, dropping views that were deleted or unshared. */
+export function resolveSidebarViewItems(
+ order: readonly string[],
+ views: readonly IssueView[],
+): SidebarViewItem[] {
+ const byId = new Map(views.map((view) => [savedViewItemId(view.id), view]));
+ const builtins = new Map(BUILTIN_VIEW_KEYS.map((key) => [builtinViewItemId(key), key]));
+ const items: SidebarViewItem[] = [];
+ const seen = new Set<string>();
+ for (const id of order) {
+ if (seen.has(id)) continue;
+ seen.add(id);
+ const key = builtins.get(id);
+ if (key) {
+ items.push({ id, kind: "builtin", key });
+ continue;
+ }
+ const view = byId.get(id);
+ if (view) items.push({ id, kind: "view", view });
+ }
+ return items;
+}
+
+/**
+ * Puts the visible ids, in their new order, back into the slots visible ids
+ * held, so starred views that do not resolve yet keep their place.
+ */
+export function reorderSidebarViewOrder(order: readonly string[], visibleIds: readonly string[]): string[] {
+ const visible = new Set(visibleIds);
+ const queue = [...visibleIds];
+ const next = [...new Set(order)].map((id) => (visible.has(id) ? queue.shift()! : id));
+ return [...next, ...queue];
+}
+
+/**
+ * The user's starred views in sidebar order, with the writes that rearrange
+ * them. Until the first write the list is derived, so views the user creates
+ * elsewhere still show up.
+ */
+export function useSidebarViews(wsId: string, userId: string | undefined) {
+ const viewsQuery = useQuery(issueViewEverywhereOptions(wsId));
+ const views = viewsQuery.data ?? EMPTY_VIEWS;
+ const preferenceQuery = useQuery(issueViewPreferenceOptions(wsId, SIDEBAR_VIEWS_SCOPE));
+ const pinsQuery = useQuery({
+ ...pinListOptions(wsId, userId ?? ""),
+ enabled: !!wsId && !!userId,
+ });
+ const pins = pinsQuery.data ?? EMPTY_PINS;
+ const update = useUpdateIssueViewPreference(wsId, SIDEBAR_VIEWS_SCOPE);
+
+ const preference = preferenceQuery.data;
+ const savedOrder = preference && preference.updated_at !== "" ? preference.prefs.order : null;
+ const order = useMemo(
+ () =>
+ savedOrder ??
+ defaultSidebarViewOrder(
+ views,
+ userId,
+ pins.filter((pin) => pin.item_type === "view").map((pin) => pin.item_id),
+ ),
+ [savedOrder, views, userId, pins],
+ );
+ const items = useMemo(() => resolveSidebarViewItems(order, views), [order, views]);
+
+ // A write replaces the whole stored order, so it waits until that order is
+ // known: the saved one, or the default derived from views and pins.
+ const ready =
+ preferenceQuery.isSuccess &&
+ (savedOrder !== null || (viewsQuery.isSuccess && (!userId || pinsQuery.isSuccess)));
+ const write = useCallback(
+ (next: string[]) => {
+ if (ready) update.mutate({ hidden: [], order: next });
+ },
+ [ready, update],
+ );
+
+ return {
+ items,
+ /** Saved views are still loading; built-ins render regardless. */
+ viewsPending: viewsQuery.isPending,
+ isStarred: useCallback((id: string) => order.includes(id), [order]),
+ star: useCallback((id: string) => {
+ if (!order.includes(id)) write([...order, id]);
+ }, [order, write]),
+ unstar: useCallback((id: string) => write(order.filter((other) => other !== id)), [order, write]),
+ /** Takes the visible items' ids in their new order. */
+ reorder: useCallback((visibleIds: string[]) => write(reorderSidebarViewOrder(order, visibleIds)), [order, write]),
+ };
+}
diff --git a/packages/core/issue-views/view-target.ts b/packages/core/issue-views/view-target.ts
new file mode 100644
index 0000000000..6ba2285b99
--- /dev/null
+++ b/packages/core/issue-views/view-target.ts
@@ -0,0 +1,44 @@
+import type { IssueView } from "../api/schemas";
+import type { WorkspacePaths } from "../paths";
+import { issueViewContainerKey } from "./active-view-store";
+import type { IssueViewScope } from "./queries";
+
+export interface IssueViewTarget {
+ scope: IssueViewScope;
+ /** The surface the view opens on. */
+ path: string;
+ /** `path?view=<id>`: pages adopt it on load, so a new tab opens the view. */
+ href: string;
+ /** Active-view store key of that surface. */
+ containerKey: string;
+}
+
+/**
+ * Where a saved view opens. One resolved scope drives the path AND the
+ * container key, so an unrecognised scope_type from a newer backend degrades
+ * to the workspace surface coherently.
+ */
+export function issueViewTarget(
+ wsId: string,
+ view: Pick<IssueView, "id" | "scope_type" | "scope_id">,
+ paths: WorkspacePaths,
+): IssueViewTarget {
+ const scope: IssueViewScope =
+ view.scope_type === "my"
+ ? { scope_type: "my" }
+ : view.scope_type === "project" && view.scope_id
+ ? { scope_type: "project", scope_id: view.scope_id }
+ : { scope_type: "workspace" };
+ const path =
+ scope.scope_type === "my"
+ ? paths.myIssues()
+ : scope.scope_type === "project"
+ ? paths.projectDetail(scope.scope_id!)
+ : paths.issues();
+ return {
+ scope,
+ path,
+ href: `${path}?view=${view.id}`,
+ containerKey: issueViewContainerKey(wsId, scope),
+ };
+}
diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.ts
index a4d6d44ccf..eb9344b8df 100644
--- a/packages/core/issues/cache-coordinator.ts
+++ b/packages/core/issues/cache-coordinator.ts
@@ -575,13 +575,17 @@ export function rollbackIssueChange(
/**
* Refresh the aggregate projections a single-entity patch cannot recompute:
* assignee-grouped boards (regrouping is server logic), every Project Gantt
- * (schedule membership + row mirrors), and project metrics when the change
- * could shift per-project counts.
+ * (schedule membership + row mirrors), and project metrics plus sidebar
+ * lists when the change could shift per-project counts.
*/
export function invalidateIssueDerivatives(
qc: QueryClient,
wsId: string,
- opts: { statusOrProjectChanged: boolean },
+ opts: {
+ statusOrProjectChanged: boolean;
+ /** False when the caller refreshes the sidebar lists it can target. */
+ refreshSidebar?: boolean;
+ },
) {
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
@@ -589,6 +593,35 @@ export function invalidateIssueDerivatives(
if (opts.statusOrProjectChanged) {
qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
}
+ if (opts.refreshSidebar ?? opts.statusOrProjectChanged) {
+ qc.invalidateQueries({ queryKey: issueKeys.sidebarAll(wsId) });
+ }
+}
+
+/**
+ * Refresh the sidebar lists one issue change can reorder or move it across:
+ * lists showing it, its old and new project's lists, and every view list,
+ * built-in ones included (view membership is a server-side filter the client
+ * cannot re-evaluate).
+ */
+export function invalidateSidebarListsForIssue(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ projectIds: readonly (string | null | undefined)[],
+) {
+ const projectSources = new Set(projectIds.filter(Boolean).map((id) => `project:${id}`));
+ const prefix = issueKeys.sidebarAll(wsId);
+ qc.invalidateQueries({
+ queryKey: prefix,
+ predicate: (query) => {
+ const source = query.queryKey[prefix.length];
+ if (typeof source !== "string") return false;
+ if (source.startsWith("view:") || source.startsWith("builtin:") || projectSources.has(source)) return true;
+ const data = query.state.data as ListIssuesResponse | undefined;
+ return !!data?.issues?.some((issue) => issue.id === issueId);
+ },
+ });
}
/** True when any object part of a query key encodes the requested ordering.
diff --git a/packages/core/issues/delete-cache.ts b/packages/core/issues/delete-cache.ts
index 0a9013a884..2ef6f0925c 100644
--- a/packages/core/issues/delete-cache.ts
+++ b/packages/core/issues/delete-cache.ts
@@ -211,6 +211,7 @@ export function cleanupDeletedIssueCaches(
// refresh when an issue is removed — the deleted row may have been a
// scheduled bar visible right now.
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.sidebarAll(wsId) });
invalidateDeletedIssueDependentCaches(qc, wsId);
// Recent Issues store persists to localStorage and survives reloads, so a
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 072e91644e..4edeb62221 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -162,6 +162,7 @@ function useIssueCreateMutation<TVariables>(
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.sidebarAll(wsId) });
qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
},
});
@@ -495,6 +496,7 @@ export function useDeleteIssue() {
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.sidebarAll(wsId) });
qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
if (ctx?.metadata) invalidateDeletedIssueParentCaches(qc, wsId, ctx.metadata);
},
@@ -807,6 +809,7 @@ export function useBatchDeleteIssues() {
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.sidebarAll(wsId) });
qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
if (ctx?.parentIssueIds && ctx.parentIssueIds.size > 0) {
invalidateDeletedIssueParentCaches(qc, wsId, {
diff --git a/packages/core/issues/queries.test.ts b/packages/core/issues/queries.test.ts
index db4f98adaf..82929734dc 100644
--- a/packages/core/issues/queries.test.ts
+++ b/packages/core/issues/queries.test.ts
@@ -26,6 +26,7 @@ import {
issueListOptions,
issueTableRowPageOptions,
projectGanttIssuesOptions,
+ sidebarIssuesOptions,
sourceContextPreviewOptions,
} from "./queries";
import { onIssueUpdated } from "./ws-updaters";
@@ -715,3 +716,56 @@ describe("issueIdentifierOptions", () => {
]);
});
});
+
+describe("sidebarIssuesOptions", () => {
+ const issues = Array.from({ length: 120 }, (_, i) => makeIssue(i));
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("walks table pages past the server's 100-row cap", async () => {
+ const listIssueTableRows = vi.fn(async (params: IssueTableRowsRequest): Promise<IssueTableRowsResponse> => {
+ const start = params.page?.cursor ? Number(params.page.cursor) : 0;
+ const end = start + Math.min(params.page?.limit ?? 50, 100);
+ return {
+ query_fingerprint: "fp",
+ group_key: null,
+ parent_id: null,
+ total: issues.length,
+ rows: issues.slice(start, end).map((issue) => ({ issue, direct_child_count: 0 })),
+ branch_total: issues.length,
+ next_cursor: end < issues.length ? String(end) : null,
+ };
+ });
+ setApiInstance({ listIssueTableRows } as unknown as ApiClient);
+ const table = { scope: { kind: "workspace" }, filters: {}, sort: { field: "position", direction: "asc" } } as const;
+
+ const result = await new QueryClient().fetchQuery(sidebarIssuesOptions(WS_ID, "view:a", { table }, 120));
+
+ expect(result.issues).toHaveLength(120);
+ expect(result.total).toBe(120);
+ expect(listIssueTableRows.mock.calls.map(([params]) => params.page)).toEqual([
+ { limit: 100, cursor: null },
+ { limit: 20, cursor: "100" },
+ ]);
+ });
+
+ it("walks list pages past the server's 100-row cap", async () => {
+ const listIssues = vi.fn(async (params?: ListIssuesParams): Promise<ListIssuesResponse> => {
+ const offset = params?.offset ?? 0;
+ return { issues: issues.slice(offset, offset + Math.min(params?.limit ?? 100, 100)), total: issues.length };
+ });
+ installFakeApi(listIssues);
+
+ const result = await new QueryClient().fetchQuery(
+ sidebarIssuesOptions(WS_ID, "builtin:my_issues", { assignee_id: "u1" }, 130),
+ );
+
+ expect(result.issues.map((issue) => issue.id)).toEqual(issues.map((issue) => issue.id));
+ expect(listIssues.mock.calls.map(([params]) => [params?.limit, params?.offset])).toEqual([
+ [100, 0],
+ [30, 100],
+ ]);
+ });
+});
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index f807589057..8cc1e0357f 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -17,7 +17,9 @@ import type {
ListGroupedIssuesParams,
ListIssuesParams,
ListIssuesCache,
+ ListIssuesResponse,
} from "../types";
+import type { SidebarIssuesRequest } from "./sidebar-list";
import { ALL_STATUSES } from "./config";
import { issueColumnCategory } from "./status-category";
@@ -126,6 +128,14 @@ export const issueKeys = {
projectId,
assigneeTypes ?? null,
] as const,
+ /** Every sidebar issue list — prefix for cross-list refresh. */
+ sidebarAll: (wsId: string) => [...issueKeys.all(wsId), "sidebar"] as const,
+ /**
+ * One expanded sidebar row's issues. `source` (`project:{id}` / `view:{id}` / `builtin:{key}`)
+ * sits at a fixed index so realtime refresh can target a project's lists.
+ */
+ sidebar: (wsId: string, source: string, request: SidebarIssuesRequest, limit: number) =>
+ [...issueKeys.sidebarAll(wsId), source, request, limit] as const,
detail: (wsId: string, id: string) =>
[...issueKeys.all(wsId), "detail", id] as const,
/** Resolve a bare issue identifier (e.g. "MUL-123") to an issue. */
@@ -448,6 +458,61 @@ export function projectGanttIssuesOptions(
});
}
+/** Both list endpoints cap a page here, so a longer sidebar list is fetched in pages. */
+const SIDEBAR_MAX_PAGE = 100;
+
+async function listSidebarTableIssues(query: IssueTableQuerySpec, limit: number): Promise<ListIssuesResponse> {
+ const issues: Issue[] = [];
+ let total = 0;
+ let cursor: string | null = null;
+ do {
+ const page = await api.listIssueTableRows({
+ query,
+ group: { kind: "none" },
+ group_key: null,
+ hierarchy: { enabled: false },
+ parent_id: null,
+ page: { limit: Math.min(limit - issues.length, SIDEBAR_MAX_PAGE), cursor },
+ });
+ issues.push(...page.rows.map((row) => row.issue));
+ total = page.total;
+ cursor = page.next_cursor;
+ } while (cursor && issues.length < limit);
+ return { issues, total };
+}
+
+async function listSidebarIssues(params: ListIssuesParams, limit: number): Promise<ListIssuesResponse> {
+ const issues: Issue[] = [];
+ let total = 0;
+ do {
+ const page = await api.listIssues({
+ ...params,
+ limit: Math.min(limit - issues.length, SIDEBAR_MAX_PAGE),
+ offset: issues.length,
+ });
+ issues.push(...page.issues);
+ total = page.total;
+ if (page.issues.length === 0) break;
+ } while (issues.length < limit && issues.length < total);
+ return { issues, total };
+}
+
+/** The first `limit` issues of a sidebar list, with the filtered total. */
+export function sidebarIssuesOptions(
+ wsId: string,
+ source: string,
+ request: SidebarIssuesRequest,
+ limit: number,
+) {
+ return queryOptions({
+ queryKey: issueKeys.sidebar(wsId, source, request, limit),
+ queryFn: () =>
+ "table" in request
+ ? listSidebarTableIssues(request.table, limit)
+ : listSidebarIssues(request, limit),
+ });
+}
+
export function issueDetailOptions(wsId: string, id: string) {
return queryOptions({
queryKey: issueKeys.detail(wsId, id),
diff --git a/packages/core/issues/sidebar-list.test.ts b/packages/core/issues/sidebar-list.test.ts
new file mode 100644
index 0000000000..efbd31e55a
--- /dev/null
+++ b/packages/core/issues/sidebar-list.test.ts
@@ -0,0 +1,199 @@
+import { describe, expect, it } from "vitest";
+import type { Project } from "../types";
+import {
+ projectSidebarParams,
+ shownSidebarStatuses,
+ builtinSidebarRequest,
+ sidebarProjects,
+ viewSidebarRequest,
+} from "./sidebar-list";
+import {
+ DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ type SidebarIssueSettings,
+ type SidebarProjectSettings,
+} from "./stores/sidebar-tree-store";
+
+const STATUSES = [
+ { key: "backlog", category: "unstarted" },
+ { key: "todo", category: "unstarted" },
+ { key: "in_progress", category: "started" },
+ { key: "merged", category: "started" },
+ { key: "done", category: "done" },
+ { key: "cancelled", category: "closed" },
+] as const;
+
+describe("projectSidebarParams", () => {
+ it("leaves out finished statuses and sorts by update time by default", () => {
+ expect(projectSidebarParams("p1", DEFAULT_SIDEBAR_ISSUE_SETTINGS, STATUSES, "u1")).toEqual({
+ project_id: "p1",
+ statuses: ["backlog", "todo", "in_progress", "merged"],
+ sort_by: "updated_at",
+ sort_direction: "desc",
+ });
+ });
+
+ it("maps the assignee and sub-issue settings onto server filters", () => {
+ const settings: SidebarIssueSettings = {
+ ...DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ hiddenStatuses: [],
+ assignee: "my_agents",
+ showSubIssues: false,
+ };
+ expect(projectSidebarParams("p1", settings, STATUSES, "u1")).toEqual({
+ project_id: "p1",
+ involves_user_id: "u1",
+ top_level_only: true,
+ sort_by: "updated_at",
+ sort_direction: "desc",
+ });
+ });
+
+ it("lists nothing when every status is hidden", () => {
+ const settings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: STATUSES.map((s) => s.key) };
+ expect(shownSidebarStatuses(settings, STATUSES)).toEqual([]);
+ expect(projectSidebarParams("p1", settings, STATUSES, "u1")).toBeNull();
+ });
+});
+
+describe("viewSidebarRequest", () => {
+ const TODAY = "2026-03-11";
+ const workspace = { display: {}, scope_type: "workspace" as const, scope_variant: null };
+
+ it("carries the view's own filters, variant and ordering", () => {
+ expect(
+ viewSidebarRequest(
+ {
+ query: { statusFilters: ["todo"], labelFilters: ["l1"], priorityFilters: ["bogus"] },
+ display: { sortBy: "due_date", sortDirection: "desc", showSubIssues: false },
+ scope_variant: "agents",
+ },
+ TODAY,
+ ),
+ ).toEqual({
+ table: {
+ scope: { kind: "workspace", assignee_types: ["agent", "squad"] },
+ filters: { statuses: ["todo"], label_ids: ["l1"], include_sub_issues: false },
+ sort: { field: "due_date", direction: "desc" },
+ },
+ });
+ });
+
+ it("keeps the conditions the plain list endpoint could not express", () => {
+ const filters = (query: Record<string, unknown>) => viewSidebarRequest({ ...workspace, query }, TODAY)?.table.filters;
+ expect(filters({ relationFilters: ["assigned"] })).toMatchObject({ relations: ["assigned"] });
+ expect(filters({ statusFilters: ["done"], negatedFilters: ["status"] })).toMatchObject({
+ statuses: ["done"],
+ negate: ["statuses"],
+ });
+ expect(filters({ dueDateFilters: ["overdue"] })).toMatchObject({ due_dates: ["overdue"], today: TODAY });
+ expect(filters({ projectStatusFilters: ["completed"] })).toMatchObject({ project_statuses: ["completed"] });
+ expect(
+ filters({
+ advancedFilter: {
+ type: "group",
+ id: "root",
+ match: "any",
+ children: [{ type: "condition", id: "c1", field: "priority", negated: false, values: ["urgent"] }],
+ },
+ }),
+ ).toMatchObject({ advanced: { match: "any", children: [{ field: "priorities", values: ["urgent"] }] } });
+ // "Is not" with nothing selected is not a condition, and no due-date rule needs no day.
+ expect(filters({ negatedFilters: ["status"] })).toEqual({ include_sub_issues: true });
+ });
+
+ it("scopes project and my views like the page they open", () => {
+ const base = { query: {}, display: {} };
+ const scope = (view: Parameters<typeof viewSidebarRequest>[0]) => viewSidebarRequest(view, TODAY)?.table.scope;
+ expect(scope({ ...base, scope_type: "project", scope_id: "p1", scope_variant: null })).toEqual({
+ kind: "project",
+ project_id: "p1",
+ });
+ expect(scope({ ...base, scope_type: "my", scope_id: null, scope_variant: "created" })).toEqual({
+ kind: "my",
+ relation: "created",
+ });
+ expect(scope({ ...base, scope_type: "my", scope_id: null, scope_variant: null })).toEqual({
+ kind: "my",
+ relation: "any",
+ });
+ expect(scope({ ...base, scope_type: "project", scope_id: null, scope_variant: null })).toBeUndefined();
+ });
+
+ it("drops the dimension the scope already fixes", () => {
+ const project = viewSidebarRequest(
+ { query: { projectFilters: ["p2"], negatedFilters: ["project"] }, display: {}, scope_type: "project", scope_id: "p1", scope_variant: null },
+ TODAY,
+ );
+ expect(project?.table.filters).toEqual({ include_sub_issues: true });
+ const mine = viewSidebarRequest(
+ { query: { relationFilters: ["created"] }, display: {}, scope_type: "my", scope_id: null, scope_variant: "assigned" },
+ TODAY,
+ );
+ expect(mine?.table.filters).toEqual({ include_sub_issues: true });
+ });
+});
+
+describe("builtinSidebarRequest", () => {
+ it("scopes each built-in like its page and lists with the sidebar settings", () => {
+ const request = (builtin: Parameters<typeof builtinSidebarRequest>[0], relation: Parameters<typeof builtinSidebarRequest>[1] = "assigned") =>
+ builtinSidebarRequest(builtin, relation, DEFAULT_SIDEBAR_ISSUE_SETTINGS, STATUSES)?.table;
+ expect(request("all_issues")).toEqual({
+ scope: { kind: "workspace" },
+ filters: { statuses: ["backlog", "todo", "in_progress", "merged"], include_sub_issues: true },
+ sort: { field: "updated_at", direction: "desc" },
+ });
+ expect(request("my_issues", "created")?.scope).toEqual({ kind: "my", relation: "created" });
+ expect(request("my_issues", "all")?.scope).toEqual({ kind: "my", relation: "any" });
+ expect(request("my_agents", "assigned")?.scope).toEqual({ kind: "my", relation: "involved" });
+ });
+
+ it("maps the assignee setting and lists nothing when every status is hidden", () => {
+ const mine = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: [], assignee: "my_agents" as const };
+ expect(builtinSidebarRequest("all_issues", "assigned", mine, STATUSES)?.table.filters).toEqual({
+ relations: ["my_agents"],
+ include_sub_issues: true,
+ });
+ const none = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: STATUSES.map((s) => s.key) };
+ expect(builtinSidebarRequest("all_issues", "assigned", none, STATUSES)).toBeNull();
+ });
+});
+
+describe("sidebarProjects", () => {
+ const project = (id: string, title: string, status: Project["status"], lead_id: string | null = null) =>
+ ({
+ id,
+ title,
+ status,
+ lead_type: lead_id ? "member" : null,
+ lead_id,
+ created_at: `2026-10-0${id.slice(1)}T00:00:00Z`,
+ updated_at: `2026-10-0${id.slice(1)}T00:00:00Z`,
+ }) as Project;
+ const projects = [
+ project("p1", "Beta", "in_progress", "u1"),
+ project("p2", "Alpha", "planned"),
+ project("p3", "Gamma", "completed"),
+ project("p4", "Delta", "paused"),
+ ];
+
+ it("follows the manual order, then list order for projects it does not name", () => {
+ expect(sidebarProjects(projects, DEFAULT_SIDEBAR_PROJECT_SETTINGS, ["p4"], "u1").map((p) => p.id)).toEqual([
+ "p4",
+ "p1",
+ "p2",
+ ]);
+ });
+
+ it("filters by status and lead, and sorts by name", () => {
+ const settings: SidebarProjectSettings = {
+ ...DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ ordering: "name",
+ statuses: ["completed", "planned"],
+ };
+ expect(sidebarProjects(projects, settings, [], "u1").map((p) => p.title)).toEqual(["Alpha", "Gamma"]);
+ expect(
+ sidebarProjects(projects, { ...DEFAULT_SIDEBAR_PROJECT_SETTINGS, onlyMine: true }, [], "u1").map((p) => p.id),
+ ).toEqual(["p1"]);
+ });
+});
diff --git a/packages/core/issues/sidebar-list.ts b/packages/core/issues/sidebar-list.ts
new file mode 100644
index 0000000000..3e53bb8862
--- /dev/null
+++ b/packages/core/issues/sidebar-list.ts
@@ -0,0 +1,225 @@
+import type { IssueView } from "../api/schemas";
+import { baselineFromQuery } from "../issue-views/baseline";
+import type { BuiltinViewKey } from "../issue-views/sidebar-views";
+import type {
+ IssueStatusCategory,
+ IssueTableQuerySpec,
+ IssueTableRelation,
+ IssueTableScope,
+ IssueTableSortField,
+ ListIssuesParams,
+ Project,
+} from "../types";
+import { assigneeTypesForActorKind } from "./surface/scope";
+import { effectiveNegatedFilters } from "./stores/view-store";
+import { FILTER_DIMENSION_TABLE_FIELD, advancedFilterToTableQuery, advancedFilterUsesField } from "./stores/filter-tree";
+import type { MyIssuesRelation } from "./stores/my-issues-view-store";
+import type { SidebarIssueSettings, SidebarProjectSettings } from "./stores/sidebar-tree-store";
+
+/** Rows an expanded sidebar list shows before "Load more". */
+export const SIDEBAR_FIRST_PAGE = 5;
+/** Rows each "Load more" adds. */
+export const SIDEBAR_PAGE_STEP = 10;
+
+export const projectSidebarSource = (projectId: string) => `project:${projectId}`;
+export const viewSidebarSource = (viewId: string) => `view:${viewId}`;
+export const builtinSidebarSource = (builtin: BuiltinViewKey) => `builtin:${builtin}`;
+
+interface StatusRef {
+ key: string;
+ category: IssueStatusCategory;
+}
+
+const FINISHED: ReadonlySet<IssueStatusCategory> = new Set(["done", "closed"]);
+
+/** Status keys an expanded project lists, in catalog order. */
+export function shownSidebarStatuses(
+ settings: Pick<SidebarIssueSettings, "hiddenStatuses">,
+ statuses: readonly StatusRef[],
+): string[] {
+ const hidden = new Set(
+ settings.hiddenStatuses ?? statuses.filter((s) => FINISHED.has(s.category)).map((s) => s.key),
+ );
+ return statuses.filter((s) => !hidden.has(s.key)).map((s) => s.key);
+}
+
+/** List params for an expanded project, or `null` when the settings leave nothing to list. */
+export function projectSidebarParams(
+ projectId: string,
+ settings: SidebarIssueSettings,
+ statuses: readonly StatusRef[],
+ userId: string | undefined,
+): ListIssuesParams | null {
+ const shown = shownSidebarStatuses(settings, statuses);
+ if (shown.length === 0) return null;
+ if (settings.assignee !== "anyone" && !userId) return null;
+ return {
+ project_id: projectId,
+ ...(shown.length < statuses.length ? { statuses: shown } : {}),
+ ...(settings.assignee === "me" ? { assignee_id: userId } : {}),
+ ...(settings.assignee === "my_agents" ? { involves_user_id: userId } : {}),
+ ...(settings.showSubIssues ? {} : { top_level_only: true }),
+ sort_by: settings.sortBy,
+ sort_direction: settings.sortDirection,
+ };
+}
+
+const VIEW_SORTS = new Set<string>([
+ "position",
+ "status",
+ "priority",
+ "title",
+ "created_at",
+ "updated_at",
+ "last_activity",
+ "start_date",
+ "due_date",
+]);
+
+type SidebarViewFields = Pick<IssueView, "query" | "display" | "scope_variant"> &
+ Partial<Pick<IssueView, "scope_type" | "scope_id">>;
+
+/** A sidebar list read through the table query, which can express every view filter. */
+export interface SidebarTableRequest {
+ table: IssueTableQuerySpec;
+}
+
+export type SidebarIssuesRequest = ListIssuesParams | SidebarTableRequest;
+
+export const isSidebarTableRequest = (request: SidebarIssuesRequest): request is SidebarTableRequest =>
+ "table" in request;
+
+function viewTableScope(view: SidebarViewFields): IssueTableScope | null {
+ const assigneeTypes = assigneeTypesForActorKind(
+ view.scope_variant === "members" || view.scope_variant === "agents" ? view.scope_variant : undefined,
+ );
+ const typed = assigneeTypes ? { assignee_types: assigneeTypes } : {};
+ switch (view.scope_type ?? "workspace") {
+ case "workspace":
+ return { kind: "workspace", ...typed };
+ case "project":
+ return view.scope_id ? { kind: "project", project_id: view.scope_id, ...typed } : null;
+ case "my": {
+ const variant = view.scope_variant ?? "any";
+ return variant === "assigned" || variant === "created" || variant === "involved" || variant === "any"
+ ? { kind: "my", relation: variant }
+ : null;
+ }
+ default:
+ return null;
+ }
+}
+
+function viewTableSort(display: Record<string, unknown>): IssueTableQuerySpec["sort"] {
+ const field =
+ typeof display.sortBy === "string" && (VIEW_SORTS.has(display.sortBy) || display.sortBy.startsWith("property:"))
+ ? (display.sortBy as IssueTableSortField)
+ : "position";
+ return { field, direction: display.sortDirection === "desc" ? "desc" : "asc" };
+}
+
+/**
+ * The request for an expanded saved view: its scope, filters and ordering,
+ * so the sidebar lists what opening the view shows. `null` when the view's
+ * scope cannot be listed.
+ */
+export function viewSidebarRequest(view: SidebarViewFields, today: string): SidebarTableRequest | null {
+ const scope = viewTableScope(view);
+ if (!scope) return null;
+ const { raw } = baselineFromQuery(view.query);
+ // Same as the surface: a project view drops the project dimension, a "my"
+ // view the viewer-relation one.
+ const fields = {
+ ...raw,
+ ...(scope.kind === "project" ? { projectFilters: [], includeNoProject: false } : {}),
+ ...(scope.kind === "my" ? { relationFilters: [] } : {}),
+ };
+ const negate = effectiveNegatedFilters(fields).map((dimension) => FILTER_DIMENSION_TABLE_FIELD[dimension]);
+ const advanced = advancedFilterToTableQuery(fields.advancedFilter);
+ const usesDueDates = fields.dueDateFilters.length > 0 || advancedFilterUsesField(fields.advancedFilter, "dueDate");
+ const display = view.display ?? {};
+
+ return {
+ table: {
+ scope,
+ filters: {
+ ...(fields.statusFilters.length > 0 ? { statuses: fields.statusFilters } : {}),
+ ...(fields.priorityFilters.length > 0 ? { priorities: fields.priorityFilters } : {}),
+ ...(fields.assigneeFilters.length > 0 ? { assignees: fields.assigneeFilters } : {}),
+ ...(fields.includeNoAssignee ? { include_no_assignee: true } : {}),
+ ...(fields.creatorFilters.length > 0 ? { creators: fields.creatorFilters } : {}),
+ ...(fields.projectFilters.length > 0 ? { project_ids: fields.projectFilters } : {}),
+ ...(fields.includeNoProject ? { include_no_project: true } : {}),
+ ...(fields.projectStatusFilters.length > 0 ? { project_statuses: fields.projectStatusFilters } : {}),
+ ...(fields.labelFilters.length > 0 ? { label_ids: fields.labelFilters } : {}),
+ ...(fields.relationFilters.length > 0 ? { relations: fields.relationFilters } : {}),
+ ...(fields.dueDateFilters.length > 0 ? { due_dates: fields.dueDateFilters } : {}),
+ ...(usesDueDates ? { today } : {}),
+ ...(negate.length > 0 ? { negate } : {}),
+ ...(advanced ? { advanced } : {}),
+ ...(Object.keys(fields.propertyFilters).length > 0 ? { properties: fields.propertyFilters } : {}),
+ include_sub_issues: display.showSubIssues !== false,
+ },
+ sort: viewTableSort(display),
+ },
+ };
+}
+
+/**
+ * The request for an expanded built-in view: the page's scope, listed with
+ * the same sidebar settings as an expanded project. `null` when the settings
+ * leave nothing to list.
+ */
+export function builtinSidebarRequest(
+ builtin: BuiltinViewKey,
+ myRelation: MyIssuesRelation,
+ settings: SidebarIssueSettings,
+ statuses: readonly StatusRef[],
+): SidebarTableRequest | null {
+ const shown = shownSidebarStatuses(settings, statuses);
+ if (shown.length === 0) return null;
+ const relation = builtin === "my_agents" ? "involved" : myRelation === "all" ? "any" : myRelation;
+ const relations: IssueTableRelation[] =
+ settings.assignee === "me" ? ["assigned"] : settings.assignee === "my_agents" ? ["my_agents"] : [];
+ return {
+ table: {
+ scope: builtin === "all_issues" ? { kind: "workspace" } : { kind: "my", relation },
+ filters: {
+ ...(shown.length < statuses.length ? { statuses: shown } : {}),
+ ...(relations.length > 0 ? { relations } : {}),
+ include_sub_issues: settings.showSubIssues,
+ },
+ sort: { field: settings.sortBy, direction: settings.sortDirection },
+ },
+ };
+}
+
+/** The projects the sidebar lists, filtered and ordered by its settings. */
+export function sidebarProjects<P extends Pick<Project, "id" | "title" | "status" | "lead_type" | "lead_id" | "created_at" | "updated_at">>(
+ projects: readonly P[],
+ settings: SidebarProjectSettings,
+ manualOrder: readonly string[],
+ userId: string | undefined,
+): P[] {
+ const statuses = new Set<string>(settings.statuses);
+ const shown = projects.filter(
+ (p) =>
+ statuses.has(p.status) &&
+ (!settings.onlyMine || (p.lead_type === "member" && !!userId && p.lead_id === userId)),
+ );
+ switch (settings.ordering) {
+ case "name":
+ return shown.sort((a, b) => a.title.localeCompare(b.title));
+ case "updated":
+ return shown.sort((a, b) => b.updated_at.localeCompare(a.updated_at));
+ case "created":
+ return shown.sort((a, b) => b.created_at.localeCompare(a.created_at));
+ case "manual": {
+ const rank = new Map(manualOrder.map((id, i) => [id, i]));
+ return shown
+ .map((p, i) => ({ p, i }))
+ .sort((a, b) => (rank.get(a.p.id) ?? manualOrder.length + a.i) - (rank.get(b.p.id) ?? manualOrder.length + b.i))
+ .map(({ p }) => p);
+ }
+ }
+}
diff --git a/packages/core/issues/status-category.ts b/packages/core/issues/status-category.ts
index 2f33267868..e0246ed371 100644
--- a/packages/core/issues/status-category.ts
+++ b/packages/core/issues/status-category.ts
@@ -149,7 +149,16 @@ export function visibleStatusKeys(
statusFilters: readonly string[],
hiddenStatuses: readonly IssueStatus[],
catalog: Pick<IssueStatusCatalog, "statuses" | "entryOf" | "isLoaded" | "isPending" | "isError">,
+ negated = false,
): IssueStatus[] {
+ // "Status is not X" keeps the everyday board and drops X. Exact keys need no
+ // catalog resolution, and archived columns stay hidden as without a filter.
+ if (negated && statusFilters.length > 0) {
+ const excluded = new Set<string>(statusFilters);
+ return statusColumnKeys(catalog).filter(
+ (key) => !excluded.has(key) && !hiddenStatuses.includes(key),
+ );
+ }
const resolved = statusFilters.length > 0 ? statusFilterColumns(statusFilters, catalog) : null;
const selected = resolved?.state === "resolved" ? resolved.columns : null;
// Old archives may still carry issues. An explicit exact-key filter remains
diff --git a/packages/core/issues/status-columns.test.ts b/packages/core/issues/status-columns.test.ts
index a22929ed8d..3272fbbbf9 100644
--- a/packages/core/issues/status-columns.test.ts
+++ b/packages/core/issues/status-columns.test.ts
@@ -38,4 +38,11 @@ describe("concrete status columns", () => {
expect(visibleStatusKeys(["awaiting_response"], [], catalog)).toEqual(["awaiting_response"]);
expect(visibleStatusKeys(["backlog"], ["backlog"], catalog)).toEqual(["backlog"]);
});
+ it("'status is not' keeps the everyday board minus the excluded keys", () => {
+ expect(visibleStatusKeys(["done", "cancelled"], ["backlog"], catalog, true)).toEqual([
+ "todo", "in_progress", "in_review", "blocked", "awaiting_response",
+ ]);
+ // Excluding a key never brings back an archived column.
+ expect(visibleStatusKeys(["done"], [], catalog, true)).not.toContain("old_review");
+ });
});
diff --git a/packages/core/issues/stores/filter-operators.test.ts b/packages/core/issues/stores/filter-operators.test.ts
new file mode 100644
index 0000000000..6995f483fc
--- /dev/null
+++ b/packages/core/issues/stores/filter-operators.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import { createFilterCondition, propertyFilterField } from "./filter-tree";
+import {
+ PROPERTY_FILTER_NONE_VALUE,
+ conditionOperator,
+ conditionText,
+ filterFieldSpec,
+ filterOperatorsFor,
+ withConditionOperator,
+ withConditionText,
+} from "./filter-operators";
+
+const estimate = propertyFilterField("estimate");
+
+describe("filterOperatorsFor", () => {
+ it("offers operators by how the field holds values", () => {
+ const status = createFilterCondition("status");
+ expect(filterOperatorsFor(filterFieldSpec(status))).toEqual(["is", "is_not"]);
+ expect(filterOperatorsFor(filterFieldSpec(createFilterCondition("assignee")))).toEqual([
+ "is",
+ "is_not",
+ "is_empty",
+ "is_not_empty",
+ ]);
+ const number = createFilterCondition(estimate);
+ expect(filterOperatorsFor(filterFieldSpec(number, "number"))).toEqual([
+ "is", "is_not", "gt", "gte", "lt", "lte", "is_empty", "is_not_empty",
+ ]);
+ expect(filterOperatorsFor(filterFieldSpec(number, "url"))).toContain("not_contains");
+ expect(filterFieldSpec(createFilterCondition("label")).kind).toBe("multi");
+ // A type this build doesn't know still gets the basic operators.
+ expect(filterFieldSpec(number, "formula")).toEqual({ kind: "option", nullable: true });
+ });
+});
+
+describe("conditionOperator", () => {
+ it("reads operators off the stored values", () => {
+ const text = filterFieldSpec(createFilterCondition(estimate), "text");
+ expect(conditionOperator(createFilterCondition("status", ["todo"], true), filterFieldSpec(createFilterCondition("status")))).toBe("is_not");
+ expect(conditionOperator(createFilterCondition(estimate, [{ op: "contains", value: "a" }], true), text)).toBe("not_contains");
+ expect(conditionOperator(createFilterCondition(estimate, [{ op: "gte", value: "3" }]), text)).toBe("gte");
+ expect(conditionOperator(createFilterCondition(estimate, [PROPERTY_FILTER_NONE_VALUE], true), text)).toBe("is_not_empty");
+ const assignee = createFilterCondition("assignee", ["none"]);
+ expect(conditionOperator(assignee, filterFieldSpec(assignee))).toBe("is_empty");
+ // "No assignee or Lambda" is a value list, not emptiness.
+ const either = createFilterCondition("assignee", ["none", "agent:a1"]);
+ expect(conditionOperator(either, filterFieldSpec(either))).toBe("is");
+ });
+});
+
+describe("withConditionOperator", () => {
+ it("keeps picked values between is and is not", () => {
+ const label = createFilterCondition("label", ["bug", "ui"]);
+ const next = withConditionOperator(label, filterFieldSpec(label), "is_not");
+ expect(next).toMatchObject({ negated: true, values: ["bug", "ui"] });
+ });
+
+ it("stores emptiness as the field's no-value member", () => {
+ const project = createFilterCondition("project", ["p1"]);
+ expect(withConditionOperator(project, filterFieldSpec(project), "is_not_empty")).toMatchObject({
+ negated: true,
+ values: ["none"],
+ });
+ const empty = createFilterCondition("project", ["none"]);
+ expect(withConditionOperator(empty, filterFieldSpec(empty), "is")).toMatchObject({ negated: false, values: [] });
+ });
+
+ it("carries a typed value across operators", () => {
+ const condition = createFilterCondition(estimate, ["5", PROPERTY_FILTER_NONE_VALUE]);
+ const spec = filterFieldSpec(condition, "number");
+ const gt = withConditionOperator(condition, spec, "gt");
+ expect(gt).toMatchObject({ negated: false, values: [{ op: "gt", value: "5" }, PROPERTY_FILTER_NONE_VALUE] });
+ expect(withConditionOperator(gt, spec, "is_not")).toMatchObject({
+ negated: true,
+ values: ["5", PROPERTY_FILTER_NONE_VALUE],
+ });
+ const notContains = withConditionOperator(createFilterCondition(estimate, ["api"]), spec, "not_contains");
+ expect(notContains).toMatchObject({ negated: true, values: [{ op: "contains", value: "api" }] });
+ expect(conditionText(notContains)).toBe("api");
+ });
+});
+
+describe("withConditionText", () => {
+ it("drops an empty value so the condition filters nothing", () => {
+ const condition = createFilterCondition(estimate, [{ op: "contains", value: "a" }]);
+ expect(withConditionText(condition, "contains", " ").values).toEqual([]);
+ expect(withConditionText(condition, "after", "2026-01-01").values).toEqual([{ op: "after", value: "2026-01-01" }]);
+ });
+});
diff --git a/packages/core/issues/stores/filter-operators.ts b/packages/core/issues/stores/filter-operators.ts
new file mode 100644
index 0000000000..988aed7284
--- /dev/null
+++ b/packages/core/issues/stores/filter-operators.ts
@@ -0,0 +1,193 @@
+import { isPropertyOperatorFilter, type PropertyFilterOp, type PropertyFilterValue } from "../../types";
+import {
+ FILTER_NONE_VALUE,
+ isPropertyCondition,
+ type AdvancedFilterCondition,
+ type NegatableFilterDimension,
+} from "./filter-tree";
+
+/** The "no value" member of a property condition. */
+export const PROPERTY_FILTER_NONE_VALUE = "__none__";
+
+/**
+ * What a condition says about its field. Every operator is a reading of the
+ * stored `negated` + `values`, so trees, saved views and the server query
+ * keep one shape:
+ *
+ * - `is` / `is_not`: the values, plain or negated.
+ * - `is_empty` / `is_not_empty`: only the field's "no value" member.
+ * - `contains`, comparisons, `before` / `after`: one operator member;
+ * `not_contains` is a negated `contains`.
+ */
+export type FilterOperator =
+ | "is"
+ | "is_not"
+ | "contains"
+ | "not_contains"
+ | "gt"
+ | "gte"
+ | "lt"
+ | "lte"
+ | "before"
+ | "after"
+ | "is_empty"
+ | "is_not_empty";
+
+/**
+ * How a field holds values, which decides its operators and value editor:
+ * `option` is one pick per issue, `multi` a set of picks (labels, multi
+ * select), `list` a set of free-form strings, the rest single scalars.
+ */
+export type FilterFieldKind = "option" | "multi" | "list" | "text" | "number" | "date";
+
+export interface FilterFieldSpec {
+ kind: FilterFieldKind;
+ /** Whether the field can be unset, so "is empty" means something. */
+ nullable: boolean;
+}
+
+const DIMENSION_SPECS: Record<NegatableFilterDimension, FilterFieldSpec> = {
+ status: { kind: "option", nullable: false },
+ priority: { kind: "option", nullable: false },
+ assignee: { kind: "option", nullable: true },
+ creator: { kind: "option", nullable: false },
+ project: { kind: "option", nullable: true },
+ projectStatus: { kind: "option", nullable: false },
+ label: { kind: "multi", nullable: false },
+ relation: { kind: "option", nullable: false },
+ dueDate: { kind: "option", nullable: true },
+};
+
+const PROPERTY_KINDS: Record<string, FilterFieldKind> = {
+ select: "option",
+ actor: "option",
+ checkbox: "option",
+ multi_select: "multi",
+ multi_actor: "multi",
+ multi_text: "list",
+ multi_url: "list",
+ text: "text",
+ url: "text",
+ number: "number",
+ date: "date",
+};
+
+/** A condition's field spec. A property needs its definition's type; an
+ * unknown or missing one reads as a plain option field. */
+export function filterFieldSpec(condition: AdvancedFilterCondition, propertyType?: string): FilterFieldSpec {
+ if (!isPropertyCondition(condition)) return DIMENSION_SPECS[condition.field];
+ return { kind: (propertyType && PROPERTY_KINDS[propertyType]) || "option", nullable: true };
+}
+
+const KIND_OPERATORS: Record<FilterFieldKind, readonly FilterOperator[]> = {
+ option: ["is", "is_not"],
+ multi: ["is", "is_not"],
+ list: ["is", "is_not"],
+ text: ["is", "is_not", "contains", "not_contains"],
+ number: ["is", "is_not", "gt", "gte", "lt", "lte"],
+ date: ["is", "is_not", "before", "after"],
+};
+
+/** The operators a field offers, in menu order. */
+export function filterOperatorsFor(spec: FilterFieldSpec): FilterOperator[] {
+ return [...KIND_OPERATORS[spec.kind], ...(spec.nullable ? (["is_empty", "is_not_empty"] as const) : [])];
+}
+
+/** Operators that carry no value. */
+export function isEmptinessOperator(op: FilterOperator): boolean {
+ return op === "is_empty" || op === "is_not_empty";
+}
+
+/** Kinds whose value is typed rather than picked. */
+export function isTypedValueKind(kind: FilterFieldKind): boolean {
+ return kind === "text" || kind === "number" || kind === "date" || kind === "list";
+}
+
+function noneValue(condition: AdvancedFilterCondition): string {
+ return isPropertyCondition(condition) ? PROPERTY_FILTER_NONE_VALUE : FILTER_NONE_VALUE;
+}
+
+function operatorMember(values: readonly PropertyFilterValue[]) {
+ return values.find(isPropertyOperatorFilter);
+}
+
+/** The operator a stored condition reads as. */
+export function conditionOperator(condition: AdvancedFilterCondition, spec: FilterFieldSpec): FilterOperator {
+ const values = condition.values as readonly PropertyFilterValue[];
+ const member = operatorMember(values);
+ if (member) return member.op === "contains" && condition.negated ? "not_contains" : member.op;
+ if (spec.nullable && values.length === 1 && values[0] === noneValue(condition)) {
+ return condition.negated ? "is_not_empty" : "is_empty";
+ }
+ return condition.negated ? "is_not" : "is";
+}
+
+/** The typed value of a text, number, date or list condition. */
+export function conditionText(condition: AdvancedFilterCondition): string {
+ const values = condition.values as readonly PropertyFilterValue[];
+ const member = operatorMember(values);
+ if (member) return member.value;
+ const none = noneValue(condition);
+ return values.find((v): v is string => typeof v === "string" && v !== none) ?? "";
+}
+
+function storedOp(op: FilterOperator): PropertyFilterOp | null {
+ switch (op) {
+ case "is":
+ case "is_not":
+ case "is_empty":
+ case "is_not_empty":
+ return null;
+ case "not_contains":
+ return "contains";
+ default:
+ return op;
+ }
+}
+
+/**
+ * A typed value under an operator. "No value" stays a member alongside it,
+ * the way the simple property filter composes the two.
+ */
+export function withConditionText(
+ condition: AdvancedFilterCondition,
+ op: FilterOperator,
+ text: string,
+): AdvancedFilterCondition {
+ const value = text.trim();
+ const none = noneValue(condition);
+ const keepNone = (condition.values as readonly PropertyFilterValue[]).includes(none) && !isEmptinessOperator(op);
+ const stored = storedOp(op);
+ const member: PropertyFilterValue | null =
+ value && value !== none && !isEmptinessOperator(op) ? (stored ? { op: stored, value } : value) : null;
+ return {
+ ...condition,
+ negated: op === "is_not" || op === "not_contains",
+ values: [...(member ? [member] : []), ...(keepNone ? [none] : [])],
+ } as AdvancedFilterCondition;
+}
+
+/**
+ * The condition under another operator. Picked values survive a switch
+ * between "is" and "is not", a typed value survives any switch between
+ * value operators, and "is empty" replaces whatever was there.
+ */
+export function withConditionOperator(
+ condition: AdvancedFilterCondition,
+ spec: FilterFieldSpec,
+ op: FilterOperator,
+): AdvancedFilterCondition {
+ const none = noneValue(condition);
+ if (isEmptinessOperator(op)) {
+ return { ...condition, negated: op === "is_not_empty", values: [none] } as AdvancedFilterCondition;
+ }
+ const current = conditionOperator(condition, spec);
+ if (isTypedValueKind(spec.kind)) {
+ return withConditionText(condition, op, isEmptinessOperator(current) ? "" : conditionText(condition));
+ }
+ return {
+ ...condition,
+ negated: op === "is_not",
+ values: isEmptinessOperator(current) ? [] : condition.values,
+ } as AdvancedFilterCondition;
+}
diff --git a/packages/core/issues/stores/filter-tree.test.ts b/packages/core/issues/stores/filter-tree.test.ts
new file mode 100644
index 0000000000..ddd6bcfedf
--- /dev/null
+++ b/packages/core/issues/stores/filter-tree.test.ts
@@ -0,0 +1,282 @@
+import { describe, expect, it } from "vitest";
+import {
+ advancedFilterFromSimple,
+ advancedFilterSignature,
+ advancedFilterToTableQuery,
+ countAdvancedConditions,
+ createFilterCondition,
+ createFilterGroup,
+ dueDateMatches,
+ editAdvancedFilter,
+ EMPTY_SIMPLE_FILTER_FIELDS,
+ foldPropertyFiltersIntoTree,
+ pruneAdvancedFilter,
+ sanitizeAdvancedFilter,
+ simpleFromAdvancedFilter,
+ statusColumnFilter,
+ withoutAdvancedFilterFields,
+ type SimpleFilterFields,
+} from "./filter-tree";
+
+function simple(patch: Partial<SimpleFilterFields>): SimpleFilterFields {
+ return { ...EMPTY_SIMPLE_FILTER_FIELDS, ...patch };
+}
+
+describe("dueDateMatches", () => {
+ // Wednesday.
+ const today = "2026-03-11";
+
+ it.each([
+ ["2026-03-10", "overdue", true],
+ ["2026-03-11", "overdue", false],
+ ["2026-03-11", "today", true],
+ ["2026-03-09", "this_week", true],
+ ["2026-03-15", "this_week", true],
+ ["2026-03-16", "this_week", false],
+ ["2026-03-08", "this_week", false],
+ ["2026-03-11", "next_7_days", true],
+ ["2026-03-17", "next_7_days", true],
+ ["2026-03-18", "next_7_days", false],
+ ["2026-03-10", "next_7_days", false],
+ [null, "none", true],
+ ["2026-03-11", "none", false],
+ [null, "overdue", false],
+ ] as const)("%s in %s → %s", (due, bucket, expected) => {
+ expect(dueDateMatches(due, bucket, today)).toBe(expected);
+ });
+
+ it("starts the week on Monday when today is Sunday", () => {
+ expect(dueDateMatches("2026-03-09", "this_week", "2026-03-15")).toBe(true);
+ expect(dueDateMatches("2026-03-16", "this_week", "2026-03-15")).toBe(false);
+ });
+});
+
+describe("simple ↔ advanced", () => {
+ it("turns each dimension into one condition and back", () => {
+ const fields = simple({
+ statusFilters: ["todo", "in_progress"],
+ assigneeFilters: [{ type: "agent", id: "a1" }],
+ includeNoAssignee: true,
+ projectFilters: ["p1"],
+ dueDateFilters: ["overdue"],
+ negatedFilters: ["status"],
+ });
+ const tree = advancedFilterFromSimple(fields, fields.negatedFilters);
+ expect(tree.match).toBe("all");
+ expect(tree.children.map((c) => c.type === "condition" && [c.field, c.negated, c.values])).toEqual([
+ ["status", true, ["todo", "in_progress"]],
+ ["assignee", false, ["agent:a1", "none"]],
+ ["project", false, ["p1"]],
+ ["dueDate", false, ["overdue"]],
+ ]);
+ expect(simpleFromAdvancedFilter(tree)).toEqual(fields);
+ });
+
+ it("refuses what simple mode cannot say", () => {
+ const status = createFilterCondition("status", ["todo"]);
+ const label = createFilterCondition("label", ["l1"]);
+ expect(simpleFromAdvancedFilter(createFilterGroup("any", [status, label]))).toBeNull();
+ expect(
+ simpleFromAdvancedFilter(createFilterGroup("all", [status, createFilterCondition("status", ["done"], true)])),
+ ).toBeNull();
+ expect(simpleFromAdvancedFilter(createFilterGroup("all", [createFilterGroup("any", [status])]))).toBeNull();
+ });
+
+ it("carries property filters as conditions", () => {
+ const fields = simple({
+ priorityFilters: ["urgent"],
+ propertyFilters: { p1: ["opt-a", "__none__"], p2: [{ op: "gte", value: "3" }] },
+ });
+ const tree = advancedFilterFromSimple(fields, []);
+ expect(tree.children.map((c) => c.type === "condition" && [c.field, c.values])).toEqual([
+ ["priority", ["urgent"]],
+ ["property:p1", ["opt-a", "__none__"]],
+ ["property:p2", [{ op: "gte", value: "3" }]],
+ ]);
+ expect(simpleFromAdvancedFilter(tree)).toEqual(fields);
+ // Simple mode has no "is not" for a property.
+ expect(
+ simpleFromAdvancedFilter(createFilterGroup("all", [createFilterCondition("property:p1", ["opt-a"], true)])),
+ ).toBeNull();
+ });
+
+ it("accepts a lone condition under any, and ignores empty rows", () => {
+ const status = createFilterCondition("status", ["todo"]);
+ const tree = createFilterGroup("any", [status, createFilterCondition("label")]);
+ expect(simpleFromAdvancedFilter(tree)?.statusFilters).toEqual(["todo"]);
+ });
+});
+
+describe("tree helpers", () => {
+ it("prunes empty conditions and groups", () => {
+ const tree = createFilterGroup("all", [
+ createFilterCondition("status"),
+ createFilterGroup("any", [createFilterCondition("label")]),
+ ]);
+ expect(pruneAdvancedFilter(tree)).toBeNull();
+ expect(countAdvancedConditions(tree)).toBe(0);
+ });
+
+ it("edits, removes and duplicates by id", () => {
+ const a = createFilterCondition("status", ["todo"]);
+ const b = createFilterCondition("label", ["l1"]);
+ const group = createFilterGroup("any", [b]);
+ const root = createFilterGroup("all", [a, group]);
+ const removed = editAdvancedFilter(root, b.id, () => []);
+ expect((removed.children[1] as typeof group).children).toEqual([]);
+ const duplicated = editAdvancedFilter(root, a.id, (node) => [node, { ...node, id: "copy" }]);
+ expect(duplicated.children.map((c) => c.id)).toEqual([a.id, "copy", group.id]);
+ // The input is never mutated.
+ expect(root.children).toHaveLength(2);
+ });
+
+ it("compares trees without their ids", () => {
+ const one = createFilterGroup("all", [createFilterCondition("status", ["b", "a"])]);
+ const two = createFilterGroup("all", [createFilterCondition("status", ["a", "b"])]);
+ expect(advancedFilterSignature(one)).toBe(advancedFilterSignature(two));
+ });
+
+ it("strips the fields a scope fixes", () => {
+ const tree = createFilterGroup("all", [
+ createFilterCondition("relation", ["assigned"]),
+ createFilterGroup("any", [createFilterCondition("project", ["p1"])]),
+ ]);
+ expect(withoutAdvancedFilterFields(tree, ["relation", "project"])).toBeNull();
+ expect(countAdvancedConditions(withoutAdvancedFilterFields(tree, ["project"]))).toBe(1);
+ });
+
+ it("folds flat property filters into a tree, ANDed like they were", () => {
+ const status = createFilterCondition("status", ["todo"]);
+ const label = createFilterCondition("label", ["l1"]);
+ const props = { p1: ["opt-a"] };
+ const all = foldPropertyFiltersIntoTree(createFilterGroup("all", [status]), props);
+ expect(all?.children.map((c) => c.type === "condition" && c.field)).toEqual(["status", "property:p1"]);
+
+ const any = foldPropertyFiltersIntoTree(createFilterGroup("any", [status, label]), props);
+ expect(any?.match).toBe("all");
+ expect(any?.children[0]).toMatchObject({ type: "group", match: "any", children: [status, label] });
+ expect(any?.children[1]).toMatchObject({ field: "property:p1", values: ["opt-a"] });
+
+ // An "any" root that already holds a group can't take another level.
+ expect(
+ foldPropertyFiltersIntoTree(createFilterGroup("any", [status, createFilterGroup("all", [label])]), props),
+ ).toBeNull();
+ const untouched = createFilterGroup("any", [status]);
+ expect(foldPropertyFiltersIntoTree(untouched, { p1: [] })).toBe(untouched);
+ });
+
+ it("converts to the table query", () => {
+ const tree = createFilterGroup("all", [
+ createFilterCondition("project", ["p1"]),
+ createFilterGroup("any", [
+ createFilterCondition("priority", ["urgent"]),
+ createFilterCondition("dueDate", ["overdue"], true),
+ createFilterCondition("label"),
+ createFilterCondition("property:p1", [{ op: "lt", value: "3" }, "__none__"], true),
+ ]),
+ ]);
+ expect(advancedFilterToTableQuery(tree)).toEqual({
+ match: "all",
+ children: [
+ { field: "project_ids", values: ["p1"] },
+ {
+ match: "any",
+ children: [
+ { field: "priorities", values: ["urgent"] },
+ { field: "due_dates", negate: true, values: ["overdue"] },
+ { field: "property:p1", negate: true, values: [{ op: "lt", value: "3" }, "__none__"] },
+ ],
+ },
+ ],
+ });
+ });
+});
+
+describe("sanitizeAdvancedFilter", () => {
+ it("keeps known fields and values and drops the rest", () => {
+ const tree = sanitizeAdvancedFilter({
+ type: "group",
+ id: "root",
+ match: "any",
+ children: [
+ { type: "condition", id: "c1", field: "priority", negated: true, values: ["urgent", "bogus", "urgent"] },
+ { type: "condition", id: "c2", field: "nope", values: ["x"] },
+ { type: "condition", id: "c3", field: "creator", values: ["none", "member:u1", "robot:x"] },
+ {
+ type: "condition",
+ id: "c4",
+ field: "property:p1",
+ values: ["opt-a", "", 3, { op: "gte", value: "2" }, { op: "bogus", value: "2" }, "opt-a"],
+ },
+ { type: "condition", id: "c5", field: "property:", values: ["x"] },
+ {
+ type: "group",
+ id: "g1",
+ match: "all",
+ // Deeper than one level is not representable.
+ children: [{ type: "group", id: "g2", match: "all", children: [] }],
+ },
+ ],
+ });
+ expect(tree).toEqual({
+ type: "group",
+ id: "root",
+ match: "any",
+ children: [
+ { type: "condition", id: "c1", field: "priority", negated: true, values: ["urgent"] },
+ { type: "condition", id: "c3", field: "creator", negated: false, values: ["member:u1"] },
+ {
+ type: "condition",
+ id: "c4",
+ field: "property:p1",
+ negated: false,
+ values: ["opt-a", { op: "gte", value: "2" }],
+ },
+ { type: "group", id: "g1", match: "all", children: [] },
+ ],
+ });
+ });
+
+ it("rejects anything that is not a group", () => {
+ expect(sanitizeAdvancedFilter(null)).toBeNull();
+ expect(sanitizeAdvancedFilter({ type: "condition", field: "status", values: ["x"] })).toBeNull();
+ });
+});
+
+describe("statusColumnFilter", () => {
+ const hidden = ["cancelled", "done"];
+
+ it("keeps the simple status filter, which the tree is ANDed with", () => {
+ const tree = createFilterGroup("all", [createFilterCondition("status", ["todo"])]);
+ expect(statusColumnFilter(["cancelled"], false, tree, hidden)).toEqual({
+ statuses: ["cancelled"],
+ negated: false,
+ hiddenStatuses: hidden,
+ });
+ });
+
+ it("picks columns from a status every row must meet", () => {
+ const tree = createFilterGroup("all", [
+ createFilterCondition("status", ["cancelled"], true),
+ createFilterGroup("any", [createFilterCondition("priority", ["urgent"])]),
+ ]);
+ expect(statusColumnFilter([], false, tree, hidden)).toEqual({
+ statuses: ["cancelled"],
+ negated: true,
+ hiddenStatuses: hidden,
+ });
+ });
+
+ it("un-hides a status a looser tree names, without narrowing", () => {
+ const tree = createFilterGroup("any", [
+ createFilterCondition("status", ["cancelled"]),
+ createFilterCondition("status", ["done"], true),
+ createFilterCondition("priority", ["urgent"]),
+ ]);
+ expect(statusColumnFilter([], false, tree, hidden)).toEqual({
+ statuses: [],
+ negated: false,
+ hiddenStatuses: ["done"],
+ });
+ });
+});
diff --git a/packages/core/issues/stores/filter-tree.ts b/packages/core/issues/stores/filter-tree.ts
new file mode 100644
index 0000000000..7e6dbeb97f
--- /dev/null
+++ b/packages/core/issues/stores/filter-tree.ts
@@ -0,0 +1,640 @@
+import {
+ isKnownPropertyFilterOp,
+ isPropertyOperatorFilter,
+ propertyFilterValueKey,
+ type IssuePriority,
+ type IssueStatus,
+ type IssueTableFilterGroup,
+ type IssueTableFilterNode,
+ type IssueTableNegatableFilter,
+ type ProjectStatus,
+ type PropertyFilterValue,
+} from "../../types";
+import { PRIORITY_DISPLAY_ORDER } from "../config/priority";
+import { PROJECT_STATUS_ORDER } from "../../projects/config";
+import { dateOnlyToUTCDate } from "../date";
+import { createSafeId } from "../../utils";
+
+/** How the viewer relates to an issue. Unlike the "my issues" scope axis this
+ * is an ordinary filter dimension: OR within, AND with everything else. */
+export type IssueRelationFilter = "assigned" | "created" | "my_agents";
+
+export const ISSUE_RELATION_FILTERS: readonly IssueRelationFilter[] = [
+ "assigned",
+ "created",
+ "my_agents",
+];
+
+/** Relative due-date buckets. A view stores the bucket, never a date, so it
+ * keeps meaning "overdue" tomorrow. Weeks run Monday to Sunday. */
+export type DueDateFilter = "overdue" | "today" | "this_week" | "next_7_days" | "none";
+
+export const DUE_DATE_FILTERS: readonly DueDateFilter[] = [
+ "overdue",
+ "today",
+ "this_week",
+ "next_7_days",
+ "none",
+];
+
+/** The built-in value dimensions: what the simple menu lists one row each
+ * for and what can say "is not" there. Custom properties carry their own
+ * operators and are not part of this. */
+export type NegatableFilterDimension =
+ | "status"
+ | "priority"
+ | "assignee"
+ | "creator"
+ | "project"
+ | "projectStatus"
+ | "label"
+ | "relation"
+ | "dueDate";
+
+export const NEGATABLE_FILTER_DIMENSIONS: readonly NegatableFilterDimension[] = [
+ "status",
+ "priority",
+ "assignee",
+ "creator",
+ "project",
+ "projectStatus",
+ "label",
+ "relation",
+ "dueDate",
+];
+
+/** Each dimension's field name in the issue table query. */
+export const FILTER_DIMENSION_TABLE_FIELD: Record<NegatableFilterDimension, IssueTableNegatableFilter> = {
+ status: "statuses",
+ priority: "priorities",
+ assignee: "assignees",
+ creator: "creators",
+ project: "project_ids",
+ projectStatus: "project_statuses",
+ label: "label_ids",
+ relation: "relations",
+ dueDate: "due_dates",
+};
+
+/** Condition value for "no assignee" / "no project". */
+export const FILTER_NONE_VALUE = "none";
+
+/** A custom property as a condition field. */
+export type PropertyFilterField = `property:${string}`;
+
+/** What an advanced condition can test: a built-in dimension or a property. */
+export type AdvancedFilterField = NegatableFilterDimension | PropertyFilterField;
+
+const PROPERTY_FIELD_PREFIX = "property:";
+
+export function propertyFilterField(propertyId: string): PropertyFilterField {
+ return `${PROPERTY_FIELD_PREFIX}${propertyId}`;
+}
+
+/** The property a field tests, or null for a built-in dimension. */
+export function propertyIdOfField(field: AdvancedFilterField): string | null {
+ return field.startsWith(PROPERTY_FIELD_PREFIX) ? field.slice(PROPERTY_FIELD_PREFIX.length) : null;
+}
+
+export interface DimensionFilterCondition {
+ type: "condition";
+ id: string;
+ field: NegatableFilterDimension;
+ negated: boolean;
+ /**
+ * OR within the condition. Actors are `${type}:${id}`; assignee and project
+ * also take {@link FILTER_NONE_VALUE}; everything else is the value the
+ * simple filter stores.
+ */
+ values: string[];
+}
+
+export interface PropertyFilterCondition {
+ type: "condition";
+ id: string;
+ field: PropertyFilterField;
+ negated: boolean;
+ /** OR within the condition, in the simple property filter's shape: option
+ * ids, the "no value" sentinel, or operator objects. */
+ values: PropertyFilterValue[];
+}
+
+export type AdvancedFilterCondition = DimensionFilterCondition | PropertyFilterCondition;
+
+export function isPropertyCondition(condition: AdvancedFilterCondition): condition is PropertyFilterCondition {
+ return propertyIdOfField(condition.field) !== null;
+}
+
+export interface AdvancedFilterGroup {
+ type: "group";
+ id: string;
+ match: "all" | "any";
+ /** The root may hold groups; a group under the root holds conditions only. */
+ children: AdvancedFilterNode[];
+}
+
+export type AdvancedFilterNode = AdvancedFilterCondition | AdvancedFilterGroup;
+
+/** The simple-mode value fields, in the shape the view store keeps them. */
+export interface SimpleFilterFields {
+ statusFilters: IssueStatus[];
+ priorityFilters: IssuePriority[];
+ assigneeFilters: { type: "member" | "agent" | "squad"; id: string }[];
+ includeNoAssignee: boolean;
+ creatorFilters: { type: "member" | "agent" | "squad"; id: string }[];
+ projectFilters: string[];
+ includeNoProject: boolean;
+ projectStatusFilters: ProjectStatus[];
+ labelFilters: string[];
+ relationFilters: IssueRelationFilter[];
+ dueDateFilters: DueDateFilter[];
+ negatedFilters: NegatableFilterDimension[];
+ propertyFilters: Record<string, PropertyFilterValue[]>;
+}
+
+export const EMPTY_SIMPLE_FILTER_FIELDS: Readonly<SimpleFilterFields> = {
+ statusFilters: [],
+ priorityFilters: [],
+ assigneeFilters: [],
+ includeNoAssignee: false,
+ creatorFilters: [],
+ projectFilters: [],
+ includeNoProject: false,
+ projectStatusFilters: [],
+ labelFilters: [],
+ relationFilters: [],
+ dueDateFilters: [],
+ negatedFilters: [],
+ propertyFilters: {},
+};
+
+export function createFilterCondition(
+ field: NegatableFilterDimension,
+ values?: string[],
+ negated?: boolean,
+): DimensionFilterCondition;
+export function createFilterCondition(
+ field: PropertyFilterField,
+ values?: PropertyFilterValue[],
+ negated?: boolean,
+): PropertyFilterCondition;
+export function createFilterCondition(
+ field: AdvancedFilterField,
+ values?: PropertyFilterValue[],
+ negated?: boolean,
+): AdvancedFilterCondition;
+export function createFilterCondition(
+ field: AdvancedFilterField,
+ values: PropertyFilterValue[] = [],
+ negated = false,
+): AdvancedFilterCondition {
+ return { type: "condition", id: createSafeId(), field, negated, values } as AdvancedFilterCondition;
+}
+
+export function createFilterGroup(
+ match: "all" | "any" = "all",
+ children: AdvancedFilterNode[] = [],
+): AdvancedFilterGroup {
+ return { type: "group", id: createSafeId(), match, children };
+}
+
+// ---------------------------------------------------------------------------
+// Due dates
+
+const DAY_MS = 86_400_000;
+
+function dayNumber(dateOnly: string | null | undefined): number | null {
+ const date = dateOnlyToUTCDate(dateOnly);
+ return date ? Math.floor(date.getTime() / DAY_MS) : null;
+}
+
+/** Whether a "YYYY-MM-DD" due date falls in a bucket, `today` being the
+ * viewer's calendar day. Mirrors `issueTableDueDatePredicate` on the server. */
+export function dueDateMatches(
+ dueDate: string | null | undefined,
+ bucket: DueDateFilter,
+ today: string,
+): boolean {
+ const due = dayNumber(dueDate);
+ if (bucket === "none") return due === null;
+ const now = dayNumber(today);
+ if (due === null || now === null) return false;
+ switch (bucket) {
+ case "overdue":
+ return due < now;
+ case "today":
+ return due === now;
+ case "this_week": {
+ const weekday = new Date(now * DAY_MS).getUTCDay();
+ const monday = now - ((weekday + 6) % 7);
+ return due >= monday && due < monday + 7;
+ }
+ case "next_7_days":
+ return due >= now && due < now + 7;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Trees
+
+/** Conditions that constrain something (have values). */
+export function countAdvancedConditions(group: AdvancedFilterGroup | null | undefined): number {
+ if (!group) return 0;
+ let count = 0;
+ for (const child of group.children) {
+ if (child.type === "group") count += countAdvancedConditions(child);
+ else if (child.values.length > 0) count++;
+ }
+ return count;
+}
+
+/**
+ * The tree without empty conditions and groups, or null when nothing is
+ * left. An empty member must drop out rather than read as "true": inside an
+ * "any" group that would match everything.
+ */
+export function pruneAdvancedFilter(
+ group: AdvancedFilterGroup | null | undefined,
+): AdvancedFilterGroup | null {
+ if (!group) return null;
+ const children: AdvancedFilterNode[] = [];
+ for (const child of group.children) {
+ if (child.type === "group") {
+ const pruned = pruneAdvancedFilter(child);
+ if (pruned) children.push(pruned);
+ } else if (child.values.length > 0) {
+ children.push(child);
+ }
+ }
+ return children.length > 0 ? { ...group, children } : null;
+}
+
+const ACTOR_TYPES = new Set(["member", "agent", "squad"]);
+
+function knownValues(field: NegatableFilterDimension, values: string[]): string[] {
+ const keep = (allowed: readonly string[]) => values.filter((v) => allowed.includes(v));
+ switch (field) {
+ case "priority":
+ return keep(PRIORITY_DISPLAY_ORDER);
+ case "projectStatus":
+ return keep(PROJECT_STATUS_ORDER);
+ case "relation":
+ return keep(ISSUE_RELATION_FILTERS);
+ case "dueDate":
+ return keep(DUE_DATE_FILTERS);
+ case "assignee":
+ case "creator":
+ return values.filter((v) => {
+ if (v === FILTER_NONE_VALUE) return field === "assignee";
+ const [type, id] = v.split(":");
+ return !!type && !!id && ACTOR_TYPES.has(type);
+ });
+ default:
+ return values.filter((v) => v.length > 0);
+ }
+}
+
+function sanitizeNode(raw: unknown, depth: number): AdvancedFilterNode | null {
+ if (!raw || typeof raw !== "object") return null;
+ const node = raw as Record<string, unknown>;
+ const id = typeof node.id === "string" && node.id ? node.id : createSafeId();
+ if (node.type === "group") {
+ if (depth > 1 || !Array.isArray(node.children)) return null;
+ const children = node.children
+ .map((child) => sanitizeNode(child, depth + 1))
+ .filter((child): child is AdvancedFilterNode => child !== null);
+ return { type: "group", id, match: node.match === "any" ? "any" : "all", children };
+ }
+ if (node.type !== "condition") return null;
+ const negated = node.negated === true;
+ if (typeof node.field === "string" && node.field.length > PROPERTY_FIELD_PREFIX.length) {
+ const propertyField = node.field as PropertyFilterField;
+ if (propertyIdOfField(propertyField) !== null) {
+ const members = Array.isArray(node.values)
+ ? node.values.filter(
+ (v): v is PropertyFilterValue =>
+ (typeof v === "string" && v.length > 0) ||
+ (isPropertyOperatorFilter(v) && isKnownPropertyFilterOp(v.op)),
+ )
+ : [];
+ const values = [...new Map(members.map((v) => [propertyFilterValueKey(v), v])).values()];
+ return { type: "condition", id, field: propertyField, negated, values };
+ }
+ }
+ const field = node.field as NegatableFilterDimension;
+ if (!NEGATABLE_FILTER_DIMENSIONS.includes(field)) return null;
+ const values = Array.isArray(node.values)
+ ? [...new Set(node.values.filter((v): v is string => typeof v === "string"))]
+ : [];
+ return { type: "condition", id, field, negated, values: knownValues(field, values) };
+}
+
+/**
+ * A stored tree (a persisted snapshot or a saved view, both hand-editable)
+ * reduced to what the store can represent: known fields and values, at most
+ * one level of groups under the root. Anything unrecognizable drops out.
+ */
+export function sanitizeAdvancedFilter(raw: unknown): AdvancedFilterGroup | null {
+ const node = sanitizeNode(raw, 0);
+ return node && node.type === "group" ? node : null;
+}
+
+function actorValue(actor: { type: string; id: string }): string {
+ return `${actor.type}:${actor.id}`;
+}
+
+function parseActorValue(value: string): { type: "member" | "agent" | "squad"; id: string } | null {
+ const separator = value.indexOf(":");
+ if (separator <= 0) return null;
+ const type = value.slice(0, separator);
+ const id = value.slice(separator + 1);
+ return ACTOR_TYPES.has(type) && id ? { type: type as "member" | "agent" | "squad", id } : null;
+}
+
+/** One simple dimension's selection in condition-value form. */
+export function simpleFieldValues(
+ fields: Omit<SimpleFilterFields, "negatedFilters" | "propertyFilters">,
+ field: NegatableFilterDimension,
+): string[] {
+ switch (field) {
+ case "status":
+ return fields.statusFilters;
+ case "priority":
+ return fields.priorityFilters;
+ case "assignee":
+ return [
+ ...fields.assigneeFilters.map(actorValue),
+ ...(fields.includeNoAssignee ? [FILTER_NONE_VALUE] : []),
+ ];
+ case "creator":
+ return fields.creatorFilters.map(actorValue);
+ case "project":
+ return [...fields.projectFilters, ...(fields.includeNoProject ? [FILTER_NONE_VALUE] : [])];
+ case "projectStatus":
+ return fields.projectStatusFilters;
+ case "label":
+ return fields.labelFilters;
+ case "relation":
+ return fields.relationFilters;
+ case "dueDate":
+ return fields.dueDateFilters;
+ }
+}
+
+/** One condition per simple dimension and property that has values, ANDed:
+ * the same filter, as a rule list. `negated` must already be the effective
+ * set. */
+export function advancedFilterFromSimple(
+ fields: Omit<SimpleFilterFields, "negatedFilters">,
+ negated: readonly NegatableFilterDimension[],
+): AdvancedFilterGroup {
+ const children: AdvancedFilterNode[] = NEGATABLE_FILTER_DIMENSIONS.flatMap((field) => {
+ const values = simpleFieldValues(fields, field);
+ return values.length > 0
+ ? [createFilterCondition(field, [...values], negated.includes(field))]
+ : [];
+ });
+ for (const [propertyId, values] of Object.entries(fields.propertyFilters)) {
+ if (values.length > 0) children.push(createFilterCondition(propertyFilterField(propertyId), [...values]));
+ }
+ return createFilterGroup("all", children);
+}
+
+/**
+ * The simple fields a tree means, or null when simple mode cannot say it: a
+ * group, an "any" across two or more conditions, one field tested twice, or
+ * "is not" on a property. Empty conditions are ignored.
+ */
+export function simpleFromAdvancedFilter(
+ group: AdvancedFilterGroup | null | undefined,
+): SimpleFilterFields | null {
+ const pruned = pruneAdvancedFilter(group);
+ const fields: SimpleFilterFields = {
+ ...EMPTY_SIMPLE_FILTER_FIELDS,
+ assigneeFilters: [],
+ creatorFilters: [],
+ negatedFilters: [],
+ propertyFilters: {},
+ };
+ if (!pruned) return fields;
+ if (pruned.match === "any" && pruned.children.length > 1) return null;
+ const seen = new Set<AdvancedFilterField>();
+ for (const child of pruned.children) {
+ if (child.type === "group" || seen.has(child.field)) return null;
+ seen.add(child.field);
+ if (isPropertyCondition(child)) {
+ if (child.negated) return null;
+ fields.propertyFilters[propertyIdOfField(child.field) ?? ""] = [...child.values];
+ continue;
+ }
+ if (child.negated) fields.negatedFilters.push(child.field);
+ const values = child.values;
+ const none = values.includes(FILTER_NONE_VALUE);
+ const actors = () =>
+ values
+ .map(parseActorValue)
+ .filter((actor): actor is NonNullable<typeof actor> => actor !== null);
+ switch (child.field) {
+ case "status":
+ fields.statusFilters = [...values];
+ break;
+ case "priority":
+ fields.priorityFilters = values as IssuePriority[];
+ break;
+ case "assignee":
+ fields.assigneeFilters = actors();
+ fields.includeNoAssignee = none;
+ break;
+ case "creator":
+ fields.creatorFilters = actors();
+ break;
+ case "project":
+ fields.projectFilters = values.filter((v) => v !== FILTER_NONE_VALUE);
+ fields.includeNoProject = none;
+ break;
+ case "projectStatus":
+ fields.projectStatusFilters = values as ProjectStatus[];
+ break;
+ case "label":
+ fields.labelFilters = [...values];
+ break;
+ case "relation":
+ fields.relationFilters = values as IssueRelationFilter[];
+ break;
+ case "dueDate":
+ fields.dueDateFilters = values as DueDateFilter[];
+ break;
+ }
+ }
+ fields.negatedFilters = NEGATABLE_FILTER_DIMENSIONS.filter((d) => fields.negatedFilters.includes(d));
+ return fields;
+}
+
+/** The pruned tree without the conditions `drop` picks. */
+export function withoutAdvancedFilterConditions(
+ group: AdvancedFilterGroup | null | undefined,
+ drop: (condition: AdvancedFilterCondition) => boolean,
+): AdvancedFilterGroup | null {
+ if (!group) return null;
+ const strip = (node: AdvancedFilterGroup): AdvancedFilterGroup => ({
+ ...node,
+ children: node.children.flatMap((child): AdvancedFilterNode[] =>
+ child.type === "group" ? [strip(child)] : drop(child) ? [] : [child],
+ ),
+ });
+ return pruneAdvancedFilter(strip(group));
+}
+
+/** The pruned tree without conditions on these fields — the ones a surface's
+ * scope already fixes. */
+export function withoutAdvancedFilterFields(
+ group: AdvancedFilterGroup | null | undefined,
+ fields: readonly NegatableFilterDimension[],
+): AdvancedFilterGroup | null {
+ if (fields.length === 0) return pruneAdvancedFilter(group);
+ return withoutAdvancedFilterConditions(group, (condition) =>
+ (fields as readonly string[]).includes(condition.field),
+ );
+}
+
+/**
+ * Flat property filters folded into a tree as conditions, ANDed like they
+ * were. Returns null when the tree's shape can't take them: an "any" root
+ * that already holds a group.
+ */
+export function foldPropertyFiltersIntoTree(
+ tree: AdvancedFilterGroup,
+ propertyFilters: Record<string, PropertyFilterValue[]>,
+): AdvancedFilterGroup | null {
+ const conditions = Object.entries(propertyFilters)
+ .filter(([, values]) => values.length > 0)
+ .map(([propertyId, values]) => createFilterCondition(propertyFilterField(propertyId), [...values]));
+ if (conditions.length === 0) return tree;
+ if (tree.match === "all") return { ...tree, children: [...tree.children, ...conditions] };
+ if (tree.children.some((child) => child.type === "group")) return null;
+ const inner = tree.children.length > 0 ? [{ ...tree, id: createSafeId() }] : [];
+ return { ...tree, match: "all", children: [...inner, ...conditions] };
+}
+
+/**
+ * The tree with the node `id` replaced by `edit(node)`: no nodes removes it,
+ * one updates it, more inserts siblings after it. Editing the root keeps a
+ * root: anything but a group comes back as an empty one.
+ */
+export function editAdvancedFilter(
+ root: AdvancedFilterGroup,
+ id: string,
+ edit: (node: AdvancedFilterNode) => AdvancedFilterNode[],
+): AdvancedFilterGroup {
+ if (root.id === id) {
+ const [next] = edit(root);
+ return next?.type === "group" ? next : { ...root, children: [] };
+ }
+ const visit = (group: AdvancedFilterGroup): AdvancedFilterGroup => ({
+ ...group,
+ children: group.children.flatMap((child) =>
+ child.id === id ? edit(child) : child.type === "group" ? [visit(child)] : [child],
+ ),
+ });
+ return visit(root);
+}
+
+/** Conditions in the tree, empty ones included — what the server's
+ * per-request limit counts once they have values. */
+export function advancedFilterConditionSlots(group: AdvancedFilterGroup | null | undefined): number {
+ if (!group) return 0;
+ return group.children.reduce(
+ (sum, child) => sum + (child.type === "group" ? advancedFilterConditionSlots(child) : 1),
+ 0,
+ );
+}
+
+/** The server rejects more conditions than this in one tree. */
+export const ADVANCED_FILTER_MAX_CONDITIONS = 50;
+
+/** Whether a (pruned) tree tests this field anywhere. */
+export function advancedFilterUsesField(
+ group: AdvancedFilterGroup | null | undefined,
+ field: AdvancedFilterField,
+): boolean {
+ if (!group) return false;
+ return group.children.some((child) =>
+ child.type === "group" ? advancedFilterUsesField(child, field) : child.field === field && child.values.length > 0,
+ );
+}
+
+/** The table-query form of a tree, or undefined when it constrains nothing. */
+export function advancedFilterToTableQuery(
+ group: AdvancedFilterGroup | null | undefined,
+): IssueTableFilterGroup | undefined {
+ const pruned = pruneAdvancedFilter(group);
+ if (!pruned) return undefined;
+ const convert = (node: AdvancedFilterNode): IssueTableFilterNode =>
+ node.type === "group"
+ ? { match: node.match, children: node.children.map(convert) }
+ : {
+ field: isPropertyCondition(node) ? node.field : FILTER_DIMENSION_TABLE_FIELD[node.field],
+ ...(node.negated ? { negate: true } : {}),
+ values: node.values,
+ };
+ return { match: pruned.match, children: pruned.children.map(convert) };
+}
+
+export interface StatusColumnFilter<S extends string = string> {
+ statuses: readonly string[];
+ negated: boolean;
+ hiddenStatuses: readonly S[];
+}
+
+/**
+ * The status selection that decides which columns a surface draws, given the
+ * simple status filter and the rule tree it is ANDed with.
+ *
+ * A status condition every row must meet (the root matches all, or it is the
+ * only rule) picks columns exactly like the simple filter. A looser tree can't
+ * narrow the columns, but a status it names positively still un-hides that
+ * column, so its rows have somewhere to land.
+ */
+export function statusColumnFilter<S extends string>(
+ statusFilters: readonly string[],
+ negated: boolean,
+ tree: AdvancedFilterGroup | null | undefined,
+ hiddenStatuses: readonly S[],
+): StatusColumnFilter<S> {
+ const pruned = statusFilters.length > 0 ? null : pruneAdvancedFilter(tree);
+ if (!pruned) return { statuses: statusFilters, negated, hiddenStatuses };
+ const required =
+ pruned.match === "all" || pruned.children.length === 1
+ ? pruned.children.filter(
+ (child): child is DimensionFilterCondition => child.type === "condition" && child.field === "status",
+ )
+ : [];
+ const [only] = required;
+ if (only && required.length === 1) {
+ return { statuses: only.values, negated: only.negated, hiddenStatuses };
+ }
+ const named = new Set<string>();
+ const visit = (node: AdvancedFilterNode) => {
+ if (node.type === "group") node.children.forEach(visit);
+ else if (node.field === "status" && !node.negated) {
+ for (const value of node.values) if (typeof value === "string") named.add(value);
+ }
+ };
+ visit(pruned);
+ return {
+ statuses: [],
+ negated: false,
+ hiddenStatuses: named.size > 0 ? hiddenStatuses.filter((key) => !named.has(key)) : hiddenStatuses,
+ };
+}
+
+/** A tree's meaning without its ids, for comparing two trees. */
+export function advancedFilterSignature(group: AdvancedFilterGroup | null | undefined): string {
+ const pruned = pruneAdvancedFilter(group);
+ if (!pruned) return "";
+ const sign = (node: AdvancedFilterNode): unknown =>
+ node.type === "group"
+ ? [node.match, node.children.map(sign)]
+ : [node.field, node.negated, node.values.map(propertyFilterValueKey).sort()];
+ return JSON.stringify(sign(pruned));
+}
diff --git a/packages/core/issues/stores/my-issues-view-store.test.ts b/packages/core/issues/stores/my-issues-view-store.test.ts
index 21f2714b79..d0f7e680d3 100644
--- a/packages/core/issues/stores/my-issues-view-store.test.ts
+++ b/packages/core/issues/stores/my-issues-view-store.test.ts
@@ -3,6 +3,7 @@
import { describe, expect, it } from "vitest";
import {
myIssuesRelationFromScope,
+ myIssuesScopeFor,
type MyIssuesScope,
} from "./my-issues-view-store";
@@ -19,3 +20,14 @@ describe("myIssuesRelationFromScope", () => {
},
);
});
+
+describe("myIssuesScopeFor", () => {
+ it("opens My agents' work only from the URL", () => {
+ expect(myIssuesScopeFor(new URLSearchParams("scope=agents"), "created")).toBe("agents");
+ expect(myIssuesScopeFor(new URLSearchParams(), "created")).toBe("created");
+ });
+
+ it("reads a stored agents scope as the My issues default", () => {
+ expect(myIssuesScopeFor(new URLSearchParams(), "agents")).toBe("assigned");
+ });
+});
diff --git a/packages/core/issues/stores/my-issues-view-store.ts b/packages/core/issues/stores/my-issues-view-store.ts
index a95976bbbb..49af2ed7ee 100644
--- a/packages/core/issues/stores/my-issues-view-store.ts
+++ b/packages/core/issues/stores/my-issues-view-store.ts
@@ -9,6 +9,7 @@ import {
mergeViewStatePersisted,
} from "./view-store";
import { registerForWorkspaceRehydration } from "../../platform/workspace-storage";
+import { isMyAgentsSearch } from "../../paths/paths";
export type MyIssuesScope = "all" | "assigned" | "created" | "agents";
export type MyIssuesRelation = "all" | "assigned" | "created" | "involved";
@@ -22,6 +23,19 @@ export function myIssuesRelationFromScope(
return scope;
}
+/**
+ * The scope a My issues page shows. My agents' work comes from the URL
+ * (`?scope=agents`); the store keeps only My issues' own relation, so an
+ * "agents" persisted before the two were split reads as the default.
+ */
+export function myIssuesScopeFor(
+ searchParams: URLSearchParams,
+ stored: MyIssuesScope,
+): MyIssuesScope {
+ if (isMyAgentsSearch(searchParams)) return "agents";
+ return stored === "agents" ? "assigned" : stored;
+}
+
export interface MyIssuesViewState extends IssueViewState {
scope: MyIssuesScope;
setScope: (scope: MyIssuesScope) => void;
diff --git a/packages/core/issues/stores/sidebar-tree-store.test.ts b/packages/core/issues/stores/sidebar-tree-store.test.ts
new file mode 100644
index 0000000000..30beb7cbee
--- /dev/null
+++ b/packages/core/issues/stores/sidebar-tree-store.test.ts
@@ -0,0 +1,37 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { DEFAULT_SIDEBAR_ISSUE_SETTINGS, useSidebarTreeStore } from "./sidebar-tree-store";
+
+beforeEach(() => {
+ useSidebarTreeStore.setState({ expanded: [], issueSettings: DEFAULT_SIDEBAR_ISSUE_SETTINGS });
+});
+
+describe("useSidebarTreeStore", () => {
+ it("patches the shared issue settings", () => {
+ const store = useSidebarTreeStore.getState();
+ store.setIssueSettings({ sortBy: "priority" });
+ store.setIssueSettings({ assignee: "me" });
+ expect(useSidebarTreeStore.getState().issueSettings).toEqual({
+ ...DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ sortBy: "priority",
+ assignee: "me",
+ });
+ });
+
+ it("toggles expansion idempotently", () => {
+ const store = useSidebarTreeStore.getState();
+ store.setExpanded("project:p1", true);
+ store.setExpanded("project:p1", true);
+ expect(useSidebarTreeStore.getState().expanded).toEqual(["project:p1"]);
+ store.setExpanded("project:p1", false);
+ expect(useSidebarTreeStore.getState().expanded).toEqual([]);
+ });
+
+ it("collapses each section on its own", () => {
+ useSidebarTreeStore.setState({ viewsCollapsed: false, pinnedCollapsed: false, projectsCollapsed: false });
+ useSidebarTreeStore.getState().setPinnedCollapsed(true);
+ const state = useSidebarTreeStore.getState();
+ expect([state.viewsCollapsed, state.pinnedCollapsed, state.projectsCollapsed]).toEqual([false, true, false]);
+ state.setViewsCollapsed(true);
+ expect(useSidebarTreeStore.getState().viewsCollapsed).toBe(true);
+ });
+});
diff --git a/packages/core/issues/stores/sidebar-tree-store.ts b/packages/core/issues/stores/sidebar-tree-store.ts
new file mode 100644
index 0000000000..f5fc21b091
--- /dev/null
+++ b/packages/core/issues/stores/sidebar-tree-store.ts
@@ -0,0 +1,132 @@
+"use client";
+
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
+import { defaultStorage } from "../../platform/storage";
+import type { ProjectStatus } from "../../types";
+
+export type SidebarIssueSort = "updated_at" | "created_at" | "priority" | "status" | "title" | "due_date";
+export type SidebarIssueAssignee = "anyone" | "me" | "my_agents";
+
+/** How expanded projects list their issues in the sidebar. */
+export interface SidebarIssueSettings {
+ sortBy: SidebarIssueSort;
+ sortDirection: "asc" | "desc";
+ /** Status keys left out; `null` leaves out every finished (done / closed) status. */
+ hiddenStatuses: string[] | null;
+ assignee: SidebarIssueAssignee;
+ showSubIssues: boolean;
+}
+
+export const DEFAULT_SIDEBAR_ISSUE_SETTINGS: SidebarIssueSettings = {
+ sortBy: "updated_at",
+ sortDirection: "desc",
+ hiddenStatuses: null,
+ assignee: "anyone",
+ showSubIssues: true,
+};
+
+export type SidebarProjectOrdering = "manual" | "name" | "updated" | "created";
+
+/** Which projects the sidebar lists, and in what order. */
+export interface SidebarProjectSettings {
+ ordering: SidebarProjectOrdering;
+ statuses: ProjectStatus[];
+ onlyMine: boolean;
+ showCount: boolean;
+}
+
+export const DEFAULT_SIDEBAR_PROJECT_SETTINGS: SidebarProjectSettings = {
+ ordering: "manual",
+ statuses: ["planned", "in_progress", "paused"],
+ onlyMine: false,
+ showCount: true,
+};
+
+
+interface SidebarTreeState {
+ /** Expanded rows as `project:{id}` / `view:{id}`. */
+ expanded: string[];
+ issueSettings: SidebarIssueSettings;
+ projectSettings: SidebarProjectSettings;
+ /** Manual project order; projects missing from it follow in list order. */
+ projectOrder: string[];
+ projectsCollapsed: boolean;
+ viewsCollapsed: boolean;
+ pinnedCollapsed: boolean;
+ setExpanded: (key: string, expanded: boolean) => void;
+ setIssueSettings: (patch: Partial<SidebarIssueSettings>) => void;
+ setProjectSettings: (patch: Partial<SidebarProjectSettings>) => void;
+ setProjectOrder: (ids: string[]) => void;
+ setProjectsCollapsed: (collapsed: boolean) => void;
+ setViewsCollapsed: (collapsed: boolean) => void;
+ setPinnedCollapsed: (collapsed: boolean) => void;
+}
+
+type PersistedSidebarTree = Pick<
+ SidebarTreeState,
+ | "expanded"
+ | "issueSettings"
+ | "projectSettings"
+ | "projectOrder"
+ | "projectsCollapsed"
+ | "viewsCollapsed"
+ | "pinnedCollapsed"
+>;
+
+const INITIAL: PersistedSidebarTree = {
+ expanded: [],
+ issueSettings: DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ projectSettings: DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ projectOrder: [],
+ projectsCollapsed: false,
+ viewsCollapsed: false,
+ pinnedCollapsed: false,
+};
+
+export const useSidebarTreeStore = create<SidebarTreeState>()(
+ persist(
+ (set) => ({
+ ...INITIAL,
+ setExpanded: (key, expanded) =>
+ set((s) => {
+ if (s.expanded.includes(key) === expanded) return s;
+ return { expanded: expanded ? [...s.expanded, key] : s.expanded.filter((k) => k !== key) };
+ }),
+ setIssueSettings: (patch) => set((s) => ({ issueSettings: { ...s.issueSettings, ...patch } })),
+ setProjectSettings: (patch) => set((s) => ({ projectSettings: { ...s.projectSettings, ...patch } })),
+ setProjectOrder: (ids) => set({ projectOrder: ids }),
+ setProjectsCollapsed: (collapsed) => set({ projectsCollapsed: collapsed }),
+ setViewsCollapsed: (collapsed) => set({ viewsCollapsed: collapsed }),
+ setPinnedCollapsed: (collapsed) => set({ pinnedCollapsed: collapsed }),
+ }),
+ {
+ name: "multica_sidebar_tree",
+ storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
+ partialize: (state): PersistedSidebarTree => ({
+ expanded: state.expanded,
+ issueSettings: state.issueSettings,
+ projectSettings: state.projectSettings,
+ projectOrder: state.projectOrder,
+ projectsCollapsed: state.projectsCollapsed,
+ viewsCollapsed: state.viewsCollapsed,
+ pinnedCollapsed: state.pinnedCollapsed,
+ }),
+ // A workspace switch rehydrates into the previous workspace's state:
+ // start from the initial values, never from `current`'s data.
+ merge: (persisted, current) => {
+ const p = (persisted ?? {}) as Partial<PersistedSidebarTree>;
+ return {
+ ...current,
+ ...INITIAL,
+ ...p,
+ issueSettings: { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, ...p.issueSettings },
+ projectSettings: { ...DEFAULT_SIDEBAR_PROJECT_SETTINGS, ...p.projectSettings },
+ };
+ },
+ },
+ ),
+);
+
+registerForWorkspaceRehydration(() => useSidebarTreeStore.persist.rehydrate());
diff --git a/packages/core/issues/stores/view-store-advanced.test.ts b/packages/core/issues/stores/view-store-advanced.test.ts
new file mode 100644
index 0000000000..c7e737e721
--- /dev/null
+++ b/packages/core/issues/stores/view-store-advanced.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment node
+import { describe, expect, it, beforeEach } from "vitest";
+import { createStore, type StoreApi } from "zustand/vanilla";
+import { mergeViewStatePersisted, viewStoreSlice, type IssueViewState } from "./view-store";
+import { createFilterCondition, createFilterGroup } from "./filter-tree";
+import { isIssueViewModified, issueViewSeedDefinition, modifiedFilterDimensions } from "../../issue-views/definition";
+
+function newStore(): StoreApi<IssueViewState> {
+ return createStore<IssueViewState>()((set) => viewStoreSlice(set));
+}
+
+describe("advanced filter mode", () => {
+ let store: StoreApi<IssueViewState>;
+ beforeEach(() => {
+ store = newStore();
+ });
+
+ it("moves the simple filters into a tree and back", () => {
+ const s = store.getState();
+ s.toggleStatusFilter("done");
+ s.setFilterNegated("status", true);
+ s.toggleDueDateFilter("overdue");
+ s.togglePropertyFilter("prop", "opt");
+ store.getState().enterAdvancedFilter();
+ const entered = store.getState();
+ expect(entered.statusFilters).toEqual([]);
+ expect(entered.dueDateFilters).toEqual([]);
+ expect(entered.negatedFilters).toEqual([]);
+ // Custom properties become conditions like the rest.
+ expect(entered.propertyFilters).toEqual({});
+ expect(entered.advancedFilter?.children).toHaveLength(3);
+ expect(entered.advancedFilter?.children[2]).toMatchObject({ field: "property:prop", values: ["opt"] });
+
+ store.getState().exitAdvancedFilter();
+ const back = store.getState();
+ expect(back.advancedFilter).toBeNull();
+ expect(back.statusFilters).toEqual(["done"]);
+ expect(back.negatedFilters).toEqual(["status"]);
+ expect(back.dueDateFilters).toEqual(["overdue"]);
+ expect(back.propertyFilters).toEqual({ prop: ["opt"] });
+ });
+
+ it("stays advanced when simple mode cannot say the tree", () => {
+ store.getState().setAdvancedFilter(
+ createFilterGroup("any", [
+ createFilterCondition("status", ["todo"]),
+ createFilterCondition("label", ["l1"]),
+ ]),
+ );
+ store.getState().exitAdvancedFilter();
+ expect(store.getState().advancedFilter?.match).toBe("any");
+ });
+
+ it("clears the tree with the rest of the filters", () => {
+ store.getState().enterAdvancedFilter();
+ store.getState().clearFilters();
+ expect(store.getState().advancedFilter).toBeNull();
+ });
+
+ it("sanitizes persisted trees and due dates", () => {
+ const merged = mergeViewStatePersisted(
+ {
+ dueDateFilters: ["today", "someday", "today"],
+ advancedFilter: { type: "group", match: "any", children: [{ type: "condition", field: "status", values: ["todo"] }] },
+ },
+ store.getState(),
+ );
+ expect(merged.dueDateFilters).toEqual(["today"]);
+ expect(merged.advancedFilter?.match).toBe("any");
+ expect(merged.advancedFilter?.children[0]).toMatchObject({ field: "status", values: ["todo"], negated: false });
+ expect(mergeViewStatePersisted({ advancedFilter: "junk" }, store.getState()).advancedFilter).toBeNull();
+ });
+
+ it("folds property filters persisted beside a tree into it", () => {
+ const merged = mergeViewStatePersisted(
+ {
+ advancedFilter: { type: "group", match: "all", children: [{ type: "condition", field: "status", values: ["todo"] }] },
+ propertyFilters: { prop: ["opt"] },
+ },
+ store.getState(),
+ );
+ expect(merged.propertyFilters).toEqual({});
+ expect(merged.advancedFilter?.children[1]).toMatchObject({ field: "property:prop", values: ["opt"] });
+ });
+});
+
+describe("saved views in advanced mode", () => {
+ const view = {
+ query: { statusFilters: ["todo"], labelFilters: ["l1"] },
+ display: {},
+ };
+ function openView(v: { query: Record<string, unknown>; display: Record<string, unknown> }) {
+ const store = newStore();
+ const seed = issueViewSeedDefinition(v);
+ store.setState({ ...seed.query, ...seed.display } as Partial<IssueViewState>);
+ return store;
+ }
+
+ it("does not count switching modes as a change", () => {
+ const store = openView(view);
+ store.getState().enterAdvancedFilter();
+ expect(isIssueViewModified(view, store.getState()).filters).toBe(false);
+ expect(modifiedFilterDimensions(view, store.getState()).size).toBe(0);
+ });
+
+ it("does not count property filters moving into the tree as a change", () => {
+ const withProperty = { query: { ...view.query, propertyFilters: { prop: ["opt"] } }, display: {} };
+ const store = openView(withProperty);
+ store.getState().enterAdvancedFilter();
+ expect(store.getState().propertyFilters).toEqual({});
+ expect(isIssueViewModified(withProperty, store.getState()).filters).toBe(false);
+ expect(modifiedFilterDimensions(withProperty, store.getState()).size).toBe(0);
+ });
+
+ it("reports a tree simple mode cannot say as an advanced change", () => {
+ const store = openView(view);
+ store.getState().enterAdvancedFilter();
+ const tree = store.getState().advancedFilter!;
+ store.getState().setAdvancedFilter({ ...tree, match: "any" });
+ expect(isIssueViewModified(view, store.getState()).filters).toBe(true);
+ expect(modifiedFilterDimensions(view, store.getState()).has("advanced")).toBe(true);
+ });
+
+ it("reopens an advanced view unmodified", () => {
+ const advancedView = {
+ query: {
+ advancedFilter: createFilterGroup("any", [
+ createFilterCondition("status", ["todo"]),
+ createFilterGroup("all", [createFilterCondition("label", ["l1"])]),
+ ]),
+ },
+ display: {},
+ };
+ const store = openView(advancedView);
+ expect(store.getState().advancedFilter?.match).toBe("any");
+ expect(isIssueViewModified(advancedView, store.getState()).filters).toBe(false);
+ });
+});
diff --git a/packages/core/issues/stores/view-store-negation.test.ts b/packages/core/issues/stores/view-store-negation.test.ts
new file mode 100644
index 0000000000..cb600778c3
--- /dev/null
+++ b/packages/core/issues/stores/view-store-negation.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment node
+import { describe, expect, it, beforeEach } from "vitest";
+import { createStore, type StoreApi } from "zustand/vanilla";
+import {
+ effectiveNegatedFilters,
+ mergeViewStatePersisted,
+ viewStoreSlice,
+ type IssueViewState,
+} from "./view-store";
+
+function newStore(): StoreApi<IssueViewState> {
+ return createStore<IssueViewState>()((set) => viewStoreSlice(set));
+}
+
+describe("negated filters", () => {
+ let store: StoreApi<IssueViewState>;
+ beforeEach(() => {
+ store = newStore();
+ });
+
+ it("flips a dimension to 'is not' and back without touching its values", () => {
+ store.getState().toggleStatusFilter("done");
+ store.getState().setFilterNegated("status", true);
+ store.getState().setFilterNegated("status", true);
+ expect(store.getState().negatedFilters).toEqual(["status"]);
+ expect(store.getState().statusFilters).toEqual(["done"]);
+ store.getState().setFilterNegated("status", false);
+ expect(store.getState().negatedFilters).toEqual([]);
+ expect(store.getState().statusFilters).toEqual(["done"]);
+ });
+
+ it("only counts a negation once the dimension has values", () => {
+ store.getState().setFilterNegated("label", true);
+ store.getState().setFilterNegated("assignee", true);
+ store.getState().toggleNoAssignee();
+ expect(effectiveNegatedFilters(store.getState())).toEqual(["assignee"]);
+ });
+
+ it("clears with its own dimension and with clearFilters", () => {
+ store.getState().toggleStatusFilter("done");
+ store.getState().toggleLabelFilter("l-1");
+ store.getState().setFilterNegated("status", true);
+ store.getState().setFilterNegated("label", true);
+ store.getState().clearFilterDimension("status");
+ expect(store.getState().negatedFilters).toEqual(["label"]);
+
+ store.getState().clearFilters();
+ expect(store.getState().negatedFilters).toEqual([]);
+ });
+});
+
+describe("relation filters", () => {
+ it("toggles relations and clears them as one dimension", () => {
+ const store = newStore();
+ store.getState().toggleRelationFilter("assigned");
+ store.getState().toggleRelationFilter("my_agents");
+ expect(store.getState().relationFilters).toEqual(["assigned", "my_agents"]);
+ store.getState().toggleRelationFilter("assigned");
+ expect(store.getState().relationFilters).toEqual(["my_agents"]);
+ store.getState().setFilterNegated("relation", true);
+ store.getState().clearFilterDimension("relation");
+ expect(store.getState().relationFilters).toEqual([]);
+ expect(store.getState().negatedFilters).toEqual([]);
+ });
+});
+
+describe("mergeViewStatePersisted negation and relations", () => {
+ const defaults = () => newStore().getState();
+
+ it("keeps known members and drops the rest", () => {
+ const merged = mergeViewStatePersisted(
+ {
+ relationFilters: ["assigned", "involved", 3],
+ negatedFilters: ["status", "status", "date", "property:x", null],
+ },
+ defaults(),
+ );
+ expect(merged.relationFilters).toEqual(["assigned"]);
+ expect(merged.negatedFilters).toEqual(["status"]);
+ });
+
+ it("falls back to no filter for a snapshot saved before the fields", () => {
+ const merged = mergeViewStatePersisted({ statusFilters: ["done"] }, defaults());
+ expect(merged.relationFilters).toEqual([]);
+ expect(merged.negatedFilters).toEqual([]);
+ });
+});
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index 4f6ed533d7..7826f39b54 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -8,6 +8,30 @@ import type { IssueStatus, IssuePriority, ProjectStatus, PropertyFilterValue } f
import { PROJECT_STATUS_ORDER } from "../../projects/config";
import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
import { defaultStorage } from "../../platform/storage";
+import {
+ advancedFilterFromSimple,
+ DUE_DATE_FILTERS,
+ EMPTY_SIMPLE_FILTER_FIELDS,
+ foldPropertyFiltersIntoTree,
+ ISSUE_RELATION_FILTERS,
+ NEGATABLE_FILTER_DIMENSIONS,
+ sanitizeAdvancedFilter,
+ simpleFromAdvancedFilter,
+ type AdvancedFilterGroup,
+ type DueDateFilter,
+ type IssueRelationFilter,
+ type NegatableFilterDimension,
+} from "./filter-tree";
+
+export {
+ DUE_DATE_FILTERS,
+ ISSUE_RELATION_FILTERS,
+ NEGATABLE_FILTER_DIMENSIONS,
+ type AdvancedFilterGroup,
+ type DueDateFilter,
+ type IssueRelationFilter,
+ type NegatableFilterDimension,
+};
export type ViewMode = "board" | "list" | "table" | "gantt" | "swimlane";
export type GanttZoom = "day" | "week" | "month";
@@ -117,8 +141,8 @@ export interface ActorFilterValue {
id: string;
}
-/** The ten query-defining filter fields as one value — what a saved view
- * fixes, and what resets restore. */
+/** The query-defining filter fields as one value — what a saved view fixes,
+ * and what resets restore. */
export interface FilterSnapshot {
statusFilters: IssueStatus[];
priorityFilters: IssuePriority[];
@@ -129,20 +153,56 @@ export interface FilterSnapshot {
includeNoProject: boolean;
projectStatusFilters: ProjectStatus[];
labelFilters: string[];
+ relationFilters: IssueRelationFilter[];
+ dueDateFilters: DueDateFilter[];
+ negatedFilters: NegatableFilterDimension[];
propertyFilters: Record<string, PropertyFilterValue[]>;
+ advancedFilter: AdvancedFilterGroup | null;
}
/** Filter-bar chip dimensions. Date is excluded: `dateFilter` lives outside
* the persisted slice and clears through `setDateFilter(null)`. */
-export type FilterDimension =
- | "status"
- | "priority"
- | "assignee"
- | "creator"
- | "project"
- | "projectStatus"
- | "label"
- | `property:${string}`;
+export type FilterDimension = NegatableFilterDimension | `property:${string}`;
+
+/** Whether a negatable dimension has anything selected. */
+export function filterDimensionHasSelection(
+ state: Omit<FilterSnapshot, "negatedFilters" | "propertyFilters" | "advancedFilter">,
+ dimension: NegatableFilterDimension,
+): boolean {
+ switch (dimension) {
+ case "status":
+ return state.statusFilters.length > 0;
+ case "priority":
+ return state.priorityFilters.length > 0;
+ case "assignee":
+ return state.assigneeFilters.length > 0 || state.includeNoAssignee;
+ case "creator":
+ return state.creatorFilters.length > 0;
+ case "project":
+ return state.projectFilters.length > 0 || state.includeNoProject;
+ case "projectStatus":
+ return state.projectStatusFilters.length > 0;
+ case "label":
+ return state.labelFilters.length > 0;
+ case "relation":
+ return state.relationFilters.length > 0;
+ case "dueDate":
+ return state.dueDateFilters.length > 0;
+ }
+}
+
+/**
+ * The negations that actually change the result, in canonical order. "Is
+ * not" on a dimension with nothing selected is a UI state, not a filter.
+ */
+export function effectiveNegatedFilters(
+ state: Omit<FilterSnapshot, "propertyFilters" | "advancedFilter">,
+): NegatableFilterDimension[] {
+ const negated = new Set(state.negatedFilters);
+ return NEGATABLE_FILTER_DIMENSIONS.filter(
+ (dimension) => negated.has(dimension) && filterDimensionHasSelection(state, dimension),
+ );
+}
export const PROPERTY_VIEW_PREFIX = "property:";
@@ -254,6 +314,14 @@ export interface IssueViewState {
*/
projectStatusFilters: ProjectStatus[];
labelFilters: string[];
+ relationFilters: IssueRelationFilter[];
+ dueDateFilters: DueDateFilter[];
+ /**
+ * Dimensions whose selection is excluded instead of matched ("status is
+ * not done"). The selection itself lives in the dimension's own field; an
+ * entry here with nothing selected filters nothing.
+ */
+ negatedFilters: NegatableFilterDimension[];
/**
* Custom-property filters: definition id → selected values (checkbox
* definitions use the pseudo-options "true"/"false"; scalars hold the
@@ -263,6 +331,13 @@ export interface IssueViewState {
* across definitions, mirroring the other filter groups.
*/
propertyFilters: Record<string, PropertyFilterValue[]>;
+ /**
+ * Advanced mode: a rule tree that can "or" across dimensions. Non-null
+ * means the surface is in advanced mode; entering moves the simple value
+ * fields into the tree, so they sit empty while it is set. Custom-property
+ * filters stay where they are and still apply.
+ */
+ advancedFilter: AdvancedFilterGroup | null;
dateFilter: IssueDateFilter | null;
// When true, the list only shows issues that currently have at least one
// agent task in `running` status. Drives the workspace "agents working"
@@ -324,11 +399,22 @@ export interface IssueViewState {
toggleNoProject: () => void;
toggleProjectStatusFilter: (status: ProjectStatus) => void;
toggleLabelFilter: (labelId: string) => void;
+ toggleRelationFilter: (relation: IssueRelationFilter) => void;
+ toggleDueDateFilter: (bucket: DueDateFilter) => void;
+ setFilterNegated: (dimension: NegatableFilterDimension, negated: boolean) => void;
togglePropertyFilter: (propertyId: string, optionId: string) => void;
/** Replace a property's full filter value set (used by scalar value inputs
* for text/number/date/url, which build the array including "__none__"). */
setPropertyFilterValues: (propertyId: string, optionIds: PropertyFilterValue[]) => void;
setDateFilter: (filter: IssueDateFilter | null) => void;
+ /** Replace the advanced tree; null leaves advanced mode without carrying
+ * anything back. */
+ setAdvancedFilter: (filter: AdvancedFilterGroup | null) => void;
+ /** Move the simple value filters into a tree and switch to advanced mode. */
+ enterAdvancedFilter: () => void;
+ /** Back to simple mode with the same filter. A no-op when the tree is
+ * something simple mode cannot say (`simpleFromAdvancedFilter`). */
+ exitAdvancedFilter: () => void;
toggleAgentRunningFilter: () => void;
hideStatus: (status: IssueStatus) => void;
showStatus: (status: IssueStatus) => void;
@@ -373,7 +459,11 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
includeNoProject: false,
projectStatusFilters: [],
labelFilters: [],
+ relationFilters: [],
+ dueDateFilters: [],
+ negatedFilters: [],
propertyFilters: {},
+ advancedFilter: null,
dateFilter: null,
agentRunningFilter: false,
sortBy: "created_at",
@@ -477,6 +567,27 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
? state.labelFilters.filter((id) => id !== labelId)
: [...state.labelFilters, labelId],
})),
+ toggleRelationFilter: (relation) =>
+ set((state) => ({
+ relationFilters: state.relationFilters.includes(relation)
+ ? state.relationFilters.filter((r) => r !== relation)
+ : [...state.relationFilters, relation],
+ })),
+ toggleDueDateFilter: (bucket) =>
+ set((state) => ({
+ dueDateFilters: state.dueDateFilters.includes(bucket)
+ ? state.dueDateFilters.filter((b) => b !== bucket)
+ : [...state.dueDateFilters, bucket],
+ })),
+ setFilterNegated: (dimension, negated) =>
+ set((state) => {
+ if (state.negatedFilters.includes(dimension) === negated) return state;
+ return {
+ negatedFilters: negated
+ ? [...state.negatedFilters, dimension]
+ : state.negatedFilters.filter((d) => d !== dimension),
+ };
+ }),
togglePropertyFilter: (propertyId, optionId) =>
set((state) => {
const current = state.propertyFilters[propertyId] ?? [];
@@ -496,6 +607,22 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
return { propertyFilters };
}),
setDateFilter: (filter) => set({ dateFilter: filter }),
+ setAdvancedFilter: (advancedFilter) => set({ advancedFilter }),
+ enterAdvancedFilter: () =>
+ set((state) =>
+ state.advancedFilter
+ ? state
+ : {
+ ...EMPTY_SIMPLE_FILTER_FIELDS,
+ advancedFilter: advancedFilterFromSimple(state, effectiveNegatedFilters(state)),
+ },
+ ),
+ exitAdvancedFilter: () =>
+ set((state) => {
+ if (!state.advancedFilter) return state;
+ const simple = simpleFromAdvancedFilter(state.advancedFilter);
+ return simple ? { ...simple, advancedFilter: null } : state;
+ }),
toggleAgentRunningFilter: () =>
set((state) => ({ agentRunningFilter: !state.agentRunningFilter })),
hideStatus: (status) =>
@@ -519,28 +646,37 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
includeNoProject: false,
projectStatusFilters: [],
labelFilters: [],
+ relationFilters: [],
+ dueDateFilters: [],
+ negatedFilters: [],
propertyFilters: {},
+ advancedFilter: null,
dateFilter: null,
agentRunningFilter: false,
}),
resetFiltersTo: (snapshot) => set({ ...snapshot }),
clearFilterDimension: (dimension) =>
set((state) => {
+ const negatedFilters = state.negatedFilters.filter((d) => d !== dimension);
switch (dimension) {
case "status":
- return { statusFilters: [] };
+ return { statusFilters: [], negatedFilters };
case "priority":
- return { priorityFilters: [] };
+ return { priorityFilters: [], negatedFilters };
case "assignee":
- return { assigneeFilters: [], includeNoAssignee: false };
+ return { assigneeFilters: [], includeNoAssignee: false, negatedFilters };
case "creator":
- return { creatorFilters: [] };
+ return { creatorFilters: [], negatedFilters };
case "project":
- return { projectFilters: [], includeNoProject: false };
+ return { projectFilters: [], includeNoProject: false, negatedFilters };
case "projectStatus":
- return { projectStatusFilters: [] };
+ return { projectStatusFilters: [], negatedFilters };
case "label":
- return { labelFilters: [] };
+ return { labelFilters: [], negatedFilters };
+ case "relation":
+ return { relationFilters: [], negatedFilters };
+ case "dueDate":
+ return { dueDateFilters: [], negatedFilters };
default: {
const propertyId = propertyIdFromViewKey(dimension);
if (!propertyId || !(propertyId in state.propertyFilters)) return state;
@@ -676,7 +812,11 @@ export const viewStorePersistOptions = (name: string) => ({
includeNoProject: state.includeNoProject,
projectStatusFilters: state.projectStatusFilters,
labelFilters: state.labelFilters,
+ relationFilters: state.relationFilters,
+ dueDateFilters: state.dueDateFilters,
+ negatedFilters: state.negatedFilters,
propertyFilters: state.propertyFilters,
+ advancedFilter: state.advancedFilter,
sortBy: state.sortBy,
sortDirection: state.sortDirection,
sortDirections: state.sortDirections,
@@ -798,7 +938,31 @@ export function mergeViewStatePersisted<T extends IssueViewState>(
(PROJECT_STATUS_ORDER as readonly string[]).includes(status as string),
)
: current.projectStatusFilters,
+ relationFilters: Array.isArray(p.relationFilters)
+ ? p.relationFilters.filter((relation): relation is IssueRelationFilter =>
+ (ISSUE_RELATION_FILTERS as readonly unknown[]).includes(relation),
+ )
+ : current.relationFilters,
+ dueDateFilters: Array.isArray(p.dueDateFilters)
+ ? [...new Set(p.dueDateFilters.filter((bucket): bucket is DueDateFilter =>
+ (DUE_DATE_FILTERS as readonly unknown[]).includes(bucket),
+ ))]
+ : current.dueDateFilters,
+ advancedFilter: p.advancedFilter === undefined
+ ? current.advancedFilter
+ : sanitizeAdvancedFilter(p.advancedFilter),
+ negatedFilters: Array.isArray(p.negatedFilters)
+ ? [...new Set(p.negatedFilters.filter((dimension): dimension is NegatableFilterDimension =>
+ (NEGATABLE_FILTER_DIMENSIONS as readonly unknown[]).includes(dimension),
+ ))]
+ : current.negatedFilters,
};
+ // Property filters are conditions in advanced mode; flat ones stored next to
+ // a tree (by an earlier build) would otherwise filter without being shown.
+ if (merged.advancedFilter && Object.keys(merged.propertyFilters ?? {}).length > 0) {
+ const folded = foldPropertyFiltersIntoTree(merged.advancedFilter, merged.propertyFilters);
+ if (folded) Object.assign(merged, { advancedFilter: folded, propertyFilters: {} });
+ }
return {
...merged,
...normalizeSortForGrouping(
diff --git a/packages/core/issues/wakeups.ts b/packages/core/issues/wakeups.ts
index 5f3b782e62..4f68c6803c 100644
--- a/packages/core/issues/wakeups.ts
+++ b/packages/core/issues/wakeups.ts
@@ -1,4 +1,5 @@
import {
+ infiniteQueryOptions,
queryOptions,
useMutation,
useQueryClient,
@@ -177,6 +178,24 @@ export function workspaceWakeupsOptions(
});
}
+/** The workspace list, one `limit`-sized page per "Load more". */
+export function workspaceWakeupsInfiniteOptions(
+ workspaceId: string,
+ filters: Omit<WorkspaceWakeupFilters, "offset">,
+) {
+ return infiniteQueryOptions({
+ queryKey: ["workspace-wakeups", workspaceId, "pages", filters],
+ initialPageParam: 0,
+ queryFn: ({ pageParam }) => api.listWorkspaceWakeups({ ...filters, offset: pageParam }),
+ getNextPageParam: (lastPage, pages) => {
+ const loaded = pages.reduce((sum, page) => sum + page.items.length, 0);
+ return lastPage.items.length > 0 && loaded < lastPage.total ? loaded : undefined;
+ },
+ enabled: !!workspaceId,
+ refetchInterval: 10_000,
+ });
+}
+
export function useDisableWorkspaceWakeups(workspaceId: string) {
const client = useQueryClient();
return useMutation({
diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.ts
index 37c2d10507..aba7600a44 100644
--- a/packages/core/issues/ws-updaters.test.ts
+++ b/packages/core/issues/ws-updaters.test.ts
@@ -1126,3 +1126,52 @@ describe("project gantt cache invalidation", () => {
expectInvalidated(qc, issueKeys.projectGantt(WS_ID, PROJECT_ID));
});
});
+
+// Expanded sidebar rows list issues from these caches. An update refetches
+// only the lists it can reorder or move the issue across.
+describe("sidebar issue lists", () => {
+ const PROJECT_ID = "project-1";
+ const params = { project_id: PROJECT_ID, sort_by: "updated_at", sort_direction: "desc" } as const;
+ const ownKey = issueKeys.sidebar(WS_ID, `project:${PROJECT_ID}`, params, 5);
+ const otherKey = issueKeys.sidebar(WS_ID, "project:project-9", { project_id: "project-9" }, 5);
+ const viewKey = issueKeys.sidebar(WS_ID, "view:view-1", {}, 5);
+ const builtinKey = issueKeys.sidebar(
+ WS_ID,
+ "builtin:all_issues",
+ { table: { scope: { kind: "workspace" }, filters: {}, sort: { field: "updated_at", direction: "desc" } } },
+ 5,
+ );
+ let qc: QueryClient;
+
+ beforeEach(() => {
+ qc = new QueryClient();
+ qc.setQueryData(ownKey, { issues: [{ ...baseIssue, revision: 1 }], total: 1 });
+ qc.setQueryData(otherKey, { issues: [], total: 0 });
+ qc.setQueryData(viewKey, { issues: [], total: 0 });
+ qc.setQueryData(builtinKey, { issues: [], total: 0 });
+ });
+
+ const invalidated = (key: readonly unknown[]) => qc.getQueryState(key)?.isInvalidated;
+
+ it("refetches the issue's own lists and views, leaving other projects alone", () => {
+ onIssueUpdated(qc, WS_ID, { id: ISSUE_ID, title: "Renamed", revision: 2 });
+ expect(invalidated(ownKey)).toBe(true);
+ expect(invalidated(viewKey)).toBe(true);
+ expect(invalidated(builtinKey)).toBe(true);
+ expect(invalidated(otherKey)).toBe(false);
+ });
+
+ it("refetches the project an issue moves into", () => {
+ onIssueUpdated(qc, WS_ID, { id: ISSUE_ID, project_id: "project-9", revision: 2 }, { projectChanged: true });
+ expect(invalidated(otherKey)).toBe(true);
+ });
+
+ it("refetches every list when an issue is created or deleted", () => {
+ onIssueCreated(qc, WS_ID, otherIssue);
+ expect(invalidated(otherKey)).toBe(true);
+
+ qc.setQueryData(otherKey, { issues: [], total: 0 });
+ onIssueDeleted(qc, WS_ID, ISSUE_ID);
+ expect(invalidated(otherKey)).toBe(true);
+ });
+});
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index fa661caeb7..e79331ba4e 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -8,6 +8,7 @@ import {
bucketedListEntries,
flatListEntries,
invalidateIssueDerivatives,
+ invalidateSidebarListsForIssue,
invalidateLastActivitySortedIssueLists,
invalidateStaleListKeys,
invalidateUpdatedAtSortedIssueLists,
@@ -407,6 +408,7 @@ export function onIssueCreated(
// because a fresh issue isn't necessarily scheduled yet; the active Gantt
// page (if any) will refetch and pick it up if it qualifies.
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.sidebarAll(wsId) });
if (issue.parent_issue_id) {
qc.invalidateQueries({ queryKey: issueKeys.children(wsId, issue.parent_issue_id) });
qc.invalidateQueries({ queryKey: issueKeys.childProgress(wsId) });
@@ -499,7 +501,9 @@ export function onIssueUpdated(
invalidateIssueDerivatives(qc, wsId, {
statusOrProjectChanged:
issue.status !== undefined || issue.project_id !== undefined,
+ refreshSidebar: false,
});
+ invalidateSidebarListsForIssue(qc, wsId, issue.id, [oldProjectId, issue.project_id]);
// Group counts, branch membership and hierarchy are server-owned. Never
// guess deltas from a partial branch; refetch the active Table queries.
qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
diff --git a/packages/core/package.json b/packages/core/package.json
index c25543b887..27287d1de9 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -50,6 +50,7 @@
"./issues/run-steering": "./issues/run-steering.ts",
"./issues/date": "./issues/date.ts",
"./issues/ws-updaters": "./issues/ws-updaters.ts",
+ "./issues/sidebar-list": "./issues/sidebar-list.ts",
"./issues/surface/*": "./issues/surface/*.ts",
"./issues/config": "./issues/config/index.ts",
"./issues/config/status": "./issues/config/status.ts",
@@ -120,6 +121,10 @@
"./issue-views/use-active-view": "./issue-views/use-active-view.ts",
"./issue-views/baseline": "./issue-views/baseline.ts",
"./issue-views/preferences": "./issue-views/preferences.ts",
+ "./issue-views/sidebar-views": "./issue-views/sidebar-views.ts",
+ "./issue-views/view-target": "./issue-views/view-target.ts",
+ "./issue-views/definition": "./issue-views/definition.ts",
+ "./issue-views/rename-store": "./issue-views/rename-store.ts",
"./billing": "./billing/index.ts",
"./billing/recovery": "./billing/recovery.ts",
"./billing/queries": "./billing/queries.ts",
diff --git a/packages/core/paths/index.ts b/packages/core/paths/index.ts
index 6a7cfe4364..d9c853b58a 100644
--- a/packages/core/paths/index.ts
+++ b/packages/core/paths/index.ts
@@ -1,6 +1,7 @@
export {
paths,
isGlobalPath,
+ isMyAgentsSearch,
AGENT_FOCUS_CONVERSATION_STARTERS,
} from "./paths";
export type { WorkspacePaths } from "./paths";
@@ -17,6 +18,8 @@ export type {
WorkspacePageKey,
WorkspacePage,
} from "./route-icons";
+export { RAIL_SPACES, spaceForPath } from "./spaces";
+export type { AppSpaceId, RailSpaceId } from "./spaces";
export {
parseTabSubject,
tabSubjectKey,
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
index bda798fd10..480d4ea893 100644
--- a/packages/core/paths/paths.ts
+++ b/packages/core/paths/paths.ts
@@ -22,6 +22,19 @@ const encode = (id: string) => encodeURIComponent(id);
*/
export const AGENT_FOCUS_CONVERSATION_STARTERS = "conversation_starters";
+/**
+ * My agents' work is the My issues route with `?scope=agents`. It is URL
+ * vocabulary rather than stored state so every tab and window keeps its own
+ * — a Cmd-click opens it beside My issues, and one tab's switch leaves the
+ * others alone.
+ */
+const MY_AGENTS_SCOPE = "agents";
+
+/** Whether a My issues URL's search params open My agents' work. */
+export function isMyAgentsSearch(searchParams: URLSearchParams): boolean {
+ return searchParams.get("scope") === MY_AGENTS_SCOPE;
+}
+
function workspaceScoped(slug: string) {
const ws = `/${encode(slug)}`;
return {
@@ -64,6 +77,8 @@ function workspaceScoped(slug: string) {
chatSession: (sessionId: string) =>
`${ws}/chat?session=${encode(sessionId)}`,
myIssues: () => `${ws}/my-issues`,
+ myAgents: () => `${ws}/my-issues?scope=${MY_AGENTS_SCOPE}`,
+ views: () => `${ws}/views`,
runtimes: () => `${ws}/runtimes`,
runtimeDetail: (id: string) => `${ws}/runtimes/${encode(id)}`,
runtimeSettings: (machineId: string, runtimeId: string) =>
diff --git a/packages/core/paths/reserved-slugs.ts b/packages/core/paths/reserved-slugs.ts
index a5b9ca1b6b..edcee79a7b 100644
--- a/packages/core/paths/reserved-slugs.ts
+++ b/packages/core/paths/reserved-slugs.ts
@@ -85,6 +85,7 @@ export const RESERVED_SLUGS: ReadonlySet<string> = new Set([
"squads",
"inbox",
"my-issues",
+ "views",
"usage",
"runtimes",
"skills",
diff --git a/packages/core/paths/route-icons.test.ts b/packages/core/paths/route-icons.test.ts
index 55b56fe820..3ea4ba8961 100644
--- a/packages/core/paths/route-icons.test.ts
+++ b/packages/core/paths/route-icons.test.ts
@@ -30,7 +30,7 @@ describe("workspace page coverage", () => {
for (const [method, fn] of Object.entries(ws)) {
if (typeof fn !== "function" || fn.length !== 0) continue;
if (EXCLUDED_METHODS.has(method)) continue;
- const segment = fn().split("/").filter(Boolean)[1] ?? "";
+ const segment = fn().split(/[?#]/)[0]!.split("/").filter(Boolean)[1] ?? "";
if (!KNOWN_SEGMENTS.has(segment)) missing.push(`${method} → "${segment}"`);
}
diff --git a/packages/core/paths/route-icons.ts b/packages/core/paths/route-icons.ts
index 814d247b0e..f63206127f 100644
--- a/packages/core/paths/route-icons.ts
+++ b/packages/core/paths/route-icons.ts
@@ -25,6 +25,7 @@ export type RouteIconName =
| "CircleUser"
| "ListTodo"
| "FolderKanban"
+ | "Layers"
| "Zap"
| "Bot"
| "Users"
@@ -49,6 +50,7 @@ export type NavLabelKey =
| "my_issues"
| "issues"
| "projects"
+ | "views"
| "autopilots"
| "agents"
| "squads"
@@ -64,6 +66,7 @@ export type WorkspacePageKey =
| "myIssues"
| "issues"
| "projects"
+ | "views"
| "autopilots"
| "agents"
| "squads"
@@ -91,6 +94,7 @@ export const WORKSPACE_PAGES: Record<WorkspacePageKey, WorkspacePage> = {
myIssues: { segment: "my-issues", icon: "CircleUser", navKey: "my_issues" },
issues: { segment: "issues", icon: "ListTodo", navKey: "issues" },
projects: { segment: "projects", icon: "FolderKanban", navKey: "projects" },
+ views: { segment: "views", icon: "Layers", navKey: "views" },
autopilots: { segment: "autopilots", icon: "Zap", navKey: "autopilots" },
agents: { segment: "agents", icon: "Bot", navKey: "agents" },
squads: { segment: "squads", icon: "Users", navKey: "squads" },
diff --git a/packages/core/paths/spaces.test.ts b/packages/core/paths/spaces.test.ts
new file mode 100644
index 0000000000..4cc5f1d7a3
--- /dev/null
+++ b/packages/core/paths/spaces.test.ts
@@ -0,0 +1,41 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { paths } from "./paths";
+import { WORKSPACE_PAGES, type WorkspacePageKey } from "./route-icons";
+import { spaceForPath } from "./spaces";
+
+describe("spaceForPath", () => {
+ const ws = paths.workspace("acme");
+
+ it("groups every workspace nav page into a space", () => {
+ const unassigned = (Object.keys(WORKSPACE_PAGES) as WorkspacePageKey[]).filter(
+ (key) => spaceForPath(`/acme/${WORKSPACE_PAGES[key].segment}`) === null,
+ );
+ expect(unassigned).toEqual([]);
+ });
+
+ it.each([
+ [ws.inbox(), "inbox"],
+ [ws.myIssues(), "work"],
+ [ws.issues(), "work"],
+ [ws.issueDetail("MUL-1"), "work"],
+ [ws.projectDetail("p-1"), "work"],
+ [ws.agentDetail("a-1"), "team"],
+ [ws.squadDetail("s-1"), "team"],
+ [ws.memberDetail("m-1"), "team"],
+ [ws.runtimeDetail("r-1"), "team"],
+ [ws.skills(), "team"],
+ [ws.usage(), "team"],
+ [ws.chatSession("c-1"), "chat"],
+ [ws.autopilotDetail("ap-1"), "autopilots"],
+ [`${ws.settings()}?tab=members`, "settings"],
+ ])("maps %s to %s", (path, space) => {
+ expect(spaceForPath(path)).toBe(space);
+ });
+
+ it("returns null outside every space", () => {
+ expect(spaceForPath(ws.attachmentPreview("f-1"))).toBeNull();
+ expect(spaceForPath("/acme")).toBeNull();
+ expect(spaceForPath("/")).toBeNull();
+ });
+});
diff --git a/packages/core/paths/spaces.ts b/packages/core/paths/spaces.ts
new file mode 100644
index 0000000000..1fd4047d6f
--- /dev/null
+++ b/packages/core/paths/spaces.ts
@@ -0,0 +1,54 @@
+/**
+ * Workspace "spaces": the top-level groups the app rail switches between.
+ *
+ * Every workspace page belongs to at most one space, keyed by its route
+ * segment (`/{slug}/{segment}/...`). The rail highlights the space of the
+ * current route, and the shell decides from the space which panel to show.
+ */
+
+export type AppSpaceId =
+ | "inbox"
+ | "work"
+ | "team"
+ | "chat"
+ | "autopilots"
+ | "settings";
+
+/** Settings lives in the rail footer rather than the space list. */
+export type RailSpaceId = Exclude<AppSpaceId, "settings">;
+
+/** Spaces in rail order. */
+export const RAIL_SPACES: readonly RailSpaceId[] = [
+ "inbox",
+ "work",
+ "team",
+ "chat",
+ "autopilots",
+];
+
+const SPACE_BY_SEGMENT: Record<string, AppSpaceId> = {
+ inbox: "inbox",
+ "my-issues": "work",
+ issues: "work",
+ projects: "work",
+ views: "work",
+ agents: "team",
+ squads: "team",
+ members: "team",
+ skills: "team",
+ runtimes: "team",
+ usage: "team",
+ chat: "chat",
+ autopilots: "autopilots",
+ settings: "settings",
+};
+
+/**
+ * The space a workspace-scoped path or full URL belongs to, or null for
+ * routes outside every space (attachment previews, unknown segments).
+ */
+export function spaceForPath(path: string): AppSpaceId | null {
+ const pathname = path.split(/[?#]/)[0] ?? "";
+ const segment = pathname.split("/").filter(Boolean)[1] ?? "";
+ return SPACE_BY_SEGMENT[segment] ?? null;
+}
diff --git a/packages/core/paths/tab-presentation.test.ts b/packages/core/paths/tab-presentation.test.ts
index 81856afece..ff1d8bced6 100644
--- a/packages/core/paths/tab-presentation.test.ts
+++ b/packages/core/paths/tab-presentation.test.ts
@@ -24,6 +24,13 @@ describe("resolveTabPresentation — pages", () => {
title: { kind: "nav", navKey: "projects" },
});
});
+
+ it("titles My agents' work as its own page rather than My issues", () => {
+ expect(present("/acme/my-issues?scope=agents")).toEqual({
+ visual: { kind: "icon", icon: "Bot" },
+ title: { kind: "tab", tabKey: "my_agents" },
+ });
+ });
});
describe("resolveTabPresentation — direct resources", () => {
diff --git a/packages/core/paths/tab-presentation.ts b/packages/core/paths/tab-presentation.ts
index 9024842d4e..8e7f8ab7c7 100644
--- a/packages/core/paths/tab-presentation.ts
+++ b/packages/core/paths/tab-presentation.ts
@@ -51,6 +51,7 @@ export type TabLabelKey =
| "runtime"
| "attachment"
| "create_agent"
+ | "my_agents"
| "unknown";
/** How a tab's title should be produced. */
@@ -155,6 +156,11 @@ export function resolveTabPresentation(
title: { kind: "nav", navKey: page.navKey },
};
}
+ case "myAgents":
+ return {
+ visual: { kind: "icon", icon: "Bot" },
+ title: { kind: "tab", tabKey: "my_agents" },
+ };
case "issue":
return {
visual: {
diff --git a/packages/core/paths/tab-subject.test.ts b/packages/core/paths/tab-subject.test.ts
index 6c734807f2..6a5563bf2f 100644
--- a/packages/core/paths/tab-subject.test.ts
+++ b/packages/core/paths/tab-subject.test.ts
@@ -10,6 +10,8 @@ describe("parseTabSubject", () => {
// Collection / tool pages
["/acme/issues", { kind: "page", page: "issues" }],
["/acme/my-issues", { kind: "page", page: "myIssues" }],
+ ["/acme/my-issues?scope=agents", { kind: "myAgents" }],
+ ["/acme/my-issues?scope=created", { kind: "page", page: "myIssues" }],
["/acme/projects", { kind: "page", page: "projects" }],
["/acme/autopilots", { kind: "page", page: "autopilots" }],
["/acme/agents", { kind: "page", page: "agents" }],
@@ -92,6 +94,9 @@ describe("tabSubjectKey", () => {
expect(tabSubjectKey({ kind: "issue", id: "x" })).toBe("issue:x");
expect(tabSubjectKey({ kind: "chat", sessionId: null })).toBe("chat:");
expect(tabSubjectKey({ kind: "chat", sessionId: "s1" })).toBe("chat:s1");
+ expect(tabSubjectKey({ kind: "myAgents" })).not.toBe(
+ tabSubjectKey({ kind: "page", page: "myIssues" }),
+ );
expect(
tabSubjectKey({ kind: "actor", actorType: "member", id: "m1" }),
).toBe("actor:member:m1");
diff --git a/packages/core/paths/tab-subject.ts b/packages/core/paths/tab-subject.ts
index 93cf6f5aff..b7453d75c6 100644
--- a/packages/core/paths/tab-subject.ts
+++ b/packages/core/paths/tab-subject.ts
@@ -13,6 +13,7 @@
* Chat) rides in the query string, so it is parsed too — the URL is the single
* source of truth for what a tab has open, including which item.
*/
+import { isMyAgentsSearch } from "./paths";
import { pageForSegment, type WorkspacePageKey } from "./route-icons";
export type TabActorType = "agent" | "member" | "squad";
@@ -20,6 +21,8 @@ export type TabActorType = "agent" | "member" | "squad";
export type TabSubject =
/** A collection or tool page with no specific resource. */
| { kind: "page"; page: WorkspacePageKey }
+ /** My agents' work: the My issues route's `?scope=agents`. */
+ | { kind: "myAgents" }
/** A single issue detail. */
| { kind: "issue"; id: string }
/** A single project detail. */
@@ -79,7 +82,9 @@ export function parseTabSubject(url: string): TabSubject {
case "issues":
return id ? { kind: "issue", id } : { kind: "page", page: "issues" };
case "my-issues":
- return { kind: "page", page: "myIssues" };
+ return isMyAgentsSearch(query) ? { kind: "myAgents" } : { kind: "page", page: "myIssues" };
+ case "views":
+ return { kind: "page", page: "views" };
case "projects":
return id ? { kind: "project", id } : { kind: "page", page: "projects" };
case "autopilots":
@@ -141,6 +146,8 @@ export function tabSubjectKey(subject: TabSubject): string {
switch (subject.kind) {
case "page":
return `page:${subject.page}`;
+ case "myAgents":
+ return "my-agents";
case "issue":
return `issue:${subject.id}`;
case "project":
diff --git a/packages/core/projects/stores/view-store.ts b/packages/core/projects/stores/view-store.ts
index e4de867fac..677d7ee95d 100644
--- a/packages/core/projects/stores/view-store.ts
+++ b/packages/core/projects/stores/view-store.ts
@@ -1,9 +1,10 @@
"use client";
-import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
-import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
-import { defaultStorage } from "../../platform/storage";
+import {
+ createCollectionViewStore,
+ type CollectionSortDirection,
+ type CollectionViewCore,
+} from "../../collections/view-store";
// Projects is the one dual-view list: a dense table (compact) and a card
// grid (comfortable), toggled by viewMode. Sort + filters feed both views;
@@ -14,7 +15,7 @@ export type ProjectViewMode = "compact" | "comfortable";
export type ProjectSortField = "name" | "priority" | "status" | "progress" | "created";
-export type ProjectSortDirection = "asc" | "desc";
+export type ProjectSortDirection = CollectionSortDirection;
export const PROJECT_SORT_DEFAULT_DIRECTION: Record<
ProjectSortField,
@@ -51,93 +52,28 @@ export type ProjectColumnKey = "priority" | "progress" | "lead" | "issues" | "cr
* compact table). */
export const PROJECT_DEFAULT_HIDDEN_COLUMNS: ProjectColumnKey[] = ["issues"];
-export interface ProjectViewState {
+export interface ProjectViewState
+ extends CollectionViewCore<
+ ProjectSortField,
+ ProjectColumnKey,
+ ProjectListFilters
+ > {
viewMode: ProjectViewMode;
- sortField: ProjectSortField;
- sortDirection: ProjectSortDirection;
- hiddenColumns: ProjectColumnKey[];
- filters: ProjectListFilters;
setViewMode: (mode: ProjectViewMode) => void;
- toggleSort: (field: ProjectSortField) => void;
- setSortField: (field: ProjectSortField) => void;
- setSortDirection: (direction: ProjectSortDirection) => void;
- toggleColumn: (key: ProjectColumnKey) => void;
- toggleFilter: (key: keyof ProjectListFilters, value: string) => void;
- clearFilters: () => void;
}
-const DEFAULTS = {
- viewMode: "compact" as ProjectViewMode,
- sortField: "created" as ProjectSortField,
- sortDirection: PROJECT_SORT_DEFAULT_DIRECTION.created,
- hiddenColumns: PROJECT_DEFAULT_HIDDEN_COLUMNS,
- filters: EMPTY_PROJECT_FILTERS,
-};
-
-export const useProjectViewStore = create<ProjectViewState>()(
- persist(
- (set) => ({
- ...DEFAULTS,
- setViewMode: (mode) => set({ viewMode: mode }),
- toggleSort: (field) =>
- set((state) =>
- state.sortField === field
- ? { sortDirection: state.sortDirection === "asc" ? "desc" : "asc" }
- : {
- sortField: field,
- sortDirection: PROJECT_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortField: (field) =>
- set((state) =>
- state.sortField === field
- ? {}
- : {
- sortField: field,
- sortDirection: PROJECT_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortDirection: (direction) => set({ sortDirection: direction }),
- toggleColumn: (key) =>
- set((state) => ({
- hiddenColumns: state.hiddenColumns.includes(key)
- ? state.hiddenColumns.filter((k) => k !== key)
- : [...state.hiddenColumns, key],
- })),
- toggleFilter: (key, value) =>
- set((state) => {
- const list = state.filters[key] as string[];
- const next = list.includes(value)
- ? list.filter((v) => v !== value)
- : [...list, value];
- return { filters: { ...state.filters, [key]: next } };
- }),
- clearFilters: () => set({ filters: EMPTY_PROJECT_FILTERS }),
- }),
- {
- name: "multica_projects_view",
- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
- partialize: (state) => ({
- viewMode: state.viewMode,
- sortField: state.sortField,
- sortDirection: state.sortDirection,
- hiddenColumns: state.hiddenColumns,
- filters: state.filters,
- }),
- // Deep-merge filters so a payload persisted before a filter dimension
- // existed still gets that key's default (avoids `.length` on
- // undefined). Same hardening as the other view stores.
- merge: (persisted, current) => {
- if (!persisted) return { ...current, ...DEFAULTS };
- const p = persisted as Partial<ProjectViewState>;
- return {
- ...current,
- ...p,
- filters: { ...EMPTY_PROJECT_FILTERS, ...(p.filters ?? {}) },
- };
- },
- }
- )
-);
-
-registerForWorkspaceRehydration(() => useProjectViewStore.persist.rehydrate());
+export const useProjectViewStore = createCollectionViewStore<
+ ProjectSortField,
+ ProjectColumnKey,
+ ProjectListFilters,
+ { viewMode: ProjectViewMode },
+ { setViewMode: (mode: ProjectViewMode) => void }
+>({
+ name: "multica_projects_view",
+ defaultSortField: "created",
+ sortDefaultDirection: PROJECT_SORT_DEFAULT_DIRECTION,
+ defaultHiddenColumns: PROJECT_DEFAULT_HIDDEN_COLUMNS,
+ emptyFilters: EMPTY_PROJECT_FILTERS,
+ extraState: { viewMode: "compact" },
+ extraActions: (set) => ({ setViewMode: (mode) => set({ viewMode: mode }) }),
+});
diff --git a/packages/core/skills/stores/view-store.ts b/packages/core/skills/stores/view-store.ts
index 5b6f6024ce..6647c877ae 100644
--- a/packages/core/skills/stores/view-store.ts
+++ b/packages/core/skills/stores/view-store.ts
@@ -1,12 +1,10 @@
"use client";
-import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
import {
- createWorkspaceAwareStorage,
- registerForWorkspaceRehydration,
-} from "../../platform/workspace-storage";
-import { defaultStorage } from "../../platform/storage";
+ createCollectionViewStore,
+ type CollectionSortDirection,
+ type CollectionViewCore,
+} from "../../collections/view-store";
// View preferences for the skills list page: sort, column visibility, and
// filters. Persisted per workspace (workspace-aware storage), per user/device
@@ -16,7 +14,7 @@ import { defaultStorage } from "../../platform/storage";
export type SkillSortField = "name" | "usedBy" | "updated" | "created";
-export type SkillSortDirection = "asc" | "desc";
+export type SkillSortDirection = CollectionSortDirection;
/** Per-field direction applied when the user switches TO that field. */
export const SKILL_SORT_DEFAULT_DIRECTION: Record<
@@ -65,96 +63,20 @@ export type SkillColumnKey =
/** Source and created are opt-in: hidden until the user enables them. */
export const DEFAULT_HIDDEN_COLUMNS: SkillColumnKey[] = ["source", "created"];
-export interface SkillsViewState {
- sortField: SkillSortField;
- sortDirection: SkillSortDirection;
- hiddenColumns: SkillColumnKey[];
- filters: SkillListFilters;
- /** Header click: toggles direction on the active field, otherwise switches
- * to the field with its default direction. */
- toggleSort: (field: SkillSortField) => void;
- /** Display panel select: switches field (default direction), no toggle. */
- setSortField: (field: SkillSortField) => void;
- setSortDirection: (direction: SkillSortDirection) => void;
- toggleColumn: (key: SkillColumnKey) => void;
- toggleFilter: (key: keyof SkillListFilters, value: string) => void;
- clearFilters: () => void;
-}
-
-const DEFAULTS = {
- sortField: "updated" as SkillSortField,
- sortDirection: SKILL_SORT_DEFAULT_DIRECTION.updated,
- hiddenColumns: DEFAULT_HIDDEN_COLUMNS,
- filters: EMPTY_SKILL_FILTERS,
-};
-
-export const useSkillsViewStore = create<SkillsViewState>()(
- persist(
- (set) => ({
- ...DEFAULTS,
- toggleSort: (field) =>
- set((state) =>
- state.sortField === field
- ? {
- sortDirection: state.sortDirection === "asc" ? "desc" : "asc",
- }
- : {
- sortField: field,
- sortDirection: SKILL_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortField: (field) =>
- set((state) =>
- state.sortField === field
- ? {}
- : {
- sortField: field,
- sortDirection: SKILL_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortDirection: (direction) => set({ sortDirection: direction }),
- toggleColumn: (key) =>
- set((state) => ({
- hiddenColumns: state.hiddenColumns.includes(key)
- ? state.hiddenColumns.filter((k) => k !== key)
- : [...state.hiddenColumns, key],
- })),
- toggleFilter: (key, value) =>
- set((state) => {
- const list = state.filters[key] as string[];
- const next = list.includes(value)
- ? list.filter((v) => v !== value)
- : [...list, value];
- return { filters: { ...state.filters, [key]: next } };
- }),
- clearFilters: () => set({ filters: EMPTY_SKILL_FILTERS }),
- }),
- {
- name: "multica_skills_view",
- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
- partialize: (state) => ({
- sortField: state.sortField,
- sortDirection: state.sortDirection,
- hiddenColumns: state.hiddenColumns,
- filters: state.filters,
- }),
- // On rehydrate, if the new workspace has no persisted value, reset to
- // the defaults instead of leaving the previous workspace's in-memory
- // view state in place (same rationale as the agents view store).
- merge: (persisted, current) => {
- if (!persisted) return { ...current, ...DEFAULTS };
- const p = persisted as Partial<SkillsViewState>;
- // Deep-merge filters so a payload persisted before a new filter
- // dimension existed still gets that key's default instead of
- // dropping it to undefined (which crashes `.length` reads).
- return {
- ...current,
- ...p,
- filters: { ...EMPTY_SKILL_FILTERS, ...(p.filters ?? {}) },
- };
- },
- },
- ),
-);
+export type SkillsViewState = CollectionViewCore<
+ SkillSortField,
+ SkillColumnKey,
+ SkillListFilters
+>;
-registerForWorkspaceRehydration(() => useSkillsViewStore.persist.rehydrate());
+export const useSkillsViewStore = createCollectionViewStore<
+ SkillSortField,
+ SkillColumnKey,
+ SkillListFilters
+>({
+ name: "multica_skills_view",
+ defaultSortField: "updated",
+ sortDefaultDirection: SKILL_SORT_DEFAULT_DIRECTION,
+ defaultHiddenColumns: DEFAULT_HIDDEN_COLUMNS,
+ emptyFilters: EMPTY_SKILL_FILTERS,
+});
diff --git a/packages/core/squads/stores/view-store.ts b/packages/core/squads/stores/view-store.ts
index f572be04b2..65ad4bb124 100644
--- a/packages/core/squads/stores/view-store.ts
+++ b/packages/core/squads/stores/view-store.ts
@@ -1,12 +1,10 @@
"use client";
-import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
import {
- createWorkspaceAwareStorage,
- registerForWorkspaceRehydration,
-} from "../../platform/workspace-storage";
-import { defaultStorage } from "../../platform/storage";
+ createCollectionViewStore,
+ type CollectionSortDirection,
+ type CollectionViewCore,
+} from "../../collections/view-store";
// View preferences for the squads list page: scope, sort, column visibility.
// Persisted per workspace, per user/device. No filters (the set is tiny);
@@ -21,7 +19,7 @@ export const SQUAD_SCOPES: SquadsScope[] = ["mine", "all"];
export type SquadSortField = "name" | "members" | "created";
-export type SquadSortDirection = "asc" | "desc";
+export type SquadSortDirection = CollectionSortDirection;
/** Per-field direction applied when the user switches TO that field. */
export const SQUAD_SORT_DEFAULT_DIRECTION: Record<
@@ -57,100 +55,24 @@ export const EMPTY_SQUAD_FILTERS: SquadListFilters = {
creators: [],
};
-export interface SquadsViewState {
+export interface SquadsViewState
+ extends CollectionViewCore<SquadSortField, SquadColumnKey, SquadListFilters> {
scope: SquadsScope;
- sortField: SquadSortField;
- sortDirection: SquadSortDirection;
- hiddenColumns: SquadColumnKey[];
- filters: SquadListFilters;
setScope: (scope: SquadsScope) => void;
- /** Header click: toggles direction on the active field, otherwise switches
- * to the field with its default direction. */
- toggleSort: (field: SquadSortField) => void;
- /** Display panel select: switches field (default direction), no toggle. */
- setSortField: (field: SquadSortField) => void;
- setSortDirection: (direction: SquadSortDirection) => void;
- toggleColumn: (key: SquadColumnKey) => void;
- toggleFilter: (key: keyof SquadListFilters, value: string) => void;
- clearFilters: () => void;
}
-const DEFAULTS = {
- scope: "mine" as SquadsScope,
- sortField: "name" as SquadSortField,
- sortDirection: SQUAD_SORT_DEFAULT_DIRECTION.name,
- hiddenColumns: SQUAD_DEFAULT_HIDDEN_COLUMNS,
- filters: EMPTY_SQUAD_FILTERS,
-};
-
-export const useSquadsViewStore = create<SquadsViewState>()(
- persist(
- (set) => ({
- ...DEFAULTS,
- setScope: (scope) => set({ scope }),
- toggleSort: (field) =>
- set((state) =>
- state.sortField === field
- ? {
- sortDirection: state.sortDirection === "asc" ? "desc" : "asc",
- }
- : {
- sortField: field,
- sortDirection: SQUAD_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortField: (field) =>
- set((state) =>
- state.sortField === field
- ? {}
- : {
- sortField: field,
- sortDirection: SQUAD_SORT_DEFAULT_DIRECTION[field],
- },
- ),
- setSortDirection: (direction) => set({ sortDirection: direction }),
- toggleColumn: (key) =>
- set((state) => ({
- hiddenColumns: state.hiddenColumns.includes(key)
- ? state.hiddenColumns.filter((k) => k !== key)
- : [...state.hiddenColumns, key],
- })),
- toggleFilter: (key, value) =>
- set((state) => {
- const list = state.filters[key] as string[];
- const next = list.includes(value)
- ? list.filter((v) => v !== value)
- : [...list, value];
- return { filters: { ...state.filters, [key]: next } };
- }),
- clearFilters: () => set({ filters: EMPTY_SQUAD_FILTERS }),
- }),
- {
- name: "multica_squads_view",
- storage: createJSONStorage(() =>
- createWorkspaceAwareStorage(defaultStorage),
- ),
- partialize: (state) => ({
- scope: state.scope,
- sortField: state.sortField,
- sortDirection: state.sortDirection,
- hiddenColumns: state.hiddenColumns,
- filters: state.filters,
- }),
- // On rehydrate, if the new workspace has no persisted value, reset to
- // the defaults instead of leaking the previous workspace's state.
- // Deep-merge filters so a pre-filters payload backfills defaults.
- merge: (persisted, current) => {
- if (!persisted) return { ...current, ...DEFAULTS };
- const p = persisted as Partial<SquadsViewState>;
- return {
- ...current,
- ...p,
- filters: { ...EMPTY_SQUAD_FILTERS, ...(p.filters ?? {}) },
- };
- },
- },
- ),
-);
-
-registerForWorkspaceRehydration(() => useSquadsViewStore.persist.rehydrate());
+export const useSquadsViewStore = createCollectionViewStore<
+ SquadSortField,
+ SquadColumnKey,
+ SquadListFilters,
+ { scope: SquadsScope },
+ { setScope: (scope: SquadsScope) => void }
+>({
+ name: "multica_squads_view",
+ defaultSortField: "name",
+ sortDefaultDirection: SQUAD_SORT_DEFAULT_DIRECTION,
+ defaultHiddenColumns: SQUAD_DEFAULT_HIDDEN_COLUMNS,
+ emptyFilters: EMPTY_SQUAD_FILTERS,
+ extraState: { scope: "mine" },
+ extraActions: (set) => ({ setScope: (scope) => set({ scope }) }),
+});
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index ae31216179..03f74e1b69 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -312,6 +312,38 @@ export type IssueTableScope =
| { kind: "creator"; actor: IssueActorRef }
| { kind: "my"; relation: "assigned" | "created" | "involved" | "any" };
+export type IssueTableRelation = "assigned" | "created" | "my_agents";
+
+export type IssueTableNegatableFilter =
+ | "statuses"
+ | "priorities"
+ | "assignees"
+ | "creators"
+ | "project_ids"
+ | "project_statuses"
+ | "label_ids"
+ | "relations"
+ | "due_dates";
+
+export type IssueTableDueDate = "overdue" | "today" | "this_week" | "next_7_days" | "none";
+
+/** One node of `filters.advanced`: a group when it has `children`. */
+export type IssueTableFilterNode = IssueTableFilterGroup | IssueTableFilterCondition;
+
+export interface IssueTableFilterGroup {
+ match: "all" | "any";
+ children: IssueTableFilterNode[];
+}
+
+export interface IssueTableFilterCondition {
+ /** A flat filter's field, or `property:<definitionId>`. */
+ field: IssueTableNegatableFilter | `property:${string}`;
+ negate?: boolean;
+ /** Actors are `${type}:${id}`; assignees and project_ids accept "none".
+ * A property takes `filters.properties` members. */
+ values: PropertyFilterValue[];
+}
+
export interface IssueTableFilters {
statuses?: IssueStatus[];
priorities?: IssuePriority[];
@@ -325,6 +357,19 @@ export interface IssueTableFilters {
* matches. */
project_statuses?: ProjectStatus[];
label_ids?: string[];
+ /** How the requesting user relates to the issue, OR within the list:
+ * assigned to me, created by me, assigned to an agent I own. */
+ relations?: IssueTableRelation[];
+ /** Dimensions whose predicate is inverted ("is not"). Listing a dimension
+ * that has no values of its own changes nothing. */
+ negate?: IssueTableNegatableFilter[];
+ /** Relative due-date buckets, OR within the list. Needs `today`. */
+ due_dates?: IssueTableDueDate[];
+ /** The viewer's calendar day ("YYYY-MM-DD") the due-date buckets resolve
+ * against. */
+ today?: string;
+ /** A condition tree ANDed with the flat filters above. */
+ advanced?: IssueTableFilterGroup;
/** Same shape as `ListIssuesParams.properties`: bare strings are exact
* equality / "No value", operator objects narrow scalar matches. */
properties?: Record<string, PropertyFilterValue[]>;
diff --git a/packages/ui/components/ui/list-grid.tsx b/packages/ui/components/ui/list-grid.tsx
deleted file mode 100644
index 6c8db867d5..0000000000
--- a/packages/ui/components/ui/list-grid.tsx
+++ /dev/null
@@ -1,223 +0,0 @@
-"use client";
-
-import { ArrowDown, ArrowUp } from "@multica/ui/icons";
-
-import { cn } from "../../lib/utils";
-
-// Linear-style list grid. The container declares every column track once via
-// a literal `grid-cols-[...]` class (plus responsive variants); the header and
-// each row span the full template with `grid-cols-subgrid`, so column widths
-// have a single source of truth and never drift between header, rows, and
-// skeletons.
-//
-// Conventions the container class must follow:
-// - First and last tracks are edge-padding columns (e.g. 1.25rem) so row
-// hover backgrounds stay full-bleed while content aligns with page chrome.
-// ListGridHeader/ListGridRow render the matching placeholder cells.
-// - Responsiveness is TWO-ZONE and CONTAINER-query driven (wrap the ListGrid
-// in a `@container` element; `@<bp>:` variants, never viewport `sm:`/`lg:`,
-// so sidebars and split panes are accounted for):
-// - ≥ @2xl: WYSIWYG — every user-enabled column renders. The grid carries
-// `@2xl:min-w-[var(--…-minw)]` (Σ enabled tracks + gaps, computed from
-// the page's column-width constants) and the wrapper has
-// `overflow-x-auto`, so an over-provisioned column set scrolls instead
-// of clipping. An enabled column must NEVER be silently hidden behind a
-// width tier — that "dead toggle" bug shipped twice.
-// - < @2xl: a static core template (name + one key column), no horizontal
-// scroll, column toggles don't apply. Non-core cells carry
-// `hidden @2xl:flex`; display:none cells drop out of subgrid
-// auto-placement so the remaining cells fill the right tracks.
-// - Keep the class a literal string in the page source so Tailwind sees it.
-
-export type ListGridSortDirection = "asc" | "desc";
-
-function ListGrid({
- className,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) {
- return (
- <div
- role="table"
- className={cn("grid w-full min-w-0 content-start gap-x-3", className)}
- {...props}
- />
- );
-}
-
-function ListGridHeader({
- className,
- children,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) {
- return (
- <div
- role="row"
- className={cn(
- "group/header sticky top-0 z-10 col-span-full grid h-9 grid-cols-subgrid items-center bg-background after:pointer-events-none after:absolute after:inset-x-0 after:top-full after:h-3 after:bg-gradient-to-b after:from-background after:to-transparent",
- className,
- )}
- {...props}
- >
- <span aria-hidden="true" />
- {children}
- <span aria-hidden="true" />
- </div>
- );
-}
-
-interface ListGridHeaderCellProps
- extends React.HTMLAttributes<HTMLDivElement> {
- /** Current sort state of this column; `false` when not the active sort. */
- sorted?: ListGridSortDirection | false;
- /** When provided the header renders as a sort button. */
- onSort?: () => void;
- align?: "left" | "right";
-}
-
-function ListGridHeaderCell({
- sorted = false,
- onSort,
- align = "left",
- className,
- children,
- ...props
-}: ListGridHeaderCellProps) {
- if (!onSort) {
- return (
- <div
- role="columnheader"
- className={cn(
- "flex min-w-0 items-center px-2 text-caption text-muted-foreground",
- align === "right" && "justify-end",
- className,
- )}
- {...props}
- >
- {children}
- </div>
- );
- }
- const Arrow = sorted === "asc" ? ArrowUp : ArrowDown;
- return (
- <div
- role="columnheader"
- aria-sort={
- sorted === "asc"
- ? "ascending"
- : sorted === "desc"
- ? "descending"
- : undefined
- }
- className={cn(
- "flex min-w-0 items-center px-2",
- align === "right" && "justify-end",
- className,
- )}
- {...props}
- >
- <button
- type="button"
- onClick={onSort}
- className={cn(
- "group/sort flex h-6 items-center gap-0.5 rounded-md text-caption transition-colors",
- // Active sort column: emphasis via weight + full foreground color
- // only — no background, so the header row stays quiet.
- sorted
- ? "font-medium text-foreground"
- : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
- align === "right" ? "-mr-1.5 flex-row-reverse pl-1 pr-1.5" : "-ml-1.5 pl-1.5 pr-1",
- )}
- >
- {children}
- <Arrow
- className={cn(
- "size-3 shrink-0",
- sorted ? "opacity-100" : "opacity-0 group-hover/sort:opacity-50",
- )}
- />
- </button>
- </div>
- );
-}
-
-// Rows area — a plain subgrid passthrough that groups the rows and carries
-// the virtualization padding. It does NOT scroll: both scroll axes live on
-// the single outer wrapper (`overflow-auto @container`), with the sticky
-// header pinning inside that scroller. Splitting horizontal scrolling
-// (wrapper) from vertical scrolling (this element) connected by an h-full
-// percentage bridge caused a non-converging layout loop (flickering double
-// scrollbars), clipped the last row under the horizontal scrollbar, and
-// let a classic vertical scrollbar shift row tracks relative to the header.
-function ListGridBody({
- className,
- ...props
-}: React.ComponentProps<"div">) {
- return (
- <div
- role="rowgroup"
- className={cn(
- "col-span-full grid grid-cols-subgrid content-start",
- className,
- )}
- {...props}
- />
- );
-}
-
-// Bottom clearance appended to the rows area's padding so the last row can
-// scroll clear of floating UI anchored to the pane's bottom edge (the chat
-// FAB at bottom-right covers ~48px; the batch toolbar ~62px). One row of
-// extra runway keeps both off the final row's kebab.
-export const LIST_GRID_BOTTOM_CLEARANCE = 64;
-
-// A row is a plain `<div>`, never an `<a>` — so interactive cells (checkbox,
-// kebab, inline editors) are valid siblings, not interactive content nested
-// inside an anchor (which is invalid HTML and made native navigation fire on
-// every child click). Whole-row navigation is a MOUSE convenience layered on
-// via `onClick`/`onAuxClick` (see views `useRowLink`); the keyboard- and
-// screen-reader-accessible link, plus right-click "open in new tab", live on
-// the real `<AppLink>` inside the name cell. Interactive cells call
-// `stopPropagation` so clicking them never triggers the row's navigation.
-type ListGridRowProps = React.HTMLAttributes<HTMLDivElement>;
-
-function ListGridRow({ className, children, ...props }: ListGridRowProps) {
- return (
- <div
- role="row"
- className={cn(
- "group/row col-span-full grid h-12 grid-cols-subgrid items-center transition-colors hover:bg-accent/40",
- className,
- )}
- {...props}
- >
- <span aria-hidden="true" />
- {children}
- <span aria-hidden="true" />
- </div>
- );
-}
-
-// Cells and header cells carry the same default horizontal padding so the
-// header can never drift out of alignment with row content. Structural
-// columns (checkbox, kebab) opt out with `px-0`.
-function ListGridCell({
- className,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) {
- return (
- <div
- role="cell"
- className={cn("flex min-w-0 items-center px-2", className)}
- {...props}
- />
- );
-}
-
-export {
- ListGrid,
- ListGridBody,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
- ListGridCell,
-};
diff --git a/packages/ui/components/ui/sidebar.tsx b/packages/ui/components/ui/sidebar.tsx
index defe8d6e97..1dac84bbbc 100644
--- a/packages/ui/components/ui/sidebar.tsx
+++ b/packages/ui/components/ui/sidebar.tsx
@@ -26,17 +26,17 @@ import {
} from "@multica/ui/components/ui/tooltip"
import { PanelLeftIcon } from "@multica/ui/icons"
-const SIDEBAR_WIDTH_DEFAULT = 256
+const SIDEBAR_WIDTH_DEFAULT = 240
const SIDEBAR_WIDTH_MIN = 200
-const SIDEBAR_WIDTH_MAX = 360
+const SIDEBAR_WIDTH_MAX = 320
const SIDEBAR_WIDTH_STORAGE_KEY = "sidebar_width"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_DRAG_THRESHOLD = 2
-// Tailwind `md`–`xl`: wide enough to keep a two-pane list/detail surface, too
-// narrow to also spend 256px on the nav by default. The nav starts collapsed
-// here and the header's trigger docks it back.
-const SIDEBAR_AUTO_COLLAPSE_QUERY = "(min-width: 768px) and (max-width: 1279px)"
+// Tailwind `md`–`lg`: wide enough to keep a two-pane list/detail surface, too
+// narrow to also spend the panel's width on the nav by default. The nav starts
+// collapsed here and the header's trigger docks it back.
+const SIDEBAR_AUTO_COLLAPSE_QUERY = "(min-width: 768px) and (max-width: 1023px)"
/**
* Paints an element with whatever the sidebar wrapper is currently filled with.
@@ -165,7 +165,7 @@ function SidebarProvider({
// because nothing ever read it, and restoring the pair would be a bug rather
// than a feature: the auto-collapse below drives `setOpen(false)` from the
// viewport, so persisting its result would carry a collapse the user never
- // asked for out of the `md`–`xl` band and into their next session on a wider
+ // asked for out of the `md`–`lg` band and into their next session on a wider
// display. Persisting this needs a source that distinguishes a user toggle
// from an automated one — not a cookie on this callback.
const [_open, _setOpen] = React.useState(defaultOpen)
@@ -182,7 +182,7 @@ function SidebarProvider({
[setOpenProp, open]
)
- // Auto-collapse across the `md`–`xl` band. Only the two crossings are
+ // Auto-collapse across the `md`–`lg` band. Only the two crossings are
// automated: entering it parks the state we came in with and closes the nav,
// leaving it restores that state. Anything the user does in between — most
// of all re-opening the nav — is left alone until the next crossing.
@@ -417,7 +417,8 @@ function SidebarTrigger({
className={cn(className)}
onClick={(event) => {
onClick?.(event)
- toggleSidebar()
+ // A host that routes the toggle elsewhere prevents the default.
+ if (!event.defaultPrevented) toggleSidebar()
}}
{...props}
>
@@ -1006,6 +1007,8 @@ export {
SidebarRail,
SidebarSeparator,
SidebarTrigger,
+ clampSidebarWidth,
useSidebar,
+ useSidebarResize,
useSidebarSafe,
}
diff --git a/packages/ui/hooks/use-mobile.ts b/packages/ui/hooks/use-mobile.ts
index 4e0675c95e..b05f228d2a 100644
--- a/packages/ui/hooks/use-mobile.ts
+++ b/packages/ui/hooks/use-mobile.ts
@@ -2,7 +2,7 @@ import * as React from "react"
const MOBILE_BREAKPOINT = 768
// Tailwind `md`. Below it the nav is a sheet and list/detail surfaces fold to
-// one column. From here up to `xl` the nav stays a docked column but starts
+// one column. From here up to `lg` the nav stays a docked column but starts
// collapsed (see SIDEBAR_AUTO_COLLAPSE_QUERY), which leaves a foldable's inner
// screen or a tablet enough reading width for both panes.
const COMPACT_BREAKPOINT = 768
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index e11e69180e..e344cd606a 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -102,7 +102,9 @@
* per-frame text repaint caused by animating a clipped background-position.
* The old 200%-wide gradient travelled four label widths per 2.5s cycle.
* A six-width window with a repeating two-width mask preserves that spacing
- * and covers the label throughout the sweep, including the loop seam. */
+ * and covers the label throughout the sweep, including the loop seam.
+ * Hosts can raise contrast through the --shimmer-text-* variables (base and
+ * highlight colors, and how far the highlight band spreads from its peak). */
@keyframes shimmer-text-window {
from { transform: translateX(-66.6666666667%); }
to { transform: translateX(0%); }
@@ -121,7 +123,7 @@
vertical-align: bottom;
white-space: nowrap;
text-overflow: ellipsis;
- color: var(--muted-foreground);
+ color: var(--shimmer-text-base, var(--muted-foreground));
}
.shimmer-text-window {
@@ -132,7 +134,12 @@
height: 100%;
pointer-events: none;
user-select: none;
- mask-image: linear-gradient(90deg, transparent 35%, black 50%, transparent 65%);
+ mask-image: linear-gradient(
+ 90deg,
+ transparent calc(50% - var(--shimmer-text-spread, 15%)),
+ black 50%,
+ transparent calc(50% + var(--shimmer-text-spread, 15%))
+ );
mask-size: calc(100% / 3) 100%;
mask-repeat: repeat-x;
animation: shimmer-text-window 2.5s linear infinite;
@@ -146,7 +153,7 @@
width: calc(100% / 6);
overflow: hidden;
text-overflow: ellipsis;
- color: var(--foreground);
+ color: var(--shimmer-text-highlight, var(--foreground));
animation: shimmer-text-copy 2.5s linear infinite;
}
@@ -280,7 +287,9 @@ html[data-dnd-dragging="true"] * {
[data-sidebar-resizing="true"] [data-slot="sidebar-gap"],
[data-sidebar-resizing="true"] [data-slot="sidebar-container"],
-[data-sidebar-resizing="true"] [data-sidebar-resize-consumer] {
+[data-sidebar-resizing="true"] [data-sidebar-resize-consumer],
+[data-sidebar-resizing="true"] [data-slot="space-panel"],
+[data-sidebar-resizing="true"] [data-slot="list-column"] {
transition: none !important;
}
@@ -288,6 +297,15 @@ html[data-dnd-dragging="true"] * {
background-color: var(--sidebar-border);
}
+[data-sidebar-resizing="true"] [data-slot="space-panel-resize"]::after {
+ background-color: color-mix(in oklab, var(--ring) 60%, transparent);
+}
+
+html[data-sidebar-resizing="true"] {
+ cursor: ew-resize;
+ user-select: none;
+}
+
/* Right detail sidebars use react-resizable-panels, which sizes panels by
* updating the outer panel's flex-grow. Animate that property for button
* toggles only; mount-time layout restoration and resize sync should snap
diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.css
index 196a2aae58..b736754703 100644
--- a/packages/ui/styles/tokens.css
+++ b/packages/ui/styles/tokens.css
@@ -131,6 +131,11 @@
--dialog-exit-duration: 100ms;
--dialog-enter-easing: ease;
--dialog-exit-easing: ease;
+ /* Nav panel collapse, shared by the space panel and list columns. The
+ first frame also pays for the toggle's render and the page relayout, so
+ the curve starts soft instead of jumping. */
+ --nav-panel-duration: 220ms;
+ --nav-panel-easing: ease;
color-scheme: light;
/* Button geometry. Text and icon-only buttons share the height ladder.
diff --git a/packages/views/agents/components/agent-advanced-settings.test.tsx b/packages/views/agents/components/agent-advanced-settings.test.tsx
new file mode 100644
index 0000000000..233367612b
--- /dev/null
+++ b/packages/views/agents/components/agent-advanced-settings.test.tsx
@@ -0,0 +1,323 @@
+// @vitest-environment jsdom
+
+import { useEffect } from "react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enAgents from "../../locales/en/agents.json";
+import {
+ NavigationProvider,
+ type NavigationAdapter,
+} from "../../navigation";
+
+const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
+
+// The dialog decides which sections exist; what each section does is
+// covered by its own tests, so the editors are stubs.
+vi.mock("./agent-detail-inspector", () => ({
+ AgentDetailInspector: () => <div>general-form</div>,
+}));
+vi.mock("./agent-access-settings", () => ({
+ AgentAccessSettings: () => <div>agent-access-settings</div>,
+}));
+vi.mock("./tabs/skills-tab", () => ({
+ SkillsTab: () => <div>skills-tab</div>,
+}));
+vi.mock("./tabs/env-tab", () => ({
+ EnvTab: () => <div>env-tab</div>,
+}));
+vi.mock("./tabs/custom-args-tab", () => ({
+ CustomArgsTab: ({ onDirtyChange }: { onDirtyChange?: (dirty: boolean) => void }) => {
+ useEffect(() => onDirtyChange?.(true), [onDirtyChange]);
+ return <div>custom-args-tab</div>;
+ },
+}));
+vi.mock("./tabs/mcp-config-tab", () => ({
+ McpConfigTab: () => <div>mcp-config-tab</div>,
+}));
+vi.mock("./tabs/agent-mcp-tab", () => ({
+ AgentMcpTab: () => <div>agent-mcp-tab</div>,
+}));
+vi.mock("./tabs/integrations-tab", () => ({
+ IntegrationsTab: () => <div>integrations-tab</div>,
+}));
+vi.mock("./tabs/qoder-agent-tab", () => ({
+ QoderAgentTab: () => <div>qoder-agent-tab</div>,
+}));
+vi.mock("./tabs/runtime-config-tab", () => ({
+ RuntimeConfigTab: () => <div>runtime-config-tab</div>,
+}));
+
+// Whether the Integrations section is worth showing depends on the
+// deployment having a channel integration configured. Each listing is
+// backed by a ref so a test can flip `configured`.
+const larkListingRef = vi.hoisted(() => ({
+ current: { installations: [] as unknown[], configured: false },
+}));
+const slackListingRef = vi.hoisted(() => ({
+ current: { installations: [] as unknown[], configured: false },
+}));
+const telegramListingRef = vi.hoisted(() => ({
+ current: { installations: [] as unknown[], configured: false },
+}));
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+vi.mock("@multica/core/lark", () => ({
+ larkInstallationsOptions: () => ({
+ queryKey: ["lark", "installations"],
+ queryFn: () => Promise.resolve(larkListingRef.current),
+ }),
+}));
+vi.mock("@multica/core/slack", () => ({
+ slackInstallationsOptions: () => ({
+ queryKey: ["slack", "installations"],
+ queryFn: () => Promise.resolve(slackListingRef.current),
+ }),
+}));
+vi.mock("@multica/core/telegram", () => ({
+ telegramInstallationsOptions: () => ({
+ queryKey: ["telegram", "installations"],
+ queryFn: () => Promise.resolve(telegramListingRef.current),
+ }),
+}));
+
+import { AgentAdvancedSettings, type AdvancedSection } from "./agent-advanced-settings";
+
+const baseAgent: Agent = {
+ id: "agent-1",
+ workspace_id: "ws-1",
+ runtime_id: "runtime-1",
+ name: "Agent",
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ runtime_mode: "local",
+ runtime_config: {},
+ custom_args: [],
+ visibility: "workspace",
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ status: "idle",
+ max_concurrent_tasks: 1,
+ model: "",
+ owner_id: "user-1",
+ skills: [],
+ created_at: "2026-05-28T00:00:00Z",
+ updated_at: "2026-05-28T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+};
+
+function makeRuntime(provider: string): AgentRuntime {
+ return {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ daemon_id: null,
+ name: "Runtime",
+ runtime_mode: "local",
+ provider,
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: null,
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-05-28T00:00:00Z",
+ updated_at: "2026-05-28T00:00:00Z",
+ };
+}
+
+function renderDialog(
+ runtimes: AgentRuntime[],
+ {
+ canEdit = true,
+ section = "general",
+ onSectionChange = vi.fn(),
+ }: {
+ canEdit?: boolean;
+ section?: AdvancedSection | null;
+ onSectionChange?: (section: AdvancedSection | null) => void;
+ } = {},
+) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const navigation: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/agents/agent-1",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ };
+ return render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <NavigationProvider value={navigation}>
+ <QueryClientProvider client={queryClient}>
+ <AgentAdvancedSettings
+ agent={baseAgent}
+ runtime={runtimes[0] ?? null}
+ runtimes={runtimes}
+ members={[]}
+ onUpdate={vi.fn().mockResolvedValue(undefined)}
+ currentUserId="user-1"
+ canEdit={canEdit}
+ section={section}
+ onSectionChange={onSectionChange}
+ />
+ </QueryClientProvider>
+ </NavigationProvider>
+ </I18nProvider>,
+ );
+}
+
+const sectionNames = () =>
+ screen.getAllByRole("tab").map((tab) => tab.textContent);
+
+beforeEach(() => {
+ larkListingRef.current = { installations: [], configured: false };
+ slackListingRef.current = { installations: [], configured: false };
+ telegramListingRef.current = { installations: [], configured: false };
+});
+
+describe("AgentAdvancedSettings MCP section visibility", () => {
+ it.each([
+ ["Claude", "claude"],
+ ["Codex", "codex"],
+ ["Cursor", "cursor"],
+ ["Hermes", "hermes"],
+ ["Kimi", "kimi"],
+ ["Kiro", "kiro"],
+ ["OpenCode", "opencode"],
+ ["OpenClaw", "openclaw"],
+ ["Oh My Pi", "omp"],
+ ])("offers MCP when the agent runs on the %s runtime", (_label, provider) => {
+ renderDialog([makeRuntime(provider)]);
+ expect(screen.getByRole("tab", { name: /^MCP$/i })).toBeInTheDocument();
+ });
+
+ it("hides MCP for providers whose backend does not read mcp_config", () => {
+ // Saving an MCP config on e.g. Gemini would be a silent no-op at run
+ // time — that's the bug this hiding logic is meant to prevent.
+ renderDialog([makeRuntime("gemini")]);
+ expect(screen.queryByRole("tab", { name: /^MCP$/i })).not.toBeInTheDocument();
+ });
+
+ it("keeps MCP visible when the runtime row hasn't loaded yet", () => {
+ // Empty runtimes[] mimics the brief window between the page mounting and
+ // the runtimes query resolving. Hiding it would flicker it off and back on.
+ renderDialog([]);
+ expect(screen.getByRole("tab", { name: /^MCP$/i })).toBeInTheDocument();
+ });
+});
+
+describe("AgentAdvancedSettings Integrations section visibility", () => {
+ it.each([
+ ["Lark", larkListingRef],
+ // Regression: the gate must consider Slack too, not just Lark — a
+ // Slack-only deployment was hiding the section (and its bind entry).
+ ["Slack", slackListingRef],
+ ["Telegram", telegramListingRef],
+ ])("shows Integrations once %s is configured", async (_name, ref) => {
+ ref.current = { installations: [], configured: true };
+ renderDialog([makeRuntime("claude")]);
+ expect(
+ await screen.findByRole("tab", { name: /^Integrations$/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("hides Integrations when no channel integration is configured", () => {
+ renderDialog([makeRuntime("claude")]);
+ expect(
+ screen.queryByRole("tab", { name: /^Integrations$/i }),
+ ).not.toBeInTheDocument();
+ });
+});
+
+describe("AgentAdvancedSettings Environment section visibility", () => {
+ it("shows Environment to someone who can manage the agent", () => {
+ renderDialog([makeRuntime("claude")]);
+ expect(screen.getByRole("tab", { name: /^Environment$/i })).toBeInTheDocument();
+ });
+
+ it("hides Environment from users who cannot manage the agent", () => {
+ // The env endpoints admit the agent owner or a workspace owner/admin
+ // (MUL-5438) — the rule `canEdit` already encodes. Anyone else who opens
+ // it hits a guaranteed 403 on "Reveal & edit".
+ renderDialog([makeRuntime("claude")], { canEdit: false });
+ expect(
+ screen.queryByRole("tab", { name: /^Environment$/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("lands a link to a section the user can't open on General", () => {
+ renderDialog([makeRuntime("claude")], { canEdit: false, section: "env" });
+ expect(screen.getByRole("tab", { name: "General" })).toHaveAttribute(
+ "aria-selected",
+ "true",
+ );
+ expect(screen.getByText("general-form")).toBeInTheDocument();
+ expect(screen.queryByText("env-tab")).not.toBeInTheDocument();
+ });
+});
+
+describe("AgentAdvancedSettings section lists", () => {
+ it("lists settings, then capabilities, for an ordinary runtime", () => {
+ renderDialog([makeRuntime("claude")]);
+ expect(sectionNames()).toEqual([
+ "General",
+ "Access",
+ "Environment",
+ "Custom Args",
+ "Skills",
+ "MCP",
+ ]);
+ });
+
+ it("offers Routing only on OpenClaw", () => {
+ renderDialog([makeRuntime("openclaw")]);
+ expect(screen.getByRole("tab", { name: "Routing" })).toBeInTheDocument();
+ });
+
+ it("drops what the Qoder bridge rejects and names the Qoder Cloud Agents section", () => {
+ larkListingRef.current = { installations: [], configured: true };
+ renderDialog([makeRuntime("qoder_cloud")]);
+ expect(sectionNames()).toEqual(["General", "Access", "Qoder Cloud Agents"]);
+ });
+
+ it("renders nothing while closed", () => {
+ renderDialog([makeRuntime("claude")], { section: null });
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
+
+describe("AgentAdvancedSettings unsaved edits", () => {
+ it("asks before leaving a section with unsaved edits", () => {
+ const onSectionChange = vi.fn();
+ renderDialog([makeRuntime("claude")], {
+ section: "custom_args",
+ onSectionChange,
+ });
+ expect(screen.getByText("custom-args-tab")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("tab", { name: "General" }));
+ expect(onSectionChange).not.toHaveBeenCalled();
+ expect(screen.getByText("Discard unsaved changes?")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Discard changes" }));
+ expect(onSectionChange).toHaveBeenCalledWith("general");
+ });
+
+ it("moves straight to a section when nothing is unsaved", () => {
+ const onSectionChange = vi.fn();
+ renderDialog([makeRuntime("claude")], { onSectionChange });
+ fireEvent.click(screen.getByRole("tab", { name: "Skills" }));
+ expect(onSectionChange).toHaveBeenCalledWith("skills");
+ });
+});
diff --git a/packages/views/agents/components/agent-advanced-settings.tsx b/packages/views/agents/components/agent-advanced-settings.tsx
new file mode 100644
index 0000000000..6181120ee2
--- /dev/null
+++ b/packages/views/agents/components/agent-advanced-settings.tsx
@@ -0,0 +1,411 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
+import { providerSupportsMcpConfig } from "@multica/core/agents";
+import { useFeatureEnabled } from "@multica/core/config";
+import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { larkInstallationsOptions } from "@multica/core/lark";
+import { slackInstallationsOptions } from "@multica/core/slack";
+import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
+import { wecomInstallationsOptions } from "@multica/core/wecom";
+import { telegramInstallationsOptions } from "@multica/core/telegram";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { SkillsTab } from "./tabs/skills-tab";
+import { EnvTab } from "./tabs/env-tab";
+import { CustomArgsTab } from "./tabs/custom-args-tab";
+import { McpConfigTab } from "./tabs/mcp-config-tab";
+import { AgentMcpTab } from "./tabs/agent-mcp-tab";
+import { IntegrationsTab } from "./tabs/integrations-tab";
+import { QoderAgentTab } from "./tabs/qoder-agent-tab";
+import { RuntimeConfigTab } from "./tabs/runtime-config-tab";
+import { AgentDetailInspector } from "./agent-detail-inspector";
+import { AgentAccessSettings } from "./agent-access-settings";
+import { useT } from "../../i18n";
+
+export type AdvancedSection =
+ | "general"
+ | "access"
+ | "env"
+ | "custom_args"
+ | "runtime_config"
+ | "skills"
+ | "mcp_config"
+ | "composio_mcp"
+ | "integrations";
+
+type SectionLabelKey =
+ | "general"
+ | "access"
+ | "environment"
+ | "custom_args"
+ | "runtime_config"
+ | "qoder_agent"
+ | "skills"
+ | "mcp_config"
+ | "composio_mcp"
+ | "integrations";
+
+type SectionDef = { id: AdvancedSection; labelKey: SectionLabelKey };
+
+const SETTINGS_SECTIONS: SectionDef[] = [
+ { id: "general", labelKey: "general" },
+ { id: "access", labelKey: "access" },
+ { id: "env", labelKey: "environment" },
+ { id: "custom_args", labelKey: "custom_args" },
+ { id: "runtime_config", labelKey: "runtime_config" },
+];
+
+const CAPABILITY_SECTIONS: SectionDef[] = [
+ { id: "skills", labelKey: "skills" },
+ { id: "mcp_config", labelKey: "mcp_config" },
+ { id: "composio_mcp", labelKey: "composio_mcp" },
+ { id: "integrations", labelKey: "integrations" },
+];
+
+const ADVANCED_SECTIONS = new Set<string>(
+ [...SETTINGS_SECTIONS, ...CAPABILITY_SECTIONS].map((section) => section.id),
+);
+
+export function isAdvancedSection(value: string | null): value is AdvancedSection {
+ return value !== null && ADVANCED_SECTIONS.has(value);
+}
+
+interface AgentAdvancedSettingsProps {
+ agent: Agent;
+ runtime: AgentRuntime | null;
+ runtimes: AgentRuntime[];
+ members: MemberWithUser[];
+ onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+ currentUserId: string | null;
+ canEdit: boolean;
+ /** The open section, or `null` when the dialog is closed. */
+ section: AdvancedSection | null;
+ onSectionChange: (section: AdvancedSection | null) => void;
+}
+
+/**
+ * Every agent setting that is not a section of the page or a property in its
+ * panel. Sections the agent's runtime cannot use are not offered, and a
+ * section with unsaved edits asks before it is left or closed.
+ */
+export function AgentAdvancedSettings({
+ agent,
+ runtime,
+ runtimes,
+ members,
+ onUpdate,
+ currentUserId,
+ canEdit,
+ section,
+ onSectionChange,
+}: AgentAdvancedSettingsProps) {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const composioMCPAppsEnabled = useFeatureEnabled(
+ COMPOSIO_MCP_APPS_FLAG,
+ false,
+ );
+ const [dirty, setDirty] = useState(false);
+ // `undefined` = no pending move; `null` = a pending close.
+ const [pending, setPending] = useState<AdvancedSection | null | undefined>(
+ undefined,
+ );
+
+ const { data: larkListing } = useQuery({
+ ...larkInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
+ const { data: slackListing } = useQuery({
+ ...slackInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
+ const { data: dingtalkListing } = useQuery({
+ ...dingtalkInstallationsOptions(wsId),
+ });
+ const { data: wecomListing } = useQuery({
+ ...wecomInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
+ const { data: telegramListing } = useQuery({
+ ...telegramInstallationsOptions(wsId),
+ enabled: !!wsId,
+ });
+
+ const integrationsConfigured =
+ larkListing?.configured === true ||
+ slackListing?.configured === true ||
+ dingtalkListing?.configured === true ||
+ wecomListing?.configured === true ||
+ telegramListing?.configured === true;
+
+ // The Qoder bridge fails every task carrying skills, MCP, connected apps,
+ // env, args or a model override, and runs issues only (no chat). Those
+ // editors are not offered; the agent in Qoder Cloud Agents owns that configuration.
+ const qoderRuntime = runtime?.provider === "qoder_cloud";
+
+ const settingsSections = useMemo(
+ () =>
+ SETTINGS_SECTIONS.filter((item) => {
+ if (qoderRuntime) return item.id !== "env" && item.id !== "custom_args";
+ // Env is the only section backed by a secret-bearing endpoint.
+ // GET/PUT /api/agents/{id}/env admits the agent owner or a workspace
+ // owner/admin (MUL-5438) — the same rule `canEdit` encodes — so
+ // showing it to anyone else guarantees a 403 on "Reveal & edit".
+ // The server stays the boundary; this only removes a dead entry point.
+ if (item.id === "env") return canEdit;
+ if (item.id === "runtime_config") return runtime?.provider === "openclaw";
+ return true;
+ }).map((item) =>
+ qoderRuntime && item.id === "runtime_config"
+ ? { ...item, labelKey: "qoder_agent" as const }
+ : item,
+ ),
+ [canEdit, qoderRuntime, runtime?.provider],
+ );
+
+ const capabilitySections = useMemo(() => {
+ if (qoderRuntime) return [];
+ const showMcp = runtime ? providerSupportsMcpConfig(runtime.provider) : true;
+ const showComposioMcp =
+ composioMCPAppsEnabled &&
+ !!currentUserId &&
+ !!agent.owner_id &&
+ agent.owner_id === currentUserId;
+ return CAPABILITY_SECTIONS.filter((item) => {
+ if (item.id === "mcp_config") return showMcp;
+ if (item.id === "composio_mcp") return showComposioMcp;
+ if (item.id === "integrations") return integrationsConfigured;
+ return true;
+ });
+ }, [
+ agent.owner_id,
+ composioMCPAppsEnabled,
+ currentUserId,
+ integrationsConfigured,
+ qoderRuntime,
+ runtime,
+ ]);
+
+ const visible = [...settingsSections, ...capabilitySections];
+ // A link to a section this agent doesn't offer lands on General.
+ const active =
+ visible.find((item) => item.id === section) ?? visible[0] ?? SETTINGS_SECTIONS[0]!;
+
+ const request = (next: AdvancedSection | null) => {
+ if (next === active.id) return;
+ if (dirty) {
+ setPending(next);
+ return;
+ }
+ onSectionChange(next);
+ };
+
+ const confirmDiscard = () => {
+ if (pending === undefined) return;
+ setDirty(false);
+ onSectionChange(pending);
+ setPending(undefined);
+ };
+
+ const save = (updates: Record<string, unknown>) => onUpdate(agent.id, updates);
+
+ const groups = [
+ { label: t(($) => $.tabs.settings), items: settingsSections },
+ { label: t(($) => $.tabs.capabilities), items: capabilitySections },
+ ].filter((group) => group.items.length > 0);
+
+ return (
+ <>
+ <Dialog
+ open={section !== null}
+ onOpenChange={(open) => {
+ if (!open) request(null);
+ }}
+ >
+ <DialogContent className="flex h-[min(85dvh,52rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-5xl">
+ <DialogHeader className="shrink-0 gap-1 border-b px-5 py-4 pr-12">
+ <DialogTitle>{t(($) => $.detail.advanced_settings)}</DialogTitle>
+ <DialogDescription className="truncate">{agent.name}</DialogDescription>
+ </DialogHeader>
+
+ {/* Sidebar on md+ (nav pinned, content scrolls); below md the nav
+ is a horizontal strip above the content. */}
+ <div className="flex min-h-0 flex-1 flex-col md:flex-row">
+ <nav
+ className="shrink-0 overflow-x-auto border-b px-3 py-2 md:w-48 md:overflow-y-auto md:border-b-0 md:border-r md:py-3"
+ aria-label={t(($) => $.tabs.section_navigation_aria)}
+ >
+ <div className="flex w-max min-w-full items-center gap-1 md:w-full md:flex-col md:items-stretch md:gap-4">
+ {groups.map((group) => (
+ <div
+ key={group.label}
+ role="tablist"
+ aria-orientation="vertical"
+ aria-label={group.label}
+ className="flex items-center gap-1 md:flex-col md:items-stretch md:gap-0.5"
+ >
+ <span className="hidden px-2.5 pb-1 text-micro font-medium text-muted-foreground md:block">
+ {group.label}
+ </span>
+ {group.items.map((item) => {
+ const selected = active.id === item.id;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ role="tab"
+ aria-selected={selected}
+ onClick={() => request(item.id)}
+ className={cn(
+ "flex h-8 shrink-0 items-center rounded-md px-2.5 text-left text-caption transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring md:w-full",
+ selected
+ ? "bg-surface-selected text-surface-selected-foreground hover:bg-surface-selected"
+ : "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
+ )}
+ >
+ {t(($) => $.tabs[item.labelKey])}
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </nav>
+
+ <section role="tabpanel" className="min-w-0 flex-1 overflow-y-auto">
+ {/* General is wider: its profile sits beside a preview of the
+ new chat it produces. */}
+ <div
+ className={cn(
+ "w-full p-5 sm:p-6",
+ active.id === "general" ? "max-w-5xl" : "max-w-3xl",
+ )}
+ >
+ <h2 className="text-title-sm font-medium text-balance">
+ {t(($) => $.tabs[active.labelKey])}
+ </h2>
+ <div className="mt-6">
+ {active.id === "general" && (
+ <AgentDetailInspector
+ agent={agent}
+ runtime={runtime}
+ runtimes={runtimes}
+ members={members}
+ currentUserId={currentUserId}
+ canEdit={canEdit}
+ onUpdate={onUpdate}
+ />
+ )}
+ {active.id === "access" && (
+ <AgentAccessSettings
+ agent={agent}
+ members={members}
+ currentUserId={currentUserId}
+ onDirtyChange={setDirty}
+ onUpdate={onUpdate}
+ />
+ )}
+ {active.id === "env" && (
+ <EnvTab agent={agent} onDirtyChange={setDirty} />
+ )}
+ {active.id === "custom_args" && (
+ <CustomArgsTab
+ agent={agent}
+ runtimeDevice={runtime ?? undefined}
+ onSave={save}
+ onDirtyChange={setDirty}
+ />
+ )}
+ {active.id === "runtime_config" &&
+ (qoderRuntime ? (
+ <QoderAgentTab
+ canEdit={canEdit}
+ key={agent.id}
+ agent={agent}
+ onSave={save}
+ onDirtyChange={setDirty}
+ />
+ ) : (
+ <RuntimeConfigTab
+ agent={agent}
+ onSave={save}
+ onDirtyChange={setDirty}
+ />
+ ))}
+ {active.id === "skills" && (
+ <SkillsTab
+ agent={agent}
+ runtime={runtime}
+ currentUserId={currentUserId}
+ canEdit={canEdit}
+ />
+ )}
+ {active.id === "mcp_config" && (
+ <McpConfigTab
+ agent={agent}
+ runtime={runtime}
+ currentUserId={currentUserId}
+ canEdit={canEdit}
+ onSave={save}
+ onDirtyChange={setDirty}
+ />
+ )}
+ {active.id === "composio_mcp" && <AgentMcpTab agent={agent} />}
+ {active.id === "integrations" && (
+ <IntegrationsTab agent={agent} />
+ )}
+ </div>
+ </div>
+ </section>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {pending !== undefined && (
+ <AlertDialog
+ open
+ onOpenChange={(open) => {
+ if (!open) setPending(undefined);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.tabs.discard_dialog_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.tabs.discard_dialog_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.tabs.discard_keep)}</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={confirmDiscard}>
+ {t(($) => $.tabs.discard_confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+ </>
+ );
+}
diff --git a/packages/views/agents/components/agent-batch-toolbar.tsx b/packages/views/agents/components/agent-batch-toolbar.tsx
index d3746679ee..095c7b68b3 100644
--- a/packages/views/agents/components/agent-batch-toolbar.tsx
+++ b/packages/views/agents/components/agent-batch-toolbar.tsx
@@ -1,7 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
-import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import type { MemberWithUser } from "@multica/core/types";
@@ -9,11 +8,6 @@ import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { workspaceKeys } from "@multica/core/workspace/queries";
import { Button } from "@multica/ui/components/ui/button";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-import {
- UI_EASE_OUT,
- UI_MOTION_DURATION,
-} from "@multica/ui/lib/motion";
import {
Dialog,
DialogContent,
@@ -22,8 +16,9 @@ import {
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
-import { Archive, ArchiveRestore, Loader2, X } from "@multica/ui/icons";
+import { Archive, ArchiveRestore, Loader2 } from "@multica/ui/icons";
import { useT } from "../../i18n";
+import { CollectionBatchBar } from "../../layout/collection-list";
import { AccessPicker, type AccessChange } from "./inspector/access-picker";
import type { AgentListRow } from "./agents-page";
@@ -51,7 +46,6 @@ export function AgentBatchToolbar({
const { t } = useT("agents");
const wsId = useWorkspaceId();
const qc = useQueryClient();
- const shouldReduceMotion = useReducedMotion() ?? false;
const [confirmArchive, setConfirmArchive] = useState(false);
const [confirmAccess, setConfirmAccess] = useState(false);
const [accessChange, setAccessChange] = useState<AccessChange | null>(null);
@@ -137,57 +131,7 @@ export function AgentBatchToolbar({
return (
<>
- <AnimatePresence initial={false}>
- {rows.length > 0 && (
- <div
- key="agent-batch-toolbar"
- className="absolute bottom-6 left-1/2 z-50 -translate-x-1/2 max-md:above-chat-launcher"
- >
- <motion.div
- className="flex items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg"
- initial={{
- opacity: 0,
- transform: shouldReduceMotion
- ? "translateY(0)"
- : "translateY(8px)",
- }}
- animate={{
- opacity: 1,
- transform: "translateY(0)",
- transition: {
- duration: UI_MOTION_DURATION.fast,
- ease: UI_EASE_OUT,
- },
- }}
- exit={{
- opacity: 0,
- transform: shouldReduceMotion
- ? "translateY(0)"
- : "translateY(8px)",
- transition: {
- duration: shouldReduceMotion
- ? UI_MOTION_DURATION.fast
- : UI_MOTION_DURATION.micro,
- ease: UI_EASE_OUT,
- },
- }}
- >
- <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">
- <span className="text-body font-medium">
- {t(($) => $.actions.selected, { count: rows.length })}
- </span>
- <TooltipHint label={t(($) => $.actions.clear_selection)}>
- <button
- type="button"
- aria-label={t(($) => $.actions.clear_selection)}
- onClick={onClear}
- className="rounded-xs p-0.5 transition-colors hover:bg-accent"
- >
- <X className="size-3.5 text-muted-foreground" />
- </button>
- </TooltipHint>
- </div>
-
+ <CollectionBatchBar count={rows.length} onClear={onClear}>
{anyArchived && (
<Button
variant="ghost"
@@ -227,10 +171,7 @@ export function AgentBatchToolbar({
{t(($) => $.row_actions.archive)}
</Button>
)}
- </motion.div>
- </div>
- )}
- </AnimatePresence>
+ </CollectionBatchBar>
{/* Archive confirm dialog */}
{rows.length > 0 && <Dialog open={confirmArchive} onOpenChange={setConfirmArchive}>
diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsx
index 36a0f8e00d..ab0bfd8243 100644
--- a/packages/views/agents/components/agent-detail-inspector.tsx
+++ b/packages/views/agents/components/agent-detail-inspector.tsx
@@ -1,7 +1,6 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
import type {
Agent,
AgentConversationStarter,
@@ -13,10 +12,6 @@ import {
AGENT_MAX_CONCURRENT_TASKS_MAX,
AGENT_MAX_CONCURRENT_TASKS_MIN,
} from "@multica/core/agents";
-import {
- isRuntimeUsableForUser,
- runtimeModelsOptions,
-} from "@multica/core/runtimes";
import { useConfigStore } from "@multica/core/config";
import { isImeComposing } from "@multica/core/utils";
import { Input } from "@multica/ui/components/ui/input";
@@ -37,13 +32,10 @@ import { ConversationStartersEditor } from "./conversation-starters-editor";
import { NewChatPreview } from "./new-chat-preview";
import { useConversationStartersFocus } from "./use-conversation-starters-focus";
import { ModelPicker } from "./inspector/model-picker";
-import {
- buildModelChangeUpdate,
- type ModelCatalog,
-} from "./inspector/model-change-cleanup";
import { RuntimePicker } from "./inspector/runtime-picker";
import { ThinkingSettingField } from "./inspector/thinking-prop-row";
import { ServiceTierSettingField } from "./inspector/service-tier-setting-field";
+import { useExecutionControls } from "./inspector/use-execution-controls";
interface InspectorProps {
agent: Agent;
@@ -144,11 +136,13 @@ export function AgentDetailInspector({
isEqual: profileDraftsEqual,
});
- // A Qoder agent is bound to an agent in Qoder Cloud Agents, and the model lives there. Moving
- // between Qoder and any other runtime would need a different configuration
- // the server either rejects or the bridge refuses, so neither direction is
- // offered here.
- const qoderRuntime = runtime?.provider === "qoder_cloud";
+ const {
+ qoderRuntime,
+ canDiscoverRuntimeModels,
+ runtimeOptions,
+ changeModel,
+ changeRuntime,
+ } = useExecutionControls({ agent, runtime, runtimes, currentUserId, update });
const conversationStartersEnabled = useConfigStore(
(state) => state.agentConversationStartersSupported,
);
@@ -174,47 +168,7 @@ export function AgentDetailInspector({
isEqual: startersEqual,
});
const startersFocus = useConversationStartersFocus(agent.id, showStarters);
- const isOnline = runtime?.status === "online";
- const canReadRuntime =
- runtime != null && isRuntimeUsableForUser(runtime, currentUserId);
- const canDiscoverRuntimeModels = isOnline && canReadRuntime && !qoderRuntime;
const nameInvalid = name.trim().length === 0;
- const runtimeOptions = useMemo(
- () =>
- qoderRuntime
- ? runtimes
- : runtimes.filter((r) => r.provider !== "qoder_cloud"),
- [qoderRuntime, runtimes],
- );
-
- // Same query the Thinking / Speed fields already use, so switching model
- // costs no extra request. `null` = not authoritative (offline runtime, still
- // loading, or discovery failed) and must not trigger any clearing.
- const modelsQuery = useQuery(
- runtimeModelsOptions(canDiscoverRuntimeModels ? agent.runtime_id : null),
- );
- const modelCatalog = useMemo<ModelCatalog>(
- () =>
- modelsQuery.isSuccess
- ? modelsQuery.data.supported
- ? modelsQuery.data.models
- : []
- : null,
- [modelsQuery.data, modelsQuery.isSuccess],
- );
- const handleModelChange = useCallback(
- (model: string) =>
- update(
- buildModelChangeUpdate({
- provider: runtime?.provider ?? "",
- model,
- thinkingLevel: agent.thinking_level ?? "",
- serviceTier: agent.service_tier ?? "",
- catalog: modelCatalog,
- }),
- ),
- [agent.service_tier, agent.thinking_level, modelCatalog, runtime?.provider, update],
- );
return (
<div className="@container">
@@ -346,17 +300,7 @@ export function AgentDetailInspector({
members={members}
currentUserId={currentUserId}
canEdit={canEdit && !qoderRuntime}
- // Model, thinking level, and service tier are runtime/model
- // native. Clear them together so the new runtime resolves its
- // own defaults instead of inheriting incompatible tokens.
- onChange={(id) =>
- update({
- runtime_id: id,
- model: "",
- thinking_level: "",
- service_tier: "",
- })
- }
+ onChange={changeRuntime}
/>
</SettingsRow>
{qoderRuntime ? null : (
@@ -372,7 +316,7 @@ export function AgentDetailInspector({
runtimeOnline={canDiscoverRuntimeModels}
value={agent.model ?? ""}
canEdit={canEdit}
- onChange={handleModelChange}
+ onChange={changeModel}
/>
</SettingsRow>
<ThinkingSettingField
diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsx
index ce731f472a..3cec15c71d 100644
--- a/packages/views/agents/components/agent-detail-page.test.tsx
+++ b/packages/views/agents/components/agent-detail-page.test.tsx
@@ -7,58 +7,131 @@ import {
render,
screen,
waitFor,
+ within,
} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ApiError } from "@multica/core/api";
import type { Agent } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enAgents from "../../locales/en/agents.json";
+import { RESOURCES } from "../../locales";
import {
NavigationProvider,
type NavigationAdapter,
} from "../../navigation";
-const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
-
-// The DM tests exercise the header action wiring plus the real permission
-// rules (via auth + member fixtures); the tabbed body and avatar/presence
-// widgets are irrelevant weight, so they're stubbed.
-vi.mock("./agent-overview-pane", () => ({
- AgentOverviewPane: ({
+// The page-level tests exercise the header actions, the URL-driven dialogs and
+// the real permission rules (via auth + member fixtures). Each body section,
+// the properties panel and both dialogs have their own tests, so they're
+// stubbed down to the props the page hands them.
+vi.mock("./agent-properties-panel", () => ({
+ AgentPropertiesPanel: ({
agent,
onUpdate,
+ onEditAccess,
}: {
agent: Agent;
onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+ onEditAccess: () => void;
}) => (
- <button
- type="button"
- onClick={() => void onUpdate(agent.id, { model: "new-model" })}
- >
- update model
+ <div>
+ <span>model:{agent.model}</span>
+ <button
+ type="button"
+ onClick={() => void onUpdate(agent.id, { model: "new-model" })}
+ >
+ update model
+ </button>
+ <button type="button" onClick={onEditAccess}>
+ edit access
+ </button>
+ </div>
+ ),
+}));
+vi.mock("./tabs/activity-tab", () => ({
+ AgentWorkSections: ({ onViewAll }: { onViewAll: () => void }) => (
+ <button type="button" onClick={onViewAll}>
+ view all work
+ </button>
+ ),
+}));
+vi.mock("./agent-instructions-section", () => ({
+ AgentInstructionsSection: () => <div>instructions-section</div>,
+}));
+vi.mock("./agent-skills-section", () => ({
+ AgentSkillsSection: ({ onManage }: { onManage: () => void }) => (
+ <button type="button" onClick={onManage}>
+ manage skills
</button>
),
}));
+vi.mock("./agent-advanced-settings", () => ({
+ isAdvancedSection: (value: unknown) =>
+ typeof value === "string" &&
+ [
+ "general",
+ "access",
+ "env",
+ "custom_args",
+ "runtime_config",
+ "skills",
+ "mcp_config",
+ "composio_mcp",
+ "integrations",
+ ].includes(value),
+ AgentAdvancedSettings: ({
+ section,
+ onSectionChange,
+ }: {
+ section: string | null;
+ onSectionChange: (section: string | null) => void;
+ }) =>
+ section === null ? null : (
+ <div data-testid="advanced-settings">
+ advanced:{section}
+ <button type="button" onClick={() => onSectionChange(null)}>
+ close advanced
+ </button>
+ </div>
+ ),
+}));
+vi.mock("./agent-work-dialog", () => ({
+ AgentWorkDialog: ({
+ open,
+ onOpenChange,
+ }: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ }) =>
+ open ? (
+ <div data-testid="work-dialog">
+ <button type="button" onClick={() => onOpenChange(false)}>
+ close work
+ </button>
+ </div>
+ ) : null,
+}));
vi.mock("../../common/actor-avatar", () => ({
ActorAvatar: () => <div>actor-avatar</div>,
}));
-vi.mock("./agent-presence-indicator", () => ({
- AgentPresenceIndicator: () => null,
-}));
const agentsRef = vi.hoisted(() => ({ current: [] as unknown[] }));
const membersRef = vi.hoisted(() => ({ current: [] as unknown[] }));
// When set, the member query never resolves — the "membership still loading"
// window in which the DM decision is undetermined.
const membersPendingRef = vi.hoisted(() => ({ current: false }));
+const presenceRef = vi.hoisted(() => ({ current: new Map<string, unknown>() }));
+const runtimesRef = vi.hoisted(() => ({ current: [] as unknown[] }));
const currentUserRef = vi.hoisted(() => ({
current: { id: "user-1" } as { id: string } | null,
}));
const mockToastError = vi.hoisted(() => vi.fn());
+const mockToastSuccess = vi.hoisted(() => vi.fn());
const mockModalOpen = vi.hoisted(() => vi.fn());
const mockGetAgent = vi.hoisted(() => vi.fn());
const mockUpdateAgent = vi.hoisted(() => vi.fn());
+const mockArchiveAgent = vi.hoisted(() => vi.fn());
+const mockCancelAgentTasks = vi.hoisted(() => vi.fn());
+const mockCopyText = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
@@ -66,7 +139,7 @@ vi.mock("@multica/core/hooks", () => ({
vi.mock("@multica/core/agents", () => ({
isAgentRuntimeBound: (agent: { runtime_id: string; runtime_bound?: boolean }) =>
agent.runtime_bound !== false && agent.runtime_id.length > 0,
- useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
+ useWorkspacePresenceMap: () => ({ byAgent: presenceRef.current }),
}));
vi.mock("@multica/core/workspace/queries", () => ({
agentListOptions: (wsId: string) => ({
@@ -116,7 +189,7 @@ vi.mock("@multica/core/workspace/queries", () => ({
vi.mock("@multica/core/runtimes", () => ({
runtimeListOptions: (wsId: string) => ({
queryKey: ["runtimes", wsId],
- queryFn: () => Promise.resolve([]),
+ queryFn: () => Promise.resolve(runtimesRef.current),
}),
}));
vi.mock("@multica/core/auth", () => {
@@ -137,6 +210,8 @@ vi.mock("@multica/core/modals", () => ({
vi.mock("@multica/core/paths", () => ({
useWorkspacePaths: () => ({
agents: () => "/acme/agents",
+ agentDetail: (id: string) => `/acme/agents/${id}`,
+ newAgentManual: () => "/acme/agents/new/manual",
chat: () => "/acme/chat",
}),
}));
@@ -149,12 +224,21 @@ vi.mock("@multica/core/api", () => {
}
}
return {
- api: { getAgent: mockGetAgent, updateAgent: mockUpdateAgent },
+ api: {
+ getAgent: mockGetAgent,
+ updateAgent: mockUpdateAgent,
+ archiveAgent: mockArchiveAgent,
+ restoreAgent: vi.fn(),
+ cancelAgentTasks: mockCancelAgentTasks,
+ },
ApiError,
};
});
+vi.mock("@multica/ui/lib/clipboard", () => ({
+ copyText: mockCopyText,
+}));
vi.mock("sonner", () => ({
- toast: { success: vi.fn(), error: mockToastError },
+ toast: { success: mockToastSuccess, error: mockToastError },
}));
import { AgentDetailPage } from "./agent-detail-page";
@@ -184,22 +268,23 @@ const baseAgent: Agent = {
archived_by: null,
};
-function renderPage() {
+function renderPage(search = "") {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const push = vi.fn();
+ const replace = vi.fn();
const navigation: NavigationAdapter = {
push,
- replace: vi.fn(),
+ replace,
back: vi.fn(),
pathname: "/acme/agents/agent-1",
- searchParams: new URLSearchParams(),
+ searchParams: new URLSearchParams(search),
hash: "",
- getShareableUrl: (path) => path,
+ getShareableUrl: (path) => `https://app.test${path}`,
};
const view = render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <I18nProvider locale="en" resources={RESOURCES}>
<NavigationProvider value={navigation}>
<QueryClientProvider client={queryClient}>
<AgentDetailPage agentId="agent-1" />
@@ -207,7 +292,12 @@ function renderPage() {
</NavigationProvider>
</I18nProvider>,
);
- return { push, queryClient, ...view };
+ return { push, replace, queryClient, ...view };
+}
+
+function openMoreActions() {
+ fireEvent.click(screen.getByRole("button", { name: "Agent actions" }));
+ return screen.getByRole("menu");
}
beforeEach(() => {
@@ -215,9 +305,14 @@ beforeEach(() => {
currentUserRef.current = { id: "user-1" };
membersRef.current = [{ user_id: "user-1", role: "member" }];
membersPendingRef.current = false;
+ presenceRef.current = new Map();
+ runtimesRef.current = [];
agentsRef.current = [baseAgent];
mockGetAgent.mockRejectedValue(new ApiError("not found", 404, "Not Found"));
mockUpdateAgent.mockResolvedValue({ ...baseAgent, model: "new-model" });
+ mockArchiveAgent.mockResolvedValue(undefined);
+ mockCancelAgentTasks.mockResolvedValue({ cancelled: 2 });
+ mockCopyText.mockResolvedValue(true);
});
describe("AgentDetailPage direct-detail fallback", () => {
@@ -239,6 +334,10 @@ describe("AgentDetailPage direct-detail fallback", () => {
await waitFor(() => expect(mockGetAgent).toHaveBeenCalledWith("agent-1"));
expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();
+ // The loading state already carries the page chrome.
+ expect(
+ within(screen.getByRole("banner")).getByRole("link", { name: "Agents" }),
+ ).toHaveAttribute("href", "/acme/agents");
});
it("renders an agent returned by the detail endpoint", async () => {
@@ -258,7 +357,12 @@ describe("AgentDetailPage direct-detail fallback", () => {
renderPage();
- expect(await screen.findByText("Agent not found")).toBeInTheDocument();
+ expect(
+ await screen.findByRole("heading", { name: "Agent not found" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Back to agents" }),
+ ).toHaveAttribute("href", "/acme/agents");
});
it("keeps 403 distinct from not found", async () => {
@@ -270,7 +374,7 @@ describe("AgentDetailPage direct-detail fallback", () => {
renderPage();
expect(
- await screen.findByText("You don't have access to this agent"),
+ await screen.findByRole("heading", { name: "You don't have access to this agent" }),
).toBeInTheDocument();
expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
});
@@ -289,7 +393,9 @@ describe("AgentDetailPage direct-detail fallback", () => {
});
});
- expect(await screen.findByText("Agent not found")).toBeInTheDocument();
+ expect(
+ await screen.findByRole("heading", { name: "Agent not found" }),
+ ).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Assign work" }),
).not.toBeInTheDocument();
@@ -312,7 +418,7 @@ describe("AgentDetailPage direct-detail fallback", () => {
});
expect(
- await screen.findByText("You don't have access to this agent"),
+ await screen.findByRole("heading", { name: "You don't have access to this agent" }),
).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Assign work" }),
@@ -326,12 +432,25 @@ describe("AgentDetailPage direct-detail fallback", () => {
renderPage();
expect(
- await screen.findByText("Couldn't load this agent"),
+ await screen.findByRole("heading", { name: "Couldn't load this agent" }),
).toBeInTheDocument();
expect(screen.getByText("Network request failed")).toBeInTheDocument();
expect(screen.queryByText("Agent not found")).not.toBeInTheDocument();
});
+ it("retries a failed load from the error state", async () => {
+ agentsRef.current = [];
+ mockGetAgent.mockRejectedValueOnce(new Error("Network request failed"));
+ mockGetAgent.mockResolvedValue(baseAgent);
+
+ renderPage();
+
+ fireEvent.click(await screen.findByRole("button", { name: "Try again" }));
+ expect(
+ await screen.findByRole("button", { name: "Assign work" }),
+ ).toBeInTheDocument();
+ });
+
it("keeps successful detail data visible through a transient refetch error", async () => {
agentsRef.current = [];
mockGetAgent.mockResolvedValueOnce(baseAgent);
@@ -363,7 +482,7 @@ describe("AgentDetailPage direct-detail fallback", () => {
fireEvent.click(screen.getByRole("button", { name: "update model" }));
- expect(await screen.findByText("new-model")).toBeInTheDocument();
+ expect(await screen.findByText("model:new-model")).toBeInTheDocument();
expect(
queryClient.getQueryData<Agent>([
"agents",
@@ -375,6 +494,128 @@ describe("AgentDetailPage direct-detail fallback", () => {
});
});
+describe("AgentDetailPage layout", () => {
+ it("puts the agent in the breadcrumb and its name and description in the body", async () => {
+ agentsRef.current = [{ ...baseAgent, description: "Design and frontend" }];
+ renderPage();
+
+ await screen.findByRole("button", { name: "Assign work" });
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("link", { name: "Agents" })).toHaveAttribute(
+ "href",
+ "/acme/agents",
+ );
+ expect(within(header).getByText("Lambda")).toBeInTheDocument();
+ expect(
+ screen.getByRole("heading", { name: "Lambda", level: 1 }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Design and frontend")).toBeInTheDocument();
+ expect(screen.getByText("instructions-section")).toBeInTheDocument();
+ expect(screen.queryByRole("tablist")).not.toBeInTheDocument();
+ });
+
+ it("shows the Skills section, except on a Qoder Cloud Agents runtime", async () => {
+ const { unmount } = renderPage();
+ expect(
+ await screen.findByRole("button", { name: "manage skills" }),
+ ).toBeInTheDocument();
+ unmount();
+
+ runtimesRef.current = [{ id: "runtime-1", provider: "qoder_cloud" }];
+ renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("button", { name: "manage skills" }),
+ ).not.toBeInTheDocument(),
+ );
+ expect(screen.getByText("instructions-section")).toBeInTheDocument();
+ });
+
+ it("assigns work through the quick-create modal", async () => {
+ renderPage();
+ fireEvent.click(await screen.findByRole("button", { name: "Assign work" }));
+ expect(mockModalOpen).toHaveBeenCalledWith("quick-create-issue", {
+ agent_id: "agent-1",
+ });
+ });
+
+ it("shows the presence dot on the avatar once presence is known", async () => {
+ presenceRef.current = new Map([
+ ["agent-1", { availability: "online", runningCount: 0, queuedCount: 0 }],
+ ]);
+ renderPage();
+ expect(
+ await screen.findByRole("img", { name: /Online/ }),
+ ).toBeInTheDocument();
+ });
+});
+
+describe("AgentDetailPage deep links", () => {
+ it("opens Advanced settings at the section named by ?view=", async () => {
+ renderPage("view=general&focus=conversation_starters");
+ expect(await screen.findByTestId("advanced-settings")).toHaveTextContent(
+ "advanced:general",
+ );
+ });
+
+ it.each([
+ ["tab=settings", "advanced:general"],
+ ["tab=capabilities", "advanced:skills"],
+ ["view=mcp_config", "advanced:mcp_config"],
+ ])("maps the legacy link %s to %s", async (search, expected) => {
+ renderPage(search);
+ expect(await screen.findByTestId("advanced-settings")).toHaveTextContent(
+ expected,
+ );
+ });
+
+ it.each(["view=overview", "view=instructions", "tab=overview", "view=bogus"])(
+ "renders the plain page for %s",
+ async (search) => {
+ renderPage(search);
+ await screen.findByRole("button", { name: "Assign work" });
+ expect(screen.queryByTestId("advanced-settings")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("work-dialog")).not.toBeInTheDocument();
+ },
+ );
+
+ it("opens the full work list for ?view=work and clears the URL on close", async () => {
+ const { replace } = renderPage("view=work");
+ fireEvent.click(await screen.findByRole("button", { name: "close work" }));
+ expect(screen.queryByTestId("work-dialog")).not.toBeInTheDocument();
+ expect(replace).toHaveBeenCalledWith("/acme/agents/agent-1");
+ });
+
+ it("writes the open section to the URL, dropping a legacy ?tab=", async () => {
+ const { replace } = renderPage("tab=activity");
+ fireEvent.click(await screen.findByRole("button", { name: "manage skills" }));
+ expect(screen.getByTestId("advanced-settings")).toHaveTextContent(
+ "advanced:skills",
+ );
+ expect(replace).toHaveBeenLastCalledWith("/acme/agents/agent-1?view=skills");
+
+ fireEvent.click(screen.getByRole("button", { name: "close advanced" }));
+ expect(screen.queryByTestId("advanced-settings")).not.toBeInTheDocument();
+ expect(replace).toHaveBeenLastCalledWith("/acme/agents/agent-1");
+ });
+
+ it("opens Access settings from the properties panel", async () => {
+ renderPage();
+ fireEvent.click(await screen.findByRole("button", { name: "edit access" }));
+ expect(screen.getByTestId("advanced-settings")).toHaveTextContent(
+ "advanced:access",
+ );
+ });
+
+ it("opens the work list from View all", async () => {
+ const { replace } = renderPage();
+ fireEvent.click(await screen.findByRole("button", { name: "view all work" }));
+ expect(screen.getByTestId("work-dialog")).toBeInTheDocument();
+ expect(replace).toHaveBeenLastCalledWith("/acme/agents/agent-1?view=work");
+ });
+});
+
describe("AgentDetailPage DM button", () => {
it("navigates to the chat deep link when the user can chat with the agent", async () => {
const { push } = renderPage();
@@ -423,41 +664,11 @@ describe("AgentDetailPage DM button", () => {
// The archived banner is the signal the page has settled past loading.
await screen.findByText(/This agent is archived/);
expect(screen.queryByRole("button", { name: "DM" })).not.toBeInTheDocument();
- });
-
- it("hides the more-actions trigger when no menu actions are available", async () => {
- // The gate must survive a caller who genuinely CAN archive: an admin
- // passes `canEditAgent`, so `canArchive` is true. The only thing keeping
- // the menu empty is the system agent's undefined `onArchive`. Assert the
- // real aria label (locale `detail.more_actions_aria` = "Agent actions"),
- // so removing the `hasMoreActions` gate would render the empty shell and
- // fail this test.
- agentsRef.current = [
- { ...baseAgent, system_key: "mika" },
- ];
- membersRef.current = [{ user_id: "user-1", role: "admin" }];
- renderPage();
-
- await screen.findByRole("button", { name: "Assign work" });
expect(
- screen.queryByLabelText("Agent actions"),
+ screen.queryByRole("button", { name: "Assign work" }),
).not.toBeInTheDocument();
});
- it("keeps the more-actions trigger for an editable non-system agent", async () => {
- // Positive counterpart: an owner of a normal agent has a real archive
- // action, so the menu trigger must still render. Guards the gate against
- // over-hiding.
- agentsRef.current = [{ ...baseAgent, owner_id: "user-1" }];
- membersRef.current = [{ user_id: "user-1", role: "member" }];
- renderPage();
-
- await screen.findByRole("button", { name: "Assign work" });
- expect(
- screen.getByLabelText("Agent actions"),
- ).toBeInTheDocument();
- });
-
it("explains an unbound agent and blocks run actions without losing the profile", async () => {
agentsRef.current = [
{
@@ -472,14 +683,117 @@ describe("AgentDetailPage DM button", () => {
expect(
await screen.findByText(/needs a runtime before it can run/i),
).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "Bind runtime" }),
- ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Bind runtime" }));
+ expect(screen.getByTestId("advanced-settings")).toHaveTextContent(
+ "advanced:general",
+ );
fireEvent.click(screen.getByRole("button", { name: "DM" }));
expect(mockToastError).toHaveBeenCalledWith(
"Bind a runtime before running this agent.",
);
+ fireEvent.click(screen.getByRole("button", { name: "Assign work" }));
+ expect(mockToastError).toHaveBeenCalledTimes(2);
expect(mockModalOpen).not.toHaveBeenCalled();
});
});
+
+describe("AgentDetailPage more actions", () => {
+ it("keeps Advanced settings and copy actions but no Archive for a system agent", async () => {
+ // An admin passes `canEditAgent`, so only the system key keeps Archive
+ // out of the menu.
+ agentsRef.current = [{ ...baseAgent, system_key: "mika" }];
+ membersRef.current = [{ user_id: "user-1", role: "admin" }];
+ renderPage();
+
+ await screen.findByRole("button", { name: "Assign work" });
+ const menu = openMoreActions();
+ expect(
+ within(menu).getByRole("menuitem", { name: "Advanced settings" }),
+ ).toBeInTheDocument();
+ expect(
+ within(menu).getByRole("menuitem", { name: "Copy link" }),
+ ).toBeInTheDocument();
+ expect(
+ within(menu).queryByRole("menuitem", { name: "Archive Agent" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("archives an owned agent after confirmation and returns to the list", async () => {
+ agentsRef.current = [{ ...baseAgent, owner_id: "user-1" }];
+ const { push } = renderPage();
+
+ await screen.findByRole("button", { name: "Assign work" });
+ fireEvent.click(
+ within(openMoreActions()).getByRole("menuitem", { name: "Archive Agent" }),
+ );
+ fireEvent.click(await screen.findByRole("button", { name: "Archive" }));
+
+ expect(mockArchiveAgent).toHaveBeenCalledWith("agent-1");
+ expect(push).toHaveBeenCalledWith("/acme/agents");
+ });
+
+ it("opens Advanced settings at General", async () => {
+ renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+ fireEvent.click(
+ within(openMoreActions()).getByRole("menuitem", { name: "Advanced settings" }),
+ );
+ expect(screen.getByTestId("advanced-settings")).toHaveTextContent(
+ "advanced:general",
+ );
+ });
+
+ it("copies the shareable link and the agent ID", async () => {
+ renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+
+ fireEvent.click(
+ within(openMoreActions()).getByRole("menuitem", { name: "Copy link" }),
+ );
+ await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith("Link copied"));
+ expect(mockCopyText).toHaveBeenCalledWith("https://app.test/acme/agents/agent-1");
+
+ fireEvent.click(
+ within(openMoreActions()).getByRole("menuitem", { name: "Copy agent ID" }),
+ );
+ await waitFor(() =>
+ expect(mockToastSuccess).toHaveBeenCalledWith("Agent ID copied"),
+ );
+ expect(mockCopyText).toHaveBeenLastCalledWith("agent-1");
+ });
+
+ it("links Duplicate to the manual create flow", async () => {
+ renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+ expect(
+ within(openMoreActions()).getByRole("menuitem", { name: "Duplicate" }),
+ ).toHaveAttribute("href", "/acme/agents/new/manual?duplicate=agent-1");
+ });
+
+ it("cancels active runs only after confirmation", async () => {
+ agentsRef.current = [{ ...baseAgent, owner_id: "user-1" }];
+ presenceRef.current = new Map([
+ ["agent-1", { availability: "online", runningCount: 1, queuedCount: 1 }],
+ ]);
+ renderPage();
+
+ await screen.findByRole("button", { name: "Assign work" });
+ fireEvent.click(
+ within(openMoreActions()).getByRole("menuitem", { name: /Cancel all/ }),
+ );
+ expect(mockCancelAgentTasks).not.toHaveBeenCalled();
+ const dialog = await screen.findByRole("alertdialog");
+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel all runs" }));
+ await waitFor(() => expect(mockCancelAgentTasks).toHaveBeenCalledWith("agent-1"));
+ });
+
+ it("offers no run cancellation while nothing is active", async () => {
+ agentsRef.current = [{ ...baseAgent, owner_id: "user-1" }];
+ renderPage();
+ await screen.findByRole("button", { name: "Assign work" });
+ expect(
+ within(openMoreActions()).queryByRole("menuitem", { name: /Cancel all/ }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index c38254eef2..249661df1a 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -1,26 +1,26 @@
"use client";
-import { useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRegisterCommandBarContext } from "../../search/register-context";
import {
AlertCircle,
- ArrowLeft,
- Bot,
- Clock3,
+ Archive,
+ Copy,
+ Hash,
+ Link2,
Lock,
MessageSquare,
MoreHorizontal,
Plus,
+ RotateCcw,
Server,
+ Settings2,
+ Square,
Trash2,
} from "@multica/ui/icons";
import { toast } from "sonner";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import type {
- Agent,
- AgentRuntime,
- UpdateAgentRequest,
-} from "@multica/core/types";
+import type { Agent, UpdateAgentRequest } from "@multica/core/types";
import {
type AgentPresenceDetail,
isAgentRuntimeBound,
@@ -38,11 +38,21 @@ import {
memberListOptions,
workspaceKeys,
} from "@multica/core/workspace/queries";
-import { runtimeDisplayLabel, runtimeListOptions } from "@multica/core/runtimes";
+import { runtimeListOptions } from "@multica/core/runtimes";
import { useAgentPermissions } from "@multica/core/permissions";
import { Button } from "@multica/ui/components/ui/button";
import { IconButton } from "@multica/ui/components/common/icon-button";
import { CapabilityBanner } from "@multica/ui/components/common/capability-banner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
@@ -55,18 +65,49 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { copyText } from "@multica/ui/lib/clipboard";
import { cn } from "@multica/ui/lib/utils";
import { AppLink, useNavigation } from "../../navigation";
-import { PAGE_GUTTER, PAGE_RAIL, PageHeader } from "../../layout/page-header";
+import { CollectionPageState } from "../../layout/collection-page";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIdentity,
+ ObjectPage,
+} from "../../layout/object-page";
import { ActorAvatar } from "../../common/actor-avatar";
-import { AgentPresenceIndicator } from "./agent-presence-indicator";
-import { VisibilityBadge } from "./visibility-badge";
-import { AgentOverviewPane, type DetailTab } from "./agent-overview-pane";
-import { ExpandableDescription } from "../../common/expandable-description";
-import { useT, useTimeAgo } from "../../i18n";
+import { useT } from "../../i18n";
+import { availabilityConfig } from "../presence";
+import {
+ AgentAdvancedSettings,
+ isAdvancedSection,
+ type AdvancedSection,
+} from "./agent-advanced-settings";
+import { AgentInstructionsSection } from "./agent-instructions-section";
+import { AgentPropertiesPanel } from "./agent-properties-panel";
+import { describeCancelImpact } from "./agent-row-actions";
+import { AgentSkillsSection } from "./agent-skills-section";
+import { AgentWorkDialog } from "./agent-work-dialog";
+import { AgentWorkSections } from "./tabs/activity-tab";
+
+const AGENT_DETAIL_LAYOUT_ID = "multica_agent_detail_layout";
+
+/**
+ * The page's `?view=` deep link. Every view the old tabbed page had stays
+ * linkable: settings sections open Advanced settings there, `work` opens the
+ * work list, and the rest are the page itself. `?tab=` predates `?view=`.
+ */
+function viewFromParams(params: URLSearchParams): string | null {
+ const view = params.get("view");
+ if (view !== null) return view;
+ const tab = params.get("tab");
+ if (tab === "settings") return "general";
+ if (tab === "capabilities") return "skills";
+ return tab;
+}
interface AgentDetailPageProps {
agentId: string;
@@ -120,10 +161,8 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
useMemo(() => (agent ? { kind: "agent", agent } : null), [agent]),
);
- // Permission hook MUST be called unconditionally — its `agent | null`
- // signature handles the not-found / loading case internally so the early
- // returns below don't violate the rules of hooks. Backend gates archive
- // and restore identically to edit, so a single `canEdit` covers them all.
+ // Backend gates archive and restore identically to edit, so a single
+ // `canEdit` covers them all.
const {
canAssign,
canEdit,
@@ -131,80 +170,121 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
} = useAgentPermissions(agent, wsId);
const [confirmArchive, setConfirmArchive] = useState(false);
+ const [confirmCancelRuns, setConfirmCancelRuns] = useState(false);
- // One-shot channel: the inspector's compact Lark status row asks the
- // overview pane to focus a tab. The pane clears it after consuming.
- const [tabNavIntent, setTabNavIntent] = useState<DetailTab | null>(null);
-
- const handleUpdate = async (id: string, data: Record<string, unknown>) => {
- // Optimistic update: patch the matching agent in the cached list
- // BEFORE the network round-trip so the inspector picker chips flip to
- // the new value immediately on click. Without this, every inspector
- // picker (thinking / visibility / concurrency / model / runtime) waits
- // 0.5-2s for the API response + invalidate + refetch before the trigger
- // updates — readable as obvious lag in the UI.
- //
- // On error we rollback only the fields THIS call wrote, leaving any
- // other concurrently-mutated fields untouched, then invalidate so the
- // cache converges with the server. A whole-list snapshot rollback
- // would clobber a concurrent successful mutation if the failing call
- // resolves last (e.g. flipping visibility then runtime simultaneously
- // and only the visibility PATCH fails).
- const optimisticData =
- typeof data.runtime_id === "string"
- ? { ...data, runtime_bound: data.runtime_id.trim().length > 0 }
- : data;
- const queryKey = workspaceKeys.agents(wsId);
- const detailQueryKey = workspaceKeys.agent(wsId, id);
- const prevAgents = qc.getQueryData<Agent[]>(queryKey);
- const prevListAgent = prevAgents?.find((a) => a.id === id);
- const prevDetailAgent = qc.getQueryData<Agent>(detailQueryKey);
- const previousFields = (previousAgent: Agent | undefined) => {
- const fields: Record<string, unknown> = {};
- if (!previousAgent) return fields;
- for (const key of Object.keys(optimisticData)) {
- fields[key] = (
- previousAgent as unknown as Record<string, unknown>
- )[key];
- }
- return fields;
- };
- const prevListFields = previousFields(prevListAgent);
- const prevDetailFields = previousFields(prevDetailAgent);
- qc.setQueryData<Agent[]>(queryKey, (old) =>
- old?.map((a) =>
- a.id === id ? ({ ...a, ...optimisticData } as Agent) : a,
- ),
- );
- qc.setQueryData<Agent>(detailQueryKey, (old) =>
- old ? ({ ...old, ...optimisticData } as Agent) : old,
- );
- try {
- const updatedAgent = await api.updateAgent(
- id,
- data as UpdateAgentRequest,
+ const urlView = viewFromParams(navigation.searchParams);
+ const [advancedSection, setAdvancedSection] = useState<AdvancedSection | null>(
+ () => (isAdvancedSection(urlView) ? urlView : null),
+ );
+ const [workOpen, setWorkOpen] = useState(() => urlView === "work");
+ const lastUrlViewRef = useRef(urlView);
+
+ // Back/forward or a link landing on this mounted page.
+ useEffect(() => {
+ if (urlView === lastUrlViewRef.current) return;
+ lastUrlViewRef.current = urlView;
+ setAdvancedSection(isAdvancedSection(urlView) ? urlView : null);
+ setWorkOpen(urlView === "work");
+ }, [urlView]);
+
+ const writeView = useCallback(
+ (view: string | null) => {
+ lastUrlViewRef.current = view;
+ const params = new URLSearchParams(navigation.searchParams);
+ params.delete("tab");
+ if (view === null) params.delete("view");
+ else params.set("view", view);
+ const query = params.toString();
+ navigation.replace(`${navigation.pathname}${query ? `?${query}` : ""}`);
+ },
+ [navigation],
+ );
+ const openAdvanced = useCallback(
+ (section: AdvancedSection | null) => {
+ setAdvancedSection(section);
+ writeView(section);
+ },
+ [writeView],
+ );
+ const openWork = useCallback(
+ (open: boolean) => {
+ setWorkOpen(open);
+ writeView(open ? "work" : null);
+ },
+ [writeView],
+ );
+
+ const handleUpdate = useCallback(
+ async (id: string, data: Record<string, unknown>) => {
+ // Optimistic update: patch the matching agent in the cached list
+ // BEFORE the network round-trip so the pickers flip to the new value
+ // immediately on click. Without this, every picker waits 0.5-2s for
+ // the API response + invalidate + refetch before the trigger updates —
+ // readable as obvious lag in the UI.
+ //
+ // On error we rollback only the fields THIS call wrote, leaving any
+ // other concurrently-mutated fields untouched, then invalidate so the
+ // cache converges with the server. A whole-list snapshot rollback
+ // would clobber a concurrent successful mutation if the failing call
+ // resolves last (e.g. flipping visibility then runtime simultaneously
+ // and only the visibility PATCH fails).
+ const optimisticData =
+ typeof data.runtime_id === "string"
+ ? { ...data, runtime_bound: data.runtime_id.trim().length > 0 }
+ : data;
+ const queryKey = workspaceKeys.agents(wsId);
+ const detailQueryKey = workspaceKeys.agent(wsId, id);
+ const prevAgents = qc.getQueryData<Agent[]>(queryKey);
+ const prevListAgent = prevAgents?.find((a) => a.id === id);
+ const prevDetailAgent = qc.getQueryData<Agent>(detailQueryKey);
+ const previousFields = (previousAgent: Agent | undefined) => {
+ const fields: Record<string, unknown> = {};
+ if (!previousAgent) return fields;
+ for (const key of Object.keys(optimisticData)) {
+ fields[key] = (
+ previousAgent as unknown as Record<string, unknown>
+ )[key];
+ }
+ return fields;
+ };
+ const prevListFields = previousFields(prevListAgent);
+ const prevDetailFields = previousFields(prevDetailAgent);
+ qc.setQueryData<Agent[]>(queryKey, (old) =>
+ old?.map((a) =>
+ a.id === id ? ({ ...a, ...optimisticData } as Agent) : a,
+ ),
);
- cacheAgentResponse(qc, wsId, updatedAgent, { insertIntoList: false });
- void qc.invalidateQueries({ queryKey });
- toast.success(t(($) => $.detail.agent_updated_toast));
- } catch (e) {
- if (prevListAgent) {
- qc.setQueryData<Agent[]>(queryKey, (old) =>
- old?.map((a) =>
- a.id === id ? ({ ...a, ...prevListFields } as Agent) : a,
- ),
- );
- }
- if (prevDetailAgent) {
- qc.setQueryData<Agent>(detailQueryKey, (old) =>
- old ? ({ ...old, ...prevDetailFields } as Agent) : old,
+ qc.setQueryData<Agent>(detailQueryKey, (old) =>
+ old ? ({ ...old, ...optimisticData } as Agent) : old,
+ );
+ try {
+ const updatedAgent = await api.updateAgent(
+ id,
+ data as UpdateAgentRequest,
);
+ cacheAgentResponse(qc, wsId, updatedAgent, { insertIntoList: false });
+ void qc.invalidateQueries({ queryKey });
+ toast.success(t(($) => $.detail.agent_updated_toast));
+ } catch (e) {
+ if (prevListAgent) {
+ qc.setQueryData<Agent[]>(queryKey, (old) =>
+ old?.map((a) =>
+ a.id === id ? ({ ...a, ...prevListFields } as Agent) : a,
+ ),
+ );
+ }
+ if (prevDetailAgent) {
+ qc.setQueryData<Agent>(detailQueryKey, (old) =>
+ old ? ({ ...old, ...prevDetailFields } as Agent) : old,
+ );
+ }
+ void qc.invalidateQueries({ queryKey });
+ toast.error(e instanceof Error ? e.message : t(($) => $.detail.update_failed_toast));
+ throw e;
}
- void qc.invalidateQueries({ queryKey });
- toast.error(e instanceof Error ? e.message : t(($) => $.detail.update_failed_toast));
- throw e;
- }
- };
+ },
+ [qc, t, wsId],
+ );
const handleArchive = async (id: string) => {
try {
@@ -226,79 +306,114 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
}
};
+ const handleCancelRuns = async (id: string) => {
+ try {
+ const { cancelled } = await api.cancelAgentTasks(id);
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ toast.success(
+ cancelled === 0
+ ? t(($) => $.row_actions.no_tasks_to_cancel_toast)
+ : t(($) => $.row_actions.cancelled_tasks_toast, { count: cancelled }),
+ );
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : t(($) => $.row_actions.cancel_failed_toast));
+ }
+ };
+
+ const listSegment = { href: paths.agents(), label: t(($) => $.page.title) };
+
// --- Loading ---
if (!agent && (agentsLoading || detailQuery.isPending)) {
- return <DetailLoadingSkeleton />;
- }
-
- // --- No permission (private agent the caller is not in allowed_principals for) ---
- if (!agent && isForbidden) {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <BackHeader paths={paths.agents()} title={t(($) => $.detail.back_to_agents)} />
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
- <Lock className="h-8 w-8 text-muted-foreground" />
- <div>
- <p className="text-body font-medium">{t(($) => $.detail.no_access_title)}</p>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.detail.no_access_hint)}
- </p>
- </div>
- <Button
- size="sm"
- render={<AppLink href={paths.agents()} />}
- nativeButton={false}
- >
- {t(($) => $.detail.back_to_agents_full)}
- </Button>
- </div>
- </div>
+ <ObjectPage
+ layoutId={AGENT_DETAIL_LAYOUT_ID}
+ segments={[listSegment]}
+ leaf={<Skeleton className="h-4 w-40" />}
+ >
+ <DetailLoadingSkeleton />
+ </ObjectPage>
);
}
- // --- Not found / error ---
- if (!agent) {
- const loadError = detailError ?? agentsError;
+ // --- No permission (private agent the caller is not in allowed_principals for) ---
+ if (!agent && isForbidden) {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <BackHeader paths={paths.agents()} title={t(($) => $.detail.back_to_agents)} />
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
- <AlertCircle className="h-8 w-8 text-destructive" />
- <div>
- <p className="text-body font-medium">
- {isNotFound
- ? t(($) => $.detail.not_found_title)
- : t(($) => $.detail.load_failed_title)}
- </p>
- <p className="mt-1 text-caption text-muted-foreground">
- {isNotFound
- ? t(($) => $.detail.not_found_default)
- : loadError instanceof Error
- ? loadError.message
- : t(($) => $.detail.load_failed_default)}
- </p>
- </div>
- <div className="flex items-center gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => {
- void Promise.all([refetchAgents(), detailQuery.refetch()]);
- }}
- >
- {t(($) => $.detail.try_again)}
- </Button>
+ <ObjectPage
+ layoutId={AGENT_DETAIL_LAYOUT_ID}
+ segments={[listSegment]}
+ leaf={
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.detail.no_access_title)}
+ </span>
+ }
+ >
+ <CollectionPageState
+ icon={Lock}
+ title={t(($) => $.detail.no_access_title)}
+ description={t(($) => $.detail.no_access_hint)}
+ actions={
<Button
size="sm"
+ variant="outline"
render={<AppLink href={paths.agents()} />}
nativeButton={false}
>
{t(($) => $.detail.back_to_agents_full)}
</Button>
- </div>
- </div>
- </div>
+ }
+ />
+ </ObjectPage>
+ );
+ }
+
+ // --- Not found / error ---
+ if (!agent) {
+ const loadError = detailError ?? agentsError;
+ const title = isNotFound
+ ? t(($) => $.detail.not_found_title)
+ : t(($) => $.detail.load_failed_title);
+ return (
+ <ObjectPage
+ layoutId={AGENT_DETAIL_LAYOUT_ID}
+ segments={[listSegment]}
+ leaf={<span className="truncate text-muted-foreground">{title}</span>}
+ >
+ <CollectionPageState
+ role="alert"
+ tone="destructive"
+ icon={AlertCircle}
+ title={title}
+ description={
+ isNotFound
+ ? t(($) => $.detail.not_found_default)
+ : loadError instanceof Error
+ ? loadError.message
+ : t(($) => $.detail.load_failed_default)
+ }
+ actions={
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ void Promise.all([refetchAgents(), detailQuery.refetch()]);
+ }}
+ >
+ {t(($) => $.detail.try_again)}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ render={<AppLink href={paths.agents()} />}
+ nativeButton={false}
+ >
+ {t(($) => $.detail.back_to_agents_full)}
+ </Button>
+ </>
+ }
+ />
+ </ObjectPage>
);
}
@@ -310,6 +425,12 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
const owner = agent.owner_id
? members.find((m) => m.user_id === agent.owner_id) ?? null
: null;
+ const currentUserId = currentUser?.id ?? null;
+ const runningCount = presence?.runningCount ?? 0;
+ const queuedCount = presence?.queuedCount ?? 0;
+ const hasActiveWork = runningCount + queuedCount > 0;
+ // Multica's built-in agents cannot be archived — the server refuses it.
+ const canArchive = canEdit.allowed && !isArchived && !agent.system_key;
// Chat shares the invocation gate with assignment (MUL-3963): starting a
// chat triggers agent runs. The button stays visible either way — a denied
@@ -343,92 +464,274 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
.getState()
.open("quick-create-issue", { agent_id: agent.id });
};
+ const handleCopy = (text: string, toastText: string) => {
+ void copyText(text).then((ok) => {
+ if (ok) toast.success(toastText);
+ });
+ };
+
+ const actions = (
+ <>
+ {!isArchived && (
+ <IconButton
+ label={t(($) => $.detail.dm)}
+ tooltipSide="bottom"
+ className="text-muted-foreground data-disabled:pointer-events-none data-disabled:opacity-50"
+ disabled={permissionsLoading}
+ render={
+ <AppLink href={`${paths.chat()}?agent=${agent.id}`} onClick={handleDm} />
+ }
+ nativeButton={false}
+ >
+ <MessageSquare />
+ </IconButton>
+ )}
+ {!isArchived && canAssign.allowed && (
+ <Button type="button" size="sm" onClick={handleAssign}>
+ <Plus />
+ {t(($) => $.detail.assign_work)}
+ </Button>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={t(($) => $.detail.more_actions_aria)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ >
+ <MoreHorizontal />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-auto min-w-48">
+ <DropdownMenuItem onClick={() => openAdvanced("general")}>
+ <Settings2 />
+ {t(($) => $.detail.advanced_settings)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() =>
+ handleCopy(
+ navigation.getShareableUrl(paths.agentDetail(agent.id)),
+ t(($) => $.detail.link_copied_toast),
+ )
+ }
+ >
+ <Link2 />
+ {t(($) => $.detail.copy_link)}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => handleCopy(agent.id, t(($) => $.detail.id_copied_toast))}
+ >
+ <Hash />
+ {t(($) => $.detail.copy_id)}
+ </DropdownMenuItem>
+ {!isArchived && (
+ <DropdownMenuItem
+ render={
+ <AppLink href={`${paths.newAgentManual()}?duplicate=${agent.id}`} />
+ }
+ >
+ <Copy />
+ {t(($) => $.row_actions.duplicate)}
+ </DropdownMenuItem>
+ )}
+ {canEdit.allowed && !isArchived && hasActiveWork && (
+ <DropdownMenuItem onClick={() => setConfirmCancelRuns(true)}>
+ <Square />
+ {t(($) => $.row_actions.cancel_all_tasks)}
+ </DropdownMenuItem>
+ )}
+ {canEdit.allowed && isArchived && (
+ <DropdownMenuItem onClick={() => handleRestore(agent.id)}>
+ <RotateCcw />
+ {t(($) => $.detail.restore)}
+ </DropdownMenuItem>
+ )}
+ {canArchive && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setConfirmArchive(true)}
+ >
+ <Trash2 />
+ {t(($) => $.detail.more_archive)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </>
+ );
+
+ const notices = [
+ !canEdit.allowed && (
+ <CapabilityBanner
+ key="capability"
+ reason={canEdit.reason}
+ resource="agent"
+ ownerName={owner?.name}
+ />
+ ),
+ isArchived && (
+ <Notice
+ key="archived"
+ icon={<Archive className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />}
+ action={
+ canEdit.allowed ? (
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => handleRestore(agent.id)}
+ >
+ {t(($) => $.detail.restore)}
+ </Button>
+ ) : null
+ }
+ >
+ {t(($) => $.detail.archived_banner)}
+ </Notice>
+ ),
+ !isArchived && !runtimeBound && (
+ <Notice
+ key="runtime"
+ tone="warning"
+ icon={<Server className="size-3.5 shrink-0 text-warning" aria-hidden="true" />}
+ action={
+ canEdit.allowed ? (
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => openAdvanced("general")}
+ >
+ {t(($) => $.detail.bind_runtime)}
+ </Button>
+ ) : null
+ }
+ >
+ {t(($) => $.detail.runtime_required_banner)}
+ </Notice>
+ ),
+ ].filter(Boolean);
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <DetailHeader
- agent={agent}
- runtime={runtime}
- presence={presence}
- backHref={paths.agents()}
- canAssign={canAssign.allowed}
- canArchive={canEdit.allowed}
- dmPending={permissionsLoading}
- dmHref={`${paths.chat()}?agent=${agent.id}`}
- onDm={handleDm}
- onAssign={handleAssign}
- onArchive={
- agent.system_key ? undefined : () => setConfirmArchive(true)
+ <>
+ <ObjectPage
+ layoutId={AGENT_DETAIL_LAYOUT_ID}
+ segments={[listSegment]}
+ leaf={
+ <span className="flex min-w-0 items-center gap-1.5 text-foreground">
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size="xs"
+ profileLink={false}
+ />
+ <span className="truncate">{agent.name}</span>
+ </span>
}
- />
+ actions={actions}
+ panel={
+ <AgentPropertiesPanel
+ agent={agent}
+ runtime={runtime}
+ runtimes={runtimes}
+ presence={presence}
+ owner={owner}
+ members={members}
+ currentUserId={currentUserId}
+ canEdit={canEdit.allowed}
+ onUpdate={handleUpdate}
+ onEditAccess={() => openAdvanced("access")}
+ />
+ }
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="space-y-4">
+ <ObjectIdentity
+ media={<AgentMark agent={agent} presence={presence} />}
+ title={agent.name}
+ description={agent.description || undefined}
+ trailing={
+ isArchived ? (
+ <span className="inline-flex shrink-0 items-center rounded-md bg-muted px-1.5 py-0.5 text-caption text-muted-foreground">
+ {t(($) => $.row.archived)}
+ </span>
+ ) : null
+ }
+ />
+ {notices.length > 0 && <div className="space-y-2">{notices}</div>}
+ </div>
- {!canEdit.allowed && (
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "pt-3")}>
- <CapabilityBanner
- reason={canEdit.reason}
- resource="agent"
- ownerName={owner?.name}
+ <AgentWorkSections agent={agent} onViewAll={() => openWork(true)} />
+
+ <AgentInstructionsSection
+ agent={agent}
+ canEdit={canEdit.allowed}
+ onUpdate={handleUpdate}
/>
- </div>
- )}
- {isArchived && (
- <div className="shrink-0 border-b bg-muted/50 py-2 text-caption text-muted-foreground">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex items-center gap-2")}>
- <AlertCircle className="h-3.5 w-3.5 shrink-0" />
- <span className="flex-1">
- {t(($) => $.detail.archived_banner)}
- </span>
- {canEdit.allowed && (
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-caption"
- onClick={() => handleRestore(agent.id)}
- >
- {t(($) => $.detail.restore)}
- </Button>
- )}
- </div>
+ {/* Qoder agents take their skills from Qoder Cloud Agents. */}
+ {runtime?.provider === "qoder_cloud" ? null : (
+ <AgentSkillsSection
+ agent={agent}
+ canEdit={canEdit.allowed}
+ onManage={() => openAdvanced("skills")}
+ />
+ )}
</div>
- )}
+ </ObjectPage>
- {!isArchived && !runtimeBound && (
- <div className="shrink-0 border-b border-amber-500/30 bg-amber-500/10 py-2 text-caption text-amber-900 dark:text-amber-100">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex items-center gap-2")}>
- <Server className="h-3.5 w-3.5 shrink-0" />
- <span className="flex-1">
- {t(($) => $.detail.runtime_required_banner)}
- </span>
- {canEdit.allowed && (
- <Button
- variant="outline"
- size="sm"
- className="h-6 border-amber-500/40 bg-background/70 text-caption"
- onClick={() => setTabNavIntent("general")}
+ <AgentAdvancedSettings
+ agent={agent}
+ runtime={runtime}
+ runtimes={runtimes}
+ members={members}
+ onUpdate={handleUpdate}
+ currentUserId={currentUserId}
+ canEdit={canEdit.allowed}
+ section={advancedSection}
+ onSectionChange={openAdvanced}
+ />
+
+ <AgentWorkDialog agent={agent} open={workOpen} onOpenChange={openWork} />
+
+ {confirmCancelRuns && (
+ <AlertDialog
+ open
+ onOpenChange={(v) => {
+ if (!v) setConfirmCancelRuns(false);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.row_actions.cancel_dialog_title, { name: agent.name })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {describeCancelImpact(runningCount, queuedCount, t)}
+ {runningCount > 0 && t(($) => $.row_actions.cancel_dialog_running_note)}
+ {t(($) => $.row_actions.cancel_dialog_irreversible)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.row_actions.cancel_dialog_keep)}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setConfirmCancelRuns(false);
+ void handleCancelRuns(agent.id);
+ }}
>
- {t(($) => $.detail.bind_runtime)}
- </Button>
- )}
- </div>
- </div>
+ {t(($) => $.row_actions.cancel_dialog_confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
)}
- <div className="flex flex-1 min-h-0 flex-col overflow-hidden">
- <AgentOverviewPane
- agent={agent}
- runtime={runtime}
- owner={owner}
- runtimes={runtimes}
- members={members}
- onUpdate={handleUpdate}
- currentUserId={currentUser?.id ?? null}
- canEdit={canEdit.allowed}
- navIntent={tabNavIntent}
- onNavIntentHandled={() => setTabNavIntent(null)}
- />
- </div>
-
{confirmArchive && (
<Dialog
open
@@ -471,200 +774,89 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
</DialogContent>
</Dialog>
)}
- </div>
+ </>
);
}
-function DetailHeader({
+/** The 48px avatar with the agent's availability dot on its edge. */
+function AgentMark({
agent,
- runtime,
presence,
- backHref,
- canAssign,
- canArchive,
- dmPending,
- dmHref,
- onDm,
- onAssign,
- onArchive,
}: {
agent: Agent;
- runtime: AgentRuntime | null;
presence: AgentPresenceDetail | null;
- backHref: string;
- canAssign: boolean;
- canArchive: boolean;
- dmPending: boolean;
- dmHref: string;
- /** Runs before the link navigates; calls preventDefault when a gate denies
- * the chat, which is what stops AppLink from pushing. */
- onDm: (e: React.MouseEvent<HTMLAnchorElement>) => void;
- onAssign: () => void;
- /** Absent for Multica's built-in agents, which the server refuses to
- * archive — the menu hides the action rather than offering a failure. */
- onArchive?: () => void;
}) {
const { t } = useT("agents");
- const timeAgo = useTimeAgo();
- const isArchived = !!agent.archived_at;
- const hasMoreActions = !!onArchive;
-
return (
- <header
- className="shrink-0 border-b bg-background pb-5 pt-3"
- >
- <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
- <div className="flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
- <AppLink
- href={backHref}
- className="rounded-sm transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {t(($) => $.page.title)}
- </AppLink>
- <span aria-hidden="true">/</span>
- <span className="truncate text-foreground">{agent.name}</span>
- </div>
-
- <div className="mt-4 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
- <div className="flex min-w-0 items-start gap-4">
- <ActorAvatar
- actorType="agent"
- actorId={agent.id}
- size="2xl"
- profileLink={false}
- className="ring-1 ring-border"
- />
- <div className="min-w-0 pt-0.5">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
- <h1 className="min-w-0 text-balance text-title-lg font-semibold tracking-tight sm:text-display-sm">
- {agent.name}
- </h1>
- <AgentPresenceIndicator detail={presence} />
- </div>
- <ExpandableDescription>
- {agent.description ||
- t(($) => $.inspector.no_description_placeholder)}
- </ExpandableDescription>
- <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-caption text-muted-foreground">
- {runtime?.provider === "qoder_cloud" ? null : (
- <span className="inline-flex min-w-0 items-center gap-1.5">
- <Bot className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- <span className="truncate">{agent.model || t(($) => $.pickers.model_default)}</span>
- </span>
- )}
- <span className="inline-flex min-w-0 items-center gap-1.5">
- <Server className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- <span className="truncate">
- {runtime
- ? runtimeDisplayLabel(runtime)
- : t(($) => $.pickers.runtime_none)}
- </span>
- </span>
- <VisibilityBadge value={agent.visibility} />
- <span className="inline-flex items-center gap-1.5">
- <Clock3 className="h-3.5 w-3.5" aria-hidden="true" />
- {t(($) => $.detail.updated, { when: timeAgo(agent.updated_at) })}
- </span>
- </div>
- </div>
- </div>
-
- <div className="flex shrink-0 items-center gap-2 self-end lg:self-start">
- {!isArchived && (
- <Button
- variant="outline"
- size="sm"
- disabled={dmPending}
- // An anchor never matches `:disabled`, so the base variant's
- // `disabled:` rules never fire here — Base UI's data-disabled
- // is what carries the dimmed, inert look.
- className="data-disabled:pointer-events-none data-disabled:opacity-50"
- render={<AppLink href={dmHref} onClick={onDm} />}
- nativeButton={false}
- >
- <MessageSquare className="h-4 w-4" aria-hidden="true" />
- {t(($) => $.detail.dm)}
- </Button>
- )}
- {!isArchived && canAssign && (
- <Button type="button" size="sm" onClick={onAssign}>
- <Plus className="h-4 w-4" aria-hidden="true" />
- {t(($) => $.detail.assign_work)}
- </Button>
- )}
- {!isArchived && canArchive && hasMoreActions ? (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <IconButton
- variant="ghost"
- size="icon-sm"
- label={t(($) => $.detail.more_actions_aria)}
- tooltipSide="bottom"
- />
- }
- >
- <MoreHorizontal
- className="h-4 w-4 text-muted-foreground"
- aria-hidden="true"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-auto">
- {onArchive && (
- <DropdownMenuItem variant="destructive" onClick={onArchive}>
- <Trash2 className="h-3.5 w-3.5" aria-hidden="true" />
- {t(($) => $.detail.more_archive)}
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- ) : null}
- </div>
- </div>
- </div>
- </header>
+ <span className="relative inline-flex [--avatar-slot-size:3rem]">
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size="2xl"
+ profileLink={false}
+ className="ring-1 ring-border"
+ />
+ {presence ? (
+ <span
+ role="img"
+ aria-label={t(($) => $.presence_status_aria, {
+ status: t(($) => $.availability[presence.availability]),
+ })}
+ className={cn(
+ "absolute -right-0.5 -bottom-0.5 size-3 rounded-full ring-2 ring-background",
+ availabilityConfig[presence.availability].dotClass,
+ )}
+ />
+ ) : null}
+ </span>
);
}
-function BackHeader({ paths, title }: { paths: string; title: string }) {
+function Notice({
+ tone = "neutral",
+ icon,
+ action,
+ children,
+}: {
+ tone?: "neutral" | "warning";
+ icon: React.ReactNode;
+ action?: React.ReactNode;
+ children: React.ReactNode;
+}) {
return (
- <PageHeader>
- <AppLink
- href={paths}
- className="inline-flex h-7 items-center gap-1 rounded-md px-2 text-caption text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
- >
- <ArrowLeft className="h-3.5 w-3.5" />
- {title}
- </AppLink>
- </PageHeader>
+ <div
+ role="status"
+ className={cn(
+ "flex items-center gap-2 rounded-lg border px-3 py-2 text-caption",
+ tone === "warning"
+ ? "border-warning/30 bg-warning/10 text-foreground"
+ : "bg-muted/40 text-muted-foreground",
+ )}
+ >
+ {icon}
+ <span className="min-w-0 flex-1">{children}</span>
+ {action}
+ </div>
);
}
function DetailLoadingSkeleton() {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <div className="shrink-0 border-b pb-5 pt-3">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
- <Skeleton className="h-4 w-48" />
- <div className="mt-4 flex items-start gap-4">
- <Skeleton className="h-14 w-14 rounded-full" />
- <div className="flex-1 space-y-3">
- <Skeleton className="h-7 w-64" />
- <Skeleton className="h-4 w-full max-w-xl" />
- <Skeleton className="h-4 w-full max-w-lg" />
- </div>
- </div>
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-full" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-5 w-48" />
+ <Skeleton className="h-4 w-3/4" />
</div>
</div>
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex flex-1 flex-col py-6")}>
- <Skeleton className="h-9 w-96" />
- <div className="mt-6 grid flex-1 gap-6 xl:grid-cols-[minmax(0,1fr)_320px]">
- <div className="space-y-5">
- <Skeleton className="h-48 w-full" />
- <Skeleton className="h-64 w-full" />
- </div>
- <Skeleton className="h-96 w-full" />
- </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-14 w-full rounded-lg" />
+ </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-32 w-full rounded-lg" />
</div>
</div>
);
diff --git a/packages/views/agents/components/agent-instructions-section.tsx b/packages/views/agents/components/agent-instructions-section.tsx
new file mode 100644
index 0000000000..efc87f7303
--- /dev/null
+++ b/packages/views/agents/components/agent-instructions-section.tsx
@@ -0,0 +1,164 @@
+"use client";
+
+import { useLayoutEffect, useRef, useState } from "react";
+import { Pencil, X } from "@multica/ui/icons";
+import type { Agent } from "@multica/core/types";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { ReadonlyContent } from "../../editor/readonly-content";
+import {
+ ObjectSection,
+ ObjectSectionAction,
+} from "../../layout/object-page";
+import { useT } from "../../i18n";
+import { InstructionsTab } from "./tabs/instructions-tab";
+
+/**
+ * The agent's instructions: the prompt as it reads, clamped to a few lines,
+ * and the full editor in place of it while editing.
+ */
+export function AgentInstructionsSection({
+ agent,
+ canEdit,
+ onUpdate,
+}: {
+ agent: Agent;
+ canEdit: boolean;
+ onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+}) {
+ const { t } = useT("agents");
+ const [editing, setEditing] = useState(false);
+ const [dirty, setDirty] = useState(false);
+ const [confirmDiscard, setConfirmDiscard] = useState(false);
+
+ const stopEditing = () => {
+ setEditing(false);
+ setDirty(false);
+ };
+
+ return (
+ <ObjectSection
+ title={t(($) => $.tabs.instructions)}
+ action={
+ !canEdit ? null : editing ? (
+ <ObjectSectionAction
+ icon={X}
+ onClick={() => (dirty ? setConfirmDiscard(true) : stopEditing())}
+ >
+ {t(($) => $.inspector.cancel)}
+ </ObjectSectionAction>
+ ) : (
+ <ObjectSectionAction icon={Pencil} onClick={() => setEditing(true)}>
+ {t(($) => $.sections.edit)}
+ </ObjectSectionAction>
+ )
+ }
+ >
+ {editing ? (
+ <InstructionsTab
+ agent={agent}
+ onSave={async (updates) => {
+ await onUpdate(agent.id, updates);
+ stopEditing();
+ }}
+ onDirtyChange={setDirty}
+ />
+ ) : (
+ <InstructionsPreview content={agent.instructions ?? ""} />
+ )}
+
+ {confirmDiscard && (
+ <AlertDialog
+ open
+ onOpenChange={(open) => {
+ if (!open) setConfirmDiscard(false);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.tabs.discard_dialog_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.tabs.discard_dialog_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.tabs.discard_keep)}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ setConfirmDiscard(false);
+ stopEditing();
+ }}
+ >
+ {t(($) => $.tabs.discard_confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+ </ObjectSection>
+ );
+}
+
+function InstructionsPreview({ content }: { content: string }) {
+ const { t } = useT("agents");
+ const { t: tc } = useT("common");
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const [expanded, setExpanded] = useState(false);
+ const [overflows, setOverflows] = useState(false);
+
+ // Measured rather than assumed: only a prompt taller than the clamp gets
+ // the toggle. Re-measured on resize, because a narrower column wraps more.
+ useLayoutEffect(() => {
+ const el = bodyRef.current;
+ if (!el || expanded) return;
+ const measure = () => setOverflows(el.scrollHeight > el.clientHeight + 1);
+ measure();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [content, expanded]);
+
+ if (!content.trim()) {
+ return (
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.sections.instructions_empty)}
+ </p>
+ );
+ }
+
+ return (
+ <div className="rounded-lg border bg-card px-4 py-3">
+ <div
+ ref={bodyRef}
+ className={cn("text-body", !expanded && "max-h-24 overflow-hidden")}
+ >
+ <ReadonlyContent content={content} />
+ </div>
+ {overflows || expanded ? (
+ <button
+ type="button"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((value) => !value)}
+ className="mt-1 rounded-sm text-caption font-medium text-brand hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {expanded
+ ? tc(($) => $.expandable_description.collapse)
+ : tc(($) => $.expandable_description.expand)}
+ </button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/agent-list-toolbar.tsx b/packages/views/agents/components/agent-list-toolbar.tsx
index 8ebb703f63..e81e9bddec 100644
--- a/packages/views/agents/components/agent-list-toolbar.tsx
+++ b/packages/views/agents/components/agent-list-toolbar.tsx
@@ -1,13 +1,5 @@
"use client";
-import {
- ArrowDown,
- ArrowUp,
- ChevronDown,
- Filter,
- Search,
- X,
-} from "@multica/ui/icons";
import {
ALL_ACCESS_SCOPES,
effectiveAccessScope,
@@ -16,64 +8,22 @@ import {
import type { MemberWithUser } from "@multica/core/types";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import {
- AGENT_SCOPES,
- type AgentColumnKey,
- type AgentListFilters,
- type AgentsScope,
- type AgentSortDirection,
- type AgentSortField,
-} from "@multica/core/agents/stores";
-import { Button } from "@multica/ui/components/ui/button";
-import { IconButton } from "@multica/ui/components/common/icon-button";
-import { Input } from "@multica/ui/components/ui/input";
+import type { AgentListFilters } from "@multica/core/agents/stores";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
-import { Switch } from "@multica/ui/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
+import { CollectionFilterButton } from "../../layout/collection-page";
import { availabilityConfig } from "../presence";
import { useT } from "../../i18n";
import type { AgentListRow } from "./agents-page";
-import { PAGE_GUTTER } from "../../layout/page-header";
-import { cn } from "@multica/ui/lib/utils";
-
-const COLUMN_KEYS: AgentColumnKey[] = [
- "status",
- "owner",
- "access",
- "runtime",
- "lastActive",
- "runs",
- "model",
- "created",
-];
-
-const SORT_FIELDS: AgentSortField[] = [
- "lastActive",
- "name",
- "runs",
- "created",
-];
const AVAILABILITY_VALUES: AgentAvailability[] = [
"online",
@@ -95,53 +45,33 @@ export function countActiveFilterDimensions(
const ACCESS_SCOPES = ALL_ACCESS_SCOPES;
-export function AgentListToolbar({
- scope,
- onScopeChange,
- scopeCounts,
- search,
- onSearchChange,
+function CountBadge({ value }: { value: number }) {
+ return (
+ <span className="ml-auto pl-3 text-caption text-muted-foreground">{value}</span>
+ );
+}
+
+function SubTriggerCount({ value }: { value: number }) {
+ if (value === 0) return null;
+ return <span className="text-caption font-medium text-primary">{value}</span>;
+}
+
+/** The header's filter icon and the per-dimension filter menu it opens. */
+export function AgentListFilterMenu({
filters,
onToggleFilter,
- onClearFilters,
- sortField,
- sortDirection,
- onSortFieldChange,
- onSortDirectionChange,
- hiddenColumns,
- onToggleColumn,
allRows,
members,
- visibleCount,
}: {
- scope: AgentsScope;
- onScopeChange: (scope: AgentsScope) => void;
- /** Per-scope totals from the FULL set — scope counts ignore filters. */
- scopeCounts: Record<AgentsScope, number>;
- search: string;
- onSearchChange: (value: string) => void;
filters: AgentListFilters;
onToggleFilter: (key: keyof AgentListFilters, value: string) => void;
- onClearFilters: () => void;
- sortField: AgentSortField;
- sortDirection: AgentSortDirection;
- onSortFieldChange: (field: AgentSortField) => void;
- onSortDirectionChange: (direction: AgentSortDirection) => void;
- hiddenColumns: AgentColumnKey[];
- onToggleColumn: (key: AgentColumnKey) => void;
/** Rows within the current scope, unfiltered — filter option lists and
* counts derive from this set. */
allRows: AgentListRow[];
members: MemberWithUser[];
- /** Rows surviving the filters — shown as "n / total" when narrowed. */
- visibleCount: number;
}) {
const { t } = useT("agents");
- const activeCount = countActiveFilterDimensions(filters);
- const hasActiveFilters = activeCount > 0;
- const hasSearch = search.trim().length > 0;
-
// Option lists with counts, derived from the scope's unfiltered rows so
// toggling one dimension doesn't make the others' options vanish.
const availabilityCounts = new Map<string, number>();
@@ -175,450 +105,162 @@ export function AgentListToolbar({
if (model) modelCounts.set(model, (modelCounts.get(model) ?? 0) + 1);
}
- const SCOPE_LABELS: Record<AgentsScope, string> = {
- mine: t(($) => $.scope.mine),
- all: t(($) => $.scope.all),
- archived: t(($) => $.scope.archived),
- };
-
- const SORT_LABELS: Record<AgentSortField, string> = {
- lastActive: t(($) => $.columns.last_active),
- name: t(($) => $.columns.agent),
- runs: t(($) => $.columns.runs),
- created: t(($) => $.columns.created),
- };
-
- const COLUMN_LABELS: Record<AgentColumnKey, string> = {
- status: t(($) => $.columns.status),
- owner: t(($) => $.columns.owner),
- access: t(($) => $.columns.access),
- runtime: t(($) => $.columns.runtime),
- lastActive: t(($) => $.columns.last_active),
- runs: t(($) => $.columns.runs),
- model: t(($) => $.columns.model),
- created: t(($) => $.columns.created),
- };
- const sortLabel = SORT_LABELS[sortField];
-
- const countBadge = (n: number) => (
- <span className="ml-auto pl-3 text-caption text-muted-foreground">{n}</span>
- );
-
return (
- <div className={cn("h-12 shrink-0 overflow-x-auto [-webkit-overflow-scrolling:touch]", PAGE_GUTTER)}>
- <div className="flex h-full w-max min-w-full items-center justify-between gap-2">
- {/* Left: local search + scope buttons + result count. Scope mixes the
- ownership lens (mine/all) with the archived lifecycle stage. Button
- styling and the <md dropdown collapse follow the issues header's
- scope buttons. */}
- <div className="flex min-w-0 items-center gap-2">
- <div className="relative hidden shrink-0 md:block">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- value={search}
- onChange={(e) => onSearchChange(e.target.value)}
- aria-label={t(($) => $.page.search_placeholder)}
- placeholder={t(($) => $.page.search_placeholder)}
- className="h-8 w-56 pl-8 text-body"
- />
- </div>
-
- <div className="hidden shrink-0 items-center gap-1 md:flex">
- {AGENT_SCOPES.map((s) => (
- <Button
- key={s}
- variant="outline"
- size="sm"
- className={
- scope === s
- ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"
- : "gap-1.5 text-muted-foreground"
- }
- onClick={() => onScopeChange(s)}
- >
- {SCOPE_LABELS[s]}
- <span className="tabular-nums text-caption text-muted-foreground">
- {scopeCounts[s]}
- </span>
- </Button>
- ))}
- </div>
-
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 gap-1 text-muted-foreground md:hidden"
- >
- <span className="truncate">{SCOPE_LABELS[scope]}</span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={scope}
- onValueChange={(value) => onScopeChange(value as AgentsScope)}
- >
- {AGENT_SCOPES.map((s) => (
- <DropdownMenuRadioItem key={s} value={s}>
- {SCOPE_LABELS[s]}
- <span className="ml-2 tabular-nums text-caption text-muted-foreground">
- {scopeCounts[s]}
- </span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {(hasActiveFilters || hasSearch) && (
- <span
- title={t(($) => $.toolbar.result_count_title)}
- className="hidden shrink-0 text-caption tabular-nums text-muted-foreground md:inline"
- >
- {visibleCount} / {allRows.length}
- </span>
- )}
- </div>
-
- <div className="flex shrink-0 items-center gap-1">
- {/* Filter */}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant={hasActiveFilters ? "default" : "outline"}
- size="sm"
- className={
- hasActiveFilters
- ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"
- : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- }
- >
- <Filter className="size-3.5" />
- {hasActiveFilters ? (
- <>
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_active_count, {
- count: activeCount,
- })}
- </span>
- <span className="tabular-nums md:hidden">
- {activeCount}
- </span>
- </>
- ) : (
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_label)}
- </span>
- )}
- {hasActiveFilters && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <CollectionFilterButton count={countActiveFilterDimensions(filters)} />
+ }
+ />
+ <DropdownMenuContent align="start" className="w-auto">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_availability)}
+ </span>
+ <SubTriggerCount value={filters.availability.length} />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {AVAILABILITY_VALUES.map((value) => {
+ const visual = availabilityConfig[value];
+ return (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={filters.availability.includes(value)}
+ onCheckedChange={() => onToggleFilter("availability", value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.availability.includes(value)} />
<span
- role="button"
- tabIndex={-1}
- aria-label={t(($) => $.toolbar.clear_filters)}
- className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onClearFilters();
- }}
- onPointerDown={(e) => e.stopPropagation()}
- >
- <X className="size-3" />
- </span>
- )}
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-auto">
- {/* Availability */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_availability)}
- </span>
- {filters.availability.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.availability.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {AVAILABILITY_VALUES.map((value) => {
- const visual = availabilityConfig[value];
- return (
- <DropdownMenuCheckboxItem
- key={value}
- checked={filters.availability.includes(value)}
- onCheckedChange={() =>
- onToggleFilter("availability", value)
- }
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck
- checked={filters.availability.includes(value)}
- />
- <span
- className={`size-1.5 shrink-0 rounded-full ${visual.dotClass}`}
- />
- {t(($) => $.availability[value])}
- {countBadge(availabilityCounts.get(value) ?? 0)}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ className={`size-1.5 shrink-0 rounded-full ${visual.dotClass}`}
+ />
+ {t(($) => $.availability[value])}
+ <CountBadge value={availabilityCounts.get(value) ?? 0} />
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
- {/* Access — effective access scope (workspace / specific-people / owner-only).
- Mirrors Availability's keyboard/ARIA pattern. */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_access)}
+ {/* Access — effective access scope (workspace / specific-people / owner-only).
+ Mirrors Availability's keyboard/ARIA pattern. */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_access)}
+ </span>
+ <SubTriggerCount value={filters.access.length} />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {ACCESS_SCOPES.map((value) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={filters.access.includes(value)}
+ onCheckedChange={() => onToggleFilter("access", value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.access.includes(value)} />
+ <span className="min-w-0 truncate">
+ {t(($) =>
+ value === "workspace"
+ ? $.access.scope_labels.workspace
+ : value === "specific-people"
+ ? $.access.scope_labels.specific_people
+ : $.access.scope_labels.owner_only,
+ )}
</span>
- {filters.access.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.access.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {ACCESS_SCOPES.map((value) => (
- <DropdownMenuCheckboxItem
- key={value}
- checked={filters.access.includes(value)}
- onCheckedChange={() => onToggleFilter("access", value)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.access.includes(value)} />
- <span className="min-w-0 truncate">
- {t(($) =>
- value === "workspace"
- ? $.access.scope_labels.workspace
- : value === "specific-people"
- ? $.access.scope_labels.specific_people
- : $.access.scope_labels.owner_only,
- )}
- </span>
- {countBadge(accessCounts.get(value) ?? 0)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ <CountBadge value={accessCounts.get(value) ?? 0} />
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
- {/* Runtime */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_runtime)}
- </span>
- {filters.runtimes.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.runtimes.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...runtimeOptions.entries()].map(([id, { name, count }]) => (
- <DropdownMenuCheckboxItem
- key={id}
- checked={filters.runtimes.includes(id)}
- onCheckedChange={() => onToggleFilter("runtimes", id)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.runtimes.includes(id)} />
- <span className="min-w-0 truncate">{name}</span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Owner — the same person-axis as the Mine scope. Picking an
- owner here leaves the clean "mine" view for "all" (store
- rule), so Mine + owner never coexist. */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_owner)}
- </span>
- {filters.owners.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.owners.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...ownerCounts.entries()].map(([userId, count]) => {
- const m = memberById.get(userId);
- return (
- <DropdownMenuCheckboxItem
- key={userId}
- checked={filters.owners.includes(userId)}
- onCheckedChange={() => onToggleFilter("owners", userId)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.owners.includes(userId)} />
- <ActorAvatar
- name={m?.name ?? userId.slice(0, 8)}
- initials={(m?.name ?? "?").slice(0, 2).toUpperCase()}
- avatarUrl={resolvePublicFileUrl(m?.avatar_url ?? null)}
- size="sm"
- />
- <span className="min-w-0 truncate">
- {m?.name ?? userId.slice(0, 8)}
- </span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_runtime)}
+ </span>
+ <SubTriggerCount value={filters.runtimes.length} />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...runtimeOptions.entries()].map(([id, { name, count }]) => (
+ <DropdownMenuCheckboxItem
+ key={id}
+ checked={filters.runtimes.includes(id)}
+ onCheckedChange={() => onToggleFilter("runtimes", id)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.runtimes.includes(id)} />
+ <span className="min-w-0 truncate">{name}</span>
+ <CountBadge value={count} />
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
- {/* Model — runtime-native model id (categorical column → filter) */}
- {modelCounts.size > 0 && (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_model)}
+ {/* Owner — the same person-axis as the Mine scope. Picking an
+ owner here leaves the clean "mine" view for "all" (store
+ rule), so Mine + owner never coexist. */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_owner)}
+ </span>
+ <SubTriggerCount value={filters.owners.length} />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...ownerCounts.entries()].map(([userId, count]) => {
+ const m = memberById.get(userId);
+ return (
+ <DropdownMenuCheckboxItem
+ key={userId}
+ checked={filters.owners.includes(userId)}
+ onCheckedChange={() => onToggleFilter("owners", userId)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.owners.includes(userId)} />
+ <ActorAvatar
+ name={m?.name ?? userId.slice(0, 8)}
+ initials={(m?.name ?? "?").slice(0, 2).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(m?.avatar_url ?? null)}
+ size="sm"
+ />
+ <span className="min-w-0 truncate">
+ {m?.name ?? userId.slice(0, 8)}
</span>
- {filters.models.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.models.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-44 overflow-y-auto">
- {[...modelCounts.entries()].map(([model, count]) => (
- <DropdownMenuCheckboxItem
- key={model}
- checked={filters.models.includes(model)}
- onCheckedChange={() => onToggleFilter("models", model)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.models.includes(model)} />
- <span className="min-w-0 truncate">{model}</span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ <CountBadge value={count} />
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
- {/* Display settings */}
- <Popover>
- <Tooltip>
- <PopoverTrigger
- render={
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- >
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- <span className="hidden md:inline">{sortLabel}</span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">
- {t(($) => $.toolbar.display)}
- </TooltipContent>
- </Tooltip>
- <PopoverContent align="end" className="w-64 p-0">
- <div className="border-b px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.sort_by)}
+ {/* Model — runtime-native model id (categorical column → filter) */}
+ {modelCounts.size > 0 && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_model)}
</span>
- <div className="mt-2 flex items-center gap-1.5">
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="flex-1 justify-between text-caption"
- >
- {sortLabel}
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={sortField}
- onValueChange={(v) =>
- onSortFieldChange(v as AgentSortField)
- }
- >
- {SORT_FIELDS.map((field) => (
- <DropdownMenuRadioItem key={field} value={field}>
- {SORT_LABELS[field]}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <IconButton
- variant="outline"
- size="icon-sm"
- onClick={() =>
- onSortDirectionChange(
- sortDirection === "asc" ? "desc" : "asc",
- )
- }
- label={
- sortDirection === "asc"
- ? t(($) => $.toolbar.direction_asc)
- : t(($) => $.toolbar.direction_desc)
- }
+ <SubTriggerCount value={filters.models.length} />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-44 overflow-y-auto">
+ {[...modelCounts.entries()].map(([model, count]) => (
+ <DropdownMenuCheckboxItem
+ key={model}
+ checked={filters.models.includes(model)}
+ onCheckedChange={() => onToggleFilter("models", model)}
+ className={FILTER_ITEM_CLASS}
>
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- </IconButton>
- </div>
- </div>
-
- <div className="px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.section_columns)}
- </span>
- <div className="mt-2 space-y-2">
- {COLUMN_KEYS.map((key) => (
- <label
- key={key}
- className="flex cursor-pointer items-center justify-between"
- >
- <span className="text-body">{COLUMN_LABELS[key]}</span>
- <Switch
- size="sm"
- checked={!hiddenColumns.includes(key)}
- onCheckedChange={() => onToggleColumn(key)}
- />
- </label>
- ))}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- </div>
- </div>
- </div>
+ <HoverCheck checked={filters.models.includes(model)} />
+ <span className="min-w-0 truncate">{model}</span>
+ <CountBadge value={count} />
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
);
}
diff --git a/packages/views/agents/components/agent-overview-pane.test.tsx b/packages/views/agents/components/agent-overview-pane.test.tsx
deleted file mode 100644
index 1f304f27f2..0000000000
--- a/packages/views/agents/components/agent-overview-pane.test.tsx
+++ /dev/null
@@ -1,376 +0,0 @@
-// @vitest-environment jsdom
-
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { fireEvent, render, screen } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { Agent, AgentRuntime } from "@multica/core/types";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enAgents from "../../locales/en/agents.json";
-import {
- NavigationProvider,
- type NavigationAdapter,
-} from "../../navigation";
-
-const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
-
-const RAIL_SENTINEL = "rail-sentinel";
-const GUTTER_SENTINEL = "gutter-sentinel";
-vi.mock("../../layout/page-header", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../../layout/page-header")>()),
- PAGE_RAIL: "rail-sentinel",
- PAGE_GUTTER: "gutter-sentinel",
-}));
-
-// AgentOverviewPane pulls in ActorIssuesPanel which in turn touches the api
-// layer. The test only cares about which top-of-pane tab buttons render,
-// not what each tab does, so we stub the heavy children.
-vi.mock("./tabs/activity-tab", () => ({
- ActivityTab: () => <div>activity-tab</div>,
- AgentPerformanceSummary: () => <div>performance-summary</div>,
-}));
-vi.mock("./agent-overview-summary", () => ({
- AgentOverviewSummary: () => <div>agent-overview-summary</div>,
-}));
-vi.mock("./agent-access-settings", () => ({
- AgentAccessSettings: () => <div>agent-access-settings</div>,
-}));
-vi.mock("./tabs/instructions-tab", () => ({
- InstructionsTab: () => <div>instructions-tab</div>,
-}));
-vi.mock("./tabs/skills-tab", () => ({
- SkillsTab: () => <div>skills-tab</div>,
-}));
-vi.mock("./tabs/env-tab", () => ({
- EnvTab: () => <div>env-tab</div>,
-}));
-vi.mock("./tabs/custom-args-tab", () => ({
- CustomArgsTab: () => <div>custom-args-tab</div>,
-}));
-vi.mock("./tabs/mcp-config-tab", () => ({
- McpConfigTab: () => <div>mcp-config-tab</div>,
-}));
-vi.mock("./tabs/integrations-tab", () => ({
- IntegrationsTab: () => <div>integrations-tab</div>,
-}));
-vi.mock("../../common/actor-issues-panel", () => ({
- ActorIssuesPanel: () => <div>actor-issues-panel</div>,
-}));
-
-// The pane now reads workspace context to decide whether the Integrations
-// tab is worth showing (it queries Lark installations to learn whether the
-// deployment has the feature configured). Provide a stable workspace id and
-// a listing query backed by a ref so each test can flip `configured`.
-const larkListingRef = vi.hoisted(() => ({
- current: { installations: [] as unknown[], configured: false },
-}));
-const slackListingRef = vi.hoisted(() => ({
- current: { installations: [] as unknown[], configured: false },
-}));
-const telegramListingRef = vi.hoisted(() => ({
- current: { installations: [] as unknown[], configured: false },
-}));
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "ws-1",
-}));
-vi.mock("@multica/core/lark", () => ({
- larkInstallationsOptions: () => ({
- queryKey: ["lark", "installations"],
- queryFn: () => Promise.resolve(larkListingRef.current),
- }),
-}));
-vi.mock("@multica/core/slack", () => ({
- slackInstallationsOptions: () => ({
- queryKey: ["slack", "installations"],
- queryFn: () => Promise.resolve(slackListingRef.current),
- }),
-}));
-vi.mock("@multica/core/telegram", () => ({
- telegramInstallationsOptions: () => ({
- queryKey: ["telegram", "installations"],
- queryFn: () => Promise.resolve(telegramListingRef.current),
- }),
-}));
-
-import { AgentOverviewPane } from "./agent-overview-pane";
-
-const baseAgent: Agent = {
- id: "agent-1",
- workspace_id: "ws-1",
- runtime_id: "runtime-1",
- name: "Agent",
- description: "",
- instructions: "",
- avatar_url: null,
- runtime_mode: "local",
- runtime_config: {},
- custom_args: [],
- visibility: "workspace",
- permission_mode: "public_to",
- invocation_targets: [{ target_type: "workspace", target_id: null }],
- status: "idle",
- max_concurrent_tasks: 1,
- model: "",
- owner_id: "user-1",
- skills: [],
- created_at: "2026-05-28T00:00:00Z",
- updated_at: "2026-05-28T00:00:00Z",
- archived_at: null,
- archived_by: null,
-};
-
-function makeRuntime(provider: string): AgentRuntime {
- return {
- id: "runtime-1",
- workspace_id: "ws-1",
- daemon_id: null,
- name: "Runtime",
- runtime_mode: "local",
- provider,
- launch_header: "",
- status: "online",
- device_info: "",
- metadata: {},
- owner_id: null,
- visibility: "private",
- last_seen_at: null,
- created_at: "2026-05-28T00:00:00Z",
- updated_at: "2026-05-28T00:00:00Z",
- };
-}
-
-function renderPane(
- runtimes: AgentRuntime[],
- { canEdit = true }: { canEdit?: boolean } = {},
-) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
- const navigation: NavigationAdapter = {
- push: vi.fn(),
- replace: vi.fn(),
- back: vi.fn(),
- pathname: "/acme/agents/agent-1",
- searchParams: new URLSearchParams(),
- hash: "",
- getShareableUrl: (path) => path,
- };
- return render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <NavigationProvider value={navigation}>
- <QueryClientProvider client={queryClient}>
- <AgentOverviewPane
- agent={baseAgent}
- runtime={runtimes[0] ?? null}
- owner={null}
- runtimes={runtimes}
- members={[]}
- onUpdate={vi.fn().mockResolvedValue(undefined)}
- canEdit={canEdit}
- />
- </QueryClientProvider>
- </NavigationProvider>
- </I18nProvider>,
- );
-}
-
-function openCapabilities() {
- fireEvent.click(screen.getByRole("tab", { name: /^Capabilities$/i }));
-}
-
-function openSettings() {
- fireEvent.click(screen.getByRole("tab", { name: /^Settings$/i }));
-}
-
-beforeEach(() => {
- larkListingRef.current = { installations: [], configured: false };
- slackListingRef.current = { installations: [], configured: false };
- telegramListingRef.current = { installations: [], configured: false };
-});
-
-describe("AgentOverviewPane MCP tab visibility", () => {
- it.each([
- ["Claude", "claude"],
- ["Codex", "codex"],
- ["Cursor", "cursor"],
- ["Hermes", "hermes"],
- ["Kimi", "kimi"],
- ["Kiro", "kiro"],
- ["OpenCode", "opencode"],
- ["OpenClaw", "openclaw"],
- ["Oh My Pi", "omp"],
- ])("renders the MCP tab when the agent runs on the %s runtime", (_label, provider) => {
- renderPane([makeRuntime(provider)]);
- openCapabilities();
- expect(screen.getByRole("tab", { name: /^MCP$/i })).toBeInTheDocument();
- });
-
- it("hides the MCP tab for providers whose backend does not read mcp_config", () => {
- // Saving an MCP config on e.g. Gemini would be a silent no-op at run
- // time — that's the bug this hiding logic is meant to prevent.
- renderPane([makeRuntime("gemini")]);
- openCapabilities();
- expect(
- screen.queryByRole("tab", { name: /^MCP$/i }),
- ).not.toBeInTheDocument();
- });
-
- it("keeps the MCP tab visible when the runtime row hasn't loaded yet", () => {
- // Empty runtimes[] mimics the brief window between the page mounting and
- // the runtimes query resolving. Hiding the tab would flicker it off and
- // then back on, which reads as a bug.
- renderPane([]);
- openCapabilities();
- expect(screen.getByRole("tab", { name: /^MCP$/i })).toBeInTheDocument();
- });
-});
-
-describe("AgentOverviewPane Integrations tab visibility", () => {
- it("shows the Integrations tab once the deployment has Lark configured", async () => {
- larkListingRef.current = { installations: [], configured: true };
- renderPane([makeRuntime("claude")]);
- openCapabilities();
- expect(
- await screen.findByRole("tab", { name: /^Integrations$/i }),
- ).toBeInTheDocument();
- });
-
- it("shows the Integrations tab when only Slack is configured (Lark off)", async () => {
- // Regression: the tab gate must consider Slack too, not just Lark —
- // a Slack-only deployment was hiding the tab (and its bind entry).
- slackListingRef.current = { installations: [], configured: true };
- renderPane([makeRuntime("claude")]);
- openCapabilities();
- expect(
- await screen.findByRole("tab", { name: /^Integrations$/i }),
- ).toBeInTheDocument();
- });
-
- it("shows the Integrations tab when only Telegram is configured", async () => {
- telegramListingRef.current = { installations: [], configured: true };
- renderPane([makeRuntime("claude")]);
- openCapabilities();
- expect(
- await screen.findByRole("tab", { name: /^Integrations$/i }),
- ).toBeInTheDocument();
- });
-
- it("hides the Integrations tab when no channel integration is configured", () => {
- // Default refs are configured:false; the tab must not appear on a
- // deployment without any channel integration, the common case.
- renderPane([makeRuntime("claude")]);
- openCapabilities();
- expect(
- screen.queryByRole("tab", { name: /^Integrations$/i }),
- ).not.toBeInTheDocument();
- });
-});
-
-describe("AgentOverviewPane Environment tab visibility", () => {
- it("shows the Environment tab to someone who can manage the agent", () => {
- renderPane([makeRuntime("claude")]);
- openSettings();
- expect(
- screen.getByRole("tab", { name: /^Environment$/i }),
- ).toBeInTheDocument();
- });
-
- it("hides the Environment tab from users who cannot manage the agent", () => {
- // The env endpoints admit the agent owner or a workspace owner/admin
- // (MUL-5438) — the rule `canEdit` already encodes. Anyone else who opens
- // the tab hits a guaranteed 403 on "Reveal & edit".
- renderPane([makeRuntime("claude")], { canEdit: false });
- openSettings();
- expect(
- screen.queryByRole("tab", { name: /^Environment$/i }),
- ).not.toBeInTheDocument();
- });
-});
-
-describe("AgentOverviewPane on a Qoder Cloud Agents runtime", () => {
- const tabNames = () =>
- screen
- .getAllByRole("tab")
- .filter((tab) => tab.closest("aside"))
- .map((tab) => tab.textContent);
-
- it("offers only Instructions under Capabilities", () => {
- larkListingRef.current = { installations: [], configured: true };
- renderPane([makeRuntime("qoder_cloud")]);
- openCapabilities();
- expect(tabNames()).toEqual(["Instructions"]);
- });
-
- it("drops Environment and Custom Args and names the Qoder Cloud Agents tab", () => {
- renderPane([makeRuntime("qoder_cloud")]);
- openSettings();
- expect(tabNames()).toEqual(["General", "Access", "Qoder Cloud Agents"]);
- });
-
- it("keeps Routing off for other runtimes", () => {
- renderPane([makeRuntime("claude")]);
- openSettings();
- expect(tabNames()).toEqual([
- "General",
- "Access",
- "Environment",
- "Custom Args",
- ]);
- });
-});
-
-// MUL-7107: the header, the tab bar and every panel share one leading edge.
-// The regression these guard against is a centred width cap: `mx-auto` plus a
-// `max-w-*` moves an element's edge as the viewport grows, so chrome on a
-// centred rail and a panel on the page gutter agreed at 1440px and drifted
-// hundreds of pixels apart above it. A cap must be anchored, never centred.
-describe("AgentOverviewPane horizontal alignment", () => {
- // Every band on the page has to read the SAME rail: chrome on the rail with
- // panels off it is the original bug, and panels on it with chrome off it is
- // the mirror image. Both were shipped once (MUL-7107).
- //
- // The constants are overridden with sentinels rather than compared against
- // their real values, which are ordinary Tailwind classes a hand-written
- // element could match by accident. Only an element that reads the constant
- // picks a sentinel up.
- const panelFor = (container: HTMLElement) =>
- container.querySelector('[role="tablist"]')?.nextElementSibling
- ?.firstElementChild;
-
- it("puts the tab bar row on the rail", () => {
- const { container } = renderPane([makeRuntime("claude")]);
- const row = container.querySelector('[role="tablist"] > div');
-
- expect(row).toHaveClass(RAIL_SENTINEL);
- expect(row).toHaveClass(GUTTER_SENTINEL);
- });
-
- it("puts the Overview panel on the same rail", () => {
- const { container } = renderPane([makeRuntime("claude")]);
-
- expect(panelFor(container as HTMLElement)).toHaveClass(RAIL_SENTINEL);
- expect(panelFor(container as HTMLElement)).toHaveClass(GUTTER_SENTINEL);
- });
-
- it("puts the Work panel on the same rail", () => {
- const { container } = renderPane([makeRuntime("claude")]);
- fireEvent.click(screen.getByRole("tab", { name: /^Work$/i }));
-
- // Work takes a bare rail: the issues toolbar inside it carries the gutter
- // already, so adding one here would inset it past the tabs.
- expect(panelFor(container as HTMLElement)).toHaveClass(RAIL_SENTINEL);
- });
-
- it.each([
- ["Capabilities", openCapabilities],
- ["Settings", openSettings],
- ])("puts the %s nav-and-content row on the same rail", (_name, open) => {
- const { container } = renderPane([makeRuntime("claude")]);
- open();
-
- // Bare rail for the same reason as Work — the nav aside carries the gutter,
- // and that aside, not the form behind it, is what meets the tabs above.
- expect(panelFor(container as HTMLElement)).toHaveClass(RAIL_SENTINEL);
- expect(container.querySelector("aside")).toHaveClass(GUTTER_SENTINEL);
- });
-});
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
deleted file mode 100644
index 5ea96f1aeb..0000000000
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ /dev/null
@@ -1,586 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
-import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
-import { providerSupportsMcpConfig } from "@multica/core/agents";
-import { useFeatureEnabled } from "@multica/core/config";
-import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { larkInstallationsOptions } from "@multica/core/lark";
-import { slackInstallationsOptions } from "@multica/core/slack";
-import { dingtalkInstallationsOptions } from "@multica/core/dingtalk";
-import { wecomInstallationsOptions } from "@multica/core/wecom";
-import { telegramInstallationsOptions } from "@multica/core/telegram";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import { cn } from "@multica/ui/lib/utils";
-import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
-import { ActivityTab } from "./tabs/activity-tab";
-import { InstructionsTab } from "./tabs/instructions-tab";
-import { SkillsTab } from "./tabs/skills-tab";
-import { EnvTab } from "./tabs/env-tab";
-import { CustomArgsTab } from "./tabs/custom-args-tab";
-import { McpConfigTab } from "./tabs/mcp-config-tab";
-import { AgentMcpTab } from "./tabs/agent-mcp-tab";
-import { IntegrationsTab } from "./tabs/integrations-tab";
-import { QoderAgentTab } from "./tabs/qoder-agent-tab";
-import { RuntimeConfigTab } from "./tabs/runtime-config-tab";
-import { AgentDetailInspector } from "./agent-detail-inspector";
-import { AgentAccessSettings } from "./agent-access-settings";
-import { AgentOverviewSummary } from "./agent-overview-summary";
-import { ActorIssuesPanel } from "../../common/actor-issues-panel";
-import { useT } from "../../i18n";
-import { useNavigation } from "../../navigation";
-
-type DetailSection = "overview" | "work" | "capabilities" | "settings";
-
-export type DetailTab =
- | "overview"
- | "work"
- | "instructions"
- | "skills"
- | "mcp_config"
- | "composio_mcp"
- | "integrations"
- | "general"
- | "access"
- | "env"
- | "custom_args"
- | "runtime_config";
-
-type SecondaryTab = {
- id: DetailTab;
- labelKey:
- | "instructions"
- | "skills"
- | "mcp_config"
- | "composio_mcp"
- | "integrations"
- | "general"
- | "access"
- | "environment"
- | "custom_args"
- | "runtime_config"
- | "qoder_agent";
-};
-
-const CAPABILITY_TABS: SecondaryTab[] = [
- { id: "instructions", labelKey: "instructions" },
- { id: "skills", labelKey: "skills" },
- { id: "mcp_config", labelKey: "mcp_config" },
- { id: "composio_mcp", labelKey: "composio_mcp" },
- { id: "integrations", labelKey: "integrations" },
-];
-
-const SETTINGS_TABS: SecondaryTab[] = [
- { id: "general", labelKey: "general" },
- { id: "access", labelKey: "access" },
- { id: "env", labelKey: "environment" },
- { id: "custom_args", labelKey: "custom_args" },
- { id: "runtime_config", labelKey: "runtime_config" },
-];
-
-const TOP_TABS: { id: DetailSection; labelKey: DetailSection }[] = [
- { id: "overview", labelKey: "overview" },
- { id: "work", labelKey: "work" },
- { id: "capabilities", labelKey: "capabilities" },
- { id: "settings", labelKey: "settings" },
-];
-
-const CAPABILITY_IDS = new Set<DetailTab>(CAPABILITY_TABS.map((tab) => tab.id));
-const SETTINGS_IDS = new Set<DetailTab>(SETTINGS_TABS.map((tab) => tab.id));
-const DETAIL_VIEWS = new Set<DetailTab>([
- "overview",
- "work",
- ...CAPABILITY_TABS.map((tab) => tab.id),
- ...SETTINGS_TABS.map((tab) => tab.id),
-]);
-
-function isDetailTab(value: string | null): value is DetailTab {
- return value !== null && DETAIL_VIEWS.has(value as DetailTab);
-}
-
-function sectionForView(view: DetailTab): DetailSection {
- if (view === "overview") return "overview";
- if (view === "work") return "work";
- if (CAPABILITY_IDS.has(view)) return "capabilities";
- return "settings";
-}
-
-interface AgentOverviewPaneProps {
- agent: Agent;
- runtime: AgentRuntime | null;
- owner: MemberWithUser | null;
- runtimes: AgentRuntime[];
- members: MemberWithUser[];
- onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
- currentUserId?: string | null;
- canEdit: boolean;
- navIntent?: DetailTab | null;
- onNavIntentHandled?: () => void;
-}
-
-/**
- * Agent workbench organised around user intent instead of backend fields.
- * Overview answers "what is happening now?", Work owns the issue surface,
- * Capabilities describes what the agent can do, and Settings describes how
- * it runs. The lower-level editors stay intact so the reorganisation does not
- * alter persistence or permission semantics.
- */
-export function AgentOverviewPane({
- agent,
- runtime,
- owner,
- runtimes,
- members,
- onUpdate,
- currentUserId,
- canEdit,
- navIntent,
- onNavIntentHandled,
-}: AgentOverviewPaneProps) {
- const { t } = useT("agents");
- const wsId = useWorkspaceId();
- const navigation = useNavigation();
- const urlView = navigation.searchParams.get("view");
- const composioMCPAppsEnabled = useFeatureEnabled(
- COMPOSIO_MCP_APPS_FLAG,
- false,
- );
- const [activeView, setActiveView] = useState<DetailTab>(() =>
- isDetailTab(urlView) ? urlView : "overview",
- );
- const [activeDirty, setActiveDirty] = useState(false);
- const [pendingView, setPendingView] = useState<DetailTab | null>(null);
- const lastUrlViewRef = useRef(urlView);
-
- const { data: larkListing } = useQuery({
- ...larkInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: slackListing } = useQuery({
- ...slackInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: dingtalkListing } = useQuery({
- ...dingtalkInstallationsOptions(wsId),
- });
- const { data: wecomListing } = useQuery({
- ...wecomInstallationsOptions(wsId),
- enabled: !!wsId,
- });
- const { data: telegramListing } = useQuery({
- ...telegramInstallationsOptions(wsId),
- enabled: !!wsId,
- });
-
- const integrationsConfigured =
- larkListing?.configured === true ||
- slackListing?.configured === true ||
- dingtalkListing?.configured === true ||
- wecomListing?.configured === true ||
- telegramListing?.configured === true;
-
- // The Qoder bridge fails every task carrying skills, MCP, connected apps,
- // env, args or a model override, and runs issues only (no chat). Those
- // editors are not offered; the agent in Qoder Cloud Agents owns that configuration.
- const qoderRuntime = runtime?.provider === "qoder_cloud";
-
- const visibleCapabilityTabs = useMemo(() => {
- if (qoderRuntime) {
- return CAPABILITY_TABS.filter((tab) => tab.id === "instructions");
- }
- const showMcp = runtime
- ? providerSupportsMcpConfig(runtime.provider)
- : true;
- const showComposioMcp =
- composioMCPAppsEnabled &&
- !!currentUserId &&
- !!agent.owner_id &&
- agent.owner_id === currentUserId;
-
- return CAPABILITY_TABS.filter((tab) => {
- if (tab.id === "mcp_config") return showMcp;
- if (tab.id === "composio_mcp") return showComposioMcp;
- if (tab.id === "integrations") return integrationsConfigured;
- return true;
- });
- }, [
- agent.owner_id,
- composioMCPAppsEnabled,
- currentUserId,
- integrationsConfigured,
- qoderRuntime,
- runtime,
- ]);
-
- const visibleSettingsTabs = useMemo(
- () =>
- SETTINGS_TABS.filter((tab) => {
- if (qoderRuntime) return tab.id !== "env" && tab.id !== "custom_args";
- // Env is the only settings tab backed by a secret-bearing endpoint.
- // GET/PUT /api/agents/{id}/env admits the agent owner or a workspace
- // owner/admin (MUL-5438) — the same rule `canEdit` encodes — so
- // showing the tab to anyone else guarantees a 403 on "Reveal & edit".
- // The server stays the boundary; this only removes a dead entry point.
- if (tab.id === "env") return canEdit;
- if (tab.id === "runtime_config") return runtime?.provider === "openclaw";
- return true;
- }).map((tab) =>
- qoderRuntime && tab.id === "runtime_config"
- ? { ...tab, labelKey: "qoder_agent" as const }
- : tab,
- ),
- [canEdit, qoderRuntime, runtime?.provider],
- );
-
- const visibleViews = useMemo(
- () =>
- new Set<DetailTab>([
- "overview",
- "work",
- ...visibleCapabilityTabs.map((tab) => tab.id),
- ...visibleSettingsTabs.map((tab) => tab.id),
- ]),
- [visibleCapabilityTabs, visibleSettingsTabs],
- );
-
- const effectiveView = visibleViews.has(activeView) ? activeView : "overview";
- const activeSection = sectionForView(effectiveView);
-
- const commitView = useCallback(
- (next: DetailTab) => {
- setActiveView(next);
- const params = new URLSearchParams(navigation.searchParams);
- if (next === "overview") params.delete("view");
- else params.set("view", next);
- const query = params.toString();
- navigation.replace(`${navigation.pathname}${query ? `?${query}` : ""}`);
- },
- [navigation],
- );
-
- const requestView = useCallback(
- (next: DetailTab) => {
- if (next === effectiveView) return;
- if (activeDirty) {
- setPendingView(next);
- return;
- }
- commitView(next);
- },
- [activeDirty, commitView, effectiveView],
- );
-
- const requestSection = (section: DetailSection) => {
- if (section === "overview" || section === "work") {
- requestView(section);
- return;
- }
- if (section === "capabilities") {
- const current = CAPABILITY_IDS.has(effectiveView)
- ? effectiveView
- : visibleCapabilityTabs[0]?.id;
- if (current) requestView(current);
- return;
- }
- const current = SETTINGS_IDS.has(effectiveView)
- ? effectiveView
- : visibleSettingsTabs[0]?.id;
- if (current) requestView(current);
- };
-
- const commitViewChange = () => {
- if (!pendingView) return;
- commitView(pendingView);
- setActiveDirty(false);
- setPendingView(null);
- };
-
- useEffect(() => {
- if (urlView === lastUrlViewRef.current) return;
- lastUrlViewRef.current = urlView;
- if (urlView === null) {
- setActiveView("overview");
- return;
- }
- if (isDetailTab(urlView) && visibleViews.has(urlView)) {
- setActiveView(urlView);
- }
- }, [urlView, visibleViews]);
-
- useEffect(() => {
- if (navIntent == null) return;
- if (visibleViews.has(navIntent)) requestView(navIntent);
- onNavIntentHandled?.();
- }, [navIntent, onNavIntentHandled, requestView, visibleViews]);
-
- const secondaryTabs =
- activeSection === "capabilities"
- ? visibleCapabilityTabs
- : activeSection === "settings"
- ? visibleSettingsTabs
- : [];
- const activeSecondaryTab = secondaryTabs.find(
- (tab) => tab.id === effectiveView,
- );
- const isSecondaryLayout =
- secondaryTabs.length > 0 && activeSecondaryTab != null;
-
- return (
- <div className="flex min-h-0 flex-1 flex-col bg-background">
- <div
- className="shrink-0 overflow-x-auto border-b"
- role="tablist"
- aria-label={t(($) => $.tabs.page_navigation_aria)}
- >
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex items-center gap-6")}>
- {TOP_TABS.map((tab) => (
- <button
- key={tab.id}
- type="button"
- role="tab"
- aria-selected={activeSection === tab.id}
- onClick={() => requestSection(tab.id)}
- className={cn(
- "relative shrink-0 py-3 text-body font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
- activeSection === tab.id
- ? "text-foreground after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 after:bg-foreground"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- {t(($) => $.tabs[tab.labelKey])}
- </button>
- ))}
- </div>
- </div>
-
- {/* Header, tab bar, banners and every panel read PAGE_RAIL, so the page
- is one centred column at every width (MUL-7107). The first pass put
- the chrome on the rail and left the panels off it, which is the bug;
- the second put everything full-bleed, which aligned the leading edge
- and then stretched this two-column layout to 2200px and stranded the
- summary card 1200px from the list it summarises.
-
- A detail page is a document about one entity, not a table. Genuine
- list surfaces — Issues, My Issues, member detail — stay full-bleed on
- PAGE_GUTTER alone; `runtimes` and skill detail read the same rail.
-
- Panels that own no inner gutter take PAGE_GUTTER on the rail element
- itself; Work and the secondary nav layout take a bare rail because
- their toolbar and nav rail already carry it. Below ~1730px the rail
- is wider than the viewport, so it costs small and medium screens
- nothing.
-
- Overview/Work scroll as one page. Sidebar views split scrolling on
- md+ (nav rail pinned, content pane scrolls) like settings-page.tsx;
- below md the rail is a horizontal strip and the page scrolls whole. */}
- <div
- className={cn(
- "min-h-0 flex-1 overflow-y-auto",
- isSecondaryLayout && "md:overflow-hidden",
- )}
- >
- {effectiveView === "overview" && (
- <div
- className={cn(PAGE_RAIL, PAGE_GUTTER, "py-4 sm:py-6")}
- >
- <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]">
- <ActivityTab agent={agent} showPerformance={false} />
- <AgentOverviewSummary
- agent={agent}
- runtime={runtime}
- owner={owner}
- />
- </div>
- </div>
- )}
-
- {effectiveView === "work" && (
- <div className={cn(PAGE_RAIL, "flex min-h-[620px] flex-col")}>
- <ActorIssuesPanel actorType="agent" actorId={agent.id} />
- </div>
- )}
-
- {secondaryTabs.length > 0 && activeSecondaryTab && (
- <div className={cn(PAGE_RAIL, "flex min-h-full flex-col md:h-full md:flex-row")}>
- {/* Content-surface color, no shell tint — same rule as the settings
- nav: in-card panels must not break the desktop tab merge (MUL-4439). */}
- <aside
- className={cn(
- "shrink-0 overflow-x-auto border-b border-surface-border py-2 md:w-52 md:overflow-y-auto md:border-b-0 md:border-r md:py-4",
- PAGE_GUTTER,
- )}
- >
- <div
- className="flex w-max min-w-full items-center gap-1 md:w-full md:flex-col md:items-stretch"
- role="tablist"
- aria-orientation="vertical"
- aria-label={t(($) => $.tabs.section_navigation_aria)}
- >
- {secondaryTabs.map((tab) => {
- const active = effectiveView === tab.id;
- return (
- <button
- key={tab.id}
- type="button"
- role="tab"
- aria-selected={active}
- onClick={() => requestView(tab.id)}
- className={cn(
- "flex h-8 shrink-0 items-center rounded-md px-2.5 text-left text-caption transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring md:w-full",
- active
- ? "bg-surface-selected font-medium text-surface-selected-foreground hover:bg-surface-selected"
- : "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
- )}
- >
- {t(($) => $.tabs[tab.labelKey])}
- </button>
- );
- })}
- </div>
- </aside>
-
- <section className="min-w-0 flex-1 md:overflow-y-auto">
- {/* General is wider: its profile sits beside a preview of the
- new chat it produces. */}
- <div
- className={cn(
- "w-full p-4 sm:p-6 md:p-8",
- effectiveView === "general" ? "max-w-5xl" : "max-w-3xl",
- )}
- >
- <header>
- <h2 className="text-title-sm font-medium text-balance">
- {t(($) => $.tabs[activeSecondaryTab.labelKey])}
- </h2>
- </header>
-
- <div className="mt-6">
- {effectiveView === "instructions" && (
- <InstructionsTab
- agent={agent}
- onSave={(updates) => onUpdate(agent.id, updates)}
- onDirtyChange={setActiveDirty}
- />
- )}
- {effectiveView === "skills" && (
- <SkillsTab
- agent={agent}
- runtime={runtime}
- currentUserId={currentUserId}
- canEdit={canEdit}
- />
- )}
- {effectiveView === "mcp_config" && (
- <McpConfigTab
- agent={agent}
- runtime={runtime}
- currentUserId={currentUserId}
- canEdit={canEdit}
- onSave={(updates) => onUpdate(agent.id, updates)}
- onDirtyChange={setActiveDirty}
- />
- )}
- {effectiveView === "composio_mcp" && (
- <AgentMcpTab agent={agent} />
- )}
- {effectiveView === "integrations" && (
- <IntegrationsTab agent={agent} />
- )}
- {effectiveView === "general" && (
- <AgentDetailInspector
- agent={agent}
- runtime={runtime}
- runtimes={runtimes}
- members={members}
- currentUserId={currentUserId ?? null}
- canEdit={canEdit}
- onUpdate={onUpdate}
- />
- )}
- {effectiveView === "access" && (
- <AgentAccessSettings
- agent={agent}
- members={members}
- currentUserId={currentUserId ?? null}
- onDirtyChange={setActiveDirty}
- onUpdate={onUpdate}
- />
- )}
- {effectiveView === "env" && (
- <EnvTab agent={agent} onDirtyChange={setActiveDirty} />
- )}
- {effectiveView === "custom_args" && (
- <CustomArgsTab
- agent={agent}
- runtimeDevice={runtime ?? undefined}
- onSave={(updates) => onUpdate(agent.id, updates)}
- onDirtyChange={setActiveDirty}
- />
- )}
- {effectiveView === "runtime_config" &&
- (qoderRuntime ? (
- <QoderAgentTab
- canEdit={canEdit}
- key={agent.id}
- agent={agent}
- onSave={(updates) => onUpdate(agent.id, updates)}
- onDirtyChange={setActiveDirty}
- />
- ) : (
- <RuntimeConfigTab
- agent={agent}
- onSave={(updates) => onUpdate(agent.id, updates)}
- onDirtyChange={setActiveDirty}
- />
- ))}
- </div>
- </div>
- </section>
- </div>
- )}
- </div>
-
- {pendingView !== null && (
- <AlertDialog
- open
- onOpenChange={(open) => {
- if (!open) setPendingView(null);
- }}
- >
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $.tabs.discard_dialog_title)}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.tabs.discard_dialog_description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>
- {t(($) => $.tabs.discard_keep)}
- </AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
- onClick={commitViewChange}
- >
- {t(($) => $.tabs.discard_confirm)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )}
- </div>
- );
-}
diff --git a/packages/views/agents/components/agent-overview-summary.tsx b/packages/views/agents/components/agent-overview-summary.tsx
deleted file mode 100644
index e1743f1450..0000000000
--- a/packages/views/agents/components/agent-overview-summary.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-"use client";
-
-import { Bot, Server } from "@multica/ui/icons";
-import type {
- Agent,
- AgentRuntime,
- MemberWithUser,
-} from "@multica/core/types";
-import { qoderAgentId } from "@multica/core/agents";
-import { runtimeDisplayLabel } from "@multica/core/runtimes";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { useT } from "../../i18n";
-import { VisibilityBadge } from "./visibility-badge";
-import { AgentPerformanceSummary } from "./tabs/activity-tab";
-
-interface AgentOverviewSummaryProps {
- agent: Agent;
- runtime: AgentRuntime | null;
- owner: MemberWithUser | null;
-}
-
-/**
- * Read-only context for the workbench Overview. Editing lives under Settings;
- * keeping this surface non-interactive lets users scan identity, execution,
- * and capability context without mistaking every value for a control.
- */
-export function AgentOverviewSummary({
- agent,
- runtime,
- owner,
-}: AgentOverviewSummaryProps) {
- const { t } = useT("agents");
- const { t: tr } = useT("runtimes");
- const runtimeOnline = runtime?.status === "online";
- const qoderRuntime = runtime?.provider === "qoder_cloud";
-
- return (
- <aside className="self-start rounded-xl border border-surface-border bg-surface p-5 shadow-[var(--surface-shadow)] xl:sticky xl:top-6">
- <section>
- <h2 className="text-body font-medium">
- {t(($) => $.overview.agent_context)}
- </h2>
- <dl className="mt-4 space-y-3 text-caption">
- {owner && (
- <SummaryRow label={t(($) => $.inspector.prop_owner)}>
- <span className="flex min-w-0 items-center gap-1.5">
- <ActorAvatar
- actorType="member"
- actorId={owner.user_id}
- size="xs"
- />
- <span className="truncate text-foreground">{owner.name}</span>
- </span>
- </SummaryRow>
- )}
- <SummaryRow label={t(($) => $.overview.access)}>
- <VisibilityBadge value={agent.visibility} />
- </SummaryRow>
- <SummaryRow label={t(($) => $.inspector.prop_runtime)}>
- <span className="flex min-w-0 items-center gap-1.5 text-foreground">
- <span
- className={`h-1.5 w-1.5 shrink-0 rounded-full ${
- runtimeOnline ? "bg-success" : "bg-muted-foreground/40"
- }`}
- aria-hidden="true"
- />
- <Server className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
- <span className="truncate">
- {runtime
- ? runtimeDisplayLabel(runtime)
- : t(($) => $.pickers.runtime_none)}
- </span>
- </span>
- </SummaryRow>
- {qoderRuntime ? (
- <SummaryRow label={tr(($) => $.qoder.agent)}>
- <span className="block truncate font-mono text-foreground">
- {qoderAgentId(agent.runtime_config) || "—"}
- </span>
- </SummaryRow>
- ) : (
- <SummaryRow label={t(($) => $.inspector.prop_model)}>
- <span className="flex min-w-0 items-center gap-1.5 text-foreground">
- <Bot className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
- <span className="truncate">
- {agent.model || t(($) => $.pickers.model_default)}
- </span>
- </span>
- </SummaryRow>
- )}
- <SummaryRow label={t(($) => $.inspector.prop_concurrency)}>
- <span className="font-mono tabular-nums text-foreground">
- {agent.max_concurrent_tasks}
- </span>
- </SummaryRow>
- </dl>
- </section>
-
- {qoderRuntime ? null : (
- <section className="mt-5 border-t pt-5">
- <div className="flex items-center justify-between gap-3">
- <h2 className="text-body font-medium">
- {t(($) => $.inspector.section_skills)}
- </h2>
- <span className="font-mono text-caption tabular-nums text-muted-foreground">
- {agent.skills.length}
- </span>
- </div>
- {agent.skills.length > 0 ? (
- <div className="mt-3 flex flex-wrap gap-1.5">
- {agent.skills.map((skill) => (
- <span
- key={skill.id}
- className="max-w-full truncate rounded-md border border-surface-border bg-surface-hover px-2 py-1 text-caption text-muted-foreground"
- >
- {skill.name}
- </span>
- ))}
- </div>
- ) : (
- <p className="mt-3 text-caption text-muted-foreground">
- {t(($) => $.tab_body.skills.empty_title)}
- </p>
- )}
- </section>
- )}
-
- <AgentPerformanceSummary agent={agent} />
- </aside>
- );
-}
-
-function SummaryRow({
- label,
- children,
-}: {
- label: string;
- children: React.ReactNode;
-}) {
- return (
- <div className="grid grid-cols-[88px_minmax(0,1fr)] items-center gap-3">
- <dt className="text-muted-foreground">{label}</dt>
- <dd className="min-w-0">{children}</dd>
- </div>
- );
-}
diff --git a/packages/views/agents/components/agent-presence-indicator.tsx b/packages/views/agents/components/agent-presence-indicator.tsx
index d028ebc8fb..a99bae9d3d 100644
--- a/packages/views/agents/components/agent-presence-indicator.tsx
+++ b/packages/views/agents/components/agent-presence-indicator.tsx
@@ -13,6 +13,9 @@ interface PresenceIndicatorProps {
detail: AgentPresenceDetail | null | undefined;
// Compact = dot only, no label / no workload chip. Used in dense rows.
compact?: boolean;
+ // Drops the running / queued counts, for surfaces that list the runs
+ // themselves next to the label.
+ hideCounts?: boolean;
}
/**
@@ -33,6 +36,7 @@ interface PresenceIndicatorProps {
export function AgentPresenceIndicator({
detail,
compact,
+ hideCounts,
}: PresenceIndicatorProps) {
const { t } = useT("agents");
if (!detail) {
@@ -49,7 +53,9 @@ export function AgentPresenceIndicator({
const workloadLabel = t(($) => $.workload[detail.workload]);
const isWorking = detail.workload === "working";
const isQueued = detail.workload === "queued";
- const showQueueBadge = isWorking && detail.queuedCount > 0;
+ const showWorkingCount = !hideCounts && isWorking;
+ const showQueuedCount = !hideCounts && isQueued;
+ const showQueueBadge = showWorkingCount && detail.queuedCount > 0;
// Queued's amber comes from workloadConfig as the *severe* tone — meant
// for "stuck on offline runtime", which is the dominant cause. But on a
// healthy runtime, queued is just a brief race between enqueue and the
@@ -94,7 +100,7 @@ export function AgentPresenceIndicator({
>
{workloadLabel}
</span>
- {isWorking && (
+ {showWorkingCount && (
<span className="font-mono text-caption tabular-nums text-muted-foreground">
{detail.runningCount} / {detail.capacity}
</span>
@@ -107,7 +113,7 @@ export function AgentPresenceIndicator({
{/* Queued (no running) — show the queued count directly, since
there's no running/capacity ratio to anchor on. Honestly
surfaces "stuck" on offline runtimes. */}
- {isQueued && (
+ {showQueuedCount && (
<span className="font-mono text-caption tabular-nums text-muted-foreground">
{detail.queuedCount}
</span>
diff --git a/packages/views/agents/components/agent-properties-panel.test.tsx b/packages/views/agents/components/agent-properties-panel.test.tsx
new file mode 100644
index 0000000000..3c1a2cc700
--- /dev/null
+++ b/packages/views/agents/components/agent-properties-panel.test.tsx
@@ -0,0 +1,241 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, screen } from "@testing-library/react";
+import type { AgentActivity } from "@multica/core/agents";
+import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+
+const pickers = vi.hoisted(() => ({
+ runtime: null as null | {
+ runtimes: AgentRuntime[];
+ canEdit?: boolean;
+ onChange: (id: string) => void;
+ },
+ model: null as null | { canEdit?: boolean; onChange: (model: string) => void },
+}));
+const activityRef = vi.hoisted(() => ({
+ current: new Map<string, unknown>(),
+}));
+const mockInitiateListModels = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ initiateListModels: (...args: unknown[]) => mockInitiateListModels(...args),
+ getListModelsResult: vi.fn(),
+ },
+}));
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "workspace-1",
+}));
+vi.mock("@multica/core/agents", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/agents")>()),
+ useWorkspaceActivityMap: () => ({ byAgent: activityRef.current, loading: false }),
+}));
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => <span data-testid="avatar" />,
+}));
+vi.mock("./agent-presence-indicator", () => ({
+ AgentPresenceIndicator: () => <span>presence</span>,
+}));
+vi.mock("./inspector/runtime-picker", () => ({
+ RuntimePicker: (props: NonNullable<typeof pickers.runtime>) => {
+ pickers.runtime = props;
+ return <div data-testid="runtime-picker" />;
+ },
+}));
+vi.mock("./inspector/model-picker", () => ({
+ ModelPicker: (props: NonNullable<typeof pickers.model>) => {
+ pickers.model = props;
+ return <div data-testid="model-picker" />;
+ },
+}));
+
+import { AgentPropertiesPanel } from "./agent-properties-panel";
+
+function runtime(id: string, provider: string): AgentRuntime {
+ return {
+ id,
+ workspace_id: "workspace-1",
+ daemon_id: null,
+ name: id,
+ runtime_mode: provider === "qoder_cloud" ? "cloud" : "local",
+ provider,
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: "user-1",
+ visibility: "public",
+ last_seen_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+}
+
+const claude = runtime("rt-claude", "claude");
+const qoder = runtime("rt-qoder", "qoder_cloud");
+
+const owner = { user_id: "user-2", name: "Ada" } as MemberWithUser;
+
+function agentOn(bound: AgentRuntime, over: Partial<Agent> = {}): Agent {
+ return {
+ id: "agent-1",
+ workspace_id: "workspace-1",
+ name: "Lambda",
+ description: "",
+ runtime_id: bound.id,
+ runtime_config: {},
+ model: "",
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ created_at: "2026-05-28T00:00:00Z",
+ ...over,
+ } as Agent;
+}
+
+function renderPanel(
+ bound: AgentRuntime,
+ {
+ agent = agentOn(bound),
+ canEdit = true,
+ }: { agent?: Agent; canEdit?: boolean } = {},
+) {
+ const onUpdate = vi.fn(async () => {});
+ const onEditAccess = vi.fn();
+ renderWithI18n(
+ <QueryClientProvider
+ client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
+ >
+ <AgentPropertiesPanel
+ agent={agent}
+ runtime={bound}
+ runtimes={[claude, qoder]}
+ presence={null}
+ owner={owner}
+ members={[owner]}
+ currentUserId="user-1"
+ canEdit={canEdit}
+ onUpdate={onUpdate}
+ onEditAccess={onEditAccess}
+ />
+ </QueryClientProvider>,
+ );
+ return { onUpdate, onEditAccess };
+}
+
+function activityToday(total: number, completed: number, failed: number): AgentActivity {
+ const buckets = Array.from({ length: 30 }, () => ({
+ total: 0,
+ failed: 0,
+ completed: 0,
+ cancelled: 0,
+ }));
+ buckets[29] = { total, failed, completed, cancelled: total - completed - failed };
+ return { buckets, daysSinceCreated: 30 };
+}
+
+beforeEach(() => {
+ pickers.runtime = null;
+ pickers.model = null;
+ activityRef.current = new Map();
+ mockInitiateListModels.mockReset();
+});
+afterEach(cleanup);
+
+describe("AgentPropertiesPanel", () => {
+ it("lists the agent's properties", () => {
+ renderPanel(claude);
+
+ for (const label of [
+ "Properties",
+ "Status",
+ "Owner",
+ "Runtime",
+ "Harness",
+ "Model",
+ "Access",
+ "Runs (7d)",
+ "Created",
+ ]) {
+ expect(screen.getByText(label)).toBeInTheDocument();
+ }
+ expect(screen.getByText("Ada")).toBeInTheDocument();
+ expect(screen.getByText("Claude")).toBeInTheDocument();
+ });
+
+ it("changes the runtime and clears the runtime-native model settings with it", () => {
+ const { onUpdate } = renderPanel(claude);
+
+ expect(pickers.runtime?.canEdit).toBe(true);
+ pickers.runtime?.onChange("rt-other");
+ expect(onUpdate).toHaveBeenCalledWith("agent-1", {
+ runtime_id: "rt-other",
+ model: "",
+ thinking_level: "",
+ service_tier: "",
+ });
+ });
+
+ it("changes the model in place", () => {
+ const { onUpdate } = renderPanel(claude);
+
+ expect(pickers.model?.canEdit).toBe(true);
+ pickers.model?.onChange("sonnet");
+ expect(onUpdate).toHaveBeenCalledWith(
+ "agent-1",
+ expect.objectContaining({ model: "sonnet" }),
+ );
+ });
+
+ it("keeps runtime and model read-only for someone who cannot edit", () => {
+ renderPanel(claude, { canEdit: false });
+
+ expect(pickers.runtime?.canEdit).toBe(false);
+ expect(pickers.model?.canEdit).toBe(false);
+ });
+
+ it("does not offer the Qoder runtime to other agents", () => {
+ renderPanel(claude);
+
+ expect(pickers.runtime?.runtimes.map((r) => r.id)).toEqual(["rt-claude"]);
+ });
+
+ it("locks the runtime and shows the Qoder agent instead of a model on Qoder", () => {
+ renderPanel(qoder, {
+ agent: agentOn(qoder, { runtime_config: { qoder_agent_id: "qa-42" } }),
+ });
+
+ expect(pickers.runtime?.canEdit).toBe(false);
+ expect(pickers.model).toBeNull();
+ expect(screen.queryByText("Model")).not.toBeInTheDocument();
+ expect(screen.getByText("Remote agent")).toBeInTheDocument();
+ expect(screen.getByText("qa-42")).toBeInTheDocument();
+ expect(mockInitiateListModels).not.toHaveBeenCalled();
+ });
+
+ it("opens the access form from the Access value", () => {
+ const { onEditAccess } = renderPanel(claude, {
+ agent: agentOn(claude, { permission_mode: "private", invocation_targets: [] }),
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: /^Access: .+\. Change access$/ }));
+ expect(onEditAccess).toHaveBeenCalledTimes(1);
+ });
+
+ it("counts the last 7 days of runs with their success rate", () => {
+ activityRef.current = new Map([["agent-1", activityToday(4, 3, 1)]]);
+ renderPanel(claude);
+
+ expect(screen.getByText("4")).toBeInTheDocument();
+ expect(screen.getByText("75% success")).toBeInTheDocument();
+ });
+
+ it("shows no success rate before the agent has run", () => {
+ renderPanel(claude);
+
+ expect(screen.getByText("0")).toBeInTheDocument();
+ expect(screen.queryByText(/% success/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/components/agent-properties-panel.tsx b/packages/views/agents/components/agent-properties-panel.tsx
new file mode 100644
index 0000000000..efc2d95dff
--- /dev/null
+++ b/packages/views/agents/components/agent-properties-panel.tsx
@@ -0,0 +1,219 @@
+"use client";
+
+import { useCallback, type ReactNode } from "react";
+import { Globe, Lock, Users } from "@multica/ui/icons";
+import type {
+ Agent,
+ AgentRuntime,
+ MemberWithUser,
+} from "@multica/core/types";
+import {
+ type AgentPresenceDetail,
+ effectiveAccessScope,
+ qoderAgentId,
+ summarizeActivityWindow,
+ useWorkspaceActivityMap,
+} from "@multica/core/agents";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { providerDisplayName } from "@multica/core/runtimes";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { ObjectPanelSection, ObjectProperty } from "../../layout/object-page";
+import { ProviderLogo } from "../../runtimes/components/provider-logo";
+import { useLocale, useT } from "../../i18n";
+import { AgentPresenceIndicator } from "./agent-presence-indicator";
+import { CHIP_CLASS } from "./inspector/chip";
+import { ModelPicker } from "./inspector/model-picker";
+import { RuntimePicker } from "./inspector/runtime-picker";
+import { useExecutionControls } from "./inspector/use-execution-controls";
+import { AgentPerformanceSummary, SuccessRate } from "./tabs/activity-tab";
+
+const ACCESS_ICONS = {
+ workspace: Globe,
+ "specific-people": Users,
+ "owner-only": Lock,
+} as const;
+
+/**
+ * The agent page's right panel: what it is and where it runs, with the
+ * runtime and model editable in place.
+ */
+export function AgentPropertiesPanel({
+ agent,
+ runtime,
+ runtimes,
+ presence,
+ owner,
+ members,
+ currentUserId,
+ canEdit,
+ onUpdate,
+ onEditAccess,
+}: {
+ agent: Agent;
+ runtime: AgentRuntime | null;
+ runtimes: AgentRuntime[];
+ presence: AgentPresenceDetail | null;
+ owner: MemberWithUser | null;
+ members: MemberWithUser[];
+ currentUserId: string | null;
+ canEdit: boolean;
+ onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;
+ /** Opens the full access form; access is a draft-and-save choice. */
+ onEditAccess: () => void;
+}) {
+ const { t } = useT("agents");
+ const { t: tl } = useT("layout");
+ const { t: tr } = useT("runtimes");
+ const locale = useLocale();
+ const wsId = useWorkspaceId();
+ const update = useCallback(
+ (data: Record<string, unknown>) => onUpdate(agent.id, data),
+ [agent.id, onUpdate],
+ );
+ const {
+ qoderRuntime,
+ canDiscoverRuntimeModels,
+ runtimeOptions,
+ changeModel,
+ changeRuntime,
+ } = useExecutionControls({ agent, runtime, runtimes, currentUserId, update });
+
+ const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);
+ const week = summarizeActivityWindow(activityMap.get(agent.id), 7);
+
+ const accessScope = effectiveAccessScope(
+ agent.permission_mode,
+ agent.invocation_targets,
+ );
+ const AccessIcon = ACCESS_ICONS[accessScope];
+ const accessLabel = t(($) =>
+ accessScope === "workspace"
+ ? $.access.scope_labels.workspace
+ : accessScope === "specific-people"
+ ? $.access.scope_labels.specific_people
+ : $.access.scope_labels.owner_only,
+ );
+
+ return (
+ <div className="space-y-4">
+ <ObjectPanelSection title={tl(($) => $.object_page.properties)}>
+ <ObjectProperty label={t(($) => $.panel.status)}>
+ <Value>
+ <AgentPresenceIndicator detail={presence} hideCounts />
+ </Value>
+ </ObjectProperty>
+
+ <ObjectProperty label={t(($) => $.inspector.prop_owner)}>
+ <Value>
+ {owner ? (
+ <>
+ <ActorAvatar actorType="member" actorId={owner.user_id} size="xs" />
+ <span className="truncate">{owner.name}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </Value>
+ </ObjectProperty>
+
+ <ObjectProperty label={t(($) => $.inspector.prop_runtime)}>
+ <RuntimePicker
+ value={agent.runtime_id}
+ runtimes={runtimeOptions}
+ members={members}
+ currentUserId={currentUserId}
+ canEdit={canEdit && !qoderRuntime}
+ onChange={changeRuntime}
+ />
+ </ObjectProperty>
+
+ <ObjectProperty label={tr(($) => $.page.columns.harness)}>
+ <Value>
+ {runtime ? (
+ <>
+ <ProviderLogo provider={runtime.provider} className="size-3.5 shrink-0" />
+ <span className="truncate">{providerDisplayName(runtime.provider)}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </Value>
+ </ObjectProperty>
+
+ {/* A Qoder agent's model lives on its agent in Qoder Cloud Agents; the
+ bound agent id is what identifies it here. */}
+ {qoderRuntime ? (
+ <ObjectProperty label={tr(($) => $.qoder.agent)}>
+ <Value>
+ <span className="truncate font-mono">
+ {qoderAgentId(agent.runtime_config) || "—"}
+ </span>
+ </Value>
+ </ObjectProperty>
+ ) : (
+ <ObjectProperty label={t(($) => $.inspector.prop_model)}>
+ <ModelPicker
+ runtimeId={agent.runtime_id}
+ runtimeOnline={canDiscoverRuntimeModels}
+ value={agent.model ?? ""}
+ canEdit={canEdit}
+ onChange={changeModel}
+ />
+ </ObjectProperty>
+ )}
+
+ <ObjectProperty label={t(($) => $.columns.access)}>
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ onClick={onEditAccess}
+ aria-label={t(($) => $.panel.edit_access_aria, { value: accessLabel })}
+ >
+ <AccessIcon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <span className="truncate">{accessLabel}</span>
+ </button>
+ </ObjectProperty>
+
+ <ObjectProperty label={t(($) => $.panel.runs_7d)}>
+ <Value>
+ <span className="tabular-nums">{week.totalRuns}</span>
+ {week.totalRuns > 0 ? (
+ <>
+ <span className="text-faint-foreground" aria-hidden="true">·</span>
+ <SuccessRate rate={week.successRate} labelled />
+ </>
+ ) : null}
+ </Value>
+ </ObjectProperty>
+
+ <ObjectProperty label={t(($) => $.inspector.prop_created)}>
+ <Value>
+ <span className="truncate tabular-nums">
+ {new Date(agent.created_at).toLocaleDateString(locale, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ })}
+ </span>
+ </Value>
+ </ObjectProperty>
+ </ObjectPanelSection>
+
+ <ObjectPanelSection
+ title={t(($) => $.tab_body.activity.section_last_30d)}
+ defaultOpen={false}
+ >
+ <div className="py-1">
+ <AgentPerformanceSummary agent={agent} />
+ </div>
+ </ObjectPanelSection>
+ </div>
+ );
+}
+
+/** A read-only value, inset to line up with the pickers' chip text. */
+function Value({ children }: { children: ReactNode }) {
+ return (
+ <span className="flex min-w-0 items-center gap-1.5 px-1.5">{children}</span>
+ );
+}
diff --git a/packages/views/agents/components/agent-row-actions.tsx b/packages/views/agents/components/agent-row-actions.tsx
index 0b1b44f63c..6eac1580bd 100644
--- a/packages/views/agents/components/agent-row-actions.tsx
+++ b/packages/views/agents/components/agent-row-actions.tsx
@@ -5,7 +5,6 @@ import {
AlertCircle,
Copy,
ExternalLink,
- MoreHorizontal,
RotateCcw,
Square,
Trash2,
@@ -29,15 +28,12 @@ import {
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
- DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { useT } from "../../i18n";
import { AppLink, useIntentNavigate } from "../../navigation";
-import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
+import { CollectionRowMenu } from "../../layout/collection-list";
interface AgentRowActionsProps {
agent: Agent;
@@ -57,12 +53,7 @@ interface AgentRowActionsProps {
* Per-row dropdown menu for the agents list. The set of actions is derived
* from (a) the agent's lifecycle state (active vs archived) and (b) the
* caller's permission level. "Open in new tab" applies to every row, so the
- * trigger always renders.
- *
- * The row is a plain `<div>` whose whole-row navigation is a mouse `onClick`
- * (see `useRowLink`), not an ancestor `<a>`. The host cell stops click
- * propagation so opening this menu never navigates the row; the trigger
- * itself needs no guard. Menu and dialog content is portaled out of the row.
+ * trigger always renders. The same items open on right-click.
*/
export function AgentRowActions({
agent,
@@ -137,75 +128,57 @@ export function AgentRowActions({
return (
<>
- <DropdownMenu>
- <DeferredTooltip
- content={t(($) => $.row.actions_aria)}
- trigger={
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- aria-label={t(($) => $.row.actions_aria)}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-100 @2xl:opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"
- >
- <MoreHorizontal className="size-4" />
- </button>
- }
- />
+ <CollectionRowMenu label={t(($) => $.row.actions_aria)} contentClassName="w-auto">
+ {/* Same shape as every other entity row menu: an explicit CTA is a
+ foreground open executed through the adapter (an anchor-based
+ item would depend on native activation surviving the menu
+ closing under it). */}
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ paths.agentDetail(agent.id),
+ "foreground-tab",
+ agent.name,
+ )
}
- />
- <DropdownMenuContent align="end" className="w-auto">
- {/* Same shape as every other entity row menu: an explicit CTA is a
- foreground open executed through the adapter (an anchor-based
- item would depend on native activation surviving the menu
- closing under it). */}
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {showStop && (
<DropdownMenuItem
- onClick={() =>
- intentNavigate(
- paths.agentDetail(agent.id),
- "foreground-tab",
- agent.name,
- )
- }
+ onClick={() => setConfirmCancel(true)}
>
- <ExternalLink className="h-3.5 w-3.5" />
- {tCommon(($) => $.navigation.open_in_new_tab)}
+ <Square className="h-3.5 w-3.5" />
+ {t(($) => $.row_actions.cancel_all_tasks)}
+ </DropdownMenuItem>
+ )}
+ {showDuplicate && (
+ <DropdownMenuItem render={<AppLink href={duplicateHref} />}>
+ <Copy className="h-3.5 w-3.5" />
+ {t(($) => $.row_actions.duplicate)}
</DropdownMenuItem>
- <DropdownMenuSeparator />
- {showStop && (
+ )}
+ {showRestore && (
+ <DropdownMenuItem onClick={handleRestore}>
+ <RotateCcw className="h-3.5 w-3.5" />
+ {t(($) => $.row_actions.restore)}
+ </DropdownMenuItem>
+ )}
+ {showArchive && (
+ <>
+ <DropdownMenuSeparator />
<DropdownMenuItem
- onClick={() => setConfirmCancel(true)}
+ variant="destructive"
+ onClick={() => setConfirmArchive(true)}
>
- <Square className="h-3.5 w-3.5" />
- {t(($) => $.row_actions.cancel_all_tasks)}
- </DropdownMenuItem>
- )}
- {showDuplicate && (
- <DropdownMenuItem render={<AppLink href={duplicateHref} />}>
- <Copy className="h-3.5 w-3.5" />
- {t(($) => $.row_actions.duplicate)}
+ <Trash2 className="h-3.5 w-3.5" />
+ {t(($) => $.row_actions.archive)}
</DropdownMenuItem>
- )}
- {showRestore && (
- <DropdownMenuItem onClick={handleRestore}>
- <RotateCcw className="h-3.5 w-3.5" />
- {t(($) => $.row_actions.restore)}
- </DropdownMenuItem>
- )}
- {showArchive && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setConfirmArchive(true)}
- >
- <Trash2 className="h-3.5 w-3.5" />
- {t(($) => $.row_actions.archive)}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ </>
+ )}
+ </CollectionRowMenu>
{confirmCancel && (
<AlertDialog
@@ -285,7 +258,7 @@ export function AgentRowActions({
type AgentsT = ReturnType<typeof useT<"agents">>["t"];
-function describeCancelImpact(running: number, queued: number, t: AgentsT): string {
+export function describeCancelImpact(running: number, queued: number, t: AgentsT): string {
if (running === 0 && queued === 0) {
return t(($) => $.row_actions.cancel_dialog_no_tasks);
}
diff --git a/packages/views/agents/components/agent-skills-section.tsx b/packages/views/agents/components/agent-skills-section.tsx
new file mode 100644
index 0000000000..955ff39c77
--- /dev/null
+++ b/packages/views/agents/components/agent-skills-section.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { useState } from "react";
+import { Loader2, Plus, Settings2, X } from "@multica/ui/icons";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { Agent } from "@multica/core/types";
+import { api } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ skillListOptions,
+ workspaceKeys,
+} from "@multica/core/workspace/queries";
+import { cn } from "@multica/ui/lib/utils";
+import { SkillIcon } from "../../skills/lib/skill-icon";
+import {
+ ObjectSection,
+ ObjectSectionAction,
+} from "../../layout/object-page";
+import { useT } from "../../i18n";
+import { SkillAddDialog } from "./skill-add-dialog";
+
+/**
+ * The skills assigned to the agent, as chips. Adding and removing happen
+ * here; pausing a skill and the runtime's own skills live in Advanced
+ * settings, which `onManage` opens.
+ */
+export function AgentSkillsSection({
+ agent,
+ canEdit,
+ onManage,
+}: {
+ agent: Agent;
+ canEdit: boolean;
+ onManage: () => void;
+}) {
+ const { t } = useT("agents");
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
+ const [showAdd, setShowAdd] = useState(false);
+ const [removingId, setRemovingId] = useState<string | null>(null);
+
+ const handleRemove = async (skillId: string) => {
+ setRemovingId(skillId);
+ try {
+ await api.removeAgentSkill(agent.id, skillId);
+ await qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.tab_body.skills.remove_failed_toast),
+ );
+ } finally {
+ setRemovingId(null);
+ }
+ };
+
+ return (
+ <ObjectSection
+ title={t(($) => $.tabs.skills)}
+ count={agent.skills.length}
+ action={
+ <>
+ <ObjectSectionAction icon={Settings2} onClick={onManage}>
+ {t(($) => $.sections.manage)}
+ </ObjectSectionAction>
+ {canEdit ? (
+ <ObjectSectionAction
+ icon={Plus}
+ onClick={() => setShowAdd(true)}
+ disabled={workspaceSkills.length === 0}
+ >
+ {t(($) => $.sections.add)}
+ </ObjectSectionAction>
+ ) : null}
+ </>
+ }
+ >
+ {agent.skills.length === 0 ? (
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.tab_body.skills.empty_title)}
+ </p>
+ ) : (
+ <ul className="flex flex-wrap gap-1.5">
+ {agent.skills.map((skill) => {
+ const paused = skill.enabled === false;
+ return (
+ <li
+ key={skill.id}
+ className={cn(
+ "group flex h-7 max-w-full items-center gap-1.5 rounded-md border bg-card pl-2 text-caption",
+ canEdit ? "pr-1" : "pr-2",
+ paused && "text-muted-foreground",
+ )}
+ >
+ <SkillIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 truncate">{skill.name}</span>
+ {canEdit ? (
+ <button
+ type="button"
+ onClick={() => handleRemove(skill.id)}
+ disabled={removingId !== null}
+ aria-label={t(($) => $.tab_body.skills.remove_aria, {
+ name: skill.name,
+ })}
+ className="flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed group-hover:opacity-100 [@media(hover:none)]:opacity-100"
+ >
+ {removingId === skill.id ? (
+ <Loader2 className="size-3 animate-spin motion-reduce:animate-none" />
+ ) : (
+ <X className="size-3" aria-hidden="true" />
+ )}
+ </button>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <SkillAddDialog agent={agent} open={showAdd} onOpenChange={setShowAdd} />
+ </ObjectSection>
+ );
+}
diff --git a/packages/views/agents/components/agent-work-dialog.tsx b/packages/views/agents/components/agent-work-dialog.tsx
new file mode 100644
index 0000000000..b5e9a67988
--- /dev/null
+++ b/packages/views/agents/components/agent-work-dialog.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import type { Agent } from "@multica/core/types";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { ActorIssuesPanel } from "../../common/actor-issues-panel";
+import { useT } from "../../i18n";
+
+/** The agent's issues, with the issue list's own scopes, filters and display
+ * options. */
+export function AgentWorkDialog({
+ agent,
+ open,
+ onOpenChange,
+}: {
+ agent: Agent;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useT("agents");
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex h-[min(85dvh,52rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-5xl">
+ <DialogHeader className="shrink-0 gap-1 border-b px-5 py-4 pr-12">
+ <DialogTitle>{t(($) => $.tabs.work)}</DialogTitle>
+ <DialogDescription className="truncate">{agent.name}</DialogDescription>
+ </DialogHeader>
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ <ActorIssuesPanel actorType="agent" actorId={agent.id} />
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/agents/components/agents-page-filter-predicate.test.ts b/packages/views/agents/components/agents-page-filter-predicate.test.ts
index f4d8c81f73..f492414057 100644
--- a/packages/views/agents/components/agents-page-filter-predicate.test.ts
+++ b/packages/views/agents/components/agents-page-filter-predicate.test.ts
@@ -71,9 +71,9 @@ describe("rowMatchesFilters — access dimension", () => {
permission_mode: "public_to",
invocation_targets: [{ target_type: "member", target_id: "u" }],
});
- expect(rowMatchesFilters(ownerOnly, noFilters, "")).toBe(true);
- expect(rowMatchesFilters(workspace, noFilters, "")).toBe(true);
- expect(rowMatchesFilters(specific, noFilters, "")).toBe(true);
+ expect(rowMatchesFilters(ownerOnly, noFilters)).toBe(true);
+ expect(rowMatchesFilters(workspace, noFilters)).toBe(true);
+ expect(rowMatchesFilters(specific, noFilters)).toBe(true);
});
it("filters to owner-only", () => {
@@ -82,8 +82,8 @@ describe("rowMatchesFilters — access dimension", () => {
permission_mode: "public_to",
invocation_targets: [{ target_type: "workspace", target_id: null }],
});
- expect(rowMatchesFilters(ownerOnly, withAccess(noFilters, "owner-only"), "")).toBe(true);
- expect(rowMatchesFilters(workspace, withAccess(noFilters, "owner-only"), "")).toBe(false);
+ expect(rowMatchesFilters(ownerOnly, withAccess(noFilters, "owner-only"))).toBe(true);
+ expect(rowMatchesFilters(workspace, withAccess(noFilters, "owner-only"))).toBe(false);
});
it("filters to workspace", () => {
@@ -96,9 +96,9 @@ describe("rowMatchesFilters — access dimension", () => {
permission_mode: "public_to",
invocation_targets: [{ target_type: "member", target_id: "u" }],
});
- expect(rowMatchesFilters(workspace, withAccess(noFilters, "workspace"), "")).toBe(true);
- expect(rowMatchesFilters(ownerOnly, withAccess(noFilters, "workspace"), "")).toBe(false);
- expect(rowMatchesFilters(specific, withAccess(noFilters, "workspace"), "")).toBe(false);
+ expect(rowMatchesFilters(workspace, withAccess(noFilters, "workspace"))).toBe(true);
+ expect(rowMatchesFilters(ownerOnly, withAccess(noFilters, "workspace"))).toBe(false);
+ expect(rowMatchesFilters(specific, withAccess(noFilters, "workspace"))).toBe(false);
});
it("filters to specific-people", () => {
@@ -111,9 +111,9 @@ describe("rowMatchesFilters — access dimension", () => {
permission_mode: "public_to",
invocation_targets: [{ target_type: "member", target_id: "u" }],
});
- expect(rowMatchesFilters(specific, withAccess(noFilters, "specific-people"), "")).toBe(true);
- expect(rowMatchesFilters(workspace, withAccess(noFilters, "specific-people"), "")).toBe(false);
- expect(rowMatchesFilters(ownerOnly, withAccess(noFilters, "specific-people"), "")).toBe(false);
+ expect(rowMatchesFilters(specific, withAccess(noFilters, "specific-people"))).toBe(true);
+ expect(rowMatchesFilters(workspace, withAccess(noFilters, "specific-people"))).toBe(false);
+ expect(rowMatchesFilters(ownerOnly, withAccess(noFilters, "specific-people"))).toBe(false);
});
it("multi-select access filter is OR-combined", () => {
@@ -123,8 +123,8 @@ describe("rowMatchesFilters — access dimension", () => {
invocation_targets: [{ target_type: "workspace", target_id: null }],
});
const filters: AgentListFilters = { ...noFilters, access: ["owner-only", "workspace"] };
- expect(rowMatchesFilters(ownerOnly, filters, "")).toBe(true);
- expect(rowMatchesFilters(workspace, filters, "")).toBe(true);
+ expect(rowMatchesFilters(ownerOnly, filters)).toBe(true);
+ expect(rowMatchesFilters(workspace, filters)).toBe(true);
});
it("access filter combines with other dimensions (AND)", () => {
@@ -141,8 +141,8 @@ describe("rowMatchesFilters — access dimension", () => {
access: ["owner-only"],
owners: ["user-1"],
};
- expect(rowMatchesFilters(ownerUser1, filters, "")).toBe(true);
- expect(rowMatchesFilters(ownerUser2, filters, "")).toBe(false);
+ expect(rowMatchesFilters(ownerUser1, filters)).toBe(true);
+ expect(rowMatchesFilters(ownerUser2, filters)).toBe(false);
});
it("access + availability filter: both must pass (AND)", () => {
@@ -159,8 +159,8 @@ describe("rowMatchesFilters — access dimension", () => {
access: ["workspace"],
availability: ["online"],
};
- expect(rowMatchesFilters(onlineAgent, filters, "")).toBe(true);
- expect(rowMatchesFilters(offlineAgent, filters, "")).toBe(false);
+ expect(rowMatchesFilters(onlineAgent, filters)).toBe(true);
+ expect(rowMatchesFilters(offlineAgent, filters)).toBe(false);
});
it("access + runtimes filter: both must pass (AND)", () => {
@@ -175,8 +175,8 @@ describe("rowMatchesFilters — access dimension", () => {
access: ["owner-only"],
runtimes: ["rt-local"],
};
- expect(rowMatchesFilters(localAgent, filters, "")).toBe(true);
- expect(rowMatchesFilters(cloudAgent, filters, "")).toBe(false);
+ expect(rowMatchesFilters(localAgent, filters)).toBe(true);
+ expect(rowMatchesFilters(cloudAgent, filters)).toBe(false);
});
it("access filter value matches the same derivation as effectiveAccessScope", () => {
diff --git a/packages/views/agents/components/agents-page.test.tsx b/packages/views/agents/components/agents-page.test.tsx
index af3b49e1e9..d353539280 100644
--- a/packages/views/agents/components/agents-page.test.tsx
+++ b/packages/views/agents/components/agents-page.test.tsx
@@ -1,6 +1,6 @@
import React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { screen } from "@testing-library/react";
+import { fireEvent, screen, within } from "@testing-library/react";
import type { Agent } from "@multica/core/types";
import type { AgentActivity } from "@multica/core/agents";
import type { SupportedLocale } from "@multica/core/i18n";
@@ -42,8 +42,6 @@ const mocks = vi.hoisted(() => ({
models: [] as string[],
access: [] as string[],
},
- search: "",
- setSearch: vi.fn(),
setScope: vi.fn(),
toggleSort: vi.fn(),
setSortField: vi.fn(),
@@ -146,12 +144,14 @@ vi.mock("@multica/core/runtimes", () => ({
}));
// View-layer children with heavy / portal deps — stub to keep the test focused
-// on the gate, not on avatars, row menus, the toolbar, or tooltip portals.
+// on the gate, not on avatars, row menus, the filter/display menus, or
+// tooltip portals.
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
vi.mock("./agent-row-actions", () => ({ AgentRowActions: () => null }));
vi.mock("./agent-list-toolbar", () => ({
- AgentListToolbar: () => <div data-testid="agent-list-toolbar" />,
- countActiveFilterDimensions: () => 0,
+ AgentListFilterMenu: () => <div data-testid="agent-list-filter" />,
+ countActiveFilterDimensions: (filters: Record<string, unknown[]>) =>
+ Object.values(filters).filter((values) => values.length > 0).length,
}));
vi.mock("../presence", () => ({ availabilityConfig: {} }));
vi.mock("@multica/ui/components/ui/skeleton", () => ({
@@ -223,12 +223,14 @@ function makeAdapter(
}
function renderPage(locale?: SupportedLocale) {
+ const adapter = makeAdapter();
renderWithI18n(
- <NavigationProvider value={makeAdapter()}>
+ <NavigationProvider value={adapter}>
<AgentsPage />
</NavigationProvider>,
{ locale },
);
+ return adapter;
}
/** Beta before Alpha in document order? */
@@ -241,6 +243,7 @@ function betaPrecedesAlpha(): boolean {
}
beforeEach(() => {
+ vi.clearAllMocks();
mocks.agents = [ALPHA, BETA];
mocks.agentsLoading = false;
mocks.runCounts = [];
@@ -251,7 +254,6 @@ beforeEach(() => {
mocks.viewState.sortField = "lastActive";
mocks.viewState.sortDirection = "desc";
mocks.viewState.hiddenColumns = ["created"];
- mocks.viewState.search = "";
mocks.viewState.filters = {
availability: [],
runtimes: [],
@@ -328,15 +330,16 @@ describe("AgentsPage listReady gate", () => {
expect(screen.getAllByTestId("skeleton").length).toBeGreaterThan(0);
});
- it("keeps the toolbar above the skeleton while the agent list loads", () => {
- // A toolbar that only mounts once rows land pushes the list down by its
- // height mid-navigation (MUL-8337).
+ it("keeps the header tools above the skeleton while the agent list loads", () => {
+ // Tools that only mount once rows land shift the page mid-navigation
+ // (MUL-8337).
mocks.agents = [];
mocks.agentsLoading = true;
renderPage();
- expect(screen.getByTestId("agent-list-toolbar")).toBeInTheDocument();
+ const header = screen.getByRole("banner");
+ expect(within(header).getByTestId("agent-list-filter")).toBeInTheDocument();
expect(screen.getAllByTestId("skeleton").length).toBeGreaterThan(0);
expect(screen.queryByText("No agents yet")).not.toBeInTheDocument();
});
@@ -355,29 +358,70 @@ describe("AgentsPage listReady gate", () => {
});
});
-describe("AgentsPage docs link", () => {
- it("points Learn more at the viewer's docs locale", () => {
+describe("AgentsPage header", () => {
+ it("titles the page with the scope and switches scope from its menu", () => {
+ renderPage();
+
+ const header = screen.getByRole("banner");
+ const title = within(header).getByRole("heading", { level: 1 });
+ expect(title).toHaveTextContent("All agents");
+ expect(within(header).queryByText(/\d/)).not.toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: /Learn more/ })).not.toBeInTheDocument();
+
+ fireEvent.click(within(title).getByRole("button"));
+ const options = screen.getAllByRole("menuitemradio");
+ expect(options.map((option) => option.textContent)).toEqual([
+ "My agents2",
+ "All agents2",
+ "Archived agents0",
+ ]);
+ fireEvent.click(options[0]!);
+ expect(mocks.viewState.setScope).toHaveBeenCalledWith("mine");
+ });
+
+ it("localizes the scope title", () => {
+ mocks.viewState.scope = "archived";
renderPage("fr");
expect(
- screen.getByRole("link", { name: "En savoir plus →" }),
- ).toHaveAttribute("href", "https://multica.ai/docs/fr/agents");
+ within(screen.getByRole("banner")).getByRole("heading", { level: 1 }),
+ ).toHaveTextContent("Agents archivés");
});
-});
-describe("AgentsPage search + model column (GitHub #9500)", () => {
- it("filters by the store's search query so it survives leaving the page", () => {
- // The query comes from the view store, not page-local state: a remount
- // (open agent → back) renders with the same query already applied.
- mocks.viewState.sortField = "name";
- mocks.viewState.search = "beta";
+ it("has no search in the header", () => {
+ renderPage();
+ expect(
+ within(screen.getByRole("banner")).queryByRole("textbox"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /search/i })).not.toBeInTheDocument();
+ });
+ it("offers Reset only while a filter narrows the list", () => {
renderPage();
+ expect(screen.queryByRole("button", { name: "Reset" })).not.toBeInTheDocument();
+ });
- expect(screen.getByText("Beta Agent")).toBeInTheDocument();
- expect(screen.queryByText("Alpha Agent")).not.toBeInTheDocument();
+ it("resets the filters", () => {
+ mocks.viewState.filters.access = ["workspace"];
+ renderPage();
+
+ fireEvent.click(screen.getByRole("button", { name: "Reset" }));
+ expect(mocks.viewState.clearFilters).toHaveBeenCalled();
});
+ it("puts display and create on the right, with create opening the new-agent flow", () => {
+ const adapter = renderPage();
+
+ const header = screen.getByRole("banner");
+ expect(
+ within(header).getByRole("button", { name: "Display settings" }),
+ ).toBeInTheDocument();
+ fireEvent.click(within(header).getByRole("button", { name: "New agent" }));
+ expect(adapter.push).toHaveBeenCalledWith("/test-workspace/agents/new");
+ });
+});
+
+describe("AgentsPage model column (GitHub #9500)", () => {
it("renders the model column by default", () => {
mocks.viewState.sortField = "name";
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index 08394a53de..552a5e8961 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import {
AlertCircle,
Bot,
@@ -8,7 +8,6 @@ import {
Plus,
} from "@multica/ui/icons";
import { useQuery } from "@tanstack/react-query";
-import { useVirtualizer } from "@tanstack/react-virtual";
import type {
Agent,
AgentRuntime,
@@ -27,7 +26,6 @@ import {
import {
type AgentListFilters,
useAgentsViewStore,
- AGENT_DEFAULT_HIDDEN_COLUMNS,
AGENT_SCOPES,
type AgentColumnKey,
type AgentsScope,
@@ -42,104 +40,38 @@ import {
} from "@multica/core/workspace/queries";
import { runtimeDisplayLabel, runtimeListOptions } from "@multica/core/runtimes";
import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import {
- LIST_GRID_BOTTOM_CLEARANCE,
- ListGrid,
- ListGridBody,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
- type ListGridSortDirection,
-} from "@multica/ui/components/ui/list-grid";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";
-import { useNavigation, useRowLink } from "../../navigation";
+import { useNavigation } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
-import { docsLocalePrefix } from "../../common/docs-locale";
import { ProviderLogo } from "../../runtimes/components/provider-logo";
import {
+ CollectionCreateButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
} from "../../layout/collection-page";
+import {
+ CollectionDisplayMenu,
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ CollectionTag,
+ type CollectionColumn,
+ type CollectionSort,
+} from "../../layout/collection-list";
import { availabilityConfig } from "../presence";
import { AgentRowActions } from "./agent-row-actions";
import {
- AgentListToolbar,
+ AgentListFilterMenu,
countActiveFilterDimensions,
} from "./agent-list-toolbar";
import { useLocale, useT } from "../../i18n";
-import { matchesPinyin } from "../../editor/extensions/pinyin-match";
-
-// Column template — single source of truth for header, rows, and skeletons.
-// Same conventions as the skills/autopilots lists (see list-grid.tsx):
-// deterministic var-width tracks, two-zone responsiveness (≥@2xl WYSIWYG
-// with min-width + horizontal-scroll escape valve; <@2xl static core set of
-// name + status, toggles don't apply).
-//
-// Agents are identity-type entities (few, avatar + persona), so rows are
-// the TWO-LINE form: avatar left, name + description right, 64px tall —
-// the documented exception to the single-line management-list rule.
-const GRID_COLS =
- "grid-cols-[0.75rem_minmax(120px,1fr)_var(--agc-status-mobile)_1.75rem_0.75rem] " +
- "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_var(--agc-status-desktop)_var(--agc-owner)_var(--agc-access)_var(--agc-runtime)_var(--agc-lastactive)_var(--agc-runs)_var(--agc-model)_var(--agc-created)_1.75rem_0.75rem]";
-
-// Two-line rows; the virtualizer's fixed-size contract.
-const ROW_HEIGHT = 64;
-
-// Single source for hideable column widths: track vars and the grid's
-// min-width derive from the same numbers.
-const COLUMN_WIDTHS: Record<AgentColumnKey, number> = {
- // Sized for the worst case "Online · 2 tasks" (~140px incl. padding);
- // idle rows show only the dot + label and leave some in-track slack.
- status: 144,
- owner: 144,
- // Fits the longest label "Specific people" (~120px incl. padding).
- access: 132,
- runtime: 144,
- lastActive: 120,
- runs: 88,
- // Shown by default; wide enough for common ids like "claude-sonnet-4-5".
- model: 160,
- created: 104,
-};
-
-// Fixed tracks (edges 12+12, checkbox 16, name min 200, kebab 28) plus the
-// 11 gap-x-3 gaps between the wide template's 12 tracks (zero-width tracks
-// still carry gaps).
-const FIXED_TRACKS_WIDTH = 268 + 11 * 12;
-
-function columnTrackVars(
- isVisible: (key: AgentColumnKey) => boolean,
-): React.CSSProperties {
- const width = (key: AgentColumnKey) =>
- isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";
- const minWidth =
- FIXED_TRACKS_WIDTH +
- (Object.keys(COLUMN_WIDTHS) as AgentColumnKey[]).reduce(
- (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),
- 0,
- );
- return {
- "--agc-status-mobile": isVisible("status") ? "96px" : "0px",
- "--agc-status-desktop": width("status"),
- "--agc-owner": width("owner"),
- "--agc-access": width("access"),
- "--agc-runtime": width("runtime"),
- "--agc-lastactive": width("lastActive"),
- "--agc-runs": width("runs"),
- "--agc-model": width("model"),
- "--agc-created": width("created"),
- "--agc-minw": `${minWidth}px`,
- } as React.CSSProperties;
-}
export interface AgentListRow {
agent: Agent;
@@ -166,17 +98,6 @@ function lastActiveDaysAgo(activity: AgentActivity | null): number | null {
return null;
}
-function matchesAgentSearch(row: AgentListRow, query: string): boolean {
- if (!query) return true;
- const { agent } = row;
- return (
- agent.name.toLowerCase().includes(query) ||
- matchesPinyin(agent.name, query) ||
- (agent.description?.toLowerCase().includes(query) ?? false) ||
- (agent.description ? matchesPinyin(agent.description, query) : false)
- );
-}
-
/**
* Pure row-filter predicate: returns true if the row matches all active
* filter dimensions. Empty filter arrays are inactive (the row passes). The
@@ -187,9 +108,7 @@ function matchesAgentSearch(row: AgentListRow, query: string): boolean {
export function rowMatchesFilters(
row: AgentListRow,
filters: AgentListFilters,
- query: string,
): boolean {
- if (!matchesAgentSearch(row, query.trim().toLowerCase())) return false;
if (
filters.availability.length > 0 &&
(!row.presence || !filters.availability.includes(row.presence.availability))
@@ -249,64 +168,31 @@ export interface AgentsPageProps {
// Page header
-function PageHeaderBar({
- totalCount,
- onCreate,
-}: {
- totalCount: number;
- onCreate: () => void;
-}) {
- const { t, i18n } = useT("agents");
- return (
- <CollectionPageHeader
- icon={Bot}
- title={t(($) => $.page.title)}
- count={totalCount}
- learnMore={{
- href: `https://multica.ai/docs${docsLocalePrefix(i18n.language)}/agents`,
- label: t(($) => $.page.learn_more),
- }}
- actions={
- <CollectionPageHeaderAction
- icon={Plus}
- label={t(($) => $.page.new_agent)}
- onClick={onCreate}
- />
- }
- />
- );
-}
-
function ListError({
- onCreate,
listError,
onRetry,
}: {
- onCreate: () => void;
listError: unknown;
onRetry: () => void;
}) {
const { t } = useT("agents");
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <PageHeaderBar totalCount={0} onCreate={onCreate} />
- <CollectionPageState
- role="alert"
- tone="destructive"
- icon={AlertCircle}
- title={t(($) => $.page.list_load_failed)}
- description={
- listError instanceof Error
- ? listError.message
- : t(($) => $.page.list_load_failed_default)
- }
- actions={
- <Button type="button" variant="outline" size="sm" onClick={onRetry}>
- {t(($) => $.page.try_again)}
- </Button>
- }
- />
- </div>
+ <CollectionPageState
+ role="alert"
+ tone="destructive"
+ icon={AlertCircle}
+ title={t(($) => $.page.list_load_failed)}
+ description={
+ listError instanceof Error
+ ? listError.message
+ : t(($) => $.page.list_load_failed_default)
+ }
+ actions={
+ <Button type="button" variant="outline" size="sm" onClick={onRetry}>
+ {t(($) => $.page.try_again)}
+ </Button>
+ }
+ />
);
}
@@ -329,86 +215,39 @@ function EmptyState({ onCreate }: { onCreate: () => void }) {
// Cells
-function CheckboxCell({
- checked,
- onToggle,
-}: {
- checked: boolean;
- onToggle: () => void;
-}) {
- return (
- <ListGridCell className="hidden justify-center px-0 @2xl:flex">
- <button
- type="button"
- aria-pressed={checked}
- onClick={(e) => {
- e.stopPropagation();
- onToggle();
- }}
- className={`-m-1.5 flex items-center p-1.5 ${
- checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"
- }`}
- >
- <Checkbox
- checked={checked}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
- </ListGridCell>
- );
-}
-
-// Two-line identity cell: avatar left, name + description right. The
-// documented exception to the single-line rule — agents are few and
-// identity-rich, so this is the "team roster" form (GitHub org members,
-// Slack member list).
function NameCell({ row }: { row: AgentListRow }) {
const { t } = useT("agents");
const { agent, isOwnedByMe } = row;
const isArchived = !!agent.archived_at;
const isPrivate = agent.visibility === "private";
return (
- <ListGridCell className="gap-3">
- <ActorAvatar
- actorType="agent"
- actorId={agent.id}
- size="lg"
- className={`shrink-0 ${isArchived ? "opacity-50 grayscale" : ""}`}
- showStatusDot
- />
- <div className="min-w-0 flex-1">
- <div className="flex min-w-0 items-center gap-2">
- <span
- className={`min-w-0 truncate text-body font-medium ${
- isArchived ? "text-muted-foreground" : ""
- }`}
- >
- {agent.name}
- </span>
+ <CollectionNameCell
+ icon={
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size="sm"
+ className={`shrink-0 ${isArchived ? "opacity-50 grayscale" : ""}`}
+ showStatusDot
+ />
+ }
+ title={agent.name}
+ muted={isArchived}
+ badges={
+ <>
{isPrivate && !isArchived && (
<Tooltip>
<TooltipTrigger
- render={
- <Lock className="h-3 w-3 shrink-0 text-faint-foreground" />
- }
+ render={<Lock className="h-3 w-3 shrink-0 text-faint-foreground" />}
/>
<TooltipContent>{VISIBILITY_TOOLTIP.private}</TooltipContent>
</Tooltip>
)}
- {isOwnedByMe && (
- <span className="shrink-0 rounded-xs bg-muted px-1 text-micro font-medium text-muted-foreground">
- {t(($) => $.row.you)}
- </span>
- )}
- </div>
- {agent.description ? (
- <div className="mt-0.5 truncate text-caption text-muted-foreground">
- {agent.description}
- </div>
- ) : null}
- </div>
- </ListGridCell>
+ {isOwnedByMe && <CollectionTag>{t(($) => $.row.you)}</CollectionTag>}
+ </>
+ }
+ description={agent.description || undefined}
+ />
);
}
@@ -417,38 +256,24 @@ function NameCell({ row }: { row: AgentListRow }) {
function StatusCell({ row }: { row: AgentListRow }) {
const { t } = useT("agents");
const { agent, presence } = row;
- if (agent.archived_at) {
- return (
- <ListGridCell>
- <span className="text-caption text-muted-foreground">
- {t(($) => $.row.archived)}
- </span>
- </ListGridCell>
- );
- }
+ if (agent.archived_at) return <span>{t(($) => $.row.archived)}</span>;
if (!isAgentRuntimeBound(agent)) {
return (
- <ListGridCell className="gap-1.5">
+ <>
<AlertCircle className="size-3.5 shrink-0 text-amber-500" />
- <span className="truncate text-caption text-amber-600 dark:text-amber-400">
+ <span className="truncate text-amber-600 dark:text-amber-400">
{t(($) => $.row.needs_runtime)}
</span>
- </ListGridCell>
- );
- }
- if (!presence) {
- return (
- <ListGridCell>
- <span className="text-caption text-faint-foreground">—</span>
- </ListGridCell>
+ </>
);
}
+ if (!presence) return <CollectionEmptyValue />;
const visual = availabilityConfig[presence.availability];
const active = presence.runningCount + presence.queuedCount;
return (
- <ListGridCell className="gap-1.5">
+ <>
<span className={`size-1.5 shrink-0 rounded-full ${visual.dotClass}`} />
- <span className={`truncate text-caption ${visual.textClass}`}>
+ <span className={`truncate ${visual.textClass}`}>
{t(($) => $.availability[presence.availability])}
{active > 0 && (
<span className="text-muted-foreground">
@@ -457,7 +282,7 @@ function StatusCell({ row }: { row: AgentListRow }) {
</span>
)}
</span>
- </ListGridCell>
+ </>
);
}
@@ -466,20 +291,14 @@ function StatusCell({ row }: { row: AgentListRow }) {
// the column is "Owner", not "Created by".
function OwnerCell({ row }: { row: AgentListRow }) {
const { agent, owner } = row;
- if (!agent.owner_id) {
- return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="text-caption text-faint-foreground">—</span>
- </ListGridCell>
- );
- }
+ if (!agent.owner_id) return <CollectionEmptyValue />;
return (
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
+ <>
<ActorAvatar actorType="member" actorId={agent.owner_id} size="sm" />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
+ <span className="min-w-0 truncate">
{owner?.name ?? agent.owner_id.slice(0, 8)}
</span>
- </ListGridCell>
+ </>
);
}
@@ -503,261 +322,49 @@ export function AccessCell({ row }: { row: AgentListRow }) {
? $.access.scope_labels.specific_people
: $.access.scope_labels.owner_only,
);
- return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {label}
- </span>
- </ListGridCell>
- );
+ return <span className="min-w-0 truncate">{label}</span>;
}
function RuntimeCell({ row }: { row: AgentListRow }) {
const { t } = useT("agents");
if (!isAgentRuntimeBound(row.agent)) {
return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="truncate text-caption text-amber-600 dark:text-amber-400">
- {t(($) => $.row.needs_runtime)}
- </span>
- </ListGridCell>
+ <span className="truncate text-amber-600 dark:text-amber-400">
+ {t(($) => $.row.needs_runtime)}
+ </span>
);
}
const runtime = row.runtime;
+ if (!runtime) return <CollectionEmptyValue />;
+ // Provider mark before the label: scanning this column for "which of these
+ // run on Codex" is a shape match, not a read.
return (
- <ListGridCell className="hidden @2xl:flex">
- {runtime ? (
- // Provider mark before the label: scanning this column for "which of
- // these run on Codex" is a shape match, not a read.
- <span className="inline-flex min-w-0 items-center gap-1.5">
- <ProviderLogo
- provider={runtime.provider}
- className="h-3.5 w-3.5 shrink-0"
- />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {runtimeDisplayLabel(runtime)}
- </span>
- </span>
- ) : (
- <span className="text-caption text-faint-foreground">—</span>
- )}
- </ListGridCell>
+ <>
+ <ProviderLogo provider={runtime.provider} className="h-3.5 w-3.5 shrink-0" />
+ <span className="min-w-0 truncate">{runtimeDisplayLabel(runtime)}</span>
+ </>
);
}
function LastActiveCell({ row }: { row: AgentListRow }) {
const { t } = useT("agents");
const days = row.lastActiveDays;
+ if (days === null) {
+ return (
+ <span className="truncate">
+ {row.agent.archived_at ? "—" : t(($) => $.last_active.none)}
+ </span>
+ );
+ }
return (
- <ListGridCell className="hidden @2xl:flex">
- {days === null ? (
- <span className="truncate text-caption text-muted-foreground">
- {row.agent.archived_at ? "—" : t(($) => $.last_active.none)}
- </span>
- ) : (
- <span className="whitespace-nowrap text-caption tabular-nums text-muted-foreground">
- {days === 0
- ? t(($) => $.last_active.today)
- : t(($) => $.last_active.days_ago, { count: days })}
- </span>
- )}
- </ListGridCell>
- );
-}
-
-// Header row + skeleton
-
-function AgentListHeader({
- sortField,
- sortDirection,
- onSort,
- allSelected,
- someSelected,
- onToggleAll,
- isColVisible,
-}: {
- sortField: AgentSortField;
- sortDirection: ListGridSortDirection;
- onSort: (field: AgentSortField) => void;
- allSelected: boolean;
- someSelected: boolean;
- onToggleAll: () => void;
- isColVisible: (key: AgentColumnKey) => boolean;
-}) {
- const { t } = useT("agents");
- const sorted = (field: AgentSortField) =>
- sortField === field ? sortDirection : false;
- const anySelected = allSelected || someSelected;
- return (
- <ListGridHeader>
- <div className="hidden items-center justify-center @2xl:flex">
- <button
- type="button"
- aria-pressed={allSelected}
- onClick={onToggleAll}
- className={`-m-1.5 flex items-center p-1.5 ${
- anySelected
- ? ""
- : "opacity-0 transition-opacity group-hover/header:opacity-100"
- }`}
- >
- <Checkbox
- checked={allSelected}
- indeterminate={someSelected && !allSelected}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
- </div>
- <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>
- {t(($) => $.columns.agent)}
- </ListGridHeaderCell>
- {isColVisible("status") ? (
- <ListGridHeaderCell>{t(($) => $.columns.status)}</ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="px-0" />
- )}
- {isColVisible("owner") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.columns.owner)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("access") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.columns.access)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("runtime") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.columns.runtime)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("lastActive") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("lastActive")}
- onSort={() => onSort("lastActive")}
- >
- {t(($) => $.columns.last_active)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("runs") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- align="right"
- sorted={sorted("runs")}
- onSort={() => onSort("runs")}
- >
- {t(($) => $.columns.runs)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("model") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.columns.model)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("created")}
- onSort={() => onSort("created")}
- >
- {t(($) => $.columns.created)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- <span aria-hidden="true" />
- </ListGridHeader>
- );
-}
-
-function LoadingSkeleton() {
- return (
- <ListGrid
- className={GRID_COLS}
- style={columnTrackVars(
- (key) => !AGENT_DEFAULT_HIDDEN_COLUMNS.includes(key),
- )}
- >
- <ListGridHeader>
- <span aria-hidden="true" className="hidden @2xl:inline" />
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-10" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridHeader>
- {Array.from({ length: 5 }).map((_, i) => (
- <ListGridRow key={i} className="h-16 hover:bg-transparent">
- <span aria-hidden="true" className="hidden @2xl:inline" />
- <ListGridCell className="gap-3">
- <Skeleton className="size-8 rounded-full" />
- <div className="min-w-0 flex-1 space-y-1.5">
- <Skeleton className="h-3.5 w-32 max-w-full" />
- <Skeleton className="h-3 w-48 max-w-full" />
- </div>
- </ListGridCell>
- <ListGridCell>
- <Skeleton className="h-3 w-16" />
- </ListGridCell>
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
- <Skeleton className="size-5 rounded-full" />
- <Skeleton className="h-3 w-12" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-16" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-12" />
- </ListGridCell>
- <ListGridCell className="hidden justify-end @2xl:flex">
- <Skeleton className="h-3 w-8" />
- </ListGridCell>
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridRow>
- ))}
- </ListGrid>
+ <span className="tabular-nums">
+ {days === 0
+ ? t(($) => $.last_active.today)
+ : t(($) => $.last_active.days_ago, { count: days })}
+ </span>
);
}
-// Batch toolbar — archive (with confirm; archiving cancels active tasks) and
// Page
export function AgentsPage(_props: AgentsPageProps = {}) {
@@ -766,7 +373,6 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
- const rowLink = useRowLink();
const currentUser = useAuthStore((s) => s.user);
const {
@@ -790,11 +396,6 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(
new Set(),
);
- // Search lives in the view store (session-only) so it survives opening an
- // agent and navigating back to the list.
- const search = useAgentsViewStore((s) => s.search);
- const setSearch = useAgentsViewStore((s) => s.setSearch);
-
const rawScope = useAgentsViewStore((s) => s.scope);
const scope = AGENT_SCOPES.includes(rawScope) ? rawScope : "mine";
const setScope = useAgentsViewStore((s) => s.setScope);
@@ -809,17 +410,6 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
const toggleFilter = useAgentsViewStore((s) => s.toggleFilter);
const clearFilters = useAgentsViewStore((s) => s.clearFilters);
- const isColVisible = (key: AgentColumnKey) => !hiddenColumns.includes(key);
-
- const toggleSelected = (id: string) => {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- };
-
const runtimesById = useMemo(() => {
const m = new Map<string, AgentRuntime>();
for (const r of runtimes) m.set(r.id, r);
@@ -862,8 +452,8 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
}, [agents, currentUser]);
// Rows within the current scope, unfiltered, fully assembled — the
- // toolbar's option lists and the "n / total" denominator derive from
- // this; cells never pull their own queries.
+ // filter menu's option lists derive from this; cells never pull their
+ // own queries.
const scopeRows = useMemo<AgentListRow[]>(() => {
const inScope = agents.filter((a) => {
if (scope === "archived") return !!a.archived_at;
@@ -900,9 +490,9 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
isWorkspaceAdmin,
]);
- // Visible rows: local search + filters, then sort.
+ // Visible rows: filters, then sort.
const rows = useMemo<AgentListRow[]>(() => {
- const filtered = scopeRows.filter((row) => rowMatchesFilters(row, filters, search));
+ const filtered = scopeRows.filter((row) => rowMatchesFilters(row, filters));
const dir = sortDirection === "asc" ? 1 : -1;
filtered.sort((a, b) => {
@@ -931,41 +521,15 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
);
});
return filtered;
- }, [scopeRows, search, filters, sortField, sortDirection]);
+ }, [scopeRows, filters, sortField, sortDirection]);
const noMatchText = useMemo(() => {
- const query = search.trim();
- if (query) {
- if (scope === "archived") {
- return t(($) => $.no_matches.search_archived, { query });
- }
- if (countActiveFilterDimensions(filters) > 0) {
- return t(($) => $.no_matches.search_active_filtered, { query });
- }
- return t(($) => $.no_matches.search_active, { query });
- }
if (scope === "archived") return t(($) => $.no_matches.no_archived);
if (countActiveFilterDimensions(filters) > 0) {
return t(($) => $.no_matches.no_filter_match);
}
return t(($) => $.no_matches.title);
- }, [filters, scope, search, t]);
-
- // Row virtualization — headless math, offsets as padding on the rows
- // wrapper, fixed-height rows. The scroll element is the SINGLE outer
- // scroller (both axes): splitting horizontal scrolling (wrapper) from
- // vertical scrolling (an inner element) connected by an h-full
- // percentage bridge caused a non-converging layout loop (flickering
- // double scrollbars) and clipped the last row under the horizontal
- // scrollbar. The sticky header pins inside this scroller; the vertical
- // scrollbar spans the full pane height (Linear's structure).
- const listScrollRef = useRef<HTMLDivElement | null>(null);
- const rowVirtualizer = useVirtualizer({
- count: rows.length,
- getScrollElement: () => listScrollRef.current,
- estimateSize: () => ROW_HEIGHT,
- overscan: 10,
- });
+ }, [filters, scope, t]);
// Straight to the manual form: a duplicate already has every field decided,
// so the method chooser would be a step with nothing to choose.
@@ -976,36 +540,106 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
);
const selectedRows = rows.filter((row) => selectedIds.has(row.agent.id));
- const allSelected = rows.length > 0 && selectedRows.length === rows.length;
- const someSelected = selectedRows.length > 0 && !allSelected;
- const handleToggleAll = () => {
- setSelectedIds(
- allSelected ? new Set() : new Set(rows.map((r) => r.agent.id)),
- );
- };
- const virtualItems = rowVirtualizer.getVirtualItems();
- const firstVirtual = virtualItems[0];
- const lastVirtual = virtualItems[virtualItems.length - 1];
- const virtualPadding = {
- top: firstVirtual ? firstVirtual.start : 0,
- bottom: lastVirtual
- ? rowVirtualizer.getTotalSize() - lastVirtual.end
- : 0,
- };
+ const columns = useMemo<CollectionColumn<AgentListRow>[]>(
+ () => [
+ {
+ key: "name",
+ header: t(($) => $.columns.agent),
+ sortKey: "name",
+ cell: (row) => <NameCell row={row} />,
+ },
+ {
+ key: "status",
+ // Sized for the worst case "Online · 2 tasks".
+ header: t(($) => $.columns.status),
+ width: 132,
+ core: true,
+ hideable: true,
+ cell: (row) => <StatusCell row={row} />,
+ },
+ {
+ key: "owner",
+ header: t(($) => $.columns.owner),
+ width: 132,
+ hideable: true,
+ cell: (row) => <OwnerCell row={row} />,
+ },
+ {
+ key: "access",
+ header: t(($) => $.columns.access),
+ width: 120,
+ hideable: true,
+ cell: (row) => <AccessCell row={row} />,
+ },
+ {
+ key: "runtime",
+ header: t(($) => $.columns.runtime),
+ width: 152,
+ hideable: true,
+ cell: (row) => <RuntimeCell row={row} />,
+ },
+ {
+ key: "model",
+ header: t(($) => $.columns.model),
+ width: 140,
+ hideable: true,
+ cell: (row) => (
+ <TruncatedTooltip content={row.agent.model || undefined}>
+ <span className="min-w-0 truncate">{row.agent.model || "—"}</span>
+ </TruncatedTooltip>
+ ),
+ },
+ {
+ key: "lastActive",
+ header: t(($) => $.columns.last_active),
+ width: 104,
+ sortKey: "lastActive",
+ hideable: true,
+ cell: (row) => <LastActiveCell row={row} />,
+ },
+ {
+ key: "runs",
+ header: t(($) => $.columns.runs),
+ width: 48,
+ align: "end",
+ sortKey: "runs",
+ hideable: true,
+ className: "font-mono tabular-nums",
+ cell: (row) => row.runCount.toLocaleString(locale),
+ },
+ {
+ key: "created",
+ header: t(($) => $.columns.created),
+ width: 104,
+ sortKey: "created",
+ hideable: true,
+ cell: (row) => (
+ <span className="tabular-nums">
+ {new Date(row.agent.created_at).toLocaleDateString(locale)}
+ </span>
+ ),
+ },
+ ],
+ [t, locale],
+ );
- if (listError) {
- return (
- <ListError
- onCreate={() => navigation.push(paths.newAgent())}
- listError={listError}
- onRetry={() => refetchList()}
- />
- );
- }
+ const sort: CollectionSort = {
+ field: sortField,
+ direction: sortDirection,
+ onToggle: (field) => handleSort(field as AgentSortField),
+ onFieldChange: (field) => handleSortFieldSelect(field as AgentSortField),
+ onDirectionChange: setSortDirection,
+ };
- const totalCount = agents.filter((a) => !a.archived_at).length;
- const showEmpty = !isLoading && agents.length === 0;
+ const showEmpty = !listError && !isLoading && agents.length === 0;
+ const hasNarrowing = countActiveFilterDimensions(filters) > 0;
+ const scopeTitles: Record<AgentsScope, string> = {
+ mine: t(($) => $.page.scope_title.mine),
+ all: t(($) => $.page.scope_title.all),
+ archived: t(($) => $.page.scope_title.archived),
+ };
+ const openCreate = () => navigation.push(paths.newAgent());
// The active sort field / availability filter reads columns that arrive in
// separate queries from the main agent list (activity → lastActiveDays,
@@ -1032,163 +666,75 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
// relative: positioning anchor for the batch toolbar (page-centered,
// not viewport-centered).
<div className="relative flex flex-1 min-h-0 flex-col">
- <PageHeaderBar
- totalCount={totalCount}
- onCreate={() => navigation.push(paths.newAgent())}
+ <CollectionPageHeader
+ icon={Bot}
+ title={scopeTitles[scope]}
+ menu={
+ <CollectionScopeItems
+ value={scope}
+ onChange={setScope}
+ options={AGENT_SCOPES.map((value) => ({
+ value,
+ label: scopeTitles[value],
+ count: scopeCounts[value],
+ }))}
+ />
+ }
+ tools={
+ <>
+ <AgentListFilterMenu
+ filters={filters}
+ onToggleFilter={toggleFilter}
+ allRows={scopeRows}
+ members={members}
+ />
+ {hasNarrowing ? <CollectionResetButton onClick={clearFilters} /> : null}
+ </>
+ }
+ actions={
+ <>
+ <CollectionDisplayMenu
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ onToggleColumn={(key) => toggleColumn(key as AgentColumnKey)}
+ sort={sort}
+ />
+ <CollectionCreateButton
+ label={t(($) => $.page.new_agent)}
+ onClick={openCreate}
+ />
+ </>
+ }
/>
- {showEmpty ? (
+ {listError ? (
+ <ListError listError={listError} onRetry={() => refetchList()} />
+ ) : showEmpty ? (
<div className="flex flex-1 items-center justify-center">
- <EmptyState onCreate={() => navigation.push(paths.newAgent())} />
+ <EmptyState onCreate={openCreate} />
</div>
) : (
- <>
- {/* Mounted through loading so the rows don't drop by a toolbar's
- height when the list lands. */}
- <AgentListToolbar
- scope={scope}
- onScopeChange={setScope}
- scopeCounts={scopeCounts}
- search={search}
- onSearchChange={setSearch}
- filters={filters}
- onToggleFilter={toggleFilter}
- onClearFilters={clearFilters}
- sortField={sortField}
- sortDirection={sortDirection}
- onSortFieldChange={handleSortFieldSelect}
- onSortDirectionChange={setSortDirection}
- hiddenColumns={hiddenColumns}
- onToggleColumn={toggleColumn}
- allRows={scopeRows}
- members={members}
- visibleCount={rows.length}
- />
- {isLoading || !listReady ? (
- <div className="flex-1 overflow-y-auto @container">
- <LoadingSkeleton />
- </div>
- ) : (
- <div
- ref={listScrollRef}
- className="min-h-0 flex-1 overflow-auto @container"
- >
- <ListGrid
- className={`${GRID_COLS} @2xl:min-w-[var(--agc-minw)]`}
- style={columnTrackVars(isColVisible)}
- >
- <AgentListHeader
- sortField={sortField}
- sortDirection={sortDirection}
- onSort={handleSort}
- allSelected={allSelected}
- someSelected={someSelected}
- onToggleAll={handleToggleAll}
- isColVisible={isColVisible}
- />
- <ListGridBody
- style={{
- paddingTop: virtualPadding.top,
- paddingBottom:
- virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,
- }}
- >
- {rows.length === 0 && (
- <div className="col-span-full py-16 text-center text-body text-muted-foreground">
- {noMatchText}
- </div>
- )}
- {virtualItems.map((vi) => {
- const row = rows[vi.index];
- if (!row) return null;
- return (
- <ListGridRow
- key={row.agent.id}
- className={`h-16 cursor-pointer ${
- selectedIds.has(row.agent.id) ? "bg-accent/30" : ""
- }`}
- {...rowLink(paths.agentDetail(row.agent.id), row.agent.name)}
- >
- <CheckboxCell
- checked={selectedIds.has(row.agent.id)}
- onToggle={() => toggleSelected(row.agent.id)}
- />
- <NameCell row={row} />
- {isColVisible("status") ? (
- <StatusCell row={row} />
- ) : (
- <ListGridCell className="px-0" />
- )}
- {isColVisible("owner") ? (
- <OwnerCell row={row} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("access") ? (
- <AccessCell row={row} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("runtime") ? (
- <RuntimeCell row={row} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("lastActive") ? (
- <LastActiveCell row={row} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("runs") ? (
- <ListGridCell className="hidden justify-end font-mono text-caption tabular-nums text-muted-foreground @2xl:flex">
- {row.runCount.toLocaleString(locale)}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("model") ? (
- <ListGridCell className="hidden @2xl:flex">
- <TruncatedTooltip content={row.agent.model || undefined}>
- <span
- className="min-w-0 truncate text-caption text-muted-foreground"
- >
- {row.agent.model || "—"}
- </span>
- </TruncatedTooltip>
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">
- {new Date(
- row.agent.created_at,
- ).toLocaleDateString(locale)}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- <ListGridCell className="justify-end px-0">
- <span
- onClick={(e) => e.stopPropagation()}
- className="flex items-center"
- >
- <AgentRowActions
- agent={row.agent}
- presence={row.presence}
- canManage={row.canManage}
- duplicateHref={duplicateHref(row.agent)}
- />
- </span>
- </ListGridCell>
- </ListGridRow>
- );
- })}
- </ListGridBody>
- </ListGrid>
- </div>
+ <CollectionList
+ label={scopeTitles[scope]}
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ rows={rows}
+ loading={isLoading || !listReady}
+ getRowId={(row) => row.agent.id}
+ getRowHref={(row) => paths.agentDetail(row.agent.id)}
+ getRowTitle={(row) => row.agent.name}
+ rowMenu={(row) => (
+ <AgentRowActions
+ agent={row.agent}
+ presence={row.presence}
+ canManage={row.canManage}
+ duplicateHref={duplicateHref(row.agent)}
+ />
)}
- </>
+ sort={sort}
+ selection={{ selectedIds, onChange: setSelectedIds }}
+ empty={noMatchText}
+ />
)}
<AgentBatchToolbar
diff --git a/packages/views/agents/components/inspector/use-execution-controls.ts b/packages/views/agents/components/inspector/use-execution-controls.ts
new file mode 100644
index 0000000000..2d587a7473
--- /dev/null
+++ b/packages/views/agents/components/inspector/use-execution-controls.ts
@@ -0,0 +1,97 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import {
+ isRuntimeUsableForUser,
+ runtimeModelsOptions,
+} from "@multica/core/runtimes";
+import { buildModelChangeUpdate, type ModelCatalog } from "./model-change-cleanup";
+
+/**
+ * Runtime and model editing shared by the properties panel and the General
+ * settings form, so both write the same PATCH for the same change.
+ */
+export function useExecutionControls({
+ agent,
+ runtime,
+ runtimes,
+ currentUserId,
+ update,
+}: {
+ agent: Agent;
+ runtime: AgentRuntime | null;
+ runtimes: AgentRuntime[];
+ currentUserId: string | null;
+ update: (data: Record<string, unknown>) => Promise<void>;
+}) {
+ // A Qoder agent is bound to an agent in Qoder Cloud Agents, and the model lives there. Moving
+ // between Qoder and any other runtime would need a different configuration
+ // the server either rejects or the bridge refuses, so neither direction is
+ // offered.
+ const qoderRuntime = runtime?.provider === "qoder_cloud";
+ const isOnline = runtime?.status === "online";
+ const canReadRuntime =
+ runtime != null && isRuntimeUsableForUser(runtime, currentUserId);
+ const canDiscoverRuntimeModels = isOnline && canReadRuntime && !qoderRuntime;
+ const runtimeOptions = useMemo(
+ () =>
+ qoderRuntime
+ ? runtimes
+ : runtimes.filter((r) => r.provider !== "qoder_cloud"),
+ [qoderRuntime, runtimes],
+ );
+
+ // Same query the Thinking / Speed fields already use, so switching model
+ // costs no extra request. `null` = not authoritative (offline runtime, still
+ // loading, or discovery failed) and must not trigger any clearing.
+ const modelsQuery = useQuery(
+ runtimeModelsOptions(canDiscoverRuntimeModels ? agent.runtime_id : null),
+ );
+ const modelCatalog = useMemo<ModelCatalog>(
+ () =>
+ modelsQuery.isSuccess
+ ? modelsQuery.data.supported
+ ? modelsQuery.data.models
+ : []
+ : null,
+ [modelsQuery.data, modelsQuery.isSuccess],
+ );
+
+ const changeModel = useCallback(
+ (model: string) =>
+ update(
+ buildModelChangeUpdate({
+ provider: runtime?.provider ?? "",
+ model,
+ thinkingLevel: agent.thinking_level ?? "",
+ serviceTier: agent.service_tier ?? "",
+ catalog: modelCatalog,
+ }),
+ ),
+ [agent.service_tier, agent.thinking_level, modelCatalog, runtime?.provider, update],
+ );
+
+ // Model, thinking level, and service tier are runtime/model native. Clear
+ // them together so the new runtime resolves its own defaults instead of
+ // inheriting incompatible tokens.
+ const changeRuntime = useCallback(
+ (runtimeId: string) =>
+ update({
+ runtime_id: runtimeId,
+ model: "",
+ thinking_level: "",
+ service_tier: "",
+ }),
+ [update],
+ );
+
+ return {
+ qoderRuntime,
+ canDiscoverRuntimeModels,
+ runtimeOptions,
+ changeModel,
+ changeRuntime,
+ };
+}
diff --git a/packages/views/agents/components/tabs/activity-tab.render.test.tsx b/packages/views/agents/components/tabs/activity-tab.render.test.tsx
index 240f4c94d7..077b828238 100644
--- a/packages/views/agents/components/tabs/activity-tab.render.test.tsx
+++ b/packages/views/agents/components/tabs/activity-tab.render.test.tsx
@@ -56,7 +56,7 @@ vi.mock("@multica/core/agents", async (importOriginal) => {
};
});
-import { ActivityTab, AgentPerformanceSummary } from "./activity-tab";
+import { AgentPerformanceSummary, AgentWorkSections } from "./activity-tab";
const baseAgent = {
id: "agent-1",
@@ -65,7 +65,7 @@ const baseAgent = {
const EMPTY_RECENT = "This agent hasn't completed anything yet.";
-function renderTab(performance = false) {
+function renderTab(performance = false, onViewAll = vi.fn()) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
@@ -84,7 +84,7 @@ function renderTab(performance = false) {
<QueryClientProvider client={queryClient}>
<WorkspaceSlugProvider slug="acme">
{performance && <AgentPerformanceSummary agent={baseAgent} />}
- <ActivityTab agent={baseAgent} showPerformance={performance} />
+ <AgentWorkSections agent={baseAgent} onViewAll={onViewAll} />
</WorkspaceSlugProvider>
</QueryClientProvider>
</NavigationProvider>
@@ -98,7 +98,7 @@ beforeEach(() => {
});
describe("agent outcome presentation", () => {
- it("uses completed and failed outcomes in both summaries and shows cancellations separately", () => {
+ it("uses completed and failed outcomes for success and shows cancellations separately", () => {
activityRef.current = [{
agent_id: "agent-1",
bucket_at: new Date().toISOString(),
@@ -109,8 +109,7 @@ describe("agent outcome presentation", () => {
}];
renderTab(true);
expect(screen.getByText("50%")).toBeInTheDocument();
- expect(screen.getByText("50% success")).toBeInTheDocument();
- expect(screen.getAllByText("8 cancelled")).toHaveLength(2);
+ expect(screen.getByText("8 cancelled")).toBeInTheDocument();
expect(screen.queryByText("90%")).not.toBeInTheDocument();
});
@@ -131,7 +130,7 @@ describe("agent outcome presentation", () => {
});
});
-describe("ActivityTab Recent work loading state", () => {
+describe("AgentWorkSections Recent work loading state", () => {
it("shows a skeleton, not the empty state, while the task list is loading", () => {
// Never-resolving queryFn keeps the per-agent task query pending, which is
// exactly the first-paint window the skeleton is meant to cover.
@@ -153,7 +152,7 @@ describe("ActivityTab Recent work loading state", () => {
});
-describe("ActivityTab server pagination", () => {
+describe("AgentWorkSections server pagination", () => {
it("requests older history only on demand, disables duplicate fetches, and retries failures", async () => {
let finish: (value: unknown) => void = () => {};
const query = vi.fn()
@@ -203,7 +202,7 @@ function historyTask(index: number): AgentTask {
};
}
-describe("ActivityTab loaded history rows", () => {
+describe("AgentWorkSections loaded history rows", () => {
it("reveals cached rows before requesting older history and deduplicates overlapping pages", async () => {
const tasks = Array.from({ length: 31 }, (_, i) => historyTask(i));
const query = vi.fn()
@@ -248,50 +247,39 @@ describe("ActivityTab loaded history rows", () => {
});
});
-// A loaded page is not the total history. Keep the denominator unknown until
-// the server reports that the last page has been reached.
-describe("ActivityTab history completeness", () => {
- it.each([
- { nextCursor: "older", subtitle: "10 latest runs" },
- { nextCursor: null, subtitle: "10 of 200 runs" },
- ])("shows '$subtitle' for a 200-row page with cursor $nextCursor", async ({ nextCursor, subtitle }) => {
+// The Recent work count is the 7-day run total from the activity window, not
+// the number of history rows loaded so far.
+describe("AgentWorkSections section counts", () => {
+ it("counts this week's runs from the activity window, whatever history has loaded", async () => {
+ activityRef.current = [
+ { agent_id: "agent-1", bucket_at: new Date().toISOString(), task_count: 38,
+ failed_count: 2, completed_count: 36, cancelled_count: 0 },
+ { agent_id: "agent-1", bucket_at: new Date(Date.now() - 20 * 86_400_000).toISOString(),
+ task_count: 90, failed_count: 0, completed_count: 90, cancelled_count: 0 },
+ ];
agentTasksRef.current = () => Promise.resolve({
tasks: Array.from({ length: 200 }, (_, i) => historyTask(i)),
- nextCursor,
+ nextCursor: "older",
});
renderTab();
- expect(await screen.findByText(subtitle)).toBeInTheDocument();
- if (nextCursor) {
- expect(screen.queryByText("10 of 200 runs")).not.toBeInTheDocument();
- }
+ await screen.findByTestId("task-0");
+ expect(screen.getByText("38 this week")).toBeInTheDocument();
expect(screen.getAllByTestId(/^task-/)).toHaveLength(10);
});
- it.each([
- { nextCursor: "oldest", subtitle: "50 latest runs" },
- { nextCursor: null, subtitle: "50 of 220 runs" },
- ])("shows '$subtitle' after loading more history with cursor $nextCursor", async ({ nextCursor, subtitle }) => {
- const query = vi.fn()
- .mockResolvedValueOnce({
- tasks: Array.from({ length: 20 }, (_, i) => historyTask(i)),
- nextCursor: "older",
- })
- .mockResolvedValueOnce({
- tasks: Array.from({ length: 200 }, (_, i) => historyTask(i + 20)),
- nextCursor,
- });
- agentTasksRef.current = query;
+ it("shows no Now count and a quiet line while nothing is running", async () => {
+ agentTasksRef.current = () => Promise.resolve({ tasks: [], nextCursor: null });
renderTab();
- expect(await screen.findByText("10 latest runs")).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: /Show more/ }));
- expect(screen.getByText("20 latest runs")).toBeInTheDocument();
- expect(query).toHaveBeenCalledTimes(1);
- fireEvent.click(screen.getByRole("button", { name: /Show more/ }));
- expect(await screen.findByText(subtitle)).toBeInTheDocument();
- if (nextCursor) {
- expect(screen.queryByText(/of 220 runs/)).not.toBeInTheDocument();
- }
- expect(screen.getAllByTestId(/^task-/)).toHaveLength(50);
- expect(query.mock.calls[1]?.[0]).toBe("older");
+ expect(
+ await screen.findByText("This agent isn't running anything right now."),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/^\d+ runs?$/)).not.toBeInTheDocument();
+ });
+
+ it("opens the full work list from View all", () => {
+ const onViewAll = vi.fn();
+ renderTab(false, onViewAll);
+ fireEvent.click(screen.getByRole("button", { name: "View all" }));
+ expect(onViewAll).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsx
index 137683dd85..7bcad49c23 100644
--- a/packages/views/agents/components/tabs/activity-tab.tsx
+++ b/packages/views/agents/components/tabs/activity-tab.tsx
@@ -17,12 +17,11 @@ import {
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { Button } from "@multica/ui/components/ui/button";
-import { NumberFlow } from "@multica/ui/components/ui/number-flow";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { cn } from "@multica/ui/lib/utils";
import { useInfiniteQuery, useQueries, useQuery } from "@tanstack/react-query";
import type { Agent, AgentTask, Issue } from "@multica/core/types";
import {
- type AgentActivity,
agentTaskSnapshotOptions,
agentTasksOptions,
summarizeActivityWindow,
@@ -35,6 +34,11 @@ import { issueDetailOptions } from "@multica/core/issues/queries";
import { AppLink } from "../../../navigation";
import { TranscriptButton } from "../../../common/task-transcript";
import { AttributionBadge } from "../../../issues/components/attribution-badge";
+import {
+ ObjectSection,
+ ObjectSectionAction,
+ ObjectSectionCard,
+} from "../../../layout/object-page";
import { taskStatusConfig } from "../../config";
import { cancellationActorLabel, cancelReasonLabel, failureReasonLabel } from "./task-failure";
import { Sparkline } from "../sparkline";
@@ -44,36 +48,34 @@ import { useT, useTimeAgo } from "../../../i18n";
const RECENT_INITIAL = 10;
const RECENT_PAGE = 20;
// Placeholder rows shown while the lazily-loaded per-agent task list is
-// still in flight, so first paint of the tab is a skeleton rather than the
-// "nothing finished yet" empty state (which reads as a wrong answer).
+// still in flight, so first paint is a skeleton rather than the "nothing
+// finished yet" empty state (which reads as a wrong answer).
const RECENT_SKELETON_ROWS = 4;
// Row actions are 22px for a pointer; on touch they need a fingertip-sized
-// target (30px fits inside the two-line row without growing it).
+// target.
const TOUCH_ACTION_CLASS = "[@media(hover:none)]:p-2";
-interface ActivityTabProps {
- agent: Agent;
- showPerformance?: boolean;
-}
-
/**
- * Right-pane Activity tab on the agent detail page. Three sections framed
- * around the user's three diagnostic questions, in scan order:
+ * The agent page's two work sections, in scan order: Now (what is it doing
+ * this second?) and Recent work (what did it just finish?).
*
- * Now — what's it doing right this second?
- * Last 30 days — how has it been doing in aggregate?
- * Recent work — what did it just finish?
- *
- * "Now" and performance reuse workspace projections. Recent work loads
- * bounded history pages on demand; opening the tab never fetches all runs.
+ * "Now" reads the workspace task snapshot. Recent work loads bounded history
+ * pages on demand; opening the page never fetches all runs.
*/
-export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps) {
+export function AgentWorkSections({
+ agent,
+ onViewAll,
+}: {
+ agent: Agent;
+ /** Opens every issue assigned to this agent. */
+ onViewAll: () => void;
+}) {
const wsId = useWorkspaceId();
const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));
// `isLoading` (pending + fetching, no cached data) is true only on the
- // very first fetch. Once the page has hydrated this cache elsewhere the
- // tab opens straight into data with no skeleton flash.
+ // very first fetch. Once this cache is hydrated the section opens
+ // straight into data with no skeleton flash.
const {
data,
isLoading: isLoadingRecent,
@@ -89,8 +91,9 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)
}
return [...tasks.values()];
}, [data]);
- const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);
- const activity = activityMap.get(agent.id);
+ const { byAgent: activityMap, loading: activityLoading } =
+ useWorkspaceActivityMap(wsId);
+ const weekRuns = summarizeActivityWindow(activityMap.get(agent.id), 7).totalRuns;
const [recentDisplayLimit, setRecentDisplayLimit] = useState(RECENT_INITIAL);
@@ -150,8 +153,6 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)
);
const hasMoreRecent = recentTasksAll.length > recentTasks.length || hasNextPage;
- const avgDurationMs = activity?.avgDurationMs ?? 0;
-
// Resolve issue identifiers + titles for any task we'll render. Going
// through `issueDetailOptions` is the same lookup the rest of the app
// uses, so the cache is shared and we don't pay for a duplicate request.
@@ -179,14 +180,11 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)
}, [issueQueries, issueIds]);
return (
- <div className="flex min-w-0 flex-col gap-6">
+ <>
<NowSection tasks={activeTasks} issueMap={issueMap} agent={agent} />
- {showPerformance && (
- <Last30dSection activity={activity} avgDurationMs={avgDurationMs} />
- )}
<RecentWorkSection
tasks={recentTasks}
- totalCount={hasNextPage ? undefined : recentTasksAll.length}
+ weekRuns={activityLoading ? null : weekRuns}
hasMore={hasMoreRecent}
loading={isLoadingRecent}
fetchingMore={isFetchingNextPage}
@@ -202,15 +200,16 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)
});
}
}}
+ onViewAll={onViewAll}
issueMap={issueMap}
agent={agent}
/>
- </div>
+ </>
);
}
-/** Compact performance context for the Overview sidebar. Kept separate from
- * the work list so metrics never outrank current tasks or failures. */
+/** The 30-day performance numbers for the properties panel. Kept apart from
+ * the work sections so metrics never outrank current tasks or failures. */
export function AgentPerformanceSummary({ agent }: { agent: Agent }) {
const { t } = useT("agents");
const wsId = useWorkspaceId();
@@ -219,54 +218,51 @@ export function AgentPerformanceSummary({ agent }: { agent: Agent }) {
const summary = summarizeActivityWindow(activity, 30);
const avgDurationMs = activity?.avgDurationMs ?? 0;
+ if (summary.totalRuns === 0) {
+ return (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.tab_body.activity.empty_30d)}
+ </p>
+ );
+ }
+
return (
- <section className="mt-5 border-t pt-5">
- <h2 className="text-body font-medium">
- {t(($) => $.tab_body.activity.section_last_30d)}
- </h2>
- {summary.totalRuns === 0 ? (
- <p className="mt-3 text-caption text-muted-foreground">
- {t(($) => $.tab_body.activity.empty_30d)}
+ <div>
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
+ <Metric
+ value={String(summary.totalRuns)}
+ label={t(($) => $.tab_body.activity.runs, {
+ count: summary.totalRuns,
+ })}
+ />
+ <Metric
+ value={<SuccessRate rate={summary.successRate} />}
+ label={t(($) => $.tab_body.activity.success_label)}
+ />
+ <Metric
+ value={avgDurationMs > 0 ? formatDurationMs(avgDurationMs) : "—"}
+ label={t(($) => $.tab_body.activity.avg_duration_label)}
+ />
+ <Metric
+ value={String(summary.totalFailed)}
+ label={t(($) => $.tab_body.activity.failed_label)}
+ destructive={summary.totalFailed > 0}
+ />
+ </div>
+ {summary.totalCancelled > 0 && (
+ <p className="mt-2 text-caption text-muted-foreground">
+ {t(($) => $.tab_body.activity.cancelled_count, {
+ count: summary.totalCancelled,
+ })}
</p>
- ) : (
- <>
- <div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-3">
- <Metric
- value={String(summary.totalRuns)}
- label={t(($) => $.tab_body.activity.runs, {
- count: summary.totalRuns,
- })}
- />
- <Metric
- value={<SuccessRate rate={summary.successRate} />}
- label={t(($) => $.tab_body.activity.success_label)}
- />
- <Metric
- value={avgDurationMs > 0 ? formatDurationMs(avgDurationMs) : "—"}
- label={t(($) => $.tab_body.activity.avg_duration_label)}
- />
- <Metric
- value={String(summary.totalFailed)}
- label={t(($) => $.tab_body.activity.failed_label)}
- destructive={summary.totalFailed > 0}
- />
- </div>
- {summary.totalCancelled > 0 && (
- <p className="mt-2 text-caption text-muted-foreground">
- {t(($) => $.tab_body.activity.cancelled_count, {
- count: summary.totalCancelled,
- })}
- </p>
- )}
- <Sparkline
- buckets={summary.buckets}
- width={250}
- height={36}
- className="mt-4 h-9 w-full"
- />
- </>
)}
- </section>
+ <Sparkline
+ buckets={summary.buckets}
+ width={250}
+ height={36}
+ className="mt-4 h-9 w-full"
+ />
+ </div>
);
}
@@ -293,7 +289,8 @@ function Metric({
);
}
-function SuccessRate({
+/** A success rate with the tooltip that says what it counts. */
+export function SuccessRate({
rate,
labelled = false,
}: {
@@ -330,150 +327,82 @@ function NowSection({
}) {
const { t } = useT("agents");
return (
- <Section
+ <ObjectSection
title={t(($) => $.tab_body.activity.section_now)}
- subtitle={
- tasks.length === 0
- ? t(($) => $.tab_body.activity.subtitle_no_active)
- : t(($) => $.tab_body.activity.subtitle_active, { count: tasks.length })
+ count={
+ tasks.length > 0
+ ? t(($) => $.sections.runs_count, { count: tasks.length })
+ : undefined
}
>
{tasks.length === 0 ? (
- <EmptyText>{t(($) => $.tab_body.activity.empty_now)}</EmptyText>
- ) : (
- <TaskList
- tasks={tasks}
- issueMap={issueMap}
- timeMode="active"
- agent={agent}
- />
- )}
- </Section>
- );
-}
-
-function Last30dSection({
- activity,
- avgDurationMs,
-}: {
- activity: AgentActivity | undefined;
- avgDurationMs: number;
-}) {
- const { t, i18n } = useT("agents");
- const summary = summarizeActivityWindow(activity, 30);
- const { totalRuns, totalFailed } = summary;
- const locales = i18n.resolvedLanguage ?? i18n.language;
-
- return (
- <Section title={t(($) => $.tab_body.activity.section_last_30d)} subtitle={t(($) => $.tab_body.activity.subtitle_performance)}>
- {totalRuns === 0 ? (
- <EmptyText>{t(($) => $.tab_body.activity.empty_30d)}</EmptyText>
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.tab_body.activity.empty_now)}
+ </p>
) : (
- <div className="flex items-end justify-between gap-5">
- <div className="flex min-w-0 flex-col gap-1">
- <div className="flex items-baseline gap-1.5">
- <NumberFlow
- value={totalRuns}
- locales={locales}
- format={{ maximumFractionDigits: 0 }}
- aria-label={String(totalRuns)}
- className="text-display font-bold leading-none"
- />
- <span className="text-body text-muted-foreground">
- {t(($) => $.tab_body.activity.runs, { count: totalRuns })}
- </span>
- </div>
- <div className="text-caption text-muted-foreground">
- <SuccessRate rate={summary.successRate} labelled />
- {avgDurationMs > 0 && (
- <>
- <Sep />
- <span>{t(($) => $.tab_body.activity.avg_duration, { value: formatDurationMs(avgDurationMs) })}</span>
- </>
- )}
- {totalFailed > 0 && (
- <>
- <Sep />
- <span className="text-destructive">
- {t(($) => $.tab_body.activity.failed_count, { count: totalFailed })}
- </span>
- </>
- )}
- {summary.totalCancelled > 0 && (
- <>
- <Sep />
- <span>
- {t(($) => $.tab_body.activity.cancelled_count, {
- count: summary.totalCancelled,
- })}
- </span>
- </>
- )}
- </div>
- </div>
- {/* Garnish, not hero — small enough that a sparse 30-day series
- doesn't read as visually broken. Bottom-aligned with the
- number so the dense end of the bars sits on the same
- baseline as the digits. */}
- <Sparkline
- buckets={summary.buckets}
- width={120}
- height={32}
- className="shrink-0"
- />
- </div>
+ <ObjectSectionCard>
+ {tasks.map((task) => (
+ <LiveTaskRow key={task.id} task={task} issueMap={issueMap} agent={agent} />
+ ))}
+ </ObjectSectionCard>
)}
- </Section>
+ </ObjectSection>
);
}
function RecentWorkSection({
tasks,
- totalCount,
+ weekRuns,
hasMore,
loading,
onShowMore,
fetchingMore,
fetchMoreFailed,
+ onViewAll,
issueMap,
agent,
}: {
tasks: AgentTask[];
- // Only known after the server has returned the final history page.
- totalCount?: number;
+ /** Runs in the last 7 days; `null` until the activity window has loaded. */
+ weekRuns: number | null;
hasMore: boolean;
loading: boolean;
onShowMore: () => void;
fetchingMore: boolean;
fetchMoreFailed: boolean;
+ onViewAll: () => void;
issueMap: Map<string, Issue>;
agent: Agent;
}) {
const { t } = useT("agents");
- // While the first fetch is in flight we have no counts to summarise, so
- // the subtitle stays blank rather than claiming "nothing finished yet".
- const subtitle = loading
- ? ""
- : tasks.length === 0
- ? hasMore
- ? ""
- : t(($) => $.tab_body.activity.subtitle_no_recent)
- : totalCount !== undefined && totalCount > tasks.length
- ? t(($) => $.tab_body.activity.subtitle_recent_progress, { shown: tasks.length, total: totalCount })
- : t(($) => $.tab_body.activity.subtitle_recent_latest, { count: tasks.length });
return (
- <Section title={t(($) => $.tab_body.activity.section_recent)} subtitle={subtitle}>
+ <ObjectSection
+ title={t(($) => $.tab_body.activity.section_recent)}
+ count={
+ weekRuns === null
+ ? undefined
+ : t(($) => $.sections.recent_this_week, { count: weekRuns })
+ }
+ action={
+ <ObjectSectionAction icon={ArrowUpRight} onClick={onViewAll}>
+ {t(($) => $.sections.view_all)}
+ </ObjectSectionAction>
+ }
+ >
{loading ? (
<RecentWorkSkeleton />
) : tasks.length === 0 ? (
- hasMore ? null : <EmptyText>{t(($) => $.tab_body.activity.empty_recent)}</EmptyText>
+ hasMore ? null : (
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.tab_body.activity.empty_recent)}
+ </p>
+ )
) : (
- <TaskList
- tasks={tasks}
- issueMap={issueMap}
- timeMode="completed"
- agent={agent}
- />
+ <ObjectSectionCard>
+ {tasks.map((task) => (
+ <RecentTaskRow key={task.id} task={task} issueMap={issueMap} agent={agent} />
+ ))}
+ </ObjectSectionCard>
)}
{!loading && hasMore && (
<Button
@@ -483,120 +412,47 @@ function RecentWorkSection({
onClick={onShowMore}
disabled={fetchingMore}
aria-busy={fetchingMore}
- className="self-start"
+ className="text-muted-foreground"
>
{fetchMoreFailed ? t(($) => $.detail.try_again) : t(($) => $.tab_body.activity.show_more)}
</Button>
)}
- </Section>
+ </ObjectSection>
);
}
/**
- * Loading placeholder for the Recent work list. Mirrors the completed-mode
- * TaskList shell (bordered, divided rows) and the two-line TaskRow rhythm —
- * a status glyph plus title and meta line — so the skeleton settles into the
- * real rows without a layout jump. Widths are staggered per row so it reads
- * as content rather than a solid block.
+ * Loading placeholder for the Recent work list. Mirrors the card and the
+ * one-line row rhythm so the skeleton settles into the real rows without a
+ * layout jump. Widths are staggered per row so it reads as content rather
+ * than a solid block.
*/
function RecentWorkSkeleton() {
const titleWidths = ["w-3/5", "w-4/5", "w-1/2", "w-2/3"];
- const metaWidths = ["w-2/5", "w-1/3", "w-2/5", "w-1/4"];
return (
- <div
- className="overflow-hidden rounded-lg border divide-y"
- aria-hidden="true"
- >
- {Array.from({ length: RECENT_SKELETON_ROWS }).map((_, i) => (
- <div key={i} className="flex items-center gap-3 px-3 py-3">
- <Skeleton className="h-4 w-4 shrink-0 rounded-full" />
- <div className="min-w-0 flex-1 space-y-2">
+ <ObjectSectionCard className="bg-transparent">
+ <div aria-hidden="true" className="divide-y">
+ {Array.from({ length: RECENT_SKELETON_ROWS }).map((_, i) => (
+ <div key={i} className="flex h-10 items-center gap-3 px-3">
+ <Skeleton className="size-4 shrink-0 rounded-full" />
<Skeleton className={`h-3.5 ${titleWidths[i % titleWidths.length]}`} />
- <Skeleton className={`h-3 ${metaWidths[i % metaWidths.length]}`} />
+ <Skeleton className="ml-auto h-3 w-20" />
</div>
- </div>
- ))}
- </div>
+ ))}
+ </div>
+ </ObjectSectionCard>
);
}
-function TaskList({
- tasks,
- issueMap,
- timeMode,
- agent,
-}: {
- tasks: AgentTask[];
- issueMap: Map<string, Issue>;
- timeMode: "active" | "completed";
- agent: Agent;
-}) {
- return (
- <div
- className={
- timeMode === "completed"
- ? "overflow-hidden rounded-lg border divide-y"
- : "space-y-2"
- }
- >
- {tasks.map((task) => (
- <TaskRow
- key={task.id}
- task={task}
- issueMap={issueMap}
- timeMode={timeMode}
- agent={agent}
- />
- ))}
- </div>
- );
-}
+type AgentsT = ReturnType<typeof useT<"agents">>["t"];
+type TimeAgoFn = (dateStr: string) => string;
-function TaskRow({
- task,
- issueMap,
- timeMode,
- agent,
-}: {
- task: AgentTask;
- issueMap: Map<string, Issue>;
- timeMode: "active" | "completed";
- agent: Agent;
-}) {
+/** What every task row shows, whichever section it sits in. */
+function useTaskRowModel(task: AgentTask, issueMap: Map<string, Issue>) {
const { t } = useT("agents");
- const timeAgo = useTimeAgo();
- const paths = useWorkspacePaths();
- const [cancelling, setCancelling] = useState(false);
const cfg = taskStatusConfig[task.status] ?? taskStatusConfig.queued!;
- const Icon = cfg.icon;
const hasIssue = task.issue_id !== "";
const issue = hasIssue ? issueMap.get(task.issue_id) : undefined;
- const isRunning = task.status === "running";
- // Queued tasks have no messages yet — hiding the transcript button avoids
- // a guaranteed "No execution data recorded." dialog open.
- const showTranscript = task.status !== "queued";
- // Cancel only makes sense for the three active states. Terminal rows
- // (completed / failed / cancelled) hide the button entirely.
- const showCancel =
- timeMode === "active" &&
- (task.status === "queued" ||
- task.status === "dispatched" ||
- task.status === "running");
-
- const handleCancel = async () => {
- if (cancelling) return;
- setCancelling(true);
- try {
- await api.cancelTaskById(task.id);
- // No manual invalidate needed — the task:cancelled WS event flows
- // through useRealtimeSync's `task:` prefix path which already
- // invalidates snapshot + per-agent + per-issue task lists.
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.tab_body.activity.cancel_failed_toast));
- setCancelling(false);
- }
- };
-
const isTerminalStatus =
task.status === "completed" ||
task.status === "failed" ||
@@ -612,7 +468,6 @@ function TaskRow({
? t(($) => $.tab_body.activity.source_autopilot_run)
: t(($) => $.tab_body.activity.source_untracked)
: null;
-
const SourceIcon = hasIssue
? Hash
: task.chat_session_id
@@ -627,159 +482,159 @@ function TaskRow({
: task.autopilot_run_id
? t(($) => $.tab_body.activity.source_autopilot)
: t(($) => $.tab_body.activity.source_untracked);
-
- const timeText =
- timeMode === "active"
- ? activeTaskTimeText(task, t, timeAgo)
- : task.completed_at
- ? timeAgo(task.completed_at)
- : "—";
-
+ const title =
+ issue?.title ??
+ (hasIssue
+ ? t(($) => $.tab_body.activity.issue_short_fallback, { prefix: task.issue_id.slice(0, 8) })
+ : (sourceFallback ?? t(($) => $.tab_body.activity.source_untracked)));
// Failure reason. The back-end emits "" on non-failed tasks (omitempty
// strips it on the wire) so the truthy guard is the right shape.
// failureReasonLabel takes the raw open string because the taxonomy grows,
- // so there is no enum to cast to. Cancelled rows get a
- // label only when the SERVER cancelled them for a persisted reason
- // (worktree claim gate, preserved-work delivery); a user's own cancel
- // stays a plain "Cancelled".
+ // so there is no enum to cast to. Cancelled rows get a label only when the
+ // SERVER cancelled them for a persisted reason (worktree claim gate,
+ // preserved-work delivery); a user's own cancel stays a plain "Cancelled".
const failureLabel =
task.status === "failed"
? failureReasonLabel(task.failure_reason, t)
: cancelReasonLabel(task, t);
const statusLabel = cancellationActorLabel(task, t) ?? taskStatusLabel(task.status, t);
+ return {
+ cfg,
+ hasIssue,
+ issue,
+ title,
+ SourceIcon,
+ sourceLabel,
+ sourceFallback,
+ failureLabel,
+ statusLabel,
+ };
+}
- // Only show duration for terminal rows. An active row's duration is
- // inferred from the timeText already ("Started 2m ago") and adding a
- // second time bubble next to it just clutters the line.
- let durationText: string | null = null;
- if (timeMode === "completed" && task.started_at && task.completed_at) {
- const dur =
- new Date(task.completed_at).getTime() -
- new Date(task.started_at).getTime();
- if (dur > 0) durationText = formatDurationMs(dur);
+/** The task title; hovering it says why the task ran. */
+function TaskTitle({ task, title }: { task: AgentTask; title: string }) {
+ const { t } = useT("agents");
+ if (!task.trigger_summary) {
+ return <span className="min-w-0 truncate text-body">{title}</span>;
}
+ // The snapshot lets the row stay anchored on issue.title while the user
+ // can still dwell to see the trigger context — the same pattern as GitHub
+ // Actions surfacing the commit message on hover.
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={<span className="min-w-0 truncate text-body">{title}</span>}
+ />
+ <TooltipContent className="max-w-md">
+ <div className="text-micro font-medium uppercase tracking-wider text-muted-foreground">
+ {t(($) => $.tab_body.activity.triggered_by)}
+ </div>
+ <div className="mt-0.5 whitespace-pre-wrap text-caption">
+ {task.trigger_summary}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function OpenIssueIconLink({ issueId }: { issueId: string }) {
+ const { t } = useT("agents");
+ const paths = useWorkspacePaths();
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={<AppLink href={paths.issueDetail(issueId)} />}
+ aria-label={t(($) => $.tab_body.activity.open_issue_aria)}
+ className={`flex items-center justify-center rounded-xs p-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground ${TOUCH_ACTION_CLASS}`}
+ >
+ <ArrowUpRight className="h-3.5 w-3.5" aria-hidden="true" />
+ </TooltipTrigger>
+ <TooltipContent>{t(($) => $.tab_body.activity.open_issue_tooltip)}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+// The rows are intentionally non-clickable so neither destination is
+// privileged — issue detail and transcript are equally valid follow-ups.
+// focus-within keeps the action slot reachable for keyboard users; touch
+// screens have no hover, so there the slot stays visible.
+const HOVER_ACTIONS_CLASS =
+ "flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-100 group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100";
+
+/** A run in progress: what it is working on, for how long, and a way in. */
+function LiveTaskRow({
+ task,
+ issueMap,
+ agent,
+}: {
+ task: AgentTask;
+ issueMap: Map<string, Issue>;
+ agent: Agent;
+}) {
+ const { t } = useT("agents");
+ const timeAgo = useTimeAgo();
+ const paths = useWorkspacePaths();
+ const [cancelling, setCancelling] = useState(false);
+ const { cfg, hasIssue, issue, title, SourceIcon, sourceLabel, sourceFallback, statusLabel } =
+ useTaskRowModel(task, issueMap);
+ const Icon = cfg.icon;
+ const isRunning = task.status === "running";
+ // Queued tasks have no messages yet — hiding the transcript button avoids
+ // a guaranteed "No execution data recorded." dialog open.
+ const showTranscript = task.status !== "queued";
+ const showCancel =
+ task.status === "queued" ||
+ task.status === "dispatched" ||
+ task.status === "running";
- const rowClass =
- timeMode === "completed"
- ? "group flex items-center gap-3 px-3 py-3 transition-colors hover:bg-muted/30"
- : `group flex items-center gap-3 rounded-md border px-3 py-3 ${
- isRunning ? "border-brand/40 bg-brand/5" : ""
- }`;
+ const handleCancel = async () => {
+ if (cancelling) return;
+ setCancelling(true);
+ try {
+ await api.cancelTaskById(task.id);
+ // No manual invalidate needed — the task:cancelled WS event flows
+ // through useRealtimeSync's `task:` prefix path which already
+ // invalidates snapshot + per-agent + per-issue task lists.
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : t(($) => $.tab_body.activity.cancel_failed_toast));
+ setCancelling(false);
+ }
+ };
return (
- <div className={rowClass}>
- <Icon
- className={`h-4 w-4 shrink-0 ${cfg.color} ${
- isRunning ? "animate-spin motion-reduce:animate-none" : ""
- }`}
- aria-hidden="true"
- />
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-1.5">
- <SourceIcon
- className="h-3 w-3 shrink-0 text-faint-foreground"
- aria-label={sourceLabel}
- />
- {issue && (
- <span className="shrink-0 font-mono text-caption text-muted-foreground">
- {issue.identifier}
- </span>
- )}
- {task.trigger_summary ? (
- // Hover surfaces "why this task ran" — the snapshot lets the
- // agent-side row stay anchored on issue.title (the
- // identification axis here) while still letting the user
- // dwell to see the trigger context. Same pattern as
- // GitHub Actions surfacing the commit message on hover.
- <Tooltip>
- <TooltipTrigger
- render={
- <span className="truncate text-body">
- {issue?.title ??
- (hasIssue
- ? t(($) => $.tab_body.activity.issue_short_fallback, { prefix: task.issue_id.slice(0, 8) })
- : (sourceFallback ?? t(($) => $.tab_body.activity.source_untracked)))}
- </span>
- }
- />
- <TooltipContent className="max-w-md">
- <div className="text-micro font-medium uppercase tracking-wider text-muted-foreground">
- {t(($) => $.tab_body.activity.triggered_by)}
- </div>
- <div className="mt-0.5 whitespace-pre-wrap text-caption">
- {task.trigger_summary}
- </div>
- </TooltipContent>
- </Tooltip>
- ) : (
- <span className="truncate text-body">
- {issue?.title ??
- (hasIssue
- ? t(($) => $.tab_body.activity.issue_short_fallback, { prefix: task.issue_id.slice(0, 8) })
- : (sourceFallback ?? t(($) => $.tab_body.activity.source_untracked)))}
- </span>
+ <div className="group flex items-center gap-3 px-3 py-2.5">
+ <span
+ className={cn(
+ "flex size-8 shrink-0 items-center justify-center rounded-md",
+ isRunning ? "bg-brand/10" : "bg-muted",
+ )}
+ >
+ <Icon
+ className={cn(
+ "size-4",
+ cfg.color,
+ isRunning && "animate-spin motion-reduce:animate-none",
)}
- </div>
- <div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-caption text-muted-foreground">
- <span className={cfg.color}>
- {statusLabel}
+ aria-hidden="true"
+ />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
+ <SourceIcon className="size-3 shrink-0 text-faint-foreground" aria-label={sourceLabel} />
+ <span className={cn("shrink-0", issue && "font-mono")}>
+ {issue?.identifier ?? sourceFallback ?? sourceLabel}
</span>
- <Sep />
- <span>{timeText}</span>
- {durationText && (
- <>
- <Sep />
- <span>{durationText}</span>
- </>
- )}
- {failureLabel && (
- <>
- <Sep />
- {/* The localized reason is the whole user-facing explanation
- here. The raw `task.error` used to ride along as this
- element's `title`, which put untranslated English (and
- absolute paths) in front of every non-English workspace
- (#7411); the full diagnostic lives in the transcript's Run
- details instead. */}
- <span className="text-destructive">{failureLabel}</span>
- </>
- )}
- {/* Accountable member (MUL-4302 §9): whose behalf this run is on.
- A leading separator keeps the avatar on the same middot rhythm as
- the rest of the meta line instead of glued to the duration. The
- guard mirrors the badge's own render condition (avatar-only needs
- an initiator) so no dangling separator is left for an
- unattributed run. */}
- {task.attribution?.initiator && (
- <>
- <Sep />
- <AttributionBadge
- attribution={task.attribution}
- variant="avatar"
- />
- </>
- )}
+ <span aria-hidden="true">·</span>
+ <span className={cn("truncate", cfg.color)}>{statusLabel}</span>
+ </div>
+ <div className="flex min-w-0">
+ <TaskTitle task={task} title={title} />
</div>
</div>
-
- {/* Hover-revealed actions. The row is intentionally non-clickable so
- neither destination is privileged — issue detail and transcript
- are equally valid follow-ups. focus-within keeps the slot
- reachable for keyboard users; touch screens have no hover, so
- there the slot stays visible with larger tap targets. */}
- <div className="ml-2 flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-100 group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:none)]:opacity-100">
- {hasIssue && (
- <Tooltip>
- <TooltipTrigger
- render={<AppLink href={paths.issueDetail(task.issue_id)} />}
- aria-label={t(($) => $.tab_body.activity.open_issue_aria)}
- className={`flex items-center justify-center rounded-xs p-1 text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors ${TOUCH_ACTION_CLASS}`}
- >
- <ArrowUpRight className="h-3.5 w-3.5" aria-hidden="true" />
- </TooltipTrigger>
- <TooltipContent>{t(($) => $.tab_body.activity.open_issue_tooltip)}</TooltipContent>
- </Tooltip>
- )}
+ <span className="hidden shrink-0 text-caption text-muted-foreground sm:inline">
+ {activeTaskTimeText(task, t, timeAgo)}
+ </span>
+ <div className={HOVER_ACTIONS_CLASS}>
{showTranscript && (
<TranscriptButton
task={task}
@@ -810,46 +665,100 @@ function TaskRow({
</Tooltip>
)}
</div>
+ {hasIssue && (
+ <Button
+ variant="outline"
+ size="sm"
+ render={<AppLink href={paths.issueDetail(task.issue_id)} />}
+ nativeButton={false}
+ >
+ {t(($) => $.sections.open)}
+ </Button>
+ )}
</div>
);
}
-function Section({
- title,
- subtitle,
- children,
+/** A finished run on one line: outcome, what it was, and when. */
+function RecentTaskRow({
+ task,
+ issueMap,
+ agent,
}: {
- title: string;
- subtitle: string;
- children: ReactNode;
+ task: AgentTask;
+ issueMap: Map<string, Issue>;
+ agent: Agent;
}) {
+ const { t } = useT("agents");
+ const timeAgo = useTimeAgo();
+ const { cfg, hasIssue, issue, title, SourceIcon, sourceLabel, failureLabel, statusLabel } =
+ useTaskRowModel(task, issueMap);
+ const Icon = cfg.icon;
+
+ let durationText: string | null = null;
+ if (task.started_at && task.completed_at) {
+ const dur =
+ new Date(task.completed_at).getTime() -
+ new Date(task.started_at).getTime();
+ if (dur > 0) durationText = formatDurationMs(dur);
+ }
+
return (
- <section className="flex flex-col gap-3 border-b pb-6 last:border-b-0 last:pb-0">
- <div className="flex items-baseline gap-2">
- <h2 className="text-body font-semibold text-foreground">
- {title}
- </h2>
- <span className="text-micro text-muted-foreground">{subtitle}</span>
+ <div className="group flex min-h-10 items-center gap-3 px-3 py-2 transition-colors hover:bg-accent/40">
+ <Icon className={cn("size-4 shrink-0", cfg.color)} aria-hidden="true" />
+ {issue ? (
+ <span className="shrink-0 font-mono text-caption text-muted-foreground">
+ {issue.identifier}
+ </span>
+ ) : (
+ <SourceIcon className="size-3 shrink-0 text-faint-foreground" aria-label={sourceLabel} />
+ )}
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <TaskTitle task={task} title={title} />
+ {/* The localized reason is the whole user-facing explanation here;
+ the raw `task.error` (untranslated, with absolute paths, #7411)
+ lives in the transcript's Run details instead. */}
+ {failureLabel && (
+ <span className="hidden shrink-0 text-caption text-destructive sm:inline">
+ {failureLabel}
+ </span>
+ )}
+ </div>
+ {/* Accountable member (MUL-4302 §9): whose behalf this run is on. */}
+ {task.attribution?.initiator && (
+ <AttributionBadge attribution={task.attribution} variant="avatar" />
+ )}
+ <span className="shrink-0 text-caption text-muted-foreground">
+ <span className={cfg.color}>{statusLabel}</span>
+ <Sep />
+ {task.completed_at ? timeAgo(task.completed_at) : "—"}
+ {durationText && (
+ <span className="hidden sm:inline">
+ <Sep />
+ {durationText}
+ </span>
+ )}
+ </span>
+ <div className={HOVER_ACTIONS_CLASS}>
+ {hasIssue && <OpenIssueIconLink issueId={task.issue_id} />}
+ <TranscriptButton
+ task={task}
+ agentName={agent.name}
+ isLive={false}
+ title={t(($) => $.tab_body.activity.transcript_tooltip)}
+ className={TOUCH_ACTION_CLASS}
+ />
</div>
- {children}
- </section>
+ </div>
);
}
-function EmptyText({ children }: { children: ReactNode }) {
- return <p className="text-caption italic text-muted-foreground">{children}</p>;
-}
-
function Sep() {
// mx-1 puts visible whitespace around the dot; without it inline JSX
- // collapses neighbouring tokens to "100% success·avg 30s" which reads
- // as "successdotavg" at a glance.
+ // collapses neighbouring tokens into one word at a glance.
return <span className="mx-1 text-faint-foreground">·</span>;
}
-type AgentsT = ReturnType<typeof useT<"agents">>["t"];
-type TimeAgoFn = (dateStr: string) => string;
-
function taskStatusLabel(status: AgentTask["status"], t: AgentsT): string {
switch (status) {
case "queued":
diff --git a/packages/views/agents/create/agent-created-page.tsx b/packages/views/agents/create/agent-created-page.tsx
index 194fca6a43..c4e367d219 100644
--- a/packages/views/agents/create/agent-created-page.tsx
+++ b/packages/views/agents/create/agent-created-page.tsx
@@ -12,11 +12,13 @@ import {
agentDetailOptions,
squadListOptions,
} from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "../../common/actor-avatar";
import { AppLink, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
+import { CreateFlowFooter } from "./create-agent-footer";
import { AgentCreateShell } from "./create-shell";
/**
@@ -42,8 +44,7 @@ export function AgentCreatedPage({ agentId }: { agentId: string }) {
title={t(($) => $.creation_studio.title)}
step={t(($) => $.creation_studio.steps.done)}
stepIndex={3}
- closeIcon
- onBack={() => navigation.replace(paths.agentDetail(agentId))}
+ onClose={() => navigation.replace(paths.agentDetail(agentId))}
>
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 py-12">
<div className="m-auto w-full max-w-xl">
@@ -115,24 +116,16 @@ export function AgentCreatedPage({ agentId }: { agentId: string }) {
href={squad ? paths.squadDetail(squad.id) : paths.squads()}
/>
</div>
-
- <div className="mt-8 flex items-center justify-center gap-4 text-label">
- <AppLink
- href={paths.agentDetail(agentId)}
- className="font-medium text-foreground underline-offset-4 hover:underline"
- >
- {t(($) => $.creation_studio.done.open_agent)}
- </AppLink>
- <span aria-hidden="true" className="text-muted-foreground">·</span>
- <AppLink
- href={paths.agents()}
- className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
- >
- {t(($) => $.creation_studio.done.back_to_list)}
- </AppLink>
- </div>
</div>
</main>
+ <CreateFlowFooter stepIndex={3}>
+ <Button variant="ghost" render={<AppLink href={paths.agents()} />} nativeButton={false}>
+ {t(($) => $.creation_studio.done.back_to_list)}
+ </Button>
+ <Button render={<AppLink href={paths.agentDetail(agentId)} />} nativeButton={false}>
+ {t(($) => $.creation_studio.done.open_agent)}
+ </Button>
+ </CreateFlowFooter>
</AgentCreateShell>
);
}
diff --git a/packages/views/agents/create/ai-builder-session-page.tsx b/packages/views/agents/create/ai-builder-session-page.tsx
index 6860b5389d..1bc06c0345 100644
--- a/packages/views/agents/create/ai-builder-session-page.tsx
+++ b/packages/views/agents/create/ai-builder-session-page.tsx
@@ -5,7 +5,7 @@ import { useQuery } from "@tanstack/react-query";
import { agentBuilderSessionListOptions } from "@multica/core/agents";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
-import { useBackOrReplace, useNavigation } from "../../navigation";
+import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { BuilderWorkspace } from "./builder-workspace";
import { AgentCreateChip, AgentCreateShell } from "./create-shell";
@@ -24,7 +24,6 @@ export function AiBuilderSessionPage({ sessionId }: { sessionId: string }) {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
- const backOrReplace = useBackOrReplace();
const squadId = navigation.searchParams.get("squad");
// The runtime this conversation was just started on. It cannot be read back
// for the first turn — a conversation joins the list only once it has a
@@ -56,7 +55,11 @@ export function AiBuilderSessionPage({ sessionId }: { sessionId: string }) {
: t(($) => $.creation_studio.title)
}
step={t(($) => $.creation_studio.step_ai)}
- onBack={() => backOrReplace(paths.newAgent())}
+ // Leaving keeps the conversation — step 1 lists it to resume — so close
+ // exits the flow instead of stepping back to the runtime list.
+ onClose={() =>
+ navigation.push(squadId ? paths.squadDetail(squadId) : paths.agents())
+ }
chips={
<>
<AgentCreateChip>
diff --git a/packages/views/agents/create/ai-create-agent-page.tsx b/packages/views/agents/create/ai-create-agent-page.tsx
index 6108f79c84..6904d0e0a2 100644
--- a/packages/views/agents/create/ai-create-agent-page.tsx
+++ b/packages/views/agents/create/ai-create-agent-page.tsx
@@ -7,7 +7,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
import type { RuntimeDevice } from "@multica/core/types";
-import { useBackOrReplace, useNavigation } from "../../navigation";
+import { useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { BuilderSetupPanel } from "./builder-setup-panel";
import { AgentCreateChip, AgentCreateShell } from "./create-shell";
@@ -33,7 +33,6 @@ export function AiCreateAgentPage() {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
- const backOrReplace = useBackOrReplace();
const squadId = navigation.searchParams.get("squad");
const builderSessions = useQuery(agentBuilderSessionListOptions(wsId));
@@ -66,7 +65,9 @@ export function AiCreateAgentPage() {
: t(($) => $.creation_studio.title)
}
step={t(($) => $.creation_studio.step_ai)}
- onBack={() => backOrReplace(paths.newAgent())}
+ onClose={() =>
+ navigation.push(squadId ? paths.squadDetail(squadId) : paths.agents())
+ }
chips={
<>
<AgentCreateChip>
diff --git a/packages/views/agents/create/choose-runtime-page.tsx b/packages/views/agents/create/choose-runtime-page.tsx
index 7a9250e3b3..4f9995c351 100644
--- a/packages/views/agents/create/choose-runtime-page.tsx
+++ b/packages/views/agents/create/choose-runtime-page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
-import { ArrowRight, Search } from "@multica/ui/icons";
+import { ChevronRight, Search } from "@multica/ui/icons";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { agentBuilderSessionListOptions } from "@multica/core/agents";
import { useAuthStore } from "@multica/core/auth";
@@ -19,6 +19,7 @@ import { ConnectRemoteDialog } from "../../runtimes/components/connect-remote-di
import { RemoteRuntimeDialog } from "../../runtimes/components/remote-runtime-dialog";
import { QODER_RUNTIME_LOCATOR } from "../../runtimes/components/qoder-detail-page";
import { buildRuntimeMachines } from "../../runtimes/components/runtime-machines";
+import { CreateFlowFooter } from "./create-agent-footer";
import { AgentCreateShell } from "./create-shell";
import { buildRuntimeChoiceGroups, type HarnessOption } from "./runtime-choice";
import { RuntimeChoiceList, qoderChoiceState } from "./runtime-choice-list";
@@ -200,8 +201,7 @@ export function ChooseRuntimePage({
}
step={t(($) => $.creation_studio.steps.runtime)}
stepIndex={1}
- onBack={() => backOrReplace(paths.agents())}
- closeIcon
+ onClose={() => backOrReplace(paths.agents())}
>
<main className="min-h-0 flex-1 overflow-y-auto">
<div className="mx-auto w-full max-w-3xl px-5 py-8 sm:px-8">
@@ -273,23 +273,25 @@ export function ChooseRuntimePage({
</div>
</div>
</main>
- <footer className="flex shrink-0 items-center gap-3 border-t bg-background px-5 py-3">
- <p className="min-w-0 flex-1 truncate text-label text-muted-foreground">
- {summary ? (
- <>
+ <CreateFlowFooter
+ stepIndex={1}
+ status={
+ summary ? (
+ <p className="min-w-0 truncate text-caption text-muted-foreground">
{t(($) => $.creation_studio.runtime_step.footer_selected)}{" "}
<span className="font-medium text-foreground">{summary}</span>
- </>
- ) : null}
- </p>
+ </p>
+ ) : null
+ }
+ >
<Button variant="ghost" onClick={() => backOrReplace(paths.agents())}>
{t(($) => $.creation_studio.runtime_step.cancel)}
</Button>
<Button disabled={!nextRuntimeId} onClick={() => nextRuntimeId && goNext(nextRuntimeId)}>
{t(($) => $.creation_studio.runtime_step.next)}
- <ArrowRight aria-hidden="true" className="size-3.5" />
+ <ChevronRight aria-hidden="true" className="size-3.5" />
</Button>
- </footer>
+ </CreateFlowFooter>
{showConnectRemote ? (
<ConnectRemoteDialog onClose={() => setShowConnectRemote(false)} />
) : null}
diff --git a/packages/views/agents/create/create-agent-footer.tsx b/packages/views/agents/create/create-agent-footer.tsx
index e25b4651df..cf07e95887 100644
--- a/packages/views/agents/create/create-agent-footer.tsx
+++ b/packages/views/agents/create/create-agent-footer.tsx
@@ -1,65 +1,106 @@
"use client";
+import type { ReactNode } from "react";
import { Loader2 } from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
-import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
+import { AGENT_CREATE_STEP_COUNT, type AgentCreateStep } from "./create-shell";
/**
- * Where the flow ends. Both exits live here — commit the agent, or abandon the
- * attempt — because they are the two answers to one question, and reading them
+ * The bar pinned under every creation step: where the reader is on the left,
+ * the way out and the one way forward on the right. Its end padding keeps the
+ * forward button clear of the chat launcher, which owns that corner.
+ */
+export function CreateFlowFooter({
+ stepIndex,
+ status,
+ children,
+}: {
+ /** Position in runtime → configure → done. Omitted by off-path routes. */
+ stepIndex?: AgentCreateStep;
+ /** Beside the step: the current selection, or what went wrong. */
+ status?: ReactNode;
+ children: ReactNode;
+}) {
+ const { t } = useT("agents");
+ return (
+ <footer className="pe-chat-launcher flex min-h-14 shrink-0 items-center gap-3 border-t bg-background py-3 pl-4">
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ {stepIndex ? (
+ <p className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.creation_studio.steps.progress, {
+ current: stepIndex,
+ total: AGENT_CREATE_STEP_COUNT,
+ })}
+ </p>
+ ) : null}
+ {status}
+ </div>
+ <div className="flex shrink-0 items-center gap-2">{children}</div>
+ </footer>
+ );
+}
+
+/**
+ * Where the configure step ends. Both exits live here — commit the agent, or
+ * leave — because they are the two answers to one question, and reading them
* side by side is what makes the destructive one legible. A discard control
* parked elsewhere (say, a trash icon over the transcript) reads as "clear this
* chat" rather than "throw away what I am building".
*
- * `onDiscard` is optional: the manual route has nothing to abandon, its form is
- * gone the moment the user navigates away.
+ * The builder passes `onDiscard`: its conversation outlives the screen, so
+ * leaving it behind has to be an explicit choice. The manual route passes
+ * `onCancel` instead; its form has nothing to throw away.
*/
export function CreateAgentFooter({
+ stepIndex,
canCreate,
creating,
squad,
error,
onCreate,
+ onCancel,
onDiscard,
discarding = false,
}: {
+ stepIndex?: AgentCreateStep;
canCreate: boolean;
creating: boolean;
squad: boolean;
error: string | null;
onCreate: () => void;
+ onCancel?: () => void;
onDiscard?: () => void;
discarding?: boolean;
}) {
const { t } = useT("agents");
return (
- <div className="pe-chat-launcher sticky bottom-0 mt-8 flex items-center justify-between gap-3 border-t bg-background/95 py-3 pl-5 backdrop-blur">
- {error ? (
- <p
- role="alert"
- className="min-w-0 flex-1 break-words text-body text-destructive"
- >
- {error}
- </p>
- ) : null}
+ <CreateFlowFooter
+ stepIndex={stepIndex}
+ status={
+ error ? (
+ <p role="alert" className="min-w-0 flex-1 break-words text-body text-destructive">
+ {error}
+ </p>
+ ) : null
+ }
+ >
{onDiscard ? (
<Button
type="button"
variant="ghost"
- className="ml-auto shrink-0 text-muted-foreground hover:text-foreground"
+ className="text-muted-foreground hover:text-foreground"
onClick={onDiscard}
disabled={creating || discarding}
>
{t(($) => $.creation_studio.drafts.discard)}
</Button>
+ ) : onCancel ? (
+ <Button type="button" variant="ghost" onClick={onCancel}>
+ {t(($) => $.creation_studio.runtime_step.cancel)}
+ </Button>
) : null}
- <Button
- type="button"
- className={cn("shrink-0", !onDiscard && "ml-auto")}
- onClick={onCreate}
- disabled={!canCreate}
- >
+ <Button type="button" onClick={onCreate} disabled={!canCreate}>
{creating && <Loader2 className="size-4 animate-spin" />}
{creating
? t(($) => $.creation_studio.creating)
@@ -67,6 +108,6 @@ export function CreateAgentFooter({
? t(($) => $.creation_studio.create_and_add)
: t(($) => $.creation_studio.create_agent)}
</Button>
- </div>
+ </CreateFlowFooter>
);
}
diff --git a/packages/views/agents/create/create-agent-ui.test.ts b/packages/views/agents/create/create-agent-ui.test.ts
index 97af143881..a369e8dac6 100644
--- a/packages/views/agents/create/create-agent-ui.test.ts
+++ b/packages/views/agents/create/create-agent-ui.test.ts
@@ -134,7 +134,7 @@ describe("Agent creation errors", () => {
const error = screen.getByRole("alert");
const button = screen.getByRole("button", { name: "Create agent" });
- expect(error.parentElement).toBe(button.parentElement);
+ expect(error.closest("footer")).toContainElement(button);
expect(
error.compareDocumentPosition(button) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
diff --git a/packages/views/agents/create/create-flow-chrome.test.tsx b/packages/views/agents/create/create-flow-chrome.test.tsx
new file mode 100644
index 0000000000..a3b179442e
--- /dev/null
+++ b/packages/views/agents/create/create-flow-chrome.test.tsx
@@ -0,0 +1,112 @@
+// @vitest-environment jsdom
+
+import { cleanup, fireEvent, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Button } from "@multica/ui/components/ui/button";
+import { renderWithI18n } from "../../test/i18n";
+import { AgentCreateShell } from "./create-shell";
+import { CreateAgentFooter, CreateFlowFooter } from "./create-agent-footer";
+
+afterEach(cleanup);
+
+describe("AgentCreateShell", () => {
+ it("puts close, the title and the step indicator in one header", () => {
+ const onClose = vi.fn();
+ renderWithI18n(
+ <AgentCreateShell title="Create an agent" step="unused" stepIndex={2} onClose={onClose}>
+ <main />
+ </AgentCreateShell>,
+ );
+
+ const header = screen.getByRole("banner");
+ expect(
+ within(header).getByRole("heading", { name: "Create an agent" }),
+ ).toBeInTheDocument();
+
+ const steps = within(header).getByRole("list", { name: "Agent creation steps" });
+ const current = within(steps)
+ .getAllByRole("listitem")
+ .find((item) => item.getAttribute("aria-current") === "step");
+ expect(current).toHaveTextContent("Configure");
+ expect(within(steps).getByText("Choose runtime")).toBeInTheDocument();
+ expect(within(steps).getByText("Done")).toBeInTheDocument();
+
+ fireEvent.click(within(header).getByRole("button", { name: "Close" }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("names the screen instead of showing steps off the step path", () => {
+ renderWithI18n(
+ <AgentCreateShell
+ title="Create an agent"
+ step="Build through conversation"
+ onClose={vi.fn()}
+ >
+ <main />
+ </AgentCreateShell>,
+ );
+
+ const header = screen.getByRole("banner");
+ expect(within(header).getByText("Build through conversation")).toBeInTheDocument();
+ expect(within(header).queryByRole("list")).not.toBeInTheDocument();
+ expect(within(header).getByRole("button", { name: "Close" })).toBeInTheDocument();
+ });
+});
+
+describe("create flow footer", () => {
+ it("shows the step position next to Cancel and one Next", () => {
+ renderWithI18n(
+ <CreateFlowFooter stepIndex={1}>
+ <Button variant="ghost">Cancel</Button>
+ <Button>Next</Button>
+ </CreateFlowFooter>,
+ );
+
+ const footer = screen.getByRole("contentinfo");
+ expect(within(footer).getByText("Step 1 of 3")).toBeInTheDocument();
+ expect(within(footer).getAllByRole("button").map((b) => b.textContent)).toEqual([
+ "Cancel",
+ "Next",
+ ]);
+ });
+
+ it("ends the configure step with Cancel and Create agent", () => {
+ const onCreate = vi.fn();
+ const onCancel = vi.fn();
+ renderWithI18n(
+ <CreateAgentFooter
+ stepIndex={2}
+ canCreate
+ creating={false}
+ squad={false}
+ error={null}
+ onCreate={onCreate}
+ onCancel={onCancel}
+ />,
+ );
+
+ const footer = screen.getByRole("contentinfo");
+ expect(within(footer).getByText("Step 2 of 3")).toBeInTheDocument();
+ fireEvent.click(within(footer).getByRole("button", { name: "Cancel" }));
+ fireEvent.click(within(footer).getByRole("button", { name: "Create agent" }));
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(onCreate).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves out the step position where the flow has none", () => {
+ renderWithI18n(
+ <CreateAgentFooter
+ canCreate
+ creating={false}
+ squad={false}
+ error={null}
+ onCreate={vi.fn()}
+ onDiscard={vi.fn()}
+ />,
+ );
+
+ const footer = screen.getByRole("contentinfo");
+ expect(within(footer).queryByText(/Step \d of 3/)).not.toBeInTheDocument();
+ expect(within(footer).getByRole("button", { name: "Create agent" })).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/create/create-shell.tsx b/packages/views/agents/create/create-shell.tsx
index 25c3520a55..23c44f04da 100644
--- a/packages/views/agents/create/create-shell.tsx
+++ b/packages/views/agents/create/create-shell.tsx
@@ -1,36 +1,37 @@
"use client";
import { Fragment, type ReactNode } from "react";
-import { ArrowLeft, Check, X } from "@multica/ui/icons";
+import { Check, X } from "@multica/ui/icons";
import { IconButton } from "@multica/ui/components/common/icon-button";
+import { Separator } from "@multica/ui/components/ui/separator";
import { cn } from "@multica/ui/lib/utils";
+import { PageHeader } from "../../layout/page-header";
import { useT } from "../../i18n";
export type AgentCreateStep = 1 | 2 | 3;
+export const AGENT_CREATE_STEP_COUNT = 3;
+
/**
- * Chrome shared by every agent-creation route: the back control, the flow
- * title, and the current step. Each route owns what "back" means, so the shell
- * takes a handler rather than deriving it.
+ * Chrome shared by every agent-creation route: the close control, the flow
+ * title, and where the route sits in runtime → configure → done. Each route
+ * owns what leaving means, so the shell takes a handler rather than deriving
+ * it.
*/
export function AgentCreateShell({
title,
step,
stepIndex,
- onBack,
- backDisabled = false,
- closeIcon = false,
+ onClose,
chips,
children,
}: {
title: string;
+ /** Names the screen where there is no step position to show. */
step: string;
/** Position in runtime → configure → done. Omitted by off-path routes. */
stepIndex?: AgentCreateStep;
- onBack: () => void;
- backDisabled?: boolean;
- /** The flow is finished, so the control leaves it instead of going back. */
- closeIcon?: boolean;
+ onClose: () => void;
/** Right-aligned context badges (method, runtime). Hidden on small screens. */
chips?: ReactNode;
children: ReactNode;
@@ -38,37 +39,36 @@ export function AgentCreateShell({
const { t } = useT("agents");
return (
<div className="flex min-h-0 flex-1 flex-col bg-background">
- <header className="flex h-14 shrink-0 items-center gap-3 border-b px-5">
- <IconButton
- type="button"
- variant="ghost"
- size="icon"
- onClick={onBack}
- disabled={backDisabled}
- label={
- closeIcon
- ? t(($) => $.creation_studio.close)
- : t(($) => $.creation_studio.back)
- }
- tooltipSide="bottom"
- >
- {closeIcon ? (
- <X className="size-4" aria-hidden="true" />
+ <PageHeader
+ leading={
+ <IconButton
+ label={t(($) => $.creation_studio.close)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={onClose}
+ >
+ <X />
+ </IconButton>
+ }
+ >
+ <div className="flex min-w-0 flex-1 items-center gap-3">
+ <h1 className="min-w-0 truncate text-body font-medium">{title}</h1>
+ <Separator
+ orientation="vertical"
+ className="data-vertical:h-4 data-vertical:self-center"
+ />
+ {stepIndex ? (
+ <CreateStepper active={stepIndex} />
) : (
- <ArrowLeft className="size-4" aria-hidden="true" />
+ <p className="min-w-0 truncate text-body text-muted-foreground">{step}</p>
)}
- </IconButton>
- <div className="min-w-0">
- <h1 className="truncate text-body font-semibold">{title}</h1>
- <p className="truncate text-caption text-muted-foreground">{step}</p>
</div>
- {chips || stepIndex ? (
- <div className="ml-auto hidden items-center gap-4 text-caption text-muted-foreground sm:flex">
- {chips ? <div className="flex items-center gap-2">{chips}</div> : null}
- {stepIndex ? <CreateStepper active={stepIndex} /> : null}
+ {chips ? (
+ <div className="hidden shrink-0 items-center gap-2 text-caption text-muted-foreground sm:flex">
+ {chips}
</div>
) : null}
- </header>
+ </PageHeader>
{children}
</div>
);
@@ -91,7 +91,7 @@ function CreateStepper({ active }: { active: AgentCreateStep }) {
];
return (
<ol
- className="hidden items-center gap-2 lg:flex"
+ className="flex min-w-0 items-center gap-2 text-body text-muted-foreground"
aria-label={t(($) => $.creation_studio.steps.aria)}
>
{labels.map((label, index) => {
@@ -101,25 +101,25 @@ function CreateStepper({ active }: { active: AgentCreateStep }) {
return (
<Fragment key={label}>
{index > 0 ? (
- <li aria-hidden="true" className="h-px w-5 bg-border" />
+ <li aria-hidden="true" className="hidden h-px w-8 bg-border md:block" />
) : null}
<li
aria-current={current ? "step" : undefined}
className={cn(
- "flex items-center gap-1.5",
- current && "font-medium text-foreground",
+ "flex min-w-0 items-center gap-1.5",
+ current ? "font-medium text-foreground" : "hidden md:flex",
)}
>
<span
className={cn(
- "flex size-[18px] items-center justify-center rounded-full border text-micro tabular-nums",
+ "flex size-[18px] shrink-0 items-center justify-center rounded-full border text-micro tabular-nums",
current && "border-primary bg-primary text-primary-foreground",
done && "border-success/30 bg-success/10 text-success",
)}
>
{done ? <Check className="size-3" aria-hidden="true" /> : number}
</span>
- {label}
+ <span className="truncate">{label}</span>
</li>
</Fragment>
);
diff --git a/packages/views/agents/create/manual-create-agent-page.tsx b/packages/views/agents/create/manual-create-agent-page.tsx
index 5ee69ad9ed..0da01a8758 100644
--- a/packages/views/agents/create/manual-create-agent-page.tsx
+++ b/packages/views/agents/create/manual-create-agent-page.tsx
@@ -128,6 +128,14 @@ export function ManualCreateAgentPage() {
}),
);
+ // A duplicate arrives from the agents list, so going back returns there.
+ // Behind step 2 is step 1, so leaving the flow has to go forward to where it
+ // was opened from instead.
+ const leave = () =>
+ duplicateId
+ ? backOrReplace(paths.agents())
+ : navigation.push(squadId ? paths.squadDetail(squadId) : paths.agents());
+
// Hands the current draft to a builder conversation on the same runtime.
const [startingAi, setStartingAi] = useState(false);
const [aiError, setAiError] = useState<string | null>(null);
@@ -185,11 +193,7 @@ export function ManualCreateAgentPage() {
}
step={t(($) => $.creation_studio.steps.configure)}
stepIndex={duplicateId ? undefined : 2}
- // A duplicate arrives from the agents list, not from step 1, so it
- // returns to where it came from instead of offering a runtime to pick.
- onBack={() =>
- duplicateId ? backOrReplace(paths.agents()) : changeRuntime()
- }
+ onClose={leave}
chips={
duplicateId && form.selectedRuntime ? (
<AgentCreateChip>
@@ -261,14 +265,16 @@ export function ManualCreateAgentPage() {
}
/>
</div>
- <CreateAgentFooter
- canCreate={canCreate}
- creating={submit.creating}
- squad={!!squadId}
- error={submit.formError}
- onCreate={() => void submit.create()}
- />
</div>
+ <CreateAgentFooter
+ stepIndex={duplicateId ? undefined : 2}
+ canCreate={canCreate}
+ creating={submit.creating}
+ squad={!!squadId}
+ error={submit.formError}
+ onCreate={() => void submit.create()}
+ onCancel={leave}
+ />
</AgentCreateShell>
);
}
diff --git a/packages/views/autopilots/components/autopilot-detail-page.test.tsx b/packages/views/autopilots/components/autopilot-detail-page.test.tsx
new file mode 100644
index 0000000000..cf637929f3
--- /dev/null
+++ b/packages/views/autopilots/components/autopilot-detail-page.test.tsx
@@ -0,0 +1,229 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Autopilot, AutopilotRun, AutopilotTrigger } from "@multica/core/types";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import { renderWithI18n } from "../../test/i18n";
+
+const update = vi.fn();
+const runNow = vi.fn();
+let detail: { autopilot: Autopilot; triggers: AutopilotTrigger[]; collaborators: [] };
+let runs: AutopilotRun[];
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ autopilots: () => "/ws/autopilots",
+ autopilotDetail: (id: string) => `/ws/autopilots/${id}`,
+ issueDetail: (id: string) => `/ws/issues/${id}`,
+ projectDetail: (id: string) => `/ws/projects/${id}`,
+ agentDetail: (id: string) => `/ws/agents/${id}`,
+ }),
+}));
+vi.mock("@multica/core/api", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/api")>();
+ return { ...actual, api: { ...actual.api, getBaseUrl: () => "https://api.test" } };
+});
+vi.mock("@multica/core/autopilots/queries", () => ({
+ autopilotDetailOptions: () => ({ queryKey: ["autopilot"], queryFn: async () => detail }),
+ autopilotRunsOptions: () => ({ queryKey: ["runs"], queryFn: async () => runs }),
+ autopilotRunOptions: () => ({ queryKey: ["run"], queryFn: async () => null }),
+}));
+vi.mock("@multica/core/autopilots/mutations", () => ({
+ useUpdateAutopilot: () => ({ mutate: update }),
+ useDeleteAutopilot: () => ({ mutateAsync: vi.fn() }),
+ useCreateAutopilotTrigger: () => ({ mutateAsync: vi.fn() }),
+ useDeleteAutopilotTrigger: () => ({ mutateAsync: vi.fn() }),
+ useRotateAutopilotTriggerWebhookToken: () => ({ mutateAsync: vi.fn(), isPending: false }),
+}));
+vi.mock("@multica/core/projects/queries", () => ({
+ projectDetailOptions: () => ({ queryKey: ["project"], queryFn: async () => null }),
+ projectListOptions: () => ({ queryKey: ["projects"], queryFn: async () => [] }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({ queryKey: ["members"], queryFn: async () => [] }),
+ agentListOptions: () => ({ queryKey: ["agents"], queryFn: async () => [] }),
+ squadListOptions: () => ({ queryKey: ["squads"], queryFn: async () => [] }),
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: (_type: string, id: string) => (id === "agent-1" ? "Eve" : "Jiayuan") }),
+}));
+vi.mock("./use-run-autopilot-now", () => ({
+ useRunAutopilotNow: () => ({ runNow, isPending: false }),
+}));
+vi.mock("./autopilot-dialog", () => ({
+ AutopilotDialog: () => <div role="dialog">Edit autopilot dialog</div>,
+}));
+vi.mock("./edit-schedule-trigger-dialog", () => ({ EditScheduleTriggerDialog: () => null }));
+vi.mock("./webhook-deliveries-section", () => ({ WebhookDeliveriesSection: () => null }));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("../../common/task-transcript", () => ({ TranscriptButton: () => null }));
+vi.mock("../../search/register-context", () => ({ useRegisterCommandBarContext: () => {} }));
+vi.mock("../../editor", () => ({
+ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+import { AutopilotDetailPage } from "./autopilot-detail-page";
+
+function makeAutopilot(overrides: Partial<Autopilot> = {}): Autopilot {
+ return {
+ id: "ap-1",
+ workspace_id: "ws",
+ title: "Daily Sync",
+ description: "Summarize what changed yesterday.",
+ status: "active",
+ assignee_type: "agent",
+ assignee_id: "agent-1",
+ execution_mode: "create_issue",
+ project_id: null,
+ created_by_type: "member",
+ created_by_id: "member-1",
+ subscribers: [],
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ } as unknown as Autopilot;
+}
+
+const scheduleTrigger = {
+ id: "trg-1",
+ autopilot_id: "ap-1",
+ kind: "schedule",
+ enabled: true,
+ cron_expression: "0 9 * * 1-5",
+ timezone: "Asia/Shanghai",
+ next_run_at: "2126-07-14T01:00:00Z",
+ webhook_token: null,
+ label: null,
+ last_fired_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+} as AutopilotTrigger;
+
+function run(overrides: Partial<AutopilotRun>): AutopilotRun {
+ return {
+ id: "run",
+ autopilot_id: "ap-1",
+ source: "schedule",
+ status: "issue_created",
+ issue_id: null,
+ task_id: null,
+ failure_reason: null,
+ triggered_at: "2026-10-30T01:00:00Z",
+ completed_at: null,
+ created_at: "2026-10-30T01:00:00Z",
+ ...overrides,
+ } as unknown as AutopilotRun;
+}
+
+// The panel's resize handle claims every pointerdown in jsdom, where all boxes
+// measure 0×0 — so the menu trigger only sees a plain click.
+function openMoreActions() {
+ fireEvent.click(screen.getByRole("button", { name: "More actions" }));
+}
+
+function mount() {
+ const adapter: NavigationAdapter = {
+ pathname: "/ws/autopilots/ap-1",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ getShareableUrl: (p) => p,
+ };
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return renderWithI18n(
+ <QueryClientProvider client={client}>
+ <NavigationProvider value={adapter}>
+ <AutopilotDetailPage autopilotId="ap-1" />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ update.mockReset();
+ runNow.mockReset();
+ detail = { autopilot: makeAutopilot(), triggers: [scheduleTrigger], collaborators: [] };
+ runs = [
+ run({ id: "r1", issue_id: "issue-24" }),
+ run({ id: "r2", status: "failed", failure_reason: "Runtime is offline" }),
+ ];
+});
+
+describe("AutopilotDetailPage", () => {
+ it("puts the list in the breadcrumb and runs the autopilot from the one solid action", async () => {
+ const user = userEvent.setup();
+ mount();
+ const header = await screen.findByRole("banner");
+ await within(header).findByText("Daily Sync");
+
+ expect(within(header).getByRole("link", { name: "Autopilots" })).toHaveAttribute("href", "/ws/autopilots");
+ await user.click(within(header).getByRole("button", { name: "Run now" }));
+ expect(runNow).toHaveBeenCalledWith("ap-1");
+ });
+
+ it("can't run a paused autopilot", async () => {
+ detail.autopilot = makeAutopilot({ status: "paused" });
+ mount();
+
+ expect(await screen.findByRole("button", { name: "Run now" })).toBeDisabled();
+ });
+
+ it("keeps edit, copy link and delete in the ⋯ menu", async () => {
+ const user = userEvent.setup();
+ mount();
+ await screen.findByRole("heading", { name: "Daily Sync", level: 1 });
+
+ openMoreActions();
+ expect(await screen.findByRole("menuitem", { name: "Copy link" })).toBeInTheDocument();
+ expect(screen.getByRole("menuitem", { name: "Delete autopilot" })).toBeInTheDocument();
+ await user.click(screen.getByRole("menuitem", { name: "Edit" }));
+ expect(await screen.findByRole("dialog")).toHaveTextContent("Edit autopilot dialog");
+ });
+
+ it("pauses from the panel's status switch", async () => {
+ const user = userEvent.setup();
+ mount();
+
+ await user.click(await screen.findByRole("switch", { name: "Pause autopilot" }));
+ expect(update).toHaveBeenCalledWith({ id: "ap-1", status: "paused" }, expect.anything());
+ });
+
+ it("lays out prompt, triggers and run history as sections", async () => {
+ mount();
+ const identity = await screen.findByRole("heading", { name: "Daily Sync", level: 1 });
+ expect(identity.parentElement?.parentElement).toHaveTextContent("Eve creates an issue each run");
+
+ const prompt = screen.getByRole("heading", { name: "Prompt", level: 2 }).closest("section")!;
+ expect(within(prompt).getByText("Summarize what changed yesterday.")).toBeVisible();
+ expect(within(prompt).getByRole("button", { name: "Edit" })).toBeVisible();
+
+ const triggers = screen.getByRole("heading", { name: "Triggers", level: 2 }).closest("section")!;
+ expect(within(triggers).getByText("1")).toBeVisible();
+ expect(within(triggers).getByRole("button", { name: "Add trigger" })).toBeVisible();
+ expect(within(triggers).getByText(/Asia\/Shanghai/)).toBeVisible();
+
+ const history = screen.getByRole("heading", { name: "Run history", level: 2 }).closest("section")!;
+ expect(await within(history).findByText("2")).toBeVisible();
+ expect(within(history).getByRole("link", { name: /Issue linked/ })).toHaveAttribute("href", "/ws/issues/issue-24");
+ expect(within(history).getByText("Runtime is offline")).toHaveClass("text-destructive");
+ });
+
+ it("shows a reader the page without write controls", async () => {
+ detail.autopilot = makeAutopilot({ can_write: false } as Partial<Autopilot>);
+ mount();
+ await screen.findByRole("heading", { name: "Daily Sync", level: 1 });
+
+ expect(screen.queryByRole("button", { name: "Run now" })).toBeNull();
+ expect(screen.getByRole("switch", { name: "Pause autopilot" })).toHaveAttribute("aria-disabled", "true");
+ expect(screen.queryByRole("button", { name: "Add trigger" })).toBeNull();
+ openMoreActions();
+ expect(await screen.findByRole("menuitem", { name: "Copy link" })).toBeInTheDocument();
+ expect(screen.queryByRole("menuitem", { name: "Edit" })).toBeNull();
+ expect(screen.queryByRole("menuitem", { name: "Delete autopilot" })).toBeNull();
+ });
+});
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 1800dfe1ce..84e720d6c3 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -1,9 +1,9 @@
"use client";
-import { useMemo, useState } from "react";
+import { useMemo, useState, type ReactNode } from "react";
import {
Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil,
- Ban, ChevronDown, ChevronRight,
+ Ban, ChevronDown, ChevronRight, MoreHorizontal, Link2, ArrowUpRight, FilePlus2,
Webhook, RotateCw, Server,
} from "@multica/ui/icons";
import { useQuery } from "@tanstack/react-query";
@@ -21,20 +21,30 @@ import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
+import { memberListOptions } from "@multica/core/workspace/queries";
import { useNavigation, AppLink } from "../../navigation";
-import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
import { ActorAvatar } from "../../common/actor-avatar";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Button } from "@multica/ui/components/ui/button";
import { IconButton } from "@multica/ui/components/common/icon-button";
import { Switch } from "@multica/ui/components/ui/switch";
import { cn } from "@multica/ui/lib/utils";
+import { copyText } from "@multica/ui/lib/clipboard";
import { toast } from "sonner";
import {
Dialog,
DialogContent,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import {
AlertDialog,
AlertDialogAction,
@@ -55,9 +65,9 @@ import { formatInTimeZone } from "../../common/format-in-time-zone";
import { SegmentedToggle } from "../../common/segmented-toggle";
import { useScheduleSubmitGate } from "./schedule-editor/validate";
import type {
+ Autopilot,
AutopilotExecutionMode,
AutopilotRun,
- AutopilotSubscriber,
AutopilotTrigger,
} from "@multica/core/types";
import type { AgentTask } from "@multica/core/types/agent";
@@ -69,9 +79,45 @@ import { useRunAutopilotNow } from "./use-run-autopilot-now";
import { useRegisterCommandBarContext } from "../../search/register-context";
import { WebhookPayloadPreview } from "./webhook-payload-preview";
import { WebhookDeliveriesSection } from "./webhook-deliveries-section";
+import { AgentPicker } from "./pickers/agent-picker";
+import { ProjectPicker } from "../../projects/components/project-picker";
import { ProjectIcon } from "../../projects/components/project-icon";
+import {
+ PickerEmpty,
+ PickerItem,
+ PropertyPicker,
+} from "../../issues/components/pickers/property-picker";
+import { matchesPinyin } from "../../editor/extensions/pinyin-match";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIconMark,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectPanelSection,
+ ObjectProperty,
+ ObjectSection,
+ ObjectSectionAction,
+ ObjectSectionCard,
+} from "../../layout/object-page";
import { useT } from "../../i18n";
-import { PageHeader } from "../../layout/page-header";
+
+const LAYOUT_ID = "multica_autopilot_detail_layout";
+
+const TRIGGER_ICON: Record<AutopilotTrigger["kind"], typeof Clock> = {
+ schedule: Clock,
+ webhook: Webhook,
+ api: Zap,
+};
+
+// A property value that opens its picker; the row around it carries the hover.
+const PROPERTY_TRIGGER =
+ "flex min-w-0 items-center gap-1.5 rounded-sm text-caption outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-default";
+
+const OUTPUT_MODES: AutopilotExecutionMode[] = ["create_issue", "run_only"];
+const OUTPUT_MODE_ICONS: Record<AutopilotExecutionMode, typeof FilePlus2> = {
+ create_issue: FilePlus2,
+ run_only: Play,
+};
// A run that already happened is an instant in the reader's day, so it reads in
// the reader's zone (no timeZone passed). A run that is still to come belongs to
@@ -80,13 +126,13 @@ import { PageHeader } from "../../layout/page-header";
type RunStatus = "issue_created" | "running" | "skipped" | "completed" | "failed";
const RUN_VISUAL: Record<RunStatus, { color: string; icon: typeof CheckCircle2; spin?: boolean }> = {
- issue_created: { color: "text-blue-500", icon: Clock },
- running: { color: "text-blue-500", icon: Loader2, spin: true },
+ issue_created: { color: "text-info", icon: Clock },
+ running: { color: "text-info", icon: Loader2, spin: true },
// `skipped` (admission check found the assignee runtime offline,
// MUL-1899) is muted so it doesn't read as a failure-ratio inflator.
// The row still shows failure_reason which carries the skip context.
skipped: { color: "text-muted-foreground", icon: Ban },
- completed: { color: "text-emerald-500", icon: CheckCircle2 },
+ completed: { color: "text-success", icon: CheckCircle2 },
failed: { color: "text-destructive", icon: XCircle },
};
@@ -114,6 +160,7 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strin
const status = (RUN_VISUAL[run.status as RunStatus] ? (run.status as RunStatus) : "issue_created");
const visual = RUN_VISUAL[status];
const StatusIcon = visual.icon;
+ const statusLabel = t(($) => $.run_status[status]);
// For runs with a task_id (run_only mode), build a minimal AgentTask so
// TranscriptButton can lazy-load the execution transcript.
@@ -140,22 +187,25 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strin
const content = (
<>
- <StatusIcon className={cn("h-4 w-4 shrink-0", visual.color, visual.spin && "animate-spin")} />
- <span className={cn("w-24 shrink-0 text-caption font-medium", visual.color)}>
- {t(($) => $.run_status[status])}
+ <span className="flex shrink-0" title={statusLabel}>
+ <StatusIcon aria-hidden="true" className={cn("size-4", visual.color, visual.spin && "animate-spin")} />
+ <span className="sr-only">{statusLabel}</span>
</span>
- <span className="w-20 shrink-0 text-caption text-muted-foreground">
- {t(($) => $.run_source[run.source as "schedule" | "manual" | "webhook" | "api"]) ?? run.source}
+ <span className="w-28 shrink-0 text-caption tabular-nums text-muted-foreground">
+ {formatInTimeZone(run.triggered_at || run.created_at, undefined, i18n.language)}
</span>
- <span className="flex-1 min-w-0 text-caption text-muted-foreground truncate">
- {run.issue_id ? (
- t(($) => $.run.issue_linked)
- ) : run.failure_reason ? (
- <span className="text-destructive">{run.failure_reason}</span>
- ) : null}
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate",
+ !run.issue_id && run.failure_reason ? "text-destructive" : "text-foreground",
+ )}
+ >
+ {run.issue_id
+ ? t(($) => $.run.issue_linked)
+ : run.failure_reason || statusLabel}
</span>
- <span className="w-32 shrink-0 text-right text-caption text-muted-foreground tabular-nums">
- {formatInTimeZone(run.triggered_at || run.created_at, undefined, i18n.language)}
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.run_source[run.source as "schedule" | "manual" | "webhook" | "api"]) ?? run.source}
</span>
{syntheticTask && !run.issue_id && (
<TranscriptButton
@@ -173,7 +223,7 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strin
</>
);
- const rowClass = "flex items-center gap-3 px-4 py-2.5 text-body hover:bg-accent/30 transition-colors";
+ const rowClass = "flex min-h-10 items-center gap-3 px-3 py-2 text-body transition-colors hover:bg-accent/30";
if (run.issue_id) {
return (
@@ -199,14 +249,14 @@ function RunHistoryList({
const skippedRuns = runs.filter((run) => run.status === "skipped");
return (
- <div className="rounded-md border overflow-hidden">
+ <ObjectSectionCard>
{visibleRuns.map((run) => (
<RunRow key={run.id} run={run} agentId={agentId} agentName={agentName} />
))}
{skippedRuns.length > 0 && (
<SkippedRunsGroup runs={skippedRuns} agentId={agentId} agentName={agentName} />
)}
- </div>
+ </ObjectSectionCard>
);
}
@@ -225,29 +275,28 @@ function SkippedRunsGroup({
const ToggleIcon = open ? ChevronDown : ChevronRight;
return (
- <div className="border-t bg-muted/20">
+ <div className="bg-muted/20">
<button
type="button"
- className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-body hover:bg-accent/30 transition-colors"
+ className="flex min-h-10 w-full items-center gap-3 px-3 py-2 text-left text-body transition-colors hover:bg-accent/30"
onClick={() => setOpen((value) => !value)}
aria-expanded={open}
>
- <ToggleIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
- <Ban className="h-4 w-4 shrink-0 text-muted-foreground" />
- <span className="w-24 shrink-0 text-caption font-medium text-muted-foreground">
- {t(($) => $.run.skipped_group.label)}
- </span>
- <span className="flex-1 min-w-0 text-caption text-muted-foreground truncate">
- {t(($) => $.run.skipped_group.summary, { count: runs.length })}
- </span>
+ <ToggleIcon className="size-4 shrink-0 text-muted-foreground" />
{latestRun && (
- <span className="w-32 shrink-0 text-right text-caption text-muted-foreground tabular-nums">
+ <span className="w-28 shrink-0 text-caption tabular-nums text-muted-foreground">
{formatInTimeZone(latestRun.triggered_at || latestRun.created_at, undefined, i18n.language)}
</span>
)}
+ <span className="min-w-0 flex-1 truncate text-muted-foreground">
+ <span className="font-medium">{t(($) => $.run.skipped_group.label)}</span>
+ {" · "}
+ {t(($) => $.run.skipped_group.summary, { count: runs.length })}
+ </span>
+ <Ban className="size-4 shrink-0 text-muted-foreground" />
</button>
{open && (
- <div className="border-t bg-background">
+ <div className="divide-y border-t bg-background">
{runs.map((run) => (
<RunRow key={run.id} run={run} agentId={agentId} agentName={agentName} />
))}
@@ -311,7 +360,7 @@ export function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: Autopi
}
};
- const Icon = isWebhook ? Webhook : isApi ? Zap : Clock;
+ const Icon = TRIGGER_ICON[trigger.kind] ?? Clock;
const showWebhookUrlRow = isWebhook && webhookUrl;
// null when the expression is beyond the structured model — those rows keep
// showing the raw cron on its own.
@@ -319,22 +368,22 @@ export function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: Autopi
? parseCron(trigger.cron_expression, trigger.timezone ?? "UTC")
: null;
const scheduleDescription = scheduleConfig ? describeSchedule(scheduleConfig) : null;
+ const scheduleText = trigger.cron_expression
+ ? [scheduleDescription ?? trigger.cron_expression, trigger.timezone].filter(Boolean).join(" · ")
+ : null;
- // Delete control extracted so a webhook trigger can render it inline
- // with Copy / Rotate on the URL action row (where the other action
- // buttons live), while schedule / api triggers — which have no URL row
- // — keep it pinned to the row's top-right corner. Without this the
- // trash icon visually floats above the URL action buttons because the
- // outer flex uses `items-start`.
+ // A webhook trigger's Delete sits with Copy / Rotate on its URL row, where
+ // the other actions on that trigger live; every other kind keeps it at the
+ // end of the summary line.
const deleteButton = canWrite ? (
<IconButton
- size="icon"
+ size="icon-sm"
variant="ghost"
- className="h-7 w-7 shrink-0"
+ className="shrink-0 text-muted-foreground"
onClick={() => setConfirmOpen(true)}
label={t(($) => $.trigger_row.delete_dialog.confirm)}
>
- <Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
+ <Trash2 className="size-3.5" />
</IconButton>
) : null;
@@ -345,97 +394,88 @@ export function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: Autopi
const editButton =
canWrite && trigger.kind === "schedule" ? (
<IconButton
- size="icon"
+ size="icon-sm"
variant="ghost"
- className="h-7 w-7 shrink-0"
+ className="shrink-0 text-muted-foreground"
onClick={() => setEditOpen(true)}
label={t(($) => $.trigger_row.edit_schedule)}
>
- <Pencil className="h-3.5 w-3.5 text-muted-foreground" />
+ <Pencil className="size-3.5" />
</IconButton>
) : null;
return (
- <div className="flex items-start gap-3 rounded-md border px-3 py-2">
- <Icon className="h-4 w-4 shrink-0 text-muted-foreground mt-0.5" />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-body font-medium">{t(($) => $.trigger_kind[trigger.kind])}</span>
- {trigger.label && (
- <span className="text-caption text-muted-foreground">({trigger.label})</span>
- )}
- {!trigger.enabled && (
- <span className="text-caption bg-muted px-1.5 py-0.5 rounded-xs">
- {t(($) => $.trigger_row.disabled_badge)}
- </span>
- )}
- {isApi && (
- <span className="text-caption bg-muted px-1.5 py-0.5 rounded-xs">
- {t(($) => $.trigger_row.deprecated_badge)}
- </span>
- )}
- </div>
- {trigger.cron_expression && (
- // The plain-language line leads; the raw expression drops to a
- // secondary line so the two never run together as one blob.
- <div className="mt-0.5 space-y-0.5">
- <div className="text-caption text-muted-foreground">
- {scheduleDescription ?? trigger.cron_expression}
- {trigger.timezone && ` (${trigger.timezone})`}
- </div>
- {scheduleDescription !== null && scheduleConfig !== null && (
- // Fields only: the zone already reads out in the sentence above,
- // where a person can use it — same rule as the editor's readback.
- <div className="font-mono text-micro text-muted-foreground">
- {cronFields(scheduleConfig)}
- </div>
- )}
- </div>
+ <div className="px-3 py-2">
+ <div className="flex min-h-7 items-center gap-2">
+ <Icon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="shrink-0 text-body font-medium">{t(($) => $.trigger_kind[trigger.kind])}</span>
+ {trigger.label && (
+ <span className="min-w-0 shrink truncate text-caption text-muted-foreground">({trigger.label})</span>
)}
- {/* A disabled trigger keeps the next_run_at it had — the dispatcher
- filters on `enabled` instead of clearing it — so the row would
- otherwise carry the Disabled badge and a promise to run at 09:00
- in the same breath. The badge is the true one. */}
- {trigger.next_run_at && trigger.enabled && (
- <div className="text-caption text-muted-foreground">
- {t(($) => $.trigger_row.next_label, {
- date: formatInTimeZone(
- trigger.next_run_at,
- trigger.timezone ?? undefined,
- i18n.language,
- ),
- })}
- </div>
+ {!trigger.enabled && (
+ <span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-caption">
+ {t(($) => $.trigger_row.disabled_badge)}
+ </span>
)}
- {showWebhookUrlRow && (
- <div className="mt-1.5">
- <WebhookUrlField
- url={webhookUrl}
- actions={
- <>
- {canWrite && (
- <IconButton
- size="icon"
- variant="ghost"
- className="h-7 w-7 shrink-0"
- onClick={() => setRotateOpen(true)}
- label={t(($) => $.trigger_row.rotate_url)}
- disabled={rotateToken.isPending}
- >
- <RotateCw className={cn("h-3.5 w-3.5 text-muted-foreground", rotateToken.isPending && "animate-spin")} />
- </IconButton>
- )}
- {deleteButton}
- </>
- }
- />
- </div>
+ {isApi && (
+ <span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-caption">
+ {t(($) => $.trigger_row.deprecated_badge)}
+ </span>
)}
- </div>
- {!showWebhookUrlRow && (
- <div className="flex shrink-0 items-center gap-0.5">
+ {scheduleText && (
+ <span className="min-w-0 truncate text-caption text-muted-foreground" title={scheduleText}>
+ {scheduleText}
+ </span>
+ )}
+ <div className="ml-auto flex shrink-0 items-center gap-0.5">
+ {/* A disabled trigger keeps the next_run_at it had — the dispatcher
+ filters on `enabled` instead of clearing it — so the row would
+ otherwise carry the Disabled badge and a promise to run at 09:00
+ in the same breath. The badge is the true one. */}
+ {trigger.next_run_at && trigger.enabled && (
+ <span className="mr-1 hidden text-caption tabular-nums text-muted-foreground sm:inline">
+ {t(($) => $.trigger_row.next_label, {
+ date: formatInTimeZone(
+ trigger.next_run_at,
+ trigger.timezone ?? undefined,
+ i18n.language,
+ ),
+ })}
+ </span>
+ )}
{editButton}
- {deleteButton}
+ {!showWebhookUrlRow && deleteButton}
+ </div>
+ </div>
+ {scheduleDescription !== null && scheduleConfig !== null && (
+ // Fields only: the zone already reads out in the line above, where a
+ // person can use it — same rule as the editor's readback.
+ <div className="pl-6 font-mono text-micro text-muted-foreground">
+ {cronFields(scheduleConfig)}
+ </div>
+ )}
+ {showWebhookUrlRow && (
+ <div className="mt-1.5 pl-6">
+ <WebhookUrlField
+ url={webhookUrl}
+ actions={
+ <>
+ {canWrite && (
+ <IconButton
+ size="icon"
+ variant="ghost"
+ className="h-7 w-7 shrink-0"
+ onClick={() => setRotateOpen(true)}
+ label={t(($) => $.trigger_row.rotate_url)}
+ disabled={rotateToken.isPending}
+ >
+ <RotateCw className={cn("h-3.5 w-3.5 text-muted-foreground", rotateToken.isPending && "animate-spin")} />
+ </IconButton>
+ )}
+ {deleteButton}
+ </>
+ }
+ />
</div>
)}
<AlertDialog open={confirmOpen} onOpenChange={(v) => { if (!v && !deleting) setConfirmOpen(false); }}>
@@ -640,42 +680,306 @@ function AddTriggerDialog({
);
}
-// Read-only chip row; edits flow through AutopilotDialog → SubscriberMultiSelect
-// so the detail page never holds in-flight selection state.
-function SubscriberChips({
- subscribers,
-}: {
- subscribers: AutopilotSubscriber[] | undefined;
-}) {
+/**
+ * Member subscribers as one property: the picker edits a draft while it is
+ * open and saves the whole list once on close, because the server replaces
+ * the list on every write.
+ */
+function SubscribersProperty({ autopilot, canWrite }: { autopilot: Autopilot; canWrite: boolean }) {
const { t } = useT("autopilots");
+ const wsId = useWorkspaceId();
const { getActorName } = useActorName();
- const members = (subscribers ?? []).filter((s) => s.user_type === "member");
- if (members.length === 0) {
- return (
- <div className="mt-1 text-body text-muted-foreground">
- {t(($) => $.detail.field_subscribers_none)}
- </div>
+ const updateAutopilot = useUpdateAutopilot();
+ const { data: members = [] } = useQuery({ ...memberListOptions(wsId), enabled: canWrite });
+ const [open, setOpen] = useState(false);
+ const [filter, setFilter] = useState("");
+ const [draft, setDraft] = useState<string[] | null>(null);
+
+ const savedIds = useMemo(
+ () => (autopilot.subscribers ?? []).filter((s) => s.user_type === "member").map((s) => s.user_id),
+ [autopilot.subscribers],
+ );
+ const selectedIds = draft ?? savedIds;
+
+ const value =
+ selectedIds.length === 0 ? (
+ <span className="truncate text-muted-foreground">{t(($) => $.detail.field_subscribers_none)}</span>
+ ) : selectedIds.length === 1 ? (
+ <>
+ <ActorAvatar actorType="member" actorId={selectedIds[0]!} size="xs" />
+ <span className="truncate">{getActorName("member", selectedIds[0]!)}</span>
+ </>
+ ) : (
+ <>
+ <span className="flex shrink-0 items-center -space-x-1">
+ {selectedIds.slice(0, 4).map((id) => (
+ <span key={id} className="inline-flex rounded-full ring-2 ring-background">
+ <ActorAvatar actorType="member" actorId={id} size="xs" />
+ </span>
+ ))}
+ </span>
+ <span className="truncate tabular-nums text-muted-foreground">{selectedIds.length}</span>
+ </>
);
- }
+
+ if (!canWrite) return value;
+
+ const query = filter.trim().toLowerCase();
+ const filtered = members.filter(
+ (m) => !query || m.name.toLowerCase().includes(query) || matchesPinyin(m.name, query),
+ );
+
+ const handleOpenChange = (next: boolean) => {
+ setOpen(next);
+ if (next) {
+ setDraft(savedIds);
+ return;
+ }
+ setFilter("");
+ const changed =
+ draft !== null &&
+ (draft.length !== savedIds.length || draft.some((id) => !savedIds.includes(id)));
+ setDraft(null);
+ if (!changed) return;
+ updateAutopilot.mutate(
+ {
+ id: autopilot.id,
+ subscribers: draft.map((user_id) => ({ user_type: "member" as const, user_id })),
+ },
+ { onError: () => toast.error(t(($) => $.dialog.toast_update_failed)) },
+ );
+ };
+
+ const toggle = (userId: string) => {
+ setDraft((prev) => {
+ const current = prev ?? savedIds;
+ return current.includes(userId) ? current.filter((id) => id !== userId) : [...current, userId];
+ });
+ };
+
return (
- <div className="mt-1 flex flex-wrap gap-1.5">
- {members.map((s) => (
- <span
- key={`${s.user_type}:${s.user_id}`}
- className="inline-flex items-center gap-1 rounded-full border bg-background px-2 py-0.5 text-caption"
- >
- <ActorAvatar actorType="member" actorId={s.user_id} size="xs" />
- <span className="max-w-[14rem] truncate">
- {getActorName("member", s.user_id)}
- </span>
- </span>
- ))}
+ <PropertyPicker
+ open={open}
+ onOpenChange={handleOpenChange}
+ width="w-64"
+ align="start"
+ searchable
+ searchPlaceholder={t(($) => $.dialog.subscribers_search_placeholder)}
+ onSearchChange={setFilter}
+ triggerRender={<button type="button" className={PROPERTY_TRIGGER} />}
+ trigger={value}
+ >
+ {filtered.length === 0 ? (
+ <PickerEmpty />
+ ) : (
+ filtered.map((m) => (
+ <PickerItem key={m.user_id} selected={selectedIds.includes(m.user_id)} onClick={() => toggle(m.user_id)}>
+ <ActorAvatar actorType="member" actorId={m.user_id} size="sm" />
+ <span className="truncate">{m.name}</span>
+ </PickerItem>
+ ))
+ )}
+ </PropertyPicker>
+ );
+}
+
+function AutopilotProperties({ autopilot, canWrite }: { autopilot: Autopilot; canWrite: boolean }) {
+ const { t } = useT("autopilots");
+ const wsId = useWorkspaceId();
+ const wsPaths = useWorkspacePaths();
+ const { getActorName } = useActorName();
+ const updateAutopilot = useUpdateAutopilot();
+ const projectId = autopilot.project_id ?? null;
+ const { data: project, isLoading: projectLoading } = useQuery({
+ ...projectDetailOptions(wsId, projectId ?? ""),
+ enabled: Boolean(projectId),
+ });
+
+ const update = (fields: Omit<Parameters<typeof updateAutopilot.mutate>[0], "id">) =>
+ updateAutopilot.mutate(
+ { id: autopilot.id, ...fields },
+ { onError: () => toast.error(t(($) => $.dialog.toast_update_failed)) },
+ );
+
+ const mode = autopilot.execution_mode as AutopilotExecutionMode;
+ const ModeIcon = OUTPUT_MODE_ICONS[mode] ?? FilePlus2;
+
+ const assigneeValue = (
+ <>
+ <ActorAvatar
+ actorType={autopilot.assignee_type}
+ actorId={autopilot.assignee_id}
+ size="xs"
+ enableHoverCard={autopilot.assignee_type === "agent"}
+ showStatusDot={autopilot.assignee_type === "agent"}
+ />
+ <span className="truncate">{getActorName(autopilot.assignee_type, autopilot.assignee_id)}</span>
+ </>
+ );
+
+ const projectValue = !projectId ? (
+ <span className="truncate text-muted-foreground">{t(($) => $.detail.no_project)}</span>
+ ) : projectLoading ? (
+ <Skeleton className="h-4 w-24" />
+ ) : project ? (
+ <>
+ <ProjectIcon project={project} size="sm" />
+ <span className="truncate">{project.title}</span>
+ </>
+ ) : (
+ <span className="truncate text-muted-foreground">{t(($) => $.detail.project_unavailable)}</span>
+ );
+
+ return (
+ <>
+ <ObjectProperty label={t(($) => $.page.table.status)}>
+ <Switch
+ size="sm"
+ checked={autopilot.status === "active"}
+ onCheckedChange={(checked) => update({ status: checked ? "active" : "paused" })}
+ disabled={!canWrite || autopilot.status === "archived"}
+ aria-label={
+ autopilot.status === "active"
+ ? t(($) => $.detail.pause_aria)
+ : t(($) => $.detail.activate_aria)
+ }
+ />
+ <span className="truncate">{t(($) => $.status[autopilot.status])}</span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.field_agent)}>
+ {canWrite ? (
+ <AgentPicker
+ assignee={{ type: autopilot.assignee_type, id: autopilot.assignee_id }}
+ onChange={(next) => {
+ if (next.type === autopilot.assignee_type && next.id === autopilot.assignee_id) return;
+ update({ assignee_type: next.type, assignee_id: next.id });
+ }}
+ triggerRender={<button type="button" className={PROPERTY_TRIGGER} />}
+ trigger={assigneeValue}
+ />
+ ) : (
+ assigneeValue
+ )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.field_output_mode)}>
+ {canWrite ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger render={<button type="button" className={PROPERTY_TRIGGER} />}>
+ <ModeIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{t(($) => $.execution_mode[mode])}</span>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-auto min-w-44">
+ <DropdownMenuRadioGroup
+ value={mode}
+ onValueChange={(next) => {
+ if (next !== mode) update({ execution_mode: next as AutopilotExecutionMode });
+ }}
+ >
+ {OUTPUT_MODES.map((key) => {
+ const Icon = OUTPUT_MODE_ICONS[key];
+ return (
+ <DropdownMenuRadioItem key={key} value={key}>
+ <Icon className="size-3.5 text-muted-foreground" />
+ {t(($) => $.execution_mode[key])}
+ </DropdownMenuRadioItem>
+ );
+ })}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <>
+ <ModeIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{t(($) => $.execution_mode[mode])}</span>
+ </>
+ )}
+ </ObjectProperty>
+ {/* Shown for BOTH output modes (MUL-6681): a run_only autopilot's
+ project decides its execution environment (repository /
+ local_directory, and therefore worktree isolation), so an
+ operator debugging a run needs to see it here. */}
+ <ObjectProperty label={t(($) => $.detail.field_project)}>
+ {canWrite ? (
+ <ProjectPicker
+ projectId={projectId}
+ onUpdate={(u) => {
+ const next = u.project_id ?? null;
+ if (next !== projectId) update({ project_id: next });
+ }}
+ triggerRender={<button type="button" className={PROPERTY_TRIGGER} />}
+ />
+ ) : (
+ projectValue
+ )}
+ {project && (
+ <AppLink
+ href={wsPaths.projectDetail(project.id)}
+ aria-label={t(($) => $.detail.open_project)}
+ title={t(($) => $.detail.open_project)}
+ className="ml-auto flex shrink-0 rounded-sm p-0.5 text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <ArrowUpRight className="size-3.5" />
+ </AppLink>
+ )}
+ </ObjectProperty>
+ {autopilot.execution_mode === "create_issue" && (
+ <ObjectProperty label={t(($) => $.detail.field_subscribers)}>
+ <SubscribersProperty autopilot={autopilot} canWrite={canWrite} />
+ </ObjectProperty>
+ )}
+ <ObjectProperty label={t(($) => $.detail.field_created_by)}>
+ {/* Creator may be a member or an agent: the HTTP create path stamps
+ member today, but backend logic also writes created_by_type=agent.
+ ActorAvatar/getActorName resolve both, so never assume member. */}
+ <ActorAvatar
+ actorType={autopilot.created_by_type}
+ actorId={autopilot.created_by_id}
+ size="xs"
+ enableHoverCard
+ showStatusDot={autopilot.created_by_type === "agent"}
+ />
+ <span className="truncate">{getActorName(autopilot.created_by_type, autopilot.created_by_id)}</span>
+ </ObjectProperty>
+ </>
+ );
+}
+
+/** One line on what the autopilot does: when it fires, then what the run produces. */
+function useAutopilotSummary(autopilot: Autopilot | null, triggers: AutopilotTrigger[]) {
+ const { t } = useT("autopilots");
+ const { getActorName } = useActorName();
+ const describeSchedule = useDescribeSchedule();
+ if (!autopilot) return { icon: Zap, text: "" };
+ const primary = triggers.find((trig) => trig.enabled) ?? triggers[0];
+ const agent = getActorName(autopilot.assignee_type, autopilot.assignee_id);
+ const action =
+ autopilot.execution_mode === "run_only"
+ ? t(($) => $.detail.summary.run_only, { agent })
+ : t(($) => $.detail.summary.create_issue, { agent });
+ if (!primary) return { icon: Zap, text: action };
+ const config = primary.cron_expression
+ ? parseCron(primary.cron_expression, primary.timezone ?? "UTC")
+ : null;
+ const when = (config && describeSchedule(config)) || t(($) => $.trigger_kind[primary.kind]);
+ return {
+ icon: TRIGGER_ICON[primary.kind] ?? Zap,
+ text: t(($) => $.detail.summary.with_trigger, { trigger: when, action }),
+ };
+}
+
+function SectionSkeleton() {
+ return (
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-16 w-full rounded-lg" />
</div>
);
}
export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const { t } = useT("autopilots");
+ const { t: tLayout } = useT("layout");
+ const { t: tCommon } = useT("common");
const wsId = useWorkspaceId();
const wsPaths = useWorkspacePaths();
const router = useNavigation();
@@ -683,7 +987,6 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const { data, isLoading } = useQuery(autopilotDetailOptions(wsId, autopilotId));
const { data: runs = [], isLoading: runsLoading } = useQuery(autopilotRunsOptions(wsId, autopilotId));
- const updateAutopilot = useUpdateAutopilot();
const deleteAutopilot = useDeleteAutopilot();
const { runNow, isPending: runNowPending } = useRunAutopilotNow();
const loadedAutopilot = data?.autopilot ?? null;
@@ -693,61 +996,45 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
[loadedAutopilot],
),
);
- const projectId = data?.autopilot.project_id ?? null;
- const { data: project, isLoading: projectLoading } = useQuery({
- ...projectDetailOptions(wsId, projectId ?? ""),
- enabled: Boolean(projectId),
- });
+ const summary = useAutopilotSummary(loadedAutopilot, data?.triggers ?? []);
const [triggerDialogOpen, setTriggerDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
+ const segments = [{ href: wsPaths.autopilots(), label: tLayout(($) => $.panels.autopilots.list) }];
+
+ const shell = (leaf: ReactNode, children: ReactNode) => (
+ <ObjectPage layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
+ {children}
+ </ObjectPage>
+ );
+
if (isLoading) {
- return (
- <div className="flex h-full flex-col">
- <PageHeader>
- <Skeleton className="h-4 w-4" />
- <span className="text-muted-foreground">/</span>
- <Skeleton className="h-4 w-32" />
- </PageHeader>
- <div className="flex-1 overflow-y-auto">
- <div className="max-w-4xl mx-auto p-6 space-y-8">
- <section className="space-y-4">
- <Skeleton className="h-3 w-20" />
- <div className="grid grid-cols-2 gap-4">
- <div className="space-y-1">
- <Skeleton className="h-3 w-12" />
- <Skeleton className="h-5 w-32" />
- </div>
- <div className="space-y-1">
- <Skeleton className="h-3 w-12" />
- <Skeleton className="h-5 w-24" />
- </div>
- </div>
- </section>
- <section className="space-y-3">
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-10 w-full rounded-md" />
- </section>
- <section className="space-y-3">
- <Skeleton className="h-4 w-24" />
- {Array.from({ length: 3 }).map((_, i) => (
- <Skeleton key={i} className="h-10 w-full" />
- ))}
- </section>
+ return shell(
+ <Skeleton className="h-4 w-32" />,
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-xl" />
+ <div className="space-y-1.5">
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-4 w-64" />
</div>
</div>
- </div>
+ <SectionSkeleton />
+ <SectionSkeleton />
+ <SectionSkeleton />
+ </div>,
);
}
if (!data) {
- return (
- <div className="flex items-center justify-center h-full text-muted-foreground">
+ return shell(
+ <span className="min-w-0 truncate text-muted-foreground">{t(($) => $.detail.not_found)}</span>,
+ <div className="flex h-full items-center justify-center text-body text-muted-foreground">
{t(($) => $.detail.not_found)}
- </div>
+ </div>,
);
}
@@ -762,8 +1049,6 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
// doesn't send the field (older backend).
const canManageAccess = autopilot.can_manage_access ?? canWrite;
- const handleRunNow = () => runNow(autopilotId);
-
const handleDelete = async () => {
setDeleting(true);
try {
@@ -780,251 +1065,178 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
}
};
- const handleToggleStatus = (checked: boolean) => {
- updateAutopilot.mutate({ id: autopilotId, status: checked ? "active" : "paused" });
+ const copyLink = () => {
+ void copyText(router.getShareableUrl(wsPaths.autopilotDetail(autopilotId))).then((ok) => {
+ if (ok) toast.success(t(($) => $.detail.link_copied));
+ else toast.error(t(($) => $.detail.link_copy_failed));
+ });
};
return (
- <div className="flex h-full flex-col">
- {/* Header */}
- <BreadcrumbHeader
- segments={[{ href: wsPaths.autopilots(), label: t(($) => $.page.title) }]}
- leaf={
- <>
- <h1 className="min-w-0 truncate text-body font-medium text-foreground">{autopilot.title}</h1>
- <div className="ml-1 flex items-center gap-1.5 shrink-0">
- <Switch
- size="sm"
- checked={autopilot.status === "active"}
- onCheckedChange={handleToggleStatus}
- disabled={autopilot.status === "archived"}
- aria-label={
- autopilot.status === "active"
- ? t(($) => $.detail.pause_aria)
- : t(($) => $.detail.activate_aria)
- }
- />
- <span className={cn(
- "text-caption font-medium hidden sm:inline",
- autopilot.status === "active" ? "text-emerald-500" :
- autopilot.status === "paused" ? "text-amber-500" :
- "text-muted-foreground",
- )}>
- {t(($) => $.status[autopilot.status])}
- </span>
- </div>
- </>
- }
- actions={
- canWrite ? (
- <>
- <Button size="sm" variant="outline" onClick={() => setEditDialogOpen(true)} className="px-2 sm:px-2.5" aria-label={t(($) => $.detail.edit)}>
- <Pencil className="h-3.5 w-3.5 sm:mr-1" />
- <span className="hidden sm:inline">{t(($) => $.detail.edit)}</span>
- </Button>
- <Button
- size="sm"
- onClick={handleRunNow}
- disabled={autopilot.status !== "active" || runNowPending}
- className="px-2 sm:px-2.5"
- aria-label={runNowPending ? t(($) => $.detail.running) : t(($) => $.detail.run_now)}
- >
- {runNowPending ? (
- <Loader2 className="h-3.5 w-3.5 sm:mr-1 animate-spin" />
- ) : (
- <Play className="h-3.5 w-3.5 sm:mr-1" />
- )}
- <span className="hidden sm:inline">
- {runNowPending
- ? t(($) => $.detail.running)
- : t(($) => $.detail.run_now)}
- </span>
- </Button>
- </>
- ) : null
- }
- />
-
- {autopilot.pause_reason === "agent_runtime_required" && (
- <div className="flex shrink-0 items-center gap-2 border-b border-amber-500/30 bg-amber-500/10 px-6 py-2 text-caption text-amber-900 dark:text-amber-100">
- <Server className="size-3.5 shrink-0" />
- <span className="flex-1">
- {t(($) => $.detail.paused_runtime_required)}
- </span>
- {autopilot.assignee_type === "agent" && (
- <AppLink
- href={`${wsPaths.agentDetail(autopilot.assignee_id)}?view=general`}
- className="font-medium underline underline-offset-2"
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={<span className="min-w-0 truncate">{autopilot.title}</span>}
+ actions={
+ <>
+ {canWrite && (
+ <Button
+ size="sm"
+ onClick={() => runNow(autopilotId)}
+ disabled={autopilot.status !== "active" || runNowPending}
>
- {t(($) => $.detail.bind_runtime)}
- </AppLink>
- )}
- </div>
- )}
-
- <div className="flex-1 overflow-y-auto">
- <div className="max-w-4xl mx-auto p-6 space-y-8">
- {/* Properties */}
- <section className="space-y-4">
- <h2 className="text-body font-medium text-muted-foreground uppercase tracking-wider">
- {t(($) => $.detail.section_properties)}
- </h2>
- <div className="grid grid-cols-2 gap-4 text-body">
- <div>
- <label className="text-caption text-muted-foreground">{t(($) => $.detail.field_agent)}</label>
- <div className="mt-1 flex items-center gap-2">
- <ActorAvatar
- actorType={autopilot.assignee_type}
- actorId={autopilot.assignee_id}
- size="sm"
- enableHoverCard={autopilot.assignee_type === "agent"}
- showStatusDot={autopilot.assignee_type === "agent"}
- />
- <span className="cursor-pointer">
- {getActorName(autopilot.assignee_type, autopilot.assignee_id)}
- </span>
- </div>
- </div>
- <div>
- <label className="text-caption text-muted-foreground">{t(($) => $.detail.field_created_by)}</label>
- <div className="mt-1 flex items-center gap-2">
- {/* Creator may be a member or an agent: the HTTP create path stamps
- member today, but backend logic also writes created_by_type=agent.
- ActorAvatar/getActorName resolve both, so never assume member. */}
- <ActorAvatar
- actorType={autopilot.created_by_type}
- actorId={autopilot.created_by_id}
- size="sm"
- enableHoverCard
- showStatusDot={autopilot.created_by_type === "agent"}
- />
- <span className="cursor-pointer">
- {getActorName(autopilot.created_by_type, autopilot.created_by_id)}
- </span>
- </div>
- </div>
- <div>
- <label className="text-caption text-muted-foreground">{t(($) => $.detail.field_output_mode)}</label>
- <div className="mt-1">
- {t(($) => $.execution_mode[autopilot.execution_mode as AutopilotExecutionMode])}
- </div>
- </div>
- {/* Shown for BOTH output modes (MUL-6681): a run_only autopilot's
- project decides its execution environment (repository /
- local_directory, and therefore worktree isolation), so an
- operator debugging a run needs to see it here. */}
- <div>
- <label className="text-caption text-muted-foreground">{t(($) => $.detail.field_project)}</label>
- <div className="mt-1 min-w-0">
- {!autopilot.project_id ? (
- <span className="text-muted-foreground">{t(($) => $.detail.no_project)}</span>
- ) : projectLoading ? (
- <Skeleton className="h-5 w-32" />
- ) : project ? (
- <AppLink
- href={wsPaths.projectDetail(project.id)}
- className="inline-flex max-w-full items-center gap-1.5 text-foreground hover:underline"
- >
- <ProjectIcon project={project} size="md" />
- <span className="truncate">{project.title}</span>
- </AppLink>
- ) : (
- <span className="text-muted-foreground">{t(($) => $.detail.project_unavailable)}</span>
- )}
- </div>
- </div>
- {autopilot.execution_mode === "create_issue" && (
- <div className="col-span-2">
- <label className="text-caption text-muted-foreground">
- {t(($) => $.detail.field_subscribers)}
- </label>
- <SubscriberChips
- subscribers={autopilot.subscribers}
- />
- </div>
+ {runNowPending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <Play className="size-3.5" />
)}
- {autopilot.description && (
- <div className="col-span-2">
- <label className="text-caption text-muted-foreground">{t(($) => $.detail.field_prompt)}</label>
- <div className="mt-1">
- <ReadonlyContent content={autopilot.description} />
- </div>
- </div>
+ {runNowPending ? t(($) => $.detail.running) : t(($) => $.detail.run_now)}
+ </Button>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={tCommon(($) => $.more_actions)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ />
+ }
+ >
+ <MoreHorizontal />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto min-w-44">
+ {canWrite && (
+ <DropdownMenuItem onClick={() => setEditDialogOpen(true)}>
+ <Pencil className="size-3.5" />
+ {t(($) => $.detail.edit)}
+ </DropdownMenuItem>
)}
- </div>
- </section>
-
- {/* Triggers */}
- <section className="space-y-3">
- <div className="flex items-center justify-between">
- <h2 className="text-body font-medium text-muted-foreground uppercase tracking-wider">
- {t(($) => $.detail.section_triggers)}
- </h2>
+ <DropdownMenuItem onClick={copyLink}>
+ <Link2 className="size-3.5" />
+ {t(($) => $.detail.copy_link)}
+ </DropdownMenuItem>
{canWrite && (
- <Button size="sm" variant="outline" onClick={() => setTriggerDialogOpen(true)}>
- <Plus className="h-3.5 w-3.5 mr-1" />
- {t(($) => $.detail.add_trigger)}
- </Button>
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleteConfirmOpen(true)}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.detail.delete_button)}
+ </DropdownMenuItem>
+ </>
)}
- </div>
- {triggers.length === 0 ? (
- <div className="rounded-md border border-dashed p-4 text-center text-body text-muted-foreground">
- {t(($) => $.detail.no_triggers)}
- </div>
- ) : (
- <div className="space-y-2">
- {triggers.map((trig) => (
- <TriggerRow key={trig.id} trigger={trig} autopilotId={autopilotId} canWrite={canWrite} />
- ))}
- </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </>
+ }
+ panel={
+ <ObjectPanelSection title={tLayout(($) => $.object_page.properties)}>
+ <AutopilotProperties autopilot={autopilot} canWrite={canWrite} />
+ </ObjectPanelSection>
+ }
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ {autopilot.pause_reason === "agent_runtime_required" && (
+ <div
+ role="status"
+ className="flex items-center gap-2 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-caption"
+ >
+ <Server className="size-3.5 shrink-0 text-warning" />
+ <span className="flex-1">
+ {t(($) => $.detail.paused_runtime_required)}
+ </span>
+ {autopilot.assignee_type === "agent" && (
+ <AppLink
+ href={`${wsPaths.agentDetail(autopilot.assignee_id)}?view=general`}
+ className="font-medium underline underline-offset-2"
+ >
+ {t(($) => $.detail.bind_runtime)}
+ </AppLink>
)}
- </section>
-
- {/* Webhook deliveries — only renders when at least one webhook
- trigger is configured. The component does its own fetch so
- schedule-only autopilots don't pay for an empty list query. */}
- <WebhookDeliveriesSection
- autopilotId={autopilotId}
- hasWebhookTrigger={triggers.some((trig) => trig.kind === "webhook")}
- />
+ </div>
+ )}
- {/* Run History */}
- <section className="space-y-3">
- <h2 className="text-body font-medium text-muted-foreground uppercase tracking-wider">
- {t(($) => $.detail.section_run_history)}
- </h2>
- {runsLoading ? (
- <div className="space-y-1">
- {Array.from({ length: 3 }).map((_, i) => (
- <Skeleton key={i} className="h-10 w-full" />
- ))}
- </div>
- ) : runs.length === 0 ? (
- <div className="rounded-md border border-dashed p-4 text-center text-body text-muted-foreground">
- {t(($) => $.detail.no_runs)}
- </div>
- ) : (
- <RunHistoryList
- runs={runs}
- agentId={autopilot.assignee_id}
- agentName={getActorName(autopilot.assignee_type, autopilot.assignee_id)}
- />
- )}
- </section>
+ <ObjectIdentity
+ media={<ObjectIconMark icon={summary.icon} />}
+ title={autopilot.title}
+ description={summary.text}
+ />
- {/* Danger zone */}
- {canWrite && (
- <section className="space-y-3 pt-4 border-t">
- <h2 className="text-body font-medium text-destructive uppercase tracking-wider">
- {t(($) => $.detail.section_danger)}
- </h2>
- <Button size="sm" variant="destructive" onClick={() => setDeleteConfirmOpen(true)}>
- <Trash2 className="h-3.5 w-3.5 mr-1" />
- {t(($) => $.detail.delete_button)}
- </Button>
- </section>
+ <ObjectSection
+ title={t(($) => $.detail.field_prompt)}
+ action={
+ canWrite ? (
+ <ObjectSectionAction icon={Pencil} onClick={() => setEditDialogOpen(true)}>
+ {t(($) => $.detail.edit)}
+ </ObjectSectionAction>
+ ) : undefined
+ }
+ >
+ {autopilot.description ? (
+ <ObjectSectionCard className="px-3 py-2.5">
+ <ReadonlyContent content={autopilot.description} />
+ </ObjectSectionCard>
+ ) : (
+ <div className="rounded-lg border border-dashed p-4 text-center text-body text-muted-foreground">
+ {t(($) => $.detail.no_prompt)}
+ </div>
)}
- </div>
+ </ObjectSection>
+
+ <ObjectSection
+ title={t(($) => $.detail.section_triggers)}
+ count={triggers.length}
+ action={
+ canWrite ? (
+ <ObjectSectionAction icon={Plus} onClick={() => setTriggerDialogOpen(true)}>
+ {t(($) => $.detail.add_trigger)}
+ </ObjectSectionAction>
+ ) : undefined
+ }
+ >
+ {triggers.length === 0 ? (
+ <div className="rounded-lg border border-dashed p-4 text-center text-body text-muted-foreground">
+ {t(($) => $.detail.no_triggers)}
+ </div>
+ ) : (
+ <ObjectSectionCard>
+ {triggers.map((trig) => (
+ <TriggerRow key={trig.id} trigger={trig} autopilotId={autopilotId} canWrite={canWrite} />
+ ))}
+ </ObjectSectionCard>
+ )}
+ </ObjectSection>
+
+ {/* Webhook deliveries — only renders when at least one webhook
+ trigger is configured. The component does its own fetch so
+ schedule-only autopilots don't pay for an empty list query. */}
+ <WebhookDeliveriesSection
+ autopilotId={autopilotId}
+ hasWebhookTrigger={triggers.some((trig) => trig.kind === "webhook")}
+ />
+
+ <ObjectSection
+ title={t(($) => $.detail.section_run_history)}
+ count={runsLoading ? undefined : runs.length}
+ >
+ {runsLoading ? (
+ <div className="space-y-1">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </div>
+ ) : runs.length === 0 ? (
+ <div className="rounded-lg border border-dashed p-4 text-center text-body text-muted-foreground">
+ {t(($) => $.detail.no_runs)}
+ </div>
+ ) : (
+ <RunHistoryList
+ runs={runs}
+ agentId={autopilot.assignee_id}
+ agentName={getActorName(autopilot.assignee_type, autopilot.assignee_id)}
+ />
+ )}
+ </ObjectSection>
</div>
{/* Mounted only while open, like the edit dialog: otherwise a rejected
@@ -1086,6 +1298,6 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- </div>
+ </ObjectPage>
);
}
diff --git a/packages/views/autopilots/components/autopilot-list-actions.tsx b/packages/views/autopilots/components/autopilot-list-actions.tsx
index fc3ef387d0..686d4bd6b0 100644
--- a/packages/views/autopilots/components/autopilot-list-actions.tsx
+++ b/packages/views/autopilots/components/autopilot-list-actions.tsx
@@ -4,11 +4,9 @@ import { useState } from "react";
import {
ExternalLink,
Loader2,
- MoreHorizontal,
Pause,
Play,
Trash2,
- X,
} from "@multica/ui/icons";
import { toast } from "sonner";
import type { Autopilot } from "@multica/core/types";
@@ -18,7 +16,6 @@ import {
} from "@multica/core/autopilots";
import { useWorkspacePaths } from "@multica/core/paths";
import { Button } from "@multica/ui/components/ui/button";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import {
Dialog,
DialogContent,
@@ -28,15 +25,15 @@ import {
DialogTitle,
} from "@multica/ui/components/ui/dialog";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
- DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { useT } from "../../i18n";
import { useIntentNavigate } from "../../navigation";
-import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
+import {
+ CollectionBatchBar,
+ CollectionRowMenu,
+} from "../../layout/collection-list";
// Delete dialog — single row (kebab) and batch share one implementation.
@@ -135,10 +132,7 @@ function useSetStatus() {
};
}
-// Row kebab — the row is a plain `<div>` whose whole-row navigation is a mouse
-// `onClick` (see `useRowLink`), not an ancestor `<a>`. The wrapper span stops
-// click propagation so opening this menu never navigates the row — just
-// stopPropagation, no preventDefault (same pattern as the skills list).
+// Row menu — the ⋯ button and right-click share these items.
export function AutopilotRowActions({ row }: { row: Autopilot }) {
const { t } = useT("autopilots");
@@ -156,69 +150,48 @@ export function AutopilotRowActions({ row }: { row: Autopilot }) {
if (row.can_write === false) return null;
return (
- <span
- onClick={(e) => e.stopPropagation()}
- className="flex items-center"
- >
- <DropdownMenu>
- <DeferredTooltip
- content={t(($) => $.actions.row_menu)}
- trigger={
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- aria-label={t(($) => $.actions.row_menu)}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"
- >
- <MoreHorizontal className="size-4" />
- </button>
- }
- />
+ <>
+ <CollectionRowMenu label={t(($) => $.actions.row_menu)}>
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ wsPaths.autopilotDetail(row.id),
+ "foreground-tab",
+ row.title,
+ )
}
- />
- <DropdownMenuContent align="end" className="w-48">
- <DropdownMenuItem
- onClick={() =>
- intentNavigate(
- wsPaths.autopilotDetail(row.id),
- "foreground-tab",
- row.title,
- )
- }
- >
- <ExternalLink className="size-3.5" />
- {tCommon(($) => $.navigation.open_in_new_tab)}
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {row.status === "active" && (
+ <DropdownMenuItem onClick={() => setStatus([row], "paused")}>
+ <Pause className="size-3.5" />
+ {t(($) => $.actions.pause)}
</DropdownMenuItem>
- <DropdownMenuSeparator />
- {row.status === "active" && (
- <DropdownMenuItem onClick={() => setStatus([row], "paused")}>
- <Pause className="size-3.5" />
- {t(($) => $.actions.pause)}
- </DropdownMenuItem>
- )}
- {row.status === "paused" && (
- <DropdownMenuItem onClick={() => setStatus([row], "active")}>
- <Play className="size-3.5" />
- {t(($) => $.actions.resume)}
- </DropdownMenuItem>
- )}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleteOpen(true)}
- >
- <Trash2 className="size-3.5" />
- {t(($) => $.actions.delete)}
+ )}
+ {row.status === "paused" && (
+ <DropdownMenuItem onClick={() => setStatus([row], "active")}>
+ <Play className="size-3.5" />
+ {t(($) => $.actions.resume)}
</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteOpen(true)}
+ >
+ <Trash2 className="size-3.5" />
+ {t(($) => $.actions.delete)}
+ </DropdownMenuItem>
+ </CollectionRowMenu>
<DeleteAutopilotsDialog
rows={[row]}
open={deleteOpen}
onOpenChange={setDeleteOpen}
/>
- </span>
+ </>
);
}
@@ -235,32 +208,12 @@ export function AutopilotBatchToolbar({
const [deleteOpen, setDeleteOpen] = useState(false);
const setStatus = useSetStatus();
- if (rows.length === 0) return null;
-
const anyActive = rows.some((r) => r.status === "active");
const anyPaused = rows.some((r) => r.status === "paused");
return (
<>
- {/* Anchored to the page root (relative), NOT the viewport — see the
- skills batch toolbar for the rationale. */}
- <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg max-md:above-chat-launcher">
- <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">
- <span className="text-body font-medium">
- {t(($) => $.actions.selected, { count: rows.length })}
- </span>
- <TooltipHint label={t(($) => $.actions.clear_selection)}>
- <button
- type="button"
- aria-label={t(($) => $.actions.clear_selection)}
- onClick={onClear}
- className="rounded-xs p-0.5 transition-colors hover:bg-accent"
- >
- <X className="size-3.5 text-muted-foreground" />
- </button>
- </TooltipHint>
- </div>
-
+ <CollectionBatchBar count={rows.length} onClear={onClear}>
{anyActive && (
<Button
variant="ghost"
@@ -290,7 +243,7 @@ export function AutopilotBatchToolbar({
<Trash2 className="mr-1 size-3.5" />
{t(($) => $.actions.delete)}
</Button>
- </div>
+ </CollectionBatchBar>
<DeleteAutopilotsDialog
rows={rows}
diff --git a/packages/views/autopilots/components/autopilot-list-toolbar.tsx b/packages/views/autopilots/components/autopilot-list-toolbar.tsx
index 5553467a5a..5ac8718f4c 100644
--- a/packages/views/autopilots/components/autopilot-list-toolbar.tsx
+++ b/packages/views/autopilots/components/autopilot-list-toolbar.tsx
@@ -1,50 +1,21 @@
"use client";
-import {
- ArrowDown,
- ArrowUp,
- ChevronDown,
- Filter,
- X,
-} from "@multica/ui/icons";
import type { Autopilot } from "@multica/core/types";
-import {
- AUTOPILOT_SCOPES,
- type AutopilotColumnKey,
- type AutopilotListFilters,
- type AutopilotScope,
- type AutopilotSortDirection,
- type AutopilotSortField,
-} from "@multica/core/autopilots/stores";
+import type { AutopilotListFilters } from "@multica/core/autopilots/stores";
import { useActorName } from "@multica/core/workspace/hooks";
-import { Button } from "@multica/ui/components/ui/button";
-import { IconButton } from "@multica/ui/components/common/icon-button";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
-import { Switch } from "@multica/ui/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "../../common/actor-avatar";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { useT } from "../../i18n";
-import { PAGE_TOOLBAR } from "../../layout/page-header";
+import { CollectionFilterButton } from "../../layout/collection-page";
// Composite "type:id" value for polymorphic actor filter dimensions, so the
// string[] filter store can hold agent/squad/member references alike.
@@ -52,23 +23,6 @@ export function actorFilterValue(type: string, id: string): string {
return `${type}:${id}`;
}
-const COLUMN_KEYS: AutopilotColumnKey[] = [
- "assignee",
- "trigger",
- "lastRun",
- "nextRun",
- "mode",
- "creator",
- "created",
-];
-
-const SORT_FIELDS: AutopilotSortField[] = [
- "name",
- "lastRun",
- "nextRun",
- "created",
-];
-
const MODES = ["create_issue", "run_only"] as const;
const TRIGGER_KINDS = ["schedule", "webhook", "api"] as const;
@@ -83,47 +37,24 @@ export function countActiveFilterDimensions(
return count;
}
-export function AutopilotListToolbar({
- scope,
- onScopeChange,
- scopeCounts,
+/**
+ * The header's filter icon and its menu. Status is the title's scope, so it
+ * never appears here.
+ */
+export function AutopilotFilterMenu({
filters,
onToggleFilter,
- onClearFilters,
- sortField,
- sortDirection,
- onSortFieldChange,
- onSortDirectionChange,
- hiddenColumns,
- onToggleColumn,
allRows,
- visibleCount,
}: {
- scope: AutopilotScope;
- onScopeChange: (scope: AutopilotScope) => void;
- /** Per-scope totals from the FULL set — scope counts ignore filters. */
- scopeCounts: Record<AutopilotScope, number>;
filters: AutopilotListFilters;
onToggleFilter: (key: keyof AutopilotListFilters, value: string) => void;
- onClearFilters: () => void;
- sortField: AutopilotSortField;
- sortDirection: AutopilotSortDirection;
- onSortFieldChange: (field: AutopilotSortField) => void;
- onSortDirectionChange: (direction: AutopilotSortDirection) => void;
- hiddenColumns: AutopilotColumnKey[];
- onToggleColumn: (key: AutopilotColumnKey) => void;
- /** Rows within the current scope, unfiltered — filter option lists and
- * counts derive from this set. */
+ /** Rows within the current scope, unfiltered — option lists and counts
+ * derive from this set. */
allRows: Autopilot[];
- /** Rows surviving the filters — shown as "n / total" when narrowed. */
- visibleCount: number;
}) {
const { t } = useT("autopilots");
const { getActorName } = useActorName();
- const activeCount = countActiveFilterDimensions(filters);
- const hasActiveFilters = activeCount > 0;
-
// Option lists with counts, derived from the scope's unfiltered rows so
// toggling one dimension doesn't make the others' options vanish.
const assigneeOptions = new Map<
@@ -164,400 +95,140 @@ export function AutopilotListToolbar({
}
}
- const SCOPE_LABELS: Record<AutopilotScope, string> = {
- all: t(($) => $.page.scope_all),
- active: t(($) => $.status.active),
- paused: t(($) => $.status.paused),
- };
-
- const SORT_LABELS: Record<AutopilotSortField, string> = {
- name: t(($) => $.page.table.name),
- lastRun: t(($) => $.page.table.last_run),
- nextRun: t(($) => $.page.table.next_run),
- created: t(($) => $.page.table.created),
- };
-
- const COLUMN_LABELS: Record<AutopilotColumnKey, string> = {
- assignee: t(($) => $.page.table.assignee),
- trigger: t(($) => $.page.table.trigger),
- lastRun: t(($) => $.page.table.last_run),
- nextRun: t(($) => $.page.table.next_run),
- mode: t(($) => $.page.table.mode),
- creator: t(($) => $.page.table.created_by),
- created: t(($) => $.page.table.created),
- };
- const sortLabel = SORT_LABELS[sortField];
-
const countBadge = (n: number) => (
<span className="ml-auto pl-3 text-caption text-muted-foreground">{n}</span>
);
return (
- <div className={PAGE_TOOLBAR}>
- {/* Left: scope buttons + result count. Scope is the promoted status
- dimension (it does NOT appear in the filter dropdown). No search
- box: scope buttons already partition the (small) set, so search
- was dropped by product call. The count only appears while filters
- narrow the list. Button styling and the <md dropdown collapse
- follow the issues header's scope buttons. */}
- <div className="flex min-w-0 items-center gap-2">
- <div className="hidden shrink-0 items-center gap-1 md:flex">
- {AUTOPILOT_SCOPES.map((s) => (
- <Button
- key={s}
- variant="outline"
- size="sm"
- className={
- scope === s
- ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"
- : "gap-1.5 text-muted-foreground"
- }
- onClick={() => onScopeChange(s)}
- >
- {SCOPE_LABELS[s]}
- <span className="tabular-nums text-caption text-muted-foreground">
- {scopeCounts[s]}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <CollectionFilterButton count={countActiveFilterDimensions(filters)} />
+ }
+ />
+ <DropdownMenuContent align="start" className="w-auto">
+ {/* Assignee */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_assignee)}
+ </span>
+ {filters.assignees.length > 0 && (
+ <span className="text-caption font-medium text-primary">
+ {filters.assignees.length}
</span>
- </Button>
- ))}
- </div>
-
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 gap-1 text-muted-foreground md:hidden"
- >
- <span className="truncate">{SCOPE_LABELS[scope]}</span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={scope}
- onValueChange={(value) =>
- onScopeChange(value as AutopilotScope)
- }
- >
- {AUTOPILOT_SCOPES.map((s) => (
- <DropdownMenuRadioItem key={s} value={s}>
- {SCOPE_LABELS[s]}
- <span className="ml-2 tabular-nums text-caption text-muted-foreground">
- {scopeCounts[s]}
- </span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {hasActiveFilters && (
- <span
- title={t(($) => $.toolbar.result_count_title)}
- className="hidden shrink-0 text-caption tabular-nums text-muted-foreground md:inline"
- >
- {visibleCount} / {allRows.length}
- </span>
- )}
- </div>
-
- <div className="flex shrink-0 items-center gap-1">
- {/* Filter */}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant={hasActiveFilters ? "default" : "outline"}
- size="sm"
- className={
- hasActiveFilters
- ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"
- : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- }
- >
- <Filter className="size-3.5" />
- {hasActiveFilters ? (
- <>
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_active_count, {
- count: activeCount,
- })}
- </span>
- <span className="tabular-nums md:hidden">
- {activeCount}
- </span>
- </>
- ) : (
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_label)}
- </span>
- )}
- {hasActiveFilters && (
- <span
- role="button"
- tabIndex={-1}
- aria-label={t(($) => $.toolbar.clear_filters)}
- className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onClearFilters();
- }}
- onPointerDown={(e) => e.stopPropagation()}
- >
- <X className="size-3" />
- </span>
- )}
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-auto">
- {/* Assignee */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_assignee)}
- </span>
- {filters.assignees.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.assignees.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...assigneeOptions.entries()].map(
- ([value, { type, id, count }]) => (
- <DropdownMenuCheckboxItem
- key={value}
- checked={filters.assignees.includes(value)}
- onCheckedChange={() =>
- onToggleFilter("assignees", value)
- }
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck
- checked={filters.assignees.includes(value)}
- />
- <ActorAvatar actorType={type} actorId={id} size="sm" />
- <span className="min-w-0 truncate">
- {getActorName(type, id)}
- </span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ),
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Trigger kind */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_trigger)}
- </span>
- {filters.triggerKinds.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.triggerKinds.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {TRIGGER_KINDS.filter((kind) =>
- triggerKindCounts.has(kind),
- ).map((kind) => (
- <DropdownMenuCheckboxItem
- key={kind}
- checked={filters.triggerKinds.includes(kind)}
- onCheckedChange={() =>
- onToggleFilter("triggerKinds", kind)
- }
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck
- checked={filters.triggerKinds.includes(kind)}
- />
- {t(($) => $.trigger_kind[kind])}
- {countBadge(triggerKindCounts.get(kind) ?? 0)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Mode */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_mode)}
- </span>
- {filters.modes.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.modes.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {MODES.map((mode) => (
- <DropdownMenuCheckboxItem
- key={mode}
- checked={filters.modes.includes(mode)}
- onCheckedChange={() => onToggleFilter("modes", mode)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.modes.includes(mode)} />
- {t(($) => $.execution_mode[mode])}
- {countBadge(modeCounts.get(mode) ?? 0)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Creator */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_creator)}
- </span>
- {filters.creators.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.creators.length}
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...assigneeOptions.entries()].map(
+ ([value, { type, id, count }]) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={filters.assignees.includes(value)}
+ onCheckedChange={() => onToggleFilter("assignees", value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.assignees.includes(value)} />
+ <ActorAvatar actorType={type} actorId={id} size="sm" />
+ <span className="min-w-0 truncate">
+ {getActorName(type, id)}
</span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...creatorOptions.entries()].map(
- ([value, { type, id, count }]) => (
- <DropdownMenuCheckboxItem
- key={value}
- checked={filters.creators.includes(value)}
- onCheckedChange={() => onToggleFilter("creators", value)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.creators.includes(value)} />
- <ActorAvatar actorType={type} actorId={id} size="sm" />
- <span className="min-w-0 truncate">
- {getActorName(type, id)}
- </span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ),
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {/* Display settings — same paradigm as skills: sort select +
- direction toggle + column switches, mutating the same store the
- list header sort buttons use. */}
- <Popover>
- <Tooltip>
- <PopoverTrigger
- render={
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- >
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- <span className="hidden md:inline">{sortLabel}</span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">
- {t(($) => $.toolbar.display)}
- </TooltipContent>
- </Tooltip>
- <PopoverContent align="end" className="w-64 p-0">
- <div className="border-b px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.sort_by)}
+ {countBadge(count)}
+ </DropdownMenuCheckboxItem>
+ ),
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ {/* Trigger kind */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_trigger)}
+ </span>
+ {filters.triggerKinds.length > 0 && (
+ <span className="text-caption font-medium text-primary">
+ {filters.triggerKinds.length}
</span>
- <div className="mt-2 flex items-center gap-1.5">
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="flex-1 justify-between text-caption"
- >
- {sortLabel}
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={sortField}
- onValueChange={(v) =>
- onSortFieldChange(v as AutopilotSortField)
- }
- >
- {SORT_FIELDS.map((field) => (
- <DropdownMenuRadioItem key={field} value={field}>
- {SORT_LABELS[field]}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <IconButton
- variant="outline"
- size="icon-sm"
- onClick={() =>
- onSortDirectionChange(
- sortDirection === "asc" ? "desc" : "asc",
- )
- }
- label={
- sortDirection === "asc"
- ? t(($) => $.toolbar.direction_asc)
- : t(($) => $.toolbar.direction_desc)
- }
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {TRIGGER_KINDS.filter((kind) => triggerKindCounts.has(kind)).map(
+ (kind) => (
+ <DropdownMenuCheckboxItem
+ key={kind}
+ checked={filters.triggerKinds.includes(kind)}
+ onCheckedChange={() => onToggleFilter("triggerKinds", kind)}
+ className={FILTER_ITEM_CLASS}
>
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- </IconButton>
- </div>
- </div>
-
- <div className="px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.section_columns)}
+ <HoverCheck checked={filters.triggerKinds.includes(kind)} />
+ {t(($) => $.trigger_kind[kind])}
+ {countBadge(triggerKindCounts.get(kind) ?? 0)}
+ </DropdownMenuCheckboxItem>
+ ),
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ {/* Mode */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.toolbar.section_mode)}</span>
+ {filters.modes.length > 0 && (
+ <span className="text-caption font-medium text-primary">
+ {filters.modes.length}
</span>
- <div className="mt-2 space-y-2">
- {COLUMN_KEYS.map((key) => (
- <label
- key={key}
- className="flex cursor-pointer items-center justify-between"
- >
- <span className="text-body">{COLUMN_LABELS[key]}</span>
- <Switch
- size="sm"
- checked={!hiddenColumns.includes(key)}
- onCheckedChange={() => onToggleColumn(key)}
- />
- </label>
- ))}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- </div>
- </div>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {MODES.map((mode) => (
+ <DropdownMenuCheckboxItem
+ key={mode}
+ checked={filters.modes.includes(mode)}
+ onCheckedChange={() => onToggleFilter("modes", mode)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.modes.includes(mode)} />
+ {t(($) => $.execution_mode[mode])}
+ {countBadge(modeCounts.get(mode) ?? 0)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ {/* Creator */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_creator)}
+ </span>
+ {filters.creators.length > 0 && (
+ <span className="text-caption font-medium text-primary">
+ {filters.creators.length}
+ </span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...creatorOptions.entries()].map(
+ ([value, { type, id, count }]) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={filters.creators.includes(value)}
+ onCheckedChange={() => onToggleFilter("creators", value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.creators.includes(value)} />
+ <ActorAvatar actorType={type} actorId={id} size="sm" />
+ <span className="min-w-0 truncate">
+ {getActorName(type, id)}
+ </span>
+ {countBadge(count)}
+ </DropdownMenuCheckboxItem>
+ ),
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
);
}
diff --git a/packages/views/autopilots/components/autopilot-templates.ts b/packages/views/autopilots/components/autopilot-templates.ts
new file mode 100644
index 0000000000..26c4fe072b
--- /dev/null
+++ b/packages/views/autopilots/components/autopilot-templates.ts
@@ -0,0 +1,99 @@
+import {
+ BarChart3,
+ Bug,
+ FileSearch,
+ GitPullRequest,
+ Newspaper,
+ Shield,
+ type IconComponent,
+} from "@multica/ui/icons";
+import type { ScheduleConfig } from "./schedule-editor/model";
+
+// Templates offered by the empty state and the Autopilots panel.
+// Prompts stay raw English because they're injected directly into the
+// agent's task input.
+
+export type AutopilotTemplateId =
+ | "daily_news"
+ | "pr_review"
+ | "bug_triage"
+ | "weekly_progress"
+ | "dependency_audit"
+ | "documentation_check";
+
+export interface AutopilotTemplate {
+ id: AutopilotTemplateId;
+ prompt: string;
+ icon: IconComponent;
+ schedule: Pick<ScheduleConfig, "time" | "days">;
+}
+
+const WEEKDAYS: ScheduleConfig["days"] = {
+ kind: "weekly",
+ daysOfWeek: [1, 2, 3, 4, 5],
+};
+const MONDAY: ScheduleConfig["days"] = { kind: "weekly", daysOfWeek: [1] };
+
+export const AUTOPILOT_TEMPLATES: AutopilotTemplate[] = [
+ {
+ id: "daily_news",
+ prompt: `1. Search the web for news and announcements published today only (strictly today's date)
+2. Filter for topics relevant to our team and industry
+3. For each item, write a short summary including: title, source, key takeaways
+4. Compile everything into a single digest post
+5. Post the digest as a comment on this issue and @mention all workspace members`,
+ icon: Newspaper,
+ schedule: { time: { kind: "at", time: "09:00" }, days: { kind: "every" } },
+ },
+ {
+ id: "pr_review",
+ prompt: `1. List all open pull requests in the repository
+2. Identify PRs that have been open for more than 24 hours without a review
+3. For each stale PR, note the author, age, and a one-line summary of the change
+4. Post a comment on this issue listing all stale PRs with links
+5. @mention the team to remind them to review`,
+ icon: GitPullRequest,
+ schedule: { time: { kind: "at", time: "10:00" }, days: WEEKDAYS },
+ },
+ {
+ id: "bug_triage",
+ prompt: `1. List all backlog issues that have not been prioritized
+2. For each issue, read the description and any attached logs or screenshots
+3. Assess severity (critical / high / medium / low) based on user impact and scope
+4. Set the priority field on the issue accordingly
+5. Add a comment explaining your assessment and suggested next steps`,
+ icon: Bug,
+ schedule: { time: { kind: "at", time: "09:00" }, days: WEEKDAYS },
+ },
+ {
+ id: "weekly_progress",
+ prompt: `1. Gather all issues completed (status "done") in the past 7 days
+2. Gather all issues currently in progress
+3. Identify any blocked issues and their blockers
+4. Calculate key metrics: issues closed, issues opened, net change
+5. Write a structured weekly report with sections: Completed, In Progress, Blocked, Metrics
+6. Post the report as a comment on this issue`,
+ icon: BarChart3,
+ schedule: { time: { kind: "at", time: "17:00" }, days: MONDAY },
+ },
+ {
+ id: "dependency_audit",
+ prompt: `1. Run dependency audit tools on the project (npm audit, go vuln check, etc.)
+2. Identify any packages with known security vulnerabilities
+3. List outdated packages that are more than 2 major versions behind
+4. For each finding, note the severity, affected package, and recommended fix
+5. Post a summary report as a comment with actionable items`,
+ icon: Shield,
+ schedule: { time: { kind: "at", time: "08:00" }, days: MONDAY },
+ },
+ {
+ id: "documentation_check",
+ prompt: `1. List all code changes merged in the past 7 days (via git log)
+2. For each significant change, check if related documentation was updated
+3. Identify any new APIs, config options, or features missing documentation
+4. Create a list of documentation gaps with file paths and suggested content
+5. Post the findings as a comment on this issue`,
+ icon: FileSearch,
+ schedule: { time: { kind: "at", time: "14:00" }, days: MONDAY },
+ },
+];
diff --git a/packages/views/autopilots/components/autopilots-page.test.tsx b/packages/views/autopilots/components/autopilots-page.test.tsx
index b3160e1cf9..bb92c83405 100644
--- a/packages/views/autopilots/components/autopilots-page.test.tsx
+++ b/packages/views/autopilots/components/autopilots-page.test.tsx
@@ -1,8 +1,14 @@
import { useState } from "react";
-import { expect, it, vi } from "vitest";
-import { fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { api } from "@multica/core/api";
+import {
+ EMPTY_AUTOPILOT_FILTERS,
+ useAutopilotsViewStore,
+} from "@multica/core/autopilots/stores";
+import type { Autopilot } from "@multica/core/types";
import { NavigationProvider } from "../../navigation";
import { renderWithI18n } from "../../test/i18n";
import { AutopilotsPage } from "./autopilots-page";
@@ -10,16 +16,67 @@ import { AutopilotsPage } from "./autopilots-page";
vi.mock("@multica/core/api", () => ({ api: { listAutopilots: vi.fn() } }));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));
vi.mock("@multica/core/paths", () => ({
- useWorkspacePaths: () => ({ autopilots: () => "/ws/autopilots" }),
+ useWorkspacePaths: () => ({
+ autopilots: () => "/ws/autopilots",
+ autopilotDetail: (id: string) => `/ws/autopilots/${id}`,
+ }),
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: () => "Lambda" }),
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("./autopilot-list-actions", () => ({
+ AutopilotBatchToolbar: () => null,
+ AutopilotRowActions: () => null,
}));
vi.mock("./workspace-wakeups", () => ({
WorkspaceWakeups: () => <div>Wakeup inventory</div>,
- WorkspaceWakeupCreate: ({ open }: { open: boolean }) => (open ? <div>Wakeup create</div> : null),
}));
-vi.mock("./autopilot-dialog", () => ({ AutopilotDialog: () => null }));
+vi.mock("./autopilot-dialog", () => ({
+ AutopilotDialog: ({ initial }: { initial?: { title: string } }) => (
+ <div role="dialog">{initial?.title ?? "Blank autopilot"}</div>
+ ),
+}));
+// jsdom has no layout, so the virtualizer would otherwise render no rows.
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: ({ count }: { count: number }) => ({
+ getVirtualItems: () =>
+ Array.from({ length: count }, (_, index) => ({
+ index,
+ key: index,
+ start: index * 44,
+ end: (index + 1) * 44,
+ size: 44,
+ })),
+ getTotalSize: () => count * 44,
+ }),
+}));
+
+function autopilot(id: string, title: string, status: Autopilot["status"]): Autopilot {
+ return {
+ id,
+ title,
+ status,
+ workspace_id: "ws",
+ description: "",
+ assignee_type: "agent",
+ assignee_id: "agent-1",
+ execution_mode: "create_issue",
+ created_by_type: "member",
+ created_by_id: "member-1",
+ trigger_kinds: ["schedule"],
+ last_run_at: null,
+ next_run_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ } as unknown as Autopilot;
+}
+
+let currentPath = "";
-function Harness() {
- const [path, setPath] = useState("/ws/autopilots?keep=yes");
+function Harness({ initialPath }: { initialPath: string }) {
+ const [path, setPath] = useState(initialPath);
+ currentPath = path;
const url = new URL(path, "https://example.test");
return (
<NavigationProvider
@@ -37,36 +94,92 @@ function Harness() {
</NavigationProvider>
);
}
-it.each(["empty", "error"])(
- "keeps wakeups reachable when autopilots are %s",
- async (state) => {
- if (state === "empty")
- vi.mocked(api.listAutopilots).mockResolvedValue({ autopilots: [], total: 0 });
- else
- vi.mocked(api.listAutopilots).mockRejectedValue(
- new Error("Autopilots unavailable"),
- );
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
- renderWithI18n(
- <QueryClientProvider client={client}>
- <Harness />
- </QueryClientProvider>,
- );
- await screen.findByText(
- state === "empty" ? "No autopilots yet" : "Autopilots unavailable",
- );
- fireEvent.click(screen.getByRole("tab", { name: "Issue wakeups" }));
+
+function mount(initialPath = "/ws/autopilots") {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return renderWithI18n(
+ <QueryClientProvider client={client}>
+ <Harness initialPath={initialPath} />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ useAutopilotsViewStore.setState({ scope: "all", filters: EMPTY_AUTOPILOT_FILTERS });
+ vi.mocked(api.listAutopilots).mockReset().mockResolvedValue({
+ autopilots: [
+ autopilot("a1", "Daily sync", "active"),
+ autopilot("a2", "Bug triage", "active"),
+ autopilot("a3", "Weekly report", "paused"),
+ autopilot("a4", "Old digest", "archived"),
+ ],
+ total: 4,
+ });
+});
+
+describe("AutopilotsPage", () => {
+ it("shows the workspace's issue wakeups on ?tab=wakeups instead of the list", async () => {
+ mount("/ws/autopilots?tab=wakeups");
+
expect(await screen.findByText("Wakeup inventory")).toBeVisible();
expect(screen.queryByRole("button", { name: "New autopilot" })).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "New wakeup" }));
- expect(await screen.findByText("Wakeup create")).toBeVisible();
- fireEvent.click(
- screen.getByRole("tab", { name: "Autopilot" }),
- );
- expect(
- await screen.findByRole("button", { name: "New autopilot" }),
- ).toBeVisible();
- },
-);
+ expect(api.listAutopilots).not.toHaveBeenCalled();
+ });
+
+ it("titles the list with its scope and switches scope from the title menu", async () => {
+ const user = userEvent.setup();
+ mount();
+ await screen.findByText("Weekly report");
+ expect(screen.getByText("Daily sync")).toBeVisible();
+ expect(screen.queryByText("Old digest")).toBeNull();
+
+ await user.click(screen.getByRole("button", { name: "All autopilots" }));
+ expect(await screen.findByRole("menuitemradio", { name: /All autopilots\s*3/ })).toBeChecked();
+ expect(screen.getByRole("menuitemradio", { name: /Active\s*2/ })).toBeInTheDocument();
+ await user.click(screen.getByRole("menuitemradio", { name: /Paused\s*1/ }));
+
+ expect(await screen.findByRole("button", { name: "Paused" })).toBeVisible();
+ expect(screen.getByText("Weekly report")).toBeVisible();
+ expect(screen.queryByText("Daily sync")).toBeNull();
+ expect(useAutopilotsViewStore.getState().scope).toBe("paused");
+ });
+
+ it("has no search, and Reset clears the filters", async () => {
+ const user = userEvent.setup();
+ useAutopilotsViewStore.setState({
+ filters: { ...EMPTY_AUTOPILOT_FILTERS, triggerKinds: ["webhook"] },
+ });
+ mount();
+ await screen.findByRole("button", { name: "Reset" });
+ expect(screen.queryByRole("button", { name: /search/i })).toBeNull();
+ expect(screen.queryByText("Daily sync")).toBeNull();
+
+ await user.click(screen.getByRole("button", { name: "Reset" }));
+ expect(await screen.findByText("Daily sync")).toBeVisible();
+ expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
+ });
+
+ it("opens the create dialog from the header", async () => {
+ const user = userEvent.setup();
+ mount();
+ await screen.findByText("Daily sync");
+
+ await user.click(screen.getByRole("button", { name: "New autopilot" }));
+ expect(await screen.findByRole("dialog")).toHaveTextContent("Blank autopilot");
+ });
+
+ it("consumes ?template once and keeps the other params", async () => {
+ mount("/ws/autopilots?template=bug_triage&keep=yes");
+
+ expect(await screen.findByRole("dialog")).toHaveTextContent("Bug triage");
+ await waitFor(() => expect(currentPath).toBe("/ws/autopilots?keep=yes"));
+ });
+
+ it("keeps create reachable when the list fails to load", async () => {
+ vi.mocked(api.listAutopilots).mockRejectedValue(new Error("Autopilots unavailable"));
+ mount();
+
+ expect(await screen.findByText("Autopilots unavailable")).toBeVisible();
+ expect(screen.getByRole("button", { name: "New autopilot" })).toBeVisible();
+ });
+});
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index 9321bb090a..ba4f8e631d 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -1,27 +1,19 @@
"use client";
-import { useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import {
AlertCircle,
- BarChart3,
- Bug,
Clock,
Code,
- FileSearch,
- GitPullRequest,
- Newspaper,
Pause,
Plus,
- Shield,
Webhook,
Zap,
} from "@multica/ui/icons";
import { useQuery } from "@tanstack/react-query";
-import { useVirtualizer } from "@tanstack/react-virtual";
import { autopilotListOptions } from "@multica/core/autopilots/queries";
import {
useAutopilotsViewStore,
- AUTOPILOT_DEFAULT_HIDDEN_COLUMNS,
AUTOPILOT_SCOPES,
type AutopilotColumnKey,
type AutopilotScope,
@@ -32,265 +24,79 @@ import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import type { Autopilot } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import {
- LIST_GRID_BOTTOM_CLEARANCE,
- ListGrid,
- ListGridBody,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
- type ListGridSortDirection,
-} from "@multica/ui/components/ui/list-grid";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import {
- Tabs,
- TabsList,
- TabsTrigger,
- TabsContent,
-} from "@multica/ui/components/ui/tabs";
-import { WorkspaceWakeupCreate, WorkspaceWakeups } from "./workspace-wakeups";
-import { useNavigation, useRowLink } from "../../navigation";
+import { WorkspaceWakeups } from "./workspace-wakeups";
+import { useNavigation } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
import { formatInTimeZone } from "../../common/format-in-time-zone";
import {
+ CollectionCreateButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
} from "../../layout/collection-page";
+import {
+ CollectionDisplayMenu,
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ type CollectionColumn,
+ type CollectionSort,
+} from "../../layout/collection-list";
import { AutopilotDialog } from "./autopilot-dialog";
import {
- AutopilotListToolbar,
+ AutopilotFilterMenu,
actorFilterValue,
+ countActiveFilterDimensions,
} from "./autopilot-list-toolbar";
import {
AutopilotBatchToolbar,
AutopilotRowActions,
} from "./autopilot-list-actions";
-import type { ScheduleConfig } from "./schedule-editor/model";
+import { AUTOPILOT_TEMPLATES, type AutopilotTemplate } from "./autopilot-templates";
+import { isWakeupsTab } from "./wakeups-tab";
import { useLocale, useT, useTimeAgo } from "../../i18n";
-// Column template — single source of truth for header, rows, and skeletons.
-// Same conventions as the skills list (see list-grid.tsx and the comment
-// there): deterministic var-width tracks (rows are virtualized), and
-// TWO-ZONE responsiveness:
-// - Container ≥ @2xl (672px): WYSIWYG — every user-enabled column renders;
-// the grid carries min-width = Σ(enabled tracks + gaps) and the wrapper
-// scrolls horizontally when the enabled set outgrows the container. An
-// enabled column must NEVER silently vanish (the "dead toggle" bug).
-// - Container < @2xl: static core set (name + assignee), no horizontal
-// scroll, column toggles don't apply.
-const GRID_COLS =
- "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_var(--apc-assignee)_1.75rem_0.75rem] " +
- "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_var(--apc-assignee)_var(--apc-trigger)_var(--apc-lastrun)_var(--apc-nextrun)_var(--apc-mode)_var(--apc-creator)_var(--apc-created)_1.75rem_0.75rem]";
-
-// h-12 rows; the virtualizer's fixed-size contract.
-const ROW_HEIGHT = 48;
-
-// Single source for hideable column widths: track vars and the grid's
-// min-width derive from the same numbers.
-const COLUMN_WIDTHS: Record<AutopilotColumnKey, number> = {
- assignee: 144,
- trigger: 144,
- lastRun: 120,
- nextRun: 104,
- mode: 104,
- creator: 144,
- created: 104,
-};
-
-// Fixed tracks (edges 12+12, checkbox 16, name min 200, kebab 28) plus the
-// 11 gap-x-3 gaps between the wide template's 12 tracks (zero-width tracks
-// still carry gaps).
-const FIXED_TRACKS_WIDTH = 268 + 11 * 12;
-
-function columnTrackVars(
- isVisible: (key: AutopilotColumnKey) => boolean,
-): React.CSSProperties {
- const width = (key: AutopilotColumnKey) =>
- isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";
- const minWidth =
- FIXED_TRACKS_WIDTH +
- (Object.keys(COLUMN_WIDTHS) as AutopilotColumnKey[]).reduce(
- (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),
- 0,
- );
- return {
- "--apc-assignee": width("assignee"),
- "--apc-trigger": width("trigger"),
- "--apc-lastrun": width("lastRun"),
- "--apc-nextrun": width("nextRun"),
- "--apc-mode": width("mode"),
- "--apc-creator": width("creator"),
- "--apc-created": width("created"),
- "--apc-minw": `${minWidth}px`,
- } as React.CSSProperties;
-}
-
-// Templates for the empty state (unchanged from the previous page version).
-// Prompts stay raw English because they're injected directly into the
-// agent's task input.
-
-type TemplateId =
- | "daily_news"
- | "pr_review"
- | "bug_triage"
- | "weekly_progress"
- | "dependency_audit"
- | "documentation_check";
-
-interface AutopilotTemplate {
- id: TemplateId;
- prompt: string;
- icon: typeof Zap;
- schedule: Pick<ScheduleConfig, "time" | "days">;
-}
-
-const WEEKDAYS: ScheduleConfig["days"] = {
- kind: "weekly",
- daysOfWeek: [1, 2, 3, 4, 5],
-};
-const MONDAY: ScheduleConfig["days"] = { kind: "weekly", daysOfWeek: [1] };
-
-const TEMPLATES: AutopilotTemplate[] = [
- {
- id: "daily_news",
- prompt: `1. Search the web for news and announcements published today only (strictly today's date)
-2. Filter for topics relevant to our team and industry
-3. For each item, write a short summary including: title, source, key takeaways
-4. Compile everything into a single digest post
-5. Post the digest as a comment on this issue and @mention all workspace members`,
- icon: Newspaper,
- schedule: { time: { kind: "at", time: "09:00" }, days: { kind: "every" } },
- },
- {
- id: "pr_review",
- prompt: `1. List all open pull requests in the repository
-2. Identify PRs that have been open for more than 24 hours without a review
-3. For each stale PR, note the author, age, and a one-line summary of the change
-4. Post a comment on this issue listing all stale PRs with links
-5. @mention the team to remind them to review`,
- icon: GitPullRequest,
- schedule: { time: { kind: "at", time: "10:00" }, days: WEEKDAYS },
- },
- {
- id: "bug_triage",
- prompt: `1. List all backlog issues that have not been prioritized
-2. For each issue, read the description and any attached logs or screenshots
-3. Assess severity (critical / high / medium / low) based on user impact and scope
-4. Set the priority field on the issue accordingly
-5. Add a comment explaining your assessment and suggested next steps`,
- icon: Bug,
- schedule: { time: { kind: "at", time: "09:00" }, days: WEEKDAYS },
- },
- {
- id: "weekly_progress",
- prompt: `1. Gather all issues completed (status "done") in the past 7 days
-2. Gather all issues currently in progress
-3. Identify any blocked issues and their blockers
-4. Calculate key metrics: issues closed, issues opened, net change
-5. Write a structured weekly report with sections: Completed, In Progress, Blocked, Metrics
-6. Post the report as a comment on this issue`,
- icon: BarChart3,
- schedule: { time: { kind: "at", time: "17:00" }, days: MONDAY },
- },
- {
- id: "dependency_audit",
- prompt: `1. Run dependency audit tools on the project (npm audit, go vuln check, etc.)
-2. Identify any packages with known security vulnerabilities
-3. List outdated packages that are more than 2 major versions behind
-4. For each finding, note the severity, affected package, and recommended fix
-5. Post a summary report as a comment with actionable items`,
- icon: Shield,
- schedule: { time: { kind: "at", time: "08:00" }, days: MONDAY },
- },
- {
- id: "documentation_check",
- prompt: `1. List all code changes merged in the past 7 days (via git log)
-2. For each significant change, check if related documentation was updated
-3. Identify any new APIs, config options, or features missing documentation
-4. Create a list of documentation gaps with file paths and suggested content
-5. Post the findings as a comment on this issue`,
- icon: FileSearch,
- schedule: { time: { kind: "at", time: "14:00" }, days: MONDAY },
- },
-];
-
// Cells
-function CheckboxCell({
- checked,
- onToggle,
-}: {
- checked: boolean;
- onToggle: () => void;
-}) {
- return (
- <ListGridCell className="justify-center px-0">
- <button
- type="button"
- aria-pressed={checked}
- onClick={(e) => {
- e.stopPropagation();
- onToggle();
- }}
- className={`-m-1.5 flex items-center p-1.5 ${
- checked
- ? ""
- : "opacity-0 transition-opacity group-hover/row:opacity-100"
- }`}
- >
- <Checkbox
- checked={checked}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
- </ListGridCell>
- );
-}
-
function NameCell({ autopilot }: { autopilot: Autopilot }) {
const { t } = useT("autopilots");
return (
- <ListGridCell className="gap-1.5">
- <span className="min-w-0 truncate text-body font-medium">
- {autopilot.title}
- </span>
- {/* Paused marker: in the "all" scope active and paused rows mix, so a
- paused automation needs an inline signal. */}
- {autopilot.status === "paused" && (
- <span
- title={
- autopilot.pause_reason === "agent_runtime_required"
- ? t(($) => $.status.paused_runtime_required)
- : t(($) => $.status.paused)
- }
- className="flex shrink-0 items-center text-amber-500"
- >
- <Pause className="size-3" />
- </span>
- )}
- </ListGridCell>
+ <CollectionNameCell
+ title={autopilot.title}
+ badges={
+ // Paused marker: in the "all" scope active and paused rows mix, so a
+ // paused automation needs an inline signal.
+ autopilot.status === "paused" ? (
+ <span
+ title={
+ autopilot.pause_reason === "agent_runtime_required"
+ ? t(($) => $.status.paused_runtime_required)
+ : t(($) => $.status.paused)
+ }
+ className="flex shrink-0 items-center text-amber-500"
+ >
+ <Pause className="size-3" />
+ </span>
+ ) : null
+ }
+ />
);
}
-function AssigneeCell({ autopilot }: { autopilot: Autopilot }) {
+function ActorCell({ type, id, hoverCard = false }: { type: string; id: string; hoverCard?: boolean }) {
const { getActorName } = useActorName();
return (
- <ListGridCell className="gap-1.5">
+ <>
<ActorAvatar
- actorType={autopilot.assignee_type}
- actorId={autopilot.assignee_id}
+ actorType={type}
+ actorId={id}
size="sm"
- enableHoverCard={autopilot.assignee_type === "agent"}
- showStatusDot={autopilot.assignee_type === "agent"}
+ enableHoverCard={hoverCard}
+ showStatusDot={hoverCard}
/>
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {getActorName(autopilot.assignee_type, autopilot.assignee_id)}
- </span>
- </ListGridCell>
+ <span className="min-w-0 truncate">{getActorName(type, id)}</span>
+ </>
);
}
@@ -303,15 +109,9 @@ const TRIGGER_ICONS: Record<string, typeof Zap> = {
function TriggerCell({ autopilot }: { autopilot: Autopilot }) {
const { t } = useT("autopilots");
const kinds = autopilot.trigger_kinds ?? [];
- if (kinds.length === 0) {
- return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="text-caption text-faint-foreground">—</span>
- </ListGridCell>
- );
- }
+ if (kinds.length === 0) return <CollectionEmptyValue />;
return (
- <ListGridCell className="hidden gap-2 @2xl:flex">
+ <span className="flex min-w-0 items-center gap-2">
{kinds.map((kind) => {
// Server-driven enum: unknown kinds get a generic icon + raw label.
const Icon = TRIGGER_ICONS[kind] ?? Zap;
@@ -320,16 +120,13 @@ function TriggerCell({ autopilot }: { autopilot: Autopilot }) {
? t(($) => $.trigger_kind[kind])
: kind;
return (
- <span
- key={kind}
- className="flex min-w-0 items-center gap-1 text-caption text-muted-foreground"
- >
+ <span key={kind} className="flex min-w-0 items-center gap-1">
<Icon className="size-3 shrink-0" />
<span className="truncate">{label}</span>
</span>
);
})}
- </ListGridCell>
+ </span>
);
}
@@ -354,13 +151,7 @@ function runStatusDotClass(status: string | null | undefined): string {
function LastRunCell({ autopilot }: { autopilot: Autopilot }) {
const { t } = useT("autopilots");
const timeAgo = useTimeAgo();
- if (!autopilot.last_run_at) {
- return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="text-caption text-faint-foreground">—</span>
- </ListGridCell>
- );
- }
+ if (!autopilot.last_run_at) return <CollectionEmptyValue />;
const status = autopilot.last_run_status;
const knownStatus =
status === "issue_created" ||
@@ -371,7 +162,7 @@ function LastRunCell({ autopilot }: { autopilot: Autopilot }) {
? status
: null;
return (
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
+ <>
<span
title={
knownStatus
@@ -380,26 +171,19 @@ function LastRunCell({ autopilot }: { autopilot: Autopilot }) {
}
className={`size-1.5 shrink-0 rounded-full ${runStatusDotClass(status)}`}
/>
- <span className="whitespace-nowrap text-caption tabular-nums text-muted-foreground">
- {timeAgo(autopilot.last_run_at)}
- </span>
- </ListGridCell>
+ <span className="tabular-nums">{timeAgo(autopilot.last_run_at)}</span>
+ </>
);
}
function NextRunCell({ autopilot }: { autopilot: Autopilot }) {
const { i18n } = useT("autopilots");
const next = autopilot.next_run_at;
+ if (!next) return <CollectionEmptyValue />;
return (
- <ListGridCell className="hidden @2xl:flex">
- {next ? (
- <span className="whitespace-nowrap text-caption tabular-nums text-muted-foreground">
- {formatInTimeZone(next, undefined, i18n.language)}
- </span>
- ) : (
- <span className="text-caption text-faint-foreground">—</span>
- )}
- </ListGridCell>
+ <span className="truncate tabular-nums">
+ {formatInTimeZone(next, undefined, i18n.language)}
+ </span>
);
}
@@ -410,216 +194,31 @@ function ModeCell({ autopilot }: { autopilot: Autopilot }) {
mode === "create_issue" || mode === "run_only"
? t(($) => $.execution_mode[mode])
: mode;
- return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="truncate text-caption text-muted-foreground">
- {label}
- </span>
- </ListGridCell>
- );
+ return <span className="truncate">{label}</span>;
}
-function CreatorCell({ autopilot }: { autopilot: Autopilot }) {
- const { getActorName } = useActorName();
- return (
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
- <ActorAvatar
- actorType={autopilot.created_by_type}
- actorId={autopilot.created_by_id}
- size="sm"
- />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {getActorName(autopilot.created_by_type, autopilot.created_by_id)}
- </span>
- </ListGridCell>
- );
-}
-
-// Header row
+// Page
-function AutopilotListHeader({
- sortField,
- sortDirection,
- onSort,
- allSelected,
- someSelected,
- onToggleAll,
- isColVisible,
-}: {
- sortField: AutopilotSortField;
- sortDirection: ListGridSortDirection;
- onSort: (field: AutopilotSortField) => void;
- allSelected: boolean;
- someSelected: boolean;
- onToggleAll: () => void;
- isColVisible: (key: AutopilotColumnKey) => boolean;
-}) {
- const { t } = useT("autopilots");
- const sorted = (field: AutopilotSortField) =>
- sortField === field ? sortDirection : false;
- const anySelected = allSelected || someSelected;
- return (
- <ListGridHeader>
- <div className="flex items-center justify-center">
- <button
- type="button"
- aria-pressed={allSelected}
- onClick={onToggleAll}
- className={`-m-1.5 flex items-center p-1.5 ${
- anySelected
- ? ""
- : "opacity-0 transition-opacity group-hover/header:opacity-100"
- }`}
- >
- <Checkbox
- checked={allSelected}
- indeterminate={someSelected && !allSelected}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
+export function AutopilotsPage() {
+ const navigation = useNavigation();
+ const wsId = useWorkspaceId();
+ if (isWakeupsTab(navigation.searchParams)) {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <WorkspaceWakeups key={wsId} />
</div>
- <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>
- {t(($) => $.page.table.name)}
- </ListGridHeaderCell>
- {isColVisible("assignee") ? (
- <ListGridHeaderCell>
- {t(($) => $.page.table.assignee)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="px-0" />
- )}
- {isColVisible("trigger") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.page.table.trigger)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("lastRun") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("lastRun")}
- onSort={() => onSort("lastRun")}
- >
- {t(($) => $.page.table.last_run)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("nextRun") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("nextRun")}
- onSort={() => onSort("nextRun")}
- >
- {t(($) => $.page.table.next_run)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("mode") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.page.table.mode)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("creator") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.page.table.created_by)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("created")}
- onSort={() => onSort("created")}
- >
- {t(($) => $.page.table.created)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- <span aria-hidden="true" />
- </ListGridHeader>
- );
-}
-
-function LoadingSkeleton() {
- return (
- <ListGrid
- className={GRID_COLS}
- style={columnTrackVars(
- (key) => !AUTOPILOT_DEFAULT_HIDDEN_COLUMNS.includes(key),
- )}
- >
- <ListGridHeader>
- <span aria-hidden="true" />
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-14" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- {/* mode/creator/created are hidden by default — keep their tracks
- mapped with empty placeholders. */}
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridHeader>
- {Array.from({ length: 5 }).map((_, i) => (
- <ListGridRow key={i} className="hover:bg-transparent">
- <span aria-hidden="true" />
- <ListGridCell>
- <Skeleton className="h-3.5 w-40 max-w-full" />
- </ListGridCell>
- <ListGridCell className="gap-1.5">
- <Skeleton className="size-5 rounded-full" />
- <Skeleton className="h-3 w-12" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-16" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-14" />
- </ListGridCell>
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridRow>
- ))}
- </ListGrid>
- );
+ );
+ }
+ return <AutopilotList />;
}
-// Page
-
-export function AutopilotsPage() {
+function AutopilotList() {
const navigation = useNavigation();
- const tab =
- navigation.searchParams.get("tab") === "wakeups" ? "wakeups" : "autopilots";
const { t } = useT("autopilots");
+ const { t: tLayout } = useT("layout");
const locale = useLocale();
const wsId = useWorkspaceId();
const wsPaths = useWorkspacePaths();
- const rowLink = useRowLink();
const {
data: autopilots = [],
isLoading,
@@ -627,11 +226,10 @@ export function AutopilotsPage() {
refetch: refetchList,
} = useQuery({
...autopilotListOptions(wsId),
- enabled: !!wsId && tab === "autopilots",
+ enabled: !!wsId,
});
const [createOpen, setCreateOpen] = useState(false);
- const [wakeupCreateOpen, setWakeupCreateOpen] = useState(false);
const [selectedTemplate, setSelectedTemplate] =
useState<AutopilotTemplate | null>(null);
const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(
@@ -654,16 +252,10 @@ export function AutopilotsPage() {
const toggleFilter = useAutopilotsViewStore((s) => s.toggleFilter);
const clearFilters = useAutopilotsViewStore((s) => s.clearFilters);
- const isColVisible = (key: AutopilotColumnKey) =>
- !hiddenColumns.includes(key);
-
- const toggleSelected = (id: string) => {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
+ const scopeLabels: Record<AutopilotScope, string> = {
+ all: tLayout(($) => $.panels.autopilots.all),
+ active: t(($) => $.status.active),
+ paused: t(($) => $.status.paused),
};
// Scope counts come from the FULL set (filters never affect them — they
@@ -680,8 +272,8 @@ export function AutopilotsPage() {
return { all: active + paused, active, paused };
}, [autopilots]);
- // Rows within the current scope, unfiltered — toolbar option lists and
- // the "n / total" denominator derive from this.
+ // Rows within the current scope, unfiltered — the filter menu's option
+ // lists and counts derive from this.
const scopeRows = useMemo<Autopilot[]>(() => {
if (scope === "all") {
return autopilots.filter((a) => a.status !== "archived");
@@ -689,6 +281,8 @@ export function AutopilotsPage() {
return autopilots.filter((a) => a.status === scope);
}, [autopilots, scope]);
+ const narrowed = countActiveFilterDimensions(filters) > 0;
+
// Visible rows: filters, then sort.
const rows = useMemo<Autopilot[]>(() => {
const filtered = scopeRows.filter((a) => {
@@ -748,35 +342,109 @@ export function AutopilotsPage() {
return filtered;
}, [scopeRows, filters, sortField, sortDirection]);
- // Row virtualization — same wiring as the skills list: headless math,
- // offsets as padding on the body, fixed-height rows.
- const listScrollRef = useRef<HTMLDivElement | null>(null);
- const rowVirtualizer = useVirtualizer({
- count: rows.length,
- getScrollElement: () => listScrollRef.current,
- estimateSize: () => ROW_HEIGHT,
- overscan: 10,
- });
+ const columns = useMemo<CollectionColumn<Autopilot>[]>(
+ () => [
+ {
+ key: "name",
+ header: t(($) => $.page.table.name),
+ sortKey: "name",
+ cell: (a) => <NameCell autopilot={a} />,
+ },
+ {
+ key: "assignee",
+ header: t(($) => $.page.table.assignee),
+ width: 144,
+ core: true,
+ hideable: true,
+ cell: (a) => (
+ <ActorCell
+ type={a.assignee_type}
+ id={a.assignee_id}
+ hoverCard={a.assignee_type === "agent"}
+ />
+ ),
+ },
+ {
+ key: "trigger",
+ header: t(($) => $.page.table.trigger),
+ width: 144,
+ hideable: true,
+ cell: (a) => <TriggerCell autopilot={a} />,
+ },
+ {
+ key: "lastRun",
+ header: t(($) => $.page.table.last_run),
+ width: 112,
+ sortKey: "lastRun",
+ hideable: true,
+ cell: (a) => <LastRunCell autopilot={a} />,
+ },
+ {
+ key: "nextRun",
+ header: t(($) => $.page.table.next_run),
+ width: 128,
+ sortKey: "nextRun",
+ hideable: true,
+ cell: (a) => <NextRunCell autopilot={a} />,
+ },
+ {
+ key: "mode",
+ header: t(($) => $.page.table.mode),
+ width: 104,
+ hideable: true,
+ cell: (a) => <ModeCell autopilot={a} />,
+ },
+ {
+ key: "creator",
+ header: t(($) => $.page.table.created_by),
+ width: 144,
+ hideable: true,
+ cell: (a) => <ActorCell type={a.created_by_type} id={a.created_by_id} />,
+ },
+ {
+ key: "created",
+ header: t(($) => $.page.table.created),
+ width: 104,
+ sortKey: "created",
+ hideable: true,
+ cell: (a) => (
+ <span className="tabular-nums">
+ {new Date(a.created_at).toLocaleDateString(locale)}
+ </span>
+ ),
+ },
+ ],
+ [t, locale],
+ );
+
+ const sort: CollectionSort = {
+ field: sortField,
+ direction: sortDirection,
+ onToggle: (field) => handleSort(field as AutopilotSortField),
+ onFieldChange: (field) => handleSortFieldSelect(field as AutopilotSortField),
+ onDirectionChange: setSortDirection,
+ };
const openCreate = (template?: AutopilotTemplate) => {
setSelectedTemplate(template ?? null);
setCreateOpen(true);
};
- const selectedRows = rows.filter((a) => selectedIds.has(a.id));
- const allSelected = rows.length > 0 && selectedRows.length === rows.length;
- const someSelected = selectedRows.length > 0 && !allSelected;
- const handleToggleAll = () => {
- setSelectedIds(allSelected ? new Set() : new Set(rows.map((a) => a.id)));
- };
+ // The Autopilots panel links here with `?create` or `?template=<id>`.
+ const createParam = navigation.searchParams.get("create");
+ const templateParam = navigation.searchParams.get("template");
+ useEffect(() => {
+ if (createParam === null && templateParam === null) return;
+ setSelectedTemplate(AUTOPILOT_TEMPLATES.find((tpl) => tpl.id === templateParam) ?? null);
+ setCreateOpen(true);
+ const params = new URLSearchParams(navigation.searchParams);
+ params.delete("create");
+ params.delete("template");
+ navigation.replace(`${navigation.pathname}${params.size ? `?${params}` : ""}${navigation.hash}`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- consume the intent once per URL change
+ }, [createParam, templateParam]);
- const virtualItems = rowVirtualizer.getVirtualItems();
- const firstVirtual = virtualItems[0];
- const lastVirtual = virtualItems[virtualItems.length - 1];
- const virtualPadding = {
- top: firstVirtual ? firstVirtual.start : 0,
- bottom: lastVirtual ? rowVirtualizer.getTotalSize() - lastVirtual.end : 0,
- };
+ const selectedRows = rows.filter((a) => selectedIds.has(a.id));
const totalCount = autopilots.length;
const showEmpty = !isLoading && !listError && totalCount === 0;
@@ -784,270 +452,151 @@ export function AutopilotsPage() {
return (
// relative: positioning anchor for the batch toolbar (page-centered,
// not viewport-centered).
- <Tabs
- className="relative flex flex-1 min-h-0 flex-col gap-0"
- value={tab}
- onValueChange={(value) => {
- const params = new URLSearchParams(navigation.searchParams);
- if (value === "wakeups") params.set("tab", "wakeups");
- else params.delete("tab");
- navigation.replace(
- `${navigation.pathname}${params.size ? `?${params}` : ""}${navigation.hash}`,
- );
- }}
- >
- {/* Header */}
+ <div className="relative flex min-h-0 flex-1 flex-col">
<CollectionPageHeader
icon={Zap}
- title={t(($) => $.page.title)}
- count={tab === "autopilots" ? totalCount : undefined}
+ title={scopeLabels[scope]}
+ menu={
+ <CollectionScopeItems
+ value={scope}
+ onChange={setScope}
+ options={AUTOPILOT_SCOPES.map((value) => ({
+ value,
+ label: scopeLabels[value],
+ count: scopeCounts[value],
+ }))}
+ />
+ }
+ tools={
+ <>
+ <AutopilotFilterMenu
+ filters={filters}
+ onToggleFilter={toggleFilter}
+ allRows={scopeRows}
+ />
+ {narrowed && <CollectionResetButton onClick={clearFilters} />}
+ </>
+ }
actions={
- tab === "autopilots" ? (
- <CollectionPageHeaderAction
- icon={Plus}
+ <>
+ <CollectionDisplayMenu
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ onToggleColumn={(key) => toggleColumn(key as AutopilotColumnKey)}
+ sort={sort}
+ />
+ <CollectionCreateButton
label={t(($) => $.page.new_autopilot)}
onClick={() => openCreate()}
/>
- ) : (
- <CollectionPageHeaderAction
- icon={Plus}
- label={t(($) => $.wakeups.create)}
- onClick={() => setWakeupCreateOpen(true)}
- />
- )
+ </>
}
/>
- <div className="shrink-0 border-b px-4 py-1">
- <TabsList variant="line" aria-label={t(($) => $.page.title)}>
- <TabsTrigger value="autopilots">{t(($) => $.page.title)}</TabsTrigger>
- <TabsTrigger value="wakeups">{t(($) => $.wakeups.title)}</TabsTrigger>
- </TabsList>
- </div>
- <TabsContent
- value="wakeups"
- className="flex min-h-0 flex-col data-hidden:hidden"
- >
- <WorkspaceWakeups key={wsId} />
- <WorkspaceWakeupCreate open={wakeupCreateOpen} onOpenChange={setWakeupCreateOpen} />
- </TabsContent>
- <TabsContent
- value="autopilots"
- className="flex min-h-0 flex-col data-hidden:hidden"
- >
- {listError ? (
- <CollectionPageState
- role="alert"
- tone="destructive"
- icon={AlertCircle}
- title={
- listError instanceof Error ? listError.message : String(listError)
- }
- actions={
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => refetchList()}
- >
- {t(($) => $.page.retry)}
- </Button>
- }
- />
- ) : showEmpty ? (
- <div className="flex flex-col items-center px-5 py-16">
- <Zap className="mb-3 h-10 w-10 text-faint-foreground" />
- <p className="text-body text-muted-foreground">
- {t(($) => $.page.empty.title)}
- </p>
- <p className="mb-6 mt-1 text-caption text-muted-foreground">
- {t(($) => $.page.empty.hint)}
- </p>
- <div className="grid w-full max-w-3xl grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
- {TEMPLATES.map((tpl) => {
- const Icon = tpl.icon;
- return (
- <button
- key={tpl.id}
- type="button"
- className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"
- onClick={() => openCreate(tpl)}
- >
- <Icon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
- <div className="min-w-0">
- <div className="text-body font-medium">
- {t(($) => $.templates[tpl.id].title)}
- </div>
- <div className="mt-0.5 line-clamp-2 text-caption text-muted-foreground">
- {t(($) => $.templates[tpl.id].summary)}
- </div>
- </div>
- </button>
- );
- })}
- </div>
+ {listError ? (
+ <CollectionPageState
+ role="alert"
+ tone="destructive"
+ icon={AlertCircle}
+ title={
+ listError instanceof Error ? listError.message : String(listError)
+ }
+ actions={
<Button
- size="sm"
+ type="button"
variant="outline"
- className="mt-4"
- onClick={() => openCreate()}
+ size="sm"
+ onClick={() => refetchList()}
>
- <Plus className="mr-1 h-3.5 w-3.5" />
- {t(($) => $.page.start_blank)}
+ {t(($) => $.page.retry)}
</Button>
- </div>
- ) : (
- <>
- {/* Mounted through loading so the rows don't drop by a toolbar's
- height when the list lands. */}
- <AutopilotListToolbar
- scope={scope}
- onScopeChange={setScope}
- scopeCounts={scopeCounts}
- filters={filters}
- onToggleFilter={toggleFilter}
- onClearFilters={clearFilters}
- sortField={sortField}
- sortDirection={sortDirection}
- onSortFieldChange={handleSortFieldSelect}
- onSortDirectionChange={setSortDirection}
- hiddenColumns={hiddenColumns}
- onToggleColumn={toggleColumn}
- allRows={scopeRows}
- visibleCount={rows.length}
- />
- {isLoading ? (
- <div className="flex-1 overflow-y-auto @container">
- <LoadingSkeleton />
- </div>
- ) : (
- <div
- ref={listScrollRef}
- className="min-h-0 flex-1 overflow-auto @container"
- >
- <ListGrid
- className={`${GRID_COLS} @2xl:min-w-[var(--apc-minw)]`}
- style={columnTrackVars(isColVisible)}
- >
- <AutopilotListHeader
- sortField={sortField}
- sortDirection={sortDirection}
- onSort={handleSort}
- allSelected={allSelected}
- someSelected={someSelected}
- onToggleAll={handleToggleAll}
- isColVisible={isColVisible}
- />
- <ListGridBody
- style={{
- paddingTop: virtualPadding.top,
- paddingBottom:
- virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,
- }}
+ }
+ />
+ ) : showEmpty ? (
+ <div className="flex flex-col items-center px-5 py-16">
+ <Zap className="mb-3 h-10 w-10 text-faint-foreground" />
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.page.empty.title)}
+ </p>
+ <p className="mb-6 mt-1 text-caption text-muted-foreground">
+ {t(($) => $.page.empty.hint)}
+ </p>
+ <div className="grid w-full max-w-3xl grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
+ {AUTOPILOT_TEMPLATES.map((tpl) => {
+ const Icon = tpl.icon;
+ return (
+ <button
+ key={tpl.id}
+ type="button"
+ className="flex items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40"
+ onClick={() => openCreate(tpl)}
>
- {rows.length === 0 && (
- <div className="col-span-full py-16 text-center text-body text-muted-foreground">
- {t(($) => $.page.no_matches)}
+ <Icon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0">
+ <div className="text-body font-medium">
+ {t(($) => $.templates[tpl.id].title)}
</div>
- )}
- {virtualItems.map((vi) => {
- const autopilot = rows[vi.index];
- if (!autopilot) return null;
- return (
- <ListGridRow
- key={autopilot.id}
- className={`cursor-pointer ${
- selectedIds.has(autopilot.id) ? "bg-accent/30" : ""
- }`}
- {...rowLink(
- wsPaths.autopilotDetail(autopilot.id),
- autopilot.title,
- )}
- >
- <CheckboxCell
- checked={selectedIds.has(autopilot.id)}
- onToggle={() => toggleSelected(autopilot.id)}
- />
- <NameCell autopilot={autopilot} />
- {isColVisible("assignee") ? (
- <AssigneeCell autopilot={autopilot} />
- ) : (
- <ListGridCell className="px-0" />
- )}
- {isColVisible("trigger") ? (
- <TriggerCell autopilot={autopilot} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("lastRun") ? (
- <LastRunCell autopilot={autopilot} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("nextRun") ? (
- <NextRunCell autopilot={autopilot} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("mode") ? (
- <ModeCell autopilot={autopilot} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("creator") ? (
- <CreatorCell autopilot={autopilot} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">
- {new Date(autopilot.created_at).toLocaleDateString(
- locale,
- )}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- <ListGridCell className="justify-end px-0">
- <AutopilotRowActions row={autopilot} />
- </ListGridCell>
- </ListGridRow>
- );
- })}
- </ListGridBody>
- </ListGrid>
- </div>
- )}
- </>
- )}
-
- <AutopilotBatchToolbar
- rows={selectedRows}
- onClear={() => setSelectedIds(new Set())}
+ <div className="mt-0.5 line-clamp-2 text-caption text-muted-foreground">
+ {t(($) => $.templates[tpl.id].summary)}
+ </div>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ className="mt-4"
+ onClick={() => openCreate()}
+ >
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ {t(($) => $.page.start_blank)}
+ </Button>
+ </div>
+ ) : (
+ <CollectionList
+ label={scopeLabels[scope]}
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ rows={rows}
+ loading={isLoading}
+ getRowId={(a) => a.id}
+ getRowHref={(a) => wsPaths.autopilotDetail(a.id)}
+ getRowTitle={(a) => a.title}
+ rowMenu={(a) => <AutopilotRowActions row={a} />}
+ sort={sort}
+ selection={{ selectedIds, onChange: setSelectedIds }}
+ empty={t(($) => $.page.no_matches)}
/>
+ )}
- {createOpen && (
- <AutopilotDialog
- mode="create"
- open={createOpen}
- onOpenChange={setCreateOpen}
- initial={
- selectedTemplate
- ? {
- // Template title pulls from i18n so the user-visible default
- // matches their locale, while the prompt body stays raw EN
- // since it's injected directly into the agent task.
- title: t(($) => $.templates[selectedTemplate.id].title),
- description: selectedTemplate.prompt,
- }
- : undefined
- }
- initialSchedule={
- selectedTemplate ? selectedTemplate.schedule : undefined
- }
- />
- )}
- </TabsContent>
- </Tabs>
+ <AutopilotBatchToolbar
+ rows={selectedRows}
+ onClear={() => setSelectedIds(new Set())}
+ />
+
+ {createOpen && (
+ <AutopilotDialog
+ mode="create"
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ initial={
+ selectedTemplate
+ ? {
+ // Template title pulls from i18n so the user-visible default
+ // matches their locale, while the prompt body stays raw EN
+ // since it's injected directly into the agent task.
+ title: t(($) => $.templates[selectedTemplate.id].title),
+ description: selectedTemplate.prompt,
+ }
+ : undefined
+ }
+ initialSchedule={
+ selectedTemplate ? selectedTemplate.schedule : undefined
+ }
+ />
+ )}
+ </div>
);
}
diff --git a/packages/views/autopilots/components/wakeups-tab.ts b/packages/views/autopilots/components/wakeups-tab.ts
new file mode 100644
index 0000000000..e92f83bead
--- /dev/null
+++ b/packages/views/autopilots/components/wakeups-tab.ts
@@ -0,0 +1,29 @@
+import { workspaceWakeupsOptions } from "@multica/core/issues/wakeups";
+
+/** The workspace's issue wakeups live on the autopilots route under `?tab=wakeups`. */
+export const WAKEUPS_TAB = "wakeups";
+
+export function isWakeupsTab(searchParams: URLSearchParams): boolean {
+ return searchParams.get("tab") === WAKEUPS_TAB;
+}
+
+export function wakeupsHref(autopilotsPath: string): string {
+ return `${autopilotsPath}?tab=${WAKEUPS_TAB}`;
+}
+
+/**
+ * Per-scope counts plus the newest rule the platform paused. The sidebar's
+ * count and the list's paused banner read this one query, so they share a
+ * request.
+ */
+export function wakeupCountsOptions(wsId: string) {
+ return workspaceWakeupsOptions(wsId, {
+ scope: "paused",
+ kind: "all",
+ source: "",
+ search: "",
+ agent_id: "",
+ offset: 0,
+ limit: 1,
+ });
+}
diff --git a/packages/views/autopilots/components/webhook-deliveries-section.tsx b/packages/views/autopilots/components/webhook-deliveries-section.tsx
index 4a2a80bf28..c4db7979c6 100644
--- a/packages/views/autopilots/components/webhook-deliveries-section.tsx
+++ b/packages/views/autopilots/components/webhook-deliveries-section.tsx
@@ -33,6 +33,7 @@ import { copyText } from "@multica/ui/lib/clipboard";
import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";
import { toast } from "sonner";
import { useLocale, useT } from "../../i18n";
+import { ObjectSection, ObjectSectionCard } from "../../layout/object-page";
import type {
WebhookDelivery,
WebhookDeliveryStatus,
@@ -51,8 +52,8 @@ type StatusVisual = {
};
const STATUS_VISUAL: Record<WebhookDeliveryStatus, StatusVisual> = {
- queued: { color: "text-blue-500", icon: Loader2, spin: true },
- dispatched: { color: "text-emerald-500", icon: CheckCircle2 },
+ queued: { color: "text-info", icon: Loader2, spin: true },
+ dispatched: { color: "text-success", icon: CheckCircle2 },
// Signature failures and pre-flight bouncebacks land here. Read as a
// failure visually, the dialog footer explains the reason.
rejected: { color: "text-destructive", icon: ShieldOff },
@@ -120,10 +121,10 @@ export function WebhookDeliveriesSection({
if (!hasWebhookTrigger) return null;
return (
- <section className="space-y-3">
- <h2 className="text-body font-medium text-muted-foreground uppercase tracking-wider">
- {t(($) => $.deliveries.section_title)}
- </h2>
+ <ObjectSection
+ title={t(($) => $.deliveries.section_title)}
+ count={isLoading ? undefined : deliveries.length}
+ >
{isLoading ? (
<div className="space-y-1">
{Array.from({ length: 3 }).map((_, i) => (
@@ -131,11 +132,11 @@ export function WebhookDeliveriesSection({
))}
</div>
) : deliveries.length === 0 ? (
- <div className="rounded-md border border-dashed p-4 text-center text-body text-muted-foreground">
+ <div className="rounded-lg border border-dashed p-4 text-center text-body text-muted-foreground">
{t(($) => $.deliveries.empty)}
</div>
) : (
- <div className="rounded-md border overflow-hidden">
+ <ObjectSectionCard>
{deliveries.map((delivery) => (
<DeliveryRow
key={delivery.id}
@@ -143,9 +144,9 @@ export function WebhookDeliveriesSection({
autopilotId={autopilotId}
/>
))}
- </div>
+ </ObjectSectionCard>
)}
- </section>
+ </ObjectSection>
);
}
@@ -174,7 +175,7 @@ function DeliveryRow({
<button
type="button"
onClick={() => setOpen(true)}
- className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-body hover:bg-accent/30 transition-colors"
+ className="flex min-h-10 w-full items-center gap-3 px-3 py-2 text-left text-body hover:bg-accent/30 transition-colors"
>
<StatusIcon
className={cn(
diff --git a/packages/views/autopilots/components/workspace-wakeups.test.tsx b/packages/views/autopilots/components/workspace-wakeups.test.tsx
index 0c93866b87..b6e9fa042c 100644
--- a/packages/views/autopilots/components/workspace-wakeups.test.tsx
+++ b/packages/views/autopilots/components/workspace-wakeups.test.tsx
@@ -35,6 +35,7 @@ vi.mock("@multica/core/paths", () => ({
issueDetail: (id: string) => `/ws/issues/${id}`,
}),
}));
+const rowLinks = vi.hoisted(() => [] as string[]);
vi.mock("../../navigation", () => ({
AppLink: ({
href,
@@ -48,6 +49,12 @@ vi.mock("../../navigation", () => ({
{children}
</a>
),
+ useIntentNavigate: () => () => {},
+ useRowLink: () => (href: string) => ({
+ onClick: () => rowLinks.push(href),
+ onAuxClick: () => {},
+ onMouseEnter: () => {},
+ }),
}));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
vi.mock("../../common/task-transcript", () => ({
@@ -89,6 +96,7 @@ function mount() {
}
beforeEach(() => {
queries = [];
+ rowLinks.length = 0;
rows = ["a", "b"].map((id) => ({
id,
issue_id: `issue-${id}`,
@@ -164,14 +172,10 @@ it("shows consumed running work separately from its off state and keeps transcri
expect(
within(row).getByRole("button", { name: "Enable again" }),
).toBeDisabled();
- expect(within(row).getByRole("checkbox")).toHaveAttribute(
- "aria-disabled",
- "true",
- );
- expect(within(row).getByRole("link", { name: /Issue a/ })).toHaveAttribute(
- "href",
- "/ws/issues/issue-a",
- );
+ // A rule that is already off is not part of batch selection.
+ expect(within(row).queryByRole("checkbox")).toBeNull();
+ fireEvent.click(within(row).getByText("Issue a"));
+ expect(rowLinks).toEqual(["/ws/issues/issue-a"]);
});
it("confirms batch consequences and retains only failed selections for retry", async () => {
@@ -182,7 +186,7 @@ it("confirms batch consequences and retains only failed selections for retry", a
await screen.findByText("Issue a");
fireEvent.click(
screen.getByRole("checkbox", {
- name: "Select enabled wakeups on this page",
+ name: "Select all enabled wakeups",
}),
);
fireEvent.click(screen.getByRole("button", { name: "Turn off selected" }));
@@ -206,16 +210,19 @@ it("confirms batch consequences and retains only failed selections for retry", a
).toBeChecked();
});
-it("resets page and selection on scope or search changes and sends bounded page requests", async () => {
+it("loads more in bounded pages and resets paging and selection on scope changes", async () => {
+ const user = userEvent.setup();
mount();
await screen.findByText("Issue a");
- fireEvent.click(screen.getByRole("button", { name: "Next" }));
- await waitFor(() => expect(queries.at(-1)?.offset).toBe(50));
+ fireEvent.click(screen.getByRole("button", { name: "Load more" }));
+ await waitFor(() => expect(queries.at(-1)).toMatchObject({ offset: 2, limit: 50 }));
await screen.findByText("Issue a");
fireEvent.click(
screen.getByRole("checkbox", { name: "Select DEV-a, Agent a" }),
);
- fireEvent.click(screen.getByRole("button", { name: /^All\s*60/ }));
+ // The scope is the header's title; its menu carries the counts.
+ await user.click(screen.getByRole("button", { name: "Waiting or executing" }));
+ await user.click(await screen.findByRole("menuitemradio", { name: /All wakeups\s*60/ }));
await waitFor(() =>
expect(queries.at(-1)).toMatchObject({
scope: "all",
@@ -223,15 +230,11 @@ it("resets page and selection on scope or search changes and sends bounded page
limit: 50,
}),
);
- expect(
- screen.queryByRole("button", { name: "Turn off selected" }),
- ).toBeNull();
- // Search runs once typing pauses; there is no submit button.
- fireEvent.change(screen.getByRole("searchbox"), {
- target: { value: "CI & release" },
- });
- await waitFor(() => expect(queries.at(-1)?.search).toBe("CI & release"));
- expect(queries.filter((q) => q.search).length).toBe(1);
+ expect(screen.getByRole("button", { name: "All wakeups" })).toBeVisible();
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Turn off selected" })).toBeNull(),
+ );
+ expect(screen.queryByRole("button", { name: /search/i })).toBeNull();
});
it("makes read-only rules non-selectable and surfaces inventory failures", async () => {
@@ -239,8 +242,8 @@ it("makes read-only rules non-selectable and surfaces inventory failures", async
const view = mount();
await screen.findByText("Issue a");
expect(
- screen.getByRole("checkbox", { name: "Select DEV-a, Agent a" }),
- ).toHaveAttribute("aria-disabled", "true");
+ screen.queryByRole("checkbox", { name: "Select DEV-a, Agent a" }),
+ ).toBeNull();
expect(
screen.getByRole("switch", { name: "Wakeup for Agent a" }),
).toHaveAttribute("aria-disabled", "true");
@@ -314,13 +317,28 @@ it("shows who created a rule and how often it ran this week", async () => {
expect(row).toHaveTextContent("4");
});
-it("filters by source", async () => {
+it("filters by source from the header's filter menu and resets it", async () => {
const user = userEvent.setup();
mount();
await screen.findByRole("row", { name: /Issue a/ });
- await user.click(screen.getByRole("combobox", { name: "Source" }));
- await user.click(await screen.findByRole("option", { name: "System" }));
+ await user.click(screen.getByRole("button", { name: "Filter" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Source" }));
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: "System" }));
await waitFor(() => expect(queries.at(-1)).toMatchObject({ source: "system", offset: 0 }));
+ expect(screen.getByRole("button", { name: "1 filter" })).toBeVisible();
+
+ await user.click(screen.getByRole("button", { name: "Reset" }));
+ await waitFor(() => expect(queries.at(-1)).toMatchObject({ source: "", scope: "active" }));
+ expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
+});
+
+it("starts a new wakeup from the header", async () => {
+ const user = userEvent.setup();
+ mount();
+ await screen.findByRole("row", { name: /Issue a/ });
+ expect(screen.queryByRole("dialog", { name: "Pick issue" })).toBeNull();
+ await user.click(screen.getByRole("button", { name: "New wakeup" }));
+ expect(await screen.findByRole("dialog", { name: "Pick issue" })).toBeVisible();
});
it("warns about paused rules and jumps to them", async () => {
diff --git a/packages/views/autopilots/components/workspace-wakeups.tsx b/packages/views/autopilots/components/workspace-wakeups.tsx
index b50998036e..6abe69cea6 100644
--- a/packages/views/autopilots/components/workspace-wakeups.tsx
+++ b/packages/views/autopilots/components/workspace-wakeups.tsx
@@ -1,13 +1,13 @@
"use client";
-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { Bell, Clock3, AlertCircle, ListChecks, Search, TriangleAlert } from "@multica/ui/icons";
+import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import { AlarmClock, Bell, Clock3, AlertCircle, ListChecks, TriangleAlert } from "@multica/ui/icons";
import { toast } from "sonner";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import {
- workspaceWakeupsOptions,
+ workspaceWakeupsInfiniteOptions,
useDisableWorkspaceWakeups,
useDisableIssueWakeup,
useEnableIssueWakeup,
@@ -20,23 +20,16 @@ import type {
} from "@multica/core/types";
import { Switch } from "@multica/ui/components/ui/switch";
import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import { Input } from "@multica/ui/components/ui/input";
import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectContent,
- SelectItem,
-} from "@multica/ui/components/ui/select";
-import {
- Table,
- TableHeader,
- TableHead,
- TableBody,
- TableRow,
- TableCell,
-} from "@multica/ui/components/ui/table";
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
@@ -46,9 +39,21 @@ import {
DialogFooter,
} from "@multica/ui/components/ui/dialog";
import { cn } from "@multica/ui/lib/utils";
-import { AppLink } from "../../navigation";
import { useLocale, useT } from "../../i18n";
-import { CollectionPageState } from "../../layout/collection-page";
+import {
+ CollectionCreateButton,
+ CollectionFilterButton,
+ CollectionPageHeader,
+ CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
+} from "../../layout/collection-page";
+import {
+ CollectionBatchBar,
+ CollectionList,
+ CollectionNameCell,
+ type CollectionColumn,
+} from "../../layout/collection-list";
import { ActorAvatar } from "../../common/actor-avatar";
import { TranscriptButton } from "../../common/task-transcript";
import { useViewingTimezone } from "../../common/use-viewing-timezone";
@@ -61,51 +66,65 @@ import {
isActiveWakeupRun,
useWakeupText,
} from "../../issues/components/wakeup-presentation";
+import { wakeupCountsOptions } from "./wakeups-tab";
+
+const SCOPES = ["active", "paused", "disabled", "ended", "all"] as const;
-// Per-row controls (selection, prompt editing, the last run's transcript)
-// stay out of the way until the pointer or focus is on the row.
+type WakeupFilters = Omit<WorkspaceWakeupFilters, "offset">;
+
+// Per-row controls (prompt editing, the last run's transcript) stay out of the
+// way until the pointer or focus is on the row.
const rowIntent =
"opacity-0 transition-opacity group-hover/row:opacity-100 group-focus-within/row:opacity-100";
-/**
- * Identifier and title on one line; the whole cell opens the issue. The column
- * takes the width the others leave and truncates, so the table fits the page.
- */
-function IssueCell({ row }: { row: WorkspaceWakeup }) {
- const paths = useWorkspacePaths();
- return (
- <TableCell className="w-full max-w-0">
- <AppLink
- href={paths.issueDetail(row.issue_id)}
- title={`${row.issue_identifier} ${row.issue_title}`}
- className="flex min-w-0 items-center gap-2 rounded-sm focus-visible:outline-2 focus-visible:outline-ring"
- >
- <span className="shrink-0 text-caption tabular-nums text-muted-foreground">{row.issue_identifier}</span>
- <span className="truncate">{row.issue_title}</span>
- </AppLink>
- </TableCell>
- );
+const rowId = (row: WorkspaceWakeup) => (row.source === "system" ? `system-${row.id}` : row.id);
+
+function useSystemTitle() {
+ const { t } = useT("issues");
+ return (row: WorkspaceWakeup) =>
+ row.system_stage != null
+ ? t(($) => $.wakeups.system.title_stage, { stage: row.system_stage })
+ : t(($) => $.wakeups.system.title_all);
}
-function TriggerCell({ icon: Icon, label, detail }: { icon: typeof Bell; label: string; detail?: string }) {
+/** Identifier and title, then what wakes it as the row's description. */
+function IssueCell({ row }: { row: WorkspaceWakeup }) {
+ const text = useWakeupText();
+ const systemTitle = useSystemTitle();
+ const system = row.source === "system";
+ const Icon = system
+ ? ListChecks
+ : (conditionIcon(row.condition) ?? (row.kind === "event" ? Bell : Clock3));
+ const trigger = system ? systemTitle(row) : text.trigger(row);
+ const detail = system ? undefined : row.kind === "cron" ? row.timezone : text.frequency(row);
return (
- <TableCell className="max-w-64">
- <span className="flex min-w-0 items-center gap-1.5" title={detail ? `${label} · ${detail}` : label}>
- <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
- <span className="truncate">{label}</span>
- </span>
- </TableCell>
+ <CollectionNameCell
+ icon={<Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />}
+ title={
+ <span title={`${row.issue_identifier} ${row.issue_title}`}>
+ <span className="mr-2 font-normal tabular-nums text-muted-foreground">
+ {row.issue_identifier}
+ </span>
+ {row.issue_title}
+ </span>
+ }
+ description={<span title={detail ? `${trigger} · ${detail}` : trigger}>{trigger}</span>}
+ />
);
}
-function AgentCell({ id, name, label }: { id: string; name: string; label?: string }) {
+function AgentCell({ row }: { row: WorkspaceWakeup }) {
+ const { t } = useT("autopilots");
+ if (!row.agent_id) return <>{t(($) => $.wakeups.no_target)}</>;
return (
- <TableCell className="max-w-44">
- <span className="flex min-w-0 items-center gap-2">
- <ActorAvatar actorType="agent" actorId={id} name={name} size="sm" />
- <span className="truncate">{label ?? name}</span>
+ <>
+ <ActorAvatar actorType="agent" actorId={row.agent_id} name={row.agent_name} size="sm" />
+ <span className="truncate">
+ {row.source === "system"
+ ? t(($) => $.wakeups.assignee_target, { name: row.agent_name })
+ : row.agent_name}
</span>
- </TableCell>
+ </>
);
}
@@ -114,14 +133,14 @@ function SourceCell({ row }: { row: WorkspaceWakeup }) {
const { t } = useT("autopilots");
if (row.source === "system") {
return (
- <span className="rounded-xs bg-muted px-1.5 py-0.5 text-caption text-muted-foreground">
+ <span className="rounded-xs bg-muted px-1.5 text-caption leading-5">
{t(($) => $.wakeups.sources.system)}
</span>
);
}
const agent = row.source === "agent" && row.source_agent_id;
return (
- <span className="flex min-w-0 items-center gap-2">
+ <>
<ActorAvatar
actorType={agent ? "agent" : "member"}
actorId={agent ? (row.source_agent_id ?? "") : ""}
@@ -129,6 +148,34 @@ function SourceCell({ row }: { row: WorkspaceWakeup }) {
size="sm"
/>
<span className="truncate">{agent ? row.source_agent_name : row.created_by_name}</span>
+ </>
+ );
+}
+
+function EndsCell({ row }: { row: WorkspaceWakeup }) {
+ const { t } = useT("autopilots");
+ const { t: ti } = useT("issues");
+ const locale = useLocale();
+ const text = useWakeupText();
+ const viewTZ = useViewingTimezone();
+ if (row.source === "system") return <>{t(($) => $.wakeups.until_issue_ends)}</>;
+ // While enabled, a rule reads as when it ends; otherwise as its state.
+ const ends = row.enabled && !row.issue_closed
+ ? (text.ending(row) ?? (row.mode === "once" ? t(($) => $.wakeups.fires_once) : text.state(row)))
+ : (text.paused(row) ?? text.state(row, row.issue_closed));
+ return (
+ <span
+ className={cn("flex min-w-0 items-center gap-1.5", row.paused_reason && "text-warning")}
+ title={
+ row.next_fire_at && row.enabled
+ ? `${new Date(row.next_fire_at).toLocaleString(locale, { timeZone: viewTZ })} · ${viewTZ}`
+ : undefined
+ }
+ >
+ <span className="truncate">{ends}</span>
+ {row.last_error && (
+ <span className="shrink-0 text-destructive">{ti(($) => $.wakeups.needs_attention)}</span>
+ )}
</span>
);
}
@@ -141,183 +188,89 @@ function RunsCell({ row }: { row: WorkspaceWakeup }) {
const status = row.task?.status;
const active = isActiveWakeupRun(status);
return (
- <TableCell>
- <div className="flex items-center gap-1 tabular-nums">
- <span>{row.runs_7d}</span>
- {row.task && active && (
- <>
- <span aria-hidden="true" className="text-muted-foreground">·</span>
- <span className="text-primary" title={row.active_runs > 1 ? t(($) => $.wakeups.active_runs, { count: row.active_runs }) : undefined}>
- {text.runState(status)}
- </span>
- </>
- )}
- {row.task && (
- <span className={cn(!active && rowIntent)}>
- <TranscriptButton task={row.task} agentName={row.agent_name} title={ti(($) => $.wakeups.last_run)} isLive={active} />
+ <span className="flex min-w-0 items-center gap-1 tabular-nums">
+ <span className="text-foreground">{row.runs_7d}</span>
+ {row.task && active && (
+ <>
+ <span aria-hidden="true">·</span>
+ <span
+ className="truncate text-primary"
+ title={row.active_runs > 1 ? t(($) => $.wakeups.active_runs, { count: row.active_runs }) : undefined}
+ >
+ {text.runState(status)}
</span>
- )}
- </div>
- </TableCell>
- );
-}
-
-function SelectCell({ checked, visible, disabled, label, onChange }: {
- checked: boolean;
- visible: boolean;
- disabled: boolean;
- label: string;
- onChange: () => void;
-}) {
- return (
- <TableCell className="w-8 pl-4 pr-0">
- <div className={cn(rowIntent, visible && "opacity-100")}>
- <Checkbox checked={checked} onCheckedChange={onChange} disabled={disabled} aria-label={label} />
- </div>
- </TableCell>
+ </>
+ )}
+ {row.task && (
+ <span className={cn("shrink-0", !active && rowIntent)}>
+ <TranscriptButton task={row.task} agentName={row.agent_name} title={ti(($) => $.wakeups.last_run)} isLive={active} />
+ </span>
+ )}
+ </span>
);
}
-/** The sub-issue system rule on one parent issue. */
-function SystemWakeupListRow({ row, busy }: { row: WorkspaceWakeup; busy: boolean }) {
- const { t } = useT("autopilots");
- const { t: ti } = useT("issues");
+/** The sub-issue system rule's per-issue switch. */
+function SystemWakeupControl({ row, busy }: { row: WorkspaceWakeup; busy: boolean }) {
+ const { t } = useT("issues");
const wsId = useWorkspaceId();
const update = useUpdateIssueSystemWakeup(wsId, row.issue_id);
- const title =
- row.system_stage != null
- ? ti(($) => $.wakeups.system.title_stage, { stage: row.system_stage })
- : ti(($) => $.wakeups.system.title_all);
return (
- <TableRow className="group/row">
- <TableCell className="w-8 pl-4 pr-0" />
- <IssueCell row={row} />
- <TriggerCell icon={ListChecks} label={title} />
- {row.agent_id ? (
- <AgentCell id={row.agent_id} name={row.agent_name} label={t(($) => $.wakeups.assignee_target, { name: row.agent_name })} />
- ) : (
- <TableCell className="text-muted-foreground">{t(($) => $.wakeups.no_target)}</TableCell>
- )}
- <TableCell>
- <SourceCell row={row} />
- </TableCell>
- <TableCell className="text-muted-foreground">{t(($) => $.wakeups.until_issue_ends)}</TableCell>
- <RunsCell row={row} />
- <TableCell className="w-px py-0 pr-4">
- <div className="flex min-h-11 items-center justify-end px-2">
- <Switch
- checked={row.enabled}
- disabled={busy || update.isPending}
- aria-label={`${row.issue_identifier} · ${ti(($) => $.wakeups.system.toggle)}`}
- onCheckedChange={(enabled) =>
- update.mutate({ rule: "child_done", enabled }, { onError: () => toast.error(ti(($) => $.wakeups.system.save_error)) })
- }
- />
- </div>
- </TableCell>
- </TableRow>
+ <Switch
+ size="sm"
+ checked={row.enabled}
+ disabled={busy || update.isPending}
+ aria-label={`${row.issue_identifier} · ${t(($) => $.wakeups.system.toggle)}`}
+ onCheckedChange={(enabled) =>
+ update.mutate({ rule: "child_done", enabled }, { onError: () => toast.error(t(($) => $.wakeups.system.save_error)) })
+ }
+ />
);
}
-function WakeupListRow({
- row,
- selected,
- selecting,
- onSelect,
- busy,
-}: {
- row: WorkspaceWakeup;
- selected: boolean;
- /** Some row is selected, so every checkbox stays visible. */
- selecting: boolean;
- onSelect: () => void;
- busy: boolean;
-}) {
+function WakeupControls({ row, busy }: { row: WorkspaceWakeup; busy: boolean }) {
const { t } = useT("autopilots");
const { t: ti } = useT("issues");
const wsId = useWorkspaceId();
- const paths = useWorkspacePaths();
- const locale = useLocale();
const text = useWakeupText();
- const viewTZ = useViewingTimezone();
const disable = useDisableIssueWakeup(wsId, row.issue_id);
const enable = useEnableIssueWakeup(wsId, row.issue_id);
- const Icon = conditionIcon(row.condition) ?? (row.kind === "event" ? Bell : Clock3);
- // While enabled, a rule reads as when it ends; otherwise as its state.
- const ends = row.enabled && !row.issue_closed
- ? (text.ending(row) ?? (row.mode === "once" ? t(($) => $.wakeups.fires_once) : text.state(row)))
- : (text.paused(row) ?? text.state(row, row.issue_closed));
return (
- <TableRow className="group/row" data-state={selected ? "selected" : undefined}>
- <SelectCell
- checked={selected}
- visible={selected || selecting}
- onChange={onSelect}
- disabled={busy || !row.can_manage || !row.enabled}
- label={t(($) => $.wakeups.select_row, { issue: row.issue_identifier, agent: row.agent_name })}
+ <span
+ className="flex items-center gap-1"
+ title={
+ !row.can_manage
+ ? t(($) => $.wakeups.read_only)
+ : row.issue_closed
+ ? ti(($) => $.wakeups.closed_hint)
+ : undefined
+ }
+ >
+ <span className={rowIntent}>
+ <WakeupInstructionEditor
+ workspaceId={wsId}
+ issueId={row.issue_id}
+ wakeupId={row.id}
+ disabled={busy || !row.can_manage}
+ triggerStyle="icon"
+ />
+ </span>
+ <WakeupControl
+ size="xs"
+ wakeup={row}
+ task={row.task ?? undefined}
+ closed={row.issue_closed}
+ pending={busy || !row.can_manage || disable.isPending || enable.isPending}
+ onDisable={() =>
+ disable.mutate(row.id, {
+ onError: (err) => toast.error(text.error(err, ti(($) => $.wakeups.disable_error))),
+ })
+ }
+ onEnable={async (input = {}) => {
+ await enable.mutateAsync({ id: row.id, revision: row.revision ?? 0, ...input });
+ }}
/>
- <IssueCell row={row} />
- <TriggerCell icon={Icon} label={text.trigger(row)} detail={row.kind === "cron" ? row.timezone : text.frequency(row)} />
- <AgentCell id={row.agent_id} name={row.agent_name} />
- <TableCell className="max-w-40">
- <SourceCell row={row} />
- </TableCell>
- <TableCell className="max-w-48">
- <span
- className={cn("flex min-w-0 items-center gap-1.5", row.paused_reason && "text-warning")}
- title={
- row.next_fire_at && row.enabled
- ? `${new Date(row.next_fire_at).toLocaleString(locale, { timeZone: viewTZ })} · ${viewTZ}`
- : undefined
- }
- >
- <span className="truncate">{ends}</span>
- {row.last_error && (
- <AppLink href={paths.issueDetail(row.issue_id)} className="shrink-0 text-caption text-destructive">
- {ti(($) => $.wakeups.needs_attention)}
- </AppLink>
- )}
- </span>
- </TableCell>
- <RunsCell row={row} />
- {/* The controls are 44px targets, so this cell sets the row height. */}
- <TableCell className="w-px py-0 pr-4">
- <div
- className="flex items-center justify-end"
- title={
- !row.can_manage
- ? t(($) => $.wakeups.read_only)
- : row.issue_closed
- ? ti(($) => $.wakeups.closed_hint)
- : undefined
- }
- >
- <span className={rowIntent}>
- <WakeupInstructionEditor
- workspaceId={wsId}
- issueId={row.issue_id}
- wakeupId={row.id}
- disabled={busy || !row.can_manage}
- triggerStyle="icon"
- />
- </span>
- <WakeupControl
- wakeup={row}
- task={row.task ?? undefined}
- closed={row.issue_closed}
- pending={busy || !row.can_manage || disable.isPending || enable.isPending}
- onDisable={() =>
- disable.mutate(row.id, {
- onError: (err) => toast.error(text.error(err, ti(($) => $.wakeups.disable_error))),
- })
- }
- onEnable={async (input = {}) => {
- await enable.mutateAsync({ id: row.id, revision: row.revision ?? 0, ...input });
- }}
- />
- </div>
- </TableCell>
- </TableRow>
+ </span>
);
}
@@ -375,85 +328,94 @@ export function WorkspaceWakeupCreate({ open, onOpenChange }: { open: boolean; o
);
}
-function FilterSelect<T extends string>({
+/** One filter dimension of the header's filter menu; the first item is "any". */
+function FilterSub<T extends string>({
label,
value,
items,
- disabled,
onChange,
}: {
label: string;
value: T;
items: { value: T; label: string }[];
- disabled: boolean;
onChange: (value: T) => void;
}) {
+ const current = value !== items[0]?.value ? items.find((item) => item.value === value) : undefined;
return (
- <Select
- items={items}
- value={value}
- disabled={disabled}
- onValueChange={(next) => {
- const item = items.find((candidate) => candidate.value === next);
- if (item) onChange(item.value);
- }}
- >
- <SelectTrigger size="sm" className="max-w-44" aria-label={label}>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {items.map((item) => (
- <SelectItem key={item.value} value={item.value}>
- {item.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{label}</span>
+ {current && (
+ <span className="max-w-32 truncate pl-3 text-caption font-medium text-primary">{current.label}</span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-44 overflow-y-auto">
+ <DropdownMenuRadioGroup
+ value={value}
+ onValueChange={(next) => {
+ const item = items.find((candidate) => candidate.value === next);
+ if (item) onChange(item.value);
+ }}
+ >
+ {items.map((item) => (
+ <DropdownMenuRadioItem key={item.value} value={item.value}>
+ <span className="truncate">{item.label}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
);
}
export function WorkspaceWakeups() {
const { t } = useT("autopilots");
const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
const text = useWakeupText();
- const [filters, setFilters] = useState<WorkspaceWakeupFilters>({
+ const [filters, setFilters] = useState<WakeupFilters>({
scope: "active",
kind: "all",
source: "",
search: "",
agent_id: "",
- offset: 0,
limit: 50,
});
- const [search, setSearch] = useState("");
+ const [createOpen, setCreateOpen] = useState(false);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [confirmation, setConfirmation] = useState<WorkspaceWakeup[]>([]);
const [batchResult, setBatchResult] = useState<{
failed: string[];
succeeded: number;
} | null>(null);
- const query = useQuery(workspaceWakeupsOptions(wsId, filters));
+ const query = useInfiniteQuery(workspaceWakeupsInfiniteOptions(wsId, filters));
+ const page = query.data?.pages[0];
// The newest rule the platform paused, for the banner above the list.
const pausedQuery = useQuery({
- ...workspaceWakeupsOptions(wsId, { scope: "paused", kind: "all", source: "", search: "", agent_id: "", offset: 0, limit: 1 }),
- enabled: !!wsId && (query.data?.counts.paused ?? 0) > 0,
+ ...wakeupCountsOptions(wsId),
+ enabled: !!wsId && (page?.counts.paused ?? 0) > 0,
});
const batch = useDisableWorkspaceWakeups(wsId);
- const rows = query.data?.items ?? [];
- const selectable = rows.filter((row) => row.enabled && row.can_manage && row.source !== "system");
- const picked = selectable.filter((row) => selected.has(row.id));
- const change = useCallback((patch: Partial<WorkspaceWakeupFilters>) => {
- setFilters((prev) => ({ ...prev, offset: 0, ...patch }));
+ // Offset pages can overlap when rules change between fetches.
+ const rows = useMemo(() => {
+ const seen = new Set<string>();
+ return (query.data?.pages ?? []).flatMap((p) =>
+ p.items.filter((row) => {
+ const id = rowId(row);
+ if (seen.has(id)) return false;
+ seen.add(id);
+ return true;
+ }),
+ );
+ }, [query.data]);
+ const isSelectable = (row: WorkspaceWakeup) =>
+ row.enabled && row.can_manage && row.source !== "system";
+ const picked = rows.filter((row) => isSelectable(row) && selected.has(row.id));
+ const change = useCallback((patch: Partial<WakeupFilters>) => {
+ setFilters((prev) => ({ ...prev, ...patch }));
setSelected(new Set());
setBatchResult(null);
}, []);
- // Search as you type, once typing pauses.
- useEffect(() => {
- const next = search.trim();
- if (next === filters.search) return;
- const timer = setTimeout(() => change({ search: next }), 300);
- return () => clearTimeout(timer);
- }, [search, filters.search, change]);
const kinds = [
{ value: "all" as const, label: t(($) => $.wakeups.all_triggers) },
{ value: "event" as const, label: t(($) => $.wakeups.event) },
@@ -462,7 +424,7 @@ export function WorkspaceWakeups() {
];
const agents = [
{ value: "", label: t(($) => $.wakeups.all_agents) },
- ...(query.data?.agents ?? []).map((a) => ({ value: a.id, label: a.name })),
+ ...(page?.agents ?? []).map((a) => ({ value: a.id, label: a.name })),
];
const sources = [
{ value: "" as const, label: t(($) => $.wakeups.sources.all) },
@@ -470,9 +432,53 @@ export function WorkspaceWakeups() {
{ value: "agent" as const, label: t(($) => $.wakeups.sources.agent) },
{ value: "system" as const, label: t(($) => $.wakeups.sources.system) },
];
- const pausedCount = query.data?.counts.paused ?? 0;
+ const pausedCount = page?.counts.paused ?? 0;
const latestPaused = pausedQuery.data?.items[0];
- const filtered = filters.scope !== "all" || !!filters.search || filters.kind !== "all" || !!filters.source || !!filters.agent_id;
+ const filtered = filters.scope !== "all" || filters.kind !== "all" || !!filters.source || !!filters.agent_id;
+ const filterCount = [filters.kind !== "all", !!filters.source, !!filters.agent_id].filter(Boolean).length;
+ const busy = batch.isPending;
+ const columns: CollectionColumn<WorkspaceWakeup>[] = [
+ { key: "issue", header: t(($) => $.wakeups.issue), cell: (row) => <IssueCell row={row} /> },
+ {
+ key: "agent",
+ header: t(($) => $.wakeups.target_agent),
+ width: 128,
+ cell: (row) => <AgentCell row={row} />,
+ },
+ {
+ key: "source",
+ header: t(($) => $.wakeups.source),
+ width: 112,
+ cell: (row) => <SourceCell row={row} />,
+ },
+ {
+ key: "ends",
+ header: t(($) => $.wakeups.ends),
+ width: 128,
+ cell: (row) => <EndsCell row={row} />,
+ },
+ {
+ key: "runs",
+ header: t(($) => $.wakeups.runs_7d),
+ width: 88,
+ interactive: true,
+ cell: (row) => <RunsCell row={row} />,
+ },
+ {
+ key: "enabled",
+ header: t(($) => $.wakeups.enabled),
+ width: 96,
+ align: "end",
+ core: true,
+ interactive: true,
+ cell: (row) =>
+ row.source === "system" ? (
+ <SystemWakeupControl row={row} busy={busy} />
+ ) : (
+ <WakeupControls row={row} busy={busy} />
+ ),
+ },
+ ];
let body: ReactNode;
if (query.isError) {
body = (
@@ -491,7 +497,7 @@ export function WorkspaceWakeups() {
} else if (query.isPending) {
body = <CollectionPageState icon={Clock3} title={t(($) => $.wakeups.loading)} />;
} else if (!rows.length) {
- const hasAny = (query.data?.counts.all ?? 0) > 0;
+ const hasAny = (page?.counts.all ?? 0) > 0;
body = (
<CollectionPageState
icon={Bell}
@@ -501,10 +507,7 @@ export function WorkspaceWakeups() {
<Button
variant="outline"
size="sm"
- onClick={() => {
- setSearch("");
- change({ scope: "all", kind: "all", source: "", search: "", agent_id: "" });
- }}
+ onClick={() => change({ scope: "all", kind: "all", source: "", agent_id: "" })}
>
{t(($) => $.wakeups.clear_filters)}
</Button>
@@ -513,63 +516,72 @@ export function WorkspaceWakeups() {
/>
);
} else {
- const selecting = picked.length > 0;
body = (
- <div className="min-h-0 flex-1 overflow-auto">
- <Table className="min-w-[900px]">
- <TableHeader>
- <TableRow className="group/row">
- <TableHead className="w-8 pl-4 pr-0">
- <div className={cn(rowIntent, selecting && "opacity-100")}>
- <Checkbox
- disabled={!selectable.length || batch.isPending}
- checked={picked.length > 0 && picked.length === selectable.length}
- indeterminate={picked.length > 0 && picked.length < selectable.length}
- onCheckedChange={() =>
- setSelected(picked.length === selectable.length ? new Set() : new Set(selectable.map((row) => row.id)))
- }
- aria-label={t(($) => $.wakeups.select_page)}
- />
- </div>
- </TableHead>
- <TableHead>{t(($) => $.wakeups.issue)}</TableHead>
- <TableHead>{t(($) => $.wakeups.trigger)}</TableHead>
- <TableHead>{t(($) => $.wakeups.target_agent)}</TableHead>
- <TableHead>{t(($) => $.wakeups.source)}</TableHead>
- <TableHead>{t(($) => $.wakeups.ends)}</TableHead>
- <TableHead>{t(($) => $.wakeups.runs_7d)}</TableHead>
- <TableHead className="w-px pr-6 text-right">{t(($) => $.wakeups.enabled)}</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {rows.map((row) =>
- row.source === "system" ? (
- <SystemWakeupListRow key={`system-${row.id}`} row={row} busy={batch.isPending} />
- ) : (
- <WakeupListRow
- key={row.id}
- row={row}
- busy={batch.isPending}
- selected={selected.has(row.id)}
- selecting={selecting}
- onSelect={() =>
- setSelected((prev) => {
- const next = new Set(prev);
- if (next.has(row.id)) next.delete(row.id);
- else next.add(row.id);
- return next;
- })
- }
- />
- ),
- )}
- </TableBody>
- </Table>
- </div>
+ <CollectionList
+ label={t(($) => $.wakeups.scopes[filters.scope])}
+ columns={columns}
+ rows={rows}
+ getRowId={rowId}
+ getRowHref={(row) => paths.issueDetail(row.issue_id)}
+ getRowTitle={(row) => `${row.issue_identifier} ${row.issue_title}`}
+ selection={{
+ selectedIds: selected,
+ onChange: (next) => {
+ if (!batch.isPending) setSelected(new Set(next));
+ },
+ isSelectable,
+ getLabel: (row) =>
+ t(($) => $.wakeups.select_row, { issue: row.issue_identifier, agent: row.agent_name }),
+ allLabel: t(($) => $.wakeups.select_page),
+ }}
+ hasMore={query.hasNextPage}
+ loadingMore={query.isFetchingNextPage}
+ onLoadMore={() => void query.fetchNextPage()}
+ />
);
}
return (
<>
+ <CollectionPageHeader
+ icon={AlarmClock}
+ title={t(($) => $.wakeups.scopes[filters.scope])}
+ menu={
+ <CollectionScopeItems
+ value={filters.scope}
+ options={SCOPES.map((scope) => ({
+ value: scope,
+ label: t(($) => $.wakeups.scopes[scope]),
+ count: page?.counts[scope],
+ }))}
+ onChange={(scope) => {
+ if (!batch.isPending) change({ scope });
+ }}
+ />
+ }
+ tools={
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={batch.isPending}
+ render={<CollectionFilterButton count={filterCount} />}
+ />
+ <DropdownMenuContent align="start" className="w-auto min-w-44">
+ <FilterSub label={t(($) => $.wakeups.source)} value={filters.source} items={sources} onChange={(source) => change({ source })} />
+ <FilterSub label={t(($) => $.wakeups.trigger)} value={filters.kind} items={kinds} onChange={(kind) => change({ kind })} />
+ <FilterSub label={t(($) => $.wakeups.target_agent)} value={filters.agent_id} items={agents} onChange={(agent_id) => change({ agent_id })} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {filterCount > 0 && (
+ <CollectionResetButton
+ onClick={() => change({ kind: "all", source: "", agent_id: "" })}
+ />
+ )}
+ </>
+ }
+ actions={
+ <CollectionCreateButton label={t(($) => $.wakeups.create)} onClick={() => setCreateOpen(true)} />
+ }
+ />
{pausedCount > 0 && latestPaused && filters.scope !== "paused" && (
<div
role="status"
@@ -589,49 +601,6 @@ export function WorkspaceWakeups() {
</Button>
</div>
)}
- {/* One row: scope on the left, the narrowing filters and search on the
- right. It only wraps on narrow windows. */}
- <div className="flex shrink-0 flex-wrap items-center gap-2 px-4 pb-2 pt-3">
- <div role="group" aria-label={t(($) => $.wakeups.scope)} className="flex shrink-0 items-center gap-0.5 rounded-lg bg-muted p-0.5">
- {(["active", "paused", "disabled", "ended", "all"] as const).map((scope) => {
- const active = filters.scope === scope;
- return (
- <button
- key={scope}
- type="button"
- aria-pressed={active}
- disabled={batch.isPending}
- onClick={() => change({ scope })}
- className={cn(
- "inline-flex h-7 items-center gap-1 rounded-md px-2.5 text-caption text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50",
- active && "bg-surface font-medium text-foreground shadow-[var(--surface-shadow)]",
- )}
- >
- {t(($) => $.wakeups.scopes[scope])}
- <span className="tabular-nums text-muted-foreground">{query.data?.counts[scope] ?? "—"}</span>
- </button>
- );
- })}
- </div>
- <div className="ml-auto flex items-center gap-2">
- <FilterSelect label={t(($) => $.wakeups.source)} value={filters.source} items={sources} disabled={batch.isPending} onChange={(source) => change({ source })} />
- <FilterSelect label={t(($) => $.wakeups.trigger)} value={filters.kind} items={kinds} disabled={batch.isPending} onChange={(kind) => change({ kind })} />
- <FilterSelect label={t(($) => $.wakeups.target_agent)} value={filters.agent_id} items={agents} disabled={batch.isPending} onChange={(agent_id) => change({ agent_id })} />
- <div className="relative">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />
- <Input
- type="search"
- className="h-8 w-52 pl-8"
- value={search}
- maxLength={256}
- disabled={batch.isPending}
- onChange={(event) => setSearch(event.target.value)}
- aria-label={t(($) => $.wakeups.search)}
- placeholder={t(($) => $.wakeups.search)}
- />
- </div>
- </div>
- </div>
{batchResult && (
<p
role="status"
@@ -644,43 +613,13 @@ export function WorkspaceWakeups() {
})}
</p>
)}
- {body}
- <div className="mt-auto flex shrink-0 flex-wrap items-center gap-2 border-t px-4 py-2 text-caption text-muted-foreground">
- {picked.length > 0 && (
- <>
- <span>{t(($) => $.wakeups.selected, { count: picked.length })}</span>
- <Button size="sm" variant="outline" disabled={batch.isPending} onClick={() => setConfirmation(picked)}>
- {t(($) => $.wakeups.disable_selected)}
- </Button>
- <Button size="sm" variant="ghost" disabled={batch.isPending} onClick={() => setSelected(new Set())}>
- {t(($) => $.wakeups.clear)}
- </Button>
- </>
- )}
- <span className="ml-auto tabular-nums">
- {query.data && !query.isError
- ? t(($) => $.wakeups.results, {
- count: query.data?.total ?? 0,
- page: Math.floor(filters.offset / filters.limit) + 1,
- })
- : "—"}
- </span>
- <Button
- size="sm"
- variant="ghost"
- disabled={batch.isPending || !filters.offset}
- onClick={() => change({ offset: Math.max(0, filters.offset - filters.limit) })}
- >
- {t(($) => $.wakeups.previous)}
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={batch.isPending || !query.data || filters.offset + filters.limit >= query.data.total}
- onClick={() => change({ offset: filters.offset + filters.limit })}
- >
- {t(($) => $.wakeups.next_page)}
- </Button>
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ {body}
+ <CollectionBatchBar count={picked.length} onClear={() => setSelected(new Set())}>
+ <Button size="sm" variant="ghost" disabled={busy} onClick={() => setConfirmation(picked)}>
+ {t(($) => $.wakeups.disable_selected)}
+ </Button>
+ </CollectionBatchBar>
</div>
<Dialog
open={confirmation.length > 0}
@@ -711,6 +650,7 @@ export function WorkspaceWakeups() {
</DialogFooter>
</DialogContent>
</Dialog>
+ <WorkspaceWakeupCreate open={createOpen} onOpenChange={setCreateOpen} />
</>
);
}
diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsx
index 568f38ef82..d2ac316cc8 100644
--- a/packages/views/chat/chat-page.test.tsx
+++ b/packages/views/chat/chat-page.test.tsx
@@ -59,18 +59,6 @@ vi.mock("./components/no-agent-banner", () => ({
vi.mock("./components/archived-agent-banner", () => ({
ArchivedAgentBanner: () => null,
}));
-vi.mock("react-resizable-panels", () => ({
- useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
-}));
-vi.mock("@multica/ui/components/ui/resizable", () => ({
- ResizablePanelGroup: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- ResizablePanel: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- ResizableHandle: () => null,
-}));
// Same width-driven layout mock the inbox page tests use: the deep-link tests
// all want the desktop two-pane layout, the breakpoint tests at the bottom set
// their own width.
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index a2ca883ba8..da09d1a563 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -1,15 +1,10 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
-import { useDefaultLayout } from "react-resizable-panels";
import { ArrowLeft, MessageSquare } from "@multica/ui/icons";
import { toast } from "sonner";
import { Button } from "@multica/ui/components/ui/button";
-import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
-} from "@multica/ui/components/ui/resizable";
+import { IconButton } from "@multica/ui/components/common/icon-button";
import { useIsCompact } from "@multica/ui/hooks/use-mobile";
import { useRequiredWorkspaceSlug, useWorkspacePaths } from "@multica/core/paths";
import { getCurrentSlug } from "@multica/core/platform";
@@ -20,7 +15,10 @@ import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-acti
import { useQuickActionsFailureToast } from "./components/use-quick-actions-failure-toast";
import { useQuery } from "@tanstack/react-query";
import type { Agent, ChatSession } from "@multica/core/types";
-import { PageHeader } from "../layout/page-header";
+import { CollapsedNavTrigger, PageHeader } from "../layout/page-header";
+import { PanelHeader } from "../layout/panel-nav";
+import { useListColumnCollapsed } from "../layout/app-shell-context";
+import { ListColumn } from "../layout/list-column";
import { useNavigation } from "../navigation";
import { useT } from "../i18n";
import { ChatMessageList, ChatMessageSkeleton } from "./components/chat-message-list";
@@ -129,9 +127,7 @@ export function ChatPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- reconcile store/route changes, not URL updates
}, [isCurrentChatRoute, workspaceSlug, c.activeSessionId]);
- const { defaultLayout, onLayoutChanged } = useDefaultLayout({
- id: "multica_chat_layout",
- });
+ const listCollapsed = useListColumnCollapsed();
// `?agent=` intent bookkeeping. The ref holds the param value already
// consumed (or superseded) so the effect below fires at most once per deep
@@ -253,10 +249,9 @@ export function ChatPage() {
);
const listHeader = (
- <PageHeader>
- <h1 className="flex-1 text-body font-semibold">{t(($) => $.page.title)}</h1>
+ <PanelHeader as="h1" title={t(($) => $.page.title)} leading={<CollapsedNavTrigger />}>
{newChatButton}
- </PageHeader>
+ </PanelHeader>
);
const listBody = (
@@ -271,6 +266,12 @@ export function ChatPage() {
</div>
);
+ const compactConversation = isCompact && (!!c.activeSessionId || composingNew);
+ const backToList = () => {
+ c.setActiveSession(null);
+ setComposingNew(false);
+ };
+
// The conversation pane: message list / skeleton / empty above a persistent
// banner + input. Identical composition to the floating window's body, so a
// brand-new chat (no active session) shows the agent-aware empty state + input.
@@ -282,6 +283,20 @@ export function ChatPage() {
<div className="flex flex-1 flex-col min-h-0 @container">
{c.currentSession && (
<ChatSessionHeader
+ leading={
+ compactConversation ? (
+ <IconButton
+ label={t(($) => $.page.title)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={backToList}
+ >
+ <ArrowLeft />
+ </IconButton>
+ ) : listCollapsed ? (
+ <CollapsedNavTrigger />
+ ) : undefined
+ }
session={c.currentSession}
agent={c.activeAgent}
onArchive={handleArchive}
@@ -385,23 +400,24 @@ export function ChatPage() {
// -- Compact: list / conversation toggle -----------------------------------
if (isCompact) {
- if (c.activeSessionId || composingNew) {
+ if (compactConversation) {
+ // An open session carries the way back in its own header; a new chat
+ // has no session header yet, so it gets a bar of its own.
return (
<div className="flex flex-1 flex-col min-h-0">
- <div className="flex h-12 shrink-0 items-center border-b px-2">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- c.setActiveSession(null);
- setComposingNew(false);
- }}
- className="gap-1.5 text-muted-foreground"
- >
- <ArrowLeft className="h-4 w-4" />
- {t(($) => $.page.title)}
- </Button>
- </div>
+ {!c.currentSession && (
+ <div className="flex h-12 shrink-0 items-center border-b px-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={backToList}
+ className="gap-1.5 text-muted-foreground"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ {t(($) => $.page.title)}
+ </Button>
+ </div>
+ )}
{conversation}
</div>
);
@@ -414,43 +430,28 @@ export function ChatPage() {
);
}
- // -- Desktop: resizable two-panel. The conversation pane appears only once
+ // -- Desktop: list column + conversation. The conversation pane appears only once
// there is a chat target — an open thread or a new chat whose agent was just
// picked via ⊕. With nothing selected there is no agent, so we show a neutral
// prompt instead of an orphaned compose box. -------------------------------
const hasTarget = !!c.activeSessionId || composingNew;
return (
- <ResizablePanelGroup
- orientation="horizontal"
- className="flex-1 min-h-0"
- defaultLayout={defaultLayout}
- onLayoutChanged={onLayoutChanged}
- >
- <ResizablePanel
- id="list"
- defaultSize={260}
- minSize={240}
- maxSize={480}
- groupResizeBehavior="preserve-pixel-size"
- >
- <div className="flex flex-col border-r h-full">
- {listHeader}
- <div className="flex-1 min-h-0 overflow-y-auto">{listBody}</div>
- </div>
- </ResizablePanel>
- <ResizableHandle />
- <ResizablePanel id="detail" minSize="40%">
- <div className="flex flex-col min-h-0 h-full">
- {hasTarget ? (
- conversation
- ) : (
- <div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
- <MessageSquare className="h-10 w-10 text-faint-foreground" />
- <p className="text-body">{t(($) => $.page.select_prompt)}</p>
- </div>
- )}
- </div>
- </ResizablePanel>
- </ResizablePanelGroup>
+ <div className="flex min-h-0 flex-1">
+ <ListColumn collapsed={listCollapsed}>
+ {listHeader}
+ <div className="flex-1 min-h-0 overflow-y-auto">{listBody}</div>
+ </ListColumn>
+ <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col">
+ {listCollapsed && !c.currentSession && <PageHeader>{newChatButton}</PageHeader>}
+ {hasTarget ? (
+ conversation
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-muted-foreground">
+ <MessageSquare className="h-10 w-10 text-faint-foreground" />
+ <p className="text-body">{t(($) => $.page.select_prompt)}</p>
+ </div>
+ )}
+ </div>
+ </div>
);
}
diff --git a/packages/views/chat/components/chat-session-header.test.tsx b/packages/views/chat/components/chat-session-header.test.tsx
index 4658de2b30..bc74881411 100644
--- a/packages/views/chat/components/chat-session-header.test.tsx
+++ b/packages/views/chat/components/chat-session-header.test.tsx
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
-import type { ChatSession } from "@multica/core/types";
+import type { Agent, ChatSession } from "@multica/core/types";
import enChat from "../../locales/en/chat.json";
const updateMutate = vi.hoisted(() => vi.fn());
@@ -26,7 +26,9 @@ vi.mock("../../common/actor-avatar", () => ({
}));
vi.mock("../../navigation", () => ({
- AppLink: ({ children }: { children: React.ReactNode }) => <a>{children}</a>,
+ AppLink: ({ children, href }: { children: React.ReactNode; href: string }) => (
+ <a href={href}>{children}</a>
+ ),
}));
import { ChatSessionHeader } from "./chat-session-header";
@@ -50,6 +52,38 @@ const session: ChatSession = {
updated_at: new Date(0).toISOString(),
};
+describe("ChatSessionHeader breadcrumb", () => {
+ it("leads with the agent as a link to its page, then the chat title", () => {
+ const agent = { id: "agent-1", name: "Lambda" } as Agent;
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatSessionHeader session={session} agent={agent} />
+ </I18nProvider>,
+ );
+
+ const header = within(screen.getByRole("banner"));
+ const agentLink = header.getByRole("link", { name: "Lambda" });
+ expect(agentLink).toHaveAttribute("href", "/agents/agent-1");
+ const title = header.getByRole("button", { name: "Original title" });
+ expect(agentLink).not.toContainElement(title);
+ expect(
+ agentLink.compareDocumentPosition(title) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it("shows only the title when the chat's agent is unavailable", () => {
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatSessionHeader session={session} agent={null} />
+ </I18nProvider>,
+ );
+
+ const header = within(screen.getByRole("banner"));
+ expect(header.queryByRole("link")).not.toBeInTheDocument();
+ expect(header.getByRole("button", { name: "Original title" })).toBeInTheDocument();
+ });
+});
+
function startRename(): HTMLInputElement {
render(
<>
diff --git a/packages/views/chat/components/chat-session-header.tsx b/packages/views/chat/components/chat-session-header.tsx
index ed85b159c0..10afcd3585 100644
--- a/packages/views/chat/components/chat-session-header.tsx
+++ b/packages/views/chat/components/chat-session-header.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useEffect, useRef, useState } from "react";
-import { Archive, ArchiveRestore, MoreHorizontal, Pencil, Trash2, UserRound } from "@multica/ui/icons";
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { Archive, ArchiveRestore, MoreHorizontal, Pencil, Trash2 } from "@multica/ui/icons";
import { IconButton } from "@multica/ui/components/common/icon-button";
import {
DropdownMenu,
@@ -30,20 +30,20 @@ import { useChatStore } from "@multica/core/chat";
import type { Agent, ChatSession } from "@multica/core/types";
import { isImeComposing } from "@multica/core/utils";
import { ActorAvatar } from "../../common/actor-avatar";
-import { AppLink } from "../../navigation";
+import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
import { useT } from "../../i18n";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
/**
- * Per-session header for the conversation pane: agent avatar + editable chat
- * title + agent subtitle, with a ⋯ menu (rename / view agent profile / delete).
- * The avatar's hover card is the lightweight "view profile" affordance; the
- * menu item navigates to the full agent page.
+ * Per-session header for the conversation pane, read as a breadcrumb: the
+ * agent the chat belongs to (a link to its page), then the chat's own title,
+ * which renames in place. The ⋯ menu holds the session actions.
*/
export function ChatSessionHeader({
session,
agent,
onArchive,
+ leading,
}: {
session: ChatSession;
agent: Agent | null;
@@ -51,6 +51,11 @@ export function ChatSessionHeader({
// next chat on desktop, back to the list on mobile), so the parent owns it —
// see ChatPage.handleArchive. Falls back to a plain status flip if unwired.
onArchive?: (session: ChatSession) => void;
+ /**
+ * Far-left control: the nav toggle while the list is collapsed, or the way
+ * back to the list at compact widths. Nothing renders there without one.
+ */
+ leading?: ReactNode;
}) {
const { t } = useT("chat");
const { t: tCommon } = useT("common");
@@ -126,136 +131,142 @@ export function ChatSessionHeader({
: setArchived.mutate({ sessionId: session.id, archived: true });
const doUnarchive = () => setArchived.mutate({ sessionId: session.id, archived: false });
- return (
- <div className="flex h-12 shrink-0 items-center gap-3 border-b px-4">
- {agent ? (
- <ActorAvatar actorType="agent" actorId={agent.id} size="lg" enableHoverCard showStatusDot />
- ) : (
- <span className="size-[30px] shrink-0" />
- )}
-
- <div className="min-w-0 flex-1">
- {editing ? (
- <input
- ref={inputRef}
- value={draft}
- maxLength={200}
- aria-label={t(($) => $.header.rename)}
- onChange={(e) => setDraft(e.target.value)}
- onCompositionStart={() => {
- isComposingRef.current = true;
- }}
- onCompositionEnd={(e) => {
+ const leaf = editing ? (
+ <input
+ ref={inputRef}
+ value={draft}
+ maxLength={200}
+ aria-label={t(($) => $.header.rename)}
+ onChange={(e) => setDraft(e.target.value)}
+ onCompositionStart={() => {
+ isComposingRef.current = true;
+ }}
+ onCompositionEnd={(e) => {
+ isComposingRef.current = false;
+ if (!commitAfterCompositionRef.current) return;
+ commitRename(e.currentTarget.value);
+ }}
+ onBlur={(e) => {
+ if (isComposingRef.current) {
+ commitAfterCompositionRef.current = true;
+ const input = e.currentTarget;
+ // Let a compositionend queued by the same focus change win.
+ // If it never arrives, commit on the next task instead of
+ // leaving an unfocused editor open indefinitely.
+ clearPendingBlurCommit();
+ blurCommitTimeoutRef.current = setTimeout(() => {
+ if (!commitAfterCompositionRef.current) return;
+ // Without compositionend, the current DOM value is not
+ // known to be final. Close without persisting a partial
+ // composition instead of recreating the original bug.
+ if (isComposingRef.current) {
+ clearPendingBlurCommit();
isComposingRef.current = false;
- if (!commitAfterCompositionRef.current) return;
- commitRename(e.currentTarget.value);
- }}
- onBlur={(e) => {
- if (isComposingRef.current) {
- commitAfterCompositionRef.current = true;
- const input = e.currentTarget;
- // Let a compositionend queued by the same focus change win.
- // If it never arrives, commit on the next task instead of
- // leaving an unfocused editor open indefinitely.
- clearPendingBlurCommit();
- blurCommitTimeoutRef.current = setTimeout(() => {
- if (!commitAfterCompositionRef.current) return;
- // Without compositionend, the current DOM value is not
- // known to be final. Close without persisting a partial
- // composition instead of recreating the original bug.
- if (isComposingRef.current) {
- clearPendingBlurCommit();
- isComposingRef.current = false;
- commitAfterCompositionRef.current = false;
- setEditing(false);
- return;
- }
- commitRename(input.value);
- }, 0);
- return;
- }
- commitRename(e.currentTarget.value);
- }}
- onKeyDown={(e) => {
- if (isImeComposing(e)) return;
- if (e.key === "Enter") {
- e.preventDefault();
- commitRename();
- } else if (e.key === "Escape") {
- e.preventDefault();
- clearPendingBlurCommit();
- isComposingRef.current = false;
- commitAfterCompositionRef.current = false;
- setEditing(false);
- }
- }}
- className="w-full rounded-sm bg-background px-1 py-0.5 text-body font-semibold outline-none ring-1 ring-border focus-visible:ring-brand"
- />
- ) : (
- <TooltipHint label={t(($) => $.header.rename)}>
- <button
- type="button"
- onClick={startRename}
- className="block max-w-full truncate text-left text-body font-semibold text-foreground outline-none hover:text-foreground/80 focus-visible:text-foreground/80"
- >
- {title}
- </button>
- </TooltipHint>
- )}
- {agent && (
- <div className="truncate text-caption text-muted-foreground">
- {agent.name}
- {agent.description ? ` · ${agent.description}` : ""}
- </div>
- )}
- </div>
+ commitAfterCompositionRef.current = false;
+ setEditing(false);
+ return;
+ }
+ commitRename(input.value);
+ }, 0);
+ return;
+ }
+ commitRename(e.currentTarget.value);
+ }}
+ onKeyDown={(e) => {
+ if (isImeComposing(e)) return;
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commitRename();
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ clearPendingBlurCommit();
+ isComposingRef.current = false;
+ commitAfterCompositionRef.current = false;
+ setEditing(false);
+ }
+ }}
+ className="min-w-0 max-w-96 flex-1 rounded-sm bg-background px-1 py-0.5 text-body font-medium outline-none ring-1 ring-border focus-visible:ring-brand"
+ />
+ ) : (
+ <TooltipHint label={t(($) => $.header.rename)}>
+ <button
+ type="button"
+ onClick={startRename}
+ className="min-w-0 truncate text-left text-body font-medium text-foreground outline-none hover:text-foreground/80 focus-visible:text-foreground/80"
+ >
+ {title}
+ </button>
+ </TooltipHint>
+ );
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <IconButton
- label={tCommon(($) => $.more_actions)}
- tooltipSide="bottom"
- className="text-muted-foreground"
- />
- }
- >
- <MoreHorizontal className="h-4 w-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuItem onClick={startRename}>
- <Pencil className="h-4 w-4" />
- {t(($) => $.header.rename)}
- </DropdownMenuItem>
- {agent && (
- <DropdownMenuItem
- render={<AppLink href={wsPaths.agentDetail(agent.id)} />}
+ return (
+ <>
+ <BreadcrumbHeader
+ leading={leading ?? false}
+ segments={
+ agent
+ ? [
+ {
+ href: wsPaths.agentDetail(agent.id),
+ label: (
+ <>
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size="sm"
+ profileLink={false}
+ showStatusDot
+ />
+ <span className="truncate">{agent.name}</span>
+ </>
+ ),
+ className: "flex min-w-0 max-w-48 shrink items-center gap-1.5",
+ },
+ ]
+ : []
+ }
+ leaf={leaf}
+ actions={
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={tCommon(($) => $.more_actions)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ />
+ }
>
- <UserRound className="h-4 w-4" />
- {t(($) => $.header.view_profile)}
- </DropdownMenuItem>
- )}
- <DropdownMenuSeparator />
- {isArchived ? (
- <>
- <DropdownMenuItem onClick={doUnarchive}>
- <ArchiveRestore className="h-4 w-4" />
- {t(($) => $.header.unarchive)}
- </DropdownMenuItem>
- {/* Hard delete is offered only once a chat is archived. */}
- <DropdownMenuItem variant="destructive" onClick={() => setConfirmDelete(true)}>
- <Trash2 className="h-4 w-4" />
- {t(($) => $.header.delete)}
+ <MoreHorizontal className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto">
+ <DropdownMenuItem onClick={startRename}>
+ <Pencil className="h-4 w-4" />
+ {t(($) => $.header.rename)}
</DropdownMenuItem>
- </>
- ) : (
- <DropdownMenuItem onClick={doArchive}>
- <Archive className="h-4 w-4" />
- {t(($) => $.header.archive)}
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ <DropdownMenuSeparator />
+ {isArchived ? (
+ <>
+ <DropdownMenuItem onClick={doUnarchive}>
+ <ArchiveRestore className="h-4 w-4" />
+ {t(($) => $.header.unarchive)}
+ </DropdownMenuItem>
+ {/* Hard delete is offered only once a chat is archived. */}
+ <DropdownMenuItem variant="destructive" onClick={() => setConfirmDelete(true)}>
+ <Trash2 className="h-4 w-4" />
+ {t(($) => $.header.delete)}
+ </DropdownMenuItem>
+ </>
+ ) : (
+ <DropdownMenuItem onClick={doArchive}>
+ <Archive className="h-4 w-4" />
+ {t(($) => $.header.archive)}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ }
+ />
<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
<AlertDialogContent>
@@ -274,6 +285,6 @@ export function ChatSessionHeader({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- </div>
+ </>
);
}
diff --git a/packages/views/chat/components/use-chat-resize.test.tsx b/packages/views/chat/components/use-chat-resize.test.tsx
new file mode 100644
index 0000000000..1fb129f6a8
--- /dev/null
+++ b/packages/views/chat/components/use-chat-resize.test.tsx
@@ -0,0 +1,94 @@
+import { useRef } from "react";
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createChatStore, registerChatStore, useChatStore } from "@multica/core/chat";
+import { useChatResize } from "./use-chat-resize";
+
+const memory = new Map<string, string>();
+registerChatStore(
+ createChatStore({
+ storage: {
+ getItem: (k) => memory.get(k) ?? null,
+ setItem: (k, v) => void memory.set(k, v),
+ removeItem: (k) => void memory.delete(k),
+ },
+ }),
+);
+
+const observers: Array<() => void> = [];
+const parentSize = { width: 1200, height: 900 };
+let renders = 0;
+
+function Harness() {
+ const ref = useRef<HTMLDivElement>(null);
+ const { renderWidth } = useChatResize(ref);
+ renders += 1;
+ return (
+ <div data-testid="parent">
+ <div ref={ref} data-testid="window" data-width={renderWidth} />
+ </div>
+ );
+}
+
+function resizeParent(width: number) {
+ parentSize.width = width;
+ act(() => {
+ for (const fire of observers) fire();
+ });
+}
+
+beforeEach(() => {
+ observers.length = 0;
+ parentSize.width = 1200;
+ parentSize.height = 900;
+ renders = 0;
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ constructor(callback: () => void) {
+ observers.push(callback);
+ }
+ observe() {}
+ disconnect() {}
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => parentSize.width);
+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockImplementation(() => parentSize.height);
+ useChatStore.setState({ chatWidth: 380, chatHeight: 600, isExpanded: false });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("useChatResize", () => {
+ it("does not re-render while the container resizes around a window that fits", () => {
+ render(<Harness />);
+ const settled = renders;
+
+ resizeParent(1000);
+ resizeParent(800);
+
+ expect(renders).toBe(settled);
+ expect(screen.getByTestId("window")).toHaveAttribute("data-width", "380");
+ });
+
+ it("re-renders once the container clamps the window", () => {
+ render(<Harness />);
+
+ resizeParent(400);
+
+ expect(screen.getByTestId("window")).toHaveAttribute("data-width", "360");
+ });
+
+ it("follows the container while expanded", () => {
+ useChatStore.setState({ isExpanded: true });
+ render(<Harness />);
+ expect(screen.getByTestId("window")).toHaveAttribute("data-width", "1080");
+
+ resizeParent(1000);
+
+ expect(screen.getByTestId("window")).toHaveAttribute("data-width", "900");
+ });
+});
diff --git a/packages/views/chat/components/use-chat-resize.ts b/packages/views/chat/components/use-chat-resize.ts
index 01a53ddeb7..c2ae02b16c 100644
--- a/packages/views/chat/components/use-chat-resize.ts
+++ b/packages/views/chat/components/use-chat-resize.ts
@@ -13,6 +13,17 @@ function clamp(v: number, min: number, max: number) {
return Math.max(min, Math.min(max, v));
}
+type Bounds = { maxW: number; maxH: number };
+
+function renderedSize(
+ { maxW, maxH }: Bounds,
+ { chatWidth, chatHeight, isExpanded }: { chatWidth: number; chatHeight: number; isExpanded: boolean },
+) {
+ const w = isExpanded ? maxW : clamp(chatWidth, CHAT_MIN_W, maxW);
+ const h = isExpanded ? maxH : clamp(chatHeight, CHAT_MIN_H, maxH);
+ return `${w}x${h}${w >= maxW && h >= maxH ? ":max" : ""}`;
+}
+
export function useChatResize(
windowRef: React.RefObject<HTMLDivElement | null>,
) {
@@ -23,7 +34,7 @@ export function useChatResize(
const setExpanded = useChatStore((s) => s.setExpanded);
// ── Container bounds via ResizeObserver ────────────────────────────────
- const boundsRef = useRef({ maxW: FALLBACK_MAX_W, maxH: FALLBACK_MAX_H });
+ const boundsRef = useRef<Bounds>({ maxW: FALLBACK_MAX_W, maxH: FALLBACK_MAX_H });
const [boundsReady, setBoundsReady] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [, setRevision] = useState(0);
@@ -36,7 +47,6 @@ export function useChatResize(
const update = () => {
const maxW = Math.floor(parent.clientWidth * MAX_RATIO);
const maxH = Math.floor(parent.clientHeight * MAX_RATIO);
- setBoundsReady(true); // idempotent once true
// Only trigger a re-render if the bounds actually changed. Without this
// guard, any spurious ResizeObserver notification (including sub-pixel
// layout jitter during mount) schedules a setState that feeds back into
@@ -44,11 +54,17 @@ export function useChatResize(
const prev = boundsRef.current;
if (prev.maxW === maxW && prev.maxH === maxH) return;
boundsRef.current = { maxW, maxH };
+ // The window stays mounted while closed and its container resizes on
+ // every frame of a nav panel toggle; re-render only when the size the
+ // bounds clamp to changes, not for every new bound.
+ const state = useChatStore.getState();
+ if (renderedSize(prev, state) === renderedSize(boundsRef.current, state)) return;
setRevision((r) => r + 1);
};
// Measure immediately (parent is already in DOM at this point)
update();
+ setBoundsReady(true);
const ro = new ResizeObserver(update);
ro.observe(parent);
diff --git a/packages/views/common/single-row-fit.ts b/packages/views/common/single-row-fit.ts
deleted file mode 100644
index 9216d4dc3e..0000000000
--- a/packages/views/common/single-row-fit.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-"use client";
-
-import { useCallback, useLayoutEffect, useRef, useState } from "react";
-
-/**
- * Fit calculator for a single-row toolbar that collapses its tail into a
- * trailing trigger (the view bar; reusable for any "N chips + overflow
- * menu" strip).
- *
- * The caller renders every candidate twice: once for real (slice to
- * `fitCount`) and once inside a hidden mirror row attached to
- * `measureRef` (absolutely positioned, `visibility: hidden`, same
- * classes). Natural widths are read off the mirror, so the fit answer
- * never depends on what is currently mounted for real — no feedback
- * loop between measurement and rendering.
- *
- * Rule: the longest prefix that fits alongside its trailing chrome wins.
- * `reserve` returns the chrome width for a candidate fit count, including
- * permanent menus even when every item fits. Resolve both from the same
- * measurement before updating state, so overflow controls cannot feed a
- * stale fit back into a later render.
- *
- * Remeasures on container resize (ResizeObserver) and after every
- * commit (labels/items change the mirror); state only updates when the
- * answer actually changes, so the extra passes are free.
- */
-export function useSingleRowFit({
- count,
- gap,
- reserve,
-}: {
- /** Number of candidate items (mirror children must match). */
- count: number;
- /** Horizontal gap between items in px (the container's `gap`). */
- gap: number;
- /** Trailing chrome width in px for a candidate number of fitting items. */
- reserve: (fitCount: number) => number;
-}) {
- const containerRef = useRef<HTMLDivElement | null>(null);
- const measureRef = useRef<HTMLDivElement | null>(null);
- const [fitCount, setFitCount] = useState(count);
-
- const recompute = useCallback(() => {
- const container = containerRef.current;
- const mirror = measureRef.current;
- if (!container || !mirror) return;
- const available = container.clientWidth;
- const widths = Array.from(mirror.children).map(
- (child) => (child as HTMLElement).offsetWidth,
- );
-
- let next = widths.length;
- let used =
- widths.reduce((sum, width) => sum + width, 0) + Math.max(0, next - 1) * gap;
- while (next > 0 && used + gap + reserve(next) > available) {
- next--;
- used -= widths[next]! + (next > 0 ? gap : 0);
- }
- setFitCount((current) => (current === next ? current : next));
- }, [gap, reserve]);
-
- // After every commit: the mirror just re-rendered with current labels.
- useLayoutEffect(() => {
- recompute();
- });
-
- useLayoutEffect(() => {
- const container = containerRef.current;
- if (!container || typeof ResizeObserver === "undefined") return;
- const observer = new ResizeObserver(() => recompute());
- observer.observe(container);
- return () => observer.disconnect();
- }, [recompute]);
-
- // Never report more than exists (items can shrink between renders).
- return { containerRef, measureRef, fitCount: Math.min(fitCount, count) };
-}
diff --git a/packages/views/common/use-language-switch.ts b/packages/views/common/use-language-switch.ts
new file mode 100644
index 0000000000..f969877ad1
--- /dev/null
+++ b/packages/views/common/use-language-switch.ts
@@ -0,0 +1,66 @@
+"use client";
+
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from "@multica/core/i18n";
+import { useLocaleAdapter } from "@multica/core/i18n/react";
+import { useT } from "../i18n";
+
+/** The UI language options, the current one, and the switch shared by Settings and the account menu. */
+export function useLanguageSwitch() {
+ const { t, i18n } = useT("settings");
+ const localeAdapter = useLocaleAdapter();
+ const user = useAuthStore((s) => s.user);
+
+ // i18next.language can be a region-tagged BCP-47 string (e.g. "en-US",
+ // "zh-Hans-CN") returned by intl-localematcher. Normalize to a supported
+ // locale before comparing — otherwise the select shows neither option.
+ const currentLocale: SupportedLocale = SUPPORTED_LOCALES.includes(
+ i18n.language as SupportedLocale,
+ )
+ ? (i18n.language as SupportedLocale)
+ : DEFAULT_LOCALE;
+
+ const options: { value: SupportedLocale; label: string }[] = [
+ { value: "en", label: t(($) => $.preferences.language.english) },
+ { value: "zh-Hans", label: t(($) => $.preferences.language.chinese) },
+ { value: "zh-Hant", label: t(($) => $.preferences.language.chinese_traditional) },
+ { value: "ko", label: t(($) => $.preferences.language.korean) },
+ { value: "ja", label: t(($) => $.preferences.language.japanese) },
+ { value: "fr", label: t(($) => $.preferences.language.french) },
+ ];
+
+ // Persist locally → sync to user.language → reload. Reload (vs in-place
+ // changeLanguage) avoids hydration mismatch and is the i18next-recommended
+ // pattern for App Router. The reload itself is the confirmation.
+ //
+ // If the cross-device sync (PATCH /api/me) fails, the local cookie is
+ // already written so the new locale will take effect after reload — but
+ // the user's other devices won't see the change. Surface that explicitly
+ // via a toast and delay the reload long enough for the toast to be read,
+ // otherwise the failure would be invisible.
+ const changeLanguage = async (next: SupportedLocale) => {
+ if (next === currentLocale) return;
+ localeAdapter.persist(next);
+
+ let syncFailed = false;
+ if (user) {
+ try {
+ await api.updateMe({ language: next });
+ } catch {
+ syncFailed = true;
+ }
+ }
+
+ if (syncFailed) {
+ toast.warning(t(($) => $.preferences.language.sync_failed));
+ // Give the toast 2.5s of visible time before navigating away.
+ setTimeout(() => window.location.reload(), 2500);
+ return;
+ }
+ window.location.reload();
+ };
+
+ return { options, currentLocale, changeLanguage };
+}
diff --git a/packages/views/dashboard/components/dashboard-filters.tsx b/packages/views/dashboard/components/dashboard-filters.tsx
index 3ac62ca94d..e39bce3d0a 100644
--- a/packages/views/dashboard/components/dashboard-filters.tsx
+++ b/packages/views/dashboard/components/dashboard-filters.tsx
@@ -42,10 +42,10 @@ export function TimeRangeFilter({
<DropdownMenuTrigger
render={
<Button
- variant="outline"
+ variant="ghost"
size="sm"
aria-label={t(($) => $.filter.period_label)}
- className="gap-1 px-2.5"
+ className="h-7 gap-1.5 px-2 text-body"
>
<CalendarDays className="size-3.5 text-muted-foreground" />
<span className="tabular-nums">{current.label}</span>
@@ -79,10 +79,10 @@ export function TimeRangeFilter({
* A single-level dropdown, deliberately not a generic "Filter" menu: with one
* dimension, a wrapper menu only hides what is filterable behind an extra
* hover. The trigger states the current value like `TimeRangeFilter` does:
- * a neutral outline throughout, showing the selected project's own icon and
- * name once narrowed — the named value is the active-state signal, no filled
- * tier. If a second dimension ships (agent, model, runtime), fold this back
- * into a combined menu in the `IssueDisplayControls` grammar.
+ * a quiet ghost control throughout, showing the selected project's own icon
+ * and name once narrowed — the named value is the active-state signal, no
+ * filled tier. If a second dimension ships (agent, model, runtime), fold this
+ * back into a combined menu in the `IssueDisplayControls` grammar.
*/
export function ProjectFilter({
projects,
@@ -106,15 +106,15 @@ export function ProjectFilter({
<DropdownMenuTrigger
render={
<Button
- variant="outline"
+ variant="ghost"
size="sm"
aria-label={t(($) => $.filter.project_label)}
- className={selected ? "gap-1 px-2.5" : "gap-1 px-2.5 text-muted-foreground"}
+ className="h-7 gap-1.5 px-2 text-body"
>
{selected ? (
<ProjectIcon project={selected} size="sm" />
) : (
- <FolderKanban className="size-3.5" />
+ <FolderKanban className="size-3.5 text-muted-foreground" />
)}
<span className="max-w-40 truncate">
{selected ? selected.title : allLabel}
diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsx
index beef438ae7..c7dfa975d8 100644
--- a/packages/views/dashboard/components/dashboard-page.test.tsx
+++ b/packages/views/dashboard/components/dashboard-page.test.tsx
@@ -718,6 +718,47 @@ describe("DashboardPage — the two questions are separate tabs", () => {
});
});
+describe("DashboardPage — one header carries the tabs and the filters", () => {
+ beforeEach(() => {
+ queryKeys.length = 0;
+ dashboardDataRef.current = true;
+ manyAgentsRef.current = false;
+ tzRef.current = "UTC";
+ cleanup();
+ });
+
+ it("puts the title, both tabs, the filters and refresh in a single header", () => {
+ renderDashboard();
+
+ const [header, ...rest] = screen.getAllByRole("banner");
+ expect(rest).toHaveLength(0);
+ const bar = within(header as HTMLElement);
+ expect(bar.getByRole("heading", { name: "Analytics" })).toBeInTheDocument();
+ expect(bar.getByRole("tab", { name: "Usage" })).toHaveAttribute("aria-selected", "true");
+ expect(bar.getByRole("tab", { name: /Errors/ })).toBeInTheDocument();
+ expect(bar.getByText(/^GMT/)).toBeInTheDocument();
+ expect(bar.getByRole("button", { name: "Refresh" })).toBeInTheDocument();
+ });
+
+ it("shows each filter's current value on its trigger", () => {
+ renderDashboard();
+
+ const bar = within(screen.getByRole("banner"));
+ expect(bar.getByRole("button", { name: "Period" })).toHaveTextContent("30d");
+ expect(bar.getByRole("button", { name: "Project" })).toHaveTextContent("All projects");
+ });
+
+ it("keeps the header in place when switching to Errors", async () => {
+ const user = userEvent.setup();
+ renderDashboard();
+ await openErrorsTab(user);
+
+ const bar = within(screen.getByRole("banner"));
+ expect(bar.getByRole("tab", { name: /Errors/ })).toHaveAttribute("aria-selected", "true");
+ expect(bar.getByRole("button", { name: "Period" })).toHaveTextContent("30d");
+ });
+});
+
// MUL-5409. The server folds every agent it won't name — those the viewer may
// not see, plus the hidden system carriers behind agent-builder sessions — onto
// one sentinel row. The leaderboard used to have a single synthetic row,
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index df6f4558c6..5dd0b10626 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -26,8 +26,7 @@ import {
} from "@multica/core/dashboard";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import { useViewingTimezone } from "../../common/use-viewing-timezone";
-import { PAGE_GUTTER } from "../../layout/page-header";
-import { CollectionPageHeader } from "../../layout/collection-page";
+import { PageHeader } from "../../layout/page-header";
import { KpiCard } from "../../runtimes/components/shared";
import { useNavigation } from "../../navigation";
import {
@@ -67,7 +66,6 @@ import { ProjectFilter, TimeRangeFilter } from "./dashboard-filters";
import { UsageTrendCard } from "./usage-trend-card";
import { Leaderboard } from "./leaderboard";
import { ErrorsTab } from "./errors-tab";
-import { cn } from "@multica/ui/lib/utils";
// Stable references — `data ?? []` would create a new empty array on
// every render while the query is loading, which breaks useMemo's
@@ -137,9 +135,9 @@ function useDataFreshness(
* where the failure breakdown sat below a leaderboard that could itself run to
* thirty rows, and the only way to chart failures was to hide spend.
*
- * Scope is expressed by where a control lives: the toolbar under the header
- * carries the tabs and the two page-scoped filters (time range, project),
- * every card carries its own view switches. All six rollups are fetched for
+ * Scope is expressed by where a control lives: the header carries the tabs and
+ * the two page-scoped filters (time range, project), every card carries its
+ * own view switches. All six rollups are fetched for
* both tabs — they are small, and prefetching is what makes switching tabs
* instant — but the loading and empty states are per tab, so Usage does not
* wait on the failure queries.
@@ -462,68 +460,58 @@ export function DashboardPage() {
onValueChange={handleTabChange}
className="flex h-full min-h-0 flex-col gap-0"
>
- <CollectionPageHeader
- icon={BarChart3}
- title={t(($) => $.title)}
- actions={
- /* Data freshness cluster: the timestamp and the action that advances
- it stay together. Refresh re-pulls the same scope, so it lives here
- with the page metadata rather than among the scope controls. */
- <div className="flex items-center gap-1">
- {tzLabel ? (
- <span className="hidden text-caption text-muted-foreground lg:inline">
- {updatedLabel
- ? t(($) => $.header.timezone_and_updated, {
- tz: tzLabel,
- time: updatedLabel,
- })
- : tzLabel}
- </span>
- ) : null}
- <IconButton
- variant="ghost"
- size="icon-sm"
- label={t(($) => $.header.refresh)}
- tooltipSide="bottom"
- onClick={handleRefresh}
- disabled={isRefreshing}
- >
- <RefreshCw className={isRefreshing ? "animate-spin" : undefined} />
- </IconButton>
- </div>
- }
- />
-
- {/* View toolbar, same grammar as the issues surface header: view
- switching on the left, page-scoped filters on the right. Both tabs
- share the range and project filter, which is why the filters live
- here and not inside a tab. */}
- <div className={cn("h-12 shrink-0 overflow-x-auto border-b [-webkit-overflow-scrolling:touch]", PAGE_GUTTER)}>
- <div className="flex h-full w-max min-w-full items-center justify-between gap-2">
- <TabsList variant="line" className="gap-0 p-0 group-data-horizontal/tabs:h-full">
+ {/* The two tabs are views of the same data, so they sit beside the
+ title; both share the range and project filter, which is why the
+ filters live in the header and not inside a tab. */}
+ <PageHeader>
+ <div className="flex min-w-0 flex-1 items-center gap-2 self-stretch">
+ <h1 className="flex min-w-0 items-center gap-2 px-2 text-body font-medium">
+ <BarChart3 aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate">{t(($) => $.title)}</span>
+ </h1>
+ <TabsList variant="line" className="shrink-0 gap-0 p-0 group-data-horizontal/tabs:h-full">
<TabsTrigger
value="usage"
- className="h-full rounded-none px-2.5 text-label group-data-horizontal/tabs:after:bottom-0"
+ className="h-full rounded-none px-2.5 group-data-horizontal/tabs:after:bottom-0"
>
{t(($) => $.tab_usage)}
</TabsTrigger>
<TabsTrigger
value="errors"
- className="h-full rounded-none px-2.5 text-label group-data-horizontal/tabs:after:bottom-0"
+ className="h-full rounded-none px-2.5 group-data-horizontal/tabs:after:bottom-0"
>
{t(($) => $.errors.title)}
</TabsTrigger>
</TabsList>
- <div className="flex shrink-0 items-center gap-2">
- <TimeRangeFilter days={days} onChange={setDays} />
- <ProjectFilter
- projects={projects}
- projectValue={projectValue}
- onProjectChange={setProjectValue}
- />
- </div>
</div>
- </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {tzLabel ? (
+ <span className="mr-1 hidden text-caption text-muted-foreground lg:inline">
+ {updatedLabel
+ ? t(($) => $.header.timezone_and_updated, {
+ tz: tzLabel,
+ time: updatedLabel,
+ })
+ : tzLabel}
+ </span>
+ ) : null}
+ <TimeRangeFilter days={days} onChange={setDays} />
+ <ProjectFilter
+ projects={projects}
+ projectValue={projectValue}
+ onProjectChange={setProjectValue}
+ />
+ <IconButton
+ label={t(($) => $.header.refresh)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={handleRefresh}
+ disabled={isRefreshing}
+ >
+ <RefreshCw className={isRefreshing ? "animate-spin" : undefined} />
+ </IconButton>
+ </div>
+ </PageHeader>
<div className="flex-1 overflow-y-auto">
<div className="mx-auto max-w-6xl p-6">
diff --git a/packages/views/inbox/components/inbox-filter-menu.test.tsx b/packages/views/inbox/components/inbox-filter-menu.test.tsx
index 64c2da82a5..4464543372 100644
--- a/packages/views/inbox/components/inbox-filter-menu.test.tsx
+++ b/packages/views/inbox/components/inbox-filter-menu.test.tsx
@@ -289,13 +289,13 @@ describe("InboxFilterMenu", () => {
);
});
- it("toggles no agents working and counts the idle rows behind it", async () => {
+ it("toggles no agents working without a count beside it", async () => {
renderMenu({ activeIssueIds: new Set(["issue-todo-high"]) });
fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
fireEvent.click(
await screen.findByRole("menuitemcheckbox", {
- name: /No agents working.*1 notification/,
+ name: /^No agents working$/,
}),
);
diff --git a/packages/views/inbox/components/inbox-filter-menu.tsx b/packages/views/inbox/components/inbox-filter-menu.tsx
index a51f3dab6e..d7e7a3a40b 100644
--- a/packages/views/inbox/components/inbox-filter-menu.tsx
+++ b/packages/views/inbox/components/inbox-filter-menu.tsx
@@ -168,12 +168,6 @@ export function InboxFilterMenu({
).filter((item) => item.read !== true).length,
[items, effectiveFilters, activeIssueIds],
);
- const idleCount = useMemo(
- () =>
- filterInboxItems(items, { ...effectiveFilters, idleOnly: true }, { activeIssueIds })
- .length,
- [items, effectiveFilters, activeIssueIds],
- );
const localStatuses = useMemo(
() => statusCounts(statusFacetItems),
[statusFacetItems],
@@ -260,11 +254,6 @@ export function InboxFilterMenu({
>
<BotOff className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.no_agents_working)}</span>
- {idleCount > 0 && (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.filters.notification_count, { count: idleCount })}
- </span>
- )}
</DropdownMenuCheckboxItem>
)}
<DropdownMenuSeparator />
diff --git a/packages/views/inbox/components/inbox-list.test.tsx b/packages/views/inbox/components/inbox-list.test.tsx
index ce01df9fab..3a05368863 100644
--- a/packages/views/inbox/components/inbox-list.test.tsx
+++ b/packages/views/inbox/components/inbox-list.test.tsx
@@ -92,7 +92,6 @@ function renderList(selectedKey: string, onSelect = vi.fn()) {
selectedKey={selectedKey}
onSelect={onSelect}
onAction={vi.fn()}
- onOpenArchived={vi.fn()}
/>,
);
// The scroll container owns the key handler; it is the row's closest
@@ -203,16 +202,9 @@ describe("InboxList keyboard navigation", () => {
describe("InboxList archive pagination", () => {
- it("keeps a count-free archive entry available with an empty inbox", () => {
- const onOpenArchived = vi.fn();
- render(<InboxList items={[]} view="inbox" selectedKey="" onSelect={vi.fn()} onAction={vi.fn()} onOpenArchived={onOpenArchived} />);
- fireEvent.click(screen.getByRole("button", { name: "Archived" }));
- expect(onOpenArchived).toHaveBeenCalledOnce();
- });
-
it("loads at the end, suppresses automatic retries, and provides a retry button", () => {
const onLoadMore = vi.fn();
- const props = { items, view: "archived" as const, selectedKey: "", onSelect: vi.fn(), onAction: vi.fn(), onOpenArchived: vi.fn(), onLoadMore };
+ const props = { items, view: "archived" as const, selectedKey: "", onSelect: vi.fn(), onAction: vi.fn(), onLoadMore };
const { rerender } = render(<InboxList {...props} />);
fireEvent.click(screen.getByRole("button", { name: "Reach list end" }));
expect(onLoadMore).toHaveBeenCalledOnce();
@@ -227,7 +219,7 @@ describe("InboxList archive pagination", () => {
it("loads the next page when restored rows drain the loaded window", () => {
const onLoadMore = vi.fn();
- render(<InboxList items={[]} view="archived" selectedKey="" onSelect={vi.fn()} onAction={vi.fn()} onOpenArchived={vi.fn()} onLoadMore={onLoadMore} />);
+ render(<InboxList items={[]} view="archived" selectedKey="" onSelect={vi.fn()} onAction={vi.fn()} onLoadMore={onLoadMore} />);
expect(onLoadMore).toHaveBeenCalledOnce();
expect(screen.queryByText("No archived notifications")).toBeNull();
});
diff --git a/packages/views/inbox/components/inbox-list.tsx b/packages/views/inbox/components/inbox-list.tsx
index 18d93ee88d..69a69625bd 100644
--- a/packages/views/inbox/components/inbox-list.tsx
+++ b/packages/views/inbox/components/inbox-list.tsx
@@ -3,14 +3,13 @@
import {
useCallback,
useEffect,
- useMemo,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";
-import { Archive, ChevronRight, Inbox } from "@multica/ui/icons";
+import { Inbox } from "@multica/ui/icons";
import { isEditableShortcutTarget } from "@multica/core/shortcuts";
import { isImeComposing } from "@multica/core/utils";
import type { InboxItem } from "@multica/core/types";
@@ -56,9 +55,9 @@ export function InboxList({
loadMoreError = false,
onSelect,
onAction,
- onOpenArchived,
emptyLabel,
emptyAction,
+ scrollRestoration = true,
}: {
items: InboxItem[];
view: InboxView;
@@ -68,9 +67,13 @@ export function InboxList({
loadMoreError?: boolean;
onSelect: (item: InboxItem) => void;
onAction: (id: string) => void;
- onOpenArchived: () => void;
emptyLabel?: string;
emptyAction?: ReactNode;
+ /**
+ * Off for a preview rendered over another route, which must neither read
+ * nor be captured as that route's `list` scroll offset.
+ */
+ scrollRestoration?: boolean;
}) {
const { t } = useT("inbox");
// Virtuoso's `customScrollParent` wants the actual HTMLElement, not a ref.
@@ -81,14 +84,15 @@ export function InboxList({
// ref-attach (the seed's estimate spacer gives the container a truthful
// height on the first commit, so the assignment sticks pre-paint) and feed
// the same offset into the Virtuoso as its initial position.
- const restoredScrollTop = useRestoredScrollOffset("list");
+ const savedScrollTop = useRestoredScrollOffset("list");
const restoreScrollRef = useRestoredScrollRef("list");
+ const restoredScrollTop = scrollRestoration ? savedScrollTop : undefined;
const attachScrollEl = useCallback(
(el: HTMLDivElement | null) => {
setScrollEl(el);
- restoreScrollRef(el);
+ if (scrollRestoration) restoreScrollRef(el);
},
- [restoreScrollRef],
+ [restoreScrollRef, scrollRestoration],
);
const virtuosoRef = useRef<VirtuosoHandle>(null);
const isArchivedView = view === "archived";
@@ -154,39 +158,15 @@ export function InboxList({
onSelect(nextItem);
};
- // The entry into the archive sits below the last row and scrolls with the
- // list (same placement as chat's). Virtuoso mounts it via `components.Footer`,
- // and swaps the component whenever that prop's identity changes — so both the
- // element and the Footer wrapping it are memoized. Without that the entry
- // remounts on every parent render and drops hover/focus mid-click.
- const archivedEntry = useMemo(
- () =>
- !isArchivedView ? (
- <button
- type="button"
- onClick={onOpenArchived}
- className="mt-1 flex h-10 w-full items-center gap-2 rounded-md px-2 text-left text-caption text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"
- >
- <span className="flex size-7 shrink-0 items-center justify-center">
- <Archive className="size-4" />
- </span>
- <span className="min-w-0 flex-1 truncate font-medium">
- {t(($) => $.list.archived_title)}
- </span>
- <ChevronRight className="size-4 shrink-0 text-faint-foreground" />
- </button>
- ) : null,
- [isArchivedView, onOpenArchived, t],
- );
-
const loadMore = useCallback(() => {
if (!loadingMore && !loadMoreError) onLoadMore?.();
}, [loadingMore, loadMoreError, onLoadMore]);
useEffect(() => {
if (items.length === 0) loadMore();
}, [items.length, loadMore]);
+ // Virtuoso remounts `components.Footer` whenever its identity changes, so
+ // it is memoized to keep the load-more button's focus across renders.
const Footer = useCallback(() => <>
- {archivedEntry}
{isArchivedView && onLoadMore && (
<div className="flex flex-col items-center gap-2 py-3">
{loadMoreError && <p role="alert" className="text-caption text-destructive">{t(($) => $.errors.archived_load_failed)}</p>}
@@ -196,7 +176,7 @@ export function InboxList({
</button>
</div>
)}
- </>, [archivedEntry, isArchivedView, onLoadMore, loadingMore, loadMoreError, t]);
+ </>, [isArchivedView, onLoadMore, loadingMore, loadMoreError, t]);
if (items.length === 0) {
return (
@@ -211,8 +191,6 @@ export function InboxList({
</p>
{emptyAction && <div className="mt-3">{emptyAction}</div>}
</div>}
- {/* Still offer the archive when the main list is empty — that is
- exactly when a user goes looking for what they filed away. */}
<div className="px-2"><Footer /></div>
</div>
);
@@ -236,7 +214,7 @@ export function InboxList({
return (
<div
ref={attachScrollEl}
- data-tab-scroll-root="list"
+ data-tab-scroll-root={scrollRestoration ? "list" : undefined}
// Programmatically focusable only: the rows already carry their own tab
// stops, so a tabbable container would just add a redundant one.
tabIndex={-1}
@@ -259,18 +237,12 @@ export function InboxList({
components={{ Footer }}
/>
) : (
- <>
- <VirtuosoSeed
- data={items}
- itemContent={itemContent}
- computeItemKey={computeItemKey}
- estimatedItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}
- />
- {/* The seed frame renders a bounded slice, so the entry would be
- mid-list rather than after the last row — only show it once the
- seed IS the whole list. */}
- {items.length <= VIRTUOSO_SEED_COUNT && archivedEntry}
- </>
+ <VirtuosoSeed
+ data={items}
+ itemContent={itemContent}
+ computeItemKey={computeItemKey}
+ estimatedItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}
+ />
)}
</div>
</div>
diff --git a/packages/views/inbox/components/inbox-page-query.test.tsx b/packages/views/inbox/components/inbox-page-query.test.tsx
index 768c8b3cb7..2f973aad9a 100644
--- a/packages/views/inbox/components/inbox-page-query.test.tsx
+++ b/packages/views/inbox/components/inbox-page-query.test.tsx
@@ -12,9 +12,6 @@ import type { InboxItem } from "@multica/core/types";
import { InboxPage } from "./inbox-page";
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
-vi.mock("react-resizable-panels", () => ({
- useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
-}));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
vi.mock("@multica/core/paths", () => ({
useWorkspacePaths: () => ({
@@ -41,11 +38,6 @@ vi.mock("../../navigation", () => ({
useReportNavigating: () => {},
}));
vi.mock("@multica/ui/hooks/use-mobile", () => ({ useIsCompact: () => false }));
-vi.mock("@multica/ui/components/ui/resizable", () => ({
- ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- ResizableHandle: () => null,
-}));
vi.mock("./inbox-list", () => ({
InboxList: ({ items, onSelect }: { items: InboxItem[]; onSelect: (item: InboxItem) => void }) => (
<div>{items.map((row) => (
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index 3cfc530573..514c60055f 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -10,9 +10,6 @@ vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));
-vi.mock("react-resizable-panels", () => ({
- useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
-}));
// The page runs two queries — the active list and the archived one. They are
// told apart by the queryKey their options carry, so each test can stock the
@@ -157,34 +154,6 @@ vi.mock("@multica/ui/hooks/use-mobile", () => ({
useIsMobile: () => layout.width < 768,
useIsCompact: () => layout.width < 768,
}));
-vi.mock("@multica/ui/components/ui/resizable", () => ({
- ResizablePanelGroup: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- ResizablePanel: ({
- children,
- id,
- defaultSize,
- minSize,
- maxSize,
- }: {
- children: React.ReactNode;
- id: string;
- defaultSize?: number;
- minSize?: number | string;
- maxSize?: number | string;
- }) => (
- <div
- data-testid={`panel-${id}`}
- data-default-size={defaultSize}
- data-min-size={minSize}
- data-max-size={maxSize}
- >
- {children}
- </div>
- ),
- ResizableHandle: () => null,
-}));
vi.mock("./inbox-list", () => ({
InboxList: ({
items,
@@ -353,16 +322,17 @@ describe("InboxPage", () => {
expect(screen.queryByTestId("row")).toBeNull();
});
- it("keeps the list subordinate to the detail pane on desktop", () => {
+ // The list takes the space panel's width, so its divider lines up with the
+ // panel's when switching spaces.
+ it("sizes the desktop list with the shared panel width", () => {
reset();
layout.width = DESKTOP;
- render(<InboxPage />);
+ const { container } = render(<InboxPage />);
- const listPanel = screen.getByTestId("panel-list");
- expect(listPanel).toHaveAttribute("data-default-size", "260");
- expect(listPanel).toHaveAttribute("data-min-size", "240");
- expect(listPanel).toHaveAttribute("data-max-size", "400");
+ expect(container.querySelector("[data-slot='list-column']")).toHaveClass(
+ "w-(--sidebar-width)",
+ );
});
it("keeps the title unread count static", () => {
@@ -594,17 +564,36 @@ describe("InboxPage", () => {
expect(screen.getByTestId("row").textContent).toBe("archived-1");
});
+ it("switches between the inbox and the archive from the title menu", async () => {
+ reset();
+ layout.width = DESKTOP;
+ searchParams = new URLSearchParams("issue=issue-1");
+ listData.active = [item({ id: "active-1", issue_id: "issue-1" })];
+ const { container } = render(<InboxPage />);
+
+ const titleMenu = container.querySelector("h1 [aria-haspopup='menu']") as HTMLElement;
+ fireEvent.click(titleMenu);
+ // The test's `useT` labels every option "Inbox", so they are located by order.
+ const [inboxOption, archivedOption] = await screen.findAllByRole("menuitemradio");
+ expect(inboxOption).toHaveAttribute("aria-checked", "true");
+ fireEvent.click(archivedOption!);
+
+ expect(replace).toHaveBeenLastCalledWith("/acme/inbox?view=archived");
+ expect(screen.getByTestId("list").dataset.view).toBe("archived");
+ });
+
it("hides the batch-actions menu in the archived view", () => {
// Every batch action archives from the MAIN inbox; offering them over the
// archived list would read as "archive all of these" and do the opposite.
reset();
listData.archived = [item({ id: "archived-1", archived: true })];
+ const batchMenu = ':not(h1) > [aria-haspopup="menu"]';
const { container: mainView } = render(<InboxPage />);
- expect(mainView.querySelector('[aria-haspopup="menu"]')).not.toBeNull();
+ expect(mainView.querySelector(batchMenu)).not.toBeNull();
searchParams = new URLSearchParams("view=archived");
const { container: archivedView } = render(<InboxPage />);
- expect(archivedView.querySelector('[aria-haspopup="menu"]')).toBeNull();
+ expect(archivedView.querySelector(batchMenu)).toBeNull();
});
it("ignores a carried-over idle selection in the archive", () => {
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 1fd27c52be..2ad643bbc1 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -8,7 +8,6 @@ import {
useMemo,
useRef,
} from "react";
-import { useDefaultLayout } from "react-resizable-panels";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
import { ApiError, errorCode } from "@multica/core/api";
@@ -67,7 +66,7 @@ import {
Archive,
ArchiveRestore,
BookCheck,
- ChevronLeft,
+ ChevronDown,
ListChecks,
ArrowLeft,
} from "@multica/ui/icons";
@@ -79,11 +78,6 @@ import {
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
-import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
-} from "@multica/ui/components/ui/resizable";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { NumberFlow } from "@multica/ui/components/ui/number-flow";
import {
@@ -91,11 +85,16 @@ import {
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
DropdownMenuSeparator,
} from "@multica/ui/components/ui/dropdown-menu";
import { useIsCompact } from "@multica/ui/hooks/use-mobile";
import { cn } from "@multica/ui/lib/utils";
-import { PAGE_GUTTER, PageHeader } from "../../layout/page-header";
+import { CollapsedNavTrigger, PAGE_GUTTER, PageHeader } from "../../layout/page-header";
+import { PanelHeader } from "../../layout/panel-nav";
+import { useListColumnCollapsed } from "../../layout/app-shell-context";
+import { ListColumn } from "../../layout/list-column";
import { useTimeAgo } from "./inbox-list-item";
import { InboxList } from "./inbox-list";
import { InboxFilterMenu } from "./inbox-filter-menu";
@@ -112,9 +111,6 @@ import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
import { useT } from "../../i18n";
import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";
-const INBOX_LIST_DEFAULT_SIZE = 260;
-const INBOX_LIST_MIN_SIZE = 240;
-const INBOX_LIST_MAX_SIZE = 400;
export function InboxPage() {
const queryClient = useQueryClient();
@@ -278,10 +274,6 @@ export function InboxPage() {
replace(buildInboxUrl(nextView, ""));
}, [replace, buildInboxUrl]);
- // Stable identity: InboxList memoizes the archive entry on this callback, so
- // an inline arrow here would rebuild (and remount) the entry every render.
- const openArchived = useCallback(() => setView("archived"), [setView]);
-
// Applying a filter can remove the open row from the list. Clear that local
// selection instead of treating it as a broken deep link and redirecting to
// the issue page; the notification still exists, it is simply filtered out.
@@ -326,11 +318,8 @@ export function InboxPage() {
setSelectedKey,
]);
- const { defaultLayout, onLayoutChanged } = useDefaultLayout({
- id: "multica_inbox_layout",
- });
-
const isCompact = useIsCompact();
+ const listCollapsed = useListColumnCollapsed();
const unreadCount = useInboxUnreadCount(wsId);
const markReadMutation = useMarkInboxRead();
@@ -618,10 +607,43 @@ export function InboxPage() {
// -- Shared sub-components --------------------------------------------------
const listHeader = (
- <PageHeader>
- <div className="flex flex-1 items-center gap-2">
- <h1 className="text-body font-semibold">{t(($) => $.page.title)}</h1>
- {unreadCount > 0 && (
+ <PanelHeader
+ as="h1"
+ title={
+ // The archive is a second list of the same page, so the title doubles
+ // as the switch between the two instead of costing a row of its own.
+ <DropdownMenu>
+ <DropdownMenuTrigger className="-ml-1.5 mr-1.5 flex min-w-0 items-center gap-1 rounded-md px-1.5 py-0.5 outline-none transition-colors hover:bg-accent/60 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring aria-expanded:bg-accent/60">
+ <span className="min-w-0 truncate">
+ {isArchivedView ? t(($) => $.list.archived_title) : t(($) => $.page.title)}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-auto min-w-44">
+ <DropdownMenuRadioGroup
+ value={view}
+ onValueChange={(value) => setView(value as InboxView)}
+ >
+ <DropdownMenuRadioItem value="inbox">
+ <Inbox className="h-4 w-4" />
+ <span className="flex-1">{t(($) => $.page.title)}</span>
+ {unreadCount > 0 && (
+ <span className="text-caption tabular-nums text-muted-foreground">
+ {unreadCount}
+ </span>
+ )}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="archived">
+ <Archive className="h-4 w-4" />
+ {t(($) => $.list.archived_title)}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ }
+ leading={<CollapsedNavTrigger />}
+ meta={
+ !isArchivedView && unreadCount > 0 && (
<NumberFlow
value={unreadCount}
animated={false}
@@ -629,8 +651,9 @@ export function InboxPage() {
aria-label={String(unreadCount)}
className="text-caption text-muted-foreground"
/>
- )}
- </div>
+ )
+ }
+ >
<InboxFilterMenu
wsId={wsId}
items={viewItems}
@@ -675,21 +698,7 @@ export function InboxPage() {
</DropdownMenuContent>
</DropdownMenu>
)}
- </PageHeader>
- );
-
- // Back out of the archive. Sits inside the list panel rather than replacing
- // the PageHeader: the user is still in the Inbox, so the page title stays put
- // and this reads as a sub-view — the same shape chat's archived view uses.
- const archivedBackRow = (
- <button
- type="button"
- onClick={() => setView("inbox")}
- className="flex w-full shrink-0 items-center gap-1.5 border-b px-3 py-2 text-left text-caption font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"
- >
- <ChevronLeft className="size-4 shrink-0" />
- <span className="truncate">{t(($) => $.list.archived_title)}</span>
- </button>
+ </PanelHeader>
);
const list = isArchivedView && archivedError ? (
@@ -720,7 +729,6 @@ export function InboxPage() {
loadMoreError={archiveQuery.isFetchNextPageError}
onSelect={handleSelect}
onAction={isArchivedView ? handleUnarchive : handleArchive}
- onOpenArchived={openArchived}
emptyLabel={
hasActiveFilters && visibleItems.length === 0
? t(($) => $.filters.empty)
@@ -744,7 +752,6 @@ export function InboxPage() {
const listPanel = (
<>
{listHeader}
- {isArchivedView && archivedBackRow}
{lookupLoading && (
<p role="status" className="shrink-0 border-b px-3 py-2 text-caption text-muted-foreground">
{t(($) => $.list.loading_selection)}
@@ -764,30 +771,6 @@ export function InboxPage() {
</>
);
- // Same header and row boxes as `InboxListItem` (32px avatar, body + caption
- // lines), so the list doesn't shift when the items land.
- const loadingListPanel = (
- <>
- {listHeader}
- {isArchivedView && archivedBackRow}
- <div className="flex-1 min-h-0 overflow-hidden px-2 py-1">
- {Array.from({ length: 6 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3 px-2 py-2.5">
- <Skeleton className="size-8 shrink-0 rounded-full" />
- <div className="min-w-0 flex-1">
- <div className="flex h-5 items-center">
- <Skeleton className="h-3.5 w-3/4" />
- </div>
- <div className="mt-0.5 flex h-4 items-center">
- <Skeleton className="h-3 w-1/2" />
- </div>
- </div>
- </div>
- ))}
- </div>
- </>
- );
-
// Compact widths only: the detail fills the screen there, so the trip back to
// the list has to live inside it. On desktop the list is still on screen in
// the left panel and needs no back control at all.
@@ -844,8 +827,9 @@ export function InboxPage() {
highlightCommentId={detailItem.details?.comment_id ?? undefined}
highlightRequestToken={highlightRequestToken}
// The split layout already has a nav trigger in the list header.
- // Explicit false suppresses the detail header's fallback trigger.
- leadingAction={compactBackAction ?? false}
+ // Explicit false suppresses the detail header's fallback trigger,
+ // which is the way back once the list column is collapsed.
+ leadingAction={compactBackAction ?? (listCollapsed ? undefined : false)}
onDelete={() => {
// Issue deletion CASCADE-deletes the inbox item server-side, and the
// issue:deleted WS event prunes it from the inbox cache. Just clear
@@ -980,7 +964,24 @@ export function InboxPage() {
if (isCompact) {
if (viewLoading) {
- return <div className="flex flex-1 flex-col min-h-0">{loadingListPanel}</div>;
+ return (
+ <div className="flex flex-1 flex-col min-h-0">
+ <div className="flex h-12 shrink-0 items-center pl-5 pr-2">
+ <Skeleton className="h-5 w-16" />
+ </div>
+ <div className="flex-1 min-h-0 overflow-y-auto space-y-1 p-2">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <div key={i} className="flex items-center gap-3 px-2 py-2.5">
+ <Skeleton className="h-7 w-7 shrink-0 rounded-full" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-3 w-1/2" />
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
}
// Compact: show detail full-screen when an item is selected. The two kinds
@@ -1014,57 +1015,59 @@ export function InboxPage() {
return <div className="flex flex-1 flex-col min-h-0">{listPanel}</div>;
}
- // -- Desktop layout: resizable two-panel -----------------------------------
+ // -- Desktop layout: list column + detail ----------------------------------
if (viewLoading) {
return (
- <ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}>
- <ResizablePanel
- id="list"
- defaultSize={INBOX_LIST_DEFAULT_SIZE}
- minSize={INBOX_LIST_MIN_SIZE}
- maxSize={INBOX_LIST_MAX_SIZE}
- groupResizeBehavior="preserve-pixel-size"
- >
- <div className="flex flex-col border-r h-full">{loadingListPanel}</div>
- </ResizablePanel>
- <ResizableHandle />
- {/* Left blank: once loaded this pane is either a centred prompt or an
- issue detail with its own skeleton, so any placeholder here would
- be a third shape. */}
- <ResizablePanel id="detail" minSize="40%" />
- </ResizablePanelGroup>
+ <div className="flex min-h-0 flex-1">
+ <ListColumn collapsed={listCollapsed}>
+ <div className="flex h-12 shrink-0 items-center pl-5 pr-2">
+ <Skeleton className="h-5 w-16" />
+ </div>
+ <div className="flex-1 min-h-0 overflow-y-auto space-y-1 p-2">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <div key={i} className="flex items-center gap-3 px-2 py-2.5">
+ <Skeleton className="h-7 w-7 shrink-0 rounded-full" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-3 w-1/2" />
+ </div>
+ </div>
+ ))}
+ </div>
+ </ListColumn>
+ <div className="min-w-0 flex-1 p-6">
+ <Skeleton className="h-6 w-48" />
+ <Skeleton className="mt-4 h-4 w-32" />
+ </div>
+ </div>
);
}
return (
- <ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}>
- <ResizablePanel
- id="list"
- defaultSize={INBOX_LIST_DEFAULT_SIZE}
- minSize={INBOX_LIST_MIN_SIZE}
- maxSize={INBOX_LIST_MAX_SIZE}
- groupResizeBehavior="preserve-pixel-size"
- >
- <div className="flex flex-col border-r h-full">
- {listPanel}
- </div>
- </ResizablePanel>
- <ResizableHandle />
- <ResizablePanel id="detail" minSize="40%">
- <div className="flex flex-col min-h-0 h-full">
+ <div className="flex min-h-0 flex-1">
+ <ListColumn collapsed={listCollapsed}>{listPanel}</ListColumn>
+ <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col">
{detailContent ?? (
- <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
+ <>
+ {listCollapsed && (
+ <PageHeader>
+ <h1 className="text-body font-semibold">{t(($) => $.page.title)}</h1>
+ </PageHeader>
+ )}
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center text-muted-foreground">
<Inbox className="mb-3 h-10 w-10 text-faint-foreground" />
<p className="text-body">
- {visibleItems.length === 0
- ? t(($) => $.detail.empty)
- : t(($) => $.detail.select_prompt)}
+ {visibleItems.length > 0
+ ? t(($) => $.detail.select_prompt)
+ : isArchivedView
+ ? t(($) => $.list.archived_empty)
+ : t(($) => $.detail.empty)}
</p>
</div>
+ </>
)}
</div>
- </ResizablePanel>
- </ResizablePanelGroup>
+ </div>
);
}
diff --git a/packages/views/issue-views/all-views-page.test.tsx b/packages/views/issue-views/all-views-page.test.tsx
new file mode 100644
index 0000000000..7169b79d53
--- /dev/null
+++ b/packages/views/issue-views/all-views-page.test.tsx
@@ -0,0 +1,223 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { IssueView } from "@multica/core/api/schemas";
+import { renderWithI18n } from "../test/i18n";
+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
+import { NavigationProvider, type NavigationAdapter } from "../navigation";
+import { AllViewsPage } from "./all-views-page";
+
+const WORKSPACE_KEY = "ws-1:workspace";
+
+const mocks = vi.hoisted(() => ({
+ views: [] as IssueView[],
+ starred: new Set<string>(),
+ star: vi.fn(),
+ unstar: vi.fn(),
+ open: vi.fn(),
+ create: vi.fn(),
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: ({ queryKey }: { queryKey: unknown[] }) => ({
+ data: queryKey.includes("views") ? mocks.views : [],
+ }),
+}));
+vi.mock("@multica/core/issue-views/queries", () => ({
+ issueViewEverywhereOptions: () => ({ queryKey: ["views"] }),
+}));
+vi.mock("@multica/core/projects/queries", () => ({
+ projectListOptions: () => ({ queryKey: ["projects"] }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({ queryKey: ["members"] }),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ issues: () => "/acme/issues",
+ myIssues: () => "/acme/my-issues",
+ myAgents: () => "/acme/my-issues?scope=agents",
+ projectDetail: (id: string) => `/acme/projects/${id}`,
+ }),
+}));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (select: (s: { user: { id: string } }) => unknown) => select({ user: { id: "me" } }),
+}));
+vi.mock("../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("./use-view-actions", () => ({
+ useIssueViewActions: () => ({
+ sidebar: {
+ isStarred: (id: string) => mocks.starred.has(id),
+ star: mocks.star,
+ unstar: mocks.unstar,
+ },
+ canManage: () => true,
+ open: mocks.open,
+ create: mocks.create,
+ duplicate: vi.fn(),
+ remove: vi.fn(),
+ copyLink: vi.fn(),
+ }),
+}));
+
+function view(id: string, name: string, patch: Partial<IssueView> = {}): IssueView {
+ return {
+ id,
+ name,
+ workspace_id: "ws-1",
+ owner_id: "me",
+ scope_type: "workspace",
+ scope_id: null,
+ scope_variant: null,
+ visibility: "private",
+ definition_version: 1,
+ query: {},
+ display: {},
+ revision: 1,
+ created_at: "2026-10-01T00:00:00Z",
+ updated_at: "2026-10-01T00:00:00Z",
+ ...patch,
+ } as IssueView;
+}
+
+function renderPage(overrides: Partial<NavigationAdapter> = {}) {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/views",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ ...overrides,
+ };
+ renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <AllViewsPage />
+ </NavigationProvider>,
+ );
+ return adapter;
+}
+
+beforeEach(() => {
+ mocks.views = [
+ view("v1", "Needs review", { query: { statusFilters: ["in_review"], labelFilters: ["l1"] } }),
+ view("v2", "Team backlog", { owner_id: "someone", visibility: "workspace" }),
+ ];
+ mocks.starred = new Set(["builtin:my_issues", "view:v1"]);
+ mocks.star.mockReset();
+ mocks.unstar.mockReset();
+ mocks.open.mockReset();
+ mocks.create.mockReset();
+ useActiveIssueViewStore.setState({ active: {} });
+});
+
+describe("AllViewsPage", () => {
+ it("lists built-in and saved views with their filter counts", () => {
+ renderPage();
+ expect(screen.getByRole("button", { name: "Add All issues to sidebar" })).toBeInTheDocument();
+ expect(screen.getByText("Needs review")).toBeInTheDocument();
+ expect(screen.getByText("Team backlog")).toBeInTheDocument();
+ expect(screen.getByText("2")).toBeInTheDocument();
+ });
+
+ it("titles the page with the scope and switches scope from the title menu", async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ expect(screen.getByRole("heading", { level: 1, name: "All views" })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "All views" }));
+ expect(await screen.findByRole("menuitemradio", { name: /^All views/ })).toHaveTextContent("5");
+ expect(screen.getByRole("menuitemradio", { name: /^Built-in/ })).toHaveTextContent("3");
+ expect(screen.getByRole("menuitemradio", { name: /^Created by me/ })).toHaveTextContent("1");
+ await user.click(screen.getByRole("menuitemradio", { name: /^Shared/ }));
+
+ expect(screen.getByRole("heading", { level: 1, name: "Shared" })).toBeInTheDocument();
+ expect(screen.queryByText("Needs review")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Add All issues to sidebar" })).not.toBeInTheDocument();
+ expect(screen.getByText("Team backlog")).toBeInTheDocument();
+ });
+
+ it("has no search in the header", () => {
+ renderPage();
+
+ expect(screen.queryByRole("button", { name: "Search views" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ it("creates a view from the header", async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(screen.getByRole("button", { name: "New view" }));
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ scope: { scope_type: "workspace" }, renameIn: "header" }),
+ );
+ });
+
+ it("stars and unstars without opening the view", async () => {
+ const user = userEvent.setup();
+ const { push } = renderPage();
+
+ await user.click(screen.getByRole("button", { name: "Remove Needs review from sidebar" }));
+ expect(mocks.unstar).toHaveBeenCalledWith("view:v1");
+ await user.click(screen.getByRole("button", { name: "Add Team backlog to sidebar" }));
+ expect(mocks.star).toHaveBeenCalledWith("view:v2");
+ expect(push).not.toHaveBeenCalled();
+ expect(useActiveIssueViewStore.getState().active).toEqual({});
+
+ await user.click(screen.getByText("Team backlog"));
+ expect(push).toHaveBeenCalledWith("/acme/issues?view=v2");
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v2");
+ });
+
+ it("opens a view in place for a shift-click, which rows never hand to the browser", async () => {
+ const user = userEvent.setup();
+ const { push } = renderPage();
+
+ await user.keyboard("{Shift>}");
+ await user.click(screen.getByText("Team backlog"));
+ await user.keyboard("{/Shift}");
+
+ expect(push).toHaveBeenCalledWith("/acme/issues?view=v2");
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v2");
+ });
+
+ it("leaves the open view alone when a view or All issues opens in a new tab", async () => {
+ const user = userEvent.setup();
+ useActiveIssueViewStore.setState({ active: { [WORKSPACE_KEY]: "v-open" } });
+ const openInNewTab = vi.fn();
+ renderPage({ openInNewTab });
+
+ const allIssuesRow = screen.getByRole("button", { name: "Add All issues to sidebar" }).closest('[role="row"]')!;
+ await user.keyboard("{Meta>}");
+ await user.click(screen.getByText("Team backlog"));
+ await user.click(allIssuesRow);
+ await user.keyboard("{/Meta}");
+
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues?view=v2", "Team backlog");
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues", "All issues");
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v-open");
+ });
+
+ it("gives My Issues and My agents' work their own URLs", async () => {
+ const user = userEvent.setup();
+ const openInNewTab = vi.fn();
+ const { push } = renderPage({ openInNewTab });
+ const row = (name: string) =>
+ screen
+ .getByRole("button", { name: new RegExp(`^(Add ${name} to|Remove ${name} from) sidebar$`) })
+ .closest('[role="row"]')!;
+
+ await user.keyboard("{Meta>}");
+ await user.click(row("My Issues"));
+ await user.click(row("My agents' work"));
+ await user.keyboard("{/Meta}");
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/my-issues", "My Issues");
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/my-issues?scope=agents", "My agents' work");
+
+ await user.click(row("My agents' work"));
+ expect(push).toHaveBeenCalledWith("/acme/my-issues?scope=agents");
+ });
+});
diff --git a/packages/views/issue-views/all-views-page.tsx b/packages/views/issue-views/all-views-page.tsx
new file mode 100644
index 0000000000..43264ebaea
--- /dev/null
+++ b/packages/views/issue-views/all-views-page.tsx
@@ -0,0 +1,305 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ Bot,
+ CircleUser,
+ Copy,
+ Layers,
+ Link2,
+ ListTodo,
+ Star,
+ Trash2,
+} from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "@multica/ui/components/ui/dropdown-menu";
+import type { IssueView } from "@multica/core/api/schemas";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { issueViewEverywhereOptions } from "@multica/core/issue-views/queries";
+import { issueViewFilterCount } from "@multica/core/issue-views/baseline";
+import { issueViewSeedDefinition } from "@multica/core/issue-views/definition";
+import {
+ BUILTIN_VIEW_KEYS,
+ builtinViewItemId,
+ savedViewItemId,
+ type BuiltinViewKey,
+} from "@multica/core/issue-views/sidebar-views";
+import { issueViewTarget } from "@multica/core/issue-views/view-target";
+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
+import { ActorAvatar } from "../common/actor-avatar";
+import {
+ CollectionCreateButton,
+ CollectionPageHeader,
+ CollectionScopeItems,
+} from "../layout/collection-page";
+import {
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ CollectionRowMenu,
+ type CollectionColumn,
+} from "../layout/collection-list";
+import { useT } from "../i18n";
+import { useBuiltinViewNavigation } from "./builtin-views";
+import { DeleteViewDialog } from "./delete-view-dialog";
+import { useIssueViewActions } from "./use-view-actions";
+
+type DirectoryScope = "all" | "builtin" | "mine" | "shared";
+const SCOPES: readonly DirectoryScope[] = ["all", "builtin", "mine", "shared"];
+
+const EMPTY_VIEWS: IssueView[] = [];
+const WORKSPACE_SCOPE = { scope_type: "workspace" } as const;
+
+type DirectoryRow =
+ | { kind: "builtin"; id: string; key: BuiltinViewKey; name: string }
+ | { kind: "view"; id: string; view: IssueView };
+
+const BUILTIN_ICON: Record<BuiltinViewKey, React.ReactNode> = {
+ my_issues: <CircleUser className="size-4 shrink-0 text-muted-foreground" />,
+ my_agents: <Bot className="size-4 shrink-0 text-muted-foreground" />,
+ all_issues: <ListTodo className="size-4 shrink-0 text-muted-foreground" />,
+};
+
+/** Every view the user can open, and the switch that puts it in the sidebar. */
+export function AllViewsPage() {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const userId = useAuthStore((s) => s.user?.id);
+ const actions = useIssueViewActions();
+ const builtinNav = useBuiltinViewNavigation();
+ const setActive = useActiveIssueViewStore((s) => s.setActive);
+ const { data: views = EMPTY_VIEWS } = useQuery(issueViewEverywhereOptions(wsId));
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const [scope, setScope] = useState<DirectoryScope>("all");
+ const [deleteTarget, setDeleteTarget] = useState<IssueView | null>(null);
+
+ const projectTitle = useMemo(() => new Map(projects.map((p) => [p.id, p.title])), [projects]);
+ const memberName = useMemo(() => new Map(members.map((m) => [m.user_id, m.name])), [members]);
+
+ const builtins = BUILTIN_VIEW_KEYS.map((key) => ({ key, name: t(($) => $.views.builtin[key]) }));
+ const sortedViews = useMemo(
+ () => [...views].sort((a, b) => a.name.localeCompare(b.name)),
+ [views],
+ );
+ const counts: Record<DirectoryScope, number> = {
+ all: builtins.length + views.length,
+ builtin: builtins.length,
+ mine: views.filter((view) => view.owner_id === userId).length,
+ shared: views.filter((view) => view.visibility === "workspace").length,
+ };
+
+ const shownBuiltins = scope === "all" || scope === "builtin" ? builtins : [];
+ const shownViews =
+ scope === "builtin"
+ ? []
+ : sortedViews.filter(
+ (view) =>
+ scope === "all" ||
+ (scope === "mine" ? view.owner_id === userId : view.visibility === "workspace"),
+ );
+
+ const scopeLabel: Record<DirectoryScope, string> = {
+ all: t(($) => $.views.directory.scope_all),
+ builtin: t(($) => $.views.directory.scope_builtin),
+ mine: t(($) => $.views.directory.scope_mine),
+ shared: t(($) => $.views.directory.scope_shared),
+ };
+
+ const location = (view: IssueView) => {
+ if (view.scope_type === "project") {
+ return projectTitle.get(view.scope_id ?? "") ?? t(($) => $.views.directory.location_project);
+ }
+ return view.scope_type === "my" ? t(($) => $.views.builtin.my_issues) : t(($) => $.views.builtin.all_issues);
+ };
+
+ const newView = () =>
+ actions.create({
+ scope: WORKSPACE_SCOPE,
+ scopeVariant: null,
+ definition: issueViewSeedDefinition({ query: {}, display: {} }),
+ renameIn: "header",
+ });
+
+ const rows: DirectoryRow[] = [
+ ...shownBuiltins.map(({ key, name }) => ({
+ kind: "builtin" as const,
+ id: builtinViewItemId(key),
+ key,
+ name,
+ })),
+ ...shownViews.map((view) => ({ kind: "view" as const, id: savedViewItemId(view.id), view })),
+ ];
+ const rowName = (row: DirectoryRow) => (row.kind === "builtin" ? row.name : row.view.name);
+
+ const columns: CollectionColumn<DirectoryRow>[] = [
+ {
+ key: "name",
+ header: t(($) => $.views.directory.col_name),
+ cell: (row) => (
+ <CollectionNameCell
+ icon={
+ row.kind === "builtin" ? (
+ BUILTIN_ICON[row.key]
+ ) : (
+ <Layers className="size-4 shrink-0 text-muted-foreground" />
+ )
+ }
+ title={rowName(row)}
+ />
+ ),
+ },
+ {
+ key: "location",
+ header: t(($) => $.views.directory.col_location),
+ width: 176,
+ cell: (row) =>
+ row.kind === "view" ? (
+ <span className="truncate">{location(row.view)}</span>
+ ) : (
+ <CollectionEmptyValue />
+ ),
+ },
+ {
+ key: "filters",
+ header: t(($) => $.views.directory.col_filters),
+ width: 64,
+ align: "end",
+ className: "tabular-nums",
+ cell: (row) => {
+ const count = row.kind === "view" ? issueViewFilterCount(row.view.query) : 0;
+ return count > 0 ? count : <CollectionEmptyValue />;
+ },
+ },
+ {
+ key: "visibility",
+ header: t(($) => $.views.directory.col_visibility),
+ width: 136,
+ cell: (row) => (
+ <span className="truncate">
+ {row.kind === "view" && row.view.visibility !== "workspace"
+ ? t(($) => $.views.only_me)
+ : t(($) => $.views.workspace_members)}
+ </span>
+ ),
+ },
+ {
+ key: "owner",
+ header: t(($) => $.views.directory.col_owner),
+ width: 144,
+ cell: (row) =>
+ row.kind === "builtin" ? (
+ t(($) => $.views.directory.owner_builtin)
+ ) : (
+ <>
+ <ActorAvatar actorType="member" actorId={row.view.owner_id} size="sm" />
+ <span className="min-w-0 truncate">{memberName.get(row.view.owner_id) ?? ""}</span>
+ </>
+ ),
+ },
+ {
+ key: "star",
+ width: 24,
+ core: true,
+ interactive: true,
+ cell: (row) => {
+ const name = rowName(row);
+ const starred = actions.sidebar.isStarred(row.id);
+ return (
+ <IconButton
+ label={
+ starred
+ ? t(($) => $.views.directory.unstar, { name })
+ : t(($) => $.views.directory.star, { name })
+ }
+ aria-pressed={starred}
+ size="icon-xs"
+ className={starred ? "text-warning" : "text-muted-foreground"}
+ onClick={() => (starred ? actions.sidebar.unstar(row.id) : actions.sidebar.star(row.id))}
+ >
+ <Star className={cn(starred && "fill-current")} />
+ </IconButton>
+ );
+ },
+ },
+ ];
+
+ return (
+ <div className="flex flex-1 min-h-0 flex-col">
+ <CollectionPageHeader
+ icon={Layers}
+ title={scopeLabel[scope]}
+ menu={
+ <CollectionScopeItems
+ value={scope}
+ onChange={setScope}
+ options={SCOPES.map((value) => ({ value, label: scopeLabel[value], count: counts[value] }))}
+ />
+ }
+ actions={<CollectionCreateButton label={t(($) => $.views.directory.new_view)} onClick={newView} />}
+ />
+ <CollectionList
+ label={scopeLabel[scope]}
+ columns={columns}
+ rows={rows}
+ getRowId={(row) => row.id}
+ getRowHref={(row) =>
+ row.kind === "builtin"
+ ? builtinNav.hrefFor(row.key)
+ : issueViewTarget(wsId, row.view, paths).href
+ }
+ getRowTitle={rowName}
+ onRowNavigate={(row) => {
+ if (row.kind === "builtin") builtinNav.prepare(row.key);
+ else setActive(issueViewTarget(wsId, row.view, paths).containerKey, row.view.id);
+ }}
+ rowMenu={(row) => {
+ if (row.kind !== "view") return null;
+ const { view } = row;
+ return (
+ <CollectionRowMenu
+ label={t(($) => $.views.directory.row_actions, { name: view.name })}
+ contentClassName="w-auto min-w-44"
+ >
+ <DropdownMenuItem onClick={() => actions.duplicate(view, "header")}>
+ <Copy className="size-3.5" />
+ {t(($) => $.views.duplicate)}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => actions.copyLink(issueViewTarget(wsId, view, paths).href)}
+ >
+ <Link2 className="size-3.5" />
+ {t(($) => $.views.copy_link)}
+ </DropdownMenuItem>
+ {actions.canManage(view) && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleteTarget(view)}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.views.delete)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </CollectionRowMenu>
+ );
+ }}
+ empty={t(($) => $.views.directory.no_matches)}
+ />
+ <DeleteViewDialog
+ view={deleteTarget}
+ onOpenChange={(open) => !open && setDeleteTarget(null)}
+ onConfirm={actions.remove}
+ />
+ </div>
+ );
+}
diff --git a/packages/views/issue-views/builtin-views.ts b/packages/views/issue-views/builtin-views.ts
new file mode 100644
index 0000000000..9c830b2ee1
--- /dev/null
+++ b/packages/views/issue-views/builtin-views.ts
@@ -0,0 +1,39 @@
+"use client";
+
+import { useCallback } from "react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { issueViewContainerKey, useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
+import type { BuiltinViewKey } from "@multica/core/issue-views/sidebar-views";
+
+const WORKSPACE_SCOPE = { scope_type: "workspace" } as const;
+const MY_SCOPE = { scope_type: "my" } as const;
+
+/**
+ * Where a built-in view lives, and the store write that makes its page show
+ * it rather than whichever saved view was left open.
+ */
+export function useBuiltinViewNavigation() {
+ const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
+ const setActive = useActiveIssueViewStore((s) => s.setActive);
+
+ const hrefFor = useCallback(
+ (key: BuiltinViewKey) =>
+ key === "all_issues" ? p.issues() : key === "my_agents" ? p.myAgents() : p.myIssues(),
+ [p],
+ );
+
+ const prepare = useCallback(
+ (key: BuiltinViewKey) => {
+ if (key === "all_issues") {
+ setActive(issueViewContainerKey(wsId, WORKSPACE_SCOPE), null);
+ return;
+ }
+ setActive(issueViewContainerKey(wsId, MY_SCOPE), null);
+ },
+ [setActive, wsId],
+ );
+
+ return { hrefFor, prepare };
+}
diff --git a/packages/views/issue-views/delete-view-dialog.tsx b/packages/views/issue-views/delete-view-dialog.tsx
new file mode 100644
index 0000000000..3e981f41be
--- /dev/null
+++ b/packages/views/issue-views/delete-view-dialog.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import type { IssueView } from "@multica/core/api/schemas";
+import { useT } from "../i18n";
+
+/** Deletes the view only — never the issues it lists. */
+export function DeleteViewDialog({
+ view,
+ onOpenChange,
+ onConfirm,
+}: {
+ view: IssueView | null;
+ onOpenChange: (open: boolean) => void;
+ onConfirm: (view: IssueView) => Promise<void>;
+}) {
+ const { t } = useT("issues");
+ return (
+ <AlertDialog open={!!view} onOpenChange={(open) => !open && onOpenChange(false)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.views.delete_title)}</AlertDialogTitle>
+ <AlertDialogDescription className="break-words">
+ {view?.visibility === "workspace"
+ ? t(($) => $.views.delete_description_shared, { name: view.name })
+ : t(($) => $.views.delete_description, { name: view?.name ?? "" })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.views.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ const target = view;
+ onOpenChange(false);
+ if (!target) return;
+ void onConfirm(target).then(
+ () => toast.success(t(($) => $.views.toast_deleted)),
+ () => toast.error(t(($) => $.views.toast_delete_failed)),
+ );
+ }}
+ >
+ {t(($) => $.views.delete)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/packages/views/issue-views/index.ts b/packages/views/issue-views/index.ts
new file mode 100644
index 0000000000..b7c0667b97
--- /dev/null
+++ b/packages/views/issue-views/index.ts
@@ -0,0 +1 @@
+export { AllViewsPage } from "./all-views-page";
diff --git a/packages/views/issue-views/use-view-actions.ts b/packages/views/issue-views/use-view-actions.ts
new file mode 100644
index 0000000000..9faafd63bf
--- /dev/null
+++ b/packages/views/issue-views/use-view-actions.ts
@@ -0,0 +1,179 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { ApiError } from "@multica/core/api/client";
+import type { CreateIssueViewRequest, IssueView } from "@multica/core/api/schemas";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { canManageIssueView, type IssueViewScope } from "@multica/core/issue-views/queries";
+import {
+ useCreateIssueView,
+ useDeleteIssueView,
+ useUpdateIssueView,
+} from "@multica/core/issue-views/mutations";
+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
+import { savedViewItemId, useSidebarViews } from "@multica/core/issue-views/sidebar-views";
+import { issueViewTarget } from "@multica/core/issue-views/view-target";
+import type { IssueViewDefinition } from "@multica/core/issue-views/definition";
+import {
+ useIssueViewRenameStore,
+ type IssueViewRenameSurface,
+} from "@multica/core/issue-views/rename-store";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+
+export interface CreateViewInput {
+ scope: IssueViewScope;
+ scopeVariant: CreateIssueViewRequest["scope_variant"];
+ definition: IssueViewDefinition;
+ name?: string;
+ /** Where the new view's name opens for editing. */
+ renameIn: IssueViewRenameSurface;
+}
+
+/**
+ * Every write a saved view offers, shared by the sidebar, the page header and
+ * the All views directory so each entrance behaves the same.
+ */
+export function useIssueViewActions() {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const userId = useAuthStore((s) => s.user?.id);
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const role = useMemo(
+ () => members.find((member) => member.user_id === userId)?.role ?? null,
+ [members, userId],
+ );
+ const sidebar = useSidebarViews(wsId, userId);
+ const createView = useCreateIssueView(wsId);
+ const updateView = useUpdateIssueView(wsId);
+ const deleteView = useDeleteIssueView(wsId);
+ const setActive = useActiveIssueViewStore((s) => s.setActive);
+ const startRename = useIssueViewRenameStore((s) => s.start);
+ const { star } = sidebar;
+
+ const open = useCallback(
+ (view: Pick<IssueView, "id" | "scope_type" | "scope_id">) => {
+ const target = issueViewTarget(wsId, view, paths);
+ setActive(target.containerKey, view.id);
+ if (navigation.pathname !== target.path) navigation.push(target.href);
+ },
+ [navigation, paths, setActive, wsId],
+ );
+
+ const create = useCallback(
+ ({ scope, scopeVariant, definition, name, renameIn }: CreateViewInput) => {
+ createView.mutate(
+ {
+ name: name ?? t(($) => $.views.untitled),
+ scope_type: scope.scope_type,
+ scope_id: scope.scope_type === "project" ? scope.scope_id : null,
+ scope_variant: scopeVariant ?? null,
+ visibility: "private",
+ definition_version: 1,
+ query: definition.query,
+ display: definition.display,
+ },
+ {
+ onSuccess: (created) => {
+ if (!created) return;
+ star(savedViewItemId(created.id));
+ open(created);
+ startRename(created.id, renameIn);
+ },
+ onError: () => toast.error(t(($) => $.views.toast_create_failed)),
+ },
+ );
+ },
+ [createView, open, star, startRename, t],
+ );
+
+ const update = useCallback(
+ (
+ view: IssueView,
+ patch: Partial<Pick<IssueView, "name" | "query" | "display">> & {
+ visibility?: "private" | "workspace";
+ },
+ success?: string,
+ ) => {
+ updateView.mutate(
+ { id: view.id, ...patch, expected_revision: view.revision },
+ {
+ onSuccess: () => {
+ if (success) toast.success(success);
+ },
+ onError: (err) => {
+ toast.error(
+ err instanceof ApiError && err.status === 409
+ ? t(($) => $.views.toast_conflict)
+ : t(($) => $.views.toast_save_failed),
+ );
+ },
+ },
+ );
+ },
+ [t, updateView],
+ );
+
+ return {
+ sidebar,
+ canManage: useCallback((view: IssueView) => canManageIssueView(view, userId ?? null, role), [role, userId]),
+ open,
+ create,
+ duplicate: useCallback(
+ (view: IssueView, renameIn: IssueViewRenameSurface) =>
+ create({
+ scope: issueViewTarget(wsId, view, paths).scope,
+ scopeVariant: (view.scope_variant ?? null) as CreateIssueViewRequest["scope_variant"],
+ definition: { query: view.query, display: view.display },
+ name: t(($) => $.views.copy_name, { name: view.name }),
+ renameIn,
+ }),
+ [create, paths, t, wsId],
+ ),
+ rename: useCallback(
+ (view: IssueView, name: string) => {
+ const next = name.trim();
+ if (next && next !== view.name) update(view, { name: next });
+ },
+ [update],
+ ),
+ save: useCallback(
+ (view: IssueView, definition: IssueViewDefinition) =>
+ update(view, definition, t(($) => $.views.toast_saved)),
+ [t, update],
+ ),
+ setVisibility: useCallback(
+ (view: IssueView, visibility: "private" | "workspace") => {
+ if (view.visibility !== visibility) update(view, { visibility });
+ },
+ [update],
+ ),
+ remove: useCallback(
+ (view: IssueView) =>
+ deleteView.mutateAsync(view.id).then(() => {
+ const target = issueViewTarget(wsId, view, paths);
+ const active = useActiveIssueViewStore.getState().active[target.containerKey];
+ if (active === view.id) setActive(target.containerKey, null);
+ }),
+ [deleteView, paths, setActive, wsId],
+ ),
+ copyLink: useCallback(
+ (href: string) => {
+ void copyText(navigation.getShareableUrl(href)).then((ok) => {
+ if (ok) toast.success(t(($) => $.views.link_copied));
+ });
+ },
+ [navigation, t],
+ ),
+ };
+}
+
+export type IssueViewActions = ReturnType<typeof useIssueViewActions>;
diff --git a/packages/views/issue-views/view-header.test.tsx b/packages/views/issue-views/view-header.test.tsx
new file mode 100644
index 0000000000..d59a28b201
--- /dev/null
+++ b/packages/views/issue-views/view-header.test.tsx
@@ -0,0 +1,100 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { myIssuesViewStore } from "@multica/core/issues/stores/my-issues-view-store";
+import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
+import { getIssueSurfaceViewStore } from "@multica/core/issues/stores/surface-view-store";
+import { NavigationProvider, type NavigationAdapter } from "../navigation";
+import { renderWithI18n } from "../test/i18n";
+import type { IssueSurfaceController } from "../issues/surface/use-issue-surface-controller";
+import { IssueViewHeader } from "./view-header";
+
+const copyLink = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
+});
+vi.mock("@multica/core/issue-views/use-active-view", () => ({
+ useActiveIssueView: () => ({ activeView: null, setActive: vi.fn(), missing: false }),
+}));
+vi.mock("./use-view-actions", () => ({
+ useIssueViewActions: () => ({
+ sidebar: { isStarred: () => false, star: vi.fn(), unstar: vi.fn() },
+ canManage: () => true,
+ copyLink,
+ remove: vi.fn(),
+ create: vi.fn(),
+ }),
+}));
+vi.mock("../issues/components/filter-chips-bar", () => ({
+ useFilterChips: () => ({ chips: [] }),
+}));
+vi.mock("../issues/components/issues-header", () => ({
+ IssueDisplayControls: () => null,
+ IssueFilterMenu: () => null,
+}));
+
+beforeEach(() => {
+ copyLink.mockClear();
+ myIssuesViewStore.setState({ scope: "assigned" });
+});
+
+describe("IssueViewHeader copy link", () => {
+ it.each([
+ {
+ kind: "workspace",
+ title: "All issues",
+ pathname: "/acme/issues",
+ search: "",
+ expected: "/acme/issues",
+ },
+ {
+ kind: "my",
+ title: "My Issues",
+ pathname: "/acme/my-issues",
+ search: "",
+ expected: "/acme/my-issues",
+ },
+ {
+ kind: "my",
+ title: "My agents' work",
+ pathname: "/acme/my-issues",
+ search: "scope=agents",
+ expected: "/acme/my-issues?scope=agents",
+ },
+ ] as const)("copies the URL for $title", async ({ kind, title, pathname, search, expected }) => {
+ const adapter: NavigationAdapter = {
+ pathname,
+ searchParams: new URLSearchParams(search),
+ hash: "",
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ getShareableUrl: (path) => path,
+ };
+ const controller = {
+ hasActiveFilters: false,
+ isRefreshing: false,
+ surfaceIssues: [],
+ workingAgents: [],
+ allowGantt: false,
+ facetCountsExact: false,
+ openCreateIssue: vi.fn(),
+ } as unknown as IssueSurfaceController;
+
+ renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <ViewStoreProvider store={getIssueSurfaceViewStore("header-copy-link")}>
+ <IssueViewHeader controller={controller} base={{ kind }} />
+ </ViewStoreProvider>
+ </NavigationProvider>,
+ );
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: title }));
+ await user.click(await screen.findByRole("menuitem", { name: "Copy link" }));
+ expect(copyLink).toHaveBeenCalledWith(expected);
+ });
+});
diff --git a/packages/views/issue-views/view-header.tsx b/packages/views/issue-views/view-header.tsx
new file mode 100644
index 0000000000..4484a9c97e
--- /dev/null
+++ b/packages/views/issue-views/view-header.tsx
@@ -0,0 +1,650 @@
+"use client";
+
+import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { useStore } from "zustand";
+import { toast } from "sonner";
+import {
+ ArrowLeft,
+ Bot,
+ ChevronDown,
+ CircleUser,
+ Copy,
+ Globe,
+ Layers,
+ Link2,
+ ListTodo,
+ Lock,
+ Pencil,
+ SquarePen,
+ Star,
+ EyeOff,
+ Filter,
+ ListTree,
+ Trash2,
+ Users,
+} from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { Separator } from "@multica/ui/components/ui/separator";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
+import type { CreateIssueViewRequest, IssueView } from "@multica/core/api/schemas";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";
+import type { IssueViewScope } from "@multica/core/issue-views/queries";
+import {
+ builtinViewItemId,
+ savedViewItemId,
+ type BuiltinViewKey,
+} from "@multica/core/issue-views/sidebar-views";
+import { issueViewTarget } from "@multica/core/issue-views/view-target";
+import {
+ isIssueViewModified,
+ issueViewDefinitionFromState,
+ issueViewSeedDefinition,
+ modifiedFilterDimensions,
+} from "@multica/core/issue-views/definition";
+import { useIssueViewRenameStore } from "@multica/core/issue-views/rename-store";
+import {
+ myIssuesViewStore,
+ type MyIssuesScope,
+} from "@multica/core/issues/stores/my-issues-view-store";
+import {
+ useIssuesScope,
+ useIssuesScopeStore,
+ type IssuesScope,
+} from "@multica/core/issues/stores/issues-scope-store";
+import { actorKindForViewVariant } from "@multica/core/issues/surface/scope";
+import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
+import {
+ countAdvancedConditions,
+ type NegatableFilterDimension,
+} from "@multica/core/issues/stores/filter-tree";
+import type { Project } from "@multica/core/types";
+import { PageHeader } from "../layout/page-header";
+import { RefreshablePageIcon } from "../layout/refreshable-page-icon";
+import { ActionShortcutKeycaps } from "../common/shortcut-keycaps";
+import { ProjectIcon } from "../projects/components/project-icon";
+import { IssueDisplayControls, IssueFilterMenu } from "../issues/components/issues-header";
+import { useFilterChips } from "../issues/components/filter-chips-bar";
+import { WorkspaceAgentWorkingChip } from "../issues/components/workspace-agent-working-chip";
+import type { IssueSurfaceController } from "../issues/surface/use-issue-surface-controller";
+import { useT } from "../i18n";
+import { useMyIssuesScope } from "../my-issues/use-my-issues-scope";
+import { DeleteViewDialog } from "./delete-view-dialog";
+import { useIssueViewActions } from "./use-view-actions";
+import { ViewNameInput } from "./view-name-input";
+
+/** The page a header sits on; a saved view opened there replaces its title. */
+export type IssueViewHeaderBase =
+ | { kind: "workspace" }
+ | { kind: "my" }
+ | { kind: "project"; project: Project };
+
+const ASSIGNEE_TYPES: IssuesScope[] = ["all", "members", "agents"];
+const PROJECT_HIDDEN_FIELDS: NegatableFilterDimension[] = ["project"];
+const MY_RELATIONS: Exclude<MyIssuesScope, "agents">[] = ["assigned", "created", "all"];
+const MY_SAVE_VARIANT: Record<MyIssuesScope, NonNullable<CreateIssueViewRequest["scope_variant"]>> = {
+ all: "any",
+ assigned: "assigned",
+ created: "created",
+ agents: "involved",
+};
+
+function viewScopeOf(base: IssueViewHeaderBase): IssueViewScope {
+ return base.kind === "project"
+ ? { scope_type: "project", scope_id: base.project.id }
+ : { scope_type: base.kind };
+}
+
+/**
+ * One row for every issue list page. The left side says what is being looked
+ * at: the view's name and its menu, the filter, then Reset / Save once they
+ * drift from what the view saves. The right side holds icon-only controls
+ * whose names live in their tooltips, so the title is the row's only text.
+ */
+export function IssueViewHeader({
+ controller,
+ base,
+ baseMenu,
+ trailing,
+}: {
+ controller: IssueSurfaceController;
+ base: IssueViewHeaderBase;
+ /** Name-menu items for the page itself, e.g. project actions. */
+ baseMenu?: ReactNode;
+ /** Layout toggles at the far end, e.g. the project's properties panel. */
+ trailing?: ReactNode;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const viewScope = viewScopeOf(base);
+ const { activeView, setActive, missing } = useActiveIssueView(wsId, viewScope);
+ const actions = useIssueViewActions();
+ const [deleteTarget, setDeleteTarget] = useState<IssueView | null>(null);
+ const renameTarget = useIssueViewRenameStore((s) => s.target);
+ const startRename = useIssueViewRenameStore((s) => s.start);
+ const stopRename = useIssueViewRenameStore((s) => s.stop);
+
+ useEffect(() => {
+ if (missing) {
+ setActive(null);
+ toast.info(t(($) => $.views.unavailable));
+ }
+ }, [missing, setActive, t]);
+
+ const scopePage = base.kind === "project" ? (`project:${base.project.id}` as const) : "issues";
+ const assigneeType = useIssuesScope(scopePage);
+ const setAssigneeTypeForPage = useIssuesScopeStore((s) => s.setScope);
+ const setAssigneeType = (next: IssuesScope) => setAssigneeTypeForPage(scopePage, next);
+ const myScope = useMyIssuesScope();
+ const setMyScope = useStore(myIssuesViewStore, (s) => s.setScope);
+
+ const storeApi = useViewStoreApi();
+ const state = useViewStore((s) => s);
+ const dateFilter = useViewStore((s) => s.dateFilter);
+ const setDateFilter = useViewStore((s) => s.setDateFilter);
+ const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);
+ const toggleAgentRunningFilter = useViewStore((s) => s.toggleAgentRunningFilter);
+
+ const builtinKey: BuiltinViewKey | null =
+ base.kind === "workspace" ? "all_issues" : base.kind === "my" ? (myScope === "agents" ? "my_agents" : "my_issues") : null;
+ const baseName =
+ base.kind === "project"
+ ? base.project.title
+ : t(($) => $.views.builtin[builtinKey!]);
+ const baseIcon =
+ base.kind === "project" ? (
+ <ProjectIcon project={base.project} size="sm" />
+ ) : builtinKey === "my_agents" ? (
+ <Bot className="size-4" />
+ ) : builtinKey === "my_issues" ? (
+ <CircleUser className="size-4" />
+ ) : (
+ <ListTodo className="size-4" />
+ );
+
+ const modified = activeView ? isIssueViewModified(activeView, state) : null;
+ const dirty = activeView
+ ? modified!.filters || modified!.display
+ : controller.hasActiveFilters;
+ const canManage = activeView ? actions.canManage(activeView) : false;
+ const starId = activeView ? savedViewItemId(activeView.id) : builtinKey ? builtinViewItemId(builtinKey) : null;
+ const starred = starId ? actions.sidebar.isStarred(starId) : false;
+ const renaming =
+ !!activeView && renameTarget?.surface === "header" && renameTarget.viewId === activeView.id;
+
+ const scopeVariant: CreateIssueViewRequest["scope_variant"] = activeView
+ ? ((activeView.scope_variant ?? null) as CreateIssueViewRequest["scope_variant"])
+ : base.kind === "my"
+ ? MY_SAVE_VARIANT[myScope]
+ : assigneeType === "all"
+ ? null
+ : assigneeType;
+
+ const reset = () => {
+ if (activeView) {
+ const seed = issueViewSeedDefinition(activeView);
+ storeApi.setState({ ...seed.query, ...seed.display } as Partial<typeof state>);
+ } else {
+ storeApi.getState().clearFilters();
+ }
+ setDateFilter(null);
+ if (agentRunningFilter) toggleAgentRunningFilter();
+ };
+ const saveAsNew = () =>
+ actions.create({
+ scope: viewScope,
+ scopeVariant,
+ definition: issueViewDefinitionFromState(storeApi.getState()),
+ renameIn: "header",
+ });
+
+ const assigneeTypeLabel = (value: IssuesScope) =>
+ t(($) => $.save_view[value === "all" ? "variant_all" : value === "members" ? "variant_members" : "variant_agents"]);
+ const myRelationLabel = (value: string) =>
+ t(($) =>
+ $.save_view[
+ value === "assigned"
+ ? "variant_my_assigned"
+ : value === "created"
+ ? "variant_my_created"
+ : value === "involved"
+ ? "variant_my_involved"
+ : "variant_my_any"
+ ],
+ );
+
+ // The surface's scope axis heads the filter menu: who the issues are
+ // assigned to, or how they relate to me. A saved view fixes it, so there it
+ // is a read-only row.
+ let scopeSection: ReactNode = null;
+ let scopeCounts = false;
+ if (activeView) {
+ const variant = activeView.scope_variant;
+ const fixedScope =
+ base.kind === "my"
+ ? { label: t(($) => $.save_view.scope_label_my), value: myRelationLabel(variant ?? "any") }
+ : actorKindForViewVariant(variant) !== "all"
+ ? {
+ label: t(($) => $.save_view.scope_label_workspace),
+ value: assigneeTypeLabel(actorKindForViewVariant(variant)),
+ }
+ : null;
+ if (fixedScope) {
+ scopeCounts = base.kind !== "my";
+ scopeSection = (
+ <DropdownMenuItem disabled title={t(($) => $.views.set_by_view)}>
+ <Users className="size-3.5" />
+ <span className="flex-1">{fixedScope.label}</span>
+ <span className="ml-3 text-caption font-medium text-muted-foreground">{fixedScope.value}</span>
+ </DropdownMenuItem>
+ );
+ }
+ } else if (base.kind === "my") {
+ if (myScope !== "agents") {
+ scopeSection = (
+ <ScopeSub
+ label={t(($) => $.save_view.scope_label_my)}
+ value={myScope}
+ options={MY_RELATIONS.map((value) => ({ value, label: myRelationLabel(value === "all" ? "any" : value) }))}
+ onChange={setMyScope}
+ />
+ );
+ }
+ } else {
+ scopeCounts = assigneeType !== "all";
+ scopeSection = (
+ <ScopeSub
+ label={t(($) => $.save_view.scope_label_workspace)}
+ value={assigneeType}
+ options={ASSIGNEE_TYPES.map((value) => ({ value, label: assigneeTypeLabel(value) }))}
+ onChange={setAssigneeType}
+ active={scopeCounts}
+ />
+ );
+ }
+
+ // "My issues" is already a relation to me; a second one there is noise.
+ const showRelation = base.kind !== "my";
+ const { chips: allFilterChips } = useFilterChips(dateFilter, setDateFilter);
+ const filterChips = showRelation
+ ? allFilterChips
+ : allFilterChips.filter((chip) => chip.key !== "relation");
+ // In advanced mode the trigger names the mode and counts its conditions.
+ const advancedFilter = useViewStore((s) => s.advancedFilter);
+ const advancedMode = advancedFilter !== null;
+ const filterCount =
+ filterChips.filter((chip) => chip.key !== "advanced").length +
+ countAdvancedConditions(advancedFilter) +
+ (scopeCounts ? 1 : 0);
+ const filterLabel = advancedMode ? t(($) => $.filters.advanced_title) : t(($) => $.views.filter);
+ // The trigger is an icon, so the tooltip is where the reader learns what
+ // the count is made of without opening the menu.
+ const filterFields = [
+ ...(scopeCounts ? [t(($) => $.save_view.scope_label_workspace)] : []),
+ ...filterChips.map((chip) => chip.label),
+ ];
+ const filterTooltip =
+ filterFields.length > 0
+ ? `${filterLabel} · ${filterFields.join(t(($) => $.workflows.list_separator))}`
+ : filterLabel;
+ // An idle surface has nothing to report, so the chip only takes room while
+ // someone is working or its filter is on.
+ const showAgentsChip = agentRunningFilter || (controller.workingAgents?.length ?? 0) > 0;
+ const modifiedKeys = useMemo(
+ () => (activeView && modified?.filters ? modifiedFilterDimensions(activeView, state) : undefined),
+ [activeView, modified?.filters, state],
+ );
+
+ const title = (
+ <>
+ <RefreshablePageIcon refreshing={controller.isRefreshing}>
+ {activeView ? <Layers className="size-4" /> : baseIcon}
+ </RefreshablePageIcon>
+ <span className="min-w-0 truncate">{activeView ? activeView.name : baseName}</span>
+ </>
+ );
+
+ return (
+ <PageHeader className="@container/issue-header">
+ <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-clip">
+ {renaming && activeView ? (
+ <span className="flex min-w-0 shrink-0 items-center gap-2">
+ <Layers className="size-4 shrink-0 text-muted-foreground" />
+ <ViewNameInput
+ initial={activeView.name}
+ onCommit={(name) => actions.rename(activeView, name)}
+ onDone={stopRename}
+ className="w-48"
+ />
+ </span>
+ ) : (
+ <DropdownMenu>
+ <h1 className="flex min-w-20">
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 min-w-0 max-w-64 shrink gap-2 px-2 text-body font-medium text-foreground"
+ />
+ }
+ >
+ {title}
+ <ChevronDown className="size-3 shrink-0 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ </h1>
+ <DropdownMenuContent align="start" className="w-auto min-w-52">
+ {activeView ? (
+ <>
+ <DropdownMenuGroup>
+ {canManage && (
+ <DropdownMenuItem onClick={() => startRename(activeView.id, "header")}>
+ <Pencil className="size-3.5" />
+ {t(($) => $.views.rename)}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onClick={() => actions.duplicate(activeView, "header")}>
+ <Copy className="size-3.5" />
+ {t(($) => $.views.duplicate)}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => actions.copyLink(issueViewTarget(wsId, activeView, paths).href)}
+ >
+ <Link2 className="size-3.5" />
+ {t(($) => $.views.copy_link)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ {canManage && activeView.scope_type !== "my" && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.views.visible_to)}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={activeView.visibility === "workspace" ? "workspace" : "private"}
+ onValueChange={(value) =>
+ actions.setVisibility(activeView, value as "private" | "workspace")
+ }
+ >
+ <DropdownMenuRadioItem value="private">
+ <Lock className="size-3.5" />
+ {t(($) => $.views.only_me)}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="workspace">
+ <Globe className="size-3.5" />
+ {t(($) => $.views.workspace_members)}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ </>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <StarItem starred={starred} onToggle={() => starId && (starred ? actions.sidebar.unstar(starId) : actions.sidebar.star(starId))} />
+ <DropdownMenuItem onClick={() => setActive(null)}>
+ <ArrowLeft className="size-3.5" />
+ {t(($) => $.views.back_to, { name: baseName })}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ {canManage && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleteTarget(activeView)}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.views.delete)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </>
+ ) : (
+ <>
+ {baseMenu ?? (
+ <DropdownMenuItem
+ onClick={() =>
+ actions.copyLink(
+ builtinKey === "my_agents"
+ ? paths.myAgents()
+ : base.kind === "my"
+ ? paths.myIssues()
+ : paths.issues(),
+ )
+ }
+ >
+ <Link2 className="size-3.5" />
+ {t(($) => $.views.copy_link)}
+ </DropdownMenuItem>
+ )}
+ {starId && (
+ <>
+ <DropdownMenuSeparator />
+ <StarItem starred={starred} onToggle={() => (starred ? actions.sidebar.unstar(starId) : actions.sidebar.star(starId))} />
+ </>
+ )}
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+
+ <IssueFilterMenu
+ align="start"
+ tooltip={filterTooltip}
+ trigger={
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "h-7 min-w-7 shrink-0 gap-1.5 px-1.5 text-muted-foreground",
+ filterCount > 0 && "text-foreground",
+ )}
+ aria-label={
+ filterCount > 0 && !advancedMode
+ ? t(($) => $.views.filter_count, { count: filterCount })
+ : filterLabel
+ }
+ >
+ {advancedMode ? <ListTree className="size-4" /> : <Filter className="size-4" />}
+ {filterCount > 0 && (
+ <span className="rounded-sm bg-brand/10 px-1 text-caption font-medium tabular-nums text-brand">
+ {filterCount}
+ </span>
+ )}
+ </Button>
+ }
+ leadingSections={scopeSection}
+ showRelation={showRelation}
+ hiddenFields={base.kind === "project" ? PROJECT_HIDDEN_FIELDS : undefined}
+ modifiedKeys={modifiedKeys}
+ summaryTitle={activeView?.name ?? baseName}
+ scopedIssues={controller.surfaceIssues}
+ facetCountsExact={controller.facetCountsExact}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
+ dateFilter={dateFilter}
+ onDateFilterChange={setDateFilter}
+ />
+
+ {dirty && (
+ <span className="flex shrink-0 items-center gap-1">
+ <Button variant="ghost" size="sm" className="h-7 px-2 text-muted-foreground" onClick={reset}>
+ {t(($) => $.views.reset)}
+ </Button>
+ {activeView && canManage ? (
+ <SaveSplitButton
+ viewName={activeView.name}
+ shared={activeView.visibility === "workspace"}
+ onSave={() => actions.save(activeView, issueViewDefinitionFromState(storeApi.getState()))}
+ onSaveAsNew={saveAsNew}
+ />
+ ) : (
+ <Button size="sm" className="h-7 px-2.5" onClick={saveAsNew}>
+ {activeView ? t(($) => $.views.save_as_new) : t(($) => $.views.save_as_view)}
+ </Button>
+ )}
+ </span>
+ )}
+ </div>
+
+ <div className="flex shrink-0 items-center gap-1">
+ {showAgentsChip && (
+ <WorkspaceAgentWorkingChip
+ value={agentRunningFilter}
+ onToggle={toggleAgentRunningFilter}
+ agents={controller.workingAgents}
+ compact
+ />
+ )}
+ <IssueDisplayControls
+ hideFilter
+ scopedIssues={controller.surfaceIssues}
+ allowGantt={controller.allowGantt}
+ facetCountsExact={controller.facetCountsExact}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
+ iconOnly
+ />
+ <IconButton
+ label={t(($) => $.views.new_issue)}
+ shortcut={<ActionShortcutKeycaps action="createIssue" />}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={() => controller.openCreateIssue()}
+ >
+ <SquarePen />
+ </IconButton>
+ {trailing && (
+ <>
+ <Separator orientation="vertical" className="ml-1 data-vertical:h-4 data-vertical:self-center" />
+ {trailing}
+ </>
+ )}
+ </div>
+
+ <DeleteViewDialog
+ view={deleteTarget}
+ onOpenChange={(open) => !open && setDeleteTarget(null)}
+ onConfirm={actions.remove}
+ />
+ </PageHeader>
+ );
+}
+
+function ScopeSub<T extends string>({
+ label,
+ value,
+ options,
+ onChange,
+ active = false,
+}: {
+ label: string;
+ value: T;
+ options: { value: T; label: string }[];
+ onChange: (value: T) => void;
+ /** Narrows the page beyond its default, so it reads like a filter. */
+ active?: boolean;
+}) {
+ const current = options.find((option) => option.value === value)?.label ?? value;
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Users className="size-3.5" />
+ <span className="flex-1">{label}</span>
+ <span
+ className={cn(
+ "ml-3 text-caption font-medium",
+ active ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ {current}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ <DropdownMenuRadioGroup value={value} onValueChange={(next) => onChange(next as T)}>
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
+function StarItem({ starred, onToggle }: { starred: boolean; onToggle: () => void }) {
+ const { t } = useT("issues");
+ return (
+ <DropdownMenuItem onClick={onToggle}>
+ {starred ? <EyeOff className="size-3.5" /> : <Star className="size-3.5" />}
+ {starred ? t(($) => $.views.remove_from_sidebar) : t(($) => $.views.add_to_sidebar)}
+ </DropdownMenuItem>
+ );
+}
+
+function SaveSplitButton({
+ viewName,
+ shared,
+ onSave,
+ onSaveAsNew,
+}: {
+ viewName: string;
+ shared: boolean;
+ onSave: () => void;
+ onSaveAsNew: () => void;
+}) {
+ const { t } = useT("issues");
+ return (
+ <span className="flex items-center">
+ <Button size="sm" className="h-7 rounded-r-none px-2.5" onClick={onSave}>
+ {t(($) => $.views.save)}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ size="sm"
+ className="h-7 w-6 rounded-l-none border-l border-primary-foreground/20 px-0"
+ aria-label={t(($) => $.views.save_options)}
+ />
+ }
+ >
+ <ChevronDown className="size-3" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-72">
+ <DropdownMenuItem onClick={onSave} className="items-start">
+ <span className="flex flex-col gap-0.5">
+ <span>{t(($) => $.views.save_to, { name: viewName })}</span>
+ <span className={cn("text-caption text-muted-foreground")}>
+ {shared ? t(($) => $.views.save_to_hint_shared) : t(($) => $.views.save_to_hint_private)}
+ </span>
+ </span>
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={onSaveAsNew} className="items-start">
+ <span className="flex flex-col gap-0.5">
+ <span>{t(($) => $.views.save_as_new)}</span>
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.views.save_as_new_hint, { name: viewName })}
+ </span>
+ </span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </span>
+ );
+}
diff --git a/packages/views/issue-views/view-name-input.tsx b/packages/views/issue-views/view-name-input.tsx
new file mode 100644
index 0000000000..45b513059b
--- /dev/null
+++ b/packages/views/issue-views/view-name-input.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+
+/**
+ * In-place name editor. Enter or blur commits, Escape cancels; an empty name
+ * keeps the old one.
+ */
+export function ViewNameInput({
+ initial,
+ onCommit,
+ onDone,
+ className,
+}: {
+ initial: string;
+ onCommit: (name: string) => void;
+ onDone: () => void;
+ className?: string;
+}) {
+ const { t } = useT("issues");
+ const [value, setValue] = useState(initial);
+ const ref = useRef<HTMLInputElement>(null);
+ const finished = useRef(false);
+
+ useEffect(() => {
+ ref.current?.focus();
+ ref.current?.select();
+ }, []);
+
+ const finish = (commit: boolean) => {
+ if (finished.current) return;
+ finished.current = true;
+ if (commit && value.trim()) onCommit(value);
+ onDone();
+ };
+
+ return (
+ <input
+ ref={ref}
+ value={value}
+ maxLength={80}
+ aria-label={t(($) => $.views.rename)}
+ onChange={(event) => setValue(event.target.value)}
+ onBlur={() => finish(true)}
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ if (event.key === "Enter") finish(true);
+ else if (event.key === "Escape") finish(false);
+ }}
+ onPointerDown={(event) => event.stopPropagation()}
+ className={cn(
+ "h-6 min-w-0 rounded-md border border-ring bg-background px-1.5 text-body text-foreground outline-none",
+ className,
+ )}
+ />
+ );
+}
diff --git a/packages/views/issues/components/advanced-filter-panel.tsx b/packages/views/issues/components/advanced-filter-panel.tsx
new file mode 100644
index 0000000000..e7e302bfc5
--- /dev/null
+++ b/packages/views/issues/components/advanced-filter-panel.tsx
@@ -0,0 +1,928 @@
+"use client";
+
+import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ChevronDown, Ellipsis, ListTree, Plus, SlidersHorizontal } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { cn } from "@multica/ui/lib/utils";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import {
+ ADVANCED_FILTER_MAX_CONDITIONS,
+ advancedFilterConditionSlots,
+ createFilterCondition,
+ createFilterGroup,
+ editAdvancedFilter,
+ isPropertyCondition,
+ propertyFilterField,
+ propertyIdOfField,
+ pruneAdvancedFilter,
+ simpleFromAdvancedFilter,
+ type AdvancedFilterCondition,
+ type AdvancedFilterField,
+ type AdvancedFilterGroup,
+ type AdvancedFilterNode,
+ type DimensionFilterCondition,
+ type NegatableFilterDimension,
+ type PropertyFilterCondition,
+} from "@multica/core/issues/stores/filter-tree";
+import {
+ conditionOperator,
+ conditionText,
+ filterFieldSpec,
+ filterOperatorsFor,
+ isEmptinessOperator,
+ isTypedValueKind,
+ withConditionOperator,
+ withConditionText,
+ type FilterFieldKind,
+ type FilterOperator,
+} from "@multica/core/issues/stores/filter-operators";
+import { useViewStore } from "@multica/core/issues/stores/view-store-context";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { propertyListOptions } from "@multica/core/properties";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import {
+ isActorPropertyType,
+ isFilterablePropertyType,
+ PROPERTY_FILTER_OP_SYMBOLS,
+ propertyFilterValueKey,
+ type IssueProperty,
+ type PropertyFilterValue,
+} from "@multica/core/types";
+import { useT } from "../../i18n";
+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
+import { PropertyIcon } from "../../common/property-icon";
+import { buildChipActorNames, summarize } from "./filter-chips-bar";
+import { PropertyFilterOptions, usePropertyValueName } from "./property-filter-options";
+import {
+ FILTER_FIELD_ICONS,
+ matchesFilterQuery,
+ useFilterFieldLabels,
+ useFilterValueCatalog,
+ type FilterValueOption,
+} from "./filter-field-options";
+
+/** Navigation keys move into the list; everything else stays in the input
+ * instead of feeding the menu's typeahead. */
+export function stopMenuSearchKeys(event: React.KeyboardEvent) {
+ if (["Escape", "Tab", "ArrowDown", "ArrowUp"].includes(event.key)) return;
+ event.stopPropagation();
+}
+
+type Catalog = (field: NegatableFilterDimension) => FilterValueOption[];
+
+const CONNECTOR_CLASS = "flex h-7 w-14 shrink-0 items-center text-caption text-muted-foreground";
+const ROW_SELECT_CLASS = "h-7 rounded-md text-caption";
+const VALUE_TRIGGER_CLASS =
+ "flex h-7 min-w-0 flex-1 items-center gap-1.5 rounded-md border border-input px-2 text-left text-caption outline-none hover:bg-accent/50 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 dark:bg-input/30";
+
+interface FieldOption {
+ field: AdvancedFilterField;
+ label: string;
+ icon: ReactNode;
+}
+
+/** What a condition can test: the surface's built-in fields, then every
+ * filterable custom property. */
+interface ConditionFields {
+ builtIn: FieldOption[];
+ properties: FieldOption[];
+ propertyById: ReadonlyMap<string, IssueProperty>;
+ /** Label and icon for any stored field, including a hidden or deleted one. */
+ describe: (field: AdvancedFilterField) => FieldOption;
+}
+
+function useConditionFields(fields: readonly NegatableFilterDimension[]): ConditionFields {
+ const { t } = useT("issues");
+ const labels = useFilterFieldLabels();
+ const wsId = useWorkspaceId();
+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
+ const unknownLabel = t(($) => $.filters.advanced_unknown_property);
+ return useMemo(() => {
+ const dimension = (field: NegatableFilterDimension): FieldOption => {
+ const Icon = FILTER_FIELD_ICONS[field];
+ return { field, label: labels[field], icon: <Icon className="size-3.5 text-muted-foreground" /> };
+ };
+ const property = (p: IssueProperty): FieldOption => ({
+ field: propertyFilterField(p.id),
+ label: p.name,
+ icon: p.icon ? (
+ <PropertyIcon property={p} className="size-3.5 text-caption" />
+ ) : (
+ <SlidersHorizontal className="size-3.5 text-muted-foreground" />
+ ),
+ });
+ const filterable = workspaceProperties.filter((p) => isFilterablePropertyType(p.type));
+ const propertyById = new Map(filterable.map((p) => [p.id, p]));
+ return {
+ builtIn: fields.map(dimension),
+ properties: filterable.map(property),
+ propertyById,
+ describe: (field) => {
+ const propertyId = propertyIdOfField(field);
+ if (propertyId === null) return dimension(field as NegatableFilterDimension);
+ const known = propertyById.get(propertyId);
+ return known
+ ? property(known)
+ : { field, label: unknownLabel, icon: <SlidersHorizontal className="size-3.5 text-muted-foreground" /> };
+ },
+ };
+ }, [fields, labels, workspaceProperties, unknownLabel]);
+}
+
+function FieldPickerMenu({
+ fields,
+ trigger,
+ heading,
+ defaultOpen,
+ onOpenChange,
+ onPick,
+}: {
+ fields: ConditionFields;
+ trigger: React.ReactElement;
+ heading?: string;
+ /** Open as soon as it mounts: the menu of a group just created. */
+ defaultOpen?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ onPick: (field: AdvancedFilterField) => void;
+}) {
+ const item = (option: FieldOption) => (
+ <DropdownMenuItem key={option.field} onClick={() => onPick(option.field)}>
+ {option.icon}
+ <span className="truncate">{option.label}</span>
+ </DropdownMenuItem>
+ );
+ return (
+ <DropdownMenu defaultOpen={defaultOpen} onOpenChange={(open) => onOpenChange?.(open)}>
+ <DropdownMenuTrigger render={trigger} />
+ <DropdownMenuContent align="start" className="w-52">
+ {heading && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{heading}</DropdownMenuLabel>
+ </DropdownMenuGroup>
+ )}
+ {fields.builtIn.map(item)}
+ {fields.properties.length > 0 && <DropdownMenuSeparator />}
+ {fields.properties.map(item)}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function MatchSelect({
+ value,
+ onChange,
+ className,
+}: {
+ value: "all" | "any";
+ onChange: (value: "all" | "any") => void;
+ className?: string;
+}) {
+ const { t } = useT("issues");
+ const items = [
+ { value: "all", label: t(($) => $.filters.match_all) },
+ { value: "any", label: t(($) => $.filters.match_any) },
+ ];
+ return (
+ <Select
+ items={items}
+ value={value}
+ onValueChange={(next) => {
+ if (next === "all" || next === "any") onChange(next);
+ }}
+ >
+ <SelectTrigger size="sm" className={cn(ROW_SELECT_CLASS, "w-auto", className)}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false} align="start">
+ {items.map((item) => (
+ <SelectItem key={item.value} value={item.value} className="text-caption">
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function useJoinWord() {
+ const { t } = useT("issues");
+ return (match: "all" | "any") =>
+ match === "any" ? t(($) => $.filters.advanced_or) : t(($) => $.filters.advanced_and);
+}
+
+/** "Where" before the first row, then the word the group's match joins rows
+ * with. The word is chosen in the group's header, not on a row. */
+function RowConnector({ index, match }: { index: number; match: "all" | "any" }) {
+ const { t } = useT("issues");
+ const joinWord = useJoinWord();
+ return (
+ <span className={CONNECTOR_CLASS}>
+ {index === 0 ? t(($) => $.filters.advanced_where) : joinWord(match)}
+ </span>
+ );
+}
+
+function useOperatorLabel() {
+ const { t } = useT("issues");
+ return (op: FilterOperator, kind: FilterFieldKind): string => {
+ const set = kind === "multi" || kind === "list";
+ switch (op) {
+ case "is":
+ if (kind === "number") return "=";
+ return set ? t(($) => $.filters.operator_has_any) : t(($) => $.filters.operator_is);
+ case "is_not":
+ if (kind === "number") return "≠";
+ return set ? t(($) => $.filters.operator_has_none) : t(($) => $.filters.operator_is_not);
+ case "contains":
+ return t(($) => $.filters.operator_contains);
+ case "not_contains":
+ return t(($) => $.filters.operator_not_contains);
+ case "before":
+ return t(($) => $.filters.operator_before);
+ case "after":
+ return t(($) => $.filters.operator_after);
+ case "is_empty":
+ return t(($) => $.filters.operator_empty);
+ case "is_not_empty":
+ return t(($) => $.filters.operator_not_empty);
+ default:
+ return PROPERTY_FILTER_OP_SYMBOLS[op] ?? op;
+ }
+ };
+}
+
+/** A typed value (text, number, date, list element), committed on Enter or
+ * blur so each keystroke doesn't refetch. */
+function TypedValueInput({
+ kind,
+ value,
+ onCommit,
+}: {
+ kind: FilterFieldKind;
+ value: string;
+ onCommit: (text: string) => void;
+}) {
+ const { t } = useT("issues");
+ const [draft, setDraft] = useState(value);
+ useEffect(() => setDraft(value), [value]);
+ const commit = () => {
+ if (draft.trim() !== value) onCommit(draft);
+ };
+ return (
+ <Input
+ type={kind === "number" ? "number" : kind === "date" ? "date" : "text"}
+ step={kind === "number" ? "any" : undefined}
+ inputMode={kind === "number" ? "decimal" : undefined}
+ aria-label={t(($) => $.filters.advanced_values_label)}
+ placeholder={
+ kind === "number"
+ ? t(($) => $.pickers.custom_property.number_placeholder)
+ : t(($) => $.pickers.custom_property.value_placeholder)
+ }
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") commit();
+ }}
+ className="h-7 min-w-0 flex-1 rounded-md px-2 text-caption md:text-caption"
+ />
+ );
+}
+
+function ValuePicker({
+ condition,
+ catalog,
+ onChange,
+}: {
+ condition: DimensionFilterCondition;
+ catalog: Catalog;
+ onChange: (values: string[]) => void;
+}) {
+ const { t } = useT("issues");
+ const [search, setSearch] = useState("");
+ const options = catalog(condition.field);
+ const query = search.trim().toLowerCase();
+ const visible = options.filter((option) => matchesFilterQuery(option.label, query));
+ const selected = options.filter((option) => condition.values.includes(option.value));
+ const toggle = (value: string) =>
+ onChange(
+ condition.values.includes(value)
+ ? condition.values.filter((v) => v !== value)
+ : [...condition.values, value],
+ );
+ const [first] = selected;
+ const summary =
+ condition.values.length === 0
+ ? null
+ : first
+ ? condition.values.length > 1
+ ? `${first.label} +${condition.values.length - 1}`
+ : first.label
+ : String(condition.values.length);
+
+ let lastGroup: string | undefined;
+ return (
+ <DropdownMenu onOpenChange={(open) => !open && setSearch("")}>
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ aria-label={t(($) => $.filters.advanced_values_label)}
+ className={VALUE_TRIGGER_CLASS}
+ />
+ }
+ >
+ {selected.slice(0, 3).map((option) => (
+ <span key={option.value} className="flex shrink-0 items-center">
+ {option.icon}
+ </span>
+ ))}
+ <span className={cn("min-w-0 flex-1 truncate", summary ? "font-medium" : "text-muted-foreground")}>
+ {summary ?? t(($) => $.filters.advanced_values_placeholder)}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-64 p-0">
+ <div className="border-b border-foreground/5 px-2 py-1.5">
+ <input
+ type="text"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ onKeyDown={stopMenuSearchKeys}
+ placeholder={t(($) => $.filters.placeholder)}
+ className="w-full bg-transparent text-body outline-none placeholder:text-muted-foreground"
+ autoFocus
+ />
+ </div>
+ <div className="max-h-64 overflow-y-auto p-1">
+ {visible.map((option) => {
+ const checked = condition.values.includes(option.value);
+ const heading =
+ option.group && option.group !== lastGroup ? option.group : undefined;
+ lastGroup = option.group;
+ return (
+ <div key={option.value}>
+ {heading && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{heading}</DropdownMenuLabel>
+ </DropdownMenuGroup>
+ )}
+ <DropdownMenuCheckboxItem
+ checked={checked}
+ onCheckedChange={() => toggle(option.value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ {option.icon}
+ <span className="truncate">{option.label}</span>
+ </DropdownMenuCheckboxItem>
+ </div>
+ );
+ })}
+ {visible.length === 0 && (
+ <div className="px-2 py-3 text-center text-body text-muted-foreground">
+ {t(($) => $.filters.no_results)}
+ </div>
+ )}
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/** A property condition edits its values with the property's own options:
+ * option checkboxes, operator + value for scalars, and "No value". */
+function PropertyValuePicker({
+ condition,
+ property,
+ onChange,
+}: {
+ condition: PropertyFilterCondition;
+ property: IssueProperty | undefined;
+ onChange: (values: PropertyFilterValue[]) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { data: members = [] } = useQuery({
+ ...memberListOptions(wsId),
+ enabled: !!property && isActorPropertyType(property.type),
+ });
+ const actorName = useMemo(() => buildChipActorNames(members, [], []), [members]);
+ const valueName = usePropertyValueName(actorName);
+ const summary =
+ condition.values.length === 0
+ ? null
+ : summarize(condition.values.map((value) => (property ? valueName(property, value) : undefined)));
+ const toggle = (value: string) =>
+ onChange(
+ condition.values.some((v) => propertyFilterValueKey(v) === value)
+ ? condition.values.filter((v) => propertyFilterValueKey(v) !== value)
+ : [...condition.values, value],
+ );
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={!property}
+ render={
+ <button
+ type="button"
+ aria-label={t(($) => $.filters.advanced_values_label)}
+ className={VALUE_TRIGGER_CLASS}
+ />
+ }
+ >
+ <span className={cn("min-w-0 flex-1 truncate", summary ? "font-medium" : "text-muted-foreground")}>
+ {summary ?? t(($) => $.filters.advanced_values_placeholder)}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ {property && (
+ <DropdownMenuContent align="start" className="max-h-80 w-auto min-w-52">
+ <PropertyFilterOptions
+ property={property}
+ counts={undefined}
+ selected={condition.values}
+ onToggle={toggle}
+ onSetValues={onChange}
+ />
+ </DropdownMenuContent>
+ )}
+ </DropdownMenu>
+ );
+}
+
+function RowActions({ children }: { children: ReactNode }) {
+ const { t } = useT("issues");
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.filters.advanced_actions)}
+ className="size-7 shrink-0 text-muted-foreground"
+ />
+ }
+ >
+ <Ellipsis className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ {children}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function ConditionRow({
+ condition,
+ fields,
+ catalog,
+ canAdd,
+ onEdit,
+ onTurnIntoGroup,
+}: {
+ condition: AdvancedFilterCondition;
+ fields: ConditionFields;
+ catalog: Catalog;
+ canAdd: boolean;
+ onEdit: (edit: (node: AdvancedFilterNode) => AdvancedFilterNode[]) => void;
+ /** Only rows directly under the root can become a group. */
+ onTurnIntoGroup?: () => void;
+}) {
+ const { t } = useT("issues");
+ const operatorLabel = useOperatorLabel();
+ const current = fields.describe(condition.field);
+ // A stored condition on a field this surface hides (or a deleted property)
+ // still renders, so it can be seen and removed.
+ const known = [...fields.builtIn, ...fields.properties].some((o) => o.field === condition.field);
+ const fieldItems = [...fields.builtIn, ...fields.properties, ...(known ? [] : [current])];
+ const property = isPropertyCondition(condition)
+ ? fields.propertyById.get(propertyIdOfField(condition.field) ?? "")
+ : undefined;
+ const spec = filterFieldSpec(condition, property?.type);
+ // The operator the row last showed. An operator stored in the values
+ // ("contains", "> 3") is lost while the value is empty, and picking only
+ // "No value" under "is" reads back as "is empty"; either way the row keeps
+ // what the user chose instead of swapping its editor mid-edit.
+ const [pendingOp, setPendingOp] = useState<FilterOperator | null>(null);
+ const derived = conditionOperator(condition, spec);
+ const operator =
+ pendingOp &&
+ (condition.values.length === 0 ||
+ (isEmptinessOperator(derived) && (pendingOp === "is" || pendingOp === "is_not")))
+ ? pendingOp
+ : derived;
+ const operators = filterOperatorsFor(spec);
+ if (!operators.includes(operator)) operators.push(operator);
+ const operatorItems = operators.map((op) => ({ value: op, label: operatorLabel(op, spec.kind) }));
+ const replace = (next: AdvancedFilterCondition) => onEdit(() => [next]);
+ const setValues = (next: AdvancedFilterCondition) => {
+ setPendingOp(operator);
+ replace(next);
+ };
+ const fieldItem = (option: FieldOption) => (
+ <SelectItem key={option.field} value={option.field} className="text-caption">
+ {option.icon}
+ <span className="truncate">{option.label}</span>
+ </SelectItem>
+ );
+ return (
+ <>
+ <Select
+ items={fieldItems.map((option) => ({ value: option.field, label: option.label }))}
+ value={condition.field}
+ onValueChange={(next) => {
+ if (next && next !== condition.field) {
+ setPendingOp(null);
+ replace({ ...condition, field: next, values: [], negated: false } as AdvancedFilterCondition);
+ }
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label={t(($) => $.filters.advanced_field_label)}
+ className={cn(ROW_SELECT_CLASS, "w-36 shrink-0")}
+ >
+ {current.icon}
+ <SelectValue className="truncate" />
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false} align="start" className="max-h-80">
+ {fields.builtIn.map(fieldItem)}
+ {fields.properties.length > 0 && <SelectSeparator />}
+ {fields.properties.map(fieldItem)}
+ {!known && fieldItem(current)}
+ </SelectContent>
+ </Select>
+ <Select
+ items={operatorItems}
+ value={operator}
+ onValueChange={(next) => {
+ const op = next as FilterOperator;
+ setPendingOp(op);
+ replace(withConditionOperator(condition, spec, op));
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label={t(($) => $.filters.operator_label)}
+ className={cn(ROW_SELECT_CLASS, "w-32 shrink-0")}
+ >
+ <SelectValue className="truncate" />
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false} align="start">
+ {operatorItems.map((item) => (
+ <SelectItem key={item.value} value={item.value} className="text-caption">
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {isEmptinessOperator(operator) ? (
+ <span className="min-w-0 flex-1" />
+ ) : isTypedValueKind(spec.kind) ? (
+ <TypedValueInput
+ kind={spec.kind}
+ value={conditionText(condition)}
+ onCommit={(text) => setValues(withConditionText(condition, operator, text))}
+ />
+ ) : isPropertyCondition(condition) ? (
+ <PropertyValuePicker
+ condition={condition}
+ property={property}
+ onChange={(values) => setValues({ ...condition, values })}
+ />
+ ) : (
+ <ValuePicker condition={condition} catalog={catalog} onChange={(values) => setValues({ ...condition, values })} />
+ )}
+ <RowActions>
+ {onTurnIntoGroup && (
+ <DropdownMenuItem onClick={onTurnIntoGroup}>{t(($) => $.filters.advanced_turn_into_group)}</DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ disabled={!canAdd}
+ onClick={() =>
+ onEdit((node) => [
+ node,
+ createFilterCondition(condition.field, [...condition.values], condition.negated),
+ ])
+ }
+ >
+ {t(($) => $.filters.advanced_duplicate)}
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="destructive" onClick={() => onEdit(() => [])}>
+ {t(($) => $.filters.advanced_delete)}
+ </DropdownMenuItem>
+ </RowActions>
+ </>
+ );
+}
+
+function AddButton({ children, ...props }: React.ComponentProps<typeof Button>) {
+ return (
+ <Button variant="ghost" size="sm" className="h-7 gap-1.5 px-2 text-caption text-muted-foreground" {...props}>
+ <Plus className="size-3.5" />
+ {children}
+ </Button>
+ );
+}
+
+/** A condition as a phrase: "Label includes any of Bug +1". */
+function useConditionPhrase(fields: ConditionFields, catalog: Catalog) {
+ const operatorLabel = useOperatorLabel();
+ const wsId = useWorkspaceId();
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const actorName = useMemo(() => buildChipActorNames(members, [], []), [members]);
+ const valueName = usePropertyValueName(actorName);
+ return (condition: AdvancedFilterCondition): string => {
+ const property = isPropertyCondition(condition)
+ ? fields.propertyById.get(propertyIdOfField(condition.field) ?? "")
+ : undefined;
+ const spec = filterFieldSpec(condition, property?.type);
+ const op = conditionOperator(condition, spec);
+ const head = `${fields.describe(condition.field).label} ${operatorLabel(op, spec.kind)}`;
+ if (isEmptinessOperator(op)) return head;
+ let value: string;
+ if (isTypedValueKind(spec.kind)) {
+ value = conditionText(condition);
+ } else if (isPropertyCondition(condition)) {
+ value = summarize(condition.values.map((v) => (property ? valueName(property, v) : undefined)));
+ } else {
+ const options = catalog(condition.field);
+ value = summarize(condition.values.map((v) => options.find((option) => option.value === v)?.label));
+ }
+ return `${head} ${value}`;
+ };
+}
+
+/** A pruned tree as one sentence, a group in parentheses. */
+function describeGroup(
+ group: AdvancedFilterGroup,
+ phrase: (condition: AdvancedFilterCondition) => string,
+ joinWord: (match: "all" | "any") => string,
+ nested = false,
+): string {
+ const parts = group.children.map((child) =>
+ child.type === "group" ? describeGroup(child, phrase, joinWord, true) : phrase(child),
+ );
+ const text = parts.join(` ${joinWord(group.match)} `);
+ return nested && parts.length > 1 ? `(${text})` : text;
+}
+
+/** A group under the root: its own match in the header, then its rows. An
+ * empty group is a slot to add the first condition into. */
+function FilterGroupCard({
+ group,
+ fields,
+ catalog,
+ canAdd,
+ openAddMenu,
+ onAddMenuClosed,
+ edit,
+ onAppend,
+ onMatchChange,
+ onDelete,
+}: {
+ group: AdvancedFilterGroup;
+ fields: ConditionFields;
+ catalog: Catalog;
+ canAdd: boolean;
+ openAddMenu: boolean;
+ onAddMenuClosed: () => void;
+ edit: (id: string) => (fn: (node: AdvancedFilterNode) => AdvancedFilterNode[]) => void;
+ onAppend: (node: AdvancedFilterNode) => void;
+ onMatchChange: (match: "all" | "any") => void;
+ onDelete: () => void;
+}) {
+ const { t } = useT("issues");
+ const joinWord = useJoinWord();
+ const addMenu = (
+ <FieldPickerMenu
+ fields={fields}
+ heading={t(($) => $.filters.advanced_add_to_group)}
+ defaultOpen={openAddMenu && canAdd}
+ onOpenChange={(open) => {
+ if (!open) onAddMenuClosed();
+ }}
+ trigger={<AddButton disabled={!canAdd}>{t(($) => $.filters.advanced_add_condition)}</AddButton>}
+ onPick={(field) => {
+ onAddMenuClosed();
+ onAppend(createFilterCondition(field));
+ }}
+ />
+ );
+ return (
+ <div
+ className="flex min-w-0 flex-1 flex-col gap-1.5 rounded-lg border border-border bg-muted/40 p-2"
+ data-testid="advanced-filter-group"
+ >
+ <div className="flex items-center gap-1.5">
+ <span className="pl-1 text-caption text-muted-foreground">
+ {t(($) => $.filters.advanced_group_match_leading)}
+ </span>
+ <MatchSelect value={group.match} onChange={onMatchChange} />
+ <span className="min-w-0 flex-1 truncate text-caption text-muted-foreground">
+ {t(($) => $.filters.advanced_group_match_trailing)}
+ </span>
+ <RowActions>
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ {t(($) => $.filters.advanced_delete_group)}
+ </DropdownMenuItem>
+ </RowActions>
+ </div>
+ {group.children.length === 0 ? (
+ <div className="flex items-center gap-2 rounded-md border border-dashed border-border p-0.5">
+ {addMenu}
+ <span className="min-w-0 truncate text-caption text-muted-foreground">
+ {t(($) => $.filters.advanced_group_hint, { word: joinWord(group.match) })}
+ </span>
+ </div>
+ ) : (
+ <>
+ {group.children.map((child, index) =>
+ child.type === "condition" ? (
+ <div key={child.id} className="flex items-start gap-1.5">
+ <RowConnector index={index} match={group.match} />
+ <ConditionRow
+ condition={child}
+ fields={fields}
+ catalog={catalog}
+ canAdd={canAdd}
+ onEdit={edit(child.id)}
+ />
+ </div>
+ ) : null,
+ )}
+ <div>{addMenu}</div>
+ </>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The advanced filter: a rule list with "all" / "any" and one level of
+ * groups, edited in place on the view store. Edits apply live, like the
+ * simple menu; rows without values filter nothing until they get one.
+ */
+export function AdvancedFilterPanel({
+ fields: surfaceFields,
+}: {
+ /** Fields the surface offers; a scope that fixes one leaves it out. */
+ fields: readonly NegatableFilterDimension[];
+}) {
+ const { t } = useT("issues");
+ const stored = useViewStore((s) => s.advancedFilter);
+ const setAdvancedFilter = useViewStore((s) => s.setAdvancedFilter);
+ const exitAdvancedFilter = useViewStore((s) => s.exitAdvancedFilter);
+ const emptyRoot = useMemo(() => createFilterGroup(), []);
+ const root = stored ?? emptyRoot;
+ const catalog = useFilterValueCatalog(true);
+ const fields = useConditionFields(surfaceFields);
+ const canAdd = advancedFilterConditionSlots(root) < ADVANCED_FILTER_MAX_CONDITIONS;
+ const representable = simpleFromAdvancedFilter(root) !== null;
+
+ const edit = (id: string) => (fn: (node: AdvancedFilterNode) => AdvancedFilterNode[]) =>
+ setAdvancedFilter(editAdvancedFilter(root, id, fn));
+ const append = (groupId: string, node: AdvancedFilterNode) =>
+ edit(groupId)((group) => [
+ { ...(group as AdvancedFilterGroup), children: [...(group as AdvancedFilterGroup).children, node] },
+ ]);
+ const setMatch = (groupId: string) => (match: "all" | "any") =>
+ edit(groupId)((group) => [{ ...(group as AdvancedFilterGroup), match }]);
+ // The group whose add menu opens as it mounts: one just created or just
+ // made from a row. Cleared once a menu closes, so a remount stays shut.
+ const [openGroupId, setOpenGroupId] = useState<string | null>(null);
+ // A group is usually the other word: "and" rules holding an "or".
+ const newGroup = (children: AdvancedFilterNode[] = []) =>
+ createFilterGroup(root.match === "all" ? "any" : "all", children);
+ const phrase = useConditionPhrase(fields, catalog);
+ const joinWord = useJoinWord();
+ const pruned = pruneAdvancedFilter(root);
+ const summary = pruned?.children.some((child) => child.type === "group")
+ ? describeGroup(pruned, phrase, joinWord)
+ : null;
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-1.5 px-3 pt-3 pb-2">
+ <ListTree className="size-3.5 text-muted-foreground" />
+ <span className="font-medium">{t(($) => $.filters.advanced_title)}</span>
+ <span className="ml-2 text-caption text-muted-foreground">
+ {t(($) => $.filters.advanced_match_leading)}
+ </span>
+ <MatchSelect value={root.match} onChange={setMatch(root.id)} />
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.filters.advanced_match_trailing)}
+ </span>
+ </div>
+
+ <div className="flex max-h-[60vh] flex-col gap-1.5 overflow-y-auto px-3 py-1">
+ {root.children.length === 0 && (
+ <p className="py-3 text-caption text-muted-foreground">{t(($) => $.filters.advanced_empty)}</p>
+ )}
+ {root.children.map((child, index) => (
+ <div key={child.id} className="flex items-start gap-1.5" data-testid="advanced-filter-row">
+ <RowConnector index={index} match={root.match} />
+ {child.type === "condition" ? (
+ <ConditionRow
+ condition={child}
+ fields={fields}
+ catalog={catalog}
+ canAdd={canAdd}
+ onEdit={edit(child.id)}
+ onTurnIntoGroup={() => {
+ const group = newGroup([child]);
+ edit(child.id)(() => [group]);
+ setOpenGroupId(group.id);
+ }}
+ />
+ ) : (
+ <FilterGroupCard
+ group={child}
+ fields={fields}
+ catalog={catalog}
+ canAdd={canAdd}
+ openAddMenu={openGroupId === child.id}
+ onAddMenuClosed={() => setOpenGroupId(null)}
+ edit={edit}
+ onAppend={(node) => append(child.id, node)}
+ onMatchChange={setMatch(child.id)}
+ onDelete={() => edit(child.id)(() => [])}
+ />
+ )}
+ </div>
+ ))}
+ {summary && (
+ <p className="pt-1 text-caption text-pretty text-muted-foreground" data-testid="advanced-filter-summary">
+ {t(($) => $.filters.advanced_summary, { summary })}
+ </p>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1 px-2 py-1.5">
+ <FieldPickerMenu
+ fields={fields}
+ trigger={<AddButton disabled={!canAdd}>{t(($) => $.filters.advanced_add_condition)}</AddButton>}
+ onPick={(field) => append(root.id, createFilterCondition(field))}
+ />
+ <AddButton
+ disabled={!canAdd}
+ onClick={() => {
+ const group = newGroup();
+ append(root.id, group);
+ setOpenGroupId(group.id);
+ }}
+ >
+ {t(($) => $.filters.advanced_add_group)}
+ </AddButton>
+ </div>
+
+ <div className="flex items-center gap-2 border-t border-border px-2 py-1.5">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 shrink-0 px-2 text-caption"
+ disabled={!representable}
+ onClick={exitAdvancedFilter}
+ >
+ {t(($) => $.filters.advanced_to_simple)}
+ </Button>
+ {!representable && (
+ <span className="min-w-0 truncate text-caption text-muted-foreground" title={t(($) => $.filters.advanced_to_simple_blocked)}>
+ {t(($) => $.filters.advanced_to_simple_blocked)}
+ </span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto h-7 shrink-0 px-2 text-caption text-muted-foreground"
+ disabled={root.children.length === 0}
+ onClick={() => setAdvancedFilter(createFilterGroup(root.match))}
+ >
+ {t(($) => $.filters.advanced_clear)}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index 7b32087806..e4e80e99b2 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -1,8 +1,7 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import { AnimatePresence, motion, useReducedMotion } from "motion/react";
-import { X, Trash2 } from "@multica/ui/icons";
+import { Trash2 } from "@multica/ui/icons";
import { toast } from "sonner";
import { Button } from "@multica/ui/components/ui/button";
import {
@@ -25,11 +24,7 @@ import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues
import { useModalStore } from "@multica/core/modals";
import { StatusPicker, PriorityPicker, AssigneePicker } from "./pickers";
import { useT } from "../../i18n";
-import { cn } from "@multica/ui/lib/utils";
-import {
- UI_EASE_OUT,
- UI_MOTION_DURATION,
-} from "@multica/ui/lib/motion";
+import { CollectionBatchBar } from "../../layout/collection-list";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
import { useIssueSurfaceSelection } from "../surface/selection-context";
import { useRegisterCommandBarContext } from "../../search/register-context";
@@ -66,7 +61,6 @@ export function BatchActionToolbar({
const selection = useIssueSurfaceSelection();
const selectedIds = selection.selectedIds;
const clear = selection.clear;
- const shouldReduceMotion = useReducedMotion() ?? false;
// The authoritative selection is selectedIds ∩ the visible universe. Acting
// on raw selectedIds while other consumers (Export selected, common fields)
@@ -208,57 +202,12 @@ export function BatchActionToolbar({
return (
<>
- <AnimatePresence initial={false}>
- {count > 0 && (
- <div
- key="issue-batch-toolbar"
- className={cn(
- "z-50",
- placement === "fixed-bottom"
- ? "fixed bottom-6 left-1/2 -translate-x-1/2 max-md:above-chat-launcher"
- : "mb-2 w-fit",
- )}
- >
- <motion.div
- className="flex items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg"
- initial={{
- opacity: 0,
- transform: shouldReduceMotion
- ? "translateY(0)"
- : "translateY(8px)",
- }}
- animate={{
- opacity: 1,
- transform: "translateY(0)",
- transition: {
- duration: UI_MOTION_DURATION.fast,
- ease: UI_EASE_OUT,
- },
- }}
- exit={{
- opacity: 0,
- transform: shouldReduceMotion
- ? "translateY(0)"
- : "translateY(8px)",
- transition: {
- duration: shouldReduceMotion
- ? UI_MOTION_DURATION.fast
- : UI_MOTION_DURATION.micro,
- ease: UI_EASE_OUT,
- },
- }}
- >
- <div className="flex items-center gap-1.5 pl-1 pr-2 border-r mr-1">
- <span className="text-body font-medium">{t(($) => $.batch.selected, { count })}</span>
- <button
- type="button"
- onClick={clear}
- className="rounded-xs p-0.5 hover:bg-accent transition-colors"
- >
- <X className="size-3.5 text-muted-foreground" />
- </button>
- </div>
-
+ <CollectionBatchBar
+ count={count}
+ onClear={clear}
+ placement={placement === "fixed-bottom" ? "fixed" : "inline"}
+ label={t(($) => $.batch.selected, { count })}
+ >
{/* Status */}
<StatusPicker
status={common.status}
@@ -309,10 +258,7 @@ export function BatchActionToolbar({
<Trash2 className="size-3.5 mr-1" />
{t(($) => $.batch.delete)}
</Button>
- </motion.div>
- </div>
- )}
- </AnimatePresence>
+ </CollectionBatchBar>
{count > 0 && <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index 99c8f3cf74..6de552641e 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -191,7 +191,9 @@ export const BoardColumn = memo(function BoardColumn({
issue={issue}
childProgress={childProgressMap?.get(issue.id)}
project={
- issue.project_id ? projectMap?.get(issue.project_id) : undefined
+ issue.project_id && issue.project_id !== projectId
+ ? projectMap?.get(issue.project_id)
+ : undefined
}
disableSorting={!!sortLabel}
/>
diff --git a/packages/views/issues/components/display-parts.tsx b/packages/views/issues/components/display-parts.tsx
new file mode 100644
index 0000000000..723ab600cd
--- /dev/null
+++ b/packages/views/issues/components/display-parts.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import type { ComponentProps } from "react";
+import { ArrowUpDown } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { Button } from "@multica/ui/components/ui/button";
+import { Toggle } from "@multica/ui/components/ui/toggle";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
+
+/**
+ * An on/off chip in a display panel. Hover never fills an unpressed chip: in
+ * light mode `muted` and `accent` are the same grey, so a hover fill reads as
+ * selected.
+ */
+export function DisplayChip({ className, ...props }: ComponentProps<typeof Toggle>) {
+ return (
+ <Toggle
+ size="sm"
+ variant="outline"
+ className={cn(
+ "h-6 max-w-40 gap-1.5 rounded-md px-2 text-caption text-muted-foreground hover:border-foreground/25 hover:bg-transparent hover:text-foreground aria-pressed:border-transparent aria-pressed:bg-input aria-pressed:text-foreground aria-pressed:hover:bg-input/70",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+/** Flips a sort; `label` names the current direction, e.g. "Newest first". */
+export function SortDirectionButton({ label, onClick }: { label: string; onClick: () => void }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="icon-sm"
+ className="text-muted-foreground"
+ onClick={onClick}
+ aria-label={label}
+ >
+ <ArrowUpDown className="size-3.5" />
+ </Button>
+ }
+ />
+ <TooltipContent side="bottom">{label}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsx
index be3513f730..a14daabb61 100644
--- a/packages/views/issues/components/filter-chips-bar.tsx
+++ b/packages/views/issues/components/filter-chips-bar.tsx
@@ -2,15 +2,17 @@
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useStatusLabel } from "../utils/status-label";
-import { NO_PROPERTY_VALUE } from "../utils/filter";
import { useMemo, type ReactNode } from "react";
import {
+ CalendarClock,
CalendarDays,
CircleDashed,
CircleDot,
+ CircleUser,
FolderKanban,
SignalHigh,
Tag,
+ ListTree,
User,
UserPen,
X,
@@ -18,24 +20,32 @@ import {
import { useQuery } from "@tanstack/react-query";
import { Button } from "@multica/ui/components/ui/button";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { cn } from "@multica/ui/lib/utils";
import { useWorkspaceId } from "@multica/core/hooks";
import { memberListOptions, agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
import { projectListOptions } from "@multica/core/projects/queries";
import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";
import { labelListOptions } from "@multica/core/labels/queries";
import { propertyListOptions } from "@multica/core/properties";
-import { isActorPropertyType, isListPropertyType, isScalarPropertyType, parseActorRef, propertyFilterValueKey, PROPERTY_FILTER_OP_SYMBOLS, type PropertyFilterValue } from "@multica/core/types";
+import { isActorPropertyType, parseActorRef, propertyFilterValueKey, type PropertyFilterValue } from "@multica/core/types";
import {
type ActorFilterValue,
type FilterDimension,
type FilterSnapshot,
type IssueDateFilter,
+ type NegatableFilterDimension,
} from "@multica/core/issues/stores/view-store";
import {
actorFilterKey,
type IssueViewBaseline,
} from "@multica/core/issue-views/baseline";
import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
+import {
+ advancedFilterSignature,
+ countAdvancedConditions,
+} from "@multica/core/issues/stores/filter-tree";
+import { DUE_DATE_LABEL_KEY, RELATION_LABEL_KEY } from "./filter-field-options";
+import { usePropertyValueName } from "./property-filter-options";
import { StatusIcon } from "./status-icon";
import { PriorityIcon } from "./priority-icon";
import { ActorAvatar } from "../../common/actor-avatar";
@@ -43,7 +53,7 @@ import { useProjectStatusLabels } from "../../projects/components/labels";
import { useT } from "../../i18n";
/** One rendered chip: a dimension with its selected values summarised. */
-interface FilterChip {
+export interface FilterChip {
key: string;
icon: ReactNode;
/** Dimension name, e.g. "状态". */
@@ -52,10 +62,25 @@ interface FilterChip {
value: string;
/** Up to three overlapping value icons rendered before the summary text. */
valueIcons?: ReactNode;
+ /** The dimension excludes these values ("is not"). */
+ negated?: boolean;
onRemove: () => void;
}
-function summarize(names: (string | undefined)[]): string {
+/** The chip's relation word. "Is not" carries a fill so it never reads as
+ * "is" at a glance; "is" stays quiet. */
+export function FilterOperator({ negated }: { negated?: boolean }) {
+ const { t } = useT("issues");
+ return negated ? (
+ <span className="shrink-0 rounded-sm bg-muted px-1 font-semibold text-foreground">
+ {t(($) => $.filters.operator_is_not)}
+ </span>
+ ) : (
+ <span className="shrink-0 text-muted-foreground">{t(($) => $.filters.operator_is)}</span>
+ );
+}
+
+export function summarize(names: (string | undefined)[]): string {
const first = names.find((n): n is string => !!n);
if (first === undefined) return String(names.length);
const rest = names.length - 1;
@@ -64,6 +89,8 @@ function summarize(names: (string | undefined)[]): string {
const CHIP_ICON_CLASS = "size-3 shrink-0 text-muted-foreground";
+export { RELATION_LABEL_KEY };
+
/** Overlapping value icons, following the runtime-list stack pattern: each
* icon sits on an opaque wrapper so the one underneath cannot show through. */
function IconStack({ children }: { children: ReactNode[] }) {
@@ -178,7 +205,7 @@ function DotStack({ colors }: { colors: string[] }) {
* the save-view dialog. Name lookups reuse the caches the filter dropdown
* already populates; a cache miss degrades a chip to a count, never blocks.
*/
-function useFilterChips(
+export function useFilterChips(
dateFilter: IssueDateFilter | null,
onDateFilterChange?: (filter: IssueDateFilter | null) => void,
baseline?: IssueViewBaseline,
@@ -198,8 +225,13 @@ function useFilterChips(
const includeNoProject = useViewStore((s) => s.includeNoProject);
const projectStatusFilters = useViewStore((s) => s.projectStatusFilters);
const labelFilters = useViewStore((s) => s.labelFilters);
+ const relationFilters = useViewStore((s) => s.relationFilters);
+ const dueDateFilters = useViewStore((s) => s.dueDateFilters);
+ const advancedFilter = useViewStore((s) => s.advancedFilter);
+ const negatedFilters = useViewStore((s) => s.negatedFilters);
const propertyFilters = useViewStore((s) => s.propertyFilters);
const store = useViewStoreApi();
+ const negated = new Set(negatedFilters);
const hasStoreFilters =
statusFilters.length > 0 ||
@@ -211,6 +243,9 @@ function useFilterChips(
includeNoProject ||
projectStatusFilters.length > 0 ||
labelFilters.length > 0 ||
+ relationFilters.length > 0 ||
+ dueDateFilters.length > 0 ||
+ advancedFilter !== null ||
Object.values(propertyFilters).some((selected) => selected.length > 0);
const showDateChip = !!onDateFilterChange && !!dateFilter;
@@ -252,6 +287,7 @@ function useFilterChips(
() => buildChipActorNames(members, agents, squads),
[members, agents, squads],
);
+ const propertyValueName = usePropertyValueName(actorName);
// Inside a saved view chips show only the user's additions ON TOP of the
// view; removing one returns the dimension to the view's values (never
@@ -263,6 +299,7 @@ function useFilterChips(
}
const s = store.getState();
const raw = baseline.raw;
+ const otherNegations = s.negatedFilters.filter((d) => d !== dimension);
const current: FilterSnapshot = {
statusFilters: s.statusFilters,
priorityFilters: s.priorityFilters,
@@ -273,7 +310,14 @@ function useFilterChips(
includeNoProject: s.includeNoProject,
projectStatusFilters: s.projectStatusFilters,
labelFilters: s.labelFilters,
+ relationFilters: s.relationFilters,
+ dueDateFilters: s.dueDateFilters,
+ // The dimension also returns to the view's own "is" / "is not".
+ negatedFilters: baseline.negated.has(dimension as NegatableFilterDimension)
+ ? [...otherNegations, dimension as NegatableFilterDimension]
+ : otherNegations,
propertyFilters: s.propertyFilters,
+ advancedFilter: s.advancedFilter,
};
switch (dimension) {
case "status":
@@ -308,6 +352,12 @@ function useFilterChips(
case "label":
s.resetFiltersTo({ ...current, labelFilters: raw.labelFilters });
break;
+ case "relation":
+ s.resetFiltersTo({ ...current, relationFilters: raw.relationFilters });
+ break;
+ case "dueDate":
+ s.resetFiltersTo({ ...current, dueDateFilters: raw.dueDateFilters });
+ break;
default: {
const propertyId = dimension.slice("property:".length);
const propertyFilters = { ...current.propertyFilters };
@@ -319,38 +369,40 @@ function useFilterChips(
}
};
- // Values the view already fixes are invisible here — subtract them.
- const deltaStatus = baseline
- ? statusFilters.filter((s) => !baseline.status.has(s))
- : statusFilters;
- const deltaPriority = baseline
- ? priorityFilters.filter((p) => !baseline.priority.has(p))
- : priorityFilters;
- const deltaAssignees = baseline
- ? assigneeFilters.filter((a) => !baseline.assignee.has(actorFilterKey(a)))
- : assigneeFilters;
- const deltaNoAssignee = baseline
- ? includeNoAssignee && !baseline.includeNoAssignee
- : includeNoAssignee;
- const deltaCreators = baseline
- ? creatorFilters.filter((a) => !baseline.creator.has(actorFilterKey(a)))
- : creatorFilters;
- const deltaProjects = baseline
- ? projectFilters.filter((id) => !baseline.project.has(id))
- : projectFilters;
- const deltaNoProject = baseline
- ? includeNoProject && !baseline.includeNoProject
- : includeNoProject;
- const deltaProjectStatuses = (
- baseline
- ? projectStatusFilters.filter((s) => !baseline.projectStatus.has(s))
- : projectStatusFilters
+ // Values the view already fixes are invisible here — subtract them. A
+ // dimension whose "is" / "is not" differs from the view's is a new
+ // condition as a whole, so nothing is subtracted from it.
+ const fixedFor = (dimension: NegatableFilterDimension, fixed: Set<string> | undefined) =>
+ baseline && baseline.negated.has(dimension) === negated.has(dimension) ? fixed : undefined;
+ const without = <T,>(values: T[], fixed: Set<string> | undefined, key: (v: T) => string) =>
+ fixed ? values.filter((v) => !fixed.has(key(v))) : values;
+ const same = (v: string) => v;
+ const deltaStatus = without(statusFilters, fixedFor("status", baseline?.status), same);
+ const deltaPriority = without(priorityFilters, fixedFor("priority", baseline?.priority), same);
+ const assigneeFixed = fixedFor("assignee", baseline?.assignee);
+ const deltaAssignees = without(assigneeFilters, assigneeFixed, actorFilterKey);
+ const deltaNoAssignee =
+ includeNoAssignee && !(assigneeFixed && baseline?.includeNoAssignee);
+ const deltaCreators = without(creatorFilters, fixedFor("creator", baseline?.creator), actorFilterKey);
+ const projectFixed = fixedFor("project", baseline?.project);
+ const deltaProjects = without(projectFilters, projectFixed, same);
+ const deltaNoProject = includeNoProject && !(projectFixed && baseline?.includeNoProject);
+ const deltaProjectStatuses = without(
+ projectStatusFilters,
+ fixedFor("projectStatus", baseline?.projectStatus),
+ same,
// The store sanitizes on rehydrate; this keeps a member the config does
// not know from throwing on `.dotColor` if one ever gets past that.
).filter((status) => PROJECT_STATUS_CONFIG[status] !== undefined);
- const deltaLabels = baseline
- ? labelFilters.filter((id) => !baseline.label.has(id))
- : labelFilters;
+ const deltaLabels = without(labelFilters, fixedFor("label", baseline?.label), same);
+ const deltaRelations = without(relationFilters, fixedFor("relation", baseline?.relation), same);
+ const deltaDueDates = without(dueDateFilters, fixedFor("dueDate", baseline?.dueDate), same);
+ // The tree is one condition as a whole: it shows unless it is exactly the
+ // view's own.
+ const advancedConditions = countAdvancedConditions(advancedFilter);
+ const showAdvancedChip =
+ advancedFilter !== null &&
+ (!baseline || advancedFilterSignature(advancedFilter) !== advancedFilterSignature(baseline.raw.advancedFilter));
const deltaProperties: Record<string, PropertyFilterValue[]> = {};
for (const [id, selected] of Object.entries(propertyFilters)) {
const fixed = baseline?.property.get(id);
@@ -386,6 +438,7 @@ function useFilterChips(
onlyStatus !== undefined && deltaStatus.length === 1
? resolveStatusLabel(onlyStatus)
: t(($) => $.filters.chip_status_count, { count: deltaStatus.length }),
+ negated: negated.has("status"),
onRemove: () => clearDimension("status"),
});
}
@@ -406,6 +459,7 @@ function useFilterChips(
onlyPriority !== undefined && deltaPriority.length === 1
? t(($) => $.priority[onlyPriority])
: t(($) => $.filters.chip_priority_count, { count: deltaPriority.length }),
+ negated: negated.has("priority"),
onRemove: () => clearDimension("priority"),
});
}
@@ -418,6 +472,7 @@ function useFilterChips(
label: t(($) => $.filters.section_assignee),
valueIcons: deltaAssignees.length > 0 ? <AvatarStack actors={deltaAssignees} /> : undefined,
value: summarize(names),
+ negated: negated.has("assignee"),
onRemove: () => clearDimension("assignee"),
});
}
@@ -428,6 +483,7 @@ function useFilterChips(
label: t(($) => $.filters.section_creator),
valueIcons: <AvatarStack actors={deltaCreators} />,
value: summarize(deltaCreators.map(actorName)),
+ negated: negated.has("creator"),
onRemove: () => clearDimension("creator"),
});
}
@@ -451,6 +507,7 @@ function useFilterChips(
</IconStack>
) : undefined,
value: summarize(names),
+ negated: negated.has("project"),
onRemove: () => clearDimension("project"),
});
}
@@ -474,6 +531,7 @@ function useFilterChips(
value: summarize(
deltaProjectStatuses.map((status) => projectStatusLabels[status]),
),
+ negated: negated.has("projectStatus"),
onRemove: () => clearDimension("projectStatus"),
});
}
@@ -491,9 +549,43 @@ function useFilterChips(
/>
),
value: summarize(deltaLabels.map((id) => labelById.get(id)?.name)),
+ negated: negated.has("label"),
onRemove: () => clearDimension("label"),
});
}
+ if (deltaRelations.length > 0) {
+ chips.push({
+ key: "relation",
+ icon: <CircleUser className={CHIP_ICON_CLASS} />,
+ label: t(($) => $.filters.section_relation),
+ value: summarize(deltaRelations.map((relation) => t(($) => $.filters[RELATION_LABEL_KEY[relation]]))),
+ negated: negated.has("relation"),
+ onRemove: () => clearDimension("relation"),
+ });
+ }
+ if (deltaDueDates.length > 0) {
+ chips.push({
+ key: "dueDate",
+ icon: <CalendarClock className={CHIP_ICON_CLASS} />,
+ label: t(($) => $.filters.section_due_date),
+ value: summarize(deltaDueDates.map((bucket) => t(($) => $.filters[DUE_DATE_LABEL_KEY[bucket]]))),
+ negated: negated.has("dueDate"),
+ onRemove: () => clearDimension("dueDate"),
+ });
+ }
+ if (showAdvancedChip) {
+ chips.push({
+ key: "advanced",
+ icon: <ListTree className={CHIP_ICON_CLASS} />,
+ label: t(($) => $.filters.advanced_title),
+ value: t(($) => $.filters.advanced_conditions, { count: advancedConditions }),
+ onRemove: () => {
+ const s = store.getState();
+ if (baseline) s.resetFiltersTo(baseline.raw);
+ else s.setAdvancedFilter(null);
+ },
+ });
+ }
for (const [propertyId, selected] of Object.entries(deltaProperties)) {
if (selected.length === 0) continue;
const definition = workspaceProperties.find((p) => p.id === propertyId);
@@ -504,41 +596,9 @@ function useFilterChips(
// references, so names come from the directory and the icons are avatars.
const actorProperty = isActorPropertyType(definition.type);
const actorValues = actorProperty ? actorFilterValues(selected) : [];
- const optionName = (member: PropertyFilterValue): string | undefined => {
- if (member === NO_PROPERTY_VALUE) {
- return t(($) => $.pickers.custom_property.none);
- }
- // Scalar operator members summarize with their operator; the comparison
- // symbols are locale-independent, the word ops get chip phrases.
- if (typeof member === "object") {
- if (member.op === "contains") {
- return t(($) => $.filters.chip_op_contains, { value: member.value });
- }
- if (member.op === "before") {
- return t(($) => $.filters.chip_op_before, { value: member.value });
- }
- if (member.op === "after") {
- return t(($) => $.filters.chip_op_after, { value: member.value });
- }
- const symbol = PROPERTY_FILTER_OP_SYMBOLS[member.op] ?? member.op;
- return `${symbol} ${member.value}`;
- }
- if (actorProperty) {
- const ref = parseActorRef(member);
- return ref ? actorName({ type: ref.kind, id: ref.id }) : undefined;
- }
- if (definition.type === "checkbox") {
- return member === "true"
- ? t(($) => $.pickers.custom_property.true_label)
- : t(($) => $.pickers.custom_property.false_label);
- }
- // Scalar and list properties have no option list — the filter value IS
- // the label (for lists it is one matched element).
- if (isScalarPropertyType(definition.type) || isListPropertyType(definition.type)) {
- return member;
- }
- return definition.config.options?.find((o) => o.id === member)?.name;
- };
+ const optionName = (member: PropertyFilterValue) =>
+ propertyValueName(definition, member);
+
const optionColors =
definition.type === "checkbox" || actorProperty
? []
@@ -593,7 +653,7 @@ function useFilterChips(
return { chips, hasAny: chips.length > 0, clearAll };
}
-function ChipSpan({ chip }: { chip: FilterChip }) {
+export function ChipSpan({ chip, className }: { chip: FilterChip; className?: string }) {
const { t } = useT("issues");
const removeLabel = t(($) => $.filters.chip_remove, { name: chip.label });
return (
@@ -601,12 +661,13 @@ function ChipSpan({ chip }: { chip: FilterChip }) {
// first gains a value; value changes inside it re-render without
// re-animating. No exit animation — unmount presence isn't worth the
// machinery for a 150ms nicety.
- <span className="flex h-6 max-w-72 items-center gap-1.5 rounded-md bg-background pl-2 pr-1 text-caption shadow-xs animate-in fade-in-0 zoom-in-95 duration-150">
+ <span className={cn("flex h-6 max-w-72 shrink-0 items-center gap-1.5 rounded-md bg-background pl-2 pr-1 text-caption shadow-xs animate-in fade-in-0 zoom-in-95 duration-150", className)}>
<span className="flex shrink-0 items-center gap-1 text-muted-foreground">
{chip.icon}
<span>{chip.label}</span>
</span>
<span className="flex min-w-0 items-center gap-1">
+ {chip.negated && <FilterOperator negated />}
{chip.valueIcons}
<span className="truncate font-medium">{chip.value}</span>
</span>
diff --git a/packages/views/issues/components/filter-field-options.tsx b/packages/views/issues/components/filter-field-options.tsx
new file mode 100644
index 0000000000..496688559d
--- /dev/null
+++ b/packages/views/issues/components/filter-field-options.tsx
@@ -0,0 +1,299 @@
+"use client";
+
+import { useMemo, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ Bot,
+ CalendarClock,
+ CircleDashed,
+ CircleDot,
+ CircleUser,
+ FolderKanban,
+ FolderMinus,
+ SignalHigh,
+ Tag,
+ User,
+ UserMinus,
+ UserPen,
+ type IconComponent,
+} from "@multica/ui/icons";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";
+import { PROJECT_STATUS_CONFIG, PROJECT_STATUS_ORDER } from "@multica/core/projects/config";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { labelListOptions } from "@multica/core/labels/queries";
+import { memberListOptions, agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
+import {
+ DUE_DATE_FILTERS,
+ FILTER_NONE_VALUE,
+ ISSUE_RELATION_FILTERS,
+ type DueDateFilter,
+ type IssueRelationFilter,
+ type NegatableFilterDimension,
+} from "@multica/core/issues/stores/filter-tree";
+import type { ActorFilterValue } from "@multica/core/issues/stores/view-store";
+import { useT } from "../../i18n";
+import { useStatusOptions } from "../utils/status-options";
+import { matchesPinyin } from "../../editor/extensions/pinyin-match";
+import { useProjectStatusLabels } from "../../projects/components/labels";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { StatusIcon } from "./status-icon";
+import { PriorityIcon } from "./priority-icon";
+
+export const FILTER_FIELD_ICONS: Record<NegatableFilterDimension, IconComponent> = {
+ status: CircleDot,
+ priority: SignalHigh,
+ assignee: User,
+ creator: UserPen,
+ project: FolderKanban,
+ projectStatus: CircleDashed,
+ label: Tag,
+ relation: CircleUser,
+ dueDate: CalendarClock,
+};
+
+const RELATION_ICONS: Record<IssueRelationFilter, IconComponent> = {
+ assigned: CircleUser,
+ created: UserPen,
+ my_agents: Bot,
+};
+
+export const DUE_DATE_LABEL_KEY: Record<
+ DueDateFilter,
+ "due_overdue" | "due_today" | "due_this_week" | "due_next_7_days" | "due_none"
+> = {
+ overdue: "due_overdue",
+ today: "due_today",
+ this_week: "due_this_week",
+ next_7_days: "due_next_7_days",
+ none: "due_none",
+};
+
+export const RELATION_LABEL_KEY: Record<
+ IssueRelationFilter,
+ "relation_assigned" | "relation_created" | "relation_my_agents"
+> = {
+ assigned: "relation_assigned",
+ created: "relation_created",
+ my_agents: "relation_my_agents",
+};
+
+export function useFilterFieldLabels(): Record<NegatableFilterDimension, string> {
+ const { t } = useT("issues");
+ return {
+ status: t(($) => $.filters.section_status),
+ priority: t(($) => $.filters.section_priority),
+ assignee: t(($) => $.filters.section_assignee),
+ creator: t(($) => $.filters.section_creator),
+ project: t(($) => $.filters.section_project),
+ projectStatus: t(($) => $.filters.section_project_status),
+ label: t(($) => $.filters.section_label),
+ relation: t(($) => $.filters.section_relation),
+ dueDate: t(($) => $.filters.section_due_date),
+ };
+}
+
+/** One value a condition on a field can take, in condition-value form. */
+export interface FilterValueOption {
+ value: string;
+ label: string;
+ icon: ReactNode;
+ /** Heading the option sits under (members / agents / squads). */
+ group?: string;
+}
+
+/** Case-insensitive substring or pinyin-initials match. */
+export function matchesFilterQuery(text: string, query: string): boolean {
+ if (!query) return true;
+ return text.toLowerCase().includes(query) || matchesPinyin(text, query);
+}
+
+/**
+ * Every value each field can be filtered on, for the menu's search and the
+ * advanced panel. Directories load only while `enabled`; until then an
+ * actor / project / label field simply lists nothing.
+ */
+export function useFilterValueCatalog(
+ enabled: boolean,
+): (field: NegatableFilterDimension) => FilterValueOption[] {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const statusOptions = useStatusOptions(wsId);
+ const projectStatusLabels = useProjectStatusLabels();
+ const { data: members = [] } = useQuery({ ...memberListOptions(wsId), enabled });
+ const { data: agents = [] } = useQuery({ ...agentListOptions(wsId), enabled });
+ const { data: squads = [] } = useQuery({ ...squadListOptions(wsId), enabled });
+ const { data: projects = [] } = useQuery({ ...projectListOptions(wsId), enabled });
+ const { data: labels = [] } = useQuery({ ...labelListOptions(wsId), enabled });
+ const membersGroup = t(($) => $.filters.members_group);
+ const agentsGroup = t(($) => $.filters.agents_group);
+ const squadsGroup = t(($) => $.filters.squads_group);
+ const noAssignee = t(($) => $.filters.no_assignee);
+ const noProject = t(($) => $.filters.no_project);
+ const priorityLabels = Object.fromEntries(
+ PRIORITY_DISPLAY_ORDER.map((p) => [p, t(($) => $.priority[p])]),
+ );
+ const relationLabels = Object.fromEntries(
+ ISSUE_RELATION_FILTERS.map((r) => [r, t(($) => $.filters[RELATION_LABEL_KEY[r]])]),
+ );
+ const dueDateLabels = Object.fromEntries(
+ DUE_DATE_FILTERS.map((d) => [d, t(($) => $.filters[DUE_DATE_LABEL_KEY[d]])]),
+ );
+ // Labels are fresh strings per render; key the memo on their content.
+ const labelKey = JSON.stringify([
+ priorityLabels, relationLabels, dueDateLabels, projectStatusLabels,
+ membersGroup, agentsGroup, squadsGroup, noAssignee, noProject,
+ ]);
+
+ return useMemo(() => {
+ const actorOptions = (withSquads: boolean): FilterValueOption[] => [
+ ...members.map((m) => ({
+ value: `member:${m.user_id}`,
+ label: m.name,
+ group: membersGroup,
+ icon: <ActorAvatar actorType="member" actorId={m.user_id} size="xs" profileLink={false} />,
+ })),
+ ...agents
+ .filter((a) => !a.archived_at)
+ .map((a) => ({
+ value: `agent:${a.id}`,
+ label: a.name,
+ group: agentsGroup,
+ icon: <ActorAvatar actorType="agent" actorId={a.id} size="xs" profileLink={false} />,
+ })),
+ ...(withSquads
+ ? squads
+ .filter((s) => !s.archived_at)
+ .map((s) => ({
+ value: `squad:${s.id}`,
+ label: s.name,
+ group: squadsGroup,
+ icon: <ActorAvatar actorType="squad" actorId={s.id} size="xs" profileLink={false} />,
+ }))
+ : []),
+ ];
+ const byField: Record<NegatableFilterDimension, FilterValueOption[]> = {
+ status: statusOptions.map((option) => ({
+ value: option.key,
+ label: option.label,
+ icon: (
+ <StatusIcon
+ status={option.key}
+ category={option.category}
+ color={option.color}
+ icon={option.icon}
+ className="size-3.5"
+ />
+ ),
+ })),
+ priority: PRIORITY_DISPLAY_ORDER.map((p) => ({
+ value: p,
+ label: priorityLabels[p] ?? p,
+ icon: <PriorityIcon priority={p} />,
+ })),
+ assignee: [
+ {
+ value: FILTER_NONE_VALUE,
+ label: noAssignee,
+ icon: <UserMinus className="size-3.5 text-muted-foreground" />,
+ },
+ ...actorOptions(true),
+ ],
+ creator: actorOptions(false),
+ project: [
+ {
+ value: FILTER_NONE_VALUE,
+ label: noProject,
+ icon: <FolderMinus className="size-3.5 text-muted-foreground" />,
+ },
+ ...projects.map((p) => ({
+ value: p.id,
+ label: p.title,
+ icon: <ProjectIcon project={p} size="sm" />,
+ })),
+ ],
+ projectStatus: PROJECT_STATUS_ORDER.map((status) => ({
+ value: status,
+ label: projectStatusLabels[status],
+ icon: <span className={`size-2 rounded-full ${PROJECT_STATUS_CONFIG[status].dotColor}`} />,
+ })),
+ label: labels.map((l) => ({
+ value: l.id,
+ label: l.name,
+ icon: <span className="size-2 rounded-full" style={{ backgroundColor: l.color }} />,
+ })),
+ relation: ISSUE_RELATION_FILTERS.map((relation) => {
+ const Icon = RELATION_ICONS[relation];
+ return {
+ value: relation,
+ label: relationLabels[relation] ?? relation,
+ icon: <Icon className="size-3.5 text-muted-foreground" />,
+ };
+ }),
+ dueDate: DUE_DATE_FILTERS.map((bucket) => ({
+ value: bucket,
+ label: dueDateLabels[bucket] ?? bucket,
+ icon: <CalendarClock className="size-3.5 text-muted-foreground" />,
+ })),
+ };
+ return (field: NegatableFilterDimension) => byField[field];
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- translated labels are keyed by content
+ }, [agents, labelKey, labels, members, projects, squads, statusOptions]);
+}
+
+function parseActorValue(value: string): ActorFilterValue | null {
+ const separator = value.indexOf(":");
+ if (separator <= 0) return null;
+ const type = value.slice(0, separator);
+ if (type !== "member" && type !== "agent" && type !== "squad") return null;
+ return { type, id: value.slice(separator + 1) };
+}
+
+/** The simple-mode store actions the menu search needs. */
+export interface SimpleFilterToggles {
+ toggleStatusFilter: (status: string) => void;
+ togglePriorityFilter: (priority: (typeof PRIORITY_DISPLAY_ORDER)[number]) => void;
+ toggleAssigneeFilter: (value: ActorFilterValue) => void;
+ toggleNoAssignee: () => void;
+ toggleCreatorFilter: (value: ActorFilterValue) => void;
+ toggleProjectFilter: (projectId: string) => void;
+ toggleNoProject: () => void;
+ toggleProjectStatusFilter: (status: (typeof PROJECT_STATUS_ORDER)[number]) => void;
+ toggleLabelFilter: (labelId: string) => void;
+ toggleRelationFilter: (relation: IssueRelationFilter) => void;
+ toggleDueDateFilter: (bucket: DueDateFilter) => void;
+}
+
+/** Toggle one value of a simple-mode dimension, given in condition form. */
+export function toggleSimpleFilterValue(
+ act: SimpleFilterToggles,
+ field: NegatableFilterDimension,
+ value: string,
+) {
+ switch (field) {
+ case "status":
+ return act.toggleStatusFilter(value);
+ case "priority":
+ return act.togglePriorityFilter(value as (typeof PRIORITY_DISPLAY_ORDER)[number]);
+ case "assignee": {
+ if (value === FILTER_NONE_VALUE) return act.toggleNoAssignee();
+ const actor = parseActorValue(value);
+ return actor ? act.toggleAssigneeFilter(actor) : undefined;
+ }
+ case "creator": {
+ const actor = parseActorValue(value);
+ return actor ? act.toggleCreatorFilter(actor) : undefined;
+ }
+ case "project":
+ return value === FILTER_NONE_VALUE ? act.toggleNoProject() : act.toggleProjectFilter(value);
+ case "projectStatus":
+ return act.toggleProjectStatusFilter(value as (typeof PROJECT_STATUS_ORDER)[number]);
+ case "label":
+ return act.toggleLabelFilter(value);
+ case "relation":
+ return act.toggleRelationFilter(value as IssueRelationFilter);
+ case "dueDate":
+ return act.toggleDueDateFilter(value as DueDateFilter);
+ }
+}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 88d46beeb3..d95043228c 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -3931,8 +3931,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
spans the timeline — at column level `sticky bottom-0` can pin
the composer across the whole scroll range.
- Sticky treatment mirrors list-grid's sticky header, bottom
- edge: opaque bg-background under/around the card (its rounded
+ Sticky treatment, bottom edge: opaque bg-background
+ under/around the card (its rounded
corners would otherwise leak scrolled text), a 16px gradient
fade above (exactly the mt-4 gap, so at rest it sits over the
page background and is invisible), and pb-4 so the card floats
diff --git a/packages/views/issues/components/issues-header.advanced-filter.test.tsx b/packages/views/issues/components/issues-header.advanced-filter.test.tsx
new file mode 100644
index 0000000000..2b07b72520
--- /dev/null
+++ b/packages/views/issues/components/issues-header.advanced-filter.test.tsx
@@ -0,0 +1,276 @@
+// @vitest-environment jsdom
+
+/**
+ * The filter menu's search and its way into advanced mode, against the real
+ * Base UI primitives (see issues-header.property-filter.test.tsx).
+ */
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createStore, type StoreApi } from "zustand/vanilla";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { createAuthStore, registerAuthStore } from "@multica/core/auth";
+import { type IssueViewState, viewStoreSlice } from "@multica/core/issues/stores/view-store";
+import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
+import { createFilterCondition, createFilterGroup } from "@multica/core/issues/stores/filter-tree";
+import { renderWithI18n } from "../../test/i18n";
+import { IssueFilterMenu } from "./issues-header";
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+
+function renderFilterMenu(setup?: (store: StoreApi<IssueViewState>) => void, withProperty = false) {
+ setApiInstance({
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
+ listProperties: async () => ({ properties: withProperty ? [{
+ id: "estimate", workspace_id: "ws-1", name: "Estimate", type: "number",
+ config: {}, position: 1, archived: false, created_at: "", updated_at: "",
+ }] : [] }),
+ listMembers: async () => [],
+ listAgents: async () => [
+ { id: "agent-lambda", name: "Lambda", archived_at: null, owner_id: "u-1" },
+ ],
+ listSquads: async () => [],
+ listProjects: async () => ({ projects: [], total: 0 }),
+ listLabels: async () => ({ labels: [{ id: "label-bug", name: "Bug", color: "#f00" }], total: 1 }),
+ } as unknown as ApiClient);
+ registerAuthStore(
+ createAuthStore({
+ api: {} as ApiClient,
+ storage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
+ }),
+ );
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ const store = createStore<IssueViewState>()(viewStoreSlice);
+ setup?.(store);
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <ViewStoreProvider store={store}>
+ <IssueFilterMenu trigger={<button type="button">Filter</button>} />
+ </ViewStoreProvider>
+ </QueryClientProvider>,
+ );
+ return store;
+}
+
+afterEach(() => {
+ cleanup();
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+
+describe("IssueFilterMenu search", () => {
+ it("offers values as conditions and toggles them", async () => {
+ const store = renderFilterMenu();
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ const search = await screen.findByRole("textbox", { name: "Filter by field or value…" });
+ await userEvent.type(search, "lamb");
+
+ const row = await screen.findByRole("menuitemcheckbox", { name: /Assignee\s*is\s*Lambda/ });
+ fireEvent.click(row);
+ expect(store.getState().assigneeFilters).toEqual([{ type: "agent", id: "agent-lambda" }]);
+ // Creator offers the same agent as its own condition.
+ expect(screen.getByRole("menuitemcheckbox", { name: /Creator\s*is\s*Lambda/ })).toBeInTheDocument();
+ });
+
+ it("matches fields by name and buckets by label", async () => {
+ const store = renderFilterMenu();
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ const search = await screen.findByRole("textbox", { name: "Filter by field or value…" });
+ await userEvent.type(search, "overdue");
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Due date\s*is\s*Overdue/ }));
+ expect(store.getState().dueDateFilters).toEqual(["overdue"]);
+
+ await userEvent.clear(search);
+ await userEvent.type(search, "due");
+ expect(await screen.findByRole("menuitem", { name: /Due date/ })).toBeInTheDocument();
+ });
+});
+
+describe("IssueFilterMenu advanced mode", () => {
+ it("turns property filters into conditions and offers properties as fields", async () => {
+ const store = renderFilterMenu((s) => {
+ s.getState().setPropertyFilterValues("estimate", ["3"]);
+ s.getState().togglePriorityFilter("urgent");
+ }, true);
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ expect(await screen.findByRole("menuitem", { name: /Estimate/ })).toBeInTheDocument();
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Switch to advanced filter/ }));
+ await screen.findByTestId("advanced-filter-panel");
+
+ expect(store.getState().propertyFilters).toEqual({});
+ expect(store.getState().advancedFilter?.children).toMatchObject([
+ { field: "priority", values: ["urgent"] },
+ { field: "property:estimate", values: ["3"] },
+ ]);
+ const rows = screen.getAllByTestId("advanced-filter-row");
+ expect(rows).toHaveLength(2);
+ expect(rows[1]).toHaveTextContent("Estimate");
+ expect(screen.queryByRole("button", { name: "Add property filter" })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: /^Add condition$/ }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Estimate/ }));
+ expect(store.getState().advancedFilter?.children[2]).toMatchObject({
+ field: "property:estimate",
+ values: [],
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "Clear all" }));
+ expect(store.getState().advancedFilter?.children).toEqual([]);
+ expect(screen.getByRole("button", { name: "Clear all" })).toBeDisabled();
+ });
+
+ it("edits a number property with a typed value and its own operators", async () => {
+ const store = renderFilterMenu(
+ (s) =>
+ s.getState().setAdvancedFilter(
+ createFilterGroup("all", [createFilterCondition("property:estimate", [])]),
+ ),
+ true,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ const input = await screen.findByRole("spinbutton", { name: "Values" });
+ fireEvent.change(input, { target: { value: "3" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(store.getState().advancedFilter?.children).toMatchObject([
+ { field: "property:estimate", negated: false, values: ["3"] },
+ ]);
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Match" }));
+ await userEvent.click(await screen.findByRole("option", { name: ">" }));
+ expect(store.getState().advancedFilter?.children).toMatchObject([
+ { values: [{ op: "gt", value: "3" }] },
+ ]);
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Match" }));
+ await userEvent.click(await screen.findByRole("option", { name: "is empty" }));
+ expect(store.getState().advancedFilter?.children).toMatchObject([{ values: ["__none__"] }]);
+ expect(screen.queryByRole("spinbutton", { name: "Values" })).not.toBeInTheDocument();
+ // A plain "is empty" property condition is still a simple filter.
+ expect(screen.getByRole("button", { name: "Switch to simple filter" })).toBeEnabled();
+ });
+
+ it("lists actor values under their headings", async () => {
+ const store = renderFilterMenu((s) =>
+ s.getState().setAdvancedFilter(createFilterGroup("all", [createFilterCondition("assignee", [])])),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ fireEvent.click(screen.getByRole("button", { name: "Values" }));
+ expect(await screen.findByText("Agents")).toBeInTheDocument();
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Lambda/ }));
+ expect(store.getState().advancedFilter?.children).toMatchObject([{ values: ["agent:agent-lambda"] }]);
+ });
+
+ it("names set operators for labels", async () => {
+ renderFilterMenu((s) =>
+ s.getState().setAdvancedFilter(createFilterGroup("all", [createFilterCondition("label", ["label-bug"])])),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ expect(screen.getByRole("combobox", { name: "Match" })).toHaveTextContent("includes any of");
+ });
+
+ it("adds an empty group and opens its add menu", async () => {
+ const store = renderFilterMenu((s) =>
+ s.getState().setAdvancedFilter(createFilterGroup("all", [createFilterCondition("status", ["todo"])])),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ fireEvent.click(screen.getByRole("button", { name: "Add condition group" }));
+
+ expect(store.getState().advancedFilter?.children[1]).toMatchObject({ type: "group", match: "any", children: [] });
+ expect(screen.getByTestId("advanced-filter-group")).toHaveTextContent(/joined with “or”/);
+ expect(await screen.findByText("Add to group")).toBeInTheDocument();
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Priority/ }));
+ expect(store.getState().advancedFilter?.children[1]).toMatchObject({
+ type: "group",
+ children: [{ field: "priority", values: [] }],
+ });
+ });
+
+ it("turns a row into a group and reads the tree as a sentence", async () => {
+ const store = renderFilterMenu((s) =>
+ s.getState().setAdvancedFilter(
+ createFilterGroup("all", [
+ createFilterCondition("label", ["label-bug"]),
+ createFilterCondition("priority", ["urgent"]),
+ ]),
+ ),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ expect(screen.queryByTestId("advanced-filter-summary")).not.toBeInTheDocument();
+
+ const rows = screen.getAllByTestId("advanced-filter-row");
+ fireEvent.click(within(rows[1]!).getByRole("button", { name: "Condition actions" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Turn into group" }));
+ expect(store.getState().advancedFilter?.children[1]).toMatchObject({
+ type: "group",
+ match: "any",
+ children: [{ field: "priority", values: ["urgent"] }],
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("advanced-filter-summary")).toHaveTextContent(
+ "Shows issues where Label includes any of Bug and Priority is Urgent",
+ ),
+ );
+ });
+
+ it("switches to advanced with the current filters and opens the panel", async () => {
+ const store = renderFilterMenu((s) => {
+ s.getState().togglePriorityFilter("urgent");
+ s.getState().toggleLabelFilter("label-bug");
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Switch to advanced filter/ }));
+
+ expect(store.getState().priorityFilters).toEqual([]);
+ expect(store.getState().advancedFilter?.children).toHaveLength(2);
+ const panel = await screen.findByTestId("advanced-filter-panel");
+ expect(panel).toHaveTextContent("Advanced filter");
+ expect(screen.getAllByTestId("advanced-filter-row")).toHaveLength(2);
+ // Two plain "and" rows are still simple filters.
+ expect(screen.getByRole("button", { name: "Switch to simple filter" })).toBeEnabled();
+ });
+
+ it("disables switching back with the reason when the tree has a group", async () => {
+ renderFilterMenu((s) =>
+ s.getState().setAdvancedFilter(
+ createFilterGroup("all", [
+ createFilterCondition("project", ["p1"]),
+ createFilterGroup("any", [
+ createFilterCondition("priority", ["urgent"]),
+ createFilterCondition("label", ["label-bug"]),
+ ]),
+ ]),
+ ),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ expect(screen.getByTestId("advanced-filter-group")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Switch to simple filter" })).toBeDisabled();
+ expect(screen.getByText(/Simple filters can't show groups/)).toBeInTheDocument();
+ });
+
+ it("goes back to the simple menu with the same filters", async () => {
+ const store = renderFilterMenu((s) =>
+ s.getState().setAdvancedFilter(createFilterGroup("all", [createFilterCondition("status", ["todo"], true)])),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByTestId("advanced-filter-panel");
+ fireEvent.click(screen.getByRole("button", { name: "Switch to simple filter" }));
+ await waitFor(() => expect(store.getState().advancedFilter).toBeNull());
+ expect(store.getState().statusFilters).toEqual(["todo"]);
+ expect(store.getState().negatedFilters).toEqual(["status"]);
+ });
+});
diff --git a/packages/views/issues/components/issues-header.display-layout.test.tsx b/packages/views/issues/components/issues-header.display-layout.test.tsx
new file mode 100644
index 0000000000..83b2f54a10
--- /dev/null
+++ b/packages/views/issues/components/issues-header.display-layout.test.tsx
@@ -0,0 +1,84 @@
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, screen, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createStore, type StoreApi } from "zustand/vanilla";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import {
+ type IssueViewState,
+ viewStoreSlice,
+} from "@multica/core/issues/stores/view-store";
+import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
+import { renderWithI18n } from "../../test/i18n";
+import { IssueDisplayControls } from "./issues-header";
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "ws-1",
+}));
+
+function renderDisplay(
+ props: { allowGantt?: boolean } = {},
+ setup: (store: StoreApi<IssueViewState>) => void = () => {},
+) {
+ setApiInstance(
+ new Proxy({}, { get: () => async () => ({}) }) as unknown as ApiClient,
+ );
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ const store = createStore<IssueViewState>()(viewStoreSlice);
+ setup(store);
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <ViewStoreProvider store={store}>
+ <IssueDisplayControls scopedIssues={[]} {...props} />
+ </ViewStoreProvider>
+ </QueryClientProvider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Display" }));
+ return store;
+}
+
+afterEach(() => {
+ cleanup();
+ document.body.innerHTML = "";
+});
+
+describe("Display layout", () => {
+ it("switches the layout from inside the panel", async () => {
+ const store = renderDisplay({}, (s) => s.getState().setViewMode("board"));
+
+ const layouts = await screen.findByRole("group", { name: "View" });
+ expect(
+ within(layouts).getAllByRole("button").map((button) => button.textContent),
+ ).toEqual(["Board", "List", "Table", "Swimlane"]);
+ expect(within(layouts).getByRole("button", { name: "Board" })).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ expect(screen.getByText("Board options")).toBeInTheDocument();
+
+ fireEvent.click(within(layouts).getByRole("button", { name: "Table" }));
+
+ expect(store.getState().viewMode).toBe("table");
+ expect(await screen.findByText("Table options")).toBeInTheDocument();
+ });
+
+ it("offers Gantt only where the surface renders it", async () => {
+ renderDisplay({ allowGantt: true });
+
+ const layouts = await screen.findByRole("group", { name: "View" });
+ expect(within(layouts).getByRole("button", { name: "Gantt" })).toBeInTheDocument();
+ });
+
+ it("keeps the table's grouping and columns in the panel", async () => {
+ renderDisplay({}, (s) => s.getState().setViewMode("table"));
+
+ await screen.findByText("Table options");
+ expect(screen.getAllByRole("combobox", { name: "Grouping" })).toHaveLength(1);
+ expect(screen.getByRole("button", { name: /shown$/ })).toBeInTheDocument();
+ expect(screen.getByText("Hierarchy")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/issues-header.property-filter.test.tsx b/packages/views/issues/components/issues-header.property-filter.test.tsx
index f6e0adc256..0973d80568 100644
--- a/packages/views/issues/components/issues-header.property-filter.test.tsx
+++ b/packages/views/issues/components/issues-header.property-filter.test.tsx
@@ -79,12 +79,21 @@ function renderFilterMenu(props: IssueProperty[], propertyFilters: IssueViewStat
return { store, ...view };
}
+/** The submenu's value input, not the menu's own search box. */
+function valueInput() {
+ const [input] = screen
+ .getAllByRole("textbox")
+ .filter((element) => !element.closest("[data-filter-search]"));
+ if (!input) throw new Error("value input not found");
+ return input;
+}
+
async function openPropertySubmenu(name: string) {
fireEvent.click(screen.getByRole("button", { name: "Filter" }));
const trigger = await screen.findByRole("menuitem", { name: new RegExp(name) });
fireEvent.click(trigger);
await waitFor(() =>
- expect(screen.getByRole("textbox")).toBeInTheDocument(),
+ expect(valueInput()).toBeInTheDocument(),
);
}
@@ -142,7 +151,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- const input = screen.getByRole("textbox");
+ const input = valueInput();
await userEvent.type(input, "hello");
// The regression: Base UI's menu popup stops every printable key, so the
@@ -156,7 +165,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- await userEvent.type(screen.getByRole("textbox"), "hello{Enter}");
+ await userEvent.type(valueInput(), "hello{Enter}");
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["hello"] });
});
@@ -165,7 +174,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- const input = screen.getByRole("textbox");
+ const input = valueInput();
await userEvent.type(input, "hello");
fireEvent.blur(input);
@@ -178,7 +187,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- const input = screen.getByRole("textbox");
+ const input = valueInput();
await userEvent.type(input, "hello{Enter}");
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["hello"] });
@@ -199,7 +208,7 @@ describe("IssueFilterMenu scalar property filter", () => {
await userEvent.click(screen.getByRole("menuitemcheckbox", { name: /No value/ }));
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["__none__"] });
- await userEvent.type(screen.getByRole("textbox"), "abc{Enter}");
+ await userEvent.type(valueInput(), "abc{Enter}");
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["abc", "__none__"] });
});
@@ -207,16 +216,16 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- await userEvent.type(screen.getByRole("textbox"), "abc");
+ await userEvent.type(valueInput(), "abc");
// Clicking the checkbox blurs the input first; the blur guard must skip the
// premature commit so the checkbox reads the pre-blur state and the draft
// stays uncommitted in the input.
await userEvent.click(screen.getByRole("menuitemcheckbox", { name: /No value/ }));
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["__none__"] });
- expect(screen.getByRole("textbox")).toHaveValue("abc");
+ expect(valueInput()).toHaveValue("abc");
// Enter commits the draft as another member of the OR-set.
- await userEvent.type(screen.getByRole("textbox"), "{Enter}");
+ await userEvent.type(valueInput(), "{Enter}");
expect(store.getState().propertyFilters).toEqual({ [PROP]: ["abc", "__none__"] });
});
@@ -231,7 +240,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const contains = screen.getByRole("radio", { name: "contains" });
await userEvent.click(contains);
expect(contains).toBeChecked();
- await userEvent.type(screen.getByRole("textbox"), "hello{Enter}");
+ await userEvent.type(valueInput(), "hello{Enter}");
expect(store.getState().propertyFilters).toEqual({
[PROP]: [{ op: "contains", value: "hello" }],
@@ -242,7 +251,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- await userEvent.type(screen.getByRole("textbox"), "hello");
+ await userEvent.type(valueInput(), "hello");
await userEvent.click(screen.getByRole("radio", { name: "contains" }));
expect(store.getState().propertyFilters).toEqual({
@@ -254,7 +263,7 @@ describe("IssueFilterMenu scalar property filter", () => {
const { store } = renderFilterMenu([textProperty(PROP, "Note")]);
await openPropertySubmenu("Note");
- await userEvent.type(screen.getByRole("textbox"), "hello");
+ await userEvent.type(valueInput(), "hello");
await userEvent.click(screen.getByRole("radio", { name: "contains" }));
expect(store.getState().propertyFilters).toEqual({
[PROP]: [{ op: "contains", value: "hello" }],
diff --git a/packages/views/issues/components/issues-header.status-filter.test.tsx b/packages/views/issues/components/issues-header.status-filter.test.tsx
index 08767adf33..06a30b29cb 100644
--- a/packages/views/issues/components/issues-header.status-filter.test.tsx
+++ b/packages/views/issues/components/issues-header.status-filter.test.tsx
@@ -74,7 +74,11 @@ const HUMAN_REVIEW = entry({
position: 1,
});
-function renderFilterMenu(statuses: IssueStatusEntry[]) {
+function renderFilterMenu(
+ statuses: IssueStatusEntry[],
+ initial: Partial<IssueViewState> = {},
+ menuProps: { summaryTitle?: string } = {},
+) {
setApiInstance({
listIssueStatuses: async () => ({
statuses,
@@ -88,14 +92,16 @@ function renderFilterMenu(statuses: IssueStatusEntry[]) {
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
});
const store = createStore<IssueViewState>()(viewStoreSlice);
+ store.setState(initial);
- return renderWithI18n(
+ renderWithI18n(
<QueryClientProvider client={qc}>
<ViewStoreProvider store={store}>
- <IssueFilterMenu trigger={<button type="button">Filter</button>} />
+ <IssueFilterMenu trigger={<button type="button">Filter</button>} {...menuProps} />
</ViewStoreProvider>
</QueryClientProvider>,
);
+ return store;
}
/** Opens the Filter menu, then its Status submenu. */
@@ -154,3 +160,67 @@ describe("IssueFilterMenu status section", () => {
expect(screen.getAllByRole("menuitemcheckbox")).toHaveLength(BUILT_IN_STATUS_ORDER.length);
});
});
+
+describe("IssueFilterMenu active dimensions", () => {
+ const dimensionRows = () =>
+ screen.getAllByRole("menuitem").map((el) => el.textContent?.trim() ?? "");
+
+ it("lists the dimensions already filtering first, with their values", async () => {
+ renderFilterMenu(BUILT_INS, { priorityFilters: ["high"] });
+
+ fireEvent.click(screen.getByRole("button", { name: "Filter" }));
+ await screen.findByText("Active");
+
+ const rows = dimensionRows();
+ expect(rows[0]).toBe("PriorityisHigh");
+ expect(rows.slice(1, 3)).toEqual(["Status", "Assignee"]);
+ });
+
+ it("keeps a dimension in place while the menu stays open", async () => {
+ renderFilterMenu(BUILT_INS);
+
+ await openStatusSubmenu();
+ expect(screen.queryByText("Active")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /In Review/ }));
+
+ await waitFor(() =>
+ expect(screen.getByRole("menuitem", { name: /^Status/ }).textContent).toContain("In Review"),
+ );
+ expect(screen.queryByText("Active")).not.toBeInTheDocument();
+ expect(dimensionRows()[0]).toMatch(/^Status/);
+ });
+
+ // The hover summary wraps the trigger once a filter exists. Swapping the
+ // wrapper on the first pick remounted the trigger, and the open menu lost
+ // its anchor and jumped to the viewport corner.
+ it("keeps the same trigger node when the first filter lands", async () => {
+ renderFilterMenu(BUILT_INS, {}, { summaryTitle: "All issues" });
+ const trigger = screen.getByRole("button", { name: "Filter" });
+
+ await openStatusSubmenu();
+ fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /In Review/ }));
+ await waitFor(() =>
+ expect(screen.getByRole("menuitem", { name: /^Status/ }).textContent).toContain("In Review"),
+ );
+
+ expect(screen.getByRole("button", { name: "Filter" })).toBe(trigger);
+ });
+});
+
+describe("IssueFilterMenu operator switch", () => {
+ it("flips a dimension to is not without closing its submenu", async () => {
+ const store = renderFilterMenu(BUILT_INS, { statusFilters: ["in_review"] });
+
+ await openStatusSubmenu();
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "is not" }));
+
+ await waitFor(() => expect(store.getState().negatedFilters).toEqual(["status"]));
+ expect(screen.getByRole("menuitemcheckbox", { name: /In Review/ })).toBeInTheDocument();
+ expect(screen.getByRole("menuitem", { name: /^Status/ }).textContent).toBe(
+ "Statusis notIn Review",
+ );
+
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "is" }));
+ await waitFor(() => expect(store.getState().negatedFilters).toEqual([]));
+ });
+});
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 7f27d23844..a40372498f 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -1,18 +1,22 @@
"use client";
-import { cloneElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { cloneElement, useEffect, useMemo, useRef, useState } from "react";
import {
+ Bot,
+ CalendarClock,
CalendarDays,
ChartGantt,
ChevronDown,
CircleDashed,
CircleDot,
+ CircleUser,
Columns3,
Filter,
FolderKanban,
FolderMinus,
List,
- Rows3,
+ ListTree,
+ Search,
SignalHigh,
SlidersHorizontal,
Tag,
@@ -23,8 +27,8 @@ import {
Waves,
} from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
import { Spinner } from "@multica/ui/components/ui/spinner";
-import { Input } from "@multica/ui/components/ui/input";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -60,6 +64,12 @@ import {
PRIORITY_DISPLAY_ORDER,
} from "@multica/core/issues/config";
import { StatusIcon, PriorityIcon } from ".";
+import {
+ FilterOperator,
+ RELATION_LABEL_KEY,
+ useFilterChips,
+ type FilterChip,
+} from "./filter-chips-bar";
import { useQuery } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
import { memberListOptions, agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
@@ -70,13 +80,11 @@ import { propertyListOptions } from "@multica/core/properties";
import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import type {
Issue,
- IssueProperty,
IssueTableFacetSpec,
IssueTableFacetsResponse,
ProjectStatus,
- WorkingAgentSummary,
} from "@multica/core/types";
-import { formatActorRef, isActorPropertyType, isFilterablePropertyType, isListPropertyType, isScalarPropertyType, propertyFilterValueKey, MAX_ISSUE_PROPERTY_FILTER_VALUES, PROPERTY_FILTER_OP_SYMBOLS, PROPERTY_FILTER_OPS_BY_TYPE, type PropertyFilterOp, type PropertyFilterValue } from "@multica/core/types";
+import { isFilterablePropertyType, propertyFilterValueKey, type PropertyFilterValue } from "@multica/core/types";
import { ProjectIcon } from "../../projects/components/project-icon";
import { useProjectStatusLabels } from "../../projects/components/labels";
import { ActorAvatar } from "../../common/actor-avatar";
@@ -90,9 +98,12 @@ import {
CARD_PROPERTY_OPTIONS,
cardPropertyOptionsForView,
sortOptionsForView,
+ ISSUE_RELATION_FILTERS,
type ActorFilterValue,
type IssueDateField,
type IssueDateFilter,
+ type IssueRelationFilter,
+ type NegatableFilterDimension,
type SortField,
type IssueGrouping,
type SwimlaneGrouping,
@@ -100,34 +111,34 @@ import {
type ViewMode,
} from "@multica/core/issues/stores/view-store";
import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
-import { FilterChipsBar } from "./filter-chips-bar";
-import { SaveViewDialog, type SaveViewScope } from "./save-view-dialog";
-import { ViewBar } from "./view-bar";
-import { toast } from "sonner";
-import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";
-import { useAuthStore } from "@multica/core/auth";
-import type { IssueViewScope } from "@multica/core/issue-views/queries";
-import { actorFilterKey, baselineFromQuery, type IssueViewBaseline } from "@multica/core/issue-views/baseline";
-import type { IssueView } from "@multica/core/api/schemas";
-import { addDaysDateOnly, dateOnlyToLocalDate, formatDateOnly, toDateOnly, todayDateOnly } from "@multica/core/issues/date";
import {
- useIssuesScope,
- useIssuesScopeStore,
- type IssuesScope,
- type IssuesScopePageKey,
-} from "@multica/core/issues/stores/issues-scope-store";
-import { actorKindForViewVariant } from "@multica/core/issues/surface/scope";
+ advancedFilterSignature,
+ countAdvancedConditions,
+ DUE_DATE_FILTERS,
+ NEGATABLE_FILTER_DIMENSIONS,
+ simpleFieldValues,
+ type AdvancedFilterGroup,
+} from "@multica/core/issues/stores/filter-tree";
+import { actorFilterKey, type IssueViewBaseline } from "@multica/core/issue-views/baseline";
+import { addDaysDateOnly, dateOnlyToLocalDate, formatDateOnly, toDateOnly, todayDateOnly } from "@multica/core/issues/date";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
-import { cn } from "@multica/ui/lib/utils";
-import { PAGE_GUTTER } from "../../layout/page-header";
import { useT } from "../../i18n";
import { useStatusOptions } from "../utils/status-options";
import { useColumnStatuses } from "../surface/column-statuses-context";
-import { NO_PROPERTY_VALUE } from "../utils/filter";
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
-import { WorkspaceAgentWorkingChip } from "./workspace-agent-working-chip";
import { TableColumnPicker } from "./table-view";
+import { DisplayChip, SortDirectionButton } from "./display-parts";
+import { AdvancedFilterPanel, stopMenuSearchKeys } from "./advanced-filter-panel";
+import { PropertyFilterOptions } from "./property-filter-options";
+import {
+ DUE_DATE_LABEL_KEY,
+ FILTER_FIELD_ICONS,
+ matchesFilterQuery,
+ toggleSimpleFilterValue,
+ useFilterFieldLabels,
+ useFilterValueCatalog,
+} from "./filter-field-options";
type LocalDateRange = {
from: Date | undefined;
@@ -147,7 +158,11 @@ function getActiveFilterCount(
includeNoProject: boolean;
projectStatusFilters: ProjectStatus[];
labelFilters: string[];
+ relationFilters: string[];
+ dueDateFilters: string[];
+ negatedFilters: NegatableFilterDimension[];
propertyFilters?: Record<string, PropertyFilterValue[]>;
+ advancedFilter?: AdvancedFilterGroup | null;
dateFilter?: IssueDateFilter | null;
},
// Inside a saved view only the user's additions on top of the view's own
@@ -155,21 +170,36 @@ function getActiveFilterCount(
baseline?: IssueViewBaseline,
) {
let count = 0;
+ const negated = new Set(state.negatedFilters);
+ // Flipping a view's own "is" to "is not" makes the whole dimension new.
+ const fixedFor = (dimension: NegatableFilterDimension, fixed?: Set<string>) =>
+ baseline && baseline.negated.has(dimension) === negated.has(dimension) ? fixed : undefined;
const delta = (values: string[], fixed?: Set<string>) =>
fixed ? values.filter((v) => !fixed.has(v)).length : values.length;
- if (delta(state.statusFilters, baseline?.status) > 0) count++;
- if (delta(state.priorityFilters, baseline?.priority) > 0) count++;
+ if (delta(state.statusFilters, fixedFor("status", baseline?.status)) > 0) count++;
+ if (delta(state.priorityFilters, fixedFor("priority", baseline?.priority)) > 0) count++;
+ const assigneeFixed = fixedFor("assignee", baseline?.assignee);
const assigneeDelta =
- delta(state.assigneeFilters.map(actorFilterKey), baseline?.assignee) > 0 ||
- (state.includeNoAssignee && !(baseline?.includeNoAssignee ?? false));
+ delta(state.assigneeFilters.map(actorFilterKey), assigneeFixed) > 0 ||
+ (state.includeNoAssignee && !(assigneeFixed && baseline?.includeNoAssignee));
if (assigneeDelta) count++;
- if (delta(state.creatorFilters.map(actorFilterKey), baseline?.creator) > 0) count++;
+ if (delta(state.creatorFilters.map(actorFilterKey), fixedFor("creator", baseline?.creator)) > 0) count++;
+ const projectFixed = fixedFor("project", baseline?.project);
const projectDelta =
- delta(state.projectFilters, baseline?.project) > 0 ||
- (state.includeNoProject && !(baseline?.includeNoProject ?? false));
+ delta(state.projectFilters, projectFixed) > 0 ||
+ (state.includeNoProject && !(projectFixed && baseline?.includeNoProject));
if (projectDelta) count++;
- if (delta(state.projectStatusFilters, baseline?.projectStatus) > 0) count++;
- if (delta(state.labelFilters, baseline?.label) > 0) count++;
+ if (delta(state.projectStatusFilters, fixedFor("projectStatus", baseline?.projectStatus)) > 0) count++;
+ if (delta(state.labelFilters, fixedFor("label", baseline?.label)) > 0) count++;
+ if (delta(state.relationFilters, fixedFor("relation", baseline?.relation)) > 0) count++;
+ if (delta(state.dueDateFilters, fixedFor("dueDate", baseline?.dueDate)) > 0) count++;
+ const advancedFilter = state.advancedFilter ?? null;
+ if (
+ !baseline ||
+ advancedFilterSignature(advancedFilter) !== advancedFilterSignature(baseline.raw.advancedFilter)
+ ) {
+ count += countAdvancedConditions(advancedFilter);
+ }
for (const [id, selected] of Object.entries(state.propertyFilters ?? {})) {
// Property members can be operator objects — compare through their
// canonical keys so a view-fixed operator still cancels out.
@@ -304,10 +334,6 @@ function useIssueCounts(
}, [allIssues, serverFacets]);
}
-// Scope config
-
-const SCOPE_VALUES: IssuesScope[] = ["all", "members", "agents"];
-
// Actor sub-menu content (shared between Assignee and Creator)
function ActorSubContent({
@@ -701,335 +727,6 @@ function LabelSubContent({
);
}
-/**
- * Option checkboxes for one custom property inside the Filter dropdown.
- * Select/multi_select list the definition's options (dot + name); checkbox
- * definitions expose the "true"/"false" pseudo-options with Yes/No labels;
- * actor definitions have no config options at all, so their candidates come
- * from the member directory instead, with the signed-in member first so
- * "this property is me" stays one click away.
- */
-
-// Keyboard guard for the inline operator radios — same contract as the
-// scalar input below: Escape/Tab belong to the menu (close / move focus);
-// every other navigation or selection key must not bubble into the popup's
-// typeahead / list-navigation handlers.
-function stopScalarMenuKeys(event: React.KeyboardEvent) {
- if (event.key === "Escape" || event.key === "Tab") return;
- event.stopPropagation();
-}
-function PropertyFilterOptions({
- property,
- counts,
- selected,
- onToggle,
- onSetValues,
- fixedIds,
- fixedTitle,
-}: {
- property: IssueProperty;
- counts: Map<string, number> | undefined;
- selected: PropertyFilterValue[];
- onToggle: (optionId: string) => void;
- /** Replace the property's full filter value set (scalar types only). */
- onSetValues: (optionIds: PropertyFilterValue[]) => void;
- fixedIds?: Set<string>;
- fixedTitle?: string;
-}) {
- const { t } = useT("issues");
- const wsId = useWorkspaceId();
- const currentUserId = useAuthStore((s) => s.user?.id);
- const actorProperty = isActorPropertyType(property.type);
- // Scalar properties (text / number / date / url) have no option list — the
- // filter menu shows a value input plus "No value".
- const { data: actorMembers = [] } = useQuery({
- ...memberListOptions(wsId),
- enabled: actorProperty,
- });
-
- const actorOptions = useMemo(() => {
- if (!actorProperty) return [];
- return actorMembers
- .slice()
- .sort((a, b) => {
- if (a.user_id === currentUserId) return -1;
- if (b.user_id === currentUserId) return 1;
- return 0;
- })
- .map((m) => ({
- id: formatActorRef("member", m.user_id),
- name: m.name,
- actorType: "member" as const,
- actorId: m.user_id,
- }));
- }, [actorProperty, actorMembers, currentUserId]);
-
- // "No value" is offered for every property type: it selects issues where the
- // property is unset, the inverse of picking one of the options below.
- const noValueOption = {
- id: NO_PROPERTY_VALUE,
- name: t(($) => $.pickers.custom_property.none),
- color: undefined as string | undefined,
- actorType: undefined as string | undefined,
- actorId: undefined as string | undefined,
- };
- // Scalar value state lives at the top level so the hooks stay unconditional
- // (Rules of Hooks): it is only rendered for text / number / date / url and
- // the list types (equality-only input), but must be declared regardless of
- // which branch runs. The draft syncs to the committed scalar member whenever
- // that changes, so a filter cleared or rewritten elsewhere cannot be written
- // back from a stale input.
- const committedMember = selected.find((member) => member !== NO_PROPERTY_VALUE);
- const committedScalar =
- typeof committedMember === "object" ? committedMember.value : (committedMember ?? "");
- const committedOp: PropertyFilterOp | "is" =
- typeof committedMember === "object" ? committedMember.op : "is";
- const hasNoValue = selected.includes(NO_PROPERTY_VALUE);
- const [draft, setDraft] = useState(committedScalar);
- useEffect(() => setDraft(committedScalar), [committedScalar]);
- // Operator picked in the open menu but not yet committed; null defers to the
- // committed member (equality when there is none). Resets whenever the
- // committed member changes — including right after this menu commits — so a
- // value rewritten elsewhere can't inherit a stale operator.
- const [pendingOp, setPendingOp] = useState<PropertyFilterOp | "is" | null>(null);
- const committedKey =
- committedMember === undefined
- ? ""
- : typeof committedMember === "object"
- ? `op:${committedMember.op}:${committedMember.value}`
- : `eq:${committedMember}`;
- useEffect(() => setPendingOp(null), [committedKey]);
- const options = [
- ...(actorProperty
- ? actorOptions.map((option) => ({
- id: option.id,
- name: option.name,
- color: undefined as string | undefined,
- actorType: option.actorType as string | undefined,
- actorId: option.actorId as string | undefined,
- }))
- : property.type === "checkbox"
- ? [
- { id: "true", name: t(($) => $.pickers.custom_property.true_label), color: undefined, actorType: undefined, actorId: undefined },
- { id: "false", name: t(($) => $.pickers.custom_property.false_label), color: undefined, actorType: undefined, actorId: undefined },
- ]
- : (property.config.options ?? []).map((option) => ({
- id: option.id,
- name: option.name,
- color: option.color as string | undefined,
- actorType: undefined as string | undefined,
- actorId: undefined as string | undefined,
- }))),
- noValueOption,
- ];
-
- if (isScalarPropertyType(property.type) || isListPropertyType(property.type)) {
- const placeholder =
- property.type === "url" || property.type === "multi_url"
- ? t(($) => $.pickers.custom_property.url_placeholder)
- : property.type === "number"
- ? t(($) => $.pickers.custom_property.number_placeholder)
- : t(($) => $.pickers.custom_property.value_placeholder);
- const noneCount = counts?.get(NO_PROPERTY_VALUE) ?? 0;
- // A saved view locks this dimension: the value (with its operator) AND
- // "No value" are both part of the view's identity, so neither can be
- // edited in place.
- const locked = fixedIds !== undefined && fixedIds.size > 0;
- // "is" is equality and commits a bare string — the pre-operator shape.
- // Every other op commits an operator object; the server and matcher both
- // treat unknown shapes conservatively.
- const effectiveOp: PropertyFilterOp | "is" = pendingOp ?? committedOp;
- const scalarOperatorLabel = (op: PropertyFilterOp): string => {
- if (op === "contains") return t(($) => $.pickers.custom_property.op_contains);
- if (op === "before") return t(($) => $.pickers.custom_property.op_before);
- if (op === "after") return t(($) => $.pickers.custom_property.op_after);
- return PROPERTY_FILTER_OP_SYMBOLS[op] ?? op;
- };
- // List types are equality-only: their PROPERTY_FILTER_OPS_BY_TYPE entry is
- // empty by design, and looking it up needs the scalar narrowing anyway
- // (IssueProperty.type is a lenient string).
- const scalarOps = isScalarPropertyType(property.type)
- ? (PROPERTY_FILTER_OPS_BY_TYPE[property.type] ?? [])
- : [];
- const opButtons: { op: PropertyFilterOp | "is"; label: string }[] = [
- {
- op: "is",
- label:
- property.type === "number"
- ? "="
- : t(($) => $.pickers.custom_property.op_is),
- },
- ...scalarOps.map((op) => ({
- op,
- label: scalarOperatorLabel(op),
- })),
- ];
- const commitValue = (raw: string, op: PropertyFilterOp | "is" = effectiveOp) => {
- const value = raw.trim();
- // NO_PROPERTY_VALUE is the reserved "no value" sentinel — it cannot be
- // filtered as a literal value. The value and "No value" compose like
- // every other property type: committing a value replaces only the value
- // member and preserves "No value" membership.
- if (value === NO_PROPERTY_VALUE) return;
- const member: PropertyFilterValue | undefined = value
- ? op === "is"
- ? value
- : { op, value }
- : undefined;
- onSetValues([
- ...(member ? [member] : []),
- ...(hasNoValue ? [NO_PROPERTY_VALUE] : []),
- ]);
- };
- const applyOp = (op: PropertyFilterOp | "is") => {
- // An explicit click commits the current draft with the chosen op, unlike
- // the input which waits for Enter/blur. With an empty draft nothing
- // commits, so the choice rides on pendingOp and the next Enter/blur
- // commit carries it — killing pendingOp here would silently downgrade
- // that later commit back to equality.
- setPendingOp(op);
- commitValue(draft, op);
- };
- return (
- <>
- {opButtons.length > 1 && (
- <div
- role="radiogroup"
- aria-label={t(($) => $.pickers.custom_property.operator_label)}
- className="flex flex-wrap gap-1 px-2 pt-1.5"
- >
- {opButtons.map(({ op, label }) => {
- const active = effectiveOp === op;
- return (
- <label
- key={op}
- className={locked ? "cursor-not-allowed" : "cursor-pointer"}
- >
- <input
- type="radio"
- name={`property-filter-op-${property.id}`}
- value={op}
- checked={active}
- disabled={locked}
- onChange={() => applyOp(op)}
- onKeyDown={stopScalarMenuKeys}
- className="peer sr-only"
- />
- <span
- className={`inline-flex h-6 items-center rounded-md px-1.5 text-caption transition-colors peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-ring ${
- active
- ? "bg-accent font-medium text-foreground"
- : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
- }`}
- >
- {label}
- </span>
- </label>
- );
- })}
- </div>
- )}
- <div className="px-2 py-1.5">
- <Input
- type={property.type === "number" ? "number" : property.type === "date" ? "date" : "text"}
- step={property.type === "number" ? "any" : undefined}
- inputMode={property.type === "number" ? "decimal" : undefined}
- value={draft}
- onChange={(event) => setDraft(event.target.value)}
- onBlur={(event) => {
- // Clicking the "No value" menu item moves focus off the input,
- // firing blur first. That premature commit would flip the
- // checkbox's controlled state before its click handler reads it
- // — so when focus moves into a menu item in this popup, skip the
- // blur commit and let onCheckedChange decide from the pre-blur
- // state.
- const next = event.relatedTarget;
- const movedToMenuItem =
- next instanceof HTMLElement &&
- next.closest('[role="menuitemcheckbox"]') !== null;
- if (!movedToMenuItem) commitValue(draft);
- }}
- onKeyDown={(event) => {
- // Base UI's menu popup merges typeahead + list-navigation handlers
- // onto the role="menu" element and stopEvent()s every printable
- // key — without stopping propagation, the input would swallow no
- // characters at all (and arrow keys on number/date inputs would
- // be hijacked). Escape/Tab are left for the menu to close/move
- // focus; Enter commits and still needs stopPropagation so it does
- // not bubble up and activate the highlighted "No value" item.
- if (event.key === "Escape" || event.key === "Tab") return;
- if (event.key === "Enter") commitValue(draft);
- event.stopPropagation();
- }}
- disabled={locked}
- placeholder={placeholder}
- className="h-8"
- />
- </div>
- <DropdownMenuCheckboxItem
- checked={hasNoValue}
- disabled={locked}
- onCheckedChange={(checked) => {
- // "No value" toggles membership in the same OR-set as the value —
- // checking/unchecking never touches the committed value member, so
- // unchecking restores it without any draft round-trip.
- const valueMembers = selected.filter((id) => id !== NO_PROPERTY_VALUE);
- onSetValues(
- checked
- ? [...valueMembers, NO_PROPERTY_VALUE]
- : valueMembers,
- );
- }}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={hasNoValue} />
- <span className="truncate">{noValueOption.name}</span>
- {noneCount > 0 && (
- <span className="ml-auto text-caption text-muted-foreground">{noneCount}</span>
- )}
- </DropdownMenuCheckboxItem>
- </>
- );
- }
-
- const atCapacity = selected.length >= MAX_ISSUE_PROPERTY_FILTER_VALUES;
- return (
- <>
- {options.map((option) => {
- const checked = selected.includes(option.id);
- const count = counts?.get(option.id) ?? 0;
- return (
- <DropdownMenuCheckboxItem
- key={option.id}
- checked={checked}
- disabled={fixedIds?.has(option.id) === true || (atCapacity && !checked)}
- title={fixedIds?.has(option.id) === true ? fixedTitle : undefined}
- onCheckedChange={() => onToggle(option.id)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={checked} />
- {option.actorType && option.actorId && (
- <ActorAvatar actorType={option.actorType} actorId={option.actorId} size="sm" />
- )}
- {option.color && (
- <span
- className="size-2.5 shrink-0 rounded-full"
- style={{ backgroundColor: option.color }}
- />
- )}
- <span className="truncate">{option.name}</span>
- {count > 0 && (
- <span className="ml-auto text-caption text-muted-foreground">
- {count}
- </span>
- )}
- </DropdownMenuCheckboxItem>
- );
- })}
- </>
- );
-}
-
// Date sub-menu content
function DateSubContent({
@@ -1177,254 +874,108 @@ export function ViewRefreshIndicator({ active }: { active: boolean }) {
);
}
-// IssuesHeader
-
-export function IssuesHeader({
- scopedIssues,
- workingAgents,
- allowGantt = false,
- dateFilter = null,
- onDateFilterChange,
- isRefreshing,
- facetCountsExact = true,
- tableFacetCounts,
- onTableFacetChange,
- saveViewScope = { kind: "workspace" },
+/** What a dimension is filtering on, in its row of the filter menu: the
+ * relation word, the values, and a dot when it differs from the saved view. */
+function FilterTriggerValue({
+ chip,
+ modified = false,
}: {
- scopedIssues: Issue[];
- /** See IssueSurfaceController.workingAgents — the surface-scoped projection
- * behind the agents-working chip. */
- workingAgents: WorkingAgentSummary[] | undefined;
- allowGantt?: boolean;
- dateFilter?: IssueDateFilter | null;
- onDateFilterChange?: (filter: IssueDateFilter | null) => void;
- /** Omit when the page title already displays refresh feedback. */
- isRefreshing?: boolean;
- /** See IssueDisplayControls.facetCountsExact. */
- facetCountsExact?: boolean;
- tableFacetCounts?: IssueTableFacetsResponse;
- onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;
- /** Where "save as view" files the view. /issues keeps the workspace
- * default; the project-detail fallback passes its project scope; `null`
- * hides the save affordance entirely. */
- saveViewScope?: SaveViewScope | null;
+ chip: FilterChip | undefined;
+ modified?: boolean;
}) {
- const { t } = useT("issues");
- const [saveViewOpen, setSaveViewOpen] = useState(false);
- const headerWsId = useWorkspaceId();
- const viewListScope: IssueViewScope | null = saveViewScope
- ? saveViewScope.kind === "project"
- ? { scope_type: "project", scope_id: saveViewScope.projectId }
- : { scope_type: saveViewScope.kind }
- : null;
- const { activeView, views, viewsReady, setActive, missing } = useActiveIssueView(
- headerWsId,
- viewListScope,
- );
- // The open view vanished (deleted / access revoked): fall back to the
- // built-in default and say so — never a blank page (§7).
- useEffect(() => {
- if (missing) {
- setActive(null);
- toast.info(t(($) => $.view_selector.unavailable));
- }
- }, [missing, setActive, t]);
- const viewBaseline = useMemo(
- () => (activeView ? baselineFromQuery(activeView.query) : undefined),
- [activeView],
- );
- const [editTarget, setEditTarget] = useState<{
- view: IssueView;
- fromDefinition: boolean;
- } | null>(null);
- const currentUserId = useAuthStore((s) => s.user?.id ?? null);
- const isViewOwner = !!activeView && activeView.owner_id === currentUserId;
- // The tab belongs to THIS page (Issues vs each project) — see
- // IssuesScopePageKey. The header both renders the tabs and seeds the
- // save-view dialog's default variant from them.
- const scopePage: IssuesScopePageKey =
- saveViewScope?.kind === "project"
- ? `project:${saveViewScope.projectId}`
- : "issues";
- const scope = useIssuesScope(scopePage);
- const setScopeForPage = useIssuesScopeStore((s) => s.setScope);
- const setScope = useCallback(
- (next: IssuesScope) => setScopeForPage(scopePage, next),
- [setScopeForPage, scopePage],
- );
- // The save dialog's default variant: while a saved view is open the view's
- // own variant wins (the rows on screen ARE that variant — a copy must not
- // silently widen to the page tab); otherwise the page tab applies.
- const dialogActorKind = activeView
- ? actorKindForViewVariant(activeView.scope_variant)
- : scope;
- const dialogProjectId =
- saveViewScope?.kind === "project" ? saveViewScope.projectId : null;
- const dialogMyVariant =
- saveViewScope?.kind === "my" ? saveViewScope.variant : null;
- const dialogScope = useMemo<SaveViewScope | null>(() => {
- if (dialogMyVariant) return { kind: "my", variant: dialogMyVariant };
- if (dialogProjectId)
- return {
- kind: "project",
- projectId: dialogProjectId,
- actorKind: dialogActorKind,
- };
- if (saveViewScope) return { kind: "workspace", actorKind: dialogActorKind };
- return null;
- // eslint-disable-next-line react-hooks/exhaustive-deps -- identity keyed on the primitive projections
- }, [dialogMyVariant, dialogProjectId, dialogActorKind, !!saveViewScope]);
- // Bind the workspace agents-working chip to the active view store so
- // shared IssuesHeader consumers (/issues and project detail) toggle the
- // same filter state as the rest of the display controls. /my-issues keeps
- // its own sibling header and passes chip state explicitly.
- const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);
- const toggleAgentRunningFilter = useViewStore(
- (s) => s.toggleAgentRunningFilter,
+ if (!chip) return null;
+ return (
+ <span className="ml-3 flex min-w-0 items-center gap-1 text-caption">
+ <FilterOperator negated={chip.negated} />
+ <span className="max-w-40 truncate font-medium text-primary">{chip.value}</span>
+ {modified && <ModifiedDot />}
+ </span>
);
- const SCOPE_LABEL_KEY: Record<IssuesScope, "all_label" | "members_label" | "agents_label"> = {
- all: "all_label",
- members: "members_label",
- agents: "agents_label",
- };
- const SCOPE_DESC_KEY: Record<IssuesScope, "all_description" | "members_description" | "agents_description"> = {
- all: "all_description",
- members: "members_description",
- agents: "agents_description",
- };
+}
+
+function ModifiedDot() {
+ const { t } = useT("issues");
+ const label = t(($) => $.filters.modified_hint);
+ return <span role="img" aria-label={label} title={label} className="size-1.5 shrink-0 rounded-full bg-brand" />;
+}
- const scopeLabel = t(($) => $.scope[SCOPE_LABEL_KEY[scope]]);
+const OPERATOR_SEGMENT_CLASS =
+ "h-6 flex-1 justify-center rounded-md px-3 py-0 text-caption text-muted-foreground focus:bg-background/60 data-checked:bg-background data-checked:font-medium data-checked:text-foreground data-checked:shadow-xs [&>[data-slot=dropdown-menu-radio-item-indicator]]:hidden";
+/** "Is" / "is not" for one dimension, heading its submenu. Radio items keep
+ * it in the menu's keyboard order; the selection below is left as it is. */
+function FilterOperatorSwitch({ dimension }: { dimension: NegatableFilterDimension }) {
+ const { t } = useT("issues");
+ const negated = useViewStore((s) => s.negatedFilters.includes(dimension));
+ const setFilterNegated = useViewStore((s) => s.setFilterNegated);
return (
<>
- <div className={cn("min-h-12 shrink-0 py-2 [-webkit-overflow-scrolling:touch]", PAGE_GUTTER)}>
- <div className="flex w-full min-w-0 items-start justify-between gap-2">
- {/* Left: the view bar — built-in tabs and saved views as one flat,
- per-user ordered row; wraps instead of overflowing. */}
- <div className="hidden min-w-0 flex-1 md:block">
- {saveViewScope && viewListScope && (
- <ViewBar
- wsId={headerWsId}
- scope={viewListScope}
- builtins={SCOPE_VALUES.map((s) => ({
- key: s,
- label: t(($) => $.scope[SCOPE_LABEL_KEY[s]]),
- description: t(($) => $.scope[SCOPE_DESC_KEY[s]]),
- active: !activeView && scope === s,
- onSelect: () => {
- // Built-in tabs exit any open saved view; the surface
- // returns to its untouched per-tab state.
- if (activeView) setActive(null);
- setScope(s);
- },
- }))}
- views={views}
- viewsReady={viewsReady}
- activeView={activeView}
- onSelectView={(view) => setActive(view ? view.id : null)}
- onNewView={() => {
- setEditTarget(null);
- setSaveViewOpen(true);
- }}
- onEditView={(view) => {
- setEditTarget({ view, fromDefinition: true });
- setSaveViewOpen(true);
- }}
- />
- )}
- </div>
+ <DropdownMenuRadioGroup
+ aria-label={t(($) => $.filters.operator_label)}
+ value={negated ? "is_not" : "is"}
+ onValueChange={(value) => setFilterNegated(dimension, value === "is_not")}
+ className="m-1 flex gap-0.5 rounded-lg bg-muted p-0.5"
+ >
+ <DropdownMenuRadioItem value="is" closeOnClick={false} className={OPERATOR_SEGMENT_CLASS}>
+ {t(($) => $.filters.operator_is)}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="is_not" closeOnClick={false} className={OPERATOR_SEGMENT_CLASS}>
+ {t(($) => $.filters.operator_is_not)}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ </>
+ );
+}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 gap-1 text-muted-foreground md:hidden"
- >
- <span className="truncate">{scopeLabel}</span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup value={scope} onValueChange={(value) => setScope(value as IssuesScope)}>
- {SCOPE_VALUES.map((s) => (
- <DropdownMenuRadioItem key={s} value={s}>
- {t(($) => $.scope[SCOPE_LABEL_KEY[s]])}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
+const RELATION_ICONS: Record<IssueRelationFilter, typeof User> = {
+ assigned: CircleUser,
+ created: UserPen,
+ my_agents: Bot,
+};
- <div className="flex shrink-0 items-center gap-1">
- {agentRunningFilter && (
- <span className="mr-1 hidden text-caption text-muted-foreground md:inline">
- {t(($) => $.agent_activity.filter_active_label)}
- </span>
- )}
- <WorkspaceAgentWorkingChip
- value={agentRunningFilter}
- onToggle={toggleAgentRunningFilter}
- agents={workingAgents}
- />
- <IssueDisplayControls
- scopedIssues={scopedIssues}
- allowGantt={allowGantt}
- dateFilter={dateFilter}
- onDateFilterChange={onDateFilterChange}
- facetCountsExact={facetCountsExact}
- tableFacetCounts={tableFacetCounts}
- onTableFacetChange={onTableFacetChange}
- viewBaseline={viewBaseline}
- />
- {isRefreshing !== undefined && <ViewRefreshIndicator active={isRefreshing} />}
- </div>
+/** Read-only sentence form of the active filters, shown on hover so a closed
+ * menu still says what the surface is narrowed to. */
+function FilterSummary({
+ title,
+ chips,
+ modifiedKeys,
+}: {
+ title: string;
+ chips: FilterChip[];
+ modifiedKeys?: ReadonlySet<string>;
+}) {
+ const { t } = useT("issues");
+ const modifiedCount = chips.filter((chip) => modifiedKeys?.has(chip.key)).length;
+ return (
+ <div className="flex w-72 flex-col gap-1 py-1">
+ <div className="mb-1 flex items-center gap-1.5 font-medium">
+ <Filter className="size-3.5" />
+ <span className="truncate">{title}</span>
</div>
+ {chips.map((chip) => (
+ <div key={chip.key} className="flex min-w-0 items-center gap-1.5">
+ {chip.icon}
+ <span className="shrink-0 text-muted-foreground">{chip.label}</span>
+ <FilterOperator negated={chip.negated} />
+ <span className="min-w-0 truncate">{chip.value}</span>
+ {modifiedKeys?.has(chip.key) && <ModifiedDot />}
+ </div>
+ ))}
+ {modifiedCount > 0 && (
+ <div className="mt-1 flex items-center gap-1.5 border-t border-border pt-1.5 text-muted-foreground">
+ <ModifiedDot />
+ {t(($) => $.filters.unsaved_changes, { count: modifiedCount })}
+ </div>
+ )}
</div>
- <FilterChipsBar
- dateFilter={dateFilter}
- onDateFilterChange={onDateFilterChange}
- viewBaseline={viewBaseline}
- saveLabel={
- activeView
- ? isViewOwner
- ? t(($) => $.filters.chip_edit)
- : t(($) => $.filters.chip_save_as)
- : undefined
- }
- onSave={
- saveViewScope
- ? () => {
- setEditTarget(
- activeView && isViewOwner
- ? { view: activeView, fromDefinition: false }
- : null,
- );
- setSaveViewOpen(true);
- }
- : undefined
- }
- />
- {dialogScope && (
- <SaveViewDialog
- open={saveViewOpen}
- onOpenChange={setSaveViewOpen}
- scope={dialogScope}
- editView={editTarget?.view ?? null}
- seedFromDefinition={editTarget?.fromDefinition ?? false}
- />
- )}
- </>
);
}
/**
* The full filter menu (every dimension, search, counts) behind a caller-
- * supplied trigger. The toolbar wraps it in its labeled button; the
- * save-view dialog attaches it to a ghost "add filter" chip targeting the
- * draft store. Counts follow `scopedIssues` — pass nothing to hide them.
+ * supplied trigger. Counts follow `scopedIssues` — pass nothing to hide
+ * them.
*/
export function IssueFilterMenu({
trigger,
@@ -1438,9 +989,27 @@ export function IssueFilterMenu({
onOpenChange,
freezeAnchor = false,
viewBaseline,
+ leadingSections,
+ align = "end",
+ showRelation = true,
+ hiddenFields,
+ modifiedKeys,
+ summaryTitle,
}: {
trigger: React.ReactElement;
+ align?: "start" | "end";
+ /** Rendered above the filter dimensions, e.g. the surface's scope axis. */
+ leadingSections?: React.ReactNode;
tooltip?: string;
+ /** Offer "relation to me". A surface already scoped to me hides it. */
+ showRelation?: boolean;
+ /** Fields the scope already fixes, left out of search and advanced mode. */
+ hiddenFields?: readonly NegatableFilterDimension[];
+ /** Chip keys whose condition differs from the open saved view. */
+ modifiedKeys?: ReadonlySet<string>;
+ /** With active filters, hovering the trigger shows them as sentences under
+ * this title instead of `tooltip`. */
+ summaryTitle?: string;
scopedIssues?: Issue[];
facetCountsExact?: boolean;
tableFacetCounts?: IssueTableFacetsResponse;
@@ -1469,9 +1038,27 @@ export function IssueFilterMenu({
const includeNoProject = useViewStore((s) => s.includeNoProject);
const projectStatusFilters = useViewStore((s) => s.projectStatusFilters);
const labelFilters = useViewStore((s) => s.labelFilters);
+ const relationFilters = useViewStore((s) => s.relationFilters);
+ const dueDateFilters = useViewStore((s) => s.dueDateFilters);
+ const advancedFilter = useViewStore((s) => s.advancedFilter);
+ const negatedFilters = useViewStore((s) => s.negatedFilters);
const propertyFilters = useViewStore((s) => s.propertyFilters);
const viewStoreApi = useViewStoreApi();
const act = viewStoreApi.getState();
+ const advancedMode = advancedFilter !== null;
+ const [panelOpen, setPanelOpen] = useState(false);
+ // Leaving advanced mode from inside the panel unmounts it with no close
+ // event; the next entry must start closed until asked.
+ useEffect(() => {
+ if (!advancedMode) setPanelOpen(false);
+ }, [advancedMode]);
+ const [search, setSearch] = useState("");
+ const query = search.trim().toLowerCase();
+ const fieldLabels = useFilterFieldLabels();
+ const valueCatalog = useFilterValueCatalog(query.length > 0);
+ const searchFields = NEGATABLE_FILTER_DIMENSIONS.filter(
+ (field) => (showRelation || field !== "relation") && !hiddenFields?.includes(field),
+ );
const wsId = useWorkspaceId();
const statusOptions = useStatusOptions(wsId);
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
@@ -1504,11 +1091,23 @@ export function IssueFilterMenu({
includeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters: showRelation ? relationFilters : [],
+ dueDateFilters,
+ negatedFilters,
+ advancedFilter,
dateFilter: showDateFilter ? dateFilter : null,
},
viewBaseline,
) > 0;
const fixedTitle = viewBaseline ? t(($) => $.filters.in_view) : undefined;
+ const { chips: allChips } = useFilterChips(showDateFilter ? dateFilter : null, onDateFilterChange, viewBaseline);
+ const chips = showRelation ? allChips : allChips.filter((chip) => chip.key !== "relation");
+ const chipByKey = new Map(chips.map((chip) => [chip.key, chip]));
+ const triggerValue = (key: string) => (
+ <FilterTriggerValue chip={chipByKey.get(key)} modified={modifiedKeys?.has(key)} />
+ );
+ const [activeAtOpen, setActiveAtOpen] = useState<ReadonlySet<string> | null>(null);
+ const activeKeys = activeAtOpen ?? new Set(chipByKey.keys());
const dateFilterLabel = showDateFilter && dateFilter
? `${t(($) => $.filters[DATE_FIELD_LABEL_KEY[dateFilter.field]])}: ${
dateFilter.from === dateFilter.to
@@ -1517,37 +1116,24 @@ export function IssueFilterMenu({
}`
: null;
- // Base UI's render-prop merges its own ref with ours, so cloning the
- // caller's element only adds the ref we need for rect capture.
- const anchoredTrigger = freezeAnchor
- ? cloneElement(trigger, { ref: triggerRef } as Partial<React.HTMLAttributes<HTMLElement>>)
- : trigger;
-
- return (
- <DropdownMenu
- onOpenChange={(open) => {
- if (freezeAnchor) {
- if (open && triggerRef.current) {
- const rect = triggerRef.current.getBoundingClientRect();
- setFrozenAnchor({ getBoundingClientRect: () => rect });
- } else if (!open) {
- setFrozenAnchor(null);
- }
- }
- if (!open) onTableFacetChange?.(null);
- onOpenChange?.(open);
- }}
- >
- {tooltip ? (
- <Tooltip>
- <DropdownMenuTrigger render={<TooltipTrigger render={anchoredTrigger} />} />
- <TooltipContent side="bottom">{tooltip}</TooltipContent>
- </Tooltip>
- ) : (
- <DropdownMenuTrigger render={anchoredTrigger} />
- )}
- <DropdownMenuContent align="end" className="w-auto" anchor={frozenAnchor ?? undefined}>
+ // One list of dimensions rendered in two passes: the ones already
+ // filtering on first, then the rest. Membership is taken when the menu
+ // opens, so a row never jumps out from under the pointer mid-edit.
+ const inPass = (key: string, pass: "active" | "rest") =>
+ activeKeys.has(key) === (pass === "active");
+ const sectionLabel = (key: string) =>
+ key === "date"
+ ? t(($) => $.filters.section_date)
+ : key.startsWith("property:")
+ ? filterableProperties.find((p) => `property:${p.id}` === key)?.name ?? ""
+ : fieldLabels[key as NegatableFilterDimension] ?? "";
+ const renderFieldSections = (pass: "active" | "rest" | "search") => {
+ const show = (key: string) =>
+ pass === "search" ? matchesFilterQuery(sectionLabel(key), query) : inPass(key, pass);
+ return (
+ <>
{/* Status */}
+ {show("status") && (
<DropdownMenuSub
onOpenChange={(open) =>
onTableFacetChange?.(open ? { kind: "status" } : null)
@@ -1556,13 +1142,10 @@ export function IssueFilterMenu({
<DropdownMenuSubTrigger>
<CircleDot className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_status)}</span>
- {statusFilters.length > 0 && (
- <span className="text-caption text-primary font-medium">
- {statusFilters.length}
- </span>
- )}
+ {triggerValue("status")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-48">
+ <FilterOperatorSwitch dimension="status" />
{/* Options come from the workspace catalog, so a custom status
is filterable — otherwise an issue moved onto one could not
be narrowed to. One flat list in category order: the icon
@@ -1601,8 +1184,10 @@ export function IssueFilterMenu({
})}
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
{/* Priority */}
+ {show("priority") && (
<DropdownMenuSub
onOpenChange={(open) =>
onTableFacetChange?.(open ? { kind: "priority" } : null)
@@ -1611,13 +1196,10 @@ export function IssueFilterMenu({
<DropdownMenuSubTrigger>
<SignalHigh className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_priority)}</span>
- {priorityFilters.length > 0 && (
- <span className="text-caption text-primary font-medium">
- {priorityFilters.length}
- </span>
- )}
+ {triggerValue("priority")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-44">
+ <FilterOperatorSwitch dimension="priority" />
{PRIORITY_DISPLAY_ORDER.map((p) => {
const checked = priorityFilters.includes(p);
const count = counts.priority.get(p) ?? 0;
@@ -1644,8 +1226,9 @@ export function IssueFilterMenu({
})}
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
- {showDateFilter && onDateFilterChange && (
+ {showDateFilter && onDateFilterChange && show("date") && (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<CalendarDays className="size-3.5" />
@@ -1666,6 +1249,7 @@ export function IssueFilterMenu({
)}
{/* Assignee */}
+ {show("assignee") && (
<DropdownMenuSub
onOpenChange={(open) =>
onTableFacetChange?.(open ? { kind: "assignee" } : null)
@@ -1674,13 +1258,10 @@ export function IssueFilterMenu({
<DropdownMenuSubTrigger>
<User className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_assignee)}</span>
- {(assigneeFilters.length > 0 || includeNoAssignee) && (
- <span className="text-caption text-primary font-medium">
- {assigneeFilters.length + (includeNoAssignee ? 1 : 0)}
- </span>
- )}
+ {triggerValue("assignee")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-52 p-0">
+ <FilterOperatorSwitch dimension="assignee" />
<ActorSubContent
counts={counts.assignee}
selected={assigneeFilters}
@@ -1695,8 +1276,10 @@ export function IssueFilterMenu({
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
{/* Creator */}
+ {show("creator") && (
<DropdownMenuSub
onOpenChange={(open) =>
onTableFacetChange?.(open ? { kind: "creator" } : null)
@@ -1705,13 +1288,10 @@ export function IssueFilterMenu({
<DropdownMenuSubTrigger>
<UserPen className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_creator)}</span>
- {creatorFilters.length > 0 && (
- <span className="text-caption text-primary font-medium">
- {creatorFilters.length}
- </span>
- )}
+ {triggerValue("creator")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-52 p-0">
+ <FilterOperatorSwitch dimension="creator" />
<ActorSubContent
counts={counts.creator}
selected={creatorFilters}
@@ -1722,8 +1302,44 @@ export function IssueFilterMenu({
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
+
+ {/* Relation to me — OR across assigned / created / my agents,
+ which no single actor dimension can express. */}
+ {showRelation && show("relation") && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <CircleUser className="size-3.5" />
+ <span className="flex-1">{t(($) => $.filters.section_relation)}</span>
+ {triggerValue("relation")}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-52">
+ <FilterOperatorSwitch dimension="relation" />
+ {ISSUE_RELATION_FILTERS.map((relation) => {
+ const checked = relationFilters.includes(relation);
+ const fixed = viewBaseline?.relation.has(relation) === true;
+ const Icon = RELATION_ICONS[relation];
+ return (
+ <DropdownMenuCheckboxItem
+ key={relation}
+ checked={checked}
+ disabled={fixed}
+ title={fixed ? fixedTitle : undefined}
+ onCheckedChange={() => act.toggleRelationFilter(relation)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ <Icon className="size-3.5 text-muted-foreground" />
+ {t(($) => $.filters[RELATION_LABEL_KEY[relation]])}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
{/* Project */}
+ {show("project") && (
<DropdownMenuSub
onOpenChange={(open) =>
onTableFacetChange?.(open ? { kind: "project" } : null)
@@ -1732,13 +1348,10 @@ export function IssueFilterMenu({
<DropdownMenuSubTrigger>
<FolderKanban className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_project)}</span>
- {(projectFilters.length > 0 || includeNoProject) && (
- <span className="text-caption text-primary font-medium">
- {projectFilters.length + (includeNoProject ? 1 : 0)}
- </span>
- )}
+ {triggerValue("project")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-52 p-0">
+ <FilterOperatorSwitch dimension="project" />
<ProjectSubContent
counts={counts.project}
selected={projectFilters}
@@ -1752,21 +1365,20 @@ export function IssueFilterMenu({
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
{/* Project status — a dimension of its own next to Project:
"everything in the projects that are in progress", without
naming them one by one. */}
+ {show("projectStatus") && (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<CircleDashed className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_project_status)}</span>
- {projectStatusFilters.length > 0 && (
- <span className="text-caption text-primary font-medium">
- {projectStatusFilters.length}
- </span>
- )}
+ {triggerValue("projectStatus")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-52 p-0">
+ <FilterOperatorSwitch dimension="projectStatus" />
<ProjectStatusSubContent
selected={projectStatusFilters}
onToggle={act.toggleProjectStatusFilter}
@@ -1775,8 +1387,10 @@ export function IssueFilterMenu({
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
{/* Label */}
+ {show("label") && (
<DropdownMenuSub
onOpenChange={(open) =>
onTableFacetChange?.(open ? { kind: "label" } : null)
@@ -1785,13 +1399,10 @@ export function IssueFilterMenu({
<DropdownMenuSubTrigger>
<Tag className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_label)}</span>
- {labelFilters.length > 0 && (
- <span className="text-caption text-primary font-medium">
- {labelFilters.length}
- </span>
- )}
+ {triggerValue("label")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-52 p-0">
+ <FilterOperatorSwitch dimension="label" />
<LabelSubContent
counts={counts.label}
selected={labelFilters}
@@ -1801,10 +1412,44 @@ export function IssueFilterMenu({
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
+ )}
+
+ {/* Due date — relative buckets, so a saved view keeps meaning
+ "overdue" tomorrow. */}
+ {show("dueDate") && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <CalendarClock className="size-3.5" />
+ <span className="flex-1">{t(($) => $.filters.section_due_date)}</span>
+ {triggerValue("dueDate")}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-52">
+ <FilterOperatorSwitch dimension="dueDate" />
+ {DUE_DATE_FILTERS.map((bucket) => {
+ const checked = dueDateFilters.includes(bucket);
+ const fixed = viewBaseline?.dueDate.has(bucket) === true;
+ return (
+ <DropdownMenuCheckboxItem
+ key={bucket}
+ checked={checked}
+ disabled={fixed}
+ title={fixed ? fixedTitle : undefined}
+ onCheckedChange={() => act.toggleDueDateFilter(bucket)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ <CalendarClock className="size-3.5 text-muted-foreground" />
+ {t(($) => $.filters[DUE_DATE_LABEL_KEY[bucket]])}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
{/* Custom properties — one sub per filterable definition */}
- {filterableProperties.length > 0 && <DropdownMenuSeparator />}
- {filterableProperties.map((property) => {
+ {pass === "rest" && filterableProperties.some((p) => show(`property:${p.id}`)) && <DropdownMenuSeparator />}
+ {filterableProperties.filter((property) => show(`property:${property.id}`)).map((property) => {
const selected = propertyFilters[property.id] ?? [];
return (
<DropdownMenuSub
@@ -1824,11 +1469,7 @@ export function IssueFilterMenu({
<SlidersHorizontal className="size-3.5" />
)}
<span className="flex-1 truncate">{property.name}</span>
- {selected.length > 0 && (
- <span className="text-caption text-primary font-medium">
- {selected.length}
- </span>
- )}
+ {triggerValue(`property:${property.id}`)}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-44 p-1">
<PropertyFilterOptions
@@ -1845,31 +1486,234 @@ export function IssueFilterMenu({
);
})}
- {/* Reset */}
- {hasActiveFilters && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => {
- if (viewBaseline) {
- // Inside a saved view, reset returns to the view's own
- // conditions, never to nothing.
- act.resetFiltersTo(viewBaseline.raw);
- } else {
- act.clearFilters();
- }
- onDateFilterChange?.(null);
- }}
- >
- {t(($) => $.filters.reset)}
- </DropdownMenuItem>
- </>
- )}
+ </>
+ );
+ };
+
+ // Base UI's render-prop merges its own ref with ours, so cloning the
+ // caller's element only adds the ref we need for rect capture.
+ const anchoredTrigger = freezeAnchor
+ ? cloneElement(trigger, { ref: triggerRef } as Partial<React.HTMLAttributes<HTMLElement>>)
+ : trigger;
+
+ // Search: matching fields keep their submenus; matching values become
+ // one-click rows that read as the condition they add.
+ const simpleFields = {
+ statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters,
+ projectFilters, includeNoProject, projectStatusFilters, labelFilters, relationFilters,
+ dueDateFilters,
+ };
+ const negatedSet = new Set(negatedFilters);
+ const fixedValue = (field: NegatableFilterDimension, value: string) => {
+ if (!viewBaseline) return false;
+ if (value === "none" && field === "assignee") return viewBaseline.includeNoAssignee;
+ if (value === "none" && field === "project") return viewBaseline.includeNoProject;
+ return viewBaseline[field].has(value);
+ };
+ const sectionKeys = [
+ ...searchFields.filter((field) => field !== "relation" || showRelation),
+ ...(showDateFilter ? ["date"] : []),
+ ...filterableProperties.map((p) => `property:${p.id}`),
+ ];
+ const fieldHits = query ? sectionKeys.filter((key) => matchesFilterQuery(sectionLabel(key), query)) : [];
+ const valueHits = query
+ ? searchFields
+ .flatMap((field) =>
+ valueCatalog(field)
+ .filter((option) => matchesFilterQuery(option.label, query))
+ .map((option) => ({ field, option })),
+ )
+ .slice(0, 50)
+ : [];
+
+ const menuBody = query ? (
+ <>
+ {fieldHits.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.filters.search_fields)}</DropdownMenuLabel>
+ {renderFieldSections("search")}
+ </DropdownMenuGroup>
+ )}
+ {fieldHits.length > 0 && valueHits.length > 0 && <DropdownMenuSeparator />}
+ {valueHits.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.filters.search_values)}</DropdownMenuLabel>
+ {valueHits.map(({ field, option }) => {
+ const checked = simpleFieldValues(simpleFields, field).includes(option.value);
+ const fixed = fixedValue(field, option.value);
+ const FieldIcon = FILTER_FIELD_ICONS[field];
+ return (
+ <DropdownMenuCheckboxItem
+ key={`${field}:${option.value}`}
+ checked={checked}
+ disabled={fixed}
+ title={fixed ? fixedTitle : undefined}
+ onCheckedChange={() => toggleSimpleFilterValue(act, field, option.value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ <FieldIcon className="size-3.5 text-muted-foreground" />
+ <span className="shrink-0 text-muted-foreground">{fieldLabels[field]}</span>
+ <FilterOperator negated={negatedSet.has(field)} />
+ {option.icon}
+ <span className="truncate">{option.label}</span>
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuGroup>
+ )}
+ {fieldHits.length === 0 && valueHits.length === 0 && (
+ <div className="px-2 py-3 text-center text-body text-muted-foreground">
+ {t(($) => $.filters.no_results)}
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ {leadingSections && (
+ <>
+ {leadingSections}
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {activeKeys.size > 0 && (
+ <>
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.filters.active_section)}</DropdownMenuLabel>
+ {renderFieldSections("active")}
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {renderFieldSections("rest")}
+
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => {
+ act.enterAdvancedFilter();
+ setPanelOpen(true);
+ }}
+ >
+ <ListTree className="size-3.5" />
+ {t(($) => $.filters.advanced_switch)}
+ </DropdownMenuItem>
+
+ {/* Reset */}
+ {hasActiveFilters && (
+ <DropdownMenuItem
+ onClick={() => {
+ if (viewBaseline) {
+ // Inside a saved view, reset returns to the view's own
+ // conditions, never to nothing.
+ act.resetFiltersTo(viewBaseline.raw);
+ } else {
+ act.clearFilters();
+ }
+ onDateFilterChange?.(null);
+ }}
+ >
+ {t(($) => $.filters.reset)}
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+
+ const tooltipContent =
+ summaryTitle && chips.length > 0 ? (
+ <TooltipContent side="bottom" align="start" className="max-w-sm">
+ <FilterSummary title={summaryTitle} chips={chips} modifiedKeys={modifiedKeys} />
+ </TooltipContent>
+ ) : (
+ <TooltipContent side="bottom">{tooltip}</TooltipContent>
+ );
+ const withTooltip = !!(summaryTitle || tooltip);
+
+ // Advanced mode: the same trigger opens the rule panel instead of the menu.
+ if (advancedMode) {
+ return (
+ <Popover
+ open={panelOpen}
+ onOpenChange={(open) => {
+ setPanelOpen(open);
+ onOpenChange?.(open);
+ }}
+ >
+ {withTooltip ? (
+ <Tooltip disabled={(!tooltip && chips.length === 0) || panelOpen}>
+ <PopoverTrigger render={<TooltipTrigger render={trigger} />} />
+ {tooltipContent}
+ </Tooltip>
+ ) : (
+ <PopoverTrigger render={trigger} />
+ )}
+ <PopoverContent
+ align={align}
+ className="w-[680px] max-w-[calc(100vw-2rem)] gap-0 p-0"
+ data-testid="advanced-filter-panel"
+ >
+ <AdvancedFilterPanel fields={searchFields} />
+ </PopoverContent>
+ </Popover>
+ );
+ }
+
+ return (
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (freezeAnchor) {
+ if (open && triggerRef.current) {
+ const rect = triggerRef.current.getBoundingClientRect();
+ setFrozenAnchor({ getBoundingClientRect: () => rect });
+ } else if (!open) {
+ setFrozenAnchor(null);
+ }
+ }
+ setActiveAtOpen(open ? new Set(chipByKey.keys()) : null);
+ if (!open) {
+ setSearch("");
+ onTableFacetChange?.(null);
+ }
+ onOpenChange?.(open);
+ }}
+ >
+ {/* One tree for both bodies: swapping wrappers when the first filter
+ lands would remount the trigger and strand the open menu's anchor. */}
+ {withTooltip ? (
+ <Tooltip disabled={(!tooltip && chips.length === 0) || (!!summaryTitle && activeAtOpen !== null)}>
+ <DropdownMenuTrigger render={<TooltipTrigger render={anchoredTrigger} />} />
+ {tooltipContent}
+ </Tooltip>
+ ) : (
+ <DropdownMenuTrigger render={anchoredTrigger} />
+ )}
+ <DropdownMenuContent align={align} className="w-auto min-w-64 p-0" anchor={frozenAnchor ?? undefined}>
+ <div data-filter-search className="flex items-center gap-1.5 border-b border-foreground/5 px-2.5 py-2">
+ <Search className="size-3.5 shrink-0 text-muted-foreground" />
+ <input
+ type="text"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ onKeyDown={stopMenuSearchKeys}
+ placeholder={t(($) => $.filters.search_placeholder)}
+ aria-label={t(($) => $.filters.search_placeholder)}
+ className="w-full bg-transparent text-body outline-none placeholder:text-muted-foreground"
+ autoFocus
+ />
+ </div>
+ <div className="max-h-[min(70vh,36rem)] overflow-x-hidden overflow-y-auto p-1">{menuBody}</div>
</DropdownMenuContent>
</DropdownMenu>
);
}
+const LAYOUTS: { mode: ViewMode; Icon: typeof List }[] = [
+ { mode: "board", Icon: Columns3 },
+ { mode: "list", Icon: List },
+ { mode: "table", Icon: Table2 },
+ { mode: "swimlane", Icon: Waves },
+ { mode: "gantt", Icon: ChartGantt },
+];
+
export function IssueDisplayControls({
scopedIssues,
hideViewToggle = false,
@@ -1880,9 +1724,15 @@ export function IssueDisplayControls({
tableFacetCounts,
onTableFacetChange,
viewBaseline,
+ hideFilter = false,
+ iconOnly = false,
}: {
scopedIssues: Issue[];
hideViewToggle?: boolean;
+ /** The host renders its own filter trigger (the view header's chip row). */
+ hideFilter?: boolean;
+ /** A ghost icon button named only by its tooltip, for the issue view header. */
+ iconOnly?: boolean;
dateFilter?: IssueDateFilter | null;
onDateFilterChange?: (filter: IssueDateFilter | null) => void;
/** Open saved view: menu marks the view's values checked-and-disabled;
@@ -1903,8 +1753,6 @@ export function IssueDisplayControls({
onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;
}) {
const { t } = useT("issues");
- const [tableGroupMenuOpen, setTableGroupMenuOpen] = useState(false);
- const [viewMenuOpen, setViewMenuOpen] = useState(false);
const viewMode = useViewStore((s) => s.viewMode);
const statusFilters = useViewStore((s) => s.statusFilters);
const priorityFilters = useViewStore((s) => s.priorityFilters);
@@ -1916,6 +1764,10 @@ export function IssueDisplayControls({
const projectStatusFilters = useViewStore((s) => s.projectStatusFilters);
const labelFilters = useViewStore((s) => s.labelFilters);
const propertyFilters = useViewStore((s) => s.propertyFilters);
+ const relationFilters = useViewStore((s) => s.relationFilters);
+ const dueDateFilters = useViewStore((s) => s.dueDateFilters);
+ const advancedFilter = useViewStore((s) => s.advancedFilter);
+ const negatedFilters = useViewStore((s) => s.negatedFilters);
const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
const sortBy = useViewStore((s) => s.sortBy);
const sortDirection = useViewStore((s) => s.sortDirection);
@@ -1924,6 +1776,7 @@ export function IssueDisplayControls({
const cardProperties = useViewStore((s) => s.cardProperties);
const tableGrouping = useViewStore((s) => s.tableGrouping ?? "none");
const tableHierarchy = useViewStore((s) => s.tableHierarchy ?? true);
+ const tableColumnCount = useViewStore((s) => s.tableColumns.length);
const showSubIssues = useViewStore((s) => s.showSubIssues);
const hiddenStatuses = useViewStore((s) => s.hiddenStatuses);
const act = useViewStoreApi().getState();
@@ -1990,6 +1843,10 @@ export function IssueDisplayControls({
includeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters,
+ dueDateFilters,
+ negatedFilters,
+ advancedFilter,
dateFilter: showDateFilter ? dateFilter : null,
},
viewBaseline,
@@ -2058,11 +1915,20 @@ export function IssueDisplayControls({
: effectiveTableGrouping === "project"
? t(($) => $.table.columns.project)
: t(($) => $.table.group_none);
+ // A Gantt layout persisted on a surface without Gantt renders as List.
+ const layout: ViewMode = viewMode === "gantt" && !allowGantt ? "list" : viewMode;
+ const layouts = LAYOUTS.filter(({ mode }) => mode !== "gantt" || allowGantt);
+ const LayoutIcon = hideViewToggle
+ ? SlidersHorizontal
+ : LAYOUTS.find(({ mode }) => mode === layout)!.Icon;
+ const hasLayoutOptions =
+ showColumnToggles || viewMode === "table" || availableCardPropertyOptions.length > 0;
const controlButtonClass = "h-8 w-8 gap-1 px-0 text-muted-foreground md:h-7 md:w-auto md:px-2.5";
+ const controlLabelClass = "hidden md:inline @max-3xl/issue-header:hidden";
return (
<div className="flex shrink-0 items-center gap-1">
- <IssueFilterMenu
+ {!hideFilter && <IssueFilterMenu
trigger={
<Button
variant={hasActiveFilters ? "default" : "outline"}
@@ -2092,110 +1958,67 @@ export function IssueDisplayControls({
dateFilter={showDateFilter ? dateFilter : null}
onDateFilterChange={onDateFilterChange}
viewBaseline={viewBaseline}
- />
-
- {viewMode === "table" && (
- <DropdownMenu
- open={tableGroupMenuOpen}
- onOpenChange={setTableGroupMenuOpen}
- >
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className={controlButtonClass}
- >
- <Rows3 className="size-3.5" />
- <span className="hidden md:inline">
- {effectiveTableGrouping === "none"
- ? t(($) => $.table.group_label)
- : t(($) => $.table.group_active, {
- group: tableGroupingLabel,
- })}
- </span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-auto min-w-48">
- <DropdownMenuRadioGroup
- value={effectiveTableGrouping}
- onValueChange={(value) => {
- act.setTableGrouping(value as TableGrouping);
- setTableGroupMenuOpen(false);
- }}
- >
- <DropdownMenuRadioItem value="none">
- {t(($) => $.table.group_none)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="status">
- {t(($) => $.table.columns.status)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="assignee">
- {t(($) => $.table.columns.assignee)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="project">
- {t(($) => $.table.columns.project)}
- </DropdownMenuRadioItem>
- {tableGroupableProperties.map((property) => (
- <DropdownMenuRadioItem
- key={property.id}
- value={`property:${property.id}`}
- >
- <PropertyIcon
- property={property}
- className="size-3.5 text-caption"
- />
- <span>{property.name}</span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
+ />}
- {viewMode === "table" && (
- <TableColumnPicker
- properties={workspaceProperties}
- trigger={
- <Button
- variant="outline"
- size="sm"
- className={controlButtonClass}
- >
- <Columns3 className="size-3.5" />
- <span className="hidden md:inline">
- {t(($) => $.table.columns.section)}
- </span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- )}
-
- {/* Display settings */}
<Popover>
<Tooltip>
<PopoverTrigger
render={
<TooltipTrigger
render={
- <Button variant="outline" size="sm" className={controlButtonClass}>
- <SlidersHorizontal className="size-3.5" />
- <span className="hidden md:inline">{t(($) => $.display.button)}</span>
- </Button>
+ iconOnly ? (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ aria-label={t(($) => $.display.button)}
+ >
+ <LayoutIcon />
+ </Button>
+ ) : (
+ <Button
+ variant="outline"
+ size="sm"
+ className={controlButtonClass}
+ aria-label={t(($) => $.display.button)}
+ >
+ <LayoutIcon className="size-3.5" />
+ <span className={controlLabelClass}>{t(($) => $.display.button)}</span>
+ <ChevronDown className={cn("size-3 text-muted-foreground", controlLabelClass)} />
+ </Button>
+ )
}
/>
}
/>
<TooltipContent side="bottom">{t(($) => $.display.tooltip)}</TooltipContent>
</Tooltip>
- <PopoverContent align="end" className="w-72 p-3">
+ <PopoverContent align="end" className="w-88 p-3">
+ {/* Spacing separates sections — no dividers (see UI rules). */}
+ {!hideViewToggle && (
+ <div
+ role="group"
+ aria-label={t(($) => $.view.section)}
+ className={cn(
+ "mb-3 grid gap-0.5 rounded-lg bg-muted p-0.5",
+ layouts.length === 5 ? "grid-cols-5" : "grid-cols-4",
+ )}
+ >
+ {layouts.map(({ mode, Icon }) => (
+ <Toggle
+ key={mode}
+ pressed={layout === mode}
+ onPressedChange={() => act.setViewMode(mode)}
+ title={t(($) => $.view[mode])}
+ className="h-auto min-w-0 flex-col gap-1 rounded-md px-0.5 py-1.5 text-caption font-normal text-muted-foreground hover:bg-transparent hover:text-foreground aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm aria-pressed:hover:bg-background"
+ >
+ <Icon className="size-4" />
+ <span className="max-w-full truncate">{t(($) => $.view[mode])}</span>
+ </Toggle>
+ ))}
+ </div>
+ )}
<div className="space-y-3">
- {/* Caption label left, control right; multi-control sections
- (Ordering, Card properties) stack the label on top. Spacing
- separates sections — no dividers (see UI rules). */}
{viewMode === "board" && (
<div className="flex items-center justify-between gap-3">
<span className="text-caption font-medium text-muted-foreground">
@@ -2217,7 +2040,7 @@ export function IssueDisplayControls({
if (v) act.setGrouping(v as IssueGrouping);
}}
>
- <SelectTrigger size="sm" className="w-32" aria-label={t(($) => $.display.grouping_section)}>
+ <SelectTrigger size="sm" className="w-36" aria-label={t(($) => $.display.grouping_section)}>
<SelectValue>{groupingLabel}</SelectValue>
</SelectTrigger>
<SelectContent align="end">
@@ -2252,7 +2075,7 @@ export function IssueDisplayControls({
if (v) act.setSwimlaneGrouping(v as SwimlaneGrouping);
}}
>
- <SelectTrigger size="sm" className="w-32" aria-label={t(($) => $.display.grouping_section)}>
+ <SelectTrigger size="sm" className="w-36" aria-label={t(($) => $.display.grouping_section)}>
<SelectValue>{swimlaneGroupingLabel}</SelectValue>
</SelectTrigger>
<SelectContent align="end">
@@ -2267,71 +2090,58 @@ export function IssueDisplayControls({
</Select>
</div>
)}
- {showColumnToggles && (
- <div>
+ {viewMode === "table" && (
+ <div className="flex items-center justify-between gap-3">
<span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.display.columns_section)}
+ {t(($) => $.display.grouping_section)}
</span>
- {/* Same chip grammar as Card properties: pressed = column shown.
- A status filter picks the columns itself and overrides
- these, so the chips lock rather than flip to no effect. */}
- <div className="mt-2 flex flex-wrap gap-1">
- {columnOptions.map((option) => (
- <Toggle
- key={option.key}
- size="sm"
- variant="outline"
- pressed={!hiddenStatuses.includes(option.key)}
- disabled={statusFilters.length > 0}
- onPressedChange={(pressed) =>
- pressed ? act.showStatus(option.key) : act.hideStatus(option.key)
- }
- className="h-6 max-w-40 gap-1.5 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"
- >
- <StatusIcon
- status={option.key}
- category={option.category}
- color={option.color}
- icon={option.icon}
- className="size-3 shrink-0"
- />
- <span className="truncate">{option.label}</span>
- </Toggle>
- ))}
- </div>
- {statusFilters.length > 0 && (
- <p className="mt-1.5 text-caption text-faint-foreground">
- {t(($) => $.display.columns_locked_by_filter)}
- </p>
- )}
+ <Select
+ items={[
+ { value: "none", label: t(($) => $.table.group_none) },
+ { value: "status", label: t(($) => $.table.columns.status) },
+ { value: "assignee", label: t(($) => $.table.columns.assignee) },
+ { value: "project", label: t(($) => $.table.columns.project) },
+ ...tableGroupableProperties.map((p) => ({
+ value: `property:${p.id}`,
+ label: p.name,
+ })),
+ ]}
+ value={effectiveTableGrouping}
+ onValueChange={(v) => {
+ if (v) act.setTableGrouping(v as TableGrouping);
+ }}
+ >
+ <SelectTrigger size="sm" className="w-36" aria-label={t(($) => $.display.grouping_section)}>
+ <SelectValue>{tableGroupingLabel}</SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end">
+ <SelectGroup>
+ <SelectItem value="none">{t(($) => $.table.group_none)}</SelectItem>
+ <SelectItem value="status">{t(($) => $.table.columns.status)}</SelectItem>
+ <SelectItem value="assignee">{t(($) => $.table.columns.assignee)}</SelectItem>
+ <SelectItem value="project">{t(($) => $.table.columns.project)}</SelectItem>
+ {tableGroupableProperties.map((property) => (
+ <SelectItem key={property.id} value={`property:${property.id}`}>
+ <PropertyIcon property={property} className="size-3.5 text-caption" />
+ <span>{property.name}</span>
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
</div>
)}
- {viewMode === "table" && (
- <label className="flex cursor-pointer items-center justify-between gap-3">
- <span className="min-w-0">
- <span className="block text-caption font-medium text-muted-foreground">
- {t(($) => $.table.hierarchy)}
- </span>
- <span className="block text-caption text-faint-foreground">
- {t(($) => $.table.hierarchy_description)}
- </span>
- </span>
- <Switch
- size="sm"
- checked={tableHierarchy}
- onCheckedChange={() => act.toggleTableHierarchy()}
- />
- </label>
- )}
- <div>
+ <div className="flex items-center justify-between gap-3">
<span className="text-caption font-medium text-muted-foreground">
{t(($) => $.display.ordering_section)}
</span>
- {/* Direction labels run up to "Reverse workflow order", so the
- pair gets the full popover width (w-72 keeps "Status" beside
- it untruncated): the field select absorbs the slack and
- truncates, the direction label never does. */}
- <div className="mt-2 flex items-center gap-1.5">
+ <div className="flex min-w-0 items-center gap-1">
+ {sortBy !== "position" && (
+ <SortDirectionButton
+ label={sortDirectionLabel}
+ onClick={() => act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")}
+ />
+ )}
<Select
items={[
...availableSortOptions.map((opt) => ({
@@ -2348,7 +2158,7 @@ export function IssueDisplayControls({
if (v) act.setSortBy(v as SortField);
}}
>
- <SelectTrigger size="sm" className="min-w-0 flex-1" aria-label={t(($) => $.display.ordering_section)}>
+ <SelectTrigger size="sm" className="w-36" aria-label={t(($) => $.display.ordering_section)}>
<SelectValue>{sortLabel}</SelectValue>
</SelectTrigger>
<SelectContent align="end">
@@ -2366,18 +2176,6 @@ export function IssueDisplayControls({
</SelectGroup>
</SelectContent>
</Select>
- {sortBy !== "position" && (
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")
- }
- aria-label={sortDirectionLabel}
- >
- {sortDirectionLabel}
- </Button>
- )}
</div>
</div>
<label className="flex cursor-pointer items-center justify-between gap-3">
@@ -2390,6 +2188,85 @@ export function IssueDisplayControls({
onCheckedChange={() => act.toggleShowSubIssues()}
/>
</label>
+ </div>
+ {hasLayoutOptions && (
+ <div className="mt-5 space-y-3">
+ <p className="text-label font-medium text-foreground">
+ {t(($) => $.display.layout_options, { layout: t(($) => $.view[layout]) })}
+ </p>
+ {showColumnToggles && (
+ <div>
+ <span className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.display.columns_section)}
+ </span>
+ {/* Same chip grammar as Card properties: pressed = column shown.
+ A status filter picks the columns itself and overrides
+ these, so the chips lock rather than flip to no effect. */}
+ <div className="mt-2 flex flex-wrap gap-1">
+ {columnOptions.map((option) => (
+ <DisplayChip
+ key={option.key}
+ pressed={!hiddenStatuses.includes(option.key)}
+ disabled={statusFilters.length > 0}
+ onPressedChange={(pressed) =>
+ pressed ? act.showStatus(option.key) : act.hideStatus(option.key)
+ }
+ >
+ <StatusIcon
+ status={option.key}
+ category={option.category}
+ color={option.color}
+ icon={option.icon}
+ className="size-3 shrink-0"
+ />
+ <span className="truncate">{option.label}</span>
+ </DisplayChip>
+ ))}
+ </div>
+ {statusFilters.length > 0 && (
+ <p className="mt-1.5 text-caption text-faint-foreground">
+ {t(($) => $.display.columns_locked_by_filter)}
+ </p>
+ )}
+ </div>
+ )}
+ {viewMode === "table" && (
+ <label className="flex cursor-pointer items-center justify-between gap-3">
+ <span className="min-w-0">
+ <span className="block text-caption font-medium text-muted-foreground">
+ {t(($) => $.table.hierarchy)}
+ </span>
+ <span className="block text-caption text-faint-foreground">
+ {t(($) => $.table.hierarchy_description)}
+ </span>
+ </span>
+ <Switch
+ size="sm"
+ checked={tableHierarchy}
+ onCheckedChange={() => act.toggleTableHierarchy()}
+ />
+ </label>
+ )}
+ {viewMode === "table" && (
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.table.columns.section)}
+ </span>
+ <TableColumnPicker
+ properties={workspaceProperties}
+ trigger={
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-36 justify-between border-input pr-2 pl-2.5 text-body font-normal"
+ >
+ {t(($) => $.display.columns_shown, { count: tableColumnCount })}
+ <ChevronDown className="size-4 text-muted-foreground" />
+ </Button>
+ }
+ />
+ </div>
+ )}
{availableCardPropertyOptions.length > 0 && (
<div>
<span className="text-caption font-medium text-muted-foreground">
@@ -2399,124 +2276,31 @@ export function IssueDisplayControls({
dim so the active set reads at a glance. */}
<div className="mt-2 flex flex-wrap gap-1">
{availableCardPropertyOptions.map((opt) => (
- <Toggle
+ <DisplayChip
key={opt.key}
- size="sm"
- variant="outline"
pressed={cardProperties[opt.key]}
onPressedChange={() => act.toggleCardProperty(opt.key)}
- className="h-6 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"
>
{t(($) => $.display[CARD_PROPERTY_LABEL_KEY[opt.key]])}
- </Toggle>
+ </DisplayChip>
))}
{workspaceProperties.map((property) => (
- <Toggle
+ <DisplayChip
key={property.id}
- size="sm"
- variant="outline"
pressed={cardPropertyIds.includes(property.id)}
onPressedChange={() => act.toggleCardPropertyId(property.id)}
- className="h-6 max-w-40 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"
>
<span className="truncate">{property.name}</span>
- </Toggle>
+ </DisplayChip>
))}
</div>
</div>
)}
- </div>
+ </div>
+ )}
</PopoverContent>
</Popover>
- {/* View toggle. If a store has `viewMode === "gantt"` persisted but
- this surface doesn't render Gantt, fall back to "list" so the
- trigger icon matches what's actually on screen. */}
- {!hideViewToggle && (
- <DropdownMenu open={viewMenuOpen} onOpenChange={setViewMenuOpen}>
- <Tooltip>
- <DropdownMenuTrigger
- render={
- <TooltipTrigger
- render={
- <Button variant="outline" size="sm" className={controlButtonClass}>
- {viewMode === "board" ? (
- <Columns3 className="size-3.5" />
- ) : viewMode === "table" ? (
- <Table2 className="size-3.5" />
- ) : viewMode === "swimlane" ? (
- <Waves className="size-3.5" />
- ) : viewMode === "gantt" && allowGantt ? (
- <ChartGantt className="size-3.5" />
- ) : (
- <List className="size-3.5" />
- )}
- <span className="hidden md:inline">
- {viewMode === "board"
- ? t(($) => $.view.board)
- : viewMode === "table"
- ? t(($) => $.view.table)
- : viewMode === "swimlane"
- ? t(($) => $.view.swimlane)
- : viewMode === "gantt" && allowGantt
- ? t(($) => $.view.gantt)
- : t(($) => $.view.list)}
- </span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">
- {viewMode === "board"
- ? t(($) => $.view.tooltip_board)
- : viewMode === "table"
- ? t(($) => $.view.tooltip_table)
- : viewMode === "swimlane"
- ? t(($) => $.view.tooltip_swimlane)
- : viewMode === "gantt" && allowGantt
- ? t(($) => $.view.tooltip_gantt)
- : t(($) => $.view.tooltip_list)}
- </TooltipContent>
- </Tooltip>
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuGroup>
- <DropdownMenuLabel>{t(($) => $.view.section)}</DropdownMenuLabel>
- </DropdownMenuGroup>
- <DropdownMenuRadioGroup
- value={viewMode}
- onValueChange={(v) => {
- act.setViewMode(v as ViewMode);
- setViewMenuOpen(false);
- }}
- >
- <DropdownMenuRadioItem value="board">
- <Columns3 />
- {t(($) => $.view.board)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="list">
- <List />
- {t(($) => $.view.list)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="table">
- <Table2 />
- {t(($) => $.view.table)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="swimlane">
- <Waves />
- {t(($) => $.view.swimlane)}
- </DropdownMenuRadioItem>
- {allowGantt && (
- <DropdownMenuRadioItem value="gantt">
- <ChartGantt />
- {t(($) => $.view.gantt)}
- </DropdownMenuRadioItem>
- )}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
-
</div>
);
}
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index 270d1a9db8..335229a165 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -50,7 +50,7 @@ vi.mock("../../navigation", () => ({
{children}
</a>
),
- useNavigation: () => ({ push: vi.fn(), pathname: "/issues" }),
+ useNavigation: () => ({ push: vi.fn(), pathname: "/issues", searchParams: new URLSearchParams() }),
resolveClickIntent: () => "push",
useIntentNavigate: () => () => {},
NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
@@ -301,6 +301,10 @@ const mockViewState = {
includeNoProject: false,
projectStatusFilters: [] as string[],
labelFilters: [] as string[],
+ relationFilters: [] as string[],
+ dueDateFilters: [] as string[],
+ advancedFilter: null,
+ negatedFilters: [] as string[],
propertyFilters: {} as Record<string, string[]>,
cardPropertyIds: [] as string[],
sortBy: "position" as const,
@@ -344,6 +348,8 @@ vi.mock("@multica/core/issues/stores/view-store", () => ({
key.startsWith("property:") ? key.slice("property:".length) : null,
viewStorePersistOptions: () => ({ name: "test", storage: undefined, partialize: (s: any) => s }),
mergeViewStatePersisted: (_p: unknown, c: any) => c,
+ effectiveNegatedFilters: () => [],
+ ISSUE_RELATION_FILTERS: ["assigned", "created", "my_agents"],
viewStoreSlice: vi.fn(),
useIssueViewStore: Object.assign(
(selector?: any) => (selector ? selector(mockViewState) : mockViewState),
@@ -778,7 +784,7 @@ describe("IssuesPage (shared)", () => {
expect(mockListIssues).not.toHaveBeenCalled();
});
- it("shows the 'Issues' section header without a workspace prefix", async () => {
+ it("titles the page with the built-in view, without a workspace prefix", async () => {
mockListIssues.mockImplementation((params: any) =>
Promise.resolve({
issues: mockIssues.filter((i) => i.status === params?.status),
@@ -788,9 +794,7 @@ describe("IssuesPage (shared)", () => {
renderWithQuery(<IssuesPage />);
- await screen.findByText("Issues");
- // The list header is now `icon + title`, matching the other list pages.
- // The workspace/org name is no longer rendered as a breadcrumb prefix.
+ await screen.findByRole("heading", { name: "All issues" });
expect(screen.queryByText("Test WS")).not.toBeInTheDocument();
});
@@ -802,12 +806,16 @@ describe("IssuesPage (shared)", () => {
await screen.findByText("No issues yet");
});
- it("shows scope tab buttons", async () => {
- renderWithQuery(<IssuesPage />);
+ it("counts the assignee type as a filter only once it narrows the list", async () => {
+ const { unmount } = renderWithQuery(<IssuesPage />);
+ await screen.findByRole("heading", { name: "All issues" });
+ expect(screen.getByRole("button", { name: "Filter" })).toBeInTheDocument();
+ unmount();
- expect(await screen.findAllByText("All")).not.toHaveLength(0);
- expect(screen.getByText("Members")).toBeInTheDocument();
- expect(screen.getByText("Agents")).toBeInTheDocument();
+ mockScope = "agents";
+ renderWithQuery(<IssuesPage />);
+ await screen.findByRole("heading", { name: "All issues" });
+ expect(screen.getByRole("button", { name: "1 filter" })).toBeInTheDocument();
});
// The Members/Agents tabs filter server-side via assignee_types (the same
diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsx
index ae7cba35fa..30fc5087a4 100644
--- a/packages/views/issues/components/issues-page.tsx
+++ b/packages/views/issues/components/issues-page.tsx
@@ -1,59 +1,12 @@
"use client";
import { ListTodo } from "@multica/ui/icons";
-import type {
- Issue,
- IssueTableFacetSpec,
- IssueTableFacetsResponse,
- WorkingAgentSummary,
-} from "@multica/core/types";
import { useIssuesScope } from "@multica/core/issues/stores/issues-scope-store";
-import { useViewStore } from "@multica/core/issues/stores/view-store-context";
-import { PageHeader } from "../../layout/page-header";
-import { RefreshablePageIcon } from "../../layout/refreshable-page-icon";
import { useT } from "../../i18n";
import { IssueSurface } from "../surface/issue-surface";
-import { IssuesHeader } from "./issues-header";
+import { IssueViewHeader } from "../../issue-views/view-header";
-function IssuesSurfaceHeader({
- issues,
- workingAgents,
- isRefreshing,
- facetCountsExact,
- tableFacetCounts,
- onTableFacetChange,
-}: {
- issues: Issue[];
- workingAgents: WorkingAgentSummary[] | undefined;
- isRefreshing: boolean;
- facetCountsExact: boolean;
- tableFacetCounts?: IssueTableFacetsResponse;
- onTableFacetChange: (facet: IssueTableFacetSpec | null) => void;
-}) {
- const { t } = useT("issues");
- const dateFilter = useViewStore((s) => s.dateFilter);
- const setDateFilter = useViewStore((s) => s.setDateFilter);
-
- return (
- <>
- <PageHeader>
- <RefreshablePageIcon refreshing={isRefreshing}>
- <ListTodo className="size-4" />
- </RefreshablePageIcon>
- <h1 className="text-body font-medium">{t(($) => $.page.breadcrumb_title)}</h1>
- </PageHeader>
- <IssuesHeader
- scopedIssues={issues}
- workingAgents={workingAgents}
- dateFilter={dateFilter}
- onDateFilterChange={setDateFilter}
- facetCountsExact={facetCountsExact}
- tableFacetCounts={tableFacetCounts}
- onTableFacetChange={onTableFacetChange}
- />
- </>
- );
-}
+const WORKSPACE_BASE = { kind: "workspace" } as const;
export function IssuesPage() {
const { t } = useT("issues");
@@ -65,16 +18,7 @@ export function IssuesPage() {
scope={{ type: "workspace", actorKind: scope }}
modes={["board", "list", "table", "swimlane"]}
batchToolbar="list"
- renderHeader={({ controller }) => (
- <IssuesSurfaceHeader
- issues={controller.surfaceIssues}
- workingAgents={controller.workingAgents}
- isRefreshing={controller.isRefreshing}
- facetCountsExact={controller.facetCountsExact}
- tableFacetCounts={controller.tableFacetCounts}
- onTableFacetChange={controller.setActiveTableFacet}
- />
- )}
+ renderHeader={({ controller }) => <IssueViewHeader controller={controller} base={WORKSPACE_BASE} />}
renderEmpty={() => (
<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 text-muted-foreground">
<ListTodo className="h-10 w-10 text-faint-foreground" />
diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsx
index 8da4b8ff57..591bfff054 100644
--- a/packages/views/issues/components/list-view.tsx
+++ b/packages/views/issues/components/list-view.tsx
@@ -542,7 +542,9 @@ function StatusAccordionItem({
issue={issue}
childProgress={childProgressMap.get(issue.id)}
project={
- issue.project_id ? projectMap?.get(issue.project_id) : undefined
+ issue.project_id && issue.project_id !== projectId
+ ? projectMap?.get(issue.project_id)
+ : undefined
}
disableSorting={disableSorting}
/>
@@ -551,7 +553,9 @@ function StatusAccordionItem({
issue={issue}
childProgress={childProgressMap.get(issue.id)}
project={
- issue.project_id ? projectMap?.get(issue.project_id) : undefined
+ issue.project_id && issue.project_id !== projectId
+ ? projectMap?.get(issue.project_id)
+ : undefined
}
/>
);
diff --git a/packages/views/issues/components/manage-views-dialog.tsx b/packages/views/issues/components/manage-views-dialog.tsx
deleted file mode 100644
index 28a9249ea5..0000000000
--- a/packages/views/issues/components/manage-views-dialog.tsx
+++ /dev/null
@@ -1,262 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useState } from "react";
-import {
- DndContext,
- PointerSensor,
- closestCenter,
- useSensor,
- useSensors,
- type DragEndEvent,
-} from "@dnd-kit/core";
-import {
- SortableContext,
- arrayMove,
- useSortable,
- verticalListSortingStrategy,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
-import { GripVertical, Layers, Pencil, Trash2 } from "@multica/ui/icons";
-import { IconButton } from "@multica/ui/components/common/icon-button";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-import { Switch } from "@multica/ui/components/ui/switch";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import { cn } from "@multica/ui/lib/utils";
-import type { IssueView } from "@multica/core/api/schemas";
-import {
- DeleteViewConfirm,
- type ViewBarItem,
-} from "./view-bar-popover";
-import { useT } from "../../i18n";
-
-/** One row in the manager: a built-in tab or a saved view. */
-/** The vertical-locked row drag has no DragOverlay under the pointer, so
- * the grabbing cursor is promoted to the document for the drag's duration
- * (see the `data-dnd-dragging` contract in ui/styles/base.css). */
-function setDndCursor(on: boolean) {
- if (on) document.documentElement.dataset.dndDragging = "true";
- else delete document.documentElement.dataset.dndDragging;
-}
-
-function SortableRow({
- item,
- hidden,
- anchor,
- onToggleHidden,
- onEdit,
- onDelete,
-}: {
- item: ViewBarItem;
- hidden: boolean;
- /** The anchor built-in cannot be hidden — its switch is disabled. */
- anchor: boolean;
- onToggleHidden: () => void;
- onEdit?: () => void;
- onDelete?: () => void;
-}) {
- const { t } = useT("issues");
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
- useSortable({ id: item.barItemId });
-
- return (
- <div
- ref={setNodeRef}
- style={{ transform: CSS.Translate.toString(transform), transition }}
- className={cn(
- "flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5",
- isDragging && "z-10 bg-accent opacity-80",
- )}
- >
- <TooltipHint label={t(($) => $.view_bar.drag_handle)}>
- <button
- type="button"
- {...attributes}
- {...listeners}
- aria-label={t(($) => $.view_bar.drag_handle)}
- className={cn(
- "cursor-grab active:cursor-grabbing text-faint-foreground hover:text-muted-foreground",
- isDragging && "cursor-grabbing",
- )}
- >
- <GripVertical className="size-3.5" />
- </button>
- </TooltipHint>
- <span className="min-w-0 flex-1 truncate text-body">
- {item.label}
- {item.kind === "builtin" && (
- <span className="ml-1.5 text-caption text-muted-foreground">
- {t(($) => $.view_bar.builtin_tag)}
- </span>
- )}
- </span>
- {item.kind === "view" && item.canManage && (
- <span className="flex items-center gap-0.5">
- <IconButton
- variant="ghost"
- size="icon-sm"
- label={t(($) => $.view_selector.edit)}
- onClick={onEdit}
- >
- <Pencil className="size-3.5" />
- </IconButton>
- <IconButton
- variant="ghost"
- size="icon-sm"
- label={t(($) => $.view_bar.delete)}
- onClick={onDelete}
- className="text-muted-foreground hover:text-destructive"
- >
- <Trash2 className="size-3.5" />
- </IconButton>
- </span>
- )}
- <Switch
- size="sm"
- checked={!hidden}
- disabled={anchor}
- aria-label={t(($) => $.view_bar.visible_toggle)}
- onCheckedChange={onToggleHidden}
- />
- </div>
- );
-}
-
-/**
- * Central manager for one surface's view bar: order (drag), visibility
- * (switch), edit/delete for manageable saved views. Order and visibility
- * write the per-user preference document optimistically; edit/delete
- * delegate to the host (they need the save dialog / delete mutation wired
- * to the surface's state).
- */
-export function ManageViewsDialog({
- open,
- onOpenChange,
- items,
- hiddenSet,
- anchorId,
- onReorder,
- onToggleHidden,
- onEditView,
- onDeleteView,
-}: {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- /** Full ordered list (built-ins + views), pre-composed by the host. */
- items: ViewBarItem[];
- hiddenSet: Set<string>;
- anchorId: string;
- onReorder: (orderedIds: string[]) => void;
- onToggleHidden: (barItemId: string, hidden: boolean) => void;
- onEditView: (view: IssueView) => void;
- onDeleteView: (view: IssueView) => Promise<void>;
-}) {
- const { t } = useT("issues");
- const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
- );
- // Local order during a drag session so rows follow the pointer without a
- // server round-trip per pixel; committed (one PUT) on drop.
- const [localOrder, setLocalOrder] = useState<string[] | null>(null);
- // If the dialog unmounts mid-drag (close on Escape, view deleted under
- // us), dnd-kit fires no cancel — clear the document cursor ourselves.
- useEffect(() => () => setDndCursor(false), []);
- useEffect(() => {
- if (!open) setLocalOrder(null);
- }, [open]);
-
- const orderedItems = useMemo(() => {
- if (!localOrder) return items;
- const byId = new Map(items.map((item) => [item.barItemId, item]));
- const next: ViewBarItem[] = [];
- for (const id of localOrder) {
- const item = byId.get(id);
- if (item) {
- next.push(item);
- byId.delete(id);
- }
- }
- return [...next, ...byId.values()];
- }, [items, localOrder]);
-
- const [deleting, setDeleting] = useState<IssueView | null>(null);
-
- const handleDragEnd = (event: DragEndEvent) => {
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- const ids = orderedItems.map((item) => item.barItemId);
- const from = ids.indexOf(String(active.id));
- const to = ids.indexOf(String(over.id));
- if (from < 0 || to < 0) return;
- const next = arrayMove(ids, from, to);
- setLocalOrder(next);
- onReorder(next);
- };
-
- return (
- <>
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-md">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-1.5">
- <Layers className="size-4" />
- {t(($) => $.view_bar.manage_title)}
- </DialogTitle>
- <DialogDescription>{t(($) => $.view_bar.manage_hint)}</DialogDescription>
- </DialogHeader>
- <div className="-mx-2 min-w-0 overflow-hidden">
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- // Rows only ever swap vertically — same constraint the table
- // header puts on column reordering, rotated 90°. Horizontal
- // auto-scroll is likewise an axis this gesture cannot act on.
- modifiers={[restrictToVerticalAxis]}
- autoScroll={{ threshold: { x: 0, y: 0.15 } }}
- onDragStart={() => setDndCursor(true)}
- onDragCancel={() => setDndCursor(false)}
- onDragEnd={(event) => {
- setDndCursor(false);
- handleDragEnd(event);
- }}
- >
- <SortableContext
- items={orderedItems.map((item) => item.barItemId)}
- strategy={verticalListSortingStrategy}
- >
- {orderedItems.map((item) => (
- <SortableRow
- key={item.barItemId}
- item={item}
- hidden={hiddenSet.has(item.barItemId)}
- anchor={item.barItemId === anchorId}
- onToggleHidden={() =>
- onToggleHidden(item.barItemId, !hiddenSet.has(item.barItemId))
- }
- onEdit={item.view ? () => onEditView(item.view!) : undefined}
- onDelete={item.view ? () => setDeleting(item.view!) : undefined}
- />
- ))}
- </SortableContext>
- </DndContext>
- </div>
- </DialogContent>
- </Dialog>
-
- <DeleteViewConfirm
- view={deleting}
- onOpenChange={(open) => {
- if (!open) setDeleting(null);
- }}
- onConfirm={onDeleteView}
- />
- </>
- );
-}
-
diff --git a/packages/views/issues/components/property-filter-options.tsx b/packages/views/issues/components/property-filter-options.tsx
new file mode 100644
index 0000000000..37e13a5979
--- /dev/null
+++ b/packages/views/issues/components/property-filter-options.tsx
@@ -0,0 +1,401 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Input } from "@multica/ui/components/ui/input";
+import { DropdownMenuCheckboxItem } from "@multica/ui/components/ui/dropdown-menu";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import {
+ formatActorRef,
+ isActorPropertyType,
+ parseActorRef,
+ isListPropertyType,
+ isScalarPropertyType,
+ MAX_ISSUE_PROPERTY_FILTER_VALUES,
+ PROPERTY_FILTER_OP_SYMBOLS,
+ PROPERTY_FILTER_OPS_BY_TYPE,
+ type IssueProperty,
+ type PropertyFilterOp,
+ type PropertyFilterValue,
+} from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
+import { useT } from "../../i18n";
+import type { ActorFilterValue } from "@multica/core/issues/stores/view-store";
+import { NO_PROPERTY_VALUE } from "../utils/filter";
+
+/**
+ * Names one property filter value the way chips and advanced conditions show
+ * it: the option's name, Yes/No, an operator phrase, or the actor's name.
+ */
+export function usePropertyValueName(
+ actorName: (actor: ActorFilterValue) => string | undefined,
+) {
+ const { t } = useT("issues");
+ return (definition: IssueProperty, member: PropertyFilterValue): string | undefined => {
+ if (member === NO_PROPERTY_VALUE) {
+ return t(($) => $.pickers.custom_property.none);
+ }
+ // Scalar operator members summarize with their operator; the comparison
+ // symbols are locale-independent, the word ops get chip phrases.
+ if (typeof member === "object") {
+ if (member.op === "contains") {
+ return t(($) => $.filters.chip_op_contains, { value: member.value });
+ }
+ if (member.op === "before") {
+ return t(($) => $.filters.chip_op_before, { value: member.value });
+ }
+ if (member.op === "after") {
+ return t(($) => $.filters.chip_op_after, { value: member.value });
+ }
+ const symbol = PROPERTY_FILTER_OP_SYMBOLS[member.op] ?? member.op;
+ return `${symbol} ${member.value}`;
+ }
+ if (isActorPropertyType(definition.type)) {
+ const ref = parseActorRef(member);
+ return ref ? actorName({ type: ref.kind, id: ref.id }) : undefined;
+ }
+ if (definition.type === "checkbox") {
+ return member === "true"
+ ? t(($) => $.pickers.custom_property.true_label)
+ : t(($) => $.pickers.custom_property.false_label);
+ }
+ // Scalar and list properties have no option list — the filter value IS
+ // the label (for lists it is one matched element).
+ if (isScalarPropertyType(definition.type) || isListPropertyType(definition.type)) {
+ return member;
+ }
+ return definition.config.options?.find((o) => o.id === member)?.name;
+ };
+}
+
+/**
+ * Option checkboxes for one custom property inside the Filter dropdown.
+ * Select/multi_select list the definition's options (dot + name); checkbox
+ * definitions expose the "true"/"false" pseudo-options with Yes/No labels;
+ * actor definitions have no config options at all, so their candidates come
+ * from the member directory instead, with the signed-in member first so
+ * "this property is me" stays one click away.
+ */
+
+// Keyboard guard for the inline operator radios — same contract as the
+// scalar input below: Escape/Tab belong to the menu (close / move focus);
+// every other navigation or selection key must not bubble into the popup's
+// typeahead / list-navigation handlers.
+function stopScalarMenuKeys(event: React.KeyboardEvent) {
+ if (event.key === "Escape" || event.key === "Tab") return;
+ event.stopPropagation();
+}
+export function PropertyFilterOptions({
+ property,
+ counts,
+ selected,
+ onToggle,
+ onSetValues,
+ fixedIds,
+ fixedTitle,
+}: {
+ property: IssueProperty;
+ counts: Map<string, number> | undefined;
+ selected: PropertyFilterValue[];
+ onToggle: (optionId: string) => void;
+ /** Replace the property's full filter value set (scalar types only). */
+ onSetValues: (optionIds: PropertyFilterValue[]) => void;
+ fixedIds?: Set<string>;
+ fixedTitle?: string;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const currentUserId = useAuthStore((s) => s.user?.id);
+ const actorProperty = isActorPropertyType(property.type);
+ // Scalar properties (text / number / date / url) have no option list — the
+ // filter menu shows a value input plus "No value".
+ const { data: actorMembers = [] } = useQuery({
+ ...memberListOptions(wsId),
+ enabled: actorProperty,
+ });
+
+ const actorOptions = useMemo(() => {
+ if (!actorProperty) return [];
+ return actorMembers
+ .slice()
+ .sort((a, b) => {
+ if (a.user_id === currentUserId) return -1;
+ if (b.user_id === currentUserId) return 1;
+ return 0;
+ })
+ .map((m) => ({
+ id: formatActorRef("member", m.user_id),
+ name: m.name,
+ actorType: "member" as const,
+ actorId: m.user_id,
+ }));
+ }, [actorProperty, actorMembers, currentUserId]);
+
+ // "No value" is offered for every property type: it selects issues where the
+ // property is unset, the inverse of picking one of the options below.
+ const noValueOption = {
+ id: NO_PROPERTY_VALUE,
+ name: t(($) => $.pickers.custom_property.none),
+ color: undefined as string | undefined,
+ actorType: undefined as string | undefined,
+ actorId: undefined as string | undefined,
+ };
+ // Scalar value state lives at the top level so the hooks stay unconditional
+ // (Rules of Hooks): it is only rendered for text / number / date / url and
+ // the list types (equality-only input), but must be declared regardless of
+ // which branch runs. The draft syncs to the committed scalar member whenever
+ // that changes, so a filter cleared or rewritten elsewhere cannot be written
+ // back from a stale input.
+ const committedMember = selected.find((member) => member !== NO_PROPERTY_VALUE);
+ const committedScalar =
+ typeof committedMember === "object" ? committedMember.value : (committedMember ?? "");
+ const committedOp: PropertyFilterOp | "is" =
+ typeof committedMember === "object" ? committedMember.op : "is";
+ const hasNoValue = selected.includes(NO_PROPERTY_VALUE);
+ const [draft, setDraft] = useState(committedScalar);
+ useEffect(() => setDraft(committedScalar), [committedScalar]);
+ // Operator picked in the open menu but not yet committed; null defers to the
+ // committed member (equality when there is none). Resets whenever the
+ // committed member changes — including right after this menu commits — so a
+ // value rewritten elsewhere can't inherit a stale operator.
+ const [pendingOp, setPendingOp] = useState<PropertyFilterOp | "is" | null>(null);
+ const committedKey =
+ committedMember === undefined
+ ? ""
+ : typeof committedMember === "object"
+ ? `op:${committedMember.op}:${committedMember.value}`
+ : `eq:${committedMember}`;
+ useEffect(() => setPendingOp(null), [committedKey]);
+ const options = [
+ ...(actorProperty
+ ? actorOptions.map((option) => ({
+ id: option.id,
+ name: option.name,
+ color: undefined as string | undefined,
+ actorType: option.actorType as string | undefined,
+ actorId: option.actorId as string | undefined,
+ }))
+ : property.type === "checkbox"
+ ? [
+ { id: "true", name: t(($) => $.pickers.custom_property.true_label), color: undefined, actorType: undefined, actorId: undefined },
+ { id: "false", name: t(($) => $.pickers.custom_property.false_label), color: undefined, actorType: undefined, actorId: undefined },
+ ]
+ : (property.config.options ?? []).map((option) => ({
+ id: option.id,
+ name: option.name,
+ color: option.color as string | undefined,
+ actorType: undefined as string | undefined,
+ actorId: undefined as string | undefined,
+ }))),
+ noValueOption,
+ ];
+
+ if (isScalarPropertyType(property.type) || isListPropertyType(property.type)) {
+ const placeholder =
+ property.type === "url" || property.type === "multi_url"
+ ? t(($) => $.pickers.custom_property.url_placeholder)
+ : property.type === "number"
+ ? t(($) => $.pickers.custom_property.number_placeholder)
+ : t(($) => $.pickers.custom_property.value_placeholder);
+ const noneCount = counts?.get(NO_PROPERTY_VALUE) ?? 0;
+ // A saved view locks this dimension: the value (with its operator) AND
+ // "No value" are both part of the view's identity, so neither can be
+ // edited in place.
+ const locked = fixedIds !== undefined && fixedIds.size > 0;
+ // "is" is equality and commits a bare string — the pre-operator shape.
+ // Every other op commits an operator object; the server and matcher both
+ // treat unknown shapes conservatively.
+ const effectiveOp: PropertyFilterOp | "is" = pendingOp ?? committedOp;
+ const scalarOperatorLabel = (op: PropertyFilterOp): string => {
+ if (op === "contains") return t(($) => $.pickers.custom_property.op_contains);
+ if (op === "before") return t(($) => $.pickers.custom_property.op_before);
+ if (op === "after") return t(($) => $.pickers.custom_property.op_after);
+ return PROPERTY_FILTER_OP_SYMBOLS[op] ?? op;
+ };
+ // List types are equality-only: their PROPERTY_FILTER_OPS_BY_TYPE entry is
+ // empty by design, and looking it up needs the scalar narrowing anyway
+ // (IssueProperty.type is a lenient string).
+ const scalarOps = isScalarPropertyType(property.type)
+ ? (PROPERTY_FILTER_OPS_BY_TYPE[property.type] ?? [])
+ : [];
+ const opButtons: { op: PropertyFilterOp | "is"; label: string }[] = [
+ {
+ op: "is",
+ label:
+ property.type === "number"
+ ? "="
+ : t(($) => $.pickers.custom_property.op_is),
+ },
+ ...scalarOps.map((op) => ({
+ op,
+ label: scalarOperatorLabel(op),
+ })),
+ ];
+ const commitValue = (raw: string, op: PropertyFilterOp | "is" = effectiveOp) => {
+ const value = raw.trim();
+ // NO_PROPERTY_VALUE is the reserved "no value" sentinel — it cannot be
+ // filtered as a literal value. The value and "No value" compose like
+ // every other property type: committing a value replaces only the value
+ // member and preserves "No value" membership.
+ if (value === NO_PROPERTY_VALUE) return;
+ const member: PropertyFilterValue | undefined = value
+ ? op === "is"
+ ? value
+ : { op, value }
+ : undefined;
+ onSetValues([
+ ...(member ? [member] : []),
+ ...(hasNoValue ? [NO_PROPERTY_VALUE] : []),
+ ]);
+ };
+ const applyOp = (op: PropertyFilterOp | "is") => {
+ // An explicit click commits the current draft with the chosen op, unlike
+ // the input which waits for Enter/blur. With an empty draft nothing
+ // commits, so the choice rides on pendingOp and the next Enter/blur
+ // commit carries it — killing pendingOp here would silently downgrade
+ // that later commit back to equality.
+ setPendingOp(op);
+ commitValue(draft, op);
+ };
+ return (
+ <>
+ {opButtons.length > 1 && (
+ <div
+ role="radiogroup"
+ aria-label={t(($) => $.pickers.custom_property.operator_label)}
+ className="flex flex-wrap gap-1 px-2 pt-1.5"
+ >
+ {opButtons.map(({ op, label }) => {
+ const active = effectiveOp === op;
+ return (
+ <label
+ key={op}
+ className={locked ? "cursor-not-allowed" : "cursor-pointer"}
+ >
+ <input
+ type="radio"
+ name={`property-filter-op-${property.id}`}
+ value={op}
+ checked={active}
+ disabled={locked}
+ onChange={() => applyOp(op)}
+ onKeyDown={stopScalarMenuKeys}
+ className="peer sr-only"
+ />
+ <span
+ className={`inline-flex h-6 items-center rounded-md px-1.5 text-caption transition-colors peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-ring ${
+ active
+ ? "bg-accent font-medium text-foreground"
+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
+ }`}
+ >
+ {label}
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ )}
+ <div className="px-2 py-1.5">
+ <Input
+ type={property.type === "number" ? "number" : property.type === "date" ? "date" : "text"}
+ step={property.type === "number" ? "any" : undefined}
+ inputMode={property.type === "number" ? "decimal" : undefined}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onBlur={(event) => {
+ // Clicking the "No value" menu item moves focus off the input,
+ // firing blur first. That premature commit would flip the
+ // checkbox's controlled state before its click handler reads it
+ // — so when focus moves into a menu item in this popup, skip the
+ // blur commit and let onCheckedChange decide from the pre-blur
+ // state.
+ const next = event.relatedTarget;
+ const movedToMenuItem =
+ next instanceof HTMLElement &&
+ next.closest('[role="menuitemcheckbox"]') !== null;
+ if (!movedToMenuItem) commitValue(draft);
+ }}
+ onKeyDown={(event) => {
+ // Base UI's menu popup merges typeahead + list-navigation handlers
+ // onto the role="menu" element and stopEvent()s every printable
+ // key — without stopping propagation, the input would swallow no
+ // characters at all (and arrow keys on number/date inputs would
+ // be hijacked). Escape/Tab are left for the menu to close/move
+ // focus; Enter commits and still needs stopPropagation so it does
+ // not bubble up and activate the highlighted "No value" item.
+ if (event.key === "Escape" || event.key === "Tab") return;
+ if (event.key === "Enter") commitValue(draft);
+ event.stopPropagation();
+ }}
+ disabled={locked}
+ placeholder={placeholder}
+ className="h-8"
+ />
+ </div>
+ <DropdownMenuCheckboxItem
+ checked={hasNoValue}
+ disabled={locked}
+ onCheckedChange={(checked) => {
+ // "No value" toggles membership in the same OR-set as the value —
+ // checking/unchecking never touches the committed value member, so
+ // unchecking restores it without any draft round-trip.
+ const valueMembers = selected.filter((id) => id !== NO_PROPERTY_VALUE);
+ onSetValues(
+ checked
+ ? [...valueMembers, NO_PROPERTY_VALUE]
+ : valueMembers,
+ );
+ }}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={hasNoValue} />
+ <span className="truncate">{noValueOption.name}</span>
+ {noneCount > 0 && (
+ <span className="ml-auto text-caption text-muted-foreground">{noneCount}</span>
+ )}
+ </DropdownMenuCheckboxItem>
+ </>
+ );
+ }
+
+ const atCapacity = selected.length >= MAX_ISSUE_PROPERTY_FILTER_VALUES;
+ return (
+ <>
+ {options.map((option) => {
+ const checked = selected.includes(option.id);
+ const count = counts?.get(option.id) ?? 0;
+ return (
+ <DropdownMenuCheckboxItem
+ key={option.id}
+ checked={checked}
+ disabled={fixedIds?.has(option.id) === true || (atCapacity && !checked)}
+ title={fixedIds?.has(option.id) === true ? fixedTitle : undefined}
+ onCheckedChange={() => onToggle(option.id)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ {option.actorType && option.actorId && (
+ <ActorAvatar actorType={option.actorType} actorId={option.actorId} size="sm" />
+ )}
+ {option.color && (
+ <span
+ className="size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: option.color }}
+ />
+ )}
+ <span className="truncate">{option.name}</span>
+ {count > 0 && (
+ <span className="ml-auto text-caption text-muted-foreground">
+ {count}
+ </span>
+ )}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </>
+ );
+}
diff --git a/packages/views/issues/components/save-view-dialog.test.tsx b/packages/views/issues/components/save-view-dialog.test.tsx
deleted file mode 100644
index 5c9dcde3be..0000000000
--- a/packages/views/issues/components/save-view-dialog.test.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { createStore } from "zustand/vanilla";
-import { describe, expect, it, vi } from "vitest";
-import { screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import {
- type IssueViewState,
- viewStoreSlice,
-} from "@multica/core/issues/stores/view-store";
-import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
-import { renderWithI18n } from "../../test/i18n";
-import { DraftDefinitionFields, SaveViewDialog } from "./save-view-dialog";
-
-vi.mock("@tanstack/react-query", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@tanstack/react-query")>()),
- useQuery: () => ({ data: [] }),
-}));
-
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "workspace-1",
-}));
-
-vi.mock("@multica/core/issue-views/mutations", () => ({
- useCreateIssueView: () => ({ mutate: vi.fn(), isPending: false }),
- useUpdateIssueView: () => ({ mutate: vi.fn(), isPending: false }),
-}));
-
-vi.mock("./issues-header", () => ({
- IssueFilterMenu: ({ trigger }: { trigger: React.ReactNode }) => trigger,
-}));
-
-vi.mock("./filter-chips-bar", () => ({
- FilterChipList: ({ trailing }: { trailing?: React.ReactNode }) => trailing,
-}));
-
-function renderFields(sortBy: IssueViewState["sortBy"]) {
- const store = createStore<IssueViewState>()(viewStoreSlice);
- store.setState({ sortBy, sortDirection: "asc" });
- renderWithI18n(
- <ViewStoreProvider store={store}>
- <DraftDefinitionFields />
- </ViewStoreProvider>,
- );
- return store;
-}
-
-describe("DraftDefinitionFields ordering", () => {
- it("lets a saved view default switch between ascending and descending", async () => {
- const user = userEvent.setup();
- const store = renderFields("created_at");
-
- await user.click(screen.getByRole("button", { name: /Default display/ }));
- await user.click(screen.getByRole("button", { name: "Oldest first" }));
-
- expect(store.getState().sortDirection).toBe("desc");
- expect(screen.getByRole("button", { name: "Newest first" })).toBeInTheDocument();
- });
-
- it("hides direction for manual ordering, where direction has no effect", async () => {
- const user = userEvent.setup();
- renderFields("position");
-
- await user.click(screen.getByRole("button", { name: /Default display/ }));
-
- expect(screen.queryByRole("button", { name: "Workflow order" })).not.toBeInTheDocument();
- expect(
- screen.queryByRole("button", { name: "Reverse workflow order" }),
- ).not.toBeInTheDocument();
- });
-});
-
-describe("SaveViewDialog draft lifecycle", () => {
- const liveStore = createStore<IssueViewState>()(viewStoreSlice);
- // Hosts build `scope` inline, so every host render passes a new object.
- const dialog = (open: boolean) => (
- <ViewStoreProvider store={liveStore}>
- <SaveViewDialog
- open={open}
- onOpenChange={() => {}}
- scope={{ kind: "my", variant: "assigned" }}
- />
- </ViewStoreProvider>
- );
-
- it("keeps a half-typed name when the host re-renders", async () => {
- const user = userEvent.setup();
- const { rerender } = renderWithI18n(dialog(true));
-
- await user.type(screen.getByLabelText("Name"), "Ongoing");
- rerender(dialog(true));
-
- expect(screen.getByLabelText("Name")).toHaveValue("Ongoing");
- });
-
- it("starts from a blank name on the next open", async () => {
- const user = userEvent.setup();
- const { rerender } = renderWithI18n(dialog(true));
-
- await user.type(screen.getByLabelText("Name"), "Ongoing");
- rerender(dialog(false));
- rerender(dialog(true));
-
- expect(screen.getByLabelText("Name")).toHaveValue("");
- });
-});
diff --git a/packages/views/issues/components/save-view-dialog.tsx b/packages/views/issues/components/save-view-dialog.tsx
deleted file mode 100644
index 38bba94fa8..0000000000
--- a/packages/views/issues/components/save-view-dialog.tsx
+++ /dev/null
@@ -1,826 +0,0 @@
-"use client";
-
-import { useEffect, useMemo, useRef, useState } from "react";
-import { createStore, type StoreApi } from "zustand/vanilla";
-import { useQuery } from "@tanstack/react-query";
-import { ChevronRight, Plus } from "@multica/ui/icons";
-import { sortDirectionLabelKey } from "../utils/sort-direction";
-import { Button } from "@multica/ui/components/ui/button";
-import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@multica/ui/components/ui/collapsible";
-import {
- Select,
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@multica/ui/components/ui/select";
-import { Toggle } from "@multica/ui/components/ui/toggle";
-import { toast } from "sonner";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { useCreateIssueView, useUpdateIssueView } from "@multica/core/issue-views/mutations";
-import {
- issueViewContainerKey,
- useActiveIssueViewStore,
-} from "@multica/core/issue-views/active-view-store";
-import { ApiError } from "@multica/core/api/client";
-import type { CreateIssueViewRequest, IssueView } from "@multica/core/api/schemas";
-import { projectListOptions } from "@multica/core/projects/queries";
-import { propertyListOptions } from "@multica/core/properties";
-import {
- viewStoreSlice,
- viewStorePersistOptions,
- mergeViewStatePersisted,
- GROUPING_OPTIONS,
- SWIMLANE_GROUPINGS,
- cardPropertyOptionsForView,
- sortOptionsForView,
- type IssueGrouping,
- type IssueViewState,
- type SortField,
- type SwimlaneGrouping,
- type ViewMode,
-} from "@multica/core/issues/stores/view-store";
-import {
- ViewStoreProvider,
- useViewStore,
- useViewStoreApi,
-} from "@multica/core/issues/stores/view-store-context";
-import { IssueFilterMenu } from "./issues-header";
-import { FilterChipList } from "./filter-chips-bar";
-import { useT } from "../../i18n";
-
-/** Where the view being saved will live. Decided by the hosting surface, not
- * by the user — the dialog only explains it. */
-export type SaveViewScope =
- | { kind: "workspace"; actorKind?: "all" | "members" | "agents" }
- | { kind: "my"; variant: "any" | "assigned" | "created" | "involved" }
- | {
- kind: "project";
- projectId: string;
- actorKind?: "all" | "members" | "agents";
- };
-
-const WORKSPACE_VARIANTS = ["all", "members", "agents"] as const;
-const MY_VARIANTS = ["any", "assigned", "created", "involved"] as const;
-type ScopeVariantValue =
- | (typeof WORKSPACE_VARIANTS)[number]
- | (typeof MY_VARIANTS)[number];
-
-const VARIANT_LABEL_KEY = {
- all: "variant_all",
- members: "variant_members",
- agents: "variant_agents",
- any: "variant_my_any",
- assigned: "variant_my_assigned",
- created: "variant_my_created",
- involved: "variant_my_involved",
-} as const;
-
-const MY_VARIANT_HINT_KEY = {
- any: "hint_my_any",
- assigned: "hint_my_assigned",
- created: "hint_my_created",
- involved: "hint_my_involved",
-} as const;
-
-const LAYOUT_LABEL_KEY = {
- list: "list",
- board: "board",
- table: "table",
- swimlane: "swimlane",
- gantt: "gantt",
-} as const;
-
-const GROUPING_LABEL_KEY = {
- status: "group_status",
- assignee: "group_assignee",
- project: "group_project",
-} as const;
-
-const SWIMLANE_LABEL_KEY = {
- parent: "group_parent",
- project: "group_project",
- assignee: "group_assignee",
-} as const;
-
-const SORT_LABEL_KEY = {
- position: "sort_manual",
- status: "sort_status",
- priority: "sort_priority",
- start_date: "sort_start_date",
- due_date: "sort_due_date",
- created_at: "sort_created",
- updated_at: "sort_updated",
- title: "sort_title",
-} as const;
-
-const CARD_PROPERTY_LABEL_KEY = {
- priority: "card_priority",
- description: "card_description",
- assignee: "card_assignee",
- startDate: "card_start_date",
- dueDate: "card_due_date",
- project: "card_project",
- labels: "card_labels",
- childProgress: "card_child_progress",
-} as const;
-
-/** Data-only snapshot: `partialize` strips the store's bound actions (which
- * would otherwise write back to the LIVE store) and the deliberately
- * unsaved fields (date filter, agents-working toggle). */
-const snapshotState = viewStorePersistOptions("save-view-draft").partialize;
-
-const ROW_LABEL = "w-16 shrink-0 text-caption text-muted-foreground";
-
-/** Filter row + layout row + collapsible display defaults, all bound to the
- * DRAFT store via the surrounding provider. */
-export function DraftDefinitionFields() {
- const { t } = useT("issues");
- const wsId = useWorkspaceId();
- const viewMode = useViewStore((s) => s.viewMode);
- const grouping = useViewStore((s) => s.grouping);
- const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);
- const sortBy = useViewStore((s) => s.sortBy);
- const sortDirection = useViewStore((s) => s.sortDirection);
- const cardProperties = useViewStore((s) => s.cardProperties);
- const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
- const act = useViewStoreApi().getState();
- const availableSortOptions = sortOptionsForView(viewMode, grouping);
- const availableCardPropertyOptions = cardPropertyOptionsForView(viewMode);
-
- const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
- const groupableProperties = useMemo(
- () => workspaceProperties.filter((p) => p.type === "select"),
- [workspaceProperties],
- );
- const sortableProperties = useMemo(
- () => workspaceProperties.filter((p) => p.type === "number" || p.type === "date"),
- [workspaceProperties],
- );
- const propertyName = (key: string) =>
- workspaceProperties.find((p) => `property:${p.id}` === key)?.name ??
- t(($) => $.save_view.custom_property);
-
- const layoutLabel = t(($) => $.view[LAYOUT_LABEL_KEY[viewMode]]);
- const groupingLabel =
- viewMode === "board"
- ? grouping in GROUPING_LABEL_KEY
- ? t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]])
- : propertyName(grouping)
- : viewMode === "swimlane"
- ? t(($) => $.display[SWIMLANE_LABEL_KEY[swimlaneGrouping]])
- : null;
- const sortLabel =
- sortBy in SORT_LABEL_KEY
- ? t(($) => $.display[SORT_LABEL_KEY[sortBy as keyof typeof SORT_LABEL_KEY]])
- : propertyName(sortBy);
- const sortDirectionLabel =
- sortBy === "position"
- ? null
- : t(($) => $.display[sortDirectionLabelKey(sortBy, sortDirection)]);
- const displaySummary = [
- layoutLabel,
- groupingLabel,
- sortLabel,
- sortDirectionLabel,
- ]
- .filter(Boolean)
- .join(" · ");
-
- return (
- <>
- {/* Filters: bare chips + the full filter menu behind a ghost chip. */}
- <div className="flex items-start gap-3">
- <Label className={`${ROW_LABEL} pt-1`}>
- {t(($) => $.save_view.filters_label)}
- </Label>
- <div className="min-w-0 flex-1">
- <FilterChipList
- trailing={
- <IssueFilterMenu
- freezeAnchor
- trigger={
- <button
- type="button"
- className="flex h-6 items-center gap-1 rounded-md border border-dashed border-border px-2 text-caption text-muted-foreground hover:border-foreground/30 hover:bg-muted/60 hover:text-foreground"
- >
- <Plus className="size-3" />
- {t(($) => $.save_view.add_filter)}
- </button>
- }
- />
- }
- />
- </div>
- </div>
-
- {/* Display defaults: captured already; expandable for fine-tuning. */}
- <Collapsible>
- <CollapsibleTrigger className="group flex w-fit max-w-full items-center gap-1.5 rounded-md -mx-1 px-1 py-1 text-left hover:bg-muted/60">
- <ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[panel-open]:rotate-90" />
- <span className="text-caption font-medium">
- {t(($) => $.save_view.display_defaults)}
- </span>
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {displaySummary}
- </span>
- </CollapsibleTrigger>
- <CollapsibleContent className="h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200 ease-out data-starting-style:h-0 data-ending-style:h-0">
- <div className="space-y-3 pt-2 pl-5">
- <div className="flex items-center gap-3">
- <Label className={ROW_LABEL}>{t(($) => $.save_view.layout_label)}</Label>
- <Select
- items={(["list", "board", "table", "swimlane"] as const).map((mode) => ({
- value: mode as string,
- label: t(($) => $.view[LAYOUT_LABEL_KEY[mode]]),
- }))}
- value={viewMode}
- onValueChange={(v) => {
- if (v) act.setViewMode(v as ViewMode);
- }}
- >
- <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.save_view.layout_label)}>
- <SelectValue>{layoutLabel}</SelectValue>
- </SelectTrigger>
- <SelectContent align="start">
- <SelectGroup>
- {(["list", "board", "table", "swimlane"] as const).map((mode) => (
- <SelectItem key={mode} value={mode}>
- {t(($) => $.view[LAYOUT_LABEL_KEY[mode]])}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- {viewMode === "board" && (
- <div className="flex items-center gap-3">
- <Label className={ROW_LABEL}>
- {t(($) => $.display.grouping_section)}
- </Label>
- <Select
- items={[
- ...GROUPING_OPTIONS.map((opt) => ({
- value: opt.value as string,
- label: t(($) => $.display[GROUPING_LABEL_KEY[opt.value]]),
- })),
- ...groupableProperties.map((p) => ({
- value: `property:${p.id}`,
- label: p.name,
- })),
- ]}
- value={grouping}
- onValueChange={(v) => {
- if (v) act.setGrouping(v as IssueGrouping);
- }}
- >
- <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.display.grouping_section)}>
- <SelectValue>
- {grouping in GROUPING_LABEL_KEY
- ? t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]])
- : propertyName(grouping)}
- </SelectValue>
- </SelectTrigger>
- <SelectContent align="start">
- <SelectGroup>
- {GROUPING_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {t(($) => $.display[GROUPING_LABEL_KEY[opt.value]])}
- </SelectItem>
- ))}
- {groupableProperties.map((property) => (
- <SelectItem key={property.id} value={`property:${property.id}`}>
- {property.name}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- )}
- {viewMode === "swimlane" && (
- <div className="flex items-center gap-3">
- <Label className={ROW_LABEL}>
- {t(($) => $.display.grouping_section)}
- </Label>
- <Select
- items={SWIMLANE_GROUPINGS.map((value) => ({
- value: value as string,
- label: t(($) => $.display[SWIMLANE_LABEL_KEY[value]]),
- }))}
- value={swimlaneGrouping}
- onValueChange={(v) => {
- if (v) act.setSwimlaneGrouping(v as SwimlaneGrouping);
- }}
- >
- <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.display.grouping_section)}>
- <SelectValue>
- {t(($) => $.display[SWIMLANE_LABEL_KEY[swimlaneGrouping]])}
- </SelectValue>
- </SelectTrigger>
- <SelectContent align="start">
- <SelectGroup>
- {SWIMLANE_GROUPINGS.map((value) => (
- <SelectItem key={value} value={value}>
- {t(($) => $.display[SWIMLANE_LABEL_KEY[value]])}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- )}
- <div className="flex items-center gap-3">
- <Label className={ROW_LABEL}>
- {t(($) => $.display.ordering_section)}
- </Label>
- <div className="flex items-center gap-1.5">
- <Select
- items={[
- ...availableSortOptions.map((opt) => ({
- value: opt.value as string,
- label: t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]]),
- })),
- ...sortableProperties.map((p) => ({
- value: `property:${p.id}`,
- label: p.name,
- })),
- ]}
- value={sortBy}
- onValueChange={(v) => {
- if (v) act.setSortBy(v as SortField);
- }}
- >
- <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.display.ordering_section)}>
- <SelectValue>{sortLabel}</SelectValue>
- </SelectTrigger>
- <SelectContent align="start">
- <SelectGroup>
- {availableSortOptions.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]])}
- </SelectItem>
- ))}
- {sortableProperties.map((property) => (
- <SelectItem key={property.id} value={`property:${property.id}`}>
- {property.name}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- {sortBy !== "position" && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() =>
- act.setSortDirection(
- sortDirection === "asc" ? "desc" : "asc",
- )
- }
- aria-label={sortDirectionLabel ?? undefined}
- >
- {sortDirectionLabel}
- </Button>
- )}
- </div>
- </div>
- {availableCardPropertyOptions.length > 0 && (
- <div className="flex items-start gap-3">
- <Label className={`${ROW_LABEL} pt-1`}>
- {t(($) => $.display.card_properties_section)}
- </Label>
- <div className="flex min-w-0 flex-1 flex-wrap gap-1">
- {availableCardPropertyOptions.map((opt) => (
- <Toggle
- key={opt.key}
- size="sm"
- variant="outline"
- pressed={cardProperties[opt.key]}
- onPressedChange={() => act.toggleCardProperty(opt.key)}
- className="h-6 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"
- >
- {t(($) => $.display[CARD_PROPERTY_LABEL_KEY[opt.key]])}
- </Toggle>
- ))}
- {workspaceProperties.map((property) => (
- <Toggle
- key={property.id}
- size="sm"
- variant="outline"
- pressed={cardPropertyIds.includes(property.id)}
- onPressedChange={() => act.toggleCardPropertyId(property.id)}
- className="h-6 max-w-40 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"
- >
- <span className="truncate">{property.name}</span>
- </Toggle>
- ))}
- </div>
- </div>
- )}
- <p className="text-caption text-faint-foreground">
- {t(($) => $.save_view.default_hint)}
- </p>
- </div>
- </CollapsibleContent>
- </Collapsible>
- </>
- );
-}
-
-/**
- * Save the current surface state as a view. Uncontrolled: opening the dialog
- * snapshots the live panel state into a throwaway store, the embedded fields
- * edit THAT copy, and the page underneath never notices. Save reads the
- * copy; closing discards it. Prints until the API exists.
- */
-export function SaveViewDialog({
- open,
- onOpenChange,
- scope,
- editView = null,
- seedFromDefinition = false,
-}: {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- scope: SaveViewScope;
- /** Edit mode: same dialog, prefilled from this view; confirm PATCHes it
- * (with optimistic-concurrency 409 handling) instead of creating. */
- editView?: IssueView | null;
- /** Manager-initiated edits seed from the view's own definition (the user
- * may not have it open); in-view edits keep seeding from the live panel
- * so the user's current additions are part of the draft. */
- seedFromDefinition?: boolean;
-}) {
- const { t } = useT("issues");
- const wsId = useWorkspaceId();
- const liveStore = useViewStoreApi();
- const createView = useCreateIssueView(wsId);
- const setActiveInStore = useActiveIssueViewStore((s) => s.setActive);
- const updateView = useUpdateIssueView(wsId);
-
- const [name, setName] = useState("");
- const [nameError, setNameError] = useState(false);
- const nameInputRef = useRef<HTMLInputElement>(null);
- const [visibility, setVisibility] = useState<"private" | "workspace">("private");
- // Scope-layer variant (the "which tab" axis). Defaults to the tab the
- // user stood on when saving; switchable here because the dialog IS the
- // view-definition editor. scope_type itself never switches.
- const [variant, setVariant] = useState<ScopeVariantValue>("all");
- const [draftStore, setDraftStore] = useState<StoreApi<IssueViewState> | null>(null);
-
- // Fresh draft per open: seed a private store instance from the live
- // panel's data fields, then let the embedded controls mutate it freely.
- // Keyed on `open` alone: hosts rebuild `scope` on every render, and
- // re-seeding on prop identity would wipe a half-typed name (and draft
- // filters) on any background refetch. Hosts set `editView` and `open` in
- // the same event, so the values read here are the ones this open is for.
- useEffect(() => {
- if (!open) {
- setDraftStore(null);
- return;
- }
- const store = createStore<IssueViewState>()(viewStoreSlice);
- if (seedFromDefinition && editView) {
- // Same sanitizer the surface seed uses — the definition is a server
- // blob, never trusted wholesale.
- const defaults = viewStoreSlice(store.setState);
- store.setState(
- mergeViewStatePersisted({ ...editView.query, ...editView.display }, defaults),
- true,
- );
- } else {
- store.setState(snapshotState(liveStore.getState()));
- }
- setDraftStore(store);
- setName(editView?.name ?? "");
- setNameError(false);
- setVisibility(editView?.visibility === "workspace" ? "workspace" : "private");
- if (scope.kind === "workspace" || scope.kind === "project") {
- const fromEdit = editView?.scope_variant;
- setVariant(
- fromEdit === "members" || fromEdit === "agents"
- ? fromEdit
- : editView
- ? "all"
- : (scope.actorKind ?? "all"),
- );
- } else if (scope.kind === "my") {
- const fromEdit = editView?.scope_variant;
- setVariant(
- fromEdit && (MY_VARIANTS as readonly string[]).includes(fromEdit)
- ? (fromEdit as ScopeVariantValue)
- : scope.variant,
- );
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps -- seed once per open, see above
- }, [open]);
-
- const { data: projects = [] } = useQuery({
- ...projectListOptions(wsId),
- enabled: open && scope.kind === "project",
- });
- const projectTitle =
- scope.kind === "project"
- ? projects.find((p) => p.id === scope.projectId)?.title ?? ""
- : "";
-
- const scopeHint =
- scope.kind === "workspace"
- ? variant === "members"
- ? t(($) => $.save_view.hint_workspace_members)
- : variant === "agents"
- ? t(($) => $.save_view.hint_workspace_agents)
- : t(($) => $.save_view.hint_workspace)
- : scope.kind === "my"
- ? t(($) => $.save_view[
- MY_VARIANT_HINT_KEY[
- (MY_VARIANTS as readonly string[]).includes(variant)
- ? (variant as (typeof MY_VARIANTS)[number])
- : scope.variant
- ]
- ])
- : variant === "members"
- ? t(($) => $.save_view.hint_project_members, { title: projectTitle })
- : variant === "agents"
- ? t(($) => $.save_view.hint_project_agents, { title: projectTitle })
- : t(($) => $.save_view.hint_project, { title: projectTitle });
-
- const create = () => {
- if (!draftStore) return;
- if (!name.trim()) {
- setNameError(true);
- nameInputRef.current?.focus();
- return;
- }
- const state = draftStore.getState();
- const payload = {
- name: name.trim(),
- visibility: scope.kind === "my" ? ("private" as const) : visibility,
- scope_type: scope.kind,
- scope_id: scope.kind === "project" ? scope.projectId : null,
- scope_variant:
- scope.kind === "my"
- ? ((MY_VARIANTS as readonly string[]).includes(variant)
- ? (variant as CreateIssueViewRequest["scope_variant"])
- : scope.variant)
- : variant === "members" || variant === "agents"
- ? variant
- : null,
- definition_version: 1,
- query: {
- statusFilters: state.statusFilters,
- priorityFilters: state.priorityFilters,
- assigneeFilters: state.assigneeFilters,
- includeNoAssignee: state.includeNoAssignee,
- creatorFilters: state.creatorFilters,
- projectFilters: state.projectFilters,
- includeNoProject: state.includeNoProject,
- projectStatusFilters: state.projectStatusFilters,
- labelFilters: state.labelFilters,
- propertyFilters: state.propertyFilters,
- },
- display: {
- // Personal display preference (like layout): saved as the view's
- // first-open default, freely adjustable per user afterwards.
- showSubIssues: state.showSubIssues,
- viewMode: state.viewMode,
- grouping: state.grouping,
- sortBy: state.sortBy,
- sortDirection: state.sortDirection,
- cardProperties: state.cardProperties,
- cardPropertyIds: state.cardPropertyIds,
- tableColumns: state.tableColumns,
- tableGrouping: state.tableGrouping,
- tableHierarchy: state.tableHierarchy,
- tableCalculation: state.tableCalculation,
- swimlaneGrouping: state.swimlaneGrouping,
- ganttZoom: state.ganttZoom,
- ganttShowCompleted: state.ganttShowCompleted,
- },
- };
- if (editView) {
- updateView.mutate(
- {
- id: editView.id,
- name: payload.name,
- visibility: payload.visibility,
- scope_variant: payload.scope_variant ?? null,
- query: payload.query,
- display: payload.display,
- expected_revision: editView.revision,
- },
- {
- onSuccess: () => {
- toast.success(t(($) => $.save_view.toast_updated));
- onOpenChange(false);
- },
- onError: (err) => {
- if (err instanceof ApiError && err.status === 409) {
- toast.error(t(($) => $.save_view.toast_conflict));
- return;
- }
- toast.error(
- err instanceof Error ? err.message : t(($) => $.save_view.toast_failed),
- );
- },
- },
- );
- return;
- }
- createView.mutate(payload, {
- onSuccess: (created) => {
- toast.success(t(($) => $.save_view.toast_created));
- // The view you just saved is the one you want to be looking at:
- // activate it on its surface right away. `created` is null only
- // when the response failed to parse — the list refetch still shows
- // the view, it just doesn't auto-open.
- if (created) {
- setActiveInStore(
- issueViewContainerKey(wsId, {
- scope_type: payload.scope_type,
- scope_id: payload.scope_id,
- }),
- created.id,
- );
- }
- onOpenChange(false);
- },
- onError: (err) => {
- toast.error(
- err instanceof Error ? err.message : t(($) => $.save_view.toast_failed),
- );
- },
- });
- };
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-xl">
- <DialogHeader>
- <DialogTitle>
- {editView
- ? t(($) => $.save_view.edit_title)
- : t(($) => $.save_view.title)}
- </DialogTitle>
- <DialogDescription className="break-words">{scopeHint}</DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4">
- <div className="flex items-start gap-3">
- <Label className={`${ROW_LABEL} pt-2`} htmlFor="save-view-name">
- {t(($) => $.save_view.name_label)}
- </Label>
- <div className="min-w-0">
- <Input
- id="save-view-name"
- ref={nameInputRef}
- autoFocus
- required
- aria-invalid={nameError || undefined}
- aria-describedby={nameError ? "save-view-name-error" : undefined}
- value={name}
- onChange={(e) => {
- setName(e.target.value);
- if (nameError && e.target.value.trim()) setNameError(false);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") create();
- }}
- maxLength={80}
- placeholder={t(($) => $.save_view.name_placeholder)}
- className="h-8 w-64"
- />
- {nameError && (
- <p
- id="save-view-name-error"
- className="mt-1 text-caption text-destructive animate-in fade-in-0 slide-in-from-top-1 duration-150"
- >
- {t(($) => $.save_view.name_required)}
- </p>
- )}
- </div>
- </div>
-
- {scope.kind !== "my" && (
- <div className="flex items-center gap-3">
- <Label className={ROW_LABEL}>
- {t(($) => $.save_view.visibility_label)}
- </Label>
- <Select
- items={[
- { value: "private", label: t(($) => $.save_view.visibility_private) },
- { value: "workspace", label: t(($) => $.save_view.visibility_workspace) },
- ]}
- value={visibility}
- onValueChange={(v) => {
- if (v) setVisibility(v as "private" | "workspace");
- }}
- >
- <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.save_view.visibility_label)}>
- <SelectValue>
- {visibility === "private"
- ? t(($) => $.save_view.visibility_private)
- : t(($) => $.save_view.visibility_workspace)}
- </SelectValue>
- </SelectTrigger>
- <SelectContent align="start">
- <SelectGroup>
- <SelectItem value="private">
- {t(($) => $.save_view.visibility_private)}
- </SelectItem>
- <SelectItem value="workspace">
- {t(($) => $.save_view.visibility_workspace)}
- </SelectItem>
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- )}
- {scope.kind === "my" && (
- <p className="pl-19 text-caption text-muted-foreground">
- {t(($) => $.save_view.my_private_note)}
- </p>
- )}
-
- <div className="flex items-center gap-3">
- <Label className={ROW_LABEL}>
- {scope.kind === "my"
- ? t(($) => $.save_view.scope_label_my)
- : t(($) => $.save_view.scope_label_workspace)}
- </Label>
- <Select
- items={(scope.kind === "my"
- ? MY_VARIANTS
- : WORKSPACE_VARIANTS
- ).map((v) => ({
- value: v as string,
- label: t(($) => $.save_view[VARIANT_LABEL_KEY[v]]),
- }))}
- value={variant}
- onValueChange={(v) => {
- if (v) setVariant(v as ScopeVariantValue);
- }}
- >
- <SelectTrigger size="sm" className="w-64" aria-label={
- scope.kind === "my"
- ? t(($) => $.save_view.scope_label_my)
- : t(($) => $.save_view.scope_label_workspace)
- }>
- <SelectValue>
- {t(($) => $.save_view[VARIANT_LABEL_KEY[variant]])}
- </SelectValue>
- </SelectTrigger>
- <SelectContent align="start">
- <SelectGroup>
- {(scope.kind === "my" ? MY_VARIANTS : WORKSPACE_VARIANTS).map((v) => (
- <SelectItem key={v} value={v}>
- {t(($) => $.save_view[VARIANT_LABEL_KEY[v]])}
- </SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
-
- {draftStore && (
- <ViewStoreProvider store={draftStore}>
- <DraftDefinitionFields />
- </ViewStoreProvider>
- )}
- </div>
-
- <DialogFooter>
- <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)}>
- {t(($) => $.save_view.cancel)}
- </Button>
- <Button
- size="sm"
- onClick={create}
- disabled={createView.isPending || updateView.isPending}
- >
- {editView
- ? t(($) => $.save_view.update)
- : t(($) => $.save_view.create)}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsx
index 559950402a..04fa4d4863 100644
--- a/packages/views/issues/components/swimlane-view.tsx
+++ b/packages/views/issues/components/swimlane-view.tsx
@@ -679,6 +679,12 @@ function SwimLaneViewImpl({
// `project_id`. Absent → the predicate is a no-op, never match-none.
projectStatusById: activeFiltersProp?.projectStatusById,
labelFilters: activeFiltersProp?.labelFilters ?? [],
+ relationFilters: activeFiltersProp?.relationFilters ?? [],
+ relationContext: activeFiltersProp?.relationContext,
+ dueDateFilters: activeFiltersProp?.dueDateFilters ?? [],
+ today: activeFiltersProp?.today,
+ advancedFilter: activeFiltersProp?.advancedFilter ?? null,
+ negatedFilters: activeFiltersProp?.negatedFilters ?? [],
// Carry the "Show sub-issues" toggle through to the extra-children merge
// path (see `filterIssues(extra, activeFilters)` below); otherwise batch /
// per-parent loaded sub-issues get re-added even when the toggle is off.
diff --git a/packages/views/issues/components/view-bar-popover.tsx b/packages/views/issues/components/view-bar-popover.tsx
deleted file mode 100644
index 765494f763..0000000000
--- a/packages/views/issues/components/view-bar-popover.tsx
+++ /dev/null
@@ -1,309 +0,0 @@
-"use client";
-
-import {
- DndContext,
- PointerSensor,
- closestCenter,
- useSensor,
- useSensors,
- type DragEndEvent,
-} from "@dnd-kit/core";
-import {
- SortableContext,
- useSortable,
- verticalListSortingStrategy,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
-import {
- EyeOff,
- GripVertical,
- MoreHorizontal,
- Pencil,
- Pin,
- PinOff,
- Trash2,
-} from "@multica/ui/icons";
-import { toast } from "sonner";
-import { IconButton } from "@multica/ui/components/common/icon-button";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@multica/ui/components/ui/alert-dialog";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@multica/ui/components/ui/dropdown-menu";
-import { cn } from "@multica/ui/lib/utils";
-import type { IssueView } from "@multica/core/api/schemas";
-import { useT } from "../../i18n";
-
-/** One entry on the bar: a built-in tab or a saved view. */
-export interface ViewBarItem {
- barItemId: string;
- label: string;
- kind: "builtin" | "view";
- view?: IssueView;
- canManage?: boolean;
-}
-
-/** The vertical-locked row drag has no DragOverlay under the pointer, so
- * the grabbing cursor is promoted to the document for the drag's duration
- * (see the `data-dnd-dragging` contract in ui/styles/base.css). */
-function setDndCursor(on: boolean) {
- if (on) document.documentElement.dataset.dndDragging = "true";
- else delete document.documentElement.dataset.dndDragging;
-}
-
-/**
- * The one delete-view confirmation, shared by the manage dialog, the bar's
- * context menu, and the list-panel rows so every entrance carries identical
- * copy and the same "deletes the view only, never issues" contract.
- */
-export function DeleteViewConfirm({
- view,
- onOpenChange,
- onConfirm,
-}: {
- view: IssueView | null;
- onOpenChange: (open: boolean) => void;
- onConfirm: (view: IssueView) => Promise<void>;
-}) {
- const { t } = useT("issues");
- return (
- <AlertDialog open={!!view} onOpenChange={(v) => !v && onOpenChange(false)}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{t(($) => $.view_bar.delete_title)}</AlertDialogTitle>
- <AlertDialogDescription className="break-words">
- {t(($) => $.view_bar.delete_description, { name: view?.name ?? "" })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t(($) => $.save_view.cancel)}</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- const target = view;
- onOpenChange(false);
- if (!target) return;
- void onConfirm(target).then(
- () => toast.success(t(($) => $.view_bar.toast_deleted)),
- () => toast.error(t(($) => $.save_view.toast_failed)),
- );
- }}
- >
- {t(($) => $.view_bar.delete)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
-
-function SortablePanelRow({
- item,
- active,
- pinned,
- onSelect,
- onEdit,
- onDelete,
- onTogglePin,
- onHide,
-}: {
- item: ViewBarItem;
- active: boolean;
- pinned: boolean;
- onSelect: () => void;
- onEdit?: () => void;
- onDelete?: () => void;
- onTogglePin?: () => void;
- onHide?: () => void;
-}) {
- const { t } = useT("issues");
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
- useSortable({ id: item.barItemId });
- const isView = item.kind === "view";
-
- return (
- <div
- ref={setNodeRef}
- style={{ transform: CSS.Translate.toString(transform), transition }}
- className={cn(
- "group/view-row flex items-center gap-1.5 rounded-md px-1.5 py-1",
- isDragging ? "z-10 bg-accent opacity-80" : "hover:bg-muted/60",
- )}
- >
- <TooltipHint label={t(($) => $.view_bar.drag_handle)}>
- <button
- type="button"
- {...attributes}
- {...listeners}
- aria-label={t(($) => $.view_bar.drag_handle)}
- className={cn(
- "cursor-grab active:cursor-grabbing text-faint-foreground hover:text-muted-foreground",
- isDragging && "cursor-grabbing",
- )}
- >
- <GripVertical className="size-3.5" />
- </button>
- </TooltipHint>
- <button
- type="button"
- onClick={onSelect}
- className={cn(
- "flex min-w-0 flex-1 items-center gap-1.5 text-left text-body",
- active && "font-medium",
- )}
- >
- <span className="truncate">{item.label}</span>
- {item.kind === "builtin" && (
- <span className="shrink-0 text-caption text-muted-foreground">
- {t(($) => $.view_bar.builtin_tag)}
- </span>
- )}
- </button>
- {isView && item.view && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <IconButton
- variant="ghost"
- size="icon-sm"
- label={t(($) => $.view_bar.row_menu)}
- className="text-muted-foreground"
- >
- <MoreHorizontal className="size-3.5" />
- </IconButton>
- }
- />
- <DropdownMenuContent align="end" className="w-44">
- {/* Same permission presentation as the tab context menu:
- edit greys out, delete hides. */}
- <DropdownMenuItem disabled={!item.canManage} onClick={onEdit}>
- <Pencil className="size-3.5" />
- {t(($) => $.view_bar.context_edit)}
- </DropdownMenuItem>
- {item.canManage && (
- <DropdownMenuItem variant="destructive" onClick={onDelete}>
- <Trash2 className="size-3.5" />
- {t(($) => $.view_bar.delete)}
- </DropdownMenuItem>
- )}
- <DropdownMenuItem onClick={onTogglePin}>
- {pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}
- {pinned
- ? t(($) => $.view_bar.context_unpin)
- : t(($) => $.view_bar.context_pin)}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={onHide}>
- <EyeOff className="size-3.5" />
- {t(($) => $.view_bar.row_hide)}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </div>
- );
-}
-
-/**
- * The pulled-down list: EVERY tab on the bar, in bar order, drag to
- * reorder — the same preference document the bar's inline drag writes.
- * Because the bar shows the longest fitting prefix, reordering here IS
- * the control over what stays visible: drag something up to put it on
- * the bar, down to tuck it away. A separator marks the current fold.
- */
-export function ViewListPanel({
- items,
- fitCount,
- activeViewId,
- pinnedViewIds,
- onMoveItem,
- onSelectItem,
- onEditView,
- onDeleteView,
- onTogglePin,
- onHideItem,
-}: {
- /** All bar candidates in order (hidden ones excluded, as on the bar). */
- items: ViewBarItem[];
- /** How many currently fit on the bar — the fold line. */
- fitCount: number;
- activeViewId: string | null;
- pinnedViewIds: ReadonlySet<string>;
- /** Reorder request: move the item with `activeId` next to `overId`. */
- onMoveItem: (activeId: string, overId: string) => void;
- onSelectItem: (item: ViewBarItem) => void;
- onEditView: (view: IssueView) => void;
- onDeleteView: (view: IssueView) => void;
- onTogglePin: (view: IssueView, pinned: boolean) => void;
- onHideItem: (barItemId: string) => void;
-}) {
- const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
- );
-
- const handleDragEnd = (event: DragEndEvent) => {
- setDndCursor(false);
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- onMoveItem(String(active.id), String(over.id));
- };
-
- return (
- <div className="max-h-96 overflow-y-auto p-1">
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- modifiers={[restrictToVerticalAxis]}
- autoScroll={{ threshold: { x: 0, y: 0.15 } }}
- onDragStart={() => setDndCursor(true)}
- onDragCancel={() => setDndCursor(false)}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={items.map((item) => item.barItemId)}
- strategy={verticalListSortingStrategy}
- >
- {items.map((item, index) => (
- <div key={item.barItemId}>
- {/* The fold: everything above is on the bar right now. */}
- {index === fitCount && index > 0 && (
- <div className="mx-1.5 my-1 border-t border-border" />
- )}
- <SortablePanelRow
- item={item}
- active={
- item.kind === "view" && item.view
- ? item.view.id === activeViewId
- : false
- }
- pinned={!!item.view && pinnedViewIds.has(item.view.id)}
- onSelect={() => onSelectItem(item)}
- onEdit={item.view ? () => onEditView(item.view!) : undefined}
- onDelete={item.view ? () => onDeleteView(item.view!) : undefined}
- onTogglePin={
- item.view
- ? () => onTogglePin(item.view!, pinnedViewIds.has(item.view!.id))
- : undefined
- }
- onHide={() => onHideItem(item.barItemId)}
- />
- </div>
- ))}
- </SortableContext>
- </DndContext>
- </div>
- );
-}
diff --git a/packages/views/issues/components/view-bar.test.tsx b/packages/views/issues/components/view-bar.test.tsx
deleted file mode 100644
index 54eafc5cad..0000000000
--- a/packages/views/issues/components/view-bar.test.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, screen } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { createAuthStore, registerAuthStore } from "@multica/core/auth";
-import type { ApiClient } from "@multica/core/api/client";
-import { IssueViewSchema, type IssueView } from "@multica/core/api/schemas";
-import { issueViewPrefKeys } from "@multica/core/issue-views/preferences";
-import { workspaceKeys } from "@multica/core/workspace/queries";
-import { renderWithI18n } from "../../test/i18n";
-import { ViewBar, type ViewBarBuiltin } from "./view-bar";
-
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "ws-1",
-}));
-
-const scope = { scope_type: "project" as const, scope_id: "project-1" };
-const builtins: ViewBarBuiltin[] = [
- { key: "all", label: "All issues", active: true, onSelect: vi.fn() },
- { key: "board", label: "Board", active: false, onSelect: vi.fn() },
- { key: "timeline", label: "Timeline", active: false, onSelect: vi.fn() },
-];
-const views = [
- IssueViewSchema.parse({ id: "view-1", name: "My issues" }),
- IssueViewSchema.parse({ id: "view-2", name: "Recently updated" }),
-];
-
-let queryClient: QueryClient;
-let containerWidth: number;
-const resizeObservers = new Set<TestResizeObserver>();
-
-class TestResizeObserver {
- private targets = new Set<Element>();
-
- constructor(private callback: ResizeObserverCallback) {
- resizeObservers.add(this);
- }
-
- observe(target: Element) {
- this.targets.add(target);
- }
-
- unobserve(target: Element) {
- this.targets.delete(target);
- }
-
- disconnect() {
- resizeObservers.delete(this);
- }
-
- notify(target: Element) {
- if (this.targets.has(target)) {
- this.callback(
- [{ target } as ResizeObserverEntry],
- this as unknown as ResizeObserver,
- );
- }
- }
-}
-
-function renderBar({
- initialViews = views,
- activeView = null,
- viewsReady = true,
-}: {
- initialViews?: IssueView[];
- activeView?: IssueView | null;
- viewsReady?: boolean;
-} = {}) {
- const props = {
- wsId: "ws-1",
- scope,
- builtins,
- activeView,
- onSelectView: vi.fn(),
- onNewView: vi.fn(),
- onEditView: vi.fn(),
- };
- const result = renderWithI18n(
- <QueryClientProvider client={queryClient}>
- <ViewBar {...props} views={initialViews} viewsReady={viewsReady} />
- </QueryClientProvider>,
- );
- return {
- ...result,
- loadViews: () => result.rerender(
- <QueryClientProvider client={queryClient}>
- <ViewBar {...props} views={views} viewsReady />
- </QueryClientProvider>,
- ),
- resize: (width: number) => {
- act(() => {
- containerWidth = width;
- for (const observer of resizeObservers) {
- observer.notify(result.container.firstElementChild!);
- }
- });
- },
- };
-}
-
-beforeEach(() => {
- registerAuthStore(
- createAuthStore({
- api: {} as ApiClient,
- storage: {
- getItem: () => null,
- setItem: () => {},
- removeItem: () => {},
- },
- }),
- );
- queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false, staleTime: Infinity, gcTime: Infinity },
- },
- });
- queryClient.setQueryData(workspaceKeys.members("ws-1"), []);
- queryClient.setQueryData(issueViewPrefKeys.scope("ws-1", scope), {
- scope_type: "project",
- scope_id: scope.scope_id,
- prefs: {
- hidden: [],
- order: [
- ...builtins.map((item) => `builtin:${item.key}`),
- ...views.map((view) => `view:${view.id}`),
- ],
- },
- updated_at: "",
- });
- // Five 100px tabs fit with the permanent menu, but not with an overflow
- // trigger: 5 * 100 + 5 * 4 + 36 <= 570 < 5 * 100 + 5 * 4 + 68.
- containerWidth = 570;
- vi.stubGlobal("ResizeObserver", TestResizeObserver);
- vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(
- () => containerWidth,
- );
- vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(100);
-});
-
-afterEach(() => {
- cleanup();
- queryClient.clear();
- resizeObservers.clear();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-describe("ViewBar fitting", () => {
- it("settles when saved views load at the overflow boundary", () => {
- const { loadViews } = renderBar({ initialViews: [], viewsReady: false });
- expect(loadViews).not.toThrow();
-
- for (const item of [...builtins, ...views.map((view) => ({ label: view.name }))]) {
- expect(screen.getByRole("button", { name: item.label })).toBeInTheDocument();
- }
- expect(screen.queryByRole("button", { name: "More views" })).not.toBeInTheDocument();
- });
-
- it("restores all tabs when the container grows past the overflow boundary", () => {
- containerWidth = 400;
- const { resize } = renderBar();
-
- expect(screen.getByRole("button", { name: "More views" })).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: views[0]!.name })).not.toBeInTheDocument();
-
- resize(570);
-
- for (const item of [...builtins, ...views.map((view) => ({ label: view.name }))]) {
- expect(screen.getByRole("button", { name: item.label })).toBeInTheDocument();
- }
- expect(screen.queryByRole("button", { name: "More views" })).not.toBeInTheDocument();
- });
-
- it("keeps the active overflowed view available by name", () => {
- containerWidth = 450;
- renderBar({ activeView: views[1]! });
-
- expect(screen.getByRole("button", { name: "All issues" })).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "Board" })).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Timeline" })).not.toBeInTheDocument();
- expect(screen.getByRole("button", { name: views[1]!.name })).toBeInTheDocument();
- });
-
- it("keeps overflow controls available when no tab fits", () => {
- containerWidth = 80;
- renderBar();
-
- expect(screen.getByRole("button", { name: "More views" })).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "Views" })).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "All issues" })).not.toBeInTheDocument();
- });
-});
diff --git a/packages/views/issues/components/view-bar.tsx b/packages/views/issues/components/view-bar.tsx
deleted file mode 100644
index ed83a802e2..0000000000
--- a/packages/views/issues/components/view-bar.tsx
+++ /dev/null
@@ -1,597 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
-import {
- DndContext,
- PointerSensor,
- closestCenter,
- useSensor,
- useSensors,
- type DragEndEvent,
-} from "@dnd-kit/core";
-import {
- SortableContext,
- arrayMove,
- horizontalListSortingStrategy,
- useSortable,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
-import {
- ChevronDown,
- Layers,
- MoreHorizontal,
- Pencil,
- Pin,
- PinOff,
- Plus,
- Settings2,
- Trash2,
-} from "@multica/ui/icons";
-import { Button } from "@multica/ui/components/ui/button";
-import {
- ContextMenu,
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuSeparator,
- ContextMenuTrigger,
-} from "@multica/ui/components/ui/context-menu";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@multica/ui/components/ui/dropdown-menu";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
-import { cn } from "@multica/ui/lib/utils";
-import type { IssueView } from "@multica/core/api/schemas";
-import {
- canManageIssueView,
- type IssueViewScope,
-} from "@multica/core/issue-views/queries";
-import {
- applyViewBarPrefs,
- issueViewPreferenceOptions,
- useUpdateIssueViewPreference,
- EMPTY_VIEW_BAR_PREFS,
-} from "@multica/core/issue-views/preferences";
-import { useDeleteIssueView } from "@multica/core/issue-views/mutations";
-import { useAuthStore } from "@multica/core/auth";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { pinListOptions } from "@multica/core/pins/queries";
-import { useCreatePin, useDeletePin } from "@multica/core/pins/mutations";
-import { useSingleRowFit } from "../../common/single-row-fit";
-import { ManageViewsDialog } from "./manage-views-dialog";
-import {
- DeleteViewConfirm,
- ViewListPanel,
- type ViewBarItem,
-} from "./view-bar-popover";
-import { useT } from "../../i18n";
-
-export interface ViewBarBuiltin {
- key: string;
- label: string;
- description?: string;
- active: boolean;
- onSelect: () => void;
-}
-
-/** Width shared by every tab: fits short names, truncates long ones. */
-const TAB_MAX_W = "max-w-40";
-/** Reserved px beside the tabs, by what actually renders there: the [⧉]
- * menu is permanent; the "more" trigger exists only while something is
- * overflowed; the promoted active tab is the wide shape. */
-const RESERVE_MENU = 36;
-const RESERVE_MORE = RESERVE_MENU + 32;
-const RESERVE_PROMOTED = RESERVE_MENU + 200;
-
-/** One bar tab: sortable in place; suppresses the click that ends a drag. */
-function SortableBarTab({
- id,
- children,
-}: {
- id: string;
- children: React.ReactNode;
-}) {
- const { listeners, setNodeRef, transform, transition, isDragging } =
- useSortable({ id });
- const wasDragged = useRef(false);
- useEffect(() => {
- if (isDragging) {
- wasDragged.current = true;
- return;
- }
- if (!wasDragged.current) return;
- // A drop lands as a click (swallowed below); a cancelled drag (Escape)
- // produces none — clear the flag a tick later so the NEXT real click
- // isn't eaten by a drag that never dropped.
- const timer = window.setTimeout(() => {
- wasDragged.current = false;
- }, 0);
- return () => window.clearTimeout(timer);
- }, [isDragging]);
- return (
- // Listeners only — dnd-kit's aria attributes would make this span a
- // second focusable role=button wrapping the real tab button.
- <span
- ref={setNodeRef}
- style={{ transform: CSS.Translate.toString(transform), transition }}
- className={cn("inline-flex", isDragging && "z-10 opacity-70")}
- {...listeners}
- onClickCapture={(event) => {
- if (wasDragged.current) {
- wasDragged.current = false;
- event.preventDefault();
- event.stopPropagation();
- }
- }}
- >
- {children}
- </span>
- );
-}
-
-/** Shared tab chrome so the real row and the measurement mirror agree. */
-function BarTabButton({
- label,
- active,
- onClick,
-}: {
- label: string;
- active?: boolean;
- onClick?: () => void;
-}) {
- return (
- <Button
- variant="outline"
- size="sm"
- className={cn(
- TAB_MAX_W,
- active
- ? "bg-accent text-accent-foreground hover:bg-accent/80"
- : "text-muted-foreground",
- )}
- onClick={onClick}
- tabIndex={onClick ? undefined : -1}
- >
- <span className="truncate">{label}</span>
- </Button>
- );
-}
-
-/**
- * The view bar: built-in tabs and saved views as one flat, per-user
- * orderable single row. Everything that fits renders as a tab (drag to
- * reorder, horizontal axis); the rest collapses into a "more" popover
- * that appears only when needed. The OPEN view is always visible — when
- * overflowed it takes the trigger slot with its own name. The [⧉] menu
- * (new view / manage views) is unchanged.
- */
-export function ViewBar({
- wsId,
- scope,
- builtins,
- views,
- viewsReady,
- activeView,
- onSelectView,
- onNewView,
- onEditView,
-}: {
- wsId: string;
- scope: IssueViewScope;
- builtins: ViewBarBuiltin[];
- views: IssueView[];
- /** True once the views list has actually loaded — see savePrefs. */
- viewsReady: boolean;
- activeView: IssueView | null;
- onSelectView: (view: IssueView | null) => void;
- onNewView: () => void;
- /** Opens the edit dialog seeded from the view's own definition. */
- onEditView: (view: IssueView) => void;
-}) {
- const { t } = useT("issues");
- const currentUserId = useAuthStore((s) => s.user?.id ?? null);
- const { data: preference } = useQuery(issueViewPreferenceOptions(wsId, scope));
- const prefs = preference?.prefs ?? EMPTY_VIEW_BAR_PREFS;
- const updatePreference = useUpdateIssueViewPreference(wsId, scope);
- const deleteView = useDeleteIssueView(wsId);
- const [manageOpen, setManageOpen] = useState(false);
- const [moreOpen, setMoreOpen] = useState(false);
- const [deleting, setDeleting] = useState<IssueView | null>(null);
-
- // The same manage rule the server enforces: owner, or workspace
- // owner/admin for shared views. Members load from cache in one query.
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- const myRole = useMemo(
- () => members.find((m) => m.user_id === currentUserId)?.role ?? null,
- [members, currentUserId],
- );
-
- const { data: pins = [] } = useQuery({
- ...pinListOptions(wsId, currentUserId ?? ""),
- enabled: !!currentUserId,
- });
- const pinnedViewIds = useMemo(
- () =>
- new Set(
- pins.filter((p) => p.item_type === "view").map((p) => p.item_id),
- ),
- [pins],
- );
- const createPin = useCreatePin();
- const deletePin = useDeletePin();
-
- const anchorId = builtins.length > 0 ? `builtin:${builtins[0]!.key}` : "";
-
- const items = useMemo<ViewBarItem[]>(
- () => [
- ...builtins.map((b) => ({
- barItemId: `builtin:${b.key}`,
- label: b.label,
- kind: "builtin" as const,
- })),
- ...views.map((view) => ({
- barItemId: `view:${view.id}`,
- label: view.name,
- kind: "view" as const,
- view,
- canManage: canManageIssueView(view, currentUserId, myRole),
- })),
- ],
- [builtins, views, currentUserId, myRole],
- );
-
- // Synchronous mirror of a just-dropped order. The preference mutation is
- // optimistic but its onMutate is async — without this, the dropped tab
- // renders back at its OLD slot for a frame before the cache lands, which
- // reads as a bounce. Cleared as soon as the preference data catches up.
- const [localOrder, setLocalOrder] = useState<string[] | null>(null);
- useEffect(() => {
- setLocalOrder(null);
- }, [preference]);
- const displayPrefs = useMemo(
- () => (localOrder ? { ...prefs, order: localOrder } : prefs),
- [prefs, localOrder],
- );
-
- const { visible, hiddenSet, ordered } = useMemo(
- () => applyViewBarPrefs(items, displayPrefs, anchorId),
- [items, displayPrefs, anchorId],
- );
-
- const builtinByKey = useMemo(
- () => new Map(builtins.map((b) => [`builtin:${b.key}`, b])),
- [builtins],
- );
-
- // --- single-row fit -----------------------------------------------------
- const activeBarId = activeView ? `view:${activeView.id}` : null;
- const activeIndex = visible.findIndex((item) => item.barItemId === activeBarId);
- const reserve = useCallback(
- (fittingCount: number) =>
- activeIndex >= fittingCount
- ? RESERVE_PROMOTED
- : fittingCount < visible.length
- ? RESERVE_MORE
- : RESERVE_MENU,
- [activeIndex, visible.length],
- );
- const { containerRef, measureRef, fitCount } = useSingleRowFit({
- count: visible.length,
- gap: 4,
- reserve,
- });
- const fitting = visible.slice(0, fitCount);
- const overflowed = visible.slice(fitCount);
- const activeOverflowed =
- !!activeBarId && overflowed.some((item) => item.barItemId === activeBarId);
- const promoted = activeOverflowed;
-
- const savePrefs = (next: { hidden: string[]; order: string[] }) => {
- // A drag can land before the views list has loaded; pruning against an
- // in-flight (empty) list would persist "every saved view was deleted"
- // and wipe the user's order and hidden sets. Drop the write instead —
- // the gesture is re-doable one moment later.
- if (!viewsReady) return;
- // Prune ids that no longer resolve so deleted views don't accumulate.
- const known = new Set(items.map((item) => item.barItemId));
- updatePreference.mutate({
- hidden: next.hidden.filter((id) => known.has(id)),
- order: next.order.filter((id) => known.has(id)),
- });
- };
-
- const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
- );
- // Apply a move NOW (mirror) and persist it — both drag surfaces route
- // through here so the drop lands visually in the same frame.
- const applyMove = (activeId: string, overId: string) => {
- const ids = ordered.map((item) => item.barItemId);
- const from = ids.indexOf(activeId);
- const to = ids.indexOf(overId);
- if (from < 0 || to < 0) return;
- const next = arrayMove(ids, from, to);
- if (viewsReady) setLocalOrder(next);
- savePrefs({ hidden: [...hiddenSet], order: next });
- };
-
- const handleDragEnd = (event: DragEndEvent) => {
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- applyMove(String(active.id), String(over.id));
- };
-
- const confirmDelete = async (view: IssueView) => {
- await deleteView.mutateAsync(view.id);
- if (activeView?.id === view.id) onSelectView(null);
- };
-
- const toggleHidden = (barItemId: string, hidden: boolean) => {
- const nextHidden = new Set(hiddenSet);
- if (hidden) nextHidden.add(barItemId);
- else nextHidden.delete(barItemId);
- savePrefs({
- hidden: [...nextHidden],
- order: ordered.map((item) => item.barItemId),
- });
- // Hiding the open view exits it — an invisible active view would
- // strand the surface with no matching tab.
- if (hidden && activeView && barItemId === `view:${activeView.id}`) {
- onSelectView(null);
- }
- };
-
- const togglePin = (view: IssueView, pinned: boolean) =>
- pinned
- ? deletePin.mutate({ itemType: "view", itemId: view.id })
- : createPin.mutate({ item_type: "view", item_id: view.id });
-
- const selectItem = (item: ViewBarItem) => {
- if (item.kind === "builtin") {
- builtinByKey.get(item.barItemId)?.onSelect();
- } else if (item.view) {
- onSelectView(item.view);
- }
- setMoreOpen(false);
- };
-
- const renderViewTab = (item: ViewBarItem) => {
- const view = item.view!;
- const active = activeView?.id === view.id;
- const pinned = pinnedViewIds.has(view.id);
- return (
- <ContextMenu>
- <ContextMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className={cn(
- TAB_MAX_W,
- active
- ? "bg-accent text-accent-foreground hover:bg-accent/80"
- : "text-muted-foreground",
- )}
- onClick={() => onSelectView(active ? null : view)}
- />
- }
- >
- <span className="truncate">{view.name}</span>
- </ContextMenuTrigger>
- <ContextMenuContent className="w-44">
- {/* Edit stays visible but disabled without permission — the greyed
- row IS the "you can't" signal. Delete is hidden entirely: a
- destructive dead-end invites a doomed confirm flow. */}
- <ContextMenuItem
- disabled={!item.canManage}
- onClick={() => onEditView(view)}
- >
- <Pencil className="size-3.5" />
- {t(($) => $.view_bar.context_edit)}
- </ContextMenuItem>
- {item.canManage && (
- <ContextMenuItem
- variant="destructive"
- onClick={() => setDeleting(view)}
- >
- <Trash2 className="size-3.5" />
- {t(($) => $.view_bar.delete)}
- </ContextMenuItem>
- )}
- <ContextMenuSeparator />
- <ContextMenuItem onClick={() => togglePin(view, pinned)}>
- {pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}
- {pinned
- ? t(($) => $.view_bar.context_unpin)
- : t(($) => $.view_bar.context_pin)}
- </ContextMenuItem>
- </ContextMenuContent>
- </ContextMenu>
- );
- };
-
- return (
- <div
- ref={containerRef}
- className="relative flex min-w-0 flex-1 flex-nowrap items-center gap-1 overflow-hidden"
- >
- {/* Measurement mirror: every visible candidate at natural width. */}
- <div
- ref={measureRef}
- aria-hidden
- className="pointer-events-none invisible absolute left-0 top-0 flex flex-nowrap items-center gap-1"
- >
- {visible.map((item) => (
- <span key={item.barItemId} className="inline-flex">
- <BarTabButton label={item.label} />
- </span>
- ))}
- </div>
-
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- // Same gesture contract as the table's column reordering: tabs slide
- // along the row only. Overflowed items reorder via the manage dialog.
- modifiers={[restrictToHorizontalAxis]}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={fitting.map((item) => item.barItemId)}
- strategy={horizontalListSortingStrategy}
- >
- {fitting.map((item) => {
- if (item.kind === "builtin") {
- const b = builtinByKey.get(item.barItemId);
- if (!b) return null;
- const button = (
- <BarTabButton label={b.label} active={b.active} onClick={b.onSelect} />
- );
- return (
- <SortableBarTab key={item.barItemId} id={item.barItemId}>
- {b.description ? (
- <Tooltip>
- <TooltipTrigger render={button} />
- <TooltipContent side="bottom">{b.description}</TooltipContent>
- </Tooltip>
- ) : (
- button
- )}
- </SortableBarTab>
- );
- }
- return (
- <SortableBarTab key={item.barItemId} id={item.barItemId}>
- {renderViewTab(item)}
- </SortableBarTab>
- );
- })}
- </SortableContext>
- </DndContext>
-
- {/* "More" is an overflow indicator: it renders only while something
- is actually collapsed. Reordering in its panel decides what fits
- on the bar; the open view becomes the trigger when it overflows
- so it never disappears. With nothing overflowed, reorder lives on
- the bar itself and management on the [⧉] menu. */}
- {overflowed.length > 0 && (
- <Popover open={moreOpen} onOpenChange={setMoreOpen}>
- <PopoverTrigger
- render={
- promoted && activeView ? (
- <Button
- variant="outline"
- size="sm"
- className={cn(
- TAB_MAX_W,
- "shrink-0 gap-1 bg-accent text-accent-foreground hover:bg-accent/80",
- )}
- >
- <span className="truncate">{activeView.name}</span>
- <ChevronDown className="size-3 shrink-0" />
- </Button>
- ) : (
- <Button
- variant="outline"
- size="sm"
- aria-label={t(($) => $.view_bar.more_label)}
- className="shrink-0 px-1.5 text-muted-foreground"
- >
- <MoreHorizontal className="size-3.5" />
- </Button>
- )
- }
- />
- <PopoverContent align="end" className="w-64 p-0">
- <ViewListPanel
- items={visible}
- fitCount={fitCount}
- activeViewId={activeView?.id ?? null}
- pinnedViewIds={pinnedViewIds}
- onMoveItem={applyMove}
- onSelectItem={selectItem}
- onEditView={(view) => {
- setMoreOpen(false);
- onEditView(view);
- }}
- onDeleteView={(view) => {
- setMoreOpen(false);
- setDeleting(view);
- }}
- onTogglePin={togglePin}
- onHideItem={(barItemId) => {
- setMoreOpen(false);
- toggleHidden(barItemId, true);
- }}
- />
- </PopoverContent>
- </Popover>
- )}
-
- <DropdownMenu>
- <Tooltip>
- <DropdownMenuTrigger
- render={
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label={t(($) => $.view_bar.menu_label)}
- className="shrink-0 text-muted-foreground"
- >
- <Layers className="size-3.5" />
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">{t(($) => $.view_bar.menu_label)}</TooltipContent>
- </Tooltip>
- <DropdownMenuContent align="start" className="w-44">
- <DropdownMenuItem onClick={onNewView}>
- <Plus className="size-3.5" />
- {t(($) => $.view_bar.menu_new)}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setManageOpen(true)}>
- <Settings2 className="size-3.5" />
- {t(($) => $.view_bar.menu_manage)}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
-
- <ManageViewsDialog
- open={manageOpen}
- onOpenChange={setManageOpen}
- items={ordered}
- hiddenSet={hiddenSet}
- anchorId={anchorId}
- onReorder={(orderedIds) => savePrefs({ hidden: [...hiddenSet], order: orderedIds })}
- onToggleHidden={toggleHidden}
- onEditView={(view) => {
- setManageOpen(false);
- onEditView(view);
- }}
- onDeleteView={confirmDelete}
- />
-
- {/* Context-menu / overflow-row delete share one confirm. */}
- <DeleteViewConfirm
- view={deleting}
- onOpenChange={(open) => {
- if (!open) setDeleting(null);
- }}
- onConfirm={confirmDelete}
- />
- </div>
- );
-}
diff --git a/packages/views/issues/components/wakeup-control.tsx b/packages/views/issues/components/wakeup-control.tsx
index 25ff46aaed..46920dc30f 100644
--- a/packages/views/issues/components/wakeup-control.tsx
+++ b/packages/views/issues/components/wakeup-control.tsx
@@ -12,6 +12,7 @@ import {
DialogTitle,
} from "@multica/ui/components/ui/dialog";
import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
import { isActiveWakeupRun, useWakeupText } from "./wakeup-presentation";
@@ -28,7 +29,8 @@ export function WakeupControl({
task?: AgentTask;
pending: boolean;
closed: boolean;
- size?: "sm" | "default";
+ /** `xs` fits a 36px list row. */
+ size?: "xs" | "sm" | "default";
onDisable: () => void;
onEnable: (input?: { at?: string; rearm?: boolean }) => Promise<void>;
}) {
@@ -51,10 +53,19 @@ export function WakeupControl({
const needsRearm = !wakeup.enabled && (consumed || expired);
const canEnable = !closed && (!activeRun || wakeup.mode === "continuous");
return (
- <div className={`flex shrink-0 items-center px-2 ${size === "sm" ? "min-h-10 [&>button]:text-caption [&>button]:font-normal" : "min-h-11"}`}>
+ <div
+ className={cn(
+ "flex shrink-0 items-center",
+ size === "xs"
+ ? "[&>button]:h-6 [&>button]:px-2 [&>button]:text-caption [&>button]:font-normal"
+ : size === "sm"
+ ? "min-h-10 px-2 [&>button]:text-caption [&>button]:font-normal"
+ : "min-h-11 px-2",
+ )}
+ >
{wakeup.enabled || (!needsRearm && !canDisable) ? (
<Switch
- size={size}
+ size={size === "default" ? "default" : "sm"}
checked={wakeup.enabled}
disabled={pending || (!wakeup.enabled && !canEnable)}
aria-label={t(($) => $.wakeups.toggle, {
diff --git a/packages/views/issues/components/wakeup-instruction-editor.tsx b/packages/views/issues/components/wakeup-instruction-editor.tsx
index efd5307ec0..85c9b40960 100644
--- a/packages/views/issues/components/wakeup-instruction-editor.tsx
+++ b/packages/views/issues/components/wakeup-instruction-editor.tsx
@@ -48,8 +48,8 @@ export function WakeupInstructionEditor({
render={
<Button
variant="ghost"
- size={triggerStyle === "icon" ? "icon" : "sm"}
- className={triggerStyle === "icon" ? "size-11 text-muted-foreground" : undefined}
+ size={triggerStyle === "icon" ? "icon-xs" : "sm"}
+ className={triggerStyle === "icon" ? "text-muted-foreground" : undefined}
disabled={disabled}
aria-label={label}
/>
diff --git a/packages/views/issues/components/workspace-agent-working-chip.tsx b/packages/views/issues/components/workspace-agent-working-chip.tsx
index 436ed6dc41..0c2f467ce5 100644
--- a/packages/views/issues/components/workspace-agent-working-chip.tsx
+++ b/packages/views/issues/components/workspace-agent-working-chip.tsx
@@ -18,6 +18,8 @@ interface WorkspaceAgentWorkingChipProps {
/** Agents working inside the surface this header belongs to, already narrowed
* by its scope and every active filter. `undefined` = not resolved yet. */
agents: readonly WorkingAgentSummary[] | undefined;
+ /** Avatars and the number only, for a header that has run out of room. */
+ compact?: boolean;
}
/** What the projection says about activity in this surface. `unknown` is a
@@ -144,6 +146,7 @@ export function WorkspaceAgentWorkingChip({
value,
onToggle,
agents,
+ compact = false,
}: WorkspaceAgentWorkingChipProps) {
const { t } = useT("issues");
const activity = chipActivity(agents);
@@ -166,10 +169,12 @@ export function WorkspaceAgentWorkingChip({
{activity === "some" && (
<AgentAvatarStack agentIds={agentIds} size="sm" max={3} />
)}
- <span className="tabular-nums md:hidden">
+ <span className={compact ? "tabular-nums" : "tabular-nums md:hidden @max-3xl/issue-header:inline"}>
{activity === "unknown" ? "—" : agentIds.length}
</span>
- <span className="hidden tabular-nums md:inline">{label}</span>
+ {!compact && (
+ <span className="hidden tabular-nums md:inline @max-3xl/issue-header:hidden">{label}</span>
+ )}
</Button>
);
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index 267967ae6c..afd1db0b73 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -20,7 +20,6 @@ import {
seedIssueSurfaceViewState,
} from "@multica/core/issues/stores/surface-view-store";
import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";
-import { baselineFromQuery } from "@multica/core/issue-views/baseline";
import { ViewBaselineProvider, useViewBaseline } from "./view-baseline-context";
import type { IssueViewScope } from "@multica/core/issue-views/queries";
import {
@@ -34,7 +33,6 @@ import { BoardView } from "../components/board-view";
import { BOARD_COL_WIDTH } from "../components/board-column";
import { BatchActionToolbar } from "../components/batch-action-toolbar";
import { GanttView } from "../components/gantt-view";
-import { IssuesHeader } from "../components/issues-header";
import { ListView } from "../components/list-view";
import { SwimLaneView } from "../components/swimlane-view";
import { TableView } from "../components/table-view";
@@ -113,10 +111,6 @@ export function IssueSurface({
const seedDefinition = activeView
? { ...activeView.query, ...activeView.display }
: null;
- const viewBaseline = useMemo(
- () => (activeView ? baselineFromQuery(activeView.query) : null),
- [activeView],
- );
// While a view is open, the scope axis the view captured belongs to the
// VIEW, not to whichever tab the user stood on: workspace/project views
// carry an assignee-type variant, my views a relation variant. The user's
@@ -155,7 +149,6 @@ export function IssueSurface({
return (
<ViewStoreProvider store={store}>
- <ViewBaselineProvider baseline={viewBaseline}>
{/* Remount on data-window change: the list queries keep the previous
key's data as a placeholder (keepPreviousData) so sort/filter
changes within ONE surface never flash a skeleton — but reusing the
@@ -181,7 +174,6 @@ export function IssueSurface({
batchToolbar={batchToolbar}
contentClassName={contentClassName}
/>
- </ViewBaselineProvider>
</ViewStoreProvider>
);
}
@@ -264,28 +256,7 @@ function IssueSurfaceContent({
<IssueContextMenuProvider>
<IssueSurfaceSelectionProvider selection={controller.selection}>
<ColumnStatusesProvider statuses={controller.columnStatuses}>
- {renderHeader ? (
- renderHeader(renderContext)
- ) : (
- <IssuesHeader
- scopedIssues={controller.surfaceIssues}
- workingAgents={controller.workingAgents}
- allowGantt={controller.allowGantt}
- isRefreshing={controller.isRefreshing}
- facetCountsExact={
- controller.facetCountsExact
- }
- tableFacetCounts={controller.tableFacetCounts}
- onTableFacetChange={controller.setActiveTableFacet}
- saveViewScope={
- scope.type === "project"
- ? { kind: "project", projectId: scope.projectId }
- : scope.type === "workspace"
- ? { kind: "workspace" }
- : null
- }
- />
- )}
+ {renderHeader?.(renderContext)}
{/* Every view opens the side peek on Shift+Click. The host wraps the
loading and empty states too, so a view switch that briefly shows
a skeleton keeps the peek open. */}
diff --git a/packages/views/issues/surface/use-issue-status-branches.ts b/packages/views/issues/surface/use-issue-status-branches.ts
index 42355a3b85..ea99d51d62 100644
--- a/packages/views/issues/surface/use-issue-status-branches.ts
+++ b/packages/views/issues/surface/use-issue-status-branches.ts
@@ -106,13 +106,15 @@ function rebaseCursorState(
/**
* Per-status totals, never folded into lifecycle categories. The facet is
- * disjunctive, so narrow it to the selected keys when a status filter is active.
- * Unknown keys wait for catalog refresh instead of inflating another column.
+ * disjunctive, so apply the status filter to it here: keep the selected keys,
+ * or drop them when the filter is negated. Unknown keys wait for catalog
+ * refresh instead of inflating another column.
*/
function statusCountsFromFacets(
facets: IssueTableFacetsResponse | undefined,
catalog: Pick<IssueStatusCatalog, "entryOf" | "isLoaded">,
selectedStatuses: readonly string[] | undefined,
+ negated: boolean,
) {
const counts = new Map<IssueStatus, number>();
const selected =
@@ -121,7 +123,7 @@ function statusCountsFromFacets(
: null;
const statusFacet = facets?.facets.find((facet) => facet.kind === "status");
for (const value of statusFacet?.values ?? []) {
- if (selected && !selected.has(value.key)) continue;
+ if (selected && selected.has(value.key) === negated) continue;
if (!isBuiltInIssueStatus(value.key) && !catalog.entryOf(value.key)) continue;
counts.set(value.key, value.count);
}
@@ -361,9 +363,10 @@ export function useIssueStatusBranches({
statuses,
]);
+ const statusesNegated = query.filters.negate?.includes("statuses") ?? false;
const counts = useMemo(
- () => statusCountsFromFacets(facets, catalog, query.filters.statuses),
- [facets, catalog, query.filters.statuses],
+ () => statusCountsFromFacets(facets, catalog, query.filters.statuses, statusesNegated),
+ [facets, catalog, query.filters.statuses, statusesNegated],
);
const loadMore = useCallback(
(status: IssueStatus) => {
diff --git a/packages/views/issues/surface/use-issue-surface-catalog.test.tsx b/packages/views/issues/surface/use-issue-surface-catalog.test.tsx
index 7519895dc7..d1b5b2b15d 100644
--- a/packages/views/issues/surface/use-issue-surface-catalog.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-catalog.test.tsx
@@ -26,6 +26,10 @@ import { useIssueSurfaceController } from "./use-issue-surface-controller";
*/
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>
+ selector({ user: { id: "user-1" } }),
+}));
const QA_ENTRY: IssueStatusEntry = {
id: "s-qa",
diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
index 398c618f16..5c4dcaf4f6 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -62,6 +62,11 @@ vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
}));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>
+ selector({ user: { id: "user-1" } }),
+}));
+
vi.mock("@multica/core/issues/mutations", () => ({
useUpdateIssue: () => ({ mutate: updateIssueMutate, isPending: false }),
useBatchUpdateIssues: () => ({
@@ -280,6 +285,53 @@ describe("useIssueSurfaceController", () => {
);
});
+ it("sends relations and negated dimensions, and excludes negated status columns", async () => {
+ const store = getIssueSurfaceViewStore("workspace");
+ store.getState().toggleStatusFilter("done");
+ store.getState().setFilterNegated("status", true);
+ store.getState().toggleRelationFilter("assigned");
+ store.getState().toggleRelationFilter("my_agents");
+ // "Is not" with nothing selected never reaches the server.
+ store.getState().setFilterNegated("label", true);
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "workspace" },
+ modes: ["board", "list"],
+ }),
+ { wrapper: makeWrapper(qc, "workspace") },
+ );
+
+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalled());
+ expect(result.current.tableQuerySpec.filters).toMatchObject({
+ statuses: ["done"],
+ relations: ["assigned", "my_agents"],
+ negate: ["statuses"],
+ });
+ expect(result.current.visibleStatuses).not.toContain("done");
+ expect(result.current.visibleStatuses).toContain("todo");
+ });
+
+ it("ignores a persisted relation filter on a surface already scoped to me", async () => {
+ const store = getIssueSurfaceViewStore("my:user-1:assigned");
+ store.getState().toggleRelationFilter("created");
+ store.getState().setFilterNegated("relation", true);
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "my", relation: "assigned", userId: "user-1" },
+ modes: ["board", "list"],
+ }),
+ { wrapper: makeWrapper(qc, "my:user-1:assigned") },
+ );
+
+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalled());
+ expect(result.current.tableQuerySpec.filters.relations).toBeUndefined();
+ expect(result.current.tableQuerySpec.filters.negate).toBeUndefined();
+ });
+
// Off by default: an untouched surface sends no project-status key at all.
it("omits the project-status filter when nothing is selected", async () => {
const { result } = renderHook(
@@ -1330,6 +1382,61 @@ describe("useIssueSurfaceController", () => {
expect(result.current.columnStatuses).toContain("cancelled");
});
+ it("keeps an explicitly selected hidden status column after switching to advanced", async () => {
+ mockListByStatus({
+ cancelled: [makeIssue({ id: "cancelled-1", status: "cancelled" })],
+ });
+ const store = getIssueSurfaceViewStore("project:p1");
+ store.getState().toggleStatusFilter("cancelled");
+ const { result } = renderHook(
+ () => useIssueSurfaceController({
+ scope: { type: "project", projectId: "p1" },
+ modes: ["list"],
+ }),
+ { wrapper: makeWrapper(qc, "project:p1") },
+ );
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.visibleStatuses).toEqual(["cancelled"]);
+ expect(result.current.issues.map((issue) => issue.id)).toEqual(["cancelled-1"]);
+ act(() => store.getState().enterAdvancedFilter());
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.tableQuerySpec.filters.advanced).toEqual({
+ match: "all", children: [{ field: "statuses", values: ["cancelled"] }],
+ });
+ expect(result.current.visibleStatuses).toContain("cancelled");
+ expect(result.current.issues.map((issue) => issue.id)).toEqual(["cancelled-1"]);
+ });
+
+ it("keeps server branch totals for the statuses a negated filter leaves", async () => {
+ const store = getIssueSurfaceViewStore("workspace");
+ store.getState().toggleStatusFilter("done");
+ store.getState().setFilterNegated("status", true);
+ listIssueTableRows.mockImplementation(async (request) => ({
+ query_fingerprint: "review",
+ group_key: request.group_key,
+ parent_id: null,
+ total: 120,
+ branch_total: request.group_key === "status:todo" ? 120 : 0,
+ rows: request.group_key === "status:todo"
+ ? Array.from({ length: 50 }, (_, index) => ({
+ issue: makeIssue({ id: `todo-${index}`, status: "todo" }), direct_child_count: 0,
+ }))
+ : [],
+ next_cursor: request.group_key === "status:todo" ? "more" : null,
+ }));
+ listIssueTableFacets.mockResolvedValue({
+ query_fingerprint: "review", total: 120,
+ facets: [{ kind: "status", values: [{ key: "todo", count: 120 }, { key: "done", count: 10 }] }],
+ });
+ const { result } = renderHook(
+ () => useIssueSurfaceController({ scope: { type: "workspace" }, modes: ["list"] }),
+ { wrapper: makeWrapper(qc, "workspace") },
+ );
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.statusPagination?.todo.loaded).toBe(50);
+ expect(result.current.statusPagination?.todo.total).toBe(120);
+ });
+
it("treats a cancelled-only filter like any other narrowing status filter", async () => {
mockListByStatus({
todo: [makeIssue({ id: "todo-1", status: "todo" })],
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index 5a70142552..7c35ad5bb3 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -9,6 +9,7 @@ import type {
IssueTableFacetSpec,
IssueTableFacetsResponse,
IssueTableGroupsRequest,
+ IssueTableNegatableFilter,
IssueTableQuerySpec,
Project,
WorkingAgentSummary,
@@ -18,7 +19,15 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useColumnWorkflow, workflowColumns } from "../utils/workflow-columns";
import { statusFilterColumns, visibleStatusKeys } from "@multica/core/issues";
-import { dateOnlyToLocalDate } from "@multica/core/issues/date";
+import { dateOnlyToLocalDate, todayDateOnly } from "@multica/core/issues/date";
+import {
+ advancedFilterToTableQuery,
+ advancedFilterUsesField,
+ FILTER_DIMENSION_TABLE_FIELD,
+ statusColumnFilter,
+ propertyIdOfField,
+ withoutAdvancedFilterConditions,
+} from "@multica/core/issues/stores/filter-tree";
import type { IssueSortParam } from "@multica/core/issues/queries";
import { issueTableFacetsOptions } from "@multica/core/issues/queries";
import {
@@ -29,11 +38,21 @@ import {
assigneeTypesForActorKind,
type IssueScope,
} from "@multica/core/issues/surface/scope";
-import type { IssueDateFilter, SortField } from "@multica/core/issues/stores/view-store";
+import type {
+ IssueDateFilter,
+ NegatableFilterDimension,
+ SortField,
+} from "@multica/core/issues/stores/view-store";
import { propertyListOptions } from "@multica/core/properties";
-import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
+import {
+ effectiveNegatedFilters,
+ propertyIdFromViewKey,
+} from "@multica/core/issues/stores/view-store";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
-import type { IssueFilters } from "../utils/filter";
+import { useAuthStore } from "@multica/core/auth";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import { useShallow } from "zustand/react/shallow";
+import type { IssueFilters, IssueRelationContext } from "../utils/filter";
import type { ChildProgress } from "../components/list-row";
import { IssueTableExportIntegrityError } from "../components/table-view-model";
import type { IssueSurfaceMode } from "./types";
@@ -182,6 +201,9 @@ function useDebouncedTableSearch(value: string, delayMs = 250) {
* and the branch query list once per render (MUL-5477). */
const EMPTY_LIST: never[] = [];
+const TABLE_NEGATE_FIELD: Record<NegatableFilterDimension, IssueTableNegatableFilter> =
+ FILTER_DIMENSION_TABLE_FIELD;
+
/**
* Pin a derived value's identity to its CONTENT.
*
@@ -231,6 +253,10 @@ export function useIssueSurfaceController({
const includeNoProject = useViewStore((s) => s.includeNoProject);
const projectStatusFilters = useViewStore((s) => s.projectStatusFilters);
const labelFilters = useViewStore((s) => s.labelFilters);
+ const storedRelationFilters = useViewStore((s) => s.relationFilters);
+ const dueDateFilters = useViewStore((s) => s.dueDateFilters);
+ const storedAdvancedFilter = useViewStore((s) => s.advancedFilter);
+ const negatedFilters = useViewStore(useShallow(effectiveNegatedFilters));
const propertyFilters = useViewStore((s) => s.propertyFilters);
const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);
const showSubIssues = useViewStore((s) => s.showSubIssues);
@@ -242,8 +268,68 @@ export function useIssueSurfaceController({
const listCollapsedStatuses = useViewStore((s) => s.listCollapsedStatuses);
const hiddenStatusKeys = useViewStore((s) => s.hiddenStatuses);
const catalog = useIssueStatuses(wsId);
- const { workflow: projectWorkflow } = useColumnWorkflow(wsId, projectId, statusFilters.length > 0);
+ const statusNegated = negatedFilters.includes("status");
const [tableSearch, setTableSearch] = useState("");
+ // A "my issues" surface already scopes by relation; the menu hides the
+ // dimension there, and a persisted value must not silently narrow it.
+ const relationFilters = scope.type === "my" ? EMPTY_LIST : storedRelationFilters;
+ // Active property catalog. Persisted view state can outlive definitions
+ // (archive/delete): filters keyed by a non-active definition are stripped
+ // before they reach the predicates, and a sort on a non-active definition
+ // degrades to manual order — matching what the header already shows.
+ const { data: workspaceProperties = EMPTY_LIST, isSuccess: catalogSettled } = useQuery(propertyListOptions(wsId));
+ const activePropertyIds = useMemo(
+ () => new Set(workspaceProperties.map((p) => p.id)),
+ [workspaceProperties],
+ );
+ // The same rule for the rule tree, and a project surface already fixes the
+ // project; conditions on a non-active property go like flat ones do.
+ // Pruned: empty rows the panel is still editing filter nothing.
+ const advancedFilter = useMemo(() => {
+ const fixed: readonly string[] = [
+ ...(scope.type === "my" ? ["relation"] : []),
+ ...(scope.type === "project" ? ["project"] : []),
+ ];
+ return withoutAdvancedFilterConditions(storedAdvancedFilter, (condition) => {
+ if (fixed.includes(condition.field)) return true;
+ const propertyId = propertyIdOfField(condition.field);
+ return propertyId !== null && catalogSettled && !activePropertyIds.has(propertyId);
+ });
+ }, [activePropertyIds, catalogSettled, scope.type, storedAdvancedFilter]);
+ // Columns follow a status the tree requires as they follow the simple one.
+ const columnStatus = useMemo(
+ () => statusColumnFilter(statusFilters, statusNegated, advancedFilter, hiddenStatusKeys),
+ [advancedFilter, hiddenStatusKeys, statusFilters, statusNegated],
+ );
+ const { workflow: projectWorkflow } = useColumnWorkflow(
+ wsId,
+ projectId,
+ columnStatus.statuses.length > 0 && !columnStatus.negated,
+ );
+ const advancedTableFilter = useMemo(
+ () => advancedFilterToTableQuery(advancedFilter),
+ [advancedFilter],
+ );
+ // Due-date buckets resolve against the viewer's calendar day. Sent only
+ // when a bucket is in play, so other queries keep one cache key across
+ // midnight.
+ const usesDueDates =
+ dueDateFilters.length > 0 || advancedFilterUsesField(advancedFilter, "dueDate");
+ const today = usesDueDates ? todayDateOnly() : undefined;
+ const userId = useAuthStore((s) => s.user?.id);
+ const { data: agents } = useQuery({
+ ...agentListOptions(wsId),
+ enabled: relationFilters.length > 0 || advancedFilterUsesField(advancedFilter, "relation"),
+ });
+ const relationContext = useMemo<IssueRelationContext | undefined>(() => {
+ if (!userId || !agents) return undefined;
+ return {
+ userId,
+ myAgentIds: new Set(
+ agents.filter((agent) => agent.owner_id === userId).map((agent) => agent.id),
+ ),
+ };
+ }, [agents, userId]);
const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);
const fallbackMode = modes[0] ?? "list";
@@ -266,15 +352,6 @@ export function useIssueSurfaceController({
() => issueDateFilterToApiParams(dateFilter),
[dateFilter],
);
- // Active property catalog. Persisted view state can outlive definitions
- // (archive/delete): filters keyed by a non-active definition are stripped
- // before they reach the predicates, and a sort on a non-active definition
- // degrades to manual order — matching what the header already shows.
- const { data: workspaceProperties = EMPTY_LIST, isSuccess: catalogSettled } = useQuery(propertyListOptions(wsId));
- const activePropertyIds = useMemo(
- () => new Set(workspaceProperties.map((p) => p.id)),
- [workspaceProperties],
- );
const effectivePropertyFilters = useMemo(() => {
// While the catalog is still loading (or errored), persisted filters are
// passed through UNCHANGED: treating a cold catalog as confirmed-empty
@@ -339,8 +416,12 @@ export function useIssueSurfaceController({
const usesServerFacets =
usesTable || usesServerStatusSurface || usesServerGroupSurface;
const statusColumnsForFilters = useMemo(
- () => statusFilterColumns(statusFilters, catalog),
- [catalog, statusFilters],
+ // Exclusion needs no category: it only removes the listed keys.
+ () =>
+ columnStatus.negated
+ ? ({ state: "resolved", columns: new Set<IssueStatus>() } as const)
+ : statusFilterColumns(columnStatus.statuses, catalog),
+ [catalog, columnStatus],
);
/**
* A custom-status filter cannot be routed until the catalog answers. While it
@@ -367,9 +448,10 @@ export function useIssueSurfaceController({
() => {
const visible = workflowColumns(
visibleStatusKeys(
- statusFilters,
- hiddenStatusKeys,
+ columnStatus.statuses,
+ columnStatus.hiddenStatuses,
catalog,
+ columnStatus.negated,
),
projectWorkflow,
);
@@ -379,10 +461,9 @@ export function useIssueSurfaceController({
},
[
effectiveViewMode,
- hiddenStatusKeys,
listCollapsedStatuses,
catalog,
- statusFilters,
+ columnStatus,
projectWorkflow,
],
);
@@ -412,6 +493,9 @@ export function useIssueSurfaceController({
viewIncludeNoProject ||
projectStatusFilters.length > 0 ||
labelFilters.length > 0 ||
+ relationFilters.length > 0 ||
+ dueDateFilters.length > 0 ||
+ advancedFilter !== null ||
Object.keys(effectivePropertyFilters).length > 0 ||
dateFilter != null ||
agentRunningFilter === true;
@@ -487,6 +571,17 @@ export function useIssueSurfaceController({
end: dateParams.date_end,
}
: undefined;
+ const negate = negatedFilters
+ .filter((dimension) =>
+ // A project surface drops the project dimension; and on a "my"
+ // surface the relation dimension (see `relationFilters`).
+ dimension === "project"
+ ? viewProjectFilters.length > 0 || viewIncludeNoProject
+ : dimension === "relation"
+ ? relationFilters.length > 0
+ : true,
+ )
+ .map((dimension) => TABLE_NEGATE_FIELD[dimension]);
return {
scope: queryScope,
filters: {
@@ -503,6 +598,11 @@ export function useIssueSurfaceController({
? { project_statuses: projectStatusFilters }
: {}),
...(labelFilters.length > 0 ? { label_ids: labelFilters } : {}),
+ ...(relationFilters.length > 0 ? { relations: relationFilters } : {}),
+ ...(dueDateFilters.length > 0 ? { due_dates: dueDateFilters } : {}),
+ ...(today ? { today } : {}),
+ ...(negate.length > 0 ? { negate } : {}),
+ ...(advancedTableFilter ? { advanced: advancedTableFilter } : {}),
...(Object.keys(effectivePropertyFilters).length > 0
? { properties: effectivePropertyFilters }
: {}),
@@ -521,21 +621,26 @@ export function useIssueSurfaceController({
},
};
}, [
+ advancedTableFilter,
agentRunningFilter,
assigneeFilters,
creatorFilters,
dateParams,
debouncedActiveSearch,
+ dueDateFilters,
effectivePropertyFilters,
includeNoAssignee,
labelFilters,
+ negatedFilters,
priorityFilters,
projectStatusFilters,
+ relationFilters,
scope,
showSubIssues,
sort.sort_by,
sort.sort_direction,
statusFilters,
+ today,
viewIncludeNoProject,
viewProjectFilters,
workingFilterUnresolved,
@@ -678,8 +783,13 @@ export function useIssueSurfaceController({
]);
const serverGroupQuery = useMemo<IssueTableQuerySpec>(() => {
if (effectiveViewMode !== "swimlane") return tableQuerySpec;
- const { statuses: _statuses, ...filters } = tableQuerySpec.filters;
- return { ...tableQuerySpec, filters };
+ // Status is the secondary axis here: its columns already apply it.
+ const { statuses: _statuses, negate, ...filters } = tableQuerySpec.filters;
+ const otherNegate = negate?.filter((field) => field !== "statuses") ?? [];
+ return {
+ ...tableQuerySpec,
+ filters: { ...filters, ...(otherNegate.length > 0 ? { negate: otherNegate } : {}) },
+ };
}, [effectiveViewMode, tableQuerySpec]);
const serverGroupBranches = useIssueGroupBranches({
wsId,
@@ -713,6 +823,11 @@ export function useIssueSurfaceController({
viewIncludeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters,
+ dueDateFilters,
+ advancedTableFilter,
+ today,
+ negatedFilters,
effectivePropertyFilters,
agentRunningFilter,
showSubIssues,
@@ -720,18 +835,23 @@ export function useIssueSurfaceController({
debouncedActiveSearch,
]),
[
+ advancedTableFilter,
agentRunningFilter,
assigneeFilters,
creatorFilters,
dateParams,
debouncedActiveSearch,
+ dueDateFilters,
effectivePropertyFilters,
includeNoAssignee,
labelFilters,
+ negatedFilters,
priorityFilters,
projectStatusFilters,
+ relationFilters,
showSubIssues,
statusFilters,
+ today,
viewIncludeNoProject,
viewProjectFilters,
],
@@ -763,6 +883,12 @@ export function useIssueSurfaceController({
includeNoProject: viewIncludeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters,
+ relationContext,
+ dueDateFilters,
+ advancedFilter,
+ today,
+ negatedFilters,
propertyFilters: effectivePropertyFilters,
workingIssueIDs,
showSubIssues,
@@ -771,6 +897,7 @@ export function useIssueSurfaceController({
// cannot be evaluated without the catalog, so the filter itself has to
// pull it in.
projectStatusFilters.length > 0 ||
+ advancedFilterUsesField(advancedFilter, "projectStatus") ||
cardProperties.project ||
(usesTable && tableColumns.some((column) => column.key === "project")) ||
// Project group headers resolve their title through the projects query,
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index 9d4af2493e..3b2b5caff4 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -9,12 +9,23 @@ import { issueSurfaceGanttOptions } from "@multica/core/issues/surface/repositor
import type { IssueSurfaceQueryPlan } from "@multica/core/issues/surface/query-plan";
import type { IssueStatus, ProjectStatus, PropertyFilterValue } from "@multica/core/types";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import {
+ advancedFilterUsesField,
+ statusColumnFilter,
+ type AdvancedFilterGroup,
+ type DueDateFilter,
+} from "@multica/core/issues/stores/filter-tree";
import { useColumnWorkflow, workflowColumns } from "../utils/workflow-columns";
import { issueBehavesAsAny, statusColumnKeys, visibleStatusKeys } from "@multica/core/issues";
+import type {
+ IssueRelationFilter,
+ NegatableFilterDimension,
+} from "@multica/core/issues/stores/view-store";
import {
applyIssueFilters,
type IssueFilterState,
type IssueFilters,
+ type IssueRelationContext,
} from "../utils/filter";
import type { ChildProgress } from "../components/list-row";
import type {
@@ -116,6 +127,12 @@ export function useIssueSurfaceData({
includeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters,
+ relationContext,
+ dueDateFilters,
+ advancedFilter,
+ today,
+ negatedFilters,
propertyFilters,
workingIssueIDs,
showSubIssues,
@@ -146,6 +163,15 @@ export function useIssueSurfaceData({
includeNoProject: boolean;
projectStatusFilters: ProjectStatus[];
labelFilters: string[];
+ relationFilters: IssueRelationFilter[];
+ relationContext: IssueRelationContext | undefined;
+ dueDateFilters: DueDateFilter[];
+ /** The scoped, pruned rule tree. */
+ advancedFilter: AdvancedFilterGroup | null;
+ /** Set when due-date buckets are in play. */
+ today: string | undefined;
+ /** Negations that change the result (`effectiveNegatedFilters`). */
+ negatedFilters: NegatableFilterDimension[];
propertyFilters: Record<string, PropertyFilterValue[]>;
/** Distinct running-task issue ids projected by `/api/working-agents`. */
workingIssueIDs: ReadonlySet<string>;
@@ -191,15 +217,15 @@ export function useIssueSurfaceData({
// `statusFilterError` give a custom status filter. Table and the
// server-status branches filter server-side and never read the catalog.
const usesClientProjectStatusFilter =
- projectStatusFilters.length > 0 &&
+ (projectStatusFilters.length > 0 || advancedFilterUsesField(advancedFilter, "projectStatus")) &&
!usesTable &&
(usesGantt || !serverStatusBranches.enabled);
const projectCatalogPending = usesClientProjectStatusFilter && projectsPending;
const projectCatalogError = usesClientProjectStatusFilter && projectsError;
const workingFilterContext = useMemo(
- () => ({ runningIssueIds: workingIssueIDs, projectStatusById }),
- [projectStatusById, workingIssueIDs],
+ () => ({ runningIssueIds: workingIssueIDs, projectStatusById, relation: relationContext, today }),
+ [projectStatusById, relationContext, today, workingIssueIDs],
);
const bucketedIssues = serverStatusBranches.enabled
? serverStatusBranches.issues
@@ -229,21 +255,29 @@ export function useIssueSurfaceData({
includeNoProject,
projectStatusFilters,
labelFilters,
+ relationFilters,
+ dueDateFilters,
+ advancedFilter,
+ negatedFilters,
propertyFilters,
workingOnly: agentRunningFilter,
showSubIssues,
}),
[
+ advancedFilter,
assigneeFilters,
agentRunningFilter,
creatorFilters,
+ dueDateFilters,
includeNoAssignee,
includeNoProject,
labelFilters,
+ negatedFilters,
priorityFilters,
projectFilters,
projectStatusFilters,
propertyFilters,
+ relationFilters,
showSubIssues,
statusFilters,
],
@@ -373,20 +407,30 @@ export function useIssueSurfaceData({
const catalog = useIssueStatuses(wsId);
// Columns follow the project's workflow, or Default outside a project.
// (MUL-7420)
- const { workflow: projectWorkflow } = useColumnWorkflow(wsId, projectId, statusFilters.length > 0);
+ const statusNegated = negatedFilters.includes("status");
+ const columnStatus = useMemo(
+ () => statusColumnFilter(statusFilters, statusNegated, advancedFilter, hiddenStatusKeys),
+ [advancedFilter, hiddenStatusKeys, statusFilters, statusNegated],
+ );
+ const { workflow: projectWorkflow } = useColumnWorkflow(
+ wsId,
+ projectId,
+ columnStatus.statuses.length > 0 && !columnStatus.negated,
+ );
const { workflow: scopeWorkflow } = useColumnWorkflow(wsId, projectId, false);
const visibleStatuses = useMemo<IssueStatus[]>(() => {
// An explicit exact-key filter wins over hidden column preferences.
return workflowColumns(
visibleStatusKeys(
- statusFilters,
- hiddenStatusKeys,
+ columnStatus.statuses,
+ columnStatus.hiddenStatuses,
catalog,
+ columnStatus.negated,
),
projectWorkflow,
);
- }, [statusFilters, hiddenStatusKeys, catalog, projectWorkflow]);
+ }, [columnStatus, catalog, projectWorkflow]);
// The columns Display can show or hide: this surface's workflow steps, or
// the whole catalog without a workflow. A status filter does not change
@@ -409,22 +453,34 @@ export function useIssueSurfaceData({
projectStatusFilters,
projectStatusById,
labelFilters,
+ relationFilters,
+ relationContext,
+ dueDateFilters,
+ advancedFilter,
+ today,
+ negatedFilters,
propertyFilters,
showSubIssues,
}),
[
+ advancedFilter,
assigneeFilters,
agentRunningFilter,
creatorFilters,
+ dueDateFilters,
includeNoAssignee,
includeNoProject,
labelFilters,
+ negatedFilters,
propertyFilters,
priorityFilters,
projectFilters,
projectStatusById,
projectStatusFilters,
+ relationContext,
+ relationFilters,
showSubIssues,
+ today,
workingIssueIDs,
],
);
diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.ts
index f32a03344e..10f623d360 100644
--- a/packages/views/issues/utils/filter.test.ts
+++ b/packages/views/issues/utils/filter.test.ts
@@ -10,6 +10,7 @@ import {
type IssueFilters,
type IssueFilterState,
} from "./filter";
+import { createFilterCondition, createFilterGroup } from "@multica/core/issues/stores/filter-tree";
const NO_FILTER: IssueFilters = {
statusFilters: [],
@@ -714,3 +715,175 @@ describe("scalar operator filters", () => {
expect(result.map((i) => i.id)).toEqual(["B"]);
});
});
+
+describe("negated filters", () => {
+ const ids = (filters: Partial<IssueFilters>) =>
+ filterIssues(issues, { ...NO_FILTER, ...filters }).map((i) => i.id);
+
+ it("status is not done", () => {
+ expect(ids({ statusFilters: ["done"], negatedFilters: ["status"] })).toEqual(["1", "2", "4"]);
+ });
+
+ it("assignee is not a member keeps unassigned issues, like the server", () => {
+ expect(
+ ids({ assigneeFilters: [{ type: "member", id: "u-1" }], negatedFilters: ["assignee"] }),
+ ).toEqual(["2", "3", "4"]);
+ });
+
+ it("assignee is not 'No assignee' keeps every assigned issue", () => {
+ expect(ids({ includeNoAssignee: true, negatedFilters: ["assignee"] })).toEqual(["1", "2", "4"]);
+ });
+
+ it("project is not p-1 keeps projectless issues", () => {
+ expect(ids({ projectFilters: ["p-1"], negatedFilters: ["project"] })).toEqual(["2", "3"]);
+ });
+
+ it("label is not keeps unlabeled issues", () => {
+ const labeled = makeIssue({ id: "L", labels: [{ id: "bug", name: "Bug", color: "#f00" }] as Issue["labels"] });
+ const plain = makeIssue({ id: "P" });
+ const result = filterIssues([labeled, plain], {
+ ...NO_FILTER,
+ labelFilters: ["bug"],
+ negatedFilters: ["label"],
+ });
+ expect(result.map((i) => i.id)).toEqual(["P"]);
+ });
+
+ it("negation is per dimension and ANDs with the others", () => {
+ expect(
+ ids({ statusFilters: ["done"], priorityFilters: ["high"], negatedFilters: ["status"] }),
+ ).toEqual(["1"]);
+ });
+
+ it("a negated dimension without values filters nothing", () => {
+ expect(ids({ negatedFilters: ["status", "label"] })).toEqual(["1", "2", "3", "4"]);
+ });
+});
+
+describe("relation filters", () => {
+ const relationContext = { userId: "u-1", myAgentIds: new Set(["a-1"]) };
+ const ids = (filters: Partial<IssueFilters>) =>
+ filterIssues(issues, { ...NO_FILTER, relationContext, ...filters }).map((i) => i.id);
+
+ it("ORs the selected relations", () => {
+ expect(ids({ relationFilters: ["assigned"] })).toEqual(["1"]);
+ expect(ids({ relationFilters: ["my_agents"] })).toEqual(["2"]);
+ expect(ids({ relationFilters: ["assigned", "my_agents"] })).toEqual(["1", "2"]);
+ // Issue 2 was created by agent a-1, not by the member u-1.
+ expect(ids({ relationFilters: ["created"] })).toEqual(["1", "4"]);
+ });
+
+ it("can be negated", () => {
+ expect(ids({ relationFilters: ["created"], negatedFilters: ["relation"] })).toEqual(["2", "3"]);
+ });
+
+ it("is a no-op until the viewer is known", () => {
+ expect(
+ filterIssues(issues, { ...NO_FILTER, relationFilters: ["assigned"] }).map((i) => i.id),
+ ).toEqual(["1", "2", "3", "4"]);
+ });
+});
+
+describe("due date filters", () => {
+ const today = "2026-03-11";
+ const dated = [
+ makeIssue({ id: "late", due_date: "2026-03-10" }),
+ makeIssue({ id: "now", due_date: "2026-03-11" }),
+ makeIssue({ id: "sunday", due_date: "2026-03-15" }),
+ makeIssue({ id: "later", due_date: "2026-03-30" }),
+ makeIssue({ id: "undated", due_date: null }),
+ ];
+ const ids = (filters: Partial<IssueFilters>) =>
+ filterIssues(dated, { ...NO_FILTER, today, ...filters }).map((i) => i.id);
+
+ it("ORs the buckets", () => {
+ expect(ids({ dueDateFilters: ["overdue"] })).toEqual(["late"]);
+ expect(ids({ dueDateFilters: ["this_week"] })).toEqual(["late", "now", "sunday"]);
+ expect(ids({ dueDateFilters: ["today", "none"] })).toEqual(["now", "undated"]);
+ });
+
+ it("keeps undated issues under 'is not'", () => {
+ expect(ids({ dueDateFilters: ["overdue"], negatedFilters: ["dueDate"] })).toEqual([
+ "now", "sunday", "later", "undated",
+ ]);
+ });
+});
+
+describe("advanced filter", () => {
+ const ids = (advancedFilter: ReturnType<typeof createFilterGroup>, context: Partial<IssueFilters> = {}) =>
+ filterIssues(issues, { ...NO_FILTER, advancedFilter, ...context }).map((i) => i.id);
+
+ it("ORs across fields inside an any group", () => {
+ const tree = createFilterGroup("all", [
+ createFilterCondition("project", ["p-1", "none"]),
+ createFilterGroup("any", [
+ createFilterCondition("priority", ["urgent"]),
+ createFilterCondition("status", ["done"]),
+ ]),
+ ]);
+ expect(ids(tree)).toEqual(["3", "4"]);
+ });
+
+ it("negates one condition and keeps empty values", () => {
+ expect(ids(createFilterGroup("all", [createFilterCondition("assignee", ["member:u-1"], true)]))).toEqual([
+ "2", "3", "4",
+ ]);
+ expect(ids(createFilterGroup("all", [createFilterCondition("assignee", ["none"])]))).toEqual(["3"]);
+ });
+
+ it("drops empty and unanswerable conditions instead of matching everything", () => {
+ const tree = createFilterGroup("any", [
+ createFilterCondition("status", ["in_progress"]),
+ createFilterCondition("label"),
+ // No viewer context on this surface: the relation cannot be answered.
+ createFilterCondition("relation", ["assigned"]),
+ ]);
+ expect(ids(tree)).toEqual(["2"]);
+ expect(ids(createFilterGroup("any", [createFilterCondition("label")]))).toEqual(["1", "2", "3", "4"]);
+ });
+
+ it("evaluates relations once the viewer is known", () => {
+ const tree = createFilterGroup("any", [
+ createFilterCondition("relation", ["my_agents"]),
+ createFilterCondition("creator", ["member:u-2"]),
+ ]);
+ expect(ids(tree, { relationContext: { userId: "u-1", myAgentIds: new Set(["a-1"]) } })).toEqual(["2", "3"]);
+ });
+
+ it("is ANDed with the simple filters", () => {
+ const tree = createFilterGroup("all", [createFilterCondition("project", ["p-1"])]);
+ expect(ids(tree, { priorityFilters: ["high"] })).toEqual(["1"]);
+ });
+
+ it("tests custom properties like any other field", () => {
+ const estimate = "prop-estimate";
+ const small = makeIssue({ id: "S", priority: "low", properties: { [estimate]: 1 } });
+ const big = makeIssue({ id: "B", priority: "low", properties: { [estimate]: 8 } });
+ const unset = makeIssue({ id: "U", priority: "urgent" });
+ const run = (tree: ReturnType<typeof createFilterGroup>) =>
+ filterIssues([small, big, unset], { ...NO_FILTER, advancedFilter: tree }).map((i) => i.id);
+ const field = `property:${estimate}` as const;
+
+ expect(run(createFilterGroup("all", [createFilterCondition(field, [{ op: "gte", value: "5" }])]))).toEqual(["B"]);
+ // "Is not" keeps issues without a value, like the simple dimensions.
+ expect(run(createFilterGroup("all", [createFilterCondition(field, [{ op: "gte", value: "5" }], true)]))).toEqual([
+ "S", "U",
+ ]);
+ expect(
+ run(
+ createFilterGroup("any", [
+ createFilterCondition(field, [NO_PROPERTY_VALUE]),
+ createFilterCondition(field, [{ op: "lte", value: "1" }]),
+ ]),
+ ),
+ ).toEqual(["S", "U"]);
+ expect(
+ run(
+ createFilterGroup("any", [
+ createFilterCondition(field, [{ op: "gte", value: "5" }]),
+ createFilterCondition("priority", ["urgent"]),
+ ]),
+ ),
+ ).toEqual(["B", "U"]);
+ });
+});
diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.ts
index 7494822d00..33fd1069bb 100644
--- a/packages/views/issues/utils/filter.ts
+++ b/packages/views/issues/utils/filter.ts
@@ -1,5 +1,20 @@
import type { Issue, IssueStatus, IssuePriority, IssueAssigneeGroup, ProjectStatus, PropertyFilterValue, PropertyOperatorFilter } from "@multica/core/types";
-import type { ActorFilterValue } from "@multica/core/issues/stores/view-store";
+import type {
+ ActorFilterValue,
+ IssueRelationFilter,
+ NegatableFilterDimension,
+} from "@multica/core/issues/stores/view-store";
+import {
+ dueDateMatches,
+ FILTER_NONE_VALUE,
+ isPropertyCondition,
+ propertyIdOfField,
+ type AdvancedFilterCondition,
+ type AdvancedFilterGroup,
+ type DueDateFilter,
+} from "@multica/core/issues/stores/filter-tree";
+import { PROPERTY_FILTER_NONE_VALUE } from "@multica/core/issues/stores/filter-operators";
+import { todayDateOnly } from "@multica/core/issues/date";
import type { IssueActivityState } from "../surface/activity";
export interface IssueFilters {
@@ -23,6 +38,14 @@ export interface IssueFilters {
* project-status predicate, like `runningIssueIds` does for working-only. */
projectStatusById?: ReadonlyMap<string, ProjectStatus>;
labelFilters: string[];
+ relationFilters?: IssueRelationFilter[];
+ /** See IssueFilterContext.relation. */
+ relationContext?: IssueRelationContext;
+ dueDateFilters?: DueDateFilter[];
+ /** See IssueFilterContext.today. */
+ today?: string;
+ advancedFilter?: AdvancedFilterGroup | null;
+ negatedFilters?: readonly NegatableFilterDimension[];
/** Custom-property filters: definition id → selected values (OR within
* a definition, AND across definitions; checkbox uses "true"/"false"). */
propertyFilters?: Record<string, PropertyFilterValue[]>;
@@ -51,6 +74,12 @@ export interface IssueFilterState {
/** See IssueFilters.projectStatusFilters. */
projectStatusFilters?: ProjectStatus[];
labelFilters: string[];
+ relationFilters?: IssueRelationFilter[];
+ dueDateFilters?: DueDateFilter[];
+ /** A rule tree ANDed with everything else. */
+ advancedFilter?: AdvancedFilterGroup | null;
+ /** Dimensions evaluated as "is not". */
+ negatedFilters?: readonly NegatableFilterDimension[];
propertyFilters?: Record<string, PropertyFilterValue[]>;
workingOnly: boolean;
/** See IssueFilters.showSubIssues — only an explicit `false` hides. */
@@ -64,6 +93,18 @@ export interface IssueFilterContext {
* Absent on surfaces that never load it, which makes the project-status
* filter a no-op there rather than blanking the surface. */
projectStatusById?: ReadonlyMap<string, ProjectStatus>;
+ /** Who "me" is for the relation filter. Absent until the viewer and their
+ * agents are known, which makes that filter a no-op. */
+ relation?: IssueRelationContext;
+ /** The viewer's calendar day ("YYYY-MM-DD") due-date buckets resolve
+ * against; defaults to the local today. */
+ today?: string;
+}
+
+export interface IssueRelationContext {
+ userId: string;
+ /** Agents the viewer owns. */
+ myAgentIds: ReadonlySet<string>;
}
/**
@@ -72,7 +113,7 @@ export interface IssueFilterContext {
* (`server/internal/handler/property.go`); cannot collide with a real option id
* (select options are UUIDs, checkbox uses "true"/"false").
*/
-export const NO_PROPERTY_VALUE = "__none__";
+export const NO_PROPERTY_VALUE = PROPERTY_FILTER_NONE_VALUE;
/**
* Match one stored value against one operator filter member. Mirrors the
@@ -218,78 +259,209 @@ export function applyIssueFilters(
const applyWorkingOnly = workingOnly === true;
const hideSubIssues = filters.showSubIssues === false;
+ const relationFilters = filters.relationFilters ?? [];
+ // Same rule as the project-status catalog: no viewer, no answer, no filter.
+ const relationContext = context.relation;
+ const hasRelationFilter = relationFilters.length > 0 && relationContext !== undefined;
+ const dueDateFilters = filters.dueDateFilters ?? [];
+ const today = context.today ?? todayDateOnly();
+ const advancedFilter = filters.advancedFilter ?? null;
+ const negated = new Set(filters.negatedFilters ?? []);
+ // "Is not" keeps exactly what "is" drops, so an issue with no value for the
+ // dimension (unassigned, no project, no labels) survives a negated filter.
+ const passes = (dimension: NegatableFilterDimension, matched: boolean) =>
+ negated.has(dimension) ? !matched : matched;
+
return issues.filter((issue) => {
if (applyWorkingOnly && !issueIsWorking(issue.id, context))
return false;
if (hideSubIssues && issue.parent_issue_id) return false;
- if (statusFilters.length > 0 && !statusFilters.includes(issue.status))
+ if (statusFilters.length > 0 && !passes("status", statusFilters.includes(issue.status)))
return false;
- if (priorityFilters.length > 0 && !priorityFilters.includes(issue.priority))
+ if (
+ priorityFilters.length > 0 &&
+ !passes("priority", priorityFilters.includes(issue.priority))
+ )
return false;
if (hasAssigneeFilter) {
- if (!issue.assignee_id) {
- // Unassigned issue — show only if "No assignee" is checked
- if (!includeNoAssignee) return false;
- } else if (assigneeFilters.length > 0) {
- // Assigned issue — show only if assignee is in the filter list
- if (!assigneeFilters.some(
- (f) => f.type === issue.assignee_type && f.id === issue.assignee_id,
- )) return false;
- } else {
- // Only "No assignee" is checked, no specific assignees → hide assigned issues
- return false;
- }
+ // Unassigned matches only "No assignee"; assigned matches only a listed
+ // actor (an active filter with neither matches nothing).
+ const matched = !issue.assignee_id
+ ? includeNoAssignee
+ : assigneeFilters.some(
+ (f) => f.type === issue.assignee_type && f.id === issue.assignee_id,
+ );
+ if (!passes("assignee", matched)) return false;
}
if (
creatorFilters.length > 0 &&
- !creatorFilters.some(
- (f) => f.type === issue.creator_type && f.id === issue.creator_id,
+ !passes(
+ "creator",
+ creatorFilters.some(
+ (f) => f.type === issue.creator_type && f.id === issue.creator_id,
+ ),
)
) {
return false;
}
if (hasProjectFilter) {
- if (!issue.project_id) {
- if (!includeNoProject) return false;
- } else if (projectFilters.length > 0) {
- if (!projectFilters.includes(issue.project_id)) return false;
- } else {
- // Only "No project" is checked → hide issues that have a project
- return false;
- }
+ const matched = !issue.project_id
+ ? includeNoProject
+ : projectFilters.includes(issue.project_id);
+ if (!passes("project", matched)) return false;
}
if (hasProjectStatusFilter) {
- // An issue with no project has no status to match, so it never
- // survives — same as the server's EXISTS predicate. `includeNoProject`
- // widens the project-id dimension only.
+ // An issue with no project has no status to match — same as the
+ // server's EXISTS predicate. `includeNoProject` widens the project-id
+ // dimension only.
const projectStatus = issue.project_id
? projectStatusCatalog.get(issue.project_id)
: undefined;
- if (!projectStatus || !projectStatusFilters.includes(projectStatus))
- return false;
+ const matched = !!projectStatus && projectStatusFilters.includes(projectStatus);
+ if (!passes("projectStatus", matched)) return false;
}
if (labelFilters.length > 0) {
// OR semantics within the filter: keep issues that carry any of the
// selected labels. Matches existing priority / project multi-select.
- const issueLabels = issue.labels;
- if (!issueLabels || issueLabels.length === 0) return false;
- if (!issueLabels.some((l) => labelFilters.includes(l.id))) return false;
+ const matched = (issue.labels ?? []).some((l) => labelFilters.includes(l.id));
+ if (!passes("label", matched)) return false;
}
+ if (hasRelationFilter) {
+ const matched = relationFilters.some((relation) =>
+ issueMatchesRelation(issue, relation, relationContext),
+ );
+ if (!passes("relation", matched)) return false;
+ }
+
+ if (dueDateFilters.length > 0) {
+ const matched = dueDateFilters.some((bucket) => dueDateMatches(issue.due_date, bucket, today));
+ if (!passes("dueDate", matched)) return false;
+ }
+
+ if (advancedFilter && issueMatchesFilterGroup(issue, advancedFilter, context, today) === false)
+ return false;
+
if (!issueMatchesPropertyFilters(issue, filters.propertyFilters)) return false;
return true;
});
}
+function issueMatchesRelation(
+ issue: Issue,
+ relation: IssueRelationFilter,
+ context: IssueRelationContext,
+): boolean {
+ switch (relation) {
+ case "assigned":
+ return issue.assignee_type === "member" && issue.assignee_id === context.userId;
+ case "created":
+ return issue.creator_type === "member" && issue.creator_id === context.userId;
+ case "my_agents":
+ return (
+ issue.assignee_type === "agent" &&
+ !!issue.assignee_id &&
+ context.myAgentIds.has(issue.assignee_id)
+ );
+ }
+}
+
+/**
+ * One rule-tree node against an issue, or undefined when the node cannot be
+ * answered: it is empty, or it needs a catalog the surface never loaded
+ * (project statuses, the viewer). An unanswerable member drops out of its
+ * group, mirroring the server dropping empty members.
+ */
+function issueMatchesFilterGroup(
+ issue: Issue,
+ group: AdvancedFilterGroup,
+ context: IssueFilterContext,
+ today: string,
+): boolean | undefined {
+ let answered = false;
+ for (const child of group.children) {
+ const matched =
+ child.type === "group"
+ ? issueMatchesFilterGroup(issue, child, context, today)
+ : issueMatchesFilterCondition(issue, child, context, today);
+ if (matched === undefined) continue;
+ answered = true;
+ if (group.match === "any" && matched) return true;
+ if (group.match === "all" && !matched) return false;
+ }
+ if (!answered) return undefined;
+ return group.match === "all";
+}
+
+function issueMatchesFilterCondition(
+ issue: Issue,
+ condition: AdvancedFilterCondition,
+ context: IssueFilterContext,
+ today: string,
+): boolean | undefined {
+ if (condition.values.length === 0) return undefined;
+ if (isPropertyCondition(condition)) {
+ const propertyId = propertyIdOfField(condition.field) ?? "";
+ const matched = issueMatchesPropertyFilters(issue, { [propertyId]: condition.values });
+ return condition.negated ? !matched : matched;
+ }
+ const { values } = condition;
+ const actorMatches = (type: string | null, id: string | null) =>
+ !!id && values.includes(`${type}:${id}`);
+ let matched: boolean;
+ switch (condition.field) {
+ case "status":
+ matched = values.includes(issue.status);
+ break;
+ case "priority":
+ matched = values.includes(issue.priority);
+ break;
+ case "assignee":
+ matched = issue.assignee_id
+ ? actorMatches(issue.assignee_type, issue.assignee_id)
+ : values.includes(FILTER_NONE_VALUE);
+ break;
+ case "creator":
+ matched = actorMatches(issue.creator_type, issue.creator_id);
+ break;
+ case "project":
+ matched = issue.project_id
+ ? values.includes(issue.project_id)
+ : values.includes(FILTER_NONE_VALUE);
+ break;
+ case "projectStatus": {
+ if (!context.projectStatusById) return undefined;
+ const status = issue.project_id ? context.projectStatusById.get(issue.project_id) : undefined;
+ matched = !!status && values.includes(status);
+ break;
+ }
+ case "label":
+ matched = (issue.labels ?? []).some((label) => values.includes(label.id));
+ break;
+ case "relation": {
+ const relation = context.relation;
+ if (!relation) return undefined;
+ matched = values.some((value) =>
+ issueMatchesRelation(issue, value as IssueRelationFilter, relation),
+ );
+ break;
+ }
+ case "dueDate":
+ matched = values.some((bucket) => dueDateMatches(issue.due_date, bucket as DueDateFilter, today));
+ break;
+ }
+ return condition.negated ? !matched : matched;
+}
+
export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {
return applyIssueFilters(
issues,
@@ -304,6 +476,10 @@ export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {
includeNoProject: filters.includeNoProject,
projectStatusFilters: filters.projectStatusFilters,
labelFilters: filters.labelFilters,
+ relationFilters: filters.relationFilters,
+ dueDateFilters: filters.dueDateFilters,
+ advancedFilter: filters.advancedFilter,
+ negatedFilters: filters.negatedFilters,
propertyFilters: filters.propertyFilters,
workingOnly: filters.agentRunningFilter === true,
showSubIssues: filters.showSubIssues,
@@ -311,6 +487,8 @@ export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {
{
runningIssueIds: filters.runningIssueIds,
projectStatusById: filters.projectStatusById,
+ relation: filters.relationContext,
+ today: filters.today,
},
);
}
diff --git a/packages/views/layout/account-menu.tsx b/packages/views/layout/account-menu.tsx
new file mode 100644
index 0000000000..7e5cb53794
--- /dev/null
+++ b/packages/views/layout/account-menu.tsx
@@ -0,0 +1,190 @@
+"use client";
+
+import {
+ ArrowUpRight,
+ BookOpen,
+ Download,
+ History,
+ Keyboard,
+ Globe,
+ LogOut,
+ Monitor,
+ Moon,
+ Palette,
+ Sun,
+ User,
+} from "@multica/ui/icons";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { SupportedLocale } from "@multica/core/i18n";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
+import { useTheme } from "@multica/ui/components/common/theme-provider";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
+import { useLogout } from "../auth";
+import { docsLocalePrefix } from "../common/docs-locale";
+import { useLanguageSwitch } from "../common/use-language-switch";
+import { useT } from "../i18n";
+import { AppLink } from "../navigation";
+import { isDesktopShell } from "../platform/local-directory";
+import { DISCORD_URL, DiscordIcon } from "./discord";
+import { CHANGELOG_URL, DOCS_URL, DOWNLOAD_URL } from "./help-links";
+import { RAIL_ICON_BUTTON_CLASS } from "./rail-styles";
+
+const THEMES = [
+ { value: "light", icon: Sun },
+ { value: "dark", icon: Moon },
+ { value: "system", icon: Monitor },
+] as const;
+
+function SubmenuLabel({ label, value }: { label: string; value?: string }) {
+ return (
+ <>
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {value && <span className="shrink-0 text-caption text-muted-foreground">{value}</span>}
+ </>
+ );
+}
+
+function ExternalItem({ href, icon, label }: { href: string; icon: React.ReactNode; label: string }) {
+ return (
+ <DropdownMenuItem render={<a href={href} target="_blank" rel="noopener noreferrer" />}>
+ {icon}
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ <ArrowUpRight className="size-3 text-faint-foreground" />
+ </DropdownMenuItem>
+ );
+}
+
+/** The signed-in user's menu at the foot of the rail. */
+export function AccountMenu() {
+ const { t, i18n } = useT("layout");
+ const user = useAuthStore((s) => s.user);
+ const p = useWorkspacePaths();
+ const logout = useLogout();
+ const { theme, setTheme } = useTheme();
+ const language = useLanguageSwitch();
+ const themeValue = (theme ?? "system") as (typeof THEMES)[number]["value"];
+ const name = user?.name ?? "";
+ const avatar = (size: "md" | "lg") => (
+ <ActorAvatar
+ name={name}
+ initials={(name || "U").charAt(0).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(user?.avatar_url)}
+ size={size}
+ />
+ );
+
+ return (
+ <DropdownMenu>
+ <TooltipHint label={t(($) => $.account.trigger)} side="right">
+ <DropdownMenuTrigger
+ aria-label={t(($) => $.account.trigger)}
+ className={cn(RAIL_ICON_BUTTON_CLASS, "rounded-full")}
+ >
+ {avatar("md")}
+ </DropdownMenuTrigger>
+ </TooltipHint>
+ <DropdownMenuContent side="right" align="end" sideOffset={8} className="w-64">
+ <div className="flex items-center gap-2.5 px-2 py-1.5">
+ {avatar("lg")}
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-body font-medium leading-tight">{user?.name}</p>
+ <p className="truncate text-caption leading-tight text-muted-foreground">
+ {user?.email}
+ </p>
+ </div>
+ </div>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem render={<AppLink href={`${p.settings()}?tab=profile`} />}>
+ <User />
+ {t(($) => $.account.profile)}
+ </DropdownMenuItem>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Palette />
+ <SubmenuLabel
+ label={t(($) => $.account.theme)}
+ value={t(($) => $.account.themes[themeValue])}
+ />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup value={themeValue} onValueChange={setTheme}>
+ {THEMES.map(({ value, icon: Icon }) => (
+ <DropdownMenuRadioItem key={value} value={value}>
+ <Icon />
+ {t(($) => $.account.themes[value])}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Globe />
+ <SubmenuLabel
+ label={t(($) => $.account.language)}
+ value={language.options.find((o) => o.value === language.currentLocale)?.label}
+ />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup
+ value={language.currentLocale}
+ onValueChange={(next) => void language.changeLanguage(next as SupportedLocale)}
+ >
+ {language.options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuItem render={<AppLink href={`${p.settings()}?tab=shortcuts`} />}>
+ <Keyboard />
+ {t(($) => $.account.shortcuts)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <ExternalItem
+ href={`${DOCS_URL}${docsLocalePrefix(i18n.language)}`}
+ icon={<BookOpen />}
+ label={t(($) => $.help.docs)}
+ />
+ <ExternalItem href={CHANGELOG_URL} icon={<History />} label={t(($) => $.help.changelog)} />
+ <ExternalItem href={DISCORD_URL} icon={<DiscordIcon />} label={t(($) => $.help.discord)} />
+ {!isDesktopShell() && (
+ <ExternalItem
+ href={DOWNLOAD_URL}
+ icon={<Download />}
+ label={t(($) => $.help.download_desktop)}
+ />
+ )}
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem variant="destructive" onClick={logout}>
+ <LogOut />
+ {t(($) => $.sidebar.log_out)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/layout/app-rail.test.tsx b/packages/views/layout/app-rail.test.tsx
new file mode 100644
index 0000000000..14006785fe
--- /dev/null
+++ b/packages/views/layout/app-rail.test.tsx
@@ -0,0 +1,269 @@
+import type { ReactNode } from "react";
+import { act, fireEvent, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
+import { renderWithI18n } from "../test/i18n";
+import { AppRail } from "./app-rail";
+import { AppShellProvider, useAppShell } from "./app-shell-context";
+
+const state = vi.hoisted(() => ({
+ pathname: "/acme/issues",
+ appForeground: true,
+ inboxUnread: 0,
+ chatSessions: [] as { id: string; unread_count?: number }[],
+ chat: { activeSessionId: null as string | null, isOpen: false },
+ stuck: [] as unknown[],
+ failingAutopilots: [] as unknown[],
+}));
+
+vi.mock("../navigation", () => ({
+ AppLink: ({
+ children,
+ href,
+ newTabTitle: _newTabTitle,
+ ...props
+ }: { children: ReactNode; href: string; newTabTitle?: string } & React.ComponentProps<"a">) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+ useNavigation: () => ({ pathname: state.pathname, push: vi.fn() }),
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return {
+ ...actual,
+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme", slug: "acme" }),
+ useWorkspacePaths: () => actual.paths.workspace("acme"),
+ };
+});
+vi.mock("@multica/core/inbox/queries", () => ({
+ useInboxUnreadCount: () => state.inboxUnread,
+}));
+vi.mock("@multica/core/chat/queries", () => ({
+ chatSessionsOptions: (wsId: string) => ({
+ queryKey: ["chat", wsId, "sessions"],
+ queryFn: async () => state.chatSessions,
+ }),
+}));
+// Callable-store shape (selectorFn + getState) per the repo testing rules.
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: Object.assign(
+ (selector: (s: typeof state.chat) => unknown) => selector(state.chat),
+ { getState: () => state.chat },
+ ),
+}));
+vi.mock("@multica/core/shortcuts", () => ({ useShortcut: () => null }));
+vi.mock("../common/use-app-foreground", () => ({
+ useAppForeground: () => state.appForeground,
+}));
+vi.mock("./panels/team-status", () => ({
+ useTeamAgentStatus: () => ({ stuck: state.stuck }),
+}));
+vi.mock("./panels/autopilots-panel", () => ({
+ useFailingAutopilots: () => state.failingAutopilots,
+}));
+vi.mock("./rail-workspaces", () => ({ RailWorkspaces: () => null }));
+vi.mock("./help-launcher", () => ({ HelpLauncher: () => null }));
+vi.mock("./account-menu", () => ({ AccountMenu: () => null }));
+vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
+ TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+function CollapseButton() {
+ const { setOpen } = useSidebar();
+ return (
+ <button type="button" onClick={() => setOpen(false)}>
+ collapse
+ </button>
+ );
+}
+
+function renderRail(children?: ReactNode, rail: ReactNode = <AppRail />) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ client.setQueryData(["chat", "ws-1", "sessions"], state.chatSessions);
+ return renderWithI18n(
+ <QueryClientProvider client={client}>
+ <SidebarProvider>
+ <AppShellProvider>
+ {rail}
+ <CollapseButton />
+ {children}
+ </AppShellProvider>
+ </SidebarProvider>
+ </QueryClientProvider>,
+ );
+}
+
+const link = (href: string) => document.querySelector<HTMLAnchorElement>(`a[href="${href}"]`);
+const countBadge = (href: string) => link(href)?.querySelector("number-flow-react") ?? null;
+
+beforeEach(() => {
+ state.pathname = "/acme/issues";
+ state.appForeground = true;
+ state.inboxUnread = 0;
+ state.chatSessions = [];
+ state.chat = { activeSessionId: null, isOpen: false };
+ state.stuck = [];
+ state.failingAutopilots = [];
+});
+
+describe("AppRail global actions", () => {
+ it("carries New issue and search by default", () => {
+ renderRail();
+ expect(screen.getByRole("button", { name: /^new issue$/i })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Search..." })).toBeTruthy();
+ });
+
+ it("leaves them to the desktop title bar when turned off", () => {
+ renderRail(undefined, <AppRail globalActions={false} />);
+ expect(screen.queryByRole("button", { name: /^new issue$/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Search..." })).toBeNull();
+ });
+});
+
+describe("AppRail spaces", () => {
+ it("links each space and marks the current route's space", () => {
+ state.pathname = "/acme/projects/p-1";
+ renderRail();
+
+ for (const href of ["/acme/inbox", "/acme/issues", "/acme/agents", "/acme/chat", "/acme/autopilots"]) {
+ expect(link(href)).not.toBeNull();
+ }
+ // Projects belong to the work space, which links to Issues.
+ expect(link("/acme/issues")).toHaveAttribute("aria-current", "page");
+ expect(link("/acme/agents")).not.toHaveAttribute("aria-current");
+ });
+
+ it("marks Settings in the footer while on a settings route", () => {
+ state.pathname = "/acme/settings";
+ renderRail();
+ expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("aria-current", "page");
+ });
+
+ it("lands Team on agents and keeps it lit across the team pages", () => {
+ state.pathname = "/acme/runtimes";
+ renderRail();
+ expect(link("/acme/agents")).toHaveAttribute("aria-current", "page");
+ });
+});
+
+describe("AppRail badges", () => {
+ it("counts inbox unread with a static counter", () => {
+ state.inboxUnread = 4;
+ renderRail();
+ const badge = countBadge("/acme/inbox") as (HTMLElement & { animated?: boolean }) | null;
+ expect(badge).toHaveAttribute("aria-label", "4");
+ expect(badge?.animated).toBe(false);
+ });
+
+ it("shows no attention dots when nothing needs a look", () => {
+ renderRail();
+ expect(link("/acme/agents")?.querySelector(".bg-warning")).toBeNull();
+ expect(link("/acme/autopilots")?.querySelector(".bg-destructive")).toBeNull();
+ });
+
+ it("flags Team when an agent is stuck and Autopilot when a run failed", () => {
+ state.stuck = [{ id: "agent-1" }];
+ state.failingAutopilots = [{ id: "ap-1" }];
+ renderRail();
+ expect(link("/acme/agents")?.querySelector(".bg-warning")).not.toBeNull();
+ expect(link("/acme/autopilots")?.querySelector(".bg-destructive")).not.toBeNull();
+ });
+});
+
+describe("AppRail chat badge", () => {
+ const chatBadge = () => countBadge("/acme/chat");
+
+ it("sums unread messages across sessions", () => {
+ state.chatSessions = [
+ { id: "a", unread_count: 3 },
+ { id: "b", unread_count: 2 },
+ { id: "c", unread_count: 0 },
+ ];
+ renderRail();
+ expect(chatBadge()).toHaveAttribute("aria-label", "5");
+ });
+
+ it("shows nothing when every session is read", () => {
+ state.chatSessions = [{ id: "a", unread_count: 0 }, { id: "b" }];
+ renderRail();
+ expect(chatBadge()).toBeNull();
+ });
+
+ // The thread list zeroes the open session's row; the aggregate must
+ // follow, or a reply landing there flashes a count with no matching row.
+ it("excludes the session being read on the chat route", () => {
+ state.chatSessions = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
+ state.pathname = "/acme/chat";
+ state.chat = { activeSessionId: "a", isOpen: false };
+ renderRail();
+ expect(chatBadge()).toHaveAttribute("aria-label", "3");
+ });
+
+ it("excludes the session open in the floating window off-route", () => {
+ state.chatSessions = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
+ state.chat = { activeSessionId: "a", isOpen: true };
+ renderRail();
+ expect(chatBadge()).toHaveAttribute("aria-label", "3");
+ });
+
+ it("still counts a remembered selection no chat surface is showing", () => {
+ state.chatSessions = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
+ state.chat = { activeSessionId: "a", isOpen: false };
+ renderRail();
+ expect(chatBadge()).toHaveAttribute("aria-label", "5");
+ });
+
+ // Backgrounded, auto mark-read is suppressed (MUL-4485): the reply stays
+ // unread and must badge, or the notification is eaten while away.
+ it("counts the open session while the app is backgrounded", () => {
+ state.chatSessions = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
+ state.pathname = "/acme/chat";
+ state.chat = { activeSessionId: "a", isOpen: true };
+ state.appForeground = false;
+ renderRail();
+ expect(chatBadge()).toHaveAttribute("aria-label", "5");
+ });
+});
+
+describe("AppRail panel peek", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function hover(href: string) {
+ fireEvent.pointerEnter(link(href)!, { pointerType: "mouse" });
+ }
+
+ it("asks the shell to preview any space only while the nav is collapsed", () => {
+ vi.useFakeTimers();
+ let peek: string | null = null;
+ renderRail(<PeekReader onPeek={(next) => (peek = next)} />);
+
+ hover("/acme/agents");
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(peek).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: "collapse" }));
+ hover("/acme/agents");
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(peek).toBe("team");
+
+ // Inbox and Chat keep their lists in their pages but still preview.
+ hover("/acme/inbox");
+ expect(peek).toBe("inbox");
+ });
+});
+
+function PeekReader({ onPeek }: { onPeek: (space: string | null) => void }) {
+ onPeek(useAppShell()?.peekSpace ?? null);
+ return null;
+}
diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsx
new file mode 100644
index 0000000000..5b9e1c20c7
--- /dev/null
+++ b/packages/views/layout/app-rail.tsx
@@ -0,0 +1,267 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Settings, Users, type IconComponent } from "@multica/ui/icons";
+import { useChatStore } from "@multica/core/chat";
+import { chatSessionsOptions } from "@multica/core/chat/queries";
+import { countUnreadChatMessages } from "@multica/core/chat/unread";
+import { useInboxUnreadCount } from "@multica/core/inbox/queries";
+import {
+ RAIL_SPACES,
+ useCurrentWorkspace,
+ useWorkspacePaths,
+ type AppSpaceId,
+ type RailSpaceId,
+} from "@multica/core/paths";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { CappedNumberFlow } from "@multica/ui/components/ui/number-flow";
+import { cn } from "@multica/ui/lib/utils";
+import { useAppForeground } from "../common/use-app-foreground";
+import { useT } from "../i18n";
+import { AppLink, useNavigation } from "../navigation";
+import { AccountMenu } from "./account-menu";
+import { useAppShell } from "./app-shell-context";
+import { NewIssueButton, SearchButton } from "./global-actions";
+import { HelpLauncher } from "./help-launcher";
+import { isPathWithin } from "./panel-nav";
+import { useFailingAutopilots } from "./panels/autopilots-panel";
+import { useTeamAgentStatus } from "./panels/team-status";
+import { RAIL_ICON_BUTTON_CLASS } from "./rail-styles";
+import { RailWorkspaces } from "./rail-workspaces";
+import { routeIconForPath } from "./route-icon-components";
+
+type RailBadge =
+ | { kind: "count"; value: number; tone: "brand" | "neutral" }
+ | { kind: "dot"; tone: "warning" | "destructive" };
+
+/**
+ * Rail badges. Inbox and Chat count unread; Team and Autopilots only flag
+ * that something needs a look — the panel says what.
+ */
+function useRailBadges(): Partial<Record<RailSpaceId, RailBadge>> {
+ const wsId = useCurrentWorkspace()?.id;
+ const p = useWorkspacePaths();
+ const { pathname } = useNavigation();
+ const inboxUnread = useInboxUnreadCount(wsId);
+
+ const { data: chatSessions = [] } = useQuery({
+ ...chatSessionsOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ // The session the user is reading right now must not count: its row shows 0
+ // (auto mark-read is about to clear it) and a reply landing there would
+ // flash a count with no matching row. "Reading" = a session is active, a
+ // chat surface shows it (the chat route or the floating window), and the
+ // app is in the foreground. Backgrounded, auto mark-read is suppressed
+ // (MUL-4485), so the reply stays unread and must count.
+ const activeChatSessionId = useChatStore((s) => s.activeSessionId);
+ const floatingChatOpen = useChatStore((s) => s.isOpen);
+ const appForeground = useAppForeground();
+ const viewedChatSessionId =
+ appForeground && (floatingChatOpen || isPathWithin(pathname, p.chat()))
+ ? activeChatSessionId
+ : null;
+ const chatUnread = useMemo(
+ () => countUnreadChatMessages(chatSessions, viewedChatSessionId),
+ [chatSessions, viewedChatSessionId],
+ );
+
+ const { stuck } = useTeamAgentStatus(wsId);
+ const failingAutopilots = useFailingAutopilots(wsId);
+
+ const badges: Partial<Record<RailSpaceId, RailBadge>> = {};
+ if (inboxUnread > 0) badges.inbox = { kind: "count", value: inboxUnread, tone: "brand" };
+ if (chatUnread > 0) badges.chat = { kind: "count", value: chatUnread, tone: "neutral" };
+ if (stuck.length > 0) badges.team = { kind: "dot", tone: "warning" };
+ if (failingAutopilots.length > 0) badges.autopilots = { kind: "dot", tone: "destructive" };
+ return badges;
+}
+
+function RailBadgeMark({ badge }: { badge: RailBadge }) {
+ // The ring cuts the badge out of whatever the item is painted with.
+ const ring = "ring-2 ring-app-shell group-aria-[current=page]:ring-sidebar-accent";
+ if (badge.kind === "dot") {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "absolute top-1.5 right-3.5 size-2 rounded-full",
+ ring,
+ badge.tone === "warning" ? "bg-warning" : "bg-destructive",
+ )}
+ />
+ );
+ }
+ return (
+ <CappedNumberFlow
+ value={badge.value}
+ animated={false}
+ className={cn(
+ "absolute top-0.5 right-1.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-none font-medium tabular-nums",
+ ring,
+ badge.tone === "brand" ? "bg-brand text-brand-foreground" : "bg-foreground text-background",
+ )}
+ />
+ );
+}
+
+/** Hover previews of a collapsed nav. Mouse only: a touch tap navigates. */
+function usePeekHandlers(space: AppSpaceId, peekable: boolean) {
+ const shell = useAppShell();
+ return {
+ onPointerEnter: (e: React.PointerEvent) => {
+ if (!shell || e.pointerType !== "mouse") return;
+ if (peekable && shell.navCollapsed) shell.requestPeek(space);
+ else if (shell.peekSpace) shell.releasePeek();
+ },
+ onPointerLeave: (e: React.PointerEvent) => {
+ if (shell && e.pointerType === "mouse") shell.releasePeek();
+ },
+ };
+}
+
+function RailSpaceLink({
+ space,
+ href,
+ icon: Icon,
+ label,
+ fullLabel,
+ active,
+ badge,
+}: {
+ space: RailSpaceId;
+ href: string;
+ icon: IconComponent;
+ label: string;
+ fullLabel: string;
+ active: boolean;
+ badge?: RailBadge;
+}) {
+ const peekHandlers = usePeekHandlers(space, true);
+ return (
+ <li>
+ <TooltipHint label={label === fullLabel ? null : fullLabel} side="right">
+ <AppLink
+ href={href}
+ data-space={space}
+ newTabTitle={fullLabel}
+ aria-current={active ? "page" : undefined}
+ {...peekHandlers}
+ className="group relative flex h-[52px] w-[52px] flex-col items-center justify-center gap-1 rounded-xl text-muted-foreground transition-colors outline-none hover:bg-sidebar-accent/60 hover:text-sidebar-accent-foreground focus-visible:outline-2 focus-visible:outline-ring aria-[current=page]:bg-sidebar-accent aria-[current=page]:font-medium aria-[current=page]:text-sidebar-accent-foreground"
+ >
+ <Icon className="size-5" />
+ <span className="max-w-full truncate px-1 text-micro leading-[14px]">{label}</span>
+ {badge && <RailBadgeMark badge={badge} />}
+ </AppLink>
+ </TooltipHint>
+ </li>
+ );
+}
+
+/**
+ * The app rail: workspaces, New issue and search, the five spaces, then help,
+ * settings and the account. It sits on the app shell, outside the content
+ * card, and stays put while the panel beside it collapses. Desktop passes
+ * `globalActions={false}`: its title bar carries New issue and search.
+ */
+export function AppRail({
+ topSlot,
+ globalActions = true,
+ className,
+}: {
+ topSlot?: React.ReactNode;
+ globalActions?: boolean;
+ className?: string;
+}) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const shell = useAppShell();
+ const badges = useRailBadges();
+ const space = shell?.space ?? null;
+ const settingsPeek = usePeekHandlers("settings", space === "settings");
+
+ const items: Record<RailSpaceId, { href: string; icon: IconComponent; label: string; fullLabel: string }> = {
+ inbox: {
+ href: p.inbox(),
+ icon: routeIconForPath(p.inbox()),
+ label: t(($) => $.rail.inbox),
+ fullLabel: t(($) => $.nav.inbox),
+ },
+ work: {
+ href: p.issues(),
+ icon: routeIconForPath(p.issues()),
+ label: t(($) => $.rail.work),
+ fullLabel: t(($) => $.spaces.work),
+ },
+ team: {
+ href: p.agents(),
+ icon: Users,
+ label: t(($) => $.rail.team),
+ fullLabel: t(($) => $.spaces.team),
+ },
+ chat: {
+ href: p.chat(),
+ icon: routeIconForPath(p.chat()),
+ label: t(($) => $.rail.chat),
+ fullLabel: t(($) => $.nav.chat),
+ },
+ autopilots: {
+ href: p.autopilots(),
+ icon: routeIconForPath(p.autopilots()),
+ label: t(($) => $.rail.autopilots),
+ fullLabel: t(($) => $.nav.autopilots),
+ },
+ };
+
+ return (
+ <nav
+ aria-label={t(($) => $.rail.label)}
+ data-slot="app-rail"
+ className={cn(
+ "flex h-full w-16 shrink-0 flex-col items-center overflow-y-auto overflow-x-hidden pt-3 pb-2.5 [scrollbar-width:none]",
+ className,
+ )}
+ >
+ {topSlot}
+ <RailWorkspaces />
+ {globalActions ? (
+ <div className="my-2 flex flex-col items-center gap-1">
+ <NewIssueButton className={RAIL_ICON_BUTTON_CLASS} tooltipSide="right" />
+ <SearchButton className={RAIL_ICON_BUTTON_CLASS} tooltipSide="right" />
+ </div>
+ ) : (
+ <div className="h-2 shrink-0" />
+ )}
+ <ul className="flex flex-col items-center gap-0.5">
+ {RAIL_SPACES.map((id) => (
+ <RailSpaceLink
+ key={id}
+ space={id}
+ {...items[id]}
+ href={shell?.spaceHref(id, items[id].href) ?? items[id].href}
+ active={space === id}
+ badge={badges[id]}
+ />
+ ))}
+ </ul>
+ <div className="mt-auto flex flex-col items-center gap-1 pt-2">
+ <HelpLauncher />
+ <TooltipHint label={t(($) => $.nav.settings)} side="right">
+ <AppLink
+ href={shell?.spaceHref("settings", p.settings()) ?? p.settings()}
+ aria-label={t(($) => $.nav.settings)}
+ aria-current={space === "settings" ? "page" : undefined}
+ // Settings has no standalone preview; it only floats its own
+ // list column while open.
+ {...settingsPeek}
+ className={RAIL_ICON_BUTTON_CLASS}
+ >
+ <Settings />
+ </AppLink>
+ </TooltipHint>
+ <AccountMenu />
+ </div>
+ </nav>
+ );
+}
diff --git a/packages/views/layout/app-shell-context.test.tsx b/packages/views/layout/app-shell-context.test.tsx
new file mode 100644
index 0000000000..37352244bf
--- /dev/null
+++ b/packages/views/layout/app-shell-context.test.tsx
@@ -0,0 +1,214 @@
+import { act, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
+import {
+ AppShellProvider,
+ useAppShell,
+ useListColumnCollapsed,
+} from "./app-shell-context";
+
+const navigation = vi.hoisted(() => ({ pathname: "/acme/issues", search: "" }));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({
+ pathname: navigation.pathname,
+ searchParams: new URLSearchParams(navigation.search),
+ }),
+}));
+
+let shell: ReturnType<typeof useAppShell> = null;
+function Reader() {
+ shell = useAppShell();
+ return null;
+}
+
+let sidebarState: string | null = null;
+let listColumnCollapsed = false;
+let setSidebarOpen: ((open: boolean) => void) | null = null;
+function NavReader() {
+ shell = useAppShell();
+ const sidebar = useSidebar();
+ sidebarState = sidebar.state;
+ setSidebarOpen = sidebar.setOpen;
+ listColumnCollapsed = useListColumnCollapsed();
+ return null;
+}
+
+function renderNavShell() {
+ return render(
+ <SidebarProvider>
+ <AppShellProvider>
+ <NavReader />
+ </AppShellProvider>
+ </SidebarProvider>,
+ );
+}
+
+function renderShell() {
+ return render(
+ <AppShellProvider>
+ <Reader />
+ </AppShellProvider>,
+ );
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ navigation.pathname = "/acme/issues";
+ navigation.search = "";
+ shell = null;
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("AppShellProvider", () => {
+ it("is absent outside the shell", () => {
+ render(<Reader />);
+ expect(shell).toBeNull();
+ });
+
+ it("gives panels to work, team and autopilots only", () => {
+ const cases: [string, string | null, boolean][] = [
+ ["/acme/my-issues", "work", true],
+ ["/acme/squads/s-1", "team", true],
+ ["/acme/autopilots", "autopilots", true],
+ ["/acme/inbox", "inbox", false],
+ ["/acme/chat", "chat", false],
+ ["/acme/settings", "settings", false],
+ ["/acme/attachments/a-1", null, false],
+ ];
+ for (const [pathname, space, hasPanel] of cases) {
+ navigation.pathname = pathname;
+ const { unmount } = renderShell();
+ expect(shell?.space).toBe(space);
+ expect(shell?.hasPanel).toBe(hasPanel);
+ unmount();
+ }
+ });
+
+ it("opens a peek after the pointer settles and switches instantly once open", () => {
+ renderShell();
+ act(() => shell!.requestPeek("team"));
+ act(() => vi.advanceTimersByTime(100));
+ expect(shell!.peekSpace).toBeNull();
+ act(() => vi.advanceTimersByTime(100));
+ expect(shell!.peekSpace).toBe("team");
+
+ act(() => shell!.requestPeek("work"));
+ expect(shell!.peekSpace).toBe("work");
+ });
+
+ it("closes after release unless the pointer reaches the preview", () => {
+ renderShell();
+ act(() => shell!.requestPeek("team"));
+ act(() => vi.advanceTimersByTime(200));
+
+ act(() => shell!.releasePeek());
+ act(() => shell!.holdPeek());
+ act(() => vi.advanceTimersByTime(500));
+ expect(shell!.peekSpace).toBe("team");
+
+ act(() => shell!.releasePeek());
+ act(() => vi.advanceTimersByTime(250));
+ expect(shell!.peekSpace).toBeNull();
+ });
+
+ it("closes the peek once navigation lands", () => {
+ const { rerender } = renderShell();
+ act(() => shell!.requestPeek("team"));
+ act(() => vi.advanceTimersByTime(200));
+ expect(shell!.peekSpace).toBe("team");
+
+ navigation.pathname = "/acme/agents";
+ rerender(
+ <AppShellProvider>
+ <Reader />
+ </AppShellProvider>,
+ );
+ expect(shell!.peekSpace).toBeNull();
+ });
+
+ it("collapses the panel and the list columns as one sidebar across spaces", () => {
+ const { rerender } = renderNavShell();
+ const visit = (pathname: string) => {
+ navigation.pathname = pathname;
+ rerender(
+ <SidebarProvider>
+ <AppShellProvider>
+ <NavReader />
+ </AppShellProvider>
+ </SidebarProvider>,
+ );
+ };
+
+ act(() => shell!.toggleNav());
+ expect(sidebarState).toBe("collapsed");
+ visit("/acme/inbox");
+ expect(listColumnCollapsed).toBe(true);
+
+ act(() => shell!.toggleNav());
+ expect(listColumnCollapsed).toBe(false);
+ visit("/acme/issues");
+ expect(sidebarState).toBe("expanded");
+ });
+
+ it("collapses a list column the md–lg auto-collapse left open", () => {
+ navigation.pathname = "/acme/inbox";
+ renderNavShell();
+ act(() => setSidebarOpen!(false));
+ expect(listColumnCollapsed).toBe(false);
+
+ act(() => shell!.toggleNav());
+ expect(listColumnCollapsed).toBe(true);
+ expect(sidebarState).toBe("collapsed");
+ });
+
+ it("sends each rail space back to the last page visited in it", () => {
+ const { rerender } = renderShell();
+ const visit = (pathname: string, search = "") => {
+ navigation.pathname = pathname;
+ navigation.search = search;
+ rerender(
+ <AppShellProvider>
+ <Reader />
+ </AppShellProvider>,
+ );
+ };
+
+ visit("/acme/projects/p-1", "tab=issues");
+ visit("/acme/agents/a-1");
+ expect(shell!.spaceHref("work", "/acme/issues")).toBe("/acme/projects/p-1?tab=issues");
+ expect(shell!.spaceHref("chat", "/acme/chat")).toBe("/acme/chat");
+ // The current space's item leads home, so clicking it again resets.
+ expect(shell!.spaceHref("team", "/acme/agents")).toBe("/acme/agents");
+
+ // Memory is per workspace.
+ visit("/beta/inbox");
+ expect(shell!.spaceHref("work", "/beta/issues")).toBe("/beta/issues");
+ });
+
+ it("lays out the page on screen while navigation runs ahead of it", () => {
+ const shellAt = (renderedPathname: string) => (
+ <AppShellProvider renderedPathname={renderedPathname}>
+ <Reader />
+ </AppShellProvider>
+ );
+ const { rerender } = render(shellAt("/acme/issues"));
+
+ // Leaving Work for Inbox: the issues page is still mounted, so it keeps
+ // its panel until the inbox page commits.
+ navigation.pathname = "/acme/inbox";
+ rerender(shellAt("/acme/issues"));
+ expect(shell!.space).toBe("work");
+ expect(shell!.hasPanel).toBe(true);
+ // Space memory follows the navigation, not the lagging page.
+ expect(shell!.spaceHref("inbox", "/acme/inbox")).toBe("/acme/inbox");
+
+ rerender(shellAt("/acme/inbox"));
+ expect(shell!.space).toBe("inbox");
+ expect(shell!.hasPanel).toBe(false);
+ expect(shell!.spaceHref("work", "/acme/issues")).toBe("/acme/issues");
+ });
+});
diff --git a/packages/views/layout/app-shell-context.tsx b/packages/views/layout/app-shell-context.tsx
new file mode 100644
index 0000000000..d9902078dd
--- /dev/null
+++ b/packages/views/layout/app-shell-context.tsx
@@ -0,0 +1,202 @@
+"use client";
+
+import { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { spaceForPath, type AppSpaceId } from "@multica/core/paths";
+import { useSidebarSafe } from "@multica/ui/components/ui/sidebar";
+import { useNavigation } from "../navigation";
+
+/**
+ * Spaces whose navigation lives in the shell panel. Inbox, Chat and Settings
+ * are list-and-detail pages that already render their own list column in the
+ * same card, so the shell adds no panel for them.
+ */
+export const PANEL_SPACES: ReadonlySet<AppSpaceId> = new Set(["work", "team", "autopilots"]);
+
+// Opening waits for the pointer to settle so sweeping across the rail does
+// not flash every panel; closing waits long enough to cross the gap between
+// the rail and the preview.
+const PEEK_OPEN_DELAY_MS = 150;
+const PEEK_CLOSE_DELAY_MS = 200;
+
+interface AppShellContextValue {
+ space: AppSpaceId | null;
+ /** The current space has a shell panel (collapsible with the sidebar toggle). */
+ hasPanel: boolean;
+ /**
+ * Inbox, Chat and Settings keep their own list column, which collapses with
+ * the space panel. Tracked apart from the panel's open state so the md–lg
+ * auto-collapse never hides a list the page needs.
+ */
+ listCollapsed: boolean;
+ setListCollapsed: (collapsed: boolean) => void;
+ /** The sidebar toggle: the space panel and list columns together, or the compact sheet. */
+ toggleNav: () => void;
+ /**
+ * The current space's nav (its panel or list column) is off screen, so the
+ * rail previews spaces on hover. Always false in the compact layout.
+ */
+ navCollapsed: boolean;
+ /**
+ * Where a rail item leads: the last page visited in that space of this
+ * workspace, or `home` for the current space and spaces not yet visited.
+ */
+ spaceHref: (space: AppSpaceId, home: string) => string;
+ /** Space previewed over the content while the nav is collapsed. */
+ peekSpace: AppSpaceId | null;
+ requestPeek: (space: AppSpaceId) => void;
+ holdPeek: () => void;
+ releasePeek: () => void;
+ closePeek: () => void;
+}
+
+const AppShellContext = createContext<AppShellContextValue | null>(null);
+
+export function AppShellProvider({
+ renderedPathname,
+ children,
+}: {
+ /**
+ * The pathname of the page on screen, where it can trail the navigation's
+ * (desktop renders the next page in a transition). The panel and list
+ * columns follow it so they never frame the outgoing page in the incoming
+ * space's layout.
+ */
+ renderedPathname?: string | null;
+ children: React.ReactNode;
+}) {
+ const { pathname, searchParams } = useNavigation();
+ const sidebar = useSidebarSafe();
+ const navSpace = spaceForPath(pathname);
+ const space = renderedPathname ? spaceForPath(renderedPathname) : navSpace;
+ const workspaceSlug = pathname.split("/").filter(Boolean)[0] ?? "";
+ const search = searchParams?.toString() ?? "";
+ // Keyed by `${workspaceSlug}/${space}`. The fragment is left out so a
+ // comment deep link is not replayed on every return to the space.
+ const [spaceUrls, setSpaceUrls] = useState<Record<string, string>>({});
+ const hasPanel = space !== null && PANEL_SPACES.has(space);
+ const [listCollapsed, setListCollapsed] = useState(false);
+ const [peekSpace, setPeekSpace] = useState<AppSpaceId | null>(null);
+ const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const peekRef = useRef(peekSpace);
+ useEffect(() => {
+ peekRef.current = peekSpace;
+ }, [peekSpace]);
+
+ const clearTimers = useCallback(() => {
+ if (openTimer.current) clearTimeout(openTimer.current);
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ openTimer.current = null;
+ closeTimer.current = null;
+ }, []);
+
+ const requestPeek = useCallback(
+ (next: AppSpaceId) => {
+ clearTimers();
+ if (peekRef.current !== null) {
+ setPeekSpace(next);
+ return;
+ }
+ openTimer.current = setTimeout(() => setPeekSpace(next), PEEK_OPEN_DELAY_MS);
+ },
+ [clearTimers],
+ );
+ const holdPeek = useCallback(() => {
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ closeTimer.current = null;
+ }, []);
+ const releasePeek = useCallback(() => {
+ clearTimers();
+ closeTimer.current = setTimeout(() => setPeekSpace(null), PEEK_CLOSE_DELAY_MS);
+ }, [clearTimers]);
+ const closePeek = useCallback(() => {
+ clearTimers();
+ setPeekSpace(null);
+ }, [clearTimers]);
+
+ // Following a link out of the preview lands on its page; the preview has
+ // done its job. Inbox and Chat select rows through the query string alone.
+ const shownPathname = renderedPathname || pathname;
+ useEffect(() => {
+ closePeek();
+ }, [shownPathname, search, closePeek]);
+ useEffect(() => clearTimers, [clearTimers]);
+
+ useEffect(() => {
+ if (!navSpace || !workspaceSlug) return;
+ const key = `${workspaceSlug}/${navSpace}`;
+ const url = search ? `${pathname}?${search}` : pathname;
+ setSpaceUrls((urls) => (urls[key] === url ? urls : { ...urls, [key]: url }));
+ }, [pathname, search, navSpace, workspaceSlug]);
+
+ const spaceHref = useCallback(
+ (target: AppSpaceId, home: string) =>
+ target === navSpace ? home : (spaceUrls[`${workspaceSlug}/${target}`] ?? home),
+ [navSpace, spaceUrls, workspaceSlug],
+ );
+
+ const toggleSidebar = sidebar?.toggleSidebar;
+ const setSidebarOpen = sidebar?.setOpen;
+ const sidebarOpen = sidebar?.open ?? true;
+ const isCompact = sidebar?.isCompact ?? false;
+ const usesListColumn = space !== null && !hasPanel;
+ // One toggle for the whole nav: whatever the current space shows decides
+ // the direction, and the panel and every list column follow it together.
+ const toggleNav = useCallback(() => {
+ if (isCompact || !setSidebarOpen) {
+ toggleSidebar?.();
+ return;
+ }
+ const collapse = usesListColumn ? !listCollapsed : sidebarOpen;
+ setSidebarOpen(!collapse);
+ setListCollapsed(collapse);
+ }, [isCompact, listCollapsed, setSidebarOpen, sidebarOpen, toggleSidebar, usesListColumn]);
+ const navCollapsed = !isCompact && (usesListColumn ? listCollapsed : !sidebarOpen);
+
+ const value = useMemo<AppShellContextValue>(
+ () => ({
+ space,
+ hasPanel,
+ listCollapsed,
+ setListCollapsed,
+ toggleNav,
+ navCollapsed,
+ spaceHref,
+ peekSpace,
+ requestPeek,
+ holdPeek,
+ releasePeek,
+ closePeek,
+ }),
+ [
+ space,
+ hasPanel,
+ listCollapsed,
+ toggleNav,
+ navCollapsed,
+ spaceHref,
+ peekSpace,
+ requestPeek,
+ holdPeek,
+ releasePeek,
+ closePeek,
+ ],
+ );
+
+ return <AppShellContext.Provider value={value}>{children}</AppShellContext.Provider>;
+}
+
+/** Null outside the dashboard shell (standalone pages, isolated tests). */
+export function useAppShell(): AppShellContextValue | null {
+ return use(AppShellContext);
+}
+
+/**
+ * Whether a list-and-detail page (Inbox, Chat, Settings) hides its list
+ * column. Below `md` those pages manage the list themselves.
+ */
+export function useListColumnCollapsed(): boolean {
+ const shell = useAppShell();
+ const sidebar = useSidebarSafe();
+ return Boolean(shell?.listCollapsed && !shell.hasPanel && !sidebar?.isCompact);
+}
diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsx
deleted file mode 100644
index 4803879863..0000000000
--- a/packages/views/layout/app-sidebar.test.tsx
+++ /dev/null
@@ -1,545 +0,0 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
-
-vi.mock("@multica/core/issue-statuses/hooks", () => ({
- useIssueStatuses: () => buildIssueStatusCatalog([]),
-}));
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ApiError } from "@multica/core/api";
-import { renderWithI18n } from "../test/i18n";
-import { AppSidebar } from "./app-sidebar";
-
-const { appForeground, chatSessions, chatStore, detail, deletePin, invitationApi, navigation, pins, sidebarState, summary, workspaces } = vi.hoisted(() => ({
- appForeground: { current: true },
- sidebarState: { setOpenMobile: vi.fn() },
- chatSessions: { current: [] as { id?: string; unread_count?: number }[] },
- chatStore: { current: { activeSessionId: null as string | null, isOpen: false } },
- detail: { current: { isPending: false, isError: false, data: null as unknown, error: null as unknown } },
- deletePin: vi.fn(),
- // Captures the sidebar's invitation accept/decline mutations so the
- // self-heal wiring (error → invalidate the pending list) is observable.
- invitationApi: {
- accept: vi.fn(),
- decline: vi.fn(),
- invalidateQueries: vi.fn(),
- mutations: [] as Array<Record<string, unknown>>,
- },
- navigation: { current: { pathname: "/acme/issues" } },
- summary: { current: [] as { workspace_id: string; count: number }[] },
- workspaces: {
- current: [] as { id: string; name: string; slug: string; avatar_url: string | null }[],
- },
- pins: {
- current: [
- {
- id: "pin-1",
- workspace_id: "ws-1",
- user_id: "user-1",
- item_type: "issue" as const,
- item_id: "issue-1",
- position: 0,
- created_at: "2026-05-06T00:00:00Z",
- },
- ],
- },
-}));
-
-vi.mock("@dnd-kit/core", () => ({
- DndContext: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- PointerSensor: vi.fn(),
- closestCenter: vi.fn(),
- useSensor: vi.fn(),
- useSensors: vi.fn(),
-}));
-vi.mock("@dnd-kit/sortable", () => ({
- SortableContext: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- useSortable: () => ({ attributes: {}, listeners: {}, setNodeRef: vi.fn() }),
- verticalListSortingStrategy: vi.fn(),
-}));
-vi.mock("@dnd-kit/utilities", () => ({ CSS: { Transform: { toString: () => undefined } } }));
-vi.mock("@multica/ui/components/ui/sidebar", () => ({
- Sidebar: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarFooter: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarGroup: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarGroupContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarGroupLabel: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarHeader: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarMenuButton: ({
- children,
- isActive,
- render,
- ...props
- }: {
- children: React.ReactNode;
- isActive?: boolean;
- render?: React.ReactElement<{ href?: string }>;
- } & React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props} type="button" data-active={isActive ? "true" : undefined} data-href={render?.props.href}>
- {children}
- </button>
- ),
- SidebarMenuItem: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SidebarRail: () => null,
- useSidebar: () => ({ setOpenMobile: sidebarState.setOpenMobile }),
-}));
-vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({
- DropdownMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- DropdownMenuGroup: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- DropdownMenuItem: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- DropdownMenuSeparator: () => null,
- DropdownMenuTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
-}));
-vi.mock("@multica/ui/components/ui/collapsible", () => ({
- Collapsible: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- CollapsibleContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- CollapsibleTrigger: () => <button type="button" />,
-}));
-vi.mock("@multica/ui/components/ui/tooltip", () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- TooltipTrigger: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
-}));
-vi.mock("../common/use-app-foreground", () => ({
- useAppForeground: () => appForeground.current,
-}));
-vi.mock("./help-launcher", () => ({ HelpLauncher: () => null }));
-vi.mock("../auth", () => ({ useLogout: () => vi.fn() }));
-vi.mock("../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));
-vi.mock("../navigation", () => ({
- AppLink: ({ children, href }: { children: React.ReactNode; href: string }) => <a href={href}>{children}</a>,
- useNavigation: () => ({ pathname: navigation.current.pathname, push: vi.fn() }),
-}));
-vi.mock("../projects/components/project-icon", () => ({ ProjectIcon: () => <span /> }));
-vi.mock("../workspace/workspace-avatar", () => ({ WorkspaceAvatar: () => <span /> }));
-vi.mock("@multica/ui/components/common/actor-avatar", () => ({ ActorAvatar: () => <span /> }));
-
-vi.mock("@multica/core/auth", () => ({
- useAuthStore: (selector: (state: { user: { id: string } }) => unknown) => selector({ user: { id: "user-1" } }),
-}));
-// Callable-store shape (selectorFn + getState) per the repo testing rules.
-vi.mock("@multica/core/chat", () => ({
- useChatStore: Object.assign(
- (selector: (state: { activeSessionId: string | null; isOpen: boolean }) => unknown) =>
- selector(chatStore.current),
- { getState: () => chatStore.current },
- ),
-}));
-vi.mock("@multica/core/paths", async (importOriginal) => ({
- // Spread the real module so pure helpers (resolveRouteIconName, used by the
- // nav to derive each item's icon from its href) stay intact; only the
- // workspace/context hooks below are stubbed to control routes in tests.
- ...(await importOriginal<typeof import("@multica/core/paths")>()),
- paths: { workspace: (slug: string) => ({ issues: () => `/${slug}/issues` }) },
- useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme", slug: "acme" }),
- useWorkspacePaths: () => ({
- inbox: () => "/acme/inbox",
- chat: () => "/acme/chat",
- myIssues: () => "/acme/my-issues",
- issues: () => "/acme/issues",
- projects: () => "/acme/projects",
- autopilots: () => "/acme/autopilots",
- agents: () => "/acme/agents",
- squads: () => "/acme/squads",
- usage: () => "/acme/usage",
- runtimes: () => "/acme/runtimes",
- skills: () => "/acme/skills",
- settings: () => "/acme/settings",
- issueDetail: (id: string) => `/acme/issues/${id}`,
- projectDetail: (id: string) => `/acme/projects/${id}`,
- }),
-}));
-vi.mock("@multica/core/api", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@multica/core/api")>();
- return {
- ...actual,
- api: {
- ...actual.api,
- getBaseUrl: () => "http://127.0.0.1:8080",
- acceptInvitation: invitationApi.accept,
- declineInvitation: invitationApi.decline,
- },
- };
-});
-vi.mock("@multica/core/inbox/queries", () => ({
- inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),
- inboxUnreadSummaryEnabled: (wsId: string | null) => () => !!wsId,
- // The nav badge and the switcher dot read the SAME cross-workspace summary,
- // so the fixture that drives one drives the other.
- useInboxUnreadCount: (currentWsId: string | null) =>
- summary.current.find((s) => s.workspace_id === currentWsId)?.count ?? 0,
- hasOtherWorkspaceUnread: (
- entries: { workspace_id: string; count: number }[],
- currentWsId: string | null,
- ) => entries.some((s) => s.workspace_id !== currentWsId && s.count > 0),
- unreadWorkspaceIds: (entries: { workspace_id: string; count: number }[]) =>
- new Set(entries.filter((s) => s.count > 0).map((s) => s.workspace_id)),
-}));
-vi.mock("@multica/core/issues/queries", () => ({ issueDetailOptions: () => ({ queryKey: ["issue"] }) }));
-vi.mock("@multica/core/issues/stores/create-mode-store", () => ({
- useCreateModeStore: { getState: () => ({ lastMode: "agent" }) },
- openCreateIssueWithPreference: vi.fn(),
-}));
-vi.mock("@multica/core/issues/stores/draft-store", () => ({ useIssueDraftStore: () => false }));
-vi.mock("@multica/core/modals", () => ({ useModalStore: { getState: () => ({ modal: null, open: vi.fn() }) } }));
-vi.mock("@multica/core/pins/mutations", () => ({ useDeletePin: () => ({ mutate: deletePin }), useReorderPins: () => ({ mutate: vi.fn() }) }));
-vi.mock("@multica/core/pins/queries", () => ({ pinListOptions: () => ({ queryKey: ["pins"] }) }));
-vi.mock("@multica/core/projects/queries", () => ({ projectDetailOptions: () => ({ queryKey: ["project"] }) }));
-vi.mock("@multica/core/workspace/queries", () => ({
- myInvitationListOptions: () => ({ queryKey: ["invitations"] }),
- workspaceKeys: { myInvitations: () => ["invitations"] },
- workspaceListOptions: () => ({ queryKey: ["workspaces"] }),
-}));
-vi.mock("@tanstack/react-query", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@tanstack/react-query")>()),
- useMutation: (options: Record<string, unknown> = {}) => {
- invitationApi.mutations.push(options);
- return { isPending: false, mutate: vi.fn() };
- },
- useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {
- if (queryKey[0] === "pins") return { data: pins.current };
- if (queryKey[0] === "issue") return detail.current;
- if (queryKey[0] === "inbox" && queryKey[1] === "unread-summary") return { data: summary.current };
- if (queryKey[0] === "workspaces") return { data: workspaces.current };
- if (queryKey[0] === "chat" && queryKey[2] === "sessions") return { data: chatSessions.current };
- return { data: [] };
- },
- useQueryClient: () => ({
- fetchQuery: vi.fn(),
- prefetchQuery: vi.fn(),
- invalidateQueries: invitationApi.invalidateQueries,
- }),
-}));
-
-describe("PinRow", () => {
- beforeEach(() => {
- deletePin.mockReset();
- navigation.current.pathname = "/acme/issues";
- detail.current = { isPending: false, isError: false, data: null, error: null };
- summary.current = [];
- workspaces.current = [];
- });
-
- it("unpins missing details", async () => {
- detail.current = { isPending: false, isError: true, data: null, error: new ApiError("missing", 404, "Not Found") };
- render(<AppSidebar />);
- await waitFor(() => expect(deletePin).toHaveBeenCalledTimes(1));
- });
-
- it("ignores non-404 errors", async () => {
- detail.current = { isPending: false, isError: true, data: null, error: new ApiError("error", 500, "Server Error") };
- render(<AppSidebar />);
- await waitFor(() => expect(deletePin).not.toHaveBeenCalled());
- });
-
- it("renders loaded details", async () => {
- detail.current = { isPending: false, isError: false, data: { identifier: "MUL-123", title: "Keep this pin", status: "todo" }, error: null };
- render(<AppSidebar />);
- expect(await screen.findByText("Keep this pin")).toBeInTheDocument();
- expect(screen.queryByText("MUL-123 Keep this pin")).not.toBeInTheDocument();
- });
-
- it("does not also highlight the parent workspace nav for an active pin", async () => {
- navigation.current.pathname = "/acme/issues/issue-1";
- detail.current = {
- isPending: false,
- isError: false,
- data: { identifier: "MUL-123", title: "Keep this pin", status: "todo" },
- error: null,
- };
-
- const { container } = render(<AppSidebar />);
-
- expect((await screen.findByText("Keep this pin")).closest("button")).toHaveAttribute(
- "data-active",
- "true",
- );
- expect(container.querySelector('button[data-href="/acme/issues"]')).not.toHaveAttribute("data-active");
- });
-
- it("keeps the parent route active until a hidden pin is expanded", () => {
- const originalPins = pins.current;
- pins.current = Array.from({ length: 6 }, (_, index) => ({
- ...originalPins[0]!,
- id: `pin-${index + 1}`,
- item_id: `issue-${index + 1}`,
- position: index,
- }));
- navigation.current.pathname = "/acme/issues/issue-6";
- detail.current = {
- isPending: false,
- isError: false,
- data: { identifier: "MUL-123", title: "Pinned issue", status: "todo" },
- error: null,
- };
-
- try {
- const { container } = renderWithI18n(<AppSidebar />);
- const parent = () => container.querySelector('button[data-href="/acme/issues"]');
- const lastPin = () => container.querySelector('button[data-href="/acme/issues/issue-6"]');
-
- expect(lastPin()).not.toBeInTheDocument();
- expect(parent()).toHaveAttribute("data-active", "true");
-
- fireEvent.click(screen.getByRole("button", { name: "Show 1 more…" }));
- expect(lastPin()).toHaveAttribute("data-active", "true");
- expect(parent()).not.toHaveAttribute("data-active");
-
- fireEvent.click(screen.getByRole("button", { name: "Show fewer" }));
- expect(lastPin()).not.toBeInTheDocument();
- expect(parent()).toHaveAttribute("data-active", "true");
- } finally {
- pins.current = originalPins;
- }
- });
-});
-
-// On a phone the sidebar is a Sheet laid over the page, so a nav tap that
-// leaves it open renders the destination underneath and reads as a dead tap.
-describe("mobile sheet dismissal", () => {
- beforeEach(() => {
- sidebarState.setOpenMobile.mockClear();
- navigation.current = { pathname: "/acme/issues" };
- });
-
- it("dismisses the sheet once the route changes", () => {
- const { rerender } = render(<AppSidebar />);
- sidebarState.setOpenMobile.mockClear();
-
- navigation.current = { pathname: "/acme/inbox" };
- rerender(<AppSidebar />);
-
- expect(sidebarState.setOpenMobile).toHaveBeenCalledWith(false);
- });
-
- // Closing on `pathname` rather than per-link keeps every route out of the
- // sidebar covered at once — nav groups, pins, and the switcher's own push.
- it("does not re-dismiss while the route holds still", () => {
- const { rerender } = render(<AppSidebar />);
- sidebarState.setOpenMobile.mockClear();
-
- rerender(<AppSidebar />);
-
- expect(sidebarState.setOpenMobile).not.toHaveBeenCalled();
- });
-});
-
-describe("workspace-switcher unread dot", () => {
- beforeEach(() => {
- summary.current = [];
- workspaces.current = [];
- });
-
- // The aggregate switcher dot is the only `.ring-sidebar` span in the tree
- // (DraftDot is null when there's no draft, and there are no invitations).
- const dot = (container: HTMLElement) => container.querySelector("span.bg-brand.ring-sidebar");
-
- it("shows a dot when another workspace has unread inbox items", () => {
- summary.current = [{ workspace_id: "ws-2", count: 3 }];
- const { container } = render(<AppSidebar />);
- expect(dot(container)).not.toBeNull();
- });
-
- it("does not show a dot when only the active workspace has unread", () => {
- // Active workspace is ws-1 (see useCurrentWorkspace mock).
- summary.current = [{ workspace_id: "ws-1", count: 3 }];
- const { container } = render(<AppSidebar />);
- expect(dot(container)).toBeNull();
- });
-
- it("does not show a dot when no workspace has unread", () => {
- summary.current = [];
- const { container } = render(<AppSidebar />);
- expect(dot(container)).toBeNull();
- });
-});
-
-describe("workspace-switcher dropdown per-workspace dot", () => {
- beforeEach(() => {
- summary.current = [];
- // Active workspace is ws-1 (see useCurrentWorkspace mock); "Other" is ws-2.
- workspaces.current = [
- { id: "ws-1", name: "Active WS", slug: "active", avatar_url: null },
- { id: "ws-2", name: "Other WS", slug: "other", avatar_url: null },
- ];
- });
-
- // Row dots are brand dots WITHOUT the aggregate avatar dot's `ring-sidebar`.
- const rowDots = (container: HTMLElement) =>
- container.querySelectorAll("span.bg-brand:not(.ring-sidebar)");
-
- it("dots the specific other workspace that has unread", () => {
- summary.current = [{ workspace_id: "ws-2", count: 3 }];
- const { container } = render(<AppSidebar />);
- // Exactly one row dot, sitting right after the "Other WS" name; the active
- // row shows the check, not a dot.
- expect(rowDots(container)).toHaveLength(1);
- expect(screen.getByText("Other WS").nextElementSibling?.className).toContain("bg-brand");
- expect(screen.getByText("Active WS").nextElementSibling?.className ?? "").not.toContain("bg-brand");
- });
-
- it("does not dot a workspace whose unread count is zero", () => {
- summary.current = [{ workspace_id: "ws-2", count: 0 }];
- const { container } = render(<AppSidebar />);
- expect(rowDots(container)).toHaveLength(0);
- });
-
- it("never dots the active workspace even when it has unread", () => {
- summary.current = [{ workspace_id: "ws-1", count: 5 }];
- const { container } = render(<AppSidebar />);
- expect(rowDots(container)).toHaveLength(0);
- });
-});
-
-describe("navigation item presentation", () => {
- it("keeps Analytics and Settings styled like the other nav items", () => {
- const { container } = render(<AppSidebar />);
- const referenceClassName = container.querySelector(
- 'button[data-href="/acme/issues"]',
- )?.className;
-
- expect(referenceClassName).toBeTruthy();
-
- for (const href of ["/acme/usage", "/acme/settings"]) {
- expect(container.querySelector(`button[data-href="${href}"]`)?.className).toBe(
- referenceClassName,
- );
- }
- });
-});
-
-describe("personal nav — Chat", () => {
- beforeEach(() => {
- chatSessions.current = [];
- summary.current = [];
- navigation.current = { pathname: "/acme/issues" };
- chatStore.current = { activeSessionId: null, isOpen: false };
- appForeground.current = true;
- });
-
- // The mocked SidebarMenuButton exposes the AppLink target as `data-href`
- // and renders the label + badge as its children.
- const chatNav = (container: HTMLElement) =>
- container.querySelector<HTMLElement>('button[data-href="/acme/chat"]');
- const chatBadge = (container: HTMLElement) =>
- chatNav(container)?.querySelector("number-flow-react") ?? null;
-
- it("keeps persistent Inbox and Chat counters static", () => {
- summary.current = [{ workspace_id: "ws-1", count: 1 }];
- chatSessions.current = [{ id: "chat-1", unread_count: 2 }];
- const { container } = render(<AppSidebar />);
- const inboxBadge = container
- .querySelector<HTMLElement>('button[data-href="/acme/inbox"]')
- ?.querySelector("number-flow-react") as (HTMLElement & { animated?: boolean }) | null;
- const currentChatBadge = chatBadge(container) as (HTMLElement & { animated?: boolean }) | null;
-
- expect(inboxBadge?.animated).toBe(false);
- expect(currentChatBadge?.animated).toBe(false);
- });
-
- it("renders a Chat nav link to the workspace chat route", () => {
- const { container } = render(<AppSidebar />);
- expect(chatNav(container)).not.toBeNull();
- });
-
- it("badges the Chat nav with the summed unread_count of chat sessions", () => {
- chatSessions.current = [{ id: "a", unread_count: 3 }, { id: "b", unread_count: 2 }, { id: "c", unread_count: 0 }];
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
- });
-
- it("shows no Chat unread badge when every session is read", () => {
- chatSessions.current = [{ id: "a", unread_count: 0 }, { id: "b" }];
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toBeNull();
- });
-
- it("excludes the session being viewed on the chat page from the badge", () => {
- // The thread list zeroes the open session's row badge; the aggregate
- // must follow, or a reply landing in the open conversation flashes a
- // count with no matching row.
- chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
- navigation.current = { pathname: "/acme/chat" };
- chatStore.current = { activeSessionId: "a", isOpen: false };
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toHaveAttribute("aria-label", "3");
- });
-
- it("excludes the viewed session when the floating chat window is open off-route", () => {
- chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
- navigation.current = { pathname: "/acme/issues" };
- chatStore.current = { activeSessionId: "a", isOpen: true };
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toHaveAttribute("aria-label", "3");
- });
-
- it("still counts a remembered selection when no chat surface is showing it", () => {
- // activeSessionId persists after the chat page closes; with both
- // surfaces closed nothing will auto mark-read, so the badge must count.
- chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
- navigation.current = { pathname: "/acme/issues" };
- chatStore.current = { activeSessionId: "a", isOpen: false };
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
- });
-
- it("counts the active session while the floating window is open but the app is backgrounded", () => {
- // A reply landing while the app is not in the foreground is NOT auto
- // marked-read (MUL-4485), so its unread must still badge — otherwise the
- // notification is silently eaten while the user is away.
- chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
- navigation.current = { pathname: "/acme/issues" };
- chatStore.current = { activeSessionId: "a", isOpen: true };
- appForeground.current = false;
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
- });
-
- it("counts the active session on the chat route while the app is backgrounded", () => {
- chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
- navigation.current = { pathname: "/acme/chat" };
- chatStore.current = { activeSessionId: "a", isOpen: false };
- appForeground.current = false;
- const { container } = render(<AppSidebar />);
- expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
- });
-});
-
-describe("Pending invitation self-heal", () => {
- beforeEach(() => {
- invitationApi.accept.mockReset();
- invitationApi.decline.mockReset();
- invitationApi.invalidateQueries.mockClear();
- invitationApi.mutations.length = 0;
- invitationApi.accept.mockRejectedValue(new Error("invitation is not pending"));
- invitationApi.decline.mockRejectedValue(new Error("invitation is not pending"));
- navigation.current.pathname = "/acme/issues";
- workspaces.current = [];
- });
-
- // "invitation is not pending" means the row on screen was concluded from
- // another surface. Both mutations must invalidate the pending list on
- // failure so the stale row drops instead of surviving until restart.
- it("invalidates the pending-invitations list when accept or decline fails", async () => {
- render(<AppSidebar />);
- expect(invitationApi.mutations).toHaveLength(2);
-
- for (const options of invitationApi.mutations as Array<{
- mutationFn: (id: string) => Promise<unknown>;
- onError?: (...args: unknown[]) => unknown;
- onSettled?: (...args: unknown[]) => unknown;
- }>) {
- const settle = options.onError ?? options.onSettled;
- expect(settle).toBeTypeOf("function");
- invitationApi.invalidateQueries.mockClear();
- await expect(options.mutationFn("inv-1")).rejects.toThrow("invitation is not pending");
- await settle!(new Error("invitation is not pending"), "inv-1", undefined, undefined);
- expect(invitationApi.invalidateQueries).toHaveBeenCalledWith({ queryKey: ["invitations"] });
- }
- expect(invitationApi.accept).toHaveBeenCalledTimes(1);
- expect(invitationApi.decline).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
deleted file mode 100644
index 2f0656fc7d..0000000000
--- a/packages/views/layout/app-sidebar.tsx
+++ /dev/null
@@ -1,943 +0,0 @@
-"use client";
-import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
-
-import { issueStatusCategory } from "@multica/core/issues";
-import React, { useCallback, useEffect, useRef, useState } from "react";
-import { cn } from "@multica/ui/lib/utils";
-import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
-import { AppLink, useNavigation } from "../navigation";
-import { HelpLauncher } from "./help-launcher";
-import { JoinDiscordCard } from "./join-discord-card";
-import {
- DndContext,
- PointerSensor,
- useSensor,
- useSensors,
- closestCenter,
- type DragEndEvent,
-} from "@dnd-kit/core";
-import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
-import { Layers,
- ChevronDown,
- ChevronRight,
- LogOut,
- Plus,
- Check,
- SquarePen,
- X,
-} from "@multica/ui/icons";
-import { WorkspaceAvatar } from "../workspace/workspace-avatar";
-import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
-import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "@multica/ui/components/ui/collapsible";
-import { CappedNumberFlow } from "@multica/ui/components/ui/number-flow";
-import { StatusIcon } from "../issues/components/status-icon";
-import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";
-import { openCreateIssueWithPreference } from "@multica/core/issues/stores/create-mode-store";
-import {
- Sidebar,
- SidebarContent,
- SidebarFooter,
- SidebarGroup,
- SidebarGroupContent,
- SidebarGroupLabel,
- SidebarHeader,
- SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
- SidebarRail,
- useSidebar,
-} from "@multica/ui/components/ui/sidebar";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@multica/ui/components/ui/dropdown-menu";
-import { useAuthStore } from "@multica/core/auth";
-import { issueViewDetailOptions } from "@multica/core/issue-views/queries";
-import {
- issueViewContainerKey,
- useActiveIssueViewStore,
-} from "@multica/core/issue-views/active-view-store";
-import { useCurrentWorkspace, useWorkspacePaths, paths } from "@multica/core/paths";
-import { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";
-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
-import { inboxUnreadSummaryEnabled, inboxUnreadSummaryOptions, useInboxUnreadCount, hasOtherWorkspaceUnread, unreadWorkspaceIds } from "@multica/core/inbox/queries";
-import { chatSessionsOptions } from "@multica/core/chat/queries";
-import { countUnreadChatMessages } from "@multica/core/chat/unread";
-import { useChatStore } from "@multica/core/chat";
-import { api, ApiError } from "@multica/core/api";
-import { useConfigStore } from "@multica/core/config";
-import { pinListOptions } from "@multica/core/pins/queries";
-import { useDeletePin, useReorderPins } from "@multica/core/pins/mutations";
-import { issueDetailOptions } from "@multica/core/issues/queries";
-import { projectDetailOptions } from "@multica/core/projects/queries";
-import type { PinnedItem } from "@multica/core/types";
-import { useLogout } from "../auth";
-import { ProjectIcon } from "../projects/components/project-icon";
-import { routeIconForPath } from "./route-icon-components";
-import { RouteDataPrefetch } from "./route-data-prefetch";
-import { useT } from "../i18n";
-import {
- useShortcut,
-} from "@multica/core/shortcuts";
-import { ShortcutKeycaps } from "../common/shortcut-keycaps";
-import { useAppForeground } from "../common/use-app-foreground";
-
-// Top-level nav items stay active when the user is on a child route
-// (e.g. "Projects" stays lit on /:slug/projects/:id). Pinned items keep
-// strict equality elsewhere — a pinned project shouldn't highlight on
-// sub-pages of itself.
-function isNavActive(pathname: string, href: string): boolean {
- return pathname === href || pathname.startsWith(href + "/");
-}
-
-// Stable empty arrays for query defaults. Using an inline `= []` default on
-// `useQuery` creates a new array reference on every render when `data` is
-// undefined (e.g. query disabled or loading) — which in turn breaks any
-// `useEffect`/`useMemo` that depends on the value, and can trigger infinite
-// re-render loops when the effect itself calls `setState`.
-const EMPTY_PINS: PinnedItem[] = [];
-const EMPTY_WORKSPACES: Awaited<ReturnType<typeof api.listWorkspaces>> = [];
-const EMPTY_INVITATIONS: Awaited<ReturnType<typeof api.listMyInvitations>> = [];
-const EMPTY_INBOX_SUMMARY: Awaited<ReturnType<typeof api.getInboxUnreadSummary>> = [];
-const PINNED_PREVIEW_LIMIT = 5;
-
-// Nav items reference WorkspacePaths method names so they can be resolved
-// against the current workspace slug at render time (see AppSidebar body).
-// Only parameterless paths are valid nav destinations.
-type NavKey =
- | "inbox"
- | "chat"
- | "myIssues"
- | "issues"
- | "projects"
- | "autopilots"
- | "agents"
- | "squads"
- | "usage"
- | "runtimes"
- | "skills"
- | "settings";
-
-// Static schema (key only) — labels resolved at render via useT("layout"),
-// icons derived from the destination path via routeIconForPath.
-type NavLabelKey =
- | "inbox"
- | "chat"
- | "my_issues"
- | "issues"
- | "projects"
- | "autopilots"
- | "agents"
- | "squads"
- | "usage"
- | "runtimes"
- | "skills"
- | "settings";
-
-// Nav icons are NOT declared here: they are derived from each item's
-// destination path at render time, so the sidebar and the desktop tab bar
-// always agree. See route-icon-components.tsx.
-const personalNav: { key: NavKey; labelKey: NavLabelKey }[] = [
- { key: "inbox", labelKey: "inbox" },
- { key: "myIssues", labelKey: "my_issues" },
- { key: "chat", labelKey: "chat" },
-];
-
-const workNav: { key: NavKey; labelKey: NavLabelKey }[] = [
- { key: "issues", labelKey: "issues" },
- { key: "projects", labelKey: "projects" },
- { key: "autopilots", labelKey: "autopilots" },
-];
-
-const aiTeamNav: { key: NavKey; labelKey: NavLabelKey }[] = [
- { key: "agents", labelKey: "agents" },
- { key: "squads", labelKey: "squads" },
- { key: "skills", labelKey: "skills" },
- { key: "runtimes", labelKey: "runtimes" },
-];
-
-const utilityNav: { key: NavKey; labelKey: NavLabelKey }[] = [
- { key: "usage", labelKey: "usage" },
- { key: "settings", labelKey: "settings" },
-];
-
-const NAV_ITEM_CLASS_NAME =
- "text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground";
-
-function DraftDot() {
- const hasDraft = useIssueDraftStore((s) => s.hasDraft());
- if (!hasDraft) return null;
- return <span className="absolute top-0 right-0 size-1.5 rounded-full bg-brand" />;
-}
-
-/**
- * Presentational pin row. The `label` and `iconNode` are computed by the
- * parent `PinRow` from cached issue / project detail queries — keeping
- * this component dumb means the dnd-kit / navigation wiring lives in
- * one place and the data flow is explicit.
- */
-function SortablePinItem({
- pin,
- href,
- pathname,
- onUnpin,
- label,
- iconNode,
- onNavigate,
- isActiveOverride,
-}: {
- pin: PinnedItem;
- href: string;
- pathname: string;
- onUnpin: () => void;
- label: string;
- iconNode: React.ReactNode;
- /** Runs on a real click (not a drag-release) before navigation. */
- onNavigate?: () => void;
- /** Overrides the plain path comparison (view pins carry extra state). */
- isActiveOverride?: boolean;
-}) {
- const { t } = useT("layout");
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: pin.id });
- const wasDragged = useRef(false);
-
- useEffect(() => {
- if (isDragging) wasDragged.current = true;
- }, [isDragging]);
-
- const style = { transform: CSS.Transform.toString(transform), transition };
- const isActive = isActiveOverride ?? pathname === href;
-
- return (
- <SidebarMenuItem
- ref={setNodeRef}
- style={style}
- className={cn("group/pin", isDragging && "opacity-30")}
- {...attributes}
- {...listeners}
- >
- <SidebarMenuButton
- size="sm"
- isActive={isActive}
- render={<AppLink href={href} newTabTitle={label} draggable={false} />}
- onClick={(event) => {
- if (wasDragged.current) {
- wasDragged.current = false;
- event.preventDefault();
- return;
- }
- onNavigate?.();
- }}
- className={cn(
- "text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground",
- isDragging && "pointer-events-none",
- )}
- >
- {iconNode}
- <span
- className="min-w-0 flex-1 overflow-hidden whitespace-nowrap"
- style={{
- maskImage: "linear-gradient(to right, black calc(100% - 12px), transparent)",
- WebkitMaskImage: "linear-gradient(to right, black calc(100% - 12px), transparent)",
- }}
- >{label}</span>
- <Tooltip>
- <TooltipTrigger
- render={<span role="button" />}
- className="hidden size-2.5 shrink-0 items-center justify-center rounded-sm text-muted-foreground group-hover/pin:flex hover:text-foreground"
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- onUnpin();
- }}
- >
- <X className="size-1" />
- </TooltipTrigger>
- <TooltipContent side="top" sideOffset={4}>{t(($) => $.sidebar.unpin_tooltip)}</TooltipContent>
- </Tooltip>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
-}
-
-/**
- * Smart wrapper that resolves a pin's display data (label + status/icon)
- * from the issue / project detail query cache. Both queries are declared
- * unconditionally with `enabled` gates so the hook order stays stable
- * regardless of `pin.item_type`.
- *
- * Loading: render a flat skeleton so the sidebar height doesn't jump.
- * Missing (deleted item / 404): render nothing — the row hides itself
- * until the user unpins manually or a server-side cascade catches up.
- */
-function PinRow({
- pin,
- href,
- pathname,
- onUnpin,
- wsId,
-}: {
- pin: PinnedItem;
- href: string;
- pathname: string;
- onUnpin: () => void;
- wsId: string;
-}) {
- const isIssue = pin.item_type === "issue";
- const statusCatalog = useIssueStatuses(wsId);
- const isView = pin.item_type === "view";
- const p = useWorkspacePaths();
- const setActiveView = useActiveIssueViewStore((s) => s.setActive);
- const issueQuery = useQuery({
- ...issueDetailOptions(wsId, pin.item_id),
- enabled: isIssue,
- });
- const projectQuery = useQuery({
- ...projectDetailOptions(wsId, pin.item_id),
- enabled: pin.item_type === "project",
- });
- const viewQuery = useQuery({
- ...issueViewDetailOptions(wsId, pin.item_id),
- enabled: isView,
- });
-
- const triggeredRef = useRef(false);
- useEffect(() => {
- // Views are exempt from 404-auto-unpin: an installed desktop client
- // talking to an older backend without the view endpoints sees 404 for
- // every view pin — auto-unpinning would permanently delete them all.
- // A deleted view's row simply hides instead.
- if (isView) return;
- const err = isIssue ? issueQuery.error : projectQuery.error;
- if (err instanceof ApiError && err.status === 404 && !triggeredRef.current) {
- triggeredRef.current = true;
- onUnpin();
- }
- }, [isIssue, isView, issueQuery.error, onUnpin, projectQuery.error]);
-
- const activeViewByContainer = useActiveIssueViewStore((s) => s.active);
- if (isView) {
- if (viewQuery.isPending) return <PinSkeleton />;
- if (viewQuery.isError || !viewQuery.data) return null;
- const view = viewQuery.data;
- // One resolved scope drives the path AND the container key so an
- // unrecognised scope_type from a newer backend degrades coherently.
- const scopeType: "workspace" | "my" | "project" =
- view.scope_type === "my"
- ? "my"
- : view.scope_type === "project" && view.scope_id
- ? "project"
- : "workspace";
- const viewPath =
- scopeType === "my"
- ? p.myIssues()
- : scopeType === "project"
- ? p.projectDetail(view.scope_id!)
- : p.issues();
- const containerKey = issueViewContainerKey(wsId, {
- scope_type: scopeType,
- scope_id: scopeType === "project" ? view.scope_id : null,
- });
- return (
- <SortablePinItem
- pin={pin}
- // ?view= keeps a web reload on the view for the surfaces that mount
- // the URL-sync hook (/issues, /my-issues). Project pages don't sync
- // yet — there the query is inert and reload falls back to the plain
- // page; click-through activation still works everywhere.
- href={`${viewPath}?view=${view.id}`}
- pathname={pathname}
- onUnpin={onUnpin}
- label={view.name}
- iconNode={<Layers className="!size-3.5 shrink-0" />}
- // Active only when this exact view is open on its surface — the
- // path alone also matches the plain tab.
- isActiveOverride={
- pathname === viewPath && activeViewByContainer[containerKey] === view.id
- }
- onNavigate={() => setActiveView(containerKey, view.id)}
- />
- );
- }
-
- if (isIssue) {
- if (issueQuery.isPending) return <PinSkeleton />;
- if (issueQuery.isError || !issueQuery.data) return null;
- const issue = issueQuery.data;
- const label = issue.title;
- const iconNode = (
- /* Override parent [&_svg]:size-4 — pinned items need smaller icons to match sm size */
- <StatusIcon
- status={issue.status}
- color={statusCatalog.colorOf(issue.status)}
- icon={statusCatalog.iconOf(issue.status)}
- category={issueStatusCategory(issue) ?? undefined}
- className="!size-3.5 shrink-0"
- />
- );
- return (
- <SortablePinItem
- pin={pin}
- href={href}
- pathname={pathname}
- onUnpin={onUnpin}
- label={label}
- iconNode={iconNode}
- />
- );
- }
-
- if (projectQuery.isPending) return <PinSkeleton />;
- if (projectQuery.isError || !projectQuery.data) return null;
- const project = projectQuery.data;
- const iconNode = <ProjectIcon project={project} size="sm" />;
- return (
- <SortablePinItem
- pin={pin}
- href={href}
- pathname={pathname}
- onUnpin={onUnpin}
- label={project.title}
- iconNode={iconNode}
- />
- );
-}
-
-function PinSkeleton() {
- return (
- <SidebarMenuItem>
- <div className="flex h-7 w-full items-center gap-2 px-2">
- <div className="size-3.5 shrink-0 rounded-sm bg-sidebar-accent/40" />
- <div className="h-3 w-24 rounded-xs bg-sidebar-accent/40" />
- </div>
- </SidebarMenuItem>
- );
-}
-
-interface AppSidebarProps {
- /** Rendered above SidebarHeader (e.g. desktop traffic light spacer) */
- topSlot?: React.ReactNode;
- /** Rendered in the header between workspace switcher and new-issue button (e.g. search trigger) */
- searchSlot?: React.ReactNode;
- /** Extra className for SidebarHeader */
- headerClassName?: string;
- /** Extra style for SidebarHeader */
- headerStyle?: React.CSSProperties;
-}
-
-export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }: AppSidebarProps = {}) {
- const { t } = useT("layout");
- const { pathname, push } = useNavigation();
- const user = useAuthStore((s) => s.user);
- const userId = useAuthStore((s) => s.user?.id);
- const logout = useLogout();
- const workspace = useCurrentWorkspace();
- const p = useWorkspacePaths();
- const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());
- const { data: myInvitations = EMPTY_INVITATIONS } = useQuery(myInvitationListOptions());
- const workspaceCreationDisabled = useConfigStore((s) => s.workspaceCreationDisabled);
-
- // On a phone the sidebar is a Sheet covering the page, so navigating out of
- // it has to dismiss it — otherwise the destination renders underneath and the
- // tap reads as "nothing happened". Closing on `pathname` rather than on each
- // link's onClick covers every route out of here at once: the nav groups, the
- // pinned items, the workspace switcher's programmatic push, and anything
- // added later. `setOpenMobile` is a no-op on desktop, where the sheet is not
- // the sidebar's rendering at all.
- const { setOpenMobile } = useSidebar();
- useEffect(() => {
- setOpenMobile(false);
- }, [pathname, setOpenMobile]);
-
- const wsId = workspace?.id;
- // Nav badge. Reads the cross-workspace unread summary fetched just below
- // for the switcher dot, so the count costs no request of its own — it used
- // to download the whole inbox list here just to count it (MUL-6967).
- const unreadCount = useInboxUnreadCount(wsId);
- // Chat tab unread badge: IM-style total of unread *messages* across chat
- // threads (countUnreadChatMessages is the shared definition — mobile's tab
- // badge derives from the same function, keeping the platforms in agreement).
- const { data: chatSessions = [] } = useQuery({
- ...chatSessionsOptions(wsId ?? ""),
- enabled: !!wsId,
- });
- // The session the user is reading right now must not count: the thread list
- // renders its row badge as 0 (auto mark-read is about to clear it), and a
- // reply landing in the open conversation would otherwise flash a sidebar
- // count with no matching row. "Reading right now" = a session is active, a
- // chat surface is actually showing it (chat page route or the floating
- // window), AND the app is in the foreground. When the app is backgrounded,
- // auto mark-read is suppressed (MUL-4485) so the reply stays unread — the
- // badge must count it, or the notification is silently eaten while the user
- // is away. A remembered selection while both surfaces are closed also still
- // counts, for the same reason.
- const activeChatSessionId = useChatStore((s) => s.activeSessionId);
- const floatingChatOpen = useChatStore((s) => s.isOpen);
- const appForeground = useAppForeground();
- const chatHref = p.chat();
- const viewedChatSessionId =
- appForeground && (floatingChatOpen || isNavActive(pathname, chatHref))
- ? activeChatSessionId
- : null;
- const chatUnreadCount = React.useMemo(
- () => countUnreadChatMessages(chatSessions, viewedChatSessionId),
- [chatSessions, viewedChatSessionId],
- );
- // Cross-workspace unread summary backs the workspace-switcher dot. One
- // shared cache entry across workspaces; gated on an active workspace since
- // the endpoint resolves through the workspace-member middleware.
- const { data: unreadSummary = EMPTY_INBOX_SUMMARY } = useQuery({
- ...inboxUnreadSummaryOptions(),
- enabled: inboxUnreadSummaryEnabled(wsId),
- });
- const otherWorkspaceUnread = React.useMemo(
- () => hasOtherWorkspaceUnread(unreadSummary, wsId),
- [unreadSummary, wsId],
- );
- // Which workspaces have unread, so the switcher dropdown can point at the
- // specific one(s) rather than just the aggregate avatar dot.
- const unreadWsIds = React.useMemo(() => unreadWorkspaceIds(unreadSummary), [unreadSummary]);
- const { data: pinnedItems = EMPTY_PINS } = useQuery({
- ...pinListOptions(wsId ?? "", userId ?? ""),
- enabled: !!wsId && !!userId,
- });
- const deletePin = useDeletePin();
- const reorderPins = useReorderPins();
- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
- const sidebarScrollRef = useRef<HTMLDivElement>(null);
- const sidebarFadeStyle = useScrollFade(sidebarScrollRef, 24);
- const getPinHref = useCallback(
- (pin: PinnedItem) =>
- pin.item_type === "issue"
- ? p.issueDetail(pin.item_id)
- : pin.item_type === "project"
- ? p.projectDetail(pin.item_id)
- // Views know their target only after their detail loads — the row
- // resolves its own href; this placeholder never renders as a link.
- : "",
- [p],
- );
-
- // Local presentational copy of pinnedItems for drop-animation stability.
- // Follows TQ at rest; frozen during a drag gesture so a mid-drag cache
- // write (our own optimistic update, or a WS refetch) cannot reorder the
- // DOM under dnd-kit while its drop animation is still interpolating.
- const [localPinned, setLocalPinned] = useState<PinnedItem[]>(pinnedItems);
- const [localPinnedWsId, setLocalPinnedWsId] = useState<string | null>(wsId ?? null);
- const [expandedPinsWorkspaceId, setExpandedPinsWorkspaceId] = useState<string | null>(null);
- const isDraggingRef = useRef(false);
- useEffect(() => {
- if (!isDraggingRef.current) {
- setLocalPinned(pinnedItems);
- }
- }, [pinnedItems]);
- useEffect(() => {
- setLocalPinnedWsId(wsId ?? null);
- }, [wsId]);
- const visiblePinned = localPinnedWsId === (wsId ?? null) ? localPinned : EMPTY_PINS;
- const pinsExpanded = expandedPinsWorkspaceId === wsId;
- const displayedPinned = pinsExpanded ? visiblePinned : visiblePinned.slice(0, PINNED_PREVIEW_LIMIT);
- // View pins are absent here (their href resolves async): while a view
- // pin is active the plain nav row for its surface stays highlighted too.
- // Accepted — suppressing it would need every view detail lifted up here.
- const isActivePinnedRoute = displayedPinned.some((pin) => pathname === getPinHref(pin));
-
- const handleDragStart = useCallback(() => {
- isDraggingRef.current = true;
- }, []);
- const handleDragEnd = useCallback(
- (event: DragEndEvent) => {
- isDraggingRef.current = false;
- const { active, over } = event;
- if (!over || active.id === over.id) return;
- const oldIndex = localPinned.findIndex((p) => p.id === active.id);
- const newIndex = localPinned.findIndex((p) => p.id === over.id);
- if (oldIndex === -1 || newIndex === -1) return;
- const reordered = arrayMove(localPinned, oldIndex, newIndex);
- setLocalPinned(reordered);
- reorderPins.mutate(reordered);
- },
- [localPinned, reorderPins],
- );
-
- const queryClient = useQueryClient();
- const acceptInvitationMut = useMutation({
- mutationFn: (id: string) => api.acceptInvitation(id),
- // After accepting an invitation, navigate INTO the newly-joined workspace.
- // Otherwise the user stays on their current workspace and just sees the
- // new one appear in the dropdown — silent and confusing (this is MUL-820).
- onSuccess: async (_, invitationId) => {
- const invitation = myInvitations.find((i) => i.id === invitationId);
- queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
- // staleTime: 0 forces a real network fetch — we need the joined workspace
- // in the list before we can resolve its slug for navigation.
- const list = await queryClient.fetchQuery({
- ...workspaceListOptions(),
- staleTime: 0,
- });
- const joined = invitation
- ? list.find((w) => w.id === invitation.workspace_id)
- : null;
- if (joined) {
- push(paths.workspace(joined.slug).issues());
- }
- },
- onError: () => {
- // "invitation is not pending" means the invite was concluded from
- // another surface while this row was on screen. Refetch so the stale
- // row drops instead of sticking around until restart — a silent
- // failure here reads as "the button does nothing".
- queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
- },
- });
- const declineInvitationMut = useMutation({
- mutationFn: (id: string) => api.declineInvitation(id),
- // Either outcome must refresh the list: success drops the declined row,
- // and a failure ("invitation is not pending") means the invite was
- // concluded from another surface — refetch drops the stale row.
- onSettled: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
- },
- });
-
- const createIssueShortcut = useShortcut("createIssue");
-
- return (
- <RouteDataPrefetch wsId={wsId} userId={userId ?? null}>
- <Sidebar variant="inset">
- {topSlot}
- {/* Workspace Switcher */}
- <SidebarHeader className={cn("py-3", headerClassName)} style={headerStyle}>
- <SidebarMenu>
- <SidebarMenuItem>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <SidebarMenuButton>
- <span className="relative">
- <WorkspaceAvatar name={workspace?.name ?? "M"} avatarUrl={workspace?.avatar_url} size="sm" />
- {/* Shared brand dot: a pending invitation OR another
- workspace with unread inbox items. The active
- workspace's own unread stays on the Inbox nav count
- (below), so it is deliberately excluded here. */}
- {(myInvitations.length > 0 || otherWorkspaceUnread) && (
- <span className="absolute -top-0.5 -right-0.5 size-2 rounded-full bg-brand ring-1 ring-sidebar" />
- )}
- </span>
- <span className="flex-1 truncate font-medium">
- {workspace?.name ?? "Multica"}
- </span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </SidebarMenuButton>
- }
- />
- <DropdownMenuContent
- className="w-auto min-w-56"
- align="start"
- side="bottom"
- sideOffset={4}
- >
- <div className="flex items-center gap-2.5 px-2 py-1.5">
- <ActorAvatar
- name={user?.name ?? ""}
- initials={(user?.name ?? "U").charAt(0).toUpperCase()}
- avatarUrl={resolvePublicFileUrl(user?.avatar_url)}
- size="lg"
- />
- <div className="min-w-0 flex-1">
- <p className="truncate text-body font-medium leading-tight">
- {user?.name}
- </p>
- <p className="truncate text-caption text-muted-foreground leading-tight">
- {user?.email}
- </p>
- </div>
- </div>
- <DropdownMenuSeparator />
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-caption text-muted-foreground">
- {t(($) => $.sidebar.workspaces_label)}
- </DropdownMenuLabel>
- {workspaces.map((ws) => (
- <DropdownMenuItem
- key={ws.id}
- render={
- <AppLink href={paths.workspace(ws.slug).issues()} />
- }
- >
- <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />
- <span className="flex-1 truncate">{ws.name}</span>
- {/* Points at the specific workspace holding unread
- inbox items. Sits in the same right-edge slot as the
- active-workspace check; the active workspace is
- excluded (its unread is the Inbox nav count), so dot
- and check never collide on one row. */}
- {ws.id !== workspace?.id && unreadWsIds.has(ws.id) && (
- <span className="size-2 rounded-full bg-brand" />
- )}
- {ws.id === workspace?.id && (
- <Check className="h-3.5 w-3.5 text-primary" />
- )}
- </DropdownMenuItem>
- ))}
- {!workspaceCreationDisabled && (
- <DropdownMenuItem
- onClick={() => push(paths.newWorkspace())}
- >
- <Plus className="h-3.5 w-3.5" />
- {t(($) => $.sidebar.create_workspace)}
- </DropdownMenuItem>
- )}
- </DropdownMenuGroup>
- {myInvitations.length > 0 && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-caption text-muted-foreground">
- {t(($) => $.sidebar.pending_invitations_label)}
- </DropdownMenuLabel>
- {myInvitations.map((inv) => (
- <div key={inv.id} className="flex items-center gap-2 px-2 py-1.5">
- <WorkspaceAvatar name={inv.workspace_name ?? "W"} size="sm" />
- <span className="flex-1 truncate text-body">{inv.workspace_name ?? t(($) => $.sidebar.invitation_workspace_fallback)}</span>
- <button
- type="button"
- className="text-caption px-2 py-0.5 rounded-xs bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
- disabled={acceptInvitationMut.isPending}
- onClick={(e) => {
- e.stopPropagation();
- acceptInvitationMut.mutate(inv.id);
- }}
- >
- {t(($) => $.sidebar.invitation_join)}
- </button>
- <button
- type="button"
- className="text-caption px-2 py-0.5 rounded-xs bg-muted text-muted-foreground hover:bg-muted/80 disabled:opacity-50"
- disabled={declineInvitationMut.isPending}
- onClick={(e) => {
- e.stopPropagation();
- declineInvitationMut.mutate(inv.id);
- }}
- >
- {t(($) => $.sidebar.invitation_decline)}
- </button>
- </div>
- ))}
- </DropdownMenuGroup>
- </>
- )}
- <DropdownMenuSeparator />
- <DropdownMenuGroup>
- <DropdownMenuItem variant="destructive" onClick={logout}>
- <LogOut className="h-3.5 w-3.5" />
- {t(($) => $.sidebar.log_out)}
- </DropdownMenuItem>
- </DropdownMenuGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- </SidebarMenuItem>
- </SidebarMenu>
- <SidebarMenu>
- {searchSlot && (
- <SidebarMenuItem>
- {searchSlot}
- </SidebarMenuItem>
- )}
- <SidebarMenuItem>
- <SidebarMenuButton
- className="text-muted-foreground"
- onClick={() => openCreateIssueWithPreference()}
- >
- <span className="relative">
- <SquarePen />
- <DraftDot />
- </span>
- <span>{t(($) => $.sidebar.new_issue)}</span>
- {createIssueShortcut ? (
- <ShortcutKeycaps shortcut={createIssueShortcut} decorative className="pointer-events-none ml-auto" />
- ) : null}
- </SidebarMenuButton>
- </SidebarMenuItem>
- </SidebarMenu>
- </SidebarHeader>
-
- {/* Navigation */}
- <SidebarContent ref={sidebarScrollRef} style={sidebarFadeStyle}>
- <SidebarGroup>
- <SidebarGroupContent>
- <SidebarMenu className="gap-0.5">
- {personalNav.map((item) => {
- const href = p[item.key]();
- const Icon = routeIconForPath(href);
- const isActive = isNavActive(pathname, href);
- return (
- <SidebarMenuItem key={item.key}>
- <SidebarMenuButton
- isActive={isActive}
- render={<AppLink href={href} />}
- className={NAV_ITEM_CLASS_NAME}
- >
- <Icon />
- <span>{t(($) => $.nav[item.labelKey])}</span>
- {item.key === "inbox" && unreadCount > 0 && (
- <CappedNumberFlow
- value={unreadCount}
- animated={false}
- className="ml-auto text-caption"
- />
- )}
- {item.key === "chat" && chatUnreadCount > 0 && (
- <CappedNumberFlow
- value={chatUnreadCount}
- animated={false}
- className="ml-auto text-caption"
- />
- )}
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
-
- {visiblePinned.length > 0 && (
- <Collapsible defaultOpen>
- <SidebarGroup className="group/pinned">
- <SidebarGroupLabel
- render={<CollapsibleTrigger />}
- className="group/trigger cursor-pointer hover:bg-sidebar-accent/70 hover:text-sidebar-accent-foreground"
- >
- <span>{t(($) => $.sidebar.pinned_label)}</span>
- <ChevronRight className="!size-3 ml-1 stroke-[2.5] transition-transform duration-200 group-data-[panel-open]/trigger:rotate-90" />
- <span className="ml-auto text-micro text-muted-foreground opacity-0 transition-opacity group-hover/pinned:opacity-100">{visiblePinned.length}</span>
- </SidebarGroupLabel>
- <CollapsibleContent>
- <SidebarGroupContent>
- <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
- <SortableContext items={displayedPinned.map((p) => p.id)} strategy={verticalListSortingStrategy}>
- <SidebarMenu className="gap-0.5">
- {displayedPinned.map((pin: PinnedItem) => (
- <PinRow
- key={pin.id}
- pin={pin}
- href={getPinHref(pin)}
- pathname={pathname}
- onUnpin={() => deletePin.mutate({ itemType: pin.item_type, itemId: pin.item_id })}
- wsId={wsId ?? ""}
- />
- ))}
- </SidebarMenu>
- </SortableContext>
- </DndContext>
- {visiblePinned.length > PINNED_PREVIEW_LIMIT && (
- <SidebarMenuButton
- size="sm"
- aria-expanded={pinsExpanded}
- className="mt-0.5 pl-7 text-muted-foreground"
- onClick={() => setExpandedPinsWorkspaceId(pinsExpanded ? null : wsId ?? null)}
- >
- <span>
- {pinsExpanded
- ? t(($) => $.sidebar.show_fewer_pins)
- : t(($) => $.sidebar.show_more_pins, { count: visiblePinned.length - PINNED_PREVIEW_LIMIT })}
- </span>
- </SidebarMenuButton>
- )}
- </SidebarGroupContent>
- </CollapsibleContent>
- </SidebarGroup>
- </Collapsible>
- )}
-
- <SidebarGroup>
- <SidebarGroupLabel>{t(($) => $.sidebar.work_group)}</SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu className="gap-0.5">
- {workNav.map((item) => {
- const href = p[item.key]();
- const Icon = routeIconForPath(href);
- const isActive = !isActivePinnedRoute && isNavActive(pathname, href);
- return (
- <SidebarMenuItem key={item.key}>
- <SidebarMenuButton
- isActive={isActive}
- render={<AppLink href={href} />}
- className={NAV_ITEM_CLASS_NAME}
- >
- <Icon />
- <span>{t(($) => $.nav[item.labelKey])}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
-
- <SidebarGroup>
- <SidebarGroupLabel>{t(($) => $.sidebar.ai_team_group)}</SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu className="gap-0.5">
- {aiTeamNav.map((item) => {
- const href = p[item.key]();
- const Icon = routeIconForPath(href);
- const isActive = isNavActive(pathname, href);
- return (
- <SidebarMenuItem key={item.key}>
- <SidebarMenuButton
- isActive={isActive}
- render={<AppLink href={href} />}
- className={NAV_ITEM_CLASS_NAME}
- >
- <Icon />
- <span>{t(($) => $.nav[item.labelKey])}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- </SidebarContent>
-
- <SidebarFooter className="p-2">
- <SidebarMenu className="gap-0.5">
- {utilityNav.map((item) => {
- const href = p[item.key]();
- const Icon = routeIconForPath(href);
- return (
- <SidebarMenuItem key={item.key}>
- <SidebarMenuButton
- isActive={isNavActive(pathname, href)}
- render={<AppLink href={href} />}
- className={NAV_ITEM_CLASS_NAME}
- >
- <Icon />
- <span>{t(($) => $.nav[item.labelKey])}</span>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
- </SidebarMenu>
- {/* Discord fills the strip while visible; once dismissed, help
- aligns with the navigation icons above. */}
- <div className="flex items-center gap-1">
- <JoinDiscordCard />
- <HelpLauncher />
- </div>
- </SidebarFooter>
- <SidebarRail />
- </Sidebar>
- </RouteDataPrefetch>
- );
-}
diff --git a/packages/views/layout/collection-list/collection-batch-bar.tsx b/packages/views/layout/collection-list/collection-batch-bar.tsx
new file mode 100644
index 0000000000..30d2190ad0
--- /dev/null
+++ b/packages/views/layout/collection-list/collection-batch-bar.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+import { X } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { UI_EASE_OUT, UI_MOTION_DURATION } from "@multica/ui/lib/motion";
+import { useT } from "../../i18n";
+
+/**
+ * Floating bar for actions on the selected rows. `absolute` centres it on the
+ * nearest positioned ancestor (the page root, so a sidebar or split pane does
+ * not pull it off the list's centre); `fixed` centres it on the viewport;
+ * `inline` leaves it in flow.
+ */
+export function CollectionBatchBar({
+ count,
+ onClear,
+ placement = "absolute",
+ label,
+ children,
+}: {
+ count: number;
+ onClear: () => void;
+ placement?: "absolute" | "fixed" | "inline";
+ /** Overrides the "N selected" text. */
+ label?: ReactNode;
+ children: ReactNode;
+}) {
+ const { t } = useT("layout");
+ const reduceMotion = useReducedMotion() ?? false;
+ const offset = reduceMotion ? "translateY(0)" : "translateY(8px)";
+
+ return (
+ <AnimatePresence initial={false}>
+ {count > 0 && (
+ <div
+ key="collection-batch-bar"
+ className={cn(
+ "z-50",
+ placement === "inline"
+ ? "mb-2 w-fit"
+ : "bottom-6 left-1/2 -translate-x-1/2 max-md:above-chat-launcher",
+ placement === "absolute" && "absolute",
+ placement === "fixed" && "fixed",
+ )}
+ >
+ <motion.div
+ role="toolbar"
+ aria-label={t(($) => $.collection.selected, { count })}
+ className="flex items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg"
+ initial={{ opacity: 0, transform: offset }}
+ animate={{
+ opacity: 1,
+ transform: "translateY(0)",
+ transition: { duration: UI_MOTION_DURATION.fast, ease: UI_EASE_OUT },
+ }}
+ exit={{
+ opacity: 0,
+ transform: offset,
+ transition: {
+ duration: reduceMotion ? UI_MOTION_DURATION.fast : UI_MOTION_DURATION.micro,
+ ease: UI_EASE_OUT,
+ },
+ }}
+ >
+ <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">
+ <span className="whitespace-nowrap text-body font-medium">
+ {label ?? t(($) => $.collection.selected, { count })}
+ </span>
+ <TooltipHint label={t(($) => $.collection.clear_selection)}>
+ <button
+ type="button"
+ aria-label={t(($) => $.collection.clear_selection)}
+ onClick={onClear}
+ className="rounded-xs p-0.5 transition-colors hover:bg-accent"
+ >
+ <X className="size-3.5 text-muted-foreground" />
+ </button>
+ </TooltipHint>
+ </div>
+ {children}
+ </motion.div>
+ </div>
+ )}
+ </AnimatePresence>
+ );
+}
diff --git a/packages/views/layout/collection-list/collection-cells.tsx b/packages/views/layout/collection-list/collection-cells.tsx
new file mode 100644
index 0000000000..00b81cf141
--- /dev/null
+++ b/packages/views/layout/collection-list/collection-cells.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { cn } from "@multica/ui/lib/utils";
+
+/**
+ * The primary cell: leading icon, name, inline badges, then the description
+ * in muted text filling whatever width is left — one line, never two.
+ */
+export function CollectionNameCell({
+ icon,
+ title,
+ badges,
+ description,
+ trailing,
+ muted = false,
+ className,
+}: {
+ icon?: ReactNode;
+ title: ReactNode;
+ badges?: ReactNode;
+ description?: ReactNode;
+ trailing?: ReactNode;
+ muted?: boolean;
+ className?: string;
+}) {
+ return (
+ <span className={cn("flex min-w-0 flex-1 items-center gap-2 whitespace-nowrap", className)}>
+ {icon}
+ <span
+ className={cn(
+ "min-w-0 truncate font-medium",
+ muted && "text-muted-foreground",
+ )}
+ >
+ {title}
+ </span>
+ {badges}
+ {description ? (
+ <span className="min-w-0 flex-1 basis-0 truncate text-muted-foreground">
+ {description}
+ </span>
+ ) : (
+ <span className="flex-1" />
+ )}
+ {trailing}
+ </span>
+ );
+}
+
+/** Small inline tag after a name ("You", "Archived"). */
+export function CollectionTag({ children }: { children: ReactNode }) {
+ return (
+ <span className="shrink-0 rounded-xs bg-muted px-1 text-micro font-medium leading-4 text-muted-foreground">
+ {children}
+ </span>
+ );
+}
+
+/** Placeholder for an empty cell. */
+export function CollectionEmptyValue() {
+ return <span className="text-faint-foreground">—</span>;
+}
diff --git a/packages/views/layout/collection-list/collection-display-menu.tsx b/packages/views/layout/collection-list/collection-display-menu.tsx
new file mode 100644
index 0000000000..5732a9a147
--- /dev/null
+++ b/packages/views/layout/collection-list/collection-display-menu.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import type { ComponentProps, ReactNode } from "react";
+import { ArrowDown, ArrowUp, ChevronDown } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
+import { Switch } from "@multica/ui/components/ui/switch";
+import { useT } from "../../i18n";
+import { CollectionDisplayButton } from "../collection-page";
+import type { CollectionColumn, CollectionSort } from "./collection-list";
+
+/**
+ * Display settings derived from the list's own column definitions: every
+ * column with a `sortKey` is a sort option, every `hideable` column gets a
+ * switch. `extra` renders above both (e.g. a view-mode toggle).
+ */
+export function CollectionDisplayMenu<T>({
+ columns,
+ hiddenColumns,
+ onToggleColumn,
+ sort,
+ showColumns = true,
+ extra,
+ triggerIcon,
+}: {
+ columns: readonly CollectionColumn<T>[];
+ hiddenColumns?: readonly string[];
+ onToggleColumn?: (key: string) => void;
+ sort?: CollectionSort;
+ /** Off when the current view has no columns (e.g. a card grid). */
+ showColumns?: boolean;
+ extra?: ReactNode;
+ triggerIcon?: ComponentProps<typeof CollectionDisplayButton>["icon"];
+}) {
+ const { t } = useT("layout");
+ const sortOptions = columns.flatMap((col) =>
+ col.sortKey && col.header ? [{ value: col.sortKey, label: col.header }] : [],
+ );
+ const toggles =
+ showColumns && onToggleColumn
+ ? columns.filter((col, i) => i > 0 && col.hideable && col.header)
+ : [];
+ const activeSort = sort ? sortOptions.find((o) => o.value === sort.field) : undefined;
+
+ return (
+ <Popover>
+ <PopoverTrigger render={<CollectionDisplayButton icon={triggerIcon} />} />
+ <PopoverContent align="end" className="w-64 p-0">
+ {extra ? <div className="border-b px-3 py-2.5 last:border-b-0">{extra}</div> : null}
+ {sort && sortOptions.length > 0 ? (
+ <div className="border-b px-3 py-2.5 last:border-b-0">
+ <span className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.collection.sort_by)}
+ </span>
+ <div className="mt-2 flex items-center gap-1.5">
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ className="flex-1 justify-between text-caption"
+ >
+ {activeSort?.label ?? sort.field}
+ <ChevronDown className="size-3 text-muted-foreground" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="start" className="w-auto">
+ <DropdownMenuRadioGroup
+ value={sort.field}
+ onValueChange={(value) =>
+ (sort.onFieldChange ?? sort.onToggle)(value as string)
+ }
+ >
+ {sortOptions.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {sort.onDirectionChange ? (
+ <IconButton
+ variant="outline"
+ size="icon-sm"
+ onClick={() =>
+ sort.onDirectionChange?.(sort.direction === "asc" ? "desc" : "asc")
+ }
+ label={
+ sort.direction === "asc"
+ ? t(($) => $.collection.direction_asc)
+ : t(($) => $.collection.direction_desc)
+ }
+ >
+ {sort.direction === "asc" ? (
+ <ArrowUp className="size-3.5" />
+ ) : (
+ <ArrowDown className="size-3.5" />
+ )}
+ </IconButton>
+ ) : null}
+ </div>
+ </div>
+ ) : null}
+ {toggles.length > 0 ? (
+ <div className="px-3 py-2.5">
+ <span className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.collection.section_columns)}
+ </span>
+ <div className="mt-2 space-y-2">
+ {toggles.map((col) => (
+ <label
+ key={col.key}
+ className="flex cursor-pointer items-center justify-between"
+ >
+ <span className="text-body">{col.header}</span>
+ <Switch
+ size="sm"
+ checked={!hiddenColumns?.includes(col.key)}
+ onCheckedChange={() => onToggleColumn?.(col.key)}
+ />
+ </label>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/views/layout/collection-list/collection-list.tsx b/packages/views/layout/collection-list/collection-list.tsx
new file mode 100644
index 0000000000..2280ff8fe5
--- /dev/null
+++ b/packages/views/layout/collection-list/collection-list.tsx
@@ -0,0 +1,917 @@
+"use client";
+
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type MouseEvent as ReactMouseEvent,
+ type ReactNode,
+} from "react";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { ArrowDown, ArrowUp, Loader2 } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { cn } from "@multica/ui/lib/utils";
+import {
+ isEditableShortcutTarget,
+ isPortalLayerShortcutTarget,
+} from "@multica/core/shortcuts";
+import { useModalStore } from "@multica/core/modals";
+import { useIntentNavigate, useRowLink } from "../../navigation";
+import { useT } from "../../i18n";
+import { CollectionRowContext, type RowMenuState } from "./row-context";
+
+export type CollectionSortDirection = "asc" | "desc";
+
+export interface CollectionColumn<T> {
+ key: string;
+ /** Header label; also the column's name in the Display menu. */
+ header?: string;
+ /** Track width in px. The first column is the primary column: it takes the
+ * remaining space, and `width` is its minimum on wide layouts. */
+ width?: number;
+ align?: "start" | "end";
+ /** Sort field this column's header toggles. */
+ sortKey?: string;
+ /** Stays visible below the wide breakpoint (the primary column always does). */
+ core?: boolean;
+ /** Listed in the Display menu's column switches. */
+ hideable?: boolean;
+ /** Holds its own controls: clicks inside never activate the row. */
+ interactive?: boolean;
+ className?: string;
+ cell: (row: T) => ReactNode;
+}
+
+export interface CollectionSort<S extends string = string> {
+ field: S;
+ direction: CollectionSortDirection;
+ /** Header click: flips direction on the active field, else switches field. */
+ onToggle: (field: S) => void;
+ onFieldChange?: (field: S) => void;
+ onDirectionChange?: (direction: CollectionSortDirection) => void;
+}
+
+export interface CollectionSelection<T> {
+ selectedIds: ReadonlySet<string>;
+ onChange: (next: ReadonlySet<string>) => void;
+ isSelectable?: (row: T) => boolean;
+ /** Accessible name of a row's checkbox; defaults to "Select row". */
+ getLabel?: (row: T) => string;
+ /** Accessible name of the header checkbox; defaults to "Select all". */
+ allLabel?: string;
+}
+
+export interface CollectionGroup<T> {
+ key: string;
+ label: ReactNode;
+ count?: number;
+ actions?: ReactNode;
+ rows: readonly T[];
+}
+
+export interface CollectionListProps<T> {
+ /** Accessible name of the grid. */
+ label: string;
+ columns: readonly CollectionColumn<T>[];
+ hiddenColumns?: readonly string[];
+ rows?: readonly T[];
+ /** Grouped rows render as bands; takes precedence over `rows`. */
+ groups?: readonly CollectionGroup<T>[];
+ getRowId: (row: T) => string;
+ getRowHref?: (row: T) => string | null | undefined;
+ /** Tab title for new-tab opens. */
+ getRowTitle?: (row: T) => string | undefined;
+ /** Runs right before an in-place navigation to the row's href. */
+ onRowNavigate?: (row: T) => void;
+ /** Activation for rows without an href. */
+ onRowOpen?: (row: T) => void;
+ /** One menu for both the ⋯ button and right-click (see CollectionRowMenu). */
+ rowMenu?: (row: T) => ReactNode;
+ getRowClassName?: (row: T) => string | undefined;
+ sort?: CollectionSort;
+ selection?: CollectionSelection<T>;
+ loading?: boolean;
+ /** Shown in place of rows when there are none. */
+ empty?: ReactNode;
+ hasMore?: boolean;
+ loadingMore?: boolean;
+ onLoadMore?: () => void;
+ /** Renders inside the page's own scroller instead of owning one. */
+ embedded?: boolean;
+ /** J/K and arrows reach the list while nothing else has focus. */
+ pageShortcuts?: boolean;
+ className?: string;
+}
+
+const EDGE = 4;
+const SLOT = 16;
+const MENU = 24;
+const GAP = 12;
+const PAD = 8;
+const ROW_HEIGHT = 36;
+const HEADER_HEIGHT = 36;
+const GROUP_HEIGHT = 50;
+const PRIMARY_MIN = 200;
+const DEFAULT_WIDTH = 120;
+const VIRTUALIZE_AFTER = 80;
+
+const noop = () => {};
+
+type Item<T> =
+ | { kind: "group"; group: CollectionGroup<T> }
+ | { kind: "row"; row: T; index: number };
+
+function gridTemplate<T>(
+ columns: readonly CollectionColumn<T>[],
+ { wide, selectable, menu }: { wide: boolean; selectable: boolean; menu: boolean },
+) {
+ const tracks = [`${EDGE}px`];
+ if (selectable && wide) tracks.push(`${SLOT}px`);
+ columns.forEach((col, i) => {
+ if (i === 0) tracks.push(wide ? `minmax(${col.width ?? PRIMARY_MIN}px,1fr)` : "minmax(0,1fr)");
+ else if (wide || col.core) tracks.push(`${col.width ?? DEFAULT_WIDTH}px`);
+ });
+ if (menu) tracks.push(`${MENU}px`);
+ tracks.push(`${EDGE}px`);
+ return tracks;
+}
+
+function minWidth(tracks: string[]) {
+ let px = PAD * 2 + GAP * (tracks.length - 1);
+ for (const track of tracks) {
+ const match = /^(?:minmax\()?(\d+)px/.exec(track);
+ px += match ? Number(match[1]) : 0;
+ }
+ return px;
+}
+
+function isImeKey(e: KeyboardEvent | ReactKeyboardEvent) {
+ const native = "nativeEvent" in e ? e.nativeEvent : e;
+ return native.isComposing || native.keyCode === 229;
+}
+
+export function CollectionList<T>({
+ label,
+ columns: allColumns,
+ hiddenColumns,
+ rows: plainRows,
+ groups,
+ getRowId,
+ getRowHref,
+ getRowTitle,
+ onRowNavigate,
+ onRowOpen,
+ rowMenu,
+ getRowClassName,
+ sort,
+ selection,
+ loading = false,
+ empty,
+ hasMore = false,
+ loadingMore = false,
+ onLoadMore,
+ embedded = false,
+ pageShortcuts = !embedded,
+ className,
+}: CollectionListProps<T>) {
+ const { t } = useT("layout");
+ const listId = useId();
+ const rowLink = useRowLink();
+ const intentNavigate = useIntentNavigate();
+ const scrollRef = useRef<HTMLDivElement | null>(null);
+ const gridRef = useRef<HTMLDivElement | null>(null);
+
+ const columns = useMemo(
+ () =>
+ allColumns.filter(
+ (col, i) => i === 0 || !col.hideable || !hiddenColumns?.includes(col.key),
+ ),
+ [allColumns, hiddenColumns],
+ );
+
+ const items = useMemo<Item<T>[]>(() => {
+ const out: Item<T>[] = [];
+ let index = 0;
+ if (groups) {
+ for (const group of groups) {
+ out.push({ kind: "group", group });
+ for (const row of group.rows) out.push({ kind: "row", row, index: index++ });
+ }
+ } else {
+ for (const row of plainRows ?? []) out.push({ kind: "row", row, index: index++ });
+ }
+ return out;
+ }, [groups, plainRows]);
+
+ const flatRows = useMemo(
+ () =>
+ items.flatMap((item) => (item.kind === "row" ? [item.row] : [])),
+ [items],
+ );
+ const rowIds = useMemo(() => flatRows.map(getRowId), [flatRows, getRowId]);
+ const itemIndexById = useMemo(() => {
+ const map = new Map<string, number>();
+ items.forEach((item, i) => {
+ if (item.kind === "row") map.set(getRowId(item.row), i);
+ });
+ return map;
+ }, [items, getRowId]);
+
+ const selectable = !!selection;
+ const hasMenu = !!rowMenu;
+ const wideTracks = gridTemplate(columns, { wide: true, selectable, menu: hasMenu });
+ const narrowTracks = gridTemplate(columns, { wide: false, selectable, menu: hasMenu });
+ const gridStyle = {
+ "--cl-wide": wideTracks.join(" "),
+ "--cl-narrow": narrowTracks.join(" "),
+ "--cl-minw": `${minWidth(wideTracks)}px`,
+ } as CSSProperties;
+
+ const virtualize = !embedded && !loading && items.length > VIRTUALIZE_AFTER;
+ const virtualizer = useVirtualizer({
+ count: virtualize ? items.length : 0,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: (i) => (items[i]?.kind === "group" ? GROUP_HEIGHT : ROW_HEIGHT),
+ paddingStart: HEADER_HEIGHT,
+ scrollPaddingStart: HEADER_HEIGHT,
+ overscan: 12,
+ });
+
+ // Selection
+ const anchorRef = useRef<string | null>(null);
+ const selectedIds = selection?.selectedIds;
+ const isSelectable = useCallback(
+ (row: T) => selection?.isSelectable?.(row) ?? true,
+ [selection],
+ );
+ const selectableIds = useMemo(
+ () => (selection ? flatRows.filter(isSelectable).map(getRowId) : []),
+ [selection, flatRows, isSelectable, getRowId],
+ );
+ const selectedVisible = selectedIds
+ ? selectableIds.filter((id) => selectedIds.has(id)).length
+ : 0;
+ const allSelected = selectableIds.length > 0 && selectedVisible === selectableIds.length;
+ const anySelected = (selectedIds?.size ?? 0) > 0;
+
+ const toggleRow = useCallback(
+ (id: string, range: boolean) => {
+ if (!selection) return;
+ const next = new Set(selection.selectedIds);
+ const anchor = anchorRef.current;
+ if (range && anchor && anchor !== id) {
+ const a = rowIds.indexOf(anchor);
+ const b = rowIds.indexOf(id);
+ if (a >= 0 && b >= 0) {
+ const [from, to] = a < b ? [a, b] : [b, a];
+ for (let i = from; i <= to; i++) {
+ const rowId = rowIds[i];
+ const row = flatRows[i];
+ if (rowId && row && isSelectable(row)) next.add(rowId);
+ }
+ selection.onChange(next);
+ return;
+ }
+ }
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ anchorRef.current = id;
+ selection.onChange(next);
+ },
+ [selection, rowIds, flatRows, isSelectable],
+ );
+
+ const toggleAll = useCallback(() => {
+ if (!selection) return;
+ selection.onChange(allSelected ? new Set() : new Set(selectableIds));
+ }, [selection, allSelected, selectableIds]);
+
+ // Keyboard
+ const [activeId, setActiveId] = useState<string | null>(null);
+ const [showActive, setShowActive] = useState(false);
+ const activeIndex = activeId ? rowIds.indexOf(activeId) : -1;
+
+ const scrollToRow = useCallback(
+ (id: string) => {
+ if (virtualize) {
+ const itemIndex = itemIndexById.get(id);
+ if (itemIndex !== undefined) virtualizer.scrollToIndex(itemIndex, { align: "auto" });
+ return;
+ }
+ const el = document.getElementById(`${listId}-row-${id}`);
+ el?.scrollIntoView?.({ block: "nearest" });
+ },
+ [virtualize, itemIndexById, virtualizer, listId],
+ );
+
+ const openRow = useCallback(
+ (row: T, newTab: boolean) => {
+ const href = getRowHref?.(row);
+ if (href) {
+ if (!newTab) onRowNavigate?.(row);
+ intentNavigate(href, newTab ? "foreground-tab" : "push", getRowTitle?.(row));
+ return;
+ }
+ onRowOpen?.(row);
+ },
+ [getRowHref, getRowTitle, intentNavigate, onRowNavigate, onRowOpen],
+ );
+
+ const handleKey = useCallback(
+ (e: KeyboardEvent | ReactKeyboardEvent, onGrid: boolean): boolean => {
+ const mod = e.metaKey || e.ctrlKey;
+ const n = rowIds.length;
+ const move = (delta: number) => {
+ if (n === 0) return;
+ const from = activeIndex < 0 ? (delta > 0 ? -1 : n) : activeIndex;
+ const next = Math.min(n - 1, Math.max(0, from + delta));
+ const id = rowIds[next]!;
+ if (e.shiftKey && selection) {
+ const fromId = activeId ?? id;
+ if (!anchorRef.current) anchorRef.current = fromId;
+ const a = rowIds.indexOf(anchorRef.current);
+ const [lo, hi] = a < next ? [a, next] : [next, a];
+ const nextSel = new Set(selection.selectedIds);
+ for (let i = lo; i <= hi; i++) {
+ const row = flatRows[i];
+ if (row && isSelectable(row)) nextSel.add(rowIds[i]!);
+ }
+ selection.onChange(nextSel);
+ }
+ setActiveId(id);
+ setShowActive(true);
+ scrollToRow(id);
+ };
+ if (e.altKey) return false;
+ switch (e.key) {
+ case "ArrowDown":
+ case "j":
+ case "J":
+ if (mod) return false;
+ move(1);
+ return true;
+ case "ArrowUp":
+ case "k":
+ case "K":
+ if (mod) return false;
+ move(-1);
+ return true;
+ case "Home":
+ if (n === 0) return false;
+ move(-n);
+ return true;
+ case "End":
+ if (n === 0) return false;
+ move(n);
+ return true;
+ case "Enter": {
+ if (!onGrid || activeIndex < 0) return false;
+ const row = flatRows[activeIndex];
+ if (!row) return false;
+ openRow(row, mod);
+ return true;
+ }
+ case "x":
+ case "X": {
+ if (mod || e.shiftKey || !selection || activeIndex < 0) return false;
+ const row = flatRows[activeIndex];
+ if (!row || !isSelectable(row)) return false;
+ toggleRow(rowIds[activeIndex]!, false);
+ setShowActive(true);
+ return true;
+ }
+ case "a":
+ case "A":
+ if (!mod || !selection || selectableIds.length === 0) return false;
+ selection.onChange(new Set(selectableIds));
+ return true;
+ case "Escape":
+ if (selection && selection.selectedIds.size > 0) {
+ selection.onChange(new Set());
+ anchorRef.current = null;
+ return true;
+ }
+ if (activeId) {
+ setActiveId(null);
+ return true;
+ }
+ return false;
+ default:
+ return false;
+ }
+ },
+ [
+ rowIds,
+ activeIndex,
+ activeId,
+ selection,
+ flatRows,
+ isSelectable,
+ scrollToRow,
+ openRow,
+ toggleRow,
+ selectableIds,
+ ],
+ );
+
+ const onGridKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (e.defaultPrevented || isImeKey(e)) return;
+ const target = e.target as Node;
+ if (!e.currentTarget.contains(target)) return;
+ if (isEditableShortcutTarget(e.target)) return;
+ const onGrid = e.target === e.currentTarget;
+ if (handleKey(e, onGrid)) e.preventDefault();
+ };
+
+ const focusGrid = () => gridRef.current?.focus({ preventScroll: true });
+
+ const handleKeyRef = useRef(handleKey);
+ handleKeyRef.current = handleKey;
+ useEffect(() => {
+ if (!pageShortcuts) return;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.repeat || isImeKey(e)) return;
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (!["ArrowDown", "ArrowUp", "j", "k", "J", "K"].includes(e.key)) return;
+ const active = document.activeElement;
+ if (active && active !== document.body) return;
+ if (isPortalLayerShortcutTarget(e.target)) return;
+ if (useModalStore.getState().modal) return;
+ const grid = gridRef.current;
+ if (!grid || grid.getClientRects().length === 0) return;
+ grid.focus({ preventScroll: true });
+ if (handleKeyRef.current(e, true)) e.preventDefault();
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, [pageShortcuts]);
+
+ const renderRow = (row: T) => {
+ const id = getRowId(row);
+ return (
+ <CollectionRow
+ key={id}
+ domId={`${listId}-row-${id}`}
+ row={row}
+ id={id}
+ columns={columns}
+ href={getRowHref?.(row) ?? null}
+ title={getRowTitle?.(row)}
+ onNavigate={onRowNavigate}
+ onOpen={onRowOpen}
+ menu={rowMenu ? rowMenu(row) : undefined}
+ hasMenuSlot={hasMenu}
+ className={getRowClassName?.(row)}
+ rowLink={rowLink}
+ selection={
+ selection
+ ? {
+ selected: selectedIds?.has(id) ?? false,
+ selectable: isSelectable(row),
+ revealed: anySelected,
+ onToggle: (range) => {
+ toggleRow(id, range);
+ focusGrid();
+ },
+ label: selection.getLabel?.(row) ?? t(($) => $.collection.select_row),
+ }
+ : null
+ }
+ rangeSelect={anySelected ? (range) => toggleRow(id, range) : null}
+ active={showActive && activeId === id}
+ onPointerActivate={() => {
+ setActiveId(id);
+ setShowActive(false);
+ }}
+ />
+ );
+ };
+
+ const renderGroup = (group: CollectionGroup<T>) => (
+ <div
+ key={`group:${group.key}`}
+ role="row"
+ className="col-span-full pt-2 pb-0.5"
+ >
+ <div
+ role="rowheader"
+ className="flex h-10 items-center gap-2 rounded-lg bg-muted px-3 text-caption font-semibold"
+ >
+ <span className="min-w-0 truncate">{group.label}</span>
+ {group.count !== undefined ? (
+ <span className="font-normal tabular-nums text-muted-foreground">
+ {group.count}
+ </span>
+ ) : null}
+ {group.actions ? (
+ <span className="ml-auto flex items-center gap-1">{group.actions}</span>
+ ) : null}
+ </div>
+ </div>
+ );
+
+ const renderItem = (item: Item<T>) =>
+ item.kind === "group" ? renderGroup(item.group) : renderRow(item.row);
+
+ let body: ReactNode;
+ if (loading) {
+ body = Array.from({ length: 6 }).map((_, i) => (
+ <SkeletonRow key={i} columns={columns} selectable={selectable} menu={hasMenu} />
+ ));
+ } else if (flatRows.length === 0 && !groups?.length) {
+ body = empty ? (
+ <div className="col-span-full py-16 text-center text-body text-muted-foreground">
+ {empty}
+ </div>
+ ) : null;
+ } else if (virtualize) {
+ const virtualItems = virtualizer.getVirtualItems();
+ const first = virtualItems[0];
+ const last = virtualItems[virtualItems.length - 1];
+ const top = first ? first.start - HEADER_HEIGHT : 0;
+ const bottom = last ? virtualizer.getTotalSize() - last.end : 0;
+ body = (
+ <>
+ {top > 0 ? <div aria-hidden className="col-span-full" style={{ height: top }} /> : null}
+ {virtualItems.map((vi) => {
+ const item = items[vi.index];
+ return item ? renderItem(item) : null;
+ })}
+ {bottom > 0 ? (
+ <div aria-hidden className="col-span-full" style={{ height: bottom }} />
+ ) : null}
+ </>
+ );
+ } else {
+ body = items.map(renderItem);
+ }
+
+ const grid = (
+ <div
+ ref={gridRef}
+ role="grid"
+ aria-label={label}
+ aria-multiselectable={selectable || undefined}
+ aria-busy={loading || undefined}
+ aria-activedescendant={
+ showActive && activeId ? `${listId}-row-${activeId}` : undefined
+ }
+ tabIndex={0}
+ onKeyDown={onGridKeyDown}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setShowActive(false);
+ }}
+ style={gridStyle}
+ className={cn(
+ "grid min-w-0 content-start gap-x-3 px-2 outline-none",
+ "grid-cols-(--cl-narrow) @2xl:min-w-(--cl-minw) @2xl:grid-cols-(--cl-wide)",
+ !embedded && "pb-16",
+ className,
+ )}
+ >
+ <HeaderRow
+ columns={columns}
+ sort={sort}
+ selection={
+ selection
+ ? {
+ all: allSelected,
+ some: selectedVisible > 0 && !allSelected,
+ onToggle: () => {
+ toggleAll();
+ focusGrid();
+ },
+ disabled: selectableIds.length === 0,
+ label: selection.allLabel ?? t(($) => $.collection.select_all),
+ }
+ : null
+ }
+ menu={hasMenu}
+ />
+ {body}
+ {hasMore && onLoadMore && !loading ? (
+ <div className="col-span-full flex justify-center py-3">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={loadingMore}
+ onClick={onLoadMore}
+ className="text-muted-foreground"
+ >
+ {loadingMore ? <Loader2 className="size-3.5 animate-spin" /> : null}
+ {loadingMore
+ ? t(($) => $.collection.loading_more)
+ : t(($) => $.collection.load_more)}
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ );
+
+ if (embedded) return <div className="@container min-w-0 overflow-x-auto">{grid}</div>;
+ return (
+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-auto @container">
+ {grid}
+ </div>
+ );
+}
+
+function HeaderRow<T>({
+ columns,
+ sort,
+ selection,
+ menu,
+}: {
+ columns: readonly CollectionColumn<T>[];
+ sort?: CollectionSort;
+ selection: {
+ all: boolean;
+ some: boolean;
+ onToggle: () => void;
+ label: string;
+ disabled: boolean;
+ } | null;
+ menu: boolean;
+}) {
+ return (
+ <div
+ role="row"
+ className="group/header sticky top-0 z-10 col-span-full grid h-9 grid-cols-subgrid items-center bg-background text-caption text-muted-foreground shadow-[-8px_0_0_0_var(--background),8px_0_0_0_var(--background)]"
+ >
+ <span aria-hidden />
+ {selection ? (
+ <div role="columnheader" className="hidden items-center justify-center @2xl:flex">
+ <button
+ type="button"
+ role="checkbox"
+ tabIndex={-1}
+ aria-label={selection.label}
+ aria-checked={selection.all ? true : selection.some ? "mixed" : false}
+ disabled={selection.disabled}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={selection.onToggle}
+ className={cn(
+ "-m-1.5 flex items-center p-1.5",
+ !selection.all &&
+ !selection.some &&
+ "opacity-0 transition-opacity group-hover/header:opacity-100 focus-visible:opacity-100",
+ )}
+ >
+ <Checkbox
+ aria-hidden
+ checked={selection.all}
+ indeterminate={selection.some}
+ tabIndex={-1}
+ className="pointer-events-none"
+ />
+ </button>
+ </div>
+ ) : null}
+ {columns.map((col, i) => {
+ const sorted = sort && col.sortKey && sort.field === col.sortKey ? sort.direction : null;
+ return (
+ <div
+ key={col.key}
+ role="columnheader"
+ aria-sort={
+ sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : undefined
+ }
+ className={cn(
+ "flex min-w-0 items-center",
+ col.align === "end" && "justify-end",
+ i > 0 && !col.core && "hidden @2xl:flex",
+ )}
+ >
+ {col.header && col.sortKey && sort ? (
+ <button
+ type="button"
+ tabIndex={-1}
+ onClick={() => sort.onToggle(col.sortKey!)}
+ className={cn(
+ "-mx-1 inline-flex min-w-0 items-center gap-1 rounded-sm px-1 py-0.5 transition-colors hover:text-foreground",
+ sorted && "font-medium text-foreground",
+ )}
+ >
+ <span className="truncate">{col.header}</span>
+ {sorted === "asc" ? (
+ <ArrowUp className="size-3 shrink-0" />
+ ) : sorted === "desc" ? (
+ <ArrowDown className="size-3 shrink-0" />
+ ) : null}
+ </button>
+ ) : (
+ <span className="truncate">{col.header}</span>
+ )}
+ </div>
+ );
+ })}
+ {menu ? <span aria-hidden /> : null}
+ <span aria-hidden />
+ </div>
+ );
+}
+
+interface RowSelectionProps {
+ selected: boolean;
+ selectable: boolean;
+ revealed: boolean;
+ onToggle: (range: boolean) => void;
+ label: string;
+}
+
+function CollectionRow<T>({
+ domId,
+ row,
+ id,
+ columns,
+ href,
+ title,
+ onNavigate,
+ onOpen,
+ menu,
+ hasMenuSlot,
+ className,
+ rowLink,
+ selection,
+ rangeSelect,
+ active,
+ onPointerActivate,
+}: {
+ domId: string;
+ row: T;
+ id: string;
+ columns: readonly CollectionColumn<T>[];
+ href: string | null;
+ title?: string;
+ onNavigate?: (row: T) => void;
+ onOpen?: (row: T) => void;
+ menu: ReactNode;
+ hasMenuSlot: boolean;
+ className?: string;
+ rowLink: ReturnType<typeof useRowLink>;
+ selection: RowSelectionProps | null;
+ rangeSelect: ((range: boolean) => void) | null;
+ active: boolean;
+ onPointerActivate: () => void;
+}) {
+ const [menuState, setMenu] = useState<RowMenuState>({ open: false, point: null });
+ const context = useMemo(() => ({ menu: menuState, setMenu }), [menuState]);
+ const link = href ? rowLink(href, title, onNavigate ? () => onNavigate(row) : undefined) : null;
+ const clickable = !!link || !!onOpen;
+ const hasMenu = menu !== undefined && menu !== null && menu !== false;
+ const interactive = clickable || hasMenu || !!selection?.selectable;
+
+ const inside = (e: ReactMouseEvent<HTMLDivElement>) =>
+ e.currentTarget.contains(e.target as Node);
+
+ return (
+ <CollectionRowContext.Provider value={context}>
+ <div
+ id={domId}
+ role="row"
+ aria-selected={selection ? selection.selected : undefined}
+ data-selected={selection?.selected || undefined}
+ data-active={active || undefined}
+ data-menu-open={menuState.open || undefined}
+ data-row-id={id}
+ className={cn(
+ "group/row col-span-full grid h-9 scroll-mt-9 grid-cols-subgrid items-center rounded-md text-body",
+ interactive && "hover:bg-surface-hover data-menu-open:bg-surface-hover",
+ clickable && "cursor-pointer",
+ "data-selected:bg-surface-selected data-selected:hover:bg-surface-selected",
+ "data-active:ring-1 data-active:ring-ring data-active:ring-inset",
+ className,
+ )}
+ onPointerDown={(e) => {
+ if (e.button === 0 && inside(e)) onPointerActivate();
+ }}
+ onClick={(e) => {
+ if (!inside(e) || e.defaultPrevented) return;
+ if (e.shiftKey && rangeSelect && selection?.selectable) {
+ e.preventDefault();
+ rangeSelect(true);
+ return;
+ }
+ if (link) link.onClick(e);
+ else if (onOpen && e.button === 0) onOpen(row);
+ }}
+ onAuxClick={(e) => {
+ if (inside(e)) link?.onAuxClick(e);
+ }}
+ onMouseEnter={link?.onMouseEnter ?? noop}
+ onContextMenu={(e) => {
+ if (!hasMenu || !inside(e)) return;
+ e.preventDefault();
+ setMenu({ open: true, point: { x: e.clientX, y: e.clientY } });
+ }}
+ >
+ <span aria-hidden />
+ {selection ? (
+ <div role="gridcell" className="hidden items-center justify-center @2xl:flex">
+ {selection.selectable ? (
+ <button
+ type="button"
+ role="checkbox"
+ tabIndex={-1}
+ aria-label={selection.label}
+ aria-checked={selection.selected}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={(e) => {
+ e.stopPropagation();
+ selection.onToggle(e.shiftKey);
+ }}
+ onAuxClick={(e) => e.stopPropagation()}
+ className={cn(
+ "-m-1.5 flex items-center p-1.5",
+ !selection.selected &&
+ !selection.revealed &&
+ "opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100",
+ )}
+ >
+ <Checkbox
+ aria-hidden
+ checked={selection.selected}
+ tabIndex={-1}
+ className="pointer-events-none"
+ />
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ {columns.map((col, i) => (
+ <div
+ key={col.key}
+ role="gridcell"
+ className={cn(
+ "flex min-w-0 items-center",
+ col.align === "end" && "justify-end",
+ i > 0 && !col.core && "hidden @2xl:flex",
+ i > 0 && "gap-1.5 whitespace-nowrap text-caption text-muted-foreground",
+ col.className,
+ )}
+ onClick={col.interactive ? (e) => e.stopPropagation() : undefined}
+ onAuxClick={col.interactive ? (e) => e.stopPropagation() : undefined}
+ >
+ {col.cell(row)}
+ </div>
+ ))}
+ {hasMenuSlot ? (
+ <div
+ role="gridcell"
+ className="flex items-center justify-end"
+ onClick={(e) => e.stopPropagation()}
+ onAuxClick={(e) => e.stopPropagation()}
+ >
+ {menu}
+ </div>
+ ) : null}
+ <span aria-hidden />
+ </div>
+ </CollectionRowContext.Provider>
+ );
+}
+
+function SkeletonRow<T>({
+ columns,
+ selectable,
+ menu,
+}: {
+ columns: readonly CollectionColumn<T>[];
+ selectable: boolean;
+ menu: boolean;
+}) {
+ return (
+ <div aria-hidden className="col-span-full grid h-9 grid-cols-subgrid items-center">
+ <span />
+ {selectable ? <span className="hidden @2xl:block" /> : null}
+ {columns.map((col, i) => (
+ <div
+ key={col.key}
+ className={cn(
+ "flex min-w-0 items-center",
+ col.align === "end" && "justify-end",
+ i > 0 && !col.core && "hidden @2xl:flex",
+ )}
+ >
+ {i === 0 ? (
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <Skeleton className="size-5 shrink-0 rounded-full" />
+ <Skeleton className="h-3.5 w-40 max-w-full" />
+ </span>
+ ) : (
+ <Skeleton className="h-3 w-14 max-w-full" />
+ )}
+ </div>
+ ))}
+ {menu ? <span /> : null}
+ <span />
+ </div>
+ );
+}
diff --git a/packages/views/layout/collection-list/collection-row-menu.tsx b/packages/views/layout/collection-list/collection-row-menu.tsx
new file mode 100644
index 0000000000..eb4c0a0d29
--- /dev/null
+++ b/packages/views/layout/collection-list/collection-row-menu.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { useMemo, useState, type ReactNode } from "react";
+import { MoreHorizontal } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { useT } from "../../i18n";
+import { useCollectionRowMenuState, type RowMenuState } from "./row-context";
+
+/**
+ * The row's ⋯ button and its menu. Inside a CollectionList the same menu also
+ * opens on right-click, anchored at the cursor, so both entry points always
+ * show identical items.
+ */
+export function CollectionRowMenu({
+ label,
+ children,
+ contentClassName,
+ triggerClassName,
+}: {
+ label?: string;
+ children: ReactNode;
+ contentClassName?: string;
+ triggerClassName?: string;
+}) {
+ const { t } = useT("layout");
+ const row = useCollectionRowMenuState();
+ const [local, setLocal] = useState<RowMenuState>({ open: false, point: null });
+ const menu = row?.menu ?? local;
+ const setMenu = row?.setMenu ?? setLocal;
+ const name = label ?? t(($) => $.collection.row_actions);
+
+ const point = menu.point;
+ const anchor = useMemo(() => {
+ if (!point) return undefined;
+ return {
+ getBoundingClientRect: () => ({
+ x: point.x,
+ y: point.y,
+ top: point.y,
+ left: point.x,
+ right: point.x,
+ bottom: point.y,
+ width: 0,
+ height: 0,
+ toJSON: () => ({}),
+ }),
+ };
+ }, [point]);
+
+ return (
+ <DropdownMenu
+ open={menu.open}
+ onOpenChange={(open, details) => {
+ // Base UI treats a menu its trigger did not press open as hover-opened
+ // and closes it when the pointer leaves the trigger; a right-click menu
+ // never touched the trigger.
+ if (!open && point && details.reason === "trigger-hover") return;
+ setMenu(open ? { open: true, point: null } : { open: false, point });
+ }}
+ >
+ <DeferredTooltip
+ content={name}
+ trigger={
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ aria-label={name}
+ data-collection-row-menu=""
+ className={cn(
+ "flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity",
+ "hover:bg-accent hover:text-accent-foreground focus-visible:opacity-100",
+ "group-hover/row:opacity-100 group-data-menu-open/row:opacity-100",
+ "data-popup-open:bg-accent data-popup-open:text-accent-foreground data-popup-open:opacity-100",
+ "[@media(hover:none)]:opacity-100",
+ triggerClassName,
+ )}
+ >
+ <MoreHorizontal className="size-4" />
+ </button>
+ }
+ />
+ }
+ />
+ <DropdownMenuContent
+ align={point ? "start" : "end"}
+ anchor={anchor}
+ className={cn("w-48", contentClassName)}
+ >
+ {children}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/layout/collection-list/index.ts b/packages/views/layout/collection-list/index.ts
new file mode 100644
index 0000000000..b90de97706
--- /dev/null
+++ b/packages/views/layout/collection-list/index.ts
@@ -0,0 +1,17 @@
+export {
+ CollectionList,
+ type CollectionColumn,
+ type CollectionGroup,
+ type CollectionListProps,
+ type CollectionSelection,
+ type CollectionSort,
+ type CollectionSortDirection,
+} from "./collection-list";
+export { CollectionRowMenu } from "./collection-row-menu";
+export { CollectionBatchBar } from "./collection-batch-bar";
+export { CollectionDisplayMenu } from "./collection-display-menu";
+export {
+ CollectionEmptyValue,
+ CollectionNameCell,
+ CollectionTag,
+} from "./collection-cells";
diff --git a/packages/views/layout/collection-list/row-context.ts b/packages/views/layout/collection-list/row-context.ts
new file mode 100644
index 0000000000..3b60e4b8a9
--- /dev/null
+++ b/packages/views/layout/collection-list/row-context.ts
@@ -0,0 +1,19 @@
+"use client";
+
+import { createContext, useContext } from "react";
+
+export interface RowMenuState {
+ open: boolean;
+ point: { x: number; y: number } | null;
+}
+
+export interface RowContextValue {
+ menu: RowMenuState;
+ setMenu: (next: RowMenuState) => void;
+}
+
+export const CollectionRowContext = createContext<RowContextValue | null>(null);
+
+export function useCollectionRowMenuState(): RowContextValue | null {
+ return useContext(CollectionRowContext);
+}
diff --git a/packages/views/layout/collection-page.test.tsx b/packages/views/layout/collection-page.test.tsx
index 3e056f0b14..e41e1884f4 100644
--- a/packages/views/layout/collection-page.test.tsx
+++ b/packages/views/layout/collection-page.test.tsx
@@ -1,52 +1,72 @@
-import { render, screen } from "@testing-library/react";
-import { Plus, Users } from "@multica/ui/icons";
+import { screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { Users } from "@multica/ui/icons";
import { describe, expect, it, vi } from "vitest";
+import { renderWithI18n } from "../test/i18n";
import {
+ CollectionCreateButton,
+ CollectionFilterButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionScopeItems,
} from "./collection-page";
describe("CollectionPageHeader", () => {
- it("renders a semantic title, count, supporting link, and labelled action", () => {
- render(
+ it("renders the scope as the title with the tools beside it and icon actions on the right", () => {
+ renderWithI18n(
<CollectionPageHeader
icon={Users}
- title="Teams"
- count={4}
- description="Manage collaborators."
- learnMore={{ href: "https://example.com/docs", label: "Learn more" }}
- actions={
- <CollectionPageHeaderAction
- icon={Plus}
- label="New team"
- onClick={vi.fn()}
+ title="All teams"
+ tools={<CollectionFilterButton />}
+ actions={<CollectionCreateButton label="New team" onClick={vi.fn()} />}
+ />,
+ );
+
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("heading", { name: "All teams", level: 1 })).toBeInTheDocument();
+ expect(within(header).getByRole("button", { name: "Filter" })).toBeInTheDocument();
+ expect(within(header).getByRole("button", { name: "New team" })).toBeInTheDocument();
+ });
+
+ it("opens the scope menu from the title and reports the picked scope", async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ renderWithI18n(
+ <CollectionPageHeader
+ icon={Users}
+ title="My teams"
+ menu={
+ <CollectionScopeItems
+ value="mine"
+ onChange={onChange}
+ options={[
+ { value: "mine", label: "My teams", count: 2 },
+ { value: "all", label: "All teams", count: 5 },
+ ]}
/>
}
/>,
);
- expect(screen.getByRole("banner")).toBeInTheDocument();
- expect(
- screen.getByRole("heading", { name: "Teams", level: 1 }),
- ).toBeInTheDocument();
- expect(screen.getByText("4")).toBeInTheDocument();
- expect(screen.getByRole("link", { name: "Learn more" })).toHaveAttribute(
- "href",
- "https://example.com/docs",
- );
- expect(screen.getByRole("button", { name: "New team" })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: /My teams/ }));
+ const all = await screen.findByRole("menuitemradio", { name: /All teams/ });
+ expect(all).toHaveTextContent("5");
+ await user.click(all);
+ expect(onChange).toHaveBeenCalledWith("all");
});
+});
- it("does not render a zero count", () => {
- render(<CollectionPageHeader icon={Users} title="Teams" count={0} />);
- expect(screen.queryByText("0")).not.toBeInTheDocument();
+describe("CollectionFilterButton", () => {
+ it("names the number of filters that are on", () => {
+ renderWithI18n(<CollectionFilterButton count={2} />);
+ const button = screen.getByRole("button", { name: "2 filters" });
+ expect(button).toHaveTextContent("2");
});
});
describe("CollectionPageState", () => {
it("renders an alert with semantic title and description", () => {
- render(
+ renderWithI18n(
<CollectionPageState
role="alert"
icon={Users}
diff --git a/packages/views/layout/collection-page.tsx b/packages/views/layout/collection-page.tsx
index f1cad6935c..ef7e5c44fe 100644
--- a/packages/views/layout/collection-page.tsx
+++ b/packages/views/layout/collection-page.tsx
@@ -1,8 +1,22 @@
"use client";
import type { ComponentProps, ReactNode } from "react";
-import type { IconComponent } from "@multica/ui/icons";
+import {
+ ChevronDown,
+ Filter,
+ Plus,
+ SlidersHorizontal,
+ type IconComponent,
+} from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import {
Empty,
EmptyContent,
@@ -12,108 +26,213 @@ import {
EmptyTitle,
} from "@multica/ui/components/ui/empty";
import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
import { PageHeader } from "./page-header";
interface CollectionPageHeaderProps {
icon: IconComponent;
+ /** The scope being looked at, e.g. "All agents" — not the bare noun. */
title: ReactNode;
- count?: number;
- description?: ReactNode;
- learnMore?: {
- href: string;
- label: ReactNode;
- };
+ /**
+ * Items of the title's menu, usually `CollectionScopeItems`. Without one the
+ * title is plain text.
+ */
+ menu?: ReactNode;
+ /** Filter and search, right after the title. */
+ tools?: ReactNode;
+ /** Icon controls on the right: display settings, then create. */
actions?: ReactNode;
className?: string;
}
/**
- * Shared dashboard collection header: entity icon, title, optional count and
- * supporting copy on the left; page-level actions on the right.
+ * The one header row of a list page, laid out like the issues header: the
+ * title names the scope and opens the scope menu, filter and search follow
+ * it, and the right side holds icon controls whose names live in tooltips.
+ * Counts belong to the sidebar rows, so the row carries none.
*/
export function CollectionPageHeader({
icon: Icon,
title,
- count,
- description,
- learnMore,
+ menu,
+ tools,
actions,
className,
}: CollectionPageHeaderProps) {
+ const label = (
+ <>
+ <Icon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 truncate">{title}</span>
+ </>
+ );
return (
<PageHeader className={className}>
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <Icon
- aria-hidden="true"
- className="size-4 shrink-0 text-muted-foreground"
- />
- <h1 className="truncate text-body font-medium">{title}</h1>
- {typeof count === "number" && count > 0 ? (
- <span className="shrink-0 font-mono text-caption tabular-nums text-muted-foreground">
- {count}
- </span>
- ) : null}
- {description || learnMore ? (
- <p className="ml-2 hidden min-w-0 truncate text-caption text-muted-foreground md:block">
- {description}
- {learnMore ? (
- <>
- {description ? " " : null}
- <a
- href={learnMore.href}
- target="_blank"
- rel="noopener noreferrer"
- className="underline decoration-muted-foreground/30 underline-offset-4 transition-colors hover:text-foreground"
- >
- {learnMore.label}
- </a>
- </>
- ) : null}
- </p>
- ) : null}
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ {menu ? (
+ <DropdownMenu>
+ <h1 className="flex min-w-20">
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 min-w-0 max-w-64 shrink gap-2 px-2 text-body font-medium text-foreground"
+ />
+ }
+ >
+ {label}
+ <ChevronDown className="size-3 shrink-0 text-muted-foreground" />
+ </DropdownMenuTrigger>
+ </h1>
+ <DropdownMenuContent align="start" className="w-auto min-w-52">
+ {menu}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <h1 className="flex min-w-0 items-center gap-2 px-2 text-body font-medium">
+ {label}
+ </h1>
+ )}
+ {tools}
</div>
{actions ? (
- <div className="flex shrink-0 items-center justify-end gap-2">
- {actions}
- </div>
+ <div className="flex shrink-0 items-center gap-1">{actions}</div>
) : null}
</PageHeader>
);
}
-interface CollectionPageHeaderActionProps
- extends Omit<ComponentProps<typeof Button>, "children"> {
- icon: IconComponent;
- label: string;
+export interface CollectionScopeOption<T extends string> {
+ value: T;
+ label: ReactNode;
+ /** Shown in the menu only; the header never carries a count. */
+ count?: number;
}
-/** Responsive collection action: icon-only below md, labelled above md. */
-export function CollectionPageHeaderAction({
- icon: Icon,
+export function CollectionScopeItems<T extends string>({
+ value,
+ options,
+ onChange,
+}: {
+ value: T;
+ options: CollectionScopeOption<T>[];
+ onChange: (value: T) => void;
+}) {
+ return (
+ <DropdownMenuRadioGroup value={value} onValueChange={(next) => onChange(next as T)}>
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ <span className="flex-1">{option.label}</span>
+ {option.count !== undefined ? (
+ <span className="ml-3 text-caption tabular-nums text-muted-foreground">
+ {option.count}
+ </span>
+ ) : null}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ );
+}
+
+type HeaderIconButtonProps = Omit<ComponentProps<typeof IconButton>, "label" | "children"> & {
+ /** Overrides the default tooltip and accessible name. */
+ label?: string;
+};
+
+/**
+ * The filter control: an icon that turns into a count once filters are on.
+ * Pass it as the `render` of the filter menu's trigger.
+ */
+export function CollectionFilterButton({
+ count = 0,
label,
className,
- type = "button",
- size = "sm",
- variant = "outline",
...props
-}: CollectionPageHeaderActionProps) {
- const accessibleLabel = props["aria-label"] ?? label;
+}: HeaderIconButtonProps & { count?: number }) {
+ const { t } = useT("layout");
+ return (
+ <IconButton
+ {...props}
+ size="sm"
+ tooltipSide="bottom"
+ label={
+ label ??
+ (count > 0
+ ? t(($) => $.collection.filter_count, { count })
+ : t(($) => $.collection.filter))
+ }
+ className={cn(
+ "h-7 min-w-7 shrink-0 gap-1.5 px-1.5 text-muted-foreground",
+ count > 0 && "text-foreground",
+ className,
+ )}
+ >
+ <Filter className="size-4" />
+ {count > 0 ? (
+ <span className="rounded-sm bg-brand/10 px-1 text-caption font-medium tabular-nums text-brand">
+ {count}
+ </span>
+ ) : null}
+ </IconButton>
+ );
+}
+/** Clears the filters and search; render it only while one is on. */
+export function CollectionResetButton({ onClick }: { onClick: () => void }) {
+ const { t } = useT("layout");
return (
<Button
- type={type}
- size={size}
- variant={variant}
- className={cn("h-8 w-8 gap-1 px-0 md:w-auto md:px-2.5", className)}
- aria-label={accessibleLabel}
- {...props}
+ variant="ghost"
+ size="sm"
+ className="h-7 shrink-0 px-2 text-muted-foreground"
+ onClick={onClick}
>
- <Icon aria-hidden="true" className="size-3.5" />
- <span className="hidden md:inline">{label}</span>
+ {t(($) => $.collection.reset)}
</Button>
);
}
+/**
+ * Display settings (sort, columns, layout). Pass it as the `render` of the
+ * popover that holds them; `icon` shows the current layout when there is one.
+ */
+export function CollectionDisplayButton({
+ icon: Icon = SlidersHorizontal,
+ label,
+ className,
+ ...props
+}: HeaderIconButtonProps & { icon?: IconComponent }) {
+ const { t } = useT("layout");
+ return (
+ <IconButton
+ {...props}
+ tooltipSide="bottom"
+ label={label ?? t(($) => $.collection.display)}
+ className={cn("shrink-0 text-muted-foreground", className)}
+ >
+ <Icon />
+ </IconButton>
+ );
+}
+
+/** Create is always an icon; the page's one solid button is never "New". */
+export function CollectionCreateButton({
+ label,
+ className,
+ ...props
+}: Omit<ComponentProps<typeof IconButton>, "children">) {
+ return (
+ <IconButton
+ {...props}
+ tooltipSide="bottom"
+ label={label}
+ className={cn("shrink-0 text-muted-foreground", className)}
+ >
+ <Plus />
+ </IconButton>
+ );
+}
+
type PageStateTone = "muted" | "destructive" | "warning";
interface CollectionPageStateProps {
diff --git a/packages/views/layout/compact-nav-sheet.test.tsx b/packages/views/layout/compact-nav-sheet.test.tsx
new file mode 100644
index 0000000000..20d5acf443
--- /dev/null
+++ b/packages/views/layout/compact-nav-sheet.test.tsx
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithI18n } from "../test/i18n";
+import { CompactNavSheet } from "./compact-nav-sheet";
+
+const state = vi.hoisted(() => ({
+ pathname: "/acme/issues",
+ isCompact: true,
+ openMobile: false,
+ setOpenMobile: vi.fn(),
+}));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ pathname: state.pathname }),
+}));
+vi.mock("@multica/ui/components/ui/sidebar", () => ({
+ useSidebar: () => ({
+ isCompact: state.isCompact,
+ openMobile: state.openMobile,
+ setOpenMobile: state.setOpenMobile,
+ }),
+}));
+vi.mock("./app-rail", () => ({ AppRail: () => <nav data-testid="rail" /> }));
+vi.mock("./space-panel", () => ({
+ SpacePanelContent: ({ space }: { space: string | null }) => <div data-testid={`panel-${space}`} />,
+}));
+vi.mock("./app-shell-context", () => ({
+ useAppShell: () => ({ space: "work", hasPanel: true }),
+}));
+
+beforeEach(() => {
+ state.pathname = "/acme/issues";
+ state.isCompact = true;
+ state.openMobile = false;
+ state.setOpenMobile.mockClear();
+});
+
+// The sheet covers the page on a phone: a tap that navigates but leaves it
+// open renders the destination underneath and reads as a dead tap.
+describe("CompactNavSheet dismissal", () => {
+ it("dismisses the sheet once the route changes", () => {
+ const { rerender } = renderWithI18n(<CompactNavSheet />);
+ state.setOpenMobile.mockClear();
+
+ state.pathname = "/acme/inbox";
+ rerender(<CompactNavSheet />);
+ expect(state.setOpenMobile).toHaveBeenCalledWith(false);
+ });
+
+ it("does not re-dismiss while the route holds still", () => {
+ const { rerender } = renderWithI18n(<CompactNavSheet />);
+ state.setOpenMobile.mockClear();
+
+ rerender(<CompactNavSheet />);
+ expect(state.setOpenMobile).not.toHaveBeenCalled();
+ });
+});
+
+describe("CompactNavSheet content", () => {
+ it("holds the rail and the current space's panel", () => {
+ state.openMobile = true;
+ const { getByTestId } = renderWithI18n(<CompactNavSheet />);
+ expect(getByTestId("rail")).toBeInTheDocument();
+ expect(getByTestId("panel-work")).toBeInTheDocument();
+ });
+
+ it("renders nothing above the compact breakpoint", () => {
+ state.isCompact = false;
+ state.openMobile = true;
+ const { queryByTestId } = renderWithI18n(<CompactNavSheet />);
+ expect(queryByTestId("rail")).toBeNull();
+ });
+});
diff --git a/packages/views/layout/compact-nav-sheet.tsx b/packages/views/layout/compact-nav-sheet.tsx
new file mode 100644
index 0000000000..e93465f079
--- /dev/null
+++ b/packages/views/layout/compact-nav-sheet.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { useEffect } from "react";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@multica/ui/components/ui/sheet";
+import { useSidebar } from "@multica/ui/components/ui/sidebar";
+import { useT } from "../i18n";
+import { useNavigation } from "../navigation";
+import { AppRail } from "./app-rail";
+import { useAppShell } from "./app-shell-context";
+import { SpacePanelContent } from "./space-panel";
+
+/**
+ * Below `md` the rail and the current space's panel move into one sheet,
+ * opened by the page header's nav trigger.
+ */
+export function CompactNavSheet({ globalActions = true }: { globalActions?: boolean }) {
+ const { t } = useT("layout");
+ const { isCompact, openMobile, setOpenMobile } = useSidebar();
+ const { pathname } = useNavigation();
+ const shell = useAppShell();
+
+ // The sheet covers the page, so leaving through it has to dismiss it or
+ // the destination renders underneath and the tap reads as nothing
+ // happened. Keying on `pathname` covers every route out at once: rail
+ // links, panel rows, pins, and the workspace switcher.
+ useEffect(() => {
+ setOpenMobile(false);
+ }, [pathname, setOpenMobile]);
+
+ if (!isCompact) return null;
+ const hasPanel = !!shell?.hasPanel;
+
+ return (
+ <Sheet open={openMobile} onOpenChange={setOpenMobile}>
+ <SheetContent
+ side="left"
+ showCloseButton={false}
+ data-slot="compact-nav-sheet"
+ className="flex-row gap-0 overflow-hidden bg-app-shell p-0 data-[side=left]:w-auto data-[side=left]:max-w-[calc(100vw-3rem)]"
+ >
+ <SheetHeader className="sr-only">
+ <SheetTitle>{t(($) => $.rail.label)}</SheetTitle>
+ <SheetDescription>{t(($) => $.rail.sheet_description)}</SheetDescription>
+ </SheetHeader>
+ <AppRail globalActions={globalActions} />
+ {hasPanel && (
+ <div className="my-2 mr-2 flex w-[260px] min-w-0 flex-col overflow-hidden rounded-xl bg-page-canvas shadow-[var(--surface-shadow)] ring-1 ring-surface-border">
+ <SpacePanelContent space={shell?.space ?? null} />
+ </div>
+ )}
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/packages/views/layout/dashboard-layout.tsx b/packages/views/layout/dashboard-layout.tsx
index d7adbb47e6..b9d37352d0 100644
--- a/packages/views/layout/dashboard-layout.tsx
+++ b/packages/views/layout/dashboard-layout.tsx
@@ -1,29 +1,44 @@
"use client";
import type { ReactNode } from "react";
-import { SidebarProvider, SidebarInset } from "@multica/ui/components/ui/sidebar";
+import { SidebarProvider } from "@multica/ui/components/ui/sidebar";
import { ModalRegistry } from "../modals/registry";
import { SourceBackfillModal } from "../onboarding";
-import { AppSidebar } from "./app-sidebar";
+import { AppRail } from "./app-rail";
+import { AppShellProvider } from "./app-shell-context";
+import { CompactNavSheet } from "./compact-nav-sheet";
import { DashboardGuard } from "./dashboard-guard";
import { NavigationProgress } from "./navigation-progress";
+import { ShellRouteDataPrefetch } from "./route-data-prefetch";
+import { SpacePanel } from "./space-panel";
import { WorkspacePresencePrefetch } from "./workspace-presence-prefetch";
import { GlobalShortcuts } from "./global-shortcuts";
interface DashboardLayoutProps {
children: ReactNode;
- /** Rendered inside SidebarInset (e.g. ChatWindow, ChatFab — absolute-positioned overlays) */
+ /** Rendered inside the content column (e.g. ChatWindow, ChatFab — absolute-positioned overlays) */
extra?: ReactNode;
- /** Rendered inside sidebar header as a search trigger */
- searchSlot?: ReactNode;
/** Loading indicator */
loadingIndicator?: ReactNode;
}
+/**
+ * The content card: the space panel and the page share one surface on the
+ * app shell, split by a single hairline. Below `md` the card is the whole
+ * window. Desktop builds the same card in its own layout, under the tab bar.
+ */
+export function AppShellCard({ children }: { children: ReactNode }) {
+ return (
+ <main className="relative flex min-w-0 flex-1 flex-row overflow-hidden bg-page-canvas md:my-2 md:mr-2 md:rounded-xl md:shadow-[var(--surface-shadow)] md:ring-1 md:ring-surface-border">
+ <SpacePanel />
+ <div className="relative flex min-w-0 flex-1 flex-col overflow-hidden">{children}</div>
+ </main>
+ );
+}
+
export function DashboardLayout({
children,
extra,
- searchSlot,
loadingIndicator,
}: DashboardLayoutProps) {
return (
@@ -34,17 +49,22 @@ export function DashboardLayout({
</div>
}
>
- <SidebarProvider className="h-svh bg-app-shell">
- <GlobalShortcuts />
- <WorkspacePresencePrefetch />
- <AppSidebar searchSlot={searchSlot} />
- <SidebarInset className="relative overflow-hidden">
- <NavigationProgress />
- {children}
- <ModalRegistry />
- <SourceBackfillModal />
- {extra}
- </SidebarInset>
+ <SidebarProvider className="h-svh bg-app-shell [--sidebar-wrapper-fill:var(--app-shell)]">
+ <AppShellProvider>
+ <ShellRouteDataPrefetch>
+ <GlobalShortcuts />
+ <WorkspacePresencePrefetch />
+ <AppRail className="hidden md:flex" />
+ <CompactNavSheet />
+ <AppShellCard>
+ <NavigationProgress />
+ {children}
+ <ModalRegistry />
+ <SourceBackfillModal />
+ {extra}
+ </AppShellCard>
+ </ShellRouteDataPrefetch>
+ </AppShellProvider>
</SidebarProvider>
</DashboardGuard>
);
diff --git a/packages/views/layout/global-actions.test.tsx b/packages/views/layout/global-actions.test.tsx
new file mode 100644
index 0000000000..25d7043d07
--- /dev/null
+++ b/packages/views/layout/global-actions.test.tsx
@@ -0,0 +1,61 @@
+import type { ReactNode } from "react";
+import { fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithI18n } from "../test/i18n";
+import { NewIssueButton, SearchButton } from "./global-actions";
+
+const state = vi.hoisted(() => ({ pathname: "/acme/inbox", hasDraft: false }));
+const openCreateIssueWithPreference = vi.hoisted(() => vi.fn());
+const setSearchOpen = vi.hoisted(() => vi.fn());
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ pathname: state.pathname }),
+}));
+vi.mock("@multica/core/issues/stores", () => ({ openCreateIssueWithPreference }));
+vi.mock("@multica/core/issues/stores/draft-store", () => ({
+ useIssueDraftStore: (selector: (s: { hasDraft: () => boolean }) => unknown) =>
+ selector({ hasDraft: () => state.hasDraft }),
+}));
+vi.mock("../search/search-store", () => ({
+ useSearchStore: { getState: () => ({ setOpen: setSearchOpen }) },
+}));
+vi.mock("@multica/core/shortcuts", () => ({ useShortcut: () => null }));
+vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
+ TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+beforeEach(() => {
+ state.pathname = "/acme/inbox";
+ state.hasDraft = false;
+ openCreateIssueWithPreference.mockClear();
+ setSearchOpen.mockClear();
+});
+
+describe("NewIssueButton", () => {
+ it("starts an empty issue outside a project", () => {
+ renderWithI18n(<NewIssueButton className="" tooltipSide="bottom" />);
+ fireEvent.click(screen.getByRole("button", { name: /^new issue$/i }));
+ expect(openCreateIssueWithPreference).toHaveBeenCalledWith(undefined);
+ });
+
+ it("files the issue into the open project, like the C shortcut", () => {
+ state.pathname = "/acme/projects/p-1";
+ renderWithI18n(<NewIssueButton className="" tooltipSide="bottom" />);
+ fireEvent.click(screen.getByRole("button", { name: /^new issue$/i }));
+ expect(openCreateIssueWithPreference).toHaveBeenCalledWith({ project_id: "p-1" });
+ });
+
+ it("marks a saved draft", () => {
+ state.hasDraft = true;
+ renderWithI18n(<NewIssueButton className="" tooltipSide="bottom" />);
+ expect(screen.getByRole("button", { name: /^new issue$/i }).querySelector(".bg-brand")).not.toBeNull();
+ });
+});
+
+describe("SearchButton", () => {
+ it("opens search", () => {
+ renderWithI18n(<SearchButton className="" tooltipSide="bottom" />);
+ fireEvent.click(screen.getByRole("button", { name: "Search..." }));
+ expect(setSearchOpen).toHaveBeenCalledWith(true);
+ });
+});
diff --git a/packages/views/layout/global-actions.tsx b/packages/views/layout/global-actions.tsx
new file mode 100644
index 0000000000..5ed46375e4
--- /dev/null
+++ b/packages/views/layout/global-actions.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import type { ComponentProps } from "react";
+import { Search, SquarePen } from "@multica/ui/icons";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
+import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";
+import { useShortcut } from "@multica/core/shortcuts";
+import { ShortcutKeycaps } from "../common/shortcut-keycaps";
+import { useT } from "../i18n";
+import { useNavigation } from "../navigation";
+import { useSearchStore } from "../search/search-store";
+
+type TooltipSide = ComponentProps<typeof TooltipHint>["side"];
+
+/**
+ * Opens the create-issue modal the way the `C` shortcut does: a project
+ * page files the issue into that project, anywhere else starts it empty.
+ */
+export function openCreateIssueForPath(pathname: string) {
+ const projectMatch = pathname.match(/^\/[^/]+\/projects\/([^/]+)$/);
+ openCreateIssueWithPreference(projectMatch ? { project_id: projectMatch[1] } : undefined);
+}
+
+function DraftDot() {
+ const hasDraft = useIssueDraftStore((s) => s.hasDraft());
+ if (!hasDraft) return null;
+ return <span aria-hidden className="absolute -top-0.5 -right-0.5 size-1.5 rounded-full bg-brand" />;
+}
+
+/** The app-wide New issue action, reachable from every space. */
+export function NewIssueButton({
+ className,
+ tooltipSide,
+}: {
+ className: string;
+ tooltipSide: TooltipSide;
+}) {
+ const { t } = useT("layout");
+ const { pathname } = useNavigation();
+ const shortcut = useShortcut("createIssue");
+ const label = t(($) => $.sidebar.new_issue);
+ return (
+ <TooltipHint
+ label={label}
+ shortcut={shortcut ? <ShortcutKeycaps shortcut={shortcut} decorative className="ml-1.5" /> : null}
+ side={tooltipSide}
+ >
+ <button
+ type="button"
+ aria-label={label}
+ data-action="new-issue"
+ onClick={() => openCreateIssueForPath(pathname)}
+ className={className}
+ >
+ <span className="relative flex">
+ <SquarePen />
+ <DraftDot />
+ </span>
+ </button>
+ </TooltipHint>
+ );
+}
+
+export function SearchButton({
+ className,
+ tooltipSide,
+}: {
+ className: string;
+ tooltipSide: TooltipSide;
+}) {
+ const { t } = useT("search");
+ const shortcut = useShortcut("openSearch");
+ const label = t(($) => $.trigger.label);
+ return (
+ <TooltipHint
+ label={label}
+ shortcut={shortcut ? <ShortcutKeycaps shortcut={shortcut} decorative className="ml-1.5" /> : null}
+ side={tooltipSide}
+ >
+ <button
+ type="button"
+ aria-label={label}
+ data-action="search"
+ onClick={() => useSearchStore.getState().setOpen(true)}
+ className={className}
+ >
+ <Search />
+ </button>
+ </TooltipHint>
+ );
+}
diff --git a/packages/views/layout/global-shortcuts.tsx b/packages/views/layout/global-shortcuts.tsx
index 4c9971e0a5..f83078d030 100644
--- a/packages/views/layout/global-shortcuts.tsx
+++ b/packages/views/layout/global-shortcuts.tsx
@@ -11,11 +11,12 @@ import {
type ShortcutActionId,
} from "@multica/core/shortcuts";
import { useChatStore } from "@multica/core/chat";
-import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
import { useModalStore } from "@multica/core/modals";
import { useWorkspacePaths } from "@multica/core/paths";
import { isImeComposing } from "@multica/core/utils";
import { isFloatingChatRouteSuppressed } from "../chat/floating-chat-visibility";
+import { useAppShell } from "./app-shell-context";
+import { openCreateIssueForPath } from "./global-actions";
import { useNavigation } from "../navigation";
import { useSearchStore } from "../search/search-store";
@@ -47,6 +48,7 @@ export function shouldIgnoreGlobalShortcutEvent(event: KeyboardEvent): boolean {
/** Executes configurable product-level shortcuts inside the dashboard shell. */
export function GlobalShortcuts() {
const { toggleSidebar } = useSidebar();
+ const toggleNav = useAppShell()?.toggleNav ?? toggleSidebar;
const navigation = useNavigation();
const workspacePaths = useWorkspacePaths();
@@ -106,7 +108,7 @@ export function GlobalShortcuts() {
return;
}
if (actionId === "toggleSidebar") {
- toggleSidebar();
+ toggleNav();
return;
}
if (actionId === "goBack") {
@@ -121,13 +123,7 @@ export function GlobalShortcuts() {
}
if (actionId === "createIssue") {
if (useModalStore.getState().modal) return;
- const projectMatch = navigation.pathname.match(
- /^\/[^/]+\/projects\/([^/]+)$/,
- );
- const data = projectMatch
- ? { project_id: projectMatch[1] }
- : undefined;
- openCreateIssueWithPreference(data);
+ openCreateIssueForPath(navigation.pathname);
return;
}
@@ -139,7 +135,7 @@ export function GlobalShortcuts() {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [navigation, overrides, toggleSidebar, workspacePaths]);
+ }, [navigation, overrides, toggleNav, workspacePaths]);
return null;
}
diff --git a/packages/views/layout/help-launcher.tsx b/packages/views/layout/help-launcher.tsx
index c31b460176..05d93dc8f9 100644
--- a/packages/views/layout/help-launcher.tsx
+++ b/packages/views/layout/help-launcher.tsx
@@ -24,21 +24,16 @@ import { isDesktopShell } from "../platform/local-directory";
import { DISCORD_URL, DiscordIcon } from "./discord";
import { useT } from "../i18n";
import { docsLocalePrefix } from "../common/docs-locale";
+import { RAIL_ICON_BUTTON_CLASS } from "./rail-styles";
+import { CHANGELOG_URL, DOCS_URL, DOWNLOAD_URL } from "./help-links";
-const DOCS_URL = "https://multica.ai/docs";
-const CHANGELOG_URL = "https://multica.ai/changelog";
-// Absolute, including on self-hosted deployments: the installers we ship are
-// the same binaries either way, and the desktop client can point at a
-// self-hosted backend once installed. A self-host-relative /download would
-// only serve a copy of this page that still has to reach our release assets.
-const DOWNLOAD_URL = "https://multica.ai/download";
export function HelpLauncher() {
const { t, i18n } = useT("layout");
const serverVersion = useConfigStore((state) => state.serverVersion);
// Web-only: offering "download the desktop app" inside the desktop app is
- // nonsense, and this sidebar is shared — apps/desktop renders the same
- // AppSidebar as the web dashboard, so the entry has to be gated here.
+ // nonsense, and this rail is shared — apps/desktop renders the same app
+ // shell as the web dashboard, so the entry has to be gated here.
//
// No `mounted` deferral (cf. browser-notification-setting.tsx): the desktop
// renderer is a locally-bundled SPA with no SSR pass, and on web
@@ -48,17 +43,17 @@ export function HelpLauncher() {
const desktop = isDesktopShell();
return (
<DropdownMenu>
- <TooltipHint label={t(($) => $.help.trigger)}>
+ <TooltipHint label={t(($) => $.help.trigger)} side="right">
<DropdownMenuTrigger
aria-label={t(($) => $.help.trigger)}
- className="inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors cursor-pointer hover:bg-accent hover:text-foreground data-popup-open:bg-accent data-popup-open:text-foreground"
+ className={RAIL_ICON_BUTTON_CLASS}
>
- <CircleHelp className="size-4" />
+ <CircleHelp />
</DropdownMenuTrigger>
</TooltipHint>
<DropdownMenuContent
align="end"
- side="top"
+ side="right"
sideOffset={8}
className="min-w-40 max-w-56"
>
@@ -128,7 +123,7 @@ export function HelpLauncher() {
a Menu.Group context and throws if it has no Group ancestor. It
must always be wrapped in a DropdownMenuGroup — without it the
Help menu crashes the whole app on open (no error boundary sits
- above the sidebar). */}
+ above the rail). */}
<DropdownMenuGroup>
<DropdownMenuLabel className="font-normal break-words">
{t(($) => $.help.server_version, { version: serverVersion })}
diff --git a/packages/views/layout/help-links.ts b/packages/views/layout/help-links.ts
new file mode 100644
index 0000000000..9d6803ba81
--- /dev/null
+++ b/packages/views/layout/help-links.ts
@@ -0,0 +1,7 @@
+export const DOCS_URL = "https://multica.ai/docs";
+export const CHANGELOG_URL = "https://multica.ai/changelog";
+// Absolute, including on self-hosted deployments: the installers we ship are
+// the same binaries either way, and the desktop client can point at a
+// self-hosted backend once installed. A self-host-relative /download would
+// only serve a copy of this page that still has to reach our release assets.
+export const DOWNLOAD_URL = "https://multica.ai/download";
diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.ts
index af7c7e178d..318fc0eb09 100644
--- a/packages/views/layout/index.ts
+++ b/packages/views/layout/index.ts
@@ -1,9 +1,29 @@
-export { AppSidebar } from "./app-sidebar";
+export { AppRail } from "./app-rail";
+export { AppShellProvider, useAppShell } from "./app-shell-context";
+export { CompactNavSheet } from "./compact-nav-sheet";
+export { ShellRouteDataPrefetch } from "./route-data-prefetch";
+export { SpacePanel } from "./space-panel";
export {
+ CollectionCreateButton,
+ CollectionDisplayButton,
+ CollectionFilterButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
+ type CollectionScopeOption,
} from "./collection-page";
+export {
+ OBJECT_PAGE_BODY,
+ ObjectIconMark,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectPanelSection,
+ ObjectProperty,
+ ObjectSection,
+ ObjectSectionAction,
+ ObjectSectionCard,
+} from "./object-page";
export { ROUTE_ICON_COMPONENTS, routeIconForPath } from "./route-icon-components";
export {
useTabPresentation,
@@ -11,9 +31,10 @@ export {
} from "./tab-presentation";
export type { TabPresentationResult } from "./tab-presentation";
export { DashboardGuard } from "./dashboard-guard";
-export { DashboardLayout } from "./dashboard-layout";
+export { AppShellCard, DashboardLayout } from "./dashboard-layout";
export { useDashboardGuard } from "./use-dashboard-guard";
export { WorkspaceLoader } from "./workspace-loader";
export { WorkspacePresencePrefetch } from "./workspace-presence-prefetch";
export { GlobalShortcuts } from "./global-shortcuts";
+export { NewIssueButton, SearchButton } from "./global-actions";
export { NavigationProgress } from "./navigation-progress";
diff --git a/packages/views/layout/issue-page-refresh.test.tsx b/packages/views/layout/issue-page-refresh.test.tsx
index 5a03ef8ec0..b4b3710557 100644
--- a/packages/views/layout/issue-page-refresh.test.tsx
+++ b/packages/views/layout/issue-page-refresh.test.tsx
@@ -1,4 +1,4 @@
-import { act, cleanup, screen, within } from "@testing-library/react";
+import { cleanup, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithI18n } from "../test/i18n";
import { IssuesPage } from "../issues/components/issues-page";
@@ -11,9 +11,6 @@ vi.mock("@multica/core/auth", () => ({
vi.mock("@multica/core/issues/stores/issues-scope-store", () => ({
useIssuesScope: () => "all",
}));
-vi.mock("@multica/core/issues/stores/view-store-context", () => ({
- useViewStore: (select: (s: object) => unknown) => select({ dateFilter: null, setDateFilter: vi.fn() }),
-}));
vi.mock("@multica/core/issues/stores/my-issues-view-store", () => {
const scopeState = { scope: "all", setScope: vi.fn() };
return {
@@ -21,43 +18,44 @@ vi.mock("@multica/core/issues/stores/my-issues-view-store", () => {
myIssuesViewStore: { getState: () => scopeState, getInitialState: () => scopeState, subscribe: () => () => {} },
};
});
+vi.mock("../my-issues/use-my-issues-scope", () => ({
+ useMyIssuesScope: () => "all",
+}));
vi.mock("../issues/surface/issue-surface", () => ({
IssueSurface: ({ renderHeader }: { renderHeader: (context: object) => React.ReactNode }) => (
<>{renderHeader({ controller: { isRefreshing: state.refreshing, surfaceIssues: [] } })}</>
),
}));
-vi.mock("../issues/components/issues-header", () => ({
- IssuesHeader: () => <div>Issue controls</div>,
-}));
-vi.mock("../my-issues/components/my-issues-header", () => ({
- MyIssuesHeader: () => <div>My issue controls</div>,
+vi.mock("../issue-views/view-header", () => ({
+ IssueViewHeader: ({ controller, base }: { controller: { isRefreshing: boolean }; base: { kind: string } }) => (
+ <header>
+ <h1>{base.kind}</h1>
+ {controller.isRefreshing && <span role="status" />}
+ </header>
+ ),
}));
describe("issue page refresh feedback", () => {
beforeEach(() => {
state.refreshing = false;
state.user = { id: "user-1" };
- vi.useFakeTimers();
});
afterEach(() => {
cleanup();
- vi.useRealTimers();
});
- it.each([IssuesPage, MyIssuesPage])("routes surface refresh state into the page title (%#)", (Page) => {
+ it.each([
+ [IssuesPage, "workspace"],
+ [MyIssuesPage, "my"],
+ ] as const)("hands the surface controller to the view header (%#)", (Page, kind) => {
const { rerender } = renderWithI18n(<Page />);
const header = screen.getByRole("banner");
- expect(within(header).getByRole("heading")).toBeInTheDocument();
+ expect(within(header).getByRole("heading")).toHaveTextContent(kind);
expect(within(header).queryByRole("status")).not.toBeInTheDocument();
state.refreshing = true;
rerender(<Page />);
- act(() => vi.advanceTimersByTime(300));
expect(within(header).getByRole("status")).toBeInTheDocument();
-
- state.refreshing = false;
- rerender(<Page />);
- expect(within(header).queryByRole("status")).not.toBeInTheDocument();
expect(screen.getAllByRole("banner")).toHaveLength(1);
});
diff --git a/packages/views/layout/join-discord-card.test.tsx b/packages/views/layout/join-discord-card.test.tsx
deleted file mode 100644
index 914f9f86ef..0000000000
--- a/packages/views/layout/join-discord-card.test.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { JoinDiscordCard } from "./join-discord-card";
-
-// react-i18next isn't initialised in the views test env, so resolve the
-// selector against the real en/layout.json to assert on actual copy.
-vi.mock("../i18n", () => ({
- useT: () => ({
- t: (sel: (r: { sidebar: { discord_card: Record<string, string> } }) => string) =>
- sel({
- sidebar: {
- discord_card: {
- title: "Join our Discord",
- dismiss: "Dismiss",
- },
- },
- }),
- }),
-}));
-
-const userId = { current: "user-1" as string | undefined };
-vi.mock("@multica/core/auth", () => ({
- useAuthStore: (selector: (s: { user?: { id?: string } }) => unknown) =>
- selector({ user: userId.current ? { id: userId.current } : undefined }),
-}));
-
-afterEach(() => {
- localStorage.clear();
- userId.current = "user-1";
-});
-
-describe("JoinDiscordCard", () => {
- it("links to the Discord invite", () => {
- render(<JoinDiscordCard />);
- const link = screen.getByRole("link", { name: /join our discord/i });
- expect(link).toHaveAttribute("href", "https://discord.gg/W8gYBn226t");
- expect(link).toHaveAttribute("target", "_blank");
- });
-
- it("hides and stays hidden after dismiss, persisting per user", async () => {
- const user = userEvent.setup();
- const { unmount } = render(<JoinDiscordCard />);
-
- await user.click(screen.getByRole("button", { name: "Dismiss" }));
- expect(screen.queryByText("Join our Discord")).not.toBeInTheDocument();
-
- // A fresh mount for the same user keeps the card hidden.
- unmount();
- render(<JoinDiscordCard />);
- expect(screen.queryByText("Join our Discord")).not.toBeInTheDocument();
- });
-
- it("keeps the card visible for a different user", async () => {
- const user = userEvent.setup();
- const { unmount } = render(<JoinDiscordCard />);
- await user.click(screen.getByRole("button", { name: "Dismiss" }));
- unmount();
-
- userId.current = "user-2";
- render(<JoinDiscordCard />);
- expect(screen.getByText("Join our Discord")).toBeInTheDocument();
- });
-});
diff --git a/packages/views/layout/join-discord-card.tsx b/packages/views/layout/join-discord-card.tsx
deleted file mode 100644
index 2f14db8da1..0000000000
--- a/packages/views/layout/join-discord-card.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-"use client";
-
-import { X } from "@multica/ui/icons";
-import { useAuthStore } from "@multica/core/auth";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-import { DISCORD_URL, DiscordIcon } from "./discord";
-import { useDiscordCardDismissed } from "./use-discord-card-dismissed";
-import { useT } from "../i18n";
-
-/**
- * Dismissible "Join our Discord" entry sharing the sidebar footer strip with
- * the help launcher. Once dismissed it stays hidden for that user on this
- * browser — see {@link useDiscordCardDismissed}.
- *
- * Deliberately shaped as a sidebar row, not a bordered card: it matches
- * SidebarMenuButton metrics (h-8 / rounded-md / gap-2 / text-body) and
- * carries no resting border or fill. A dismissible promo is the
- * lowest-priority item in the sidebar, so it must not be drawn heavier than
- * the navigation above it.
- *
- * No external-link arrow, unlike the Help menu's outbound items: sharing one
- * 224px strip with the help trigger leaves 128px for the label, and the arrow
- * plus the dismiss button together overflow that in the widest locale (en,
- * 109px). The dismiss affordance wins because it is a user-facing capability
- * and the arrow is only a hint — the Discord mark already signals the
- * destination. `flex-1 min-w-0` makes the label truncate rather than push the
- * trigger off.
- *
- * That 128px is the budget at the DEFAULT 256px sidebar, and the sidebar is
- * user-resizable down to 200px — every 1px of drag takes 1px from the label.
- * So a title that merely fits at 256px still truncates for anyone who has
- * narrowed their sidebar; keep every locale's title comfortably under budget,
- * not just under it (MUL-5704).
- */
-export function JoinDiscordCard() {
- const { t } = useT("layout");
- const userId = useAuthStore((s) => s.user?.id);
- const [dismissed, dismiss] = useDiscordCardDismissed(userId);
-
- if (dismissed) return null;
-
- return (
- <div className="group/discord relative min-w-0 flex-1">
- <a
- href={DISCORD_URL}
- target="_blank"
- rel="noopener noreferrer"
- className="flex h-8 items-center gap-2 rounded-md px-2 pr-8 text-body text-muted-foreground ring-sidebar-ring outline-hidden transition-colors hover:bg-sidebar-accent/70 hover:text-sidebar-accent-foreground focus-visible:ring-2"
- >
- <DiscordIcon className="size-4 shrink-0" />
- <span className="truncate">
- {t(($) => $.sidebar.discord_card.title)}
- </span>
- </a>
- {/* Revealed on hover/focus so the resting row stays quiet. Coarse
- pointers get no hover, so keep it permanently visible there. */}
- <TooltipHint label={t(($) => $.sidebar.discord_card.dismiss)}>
- <button
- type="button"
- aria-label={t(($) => $.sidebar.discord_card.dismiss)}
- onClick={dismiss}
- className="absolute inset-y-0 right-1 my-auto flex size-6 cursor-pointer items-center justify-center rounded-sm text-muted-foreground opacity-0 ring-sidebar-ring transition-opacity hover:bg-sidebar-accent hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 group-hover/discord:opacity-100 [@media(hover:none)]:opacity-100"
- >
- <X className="size-3.5" />
- </button>
- </TooltipHint>
- </div>
- );
-}
diff --git a/packages/views/layout/list-column.test.tsx b/packages/views/layout/list-column.test.tsx
new file mode 100644
index 0000000000..90bc40dc75
--- /dev/null
+++ b/packages/views/layout/list-column.test.tsx
@@ -0,0 +1,76 @@
+import { act, fireEvent } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { SidebarProvider } from "@multica/ui/components/ui/sidebar";
+import { renderWithI18n } from "../test/i18n";
+import { AppShellProvider, useAppShell } from "./app-shell-context";
+import { ListColumn } from "./list-column";
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ pathname: "/acme/inbox" }),
+}));
+
+let shell: ReturnType<typeof useAppShell> = null;
+function Reader() {
+ shell = useAppShell();
+ return null;
+}
+
+describe("ListColumn", () => {
+ it("collapses the list column from its edge, like the space panel", () => {
+ const { container } = renderWithI18n(
+ <SidebarProvider>
+ <AppShellProvider>
+ <Reader />
+ <ListColumn>list</ListColumn>
+ </AppShellProvider>
+ </SidebarProvider>,
+ );
+
+ expect(container.querySelector("[data-slot='list-column']")).toHaveClass(
+ "w-(--sidebar-width)",
+ );
+ fireEvent.click(container.querySelector("[data-slot='space-panel-resize']")!);
+ expect(shell?.listCollapsed).toBe(true);
+ });
+
+ it("renders without a resize edge outside the shell", () => {
+ const { container } = renderWithI18n(<ListColumn>list</ListColumn>);
+ expect(container.querySelector("[data-slot='space-panel-resize']")).toBeNull();
+ });
+
+ // Collapsing animates the width rather than unmounting, like the space panel.
+ it("stays mounted and inert while collapsed", () => {
+ const { container } = renderWithI18n(<ListColumn collapsed>list</ListColumn>);
+ const column = container.querySelector("[data-slot='list-column']");
+ expect(column).toHaveAttribute("data-state", "collapsed");
+ expect(column).toHaveAttribute("inert");
+ expect(column).toHaveClass("w-0", "transition-[width]");
+ expect(column).toHaveTextContent("list");
+ });
+
+ it("floats over the page while its rail item is hovered, then tucks back", () => {
+ vi.useFakeTimers();
+ try {
+ const { container } = renderWithI18n(
+ <SidebarProvider>
+ <AppShellProvider>
+ <Reader />
+ <ListColumn collapsed>list</ListColumn>
+ </AppShellProvider>
+ </SidebarProvider>,
+ );
+ const column = container.querySelector("[data-slot='list-column']");
+ act(() => shell!.requestPeek("inbox"));
+ act(() => vi.advanceTimersByTime(200));
+ expect(column).not.toHaveAttribute("inert");
+ expect(column).toHaveClass("w-0");
+ expect(container.querySelector("[data-slot='list-column-peek']")).toHaveTextContent("list");
+
+ act(() => shell!.closePeek());
+ expect(column).toHaveAttribute("inert");
+ expect(container.querySelector("[data-slot='list-column-peek']")).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/views/layout/list-column.tsx b/packages/views/layout/list-column.tsx
new file mode 100644
index 0000000000..9149c6d300
--- /dev/null
+++ b/packages/views/layout/list-column.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useRef } from "react";
+import { useSidebarSafe } from "@multica/ui/components/ui/sidebar";
+import { cn } from "@multica/ui/lib/utils";
+import { useAppShell } from "./app-shell-context";
+import { PanelResizeHandle } from "./panel-resize-handle";
+import { NAV_COLUMN_MOTION_CLASS, NAV_PEEK_CLASS } from "./rail-styles";
+
+/**
+ * The list column of a list-and-detail page (Inbox, Chat, Settings). It takes
+ * the space panel's width, resize edge and collapse motion, so the column's
+ * divider stays put when switching between spaces and one drag resizes them
+ * all. It stays mounted while collapsed, keeping the list's scroll position.
+ */
+export function ListColumn({
+ collapsed = false,
+ className,
+ innerClassName,
+ children,
+}: {
+ collapsed?: boolean;
+ className?: string;
+ innerClassName?: string;
+ children: React.ReactNode;
+}) {
+ const ref = useRef<HTMLElement>(null);
+ const sidebar = useSidebarSafe();
+ const shell = useAppShell();
+ const onToggle = shell?.toggleNav ?? sidebar?.toggleSidebar;
+ // Hovering this space's rail item while collapsed floats the column itself
+ // over the page. Only the inner box moves, so the column keeps its width
+ // (no collapse motion) and the list keeps its state.
+ const peeking = collapsed && !!shell?.peekSpace && shell.peekSpace === shell.space;
+
+ return (
+ <>
+ <aside
+ ref={ref}
+ data-slot="list-column"
+ data-state={collapsed ? "collapsed" : "expanded"}
+ inert={collapsed && !peeking}
+ className={cn(
+ "relative flex h-full shrink-0 justify-end",
+ NAV_COLUMN_MOTION_CLASS,
+ collapsed ? "w-0" : "w-(--sidebar-width)",
+ !peeking && "overflow-hidden",
+ className,
+ )}
+ >
+ <div
+ data-slot={peeking ? "list-column-peek" : undefined}
+ onPointerEnter={peeking ? shell.holdPeek : undefined}
+ onPointerLeave={peeking ? shell.releasePeek : undefined}
+ className={cn(
+ "flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden",
+ peeking ? NAV_PEEK_CLASS : cn("border-r", innerClassName),
+ )}
+ >
+ {children}
+ </div>
+ </aside>
+ {!collapsed && sidebar && !sidebar.isCompact && onToggle && (
+ <div className="relative w-0 shrink-0">
+ <PanelResizeHandle panelRef={ref} onToggle={onToggle} />
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/packages/views/layout/object-page.test.tsx b/packages/views/layout/object-page.test.tsx
new file mode 100644
index 0000000000..68569c07f4
--- /dev/null
+++ b/packages/views/layout/object-page.test.tsx
@@ -0,0 +1,75 @@
+import { screen, within } from "@testing-library/react";
+import { Pencil } from "@multica/ui/icons";
+import { describe, expect, it, vi } from "vitest";
+import { NavigationProvider, type NavigationAdapter } from "../navigation";
+import { renderWithI18n } from "../test/i18n";
+import {
+ ObjectIdentity,
+ ObjectPage,
+ ObjectProperty,
+ ObjectSection,
+ ObjectSectionAction,
+} from "./object-page";
+
+function makeAdapter(): NavigationAdapter {
+ return {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/agents/a1",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ };
+}
+
+function renderPage(panel?: React.ReactNode) {
+ return renderWithI18n(
+ <NavigationProvider value={makeAdapter()}>
+ <ObjectPage
+ layoutId="test_object_page"
+ segments={[{ href: "/acme/agents", label: "Agents" }]}
+ leaf={<span>Lambda</span>}
+ actions={<button type="button">Assign work</button>}
+ panel={panel}
+ >
+ <ObjectIdentity media={<span />} title="Lambda" description="Design and frontend" />
+ <ObjectSection
+ title="Instructions"
+ action={<ObjectSectionAction icon={Pencil}>Edit</ObjectSectionAction>}
+ >
+ <p>Mock before you build.</p>
+ </ObjectSection>
+ </ObjectPage>
+ </NavigationProvider>,
+ );
+}
+
+describe("ObjectPage", () => {
+ it("puts the list it came from in the breadcrumb and the actions in the header", () => {
+ renderPage();
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("link", { name: "Agents" })).toHaveAttribute("href", "/acme/agents");
+ expect(within(header).getByText("Lambda")).toBeInTheDocument();
+ expect(within(header).getByRole("button", { name: "Assign work" })).toBeInTheDocument();
+ });
+
+ it("carries a section's actions on the section title, not in the header", () => {
+ renderPage();
+ const section = screen.getByRole("heading", { name: "Instructions", level: 2 }).closest("section")!;
+ expect(within(section).getByRole("button", { name: "Edit" })).toBeInTheDocument();
+ expect(within(screen.getByRole("banner")).queryByRole("button", { name: "Edit" })).toBeNull();
+ });
+
+ it("adds the panel toggle only when the page has a panel", () => {
+ renderPage();
+ expect(screen.queryByRole("button", { name: "Toggle right sidebar" })).toBeNull();
+ });
+
+ it("renders the properties panel beside the body", () => {
+ renderPage(<ObjectProperty label="Runtime">MacBook Pro</ObjectProperty>);
+ expect(screen.getByRole("button", { name: "Toggle right sidebar" })).toBeInTheDocument();
+ expect(screen.getByText("Runtime")).toBeInTheDocument();
+ expect(screen.getByText("MacBook Pro")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/layout/object-page.tsx b/packages/views/layout/object-page.tsx
new file mode 100644
index 0000000000..8f23fb1198
--- /dev/null
+++ b/packages/views/layout/object-page.tsx
@@ -0,0 +1,333 @@
+"use client";
+
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ComponentProps,
+ type ReactNode,
+} from "react";
+import { useDefaultLayout, usePanelRef } from "react-resizable-panels";
+import { ChevronRight, PanelRight, type IconComponent } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@multica/ui/components/ui/resizable";
+import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
+import { useIsMobile } from "@multica/ui/hooks/use-mobile";
+import { cn } from "@multica/ui/lib/utils";
+import { ActionShortcutKeycaps } from "../common/shortcut-keycaps";
+import { useT } from "../i18n";
+import {
+ AnimatedRightSidebar,
+ getAnimatedRightSidebarInitialOpen,
+ rightSidebarPanelMotionProps,
+ useAnimatedRightSidebarState,
+ useRightSidebarShortcut,
+} from "./animated-right-sidebar";
+import { BreadcrumbHeader, type BreadcrumbSegment } from "./breadcrumb-header";
+
+/** The reading column of an object page; the header above it stays full width. */
+export const OBJECT_PAGE_BODY = "mx-auto w-full max-w-[760px] px-6 py-8";
+
+interface ObjectPageProps {
+ /** The lists this object was opened from, each one a link back. */
+ segments: BreadcrumbSegment[];
+ /** The object's own crumb. */
+ leaf: ReactNode;
+ /**
+ * Header actions, before the panel toggle: icon actions, the page's one
+ * solid action, then the ⋯ menu.
+ */
+ actions?: ReactNode;
+ /** The properties panel. Omit and the page has no panel or toggle. */
+ panel?: ReactNode;
+ /** Persists the panel's size and open state per kind of object. */
+ layoutId: string;
+ /**
+ * The body. Loading, error and not-found states go here too: the header
+ * keeps its place while the body changes.
+ */
+ children: ReactNode;
+}
+
+/**
+ * The page for one object opened from a list: a breadcrumb header, the body
+ * as sections in a centred column, and the object's editable properties in a
+ * right panel the header toggles — the layout the issue page already uses.
+ * There are no tabs: what a tab would hold is a section of the body.
+ */
+export function ObjectPage({ segments, leaf, actions, panel, layoutId, children }: ObjectPageProps) {
+ const { t } = useT("layout");
+ const isMobile = useIsMobile();
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({ id: layoutId });
+ const panelRef = usePanelRef();
+ const shortcutTargetRef = useRef<HTMLDivElement | null>(null);
+ // Desktop and mobile keep separate state: a mobile sheet that shared the
+ // desktop's open default would mount open over the page.
+ const {
+ open: desktopOpen,
+ visualOpen,
+ motionEnabled,
+ beginToggle,
+ handleResize,
+ } = useAnimatedRightSidebarState(getAnimatedRightSidebarInitialOpen(true, defaultLayout));
+ const [mobileOpen, setMobileOpen] = useState(false);
+ const open = isMobile ? mobileOpen : desktopOpen;
+
+ useEffect(() => {
+ if (isMobile) setMobileOpen(false);
+ }, [isMobile]);
+
+ const toggle = useCallback(() => {
+ if (isMobile) {
+ setMobileOpen((value) => !value);
+ return;
+ }
+ const sidebar = panelRef.current;
+ if (!sidebar) return;
+ const nextOpen = sidebar.isCollapsed();
+ beginToggle(nextOpen);
+ window.requestAnimationFrame(() => {
+ if (nextOpen) sidebar.expand();
+ else sidebar.collapse();
+ });
+ }, [beginToggle, isMobile, panelRef]);
+
+ useRightSidebarShortcut(shortcutTargetRef, toggle);
+
+ const header = (
+ <BreadcrumbHeader
+ segments={segments}
+ leaf={leaf}
+ actions={
+ actions || panel ? (
+ <>
+ {actions}
+ {panel ? (
+ <IconButton
+ label={t(($) => $.object_page.toggle_panel)}
+ shortcut={<ActionShortcutKeycaps action="toggleRightSidebar" />}
+ tooltipSide="bottom"
+ variant={open ? "secondary" : "ghost"}
+ className={open ? undefined : "text-muted-foreground"}
+ onClick={toggle}
+ >
+ <PanelRight />
+ </IconButton>
+ ) : null}
+ </>
+ ) : undefined
+ }
+ />
+ );
+
+ const body = <div className="min-h-0 flex-1 overflow-y-auto">{children}</div>;
+
+ if (!panel) {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {header}
+ {body}
+ </div>
+ );
+ }
+
+ return (
+ <div ref={shortcutTargetRef} className="flex min-h-0 flex-1 flex-col">
+ {header}
+ <ResizablePanelGroup
+ orientation="horizontal"
+ className="min-h-0 flex-1"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ >
+ <ResizablePanel id="content" minSize="50%">
+ <div className="flex h-full flex-col">{body}</div>
+ </ResizablePanel>
+ {!isMobile && <ResizableHandle />}
+ {!isMobile && (
+ <ResizablePanel
+ id="sidebar"
+ {...rightSidebarPanelMotionProps}
+ data-right-sidebar-motion={motionEnabled ? "enabled" : undefined}
+ defaultSize={desktopOpen ? 300 : 0}
+ minSize={260}
+ maxSize={420}
+ collapsible
+ groupResizeBehavior="preserve-pixel-size"
+ panelRef={panelRef}
+ onResize={handleResize}
+ >
+ <AnimatedRightSidebar open={visualOpen} motionEnabled={motionEnabled}>
+ {panel}
+ </AnimatedRightSidebar>
+ </ResizablePanel>
+ )}
+ </ResizablePanelGroup>
+ {isMobile && (
+ <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
+ <SheetContent side="right" showCloseButton={false} className="w-[300px] overflow-y-auto p-4">
+ {panel}
+ </SheetContent>
+ </Sheet>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The object's name block at the top of the body: a 48px mark, the name, and
+ * one line on what it is or does.
+ */
+export function ObjectIdentity({
+ media,
+ title,
+ description,
+ trailing,
+}: {
+ /** The avatar or icon, sized by the caller to 48px. */
+ media: ReactNode;
+ title: ReactNode;
+ description?: ReactNode;
+ /** Inline status next to the name, e.g. an "Archived" badge. */
+ trailing?: ReactNode;
+}) {
+ return (
+ <div className="flex items-center gap-3">
+ <div className="shrink-0">{media}</div>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-2">
+ <h1 className="min-w-0 truncate text-title font-semibold">{title}</h1>
+ {trailing}
+ </div>
+ {description ? (
+ <p className="mt-0.5 line-clamp-2 text-body text-muted-foreground">{description}</p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+/** The 48px square mark for objects that have an icon rather than an avatar. */
+export function ObjectIconMark({ icon: Icon, className }: { icon: IconComponent; className?: string }) {
+ return (
+ <div
+ className={cn(
+ "flex size-12 items-center justify-center rounded-xl border bg-muted/50 text-muted-foreground",
+ className,
+ )}
+ >
+ <Icon className="size-5" />
+ </div>
+ );
+}
+
+/**
+ * One part of an object's body. Its actions sit at the right of its title —
+ * Edit, Add, View all — so the header never has to carry them.
+ */
+export function ObjectSection({
+ title,
+ count,
+ action,
+ children,
+ className,
+}: {
+ title: ReactNode;
+ count?: ReactNode;
+ action?: ReactNode;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <section className={cn("space-y-2", className)}>
+ <div className="flex h-7 items-center gap-2">
+ <h2 className="text-body font-medium">{title}</h2>
+ {count !== undefined && count !== null ? (
+ <span className="text-caption tabular-nums text-muted-foreground">{count}</span>
+ ) : null}
+ {action ? <div className="ml-auto flex items-center gap-1">{action}</div> : null}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+/** A quiet text action for a section title: icon plus a short verb. */
+export function ObjectSectionAction({
+ icon: Icon,
+ children,
+ className,
+ ...props
+}: Omit<ComponentProps<typeof Button>, "variant" | "size"> & { icon?: IconComponent }) {
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ className={cn("h-7 gap-1.5 px-2 text-muted-foreground", className)}
+ {...props}
+ >
+ {Icon ? <Icon className="size-3.5" /> : null}
+ {children}
+ </Button>
+ );
+}
+
+/** The bordered box a section's rows sit in; rows divide with hairlines. */
+export function ObjectSectionCard({ children, className }: { children: ReactNode; className?: string }) {
+ return (
+ <div className={cn("divide-y overflow-hidden rounded-lg border bg-card", className)}>
+ {children}
+ </div>
+ );
+}
+
+/** A titled group in the properties panel, collapsible like the issue page's. */
+export function ObjectPanelSection({
+ title,
+ children,
+ defaultOpen = true,
+}: {
+ title: ReactNode;
+ children: ReactNode;
+ defaultOpen?: boolean;
+}) {
+ const [open, setOpen] = useState(defaultOpen);
+ return (
+ <div>
+ <button
+ type="button"
+ aria-expanded={open}
+ className={cn(
+ "mb-2 flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors hover:bg-accent/70",
+ !open && "text-muted-foreground hover:text-foreground",
+ )}
+ onClick={() => setOpen(!open)}
+ >
+ {title}
+ <ChevronRight
+ className={cn(
+ "!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform",
+ open && "rotate-90",
+ )}
+ />
+ </button>
+ {open ? <div className="space-y-0.5 pl-2">{children}</div> : null}
+ </div>
+ );
+}
+
+/** One label and value in the properties panel; the value may be a picker. */
+export function ObjectProperty({ label, children }: { label: ReactNode; children: ReactNode }) {
+ return (
+ <div className="-mx-2 flex min-h-8 items-center gap-2 rounded-md px-2 transition-colors hover:bg-accent/50">
+ <span className="w-20 shrink-0 truncate text-caption text-muted-foreground">{label}</span>
+ <div className="flex min-w-0 flex-1 items-center gap-1.5 truncate text-caption">{children}</div>
+ </div>
+ );
+}
diff --git a/packages/views/layout/page-header.test.tsx b/packages/views/layout/page-header.test.tsx
index 892dcb86e5..a7bc94bcc7 100644
--- a/packages/views/layout/page-header.test.tsx
+++ b/packages/views/layout/page-header.test.tsx
@@ -1,15 +1,22 @@
-import { ListTodo, Plus, Zap } from "@multica/ui/icons";
-import { within } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
+import { ListTodo, Zap } from "@multica/ui/icons";
+import { act, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
-import { SidebarProvider } from "@multica/ui/components/ui/sidebar";
+import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
import { renderWithI18n } from "../test/i18n";
+import { AppShellProvider } from "./app-shell-context";
import {
+ CollectionCreateButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
} from "./collection-page";
import { CollapsedNavTrigger, PAGE_GUTTER, PageHeader } from "./page-header";
+const navigation = vi.hoisted(() => ({ pathname: "/acme/issues" }));
+vi.mock("../navigation", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../navigation")>()),
+ useNavigation: () => ({ pathname: navigation.pathname }),
+}));
+
// The layout rules under test are documented on `PageHeader` itself; each
// test here pins one of them against the rendered output.
@@ -23,7 +30,7 @@ function renderHeader(
return within(container).getByRole("banner");
}
-// Below `xl` the collapsed-nav trigger renders as a third flex item, so the
+// Below `lg` the collapsed-nav trigger renders as a third flex item, so the
// title stays left only while nothing distributes the free space: the content
// group grows and the header never uses `justify-between`.
function expectTitleLeftOfFreeSpace(header: HTMLElement) {
@@ -39,10 +46,7 @@ describe("PageHeader title alignment", () => {
<CollectionPageHeader
icon={Zap}
title="Autopilot"
- count={2}
- actions={
- <CollectionPageHeaderAction icon={Plus} label="New autopilot" />
- }
+ actions={<CollectionCreateButton label="New autopilot" />}
/>,
);
@@ -113,3 +117,49 @@ describe("PageHeader base chrome", () => {
expect(container.querySelector("[data-slot='sidebar-trigger']")).toBeNull();
});
});
+
+// In the app shell the rail is always on screen from `md` up, so the trigger
+// only has a job there while the space panel is collapsed (and below `md`,
+// where the rail lives in the sheet).
+describe("CollapsedNavTrigger in the app shell", () => {
+ let sidebar: ReturnType<typeof useSidebar> | null = null;
+ function Reader() {
+ sidebar = useSidebar();
+ return null;
+ }
+ function renderInShell(pathname: string) {
+ navigation.pathname = pathname;
+ const { container } = renderWithI18n(
+ <SidebarProvider>
+ <AppShellProvider>
+ <Reader />
+ <CollapsedNavTrigger />
+ </AppShellProvider>
+ </SidebarProvider>,
+ );
+ return () => container.querySelector("[data-slot='sidebar-trigger']");
+ }
+
+ it("is a compact-only trigger while the panel is open", () => {
+ const trigger = renderInShell("/acme/issues");
+ expect(trigger()).toHaveClass("md:hidden");
+ });
+
+ it("shows at every width once the panel is collapsed", () => {
+ const trigger = renderInShell("/acme/issues");
+ act(() => sidebar!.setOpen(false));
+ expect(trigger()).not.toHaveClass("md:hidden");
+ });
+
+ // Inbox brings its own list column, so the panel's open state is not what
+ // the trigger reopens there; the collapsed list column is.
+ it("follows the list column in spaces without a shell panel", () => {
+ const trigger = renderInShell("/acme/inbox");
+ act(() => sidebar!.setOpen(false));
+ expect(trigger()).toHaveClass("md:hidden");
+
+ act(() => (trigger() as HTMLButtonElement).click());
+ expect(trigger()).not.toHaveClass("md:hidden");
+ expect(sidebar!.state).toBe("collapsed");
+ });
+});
diff --git a/packages/views/layout/page-header.tsx b/packages/views/layout/page-header.tsx
index 528ebc07a0..14302f9459 100644
--- a/packages/views/layout/page-header.tsx
+++ b/packages/views/layout/page-header.tsx
@@ -3,6 +3,7 @@
import { cn } from "@multica/ui/lib/utils";
import { SidebarTrigger, useSidebarSafe } from "@multica/ui/components/ui/sidebar";
import { ActionShortcutKeycaps } from "../common/shortcut-keycaps";
+import { useAppShell } from "./app-shell-context";
/**
* The left edge every page shares: the header, the toolbar under it, and any
@@ -49,9 +50,9 @@ export const PAGE_TOOLBAR = cn(
/**
* The way back to the nav wherever it is not a permanent column: a sheet below
- * the compact breakpoint, auto-collapsed from there up to `xl`.
+ * the compact breakpoint and, in the app shell, a collapsed space panel.
*
- * Every surface below `xl` needs one of these — unless the shell around it
+ * Every surface needs one of these — unless the shell around it
* already keeps one on screen. `PageHeader` supplies it for free, so this is
* exported for the pages that build their own chrome instead; without it a
* touch user has no way to reopen the nav at all.
@@ -65,11 +66,30 @@ export const PAGE_TOOLBAR = cn(
*/
export function CollapsedNavTrigger() {
const sidebar = useSidebarSafe();
+ const shell = useAppShell();
if (!sidebar || sidebar.hasExternalTrigger) return null;
+ // In the app shell the rail is always on screen from `md` up, so the
+ // trigger only has a job there while the space panel or list column is
+ // collapsed. The `md:hidden` gate is CSS so the compact case is right
+ // before hydration.
+ const collapsed = shell
+ ? shell.hasPanel
+ ? sidebar.state === "collapsed"
+ : shell.listCollapsed
+ : false;
+ const className = shell ? (collapsed ? undefined : "md:hidden") : "lg:hidden";
return (
<SidebarTrigger
- className="xl:hidden"
+ className={className}
shortcut={<ActionShortcutKeycaps action="toggleSidebar" />}
+ onClick={
+ shell
+ ? (event) => {
+ event.preventDefault();
+ shell.toggleNav();
+ }
+ : undefined
+ }
/>
);
}
@@ -95,8 +115,8 @@ interface PageHeaderProps {
*
* The leading slot below is a flex item too, so a header that reads as two
* zones in source is three at runtime, and `justify-between` splits the free
- * space on BOTH sides of the title — parking it mid-header. Desktop windows
- * sit below `xl`, where the trigger renders, so that is where it surfaces.
+ * space on BOTH sides of the title — parking it mid-header. Narrow windows
+ * sit below `lg`, where the trigger renders, so that is where it surfaces.
*
* `gap-2` is the base for the same reason: it makes the header's own gap the
* single source of the leading-slot spacing. When the trigger carried its own
diff --git a/packages/views/layout/panel-nav.tsx b/packages/views/layout/panel-nav.tsx
new file mode 100644
index 0000000000..07c0161923
--- /dev/null
+++ b/packages/views/layout/panel-nav.tsx
@@ -0,0 +1,219 @@
+"use client";
+
+import { useId, useRef } from "react";
+import { ChevronDown } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
+import { AppLink } from "../navigation";
+
+/**
+ * Building blocks of the space panels. Rows share the Settings navigation
+ * styling: Settings renders its own column in the same card, and switching
+ * between it and a shell panel must not change how a nav row looks.
+ */
+
+/** A section root stays lit on its child routes (a project on its detail page). */
+export function isPathWithin(pathname: string, href: string): boolean {
+ return pathname === href || pathname.startsWith(href + "/");
+}
+
+/**
+ * The title band of every left column — the space panels and the list columns
+ * of Inbox, Chat and Settings — so the space name reads the same in all of
+ * them. Pages that own the column (Inbox, Chat, Settings) render it as their h1.
+ */
+export function PanelHeader({
+ title,
+ as: Heading = "h2",
+ leading,
+ meta,
+ children,
+}: {
+ title: React.ReactNode;
+ as?: "h1" | "h2";
+ /** Before the title: the nav trigger on pages that also render below `md`. */
+ leading?: React.ReactNode;
+ /** Beside the title, e.g. a count. */
+ meta?: React.ReactNode;
+ /** Trailing actions (icon buttons). */
+ children?: React.ReactNode;
+}) {
+ return (
+ <div className="flex h-12 shrink-0 items-center gap-1 pl-5 pr-2">
+ {leading}
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {/* A control passed as the title truncates its own label; clipping
+ here would also cut off its hover background. */}
+ <Heading
+ className={cn(
+ "text-title-sm font-semibold",
+ typeof title === "string" ? "truncate" : "flex min-w-0",
+ )}
+ >
+ {title}
+ </Heading>
+ {meta}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+export function PanelBody({
+ children,
+ onClickCapture,
+}: {
+ children: React.ReactNode;
+ onClickCapture?: React.MouseEventHandler<HTMLDivElement>;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const fadeStyle = useScrollFade(ref, 24);
+ return (
+ <div
+ ref={ref}
+ style={fadeStyle}
+ onClickCapture={onClickCapture}
+ className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-2 pb-4 [&>section:first-child]:mt-0"
+ >
+ {children}
+ </div>
+ );
+}
+
+export function PanelSection({
+ label,
+ action,
+ collapsed,
+ onCollapsedChange,
+ children,
+}: {
+ label: string;
+ /** Rendered at the end of the label row (e.g. a create button). */
+ action?: React.ReactNode;
+ /** With `onCollapsedChange`, the label toggles the section's content. */
+ collapsed?: boolean;
+ onCollapsedChange?: (collapsed: boolean) => void;
+ children: React.ReactNode;
+}) {
+ const id = useId();
+ const contentId = useId();
+ const collapsible = !!onCollapsedChange;
+ return (
+ <section aria-labelledby={id} className="mt-5">
+ <div className="group/section flex h-7 items-center gap-1 pl-3 pr-1">
+ <h3 id={id} className="min-w-0 flex-1 truncate text-caption font-medium text-muted-foreground">
+ {collapsible ? (
+ <button
+ type="button"
+ aria-expanded={!collapsed}
+ aria-controls={collapsed ? undefined : contentId}
+ onClick={() => onCollapsedChange(!collapsed)}
+ className="-mx-1 flex max-w-full items-center gap-0.5 rounded-md px-1 outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
+ >
+ <span className="truncate">{label}</span>
+ <ChevronDown
+ aria-hidden
+ className={cn(
+ "size-3.5 shrink-0 transition-[transform,opacity] duration-150 ease-out motion-reduce:transition-none",
+ collapsed
+ ? "-rotate-90"
+ : "opacity-0 group-hover/section:opacity-100 group-focus-within/section:opacity-100",
+ )}
+ />
+ </button>
+ ) : (
+ label
+ )}
+ </h3>
+ {action}
+ </div>
+ {!collapsed && <div id={contentId}>{children}</div>}
+ </section>
+ );
+}
+
+export function PanelList({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"ul">) {
+ return (
+ <ul className={cn("space-y-px", className)} {...props}>
+ {children}
+ </ul>
+ );
+}
+
+export const PANEL_ROW_CLASS =
+ "flex min-h-8 w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-left text-body transition-colors outline-none focus-visible:outline-2 focus-visible:outline-ring";
+
+export function panelRowStateClass(active: boolean) {
+ return active
+ ? "bg-surface-selected text-surface-selected-foreground hover:bg-surface-selected"
+ : "text-muted-foreground hover:bg-surface-hover hover:text-foreground";
+}
+
+export function PanelCount({ value, className }: { value: number; className?: string }) {
+ if (value <= 0) return null;
+ return (
+ <span className={cn("shrink-0 text-caption tabular-nums text-faint-foreground", className)}>
+ {value}
+ </span>
+ );
+}
+
+interface PanelLinkProps {
+ href: string;
+ label: string;
+ active: boolean;
+ /** Leading visual; icons are sized by the row. */
+ icon?: React.ReactNode;
+ /** Second line under the label (agent activity, schedule). */
+ description?: React.ReactNode;
+ /** End of the row: a count, a status, a tag. */
+ trailing?: React.ReactNode;
+ /** Runs before navigation, e.g. to select a list scope the page reads. */
+ onNavigate?: () => void;
+ className?: string;
+}
+
+export function PanelLink({
+ href,
+ label,
+ active,
+ icon,
+ description,
+ trailing,
+ onNavigate,
+ className,
+}: PanelLinkProps) {
+ return (
+ <li>
+ <AppLink
+ href={href}
+ newTabTitle={label}
+ aria-current={active ? "page" : undefined}
+ onClick={onNavigate}
+ className={cn(
+ PANEL_ROW_CLASS,
+ panelRowStateClass(active),
+ "[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0",
+ className,
+ )}
+ >
+ {icon}
+ {description ? (
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate">{label}</span>
+ <span className="truncate text-caption font-normal text-muted-foreground">
+ {description}
+ </span>
+ </span>
+ ) : (
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ )}
+ {trailing}
+ </AppLink>
+ </li>
+ );
+}
diff --git a/packages/views/layout/panel-resize-handle.tsx b/packages/views/layout/panel-resize-handle.tsx
new file mode 100644
index 0000000000..e91bd0c85e
--- /dev/null
+++ b/packages/views/layout/panel-resize-handle.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import { useCallback, useEffect, useRef } from "react";
+import {
+ clampSidebarWidth,
+ useSidebarResize,
+} from "@multica/ui/components/ui/sidebar";
+import { useT } from "../i18n";
+
+const RESIZE_DRAG_THRESHOLD = 2;
+
+/**
+ * A column's trailing edge: drag to resize, click to collapse. Every column
+ * sized by `--sidebar-width` shares the one committed width. The preview
+ * writes the width straight onto the panel element and commits once on
+ * release, so a drag re-renders nothing until the pointer comes up.
+ */
+export function PanelResizeHandle({
+ panelRef,
+ onToggle,
+}: {
+ panelRef: React.RefObject<HTMLElement | null>;
+ onToggle: () => void;
+}) {
+ const { t } = useT("ui");
+ const { commitWidth } = useSidebarResize();
+ const cancelRef = useRef<(() => void) | null>(null);
+ const draggedRef = useRef(false);
+
+ useEffect(() => () => cancelRef.current?.(), []);
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLButtonElement>) => {
+ const panel = panelRef.current;
+ if (e.button !== 0 || e.isPrimary === false || !panel) return;
+ e.preventDefault();
+ cancelRef.current?.();
+ draggedRef.current = false;
+ const handle = e.currentTarget;
+ const pointerId = e.pointerId;
+ const startX = e.clientX;
+ const startWidth = clampSidebarWidth(panel.getBoundingClientRect().width);
+ let latestWidth = startWidth;
+ document.documentElement.setAttribute("data-sidebar-resizing", "true");
+
+ const finish = (mode: "commit" | "cancel") => {
+ document.removeEventListener("pointermove", onMove);
+ document.removeEventListener("pointerup", onUp);
+ document.removeEventListener("pointercancel", onCancel);
+ window.removeEventListener("blur", onBlur);
+ document.documentElement.removeAttribute("data-sidebar-resizing");
+ if (mode === "commit" && draggedRef.current) commitWidth(latestWidth);
+ panel.style.removeProperty("--sidebar-width");
+ cancelRef.current = null;
+ if (handle.hasPointerCapture?.(pointerId)) handle.releasePointerCapture?.(pointerId);
+ };
+ const onMove = (event: PointerEvent) => {
+ if (event.pointerId !== pointerId) return;
+ const delta = event.clientX - startX;
+ if (!draggedRef.current && Math.abs(delta) < RESIZE_DRAG_THRESHOLD) return;
+ draggedRef.current = true;
+ const next = clampSidebarWidth(startWidth + delta);
+ if (next === latestWidth) return;
+ latestWidth = next;
+ panel.style.setProperty("--sidebar-width", `${next}px`);
+ };
+ const onUp = (event: PointerEvent) => {
+ if (event.pointerId === pointerId) finish("commit");
+ };
+ const onCancel = (event: PointerEvent) => {
+ if (event.pointerId === pointerId) finish("cancel");
+ };
+ const onBlur = () => finish("cancel");
+
+ document.addEventListener("pointermove", onMove);
+ document.addEventListener("pointerup", onUp);
+ document.addEventListener("pointercancel", onCancel);
+ window.addEventListener("blur", onBlur);
+ cancelRef.current = () => finish("cancel");
+ handle.setPointerCapture?.(pointerId);
+ },
+ [commitWidth, panelRef],
+ );
+
+ return (
+ <button
+ type="button"
+ data-slot="space-panel-resize"
+ aria-label={t(($) => $.toggle_sidebar)}
+ title={t(($) => $.toggle_sidebar)}
+ tabIndex={-1}
+ onPointerDown={onPointerDown}
+ onClick={() => {
+ if (!draggedRef.current) onToggle();
+ }}
+ className="absolute inset-y-0 -right-1 z-20 w-2 cursor-ew-resize touch-none after:absolute after:inset-y-0 after:left-1/2 after:w-px after:-translate-x-1/2 after:transition-colors hover:after:bg-ring/60"
+ />
+ );
+}
diff --git a/packages/views/layout/panels/autopilots-panel.test.tsx b/packages/views/layout/panels/autopilots-panel.test.tsx
new file mode 100644
index 0000000000..4d0e665792
--- /dev/null
+++ b/packages/views/layout/panels/autopilots-panel.test.tsx
@@ -0,0 +1,109 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, screen, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
+import { useAutopilotsViewStore } from "@multica/core/autopilots/stores";
+import type { Autopilot } from "@multica/core/types";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import { renderWithI18n } from "../../test/i18n";
+import { AutopilotsPanel } from "./autopilots-panel";
+
+vi.mock("@multica/core/api", () => ({
+ api: { listAutopilots: vi.fn(), listWorkspaceWakeups: vi.fn() },
+}));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws" }),
+ useWorkspacePaths: () => ({
+ autopilots: () => "/ws/autopilots",
+ autopilotDetail: (id: string) => `/ws/autopilots/${id}`,
+ }),
+}));
+
+function autopilot(id: string, title: string, status: Autopilot["status"]): Autopilot {
+ return { id, title, status, trigger_kinds: ["schedule"] } as unknown as Autopilot;
+}
+
+function mount(path: string, push = vi.fn()) {
+ const url = new URL(path, "https://example.test");
+ const adapter: NavigationAdapter = {
+ pathname: url.pathname,
+ searchParams: url.searchParams,
+ hash: "",
+ push,
+ replace: vi.fn(),
+ back: vi.fn(),
+ getShareableUrl: (p) => p,
+ };
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return renderWithI18n(
+ <QueryClientProvider client={client}>
+ <NavigationProvider value={adapter}>
+ <AutopilotsPanel />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+}
+
+const allRow = () => screen.getByRole("link", { name: /^All autopilots/ });
+const wakeupsRow = () => screen.getByRole("link", { name: /^Issue wakeups/ });
+
+beforeEach(() => {
+ useAutopilotsViewStore.setState({ scope: "all" });
+ vi.mocked(api.listAutopilots).mockReset().mockResolvedValue({
+ autopilots: [
+ autopilot("a1", "Daily sync", "active"),
+ autopilot("a2", "Weekly report", "paused"),
+ autopilot("a3", "Old digest", "archived"),
+ ],
+ total: 3,
+ });
+ vi.mocked(api.listWorkspaceWakeups).mockReset().mockResolvedValue({
+ items: [],
+ total: 0,
+ counts: { all: 9, active: 5, paused: 1, disabled: 2, ended: 1 },
+ agents: [],
+ });
+});
+
+describe("AutopilotsPanel", () => {
+ it("links the list and the wakeups with their counts, the list active", async () => {
+ mount("/ws/autopilots");
+ await screen.findByRole("link", { name: /Daily sync/ });
+
+ expect(allRow()).toHaveAttribute("href", "/ws/autopilots");
+ expect(allRow()).toHaveAttribute("aria-current", "page");
+ expect(within(allRow()).getByText("2")).toBeInTheDocument();
+
+ expect(wakeupsRow()).toHaveAttribute("href", "/ws/autopilots?tab=wakeups");
+ expect(wakeupsRow()).not.toHaveAttribute("aria-current");
+ expect(await within(wakeupsRow()).findByText("5")).toBeInTheDocument();
+ });
+
+ it("marks only the wakeups row on ?tab=wakeups", async () => {
+ mount("/ws/autopilots?tab=wakeups");
+ await screen.findByRole("link", { name: /Daily sync/ });
+
+ expect(wakeupsRow()).toHaveAttribute("aria-current", "page");
+ expect(allRow()).not.toHaveAttribute("aria-current");
+ });
+
+ it("leaves both top rows inactive on an autopilot's page", async () => {
+ mount("/ws/autopilots/a1");
+ const detailRow = await screen.findByRole("link", { name: /Daily sync/ });
+
+ expect(detailRow).toHaveAttribute("aria-current", "page");
+ expect(allRow()).not.toHaveAttribute("aria-current");
+ expect(wakeupsRow()).not.toHaveAttribute("aria-current");
+ });
+
+ it("opens the list on its full scope", async () => {
+ useAutopilotsViewStore.setState({ scope: "paused" });
+ const push = vi.fn();
+ mount("/ws/autopilots?tab=wakeups", push);
+ await screen.findByRole("link", { name: /Daily sync/ });
+
+ fireEvent.click(allRow());
+ expect(useAutopilotsViewStore.getState().scope).toBe("all");
+ expect(push).toHaveBeenCalledWith("/ws/autopilots");
+ });
+});
diff --git a/packages/views/layout/panels/autopilots-panel.tsx b/packages/views/layout/panels/autopilots-panel.tsx
new file mode 100644
index 0000000000..f053621374
--- /dev/null
+++ b/packages/views/layout/panels/autopilots-panel.tsx
@@ -0,0 +1,176 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { AlarmClock, Code, Clock, Plus, Webhook, Zap } from "@multica/ui/icons";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { autopilotListOptions } from "@multica/core/autopilots/queries";
+import { useAutopilotsViewStore } from "@multica/core/autopilots/stores";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import type { Autopilot } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { AUTOPILOT_TEMPLATES } from "../../autopilots/components/autopilot-templates";
+import {
+ isWakeupsTab,
+ wakeupCountsOptions,
+ wakeupsHref,
+} from "../../autopilots/components/wakeups-tab";
+import {
+ PanelBody,
+ PanelCount,
+ PanelHeader,
+ PanelLink,
+ PanelList,
+ PanelSection,
+ isPathWithin,
+} from "../panel-nav";
+
+const EMPTY_AUTOPILOTS: Autopilot[] = [];
+const PANEL_TEMPLATE_LIMIT = 3;
+
+// Server-driven enum: unknown kinds get the generic icon.
+const TRIGGER_ICONS: Record<string, typeof Zap> = {
+ schedule: Clock,
+ webhook: Webhook,
+ api: Code,
+};
+
+/** Last run failed on an autopilot that is still meant to run. */
+export function isAutopilotFailing(autopilot: Autopilot): boolean {
+ return autopilot.status === "active" && autopilot.last_run_status === "failed";
+}
+
+/** Workspace autopilots that need attention, for the rail badge and the panel. */
+export function useFailingAutopilots(wsId: string | undefined) {
+ const { data: autopilots = EMPTY_AUTOPILOTS } = useQuery({
+ ...autopilotListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ return useMemo(() => autopilots.filter(isAutopilotFailing), [autopilots]);
+}
+
+function hasDescription(autopilot: Autopilot): boolean {
+ return (
+ isAutopilotFailing(autopilot) ||
+ autopilot.status === "paused" ||
+ (autopilot.trigger_kinds?.length ?? 0) > 0
+ );
+}
+
+function AutopilotDescription({ autopilot }: { autopilot: Autopilot }) {
+ const { t } = useT("autopilots");
+ if (isAutopilotFailing(autopilot)) {
+ return <span className="text-destructive">{t(($) => $.run_status.failed)}</span>;
+ }
+ if (autopilot.status === "paused") return <>{t(($) => $.status.paused)}</>;
+ return (
+ <>
+ {(autopilot.trigger_kinds ?? [])
+ .map((kind) =>
+ kind === "schedule" || kind === "webhook" || kind === "api"
+ ? t(($) => $.trigger_kind[kind])
+ : kind,
+ )
+ .join(" · ")}
+ </>
+ );
+}
+
+export function AutopilotsPanel() {
+ const { t } = useT("layout");
+ const { t: tAutopilots } = useT("autopilots");
+ const p = useWorkspacePaths();
+ const { pathname, searchParams, push } = useNavigation();
+ const wsId = useCurrentWorkspace()?.id;
+ const setScope = useAutopilotsViewStore((s) => s.setScope);
+ const { data: autopilots = EMPTY_AUTOPILOTS } = useQuery({
+ ...autopilotListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { data: wakeups } = useQuery({
+ ...wakeupCountsOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const visible = useMemo(
+ () => autopilots.filter((autopilot) => autopilot.status !== "archived"),
+ [autopilots],
+ );
+ const onList = pathname === p.autopilots();
+ const onWakeups = onList && isWakeupsTab(searchParams);
+
+ return (
+ <>
+ <PanelHeader title={t(($) => $.nav.autopilots)}>
+ <IconButton
+ label={tAutopilots(($) => $.page.new_autopilot)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={() => push(`${p.autopilots()}?create=1`)}
+ >
+ <Plus />
+ </IconButton>
+ </PanelHeader>
+ <PanelBody>
+ <PanelList>
+ <PanelLink
+ href={p.autopilots()}
+ icon={<Zap />}
+ label={t(($) => $.panels.autopilots.all)}
+ active={onList && !onWakeups}
+ trailing={<PanelCount value={visible.length} />}
+ onNavigate={() => setScope("all")}
+ />
+ <PanelLink
+ href={wakeupsHref(p.autopilots())}
+ icon={<AlarmClock />}
+ label={tAutopilots(($) => $.wakeups.title)}
+ active={onWakeups}
+ trailing={<PanelCount value={wakeups?.counts.active ?? 0} />}
+ />
+ </PanelList>
+
+ {visible.length > 0 && (
+ <PanelSection label={t(($) => $.panels.autopilots.list)}>
+ <PanelList>
+ {visible.map((autopilot) => {
+ const href = p.autopilotDetail(autopilot.id);
+ const Icon = TRIGGER_ICONS[autopilot.trigger_kinds?.[0] ?? ""] ?? Zap;
+ return (
+ <PanelLink
+ key={autopilot.id}
+ href={href}
+ icon={<Icon />}
+ label={autopilot.title}
+ description={
+ hasDescription(autopilot) ? <AutopilotDescription autopilot={autopilot} /> : undefined
+ }
+ active={isPathWithin(pathname, href)}
+ />
+ );
+ })}
+ </PanelList>
+ </PanelSection>
+ )}
+
+ <PanelSection label={t(($) => $.panels.autopilots.templates)}>
+ <PanelList>
+ {AUTOPILOT_TEMPLATES.slice(0, PANEL_TEMPLATE_LIMIT).map((template) => {
+ const Icon = template.icon;
+ return (
+ <PanelLink
+ key={template.id}
+ href={`${p.autopilots()}?template=${template.id}`}
+ icon={<Icon />}
+ label={tAutopilots(($) => $.templates[template.id].title)}
+ active={false}
+ className="text-muted-foreground"
+ />
+ );
+ })}
+ </PanelList>
+ </PanelSection>
+ </PanelBody>
+ </>
+ );
+}
diff --git a/packages/views/layout/panels/list-space-peeks.tsx b/packages/views/layout/panels/list-space-peeks.tsx
new file mode 100644
index 0000000000..6bf6512f98
--- /dev/null
+++ b/packages/views/layout/panels/list-space-peeks.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useChatStore } from "@multica/core/chat";
+import { useSetChatSessionArchived } from "@multica/core/chat/mutations";
+import { chatSessionsOptions } from "@multica/core/chat/queries";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ filterInboxItems,
+ inboxFiltersForPrioritySupport,
+ inboxPriorityFilterSupport,
+ useInboxFilters,
+} from "@multica/core/inbox/filter-store";
+import { useArchiveInbox } from "@multica/core/inbox/mutations";
+import {
+ deduplicateInboxItems,
+ inboxListOptions,
+ useInboxUnreadCount,
+} from "@multica/core/inbox/queries";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { Agent, ChatSession, InboxItem } from "@multica/core/types";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import { ChatThreadList } from "../../chat/components/chat-thread-list";
+import { useT } from "../../i18n";
+import { InboxList } from "../../inbox/components/inbox-list";
+import { useIssueSurfaceActivity } from "../../issues/surface/activity";
+import { useNavigation } from "../../navigation";
+import { PanelCount, PanelHeader } from "../panel-nav";
+
+const EMPTY_INBOX: InboxItem[] = [];
+const EMPTY_SESSIONS: ChatSession[] = [];
+const EMPTY_AGENTS: Agent[] = [];
+
+/**
+ * Inbox previewed from another space: the list the Inbox page shows, under
+ * the same saved filters. Opening a row lands on it in the Inbox.
+ */
+export function InboxPeek() {
+ const { t } = useT("inbox");
+ const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
+ const { push } = useNavigation();
+ const { data: rawItems = EMPTY_INBOX } = useQuery(inboxListOptions(wsId));
+ const filters = useInboxFilters(wsId);
+ const { activityByIssueId } = useIssueSurfaceActivity();
+ const unreadCount = useInboxUnreadCount(wsId);
+ const archive = useArchiveInbox();
+
+ const items = useMemo(() => {
+ const effective = inboxFiltersForPrioritySupport(filters, inboxPriorityFilterSupport(rawItems));
+ return filterInboxItems(deduplicateInboxItems(rawItems), effective, {
+ activeIssueIds: effective.idleOnly ? new Set(activityByIssueId.keys()) : undefined,
+ });
+ }, [rawItems, filters, activityByIssueId]);
+
+ const open = (params: Record<string, string>) =>
+ push(`${p.inbox()}?${new URLSearchParams(params).toString()}`);
+
+ return (
+ <>
+ <PanelHeader
+ title={t(($) => $.page.title)}
+ meta={<PanelCount value={unreadCount} className="text-muted-foreground" />}
+ />
+ <InboxList
+ items={items}
+ view="inbox"
+ selectedKey=""
+ scrollRestoration={false}
+ onSelect={(item) => open({ issue: item.issue_id ?? item.id })}
+ onAction={(id) => archive.mutate(id)}
+ />
+ </>
+ );
+}
+
+/** Chat previewed from another space. Opening a thread lands on it in Chat. */
+export function ChatPeek() {
+ const { t } = useT("chat");
+ const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
+ const { push } = useNavigation();
+ const { data: sessions = EMPTY_SESSIONS } = useQuery(chatSessionsOptions(wsId));
+ const { data: agents = EMPTY_AGENTS } = useQuery(agentListOptions(wsId));
+ const activeSessionId = useChatStore((s) => s.activeSessionId);
+ const setArchived = useSetChatSessionArchived();
+
+ return (
+ <>
+ <PanelHeader title={t(($) => $.page.title)} />
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 py-1">
+ <ChatThreadList
+ sessions={sessions}
+ agents={agents}
+ activeSessionId={activeSessionId}
+ onSelectSession={(session) => push(`${p.chat()}?session=${session.id}`)}
+ onArchive={(session) => setArchived.mutate({ sessionId: session.id, archived: true })}
+ />
+ </div>
+ </>
+ );
+}
diff --git a/packages/views/layout/panels/pinned-section.test.tsx b/packages/views/layout/panels/pinned-section.test.tsx
new file mode 100644
index 0000000000..42c0c1f5fa
--- /dev/null
+++ b/packages/views/layout/panels/pinned-section.test.tsx
@@ -0,0 +1,166 @@
+import type { ReactNode } from "react";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "@multica/core/api";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
+import type { PinnedItem } from "@multica/core/types";
+import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
+import { renderWithI18n } from "../../test/i18n";
+import { PinnedSection, usePanelPins } from "./pinned-section";
+
+const state = vi.hoisted(() => ({
+ pins: [] as PinnedItem[],
+ detail: { isPending: false, isError: false, data: null as unknown, error: null as unknown },
+ deletePin: vi.fn(),
+}));
+
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog([]),
+}));
+vi.mock("@dnd-kit/core", () => ({
+ DndContext: ({ children }: { children: ReactNode }) => <>{children}</>,
+ PointerSensor: vi.fn(),
+ closestCenter: vi.fn(),
+ useSensor: vi.fn(),
+ useSensors: vi.fn(),
+}));
+vi.mock("@dnd-kit/sortable", () => ({
+ SortableContext: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useSortable: () => ({ attributes: {}, listeners: {}, setNodeRef: vi.fn() }),
+ verticalListSortingStrategy: vi.fn(),
+ arrayMove: vi.fn(),
+}));
+vi.mock("@dnd-kit/utilities", () => ({ CSS: { Translate: { toString: () => undefined } } }));
+vi.mock("../../navigation", () => ({
+ AppLink: ({ children, href, ...props }: { children: ReactNode; href: string } & React.ComponentProps<"a">) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("../../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));
+vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
+ TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
+});
+vi.mock("@multica/core/pins/queries", () => ({ pinListOptions: () => ({ queryKey: ["pins"] }) }));
+vi.mock("@multica/core/pins/mutations", () => ({
+ useDeletePin: () => ({ mutate: state.deletePin }),
+ useReorderPins: () => ({ mutate: vi.fn() }),
+}));
+vi.mock("@multica/core/issues/queries", () => ({ issueDetailOptions: () => ({ queryKey: ["issue"] }) }));
+vi.mock("@multica/core/projects/queries", () => ({ projectDetailOptions: () => ({ queryKey: ["project"] }) }));
+vi.mock("@multica/core/issue-views/queries", () => ({
+ issueViewDetailOptions: () => ({ queryKey: ["view"] }),
+}));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {
+ if (queryKey[0] === "pins") return { data: state.pins };
+ if (queryKey[0] === "issue") return state.detail;
+ return { isPending: true, isError: false, data: undefined, error: null };
+ },
+}));
+
+const pin = (n: number): PinnedItem => ({
+ id: `pin-${n}`,
+ workspace_id: "ws-1",
+ user_id: "user-1",
+ item_type: "issue",
+ item_id: `issue-${n}`,
+ position: n,
+ created_at: "2026-05-06T00:00:00Z",
+});
+
+let activePinnedRoute = false;
+function Harness({ pathname, currentIssueId = null }: { pathname: string; currentIssueId?: string | null }) {
+ const pins = usePanelPins("ws-1", "user-1", pathname, currentIssueId);
+ activePinnedRoute = pins.isActivePinnedRoute;
+ return <PinnedSection pins={pins} wsId="ws-1" />;
+}
+
+beforeEach(() => {
+ state.pins = [pin(1)];
+ state.detail = { isPending: false, isError: false, data: null, error: null };
+ state.deletePin.mockReset();
+ activePinnedRoute = false;
+ useSidebarTreeStore.setState({ pinnedCollapsed: false });
+});
+
+describe("PinnedSection", () => {
+ it("unpins items whose detail is gone", async () => {
+ state.detail = { isPending: false, isError: true, data: null, error: new ApiError("missing", 404, "Not Found") };
+ renderWithI18n(<Harness pathname="/acme/issues" />);
+ await waitFor(() => expect(state.deletePin).toHaveBeenCalledTimes(1));
+ });
+
+ it("keeps pins through other errors", async () => {
+ state.detail = { isPending: false, isError: true, data: null, error: new ApiError("error", 500, "Server Error") };
+ renderWithI18n(<Harness pathname="/acme/issues" />);
+ await waitFor(() => expect(state.deletePin).not.toHaveBeenCalled());
+ });
+
+ it("renders a loaded issue by its title and marks it active on its page", async () => {
+ state.detail = {
+ isPending: false,
+ isError: false,
+ data: { identifier: "MUL-123", title: "Keep this pin", status: "todo" },
+ error: null,
+ };
+ // The issue route rewrites the pin's UUID URL to the identifier form.
+ renderWithI18n(<Harness pathname="/acme/issues/MUL-123" currentIssueId="issue-1" />);
+ const row = (await screen.findByText("Keep this pin")).closest("a");
+ expect(row).toHaveAttribute("aria-current", "page");
+ expect(screen.queryByText("MUL-123 Keep this pin")).toBeNull();
+ expect(activePinnedRoute).toBe(true);
+ });
+
+ it("previews five pins and only counts a hidden pin as active once expanded", () => {
+ state.pins = Array.from({ length: 6 }, (_, i) => pin(i + 1));
+ state.detail = {
+ isPending: false,
+ isError: false,
+ data: { identifier: "MUL-1", title: "Pinned issue", status: "todo" },
+ error: null,
+ };
+ renderWithI18n(<Harness pathname="/acme/issues/MUL-6" currentIssueId="issue-6" />);
+ const lastPin = () => document.querySelector('a[href="/acme/issues/issue-6"]');
+
+ expect(lastPin()).toBeNull();
+ expect(activePinnedRoute).toBe(false);
+
+ fireEvent.click(screen.getByRole("button", { name: "Show 1 more…" }));
+ expect(lastPin()).toHaveAttribute("aria-current", "page");
+ expect(activePinnedRoute).toBe(true);
+
+ fireEvent.click(screen.getByRole("button", { name: "Show fewer" }));
+ expect(lastPin()).toBeNull();
+ });
+
+ it("collapses from the section label and stops claiming the active route", async () => {
+ state.detail = {
+ isPending: false,
+ isError: false,
+ data: { identifier: "MUL-123", title: "Keep this pin", status: "todo" },
+ error: null,
+ };
+ renderWithI18n(<Harness pathname="/acme/issues/MUL-123" currentIssueId="issue-1" />);
+ await screen.findByText("Keep this pin");
+ expect(activePinnedRoute).toBe(true);
+
+ fireEvent.click(screen.getByRole("button", { name: "Pinned" }));
+ expect(useSidebarTreeStore.getState().pinnedCollapsed).toBe(true);
+ expect(screen.queryByText("Keep this pin")).toBeNull();
+ expect(screen.getByRole("button", { name: "Pinned" })).toHaveAttribute("aria-expanded", "false");
+ expect(activePinnedRoute).toBe(false);
+ });
+
+ it("renders nothing without pins", () => {
+ state.pins = [];
+ const { container } = renderWithI18n(<Harness pathname="/acme/issues" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/views/layout/panels/pinned-section.tsx b/packages/views/layout/panels/pinned-section.tsx
new file mode 100644
index 0000000000..5c0fb6a923
--- /dev/null
+++ b/packages/views/layout/panels/pinned-section.tsx
@@ -0,0 +1,355 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ DndContext,
+ PointerSensor,
+ useSensor,
+ useSensors,
+ closestCenter,
+ type DragEndEvent,
+} from "@dnd-kit/core";
+import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { Folder, X } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { ShimmerText } from "@multica/ui/components/common/shimmer-text";
+import { ApiError } from "@multica/core/api";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { issueStatusCategory } from "@multica/core/issues";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import { projectDetailOptions } from "@multica/core/projects/queries";
+import { pinListOptions } from "@multica/core/pins/queries";
+import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
+import { useDeletePin, useReorderPins } from "@multica/core/pins/mutations";
+import { useWorkspacePaths, type WorkspacePaths } from "@multica/core/paths";
+import type { PinnedItem } from "@multica/core/types";
+import { AppLink } from "../../navigation";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { useT } from "../../i18n";
+import { PANEL_ROW_CLASS, PanelList, PanelSection, isPathWithin, panelRowStateClass } from "../panel-nav";
+import { IssueAgentBadge, SIDEBAR_SHIMMER_CLASS, useIssueAgentState } from "./sidebar-tree";
+
+// Stable empty default: an inline `= []` on useQuery is a new reference every
+// render while the query is disabled, which re-fires the sync effect below.
+const EMPTY_PINS: PinnedItem[] = [];
+const PINNED_PREVIEW_LIMIT = 5;
+
+function pinHref(p: WorkspacePaths, pin: PinnedItem): string {
+ return pin.item_type === "issue" ? p.issueDetail(pin.item_id) : p.projectDetail(pin.item_id);
+}
+
+/**
+ * Pin list state for the Issues panel. Lifted out of the section so the
+ * panel can keep its plain rows unlit while a pinned item is the page on
+ * screen.
+ *
+ * An issue pin matches by id, not by path: the issue route rewrites its UUID
+ * URL to the `MUL-123` form, which a pin's href never equals.
+ */
+export function usePanelPins(
+ wsId: string | undefined,
+ userId: string | undefined,
+ pathname: string,
+ currentIssueId: string | null,
+) {
+ const p = useWorkspacePaths();
+ const { data: allPins = EMPTY_PINS } = useQuery({
+ ...pinListOptions(wsId ?? "", userId ?? ""),
+ enabled: !!wsId && !!userId,
+ });
+ // View pins moved into the Views section's starred list; a reorder here
+ // still carries them so the cache keeps them.
+ const pinnedItems = useMemo(() => allPins.filter((pin) => pin.item_type !== "view"), [allPins]);
+ const viewPins = useMemo(() => allPins.filter((pin) => pin.item_type === "view"), [allPins]);
+
+ // Local presentational copy for drop-animation stability. Follows the query
+ // at rest; frozen during a drag so a mid-drag cache write (our own
+ // optimistic update, or a WS refetch) cannot reorder the DOM under dnd-kit
+ // while its drop animation is still interpolating.
+ const [localPinned, setLocalPinned] = useState<PinnedItem[]>(pinnedItems);
+ const [localPinnedWsId, setLocalPinnedWsId] = useState<string | null>(wsId ?? null);
+ const [expandedWsId, setExpandedWsId] = useState<string | null>(null);
+ const isDraggingRef = useRef(false);
+ useEffect(() => {
+ if (!isDraggingRef.current) setLocalPinned(pinnedItems);
+ }, [pinnedItems]);
+ useEffect(() => {
+ setLocalPinnedWsId(wsId ?? null);
+ }, [wsId]);
+
+ const visible = localPinnedWsId === (wsId ?? null) ? localPinned : EMPTY_PINS;
+ const expanded = expandedWsId === (wsId ?? null);
+ const displayed = expanded ? visible : visible.slice(0, PINNED_PREVIEW_LIMIT);
+ const isPinActive = (pin: PinnedItem) =>
+ pin.item_type === "issue"
+ ? pin.item_id === currentIssueId
+ : isPathWithin(pathname, pinHref(p, pin));
+ // A collapsed section shows no rows, so it must not keep the tree unlit.
+ const pinnedCollapsed = useSidebarTreeStore((s) => s.pinnedCollapsed);
+ const isActivePinnedRoute = !pinnedCollapsed && displayed.some(isPinActive);
+
+ return {
+ visible,
+ displayed,
+ expanded,
+ isActivePinnedRoute,
+ isPinActive,
+ setExpanded: (next: boolean) => setExpandedWsId(next ? wsId ?? null : null),
+ setLocalPinned,
+ isDraggingRef,
+ viewPins,
+ };
+}
+
+type PanelPins = ReturnType<typeof usePanelPins>;
+
+export function PinnedSection({ pins, wsId }: { pins: PanelPins; wsId: string }) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const deletePin = useDeletePin();
+ const reorderPins = useReorderPins();
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
+ const { visible, displayed, expanded, setExpanded, setLocalPinned, isDraggingRef, viewPins, isPinActive } = pins;
+ const collapsed = useSidebarTreeStore((s) => s.pinnedCollapsed);
+ const setCollapsed = useSidebarTreeStore((s) => s.setPinnedCollapsed);
+
+ const handleDragStart = useCallback(() => {
+ isDraggingRef.current = true;
+ }, [isDraggingRef]);
+ const handleDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ isDraggingRef.current = false;
+ const { active, over } = event;
+ if (!over || active.id === over.id) return;
+ const oldIndex = visible.findIndex((pin) => pin.id === active.id);
+ const newIndex = visible.findIndex((pin) => pin.id === over.id);
+ if (oldIndex === -1 || newIndex === -1) return;
+ const reordered = arrayMove(visible, oldIndex, newIndex);
+ setLocalPinned(reordered);
+ reorderPins.mutate([...reordered, ...viewPins]);
+ },
+ [isDraggingRef, reorderPins, setLocalPinned, viewPins, visible],
+ );
+
+ if (visible.length === 0) return null;
+
+ return (
+ <PanelSection
+ label={t(($) => $.sidebar.pinned_label)}
+ collapsed={collapsed}
+ onCollapsedChange={setCollapsed}
+ >
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
+ <SortableContext items={displayed.map((pin) => pin.id)} strategy={verticalListSortingStrategy}>
+ <PanelList>
+ {displayed.map((pin) => (
+ <PinRow
+ key={pin.id}
+ pin={pin}
+ href={pinHref(p, pin)}
+ active={isPinActive(pin)}
+ onUnpin={() => deletePin.mutate({ itemType: pin.item_type, itemId: pin.item_id })}
+ wsId={wsId}
+ />
+ ))}
+ </PanelList>
+ </SortableContext>
+ </DndContext>
+ {visible.length > PINNED_PREVIEW_LIMIT && (
+ <button
+ type="button"
+ aria-expanded={expanded}
+ className={cn(PANEL_ROW_CLASS, panelRowStateClass(false), "pl-[2.375rem] text-caption")}
+ onClick={() => setExpanded(!expanded)}
+ >
+ {expanded
+ ? t(($) => $.sidebar.show_fewer_pins)
+ : t(($) => $.sidebar.show_more_pins, { count: visible.length - PINNED_PREVIEW_LIMIT })}
+ </button>
+ )}
+ </PanelSection>
+ );
+}
+
+function SortablePinItem({
+ pin,
+ href,
+ onUnpin,
+ label,
+ iconNode,
+ active,
+ running = false,
+ trailing,
+ onNavigate,
+}: {
+ pin: PinnedItem;
+ href: string;
+ onUnpin: () => void;
+ label: string;
+ iconNode: React.ReactNode;
+ active: boolean;
+ /** Shimmers the label while an agent works on the pinned issue. */
+ running?: boolean;
+ trailing?: React.ReactNode;
+ /** Runs on a real click (not a drag-release) before navigation. */
+ onNavigate?: () => void;
+}) {
+ const { t } = useT("layout");
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: pin.id });
+ const wasDragged = useRef(false);
+
+ useEffect(() => {
+ if (isDragging) wasDragged.current = true;
+ }, [isDragging]);
+
+ return (
+ <li
+ ref={setNodeRef}
+ style={{ transform: CSS.Translate.toString(transform), transition }}
+ className={cn("group/pin relative", isDragging && "opacity-30")}
+ {...attributes}
+ {...listeners}
+ >
+ <AppLink
+ href={href}
+ newTabTitle={label}
+ draggable={false}
+ aria-current={active ? "page" : undefined}
+ onClick={(event) => {
+ if (wasDragged.current) {
+ wasDragged.current = false;
+ event.preventDefault();
+ return;
+ }
+ onNavigate?.();
+ }}
+ className={cn(
+ PANEL_ROW_CLASS,
+ panelRowStateClass(active),
+ trailing ? "pr-2" : "pr-8",
+ isDragging && "pointer-events-none",
+ )}
+ >
+ {iconNode}
+ <ShimmerText active={running} className={cn("min-w-0 flex-1 truncate", SIDEBAR_SHIMMER_CLASS)}>
+ {label}
+ </ShimmerText>
+ {/* Holds the same right-edge slot as a tree row's avatars, and yields
+ it to the unpin button on hover. */}
+ {trailing && (
+ <span className="flex shrink-0 items-center group-hover/pin:invisible group-focus-within/pin:invisible">
+ {trailing}
+ </span>
+ )}
+ </AppLink>
+ <TooltipHint label={t(($) => $.sidebar.unpin_tooltip)}>
+ <button
+ type="button"
+ aria-label={t(($) => $.sidebar.unpin_tooltip)}
+ className="absolute top-1/2 right-1.5 hidden size-5 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground group-hover/pin:flex group-focus-within/pin:flex hover:bg-surface-selected hover:text-foreground"
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ onUnpin();
+ }}
+ >
+ <X className="size-3" />
+ </button>
+ </TooltipHint>
+ </li>
+ );
+}
+
+/**
+ * Resolves a pin's display data (label + status/icon) from the issue /
+ * project / view detail cache. All three queries are declared unconditionally
+ * with `enabled` gates so the hook order stays stable regardless of
+ * `pin.item_type`.
+ *
+ * Loading renders a flat skeleton so the panel height doesn't jump. A missing
+ * item (deleted / 404) renders nothing and unpins itself.
+ */
+function PinRow({
+ pin,
+ href,
+ active,
+ onUnpin,
+ wsId,
+}: {
+ pin: PinnedItem;
+ href: string;
+ active: boolean;
+ onUnpin: () => void;
+ wsId: string;
+}) {
+ const isIssue = pin.item_type === "issue";
+ const agents = useIssueAgentState(wsId, isIssue ? pin.item_id : "");
+ const statusCatalog = useIssueStatuses(wsId);
+ const issueQuery = useQuery({ ...issueDetailOptions(wsId, pin.item_id), enabled: isIssue });
+ const projectQuery = useQuery({
+ ...projectDetailOptions(wsId, pin.item_id),
+ enabled: pin.item_type === "project",
+ });
+
+ const triggeredRef = useRef(false);
+ useEffect(() => {
+ const err = isIssue ? issueQuery.error : projectQuery.error;
+ if (err instanceof ApiError && err.status === 404 && !triggeredRef.current) {
+ triggeredRef.current = true;
+ onUnpin();
+ }
+ }, [isIssue, issueQuery.error, onUnpin, projectQuery.error]);
+
+ if (isIssue) {
+ if (issueQuery.isPending) return <PinSkeleton />;
+ if (issueQuery.isError || !issueQuery.data) return null;
+ const issue = issueQuery.data;
+ return (
+ <SortablePinItem
+ pin={pin}
+ href={href}
+ onUnpin={onUnpin}
+ label={issue.title}
+ active={active}
+ running={!!agents?.running}
+ trailing={agents && <IssueAgentBadge agents={agents} />}
+ iconNode={
+ <StatusIcon
+ status={issue.status}
+ color={statusCatalog.colorOf(issue.status)}
+ icon={statusCatalog.iconOf(issue.status)}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="size-3.5 shrink-0"
+ />
+ }
+ />
+ );
+ }
+
+ if (projectQuery.isPending) return <PinSkeleton />;
+ if (projectQuery.isError || !projectQuery.data) return null;
+ const project = projectQuery.data;
+ return (
+ <SortablePinItem
+ pin={pin}
+ href={href}
+ onUnpin={onUnpin}
+ label={project.title}
+ active={active}
+ iconNode={<Folder className="size-4 shrink-0" />}
+ />
+ );
+}
+
+function PinSkeleton() {
+ return (
+ <li className="flex h-8 items-center gap-2.5 px-3">
+ <div className="size-3.5 shrink-0 rounded-sm bg-muted" />
+ <div className="h-3 w-24 rounded-xs bg-muted" />
+ </li>
+ );
+}
diff --git a/packages/views/layout/panels/sidebar-settings.test.tsx b/packages/views/layout/panels/sidebar-settings.test.tsx
new file mode 100644
index 0000000000..e6cbd209e6
--- /dev/null
+++ b/packages/views/layout/panels/sidebar-settings.test.tsx
@@ -0,0 +1,83 @@
+import { fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
+import {
+ DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ useSidebarTreeStore,
+} from "@multica/core/issues/stores/sidebar-tree-store";
+import { renderWithI18n } from "../../test/i18n";
+import { ProjectsSectionSettings } from "./sidebar-settings";
+
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () =>
+ buildIssueStatusCatalog(
+ [
+ ["todo", "Todo", "unstarted"],
+ ["in_progress", "In Progress", "started"],
+ ["done", "Done", "done"],
+ ].map(([key, name, category], position) => ({
+ id: key!,
+ workspace_id: "ws-1",
+ key: key!,
+ name: name!,
+ description: "",
+ category: category as "unstarted",
+ color: "",
+ is_system: true,
+ position,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+ })),
+ ),
+}));
+vi.mock("../../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));
+
+beforeEach(() => {
+ useSidebarTreeStore.setState({
+ issueSettings: DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ projectSettings: DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ });
+});
+
+const chip = (name: string) => screen.getByRole("button", { name });
+
+describe("ProjectsSectionSettings", () => {
+ it("covers both the project list and every project's issues", () => {
+ renderWithI18n(<ProjectsSectionSettings wsId="ws-1" />);
+ fireEvent.click(screen.getByRole("button", { name: "Project display" }));
+
+ expect(screen.getByRole("heading", { name: "Projects" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Issues in projects" })).toBeInTheDocument();
+ });
+
+ it("toggles issue statuses from their chips", () => {
+ renderWithI18n(<ProjectsSectionSettings wsId="ws-1" />);
+ fireEvent.click(screen.getByRole("button", { name: "Project display" }));
+
+ expect(chip("Todo")).toHaveAttribute("aria-pressed", "true");
+ expect(chip("Done")).toHaveAttribute("aria-pressed", "false");
+
+ fireEvent.click(chip("Todo"));
+ const hidden = useSidebarTreeStore.getState().issueSettings.hiddenStatuses;
+ expect(hidden).toContain("todo");
+ expect(hidden).toContain("done");
+ expect(chip("Todo")).toHaveAttribute("aria-pressed", "false");
+ });
+
+ it("toggles a project status and resets everything at once", () => {
+ renderWithI18n(<ProjectsSectionSettings wsId="ws-1" />);
+ fireEvent.click(screen.getByRole("button", { name: "Project display" }));
+
+ expect(screen.queryByRole("button", { name: "Reset" })).toBeNull();
+ fireEvent.click(chip("Completed"));
+ fireEvent.click(chip("Todo"));
+ expect(useSidebarTreeStore.getState().projectSettings.statuses).toContain("completed");
+
+ fireEvent.click(screen.getByRole("button", { name: "Reset" }));
+ const state = useSidebarTreeStore.getState();
+ expect(state.projectSettings).toEqual(DEFAULT_SIDEBAR_PROJECT_SETTINGS);
+ expect(state.issueSettings).toEqual(DEFAULT_SIDEBAR_ISSUE_SETTINGS);
+ });
+});
diff --git a/packages/views/layout/panels/sidebar-settings.tsx b/packages/views/layout/panels/sidebar-settings.tsx
new file mode 100644
index 0000000000..7a8760b059
--- /dev/null
+++ b/packages/views/layout/panels/sidebar-settings.tsx
@@ -0,0 +1,287 @@
+"use client";
+
+import { SlidersHorizontal } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { Button } from "@multica/ui/components/ui/button";
+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@multica/ui/components/ui/select";
+import { Switch } from "@multica/ui/components/ui/switch";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { shownSidebarStatuses } from "@multica/core/issues/sidebar-list";
+import {
+ DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ useSidebarTreeStore,
+ type SidebarIssueAssignee,
+ type SidebarIssueSort,
+ type SidebarProjectOrdering,
+} from "@multica/core/issues/stores/sidebar-tree-store";
+import { PROJECT_STATUS_CONFIG, PROJECT_STATUS_ORDER } from "@multica/core/projects/config";
+import type { ProjectStatus } from "@multica/core/types";
+import { DisplayChip, SortDirectionButton } from "../../issues/components/display-parts";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { sortDirectionLabelKey } from "../../issues/utils/sort-direction";
+import { useProjectStatusLabels } from "../../projects/components/labels";
+import { useT } from "../../i18n";
+import { TREE_ROW_BUTTON_CLASS } from "./sidebar-tree";
+
+const ISSUE_SORTS: {
+ value: SidebarIssueSort;
+ label: "sort_updated" | "sort_created" | "sort_priority" | "sort_status" | "sort_title" | "sort_due_date";
+}[] = [
+ { value: "updated_at", label: "sort_updated" },
+ { value: "created_at", label: "sort_created" },
+ { value: "priority", label: "sort_priority" },
+ { value: "status", label: "sort_status" },
+ { value: "title", label: "sort_title" },
+ { value: "due_date", label: "sort_due_date" },
+];
+const PROJECT_ORDERINGS: SidebarProjectOrdering[] = ["manual", "name", "updated", "created"];
+
+const sameSettings = <T,>(a: T, b: T) => JSON.stringify(a) === JSON.stringify(b);
+
+function Caption({ children }: { children: React.ReactNode }) {
+ return <span className="text-caption font-medium text-muted-foreground">{children}</span>;
+}
+
+function Field({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="flex items-center justify-between gap-3">
+ <Caption>{label}</Caption>
+ {children}
+ </div>
+ );
+}
+
+function SwitchField({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
+ return (
+ <label className="flex cursor-pointer items-center justify-between gap-3">
+ <Caption>{label}</Caption>
+ <Switch size="sm" checked={checked} onCheckedChange={onChange} />
+ </label>
+ );
+}
+
+function SortSelect<T extends string>({
+ label,
+ value,
+ options,
+ onChange,
+ className,
+}: {
+ label: string;
+ value: T;
+ options: { value: T; label: string }[];
+ onChange: (value: T) => void;
+ className?: string;
+}) {
+ return (
+ <Select
+ items={options}
+ value={value}
+ onValueChange={(next) => {
+ if (next) onChange(next as T);
+ }}
+ >
+ <SelectTrigger size="sm" className={className} aria-label={label}>
+ <SelectValue>{options.find((o) => o.value === value)?.label}</SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end">
+ <SelectGroup>
+ {options.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
+
+function ProjectsGroup() {
+ const { t } = useT("layout");
+ const statusLabels = useProjectStatusLabels();
+ const settings = useSidebarTreeStore((s) => s.projectSettings);
+ const update = useSidebarTreeStore((s) => s.setProjectSettings);
+ const toggleStatus = (status: ProjectStatus, on: boolean) =>
+ update({ statuses: PROJECT_STATUS_ORDER.filter((s) => (s === status ? on : settings.statuses.includes(s))) });
+
+ return (
+ <section className="space-y-3">
+ <h3 className="text-label font-medium text-foreground">{t(($) => $.nav.projects)}</h3>
+ <Field label={t(($) => $.panels.work.projects_ordering)}>
+ <SortSelect
+ label={t(($) => $.panels.work.projects_ordering)}
+ value={settings.ordering}
+ options={PROJECT_ORDERINGS.map((value) => ({
+ value,
+ label: {
+ manual: t(($) => $.panels.work.projects_order_manual),
+ name: t(($) => $.panels.work.projects_order_name),
+ updated: t(($) => $.panels.work.projects_order_updated),
+ created: t(($) => $.panels.work.projects_order_created),
+ }[value],
+ }))}
+ onChange={(ordering) => update({ ordering })}
+ className="w-36"
+ />
+ </Field>
+ <div>
+ <Caption>{t(($) => $.panels.work.projects_show)}</Caption>
+ <div className="mt-2 flex flex-wrap gap-1">
+ {PROJECT_STATUS_ORDER.map((status) => (
+ <DisplayChip
+ key={status}
+ pressed={settings.statuses.includes(status)}
+ onPressedChange={(on) => toggleStatus(status, on)}
+ >
+ <span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", PROJECT_STATUS_CONFIG[status].dotColor)} />
+ <span className="truncate">{statusLabels[status]}</span>
+ </DisplayChip>
+ ))}
+ </div>
+ </div>
+ <SwitchField
+ label={t(($) => $.panels.work.projects_only_mine)}
+ checked={settings.onlyMine}
+ onChange={(onlyMine) => update({ onlyMine })}
+ />
+ <SwitchField
+ label={t(($) => $.panels.work.projects_show_count)}
+ checked={settings.showCount}
+ onChange={(showCount) => update({ showCount })}
+ />
+ </section>
+ );
+}
+
+function ProjectIssuesGroup({ wsId }: { wsId: string }) {
+ const { t } = useT("layout");
+ const { t: ti } = useT("issues");
+ const statusCatalog = useIssueStatuses(wsId);
+ const settings = useSidebarTreeStore((s) => s.issueSettings);
+ const update = useSidebarTreeStore((s) => s.setIssueSettings);
+ const shown = new Set(shownSidebarStatuses(settings, statusCatalog.statuses));
+ const toggleStatus = (key: string, on: boolean) =>
+ update({
+ hiddenStatuses: statusCatalog.statuses.map((s) => s.key).filter((k) => (k === key ? !on : !shown.has(k))),
+ });
+ const directionLabel = ti(($) => $.display[sortDirectionLabelKey(settings.sortBy, settings.sortDirection)]);
+ const assigneeOptions: { value: SidebarIssueAssignee; label: string }[] = [
+ { value: "anyone", label: t(($) => $.panels.work.assignee_anyone) },
+ { value: "me", label: t(($) => $.panels.work.assignee_me) },
+ { value: "my_agents", label: t(($) => $.panels.work.assignee_my_agents) },
+ ];
+
+ return (
+ <section className="mt-5 space-y-3">
+ <h3 className="text-label font-medium text-foreground">{t(($) => $.panels.work.project_issues_settings)}</h3>
+ <Field label={ti(($) => $.display.ordering_section)}>
+ <div className="flex min-w-0 items-center gap-1">
+ <SortDirectionButton
+ label={directionLabel}
+ onClick={() => update({ sortDirection: settings.sortDirection === "asc" ? "desc" : "asc" })}
+ />
+ <SortSelect
+ label={ti(($) => $.display.ordering_section)}
+ value={settings.sortBy}
+ options={ISSUE_SORTS.map((o) => ({ value: o.value, label: ti(($) => $.display[o.label]) }))}
+ onChange={(sortBy) => update({ sortBy })}
+ className="w-36"
+ />
+ </div>
+ </Field>
+ <div>
+ <Caption>{t(($) => $.panels.work.settings_status)}</Caption>
+ <div className="mt-2 flex flex-wrap gap-1">
+ {statusCatalog.activeStatuses.map((status) => (
+ <DisplayChip
+ key={status.key}
+ pressed={shown.has(status.key)}
+ onPressedChange={(on) => toggleStatus(status.key, on)}
+ >
+ <StatusIcon
+ status={status.key}
+ category={status.category}
+ color={statusCatalog.colorOf(status.key)}
+ icon={statusCatalog.iconOf(status.key)}
+ className="size-3 shrink-0"
+ />
+ <span className="truncate">{statusCatalog.labelOf(status.key)}</span>
+ </DisplayChip>
+ ))}
+ </div>
+ </div>
+ <Field label={t(($) => $.panels.work.settings_assignee)}>
+ <SortSelect
+ label={t(($) => $.panels.work.settings_assignee)}
+ value={settings.assignee}
+ options={assigneeOptions}
+ onChange={(assignee) => update({ assignee })}
+ className="w-36"
+ />
+ </Field>
+ <SwitchField
+ label={ti(($) => $.display.show_sub_issues)}
+ checked={settings.showSubIssues}
+ onChange={(showSubIssues) => update({ showSubIssues })}
+ />
+ </section>
+ );
+}
+
+/**
+ * Display settings for the whole Projects section: which projects it lists,
+ * and how every expanded project lists its issues.
+ */
+export function ProjectsSectionSettings({ wsId, className }: { wsId: string; className?: string }) {
+ const { t } = useT("layout");
+ const changed = useSidebarTreeStore(
+ (s) =>
+ !sameSettings(s.projectSettings, DEFAULT_SIDEBAR_PROJECT_SETTINGS) ||
+ !sameSettings(s.issueSettings, DEFAULT_SIDEBAR_ISSUE_SETTINGS),
+ );
+ const reset = () => {
+ const store = useSidebarTreeStore.getState();
+ store.setProjectSettings(DEFAULT_SIDEBAR_PROJECT_SETTINGS);
+ store.setIssueSettings(DEFAULT_SIDEBAR_ISSUE_SETTINGS);
+ };
+
+ return (
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ aria-label={t(($) => $.panels.work.projects_settings)}
+ className={cn(
+ TREE_ROW_BUTTON_CLASS,
+ "text-muted-foreground data-popup-open:bg-surface-selected data-popup-open:text-foreground data-popup-open:opacity-100",
+ className,
+ )}
+ />
+ }
+ >
+ <SlidersHorizontal className="size-3.5" />
+ </PopoverTrigger>
+ <PopoverContent
+ side="right"
+ align="start"
+ sideOffset={8}
+ className="max-h-(--available-height) w-80 gap-0 overflow-y-auto p-3"
+ >
+ {/* Spacing separates sections — no dividers, as in the Display panel. */}
+ <ProjectsGroup />
+ <ProjectIssuesGroup wsId={wsId} />
+ {changed && (
+ <div className="-mr-1.5 mt-4 flex justify-end">
+ <Button variant="ghost" size="sm" className="text-muted-foreground" onClick={reset}>
+ {t(($) => $.panels.work.reset)}
+ </Button>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/views/layout/panels/sidebar-tree.test.tsx b/packages/views/layout/panels/sidebar-tree.test.tsx
new file mode 100644
index 0000000000..349b73bb34
--- /dev/null
+++ b/packages/views/layout/panels/sidebar-tree.test.tsx
@@ -0,0 +1,122 @@
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { agentTaskSnapshotOptions } from "@multica/core/agents";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
+import { issueKeys } from "@multica/core/issues/queries";
+import type { AgentTask, Issue, ListIssuesParams } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { SidebarIssueList } from "./sidebar-tree";
+
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog([]),
+}));
+vi.mock("../../navigation", () => ({
+ AppLink: ({
+ children,
+ href,
+ newTabTitle: _newTabTitle,
+ ...props
+ }: { children: ReactNode; href: string; newTabTitle?: string } & React.ComponentProps<"a">) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("../../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));
+vi.mock("../../agents/components/agent-avatar-stack", () => ({
+ AgentAvatarStack: ({ agentIds }: { agentIds: string[] }) => <span data-testid="agents">{agentIds.join(",")}</span>,
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
+});
+
+const SOURCE = "project:p1";
+const PARAMS: ListIssuesParams = { project_id: "p1", sort_by: "updated_at", sort_direction: "desc" };
+const issues = (count: number): Issue[] =>
+ Array.from({ length: count }, (_, i) => ({ id: `issue-${i + 1}`, title: `Issue ${i + 1}`, status: "todo" }) as Issue);
+
+function renderList({
+ total = 18,
+ params = PARAMS,
+ tasks = [],
+ onCollapse = vi.fn(),
+}: {
+ total?: number;
+ params?: ListIssuesParams | null;
+ tasks?: Partial<AgentTask>[];
+ onCollapse?: () => void;
+} = {}) {
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
+ const all = issues(total);
+ for (const limit of [5, 15, 25]) {
+ qc.setQueryData(issueKeys.sidebar("ws-1", SOURCE, PARAMS, limit), { issues: all.slice(0, limit), total });
+ }
+ qc.setQueryData(agentTaskSnapshotOptions("ws-1").queryKey, tasks as AgentTask[]);
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <SidebarIssueList
+ id="list"
+ wsId="ws-1"
+ source={SOURCE}
+ params={params}
+ activeIssueId="issue-2"
+ onCollapse={onCollapse}
+ />
+ </QueryClientProvider>,
+ );
+ return { onCollapse };
+}
+
+const rows = () => screen.getAllByRole("link");
+
+describe("SidebarIssueList", () => {
+ it("loads more in steps, then shows less", () => {
+ renderList();
+ expect(rows()).toHaveLength(5);
+ expect(screen.getByRole("link", { name: "Issue 2" })).toHaveAttribute("aria-current", "page");
+
+ fireEvent.click(screen.getByRole("button", { name: "Load more 13" }));
+ expect(rows()).toHaveLength(15);
+ fireEvent.click(screen.getByRole("button", { name: "Load more 3" }));
+ expect(rows()).toHaveLength(18);
+
+ fireEvent.click(screen.getByRole("button", { name: "Show less" }));
+ expect(rows()).toHaveLength(5);
+ });
+
+ it("offers neither control when everything fits", () => {
+ renderList({ total: 4 });
+ expect(rows()).toHaveLength(4);
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("shows the empty state when the settings match nothing", () => {
+ renderList({ params: null });
+ expect(screen.getByText("No issues")).toBeInTheDocument();
+ });
+
+ it("marks issues an agent is working on or queued for", () => {
+ renderList({
+ tasks: [
+ { id: "t1", issue_id: "issue-1", agent_id: "a1", status: "running" },
+ { id: "t2", issue_id: "issue-3", agent_id: "a2", status: "queued" },
+ ],
+ });
+ const working = screen.getByRole("link", { name: /^Issue 1/ });
+ expect(working).toHaveTextContent("Working");
+ expect(working.querySelector(".shimmer-text")).not.toBeNull();
+ const queued = screen.getByRole("link", { name: /^Issue 3/ });
+ expect(queued).toHaveTextContent("Queued");
+ expect(queued.querySelector(".shimmer-text")).toBeNull();
+ expect(screen.getByRole("link", { name: "Issue 2" }).querySelector("[data-testid=agents]")).toBeNull();
+ });
+
+ it("collapses the row from the keyboard", () => {
+ const { onCollapse } = renderList();
+ fireEvent.keyDown(rows()[0]!, { key: "ArrowLeft" });
+ expect(onCollapse).toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/layout/panels/sidebar-tree.tsx b/packages/views/layout/panels/sidebar-tree.tsx
new file mode 100644
index 0000000000..7222c2d739
--- /dev/null
+++ b/packages/views/layout/panels/sidebar-tree.tsx
@@ -0,0 +1,325 @@
+"use client";
+
+import { forwardRef, memo, useCallback, useState } from "react";
+import { keepPreviousData, useQuery } from "@tanstack/react-query";
+import { ChevronDown, ChevronRight, ChevronUp } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { ShimmerText } from "@multica/ui/components/common/shimmer-text";
+import { agentTaskSnapshotOptions } from "@multica/core/agents";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { issueStatusCategory } from "@multica/core/issues";
+import { sidebarIssuesOptions } from "@multica/core/issues/queries";
+import { SIDEBAR_FIRST_PAGE, SIDEBAR_PAGE_STEP, type SidebarIssuesRequest } from "@multica/core/issues/sidebar-list";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { AgentTask, Issue, ListIssuesParams } from "@multica/core/types";
+import { AppLink } from "../../navigation";
+import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { selectIssueTasks } from "../../issues/surface/activity";
+import { useT } from "../../i18n";
+import { PANEL_ROW_CLASS, panelRowStateClass } from "../panel-nav";
+
+/** A working agent's issue title: dimmer at rest and a wider highlight than
+ * the default shimmer, so the sweep reads at sidebar size. */
+export const SIDEBAR_SHIMMER_CLASS =
+ "[--shimmer-text-base:var(--faint-foreground)] [--shimmer-text-spread:22%]";
+
+export const TREE_ROW_BUTTON_CLASS =
+ "relative z-10 flex size-5 shrink-0 items-center justify-center rounded-md outline-none transition-[color,opacity] hover:text-foreground focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-ring";
+
+interface TreeRowProps extends React.ComponentProps<"div"> {
+ href: string;
+ label: string;
+ icon: React.ReactNode;
+ active: boolean;
+ /** Omit the expand props for a row that only opens its page. */
+ expanded?: boolean;
+ onExpandedChange?: (expanded: boolean) => void;
+ listId?: string;
+ /** Label for the expand toggle; `aria-expanded` carries its state. */
+ toggleLabel?: string;
+ onPrefetch?: () => void;
+ /** End of the row: a count, or a settings button. */
+ trailing?: React.ReactNode;
+ onNavigate?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
+ onNavigateInPlace?: () => void;
+ rowRef?: React.Ref<HTMLDivElement>;
+}
+
+/**
+ * A nav row that expands in place. The link stretches over the whole row so
+ * the row still opens its page; the chevron, shown in the icon's place on
+ * hover, only toggles.
+ */
+export const TreeRow = forwardRef<HTMLAnchorElement, TreeRowProps>(function TreeRow(
+ {
+ href,
+ label,
+ icon,
+ active,
+ expanded,
+ onExpandedChange,
+ listId,
+ toggleLabel,
+ onPrefetch,
+ trailing,
+ onNavigate,
+ onNavigateInPlace,
+ rowRef,
+ className,
+ ...rowProps
+ },
+ linkRef,
+) {
+ const onKeyDown = (event: React.KeyboardEvent) => {
+ if (!onExpandedChange) return;
+ if (event.key === "ArrowRight" && !expanded) {
+ event.preventDefault();
+ onExpandedChange(true);
+ } else if (event.key === "ArrowLeft" && expanded) {
+ event.preventDefault();
+ onExpandedChange(false);
+ }
+ };
+
+ return (
+ <div
+ {...rowProps}
+ ref={rowRef}
+ className={cn(
+ PANEL_ROW_CLASS,
+ panelRowStateClass(active),
+ "group/row relative",
+ expanded && !active && "text-foreground",
+ className,
+ )}
+ >
+ {onExpandedChange ? (
+ // The toggle takes the icon's place on hover, so the label keeps the
+ // row's width.
+ <span className="relative flex size-4 shrink-0 items-center justify-center">
+ <span className="flex group-hover/row:opacity-0 group-has-[:focus-visible]/row:opacity-0 [@media(pointer:coarse)]:opacity-0">
+ {icon}
+ </span>
+ <button
+ type="button"
+ aria-label={toggleLabel}
+ aria-expanded={expanded}
+ aria-controls={expanded ? listId : undefined}
+ onClick={() => onExpandedChange(!expanded)}
+ onKeyDown={onKeyDown}
+ onPointerDown={(event) => event.stopPropagation()}
+ onPointerEnter={onPrefetch}
+ className={cn(
+ TREE_ROW_BUTTON_CLASS,
+ "absolute text-muted-foreground opacity-0 transition-none group-hover/row:opacity-100 group-has-[:focus-visible]/row:opacity-100 [@media(pointer:coarse)]:opacity-100",
+ )}
+ >
+ <ChevronRight
+ className={cn(
+ "size-3.5 transition-transform duration-150 ease-out motion-reduce:transition-none",
+ expanded && "rotate-90",
+ )}
+ />
+ </button>
+ </span>
+ ) : (
+ icon
+ )}
+ <AppLink
+ ref={linkRef}
+ href={href}
+ newTabTitle={label}
+ draggable={false}
+ aria-current={active ? "page" : undefined}
+ onKeyDown={onKeyDown}
+ onClick={onNavigate}
+ onNavigateInPlace={onNavigateInPlace}
+ className="min-w-0 flex-1 truncate outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:outline-2 focus-visible:after:outline-ring"
+ >
+ {label}
+ </AppLink>
+ {trailing}
+ </div>
+ );
+});
+
+/** Issues under an expanded row sit flush and a step smaller than the rows
+ * around them, so a group reads as one block. */
+const TREE_CHILD_ROW_CLASS =
+ "flex min-h-[26px] w-full items-center gap-2 rounded-lg px-2 py-[3px] text-left text-label transition-colors outline-none focus-visible:outline-2 focus-visible:outline-ring";
+
+const EMPTY_PARAMS: ListIssuesParams = {};
+
+/**
+ * The issues under an expanded row: the first page, then "Load more" in
+ * steps. `params: null` means the row's settings can match nothing;
+ * `undefined` that they are still resolving.
+ */
+export function SidebarIssueList({
+ id,
+ wsId,
+ source,
+ params,
+ activeIssueId,
+ onCollapse,
+}: {
+ id: string;
+ wsId: string;
+ source: string;
+ params: SidebarIssuesRequest | null | undefined;
+ activeIssueId: string | null;
+ onCollapse: () => void;
+}) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const statusCatalog = useIssueStatuses(wsId);
+ const [limit, setLimit] = useState(SIDEBAR_FIRST_PAGE);
+ const query = useQuery({
+ ...sidebarIssuesOptions(wsId, source, params ?? EMPTY_PARAMS, limit),
+ enabled: !!params,
+ placeholderData: keepPreviousData,
+ });
+ const issues = params ? (query.data?.issues ?? []) : [];
+ const total = params ? (query.data?.total ?? 0) : 0;
+
+ const onKeyDown = (event: React.KeyboardEvent) => {
+ if (event.key !== "ArrowLeft") return;
+ event.preventDefault();
+ onCollapse();
+ };
+
+ const tailClass = cn(TREE_CHILD_ROW_CLASS, panelRowStateClass(false), "gap-1.5 min-h-6 text-caption text-faint-foreground");
+
+ return (
+ <ul id={id} className="mb-2 ml-5 border-l border-surface-border pl-1.5">
+ {params === undefined || (params && query.isPending) ? (
+ <li className="flex h-[26px] items-center gap-2 px-2">
+ <div className="size-3 shrink-0 rounded-full bg-muted" />
+ <div className="h-3 w-24 rounded-xs bg-muted" />
+ </li>
+ ) : query.isError || issues.length === 0 ? (
+ <li className="flex h-[26px] items-center px-2 text-caption text-faint-foreground">
+ {query.isError
+ ? t(($) => $.panels.work.project_issues_error)
+ : t(($) => $.panels.work.project_issues_empty)}
+ </li>
+ ) : (
+ <>
+ {issues.map((issue) => (
+ <li key={issue.id}>
+ <SidebarIssueRow
+ wsId={wsId}
+ issue={issue}
+ href={p.issueDetail(issue.id)}
+ active={issue.id === activeIssueId}
+ statusColor={statusCatalog.colorOf(issue.status)}
+ statusIcon={statusCatalog.iconOf(issue.status)}
+ onKeyDown={onKeyDown}
+ />
+ </li>
+ ))}
+ {total > issues.length ? (
+ <li>
+ <button
+ type="button"
+ className={tailClass}
+ disabled={query.isFetching}
+ onKeyDown={onKeyDown}
+ onClick={() => setLimit(issues.length + SIDEBAR_PAGE_STEP)}
+ >
+ <ChevronDown className="size-3.5" />
+ {t(($) => $.panels.work.load_more)}{" "}
+ <span className="tabular-nums">{total - issues.length}</span>
+ </button>
+ </li>
+ ) : (
+ limit > SIDEBAR_FIRST_PAGE &&
+ issues.length > SIDEBAR_FIRST_PAGE && (
+ <li>
+ <button type="button" className={tailClass} onKeyDown={onKeyDown} onClick={() => setLimit(SIDEBAR_FIRST_PAGE)}>
+ <ChevronUp className="size-3.5" />
+ {t(($) => $.panels.work.show_less)}
+ </button>
+ </li>
+ )
+ )}
+ </>
+ )}
+ </ul>
+ );
+}
+
+type IssueAgentState = { running: boolean; agentIds: string[] } | null;
+
+/** The agents running on an issue, or queued for it when none is running yet. */
+export function useIssueAgentState(wsId: string, issueId: string): IssueAgentState {
+ const select = useCallback(
+ (snapshot: AgentTask[]): IssueAgentState => {
+ const { running, queued } = selectIssueTasks(snapshot, issueId);
+ const tasks = running.length > 0 ? running : queued;
+ if (tasks.length === 0) return null;
+ return { running: running.length > 0, agentIds: [...new Set(tasks.map((task) => task.agent_id))] };
+ },
+ [issueId],
+ );
+ const { data = null } = useQuery({ ...agentTaskSnapshotOptions(wsId), select });
+ return data;
+}
+
+export function IssueAgentBadge({ agents }: { agents: NonNullable<IssueAgentState> }) {
+ const { t } = useT("issues");
+ return (
+ <>
+ <AgentAvatarStack agentIds={agents.agentIds} size="xs" max={2} opacity={agents.running ? "full" : "half"} />
+ <span className="sr-only">
+ {agents.running
+ ? t(($) => $.agent_activity.status_running)
+ : t(($) => $.agent_activity.status_queued)}
+ </span>
+ </>
+ );
+}
+
+/** The title shimmers while an agent runs on the issue; queued agents show dimmed. */
+const SidebarIssueRow = memo(function SidebarIssueRow({
+ wsId,
+ issue,
+ href,
+ active,
+ statusColor,
+ statusIcon,
+ onKeyDown,
+}: {
+ wsId: string;
+ issue: Issue;
+ href: string;
+ active: boolean;
+ statusColor: string | null;
+ statusIcon: string | null;
+ onKeyDown: (event: React.KeyboardEvent) => void;
+}) {
+ const agents = useIssueAgentState(wsId, issue.id);
+
+ return (
+ <AppLink
+ href={href}
+ newTabTitle={issue.title}
+ aria-current={active ? "page" : undefined}
+ onKeyDown={onKeyDown}
+ className={cn(TREE_CHILD_ROW_CLASS, panelRowStateClass(active))}
+ >
+ <StatusIcon
+ status={issue.status}
+ color={statusColor}
+ icon={statusIcon}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="size-3 shrink-0"
+ />
+ <ShimmerText active={!!agents?.running} className={cn("min-w-0 flex-1 truncate", SIDEBAR_SHIMMER_CLASS)}>
+ {issue.title}
+ </ShimmerText>
+ {agents && <IssueAgentBadge agents={agents} />}
+ </AppLink>
+ );
+});
diff --git a/packages/views/layout/panels/team-panel.tsx b/packages/views/layout/panels/team-panel.tsx
new file mode 100644
index 0000000000..745b7d0637
--- /dev/null
+++ b/packages/views/layout/panels/team-panel.tsx
@@ -0,0 +1,305 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { BarChart3, BookOpenText, Bot, Monitor, Plus, User, UserPlus, Users } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { agentTaskSnapshotOptions, type AgentPresenceDetail } from "@multica/core/agents";
+import { useAgentsViewStore } from "@multica/core/agents/stores";
+import { useAuthStore } from "@multica/core/auth";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { deriveRuntimeHealth } from "@multica/core/runtimes";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import { memberListOptions, skillListOptions, squadListOptions } from "@multica/core/workspace/queries";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
+import type { Agent, AgentTask } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+import { availabilityConfig } from "../../agents/presence";
+import { useT } from "../../i18n";
+import {
+ PanelBody,
+ PanelCount,
+ PanelHeader,
+ PanelLink,
+ PanelList,
+ PanelSection,
+ isPathWithin,
+} from "../panel-nav";
+import { useTeamAgentStatus } from "./team-status";
+
+const EMPTY_TASKS: AgentTask[] = [];
+const MEMBER_AVATAR_LIMIT = 4;
+
+function AgentAvatar({ agent, detail }: { agent: Agent; detail: AgentPresenceDetail | undefined }) {
+ return (
+ <span className="relative shrink-0">
+ <ActorAvatar
+ name={agent.name}
+ initials={agent.name.charAt(0).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(agent.avatar_url)}
+ isAgent
+ size="md"
+ />
+ {detail && (
+ <span
+ className={cn(
+ "absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2 ring-page-canvas",
+ availabilityConfig[detail.availability].dotClass,
+ )}
+ />
+ )}
+ </span>
+ );
+}
+
+/** "MUL-8317 Redesign the sidebar" for the issue the agent is running, if any. */
+function useRunningIssueLabel(wsId: string, task: AgentTask | undefined) {
+ const issueId = task?.issue_id ?? "";
+ const { data: issue } = useQuery({ ...issueDetailOptions(wsId, issueId), enabled: !!issueId });
+ return issue ? `${issue.identifier} ${issue.title}` : null;
+}
+
+function WorkingAgentRow({
+ agent,
+ detail,
+ task,
+ wsId,
+ active,
+}: {
+ agent: Agent;
+ detail: AgentPresenceDetail | undefined;
+ task: AgentTask | undefined;
+ wsId: string;
+ active: boolean;
+}) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const issueLabel = useRunningIssueLabel(wsId, task);
+ const running = detail?.runningCount ?? 0;
+ return (
+ <PanelLink
+ href={p.agentDetail(agent.id)}
+ label={agent.name}
+ active={active}
+ icon={<AgentAvatar agent={agent} detail={detail} />}
+ description={
+ running > 1 || !issueLabel ? t(($) => $.panels.team.running_tasks, { count: running }) : issueLabel
+ }
+ />
+ );
+}
+
+export function TeamPanel() {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const { pathname, push } = useNavigation();
+ const wsId = useCurrentWorkspace()?.id ?? "";
+ const userId = useAuthStore((s) => s.user?.id);
+ const agentsScope = useAgentsViewStore((s) => s.scope);
+ const setAgentsScope = useAgentsViewStore((s) => s.setScope);
+ const { agents, stuck, working, byAgent } = useTeamAgentStatus(wsId || undefined);
+
+ const { data: snapshot = EMPTY_TASKS } = useQuery({
+ ...agentTaskSnapshotOptions(wsId),
+ enabled: !!wsId,
+ });
+ const runningTaskByAgent = useMemo(() => {
+ const map = new Map<string, AgentTask>();
+ for (const task of snapshot) {
+ if (task.status === "running" && !map.has(task.agent_id)) map.set(task.agent_id, task);
+ }
+ return map;
+ }, [snapshot]);
+
+ const { data: squads = [] } = useQuery({ ...squadListOptions(wsId), enabled: !!wsId });
+ const liveSquads = useMemo(() => squads.filter((squad) => !squad.archived_at), [squads]);
+ const { data: members = [] } = useQuery({ ...memberListOptions(wsId), enabled: !!wsId });
+ const { data: skills = [] } = useQuery({ ...skillListOptions(wsId), enabled: !!wsId });
+ const { data: runtimes = [] } = useQuery({ ...runtimeListOptions(wsId), enabled: !!wsId });
+ const offlineRuntimes = useMemo(() => {
+ const now = Date.now();
+ return runtimes.filter((runtime) => {
+ const health = deriveRuntimeHealth(runtime, now);
+ return health === "offline" || health === "long_offline";
+ }).length;
+ }, [runtimes]);
+
+ const mineCount = userId ? agents.filter((agent) => agent.owner_id === userId).length : 0;
+ const myRole = members.find((member) => member.user_id === userId)?.role;
+ const canInvite = myRole === "owner" || myRole === "admin";
+ const onAgents = pathname === p.agents();
+ // Member pages live under /members/:id; the list itself is a Settings tab.
+ const membersRoot = p.memberDetail("").replace(/\/$/, "");
+
+ return (
+ <>
+ <PanelHeader title={t(($) => $.spaces.team)}>
+ {canInvite && (
+ <IconButton
+ label={t(($) => $.panels.team.invite_member)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={() => push(`${p.settings()}?tab=members&invite=1`)}
+ >
+ <UserPlus />
+ </IconButton>
+ )}
+ <IconButton
+ label={t(($) => $.panels.team.new_agent)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ onClick={() => push(p.newAgent())}
+ >
+ <Plus />
+ </IconButton>
+ </PanelHeader>
+ <PanelBody>
+ {stuck.length > 0 && (
+ <PanelSection
+ label={t(($) => $.panels.team.needs_attention)}
+ action={<PanelCount value={stuck.length} className="pr-2 text-warning" />}
+ >
+ <PanelList>
+ {stuck.map((agent) => {
+ const href = p.agentDetail(agent.id);
+ return (
+ <PanelLink
+ key={agent.id}
+ href={href}
+ label={agent.name}
+ active={isPathWithin(pathname, href)}
+ icon={<AgentAvatar agent={agent} detail={byAgent.get(agent.id)} />}
+ description={
+ <span className="text-warning">
+ {t(($) => $.panels.team.stuck, { count: byAgent.get(agent.id)?.queuedCount ?? 0 })}
+ </span>
+ }
+ />
+ );
+ })}
+ </PanelList>
+ </PanelSection>
+ )}
+
+ {working.length > 0 && (
+ <PanelSection
+ label={t(($) => $.panels.team.working_now)}
+ action={<PanelCount value={working.length} className="pr-2" />}
+ >
+ <PanelList>
+ {working.map((agent) => (
+ <WorkingAgentRow
+ key={agent.id}
+ agent={agent}
+ detail={byAgent.get(agent.id)}
+ task={runningTaskByAgent.get(agent.id)}
+ wsId={wsId}
+ active={isPathWithin(pathname, p.agentDetail(agent.id))}
+ />
+ ))}
+ </PanelList>
+ </PanelSection>
+ )}
+
+ <PanelSection label={t(($) => $.nav.agents)}>
+ <PanelList>
+ <PanelLink
+ href={p.agents()}
+ icon={<Bot />}
+ label={t(($) => $.panels.team.all_agents)}
+ active={onAgents && agentsScope === "all"}
+ trailing={<PanelCount value={agents.length} />}
+ onNavigate={() => setAgentsScope("all")}
+ />
+ <PanelLink
+ href={p.agents()}
+ icon={<User />}
+ label={t(($) => $.panels.team.my_agents)}
+ active={onAgents && agentsScope === "mine"}
+ trailing={<PanelCount value={mineCount} />}
+ onNavigate={() => setAgentsScope("mine")}
+ />
+ </PanelList>
+ </PanelSection>
+
+ <PanelSection label={t(($) => $.panels.team.squads_and_members)}>
+ <PanelList>
+ <PanelLink
+ href={p.squads()}
+ icon={<Users />}
+ label={t(($) => $.nav.squads)}
+ active={pathname === p.squads()}
+ trailing={<PanelCount value={liveSquads.length} />}
+ />
+ {liveSquads.map((squad) => {
+ const href = p.squadDetail(squad.id);
+ return (
+ <PanelLink
+ key={squad.id}
+ href={href}
+ label={squad.name}
+ active={isPathWithin(pathname, href)}
+ icon={<span className="size-4" aria-hidden />}
+ className="text-caption"
+ />
+ );
+ })}
+ <PanelLink
+ href={`${p.settings()}?tab=members`}
+ label={t(($) => $.panels.team.members, { count: members.length })}
+ active={isPathWithin(pathname, membersRoot)}
+ icon={
+ <span className="flex -space-x-1">
+ {members.slice(0, MEMBER_AVATAR_LIMIT).map((member) => (
+ <ActorAvatar
+ key={member.user_id}
+ name={member.name}
+ initials={member.name.charAt(0).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(member.avatar_url)}
+ size="xs"
+ className="ring-1 ring-page-canvas"
+ />
+ ))}
+ </span>
+ }
+ />
+ </PanelList>
+ </PanelSection>
+
+ <PanelSection label={t(($) => $.panels.team.resources)}>
+ <PanelList>
+ <PanelLink
+ href={p.skills()}
+ icon={<BookOpenText />}
+ label={t(($) => $.nav.skills)}
+ active={isPathWithin(pathname, p.skills())}
+ trailing={<PanelCount value={skills.length} />}
+ />
+ <PanelLink
+ href={p.runtimes()}
+ icon={<Monitor />}
+ label={t(($) => $.nav.runtimes)}
+ active={isPathWithin(pathname, p.runtimes())}
+ trailing={
+ offlineRuntimes > 0 ? (
+ <span className="shrink-0 text-caption text-warning">
+ {t(($) => $.panels.team.runtimes_offline, { count: offlineRuntimes })}
+ </span>
+ ) : undefined
+ }
+ />
+ <PanelLink
+ href={p.usage()}
+ icon={<BarChart3 />}
+ label={t(($) => $.nav.usage)}
+ active={isPathWithin(pathname, p.usage())}
+ />
+ </PanelList>
+ </PanelSection>
+ </PanelBody>
+ </>
+ );
+}
diff --git a/packages/views/layout/panels/team-status.test.ts b/packages/views/layout/panels/team-status.test.ts
new file mode 100644
index 0000000000..df95fe9da8
--- /dev/null
+++ b/packages/views/layout/panels/team-status.test.ts
@@ -0,0 +1,23 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { AgentPresenceDetail } from "@multica/core/agents";
+import { isAgentStuck } from "./team-status";
+
+const detail = (overrides: Partial<AgentPresenceDetail>) =>
+ ({ availability: "online", workload: "idle", runningCount: 0, queuedCount: 0, ...overrides }) as AgentPresenceDetail;
+
+describe("isAgentStuck", () => {
+ it("flags queued work on a runtime that is not online", () => {
+ expect(isAgentStuck(detail({ availability: "offline", queuedCount: 2 }))).toBe(true);
+ });
+
+ // On an online runtime a queued task is just waiting to be claimed.
+ it("does not flag queued work on an online runtime", () => {
+ expect(isAgentStuck(detail({ availability: "online", queuedCount: 2 }))).toBe(false);
+ });
+
+ it("does not flag an offline agent with nothing queued", () => {
+ expect(isAgentStuck(detail({ availability: "offline", queuedCount: 0 }))).toBe(false);
+ expect(isAgentStuck(undefined)).toBe(false);
+ });
+});
diff --git a/packages/views/layout/panels/team-status.ts b/packages/views/layout/panels/team-status.ts
new file mode 100644
index 0000000000..1cffdf4436
--- /dev/null
+++ b/packages/views/layout/panels/team-status.ts
@@ -0,0 +1,39 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspacePresenceMap } from "@multica/core/agents";
+import type { AgentPresenceDetail } from "@multica/core/agents";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import type { Agent } from "@multica/core/types";
+
+const EMPTY_AGENTS: Agent[] = [];
+
+/**
+ * Queued work on a runtime that is not online cannot start until the runtime
+ * comes back — the same "stuck" reading the agent presence chip renders in
+ * amber. On an online runtime a queued task is just waiting to be claimed.
+ */
+export function isAgentStuck(detail: AgentPresenceDetail | undefined): boolean {
+ return !!detail && detail.availability !== "online" && detail.queuedCount > 0;
+}
+
+/** Live (non-archived) agents bucketed by what the team panel surfaces. */
+export function useTeamAgentStatus(wsId: string | undefined) {
+ const { data: agents = EMPTY_AGENTS } = useQuery({
+ ...agentListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const { byAgent } = useWorkspacePresenceMap(wsId);
+ return useMemo(() => {
+ const live = agents.filter((agent) => !agent.archived_at);
+ const stuck: Agent[] = [];
+ const working: Agent[] = [];
+ for (const agent of live) {
+ const detail = byAgent.get(agent.id);
+ if (isAgentStuck(detail)) stuck.push(agent);
+ else if (detail?.workload === "working") working.push(agent);
+ }
+ return { agents: live, stuck, working, byAgent };
+ }, [agents, byAgent]);
+}
diff --git a/packages/views/layout/panels/views-section.test.tsx b/packages/views/layout/panels/views-section.test.tsx
new file mode 100644
index 0000000000..1049dfca37
--- /dev/null
+++ b/packages/views/layout/panels/views-section.test.tsx
@@ -0,0 +1,178 @@
+import type { ReactNode } from "react";
+import { fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";
+import { renderWithI18n } from "../../test/i18n";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import { ViewsSection } from "./views-section";
+
+const actions = vi.hoisted(() => ({
+ sidebar: { items: [] as unknown[], reorder: vi.fn(), unstar: vi.fn() },
+ create: vi.fn(),
+ remove: vi.fn(),
+ canManage: () => true,
+}));
+
+vi.mock("../../issue-views/use-view-actions", () => ({ useIssueViewActions: () => actions }));
+vi.mock("../../issue-views/delete-view-dialog", () => ({ DeleteViewDialog: () => null }));
+vi.mock("@dnd-kit/core", () => ({
+ DndContext: ({ children }: { children: ReactNode }) => <>{children}</>,
+ PointerSensor: vi.fn(),
+ closestCenter: vi.fn(),
+ useSensor: vi.fn(),
+ useSensors: vi.fn(),
+}));
+vi.mock("@dnd-kit/sortable", () => ({
+ SortableContext: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useSortable: () => ({ listeners: {}, setNodeRef: vi.fn(), setActivatorNodeRef: vi.fn() }),
+ verticalListSortingStrategy: vi.fn(),
+ arrayMove: vi.fn(),
+}));
+vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
+ TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
+});
+vi.mock("@multica/core/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/hooks")>()),
+ useWorkspaceId: () => "ws-1",
+}));
+vi.mock("@multica/core/issue-statuses/hooks", async () => {
+ const { buildIssueStatusCatalog } = await import("@multica/core/issue-statuses/queries");
+ return { useIssueStatuses: () => buildIssueStatusCatalog([]) };
+});
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: () => ({ data: [] }),
+ useQueryClient: () => ({}),
+}));
+
+function makeAdapter(overrides: Partial<NavigationAdapter> = {}): NavigationAdapter {
+ return {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/issues",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ ...overrides,
+ };
+}
+
+function renderSection(adapter = makeAdapter()) {
+ return renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <ViewsSection
+ wsId="ws-1"
+ pathname="/acme/issues"
+ plainRowsLit
+ issueLitInTree={false}
+ activeIssueId={null}
+ />
+ </NavigationProvider>,
+ );
+}
+
+const WORKSPACE_KEY = "ws-1:workspace";
+const SAVED_VIEW = {
+ id: "v1",
+ name: "Not done",
+ scope_type: "workspace",
+ scope_id: null,
+ scope_variant: null,
+ query: { statusFilters: ["done"], negatedFilters: ["status"], relationFilters: ["assigned"] },
+ display: {},
+};
+
+beforeEach(() => {
+ actions.create.mockReset();
+ actions.sidebar.items = [];
+ useSidebarTreeStore.setState({ viewsCollapsed: false });
+ useActiveIssueViewStore.setState({ active: {} });
+});
+
+describe("ViewsSection", () => {
+ it("collapses from the section label", () => {
+ renderSection();
+ expect(screen.getByText("All views")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Views" }));
+ expect(useSidebarTreeStore.getState().viewsCollapsed).toBe(true);
+ expect(screen.queryByText("All views")).toBeNull();
+ expect(screen.getByRole("button", { name: "Views" })).toHaveAttribute("aria-expanded", "false");
+ });
+
+ it("opens again to name a new view inline", () => {
+ useSidebarTreeStore.setState({ viewsCollapsed: true });
+ renderSection();
+
+ fireEvent.click(screen.getByRole("button", { name: "New view" }));
+ expect(useSidebarTreeStore.getState().viewsCollapsed).toBe(false);
+ expect(actions.create).toHaveBeenCalledWith(expect.objectContaining({ renameIn: "sidebar" }));
+ });
+
+ it("lets every view expand, built-in or saved, whatever its filters", () => {
+ actions.sidebar.items = [
+ { id: "builtin:all_issues", kind: "builtin", key: "all_issues" },
+ { id: "view:v1", kind: "view", view: SAVED_VIEW },
+ ];
+ renderSection();
+ expect(screen.getByRole("button", { name: "Issues in All issues" })).toHaveAttribute("aria-expanded", "false");
+ expect(screen.getByRole("button", { name: "Issues in Not done" })).toHaveAttribute("aria-expanded", "false");
+ });
+
+ describe("view state follows where the click actually navigates", () => {
+ beforeEach(() => {
+ actions.sidebar.items = [
+ { id: "builtin:all_issues", kind: "builtin", key: "all_issues" },
+ { id: "view:v1", kind: "view", view: SAVED_VIEW },
+ ];
+ });
+
+ it("leaves the open view alone when All issues or a view opens in a new tab", () => {
+ useActiveIssueViewStore.setState({ active: { [WORKSPACE_KEY]: "v-open" } });
+ const openInNewTab = vi.fn();
+ renderSection(makeAdapter({ openInNewTab }));
+
+ fireEvent.click(screen.getByRole("link", { name: "All issues" }), { metaKey: true });
+ fireEvent.click(screen.getByRole("link", { name: "Not done" }), { metaKey: true });
+
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues", "All issues");
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues?view=v1", "Not done");
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v-open");
+ });
+
+ it("closes the open view for a desktop shift-click on All issues, which navigates in place", () => {
+ useActiveIssueViewStore.setState({ active: { [WORKSPACE_KEY]: "v1" } });
+ const push = vi.fn();
+ renderSection(makeAdapter({ push, openInNewTab: vi.fn() }));
+
+ fireEvent.click(screen.getByRole("link", { name: "All issues" }), { shiftKey: true });
+
+ expect(push).toHaveBeenCalledWith("/acme/issues");
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBeUndefined();
+ });
+
+ it("opens a view for a desktop shift-click", () => {
+ renderSection(makeAdapter({ openInNewTab: vi.fn() }));
+ fireEvent.click(screen.getByRole("link", { name: "Not done" }), { shiftKey: true });
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v1");
+ });
+
+ it("leaves state alone for a web shift-click, which the browser opens in a new window", () => {
+ useActiveIssueViewStore.setState({ active: { [WORKSPACE_KEY]: "v-open" } });
+ const push = vi.fn();
+ renderSection(makeAdapter({ push }));
+
+ fireEvent.click(screen.getByRole("link", { name: "All issues" }), { shiftKey: true });
+ fireEvent.click(screen.getByRole("link", { name: "Not done" }), { shiftKey: true });
+
+ expect(push).not.toHaveBeenCalled();
+ expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v-open");
+ });
+ });
+});
diff --git a/packages/views/layout/panels/views-section.tsx b/packages/views/layout/panels/views-section.tsx
new file mode 100644
index 0000000000..02e436f8e2
--- /dev/null
+++ b/packages/views/layout/panels/views-section.tsx
@@ -0,0 +1,507 @@
+"use client";
+
+import { useCallback, useEffect, useId, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useStore } from "zustand";
+import { DndContext, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
+import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
+import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
+import { CSS } from "@dnd-kit/utilities";
+import { Bot, CircleUser, Copy, EyeOff, Layers, Link2, ListTodo, MoreHorizontal, Pencil, Plus, Trash2 } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import type { IssueView } from "@multica/core/api/schemas";
+import { isMyAgentsSearch, useWorkspacePaths } from "@multica/core/paths";
+import { sidebarIssuesOptions } from "@multica/core/issues/queries";
+import {
+ SIDEBAR_FIRST_PAGE,
+ builtinSidebarRequest,
+ builtinSidebarSource,
+ viewSidebarRequest,
+ viewSidebarSource,
+ type SidebarIssuesRequest,
+} from "@multica/core/issues/sidebar-list";
+import { todayDateOnly } from "@multica/core/issues/date";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
+import {
+ myIssuesRelationFromScope,
+ myIssuesScopeFor,
+ myIssuesViewStore,
+} from "@multica/core/issues/stores/my-issues-view-store";
+import {
+ issueViewContainerKey,
+ useActiveIssueViewStore,
+} from "@multica/core/issue-views/active-view-store";
+import { issueViewEverywhereOptions } from "@multica/core/issue-views/queries";
+import { issueViewSeedDefinition } from "@multica/core/issue-views/definition";
+import { useIssueViewRenameStore } from "@multica/core/issue-views/rename-store";
+import { builtinViewItemId, type BuiltinViewKey, type SidebarViewItem } from "@multica/core/issue-views/sidebar-views";
+import { issueViewTarget } from "@multica/core/issue-views/view-target";
+import { useIssueViewActions, type IssueViewActions } from "../../issue-views/use-view-actions";
+import { DeleteViewDialog } from "../../issue-views/delete-view-dialog";
+import { ViewNameInput } from "../../issue-views/view-name-input";
+import { useBuiltinViewNavigation } from "../../issue-views/builtin-views";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { PANEL_ROW_CLASS, PanelCount, PanelLink, PanelList, PanelSection, isPathWithin, panelRowStateClass } from "../panel-nav";
+import { SidebarIssueList, TREE_ROW_BUTTON_CLASS, TreeRow } from "./sidebar-tree";
+
+const DRAG_MODIFIERS = [restrictToVerticalAxis, restrictToFirstScrollableAncestor];
+const EMPTY_VIEWS: IssueView[] = [];
+const WORKSPACE_SCOPE = { scope_type: "workspace" } as const;
+const MY_SCOPE = { scope_type: "my" } as const;
+const NO_SEARCH = new URLSearchParams();
+const ROW_MENU_CLASS = cn(
+ TREE_ROW_BUTTON_CLASS,
+ "text-muted-foreground opacity-0 group-hover/row:opacity-100 data-[popup-open]:opacity-100 [@media(pointer:coarse)]:opacity-100",
+);
+
+interface ViewsSectionProps {
+ wsId: string;
+ pathname: string;
+ plainRowsLit: boolean;
+ /** An expanded tree row lists the current issue, so "All issues" stays unlit. */
+ issueLitInTree: boolean;
+ activeIssueId: string | null;
+}
+
+/**
+ * The user's starred views, built-in and saved alike, in their own order,
+ * closed by the way to every other view.
+ */
+export function ViewsSection({
+ wsId,
+ pathname,
+ plainRowsLit,
+ issueLitInTree,
+ activeIssueId,
+}: ViewsSectionProps) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const actions = useIssueViewActions();
+ const { items, reorder } = actions.sidebar;
+ const { data: allViews = EMPTY_VIEWS } = useQuery(issueViewEverywhereOptions(wsId));
+ const [deleteTarget, setDeleteTarget] = useState<IssueView | null>(null);
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
+ const collapsed = useSidebarTreeStore((s) => s.viewsCollapsed);
+ const setCollapsed = useSidebarTreeStore((s) => s.setViewsCollapsed);
+
+ const onDragEnd = useCallback(
+ ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ const ids = items.map((item) => item.id);
+ const from = ids.indexOf(String(active.id));
+ const to = ids.indexOf(String(over.id));
+ if (from === -1 || to === -1) return;
+ reorder(arrayMove(ids, from, to));
+ },
+ [items, reorder],
+ );
+
+ return (
+ <PanelSection
+ label={t(($) => $.panels.work.views)}
+ collapsed={collapsed}
+ onCollapsedChange={setCollapsed}
+ action={
+ <IconButton
+ label={t(($) => $.panels.work.new_view)}
+ size="icon-xs"
+ className="text-muted-foreground"
+ onClick={() => {
+ // The new view is named inline in this list, so it has to be open.
+ setCollapsed(false);
+ actions.create({
+ scope: WORKSPACE_SCOPE,
+ scopeVariant: null,
+ definition: issueViewSeedDefinition({ query: {}, display: {} }),
+ renameIn: "sidebar",
+ });
+ }}
+ >
+ <Plus />
+ </IconButton>
+ }
+ >
+ <DndContext sensors={sensors} collisionDetection={closestCenter} modifiers={DRAG_MODIFIERS} onDragEnd={onDragEnd}>
+ <SortableContext items={items.map((item) => item.id)} strategy={verticalListSortingStrategy}>
+ <PanelList>
+ {items.map((item) => (
+ <SortableViewRow key={item.id} id={item.id}>
+ {(drag) =>
+ item.kind === "builtin" ? (
+ <BuiltinViewRow
+ wsId={wsId}
+ builtin={item.key}
+ pathname={pathname}
+ plainRowsLit={plainRowsLit}
+ issueLitInTree={issueLitInTree}
+ activeIssueId={activeIssueId}
+ actions={actions}
+ drag={drag}
+ />
+ ) : (
+ <SavedViewRow
+ wsId={wsId}
+ item={item}
+ pathname={pathname}
+ plainRowsLit={plainRowsLit}
+ activeIssueId={activeIssueId}
+ actions={actions}
+ onDelete={setDeleteTarget}
+ drag={drag}
+ />
+ )
+ }
+ </SortableViewRow>
+ ))}
+ </PanelList>
+ </SortableContext>
+ </DndContext>
+ <PanelList className="mt-px">
+ <PanelLink
+ href={p.views()}
+ icon={<span className="size-4" aria-hidden />}
+ label={t(($) => $.panels.work.all_views)}
+ active={pathname === p.views()}
+ trailing={<PanelCount value={allViews.length + 3} />}
+ className="text-caption"
+ />
+ </PanelList>
+ <DeleteViewDialog
+ view={deleteTarget}
+ onOpenChange={(open) => !open && setDeleteTarget(null)}
+ onConfirm={actions.remove}
+ />
+ </PanelSection>
+ );
+}
+
+function usePrefetch(wsId: string, source: string, request: SidebarIssuesRequest | null | undefined) {
+ const qc = useQueryClient();
+ return () => {
+ if (request) void qc.prefetchQuery(sidebarIssuesOptions(wsId, source, request, SIDEBAR_FIRST_PAGE));
+ };
+}
+
+interface DragBindings {
+ rowRef: (node: HTMLElement | null) => void;
+ listeners: ReturnType<typeof useSortable>["listeners"];
+ /** True right after a drag, so the release does not also navigate. */
+ consumeDrag: () => boolean;
+}
+
+function SortableViewRow({ id, children }: { id: string; children: (drag: DragBindings) => React.ReactNode }) {
+ const { listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id });
+ const wasDragged = useRef(false);
+ useEffect(() => {
+ if (isDragging) wasDragged.current = true;
+ }, [isDragging]);
+ return (
+ <li
+ ref={setNodeRef}
+ style={{ transform: CSS.Translate.toString(transform), transition }}
+ className={cn(
+ isDragging && "relative z-20 rounded-lg bg-surface-raised shadow-[var(--menu-shadow)] ring-1 ring-surface-border",
+ )}
+ >
+ {children({
+ rowRef: setActivatorNodeRef,
+ listeners,
+ consumeDrag: () => {
+ if (!wasDragged.current) return false;
+ wasDragged.current = false;
+ return true;
+ },
+ })}
+ </li>
+ );
+}
+
+/** "…" on hover, and the same menu on right-click. */
+function RowMenu({
+ label,
+ open,
+ onOpenChange,
+ children,
+}: {
+ label: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <DropdownMenu open={open} onOpenChange={onOpenChange}>
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ aria-label={label}
+ onPointerDown={(event) => event.stopPropagation()}
+ className={ROW_MENU_CLASS}
+ />
+ }
+ >
+ <MoreHorizontal className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" side="right" className="w-auto min-w-48">
+ {children}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+const BUILTIN_ICON: Record<BuiltinViewKey, React.ReactNode> = {
+ my_issues: <CircleUser className="size-4 shrink-0" />,
+ my_agents: <Bot className="size-4 shrink-0" />,
+ all_issues: <ListTodo className="size-4 shrink-0" />,
+};
+
+function BuiltinViewRow({
+ wsId,
+ builtin,
+ pathname,
+ plainRowsLit,
+ issueLitInTree,
+ activeIssueId,
+ actions,
+ drag,
+}: {
+ wsId: string;
+ builtin: BuiltinViewKey;
+ pathname: string;
+ plainRowsLit: boolean;
+ issueLitInTree: boolean;
+ activeIssueId: string | null;
+ actions: IssueViewActions;
+ drag: DragBindings;
+}) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const listId = useId();
+ const linkRef = useRef<HTMLAnchorElement>(null);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const builtinNav = useBuiltinViewNavigation();
+ const { searchParams } = useNavigation();
+ const myScope = useStore(myIssuesViewStore, (s) => myIssuesScopeFor(NO_SEARCH, s.scope));
+ const workspaceKey = issueViewContainerKey(wsId, WORKSPACE_SCOPE);
+ const myKey = issueViewContainerKey(wsId, MY_SCOPE);
+ const activeWorkspaceView = useActiveIssueViewStore((s) => s.active[workspaceKey] ?? null);
+ const activeMyView = useActiveIssueViewStore((s) => s.active[myKey] ?? null);
+
+ const onMyIssues = pathname === p.myIssues();
+ const href = builtinNav.hrefFor(builtin);
+ const label =
+ builtin === "my_issues"
+ ? t(($) => $.nav.my_issues)
+ : builtin === "my_agents"
+ ? t(($) => $.panels.work.my_agents)
+ : t(($) => $.panels.work.all_issues);
+ const active =
+ plainRowsLit &&
+ (builtin === "all_issues"
+ ? pathname === p.issues()
+ ? activeWorkspaceView === null
+ : !issueLitInTree && isPathWithin(pathname, p.issues())
+ : onMyIssues && activeMyView === null && (builtin === "my_agents") === isMyAgentsSearch(searchParams));
+
+ const source = builtinSidebarSource(builtin);
+ const expanded = useSidebarTreeStore((s) => s.expanded.includes(source));
+ const setExpanded = useSidebarTreeStore((s) => s.setExpanded);
+ const statusCatalog = useIssueStatuses(wsId);
+ const settings = useSidebarTreeStore((s) => s.issueSettings);
+ const request = statusCatalog.isLoaded
+ ? builtinSidebarRequest(builtin, myIssuesRelationFromScope(myScope), settings, statusCatalog.statuses)
+ : undefined;
+ const prefetch = usePrefetch(wsId, source, request);
+
+ return (
+ <>
+ <TreeRow
+ ref={linkRef}
+ rowRef={drag.rowRef}
+ {...drag.listeners}
+ href={href}
+ label={label}
+ icon={BUILTIN_ICON[builtin]}
+ active={active}
+ expanded={expanded}
+ onExpandedChange={(next) => setExpanded(source, next)}
+ listId={listId}
+ toggleLabel={t(($) => $.panels.work.project_issues, { name: label })}
+ onPrefetch={prefetch}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ setMenuOpen(true);
+ }}
+ onNavigate={(event) => {
+ if (drag.consumeDrag()) event.preventDefault();
+ }}
+ onNavigateInPlace={() => builtinNav.prepare(builtin)}
+ trailing={
+ <RowMenu label={t(($) => $.panels.work.view_actions, { name: label })} open={menuOpen} onOpenChange={setMenuOpen}>
+ <DropdownMenuItem onClick={() => actions.copyLink(href)}>
+ <Link2 className="size-3.5" />
+ {t(($) => $.panels.work.view_copy_link)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => actions.sidebar.unstar(builtinViewItemId(builtin))}>
+ <EyeOff className="size-3.5" />
+ {t(($) => $.panels.work.view_remove)}
+ </DropdownMenuItem>
+ </RowMenu>
+ }
+ />
+ {expanded && (
+ <SidebarIssueList
+ id={listId}
+ wsId={wsId}
+ source={source}
+ params={request}
+ activeIssueId={activeIssueId}
+ onCollapse={() => {
+ setExpanded(source, false);
+ linkRef.current?.focus();
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+function SavedViewRow({
+ wsId,
+ item,
+ pathname,
+ plainRowsLit,
+ activeIssueId,
+ actions,
+ onDelete,
+ drag,
+}: {
+ wsId: string;
+ item: Extract<SidebarViewItem, { kind: "view" }>;
+ pathname: string;
+ plainRowsLit: boolean;
+ activeIssueId: string | null;
+ actions: IssueViewActions;
+ onDelete: (view: IssueView) => void;
+ drag: DragBindings;
+}) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const { view } = item;
+ const listId = useId();
+ const linkRef = useRef<HTMLAnchorElement>(null);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const target = issueViewTarget(wsId, view, p);
+ const active = useActiveIssueViewStore(
+ (s) => plainRowsLit && pathname === target.path && s.active[target.containerKey] === view.id,
+ );
+ const setActive = useActiveIssueViewStore((s) => s.setActive);
+ const renaming = useIssueViewRenameStore(
+ (s) => s.target?.surface === "sidebar" && s.target.viewId === view.id,
+ );
+ const startRename = useIssueViewRenameStore((s) => s.start);
+ const stopRename = useIssueViewRenameStore((s) => s.stop);
+ const source = viewSidebarSource(view.id);
+ const expanded = useSidebarTreeStore((s) => s.expanded.includes(source));
+ const setExpanded = useSidebarTreeStore((s) => s.setExpanded);
+ const request = viewSidebarRequest(view, todayDateOnly());
+ const prefetch = usePrefetch(wsId, source, request);
+ const canManage = actions.canManage(view);
+
+ if (renaming) {
+ return (
+ <div className={cn(PANEL_ROW_CLASS, panelRowStateClass(active), "py-1")}>
+ <Layers className="size-4 shrink-0" />
+ <ViewNameInput
+ initial={view.name}
+ onCommit={(name) => actions.rename(view, name)}
+ onDone={stopRename}
+ className="w-full"
+ />
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <TreeRow
+ ref={linkRef}
+ rowRef={drag.rowRef}
+ {...drag.listeners}
+ href={target.href}
+ label={view.name}
+ icon={<Layers className="size-4 shrink-0" />}
+ active={active}
+ expanded={expanded}
+ onExpandedChange={(next) => setExpanded(source, next)}
+ listId={listId}
+ toggleLabel={t(($) => $.panels.work.project_issues, { name: view.name })}
+ onPrefetch={prefetch}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ setMenuOpen(true);
+ }}
+ onNavigate={(event) => {
+ if (drag.consumeDrag()) event.preventDefault();
+ }}
+ onNavigateInPlace={() => setActive(target.containerKey, view.id)}
+ trailing={
+ <RowMenu label={t(($) => $.panels.work.view_actions, { name: view.name })} open={menuOpen} onOpenChange={setMenuOpen}>
+ {canManage && (
+ <DropdownMenuItem onClick={() => startRename(view.id, "sidebar")}>
+ <Pencil className="size-3.5" />
+ {t(($) => $.panels.work.view_rename)}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onClick={() => actions.duplicate(view, "sidebar")}>
+ <Copy className="size-3.5" />
+ {t(($) => $.panels.work.view_duplicate)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => actions.copyLink(target.href)}>
+ <Link2 className="size-3.5" />
+ {t(($) => $.panels.work.view_copy_link)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => actions.sidebar.unstar(item.id)}>
+ <EyeOff className="size-3.5" />
+ {t(($) => $.panels.work.view_remove)}
+ </DropdownMenuItem>
+ {canManage && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={() => onDelete(view)}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.panels.work.view_delete)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </RowMenu>
+ }
+ />
+ {expanded && (
+ <SidebarIssueList
+ id={listId}
+ wsId={wsId}
+ source={source}
+ params={request}
+ activeIssueId={activeIssueId}
+ onCollapse={() => {
+ setExpanded(source, false);
+ linkRef.current?.focus();
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/packages/views/layout/panels/work-panel.tsx b/packages/views/layout/panels/work-panel.tsx
new file mode 100644
index 0000000000..3209e39990
--- /dev/null
+++ b/packages/views/layout/panels/work-panel.tsx
@@ -0,0 +1,118 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@multica/core/auth";
+import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import { projectSidebarSource, sidebarProjects } from "@multica/core/issues/sidebar-list";
+import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { Project } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { PanelBody, PanelHeader } from "../panel-nav";
+import { PinnedSection, usePanelPins } from "./pinned-section";
+import { ProjectsSection, useIssueShownInTree } from "./work-tree";
+import { ViewsSection } from "./views-section";
+
+const EMPTY_PROJECTS: Project[] = [];
+
+/** The `{id}` of an `/issues/{id}` route — a UUID or an identifier like `MUL-123`. */
+function issueRouteSegment(pathname: string, issuesPath: string): string | null {
+ if (!pathname.startsWith(issuesPath + "/")) return null;
+ const segment = pathname.slice(issuesPath.length + 1).split("/")[0];
+ return segment ? decodeURIComponent(segment) : null;
+}
+
+export function WorkPanel() {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const { pathname } = useNavigation();
+ const wsId = useCurrentWorkspace()?.id;
+ const userId = useAuthStore((s) => s.user?.id);
+
+ const { data: projects = EMPTY_PROJECTS } = useQuery({
+ ...projectListOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ // Cache read only: the detail page owns resolving the route's issue.
+ const issueSegment = issueRouteSegment(pathname, p.issues());
+ const { data: currentIssue } = useQuery({
+ ...issueDetailOptions(wsId ?? "", issueSegment ?? ""),
+ enabled: false,
+ });
+ const currentIssueId = issueSegment ? (currentIssue?.id ?? null) : null;
+ // An issue can sit in Pinned and in the tree at once. The row that was
+ // clicked keeps the highlight; arriving any other way (search, a link, a
+ // shortcut) lights the pin.
+ const [clickedIssue, setClickedIssue] = useState<{ segment: string; fromPins: boolean } | null>(null);
+ const treeClaimsIssue =
+ !!clickedIssue &&
+ !clickedIssue.fromPins &&
+ !!currentIssue &&
+ (clickedIssue.segment === currentIssue.id || clickedIssue.segment === currentIssue.identifier);
+ const pins = usePanelPins(wsId, userId, pathname, treeClaimsIssue ? null : currentIssueId);
+ const rememberClickedIssue = (event: React.MouseEvent) => {
+ const link = (event.target as HTMLElement).closest("a[href]");
+ if (!link) return;
+ const path = new URL(link.getAttribute("href") ?? "", window.location.href).pathname;
+ const segment = issueRouteSegment(path, p.issues());
+ setClickedIssue(segment ? { segment, fromPins: !!link.closest("[data-pinned-section]") } : null);
+ };
+ // A lit pin already marks the issue; opening its project would only push
+ // the rest of the panel down.
+ const revealProjectId =
+ issueSegment && !pins.isActivePinnedRoute ? (currentIssue?.project_id ?? null) : null;
+
+ const setExpanded = useSidebarTreeStore((s) => s.setExpanded);
+ useEffect(() => {
+ if (revealProjectId) setExpanded(projectSidebarSource(revealProjectId), true);
+ }, [revealProjectId, setExpanded]);
+
+ const projectSettings = useSidebarTreeStore((s) => s.projectSettings);
+ const projectOrder = useSidebarTreeStore((s) => s.projectOrder);
+ const shownProjects = useMemo(() => {
+ const shown = sidebarProjects(projects, projectSettings, projectOrder, userId);
+ const revealed = projects.find((project) => project.id === revealProjectId);
+ return revealed && !shown.includes(revealed) ? [...shown, revealed] : shown;
+ }, [projects, projectSettings, projectOrder, userId, revealProjectId]);
+ // A tree row takes the highlight from "All issues" while it lists the issue.
+ const issueLitInTree = useIssueShownInTree(wsId ?? "", currentIssueId);
+ const plainRowsLit = !pins.isActivePinnedRoute;
+
+ return (
+ <>
+ <PanelHeader title={t(($) => $.spaces.work)} />
+ <PanelBody onClickCapture={rememberClickedIssue}>
+ {wsId && (
+ <ViewsSection
+ wsId={wsId}
+ pathname={pathname}
+ plainRowsLit={plainRowsLit}
+ issueLitInTree={issueLitInTree}
+ activeIssueId={plainRowsLit ? currentIssueId : null}
+ />
+ )}
+
+ {wsId && (
+ <div data-pinned-section className="contents">
+ <PinnedSection pins={pins} wsId={wsId} />
+ </div>
+ )}
+
+ {wsId && (
+ <ProjectsSection
+ wsId={wsId}
+ userId={userId}
+ pathname={pathname}
+ projects={shownProjects}
+ totalProjects={projects.length}
+ plainRowsLit={plainRowsLit}
+ activeIssueId={plainRowsLit ? currentIssueId : null}
+ />
+ )}
+ </PanelBody>
+ </>
+ );
+}
diff --git a/packages/views/layout/panels/work-tree.test.tsx b/packages/views/layout/panels/work-tree.test.tsx
new file mode 100644
index 0000000000..1ce423dc33
--- /dev/null
+++ b/packages/views/layout/panels/work-tree.test.tsx
@@ -0,0 +1,124 @@
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DragEndEvent } from "@dnd-kit/core";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
+import {
+ DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ DEFAULT_SIDEBAR_PROJECT_SETTINGS,
+ useSidebarTreeStore,
+} from "@multica/core/issues/stores/sidebar-tree-store";
+import type { Project } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { ProjectsSection } from "./work-tree";
+
+const openCreateIssue = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/issues/stores/create-mode-store", () => ({
+ openCreateIssueWithPreference: openCreateIssue,
+}));
+
+const dnd = vi.hoisted(() => ({ onDragEnd: undefined as ((event: DragEndEvent) => void) | undefined }));
+
+vi.mock("@dnd-kit/core", () => ({
+ DndContext: ({ children, onDragEnd }: { children: ReactNode; onDragEnd: (event: DragEndEvent) => void }) => {
+ dnd.onDragEnd = onDragEnd;
+ return <>{children}</>;
+ },
+ PointerSensor: vi.fn(),
+ closestCenter: vi.fn(),
+ useSensor: vi.fn(),
+ useSensors: vi.fn(),
+}));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog([]),
+}));
+vi.mock("../../navigation", () => ({
+ AppLink: ({
+ children,
+ href,
+ newTabTitle: _newTabTitle,
+ ...props
+ }: { children: ReactNode; href: string; newTabTitle?: string } & React.ComponentProps<"a">) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("../../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));
+vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
+ TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
+});
+
+const project = (id: string, title: string): Project =>
+ ({ id, title, status: "in_progress", issue_count: 4, done_count: 1 }) as Project;
+const PROJECTS = [project("p1", "Desktop"), project("p2", "Mobile"), project("p3", "Web")];
+
+beforeEach(() => {
+ useSidebarTreeStore.setState({
+ expanded: [],
+ issueSettings: DEFAULT_SIDEBAR_ISSUE_SETTINGS,
+ projectSettings: { ...DEFAULT_SIDEBAR_PROJECT_SETTINGS, ordering: "name" },
+ projectOrder: ["p9"],
+ projectsCollapsed: false,
+ });
+});
+
+function renderSection() {
+ const qc = new QueryClient({ defaultOptions: { queries: { enabled: false } } });
+ renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <ProjectsSection
+ wsId="ws-1"
+ userId="u1"
+ pathname="/acme/issues"
+ projects={PROJECTS}
+ totalProjects={4}
+ plainRowsLit
+ activeIssueId={null}
+ />
+ </QueryClientProvider>,
+ );
+}
+
+describe("ProjectsSection", () => {
+ it("expands a project in place, keeping its count", () => {
+ renderSection();
+ expect(screen.getAllByText("3")).toHaveLength(3);
+
+ fireEvent.click(screen.getByRole("button", { name: "Issues in Mobile" }));
+ expect(useSidebarTreeStore.getState().expanded).toEqual(["project:p2"]);
+ expect(screen.getByRole("button", { name: "Issues in Mobile" })).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getAllByText("3")).toHaveLength(3);
+ });
+
+ it("keeps display settings on the section header only", () => {
+ renderSection();
+ fireEvent.click(screen.getByRole("button", { name: "Issues in Mobile" }));
+ expect(screen.getAllByRole("button", { name: "Project display" })).toHaveLength(1);
+ });
+
+ it("drops into a manual order, keeping hidden projects after the shown ones", () => {
+ renderSection();
+ dnd.onDragEnd?.({ active: { id: "p3" }, over: { id: "p1" } } as DragEndEvent);
+ const state = useSidebarTreeStore.getState();
+ expect(state.projectOrder).toEqual(["p3", "p1", "p2", "p9"]);
+ expect(state.projectSettings.ordering).toBe("manual");
+ });
+
+ it("creates an issue in a project from its row", () => {
+ renderSection();
+ fireEvent.click(screen.getByRole("button", { name: "New issue in Mobile" }));
+ expect(openCreateIssue).toHaveBeenCalledWith({ project_id: "p2" });
+ });
+
+ it("collapses from the section label", () => {
+ renderSection();
+ fireEvent.click(screen.getByRole("button", { name: "Projects" }));
+ expect(useSidebarTreeStore.getState().projectsCollapsed).toBe(true);
+ });
+});
diff --git a/packages/views/layout/panels/work-tree.tsx b/packages/views/layout/panels/work-tree.tsx
new file mode 100644
index 0000000000..ba03cde685
--- /dev/null
+++ b/packages/views/layout/panels/work-tree.tsx
@@ -0,0 +1,249 @@
+"use client";
+
+import { useCallback, useEffect, useId, useRef, useSyncExternalStore } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { DndContext, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
+import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
+import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
+import { CSS } from "@dnd-kit/utilities";
+import { Folder, Plus } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { issueKeys, sidebarIssuesOptions } from "@multica/core/issues/queries";
+import {
+ SIDEBAR_FIRST_PAGE,
+ projectSidebarParams,
+ projectSidebarSource,
+} from "@multica/core/issues/sidebar-list";
+import { openCreateIssueWithPreference } from "@multica/core/issues/stores/create-mode-store";
+import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
+import { useModalStore } from "@multica/core/modals";
+import { useWorkspacePaths } from "@multica/core/paths";
+import type { ListIssuesParams, ListIssuesResponse, Project } from "@multica/core/types";
+import { useT } from "../../i18n";
+import { PanelCount, PanelLink, PanelList, PanelSection, isPathWithin } from "../panel-nav";
+import { ProjectsSectionSettings } from "./sidebar-settings";
+import { SidebarIssueList, TreeRow } from "./sidebar-tree";
+
+const DRAG_MODIFIERS = [restrictToVerticalAxis, restrictToFirstScrollableAncestor];
+
+function useExpanded(key: string) {
+ const expanded = useSidebarTreeStore((s) => s.expanded.includes(key));
+ const setExpanded = useSidebarTreeStore((s) => s.setExpanded);
+ return [expanded, (next: boolean) => setExpanded(key, next)] as const;
+}
+
+function usePrefetch(wsId: string, source: string, params: ListIssuesParams | null | undefined) {
+ const qc = useQueryClient();
+ return () => {
+ if (params) void qc.prefetchQuery(sidebarIssuesOptions(wsId, source, params, SIDEBAR_FIRST_PAGE));
+ };
+}
+
+/** Whether an expanded row currently lists the issue. */
+export function useIssueShownInTree(wsId: string, issueId: string | null): boolean {
+ const cache = useQueryClient().getQueryCache();
+ const subscribe = useCallback((onChange: () => void) => cache.subscribe(onChange), [cache]);
+ return useSyncExternalStore(subscribe, () =>
+ !!issueId &&
+ cache
+ .findAll({ queryKey: issueKeys.sidebarAll(wsId) })
+ .some(
+ (query) =>
+ query.getObserversCount() > 0 &&
+ !!(query.state.data as ListIssuesResponse | undefined)?.issues?.some((issue) => issue.id === issueId),
+ ),
+ );
+}
+
+interface ProjectsSectionProps {
+ wsId: string;
+ userId: string | undefined;
+ pathname: string;
+ /** Already filtered and ordered by the section's settings. */
+ projects: Project[];
+ totalProjects: number;
+ plainRowsLit: boolean;
+ activeIssueId: string | null;
+}
+
+export function ProjectsSection({
+ wsId,
+ userId,
+ pathname,
+ projects,
+ totalProjects,
+ plainRowsLit,
+ activeIssueId,
+}: ProjectsSectionProps) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const collapsed = useSidebarTreeStore((s) => s.projectsCollapsed);
+ const setCollapsed = useSidebarTreeStore((s) => s.setProjectsCollapsed);
+ const showCount = useSidebarTreeStore((s) => s.projectSettings.showCount);
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));
+
+ const onDragEnd = useCallback(
+ ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ const ids = projects.map((project) => project.id);
+ const from = ids.indexOf(String(active.id));
+ const to = ids.indexOf(String(over.id));
+ if (from === -1 || to === -1) return;
+ const store = useSidebarTreeStore.getState();
+ const moved = arrayMove(ids, from, to);
+ // Projects the filter hides keep their relative place after the shown ones.
+ store.setProjectOrder([...moved, ...store.projectOrder.filter((id) => !moved.includes(id))]);
+ if (store.projectSettings.ordering !== "manual") store.setProjectSettings({ ordering: "manual" });
+ },
+ [projects],
+ );
+
+ return (
+ <PanelSection
+ label={t(($) => $.nav.projects)}
+ collapsed={collapsed}
+ onCollapsedChange={setCollapsed}
+ action={
+ <>
+ <ProjectsSectionSettings wsId={wsId} className="opacity-0 group-hover/section:opacity-100 group-focus-within/section:opacity-100 [@media(pointer:coarse)]:opacity-100" />
+ <IconButton
+ label={t(($) => $.panels.work.new_project)}
+ size="icon-xs"
+ className="text-muted-foreground"
+ onClick={() => useModalStore.getState().open("create-project")}
+ >
+ <Plus />
+ </IconButton>
+ </>
+ }
+ >
+ <DndContext sensors={sensors} collisionDetection={closestCenter} modifiers={DRAG_MODIFIERS} onDragEnd={onDragEnd}>
+ <SortableContext items={projects.map((project) => project.id)} strategy={verticalListSortingStrategy}>
+ <PanelList>
+ {projects.map((project) => (
+ <ProjectTreeItem
+ key={project.id}
+ wsId={wsId}
+ userId={userId}
+ project={project}
+ active={plainRowsLit && isPathWithin(pathname, p.projectDetail(project.id))}
+ showCount={showCount}
+ activeIssueId={activeIssueId}
+ />
+ ))}
+ </PanelList>
+ </SortableContext>
+ </DndContext>
+ <PanelList className="mt-px">
+ <PanelLink
+ href={p.projects()}
+ icon={<span className="size-4" aria-hidden />}
+ label={t(($) => $.panels.work.all_projects, { count: totalProjects })}
+ active={pathname === p.projects()}
+ className="text-caption"
+ />
+ </PanelList>
+ </PanelSection>
+ );
+}
+
+function ProjectTreeItem({
+ wsId,
+ userId,
+ project,
+ active,
+ showCount,
+ activeIssueId,
+}: {
+ wsId: string;
+ userId: string | undefined;
+ project: Project;
+ active: boolean;
+ showCount: boolean;
+ activeIssueId: string | null;
+}) {
+ const { t } = useT("layout");
+ const p = useWorkspacePaths();
+ const listId = useId();
+ const linkRef = useRef<HTMLAnchorElement>(null);
+ const source = projectSidebarSource(project.id);
+ const [expanded, setExpanded] = useExpanded(source);
+ const statusCatalog = useIssueStatuses(wsId);
+ const settings = useSidebarTreeStore((s) => s.issueSettings);
+ const params = statusCatalog.isLoaded
+ ? projectSidebarParams(project.id, settings, statusCatalog.statuses, userId)
+ : undefined;
+ const prefetch = usePrefetch(wsId, source, params);
+
+ const { listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id: project.id });
+ const wasDragged = useRef(false);
+ useEffect(() => {
+ if (isDragging) wasDragged.current = true;
+ }, [isDragging]);
+
+ return (
+ <li
+ ref={setNodeRef}
+ style={{ transform: CSS.Translate.toString(transform), transition }}
+ className={cn(
+ isDragging &&
+ "relative z-20 rounded-lg bg-surface-raised shadow-[var(--menu-shadow)] ring-1 ring-surface-border",
+ )}
+ >
+ <TreeRow
+ ref={linkRef}
+ rowRef={setActivatorNodeRef}
+ {...listeners}
+ href={p.projectDetail(project.id)}
+ label={project.title}
+ icon={<Folder className="size-4 shrink-0" />}
+ active={active}
+ expanded={expanded}
+ onExpandedChange={setExpanded}
+ listId={listId}
+ toggleLabel={t(($) => $.panels.work.project_issues, { name: project.title })}
+ onPrefetch={prefetch}
+ onNavigate={(event) => {
+ if (!wasDragged.current) return;
+ wasDragged.current = false;
+ event.preventDefault();
+ }}
+ trailing={
+ // The button takes the count's place on hover, so the row never reflows.
+ <span className="relative flex h-5 min-w-5 items-center justify-end">
+ {showCount && (
+ <PanelCount
+ value={project.issue_count - project.done_count}
+ className="transition-opacity group-focus-within/row:opacity-0 group-hover/row:opacity-0 [@media(pointer:coarse)]:opacity-0"
+ />
+ )}
+ <IconButton
+ label={t(($) => $.panels.work.new_issue_in_project, { name: project.title })}
+ size="icon-xs"
+ className="absolute -right-1 z-10 text-muted-foreground opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100 focus-visible:opacity-100 [@media(pointer:coarse)]:opacity-100"
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={() => openCreateIssueWithPreference({ project_id: project.id })}
+ >
+ <Plus />
+ </IconButton>
+ </span>
+ }
+ />
+ {expanded && (
+ <SidebarIssueList
+ id={listId}
+ wsId={wsId}
+ source={source}
+ params={params}
+ activeIssueId={activeIssueId}
+ onCollapse={() => {
+ setExpanded(false);
+ linkRef.current?.focus();
+ }}
+ />
+ )}
+ </li>
+ );
+}
diff --git a/packages/views/layout/rail-styles.ts b/packages/views/layout/rail-styles.ts
new file mode 100644
index 0000000000..67e346bdd5
--- /dev/null
+++ b/packages/views/layout/rail-styles.ts
@@ -0,0 +1,18 @@
+/**
+ * The rail sits on the app shell, where the page surface tokens are nearly
+ * invisible (`--surface-hover` is within a hair of `--app-shell` in light
+ * mode), so rail controls use the sidebar accent instead.
+ */
+/**
+ * The space panel's and list columns' collapse motion. Their content is
+ * end-aligned, so it slides with the moving edge instead of being wiped.
+ */
+export const NAV_COLUMN_MOTION_CLASS =
+ "transition-[width] duration-(--nav-panel-duration) ease-(--nav-panel-easing) motion-reduce:transition-none";
+
+/** A collapsed panel or list column previewed over the card's leading edge. */
+export const NAV_PEEK_CLASS =
+ "absolute inset-y-0 left-0 z-30 flex w-(--sidebar-width) flex-col overflow-hidden rounded-xl bg-page-canvas shadow-[var(--floating-shadow)] ring-1 ring-surface-border";
+
+export const RAIL_ICON_BUTTON_CLASS =
+ "relative inline-flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-lg text-muted-foreground transition-colors outline-none hover:bg-sidebar-accent/70 hover:text-sidebar-accent-foreground focus-visible:outline-2 focus-visible:outline-ring data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground aria-[current=page]:bg-sidebar-accent aria-[current=page]:text-sidebar-accent-foreground [&_svg:not([class*='size-'])]:size-[18px]";
diff --git a/packages/views/layout/rail-workspaces.test.tsx b/packages/views/layout/rail-workspaces.test.tsx
new file mode 100644
index 0000000000..f0fe167a73
--- /dev/null
+++ b/packages/views/layout/rail-workspaces.test.tsx
@@ -0,0 +1,173 @@
+import type { ReactNode } from "react";
+import { fireEvent, screen, within } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithI18n } from "../test/i18n";
+import { RailWorkspaces } from "./rail-workspaces";
+
+type Ws = { id: string; name: string; slug: string; avatar_url: string | null };
+
+const state = vi.hoisted(() => ({
+ workspaces: [] as Ws[],
+ invitations: [] as { id: string; workspace_id: string; workspace_name?: string; inviter_name?: string }[],
+ summary: [] as { workspace_id: string; count: number }[],
+ accept: vi.fn(),
+ decline: vi.fn(),
+ invalidateQueries: vi.fn(),
+ mutations: [] as Array<Record<string, unknown>>,
+ workspaceCreationDisabled: false,
+}));
+
+vi.mock("@multica/core/config", () => ({
+ useConfigStore: (selector: (s: { workspaceCreationDisabled: boolean }) => unknown) =>
+ selector({ workspaceCreationDisabled: state.workspaceCreationDisabled }),
+}));
+
+vi.mock("../navigation", () => ({
+ AppLink: ({ children, href, ...props }: { children: ReactNode; href: string } & React.ComponentProps<"a">) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+ useNavigation: () => ({ pathname: "/active/issues", push: vi.fn() }),
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Active WS", slug: "active" }),
+}));
+vi.mock("@multica/core/api", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/api")>();
+ return {
+ ...actual,
+ api: {
+ ...actual.api,
+ getBaseUrl: () => "http://127.0.0.1:8080",
+ acceptInvitation: state.accept,
+ declineInvitation: state.decline,
+ },
+ };
+});
+vi.mock("@multica/core/inbox/queries", () => ({
+ inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),
+ inboxUnreadSummaryEnabled: () => true,
+ unreadWorkspaceIds: (entries: { workspace_id: string; count: number }[]) =>
+ new Set(entries.filter((s) => s.count > 0).map((s) => s.workspace_id)),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ myInvitationListOptions: () => ({ queryKey: ["invitations"] }),
+ workspaceKeys: { myInvitations: () => ["invitations"] },
+ workspaceListOptions: () => ({ queryKey: ["workspaces"] }),
+}));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useMutation: (options: Record<string, unknown> = {}) => {
+ state.mutations.push(options);
+ return { isPending: false, mutate: vi.fn() };
+ },
+ useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {
+ if (queryKey[0] === "workspaces") return { data: state.workspaces };
+ if (queryKey[0] === "invitations") return { data: state.invitations };
+ if (queryKey[0] === "inbox") return { data: state.summary };
+ return { data: undefined };
+ },
+ useQueryClient: () => ({ fetchQuery: vi.fn(), invalidateQueries: state.invalidateQueries }),
+}));
+vi.mock("@multica/ui/components/common/tooltip-hint", () => ({
+ TooltipHint: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+const ws = (n: number): Ws => ({ id: `ws-${n}`, name: n === 1 ? "Active WS" : `WS ${n}`, slug: n === 1 ? "active" : `ws${n}`, avatar_url: null });
+const trigger = () => screen.getByRole("button", { name: "Switch workspace" });
+const triggerHasDot = () => !!trigger().querySelector(".bg-brand");
+const openMenu = async () => {
+ fireEvent.click(trigger());
+ return screen.findByRole("menu");
+};
+
+beforeEach(() => {
+ state.workspaces = [ws(1), ws(2)];
+ state.invitations = [];
+ state.summary = [];
+ state.mutations.length = 0;
+ state.workspaceCreationDisabled = false;
+});
+
+describe("RailWorkspaces", () => {
+ it("shows only the current workspace on the rail, however many there are", async () => {
+ state.workspaces = [ws(2), ws(3), ws(4), ws(5), ws(6), ws(1)];
+ renderWithI18n(<RailWorkspaces />);
+ expect(screen.queryAllByRole("link")).toHaveLength(0);
+
+ const menu = await openMenu();
+ const items = within(menu).getAllByRole("menuitem").filter((el) => el.getAttribute("href") !== "/workspaces/new");
+ expect(items.map((el) => el.textContent?.slice(1))).toEqual(["WS 2", "WS 3", "WS 4", "WS 5", "WS 6", "Active WS"]);
+ expect(within(menu).getByRole("menuitem", { name: /Active WS$/ })).toHaveAttribute("aria-current", "page");
+ expect(within(menu).getByRole("menuitem", { name: /WS 3$/ })).toHaveAttribute("href", "/ws3/issues");
+ });
+
+ it("dots the switcher while another workspace has unread inbox items", async () => {
+ state.summary = [{ workspace_id: "ws-2", count: 3 }];
+ renderWithI18n(<RailWorkspaces />);
+ expect(triggerHasDot()).toBe(true);
+ const menu = await openMenu();
+ expect(within(menu).getByRole("menuitem", { name: /WS 2$/ }).querySelector(".bg-brand")).not.toBeNull();
+ });
+
+ // The current workspace's unread is the Inbox space's count.
+ it("does not dot the switcher for the current workspace or zero counts", () => {
+ state.summary = [
+ { workspace_id: "ws-1", count: 5 },
+ { workspace_id: "ws-2", count: 0 },
+ ];
+ renderWithI18n(<RailWorkspaces />);
+ expect(triggerHasDot()).toBe(false);
+ });
+
+ it("lists pending invitations in the menu and dots the switcher", async () => {
+ state.invitations = [{ id: "inv-1", workspace_id: "ws-9", workspace_name: "Copilot Hub" }];
+ renderWithI18n(<RailWorkspaces />);
+ expect(triggerHasDot()).toBe(true);
+ const menu = await openMenu();
+ expect(within(menu).getByText("Pending invitations")).toBeInTheDocument();
+ expect(within(menu).getByRole("menuitem", { name: /Copilot Hub$/ })).toBeInTheDocument();
+ });
+
+ it("offers workspace creation unless the instance disables it", async () => {
+ const { unmount } = renderWithI18n(<RailWorkspaces />);
+ expect(within(await openMenu()).getByRole("menuitem", { name: "Create workspace" })).toBeInTheDocument();
+ unmount();
+
+ state.workspaceCreationDisabled = true;
+ renderWithI18n(<RailWorkspaces />);
+ expect(within(await openMenu()).queryByRole("menuitem", { name: "Create workspace" })).toBeNull();
+ });
+});
+
+describe("pending invitation self-heal", () => {
+ beforeEach(() => {
+ state.accept.mockReset().mockRejectedValue(new Error("invitation is not pending"));
+ state.decline.mockReset().mockRejectedValue(new Error("invitation is not pending"));
+ state.invalidateQueries.mockClear();
+ });
+
+ // "Invitation is not pending": it was concluded on another surface. Both
+ // mutations must refetch the list on failure so the stale tile drops.
+ it("invalidates the pending list when accept or decline fails", async () => {
+ renderWithI18n(<RailWorkspaces />);
+ expect(state.mutations).toHaveLength(2);
+
+ for (const options of state.mutations as Array<{
+ mutationFn: (id: string) => Promise<unknown>;
+ onError?: (...args: unknown[]) => unknown;
+ onSettled?: (...args: unknown[]) => unknown;
+ }>) {
+ const settle = options.onError ?? options.onSettled;
+ expect(settle).toBeTypeOf("function");
+ state.invalidateQueries.mockClear();
+ await expect(options.mutationFn("inv-1")).rejects.toThrow("invitation is not pending");
+ await settle!(new Error("invitation is not pending"), "inv-1", undefined, undefined);
+ expect(state.invalidateQueries).toHaveBeenCalledWith({ queryKey: ["invitations"] });
+ }
+ expect(state.accept).toHaveBeenCalledTimes(1);
+ expect(state.decline).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/layout/rail-workspaces.tsx b/packages/views/layout/rail-workspaces.tsx
new file mode 100644
index 0000000000..7d1e521428
--- /dev/null
+++ b/packages/views/layout/rail-workspaces.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import { useMemo } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Check, Plus } from "@multica/ui/icons";
+import { api } from "@multica/core/api";
+import { useConfigStore } from "@multica/core/config";
+import {
+ inboxUnreadSummaryEnabled,
+ inboxUnreadSummaryOptions,
+ unreadWorkspaceIds,
+} from "@multica/core/inbox/queries";
+import { paths, useCurrentWorkspace } from "@multica/core/paths";
+import type { Invitation, Workspace } from "@multica/core/types";
+import {
+ myInvitationListOptions,
+ workspaceKeys,
+ workspaceListOptions,
+} from "@multica/core/workspace/queries";
+import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+import { AppLink, useNavigation } from "../navigation";
+import { WorkspaceAvatar } from "../workspace/workspace-avatar";
+
+// Stable empty defaults: an inline `= []` is a new array every render.
+const EMPTY_WORKSPACES: Workspace[] = [];
+const EMPTY_INVITATIONS: Invitation[] = [];
+const EMPTY_INBOX_SUMMARY: Awaited<ReturnType<typeof api.getInboxUnreadSummary>> = [];
+
+function UnreadDot({ className }: { className?: string }) {
+ return <span aria-hidden className={cn("size-2 shrink-0 rounded-full bg-brand", className)} />;
+}
+
+function useInvitationActions(invitations: Invitation[]) {
+ const queryClient = useQueryClient();
+ const { push } = useNavigation();
+ const accept = useMutation({
+ mutationFn: (id: string) => api.acceptInvitation(id),
+ // Land inside the joined workspace; staying put and just adding a menu
+ // row reads as nothing happened (MUL-820).
+ onSuccess: async (_, invitationId) => {
+ const invitation = invitations.find((i) => i.id === invitationId);
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
+ // staleTime: 0 forces a real fetch — the joined workspace has to be in
+ // the list before its slug can be resolved.
+ const list = await queryClient.fetchQuery({ ...workspaceListOptions(), staleTime: 0 });
+ const joined = invitation ? list.find((w) => w.id === invitation.workspace_id) : null;
+ if (joined) push(paths.workspace(joined.slug).issues());
+ },
+ // "Invitation is not pending": it was concluded on another surface while
+ // this row was on screen. Refetch so the stale row drops.
+ onError: () => {
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
+ },
+ });
+ const decline = useMutation({
+ mutationFn: (id: string) => api.declineInvitation(id),
+ // Success drops the declined row; failure means it was concluded
+ // elsewhere. Either way the list is stale.
+ onSettled: () => {
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
+ },
+ });
+ return { accept, decline };
+}
+
+function InvitationItem({
+ invitation,
+ actions,
+}: {
+ invitation: Invitation;
+ actions: ReturnType<typeof useInvitationActions>;
+}) {
+ const { t } = useT("layout");
+ const name = invitation.workspace_name ?? t(($) => $.sidebar.invitation_workspace_fallback);
+ const pending = actions.accept.isPending || actions.decline.isPending;
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <WorkspaceAvatar name={name} size="sm" />
+ <span className="min-w-0 flex-1 truncate">{name}</span>
+ <UnreadDot />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="min-w-44">
+ {invitation.inviter_name && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-caption text-muted-foreground">
+ {t(($) => $.rail.invitation_from, { name: invitation.inviter_name })}
+ </DropdownMenuLabel>
+ </DropdownMenuGroup>
+ )}
+ <DropdownMenuItem disabled={pending} onClick={() => actions.accept.mutate(invitation.id)}>
+ {t(($) => $.sidebar.invitation_join)}
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled={pending} onClick={() => actions.decline.mutate(invitation.id)}>
+ {t(($) => $.sidebar.invitation_decline)}
+ </DropdownMenuItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
+/**
+ * The workspace switcher at the top of the rail: one tile for the current
+ * workspace, whatever the workspace count, so the spaces below never move.
+ * Its menu lists every workspace, pending invitations, and workspace
+ * creation. The tile carries a dot while another workspace has unread inbox
+ * items or an invitation waits; the current workspace's unread shows on the
+ * Inbox space instead.
+ */
+export function RailWorkspaces() {
+ const { t } = useT("layout");
+ const workspace = useCurrentWorkspace();
+ const wsId = workspace?.id;
+ const workspaceCreationDisabled = useConfigStore((s) => s.workspaceCreationDisabled);
+ const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());
+ const { data: invitations = EMPTY_INVITATIONS } = useQuery(myInvitationListOptions());
+ // One cross-workspace cache entry; gated on an active workspace since the
+ // endpoint resolves through the workspace-member middleware.
+ const { data: unreadSummary = EMPTY_INBOX_SUMMARY } = useQuery({
+ ...inboxUnreadSummaryOptions(),
+ enabled: inboxUnreadSummaryEnabled(wsId),
+ });
+ const unreadIds = useMemo(() => unreadWorkspaceIds(unreadSummary), [unreadSummary]);
+ const actions = useInvitationActions(invitations);
+
+ const current = workspaces.find((ws) => ws.id === wsId) ?? workspace;
+ if (!current) return null;
+ const otherUnread = workspaces.some((ws) => ws.id !== wsId && unreadIds.has(ws.id));
+ const label = t(($) => $.rail.switch_workspace);
+
+ return (
+ <DropdownMenu>
+ <TooltipHint label={current.name} side="right">
+ <DropdownMenuTrigger
+ aria-label={label}
+ className="relative inline-flex size-[34px] shrink-0 cursor-pointer items-center justify-center rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ <WorkspaceAvatar
+ name={current.name}
+ avatarUrl={current.avatar_url}
+ className="h-[34px] w-[34px] rounded-lg border-surface-border bg-surface-raised text-body text-foreground shadow-[var(--surface-shadow)]"
+ />
+ {(otherUnread || invitations.length > 0) && (
+ <UnreadDot className="absolute -top-0.5 -right-0.5 ring-2 ring-app-shell" />
+ )}
+ </DropdownMenuTrigger>
+ </TooltipHint>
+ <DropdownMenuContent side="right" align="start" sideOffset={10} className="w-64">
+ <DropdownMenuGroup className="max-h-80 overflow-y-auto">
+ <DropdownMenuLabel className="text-caption text-muted-foreground">
+ {t(($) => $.sidebar.workspaces_label)}
+ </DropdownMenuLabel>
+ {workspaces.map((ws) => {
+ const isCurrent = ws.id === wsId;
+ return (
+ <DropdownMenuItem
+ key={ws.id}
+ aria-current={isCurrent ? "page" : undefined}
+ render={<AppLink href={paths.workspace(ws.slug).issues()} />}
+ >
+ <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />
+ <span className="min-w-0 flex-1 truncate">{ws.name}</span>
+ {isCurrent ? <Check /> : unreadIds.has(ws.id) && <UnreadDot />}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuGroup>
+ {invitations.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="text-caption text-muted-foreground">
+ {t(($) => $.sidebar.pending_invitations_label)}
+ </DropdownMenuLabel>
+ {invitations.map((invitation) => (
+ <InvitationItem key={invitation.id} invitation={invitation} actions={actions} />
+ ))}
+ </DropdownMenuGroup>
+ </>
+ )}
+ {!workspaceCreationDisabled && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem render={<AppLink href={paths.newWorkspace()} />}>
+ <Plus />
+ {t(($) => $.sidebar.create_workspace)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/layout/route-data-prefetch.tsx b/packages/views/layout/route-data-prefetch.tsx
index c7e1dd4552..682addd40b 100644
--- a/packages/views/layout/route-data-prefetch.tsx
+++ b/packages/views/layout/route-data-prefetch.tsx
@@ -10,7 +10,8 @@ import {
import { autopilotListOptions } from "@multica/core/autopilots/queries";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { inboxListOptions } from "@multica/core/inbox/queries";
-import { useWorkspacePaths } from "@multica/core/paths";
+import { useAuthStore } from "@multica/core/auth";
+import { paths, useCurrentWorkspace, useWorkspaceSlug } from "@multica/core/paths";
import { pinListOptions } from "@multica/core/pins/queries";
import { projectListOptions } from "@multica/core/projects/queries";
import { runtimeProfileListOptions } from "@multica/core/runtimes";
@@ -97,15 +98,16 @@ export function RouteDataPrefetch({
children: ReactNode;
}) {
const qc = useQueryClient();
- const p = useWorkspacePaths();
+ // Null-safe: the desktop shell mounts before a workspace is open.
+ const slug = useWorkspaceSlug();
- const routeByHref = useMemo(
- () =>
- new Map<string, WarmRoute>(
- (Object.keys(ROUTES) as RouteKey[]).map((key) => [p[key](), ROUTES[key]]),
- ),
- [p],
- );
+ const routeByHref = useMemo(() => {
+ if (!slug) return new Map<string, WarmRoute>();
+ const p = paths.workspace(slug);
+ return new Map<string, WarmRoute>(
+ (Object.keys(ROUTES) as RouteKey[]).map((key) => [p[key](), ROUTES[key]]),
+ );
+ }, [slug]);
const prefetch = useCallback(
(href: string) => {
@@ -135,3 +137,14 @@ export function RouteDataPrefetch({
</RouteDataPrefetchProvider>
);
}
+
+/** `RouteDataPrefetch` for the app shell, scoped to the open workspace and user. */
+export function ShellRouteDataPrefetch({ children }: { children: ReactNode }) {
+ const wsId = useCurrentWorkspace()?.id;
+ const userId = useAuthStore((s) => s.user?.id ?? null);
+ return (
+ <RouteDataPrefetch wsId={wsId} userId={userId}>
+ {children}
+ </RouteDataPrefetch>
+ );
+}
diff --git a/packages/views/layout/route-icon-components.tsx b/packages/views/layout/route-icon-components.tsx
index 702e7592c5..84e4d497d7 100644
--- a/packages/views/layout/route-icon-components.tsx
+++ b/packages/views/layout/route-icon-components.tsx
@@ -4,6 +4,7 @@ import {
CircleUser,
ListTodo,
FolderKanban,
+ Layers,
Zap,
Bot,
Users,
@@ -37,6 +38,7 @@ export const ROUTE_ICON_COMPONENTS: Record<RouteIconName, IconComponent> = {
CircleUser,
ListTodo,
FolderKanban,
+ Layers,
Zap,
Bot,
Users,
diff --git a/packages/views/layout/sidebar-auto-collapse.test.tsx b/packages/views/layout/sidebar-auto-collapse.test.tsx
index fec1c353a1..9d995cd0d2 100644
--- a/packages/views/layout/sidebar-auto-collapse.test.tsx
+++ b/packages/views/layout/sidebar-auto-collapse.test.tsx
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
import { renderWithI18n } from "../test/i18n";
-// A width-driven `matchMedia`: the provider watches the `md`–`xl` band and
+// A width-driven `matchMedia`: the provider watches the `md`–`lg` band and
// `useIsCompact` watches `max-width: 767px`, so both have to answer against
// the same viewport and both have to be notified when it changes.
type Listener = (e: MediaQueryListEvent) => void;
@@ -49,7 +49,7 @@ function state() {
return screen.getByTestId("state").textContent;
}
-describe("sidebar auto-collapse between md and xl", () => {
+describe("sidebar auto-collapse between md and lg", () => {
beforeEach(() => {
queries.clear();
window.matchMedia = ((query: string) => {
@@ -87,7 +87,9 @@ describe("sidebar auto-collapse between md and xl", () => {
expect(state()).toBe("expanded");
});
- it("starts collapsed when the page opens inside the band", () => {
+ it("keeps the nav open in a laptop-sized window", () => {
+ // The rail stays on screen beside the panel, so a window just under the
+ // desktop default of 1280 has room for both.
setWidth(1100);
renderWithI18n(
<SidebarProvider>
@@ -95,6 +97,17 @@ describe("sidebar auto-collapse between md and xl", () => {
</SidebarProvider>,
);
+ expect(state()).toBe("expanded");
+ });
+
+ it("starts collapsed when the page opens inside the band", () => {
+ setWidth(900);
+ renderWithI18n(
+ <SidebarProvider>
+ <Probe />
+ </SidebarProvider>,
+ );
+
expect(state()).toBe("collapsed");
});
@@ -105,7 +118,7 @@ describe("sidebar auto-collapse between md and xl", () => {
</SidebarProvider>,
);
- setWidth(1100);
+ setWidth(900);
expect(state()).toBe("collapsed");
setWidth(1440);
@@ -122,11 +135,11 @@ describe("sidebar auto-collapse between md and xl", () => {
</SidebarProvider>,
);
- setWidth(1100);
+ setWidth(900);
fireEvent.click(screen.getByTestId("state"));
expect(state()).toBe("expanded");
- setWidth(1200);
+ setWidth(1000);
expect(state()).toBe("expanded");
});
@@ -179,7 +192,7 @@ describe("sidebar auto-collapse between md and xl", () => {
fireEvent.click(screen.getByTestId("state"));
expect(document.cookie).not.toContain("sidebar_state");
- setWidth(1100);
+ setWidth(900);
expect(state()).toBe("collapsed");
expect(document.cookie).not.toContain("sidebar_state");
});
diff --git a/packages/views/layout/sidebar-resize.test.tsx b/packages/views/layout/sidebar-resize.test.tsx
index 81977df2e2..fa2e64a934 100644
--- a/packages/views/layout/sidebar-resize.test.tsx
+++ b/packages/views/layout/sidebar-resize.test.tsx
@@ -85,7 +85,7 @@ describe("left sidebar resizing", () => {
expect(
liveWidthConsumer.style.getPropertyValue("--sidebar-live-width"),
).toBe("300px");
- expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("256px");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("240px");
expect(localStorage.getItem("sidebar_width")).toBeNull();
expect(stableConsumerRender).toHaveBeenCalledTimes(1);
@@ -157,7 +157,7 @@ describe("left sidebar resizing", () => {
expect(
liveWidthConsumer.style.getPropertyValue("--sidebar-live-width"),
).toBe("");
- expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("256px");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("240px");
expect(localStorage.getItem("sidebar_width")).toBeNull();
expect(wrapper).not.toHaveAttribute("data-sidebar-resizing");
expect(document.documentElement).not.toHaveAttribute("data-sidebar-resizing");
diff --git a/packages/views/layout/space-panel.test.tsx b/packages/views/layout/space-panel.test.tsx
new file mode 100644
index 0000000000..e47a13b6ab
--- /dev/null
+++ b/packages/views/layout/space-panel.test.tsx
@@ -0,0 +1,131 @@
+import { act, fireEvent, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
+import { renderWithI18n } from "../test/i18n";
+import { AppShellProvider, useAppShell } from "./app-shell-context";
+import { SpacePanel } from "./space-panel";
+
+const navigation = vi.hoisted(() => ({ pathname: "/acme/issues" }));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({ pathname: navigation.pathname }),
+}));
+vi.mock("./panels/work-panel", () => ({ WorkPanel: () => <div data-testid="work-panel" /> }));
+vi.mock("./panels/team-panel", () => ({ TeamPanel: () => <div data-testid="team-panel" /> }));
+vi.mock("./panels/autopilots-panel", () => ({
+ AutopilotsPanel: () => <div data-testid="autopilots-panel" />,
+}));
+vi.mock("./panels/list-space-peeks", () => ({
+ InboxPeek: () => <div data-testid="inbox-peek" />,
+ ChatPeek: () => <div data-testid="chat-peek" />,
+}));
+
+let shell: ReturnType<typeof useAppShell> = null;
+let sidebar: ReturnType<typeof useSidebar> | null = null;
+function Reader() {
+ shell = useAppShell();
+ sidebar = useSidebar();
+ return null;
+}
+
+function renderPanel() {
+ return renderWithI18n(
+ <SidebarProvider>
+ <AppShellProvider>
+ <Reader />
+ <SpacePanel />
+ </AppShellProvider>
+ </SidebarProvider>,
+ );
+}
+
+const panel = () => document.querySelector('[data-slot="space-panel"]');
+const peek = () => document.querySelector('[data-slot="space-panel-peek"]');
+
+beforeEach(() => {
+ navigation.pathname = "/acme/issues";
+ localStorage.clear();
+});
+
+describe("SpacePanel", () => {
+ it("renders the current space's panel", () => {
+ renderPanel();
+ expect(panel()).toHaveAttribute("data-state", "expanded");
+ expect(screen.getByTestId("work-panel")).toBeInTheDocument();
+ });
+
+ // Inbox, Chat and Settings render their own list column in the card.
+ it("renders nothing for spaces that bring their own column", () => {
+ navigation.pathname = "/acme/inbox";
+ renderPanel();
+ expect(panel()).toBeNull();
+ });
+
+ it("collapses from a click on its edge and keeps its content out of reach", () => {
+ renderPanel();
+ fireEvent.click(screen.getByRole("button", { name: "Toggle left sidebar" }));
+ expect(panel()).toHaveAttribute("data-state", "collapsed");
+ expect(panel()).toHaveAttribute("inert");
+ });
+
+ it("commits a dragged width without toggling", () => {
+ renderPanel();
+ const handle = screen.getByRole("button", { name: "Toggle left sidebar" });
+ vi.spyOn(panel()!, "getBoundingClientRect").mockReturnValue({ width: 240 } as DOMRect);
+
+ fireEvent.pointerDown(handle, { button: 0, isPrimary: true, pointerId: 1, clientX: 240 });
+ act(() => {
+ document.dispatchEvent(new PointerEvent("pointermove", { pointerId: 1, clientX: 300 }));
+ });
+ expect((panel() as HTMLElement).style.getPropertyValue("--sidebar-width")).toBe("300px");
+ act(() => {
+ document.dispatchEvent(new PointerEvent("pointerup", { pointerId: 1, clientX: 300 }));
+ });
+ fireEvent.click(handle);
+
+ expect(localStorage.getItem("sidebar_width")).toBe("300");
+ expect(panel()).toHaveAttribute("data-state", "expanded");
+ });
+
+ it("previews a hovered space over the page while collapsed", () => {
+ vi.useFakeTimers();
+ try {
+ renderPanel();
+ act(() => sidebar!.setOpen(false));
+ act(() => shell!.requestPeek("team"));
+ act(() => vi.advanceTimersByTime(200));
+ expect(peek()).not.toBeNull();
+ expect(screen.getByTestId("team-panel")).toBeInTheDocument();
+
+ act(() => sidebar!.setOpen(true));
+ expect(peek()).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("previews Inbox and Chat from another space, not over their own page", () => {
+ vi.useFakeTimers();
+ try {
+ renderPanel();
+ act(() => shell!.toggleNav());
+ act(() => shell!.requestPeek("inbox"));
+ act(() => vi.advanceTimersByTime(200));
+ expect(screen.getByTestId("inbox-peek")).toBeInTheDocument();
+ act(() => shell!.requestPeek("chat"));
+ expect(screen.getByTestId("chat-peek")).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ // There the page's own list column floats instead (ListColumn).
+ it("leaves the current list space's preview to its list column", () => {
+ navigation.pathname = "/acme/inbox";
+ renderPanel();
+ act(() => shell!.toggleNav());
+ act(() => shell!.requestPeek("inbox"));
+ act(() => shell!.requestPeek("inbox"));
+ expect(peek()).toBeNull();
+ });
+});
diff --git a/packages/views/layout/space-panel.tsx b/packages/views/layout/space-panel.tsx
new file mode 100644
index 0000000000..80ab93cef9
--- /dev/null
+++ b/packages/views/layout/space-panel.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { useRef } from "react";
+import type { AppSpaceId } from "@multica/core/paths";
+import { cn } from "@multica/ui/lib/utils";
+import { useSidebar } from "@multica/ui/components/ui/sidebar";
+import { useAppShell } from "./app-shell-context";
+import { PanelResizeHandle } from "./panel-resize-handle";
+import { AutopilotsPanel } from "./panels/autopilots-panel";
+import { ChatPeek, InboxPeek } from "./panels/list-space-peeks";
+import { NAV_COLUMN_MOTION_CLASS, NAV_PEEK_CLASS } from "./rail-styles";
+import { TeamPanel } from "./panels/team-panel";
+import { WorkPanel } from "./panels/work-panel";
+
+const PANELS: Partial<Record<AppSpaceId, () => React.ReactNode>> = {
+ work: WorkPanel,
+ team: TeamPanel,
+ autopilots: AutopilotsPanel,
+};
+
+// Inbox and Chat keep their lists in their pages, so from another space they
+// preview through a standalone copy of the list.
+const PEEKS: Partial<Record<AppSpaceId, () => React.ReactNode>> = {
+ ...PANELS,
+ inbox: InboxPeek,
+ chat: ChatPeek,
+};
+
+/** The current space's panel content, or null for spaces without one. */
+export function SpacePanelContent({ space }: { space: AppSpaceId | null }) {
+ const Panel = space ? PANELS[space] : undefined;
+ return Panel ? <Panel /> : null;
+}
+
+/**
+ * The space panel inside the content card: a column on the card's leading
+ * edge, separated from the page by one hairline. Spaces without a shell
+ * panel (Inbox, Chat, Settings) render their own `ListColumn` at the same
+ * width instead, so nothing mounts for them. While collapsed, hovering a rail space previews
+ * its panel over the page.
+ */
+export function SpacePanel() {
+ const shell = useAppShell();
+ const { open, isCompact } = useSidebar();
+ const panelRef = useRef<HTMLElement>(null);
+ if (!shell || isCompact) return null;
+
+ const { space, hasPanel, peekSpace, navCollapsed } = shell;
+ // The current space's own list column floats itself (`ListColumn`).
+ const Peek =
+ navCollapsed && peekSpace && (hasPanel || peekSpace !== space) ? PEEKS[peekSpace] : undefined;
+
+ return (
+ <>
+ {hasPanel && (
+ <aside
+ // A new space mounts at its final width; only toggling animates.
+ key={space}
+ ref={panelRef}
+ data-slot="space-panel"
+ data-state={open ? "expanded" : "collapsed"}
+ inert={!open}
+ className={cn(
+ "relative hidden shrink-0 justify-end overflow-hidden md:flex",
+ NAV_COLUMN_MOTION_CLASS,
+ open ? "w-(--sidebar-width)" : "w-0",
+ )}
+ >
+ <div className="flex h-full w-(--sidebar-width) shrink-0 flex-col overflow-hidden border-r">
+ <SpacePanelContent space={space} />
+ </div>
+ </aside>
+ )}
+ {hasPanel && open && (
+ <div className="relative hidden w-0 shrink-0 md:block">
+ <PanelResizeHandle panelRef={panelRef} onToggle={shell.toggleNav} />
+ </div>
+ )}
+ {Peek && (
+ <aside
+ data-slot="space-panel-peek"
+ onPointerEnter={shell.holdPeek}
+ onPointerLeave={shell.releasePeek}
+ className={cn(NAV_PEEK_CLASS, "max-md:hidden")}
+ >
+ <Peek />
+ </aside>
+ )}
+ </>
+ );
+}
diff --git a/packages/views/layout/use-discord-card-dismissed.ts b/packages/views/layout/use-discord-card-dismissed.ts
deleted file mode 100644
index 1991a5aa53..0000000000
--- a/packages/views/layout/use-discord-card-dismissed.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-"use client";
-
-import { useCallback, useSyncExternalStore } from "react";
-
-/**
- * Per-user "I dismissed the Join Discord sidebar card" flag.
- *
- * Lives in `localStorage` rather than the server because it is a purely
- * frontend UX preference (don't show this promo again) that never feeds
- * analytics or the backend. Keyed by user id so two people sharing a
- * browser profile don't inherit each other's dismissal.
- *
- * Tradeoff: clearing browser storage re-shows the card, and the flag does
- * not sync across devices. Both are acceptable for a low-stakes promo.
- */
-
-const STORAGE_PREFIX = "multica.discord_card.dismissed.";
-
-function storageKey(userId: string): string {
- return `${STORAGE_PREFIX}${userId}`;
-}
-
-function readDismissed(userId: string | null | undefined): boolean {
- if (!userId) return false;
- if (typeof window === "undefined") return false;
- try {
- return window.localStorage.getItem(storageKey(userId)) === "1";
- } catch {
- return false;
- }
-}
-
-// Shared listener registry so a same-tab write wakes every subscribed hook.
-const listeners = new Set<() => void>();
-function notify(): void {
- for (const fn of listeners) fn();
-}
-
-function subscribe(callback: () => void): () => void {
- listeners.add(callback);
- // Cross-tab updates arrive via the storage event.
- const handler =
- typeof window === "undefined"
- ? undefined
- : (e: StorageEvent) => {
- if (e.key && e.key.startsWith(STORAGE_PREFIX)) callback();
- };
- if (handler) window.addEventListener("storage", handler);
- return () => {
- listeners.delete(callback);
- if (handler) window.removeEventListener("storage", handler);
- };
-}
-
-/** Returns `[dismissed, dismiss]`. `dismiss` is a no-op without a user id. */
-export function useDiscordCardDismissed(
- userId: string | null | undefined,
-): readonly [boolean, () => void] {
- const dismissed = useSyncExternalStore(
- subscribe,
- () => readDismissed(userId),
- () => false,
- );
-
- const dismiss = useCallback(() => {
- if (!userId) return;
- if (typeof window === "undefined") return;
- try {
- window.localStorage.setItem(storageKey(userId), "1");
- notify();
- } catch {
- // localStorage can throw in private-mode Safari and similar — treat
- // as a no-op. Worst case the card re-shows on the next mount.
- }
- }, [userId]);
-
- return [dismissed, dismiss] as const;
-}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index a3c2da4d08..26b84fecab 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -1,19 +1,21 @@
{
"page": {
"title": "Agents",
- "learn_more": "Learn more →",
"new_agent": "New agent",
- "search_placeholder": "Search agents…",
"show_archived": "Show archived ({{count}}) →",
"of_total": "{{visible}} of {{total}}",
"list_load_failed": "Couldn't load agents",
"list_load_failed_default": "Something went wrong fetching the agent list.",
- "try_again": "Try again"
+ "try_again": "Try again",
+ "scope_title": {
+ "mine": "My agents",
+ "all": "All agents",
+ "archived": "Archived agents"
+ }
},
"scope": {
"mine": "Mine",
- "all": "All",
- "archived": "Archived"
+ "all": "All"
},
"sort": {
"label_recent": "Recent activity",
@@ -48,10 +50,7 @@
},
"no_matches": {
"title": "No matches",
- "search_archived": "No archived agents match \"{{query}}\".",
"no_archived": "No archived agents yet.",
- "search_active": "No agents match \"{{query}}\".",
- "search_active_filtered": "No agents match \"{{query}}\" in this filter.",
"no_filter_match": "No agents match this filter.",
"search_runtime_filtered": "No agents on \"{{machine}}\" match \"{{query}}\".",
"runtime_filtered": "No agents on \"{{machine}}\"."
@@ -136,7 +135,6 @@
"archive_dialog_confirm": "Archive"
},
"detail": {
- "back_to_agents": "Agents",
"back_to_agents_full": "Back to agents",
"not_found_title": "Agent not found",
"not_found_default": "This agent may have been archived or deleted.",
@@ -165,7 +163,11 @@
"runtime_required_toast": "Bind a runtime before running this agent.",
"assign_work": "Assign work",
"more_actions_aria": "Agent actions",
- "updated": "Updated {{when}}"
+ "advanced_settings": "Advanced settings",
+ "copy_link": "Copy link",
+ "copy_id": "Copy agent ID",
+ "link_copied_toast": "Link copied",
+ "id_copied_toast": "Agent ID copied"
},
"inspector": {
"section_profile": "Profile",
@@ -175,7 +177,6 @@
"section_properties": "Properties",
"section_details": "Details",
"section_details_hint": "Read-only ownership and lifecycle information.",
- "section_skills": "Skills",
"section_integrations": "Integrations",
"prop_runtime": "Runtime",
"prop_model": "Model",
@@ -186,7 +187,6 @@
"prop_owner": "Owner",
"prop_created": "Created",
"prop_updated": "Updated",
- "no_description_placeholder": "No description",
"avatar_label": "Avatar",
"name_label": "Name",
"description_label": "Description",
@@ -202,12 +202,27 @@
"cancel": "Cancel"
},
"overview": {
- "agent_context": "Agent",
- "access": "Access",
"attention_title": "Runs need attention",
"attention_queued_one": "{{count}} run is queued while the runtime is unavailable.",
"attention_queued_other": "{{count}} runs are queued while the runtime is unavailable."
},
+ "sections": {
+ "runs_count_one": "{{count}} run",
+ "runs_count_other": "{{count}} runs",
+ "recent_this_week_one": "{{count}} this week",
+ "recent_this_week_other": "{{count}} this week",
+ "view_all": "View all",
+ "open": "Open",
+ "edit": "Edit",
+ "add": "Add",
+ "manage": "Manage",
+ "instructions_empty": "No instructions yet."
+ },
+ "panel": {
+ "status": "Status",
+ "runs_7d": "Runs (7d)",
+ "edit_access_aria": "Access: {{value}}. Change access"
+ },
"skill_attach": {
"trigger_aria": "Attach a workspace skill",
"trigger_label": "Attach"
@@ -261,13 +276,11 @@
"clear_full": "Clear selection (use provider default)"
},
"tabs": {
- "overview": "Overview",
"work": "Work",
"capabilities": "Capabilities",
"settings": "Settings",
"general": "General",
"access": "Access",
- "page_navigation_aria": "Agent page",
"section_navigation_aria": "Agent section",
"activity": "Activity",
"tasks": "Runs",
@@ -289,7 +302,6 @@
"title": "Create an agent",
"squad_title": "Create an agent for this squad",
"duplicate_title": "Duplicate {{name}}",
- "back": "Go back",
"step_ai": "Build through conversation",
"modes": {
"template": {
@@ -373,7 +385,8 @@
"runtime": "Choose runtime",
"configure": "Configure",
"done": "Done",
- "aria": "Agent creation steps"
+ "aria": "Agent creation steps",
+ "progress": "Step {{current}} of {{total}}"
},
"configure_title": "Configure the agent",
"ask_ai": "Let AI write it",
@@ -793,13 +806,6 @@
"section_now": "Now",
"section_last_30d": "Last 30 days",
"section_recent": "Recent work",
- "subtitle_no_active": "No active work",
- "subtitle_active_one": "{{count}} active run",
- "subtitle_active_other": "{{count}} active runs",
- "subtitle_performance": "Performance",
- "subtitle_no_recent": "Nothing finished yet",
- "subtitle_recent_progress": "{{shown}} of {{total}} runs",
- "subtitle_recent_latest": "{{count}} latest runs",
"empty_now": "This agent isn't running anything right now.",
"empty_30d": "No completions in the last 30 days.",
"empty_recent": "This agent hasn't completed anything yet.",
@@ -811,9 +817,7 @@
"success_hint": "Completed runs divided by completed and failed runs. Cancelled runs are excluded.",
"success_unavailable": "No completed or failed runs in this period, so there is no success rate to show.",
"cancelled_count": "{{count}} cancelled",
- "avg_duration": "avg {{value}}",
"avg_duration_label": "average duration",
- "failed_count": "{{count}} failed",
"failed_label": "failed",
"source_issue": "Issue",
"source_chat": "Chat",
@@ -1042,25 +1046,11 @@
"none": "No activity (30d)"
},
"toolbar": {
- "result_count_title": "Matching agents / agents in scope",
- "filter_label": "Filter",
- "filter_active_count_one": "{{count}} filter",
- "filter_active_count_other": "{{count}} filters",
- "clear_filters": "Clear filters",
"section_availability": "Availability",
"section_access": "Access",
"section_runtime": "Runtime",
- "display": "Display",
- "sort_by": "Sort by",
- "direction_asc": "Ascending",
- "direction_desc": "Descending",
- "section_columns": "Columns",
"section_owner": "Owner",
"section_model": "Model"
},
- "actions": {
- "selected_one": "{{count}} selected",
- "selected_other": "{{count}} selected",
- "clear_selection": "Clear selection"
- }
+ "actions": {}
}
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index d3db6e12bc..4a43040e5d 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -1,6 +1,5 @@
{
"page": {
- "title": "Autopilot",
"new_autopilot": "New autopilot",
"start_blank": "Start from scratch",
"table": {
@@ -20,7 +19,6 @@
"title": "No autopilots yet",
"hint": "Schedule recurring work for your AI agents. Pick a template or start from scratch."
},
- "scope_all": "All",
"no_matches": "No automations match",
"retry": "Retry"
},
@@ -87,19 +85,27 @@
"run_blocked_quota_exceeded": "Not triggered — the run limit for this period has been reached",
"run_blocked_issue_limit_reached": "Not triggered — the workspace has reached its issue limit",
"run_blocked_generic": "Not triggered — the run was blocked",
- "section_properties": "Properties",
"section_triggers": "Triggers",
- "section_run_history": "Run History",
- "section_danger": "Danger Zone",
+ "section_run_history": "Run history",
"field_agent": "Agent",
"field_created_by": "Created by",
- "field_output_mode": "Output Mode",
+ "field_output_mode": "Output mode",
"field_project": "Project",
"no_project": "No project",
"project_unavailable": "Project unavailable",
"field_prompt": "Prompt",
"field_subscribers": "Subscribers",
"field_subscribers_none": "None",
+ "no_prompt": "No prompt yet.",
+ "copy_link": "Copy link",
+ "link_copied": "Link copied",
+ "link_copy_failed": "Couldn't copy the link",
+ "open_project": "Open project",
+ "summary": {
+ "create_issue": "{{agent}} creates an issue each run",
+ "run_only": "{{agent}} runs it without creating an issue",
+ "with_trigger": "{{trigger}} · {{action}}"
+ },
"add_trigger": "Add trigger",
"no_triggers": "No triggers configured. Add a schedule to run automatically.",
"no_runs": "No runs yet. Click \"Run now\" to trigger manually.",
@@ -196,7 +202,7 @@
}
},
"deliveries": {
- "section_title": "Webhook Deliveries",
+ "section_title": "Webhook deliveries",
"empty": "No webhook deliveries yet. Send a POST to the webhook URL to see entries here.",
"row": {
"attempts": "{{count}}× attempts",
@@ -441,29 +447,16 @@
"search_placeholder": "Search timezone..."
},
"toolbar": {
- "result_count_title": "Matching automations / all automations",
- "filter_label": "Filter",
- "filter_active_count_one": "{{count}} filter",
- "filter_active_count_other": "{{count}} filters",
- "clear_filters": "Clear filters",
"section_assignee": "Assignee",
"section_mode": "Mode",
"section_trigger": "Trigger",
- "section_creator": "Created by",
- "display": "Display",
- "sort_by": "Sort by",
- "direction_asc": "Ascending",
- "direction_desc": "Descending",
- "section_columns": "Columns"
+ "section_creator": "Created by"
},
"actions": {
"row_menu": "Automation actions",
"pause": "Pause",
"resume": "Resume",
"delete": "Delete",
- "selected_one": "{{count}} selected",
- "selected_other": "{{count}} selected",
- "clear_selection": "Clear selection",
"delete_dialog": {
"title": "Delete automation?",
"description_one": "This will permanently delete \"{{name}}\" and its run history.",
@@ -476,7 +469,6 @@
},
"wakeups": {
"title": "Issue wakeups",
- "scope": "Scope",
"issue": "Issue",
"trigger": "Trigger",
"enabled": "Enabled",
@@ -485,22 +477,16 @@
"at": "One-time",
"recurring": "Recurring",
"all_agents": "All agents",
- "search": "Search issues or agents",
"running": "Running",
"active_runs": "{{count}} active runs",
"issue_closed": "Issue closed",
"read_only": "Only the creator or a workspace admin can manage this wakeup",
"select_row": "Select {{issue}}, {{agent}}",
- "select_page": "Select enabled wakeups on this page",
+ "select_page": "Select all enabled wakeups",
"load_error": "Could not load wakeups",
"loading": "Loading wakeups…",
"empty": "No wakeup rules yet",
- "selected": "{{count}} selected",
"disable_selected": "Turn off selected",
- "clear": "Clear selection",
- "results": "Page {{page}} · {{count}} results",
- "previous": "Previous",
- "next_page": "Next",
"confirm_title": "Turn off {{count}} wakeups?",
"confirm_body": "Future wakeups will stop. Runs still queued and not handed to an agent will be withdrawn. Dispatched runs will continue; stop them from the execution log.",
"cancel": "Cancel",
@@ -509,7 +495,7 @@
"batch_result": "Turned off: {{succeeded}}. Failed: {{failed}}.",
"scopes": {
"active": "Waiting or executing",
- "all": "All",
+ "all": "All wakeups",
"disabled": "Turned off",
"ended": "Ended",
"paused": "Paused"
@@ -521,7 +507,7 @@
"batch_partial": "Turned off {{succeeded}}; {{failed}} failed. Failed items remain selected for retry.",
"source": "Source",
"sources": {
- "all": "Source: All",
+ "all": "All sources",
"member": "Members",
"agent": "Agents",
"system": "System"
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index a479d76bc5..fa2f99cd2e 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -247,7 +247,6 @@
"row_actions_aria": "Chat actions"
},
"header": {
- "view_profile": "View agent profile",
"rename": "Rename chat",
"archive": "Archive chat",
"unarchive": "Unarchive chat",
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index dce19d4578..d2c6621360 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -157,6 +157,7 @@
},
"filters": {
"tooltip": "Filter",
+ "active_section": "Active",
"placeholder": "Filter...",
"search_status": "Search status...",
"no_results": "No results",
@@ -173,6 +174,16 @@
"section_project": "Project",
"section_project_status": "Project status",
"section_label": "Label",
+ "section_relation": "Relation to me",
+ "relation_assigned": "Assigned to me",
+ "relation_created": "Created by me",
+ "relation_my_agents": "Assigned to my agents",
+ "operator_label": "Match",
+ "operator_is": "is",
+ "operator_is_not": "is not",
+ "modified_hint": "Changed from the saved view",
+ "unsaved_changes_one": "{{count}} unsaved change",
+ "unsaved_changes_other": "{{count}} unsaved changes",
"section_date": "Date",
"date_field": "Field",
"date_field_created": "Created",
@@ -198,7 +209,55 @@
"active_count_other": "{{count}} filters",
"in_view": "Already in this view",
"chip_edit": "Edit",
- "chip_save_as": "Save as"
+ "chip_save_as": "Save as",
+ "section_due_date": "Due date",
+ "due_overdue": "Overdue",
+ "due_today": "Due today",
+ "due_this_week": "Due this week",
+ "due_next_7_days": "Due in the next 7 days",
+ "due_none": "No due date",
+ "search_placeholder": "Filter by field or value…",
+ "search_fields": "Fields",
+ "search_values": "Values",
+ "advanced_switch": "Switch to advanced filter",
+ "advanced_title": "Advanced filter",
+ "advanced_match_leading": "Match",
+ "advanced_match_trailing": "of the conditions",
+ "match_all": "all",
+ "match_any": "any",
+ "advanced_where": "Where",
+ "advanced_and": "and",
+ "advanced_or": "or",
+ "advanced_add_condition": "Add condition",
+ "advanced_add_group": "Add condition group",
+ "advanced_unknown_property": "Deleted property",
+ "advanced_values_placeholder": "Select values…",
+ "advanced_field_label": "Field",
+ "advanced_values_label": "Values",
+ "advanced_actions": "Condition actions",
+ "advanced_duplicate": "Duplicate",
+ "advanced_delete": "Delete",
+ "advanced_delete_group": "Delete group",
+ "advanced_to_simple": "Switch to simple filter",
+ "advanced_to_simple_blocked": "Simple filters can't show groups, “any”, or a field used twice",
+ "advanced_clear": "Clear all",
+ "advanced_empty": "No conditions yet. Add one to start filtering.",
+ "advanced_conditions_one": "{{count}} condition",
+ "advanced_conditions_other": "{{count}} conditions",
+ "operator_has_any": "includes any of",
+ "operator_has_none": "includes none of",
+ "operator_contains": "contains",
+ "operator_not_contains": "doesn't contain",
+ "operator_before": "is before",
+ "operator_after": "is after",
+ "operator_empty": "is empty",
+ "operator_not_empty": "is not empty",
+ "advanced_group_match_leading": "Match",
+ "advanced_group_match_trailing": "of these",
+ "advanced_group_hint": "Conditions in this group are joined with “{{word}}”",
+ "advanced_add_to_group": "Add to group",
+ "advanced_turn_into_group": "Turn into group",
+ "advanced_summary": "Shows issues where {{summary}}"
},
"display": {
"tooltip": "Display settings",
@@ -208,6 +267,7 @@
"card_properties_section": "Card properties",
"columns_section": "Columns",
"columns_locked_by_filter": "Clear the status filter to show or hide columns.",
+ "columns_shown": "{{count}} shown",
"ascending_title": "Ascending",
"descending_title": "Descending",
"newest_first": "Newest first",
@@ -240,7 +300,8 @@
"card_project": "Project",
"card_labels": "Labels",
"card_child_progress": "Sub-issue progress",
- "show_sub_issues": "Show sub-issues"
+ "show_sub_issues": "Show sub-issues",
+ "layout_options": "{{layout}} options"
},
"view": {
"tooltip_board": "Board view",
@@ -388,7 +449,6 @@
"metadata_restore": "Restore dialog size",
"metadata_copy_failed": "Failed to copy metadata",
"metadata_description": "Key-value data recorded by agents and integrations for workflow coordination.",
-
"section_load_failed_retry": "Could not load. Retry",
"not_found": "This issue does not exist or has been deleted in this workspace.",
"breadcrumb_project_unknown": "Unknown project",
@@ -1000,38 +1060,6 @@
"row_todo_hint": "starts the agent"
},
"save_view": {
- "title": "Save as view",
- "hint_workspace": "Based on all workspace issues",
- "hint_my_any": "Based on My issues · All",
- "hint_my_assigned": "Based on My issues · Assigned",
- "hint_my_created": "Based on My issues · Created",
- "hint_my_involved": "Based on My issues · Involved",
- "hint_project": "Based on project “{{title}}”, available only on that project page",
- "hint_project_agents": "Based on project “{{title}}” issues assigned to agents, available only on that project page",
- "hint_project_members": "Based on project “{{title}}” issues assigned to members, available only on that project page",
- "my_private_note": "My issues views are visible only to you",
- "name_label": "Name",
- "visibility_label": "Visibility",
- "visibility_private": "Only visible to me",
- "visibility_workspace": "Visible to workspace members",
- "filters_label": "Filters",
- "custom_property": "Custom property",
- "create": "Create view",
- "layout_label": "Layout",
- "display_defaults": "Default display",
- "default_hint": "How members first see this view; everyone can adjust for themselves afterwards",
- "add_filter": "Add filter",
- "name_placeholder": "e.g. Needs review",
- "cancel": "Cancel",
- "name_required": "Enter a view name",
- "toast_created": "View created",
- "toast_failed": "Failed to create view",
- "edit_title": "Edit view",
- "update": "Save changes",
- "toast_updated": "View updated",
- "toast_conflict": "Someone else edited this view — reopen it and try again",
- "hint_workspace_members": "Based on workspace issues assigned to members",
- "hint_workspace_agents": "Based on workspace issues assigned to agents",
"scope_label_workspace": "Assignee type",
"scope_label_my": "Relation to me",
"variant_all": "Any assignee",
@@ -1042,36 +1070,6 @@
"variant_my_created": "Created by me",
"variant_my_involved": "Involved"
},
- "view_selector": {
- "trigger": "Views",
- "empty": "No saved views yet",
- "private_group": "Private",
- "shared_group": "Shared with workspace",
- "exit": "Exit view",
- "unavailable": "This view is no longer available",
- "edit": "Edit view"
- },
- "view_bar": {
- "menu_label": "Views",
- "menu_new": "New view",
- "builtin_tag": "Built-in",
- "drag_handle": "Drag to reorder",
- "delete": "Delete",
- "delete_title": "Delete view?",
- "delete_description": "“{{name}}” will be deleted for everyone who can see it",
- "toast_deleted": "View deleted",
- "context_edit": "Edit view",
- "context_pin": "Pin to sidebar",
- "context_unpin": "Unpin from sidebar",
- "row_menu": "More actions",
- "row_hide": "Hide from bar",
- "row_show": "Show on bar",
- "menu_manage": "Manage views",
- "manage_title": "Manage views",
- "manage_hint": "Order and visibility only affect you",
- "visible_toggle": "Show in view bar",
- "more_label": "More views"
- },
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} could not load its interface.",
@@ -1775,5 +1773,68 @@
},
"hover_card": {
"created_updated": "created {{created}} · updated {{updated}}"
+ },
+ "views": {
+ "builtin": {
+ "my_issues": "My Issues",
+ "my_agents": "My agents' work",
+ "all_issues": "All issues"
+ },
+ "untitled": "Untitled view",
+ "copy_name": "{{name}} (copy)",
+ "rename": "Rename",
+ "duplicate": "Duplicate",
+ "copy_link": "Copy link",
+ "link_copied": "Link copied",
+ "visible_to": "Visible to",
+ "only_me": "Only me",
+ "workspace_members": "Workspace members",
+ "add_to_sidebar": "Add to sidebar",
+ "remove_from_sidebar": "Remove from sidebar",
+ "back_to": "Back to {{name}}",
+ "delete": "Delete view",
+ "delete_title": "Delete view?",
+ "delete_description": "“{{name}}” will be deleted. This can't be undone.",
+ "delete_description_shared": "“{{name}}” is shared with the workspace and will be deleted for everyone.",
+ "cancel": "Cancel",
+ "toast_deleted": "View deleted",
+ "toast_delete_failed": "Couldn't delete view",
+ "filter": "Filter",
+ "filter_count_one": "{{count}} filter",
+ "filter_count_other": "{{count}} filters",
+ "reset": "Reset",
+ "save": "Save",
+ "save_options": "More save options",
+ "save_to": "Save to “{{name}}”",
+ "save_to_hint_shared": "Updates the view for everyone in the workspace",
+ "save_to_hint_private": "Updates your view",
+ "save_as_new": "Save as new view",
+ "save_as_new_hint": "Keeps “{{name}}” unchanged",
+ "save_as_view": "Save as view",
+ "set_by_view": "Set by this view",
+ "new_issue": "New issue",
+ "unavailable": "This view is no longer available",
+ "toast_saved": "View saved",
+ "toast_conflict": "Someone else changed this view — reload and try again",
+ "toast_create_failed": "Couldn't create view",
+ "toast_save_failed": "Couldn't save view",
+ "directory": {
+ "new_view": "New view",
+ "scope_all": "All views",
+ "scope_builtin": "Built-in",
+ "scope_mine": "Created by me",
+ "scope_shared": "Shared",
+ "col_name": "Name",
+ "col_location": "Location",
+ "col_filters": "Filters",
+ "col_visibility": "Visible to",
+ "col_owner": "Owner",
+ "owner_builtin": "Built-in",
+ "location_project": "Project",
+ "star": "Add {{name}} to sidebar",
+ "unstar": "Remove {{name}} from sidebar",
+ "row_actions": "Actions for {{name}}",
+ "no_matches": "No views match"
+ }
}
}
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index 76abed8af4..3a69bf01a7 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -11,7 +11,8 @@
"usage": "Analytics",
"runtimes": "Runtimes",
"skills": "Skills",
- "settings": "Settings"
+ "settings": "Settings",
+ "views": "Views"
},
"tab": {
"issue": "Issue",
@@ -25,6 +26,7 @@
"runtime": "Runtime",
"attachment": "Attachment",
"create_agent": "Create Agent",
+ "my_agents": "My agents' work",
"unknown": "Unknown page"
},
"help": {
@@ -57,16 +59,121 @@
"invitation_decline": "Decline",
"log_out": "Log out",
"new_issue": "New Issue",
- "new_issue_shortcut": "C",
"pinned_label": "Pinned",
- "work_group": "Work",
- "ai_team_group": "AI Team",
"show_more_pins": "Show {{count}} more…",
- "show_fewer_pins": "Show fewer",
- "unread_overflow": "99+",
- "discord_card": {
- "title": "Join our Discord",
- "dismiss": "Dismiss"
+ "show_fewer_pins": "Show fewer"
+ },
+ "spaces": {
+ "work": "Issues",
+ "team": "Team"
+ },
+ "rail": {
+ "label": "App navigation",
+ "sheet_description": "Switch spaces and workspaces.",
+ "inbox": "Inbox",
+ "work": "Issues",
+ "team": "Team",
+ "chat": "Chat",
+ "autopilots": "Auto",
+ "switch_workspace": "Switch workspace",
+ "invitation_from": "{{name}} invited you"
+ },
+ "panels": {
+ "work": {
+ "my_agents": "My agents' work",
+ "all_issues": "All issues",
+ "views": "Views",
+ "new_project": "New project",
+ "new_issue_in_project": "New issue in {{name}}",
+ "all_projects_one": "All {{count}} project",
+ "all_projects_other": "All {{count}} projects",
+ "project_issues": "Issues in {{name}}",
+ "project_issues_empty": "No issues",
+ "project_issues_error": "Couldn't load issues",
+ "project_issues_settings": "Issues in projects",
+ "settings_status": "Status",
+ "settings_assignee": "Assignee",
+ "assignee_anyone": "Anyone",
+ "assignee_me": "Me",
+ "assignee_my_agents": "My agents",
+ "reset": "Reset",
+ "load_more": "Load more",
+ "show_less": "Show less",
+ "projects_settings": "Project display",
+ "projects_ordering": "Ordering",
+ "projects_order_manual": "Manual",
+ "projects_order_name": "Name",
+ "projects_order_updated": "Recently updated",
+ "projects_order_created": "Recently created",
+ "projects_show": "Show",
+ "projects_only_mine": "Only projects I lead",
+ "projects_show_count": "Open issue count",
+ "new_view": "New view",
+ "all_views": "All views",
+ "view_actions": "Actions for {{name}}",
+ "view_copy_link": "Copy link",
+ "view_remove": "Remove from sidebar",
+ "view_rename": "Rename",
+ "view_duplicate": "Duplicate",
+ "view_delete": "Delete view"
+ },
+ "team": {
+ "new_agent": "New agent",
+ "needs_attention": "Needs attention",
+ "stuck_one": "{{count}} task waiting on an offline runtime",
+ "stuck_other": "{{count}} tasks waiting on an offline runtime",
+ "working_now": "Working now",
+ "running_tasks_one": "{{count}} task running",
+ "running_tasks_other": "{{count}} tasks running",
+ "all_agents": "All agents",
+ "my_agents": "My agents",
+ "squads_and_members": "Squads & members",
+ "members_one": "{{count}} member",
+ "members_other": "{{count}} members",
+ "resources": "Resources",
+ "runtimes_offline_one": "{{count}} offline",
+ "runtimes_offline_other": "{{count}} offline",
+ "invite_member": "Invite member"
+ },
+ "autopilots": {
+ "all": "All autopilots",
+ "list": "Autopilots",
+ "templates": "From a template"
}
+ },
+ "account": {
+ "trigger": "Account",
+ "profile": "Profile",
+ "theme": "Theme",
+ "themes": {
+ "light": "Light",
+ "dark": "Dark",
+ "system": "System"
+ },
+ "language": "Language",
+ "shortcuts": "Keyboard shortcuts"
+ },
+ "collection": {
+ "filter": "Filter",
+ "filter_count_one": "{{count}} filter",
+ "filter_count_other": "{{count}} filters",
+ "reset": "Reset",
+ "display": "Display settings",
+ "selected_one": "{{count}} selected",
+ "selected_other": "{{count}} selected",
+ "clear_selection": "Clear selection",
+ "select_all": "Select all",
+ "select_row": "Select row",
+ "row_actions": "Row actions",
+ "sort_by": "Sort by",
+ "direction_asc": "Ascending",
+ "direction_desc": "Descending",
+ "section_columns": "Columns",
+ "load_more": "Load more",
+ "loading_more": "Loading…"
+ },
+ "object_page": {
+ "toggle_panel": "Toggle right sidebar",
+ "properties": "Properties"
}
}
diff --git a/packages/views/locales/en/members.json b/packages/views/locales/en/members.json
index 945814a7e4..afc9406934 100644
--- a/packages/views/locales/en/members.json
+++ b/packages/views/locales/en/members.json
@@ -12,8 +12,11 @@
"more_agents_other": "and {{count}} other agents"
},
"detail": {
- "workspace_fallback": "Workspace",
"members_breadcrumb": "Members",
+ "role": "Role",
+ "email": "Email",
+ "joined": "Joined",
+ "relation": "Relation",
"breadcrumb_fallback": "Member",
"not_found_title": "Member not found",
"not_found_description": "This member may have left the workspace."
diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.json
index ecb8aa14dd..033f6be3cd 100644
--- a/packages/views/locales/en/projects.json
+++ b/packages/views/locales/en/projects.json
@@ -2,11 +2,13 @@
"page": {
"title": "Projects",
"new_project": "New project",
+ "scope_all": "All projects",
+ "scope_active": "Active projects",
+ "scope_closed": "Closed projects",
"empty": "No projects yet",
"create_first": "Create your first project",
"view_compact": "Compact",
"view_comfortable": "Comfortable",
- "search_placeholder": "Search projects...",
"no_search_results": "No results match your search",
"view_table": "Table",
"view_cards": "Cards",
@@ -14,10 +16,7 @@
"pin": "Pin to sidebar",
"unpin": "Unpin",
"delete": "Delete",
- "no_matches": "No projects match",
- "selected_one": "{{count}} selected",
- "selected_other": "{{count}} selected",
- "clear_selection": "Clear selection"
+ "no_matches": "No projects match"
},
"table": {
"name": "Name",
@@ -168,19 +167,9 @@
"fallback_label": "Project"
},
"toolbar": {
- "result_count_title": "Matching projects / all projects",
- "filter_label": "Filter",
- "filter_active_count_one": "{{count}} filter",
- "filter_active_count_other": "{{count}} filters",
- "clear_filters": "Clear filters",
"section_status": "Status",
"section_priority": "Priority",
"section_lead": "Lead",
- "display": "Display",
- "sort_by": "Sort by",
- "direction_asc": "Ascending",
- "direction_desc": "Descending",
- "section_columns": "Columns",
"view": "View"
}
}
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 43183ac132..f449bb7076 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -1,9 +1,7 @@
{
"page": {
"title": "Runtimes",
- "learn_more": "Learn more →",
"connect_remote": "Add a machine",
- "search_placeholder": "Search…",
"scope_mine": "Mine",
"scope_all": "All",
"live": "Live",
@@ -25,7 +23,7 @@
"title": "Starting local runtime…",
"hint": "Connecting to the workspace..."
},
- "add": "Add",
+ "add": "Add runtime",
"add_menu": {
"machines": "Machines",
"this_computer": "This computer",
@@ -67,7 +65,7 @@
"no_matches": "No machines or cloud services match"
},
"filters": {
- "all": "All",
+ "all": "All runtimes",
"online": "Online",
"offline": "Offline"
}
@@ -93,8 +91,7 @@
"this_machine": "This device",
"local_badge": "Local · this machine",
"pending_custom_runtimes": "Pending custom runtimes",
- "runtime_count_one": "{{count}} runtime",
- "runtime_count_other": "{{count}} runtimes",
+ "daemon_title": "Daemon",
"busy_count_one": "{{count}} busy",
"busy_count_other": "{{count}} busy",
"no_matches_title": "No machines",
@@ -162,14 +159,10 @@
"fact_owner": "Owner",
"fact_device": "Device",
"fact_runtime": "Runtime",
- "technical_details": "Technical details",
"fact_daemon_cli": "Daemon CLI",
"fact_daemon_id": "Daemon ID",
- "serving_title": "Serving",
- "serving_count_one": "{{count}} agent",
- "serving_count_other": "{{count}} agents",
+ "usage_title": "Usage",
"no_agents": "No agents are bound to this runtime yet.",
- "diagnostics_title": "Diagnostics",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "Visibility",
"visibility_label": {
diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.json
index ebf2187f63..2576ec2721 100644
--- a/packages/views/locales/en/skills.json
+++ b/packages/views/locales/en/skills.json
@@ -1,12 +1,10 @@
{
"page": {
"title": "Skills",
- "learn_more": "Learn more →",
"new_skill": "New skill",
- "search_placeholder": "Search skills…",
"scopes": {
"all": {
- "label": "All",
+ "label": "All skills",
"description": "All skills in this workspace"
},
"used": {
@@ -18,7 +16,7 @@
"description": "Skills not assigned to any agent"
},
"mine": {
- "label": "Created by me",
+ "label": "My skills",
"description": "Skills you created"
}
},
@@ -76,8 +74,6 @@
"added_toast": "Added to {{name}}",
"add_failed_toast": "Failed to add skill",
"delete": "Delete",
- "selected": "{{count}} selected",
- "clear_selection": "Clear selection",
"delete_no_permission": "Selection includes skills only their creator or an admin can delete",
"delete_dialog_title_one": "Delete {{count}} skill?",
"delete_dialog_title_other": "Delete {{count}} skills?",
@@ -105,29 +101,16 @@
"added_multi_toast_other": "Added to {{count}} agents"
},
"toolbar": {
- "result_count_title": "Matching skills / all skills",
- "filter_label": "Filter",
- "filter_active_count_one": "{{count}} filter",
- "filter_active_count_other": "{{count}} filters",
- "clear_filters": "Clear filters",
"section_usage": "Usage",
"section_labels": "Labels",
"filter_search_placeholder": "Filter...",
"no_labels": "No labels yet",
"no_results": "No results",
- "display": "Display",
- "sort_by": "Sort by",
- "direction_asc": "Ascending",
- "direction_desc": "Descending",
- "section_columns": "Columns",
"manage_labels": "Manage labels...",
"manage_labels_title": "Skill labels"
},
"detail": {
- "all_skills": "All skills",
"read_only": "Read-only",
- "delete_aria": "Delete skill",
- "delete_tooltip": "Delete skill",
"supporting_data_warning": "Some workspace data failed to load. Creator attribution, runtime names, or edit permissions may appear incomplete until the next refresh.",
"delete_file": "Delete file",
"name_placeholder": "skill-name",
@@ -163,8 +146,6 @@
"toast_deleted": "Skill deleted",
"toast_delete_failed": "Failed to delete skill",
"refresh": {
- "button": "Update",
- "tooltip": "Re-download this skill from its source",
"source_github": "GitHub",
"source_skills_sh": "Skills.sh",
"source_clawhub": "ClawHub",
@@ -205,32 +186,18 @@
},
"header": {
"files_one": "{{count}} file",
- "files_other": "{{count}} files",
- "used_by_one": "{{count}} agent",
- "used_by_other": "{{count}} agents",
- "updated": "Updated {{when}}",
- "updated_by": "Updated {{when}} by {{name}}"
- },
- "tabs": {
- "aria": "Skill sections",
- "overview": "Overview",
- "files_one": "Files {{count}}",
- "files_other": "Files {{count}}"
+ "files_other": "{{count}} files"
},
"overview": {
"properties": "Properties",
- "properties_hint": "These fields stay in sync with the SKILL.md frontmatter.",
"name": "Name",
"description": "Description",
"description_hint": "Agents use this to decide when to load the skill.",
"labels": "Labels",
- "used_by_one": "Used by {{count}} agent",
- "used_by_other": "Used by {{count}} agents",
"used_by_empty": "Not assigned to any agent yet. Open an agent's Skills tab to assign.",
"permissions_owner": "You can edit and delete this skill. Changes take effect on the next agent run.",
"permissions_locked_creator": "Only the creator ({{name}}) or a workspace admin can edit this skill.",
"permissions_locked": "Only the creator or a workspace admin can edit this skill.",
- "properties_help": "About skill properties",
"character_count": "{{count}} characters"
},
"files": {
@@ -244,6 +211,21 @@
"mode_preview": "Preview",
"mode_edit": "Edit",
"mode_raw": "Plain text"
+ },
+ "sections": {
+ "content": "Content",
+ "files": "Files",
+ "edit": "Edit",
+ "open": "Open",
+ "add": "Add"
+ },
+ "menu": {
+ "copy_link": "Copy link",
+ "link_copied": "Link copied",
+ "delete": "Delete skill"
+ },
+ "panel": {
+ "add_description": "Add description"
}
},
"create": {
diff --git a/packages/views/locales/en/squads.json b/packages/views/locales/en/squads.json
index a0438a8b9a..d4766b338b 100644
--- a/packages/views/locales/en/squads.json
+++ b/packages/views/locales/en/squads.json
@@ -1,7 +1,7 @@
{
"page": {
"title": "Squads",
- "new_button": "New Squad",
+ "new_button": "New squad",
"empty_no_squads": "No squads yet.",
"empty_no_match": "No squads match your filters.",
"table": {
@@ -15,10 +15,6 @@
"row_menu": "Squad actions",
"archive_action": "Archive"
},
- "inspector": {
- "details_section": "Details",
- "archive_button": "Archive"
- },
"member_type": {
"agent": "Agent",
"member": "Member"
@@ -65,17 +61,9 @@
"responsibility_placeholder": "What is this squad responsible for?",
"save": "Save"
},
- "discard_changes_dialog": {
- "title": "Discard unsaved changes?",
- "description": "You have unsaved changes on this tab. Switching tabs will discard them.",
- "keep_editing": "Keep editing",
- "discard_button": "Discard"
- },
"members_tab": {
"section_title": "Members",
- "section_count_one": "{{count}} member in this squad",
- "section_count_other": "{{count}} members in this squad",
- "add_member_button": "Add Member",
+ "add_member_button": "Add member",
"create_agent_button": "Create Agent",
"leader_chip": "Leader",
"view_agent_tooltip": "Open agent detail",
@@ -87,19 +75,29 @@
"status_unstable": "Unstable",
"status_archived": "Archived",
"issue_status_blocked": "blocked",
- "active_issue_more": "and {{count}} more",
- "last_active_label": "last active {{time}}"
- },
- "detail_tabs": {
- "members": "Members",
- "instructions": "Instructions"
+ "active_issue_more": "and {{count}} more"
+ },
+ "detail": {
+ "assign_work": "Assign work",
+ "copy_link": "Copy link",
+ "link_copied": "Link copied",
+ "not_found": "Squad not found",
+ "instructions": "Instructions",
+ "edit": "Edit",
+ "cancel": "Cancel",
+ "recent_work": "Recent work",
+ "recent_work_empty": "No issues have been assigned to this squad yet.",
+ "member_menu": "Actions for {{name}}",
+ "working_on": "Working on"
},
"details": {
"leader": "Leader",
"members": "Members",
"created_by": "Created by",
"created": "Created",
- "updated": "Updated"
+ "updated": "Updated",
+ "visibility": "Visibility",
+ "visibility_workspace": "Workspace"
},
"toasts": {
"member_added": "Member added",
@@ -130,19 +128,8 @@
"placeholder": "e.g. Always start by writing a failing test. Prefer small, atomic commits."
},
"scope": {
- "mine": "Mine",
- "all": "All"
+ "mine": "My squads",
+ "all": "All squads"
},
- "toolbar": {
- "display": "Display",
- "sort_by": "Sort by",
- "direction_asc": "Ascending",
- "direction_desc": "Descending",
- "section_columns": "Columns",
- "result_count_title": "Matching squads / all squads",
- "filter_label": "Filter",
- "filter_active_count_one": "{{count}} filter",
- "filter_active_count_other": "{{count}} filters",
- "clear_filters": "Clear filters"
- }
+ "toolbar": {}
}
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index fcf3aae567..fc56abe4a3 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -1,19 +1,21 @@
{
"page": {
"title": "Agents",
- "learn_more": "En savoir plus →",
"new_agent": "Nouvel agent",
- "search_placeholder": "Rechercher des agents…",
"show_archived": "Afficher les archivés ({{count}}) →",
"of_total": "{{visible}} sur {{total}}",
"list_load_failed": "Impossible de charger les agents",
"list_load_failed_default": "Une erreur est survenue lors de la récupération de la liste des agents.",
- "try_again": "Réessayer"
+ "try_again": "Réessayer",
+ "scope_title": {
+ "mine": "Mes agents",
+ "all": "Tous les agents",
+ "archived": "Agents archivés"
+ }
},
"scope": {
"mine": "Les miens",
- "all": "Tous",
- "archived": "Archivés"
+ "all": "Tous"
},
"sort": {
"label_recent": "Activité récente",
@@ -48,10 +50,7 @@
},
"no_matches": {
"title": "Aucune correspondance",
- "search_archived": "Aucun agent archivé ne correspond à « {{query}} ».",
"no_archived": "Aucun agent archivé pour l'instant.",
- "search_active": "Aucun agent ne correspond à « {{query}} ».",
- "search_active_filtered": "Aucun agent ne correspond à « {{query}} » dans ce filtre.",
"no_filter_match": "Aucun agent ne correspond à ce filtre.",
"search_runtime_filtered": "Aucun agent sur « {{machine}} » ne correspond à « {{query}} ».",
"runtime_filtered": "Aucun agent sur « {{machine}} »."
@@ -136,7 +135,6 @@
"archive_dialog_confirm": "Archiver"
},
"detail": {
- "back_to_agents": "Agents",
"back_to_agents_full": "Retour aux agents",
"not_found_title": "Agent introuvable",
"not_found_default": "Cet agent a peut-être été archivé ou supprimé.",
@@ -165,7 +163,11 @@
"runtime_required_toast": "Associez un runtime avant d'exécuter cet agent.",
"assign_work": "Assigner du travail",
"more_actions_aria": "Actions de l'agent",
- "updated": "Mis à jour {{when}}"
+ "advanced_settings": "Paramètres avancés",
+ "copy_link": "Copier le lien",
+ "copy_id": "Copier l'ID de l'agent",
+ "link_copied_toast": "Lien copié",
+ "id_copied_toast": "ID de l'agent copié"
},
"inspector": {
"section_profile": "Profil",
@@ -175,7 +177,6 @@
"section_properties": "Propriétés",
"section_details": "Détails",
"section_details_hint": "Informations de propriété et de cycle de vie, en lecture seule.",
- "section_skills": "Skills",
"section_integrations": "Intégrations",
"prop_runtime": "Runtime",
"prop_model": "Modèle",
@@ -186,7 +187,6 @@
"prop_owner": "Propriétaire",
"prop_created": "Création",
"prop_updated": "Mise à jour",
- "no_description_placeholder": "Aucune description",
"avatar_label": "Avatar",
"name_label": "Nom",
"description_label": "Description",
@@ -202,12 +202,27 @@
"cancel": "Annuler"
},
"overview": {
- "agent_context": "Agent",
- "access": "Accès",
"attention_title": "Des exécutions demandent votre attention",
"attention_queued_one": "{{count}} exécution est en attente car le runtime est indisponible.",
"attention_queued_other": "{{count}} exécutions sont en attente car le runtime est indisponible."
},
+ "sections": {
+ "runs_count_one": "{{count}} exécution",
+ "runs_count_other": "{{count}} exécutions",
+ "recent_this_week_one": "{{count}} cette semaine",
+ "recent_this_week_other": "{{count}} cette semaine",
+ "view_all": "Tout afficher",
+ "open": "Ouvrir",
+ "edit": "Modifier",
+ "add": "Ajouter",
+ "manage": "Gérer",
+ "instructions_empty": "Aucune instruction pour l'instant."
+ },
+ "panel": {
+ "status": "Statut",
+ "runs_7d": "Exécutions (7 j)",
+ "edit_access_aria": "Accès : {{value}}. Modifier l'accès"
+ },
"skill_attach": {
"trigger_aria": "Rattacher un skill de l'espace de travail",
"trigger_label": "Rattacher"
@@ -261,13 +276,11 @@
"clear_full": "Effacer la sélection (utiliser la valeur par défaut du fournisseur)"
},
"tabs": {
- "overview": "Vue d'ensemble",
"work": "Travail",
"capabilities": "Capacités",
"settings": "Paramètres",
"general": "Général",
"access": "Accès",
- "page_navigation_aria": "Page de l'agent",
"section_navigation_aria": "Section de l'agent",
"activity": "Activité",
"tasks": "Exécutions",
@@ -289,7 +302,6 @@
"title": "Créer un agent",
"squad_title": "Créer un agent pour ce squad",
"duplicate_title": "Dupliquer {{name}}",
- "back": "Revenir en arrière",
"step_ai": "Construire par la conversation",
"modes": {
"template": {
@@ -373,7 +385,8 @@
"runtime": "Choisir le runtime",
"configure": "Configurer",
"done": "Terminé",
- "aria": "Étapes de création de l'agent"
+ "aria": "Étapes de création de l'agent",
+ "progress": "Étape {{current}} sur {{total}}"
},
"configure_title": "Configurer l'agent",
"ask_ai": "Laisser l'IA rédiger",
@@ -793,13 +806,6 @@
"section_now": "Maintenant",
"section_last_30d": "30 derniers jours",
"section_recent": "Travaux récents",
- "subtitle_no_active": "Aucun travail en cours",
- "subtitle_active_one": "{{count}} exécution active",
- "subtitle_active_other": "{{count}} exécutions actives",
- "subtitle_performance": "Performance",
- "subtitle_no_recent": "Rien de terminé pour l'instant",
- "subtitle_recent_progress": "{{shown}} exécutions sur {{total}}",
- "subtitle_recent_latest": "{{count}} exécutions les plus récentes",
"empty_now": "Cet agent n'exécute rien pour l'instant.",
"empty_30d": "Aucune tâche terminée ces 30 derniers jours.",
"empty_recent": "Cet agent n'a encore rien terminé.",
@@ -811,9 +817,7 @@
"success_hint": "Exécutions terminées divisées par la somme des exécutions terminées et en échec. Les exécutions annulées sont exclues.",
"success_unavailable": "Aucune exécution terminée ou en échec sur cette période : aucun taux de réussite à afficher.",
"cancelled_count": "{{count}} annulées",
- "avg_duration": "moy. {{value}}",
"avg_duration_label": "durée moyenne",
- "failed_count": "{{count}} en échec",
"failed_label": "en échec",
"source_issue": "Tâche",
"source_chat": "Discussion",
@@ -1042,25 +1046,11 @@
"none": "Aucune activité (30 j)"
},
"toolbar": {
- "result_count_title": "Agents correspondants / agents dans la portée",
- "filter_label": "Filtrer",
- "filter_active_count_one": "{{count}} filtre",
- "filter_active_count_other": "{{count}} filtres",
- "clear_filters": "Effacer les filtres",
"section_availability": "Disponibilité",
"section_access": "Accès",
"section_runtime": "Runtime",
- "display": "Affichage",
- "sort_by": "Trier par",
- "direction_asc": "Croissant",
- "direction_desc": "Décroissant",
- "section_columns": "Colonnes",
"section_owner": "Propriétaire",
"section_model": "Modèle"
},
- "actions": {
- "selected_one": "{{count}} sélectionné",
- "selected_other": "{{count}} sélectionnés",
- "clear_selection": "Effacer la sélection"
- }
+ "actions": {}
}
diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.json
index 75d1b3dc1f..7541d9f56c 100644
--- a/packages/views/locales/fr/autopilots.json
+++ b/packages/views/locales/fr/autopilots.json
@@ -1,6 +1,5 @@
{
"page": {
- "title": "Automatisation",
"new_autopilot": "Nouvelle automatisation",
"start_blank": "Partir de zéro",
"table": {
@@ -20,7 +19,6 @@
"title": "Aucune automatisation pour l'instant",
"hint": "Planifiez du travail récurrent pour vos agents IA. Choisissez un modèle ou partez de zéro."
},
- "scope_all": "Toutes",
"no_matches": "Aucune automatisation correspondante",
"retry": "Réessayer"
},
@@ -87,10 +85,8 @@
"run_blocked_quota_exceeded": "Non déclenché — la limite d'exécutions de la période est atteinte",
"run_blocked_issue_limit_reached": "Non déclenchée : l'espace de travail a atteint sa limite de tâches",
"run_blocked_generic": "Non déclenchée — l'exécution a été bloquée",
- "section_properties": "Propriétés",
"section_triggers": "Déclencheurs",
"section_run_history": "Historique des exécutions",
- "section_danger": "Zone de danger",
"field_agent": "Agent",
"field_created_by": "Créé par",
"field_output_mode": "Mode de sortie",
@@ -100,6 +96,16 @@
"field_prompt": "Invite",
"field_subscribers": "Abonnés",
"field_subscribers_none": "Aucun",
+ "no_prompt": "Aucune invite pour l'instant.",
+ "copy_link": "Copier le lien",
+ "link_copied": "Lien copié",
+ "link_copy_failed": "Impossible de copier le lien",
+ "open_project": "Ouvrir le projet",
+ "summary": {
+ "create_issue": "{{agent}} crée une tâche à chaque exécution",
+ "run_only": "{{agent}} l'exécute sans créer de tâche",
+ "with_trigger": "{{trigger}} · {{action}}"
+ },
"add_trigger": "Ajouter un déclencheur",
"no_triggers": "Aucun déclencheur configuré. Ajoutez une planification pour une exécution automatique.",
"no_runs": "Aucune exécution pour l'instant. Cliquez sur « Exécuter maintenant » pour déclencher manuellement.",
@@ -441,29 +447,16 @@
"search_placeholder": "Rechercher un fuseau horaire..."
},
"toolbar": {
- "result_count_title": "Automatisations correspondantes / toutes les automatisations",
- "filter_label": "Filtrer",
- "filter_active_count_one": "{{count}} filtre",
- "filter_active_count_other": "{{count}} filtres",
- "clear_filters": "Effacer les filtres",
"section_assignee": "Assigné à",
"section_mode": "Mode",
"section_trigger": "Déclencheur",
- "section_creator": "Créé par",
- "display": "Affichage",
- "sort_by": "Trier par",
- "direction_asc": "Croissant",
- "direction_desc": "Décroissant",
- "section_columns": "Colonnes"
+ "section_creator": "Créé par"
},
"actions": {
"row_menu": "Actions de l'automatisation",
"pause": "Mettre en pause",
"resume": "Reprendre",
"delete": "Supprimer",
- "selected_one": "{{count}} sélectionnée",
- "selected_other": "{{count}} sélectionnées",
- "clear_selection": "Effacer la sélection",
"delete_dialog": {
"title": "Supprimer l'automatisation ?",
"description_one": "« {{name}} » et son historique d'exécutions seront définitivement supprimés.",
@@ -476,7 +469,6 @@
},
"wakeups": {
"title": "Réveils de tâches",
- "scope": "Périmètre",
"issue": "Tâche",
"trigger": "Déclencheur",
"enabled": "Activé",
@@ -485,22 +477,16 @@
"at": "Ponctuel",
"recurring": "Récurrent",
"all_agents": "Tous les agents",
- "search": "Rechercher des tâches ou agents",
"running": "En cours",
"active_runs": "{{count}} exécutions actives",
"issue_closed": "Tâche fermée",
"read_only": "Seuls le créateur ou un administrateur peuvent gérer ce réveil",
"select_row": "Sélectionner {{issue}}, {{agent}}",
- "select_page": "Sélectionner les réveils activés sur cette page",
+ "select_page": "Sélectionner tous les réveils activés",
"load_error": "Impossible de charger les réveils",
"loading": "Chargement des réveils…",
"empty": "Aucune règle de réveil",
- "selected": "{{count}} sélectionnés",
"disable_selected": "Désactiver la sélection",
- "clear": "Effacer la sélection",
- "results": "Page {{page}} · {{count}} résultats",
- "previous": "Précédent",
- "next_page": "Suivant",
"confirm_title": "Désactiver {{count}} réveils ?",
"confirm_body": "Les réveils futurs seront arrêtés. Les exécutions en file non confiées à un agent seront retirées. Les exécutions déjà confiées continueront ; arrêtez-les depuis le journal d’exécution.",
"cancel": "Annuler",
@@ -509,7 +495,7 @@
"batch_result": "Désactivés : {{succeeded}}. Échecs : {{failed}}.",
"scopes": {
"active": "En attente ou en cours",
- "all": "Tous",
+ "all": "Tous les réveils",
"disabled": "Désactivés",
"ended": "Terminés",
"paused": "En pause"
@@ -521,7 +507,7 @@
"batch_partial": "{{succeeded}} désactivées ; {{failed}} échecs. Les éléments en échec restent sélectionnés pour réessayer.",
"source": "Source",
"sources": {
- "all": "Source : toutes",
+ "all": "Toutes les sources",
"member": "Membres",
"agent": "Agents",
"system": "Système"
diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.json
index 4f2b0517c3..ff9944c635 100644
--- a/packages/views/locales/fr/chat.json
+++ b/packages/views/locales/fr/chat.json
@@ -247,7 +247,6 @@
"row_actions_aria": "Actions de discussion"
},
"header": {
- "view_profile": "Voir le profil de l'agent",
"rename": "Renommer la discussion",
"archive": "Archiver la discussion",
"unarchive": "Désarchiver la discussion",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 737729ca0e..33f39b8786 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -157,6 +157,7 @@
},
"filters": {
"tooltip": "Filtrer",
+ "active_section": "Actifs",
"placeholder": "Filtrer...",
"search_status": "Rechercher un état...",
"no_results": "Aucun résultat",
@@ -173,6 +174,16 @@
"section_project": "Projet",
"section_project_status": "Statut du projet",
"section_label": "Étiquette",
+ "section_relation": "Lien avec moi",
+ "relation_assigned": "Qui me sont assignés",
+ "relation_created": "Créés par moi",
+ "relation_my_agents": "Assignés à mes agents",
+ "operator_label": "Condition",
+ "operator_is": "est",
+ "operator_is_not": "n'est pas",
+ "modified_hint": "Modifié par rapport à la vue enregistrée",
+ "unsaved_changes_one": "{{count}} modification non enregistrée",
+ "unsaved_changes_other": "{{count}} modifications non enregistrées",
"section_date": "Date",
"date_field": "Champ",
"date_field_created": "Création",
@@ -198,7 +209,55 @@
"active_count_other": "{{count}} filtres",
"in_view": "Déjà dans cette vue",
"chip_edit": "Modifier",
- "chip_save_as": "Enregistrer sous"
+ "chip_save_as": "Enregistrer sous",
+ "section_due_date": "Échéance",
+ "due_overdue": "En retard",
+ "due_today": "Échéance aujourd'hui",
+ "due_this_week": "Échéance cette semaine",
+ "due_next_7_days": "Échéance dans les 7 prochains jours",
+ "due_none": "Sans échéance",
+ "search_placeholder": "Filtrer par champ ou valeur…",
+ "search_fields": "Champs",
+ "search_values": "Valeurs",
+ "advanced_switch": "Passer au filtre avancé",
+ "advanced_title": "Filtre avancé",
+ "advanced_match_leading": "Correspond à",
+ "advanced_match_trailing": "des conditions",
+ "match_all": "toutes",
+ "match_any": "au moins une",
+ "advanced_where": "Où",
+ "advanced_and": "et",
+ "advanced_or": "ou",
+ "advanced_add_condition": "Ajouter une condition",
+ "advanced_add_group": "Ajouter un groupe de conditions",
+ "advanced_unknown_property": "Propriété supprimée",
+ "advanced_values_placeholder": "Choisir des valeurs…",
+ "advanced_field_label": "Champ",
+ "advanced_values_label": "Valeurs",
+ "advanced_actions": "Actions de la condition",
+ "advanced_duplicate": "Dupliquer",
+ "advanced_delete": "Supprimer",
+ "advanced_delete_group": "Supprimer le groupe",
+ "advanced_to_simple": "Passer au filtre simple",
+ "advanced_to_simple_blocked": "Le filtre simple ne peut pas afficher les groupes, « au moins une » ou un champ utilisé deux fois",
+ "advanced_clear": "Tout effacer",
+ "advanced_empty": "Aucune condition. Ajoutez-en une pour filtrer.",
+ "advanced_conditions_one": "{{count}} condition",
+ "advanced_conditions_other": "{{count}} conditions",
+ "operator_has_any": "contient l'un de",
+ "operator_has_none": "ne contient aucun de",
+ "operator_contains": "contient",
+ "operator_not_contains": "ne contient pas",
+ "operator_before": "est avant",
+ "operator_after": "est après",
+ "operator_empty": "est vide",
+ "operator_not_empty": "n'est pas vide",
+ "advanced_group_match_leading": "Correspond à",
+ "advanced_group_match_trailing": "de ces conditions",
+ "advanced_group_hint": "Les conditions de ce groupe sont reliées par « {{word}} »",
+ "advanced_add_to_group": "Ajouter au groupe",
+ "advanced_turn_into_group": "Transformer en groupe",
+ "advanced_summary": "Affiche les tâches où {{summary}}"
},
"display": {
"tooltip": "Paramètres d'affichage",
@@ -208,6 +267,7 @@
"card_properties_section": "Propriétés des cartes",
"columns_section": "Colonnes",
"columns_locked_by_filter": "Retirez le filtre d’état pour afficher ou masquer des colonnes.",
+ "columns_shown": "{{count}} affichées",
"ascending_title": "Croissant",
"descending_title": "Décroissant",
"newest_first": "Plus récents d'abord",
@@ -240,7 +300,8 @@
"card_project": "Projet",
"card_labels": "Étiquettes",
"card_child_progress": "Avancement des sous-tâches",
- "show_sub_issues": "Afficher les sous-tâches"
+ "show_sub_issues": "Afficher les sous-tâches",
+ "layout_options": "Options de la vue {{layout}}"
},
"view": {
"tooltip_board": "Vue tableau",
@@ -999,38 +1060,6 @@
"row_todo_hint": "démarre l'agent"
},
"save_view": {
- "title": "Enregistrer comme vue",
- "hint_workspace": "Fondée sur toutes les tâches de l'espace de travail",
- "hint_my_any": "Fondée sur Mes tâches · Toutes",
- "hint_my_assigned": "Fondée sur Mes tâches · Assignées",
- "hint_my_created": "Fondée sur Mes tâches · Créées",
- "hint_my_involved": "Fondée sur Mes tâches · Impliqué",
- "hint_project": "Fondée sur le projet « {{title}} », disponible uniquement sur la page de ce projet",
- "hint_project_agents": "Fondée sur les tâches du projet « {{title}} » assignées à des agents, disponible uniquement sur la page de ce projet",
- "hint_project_members": "Fondée sur les tâches du projet « {{title}} » assignées à des membres, disponible uniquement sur la page de ce projet",
- "my_private_note": "Les vues Mes tâches ne sont visibles que par vous",
- "name_label": "Nom",
- "visibility_label": "Visibilité",
- "visibility_private": "Visible par moi seul",
- "visibility_workspace": "Visible par les membres de l'espace de travail",
- "filters_label": "Filtres",
- "custom_property": "Propriété personnalisée",
- "create": "Créer la vue",
- "layout_label": "Disposition",
- "display_defaults": "Affichage par défaut",
- "default_hint": "L'aspect initial de cette vue pour les membres ; chacun peut ensuite l'ajuster pour soi",
- "add_filter": "Ajouter un filtre",
- "name_placeholder": "ex. À relire",
- "cancel": "Annuler",
- "name_required": "Saisissez un nom de vue",
- "toast_created": "Vue créée",
- "toast_failed": "Échec de la création de la vue",
- "edit_title": "Modifier la vue",
- "update": "Enregistrer les modifications",
- "toast_updated": "Vue mise à jour",
- "toast_conflict": "Quelqu'un d'autre a modifié cette vue — rouvrez-la et réessayez",
- "hint_workspace_members": "Fondée sur les tâches de l'espace de travail assignées à des membres",
- "hint_workspace_agents": "Fondée sur les tâches de l'espace de travail assignées à des agents",
"scope_label_workspace": "Type d'assigné",
"scope_label_my": "Relation avec moi",
"variant_all": "Tout assigné",
@@ -1041,36 +1070,6 @@
"variant_my_created": "Que j'ai créés",
"variant_my_involved": "Impliqué"
},
- "view_selector": {
- "trigger": "Vues",
- "empty": "Aucune vue enregistrée pour l'instant",
- "private_group": "Privées",
- "shared_group": "Partagées avec l'espace de travail",
- "exit": "Quitter la vue",
- "unavailable": "Cette vue n'est plus disponible",
- "edit": "Modifier la vue"
- },
- "view_bar": {
- "menu_label": "Vues",
- "menu_new": "Nouvelle vue",
- "builtin_tag": "Intégrée",
- "drag_handle": "Faire glisser pour réorganiser",
- "delete": "Supprimer",
- "delete_title": "Supprimer la vue ?",
- "delete_description": "« {{name}} » sera supprimée pour toutes les personnes qui peuvent la voir",
- "toast_deleted": "Vue supprimée",
- "context_edit": "Modifier la vue",
- "context_pin": "Épingler à la barre latérale",
- "context_unpin": "Détacher de la barre latérale",
- "row_menu": "Plus d'actions",
- "row_hide": "Masquer de la barre",
- "row_show": "Afficher sur la barre",
- "menu_manage": "Gérer les vues",
- "manage_title": "Gérer les vues",
- "manage_hint": "L'ordre et la visibilité ne concernent que vous",
- "visible_toggle": "Afficher dans la barre de vues",
- "more_label": "Plus de vues"
- },
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} n'a pas pu charger son interface.",
@@ -1774,5 +1773,68 @@
},
"hover_card": {
"created_updated": "a créé {{created}} · mis à jour {{updated}}"
+ },
+ "views": {
+ "builtin": {
+ "my_issues": "Mes tâches",
+ "my_agents": "Travail de mes agents",
+ "all_issues": "Toutes les tâches"
+ },
+ "untitled": "Vue sans titre",
+ "copy_name": "{{name}} (copie)",
+ "rename": "Renommer",
+ "duplicate": "Dupliquer",
+ "copy_link": "Copier le lien",
+ "link_copied": "Lien copié",
+ "visible_to": "Visible par",
+ "only_me": "Moi uniquement",
+ "workspace_members": "Membres de l'espace de travail",
+ "add_to_sidebar": "Ajouter à la barre latérale",
+ "remove_from_sidebar": "Retirer de la barre latérale",
+ "back_to": "Revenir à {{name}}",
+ "delete": "Supprimer la vue",
+ "delete_title": "Supprimer la vue ?",
+ "delete_description": "« {{name}} » sera supprimée. Cette action est irréversible.",
+ "delete_description_shared": "« {{name}} » est partagée avec l'espace de travail et sera supprimée pour tout le monde.",
+ "cancel": "Annuler",
+ "toast_deleted": "Vue supprimée",
+ "toast_delete_failed": "Impossible de supprimer la vue",
+ "filter": "Filtrer",
+ "filter_count_one": "{{count}} filtre",
+ "filter_count_other": "{{count}} filtres",
+ "reset": "Réinitialiser",
+ "save": "Enregistrer",
+ "save_options": "Autres options d'enregistrement",
+ "save_to": "Enregistrer dans « {{name}} »",
+ "save_to_hint_shared": "Met à jour la vue pour tout l'espace de travail",
+ "save_to_hint_private": "Met à jour votre vue",
+ "save_as_new": "Enregistrer comme nouvelle vue",
+ "save_as_new_hint": "« {{name}} » reste inchangée",
+ "save_as_view": "Enregistrer comme vue",
+ "set_by_view": "Défini par cette vue",
+ "new_issue": "Nouvelle tâche",
+ "unavailable": "Cette vue n'est plus disponible",
+ "toast_saved": "Vue enregistrée",
+ "toast_conflict": "Quelqu'un d'autre a modifié cette vue — rechargez et réessayez",
+ "toast_create_failed": "Impossible de créer la vue",
+ "toast_save_failed": "Impossible d'enregistrer la vue",
+ "directory": {
+ "new_view": "Nouvelle vue",
+ "scope_all": "Toutes les vues",
+ "scope_builtin": "Intégrées",
+ "scope_mine": "Créées par moi",
+ "scope_shared": "Partagées",
+ "col_name": "Nom",
+ "col_location": "Emplacement",
+ "col_filters": "Filtres",
+ "col_visibility": "Visible par",
+ "col_owner": "Propriétaire",
+ "owner_builtin": "Intégrée",
+ "location_project": "Projet",
+ "star": "Ajouter {{name}} à la barre latérale",
+ "unstar": "Retirer {{name}} de la barre latérale",
+ "row_actions": "Actions pour {{name}}",
+ "no_matches": "Aucune vue ne correspond"
+ }
}
}
diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.json
index a9837df863..e42569334c 100644
--- a/packages/views/locales/fr/layout.json
+++ b/packages/views/locales/fr/layout.json
@@ -11,7 +11,8 @@
"usage": "Statistiques",
"runtimes": "Runtimes",
"skills": "Skills",
- "settings": "Paramètres"
+ "settings": "Paramètres",
+ "views": "Vues"
},
"tab": {
"issue": "Tâche",
@@ -25,6 +26,7 @@
"runtime": "Runtime",
"attachment": "Pièce jointe",
"create_agent": "Créer un agent",
+ "my_agents": "Travail de mes agents",
"unknown": "Page inconnue"
},
"help": {
@@ -57,16 +59,121 @@
"invitation_decline": "Refuser",
"log_out": "Se déconnecter",
"new_issue": "Nouvelle tâche",
- "new_issue_shortcut": "C",
"pinned_label": "Épinglés",
- "work_group": "Travail",
- "ai_team_group": "Équipe IA",
"show_more_pins": "Afficher {{count}} de plus…",
- "show_fewer_pins": "Afficher moins",
- "unread_overflow": "99+",
- "discord_card": {
- "title": "Rejoignez notre Discord",
- "dismiss": "Ignorer"
+ "show_fewer_pins": "Afficher moins"
+ },
+ "spaces": {
+ "work": "Tâches",
+ "team": "Équipe"
+ },
+ "rail": {
+ "label": "Navigation de l'application",
+ "sheet_description": "Changer d'espace et d'espace de travail.",
+ "inbox": "Boîte",
+ "work": "Tâches",
+ "team": "Équipe",
+ "chat": "Chat",
+ "autopilots": "Auto",
+ "switch_workspace": "Changer d'espace de travail",
+ "invitation_from": "{{name}} vous a invité"
+ },
+ "panels": {
+ "work": {
+ "my_agents": "Travail de mes agents",
+ "all_issues": "Toutes les tâches",
+ "views": "Vues",
+ "new_project": "Nouveau projet",
+ "new_issue_in_project": "Nouvelle tâche dans {{name}}",
+ "all_projects_one": "Tous les projets ({{count}})",
+ "all_projects_other": "Tous les projets ({{count}})",
+ "project_issues": "Tâches de {{name}}",
+ "project_issues_empty": "Aucune tâche",
+ "project_issues_error": "Impossible de charger les tâches",
+ "project_issues_settings": "Tâches des projets",
+ "settings_status": "Statut",
+ "settings_assignee": "Responsable",
+ "assignee_anyone": "Tout le monde",
+ "assignee_me": "Moi",
+ "assignee_my_agents": "Mes agents",
+ "reset": "Réinitialiser",
+ "load_more": "Afficher plus",
+ "show_less": "Afficher moins",
+ "projects_settings": "Affichage des projets",
+ "projects_ordering": "Tri",
+ "projects_order_manual": "Manuel",
+ "projects_order_name": "Nom",
+ "projects_order_updated": "Mis à jour récemment",
+ "projects_order_created": "Créés récemment",
+ "projects_show": "Afficher",
+ "projects_only_mine": "Seulement les projets que je dirige",
+ "projects_show_count": "Nombre de tâches ouvertes",
+ "new_view": "Nouvelle vue",
+ "all_views": "Toutes les vues",
+ "view_actions": "Actions pour {{name}}",
+ "view_copy_link": "Copier le lien",
+ "view_remove": "Retirer de la barre latérale",
+ "view_rename": "Renommer",
+ "view_duplicate": "Dupliquer",
+ "view_delete": "Supprimer la vue"
+ },
+ "team": {
+ "new_agent": "Nouvel agent",
+ "needs_attention": "À traiter",
+ "stuck_one": "{{count}} tâche attend un runtime hors ligne",
+ "stuck_other": "{{count}} tâches attendent un runtime hors ligne",
+ "working_now": "En cours",
+ "running_tasks_one": "{{count}} tâche en cours",
+ "running_tasks_other": "{{count}} tâches en cours",
+ "all_agents": "Tous les agents",
+ "my_agents": "Mes agents",
+ "squads_and_members": "Squads et membres",
+ "members_one": "{{count}} membre",
+ "members_other": "{{count}} membres",
+ "resources": "Ressources",
+ "runtimes_offline_one": "{{count}} hors ligne",
+ "runtimes_offline_other": "{{count}} hors ligne",
+ "invite_member": "Inviter un membre"
+ },
+ "autopilots": {
+ "all": "Toutes les automatisations",
+ "list": "Automatisations",
+ "templates": "À partir d’un modèle"
}
+ },
+ "account": {
+ "trigger": "Compte",
+ "profile": "Profil",
+ "theme": "Thème",
+ "themes": {
+ "light": "Clair",
+ "dark": "Sombre",
+ "system": "Système"
+ },
+ "language": "Langue",
+ "shortcuts": "Raccourcis clavier"
+ },
+ "collection": {
+ "filter": "Filtrer",
+ "filter_count_one": "{{count}} filtre",
+ "filter_count_other": "{{count}} filtres",
+ "reset": "Réinitialiser",
+ "display": "Affichage",
+ "selected_one": "{{count}} sélectionné",
+ "selected_other": "{{count}} sélectionnés",
+ "clear_selection": "Effacer la sélection",
+ "select_all": "Tout sélectionner",
+ "select_row": "Sélectionner la ligne",
+ "row_actions": "Actions de la ligne",
+ "sort_by": "Trier par",
+ "direction_asc": "Croissant",
+ "direction_desc": "Décroissant",
+ "section_columns": "Colonnes",
+ "load_more": "Charger plus",
+ "loading_more": "Chargement…"
+ },
+ "object_page": {
+ "toggle_panel": "Afficher ou masquer le panneau de droite",
+ "properties": "Propriétés"
}
}
diff --git a/packages/views/locales/fr/members.json b/packages/views/locales/fr/members.json
index 93f2c94e1c..9bf0c92966 100644
--- a/packages/views/locales/fr/members.json
+++ b/packages/views/locales/fr/members.json
@@ -12,8 +12,11 @@
"more_agents_other": "et {{count}} autres agents"
},
"detail": {
- "workspace_fallback": "Espace de travail",
"members_breadcrumb": "Membres",
+ "role": "Rôle",
+ "email": "E-mail",
+ "joined": "Membre depuis",
+ "relation": "Relation",
"breadcrumb_fallback": "Membre",
"not_found_title": "Membre introuvable",
"not_found_description": "Ce membre a peut-être quitté l'espace de travail."
diff --git a/packages/views/locales/fr/projects.json b/packages/views/locales/fr/projects.json
index f1978fa495..0fa282f019 100644
--- a/packages/views/locales/fr/projects.json
+++ b/packages/views/locales/fr/projects.json
@@ -2,11 +2,13 @@
"page": {
"title": "Projets",
"new_project": "Nouveau projet",
+ "scope_all": "Tous les projets",
+ "scope_active": "Projets actifs",
+ "scope_closed": "Projets clos",
"empty": "Aucun projet pour l'instant",
"create_first": "Créez votre premier projet",
"view_compact": "Compact",
"view_comfortable": "Confortable",
- "search_placeholder": "Rechercher des projets...",
"no_search_results": "Aucun résultat ne correspond à votre recherche",
"view_table": "Grille",
"view_cards": "Cartes",
@@ -14,10 +16,7 @@
"pin": "Épingler à la barre latérale",
"unpin": "Détacher",
"delete": "Supprimer",
- "no_matches": "Aucun projet correspondant",
- "selected_one": "{{count}} sélectionné",
- "selected_other": "{{count}} sélectionnés",
- "clear_selection": "Effacer la sélection"
+ "no_matches": "Aucun projet correspondant"
},
"table": {
"name": "Nom",
@@ -168,19 +167,9 @@
"fallback_label": "Projet"
},
"toolbar": {
- "result_count_title": "Projets correspondants / tous les projets",
- "filter_label": "Filtrer",
- "filter_active_count_one": "{{count}} filtre",
- "filter_active_count_other": "{{count}} filtres",
- "clear_filters": "Effacer les filtres",
"section_status": "Statut",
"section_priority": "Priorité",
"section_lead": "Responsable",
- "display": "Affichage",
- "sort_by": "Trier par",
- "direction_asc": "Croissant",
- "direction_desc": "Décroissant",
- "section_columns": "Colonnes",
"view": "Vue"
}
}
diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.json
index 175d9b7691..d725526f9c 100644
--- a/packages/views/locales/fr/runtimes.json
+++ b/packages/views/locales/fr/runtimes.json
@@ -1,9 +1,7 @@
{
"page": {
"title": "Runtimes",
- "learn_more": "En savoir plus →",
"connect_remote": "Ajouter une machine",
- "search_placeholder": "Rechercher…",
"scope_mine": "Les miens",
"scope_all": "Tous",
"live": "En direct",
@@ -25,7 +23,7 @@
"title": "Démarrage du runtime local…",
"hint": "Connexion à l’espace de travail..."
},
- "add": "Ajouter",
+ "add": "Ajouter un runtime",
"add_menu": {
"machines": "Machines",
"this_computer": "Cet ordinateur",
@@ -67,7 +65,7 @@
"no_matches": "Aucune machine ni aucun service cloud ne correspond"
},
"filters": {
- "all": "Tous",
+ "all": "Tous les runtimes",
"online": "En ligne",
"offline": "Hors ligne"
}
@@ -93,8 +91,7 @@
"this_machine": "Cet appareil",
"local_badge": "Local · cette machine",
"pending_custom_runtimes": "Runtimes personnalisés en attente",
- "runtime_count_one": "{{count}} runtime",
- "runtime_count_other": "{{count}} runtimes",
+ "daemon_title": "Daemon",
"busy_count_one": "{{count}} occupé",
"busy_count_other": "{{count}} occupés",
"no_matches_title": "Aucune machine",
@@ -162,14 +159,10 @@
"fact_owner": "Propriétaire",
"fact_device": "Appareil",
"fact_runtime": "Runtime",
- "technical_details": "Détails techniques",
"fact_daemon_cli": "CLI du daemon",
"fact_daemon_id": "Identifiant du daemon",
- "serving_title": "Au service de",
- "serving_count_one": "{{count}} agent",
- "serving_count_other": "{{count}} agents",
+ "usage_title": "Consommation",
"no_agents": "Aucun agent n'est encore associé à ce runtime.",
- "diagnostics_title": "Diagnostics",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "Visibilité",
"visibility_label": {
diff --git a/packages/views/locales/fr/skills.json b/packages/views/locales/fr/skills.json
index fda035551a..69547d0562 100644
--- a/packages/views/locales/fr/skills.json
+++ b/packages/views/locales/fr/skills.json
@@ -1,12 +1,10 @@
{
"page": {
"title": "Skills",
- "learn_more": "En savoir plus →",
"new_skill": "Nouveau skill",
- "search_placeholder": "Rechercher des skills…",
"scopes": {
"all": {
- "label": "Tous",
+ "label": "Tous les skills",
"description": "Tous les skills de cet espace de travail"
},
"used": {
@@ -18,7 +16,7 @@
"description": "Skills assignés à aucun agent"
},
"mine": {
- "label": "Créés par moi",
+ "label": "Mes skills",
"description": "Les skills que vous avez créés"
}
},
@@ -76,8 +74,6 @@
"added_toast": "Ajouté à {{name}}",
"add_failed_toast": "Échec de l'ajout du skill",
"delete": "Supprimer",
- "selected": "{{count}} sélectionnés",
- "clear_selection": "Effacer la sélection",
"delete_no_permission": "La sélection contient des skills que seuls leur créateur ou un administrateur peuvent supprimer",
"delete_dialog_title_one": "Supprimer {{count}} skill ?",
"delete_dialog_title_other": "Supprimer {{count}} skills ?",
@@ -105,29 +101,16 @@
"added_multi_toast_other": "Ajouté à {{count}} agents"
},
"toolbar": {
- "result_count_title": "Skills correspondants / tous les skills",
- "filter_label": "Filtrer",
- "filter_active_count_one": "{{count}} filtre",
- "filter_active_count_other": "{{count}} filtres",
- "clear_filters": "Effacer les filtres",
"section_usage": "Utilisation",
"section_labels": "Étiquettes",
"filter_search_placeholder": "Filtrer...",
"no_labels": "Aucune étiquette pour l'instant",
"no_results": "Aucun résultat",
- "display": "Affichage",
- "sort_by": "Trier par",
- "direction_asc": "Croissant",
- "direction_desc": "Décroissant",
- "section_columns": "Colonnes",
"manage_labels": "Gérer les étiquettes...",
"manage_labels_title": "Étiquettes des skills"
},
"detail": {
- "all_skills": "Tous les skills",
"read_only": "Lecture seule",
- "delete_aria": "Supprimer le skill",
- "delete_tooltip": "Supprimer le skill",
"supporting_data_warning": "Certaines données de l'espace de travail n'ont pas pu être chargées. L'attribution des créateurs, les noms de runtimes ou les droits de modification peuvent apparaître incomplets jusqu'à la prochaine actualisation.",
"delete_file": "Supprimer le fichier",
"name_placeholder": "nom-du-skill",
@@ -163,8 +146,6 @@
"toast_deleted": "Skill supprimé",
"toast_delete_failed": "Échec de la suppression du skill",
"refresh": {
- "button": "Mettre à jour",
- "tooltip": "Retélécharger ce skill depuis sa source",
"source_github": "GitHub",
"source_skills_sh": "Skills.sh",
"source_clawhub": "ClawHub",
@@ -205,32 +186,18 @@
},
"header": {
"files_one": "{{count}} fichier",
- "files_other": "{{count}} fichiers",
- "used_by_one": "{{count}} agent",
- "used_by_other": "{{count}} agents",
- "updated": "Mis à jour {{when}}",
- "updated_by": "Mis à jour {{when}} par {{name}}"
- },
- "tabs": {
- "aria": "Sections du skill",
- "overview": "Vue d'ensemble",
- "files_one": "Fichiers {{count}}",
- "files_other": "Fichiers {{count}}"
+ "files_other": "{{count}} fichiers"
},
"overview": {
"properties": "Propriétés",
- "properties_hint": "Ces champs restent synchronisés avec le frontmatter du SKILL.md.",
"name": "Nom",
"description": "Description",
"description_hint": "Les agents s’en servent pour décider quand charger le skill.",
"labels": "Étiquettes",
- "used_by_one": "Utilisé par {{count}} agent",
- "used_by_other": "Utilisé par {{count}} agents",
"used_by_empty": "Assigné à aucun agent pour l'instant. Ouvrez l'onglet Skills d'un agent pour l'assigner.",
"permissions_owner": "Vous pouvez modifier et supprimer ce skill. Les changements prennent effet à la prochaine exécution d'agent.",
"permissions_locked_creator": "Seuls le créateur ({{name}}) ou un administrateur de l'espace de travail peuvent modifier ce skill.",
"permissions_locked": "Seuls le créateur ou un administrateur de l'espace de travail peuvent modifier ce skill.",
- "properties_help": "À propos des propriétés du skill",
"character_count": "{{count}} caractères"
},
"files": {
@@ -244,6 +211,21 @@
"mode_preview": "Aperçu",
"mode_edit": "Modifier",
"mode_raw": "Texte brut"
+ },
+ "sections": {
+ "content": "Contenu",
+ "files": "Fichiers",
+ "edit": "Modifier",
+ "open": "Ouvrir",
+ "add": "Ajouter"
+ },
+ "menu": {
+ "copy_link": "Copier le lien",
+ "link_copied": "Lien copié",
+ "delete": "Supprimer le skill"
+ },
+ "panel": {
+ "add_description": "Ajouter une description"
}
},
"create": {
diff --git a/packages/views/locales/fr/squads.json b/packages/views/locales/fr/squads.json
index b14682c5c6..cc8b9f506b 100644
--- a/packages/views/locales/fr/squads.json
+++ b/packages/views/locales/fr/squads.json
@@ -15,10 +15,6 @@
"row_menu": "Actions du squad",
"archive_action": "Archiver"
},
- "inspector": {
- "details_section": "Détails",
- "archive_button": "Archiver"
- },
"member_type": {
"agent": "Agent",
"member": "Membre"
@@ -65,16 +61,8 @@
"responsibility_placeholder": "De quoi ce squad est-il responsable ?",
"save": "Enregistrer"
},
- "discard_changes_dialog": {
- "title": "Abandonner les modifications non enregistrées ?",
- "description": "Cet onglet contient des modifications non enregistrées. Changer d'onglet les abandonnera.",
- "keep_editing": "Continuer à modifier",
- "discard_button": "Abandonner"
- },
"members_tab": {
"section_title": "Membres",
- "section_count_one": "{{count}} membre dans ce squad",
- "section_count_other": "{{count}} membres dans ce squad",
"add_member_button": "Ajouter un membre",
"create_agent_button": "Créer un agent",
"leader_chip": "Chef",
@@ -87,19 +75,29 @@
"status_unstable": "Instable",
"status_archived": "Archivé",
"issue_status_blocked": "bloqué",
- "active_issue_more": "et {{count}} de plus",
- "last_active_label": "dernière activité {{time}}"
- },
- "detail_tabs": {
- "members": "Membres",
- "instructions": "Instructions"
+ "active_issue_more": "et {{count}} de plus"
+ },
+ "detail": {
+ "assign_work": "Assigner du travail",
+ "copy_link": "Copier le lien",
+ "link_copied": "Lien copié",
+ "not_found": "Squad introuvable",
+ "instructions": "Instructions",
+ "edit": "Modifier",
+ "cancel": "Annuler",
+ "recent_work": "Travail récent",
+ "recent_work_empty": "Aucune tâche n'a encore été assignée à ce squad.",
+ "member_menu": "Actions pour {{name}}",
+ "working_on": "Travaille sur"
},
"details": {
"leader": "Chef",
"members": "Membres",
"created_by": "Créé par",
"created": "Créé",
- "updated": "Mis à jour"
+ "updated": "Mis à jour",
+ "visibility": "Visibilité",
+ "visibility_workspace": "Espace de travail"
},
"toasts": {
"member_added": "Membre ajouté",
@@ -130,19 +128,8 @@
"placeholder": "Par exemple : commencez toujours par écrire un test qui échoue. Privilégiez des commits petits et atomiques."
},
"scope": {
- "mine": "Les miens",
- "all": "Tous"
+ "mine": "Mes squads",
+ "all": "Tous les squads"
},
- "toolbar": {
- "display": "Affichage",
- "sort_by": "Trier par",
- "direction_asc": "Croissant",
- "direction_desc": "Décroissant",
- "section_columns": "Colonnes",
- "result_count_title": "Squads correspondants / tous les squads",
- "filter_label": "Filtrer",
- "filter_active_count_one": "{{count}} filtre",
- "filter_active_count_other": "{{count}} filtres",
- "clear_filters": "Effacer les filtres"
- }
+ "toolbar": {}
}
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index c77b415c0f..1d0ef5d297 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -1,19 +1,21 @@
{
"page": {
"title": "エージェント",
- "learn_more": "詳細はこちら →",
"new_agent": "新規エージェント",
- "search_placeholder": "エージェントを検索...",
"show_archived": "アーカイブ済みを表示 ({{count}}) →",
"of_total": "{{total}} 件中 {{visible}} 件",
"list_load_failed": "エージェントを読み込めませんでした",
"list_load_failed_default": "エージェント一覧の取得中に問題が発生しました。",
- "try_again": "再試行"
+ "try_again": "再試行",
+ "scope_title": {
+ "mine": "自分のエージェント",
+ "all": "すべてのエージェント",
+ "archived": "アーカイブ済みのエージェント"
+ }
},
"scope": {
"mine": "自分のもの",
- "all": "すべて",
- "archived": "アーカイブ済み"
+ "all": "すべて"
},
"sort": {
"label_recent": "最近のアクティビティ",
@@ -47,10 +49,7 @@
},
"no_matches": {
"title": "一致する結果なし",
- "search_archived": "\"{{query}}\" に一致するアーカイブ済みエージェントがありません。",
"no_archived": "まだアーカイブ済みのエージェントはありません。",
- "search_active": "\"{{query}}\" に一致するエージェントがありません。",
- "search_active_filtered": "このフィルターで \"{{query}}\" に一致するエージェントがありません。",
"no_filter_match": "このフィルターに一致するエージェントがありません。",
"search_runtime_filtered": "\"{{machine}}\" 上に \"{{query}}\" に一致するエージェントがありません。",
"runtime_filtered": "\"{{machine}}\" 上にエージェントがありません。"
@@ -119,7 +118,6 @@
"archive_dialog_confirm": "アーカイブ"
},
"detail": {
- "back_to_agents": "エージェント",
"back_to_agents_full": "エージェントに戻る",
"not_found_title": "エージェントが見つかりません",
"not_found_default": "このエージェントはアーカイブまたは削除された可能性があります。",
@@ -148,7 +146,11 @@
"runtime_required_toast": "このエージェントを実行する前にランタイムを設定してください。",
"assign_work": "作業を割り当てる",
"more_actions_aria": "エージェントの操作",
- "updated": "{{when}}に更新"
+ "advanced_settings": "詳細設定",
+ "copy_link": "リンクをコピー",
+ "copy_id": "エージェント ID をコピー",
+ "link_copied_toast": "リンクをコピーしました",
+ "id_copied_toast": "エージェント ID をコピーしました"
},
"inspector": {
"section_profile": "プロフィール",
@@ -158,7 +160,6 @@
"section_properties": "プロパティ",
"section_details": "詳細",
"section_details_hint": "所有者とライフサイクルに関する読み取り専用情報です。",
- "section_skills": "スキル",
"section_integrations": "連携",
"prop_runtime": "ランタイム",
"prop_model": "モデル",
@@ -169,7 +170,6 @@
"prop_owner": "オーナー",
"prop_created": "作成日",
"prop_updated": "更新日",
- "no_description_placeholder": "説明なし",
"avatar_label": "アバター",
"name_label": "名前",
"description_label": "説明",
@@ -185,11 +185,24 @@
"cancel": "キャンセル"
},
"overview": {
- "agent_context": "エージェント",
- "access": "アクセス",
"attention_title": "対応が必要な実行",
"attention_queued_other": "ランタイムが利用できないため、{{count}}件の実行が待機中です。"
},
+ "sections": {
+ "runs_count_other": "{{count}} 件の実行",
+ "recent_this_week_other": "今週 {{count}} 件",
+ "view_all": "すべて表示",
+ "open": "開く",
+ "edit": "編集",
+ "add": "追加",
+ "manage": "管理",
+ "instructions_empty": "まだ指示はありません。"
+ },
+ "panel": {
+ "status": "ステータス",
+ "runs_7d": "実行 (7日)",
+ "edit_access_aria": "アクセス: {{value}}。アクセスを変更"
+ },
"skill_attach": {
"trigger_aria": "ワークスペースのスキルを追加",
"trigger_label": "追加"
@@ -243,13 +256,11 @@
"clear_full": "選択をクリア(プロバイダーのデフォルトを使用)"
},
"tabs": {
- "overview": "概要",
"work": "作業",
"capabilities": "機能",
"settings": "設定",
"general": "一般",
"access": "アクセス",
- "page_navigation_aria": "エージェントページ",
"section_navigation_aria": "エージェントセクション",
"activity": "アクティビティ",
"tasks": "実行",
@@ -618,12 +629,6 @@
"section_now": "現在",
"section_last_30d": "過去30日",
"section_recent": "最近の作業",
- "subtitle_no_active": "アクティブな作業なし",
- "subtitle_active_other": "アクティブな実行 {{count}} 件",
- "subtitle_performance": "パフォーマンス",
- "subtitle_no_recent": "まだ完了した実行はありません",
- "subtitle_recent_progress": "{{total}} 回の実行中 {{shown}} 回",
- "subtitle_recent_latest": "最新 {{count}} 回の実行",
"empty_now": "このエージェントは現在何も実行していません。",
"empty_30d": "過去30日間に完了した作業はありません。",
"empty_recent": "このエージェントはまだ何も完了していません。",
@@ -634,9 +639,7 @@
"success_hint": "完了した実行数を、完了と失敗の実行数の合計で割った割合です。キャンセルした実行は含みません。",
"success_unavailable": "この期間に完了または失敗した実行がないため、成功率を計算できません。",
"cancelled_count": "{{count}} 件キャンセル",
- "avg_duration": "平均 {{value}}",
"avg_duration_label": "平均時間",
- "failed_count": "{{count}} 回失敗",
"failed_label": "失敗",
"source_issue": "タスク",
"source_chat": "チャット",
@@ -868,18 +871,9 @@
"none": "30 日間アクティビティなし"
},
"toolbar": {
- "result_count_title": "該当エージェント / スコープ内全体",
- "filter_label": "フィルター",
- "filter_active_count_other": "{{count}} 件のフィルター",
- "clear_filters": "フィルターをクリア",
"section_availability": "可用性",
"section_access": "アクセス",
"section_runtime": "ランタイム",
- "display": "表示",
- "sort_by": "並び替え",
- "direction_asc": "昇順",
- "direction_desc": "降順",
- "section_columns": "列",
"section_owner": "オーナー",
"section_model": "モデル"
},
@@ -887,7 +881,6 @@
"title": "エージェントを作成",
"squad_title": "このスクワッド用のエージェントを作成",
"duplicate_title": "{{name}} を複製",
- "back": "戻る",
"step_ai": "会話で作成",
"modes": {
"template": {
@@ -971,7 +964,8 @@
"runtime": "ランタイムを選択",
"configure": "設定",
"done": "完了",
- "aria": "エージェント作成の手順"
+ "aria": "エージェント作成の手順",
+ "progress": "ステップ {{current}}/{{total}}"
},
"configure_title": "エージェントを設定",
"ask_ai": "AI に書いてもらう",
@@ -1032,8 +1026,5 @@
"next": "次へ"
}
},
- "actions": {
- "selected_other": "{{count}} 件選択中",
- "clear_selection": "選択を解除"
- }
+ "actions": {}
}
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index 4c577a0520..069c13afb9 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -1,6 +1,5 @@
{
"page": {
- "title": "オートパイロット",
"new_autopilot": "新規オートパイロット",
"start_blank": "ゼロから始める",
"table": {
@@ -20,7 +19,6 @@
"title": "まだオートパイロットがありません",
"hint": "AI エージェントの繰り返し作業をスケジュールしましょう。テンプレートを選ぶか、ゼロから始められます。"
},
- "scope_all": "すべて",
"no_matches": "該当する自動化はありません",
"retry": "再試行"
},
@@ -87,10 +85,8 @@
"run_blocked_quota_exceeded": "実行されませんでした — この期間の実行上限に達しました",
"run_blocked_issue_limit_reached": "実行されませんでした — ワークスペースのタスク数上限に達しました",
"run_blocked_generic": "実行されませんでした — 実行がブロックされました",
- "section_properties": "プロパティ",
"section_triggers": "トリガー",
"section_run_history": "実行履歴",
- "section_danger": "危険な操作",
"field_agent": "エージェント",
"field_created_by": "作成者",
"field_output_mode": "出力モード",
@@ -100,6 +96,16 @@
"field_prompt": "プロンプト",
"field_subscribers": "購読者",
"field_subscribers_none": "なし",
+ "no_prompt": "プロンプトはまだありません。",
+ "copy_link": "リンクをコピー",
+ "link_copied": "リンクをコピーしました",
+ "link_copy_failed": "リンクをコピーできませんでした",
+ "open_project": "プロジェクトを開く",
+ "summary": {
+ "create_issue": "{{agent}} が実行ごとにタスクを作成",
+ "run_only": "{{agent}} がタスクを作成せずに実行",
+ "with_trigger": "{{trigger}} · {{action}}"
+ },
"add_trigger": "トリガーを追加",
"no_triggers": "設定されたトリガーがありません。自動で実行するスケジュールを追加してください。",
"no_runs": "まだ実行履歴がありません。手動で実行するには「今すぐ実行」をクリックしてください。",
@@ -441,27 +447,16 @@
"search_placeholder": "タイムゾーンを検索..."
},
"toolbar": {
- "result_count_title": "該当する自動化 / すべての自動化",
- "filter_label": "フィルター",
- "filter_active_count_other": "{{count}} 件のフィルター",
- "clear_filters": "フィルターをクリア",
"section_assignee": "担当",
"section_mode": "モード",
"section_trigger": "トリガー",
- "section_creator": "作成者",
- "display": "表示",
- "sort_by": "並び替え",
- "direction_asc": "昇順",
- "direction_desc": "降順",
- "section_columns": "列"
+ "section_creator": "作成者"
},
"actions": {
"row_menu": "自動化の操作",
"pause": "一時停止",
"resume": "再開",
"delete": "削除",
- "selected_other": "{{count}} 件選択中",
- "clear_selection": "選択を解除",
"delete_dialog": {
"title": "自動化を削除しますか?",
"description_other": "{{count}} 件の自動化とその実行履歴を完全に削除します。",
@@ -473,7 +468,6 @@
},
"wakeups": {
"title": "タスクのウェイクアップ",
- "scope": "範囲",
"issue": "タスク",
"trigger": "トリガー",
"enabled": "有効",
@@ -482,22 +476,16 @@
"at": "一回限り",
"recurring": "繰り返し",
"all_agents": "すべてのエージェント",
- "search": "タスク・エージェントを検索",
"running": "実行中",
"active_runs": "{{count}} 件の実行が進行中",
"issue_closed": "タスクは終了済み",
"read_only": "作成者またはワークスペース管理者のみが管理できます",
"select_row": "{{issue}}、{{agent}} を選択",
- "select_page": "このページの有効な項目を選択",
+ "select_page": "有効な項目をすべて選択",
"load_error": "読み込めませんでした",
"loading": "読み込み中…",
"empty": "ルールはまだありません",
- "selected": "{{count}} 件選択中",
"disable_selected": "選択項目を無効化",
- "clear": "選択を解除",
- "results": "{{page}} ページ · {{count}} 件",
- "previous": "前へ",
- "next_page": "次へ",
"confirm_title": "{{count}} 件を無効にしますか?",
"confirm_body": "今後の起動を停止し、エージェントに渡されていない待機中の実行を取り消します。割り当て済みの実行は継続します。実行ログから停止できます。",
"cancel": "キャンセル",
@@ -506,7 +494,7 @@
"batch_result": "無効化:{{succeeded}} 件。失敗:{{failed}} 件。",
"scopes": {
"active": "起動待ち・実行中",
- "all": "すべて",
+ "all": "すべてのウェイクアップ",
"disabled": "無効",
"ended": "終了",
"paused": "一時停止中"
@@ -518,7 +506,7 @@
"batch_partial": "{{succeeded}} 件を無効化、{{failed}} 件が失敗しました。失敗した項目を選択したまま再試行できます。",
"source": "作成元",
"sources": {
- "all": "作成元:すべて",
+ "all": "すべての作成元",
"member": "メンバー",
"agent": "エージェント",
"system": "システム"
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index e065acad00..d284a588a7 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -243,7 +243,6 @@
"row_actions_aria": "チャットの操作"
},
"header": {
- "view_profile": "Agent のプロフィール",
"rename": "名前を変更",
"delete": "チャットを削除",
"archive": "チャットをアーカイブ",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 5c5f706f96..d125612159 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -155,6 +155,7 @@
},
"filters": {
"tooltip": "フィルター",
+ "active_section": "適用中",
"placeholder": "フィルター...",
"search_status": "ステータスを検索...",
"no_results": "結果なし",
@@ -171,6 +172,15 @@
"section_project": "プロジェクト",
"section_project_status": "プロジェクトステータス",
"section_label": "ラベル",
+ "section_relation": "自分との関係",
+ "relation_assigned": "自分が担当",
+ "relation_created": "自分が作成",
+ "relation_my_agents": "自分のエージェントが担当",
+ "operator_label": "条件",
+ "operator_is": "一致",
+ "operator_is_not": "除外",
+ "modified_hint": "保存済みビューから変更あり",
+ "unsaved_changes_other": "未保存の変更 {{count}} 件",
"section_date": "日付",
"date_field": "項目",
"date_field_created": "作成",
@@ -194,7 +204,54 @@
"active_count_other": "フィルター {{count}} 件",
"in_view": "このビューに含まれています",
"chip_edit": "編集",
- "chip_save_as": "別名で保存"
+ "chip_save_as": "別名で保存",
+ "section_due_date": "期限",
+ "due_overdue": "期限切れ",
+ "due_today": "今日が期限",
+ "due_this_week": "今週が期限",
+ "due_next_7_days": "7 日以内が期限",
+ "due_none": "期限なし",
+ "search_placeholder": "フィールドまたは値で絞り込み…",
+ "search_fields": "フィールド",
+ "search_values": "値",
+ "advanced_switch": "高度なフィルターに切り替え",
+ "advanced_title": "高度なフィルター",
+ "advanced_match_leading": "次の条件の",
+ "advanced_match_trailing": "に一致",
+ "match_all": "すべて",
+ "match_any": "いずれか",
+ "advanced_where": "条件",
+ "advanced_and": "かつ",
+ "advanced_or": "または",
+ "advanced_add_condition": "条件を追加",
+ "advanced_add_group": "条件グループを追加",
+ "advanced_unknown_property": "削除されたプロパティ",
+ "advanced_values_placeholder": "値を選択…",
+ "advanced_field_label": "フィールド",
+ "advanced_values_label": "値",
+ "advanced_actions": "条件の操作",
+ "advanced_duplicate": "複製",
+ "advanced_delete": "削除",
+ "advanced_delete_group": "グループを削除",
+ "advanced_to_simple": "シンプルフィルターに切り替え",
+ "advanced_to_simple_blocked": "グループ、「いずれか」、同じフィールドの重複はシンプルフィルターで表現できません",
+ "advanced_clear": "すべてクリア",
+ "advanced_empty": "条件はまだありません。条件を追加して絞り込みます。",
+ "advanced_conditions_other": "{{count}} 件の条件",
+ "operator_has_any": "いずれかを含む",
+ "operator_has_none": "いずれも含まない",
+ "operator_contains": "を含む",
+ "operator_not_contains": "を含まない",
+ "operator_before": "より前",
+ "operator_after": "より後",
+ "operator_empty": "空",
+ "operator_not_empty": "空ではない",
+ "advanced_group_match_leading": "このグループの",
+ "advanced_group_match_trailing": "に一致",
+ "advanced_group_hint": "このグループの条件は「{{word}}」でつながります",
+ "advanced_add_to_group": "グループに追加",
+ "advanced_turn_into_group": "グループに変換",
+ "advanced_summary": "条件:{{summary}}"
},
"display": {
"tooltip": "表示設定",
@@ -204,6 +261,7 @@
"card_properties_section": "カードのプロパティ",
"columns_section": "列",
"columns_locked_by_filter": "列を表示・非表示にするには、ステータスの絞り込みを解除してください。",
+ "columns_shown": "{{count}} 列を表示",
"ascending_title": "昇順",
"descending_title": "降順",
"newest_first": "新しい順",
@@ -236,7 +294,8 @@
"card_project": "プロジェクト",
"card_labels": "ラベル",
"card_child_progress": "サブタスクの進捗",
- "show_sub_issues": "サブタスクを表示"
+ "show_sub_issues": "サブタスクを表示",
+ "layout_options": "{{layout}}のオプション"
},
"view": {
"tooltip_board": "ボード表示",
@@ -384,7 +443,6 @@
"metadata_restore": "ダイアログのサイズを戻す",
"metadata_copy_failed": "メタデータをコピーできませんでした",
"metadata_description": "エージェントや連携機能がワークフローを引き継ぐために記録するキーと値のデータ。",
-
"section_load_failed_retry": "読み込めませんでした。再試行",
"not_found": "このタスクはこのワークスペースに存在しないか、削除されています。",
"breadcrumb_project_unknown": "不明なプロジェクト",
@@ -957,38 +1015,6 @@
"row_todo_hint": "エージェントを開始します"
},
"save_view": {
- "title": "ビューとして保存",
- "hint_workspace": "ワークスペースの全タスクをもとに作成",
- "hint_my_any": "「マイタスク · すべて」をもとに作成",
- "hint_my_assigned": "「マイタスク · 自分に割り当て」をもとに作成",
- "hint_my_created": "「マイタスク · 自分が作成」をもとに作成",
- "hint_my_involved": "「マイタスク · 関与中」をもとに作成",
- "hint_project": "プロジェクト「{{title}}」をもとに作成(そのプロジェクトページでのみ利用可能)",
- "hint_project_agents": "プロジェクト「{{title}}」のエージェントが担当するタスクをもとに作成(そのプロジェクトページでのみ利用可能)",
- "hint_project_members": "プロジェクト「{{title}}」のメンバーが担当するタスクをもとに作成(そのプロジェクトページでのみ利用可能)",
- "my_private_note": "マイタスクのビューは自分にのみ表示されます",
- "name_label": "名前",
- "visibility_label": "公開範囲",
- "visibility_private": "自分のみ",
- "visibility_workspace": "ワークスペースのメンバーに表示",
- "filters_label": "フィルター",
- "custom_property": "カスタムプロパティ",
- "create": "ビューを作成",
- "layout_label": "レイアウト",
- "display_defaults": "デフォルト表示",
- "default_hint": "メンバーが最初にこのビューを開いたときの表示。以降は各自で調整できます",
- "add_filter": "フィルターを追加",
- "name_placeholder": "例:レビュー待ち",
- "cancel": "キャンセル",
- "name_required": "ビュー名を入力してください",
- "toast_created": "ビューを作成しました",
- "toast_failed": "ビューの作成に失敗しました",
- "edit_title": "ビューを編集",
- "update": "変更を保存",
- "toast_updated": "ビューを更新しました",
- "toast_conflict": "他のユーザーがこのビューを編集しました。開き直してから再試行してください",
- "hint_workspace_members": "メンバーが担当するワークスペースのタスクをもとに作成",
- "hint_workspace_agents": "エージェントが担当するワークスペースのタスクをもとに作成",
"scope_label_workspace": "担当者タイプ",
"scope_label_my": "自分との関係",
"variant_all": "担当者を問わない",
@@ -999,36 +1025,6 @@
"variant_my_created": "自分が作成",
"variant_my_involved": "関与中"
},
- "view_selector": {
- "trigger": "ビュー",
- "empty": "保存されたビューはまだありません",
- "private_group": "プライベート",
- "shared_group": "ワークスペース共有",
- "exit": "ビューを終了",
- "unavailable": "このビューは利用できなくなりました",
- "edit": "ビューを編集"
- },
- "view_bar": {
- "menu_label": "ビュー",
- "menu_new": "新規ビュー",
- "builtin_tag": "組み込み",
- "drag_handle": "ドラッグで並べ替え",
- "delete": "削除",
- "delete_title": "ビューを削除しますか?",
- "delete_description": "「{{name}}」は閲覧できる全メンバーから削除されます",
- "toast_deleted": "ビューを削除しました",
- "context_edit": "ビューを編集",
- "context_pin": "サイドバーに固定",
- "context_unpin": "サイドバーから固定解除",
- "row_menu": "その他の操作",
- "row_hide": "バーから隠す",
- "row_show": "バーに表示",
- "menu_manage": "ビューを管理",
- "manage_title": "ビューを管理",
- "manage_hint": "並び順と表示設定は自分にのみ適用されます",
- "visible_toggle": "ビューバーに表示",
- "more_label": "その他のビュー"
- },
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} のインターフェースを読み込めませんでした。",
@@ -1709,5 +1705,67 @@
},
"hover_card": {
"created_updated": "{{created}}に作成 · {{updated}}に更新"
+ },
+ "views": {
+ "builtin": {
+ "my_issues": "マイタスク",
+ "my_agents": "マイエージェントの作業",
+ "all_issues": "すべてのタスク"
+ },
+ "untitled": "無題のビュー",
+ "copy_name": "{{name}}(コピー)",
+ "rename": "名前を変更",
+ "duplicate": "複製",
+ "copy_link": "リンクをコピー",
+ "link_copied": "リンクをコピーしました",
+ "visible_to": "公開範囲",
+ "only_me": "自分のみ",
+ "workspace_members": "ワークスペースのメンバー",
+ "add_to_sidebar": "サイドバーに追加",
+ "remove_from_sidebar": "サイドバーから削除",
+ "back_to": "{{name}} に戻る",
+ "delete": "ビューを削除",
+ "delete_title": "ビューを削除しますか?",
+ "delete_description": "「{{name}}」を削除します。この操作は元に戻せません。",
+ "delete_description_shared": "「{{name}}」はワークスペースで共有されているため、全員から削除されます。",
+ "cancel": "キャンセル",
+ "toast_deleted": "ビューを削除しました",
+ "toast_delete_failed": "ビューを削除できませんでした",
+ "filter": "フィルター",
+ "filter_count_other": "{{count}} 件のフィルター",
+ "reset": "リセット",
+ "save": "保存",
+ "save_options": "その他の保存オプション",
+ "save_to": "「{{name}}」に保存",
+ "save_to_hint_shared": "ワークスペース全員のビューを更新します",
+ "save_to_hint_private": "自分のビューを更新します",
+ "save_as_new": "新しいビューとして保存",
+ "save_as_new_hint": "「{{name}}」は変更されません",
+ "save_as_view": "ビューとして保存",
+ "set_by_view": "このビューで設定",
+ "new_issue": "新規タスク",
+ "unavailable": "このビューは利用できなくなりました",
+ "toast_saved": "ビューを保存しました",
+ "toast_conflict": "他のユーザーがこのビューを変更しました。再読み込みしてもう一度お試しください",
+ "toast_create_failed": "ビューを作成できませんでした",
+ "toast_save_failed": "ビューを保存できませんでした",
+ "directory": {
+ "new_view": "新規ビュー",
+ "scope_all": "すべてのビュー",
+ "scope_builtin": "組み込み",
+ "scope_mine": "自分が作成",
+ "scope_shared": "共有",
+ "col_name": "名前",
+ "col_location": "場所",
+ "col_filters": "フィルター",
+ "col_visibility": "公開範囲",
+ "col_owner": "作成者",
+ "owner_builtin": "組み込み",
+ "location_project": "プロジェクト",
+ "star": "{{name}} をサイドバーに追加",
+ "unstar": "{{name}} をサイドバーから削除",
+ "row_actions": "{{name}} の操作",
+ "no_matches": "一致するビューはありません"
+ }
}
}
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index 2b566c01df..541485e457 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -11,7 +11,8 @@
"usage": "分析",
"runtimes": "ランタイム",
"skills": "スキル",
- "settings": "設定"
+ "settings": "設定",
+ "views": "ビュー"
},
"tab": {
"issue": "タスク",
@@ -25,6 +26,7 @@
"runtime": "ランタイム",
"attachment": "添付ファイル",
"create_agent": "エージェントを作成",
+ "my_agents": "マイエージェントの作業",
"unknown": "不明なページ"
},
"help": {
@@ -57,16 +59,114 @@
"invitation_decline": "辞退",
"log_out": "ログアウト",
"new_issue": "新規タスク",
- "new_issue_shortcut": "C",
"pinned_label": "ピン留め済み",
- "work_group": "仕事",
- "ai_team_group": "AI チーム",
"show_more_pins": "さらに {{count}} 件を表示…",
- "show_fewer_pins": "表示を減らす",
- "unread_overflow": "99+",
- "discord_card": {
- "title": "Discord に参加",
- "dismiss": "閉じる"
+ "show_fewer_pins": "表示を減らす"
+ },
+ "spaces": {
+ "work": "タスク",
+ "team": "チーム"
+ },
+ "rail": {
+ "label": "アプリナビゲーション",
+ "sheet_description": "スペースとワークスペースを切り替えます。",
+ "inbox": "受信箱",
+ "work": "タスク",
+ "team": "チーム",
+ "chat": "チャット",
+ "autopilots": "自動化",
+ "switch_workspace": "ワークスペースを切り替え",
+ "invitation_from": "{{name}} さんから招待されています"
+ },
+ "panels": {
+ "work": {
+ "my_agents": "マイエージェントの作業",
+ "all_issues": "すべてのタスク",
+ "views": "ビュー",
+ "new_project": "新規プロジェクト",
+ "new_issue_in_project": "{{name}} に新規タスク",
+ "all_projects_other": "すべてのプロジェクト({{count}})",
+ "project_issues": "{{name}} のタスク",
+ "project_issues_empty": "タスクはありません",
+ "project_issues_error": "タスクを読み込めませんでした",
+ "project_issues_settings": "プロジェクトのタスク",
+ "settings_status": "ステータス",
+ "settings_assignee": "担当者",
+ "assignee_anyone": "全員",
+ "assignee_me": "自分",
+ "assignee_my_agents": "自分のエージェント",
+ "reset": "リセット",
+ "load_more": "さらに表示",
+ "show_less": "表示を減らす",
+ "projects_settings": "プロジェクトの表示",
+ "projects_ordering": "並び順",
+ "projects_order_manual": "手動",
+ "projects_order_name": "名前",
+ "projects_order_updated": "最近更新",
+ "projects_order_created": "最近作成",
+ "projects_show": "表示",
+ "projects_only_mine": "自分がリードするプロジェクトのみ",
+ "projects_show_count": "未完了タスク数",
+ "new_view": "新規ビュー",
+ "all_views": "すべてのビュー",
+ "view_actions": "{{name}} の操作",
+ "view_copy_link": "リンクをコピー",
+ "view_remove": "サイドバーから削除",
+ "view_rename": "名前を変更",
+ "view_duplicate": "複製",
+ "view_delete": "ビューを削除"
+ },
+ "team": {
+ "new_agent": "新規エージェント",
+ "needs_attention": "要対応",
+ "stuck_other": "{{count}} 件のタスクがオフラインのランタイムを待機中",
+ "working_now": "作業中",
+ "running_tasks_other": "{{count}} 件のタスクを実行中",
+ "all_agents": "すべてのエージェント",
+ "my_agents": "マイエージェント",
+ "squads_and_members": "スクワッドとメンバー",
+ "members_other": "メンバー {{count}} 人",
+ "resources": "リソース",
+ "runtimes_offline_other": "{{count}} 件オフライン",
+ "invite_member": "メンバーを招待"
+ },
+ "autopilots": {
+ "all": "すべてのオートパイロット",
+ "list": "オートパイロット",
+ "templates": "テンプレートから"
}
+ },
+ "account": {
+ "trigger": "アカウント",
+ "profile": "プロフィール",
+ "theme": "テーマ",
+ "themes": {
+ "light": "ライト",
+ "dark": "ダーク",
+ "system": "システム"
+ },
+ "language": "言語",
+ "shortcuts": "キーボードショートカット"
+ },
+ "collection": {
+ "filter": "フィルター",
+ "filter_count_other": "{{count}} 件のフィルター",
+ "reset": "リセット",
+ "display": "表示設定",
+ "selected_other": "{{count}} 件選択中",
+ "clear_selection": "選択を解除",
+ "select_all": "すべて選択",
+ "select_row": "行を選択",
+ "row_actions": "行の操作",
+ "sort_by": "並び替え",
+ "direction_asc": "昇順",
+ "direction_desc": "降順",
+ "section_columns": "列",
+ "load_more": "さらに読み込む",
+ "loading_more": "読み込み中…"
+ },
+ "object_page": {
+ "toggle_panel": "右サイドバーを切り替え",
+ "properties": "プロパティ"
}
}
diff --git a/packages/views/locales/ja/members.json b/packages/views/locales/ja/members.json
index 124c591d2a..6ebbb9a062 100644
--- a/packages/views/locales/ja/members.json
+++ b/packages/views/locales/ja/members.json
@@ -11,8 +11,11 @@
"more_agents_other": "他 {{count}} 件のエージェント"
},
"detail": {
- "workspace_fallback": "ワークスペース",
"members_breadcrumb": "メンバー",
+ "role": "ロール",
+ "email": "メールアドレス",
+ "joined": "参加日",
+ "relation": "関係",
"breadcrumb_fallback": "メンバー",
"not_found_title": "メンバーが見つかりません",
"not_found_description": "このメンバーはワークスペースから退出した可能性があります。"
diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.json
index b4730e602e..f52ef87463 100644
--- a/packages/views/locales/ja/projects.json
+++ b/packages/views/locales/ja/projects.json
@@ -2,11 +2,13 @@
"page": {
"title": "プロジェクト",
"new_project": "新規プロジェクト",
+ "scope_all": "すべてのプロジェクト",
+ "scope_active": "進行中のプロジェクト",
+ "scope_closed": "終了したプロジェクト",
"empty": "プロジェクトはまだありません",
"create_first": "最初のプロジェクトを作成",
"view_compact": "コンパクト",
"view_comfortable": "ゆったり",
- "search_placeholder": "プロジェクトを検索...",
"no_search_results": "検索条件に一致する結果はありません",
"view_table": "テーブル",
"view_cards": "カード",
@@ -14,9 +16,7 @@
"pin": "サイドバーにピン留め",
"unpin": "ピン留め解除",
"delete": "削除",
- "no_matches": "該当するプロジェクトはありません",
- "selected_other": "{{count}} 件選択中",
- "clear_selection": "選択を解除"
+ "no_matches": "該当するプロジェクトはありません"
},
"table": {
"name": "名前",
@@ -167,18 +167,9 @@
"fallback_label": "プロジェクト"
},
"toolbar": {
- "result_count_title": "該当プロジェクト / すべてのプロジェクト",
- "filter_label": "フィルター",
- "filter_active_count_other": "{{count}} 件のフィルター",
- "clear_filters": "フィルターをクリア",
"section_status": "ステータス",
"section_priority": "優先度",
"section_lead": "リード",
- "display": "表示",
- "sort_by": "並び替え",
- "direction_asc": "昇順",
- "direction_desc": "降順",
- "section_columns": "列",
"view": "ビュー"
}
}
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index 2c2530fe6f..60c0b73c69 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -1,9 +1,7 @@
{
"page": {
"title": "ランタイム",
- "learn_more": "詳しく見る →",
"connect_remote": "マシンを追加",
- "search_placeholder": "検索…",
"scope_mine": "自分のもの",
"scope_all": "すべて",
"live": "ライブ",
@@ -25,7 +23,7 @@
"title": "ローカルランタイムを起動中…",
"hint": "ワークスペースに接続中..."
},
- "add": "追加",
+ "add": "ランタイムを追加",
"add_menu": {
"machines": "マシン",
"this_computer": "このコンピューター",
@@ -67,7 +65,7 @@
"no_matches": "一致するマシンやクラウドサービスはありません"
},
"filters": {
- "all": "すべて",
+ "all": "すべてのランタイム",
"online": "オンライン",
"offline": "オフライン"
}
@@ -93,7 +91,7 @@
"this_machine": "このデバイス",
"local_badge": "ローカル · このマシン",
"pending_custom_runtimes": "登録待ちのカスタムランタイム",
- "runtime_count_other": "ランタイム {{count}} 個",
+ "daemon_title": "デーモン",
"busy_count_other": "使用中 {{count}} 個",
"no_matches_title": "マシンなし",
"no_matches_hint": "現在の検索またはフィルターに一致するマシンがありません。",
@@ -158,13 +156,10 @@
"fact_owner": "所有者",
"fact_device": "デバイス",
"fact_runtime": "ランタイム",
- "technical_details": "技術的な詳細",
"fact_daemon_cli": "デーモン CLI",
"fact_daemon_id": "デーモン ID",
- "serving_title": "提供中",
- "serving_count_other": "エージェント {{count}} 個",
+ "usage_title": "使用量",
"no_agents": "まだこのランタイムに紐づいたエージェントがありません。",
- "diagnostics_title": "診断",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "公開範囲",
"visibility_label": {
diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.json
index ba5eb1639f..37b23d8f3f 100644
--- a/packages/views/locales/ja/skills.json
+++ b/packages/views/locales/ja/skills.json
@@ -1,12 +1,10 @@
{
"page": {
"title": "スキル",
- "learn_more": "詳しく見る →",
"new_skill": "新規スキル",
- "search_placeholder": "スキルを検索…",
"scopes": {
"all": {
- "label": "すべて",
+ "label": "すべてのスキル",
"description": "このワークスペースのすべてのスキル"
},
"used": {
@@ -18,7 +16,7 @@
"description": "どのエージェントにも割り当てられていないスキル"
},
"mine": {
- "label": "自分が作成",
+ "label": "マイスキル",
"description": "あなたが作成したスキル"
}
},
@@ -76,8 +74,6 @@
"added_toast": "{{name}} に追加しました",
"add_failed_toast": "スキルの追加に失敗しました",
"delete": "削除",
- "selected": "{{count}} 件選択中",
- "clear_selection": "選択を解除",
"delete_no_permission": "作成者または管理者のみ削除できるスキルが含まれています",
"delete_dialog_title_other": "{{count}} 件のスキルを削除しますか?",
"delete_dialog_desc_other": "選択した {{count}} 件のスキルを完全に削除し、すべてのエージェントから取り外します。",
@@ -98,28 +94,16 @@
"added_multi_toast_other": "{{count}} 件のエージェントに追加しました"
},
"toolbar": {
- "result_count_title": "該当スキル / 全スキル",
- "filter_label": "フィルター",
- "filter_active_count_other": "{{count}} 件のフィルター",
- "clear_filters": "フィルターを解除",
"section_usage": "使用状況",
"section_labels": "ラベル",
"filter_search_placeholder": "フィルター...",
"no_labels": "まだラベルがありません",
"no_results": "結果なし",
- "display": "表示",
- "sort_by": "並び替え",
- "direction_asc": "昇順",
- "direction_desc": "降順",
- "section_columns": "表示する列",
"manage_labels": "ラベルを管理...",
"manage_labels_title": "スキルのラベル"
},
"detail": {
- "all_skills": "すべてのスキル",
"read_only": "読み取り専用",
- "delete_aria": "スキルを削除",
- "delete_tooltip": "スキルを削除",
"supporting_data_warning": "一部のワークスペースデータを読み込めませんでした。次回の更新まで、作成者の表示、ランタイム名、編集権限が不完全に見える場合があります。",
"delete_file": "ファイルを削除",
"name_placeholder": "skill-name",
@@ -154,8 +138,6 @@
"toast_deleted": "スキルを削除しました",
"toast_delete_failed": "スキルを削除できませんでした",
"refresh": {
- "button": "更新",
- "tooltip": "ソースからスキルを再ダウンロードします",
"source_github": "GitHub",
"source_skills_sh": "Skills.sh",
"source_clawhub": "ClawHub",
@@ -194,29 +176,18 @@
}
},
"header": {
- "files_other": "{{count}} 個のファイル",
- "used_by_other": "{{count}} 個のエージェントが使用中",
- "updated": "{{when}}に更新",
- "updated_by": "{{name}} が{{when}}に更新"
- },
- "tabs": {
- "aria": "スキルのセクション",
- "overview": "概要",
- "files_other": "ファイル {{count}}"
+ "files_other": "{{count}} 個のファイル"
},
"overview": {
"properties": "プロパティ",
- "properties_hint": "これらの項目は SKILL.md のフロントマターと同期します。",
"name": "名前",
"description": "説明",
"description_hint": "エージェントはこれを基に skill を読み込むタイミングを判断します。",
"labels": "ラベル",
- "used_by_other": "{{count}} 個のエージェントが使用中",
"used_by_empty": "まだどのエージェントにも割り当てられていません。エージェントのスキルタブを開いて割り当ててください。",
"permissions_owner": "このスキルを編集・削除できます。変更は次回のエージェント実行から反映されます。",
"permissions_locked_creator": "作成者({{name}})またはワークスペース管理者のみがこのスキルを編集できます。",
"permissions_locked": "作成者またはワークスペース管理者のみがこのスキルを編集できます。",
- "properties_help": "skill のプロパティについて",
"character_count": "{{count}} 文字"
},
"files": {
@@ -229,6 +200,21 @@
"mode_preview": "プレビュー",
"mode_edit": "編集",
"mode_raw": "プレーンテキスト"
+ },
+ "sections": {
+ "content": "内容",
+ "files": "ファイル",
+ "edit": "編集",
+ "open": "開く",
+ "add": "追加"
+ },
+ "menu": {
+ "copy_link": "リンクをコピー",
+ "link_copied": "リンクをコピーしました",
+ "delete": "スキルを削除"
+ },
+ "panel": {
+ "add_description": "説明を追加"
}
},
"create": {
diff --git a/packages/views/locales/ja/squads.json b/packages/views/locales/ja/squads.json
index 971521b051..2985e3f1ed 100644
--- a/packages/views/locales/ja/squads.json
+++ b/packages/views/locales/ja/squads.json
@@ -15,10 +15,6 @@
"row_menu": "スカッドの操作",
"archive_action": "アーカイブ"
},
- "inspector": {
- "details_section": "詳細",
- "archive_button": "アーカイブ"
- },
"member_type": {
"agent": "エージェント",
"member": "メンバー"
@@ -65,15 +61,8 @@
"responsibility_placeholder": "このスクワッドの担当は何ですか?",
"save": "保存"
},
- "discard_changes_dialog": {
- "title": "保存していない変更を破棄しますか?",
- "description": "このタブに保存していない変更があります。タブを切り替えると変更は破棄されます。",
- "keep_editing": "編集を続ける",
- "discard_button": "破棄"
- },
"members_tab": {
"section_title": "メンバー",
- "section_count_other": "このスクワッドのメンバー {{count}}名",
"add_member_button": "メンバーを追加",
"create_agent_button": "エージェントを作成",
"leader_chip": "リーダー",
@@ -86,19 +75,29 @@
"status_unstable": "不安定",
"issue_status_blocked": "ブロック中",
"active_issue_more": "他 {{count}}件",
- "last_active_label": "最終アクティブ {{time}}",
"status_archived": "アーカイブ済み"
},
- "detail_tabs": {
- "members": "メンバー",
- "instructions": "指示"
+ "detail": {
+ "assign_work": "作業を割り当て",
+ "copy_link": "リンクをコピー",
+ "link_copied": "リンクをコピーしました",
+ "not_found": "スクワッドが見つかりません",
+ "instructions": "指示",
+ "edit": "編集",
+ "cancel": "キャンセル",
+ "recent_work": "最近の作業",
+ "recent_work_empty": "このスクワッドに割り当てられたタスクはまだありません。",
+ "member_menu": "{{name}} の操作",
+ "working_on": "作業中:"
},
"details": {
"leader": "リーダー",
"members": "メンバー",
"created_by": "作成者",
"created": "作成日時",
- "updated": "更新日時"
+ "updated": "更新日時",
+ "visibility": "公開範囲",
+ "visibility_workspace": "ワークスペース"
},
"toasts": {
"member_added": "メンバーを追加しました",
@@ -127,18 +126,8 @@
"placeholder": "例:必ず失敗するテストから始める。コミットは小さく独立させる。"
},
"scope": {
- "mine": "自分",
- "all": "すべて"
+ "mine": "自分のスクワッド",
+ "all": "すべてのスクワッド"
},
- "toolbar": {
- "display": "表示",
- "sort_by": "並び替え",
- "direction_asc": "昇順",
- "direction_desc": "降順",
- "section_columns": "列",
- "result_count_title": "該当スカッド / すべてのスカッド",
- "filter_label": "フィルター",
- "filter_active_count_other": "{{count}} 件のフィルター",
- "clear_filters": "フィルターをクリア"
- }
+ "toolbar": {}
}
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 48ca02cb2e..dc8c48fb64 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -1,19 +1,21 @@
{
"page": {
"title": "에이전트",
- "learn_more": "자세히 보기 →",
"new_agent": "새 에이전트",
- "search_placeholder": "에이전트 검색...",
"show_archived": "보관된 에이전트 보기 ({{count}}) →",
"of_total": "{{total}}개 중 {{visible}}개",
"list_load_failed": "에이전트 목록을 불러오지 못했습니다",
"list_load_failed_default": "에이전트 목록을 가져오는 중 문제가 발생했습니다.",
- "try_again": "다시 시도"
+ "try_again": "다시 시도",
+ "scope_title": {
+ "mine": "내 에이전트",
+ "all": "모든 에이전트",
+ "archived": "보관된 에이전트"
+ }
},
"scope": {
"mine": "내 것",
- "all": "전체",
- "archived": "보관됨"
+ "all": "전체"
},
"sort": {
"label_recent": "최근 활동",
@@ -47,10 +49,7 @@
},
"no_matches": {
"title": "일치하는 결과 없음",
- "search_archived": "\"{{query}}\"와 일치하는 보관된 에이전트가 없습니다.",
"no_archived": "아직 보관된 에이전트가 없습니다.",
- "search_active": "\"{{query}}\"와 일치하는 에이전트가 없습니다.",
- "search_active_filtered": "이 필터에서 \"{{query}}\"와 일치하는 에이전트가 없습니다.",
"no_filter_match": "이 필터와 일치하는 에이전트가 없습니다.",
"search_runtime_filtered": "\"{{machine}}\"에서 \"{{query}}\"와 일치하는 에이전트가 없습니다.",
"runtime_filtered": "\"{{machine}}\"에 에이전트가 없습니다."
@@ -127,7 +126,6 @@
"archive_dialog_confirm": "보관"
},
"detail": {
- "back_to_agents": "에이전트",
"back_to_agents_full": "에이전트로 돌아가기",
"not_found_title": "에이전트를 찾을 수 없습니다",
"not_found_default": "이 에이전트가 보관되었거나 삭제되었을 수 있습니다.",
@@ -156,7 +154,11 @@
"runtime_required_toast": "이 에이전트를 실행하기 전에 런타임을 연결하세요.",
"assign_work": "작업 할당",
"more_actions_aria": "에이전트 작업",
- "updated": "{{when}} 업데이트됨"
+ "advanced_settings": "고급 설정",
+ "copy_link": "링크 복사",
+ "copy_id": "에이전트 ID 복사",
+ "link_copied_toast": "링크를 복사했습니다",
+ "id_copied_toast": "에이전트 ID를 복사했습니다"
},
"inspector": {
"section_profile": "프로필",
@@ -166,7 +168,6 @@
"section_properties": "속성",
"section_details": "세부 정보",
"section_details_hint": "소유권과 수명 주기에 대한 읽기 전용 정보입니다.",
- "section_skills": "스킬",
"section_integrations": "연동",
"prop_runtime": "런타임",
"prop_model": "모델",
@@ -177,7 +178,6 @@
"prop_owner": "소유자",
"prop_created": "생성일",
"prop_updated": "수정일",
- "no_description_placeholder": "설명 없음",
"avatar_label": "아바타",
"name_label": "이름",
"description_label": "설명",
@@ -193,11 +193,24 @@
"cancel": "취소"
},
"overview": {
- "agent_context": "에이전트",
- "access": "접근 권한",
"attention_title": "확인이 필요한 실행",
"attention_queued_other": "런타임을 사용할 수 없어 {{count}}개의 실행이 대기 중입니다."
},
+ "sections": {
+ "runs_count_other": "실행 {{count}}개",
+ "recent_this_week_other": "이번 주 {{count}}개",
+ "view_all": "모두 보기",
+ "open": "열기",
+ "edit": "편집",
+ "add": "추가",
+ "manage": "관리",
+ "instructions_empty": "아직 지침이 없습니다."
+ },
+ "panel": {
+ "status": "상태",
+ "runs_7d": "실행 (7일)",
+ "edit_access_aria": "접근 권한: {{value}}. 접근 권한 변경"
+ },
"skill_attach": {
"trigger_aria": "워크스페이스 스킬 연결",
"trigger_label": "연결"
@@ -251,13 +264,11 @@
"clear_full": "선택 지우기(제공자 기본값 사용)"
},
"tabs": {
- "overview": "개요",
"work": "작업",
"capabilities": "기능",
"settings": "설정",
"general": "일반",
"access": "접근 권한",
- "page_navigation_aria": "에이전트 페이지",
"section_navigation_aria": "에이전트 섹션",
"activity": "활동",
"tasks": "실행",
@@ -626,12 +637,6 @@
"section_now": "현재",
"section_last_30d": "최근 30일",
"section_recent": "최근 작업",
- "subtitle_no_active": "활성 작업 없음",
- "subtitle_active_other": "활성 실행 {{count}}개",
- "subtitle_performance": "성과",
- "subtitle_no_recent": "아직 완료된 실행 없음",
- "subtitle_recent_progress": "{{total}}회 실행 중 {{shown}}회",
- "subtitle_recent_latest": "최근 {{count}}회 실행",
"empty_now": "이 에이전트는 지금 진행 중인 실행이 없습니다.",
"empty_30d": "최근 30일 동안 완료된 작업이 없습니다.",
"empty_recent": "이 에이전트는 아직 완료한 실행이 없습니다.",
@@ -642,9 +647,7 @@
"success_hint": "완료 및 실패한 실행 수 중 완료한 실행의 비율입니다. 취소한 실행은 제외됩니다.",
"success_unavailable": "이 기간에 완료하거나 실패한 실행이 없어 성공률을 계산할 수 없습니다.",
"cancelled_count": "{{count}}개 취소됨",
- "avg_duration": "평균 {{value}}",
"avg_duration_label": "평균 소요 시간",
- "failed_count": "{{count}}회 실패",
"failed_label": "실패",
"source_issue": "태스크",
"source_chat": "채팅",
@@ -868,18 +871,9 @@
"none": "30일간 활동 없음"
},
"toolbar": {
- "result_count_title": "일치하는 에이전트 / 범위 내 전체",
- "filter_label": "필터",
- "filter_active_count_other": "필터 {{count}}개",
- "clear_filters": "필터 지우기",
"section_availability": "가용성",
"section_access": "접근 권한",
"section_runtime": "런타임",
- "display": "표시",
- "sort_by": "정렬",
- "direction_asc": "오름차순",
- "direction_desc": "내림차순",
- "section_columns": "열",
"section_owner": "소유자",
"section_model": "모델"
},
@@ -887,7 +881,6 @@
"title": "에이전트 만들기",
"squad_title": "이 스쿼드용 에이전트 만들기",
"duplicate_title": "{{name}} 복제",
- "back": "뒤로",
"step_ai": "대화로 만들기",
"modes": {
"template": {
@@ -971,7 +964,8 @@
"runtime": "런타임 선택",
"configure": "구성",
"done": "완료",
- "aria": "에이전트 생성 단계"
+ "aria": "에이전트 생성 단계",
+ "progress": "{{total}}단계 중 {{current}}단계"
},
"configure_title": "에이전트 구성",
"ask_ai": "AI에게 작성 맡기기",
@@ -1032,8 +1026,5 @@
"next": "다음"
}
},
- "actions": {
- "selected_other": "{{count}}개 선택됨",
- "clear_selection": "선택 해제"
- }
+ "actions": {}
}
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index 2d683371ad..45bf050125 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -1,6 +1,5 @@
{
"page": {
- "title": "오토파일럿",
"new_autopilot": "새 오토파일럿",
"start_blank": "처음부터 시작",
"table": {
@@ -20,7 +19,6 @@
"title": "아직 오토파일럿이 없습니다",
"hint": "AI 에이전트의 반복 작업을 예약하세요. 템플릿을 고르거나 처음부터 시작할 수 있습니다."
},
- "scope_all": "전체",
"no_matches": "일치하는 자동화가 없습니다",
"retry": "다시 시도"
},
@@ -87,10 +85,8 @@
"run_blocked_quota_exceeded": "실행되지 않음 — 이 기간의 실행 한도에 도달했습니다",
"run_blocked_issue_limit_reached": "실행되지 않음 — 워크스페이스가 태스크 수 한도에 도달했습니다",
"run_blocked_generic": "실행되지 않음 — 실행이 차단되었습니다",
- "section_properties": "속성",
"section_triggers": "트리거",
"section_run_history": "실행 기록",
- "section_danger": "위험 영역",
"field_agent": "에이전트",
"field_created_by": "생성자",
"field_output_mode": "출력 모드",
@@ -100,6 +96,16 @@
"field_prompt": "프롬프트",
"field_subscribers": "구독자",
"field_subscribers_none": "없음",
+ "no_prompt": "아직 프롬프트가 없습니다.",
+ "copy_link": "링크 복사",
+ "link_copied": "링크를 복사했습니다",
+ "link_copy_failed": "링크를 복사하지 못했습니다",
+ "open_project": "프로젝트 열기",
+ "summary": {
+ "create_issue": "{{agent}}이(가) 실행할 때마다 태스크 생성",
+ "run_only": "{{agent}}이(가) 태스크 없이 실행",
+ "with_trigger": "{{trigger}} · {{action}}"
+ },
"add_trigger": "트리거 추가",
"no_triggers": "설정된 트리거가 없습니다. 자동으로 실행할 일정을 추가하세요.",
"no_runs": "아직 실행 기록이 없습니다. 수동으로 실행하려면 \"지금 실행\"을 클릭하세요.",
@@ -441,27 +447,16 @@
"search_placeholder": "시간대 검색..."
},
"toolbar": {
- "result_count_title": "일치하는 자동화 / 전체 자동화",
- "filter_label": "필터",
- "filter_active_count_other": "필터 {{count}}개",
- "clear_filters": "필터 지우기",
"section_assignee": "담당",
"section_mode": "모드",
"section_trigger": "트리거",
- "section_creator": "생성자",
- "display": "표시",
- "sort_by": "정렬",
- "direction_asc": "오름차순",
- "direction_desc": "내림차순",
- "section_columns": "열"
+ "section_creator": "생성자"
},
"actions": {
"row_menu": "자동화 작업",
"pause": "일시중지",
"resume": "재개",
"delete": "삭제",
- "selected_other": "{{count}}개 선택됨",
- "clear_selection": "선택 해제",
"delete_dialog": {
"title": "자동화를 삭제할까요?",
"description_other": "자동화 {{count}}개와 실행 기록이 영구 삭제됩니다.",
@@ -473,7 +468,6 @@
},
"wakeups": {
"title": "작업 깨우기",
- "scope": "범위",
"issue": "작업",
"trigger": "트리거",
"enabled": "활성화",
@@ -482,22 +476,16 @@
"at": "일회성",
"recurring": "반복",
"all_agents": "모든 에이전트",
- "search": "작업 또는 에이전트 검색",
"running": "실행 중",
"active_runs": "진행 중인 실행 {{count}}개",
"issue_closed": "종료된 작업",
"read_only": "생성자 또는 워크스페이스 관리자만 관리할 수 있습니다",
"select_row": "{{issue}}, {{agent}} 선택",
- "select_page": "이 페이지의 활성 항목 선택",
+ "select_page": "활성 항목 모두 선택",
"load_error": "깨우기를 불러오지 못했습니다",
"loading": "불러오는 중…",
"empty": "깨우기 규칙이 없습니다",
- "selected": "{{count}}개 선택됨",
"disable_selected": "선택 항목 끄기",
- "clear": "선택 해제",
- "results": "{{page}}페이지 · {{count}}개",
- "previous": "이전",
- "next_page": "다음",
"confirm_title": "깨우기 {{count}}개를 끄시겠습니까?",
"confirm_body": "이후 깨우기를 중지하고 아직 에이전트에게 전달되지 않은 대기 중 실행을 취소합니다. 전달된 실행은 계속되며 실행 로그에서 중지할 수 있습니다.",
"cancel": "취소",
@@ -506,7 +494,7 @@
"batch_result": "꺼짐: {{succeeded}}개. 실패: {{failed}}개.",
"scopes": {
"active": "깨우기 대기 또는 실행 중",
- "all": "전체",
+ "all": "모든 깨우기",
"disabled": "꺼짐",
"ended": "종료됨",
"paused": "일시중지됨"
@@ -518,7 +506,7 @@
"batch_partial": "{{succeeded}}개를 껐고 {{failed}}개는 실패했습니다. 실패 항목은 선택된 상태로 남아 다시 시도할 수 있습니다.",
"source": "만든 곳",
"sources": {
- "all": "만든 곳: 전체",
+ "all": "모든 출처",
"member": "멤버",
"agent": "에이전트",
"system": "시스템"
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 851ab8b4d0..c7574e8007 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -243,7 +243,6 @@
"row_actions_aria": "채팅 작업"
},
"header": {
- "view_profile": "Agent 프로필 보기",
"rename": "이름 변경",
"delete": "채팅 삭제",
"archive": "채팅 보관",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index be3a7b7e4f..00a8586ec2 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -155,6 +155,7 @@
},
"filters": {
"tooltip": "필터",
+ "active_section": "적용 중",
"placeholder": "필터...",
"search_status": "상태 검색...",
"no_results": "결과 없음",
@@ -171,6 +172,15 @@
"section_project": "프로젝트",
"section_project_status": "프로젝트 상태",
"section_label": "라벨",
+ "section_relation": "나와의 관계",
+ "relation_assigned": "내가 담당",
+ "relation_created": "내가 생성",
+ "relation_my_agents": "내 에이전트가 담당",
+ "operator_label": "조건",
+ "operator_is": "일치",
+ "operator_is_not": "제외",
+ "modified_hint": "저장된 뷰에서 변경됨",
+ "unsaved_changes_other": "저장되지 않은 변경 {{count}}개",
"section_date": "날짜",
"date_field": "필드",
"date_field_created": "생성",
@@ -194,7 +204,54 @@
"active_count_other": "필터 {{count}}개",
"in_view": "이미 이 뷰에 포함되어 있습니다",
"chip_edit": "편집",
- "chip_save_as": "다른 이름으로 저장"
+ "chip_save_as": "다른 이름으로 저장",
+ "section_due_date": "마감일",
+ "due_overdue": "기한 지남",
+ "due_today": "오늘 마감",
+ "due_this_week": "이번 주 마감",
+ "due_next_7_days": "7일 이내 마감",
+ "due_none": "마감일 없음",
+ "search_placeholder": "필드 또는 값으로 필터…",
+ "search_fields": "필드",
+ "search_values": "값",
+ "advanced_switch": "고급 필터로 전환",
+ "advanced_title": "고급 필터",
+ "advanced_match_leading": "다음 조건",
+ "advanced_match_trailing": "충족",
+ "match_all": "모두",
+ "match_any": "하나 이상",
+ "advanced_where": "조건",
+ "advanced_and": "그리고",
+ "advanced_or": "또는",
+ "advanced_add_condition": "조건 추가",
+ "advanced_add_group": "조건 그룹 추가",
+ "advanced_unknown_property": "삭제된 속성",
+ "advanced_values_placeholder": "값 선택…",
+ "advanced_field_label": "필드",
+ "advanced_values_label": "값",
+ "advanced_actions": "조건 작업",
+ "advanced_duplicate": "복제",
+ "advanced_delete": "삭제",
+ "advanced_delete_group": "그룹 삭제",
+ "advanced_to_simple": "간단 필터로 전환",
+ "advanced_to_simple_blocked": "그룹, '하나 이상', 같은 필드의 중복 사용은 간단 필터로 표현할 수 없습니다",
+ "advanced_clear": "모두 지우기",
+ "advanced_empty": "아직 조건이 없습니다. 조건을 추가해 필터링하세요.",
+ "advanced_conditions_other": "조건 {{count}}개",
+ "operator_has_any": "다음 중 하나 포함",
+ "operator_has_none": "모두 미포함",
+ "operator_contains": "포함",
+ "operator_not_contains": "미포함",
+ "operator_before": "이전",
+ "operator_after": "이후",
+ "operator_empty": "비어 있음",
+ "operator_not_empty": "비어 있지 않음",
+ "advanced_group_match_leading": "이 그룹 조건",
+ "advanced_group_match_trailing": "충족",
+ "advanced_group_hint": "이 그룹의 조건은 '{{word}}'(으)로 연결됩니다",
+ "advanced_add_to_group": "그룹에 추가",
+ "advanced_turn_into_group": "그룹으로 전환",
+ "advanced_summary": "조건: {{summary}}"
},
"display": {
"tooltip": "보기 설정",
@@ -204,6 +261,7 @@
"card_properties_section": "카드 속성",
"columns_section": "열",
"columns_locked_by_filter": "열을 표시하거나 숨기려면 상태 필터를 해제하세요.",
+ "columns_shown": "{{count}}개 표시",
"ascending_title": "오름차순",
"descending_title": "내림차순",
"newest_first": "최신순",
@@ -236,7 +294,8 @@
"card_project": "프로젝트",
"card_labels": "라벨",
"card_child_progress": "하위 태스크 진행률",
- "show_sub_issues": "하위 태스크 표시"
+ "show_sub_issues": "하위 태스크 표시",
+ "layout_options": "{{layout}} 옵션"
},
"view": {
"tooltip_board": "보드 보기",
@@ -384,7 +443,6 @@
"metadata_restore": "대화상자 크기 복원",
"metadata_copy_failed": "메타데이터를 복사하지 못했습니다",
"metadata_description": "에이전트와 연동 기능이 작업 흐름을 이어가기 위해 기록하는 키와 값 데이터입니다.",
-
"section_load_failed_retry": "불러오지 못했습니다. 다시 시도",
"not_found": "이 워크스페이스에 해당 태스크가 없거나 삭제되었습니다.",
"breadcrumb_project_unknown": "알 수 없는 프로젝트",
@@ -957,38 +1015,6 @@
"row_todo_hint": "에이전트 시작"
},
"save_view": {
- "title": "뷰로 저장",
- "hint_workspace": "워크스페이스 전체 태스크 기준으로 생성",
- "hint_my_any": "「내 태스크 · 전체」 기준으로 생성",
- "hint_my_assigned": "「내 태스크 · 나에게 할당됨」 기준으로 생성",
- "hint_my_created": "「내 태스크 · 내가 생성함」 기준으로 생성",
- "hint_my_involved": "「내 태스크 · 참여 중」 기준으로 생성",
- "hint_project": "프로젝트 「{{title}}」 기준으로 생성, 해당 프로젝트 페이지에서만 사용 가능",
- "hint_project_agents": "프로젝트 「{{title}}」에서 에이전트가 담당하는 태스크 기준으로 생성, 해당 프로젝트 페이지에서만 사용 가능",
- "hint_project_members": "프로젝트 「{{title}}」에서 구성원이 담당하는 태스크 기준으로 생성, 해당 프로젝트 페이지에서만 사용 가능",
- "my_private_note": "내 태스크 뷰는 본인에게만 표시됩니다",
- "name_label": "이름",
- "visibility_label": "공개 범위",
- "visibility_private": "나만 보기",
- "visibility_workspace": "워크스페이스 구성원에게 표시",
- "filters_label": "필터",
- "custom_property": "사용자 지정 속성",
- "create": "뷰 만들기",
- "layout_label": "레이아웃",
- "display_defaults": "기본 표시",
- "default_hint": "구성원이 이 뷰를 처음 열 때의 표시 방식이며, 이후 각자 조정할 수 있습니다",
- "add_filter": "필터 추가",
- "name_placeholder": "예: 리뷰 필요",
- "cancel": "취소",
- "name_required": "뷰 이름을 입력하세요",
- "toast_created": "뷰가 생성되었습니다",
- "toast_failed": "뷰 생성에 실패했습니다",
- "edit_title": "뷰 편집",
- "update": "변경 사항 저장",
- "toast_updated": "뷰가 업데이트되었습니다",
- "toast_conflict": "다른 사용자가 이 뷰를 편집했습니다. 다시 연 후 시도하세요",
- "hint_workspace_members": "구성원이 담당하는 워크스페이스 태스크 기준으로 생성",
- "hint_workspace_agents": "에이전트가 담당하는 워크스페이스 태스크 기준으로 생성",
"scope_label_workspace": "담당자 유형",
"scope_label_my": "나와의 관계",
"variant_all": "담당자 무관",
@@ -999,36 +1025,6 @@
"variant_my_created": "내가 생성함",
"variant_my_involved": "참여 중"
},
- "view_selector": {
- "trigger": "뷰",
- "empty": "저장된 뷰가 아직 없습니다",
- "private_group": "비공개",
- "shared_group": "워크스페이스 공유",
- "exit": "뷰 나가기",
- "unavailable": "이 뷰는 더 이상 사용할 수 없습니다",
- "edit": "뷰 편집"
- },
- "view_bar": {
- "menu_label": "뷰",
- "menu_new": "새 뷰",
- "builtin_tag": "기본 제공",
- "drag_handle": "드래그로 순서 변경",
- "delete": "삭제",
- "delete_title": "뷰를 삭제할까요?",
- "delete_description": "「{{name}}」이(가) 볼 수 있는 모든 구성원에게서 삭제됩니다",
- "toast_deleted": "뷰가 삭제되었습니다",
- "context_edit": "뷰 편집",
- "context_pin": "사이드바에 고정",
- "context_unpin": "사이드바 고정 해제",
- "row_menu": "추가 작업",
- "row_hide": "바에서 숨기기",
- "row_show": "바에 표시",
- "menu_manage": "뷰 관리",
- "manage_title": "뷰 관리",
- "manage_hint": "순서와 표시 설정은 본인에게만 적용됩니다",
- "visible_toggle": "뷰 바에 표시",
- "more_label": "더 많은 뷰"
- },
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}}의 인터페이스를 불러오지 못했습니다.",
@@ -1709,5 +1705,67 @@
},
"hover_card": {
"created_updated": "{{created}} 생성 · {{updated}} 수정됨"
+ },
+ "views": {
+ "builtin": {
+ "my_issues": "내 태스크",
+ "my_agents": "내 에이전트의 작업",
+ "all_issues": "전체 태스크"
+ },
+ "untitled": "제목 없는 뷰",
+ "copy_name": "{{name}} (사본)",
+ "rename": "이름 변경",
+ "duplicate": "복제",
+ "copy_link": "링크 복사",
+ "link_copied": "링크를 복사했습니다",
+ "visible_to": "공개 범위",
+ "only_me": "나만 보기",
+ "workspace_members": "워크스페이스 멤버",
+ "add_to_sidebar": "사이드바에 추가",
+ "remove_from_sidebar": "사이드바에서 제거",
+ "back_to": "{{name}}(으)로 돌아가기",
+ "delete": "뷰 삭제",
+ "delete_title": "뷰를 삭제할까요?",
+ "delete_description": "「{{name}}」이(가) 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
+ "delete_description_shared": "「{{name}}」은(는) 워크스페이스에 공유되어 있어 모든 사람에게서 삭제됩니다.",
+ "cancel": "취소",
+ "toast_deleted": "뷰가 삭제되었습니다",
+ "toast_delete_failed": "뷰를 삭제하지 못했습니다",
+ "filter": "필터",
+ "filter_count_other": "필터 {{count}}개",
+ "reset": "초기화",
+ "save": "저장",
+ "save_options": "추가 저장 옵션",
+ "save_to": "「{{name}}」에 저장",
+ "save_to_hint_shared": "워크스페이스 전체의 뷰를 업데이트합니다",
+ "save_to_hint_private": "내 뷰를 업데이트합니다",
+ "save_as_new": "새 뷰로 저장",
+ "save_as_new_hint": "「{{name}}」은(는) 그대로 유지됩니다",
+ "save_as_view": "뷰로 저장",
+ "set_by_view": "이 뷰에서 설정됨",
+ "new_issue": "새 태스크",
+ "unavailable": "이 뷰는 더 이상 사용할 수 없습니다",
+ "toast_saved": "뷰가 저장되었습니다",
+ "toast_conflict": "다른 사용자가 이 뷰를 변경했습니다. 새로고침한 후 다시 시도하세요",
+ "toast_create_failed": "뷰를 만들지 못했습니다",
+ "toast_save_failed": "뷰를 저장하지 못했습니다",
+ "directory": {
+ "new_view": "새 뷰",
+ "scope_all": "모든 뷰",
+ "scope_builtin": "기본 제공",
+ "scope_mine": "내가 만든 뷰",
+ "scope_shared": "공유됨",
+ "col_name": "이름",
+ "col_location": "위치",
+ "col_filters": "필터",
+ "col_visibility": "공개 범위",
+ "col_owner": "소유자",
+ "owner_builtin": "기본 제공",
+ "location_project": "프로젝트",
+ "star": "{{name}}을(를) 사이드바에 추가",
+ "unstar": "{{name}}을(를) 사이드바에서 제거",
+ "row_actions": "{{name}} 작업",
+ "no_matches": "일치하는 뷰가 없습니다"
+ }
}
}
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index a277f707f1..274dbbdbd0 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -11,7 +11,8 @@
"usage": "분석",
"runtimes": "런타임",
"skills": "스킬",
- "settings": "설정"
+ "settings": "설정",
+ "views": "뷰"
},
"tab": {
"issue": "태스크",
@@ -25,6 +26,7 @@
"runtime": "런타임",
"attachment": "첨부파일",
"create_agent": "에이전트 만들기",
+ "my_agents": "내 에이전트의 작업",
"unknown": "알 수 없는 페이지"
},
"help": {
@@ -57,16 +59,114 @@
"invitation_decline": "거절",
"log_out": "로그아웃",
"new_issue": "새 태스크",
- "new_issue_shortcut": "C",
"pinned_label": "고정됨",
- "work_group": "업무",
- "ai_team_group": "AI 팀",
"show_more_pins": "{{count}}개 더 보기…",
- "show_fewer_pins": "접기",
- "unread_overflow": "99+",
- "discord_card": {
- "title": "Discord 참여하기",
- "dismiss": "닫기"
+ "show_fewer_pins": "접기"
+ },
+ "spaces": {
+ "work": "태스크",
+ "team": "팀"
+ },
+ "rail": {
+ "label": "앱 탐색",
+ "sheet_description": "스페이스와 워크스페이스를 전환합니다.",
+ "inbox": "인박스",
+ "work": "태스크",
+ "team": "팀",
+ "chat": "채팅",
+ "autopilots": "자동화",
+ "switch_workspace": "워크스페이스 전환",
+ "invitation_from": "{{name}} 님이 초대했습니다"
+ },
+ "panels": {
+ "work": {
+ "my_agents": "내 에이전트의 작업",
+ "all_issues": "전체 태스크",
+ "views": "뷰",
+ "new_project": "새 프로젝트",
+ "new_issue_in_project": "{{name}}에 새 태스크",
+ "all_projects_other": "전체 프로젝트 {{count}}개",
+ "project_issues": "{{name}}의 태스크",
+ "project_issues_empty": "태스크가 없습니다",
+ "project_issues_error": "태스크를 불러오지 못했습니다",
+ "project_issues_settings": "프로젝트 태스크",
+ "settings_status": "상태",
+ "settings_assignee": "담당자",
+ "assignee_anyone": "모두",
+ "assignee_me": "나",
+ "assignee_my_agents": "내 에이전트",
+ "reset": "초기화",
+ "load_more": "더 보기",
+ "show_less": "간단히 보기",
+ "projects_settings": "프로젝트 표시",
+ "projects_ordering": "정렬",
+ "projects_order_manual": "수동",
+ "projects_order_name": "이름",
+ "projects_order_updated": "최근 업데이트",
+ "projects_order_created": "최근 생성",
+ "projects_show": "표시",
+ "projects_only_mine": "내가 리드하는 프로젝트만",
+ "projects_show_count": "미완료 태스크 수",
+ "new_view": "새 뷰",
+ "all_views": "모든 뷰",
+ "view_actions": "{{name}} 작업",
+ "view_copy_link": "링크 복사",
+ "view_remove": "사이드바에서 제거",
+ "view_rename": "이름 변경",
+ "view_duplicate": "복제",
+ "view_delete": "뷰 삭제"
+ },
+ "team": {
+ "new_agent": "새 에이전트",
+ "needs_attention": "확인 필요",
+ "stuck_other": "태스크 {{count}}개가 오프라인 런타임을 기다리는 중",
+ "working_now": "작업 중",
+ "running_tasks_other": "태스크 {{count}}개 실행 중",
+ "all_agents": "전체 에이전트",
+ "my_agents": "내 에이전트",
+ "squads_and_members": "스쿼드 및 멤버",
+ "members_other": "멤버 {{count}}명",
+ "resources": "리소스",
+ "runtimes_offline_other": "{{count}}개 오프라인",
+ "invite_member": "멤버 초대"
+ },
+ "autopilots": {
+ "all": "전체 오토파일럿",
+ "list": "오토파일럿",
+ "templates": "템플릿으로 시작"
}
+ },
+ "account": {
+ "trigger": "계정",
+ "profile": "프로필",
+ "theme": "테마",
+ "themes": {
+ "light": "라이트",
+ "dark": "다크",
+ "system": "시스템"
+ },
+ "language": "언어",
+ "shortcuts": "키보드 단축키"
+ },
+ "collection": {
+ "filter": "필터",
+ "filter_count_other": "필터 {{count}}개",
+ "reset": "초기화",
+ "display": "표시 설정",
+ "selected_other": "{{count}}개 선택됨",
+ "clear_selection": "선택 해제",
+ "select_all": "모두 선택",
+ "select_row": "행 선택",
+ "row_actions": "행 작업",
+ "sort_by": "정렬",
+ "direction_asc": "오름차순",
+ "direction_desc": "내림차순",
+ "section_columns": "열",
+ "load_more": "더 불러오기",
+ "loading_more": "불러오는 중…"
+ },
+ "object_page": {
+ "toggle_panel": "오른쪽 사이드바 전환",
+ "properties": "속성"
}
}
diff --git a/packages/views/locales/ko/members.json b/packages/views/locales/ko/members.json
index 43b4360695..607a307321 100644
--- a/packages/views/locales/ko/members.json
+++ b/packages/views/locales/ko/members.json
@@ -11,8 +11,11 @@
"more_agents_other": "외 에이전트 {{count}}개"
},
"detail": {
- "workspace_fallback": "워크스페이스",
"members_breadcrumb": "멤버",
+ "role": "역할",
+ "email": "이메일",
+ "joined": "참여일",
+ "relation": "관계",
"breadcrumb_fallback": "멤버",
"not_found_title": "멤버를 찾을 수 없습니다",
"not_found_description": "이 멤버가 워크스페이스를 떠났을 수 있습니다."
diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.json
index acc2801578..ce213be686 100644
--- a/packages/views/locales/ko/projects.json
+++ b/packages/views/locales/ko/projects.json
@@ -2,11 +2,13 @@
"page": {
"title": "프로젝트",
"new_project": "새 프로젝트",
+ "scope_all": "전체 프로젝트",
+ "scope_active": "진행 중인 프로젝트",
+ "scope_closed": "종료된 프로젝트",
"empty": "아직 프로젝트가 없습니다",
"create_first": "첫 프로젝트 만들기",
"view_compact": "간결하게",
"view_comfortable": "넓게",
- "search_placeholder": "프로젝트 검색...",
"no_search_results": "검색 결과가 없습니다",
"view_table": "테이블",
"view_cards": "카드",
@@ -14,9 +16,7 @@
"pin": "사이드바에 고정",
"unpin": "고정 해제",
"delete": "삭제",
- "no_matches": "일치하는 프로젝트가 없습니다",
- "selected_other": "{{count}}개 선택됨",
- "clear_selection": "선택 해제"
+ "no_matches": "일치하는 프로젝트가 없습니다"
},
"table": {
"name": "이름",
@@ -167,18 +167,9 @@
"fallback_label": "프로젝트"
},
"toolbar": {
- "result_count_title": "일치하는 프로젝트 / 전체 프로젝트",
- "filter_label": "필터",
- "filter_active_count_other": "필터 {{count}}개",
- "clear_filters": "필터 지우기",
"section_status": "상태",
"section_priority": "우선순위",
"section_lead": "리드",
- "display": "표시",
- "sort_by": "정렬",
- "direction_asc": "오름차순",
- "direction_desc": "내림차순",
- "section_columns": "열",
"view": "보기"
}
}
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index 066b8e497c..8da5efc9df 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -1,9 +1,7 @@
{
"page": {
"title": "런타임",
- "learn_more": "자세히 보기 →",
"connect_remote": "머신 추가",
- "search_placeholder": "검색…",
"scope_mine": "내 것",
"scope_all": "전체",
"live": "실시간",
@@ -25,7 +23,7 @@
"title": "로컬 런타임 시작 중...",
"hint": "워크스페이스에 연결 중..."
},
- "add": "추가",
+ "add": "런타임 추가",
"add_menu": {
"machines": "머신",
"this_computer": "이 컴퓨터",
@@ -67,7 +65,7 @@
"no_matches": "일치하는 머신 또는 클라우드 서비스가 없습니다"
},
"filters": {
- "all": "전체",
+ "all": "모든 런타임",
"online": "온라인",
"offline": "오프라인"
}
@@ -93,7 +91,7 @@
"this_machine": "이 Mac",
"local_badge": "로컬 · 이 기기",
"pending_custom_runtimes": "등록 대기 중인 사용자 지정 런타임",
- "runtime_count_other": "런타임 {{count}}개",
+ "daemon_title": "데몬",
"busy_count_other": "사용 중 {{count}}개",
"no_matches_title": "기기 없음",
"no_matches_hint": "현재 검색 또는 필터와 일치하는 기기가 없습니다.",
@@ -158,13 +156,10 @@
"fact_owner": "소유자",
"fact_device": "기기",
"fact_runtime": "런타임",
- "technical_details": "기술 세부 정보",
"fact_daemon_cli": "데몬 CLI",
"fact_daemon_id": "데몬 ID",
- "serving_title": "제공 중",
- "serving_count_other": "에이전트 {{count}}개",
+ "usage_title": "사용량",
"no_agents": "아직 이 런타임에 연결된 에이전트가 없습니다.",
- "diagnostics_title": "진단",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "공개 범위",
"visibility_label": {
diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.json
index 3c9fcbca25..7d1508cf50 100644
--- a/packages/views/locales/ko/skills.json
+++ b/packages/views/locales/ko/skills.json
@@ -1,12 +1,10 @@
{
"page": {
"title": "스킬",
- "learn_more": "자세히 보기 →",
"new_skill": "새 스킬",
- "search_placeholder": "스킬 검색...",
"scopes": {
"all": {
- "label": "전체",
+ "label": "모든 스킬",
"description": "이 워크스페이스의 모든 스킬"
},
"used": {
@@ -18,7 +16,7 @@
"description": "어떤 에이전트에도 할당되지 않은 스킬"
},
"mine": {
- "label": "내가 만든 스킬",
+ "label": "내 스킬",
"description": "내가 생성한 스킬"
}
},
@@ -76,8 +74,6 @@
"added_toast": "{{name}}에 추가했습니다",
"add_failed_toast": "스킬 추가에 실패했습니다",
"delete": "삭제",
- "selected": "{{count}}개 선택됨",
- "clear_selection": "선택 해제",
"delete_no_permission": "작성자 또는 관리자만 삭제할 수 있는 스킬이 포함되어 있습니다",
"delete_dialog_title_other": "스킬 {{count}}개를 삭제할까요?",
"delete_dialog_desc_other": "선택한 스킬 {{count}}개를 영구 삭제하고 모든 에이전트에서 제거합니다.",
@@ -98,28 +94,16 @@
"added_multi_toast_other": "에이전트 {{count}}개에 추가했습니다"
},
"toolbar": {
- "result_count_title": "일치하는 스킬 / 전체 스킬",
- "filter_label": "필터",
- "filter_active_count_other": "필터 {{count}}개",
- "clear_filters": "필터 해제",
"section_usage": "사용 상태",
"section_labels": "라벨",
"filter_search_placeholder": "필터...",
"no_labels": "아직 라벨이 없습니다",
"no_results": "결과 없음",
- "display": "표시",
- "sort_by": "정렬",
- "direction_asc": "오름차순",
- "direction_desc": "내림차순",
- "section_columns": "표시 열",
"manage_labels": "라벨 관리...",
"manage_labels_title": "스킬 라벨"
},
"detail": {
- "all_skills": "모든 스킬",
"read_only": "읽기 전용",
- "delete_aria": "스킬 삭제",
- "delete_tooltip": "스킬 삭제",
"supporting_data_warning": "일부 워크스페이스 데이터를 불러오지 못했습니다. 다음 새로고침 전까지 생성자 표시, 런타임 이름, 수정 권한이 불완전하게 보일 수 있습니다.",
"delete_file": "파일 삭제",
"name_placeholder": "skill-name",
@@ -154,8 +138,6 @@
"toast_deleted": "스킬을 삭제했습니다",
"toast_delete_failed": "스킬을 삭제하지 못했습니다",
"refresh": {
- "button": "업데이트",
- "tooltip": "소스에서 스킬을 다시 다운로드합니다",
"source_github": "GitHub",
"source_skills_sh": "Skills.sh",
"source_clawhub": "ClawHub",
@@ -194,29 +176,18 @@
}
},
"header": {
- "files_other": "파일 {{count}}개",
- "used_by_other": "에이전트 {{count}}개가 사용 중",
- "updated": "{{when}} 업데이트",
- "updated_by": "{{name}}이(가) {{when}} 업데이트"
- },
- "tabs": {
- "aria": "스킬 섹션",
- "overview": "개요",
- "files_other": "파일 {{count}}"
+ "files_other": "파일 {{count}}개"
},
"overview": {
"properties": "속성",
- "properties_hint": "이 필드는 SKILL.md 프런트매터와 동기화됩니다.",
"name": "이름",
"description": "설명",
"description_hint": "에이전트가 이를 보고 skill을 불러올 시점을 판단합니다.",
"labels": "라벨",
- "used_by_other": "에이전트 {{count}}개가 사용 중",
"used_by_empty": "아직 어떤 에이전트에도 할당되지 않았습니다. 에이전트의 스킬 탭에서 할당하세요.",
"permissions_owner": "이 스킬을 편집하고 삭제할 수 있습니다. 변경 사항은 다음 에이전트 실행부터 적용됩니다.",
"permissions_locked_creator": "작성자({{name}}) 또는 워크스페이스 관리자만 이 스킬을 편집할 수 있습니다.",
"permissions_locked": "작성자 또는 워크스페이스 관리자만 이 스킬을 편집할 수 있습니다.",
- "properties_help": "skill 속성 정보",
"character_count": "{{count}}자"
},
"files": {
@@ -229,6 +200,21 @@
"mode_preview": "미리보기",
"mode_edit": "편집",
"mode_raw": "일반 텍스트"
+ },
+ "sections": {
+ "content": "내용",
+ "files": "파일",
+ "edit": "편집",
+ "open": "열기",
+ "add": "추가"
+ },
+ "menu": {
+ "copy_link": "링크 복사",
+ "link_copied": "링크를 복사했습니다",
+ "delete": "스킬 삭제"
+ },
+ "panel": {
+ "add_description": "설명 추가"
}
},
"create": {
diff --git a/packages/views/locales/ko/squads.json b/packages/views/locales/ko/squads.json
index 4e743a8f4e..f3ed89ee1f 100644
--- a/packages/views/locales/ko/squads.json
+++ b/packages/views/locales/ko/squads.json
@@ -15,10 +15,6 @@
"row_menu": "스쿼드 작업",
"archive_action": "보관"
},
- "inspector": {
- "details_section": "세부 정보",
- "archive_button": "보관"
- },
"member_type": {
"agent": "에이전트",
"member": "멤버"
@@ -65,15 +61,8 @@
"responsibility_placeholder": "이 스쿼드는 무엇을 담당하나요?",
"save": "저장"
},
- "discard_changes_dialog": {
- "title": "저장하지 않은 변경사항을 버릴까요?",
- "description": "이 탭에 저장하지 않은 변경사항이 있습니다. 탭을 전환하면 변경사항이 사라집니다.",
- "keep_editing": "계속 편집",
- "discard_button": "버리기"
- },
"members_tab": {
"section_title": "멤버",
- "section_count_other": "이 스쿼드의 멤버 {{count}}명",
"add_member_button": "멤버 추가",
"create_agent_button": "에이전트 만들기",
"leader_chip": "리더",
@@ -86,19 +75,29 @@
"status_unstable": "불안정",
"status_archived": "보관됨",
"issue_status_blocked": "막힘",
- "active_issue_more": "외 {{count}}개",
- "last_active_label": "마지막 활동 {{time}}"
- },
- "detail_tabs": {
- "members": "멤버",
- "instructions": "지침"
+ "active_issue_more": "외 {{count}}개"
+ },
+ "detail": {
+ "assign_work": "작업 할당",
+ "copy_link": "링크 복사",
+ "link_copied": "링크를 복사했습니다",
+ "not_found": "스쿼드를 찾을 수 없습니다",
+ "instructions": "지침",
+ "edit": "편집",
+ "cancel": "취소",
+ "recent_work": "최근 작업",
+ "recent_work_empty": "아직 이 스쿼드에 할당된 태스크가 없습니다.",
+ "member_menu": "{{name}} 작업",
+ "working_on": "작업 중:"
},
"details": {
"leader": "리더",
"members": "멤버",
"created_by": "생성자",
"created": "생성일",
- "updated": "수정일"
+ "updated": "수정일",
+ "visibility": "공개 범위",
+ "visibility_workspace": "워크스페이스"
},
"toasts": {
"member_added": "멤버를 추가했습니다",
@@ -128,17 +127,7 @@
},
"scope": {
"mine": "내 스쿼드",
- "all": "전체"
+ "all": "전체 스쿼드"
},
- "toolbar": {
- "display": "표시",
- "sort_by": "정렬",
- "direction_asc": "오름차순",
- "direction_desc": "내림차순",
- "section_columns": "열",
- "result_count_title": "일치하는 스쿼드 / 전체 스쿼드",
- "filter_label": "필터",
- "filter_active_count_other": "필터 {{count}}개",
- "clear_filters": "필터 지우기"
- }
+ "toolbar": {}
}
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 0c4f041a40..e2c13add53 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -1,19 +1,21 @@
{
"page": {
"title": "智能体",
- "learn_more": "了解更多 →",
"new_agent": "新建智能体",
- "search_placeholder": "搜索智能体...",
"show_archived": "显示已归档({{count}})→",
"of_total": "{{visible}} / {{total}}",
"list_load_failed": "无法加载智能体列表",
"list_load_failed_default": "获取智能体列表时出错。",
- "try_again": "重试"
+ "try_again": "重试",
+ "scope_title": {
+ "mine": "我的智能体",
+ "all": "全部智能体",
+ "archived": "已归档智能体"
+ }
},
"scope": {
"mine": "我的",
- "all": "全部",
- "archived": "已归档"
+ "all": "全部"
},
"sort": {
"label_recent": "最近活跃",
@@ -47,10 +49,7 @@
},
"no_matches": {
"title": "无匹配项",
- "search_archived": "没有已归档智能体匹配\"{{query}}\"。",
"no_archived": "还没有已归档智能体。",
- "search_active": "没有智能体匹配\"{{query}}\"。",
- "search_active_filtered": "在该筛选下没有智能体匹配\"{{query}}\"。",
"no_filter_match": "该筛选下没有匹配的智能体。",
"search_runtime_filtered": "\"{{machine}}\"上没有匹配\"{{query}}\"的智能体。",
"runtime_filtered": "\"{{machine}}\"上还没有智能体。"
@@ -127,7 +126,6 @@
"archive_dialog_confirm": "归档"
},
"detail": {
- "back_to_agents": "智能体",
"back_to_agents_full": "返回智能体列表",
"not_found_title": "未找到该智能体",
"not_found_default": "该智能体可能已被归档或删除。",
@@ -156,7 +154,11 @@
"runtime_required_toast": "请先绑定运行时,再运行该智能体。",
"assign_work": "分配工作",
"more_actions_aria": "智能体操作",
- "updated": "{{when}}更新"
+ "advanced_settings": "高级设置",
+ "copy_link": "复制链接",
+ "copy_id": "复制智能体 ID",
+ "link_copied_toast": "链接已复制",
+ "id_copied_toast": "智能体 ID 已复制"
},
"inspector": {
"section_profile": "资料",
@@ -166,7 +168,6 @@
"section_properties": "属性",
"section_details": "详情",
"section_details_hint": "只读的所有权和生命周期信息。",
- "section_skills": "Skills",
"section_integrations": "集成",
"prop_runtime": "运行时",
"prop_model": "模型",
@@ -177,7 +178,6 @@
"prop_owner": "所有者",
"prop_created": "创建时间",
"prop_updated": "更新时间",
- "no_description_placeholder": "暂无描述",
"avatar_label": "头像",
"name_label": "名称",
"description_label": "描述",
@@ -193,11 +193,24 @@
"cancel": "取消"
},
"overview": {
- "agent_context": "智能体",
- "access": "访问权限",
"attention_title": "需要处理的运行",
"attention_queued_other": "运行时不可用,当前有 {{count}} 次运行正在排队。"
},
+ "sections": {
+ "runs_count_other": "{{count}} 次运行",
+ "recent_this_week_other": "本周 {{count}} 次",
+ "view_all": "查看全部",
+ "open": "打开",
+ "edit": "编辑",
+ "add": "添加",
+ "manage": "管理",
+ "instructions_empty": "还没有指令。"
+ },
+ "panel": {
+ "status": "状态",
+ "runs_7d": "运行(7 天)",
+ "edit_access_aria": "访问权限:{{value}}。更改访问权限"
+ },
"skill_attach": {
"trigger_aria": "附加工作区 skill",
"trigger_label": "附加"
@@ -251,13 +264,11 @@
"clear_full": "清除选择(使用提供方默认)"
},
"tabs": {
- "overview": "概览",
"work": "工作",
"capabilities": "能力",
"settings": "设置",
"general": "通用",
"access": "访问权限",
- "page_navigation_aria": "智能体页面",
"section_navigation_aria": "智能体分区",
"activity": "动态",
"tasks": "运行",
@@ -279,7 +290,6 @@
"title": "创建智能体",
"squad_title": "为小队创建智能体",
"duplicate_title": "复制 {{name}}",
- "back": "返回",
"step_ai": "通过对话创建",
"modes": {
"template": {
@@ -363,7 +373,8 @@
"runtime": "选择运行时",
"configure": "配置",
"done": "完成",
- "aria": "创建智能体步骤"
+ "aria": "创建智能体步骤",
+ "progress": "第 {{current}} 步,共 {{total}} 步"
},
"configure_title": "配置智能体",
"ask_ai": "让 AI 帮我写",
@@ -775,12 +786,6 @@
"section_now": "当前",
"section_last_30d": "近 30 天",
"section_recent": "最近工作",
- "subtitle_no_active": "无进行中的工作",
- "subtitle_active_other": "{{count}} 次运行进行中",
- "subtitle_performance": "表现",
- "subtitle_no_recent": "还没有完成的运行",
- "subtitle_recent_progress": "显示 {{shown}} / {{total}} 次运行",
- "subtitle_recent_latest": "最近 {{count}} 次运行",
"empty_now": "这个智能体当前没有在运行。",
"empty_30d": "近 30 天没有任何完成记录。",
"empty_recent": "这个智能体还没有完成过任何运行。",
@@ -791,9 +796,7 @@
"success_hint": "成功率按已完成和失败的运行计算,不包含已取消的运行。",
"success_unavailable": "本期间没有已完成或失败的运行,无法计算成功率。",
"cancelled_count": "{{count}} 次已取消",
- "avg_duration": "平均 {{value}}",
"avg_duration_label": "平均耗时",
- "failed_count": "{{count}} 次失败",
"failed_label": "失败",
"source_issue": "任务",
"source_chat": "聊天",
@@ -1017,23 +1020,11 @@
"none": "30 天内无活动"
},
"toolbar": {
- "result_count_title": "当前结果 / 范围内全部",
- "filter_label": "筛选",
- "filter_active_count_other": "{{count}} 项筛选",
- "clear_filters": "清除筛选",
"section_availability": "可用性",
"section_access": "访问权限",
"section_runtime": "运行时",
- "display": "显示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列",
"section_owner": "owner",
"section_model": "模型"
},
- "actions": {
- "selected_other": "已选 {{count}} 项",
- "clear_selection": "清除选择"
- }
+ "actions": {}
}
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index 7603f66ac8..3f021f40cc 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -1,6 +1,5 @@
{
"page": {
- "title": "自动化",
"new_autopilot": "新建自动化",
"start_blank": "从空白开始",
"table": {
@@ -20,7 +19,6 @@
"title": "还没有自动化",
"hint": "为你的智能体安排周期性工作。从模板选一个,或从空白开始。"
},
- "scope_all": "全部",
"no_matches": "没有匹配的自动化",
"retry": "重试"
},
@@ -87,10 +85,8 @@
"run_blocked_quota_exceeded": "未触发——本周期的运行额度已用尽",
"run_blocked_issue_limit_reached": "未触发——工作区任务总数已达到上限",
"run_blocked_generic": "未触发——本次运行已被拦截",
- "section_properties": "属性",
"section_triggers": "触发器",
"section_run_history": "运行历史",
- "section_danger": "危险操作",
"field_agent": "智能体",
"field_created_by": "创建者",
"field_output_mode": "输出模式",
@@ -100,6 +96,16 @@
"field_prompt": "Prompt",
"field_subscribers": "订阅者",
"field_subscribers_none": "无",
+ "no_prompt": "还没有 Prompt。",
+ "copy_link": "复制链接",
+ "link_copied": "链接已复制",
+ "link_copy_failed": "无法复制链接",
+ "open_project": "打开项目",
+ "summary": {
+ "create_issue": "{{agent}} 每次运行创建一个任务",
+ "run_only": "{{agent}} 直接运行,不创建任务",
+ "with_trigger": "{{trigger}} · {{action}}"
+ },
"add_trigger": "添加触发器",
"no_triggers": "未配置触发器。添加一个时间表让它自动运行。",
"no_runs": "暂无运行记录。点击\"立即运行\"手动触发。",
@@ -441,27 +447,16 @@
"search_placeholder": "搜索时区..."
},
"toolbar": {
- "result_count_title": "当前结果 / 全部自动化",
- "filter_label": "筛选",
- "filter_active_count_other": "{{count}} 项筛选",
- "clear_filters": "清除筛选",
"section_assignee": "执行者",
"section_mode": "模式",
"section_trigger": "触发器",
- "section_creator": "创建者",
- "display": "显示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列"
+ "section_creator": "创建者"
},
"actions": {
"row_menu": "自动化操作",
"pause": "暂停",
"resume": "恢复",
"delete": "删除",
- "selected_other": "已选 {{count}} 项",
- "clear_selection": "清除选择",
"delete_dialog": {
"title": "删除自动化?",
"description_other": "将永久删除 {{count}} 个自动化及其运行历史。",
@@ -473,7 +468,6 @@
},
"wakeups": {
"title": "任务唤醒",
- "scope": "范围",
"issue": "任务",
"trigger": "触发条件",
"enabled": "开启",
@@ -482,22 +476,16 @@
"at": "单次定时",
"recurring": "周期",
"all_agents": "所有智能体",
- "search": "搜索任务或智能体",
"running": "运行中",
"active_runs": "{{count}} 个运行未结束",
"issue_closed": "任务已关闭",
"read_only": "仅创建者或工作区管理员可管理此唤醒",
"select_row": "选择 {{issue}},{{agent}}",
- "select_page": "选择本页已开启的唤醒",
+ "select_page": "选择所有已开启的唤醒",
"load_error": "无法加载唤醒",
"loading": "正在加载唤醒…",
"empty": "暂无唤醒规则",
- "selected": "已选择 {{count}} 项",
"disable_selected": "关闭所选",
- "clear": "清除选择",
- "results": "第 {{page}} 页 · 共 {{count}} 项",
- "previous": "上一页",
- "next_page": "下一页",
"confirm_title": "关闭 {{count}} 个唤醒?",
"confirm_body": "关闭后将停止后续唤醒,并撤回仍在排队、尚未交给智能体的运行。已交给智能体的运行会继续,可在执行日志中停止。",
"cancel": "取消",
@@ -506,7 +494,7 @@
"batch_result": "已关闭 {{succeeded}} 项,失败 {{failed}} 项。",
"scopes": {
"active": "待唤醒或执行中",
- "all": "全部",
+ "all": "全部唤醒",
"disabled": "已关闭",
"ended": "已结束",
"paused": "已暂停"
@@ -518,7 +506,7 @@
"batch_partial": "已关闭 {{succeeded}} 条,{{failed}} 条失败;失败项仍保留选中,可重试。",
"source": "来源",
"sources": {
- "all": "来源:全部",
+ "all": "全部来源",
"member": "成员",
"agent": "智能体",
"system": "系统"
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index c835de785d..224cf0c9d6 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -243,7 +243,6 @@
"row_actions_aria": "聊天操作"
},
"header": {
- "view_profile": "查看智能体资料",
"rename": "重命名会话",
"delete": "删除会话",
"archive": "归档会话",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index d556654957..9c6b732221 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -155,6 +155,7 @@
},
"filters": {
"tooltip": "筛选",
+ "active_section": "已启用",
"placeholder": "筛选...",
"search_status": "搜索状态...",
"no_results": "无结果",
@@ -171,6 +172,15 @@
"section_project": "项目",
"section_project_status": "项目状态",
"section_label": "标签",
+ "section_relation": "与我的关系",
+ "relation_assigned": "分配给我的",
+ "relation_created": "我创建的",
+ "relation_my_agents": "分配给我的智能体的",
+ "operator_label": "关系",
+ "operator_is": "是",
+ "operator_is_not": "不是",
+ "modified_hint": "相对视图有改动",
+ "unsaved_changes_other": "{{count}} 处未保存的改动",
"section_date": "日期",
"date_field": "字段",
"date_field_created": "创建时间",
@@ -194,7 +204,54 @@
"active_count_other": "{{count}} 个筛选",
"in_view": "已包含在视图中",
"chip_edit": "编辑",
- "chip_save_as": "另存"
+ "chip_save_as": "另存",
+ "section_due_date": "截止日期",
+ "due_overdue": "已逾期",
+ "due_today": "今天截止",
+ "due_this_week": "本周截止",
+ "due_next_7_days": "7 天内截止",
+ "due_none": "无截止日期",
+ "search_placeholder": "按字段或值筛选…",
+ "search_fields": "字段",
+ "search_values": "值",
+ "advanced_switch": "切换到高级筛选",
+ "advanced_title": "高级筛选",
+ "advanced_match_leading": "满足",
+ "advanced_match_trailing": "条件",
+ "match_all": "全部",
+ "match_any": "任一",
+ "advanced_where": "当",
+ "advanced_and": "且",
+ "advanced_or": "或",
+ "advanced_add_condition": "添加条件",
+ "advanced_add_group": "添加条件组",
+ "advanced_unknown_property": "已删除的属性",
+ "advanced_values_placeholder": "选择值…",
+ "advanced_field_label": "字段",
+ "advanced_values_label": "值",
+ "advanced_actions": "条件操作",
+ "advanced_duplicate": "复制",
+ "advanced_delete": "删除",
+ "advanced_delete_group": "删除条件组",
+ "advanced_to_simple": "切回简单筛选",
+ "advanced_to_simple_blocked": "含条件组、“任一”或重复字段,简单筛选表达不了",
+ "advanced_clear": "清除全部",
+ "advanced_empty": "还没有条件,添加一条开始筛选。",
+ "advanced_conditions_other": "{{count}} 个条件",
+ "operator_has_any": "包含任一",
+ "operator_has_none": "都不包含",
+ "operator_contains": "包含",
+ "operator_not_contains": "不包含",
+ "operator_before": "早于",
+ "operator_after": "晚于",
+ "operator_empty": "为空",
+ "operator_not_empty": "不为空",
+ "advanced_group_match_leading": "满足组内",
+ "advanced_group_match_trailing": "条件",
+ "advanced_group_hint": "组内条件之间用「{{word}}」连接",
+ "advanced_add_to_group": "添加到条件组",
+ "advanced_turn_into_group": "转为条件组",
+ "advanced_summary": "筛选:{{summary}}"
},
"display": {
"tooltip": "显示设置",
@@ -204,6 +261,7 @@
"card_properties_section": "卡片属性",
"columns_section": "列",
"columns_locked_by_filter": "清除状态筛选后才能显示或隐藏列。",
+ "columns_shown": "显示 {{count}} 列",
"ascending_title": "升序",
"descending_title": "降序",
"newest_first": "最新优先",
@@ -236,7 +294,8 @@
"card_project": "项目",
"card_labels": "标签",
"card_child_progress": "子任务进度",
- "show_sub_issues": "显示子任务"
+ "show_sub_issues": "显示子任务",
+ "layout_options": "{{layout}}选项"
},
"view": {
"tooltip_board": "看板视图",
@@ -384,7 +443,6 @@
"metadata_restore": "恢复弹窗大小",
"metadata_copy_failed": "复制元数据失败",
"metadata_description": "智能体和集成记录的键值数据,用于衔接工作流程。",
-
"section_load_failed_retry": "加载失败,点击重试",
"not_found": "这个任务不存在或已在该工作区被删除。",
"breadcrumb_project_unknown": "未知项目",
@@ -957,38 +1015,6 @@
"row_todo_hint": "启动智能体"
},
"save_view": {
- "title": "保存为视图",
- "hint_workspace": "基于工作区全部任务创建",
- "hint_my_any": "基于「我的任务 · 全部」创建",
- "hint_my_assigned": "基于「我的任务 · 分配给我」创建",
- "hint_my_created": "基于「我的任务 · 我创建的」创建",
- "hint_my_involved": "基于「我的任务 · 我参与的」创建",
- "hint_project": "基于项目「{{title}}」创建,仅在该项目页面可用",
- "hint_project_agents": "基于项目「{{title}}」中智能体负责的任务创建,仅在该项目页面可用",
- "hint_project_members": "基于项目「{{title}}」中成员负责的任务创建,仅在该项目页面可用",
- "my_private_note": "我的任务视图仅自己可见",
- "name_label": "名称",
- "visibility_label": "可见性",
- "visibility_private": "仅自己可见",
- "visibility_workspace": "工作区成员可见",
- "filters_label": "筛选",
- "custom_property": "自定义属性",
- "create": "创建视图",
- "layout_label": "布局",
- "display_defaults": "默认显示",
- "default_hint": "成员首次打开此视图时的显示方式,之后各自可调",
- "add_filter": "添加筛选",
- "name_placeholder": "例如:需要 Review",
- "cancel": "取消",
- "name_required": "请输入视图名称",
- "toast_created": "视图已创建",
- "toast_failed": "创建视图失败",
- "edit_title": "编辑视图",
- "update": "保存修改",
- "toast_updated": "视图已更新",
- "toast_conflict": "视图已被他人修改,请重新打开后再试",
- "hint_workspace_members": "基于工作区中成员负责的任务创建",
- "hint_workspace_agents": "基于工作区中智能体负责的任务创建",
"scope_label_workspace": "负责人类型",
"scope_label_my": "与我的关系",
"variant_all": "不限负责人",
@@ -999,36 +1025,6 @@
"variant_my_created": "我创建的",
"variant_my_involved": "我参与的"
},
- "view_selector": {
- "trigger": "视图",
- "empty": "还没有保存的视图",
- "private_group": "私有",
- "shared_group": "工作区共享",
- "exit": "退出视图",
- "unavailable": "该视图已不可用",
- "edit": "编辑视图"
- },
- "view_bar": {
- "menu_label": "视图",
- "menu_new": "新增视图",
- "builtin_tag": "内置",
- "drag_handle": "拖拽排序",
- "delete": "删除",
- "delete_title": "删除视图?",
- "delete_description": "「{{name}}」将对所有可见成员删除",
- "toast_deleted": "视图已删除",
- "context_edit": "编辑视图",
- "context_pin": "固定到侧栏",
- "context_unpin": "从侧栏取消固定",
- "row_menu": "更多操作",
- "row_hide": "在栏中隐藏",
- "row_show": "在栏中显示",
- "menu_manage": "管理视图",
- "manage_title": "管理视图",
- "manage_hint": "排序与显隐只影响你自己",
- "visible_toggle": "在视图栏显示",
- "more_label": "更多视图"
- },
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} 的界面加载失败。",
@@ -1709,5 +1705,67 @@
},
"hover_card": {
"created_updated": "创建于 {{created}} · 更新于 {{updated}}"
+ },
+ "views": {
+ "builtin": {
+ "my_issues": "我的任务",
+ "my_agents": "我的智能体在做",
+ "all_issues": "全部任务"
+ },
+ "untitled": "未命名视图",
+ "copy_name": "{{name}}(副本)",
+ "rename": "重命名",
+ "duplicate": "创建副本",
+ "copy_link": "复制链接",
+ "link_copied": "链接已复制",
+ "visible_to": "可见范围",
+ "only_me": "仅自己",
+ "workspace_members": "工作区成员",
+ "add_to_sidebar": "添加到侧栏",
+ "remove_from_sidebar": "从侧栏移除",
+ "back_to": "返回{{name}}",
+ "delete": "删除视图",
+ "delete_title": "删除视图?",
+ "delete_description": "「{{name}}」将被删除,此操作无法撤销。",
+ "delete_description_shared": "「{{name}}」已共享给工作区,删除后所有人都将无法使用。",
+ "cancel": "取消",
+ "toast_deleted": "视图已删除",
+ "toast_delete_failed": "删除视图失败",
+ "filter": "筛选",
+ "filter_count_other": "{{count}} 个筛选",
+ "reset": "重置",
+ "save": "保存",
+ "save_options": "更多保存选项",
+ "save_to": "保存到「{{name}}」",
+ "save_to_hint_shared": "为工作区所有人更新此视图",
+ "save_to_hint_private": "更新你的视图",
+ "save_as_new": "另存为新视图",
+ "save_as_new_hint": "「{{name}}」保持不变",
+ "save_as_view": "保存为视图",
+ "set_by_view": "由此视图设定",
+ "new_issue": "新建任务",
+ "unavailable": "此视图已不可用",
+ "toast_saved": "视图已保存",
+ "toast_conflict": "视图已被他人修改,请刷新后重试",
+ "toast_create_failed": "创建视图失败",
+ "toast_save_failed": "保存视图失败",
+ "directory": {
+ "new_view": "新建视图",
+ "scope_all": "全部视图",
+ "scope_builtin": "内置",
+ "scope_mine": "我创建的",
+ "scope_shared": "已共享",
+ "col_name": "名称",
+ "col_location": "位置",
+ "col_filters": "筛选",
+ "col_visibility": "可见范围",
+ "col_owner": "所有者",
+ "owner_builtin": "内置",
+ "location_project": "项目",
+ "star": "将{{name}}添加到侧栏",
+ "unstar": "将{{name}}从侧栏移除",
+ "row_actions": "{{name}} 的操作",
+ "no_matches": "没有匹配的视图"
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index b68080c430..5bfd32a1e4 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -11,7 +11,8 @@
"usage": "统计",
"runtimes": "运行时",
"skills": "Skills",
- "settings": "设置"
+ "settings": "设置",
+ "views": "视图"
},
"tab": {
"issue": "任务",
@@ -25,6 +26,7 @@
"runtime": "运行时",
"attachment": "附件",
"create_agent": "创建智能体",
+ "my_agents": "我的智能体在做",
"unknown": "未知页面"
},
"help": {
@@ -57,16 +59,114 @@
"invitation_decline": "拒绝",
"log_out": "退出登录",
"new_issue": "新建任务",
- "new_issue_shortcut": "C",
"pinned_label": "固定",
- "work_group": "工作",
- "ai_team_group": "AI 团队",
"show_more_pins": "再显示 {{count}} 项...",
- "show_fewer_pins": "收起",
- "unread_overflow": "99+",
- "discord_card": {
- "title": "加入 Discord",
- "dismiss": "关闭"
+ "show_fewer_pins": "收起"
+ },
+ "spaces": {
+ "work": "任务",
+ "team": "团队"
+ },
+ "rail": {
+ "label": "应用导航",
+ "sheet_description": "切换空间和工作区。",
+ "inbox": "收件箱",
+ "work": "任务",
+ "team": "团队",
+ "chat": "聊天",
+ "autopilots": "自动化",
+ "switch_workspace": "切换工作区",
+ "invitation_from": "{{name}} 邀请你加入"
+ },
+ "panels": {
+ "work": {
+ "my_agents": "我的智能体在做",
+ "all_issues": "全部任务",
+ "views": "视图",
+ "new_project": "新建项目",
+ "new_issue_in_project": "在 {{name}} 中新建任务",
+ "all_projects_other": "全部 {{count}} 个项目",
+ "project_issues": "{{name}} 的任务",
+ "project_issues_empty": "没有任务",
+ "project_issues_error": "无法加载任务",
+ "project_issues_settings": "项目中的任务",
+ "settings_status": "状态",
+ "settings_assignee": "负责人",
+ "assignee_anyone": "所有人",
+ "assignee_me": "我",
+ "assignee_my_agents": "我的智能体",
+ "reset": "重置",
+ "load_more": "加载更多",
+ "show_less": "收起",
+ "projects_settings": "项目显示",
+ "projects_ordering": "排序",
+ "projects_order_manual": "手动",
+ "projects_order_name": "名称",
+ "projects_order_updated": "最近更新",
+ "projects_order_created": "最近创建",
+ "projects_show": "显示",
+ "projects_only_mine": "只看我负责的项目",
+ "projects_show_count": "未完成任务数",
+ "new_view": "新建视图",
+ "all_views": "全部视图",
+ "view_actions": "{{name}} 的操作",
+ "view_copy_link": "复制链接",
+ "view_remove": "从侧栏移除",
+ "view_rename": "重命名",
+ "view_duplicate": "创建副本",
+ "view_delete": "删除视图"
+ },
+ "team": {
+ "new_agent": "新建智能体",
+ "needs_attention": "需要处理",
+ "stuck_other": "{{count}} 个任务在等待离线的运行时",
+ "working_now": "正在工作",
+ "running_tasks_other": "{{count}} 个任务运行中",
+ "all_agents": "全部智能体",
+ "my_agents": "我的智能体",
+ "squads_and_members": "小队与成员",
+ "members_other": "{{count}} 位成员",
+ "resources": "资源",
+ "runtimes_offline_other": "{{count}} 个离线",
+ "invite_member": "邀请成员"
+ },
+ "autopilots": {
+ "all": "全部自动化",
+ "list": "自动化",
+ "templates": "从模板开始"
}
+ },
+ "account": {
+ "trigger": "账户",
+ "profile": "个人资料",
+ "theme": "主题",
+ "themes": {
+ "light": "浅色",
+ "dark": "深色",
+ "system": "跟随系统"
+ },
+ "language": "语言",
+ "shortcuts": "快捷键"
+ },
+ "collection": {
+ "filter": "筛选",
+ "filter_count_other": "{{count}} 个筛选",
+ "reset": "重置",
+ "display": "显示设置",
+ "selected_other": "已选 {{count}} 项",
+ "clear_selection": "清除选择",
+ "select_all": "全选",
+ "select_row": "选择此行",
+ "row_actions": "更多操作",
+ "sort_by": "排序",
+ "direction_asc": "升序",
+ "direction_desc": "降序",
+ "section_columns": "列",
+ "load_more": "加载更多",
+ "loading_more": "加载中…"
+ },
+ "object_page": {
+ "toggle_panel": "切换右侧边栏",
+ "properties": "属性"
}
}
diff --git a/packages/views/locales/zh-Hans/members.json b/packages/views/locales/zh-Hans/members.json
index 991602d34b..88062f3fac 100644
--- a/packages/views/locales/zh-Hans/members.json
+++ b/packages/views/locales/zh-Hans/members.json
@@ -11,8 +11,11 @@
"more_agents_other": "另有 {{count}} 个智能体"
},
"detail": {
- "workspace_fallback": "工作区",
"members_breadcrumb": "成员",
+ "role": "角色",
+ "email": "邮箱",
+ "joined": "加入时间",
+ "relation": "关系",
"breadcrumb_fallback": "成员",
"not_found_title": "未找到该成员",
"not_found_description": "该成员可能已经离开工作区。"
diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.json
index b8b6d87729..e5315fbff8 100644
--- a/packages/views/locales/zh-Hans/projects.json
+++ b/packages/views/locales/zh-Hans/projects.json
@@ -2,11 +2,13 @@
"page": {
"title": "项目",
"new_project": "新建项目",
+ "scope_all": "全部项目",
+ "scope_active": "进行中的项目",
+ "scope_closed": "已结束的项目",
"empty": "还没有项目",
"create_first": "创建第一个项目",
"view_compact": "紧凑视图",
"view_comfortable": "舒适视图",
- "search_placeholder": "搜索项目...",
"no_search_results": "未找到匹配的项目",
"view_table": "表格",
"view_cards": "卡片",
@@ -14,9 +16,7 @@
"pin": "固定到侧边栏",
"unpin": "取消钉选",
"delete": "删除",
- "no_matches": "没有匹配的项目",
- "selected_other": "已选 {{count}} 项",
- "clear_selection": "清除选择"
+ "no_matches": "没有匹配的项目"
},
"table": {
"name": "名称",
@@ -167,18 +167,9 @@
"fallback_label": "项目"
},
"toolbar": {
- "result_count_title": "当前结果 / 全部项目",
- "filter_label": "筛选",
- "filter_active_count_other": "{{count}} 项筛选",
- "clear_filters": "清除筛选",
"section_status": "状态",
"section_priority": "优先级",
"section_lead": "负责人",
- "display": "显示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列",
"view": "视图"
}
}
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index c9aff6cc50..49ed1f31a3 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -1,9 +1,7 @@
{
"page": {
"title": "运行时",
- "learn_more": "了解更多 →",
"connect_remote": "添加机器",
- "search_placeholder": "搜索...",
"scope_mine": "我的",
"scope_all": "全部",
"live": "实时",
@@ -25,7 +23,7 @@
"title": "正在启动本地运行时...",
"hint": "正在连接工作区..."
},
- "add": "添加",
+ "add": "添加运行时",
"add_menu": {
"machines": "机器",
"this_computer": "这台电脑",
@@ -67,7 +65,7 @@
"no_matches": "没有匹配的机器或云服务"
},
"filters": {
- "all": "全部",
+ "all": "全部运行时",
"online": "在线",
"offline": "离线"
}
@@ -93,7 +91,7 @@
"this_machine": "本机",
"local_badge": "本地 · 这台机器",
"pending_custom_runtimes": "待注册自定义运行时",
- "runtime_count_other": "{{count}} 个运行时",
+ "daemon_title": "守护进程",
"busy_count_other": "{{count}} 个忙碌",
"no_matches_title": "没有机器",
"no_matches_hint": "没有机器匹配当前搜索或筛选。",
@@ -158,13 +156,10 @@
"fact_owner": "所有者",
"fact_device": "设备",
"fact_runtime": "运行时",
- "technical_details": "技术详情",
"fact_daemon_cli": "守护进程 CLI",
"fact_daemon_id": "守护进程 ID",
- "serving_title": "服务中",
- "serving_count_other": "{{count}} 个智能体",
+ "usage_title": "用量",
"no_agents": "还没有智能体绑定到这个运行时。",
- "diagnostics_title": "诊断",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "可见性",
"visibility_label": {
diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.json
index 856a5ff774..53ac23f8b4 100644
--- a/packages/views/locales/zh-Hans/skills.json
+++ b/packages/views/locales/zh-Hans/skills.json
@@ -1,12 +1,10 @@
{
"page": {
"title": "Skills",
- "learn_more": "了解更多 →",
"new_skill": "新建 skill",
- "search_placeholder": "搜索 skill...",
"scopes": {
"all": {
- "label": "全部",
+ "label": "全部 skill",
"description": "工作区里所有 skill"
},
"used": {
@@ -18,7 +16,7 @@
"description": "未分配给任何智能体的 skill"
},
"mine": {
- "label": "我创建的",
+ "label": "我的 skill",
"description": "你创建的 skill"
}
},
@@ -76,8 +74,6 @@
"added_toast": "已添加到 {{name}}",
"add_failed_toast": "添加 skill 失败",
"delete": "删除",
- "selected": "已选 {{count}} 项",
- "clear_selection": "清除选择",
"delete_no_permission": "选中项包含仅创建者或管理员可删除的 skill",
"delete_dialog_title_other": "删除 {{count}} 个 skill?",
"delete_dialog_desc_other": "将永久删除选中的 {{count}} 个 skill,并从所有智能体上移除。",
@@ -98,28 +94,16 @@
"added_multi_toast_other": "已添加到 {{count}} 个智能体"
},
"toolbar": {
- "result_count_title": "当前结果 / 全部 skill",
- "filter_label": "筛选",
- "filter_active_count_other": "{{count}} 项筛选",
- "clear_filters": "清除筛选",
"section_usage": "使用状态",
"section_labels": "标签",
"filter_search_placeholder": "筛选...",
"no_labels": "还没有标签",
"no_results": "无结果",
- "display": "显示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "显示列",
"manage_labels": "管理标签...",
"manage_labels_title": "Skill 标签"
},
"detail": {
- "all_skills": "全部 skill",
"read_only": "只读",
- "delete_aria": "删除 skill",
- "delete_tooltip": "删除 skill",
"supporting_data_warning": "部分工作区数据加载失败。创建者归属、运行时名称、编辑权限可能要等下次刷新才完整。",
"delete_file": "删除文件",
"name_placeholder": "skill-name",
@@ -154,8 +138,6 @@
"toast_deleted": "已删除 skill",
"toast_delete_failed": "删除 skill 失败",
"refresh": {
- "button": "更新",
- "tooltip": "从来源重新下载这个 skill",
"source_github": "GitHub",
"source_skills_sh": "Skills.sh",
"source_clawhub": "ClawHub",
@@ -194,29 +176,18 @@
}
},
"header": {
- "files_other": "{{count}} 个文件",
- "used_by_other": "{{count}} 个智能体在用",
- "updated": "{{when}}更新",
- "updated_by": "{{name}} 于{{when}}更新"
- },
- "tabs": {
- "aria": "技能分区",
- "overview": "概览",
- "files_other": "文件 {{count}}"
+ "files_other": "{{count}} 个文件"
},
"overview": {
"properties": "属性",
- "properties_hint": "这些字段与 SKILL.md 的 frontmatter 保持同步。",
"name": "名称",
"description": "描述",
"description_hint": "智能体据此决定何时加载 skill。",
"labels": "标签",
- "used_by_other": "被 {{count}} 个智能体使用",
"used_by_empty": "还未分配给任何智能体。打开某个智能体的 Skills 标签页进行分配。",
"permissions_owner": "你可以编辑和删除该技能。改动将在智能体下次运行时生效。",
"permissions_locked_creator": "只有创建者({{name}})或工作区管理员可以编辑该技能。",
"permissions_locked": "只有创建者或工作区管理员可以编辑该技能。",
- "properties_help": "关于 skill 属性",
"character_count": "{{count}} 个字符"
},
"files": {
@@ -229,6 +200,21 @@
"mode_preview": "预览",
"mode_edit": "编辑",
"mode_raw": "纯文本"
+ },
+ "sections": {
+ "content": "内容",
+ "files": "文件",
+ "edit": "编辑",
+ "open": "打开",
+ "add": "添加"
+ },
+ "menu": {
+ "copy_link": "复制链接",
+ "link_copied": "已复制链接",
+ "delete": "删除 skill"
+ },
+ "panel": {
+ "add_description": "添加描述"
}
},
"create": {
diff --git a/packages/views/locales/zh-Hans/squads.json b/packages/views/locales/zh-Hans/squads.json
index f8806d09d5..68d99906be 100644
--- a/packages/views/locales/zh-Hans/squads.json
+++ b/packages/views/locales/zh-Hans/squads.json
@@ -15,10 +15,6 @@
"row_menu": "小队操作",
"archive_action": "归档"
},
- "inspector": {
- "details_section": "详情",
- "archive_button": "归档"
- },
"member_type": {
"agent": "智能体",
"member": "成员"
@@ -65,15 +61,8 @@
"responsibility_placeholder": "这个小队负责什么?",
"save": "保存"
},
- "discard_changes_dialog": {
- "title": "放弃未保存的修改?",
- "description": "当前标签页有未保存的修改,切换标签会丢弃这些修改。",
- "keep_editing": "继续编辑",
- "discard_button": "放弃"
- },
"members_tab": {
"section_title": "成员",
- "section_count_other": "该小队有 {{count}} 名成员",
"add_member_button": "添加成员",
"create_agent_button": "创建智能体",
"leader_chip": "队长",
@@ -86,19 +75,29 @@
"status_unstable": "不稳定",
"status_archived": "已归档",
"issue_status_blocked": "已阻塞",
- "active_issue_more": "还有 {{count}} 个",
- "last_active_label": "最近活动 {{time}}"
- },
- "detail_tabs": {
- "members": "成员",
- "instructions": "指引"
+ "active_issue_more": "还有 {{count}} 个"
+ },
+ "detail": {
+ "assign_work": "分配工作",
+ "copy_link": "复制链接",
+ "link_copied": "已复制链接",
+ "not_found": "未找到该小队",
+ "instructions": "指引",
+ "edit": "编辑",
+ "cancel": "取消",
+ "recent_work": "近期工作",
+ "recent_work_empty": "还没有分配给这个小队的任务。",
+ "member_menu": "{{name}} 的操作",
+ "working_on": "正在处理"
},
"details": {
"leader": "队长",
"members": "成员",
"created_by": "创建者",
"created": "创建时间",
- "updated": "更新时间"
+ "updated": "更新时间",
+ "visibility": "可见范围",
+ "visibility_workspace": "工作区"
},
"toasts": {
"member_added": "已添加成员",
@@ -127,18 +126,8 @@
"placeholder": "例如:始终先编写失败测试。提交应保持小而独立。"
},
"scope": {
- "mine": "我的",
- "all": "全部"
+ "mine": "我的小队",
+ "all": "全部小队"
},
- "toolbar": {
- "display": "显示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列",
- "result_count_title": "当前结果 / 全部小队",
- "filter_label": "筛选",
- "filter_active_count_other": "{{count}} 项筛选",
- "clear_filters": "清除筛选"
- }
+ "toolbar": {}
}
diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.json
index c2746c9abd..5f4191607d 100644
--- a/packages/views/locales/zh-Hant/agents.json
+++ b/packages/views/locales/zh-Hant/agents.json
@@ -1,19 +1,21 @@
{
"page": {
"title": "智慧體",
- "learn_more": "瞭解更多 →",
"new_agent": "新建智慧體",
- "search_placeholder": "搜尋智慧體...",
"show_archived": "顯示已歸檔({{count}})→",
"of_total": "{{visible}} / {{total}}",
"list_load_failed": "無法載入智慧體列表",
"list_load_failed_default": "獲取智慧體列表時出錯。",
- "try_again": "重試"
+ "try_again": "重試",
+ "scope_title": {
+ "mine": "我的智慧體",
+ "all": "全部智慧體",
+ "archived": "已歸檔智慧體"
+ }
},
"scope": {
"mine": "我的",
- "all": "全部",
- "archived": "已歸檔"
+ "all": "全部"
},
"sort": {
"label_recent": "最近活躍",
@@ -47,10 +49,7 @@
},
"no_matches": {
"title": "無匹配項",
- "search_archived": "沒有已歸檔智慧體匹配\"{{query}}\"。",
"no_archived": "還沒有已歸檔智慧體。",
- "search_active": "沒有智慧體匹配\"{{query}}\"。",
- "search_active_filtered": "在該篩選下沒有智慧體匹配\"{{query}}\"。",
"no_filter_match": "該篩選下沒有匹配的智慧體。",
"search_runtime_filtered": "\"{{machine}}\"上沒有匹配\"{{query}}\"的智慧體。",
"runtime_filtered": "\"{{machine}}\"上還沒有智慧體。"
@@ -127,7 +126,6 @@
"archive_dialog_confirm": "歸檔"
},
"detail": {
- "back_to_agents": "智慧體",
"back_to_agents_full": "返回智慧體列表",
"not_found_title": "未找到該智慧體",
"not_found_default": "該智慧體可能已被歸檔或刪除。",
@@ -156,7 +154,11 @@
"runtime_required_toast": "請先繫結執行時,再執行該智慧體。",
"assign_work": "分配工作",
"more_actions_aria": "智慧體操作",
- "updated": "{{when}}更新"
+ "advanced_settings": "進階設定",
+ "copy_link": "複製連結",
+ "copy_id": "複製智慧體 ID",
+ "link_copied_toast": "連結已複製",
+ "id_copied_toast": "智慧體 ID 已複製"
},
"inspector": {
"section_profile": "資料",
@@ -166,7 +168,6 @@
"section_properties": "屬性",
"section_details": "詳情",
"section_details_hint": "只讀的所有權和生命週期資訊。",
- "section_skills": "Skills",
"section_integrations": "整合",
"prop_runtime": "執行時",
"prop_model": "模型",
@@ -177,7 +178,6 @@
"prop_owner": "所有者",
"prop_created": "建立時間",
"prop_updated": "更新時間",
- "no_description_placeholder": "暫無描述",
"avatar_label": "頭像",
"name_label": "名稱",
"description_label": "描述",
@@ -193,11 +193,24 @@
"cancel": "取消"
},
"overview": {
- "agent_context": "智慧體",
- "access": "訪問權限",
"attention_title": "需要處理的執行",
"attention_queued_other": "執行時不可用,當前有 {{count}} 次執行正在排隊。"
},
+ "sections": {
+ "runs_count_other": "{{count}} 次執行",
+ "recent_this_week_other": "本週 {{count}} 次",
+ "view_all": "查看全部",
+ "open": "開啟",
+ "edit": "編輯",
+ "add": "新增",
+ "manage": "管理",
+ "instructions_empty": "還沒有指令。"
+ },
+ "panel": {
+ "status": "狀態",
+ "runs_7d": "執行(7 天)",
+ "edit_access_aria": "訪問權限:{{value}}。變更訪問權限"
+ },
"skill_attach": {
"trigger_aria": "附加工作區 skill",
"trigger_label": "附加"
@@ -251,13 +264,11 @@
"clear_full": "清除選擇(使用提供方預設)"
},
"tabs": {
- "overview": "概覽",
"work": "工作",
"capabilities": "能力",
"settings": "設定",
"general": "通用",
"access": "訪問權限",
- "page_navigation_aria": "智慧體頁面",
"section_navigation_aria": "智慧體分區",
"activity": "動態",
"tasks": "執行",
@@ -279,7 +290,6 @@
"title": "建立智慧體",
"squad_title": "為小隊建立智慧體",
"duplicate_title": "複製 {{name}}",
- "back": "返回",
"step_ai": "透過對話建立",
"modes": {
"template": {
@@ -363,7 +373,8 @@
"runtime": "選擇執行時",
"configure": "配置",
"done": "完成",
- "aria": "建立智慧體步驟"
+ "aria": "建立智慧體步驟",
+ "progress": "第 {{current}} 步,共 {{total}} 步"
},
"configure_title": "配置智慧體",
"ask_ai": "讓 AI 幫我寫",
@@ -775,12 +786,6 @@
"section_now": "當前",
"section_last_30d": "近 30 天",
"section_recent": "最近工作",
- "subtitle_no_active": "無進行中的工作",
- "subtitle_active_other": "{{count}} 次執行進行中",
- "subtitle_performance": "表現",
- "subtitle_no_recent": "還沒有完成的執行",
- "subtitle_recent_progress": "顯示 {{shown}} / {{total}} 次執行",
- "subtitle_recent_latest": "最近 {{count}} 次執行",
"empty_now": "這個智慧體當前沒有在執行。",
"empty_30d": "近 30 天沒有任何完成記錄。",
"empty_recent": "這個智慧體還沒有完成過任何執行。",
@@ -791,9 +796,7 @@
"success_hint": "成功率按已完成和失敗的執行計算,不包含已取消的執行。",
"success_unavailable": "本期間沒有已完成或失敗的執行,無法計算成功率。",
"cancelled_count": "{{count}} 次已取消",
- "avg_duration": "平均 {{value}}",
"avg_duration_label": "平均耗時",
- "failed_count": "{{count}} 次失敗",
"failed_label": "失敗",
"source_issue": "任務",
"source_chat": "聊天",
@@ -1017,23 +1020,11 @@
"none": "30 天內無活動"
},
"toolbar": {
- "result_count_title": "當前結果 / 範圍內全部",
- "filter_label": "篩選",
- "filter_active_count_other": "{{count}} 項篩選",
- "clear_filters": "清除篩選",
"section_availability": "可用性",
"section_access": "訪問權限",
"section_runtime": "執行時",
- "display": "顯示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列",
"section_owner": "owner",
"section_model": "模型"
},
- "actions": {
- "selected_other": "已選 {{count}} 項",
- "clear_selection": "清除選擇"
- }
+ "actions": {}
}
diff --git a/packages/views/locales/zh-Hant/autopilots.json b/packages/views/locales/zh-Hant/autopilots.json
index 8ce19529bb..9363abb50e 100644
--- a/packages/views/locales/zh-Hant/autopilots.json
+++ b/packages/views/locales/zh-Hant/autopilots.json
@@ -1,6 +1,5 @@
{
"page": {
- "title": "自動化",
"new_autopilot": "新建自動化",
"start_blank": "從空白開始",
"table": {
@@ -20,7 +19,6 @@
"title": "還沒有自動化",
"hint": "為你的智慧體安排週期性工作。從模板選一個,或從空白開始。"
},
- "scope_all": "全部",
"no_matches": "沒有匹配的自動化",
"retry": "重試"
},
@@ -87,10 +85,8 @@
"run_blocked_quota_exceeded": "未觸發——本週期的執行額度已用盡",
"run_blocked_issue_limit_reached": "未觸發——工作區任務總數已達到上限",
"run_blocked_generic": "未觸發——本次執行已被攔截",
- "section_properties": "屬性",
"section_triggers": "觸發器",
"section_run_history": "執行歷史",
- "section_danger": "危險操作",
"field_agent": "智慧體",
"field_created_by": "建立者",
"field_output_mode": "輸出模式",
@@ -100,6 +96,16 @@
"field_prompt": "Prompt",
"field_subscribers": "訂閱者",
"field_subscribers_none": "無",
+ "no_prompt": "還沒有 Prompt。",
+ "copy_link": "複製連結",
+ "link_copied": "連結已複製",
+ "link_copy_failed": "無法複製連結",
+ "open_project": "開啟專案",
+ "summary": {
+ "create_issue": "{{agent}} 每次執行建立一個任務",
+ "run_only": "{{agent}} 直接執行,不建立任務",
+ "with_trigger": "{{trigger}} · {{action}}"
+ },
"add_trigger": "新增觸發器",
"no_triggers": "未配置觸發器。新增一個時間表讓它自動執行。",
"no_runs": "暫無執行記錄。點選\"立即執行\"手動觸發。",
@@ -441,27 +447,16 @@
"search_placeholder": "搜尋時區..."
},
"toolbar": {
- "result_count_title": "當前結果 / 全部自動化",
- "filter_label": "篩選",
- "filter_active_count_other": "{{count}} 項篩選",
- "clear_filters": "清除篩選",
"section_assignee": "執行者",
"section_mode": "模式",
"section_trigger": "觸發器",
- "section_creator": "建立者",
- "display": "顯示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列"
+ "section_creator": "建立者"
},
"actions": {
"row_menu": "自動化操作",
"pause": "暫停",
"resume": "恢復",
"delete": "刪除",
- "selected_other": "已選 {{count}} 項",
- "clear_selection": "清除選擇",
"delete_dialog": {
"title": "刪除自動化?",
"description_other": "將永久刪除 {{count}} 個自動化及其執行歷史。",
@@ -473,7 +468,6 @@
},
"wakeups": {
"title": "任務喚醒",
- "scope": "範圍",
"issue": "任務",
"trigger": "觸發條件",
"enabled": "開啟",
@@ -482,22 +476,16 @@
"at": "單次定時",
"recurring": "週期",
"all_agents": "所有智慧體",
- "search": "搜尋任務或智慧體",
"running": "執行中",
"active_runs": "{{count}} 個執行未結束",
"issue_closed": "任務已關閉",
"read_only": "僅建立者或工作區管理員可管理此喚醒",
"select_row": "選擇 {{issue}},{{agent}}",
- "select_page": "選擇本頁已開啟的喚醒",
+ "select_page": "選擇所有已開啟的喚醒",
"load_error": "無法載入喚醒",
"loading": "正在載入喚醒…",
"empty": "暫無喚醒規則",
- "selected": "已選擇 {{count}} 項",
"disable_selected": "關閉所選",
- "clear": "清除選擇",
- "results": "第 {{page}} 頁 · 共 {{count}} 項",
- "previous": "上一頁",
- "next_page": "下一頁",
"confirm_title": "關閉 {{count}} 個喚醒?",
"confirm_body": "關閉後將停止後續喚醒,並撤回仍在排隊、尚未交給智慧體的執行。已交給智慧體的執行會繼續,可在執行日誌中停止。",
"cancel": "取消",
@@ -506,7 +494,7 @@
"batch_result": "已關閉 {{succeeded}} 項,失敗 {{failed}} 項。",
"scopes": {
"active": "待喚醒或執行中",
- "all": "全部",
+ "all": "全部喚醒",
"disabled": "已關閉",
"ended": "已結束",
"paused": "已暫停"
@@ -518,7 +506,7 @@
"batch_partial": "已關閉 {{succeeded}} 條,{{failed}} 條失敗;失敗項仍保留選中,可重試。",
"source": "來源",
"sources": {
- "all": "來源:全部",
+ "all": "全部來源",
"member": "成員",
"agent": "智慧體",
"system": "系統"
diff --git a/packages/views/locales/zh-Hant/chat.json b/packages/views/locales/zh-Hant/chat.json
index 39470d1c92..9082ac4589 100644
--- a/packages/views/locales/zh-Hant/chat.json
+++ b/packages/views/locales/zh-Hant/chat.json
@@ -243,7 +243,6 @@
"row_actions_aria": "聊天操作"
},
"header": {
- "view_profile": "檢視智慧體資料",
"rename": "重新命名會話",
"delete": "刪除會話",
"archive": "歸檔會話",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index bcfd21c185..2e14116a84 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -155,6 +155,7 @@
},
"filters": {
"tooltip": "篩選",
+ "active_section": "已啟用",
"placeholder": "篩選...",
"search_status": "搜尋狀態...",
"no_results": "無結果",
@@ -171,6 +172,15 @@
"section_project": "專案",
"section_project_status": "專案狀態",
"section_label": "標籤",
+ "section_relation": "與我的關係",
+ "relation_assigned": "分配給我的",
+ "relation_created": "我建立的",
+ "relation_my_agents": "分配給我的智慧體的",
+ "operator_label": "關係",
+ "operator_is": "是",
+ "operator_is_not": "不是",
+ "modified_hint": "相對檢視有變更",
+ "unsaved_changes_other": "{{count}} 處未儲存的變更",
"section_date": "日期",
"date_field": "欄位",
"date_field_created": "建立時間",
@@ -194,7 +204,54 @@
"active_count_other": "{{count}} 個篩選",
"in_view": "已包含在檢視中",
"chip_edit": "編輯",
- "chip_save_as": "另存"
+ "chip_save_as": "另存",
+ "section_due_date": "截止日期",
+ "due_overdue": "已逾期",
+ "due_today": "今天截止",
+ "due_this_week": "本週截止",
+ "due_next_7_days": "7 天內截止",
+ "due_none": "無截止日期",
+ "search_placeholder": "依欄位或值篩選…",
+ "search_fields": "欄位",
+ "search_values": "值",
+ "advanced_switch": "切換到進階篩選",
+ "advanced_title": "進階篩選",
+ "advanced_match_leading": "滿足",
+ "advanced_match_trailing": "條件",
+ "match_all": "全部",
+ "match_any": "任一",
+ "advanced_where": "當",
+ "advanced_and": "且",
+ "advanced_or": "或",
+ "advanced_add_condition": "新增條件",
+ "advanced_add_group": "新增條件組",
+ "advanced_unknown_property": "已刪除的屬性",
+ "advanced_values_placeholder": "選擇值…",
+ "advanced_field_label": "欄位",
+ "advanced_values_label": "值",
+ "advanced_actions": "條件操作",
+ "advanced_duplicate": "複製",
+ "advanced_delete": "刪除",
+ "advanced_delete_group": "刪除條件組",
+ "advanced_to_simple": "切回簡單篩選",
+ "advanced_to_simple_blocked": "含條件組、「任一」或重複欄位,簡單篩選無法表達",
+ "advanced_clear": "清除全部",
+ "advanced_empty": "還沒有條件,新增一條開始篩選。",
+ "advanced_conditions_other": "{{count}} 個條件",
+ "operator_has_any": "包含任一",
+ "operator_has_none": "都不包含",
+ "operator_contains": "包含",
+ "operator_not_contains": "不包含",
+ "operator_before": "早於",
+ "operator_after": "晚於",
+ "operator_empty": "為空",
+ "operator_not_empty": "不為空",
+ "advanced_group_match_leading": "滿足組內",
+ "advanced_group_match_trailing": "條件",
+ "advanced_group_hint": "組內條件之間用「{{word}}」連接",
+ "advanced_add_to_group": "新增到條件組",
+ "advanced_turn_into_group": "轉為條件組",
+ "advanced_summary": "篩選:{{summary}}"
},
"display": {
"tooltip": "顯示設定",
@@ -204,6 +261,7 @@
"card_properties_section": "卡片屬性",
"columns_section": "欄",
"columns_locked_by_filter": "清除狀態篩選後才能顯示或隱藏欄。",
+ "columns_shown": "顯示 {{count}} 欄",
"ascending_title": "升序",
"descending_title": "降序",
"newest_first": "最新優先",
@@ -236,7 +294,8 @@
"card_project": "專案",
"card_labels": "標籤",
"card_child_progress": "子任務進度",
- "show_sub_issues": "顯示子任務"
+ "show_sub_issues": "顯示子任務",
+ "layout_options": "{{layout}}選項"
},
"view": {
"tooltip_board": "看板檢視",
@@ -956,38 +1015,6 @@
"row_todo_hint": "啟動智慧體"
},
"save_view": {
- "title": "儲存為檢視",
- "hint_workspace": "基於工作區全部任務建立",
- "hint_my_any": "基於「我的任務 · 全部」建立",
- "hint_my_assigned": "基於「我的任務 · 分配給我」建立",
- "hint_my_created": "基於「我的任務 · 我建立的」建立",
- "hint_my_involved": "基於「我的任務 · 我參與的」建立",
- "hint_project": "基於專案「{{title}}」建立,僅在該專案頁面可用",
- "hint_project_agents": "基於專案「{{title}}」中智慧體負責的任務建立,僅在該專案頁面可用",
- "hint_project_members": "基於專案「{{title}}」中成員負責的任務建立,僅在該專案頁面可用",
- "my_private_note": "我的任務檢視僅自己可見",
- "name_label": "名稱",
- "visibility_label": "可見性",
- "visibility_private": "僅自己可見",
- "visibility_workspace": "工作區成員可見",
- "filters_label": "篩選",
- "custom_property": "自定義屬性",
- "create": "建立檢視",
- "layout_label": "佈局",
- "display_defaults": "預設顯示",
- "default_hint": "成員首次開啟此檢視時的顯示方式,之後各自可調",
- "add_filter": "新增篩選",
- "name_placeholder": "例如:需要 Review",
- "cancel": "取消",
- "name_required": "請輸入檢視名稱",
- "toast_created": "檢視已建立",
- "toast_failed": "建立檢視失敗",
- "edit_title": "編輯檢視",
- "update": "儲存修改",
- "toast_updated": "檢視已更新",
- "toast_conflict": "檢視已被他人修改,請重新開啟後再試",
- "hint_workspace_members": "基於工作區中成員負責的任務建立",
- "hint_workspace_agents": "基於工作區中智慧體負責的任務建立",
"scope_label_workspace": "負責人型別",
"scope_label_my": "與我的關係",
"variant_all": "不限負責人",
@@ -998,36 +1025,6 @@
"variant_my_created": "我建立的",
"variant_my_involved": "我參與的"
},
- "view_selector": {
- "trigger": "檢視",
- "empty": "還沒有儲存的檢視",
- "private_group": "私有",
- "shared_group": "工作區共享",
- "exit": "退出檢視",
- "unavailable": "該檢視已不可用",
- "edit": "編輯檢視"
- },
- "view_bar": {
- "menu_label": "檢視",
- "menu_new": "新增檢視",
- "builtin_tag": "內建",
- "drag_handle": "拖拽排序",
- "delete": "刪除",
- "delete_title": "刪除檢視?",
- "delete_description": "「{{name}}」將對所有可見成員刪除",
- "toast_deleted": "檢視已刪除",
- "context_edit": "編輯檢視",
- "context_pin": "固定到側欄",
- "context_unpin": "從側欄取消固定",
- "row_menu": "更多操作",
- "row_hide": "在欄中隱藏",
- "row_show": "在欄中顯示",
- "menu_manage": "管理檢視",
- "manage_title": "管理檢視",
- "manage_hint": "排序與顯隱隻影響你自己",
- "visible_toggle": "在檢視欄顯示",
- "more_label": "更多檢視"
- },
"plugins": {
"panels": "Plugins",
"surface_failed": "{{name}} 的介面載入失敗。",
@@ -1708,5 +1705,67 @@
},
"hover_card": {
"created_updated": "建立於 {{created}} · 更新於 {{updated}}"
+ },
+ "views": {
+ "builtin": {
+ "my_issues": "我的任務",
+ "my_agents": "我的智慧體在做",
+ "all_issues": "全部任務"
+ },
+ "untitled": "未命名檢視",
+ "copy_name": "{{name}}(副本)",
+ "rename": "重新命名",
+ "duplicate": "建立副本",
+ "copy_link": "複製連結",
+ "link_copied": "連結已複製",
+ "visible_to": "可見範圍",
+ "only_me": "僅自己",
+ "workspace_members": "工作區成員",
+ "add_to_sidebar": "新增到側欄",
+ "remove_from_sidebar": "從側欄移除",
+ "back_to": "返回{{name}}",
+ "delete": "刪除檢視",
+ "delete_title": "刪除檢視?",
+ "delete_description": "「{{name}}」將被刪除,此操作無法復原。",
+ "delete_description_shared": "「{{name}}」已共享給工作區,刪除後所有人都將無法使用。",
+ "cancel": "取消",
+ "toast_deleted": "檢視已刪除",
+ "toast_delete_failed": "刪除檢視失敗",
+ "filter": "篩選",
+ "filter_count_other": "{{count}} 個篩選",
+ "reset": "重設",
+ "save": "儲存",
+ "save_options": "更多儲存選項",
+ "save_to": "儲存到「{{name}}」",
+ "save_to_hint_shared": "為工作區所有人更新此檢視",
+ "save_to_hint_private": "更新你的檢視",
+ "save_as_new": "另存為新檢視",
+ "save_as_new_hint": "「{{name}}」保持不變",
+ "save_as_view": "儲存為檢視",
+ "set_by_view": "由此檢視設定",
+ "new_issue": "新增任務",
+ "unavailable": "此檢視已無法使用",
+ "toast_saved": "檢視已儲存",
+ "toast_conflict": "檢視已被他人修改,請重新整理後再試",
+ "toast_create_failed": "建立檢視失敗",
+ "toast_save_failed": "儲存檢視失敗",
+ "directory": {
+ "new_view": "新增檢視",
+ "scope_all": "全部檢視",
+ "scope_builtin": "內建",
+ "scope_mine": "我建立的",
+ "scope_shared": "已共享",
+ "col_name": "名稱",
+ "col_location": "位置",
+ "col_filters": "篩選",
+ "col_visibility": "可見範圍",
+ "col_owner": "擁有者",
+ "owner_builtin": "內建",
+ "location_project": "專案",
+ "star": "將{{name}}新增到側欄",
+ "unstar": "將{{name}}從側欄移除",
+ "row_actions": "{{name}} 的操作",
+ "no_matches": "沒有符合的檢視"
+ }
}
}
diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.json
index 70741113f9..ba57f0da64 100644
--- a/packages/views/locales/zh-Hant/layout.json
+++ b/packages/views/locales/zh-Hant/layout.json
@@ -11,7 +11,8 @@
"usage": "統計",
"runtimes": "執行時",
"skills": "Skills",
- "settings": "設定"
+ "settings": "設定",
+ "views": "檢視"
},
"tab": {
"issue": "任務",
@@ -25,6 +26,7 @@
"runtime": "執行時",
"attachment": "附件",
"create_agent": "建立智慧體",
+ "my_agents": "我的智慧體在做",
"unknown": "未知頁面"
},
"help": {
@@ -57,16 +59,114 @@
"invitation_decline": "拒絕",
"log_out": "退出登入",
"new_issue": "新建任務",
- "new_issue_shortcut": "C",
"pinned_label": "固定",
- "work_group": "工作",
- "ai_team_group": "AI 團隊",
"show_more_pins": "再顯示 {{count}} 項...",
- "show_fewer_pins": "收起",
- "unread_overflow": "99+",
- "discord_card": {
- "title": "加入 Discord",
- "dismiss": "關閉"
+ "show_fewer_pins": "收起"
+ },
+ "spaces": {
+ "work": "任務",
+ "team": "團隊"
+ },
+ "rail": {
+ "label": "應用導覽",
+ "sheet_description": "切換空間和工作區。",
+ "inbox": "收件箱",
+ "work": "任務",
+ "team": "團隊",
+ "chat": "聊天",
+ "autopilots": "自動化",
+ "switch_workspace": "切換工作區",
+ "invitation_from": "{{name}} 邀請你加入"
+ },
+ "panels": {
+ "work": {
+ "my_agents": "我的智慧體在做",
+ "all_issues": "全部任務",
+ "views": "檢視",
+ "new_project": "新建專案",
+ "new_issue_in_project": "在 {{name}} 中新建任務",
+ "all_projects_other": "全部 {{count}} 個專案",
+ "project_issues": "{{name}} 的任務",
+ "project_issues_empty": "沒有任務",
+ "project_issues_error": "無法載入任務",
+ "project_issues_settings": "專案中的任務",
+ "settings_status": "狀態",
+ "settings_assignee": "負責人",
+ "assignee_anyone": "所有人",
+ "assignee_me": "我",
+ "assignee_my_agents": "我的智慧體",
+ "reset": "重設",
+ "load_more": "載入更多",
+ "show_less": "收合",
+ "projects_settings": "專案顯示",
+ "projects_ordering": "排序",
+ "projects_order_manual": "手動",
+ "projects_order_name": "名稱",
+ "projects_order_updated": "最近更新",
+ "projects_order_created": "最近建立",
+ "projects_show": "顯示",
+ "projects_only_mine": "只看我負責的專案",
+ "projects_show_count": "未完成任務數",
+ "new_view": "新增檢視",
+ "all_views": "全部檢視",
+ "view_actions": "{{name}} 的操作",
+ "view_copy_link": "複製連結",
+ "view_remove": "從側欄移除",
+ "view_rename": "重新命名",
+ "view_duplicate": "建立副本",
+ "view_delete": "刪除檢視"
+ },
+ "team": {
+ "new_agent": "新建智慧體",
+ "needs_attention": "需要處理",
+ "stuck_other": "{{count}} 個任務在等待離線的執行時",
+ "working_now": "正在工作",
+ "running_tasks_other": "{{count}} 個任務執行中",
+ "all_agents": "全部智慧體",
+ "my_agents": "我的智慧體",
+ "squads_and_members": "小隊與成員",
+ "members_other": "{{count}} 位成員",
+ "resources": "資源",
+ "runtimes_offline_other": "{{count}} 個離線",
+ "invite_member": "邀請成員"
+ },
+ "autopilots": {
+ "all": "全部自動化",
+ "list": "自動化",
+ "templates": "從範本開始"
}
+ },
+ "account": {
+ "trigger": "帳戶",
+ "profile": "個人資料",
+ "theme": "主題",
+ "themes": {
+ "light": "淺色",
+ "dark": "深色",
+ "system": "跟隨系統"
+ },
+ "language": "語言",
+ "shortcuts": "快捷鍵"
+ },
+ "collection": {
+ "filter": "篩選",
+ "filter_count_other": "{{count}} 個篩選",
+ "reset": "重設",
+ "display": "顯示設定",
+ "selected_other": "已選 {{count}} 項",
+ "clear_selection": "清除選擇",
+ "select_all": "全選",
+ "select_row": "選擇此列",
+ "row_actions": "更多操作",
+ "sort_by": "排序",
+ "direction_asc": "升序",
+ "direction_desc": "降序",
+ "section_columns": "欄",
+ "load_more": "載入更多",
+ "loading_more": "載入中…"
+ },
+ "object_page": {
+ "toggle_panel": "切換右側邊欄",
+ "properties": "屬性"
}
}
diff --git a/packages/views/locales/zh-Hant/members.json b/packages/views/locales/zh-Hant/members.json
index 9b1eaf78f2..626d0781d6 100644
--- a/packages/views/locales/zh-Hant/members.json
+++ b/packages/views/locales/zh-Hant/members.json
@@ -11,8 +11,11 @@
"more_agents_other": "另有 {{count}} 個智慧體"
},
"detail": {
- "workspace_fallback": "工作區",
"members_breadcrumb": "成員",
+ "role": "角色",
+ "email": "電子郵件",
+ "joined": "加入時間",
+ "relation": "關係",
"breadcrumb_fallback": "成員",
"not_found_title": "未找到該成員",
"not_found_description": "該成員可能已經離開工作區。"
diff --git a/packages/views/locales/zh-Hant/projects.json b/packages/views/locales/zh-Hant/projects.json
index 4ba3e42691..30f8ec2384 100644
--- a/packages/views/locales/zh-Hant/projects.json
+++ b/packages/views/locales/zh-Hant/projects.json
@@ -2,11 +2,13 @@
"page": {
"title": "專案",
"new_project": "新建專案",
+ "scope_all": "全部專案",
+ "scope_active": "進行中的專案",
+ "scope_closed": "已結束的專案",
"empty": "還沒有專案",
"create_first": "建立第一個專案",
"view_compact": "緊湊檢視",
"view_comfortable": "舒適檢視",
- "search_placeholder": "搜尋專案...",
"no_search_results": "未找到匹配的專案",
"view_table": "表格",
"view_cards": "卡片",
@@ -14,9 +16,7 @@
"pin": "固定到側邊欄",
"unpin": "取消釘選",
"delete": "刪除",
- "no_matches": "沒有匹配的專案",
- "selected_other": "已選 {{count}} 項",
- "clear_selection": "清除選擇"
+ "no_matches": "沒有匹配的專案"
},
"table": {
"name": "名稱",
@@ -167,18 +167,9 @@
"fallback_label": "專案"
},
"toolbar": {
- "result_count_title": "當前結果 / 全部專案",
- "filter_label": "篩選",
- "filter_active_count_other": "{{count}} 項篩選",
- "clear_filters": "清除篩選",
"section_status": "狀態",
"section_priority": "優先順序",
"section_lead": "負責人",
- "display": "顯示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列",
"view": "檢視"
}
}
diff --git a/packages/views/locales/zh-Hant/runtimes.json b/packages/views/locales/zh-Hant/runtimes.json
index 936d3c519d..cc90c40d1d 100644
--- a/packages/views/locales/zh-Hant/runtimes.json
+++ b/packages/views/locales/zh-Hant/runtimes.json
@@ -1,9 +1,7 @@
{
"page": {
"title": "執行時",
- "learn_more": "瞭解更多 →",
"connect_remote": "新增機器",
- "search_placeholder": "搜尋...",
"scope_mine": "我的",
"scope_all": "全部",
"live": "實時",
@@ -25,7 +23,7 @@
"title": "正在啟動本地執行時...",
"hint": "正在連線工作區..."
},
- "add": "新增",
+ "add": "新增執行時",
"add_menu": {
"machines": "機器",
"this_computer": "這臺電腦",
@@ -67,7 +65,7 @@
"no_matches": "沒有匹配的機器或雲服務"
},
"filters": {
- "all": "全部",
+ "all": "全部執行時",
"online": "線上",
"offline": "離線"
}
@@ -93,7 +91,7 @@
"this_machine": "本機",
"local_badge": "本地 · 這臺機器",
"pending_custom_runtimes": "待註冊自定義執行時",
- "runtime_count_other": "{{count}} 個執行時",
+ "daemon_title": "守護程序",
"busy_count_other": "{{count}} 個忙碌",
"no_matches_title": "沒有機器",
"no_matches_hint": "沒有機器匹配當前搜尋或篩選。",
@@ -158,13 +156,10 @@
"fact_owner": "所有者",
"fact_device": "裝置",
"fact_runtime": "執行時",
- "technical_details": "技術詳情",
"fact_daemon_cli": "守護程序 CLI",
"fact_daemon_id": "守護程序 ID",
- "serving_title": "服務中",
- "serving_count_other": "{{count}} 個智慧體",
+ "usage_title": "用量",
"no_agents": "還沒有智慧體繫結到這個執行時。",
- "diagnostics_title": "診斷",
"diagnostics_cli": "CLI",
"diagnostics_visibility": "可見性",
"visibility_label": {
diff --git a/packages/views/locales/zh-Hant/skills.json b/packages/views/locales/zh-Hant/skills.json
index 82716167e9..6f88a73063 100644
--- a/packages/views/locales/zh-Hant/skills.json
+++ b/packages/views/locales/zh-Hant/skills.json
@@ -1,12 +1,10 @@
{
"page": {
"title": "Skills",
- "learn_more": "瞭解更多 →",
"new_skill": "新建 skill",
- "search_placeholder": "搜尋 skill...",
"scopes": {
"all": {
- "label": "全部",
+ "label": "全部 skill",
"description": "工作區裡所有 skill"
},
"used": {
@@ -18,7 +16,7 @@
"description": "未分配給任何智慧體的 skill"
},
"mine": {
- "label": "我建立的",
+ "label": "我的 skill",
"description": "你建立的 skill"
}
},
@@ -76,8 +74,6 @@
"added_toast": "已新增到 {{name}}",
"add_failed_toast": "新增 skill 失敗",
"delete": "刪除",
- "selected": "已選 {{count}} 項",
- "clear_selection": "清除選擇",
"delete_no_permission": "選中項包含僅建立者或管理員可刪除的 skill",
"delete_dialog_title_other": "刪除 {{count}} 個 skill?",
"delete_dialog_desc_other": "將永久刪除選中的 {{count}} 個 skill,並從所有智慧體上移除。",
@@ -98,28 +94,16 @@
"added_multi_toast_other": "已新增到 {{count}} 個智慧體"
},
"toolbar": {
- "result_count_title": "當前結果 / 全部 skill",
- "filter_label": "篩選",
- "filter_active_count_other": "{{count}} 項篩選",
- "clear_filters": "清除篩選",
"section_usage": "使用狀態",
"section_labels": "標籤",
"filter_search_placeholder": "篩選...",
"no_labels": "還沒有標籤",
"no_results": "無結果",
- "display": "顯示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "顯示列",
"manage_labels": "管理標籤...",
"manage_labels_title": "Skill 標籤"
},
"detail": {
- "all_skills": "全部 skill",
"read_only": "只讀",
- "delete_aria": "刪除 skill",
- "delete_tooltip": "刪除 skill",
"supporting_data_warning": "部分工作區資料載入失敗。建立者歸屬、執行時名稱、編輯權限可能要等下次重新整理才完整。",
"delete_file": "刪除檔案",
"name_placeholder": "skill-name",
@@ -154,8 +138,6 @@
"toast_deleted": "已刪除 skill",
"toast_delete_failed": "刪除 skill 失敗",
"refresh": {
- "button": "更新",
- "tooltip": "從來源重新下載這個 skill",
"source_github": "GitHub",
"source_skills_sh": "Skills.sh",
"source_clawhub": "ClawHub",
@@ -194,29 +176,18 @@
}
},
"header": {
- "files_other": "{{count}} 個檔案",
- "used_by_other": "{{count}} 個智慧體在用",
- "updated": "{{when}}更新",
- "updated_by": "{{name}} 於{{when}}更新"
- },
- "tabs": {
- "aria": "技能分區",
- "overview": "概覽",
- "files_other": "檔案 {{count}}"
+ "files_other": "{{count}} 個檔案"
},
"overview": {
"properties": "屬性",
- "properties_hint": "這些欄位與 SKILL.md 的 frontmatter 保持同步。",
"name": "名稱",
"description": "描述",
"description_hint": "智慧體據此決定何時載入 skill。",
"labels": "標籤",
- "used_by_other": "被 {{count}} 個智慧體使用",
"used_by_empty": "還未分配給任何智慧體。開啟某個智慧體的 Skills 標籤頁進行分配。",
"permissions_owner": "你可以編輯和刪除該技能。改動將在智慧體下次執行時生效。",
"permissions_locked_creator": "只有建立者({{name}})或工作區管理員可以編輯該技能。",
"permissions_locked": "只有建立者或工作區管理員可以編輯該技能。",
- "properties_help": "關於 skill 屬性",
"character_count": "{{count}} 個字元"
},
"files": {
@@ -229,6 +200,21 @@
"mode_preview": "預覽",
"mode_edit": "編輯",
"mode_raw": "純文字"
+ },
+ "sections": {
+ "content": "內容",
+ "files": "檔案",
+ "edit": "編輯",
+ "open": "開啟",
+ "add": "新增"
+ },
+ "menu": {
+ "copy_link": "複製連結",
+ "link_copied": "已複製連結",
+ "delete": "刪除 skill"
+ },
+ "panel": {
+ "add_description": "新增描述"
}
},
"create": {
diff --git a/packages/views/locales/zh-Hant/squads.json b/packages/views/locales/zh-Hant/squads.json
index 990fa59812..ca61d96b61 100644
--- a/packages/views/locales/zh-Hant/squads.json
+++ b/packages/views/locales/zh-Hant/squads.json
@@ -15,10 +15,6 @@
"row_menu": "小隊操作",
"archive_action": "歸檔"
},
- "inspector": {
- "details_section": "詳情",
- "archive_button": "歸檔"
- },
"member_type": {
"agent": "智慧體",
"member": "成員"
@@ -65,15 +61,8 @@
"responsibility_placeholder": "這個小隊負責什麼?",
"save": "儲存"
},
- "discard_changes_dialog": {
- "title": "放棄未儲存的修改?",
- "description": "當前標籤頁有未儲存的修改,切換標籤會丟棄這些修改。",
- "keep_editing": "繼續編輯",
- "discard_button": "放棄"
- },
"members_tab": {
"section_title": "成員",
- "section_count_other": "該小隊有 {{count}} 名成員",
"add_member_button": "新增成員",
"create_agent_button": "建立智慧體",
"leader_chip": "隊長",
@@ -86,19 +75,29 @@
"status_unstable": "不穩定",
"status_archived": "已歸檔",
"issue_status_blocked": "已阻塞",
- "active_issue_more": "還有 {{count}} 個",
- "last_active_label": "最近活動 {{time}}"
- },
- "detail_tabs": {
- "members": "成員",
- "instructions": "指引"
+ "active_issue_more": "還有 {{count}} 個"
+ },
+ "detail": {
+ "assign_work": "指派工作",
+ "copy_link": "複製連結",
+ "link_copied": "已複製連結",
+ "not_found": "找不到該小隊",
+ "instructions": "指引",
+ "edit": "編輯",
+ "cancel": "取消",
+ "recent_work": "近期工作",
+ "recent_work_empty": "還沒有指派給這個小隊的任務。",
+ "member_menu": "{{name}} 的操作",
+ "working_on": "正在處理"
},
"details": {
"leader": "隊長",
"members": "成員",
"created_by": "建立者",
"created": "建立時間",
- "updated": "更新時間"
+ "updated": "更新時間",
+ "visibility": "可見範圍",
+ "visibility_workspace": "工作區"
},
"toasts": {
"member_added": "已新增成員",
@@ -127,18 +126,8 @@
"placeholder": "例如:始終先編寫失敗測試。提交應保持小而獨立。"
},
"scope": {
- "mine": "我的",
- "all": "全部"
+ "mine": "我的小隊",
+ "all": "全部小隊"
},
- "toolbar": {
- "display": "顯示",
- "sort_by": "排序",
- "direction_asc": "升序",
- "direction_desc": "降序",
- "section_columns": "列",
- "result_count_title": "當前結果 / 全部小隊",
- "filter_label": "篩選",
- "filter_active_count_other": "{{count}} 項篩選",
- "clear_filters": "清除篩選"
- }
+ "toolbar": {}
}
diff --git a/packages/views/members/member-detail-page.test.tsx b/packages/views/members/member-detail-page.test.tsx
new file mode 100644
index 0000000000..020672f05b
--- /dev/null
+++ b/packages/views/members/member-detail-page.test.tsx
@@ -0,0 +1,155 @@
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, screen, within } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { actorIssuesViewStore } from "@multica/core/issues/stores/actor-issues-view-store";
+import type { Agent, MemberWithUser } from "@multica/core/types";
+import {
+ agentListOptions,
+ memberListOptions,
+} from "@multica/core/workspace/queries";
+import { renderWithI18n } from "../test/i18n";
+import { MemberDetailPage } from "./member-detail-page";
+
+const WS = "ws-test";
+const surfaceProps = vi.hoisted(() => ({ current: null as Record<string, unknown> | null }));
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ settings: () => "/acme/settings",
+ agentDetail: (id: string) => `/acme/agents/${id}`,
+ }),
+}));
+vi.mock("@multica/core/issues/stores/view-store-context", () => ({
+ useViewStore: (select: (state: unknown) => unknown) =>
+ select({ advancedFilter: null, clearFilters: vi.fn() }),
+}));
+vi.mock("../navigation", () => ({
+ AppLink: ({ href, children, ...props }: { href: string; children: ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("../issues/components/filter-chips-bar", () => ({
+ useFilterChips: () => ({ chips: [] }),
+}));
+vi.mock("../issues/components/issues-header", () => ({
+ IssueFilterMenu: ({ trigger }: { trigger: ReactNode }) => <>{trigger}</>,
+ IssueDisplayControls: () => <button type="button">Display</button>,
+ ViewRefreshIndicator: () => null,
+}));
+vi.mock("../issues/surface/issue-surface", () => ({
+ IssueSurface: (props: {
+ renderHeader: (context: { controller: unknown; issues: unknown[] }) => ReactNode;
+ }) => {
+ surfaceProps.current = props;
+ return (
+ <div data-testid="issue-surface">
+ {props.renderHeader({
+ controller: {
+ surfaceIssues: [],
+ isRefreshing: false,
+ facetCountsExact: true,
+ setActiveTableFacet: vi.fn(),
+ },
+ issues: [],
+ })}
+ </div>
+ );
+ },
+}));
+
+const MEMBER: MemberWithUser = {
+ id: "m-1",
+ workspace_id: WS,
+ user_id: "user-1",
+ role: "admin",
+ created_at: "2026-03-14T00:00:00Z",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ avatar_url: null,
+};
+
+function renderPage(userId = "user-1", members: MemberWithUser[] | null = [MEMBER]) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ if (members) qc.setQueryData(memberListOptions(WS).queryKey, members);
+ qc.setQueryData(agentListOptions(WS).queryKey, [
+ { id: "agent-1", name: "Babbage", owner_id: "user-1", archived_at: null },
+ { id: "agent-2", name: "Retired", owner_id: "user-1", archived_at: "2026-01-01" },
+ ] as Agent[]);
+ return renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <MemberDetailPage userId={userId} />
+ </QueryClientProvider>,
+ );
+}
+
+describe("MemberDetailPage", () => {
+ beforeEach(() => {
+ surfaceProps.current = null;
+ actorIssuesViewStore.getState().setScope("assigned");
+ });
+
+ it("puts the breadcrumb and the issue tools in one header above a full-width list", () => {
+ renderPage();
+
+ expect(screen.getAllByRole("banner")).toHaveLength(1);
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("link", { name: "Members" })).toHaveAttribute(
+ "href",
+ "/acme/settings?tab=members",
+ );
+ expect(header).toHaveTextContent("Ada Lovelace");
+ expect(within(header).queryByRole("button", { name: "Search issues..." })).not.toBeInTheDocument();
+ expect(within(header).getByRole("button", { name: "Filter" })).toBeInTheDocument();
+ expect(within(header).getByRole("button", { name: "Display" })).toBeInTheDocument();
+ expect(within(header).queryByRole("button", { name: "Reset" })).not.toBeInTheDocument();
+ expect(screen.getByTestId("issue-surface")).toBeInTheDocument();
+ expect(surfaceProps.current?.scope).toEqual({
+ type: "actor",
+ actorType: "member",
+ actorId: "user-1",
+ relation: "assigned",
+ });
+ });
+
+ it("shows who the member is in the properties panel", () => {
+ renderPage();
+
+ expect(screen.getByRole("button", { name: "Properties" })).toBeInTheDocument();
+ expect(screen.getByText("Role")).toBeInTheDocument();
+ expect(screen.getByText("Admin")).toBeInTheDocument();
+ expect(screen.getByText("[email protected]")).toBeInTheDocument();
+ expect(screen.getByText("Joined")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Babbage" })).toHaveAttribute(
+ "href",
+ "/acme/agents/agent-1",
+ );
+ expect(screen.queryByText("Retired")).not.toBeInTheDocument();
+ });
+
+ it("counts the Created relation as a filter and resets it", () => {
+ actorIssuesViewStore.getState().setScope("created");
+ renderPage();
+
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("button", { name: "1 filter" })).toBeInTheDocument();
+ fireEvent.click(within(header).getByRole("button", { name: "Reset" }));
+ expect(actorIssuesViewStore.getState().scope).toBe("assigned");
+ });
+
+ it("shows not-found in the body under the Members breadcrumb", () => {
+ renderPage("missing");
+
+ expect(
+ within(screen.getByRole("banner")).getByRole("link", { name: "Members" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Member not found" })).toBeInTheDocument();
+ expect(screen.queryByTestId("issue-surface")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/members/member-detail-page.tsx b/packages/views/members/member-detail-page.tsx
index a00e1269ab..afc8c3809d 100644
--- a/packages/views/members/member-detail-page.tsx
+++ b/packages/views/members/member-detail-page.tsx
@@ -1,143 +1,337 @@
"use client";
-import { ChevronRight, UserRound } from "@multica/ui/icons";
+import { useMemo, useState } from "react";
+import { createPortal } from "react-dom";
+import { useStore } from "zustand";
+import { ListTodo, UserRound, Users } from "@multica/ui/icons";
import { useQuery } from "@tanstack/react-query";
-import type { MemberRole } from "@multica/core/types";
+import type { MemberRole, MemberWithUser } from "@multica/core/types";
import { useWorkspaceId } from "@multica/core/hooks";
-import { useCurrentWorkspace } from "@multica/core/paths";
-import { memberListOptions } from "@multica/core/workspace/queries";
-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
+import {
+ actorIssuesViewStore,
+ type ActorIssuesScope,
+} from "@multica/core/issues/stores/actor-issues-view-store";
+import { countAdvancedConditions } from "@multica/core/issues/stores/filter-tree";
+import { useViewStore } from "@multica/core/issues/stores/view-store-context";
+import {
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { PageHeader } from "../layout/page-header";
-import { WorkspaceAvatar } from "../workspace/workspace-avatar";
-import { ActorIssuesPanel } from "../common/actor-issues-panel";
-import { useT } from "../i18n";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../common/actor-avatar";
+import {
+ IssueDisplayControls,
+ IssueFilterMenu,
+ ViewRefreshIndicator,
+} from "../issues/components/issues-header";
+import { useFilterChips } from "../issues/components/filter-chips-bar";
+import { IssueSurface } from "../issues/surface/issue-surface";
+import type { IssueSurfaceController } from "../issues/surface/use-issue-surface-controller";
+import {
+ CollectionFilterButton,
+ CollectionPageState,
+ CollectionResetButton,
+} from "../layout/collection-page";
+import {
+ ObjectPage,
+ ObjectPanelSection,
+ ObjectProperty,
+} from "../layout/object-page";
+import { AppLink } from "../navigation";
+import { useLocale, useT } from "../i18n";
+const LAYOUT_ID = "multica_member_detail_layout";
+const SCOPE_VALUES: ActorIssuesScope[] = ["assigned", "created"];
+
+/**
+ * A member's page is the list of issues assigned to or created by them, so it
+ * keeps the list full width under the breadcrumb header; who they are sits in
+ * the properties panel.
+ */
export function MemberDetailPage({ userId }: { userId: string }) {
const { t } = useT("members");
const wsId = useWorkspaceId();
- const workspace = useCurrentWorkspace();
+ const paths = useWorkspacePaths();
const { data: members = [], isLoading } = useQuery(memberListOptions(wsId));
const member = members.find((m) => m.user_id === userId) ?? null;
+ const segments = [
+ {
+ href: `${paths.settings()}?tab=members`,
+ label: t(($) => $.detail.members_breadcrumb),
+ },
+ ];
- if (isLoading && !member) {
- return <MemberDetailSkeleton />;
- }
+ if (member) return <MemberIssues member={member} segments={segments} />;
- if (!member) {
+ if (isLoading) {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <MemberBreadcrumb workspaceName={workspace?.name} workspaceAvatarUrl={workspace?.avatar_url} title={t(($) => $.detail.breadcrumb_fallback)} />
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
- <UserRound className="h-8 w-8 text-muted-foreground" />
- <div>
- <p className="text-body font-medium">{t(($) => $.detail.not_found_title)}</p>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.detail.not_found_description)}
- </p>
- </div>
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={<Skeleton className="h-4 w-32" />}
+ panel={<PanelSkeleton />}
+ >
+ <div className="space-y-2 p-4">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-8 w-full" />
+ ))}
</div>
- </div>
+ </ObjectPage>
);
}
- const initials = member.name
- .split(" ")
- .map((w) => w[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
-
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <MemberBreadcrumb workspaceName={workspace?.name} workspaceAvatarUrl={workspace?.avatar_url} title={member.name} />
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.detail.breadcrumb_fallback)}
+ </span>
+ }
+ >
+ <CollectionPageState
+ icon={UserRound}
+ title={t(($) => $.detail.not_found_title)}
+ description={t(($) => $.detail.not_found_description)}
+ />
+ </ObjectPage>
+ );
+}
- <div className="flex shrink-0 items-center gap-3 border-b px-6 py-4">
- <ActorAvatarBase
- name={member.name}
- initials={initials}
- avatarUrl={resolvePublicFileUrl(member.avatar_url)}
- size="xl"
- className="rounded-full"
+function MemberIssues({
+ member,
+ segments,
+}: {
+ member: MemberWithUser;
+ segments: { href: string; label: string }[];
+}) {
+ const { t } = useT("issues");
+ const scope = useStore(actorIssuesViewStore, (s) => s.scope);
+ const setScope = useStore(actorIssuesViewStore, (s) => s.setScope);
+ // The tools read the issue surface's view store and controller, which only
+ // exist inside the surface, so they render there and portal into the header.
+ const [toolsSlot, setToolsSlot] = useState<HTMLDivElement | null>(null);
+ const surfaceScope = useMemo(
+ () =>
+ ({
+ type: "actor" as const,
+ actorType: "member" as const,
+ actorId: member.user_id,
+ relation: scope,
+ }),
+ [member.user_id, scope],
+ );
+
+ return (
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={
+ <span className="flex min-w-0 items-center gap-1.5">
+ <ActorAvatar
+ actorType="member"
+ actorId={member.user_id}
+ size="xs"
+ profileLink={false}
+ />
+ <span className="truncate">{member.name}</span>
+ </span>
+ }
+ actions={<div ref={setToolsSlot} className="flex items-center gap-1" />}
+ panel={<MemberProperties member={member} />}
+ >
+ <div className="flex h-full min-h-0 flex-col">
+ <IssueSurface
+ scope={surfaceScope}
+ modes={["list"]}
+ batchToolbar="always"
+ contentClassName="p-1"
+ renderHeader={({ controller }) =>
+ toolsSlot
+ ? createPortal(
+ <MemberIssueTools
+ controller={controller}
+ scope={scope}
+ onScopeChange={setScope}
+ />,
+ toolsSlot,
+ )
+ : null
+ }
+ renderEmpty={() => (
+ <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 text-muted-foreground">
+ <ListTodo className="h-10 w-10 text-faint-foreground" />
+ <p className="text-body">
+ {t(($) => $.actor_issues.empty[scope].title)}
+ </p>
+ </div>
+ )}
/>
- <div className="min-w-0 flex-1">
- <div className="flex min-w-0 items-center gap-2">
- <h1 className="truncate text-title-sm font-semibold">{member.name}</h1>
- <RoleBadge role={member.role} />
- </div>
- <p className="mt-0.5 truncate text-body text-muted-foreground">
- {member.email}
- </p>
- </div>
</div>
-
- <ActorIssuesPanel actorType="member" actorId={userId} />
- </div>
+ </ObjectPage>
);
}
-function MemberBreadcrumb({
- workspaceName,
- workspaceAvatarUrl,
- title,
+function MemberIssueTools({
+ controller,
+ scope,
+ onScopeChange,
}: {
- workspaceName: string | undefined;
- workspaceAvatarUrl?: string | null;
- title: string;
+ controller: IssueSurfaceController;
+ scope: ActorIssuesScope;
+ onScopeChange: (scope: ActorIssuesScope) => void;
}) {
- const { t } = useT("members");
+ const { t } = useT("issues");
+ const { t: tMembers } = useT("members");
+ const advancedFilter = useViewStore((s) => s.advancedFilter);
+ const clearFilters = useViewStore((s) => s.clearFilters);
+ const { chips } = useFilterChips(null);
+ const scopeCounts = scope !== "assigned";
+ const filterCount =
+ chips.filter((chip) => chip.key !== "advanced").length +
+ countAdvancedConditions(advancedFilter) +
+ (scopeCounts ? 1 : 0);
+
return (
- <PageHeader className="gap-1.5">
- <WorkspaceAvatar name={workspaceName ?? "W"} avatarUrl={workspaceAvatarUrl} size="sm" />
- <span className="text-body text-muted-foreground">
- {workspaceName ?? t(($) => $.detail.workspace_fallback)}
- </span>
- <ChevronRight className="h-3 w-3 text-muted-foreground" />
- <span className="text-body text-muted-foreground">
- {t(($) => $.detail.members_breadcrumb)}
- </span>
- <ChevronRight className="h-3 w-3 text-muted-foreground" />
- <span className="truncate text-body font-medium">{title}</span>
- </PageHeader>
+ <>
+ <IssueFilterMenu
+ align="end"
+ trigger={<CollectionFilterButton count={filterCount} />}
+ leadingSections={
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Users className="size-3.5" />
+ <span className="flex-1">{tMembers(($) => $.detail.relation)}</span>
+ <span
+ className={cn(
+ "ml-3 text-caption font-medium",
+ scopeCounts ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ {t(($) => $.actor_issues.scope[scope].label)}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ <DropdownMenuRadioGroup
+ value={scope}
+ onValueChange={(next) => onScopeChange(next as ActorIssuesScope)}
+ >
+ {SCOPE_VALUES.map((value) => (
+ <DropdownMenuRadioItem key={value} value={value}>
+ {t(($) => $.actor_issues.scope[value].label)}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ }
+ scopedIssues={controller.surfaceIssues}
+ facetCountsExact={controller.facetCountsExact}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
+ />
+ {filterCount > 0 ? (
+ <CollectionResetButton
+ onClick={() => {
+ clearFilters();
+ onScopeChange("assigned");
+ }}
+ />
+ ) : null}
+ <IssueDisplayControls
+ scopedIssues={controller.surfaceIssues}
+ hideViewToggle
+ hideFilter
+ iconOnly
+ facetCountsExact={controller.facetCountsExact}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
+ />
+ <ViewRefreshIndicator active={controller.isRefreshing} />
+ </>
);
}
-function RoleBadge({ role }: { role: MemberRole }) {
+function MemberProperties({ member }: { member: MemberWithUser }) {
const { t } = useT("members");
+ const { t: tLayout } = useT("layout");
+ const locale = useLocale();
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const ownedAgents = agents.filter(
+ (agent) => agent.owner_id === member.user_id && !agent.archived_at,
+ );
+ const joined = new Date(member.created_at);
+
return (
- <span className="rounded-md bg-muted px-1.5 py-0.5 text-micro font-medium text-muted-foreground">
- {role === "owner"
- ? t(($) => $.role.owner)
- : role === "admin"
- ? t(($) => $.role.admin)
- : t(($) => $.role.member)}
- </span>
+ <div className="space-y-5">
+ <ObjectPanelSection title={tLayout(($) => $.object_page.properties)}>
+ <ObjectProperty label={t(($) => $.detail.role)}>
+ <span className="truncate">
+ <RoleLabel role={member.role} />
+ </span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.email)}>
+ <span className="truncate select-text" title={member.email}>
+ {member.email}
+ </span>
+ </ObjectProperty>
+ {Number.isFinite(joined.getTime()) && (
+ <ObjectProperty label={t(($) => $.detail.joined)}>
+ <span className="truncate">{joined.toLocaleDateString(locale)}</span>
+ </ObjectProperty>
+ )}
+ </ObjectPanelSection>
+ {ownedAgents.length > 0 && (
+ <ObjectPanelSection
+ title={t(($) => $.card.agents_section, { count: ownedAgents.length })}
+ >
+ {ownedAgents.map((agent) => (
+ <AppLink
+ key={agent.id}
+ href={paths.agentDetail(agent.id)}
+ className="-mx-2 flex min-h-8 items-center gap-2 rounded-md px-2 text-caption transition-colors hover:bg-accent/50"
+ >
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ size="xs"
+ showStatusDot
+ profileLink={false}
+ />
+ <span className="truncate">{agent.name}</span>
+ </AppLink>
+ ))}
+ </ObjectPanelSection>
+ )}
+ </div>
);
}
-function MemberDetailSkeleton() {
+function RoleLabel({ role }: { role: MemberRole }) {
+ const { t } = useT("members");
+ return role === "owner"
+ ? t(($) => $.role.owner)
+ : role === "admin"
+ ? t(($) => $.role.admin)
+ : t(($) => $.role.member);
+}
+
+function PanelSkeleton() {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <PageHeader>
- <Skeleton className="h-5 w-52" />
- </PageHeader>
- <div className="flex shrink-0 items-center gap-3 border-b px-6 py-4">
- <Skeleton className="h-11 w-11 rounded-full" />
- <div className="flex-1 space-y-2">
- <Skeleton className="h-5 w-40" />
- <Skeleton className="h-4 w-56" />
- </div>
- </div>
- <div className="flex flex-1 min-h-0 gap-4 overflow-hidden p-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <div key={i} className="flex min-w-52 flex-1 flex-col gap-2">
- <Skeleton className="h-4 w-20" />
- <Skeleton className="h-24 w-full rounded-lg" />
- <Skeleton className="h-24 w-full rounded-lg" />
- </div>
- ))}
- </div>
+ <div className="space-y-3 px-2">
+ <Skeleton className="h-3 w-20" />
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-4 w-full" />
+ ))}
</div>
);
}
diff --git a/packages/views/my-issues/components/my-issues-header.tsx b/packages/views/my-issues/components/my-issues-header.tsx
deleted file mode 100644
index aaac322473..0000000000
--- a/packages/views/my-issues/components/my-issues-header.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import { ChevronDown } from "@multica/ui/icons";
-import { Button } from "@multica/ui/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuTrigger,
-} from "@multica/ui/components/ui/dropdown-menu";
-import type {
- Issue,
- IssueTableFacetSpec,
- IssueTableFacetsResponse,
- WorkingAgentSummary,
-} from "@multica/core/types";
-import { type MyIssuesScope } from "@multica/core/issues/stores/my-issues-view-store";
-import { useViewStore } from "@multica/core/issues/stores/view-store-context";
-import { useT } from "../../i18n";
-import { WorkspaceAgentWorkingChip } from "../../issues/components/workspace-agent-working-chip";
-import {
- IssueDisplayControls,
-} from "../../issues/components/issues-header";
-import { cn } from "@multica/ui/lib/utils";
-import { PAGE_GUTTER } from "../../layout/page-header";
-import { FilterChipsBar } from "../../issues/components/filter-chips-bar";
-import { toast } from "sonner";
-import { SaveViewDialog, type SaveViewScope } from "../../issues/components/save-view-dialog";
-import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { baselineFromQuery } from "@multica/core/issue-views/baseline";
-import { ViewBar } from "../../issues/components/view-bar";
-import type { IssueView } from "@multica/core/api/schemas";
-
-/** My Issues tab → saved-view scope_variant (API vocabulary). */
-const SAVE_VARIANT: Record<MyIssuesScope, Extract<SaveViewScope, { kind: "my" }>["variant"]> = {
- all: "any",
- assigned: "assigned",
- created: "created",
- agents: "involved",
-};
-
-export function MyIssuesHeader({
- allIssues,
- workingAgents,
- scope,
- onScopeChange,
- facetCountsExact = true,
- tableFacetCounts,
- onTableFacetChange,
-}: {
- allIssues: Issue[];
- /** See IssueSurfaceController.workingAgents. My Issues used to ask the
- * working-agents endpoint for its own relation-scoped count; the surface
- * projection now covers the relation AND every active filter. */
- workingAgents: WorkingAgentSummary[] | undefined;
- scope: MyIssuesScope;
- onScopeChange: (scope: MyIssuesScope) => void;
- /** See IssueDisplayControls.facetCountsExact. */
- facetCountsExact?: boolean;
- tableFacetCounts?: IssueTableFacetsResponse;
- onTableFacetChange: (facet: IssueTableFacetSpec | null) => void;
-}) {
- const { t } = useT("my-issues");
- const { t: tIssues } = useT("issues");
- const [saveViewOpen, setSaveViewOpen] = useState(false);
- const saveScope: SaveViewScope = { kind: "my", variant: SAVE_VARIANT[scope] };
- const wsId = useWorkspaceId();
- const { activeView, views, viewsReady, setActive, missing } = useActiveIssueView(
- wsId,
- { scope_type: "my" },
- );
- useEffect(() => {
- if (missing) {
- setActive(null);
- toast.info(tIssues(($) => $.view_selector.unavailable));
- }
- }, [missing, setActive, tIssues]);
- const viewBaseline = activeView ? baselineFromQuery(activeView.query) : undefined;
- const [editTarget, setEditTarget] = useState<{
- view: IssueView;
- fromDefinition: boolean;
- } | null>(null);
- const SCOPES: { value: MyIssuesScope; label: string; description: string }[] = [
- { value: "all", label: t(($) => $.header.scope.all_label), description: t(($) => $.header.scope.all_description) },
- { value: "assigned", label: t(($) => $.header.scope.assigned_label), description: t(($) => $.header.scope.assigned_description) },
- { value: "created", label: t(($) => $.header.scope.created_label), description: t(($) => $.header.scope.created_description) },
- { value: "agents", label: t(($) => $.header.scope.agents_label), description: t(($) => $.header.scope.agents_description) },
- ];
- const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);
- const toggleAgentRunningFilter = useViewStore(
- (s) => s.toggleAgentRunningFilter,
- );
- const scopeLabel = SCOPES.find((s) => s.value === scope)?.label ?? SCOPES[0]?.label;
-
- return (
- <>
- <div className={cn("min-h-12 shrink-0 py-2 [-webkit-overflow-scrolling:touch]", PAGE_GUTTER)}>
- <div className="flex w-full min-w-0 items-start justify-between gap-2">
- <div className="hidden min-w-0 flex-1 md:block">
- <ViewBar
- wsId={wsId}
- scope={{ scope_type: "my" }}
- builtins={SCOPES.map((s) => ({
- key: s.value,
- label: s.label,
- description: s.description,
- active: !activeView && scope === s.value,
- onSelect: () => {
- if (activeView) setActive(null);
- onScopeChange(s.value);
- },
- }))}
- views={views}
- viewsReady={viewsReady}
- activeView={activeView}
- onSelectView={(view) => setActive(view ? view.id : null)}
- onNewView={() => {
- setEditTarget(null);
- setSaveViewOpen(true);
- }}
- onEditView={(view) => {
- setEditTarget({ view, fromDefinition: true });
- setSaveViewOpen(true);
- }}
- />
- </div>
-
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 gap-1 text-muted-foreground md:hidden"
- >
- <span className="truncate">{scopeLabel}</span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={scope}
- onValueChange={(value) => onScopeChange(value as MyIssuesScope)}
- >
- {SCOPES.map((s) => (
- <DropdownMenuRadioItem key={s.value} value={s.value}>
- {s.label}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
-
- <div className="flex shrink-0 items-center gap-1">
- {agentRunningFilter && (
- <span className="mr-1 hidden text-caption text-muted-foreground md:inline">
- {tIssues(($) => $.agent_activity.filter_active_label)}
- </span>
- )}
- <WorkspaceAgentWorkingChip
- value={agentRunningFilter}
- onToggle={toggleAgentRunningFilter}
- agents={workingAgents}
- />
- <IssueDisplayControls
- scopedIssues={allIssues}
- facetCountsExact={facetCountsExact}
- tableFacetCounts={tableFacetCounts}
- onTableFacetChange={onTableFacetChange}
- viewBaseline={viewBaseline}
- />
- </div>
- </div>
- </div>
- <FilterChipsBar
- viewBaseline={viewBaseline}
- saveLabel={activeView ? tIssues(($) => $.filters.chip_edit) : undefined}
- onSave={() => {
- setEditTarget(
- activeView ? { view: activeView, fromDefinition: false } : null,
- );
- setSaveViewOpen(true);
- }}
- />
- <SaveViewDialog
- open={saveViewOpen}
- onOpenChange={setSaveViewOpen}
- scope={saveScope}
- editView={editTarget?.view ?? null}
- seedFromDefinition={editTarget?.fromDefinition ?? false}
- />
- </>
- );
-}
diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsx
index ed8806d8b5..b7a909ee9d 100644
--- a/packages/views/my-issues/components/my-issues-page.tsx
+++ b/packages/views/my-issues/components/my-issues-page.tsx
@@ -1,32 +1,20 @@
"use client";
-import { useStore } from "zustand";
import { ListTodo } from "@multica/ui/icons";
import { useAuthStore } from "@multica/core/auth";
-import {
- myIssuesRelationFromScope,
- myIssuesViewStore,
-} from "@multica/core/issues/stores/my-issues-view-store";
+import { myIssuesRelationFromScope } from "@multica/core/issues/stores/my-issues-view-store";
import { PageHeader } from "../../layout/page-header";
-import { RefreshablePageIcon } from "../../layout/refreshable-page-icon";
import { IssueSurface } from "../../issues/surface/issue-surface";
+import { IssueViewHeader } from "../../issue-views/view-header";
import { useT } from "../../i18n";
-import { MyIssuesHeader } from "./my-issues-header";
+import { useMyIssuesScope } from "../use-my-issues-scope";
+
+const MY_BASE = { kind: "my" } as const;
export function MyIssuesPage() {
const { t } = useT("my-issues");
const user = useAuthStore((s) => s.user);
- const scope = useStore(myIssuesViewStore, (s) => s.scope);
- const setScope = useStore(myIssuesViewStore, (s) => s.setScope);
-
- const renderTitle = (refreshing = false) => (
- <PageHeader>
- <RefreshablePageIcon refreshing={refreshing}>
- <ListTodo className="size-4" />
- </RefreshablePageIcon>
- <h1 className="text-body font-medium">{t(($) => $.page.breadcrumb)}</h1>
- </PageHeader>
- );
+ const scope = useMyIssuesScope();
return (
<div className="flex flex-1 min-h-0 flex-col">
@@ -39,20 +27,7 @@ export function MyIssuesPage() {
}}
modes={["board", "list", "table", "swimlane"]}
batchToolbar="list"
- renderHeader={({ controller }) => (
- <>
- {renderTitle(controller.isRefreshing)}
- <MyIssuesHeader
- allIssues={controller.surfaceIssues}
- workingAgents={controller.workingAgents}
- scope={scope}
- onScopeChange={setScope}
- facetCountsExact={controller.facetCountsExact}
- tableFacetCounts={controller.tableFacetCounts}
- onTableFacetChange={controller.setActiveTableFacet}
- />
- </>
- )}
+ renderHeader={({ controller }) => <IssueViewHeader controller={controller} base={MY_BASE} />}
renderEmpty={() => (
<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 text-muted-foreground">
<ListTodo className="h-10 w-10 text-faint-foreground" />
@@ -61,7 +36,12 @@ export function MyIssuesPage() {
</div>
)}
/>
- ) : renderTitle()}
+ ) : (
+ <PageHeader>
+ <ListTodo className="size-4 text-muted-foreground" />
+ <h1 className="text-body font-medium">{t(($) => $.page.breadcrumb)}</h1>
+ </PageHeader>
+ )}
</div>
);
}
diff --git a/packages/views/my-issues/use-my-issues-scope.ts b/packages/views/my-issues/use-my-issues-scope.ts
new file mode 100644
index 0000000000..958e771862
--- /dev/null
+++ b/packages/views/my-issues/use-my-issues-scope.ts
@@ -0,0 +1,16 @@
+"use client";
+
+import { useStore } from "zustand";
+import {
+ myIssuesScopeFor,
+ myIssuesViewStore,
+ type MyIssuesScope,
+} from "@multica/core/issues/stores/my-issues-view-store";
+import { useNavigation } from "../navigation";
+
+/** The scope the current My issues location shows. */
+export function useMyIssuesScope(): MyIssuesScope {
+ const { searchParams } = useNavigation();
+ const stored = useStore(myIssuesViewStore, (s) => s.scope);
+ return myIssuesScopeFor(searchParams, stored);
+}
diff --git a/packages/views/navigation/app-link.test.tsx b/packages/views/navigation/app-link.test.tsx
index 3d06ad559c..dbf0c26b07 100644
--- a/packages/views/navigation/app-link.test.tsx
+++ b/packages/views/navigation/app-link.test.tsx
@@ -163,6 +163,65 @@ describe("AppLink", () => {
expect(push).not.toHaveBeenCalled();
});
+ describe("onNavigateInPlace", () => {
+ function renderWithInPlace(adapter: NavigationAdapter, extra: Partial<React.ComponentProps<typeof AppLink>> = {}) {
+ const onNavigateInPlace = vi.fn();
+ renderLink(adapter, { href: "/issues", onNavigateInPlace, ...extra });
+ return onNavigateInPlace;
+ }
+
+ it("runs right before an in-place push, after the caller's onClick", () => {
+ const order: string[] = [];
+ const adapter = makeAdapter({ push: vi.fn(() => order.push("push")) });
+ renderLink(adapter, {
+ href: "/issues",
+ onClick: () => order.push("onClick"),
+ onNavigateInPlace: () => order.push("inPlace"),
+ });
+ fireEvent.click(screen.getByText("go"));
+ expect(order).toEqual(["onClick", "inPlace", "push"]);
+ });
+
+ it("runs for a desktop shift-click, which pushes in place", () => {
+ const onNavigateInPlace = renderWithInPlace(makeAdapter({ openInNewTab: vi.fn() }));
+ fireEvent.click(screen.getByText("go"), { shiftKey: true });
+ expect(onNavigateInPlace).toHaveBeenCalledTimes(1);
+ });
+
+ it("skips a web shift-click, which the browser opens in a new window", () => {
+ const onNavigateInPlace = renderWithInPlace(makeAdapter());
+ fireEvent.click(screen.getByText("go"), { shiftKey: true });
+ expect(onNavigateInPlace).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["desktop", { openInNewTab: vi.fn() }],
+ ["web", {}],
+ ])("skips modifier and middle clicks on %s", (_platform, overrides) => {
+ const onNavigateInPlace = renderWithInPlace(makeAdapter(overrides));
+ const link = screen.getByText("go");
+ fireEvent.click(link, { metaKey: true });
+ fireEvent.click(link, { ctrlKey: true });
+ fireEvent.click(link, { metaKey: true, shiftKey: true });
+ fireEvent(link, new MouseEvent("auxclick", { bubbles: true, cancelable: true, button: 1 }));
+ expect(onNavigateInPlace).not.toHaveBeenCalled();
+ });
+
+ it("skips a target=_blank link, which opens a tab", () => {
+ const blank = renderWithInPlace(makeAdapter({ openInNewTab: vi.fn() }), { target: "_blank" });
+ fireEvent.click(screen.getByText("go"));
+ expect(blank).not.toHaveBeenCalled();
+ });
+
+ it("skips a click whose onClick called preventDefault", () => {
+ const push = vi.fn();
+ const onNavigateInPlace = renderWithInPlace(makeAdapter({ push }), { onClick: (e) => e.preventDefault() });
+ fireEvent.click(screen.getByText("go"));
+ expect(onNavigateInPlace).not.toHaveBeenCalled();
+ expect(push).not.toHaveBeenCalled();
+ });
+ });
+
describe("target=_blank (open-in-new-tab links)", () => {
it("plain click opens a foreground new tab via the adapter (desktop) and does NOT push", () => {
const push = vi.fn();
diff --git a/packages/views/navigation/app-link.tsx b/packages/views/navigation/app-link.tsx
index e99aad19b3..6c4f5da9d3 100644
--- a/packages/views/navigation/app-link.tsx
+++ b/packages/views/navigation/app-link.tsx
@@ -13,6 +13,13 @@ interface AppLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
* path.
*/
newTabTitle?: string;
+ /**
+ * Runs right before the link navigates the current page, and on no other
+ * path: page state that only the current page should take (an open view,
+ * a selected tab) belongs here rather than in `onClick`, which also sees
+ * clicks that open a new tab or window.
+ */
+ onNavigateInPlace?: () => void;
}
export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
@@ -26,6 +33,7 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
onFocus,
target,
newTabTitle,
+ onNavigateInPlace,
...props
},
ref,
@@ -85,6 +93,7 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
return;
}
e.preventDefault();
+ onNavigateInPlace?.();
push(href);
};
diff --git a/packages/views/navigation/use-row-link.test.tsx b/packages/views/navigation/use-row-link.test.tsx
index 1dce7ee8d5..3d88111c89 100644
--- a/packages/views/navigation/use-row-link.test.tsx
+++ b/packages/views/navigation/use-row-link.test.tsx
@@ -222,4 +222,35 @@ describe("useRowLink", () => {
expect(push).not.toHaveBeenCalled();
expect(openInNewTab).not.toHaveBeenCalled();
});
+
+ it.each([
+ ["desktop", { openInNewTab: vi.fn() }],
+ ["web", {}],
+ ])("runs onNavigateInPlace before each in-place push only, shift included, on %s", (_platform, overrides) => {
+ const order: string[] = [];
+ const adapter = makeAdapter({ push: vi.fn(() => order.push("push")), ...overrides });
+ vi.spyOn(window, "open").mockReturnValue(null);
+
+ function InPlaceProbe() {
+ const rowLink = useRowLink();
+ return (
+ <div role="row" {...rowLink("/acme/projects/p1", undefined, () => order.push("inPlace"))}>
+ row
+ </div>
+ );
+ }
+ render(
+ <NavigationProvider value={adapter}>
+ <InPlaceProbe />
+ </NavigationProvider>,
+ );
+
+ const row = screen.getByRole("row");
+ fireEvent.click(row);
+ fireEvent.click(row, { shiftKey: true });
+ fireEvent.click(row, { metaKey: true });
+ fireEvent(row, new MouseEvent("auxclick", { bubbles: true, cancelable: true, button: 1 }));
+
+ expect(order).toEqual(["inPlace", "push", "inPlace", "push"]);
+ });
});
diff --git a/packages/views/navigation/use-row-link.ts b/packages/views/navigation/use-row-link.ts
index 75f2a57c3e..396b2c9c11 100644
--- a/packages/views/navigation/use-row-link.ts
+++ b/packages/views/navigation/use-row-link.ts
@@ -12,6 +12,8 @@ import { useNavigation } from "./context";
* Nested interactive cells use rowLinkInteractiveProps to stop both click and
* auxclick propagation. Do not prevent their defaults: anchors must retain native
* middle-click behavior. Callers own cursor styling and temporary tab titles.
+ * `onNavigateInPlace` has AppLink's contract: it runs only when the row is
+ * about to navigate the current page.
*/
export const rowLinkInteractiveProps = {
onClick: (e: React.MouseEvent) => e.stopPropagation(),
@@ -22,9 +24,10 @@ export function useRowLink() {
const { push, openInNewTab, prefetch, getShareableUrl } = useNavigation();
return useCallback(
- (href: string, newTabTitle?: string) => {
+ (href: string, newTabTitle?: string, onNavigateInPlace?: () => void) => {
const open = (intent: LinkClickIntent) => {
if (intent === "push") {
+ onNavigateInPlace?.();
push(href);
return;
}
diff --git a/packages/views/package.json b/packages/views/package.json
index d0bc903577..74ab0eb6f6 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -14,6 +14,7 @@
"./common/cli-install-command": "./common/cli-install-command.tsx",
"./common/shortcut-keycaps": "./common/shortcut-keycaps.tsx",
"./editor": "./editor/index.ts",
+ "./issue-views": "./issue-views/index.ts",
"./issues/components": "./issues/components/index.ts",
"./issues/hooks": "./issues/hooks/index.ts",
"./issues/utils/filter": "./issues/utils/filter.ts",
diff --git a/packages/views/projects/components/project-detail.test.tsx b/packages/views/projects/components/project-detail.test.tsx
index 2a4933fcde..57acbb0fea 100644
--- a/packages/views/projects/components/project-detail.test.tsx
+++ b/packages/views/projects/components/project-detail.test.tsx
@@ -21,7 +21,9 @@ vi.mock("@multica/ui/lib/clipboard", () => ({
copyText: mocks.copyText,
}));
-vi.mock("../../workflows/project-workflow-menu", () => ({ ProjectWorkflowMenu: () => null }));
+vi.mock("../../workflows/project-workflow-menu", () => ({
+ ProjectWorkflowMenuHost: ({ children }: { children: (submenu: null) => React.ReactNode }) => children(null),
+}));
vi.mock("../../workflows/project-workflow-row", () => ({ ProjectWorkflowControl: () => null }));
vi.mock("@tanstack/react-query", () => ({
@@ -234,12 +236,25 @@ vi.mock("./project-due-date-picker", () => ({
}));
vi.mock("../../issues/surface/issue-surface", () => ({
- IssueSurface: () => null,
+ IssueSurface: ({
+ renderHeader,
+ }: {
+ renderHeader?: (ctx: { controller: unknown }) => React.ReactNode;
+ }) => <>{renderHeader?.({ controller: {} })}</>,
}));
-vi.mock("../../layout/breadcrumb-header", () => ({
- BreadcrumbHeader: ({ actions }: { actions: React.ReactNode }) => (
- <header>{actions}</header>
+vi.mock("../../issue-views/view-header", () => ({
+ IssueViewHeader: ({
+ baseMenu,
+ trailing,
+ }: {
+ baseMenu?: React.ReactNode;
+ trailing?: React.ReactNode;
+ }) => (
+ <header>
+ {baseMenu}
+ {trailing}
+ </header>
),
}));
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index 9bfe389a8d..46b4e52cfb 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -3,7 +3,7 @@
import { useMemo, useState, useCallback, useRef, useEffect } from "react";
import { useRegisterCommandBarContext } from "../../search/register-context";
import { useDefaultLayout, usePanelRef } from "react-resizable-panels";
-import { Check, ChevronRight, Link2, MoreHorizontal, PanelRight, Pin, PinOff, Trash2, UserMinus } from "@multica/ui/icons";
+import { Check, ChevronRight, Link2, PanelRight, Pin, PinOff, Trash2, UserMinus } from "@multica/ui/icons";
import { useQuery } from "@tanstack/react-query";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
@@ -30,11 +30,10 @@ import { ProjectResourcesSection } from "./project-resources-section";
import { ProjectStartDatePicker } from "./project-start-date-picker";
import { ProjectDueDatePicker } from "./project-due-date-picker";
import { ProjectWorkflowControl } from "../../workflows/project-workflow-row";
-import { ProjectWorkflowMenu } from "../../workflows/project-workflow-menu";
+import { ProjectWorkflowMenuHost } from "../../workflows/project-workflow-menu";
import { IssueSurface } from "../../issues/surface/issue-surface";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Button } from "@multica/ui/components/ui/button";
-import { IconButton } from "@multica/ui/components/common/icon-button";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";
import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
@@ -57,7 +56,7 @@ import {
TooltipContent,
} from "@multica/ui/components/ui/tooltip";
import { EmojiPicker } from "@multica/ui/components/common/emoji-picker";
-import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
+import { IssueViewHeader } from "../../issue-views/view-header";
import {
AnimatedRightSidebar,
getAnimatedRightSidebarInitialOpen,
@@ -112,7 +111,6 @@ function ProjectWorkflowPropRow({ project }: { project: Project }) {
export function ProjectDetail({ projectId }: { projectId: string }) {
const { t } = useT("projects");
- const { t: tCommon } = useT("common");
const statusLabels = useProjectStatusLabels();
const priorityLabels = useProjectPriorityLabels();
const wsId = useWorkspaceId();
@@ -496,83 +494,77 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
<ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}>
<ResizablePanel id="content" minSize="50%">
<div ref={rightSidebarShortcutTargetRef} className="flex h-full flex-col">
- <BreadcrumbHeader
- segments={[{ href: wsPaths.projects(), label: t(($) => $.detail.breadcrumb_fallback) }]}
- leaf={<span className="truncate font-medium text-foreground">{project.title}</span>}
- actions={
- <>
- <ProjectWorkflowMenu project={project} />
- <IconButton
- label={isPinned ? t(($) => $.detail.unpin_tooltip) : t(($) => $.detail.pin_tooltip)}
- tooltipSide="bottom"
- className={cn("text-muted-foreground", isPinned && "text-foreground")}
- onClick={() => {
- if (isPinned) {
- deletePinMut.mutate({ itemType: "project", itemId: projectId });
- } else {
- createPin.mutate({ item_type: "project", item_id: projectId });
- }
- }}
- >
- {isPinned ? <PinOff /> : <Pin />}
- </IconButton>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <IconButton
- label={tCommon(($) => $.more_actions)}
- tooltipSide="bottom"
- className="text-muted-foreground"
- >
- <MoreHorizontal />
- </IconButton>
- }
- />
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuItem onClick={() => {
- void copyText(router.getShareableUrl(currentPath(router))).then((ok) => {
- if (ok) toast.success(t(($) => $.detail.toast_link_copied));
- });
- }}>
- <Link2 className="h-3.5 w-3.5" />
- {t(($) => $.detail.copy_link)}
- </DropdownMenuItem>
- {isWorkspaceAdmin && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleteDialogOpen(true)}
- >
- <Trash2 className="h-3.5 w-3.5" />
- {t(($) => $.detail.delete_action)}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant={sidebarOpen ? "secondary" : "ghost"}
- size="icon-sm"
- className={sidebarOpen ? "" : "text-muted-foreground"}
- onClick={handleToggleSidebar}
- >
- <PanelRight />
- </Button>
- }
- />
- <TooltipContent side="bottom">{t(($) => $.detail.sidebar_tooltip)}</TooltipContent>
- </Tooltip>
- </>
- }
- />
-
<IssueSurface
scope={issueScope}
modes={["board", "list", "table", "swimlane", "gantt"]}
+ renderHeader={({ controller }) => (
+ <ProjectWorkflowMenuHost project={project}>
+ {(workflowSubmenu) => (
+ <IssueViewHeader
+ controller={controller}
+ base={{ kind: "project", project }}
+ baseMenu={
+ <>
+ <DropdownMenuItem onClick={() => {
+ void copyText(router.getShareableUrl(currentPath(router))).then((ok) => {
+ if (ok) toast.success(t(($) => $.detail.toast_link_copied));
+ });
+ }}>
+ <Link2 className="h-3.5 w-3.5" />
+ {t(($) => $.detail.copy_link)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => {
+ if (isPinned) {
+ deletePinMut.mutate({ itemType: "project", itemId: projectId });
+ } else {
+ createPin.mutate({ item_type: "project", item_id: projectId });
+ }
+ }}>
+ {isPinned ? <PinOff className="h-3.5 w-3.5" /> : <Pin className="h-3.5 w-3.5" />}
+ {isPinned ? t(($) => $.detail.unpin_tooltip) : t(($) => $.detail.pin_tooltip)}
+ </DropdownMenuItem>
+ {workflowSubmenu && (
+ <>
+ <DropdownMenuSeparator />
+ {workflowSubmenu}
+ </>
+ )}
+ {isWorkspaceAdmin && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteDialogOpen(true)}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ {t(($) => $.detail.delete_action)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </>
+ }
+ trailing={
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant={sidebarOpen ? "secondary" : "ghost"}
+ size="icon-sm"
+ className={sidebarOpen ? "" : "text-muted-foreground"}
+ aria-label={t(($) => $.detail.sidebar_tooltip)}
+ onClick={handleToggleSidebar}
+ >
+ <PanelRight />
+ </Button>
+ }
+ />
+ <TooltipContent side="bottom">{t(($) => $.detail.sidebar_tooltip)}</TooltipContent>
+ </Tooltip>
+ }
+ />
+ )}
+ </ProjectWorkflowMenuHost>
+ )}
/>
</div>
</ResizablePanel>
diff --git a/packages/views/projects/components/projects-page.test.tsx b/packages/views/projects/components/projects-page.test.tsx
index f08d9303db..423c17648b 100644
--- a/packages/views/projects/components/projects-page.test.tsx
+++ b/packages/views/projects/components/projects-page.test.tsx
@@ -22,7 +22,7 @@ const mocks = vi.hoisted(() => ({
sortField: "name",
sortDirection: "asc",
hiddenColumns: [] as string[],
- filters: { statuses: [], priorities: [], leads: [] },
+ filters: { statuses: [] as string[], priorities: [] as string[], leads: [] as string[] },
setViewMode: vi.fn(),
toggleSort: vi.fn(),
setSortField: vi.fn(),
@@ -102,69 +102,102 @@ vi.mock("@multica/core/modals", () => ({
},
}));
-vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({
- DropdownMenu: ({ children }: { children: React.ReactNode }) => (
- <>{children}</>
- ),
- DropdownMenuTrigger: ({ render }: { render: React.ReactNode }) => (
- <>{render}</>
- ),
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- DropdownMenuGroup: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- DropdownMenuItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode;
- onClick?: () => void;
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- DropdownMenuCheckboxItem: ({
- children,
- onCheckedChange,
- }: {
- children: React.ReactNode;
- onCheckedChange?: () => void;
- }) => (
- <button type="button" onClick={onCheckedChange}>
- {children}
- </button>
- ),
- DropdownMenuRadioGroup: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- DropdownMenuRadioItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode;
- onClick?: () => void;
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- DropdownMenuSeparator: () => <hr />,
- DropdownMenuSub: ({ children }: { children: React.ReactNode }) => (
- <>{children}</>
- ),
- DropdownMenuSubContent: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- DropdownMenuSubTrigger: ({ children }: { children: React.ReactNode }) => (
- <button type="button">{children}</button>
- ),
-}));
+vi.mock("@multica/ui/components/ui/dropdown-menu", () => {
+ const RadioGroupContext = React.createContext<((value: string) => void) | undefined>(
+ undefined,
+ );
+ return {
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+ DropdownMenuTrigger: ({
+ render,
+ children,
+ }: {
+ render: React.ReactNode;
+ children?: React.ReactNode;
+ }) =>
+ children && React.isValidElement(render) ? (
+ React.cloneElement(render, undefined, children)
+ ) : (
+ <>{render}</>
+ ),
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DropdownMenuGroup: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DropdownMenuItem: ({
+ children,
+ onClick,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ }) => (
+ <button type="button" onClick={onClick}>
+ {children}
+ </button>
+ ),
+ DropdownMenuCheckboxItem: ({
+ children,
+ onCheckedChange,
+ }: {
+ children: React.ReactNode;
+ onCheckedChange?: () => void;
+ }) => (
+ <button type="button" onClick={onCheckedChange}>
+ {children}
+ </button>
+ ),
+ DropdownMenuRadioGroup: ({
+ children,
+ onValueChange,
+ }: {
+ children: React.ReactNode;
+ onValueChange?: (value: string) => void;
+ }) => (
+ <RadioGroupContext.Provider value={onValueChange}>
+ <div>{children}</div>
+ </RadioGroupContext.Provider>
+ ),
+ DropdownMenuRadioItem: function RadioItem({
+ children,
+ onClick,
+ value,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ value: string;
+ }) {
+ const onValueChange = React.useContext(RadioGroupContext);
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ onClick?.();
+ onValueChange?.(value);
+ }}
+ >
+ {children}
+ </button>
+ );
+ },
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuSub: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+ DropdownMenuSubContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DropdownMenuSubTrigger: ({ children }: { children: React.ReactNode }) => (
+ <button type="button">{children}</button>
+ ),
+ };
+});
vi.mock("@multica/ui/components/ui/popover", () => ({
Popover: ({ children }: { children: React.ReactNode }) => <>{children}</>,
@@ -243,6 +276,8 @@ beforeEach(() => {
mocks.createPin.mockClear();
mocks.deletePin.mockClear();
mocks.openModal.mockClear();
+ mocks.projectViewState.setViewMode.mockClear();
+ mocks.projectViewState.clearFilters.mockClear();
mocks.projectViewState.viewMode = "compact";
mocks.projectViewState.sortField = "name";
mocks.projectViewState.sortDirection = "asc";
@@ -278,7 +313,7 @@ describe("ProjectsPage compact row navigation", () => {
renderProjects(makeAdapter({ push }));
const row = projectRow();
- await user.click(within(row).getByRole("button", { pressed: false }));
+ await user.click(within(row).getByRole("checkbox", { name: "Select row" }));
await user.click(within(row).getByRole("button", { name: "Project actions" }));
await user.click(within(row).getAllByRole("button", { name: "In Progress" })[0]!);
await user.click(within(row).getAllByRole("button", { name: "High" })[0]!);
@@ -342,3 +377,69 @@ describe("ProjectsPage compact row navigation", () => {
open.mockRestore();
});
});
+
+describe("ProjectsPage header", () => {
+ const CLOSED: Project = {
+ ...PROJECT,
+ id: "project-2",
+ title: "Old Roadmap",
+ status: "completed",
+ };
+
+ it("titles the page with the scope and narrows rows from the scope menu", async () => {
+ const user = userEvent.setup();
+ mocks.projects = [PROJECT, CLOSED];
+ renderProjects();
+
+ expect(screen.getByRole("heading", { level: 1, name: "All projects" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /^Active projects/ })).toHaveTextContent("1");
+ expect(screen.getByText("Old Roadmap")).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /^Active projects/ }));
+ expect(screen.getByRole("heading", { level: 1, name: "Active projects" })).toBeInTheDocument();
+ expect(screen.getByText(PROJECT.title)).toBeInTheDocument();
+ expect(screen.queryByText("Old Roadmap")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /^Closed projects/ }));
+ expect(screen.queryByText(PROJECT.title)).not.toBeInTheDocument();
+ expect(screen.getByText("Old Roadmap")).toBeInTheDocument();
+ });
+
+ it("has no search, and offers Reset only while a filter narrows the list", () => {
+ mocks.projects = [PROJECT, CLOSED];
+ renderProjects();
+
+ const header = screen.getByRole("banner");
+ expect(within(header).queryByRole("button", { name: /search/i })).not.toBeInTheDocument();
+ expect(within(header).queryByRole("textbox")).not.toBeInTheDocument();
+ expect(within(header).queryByRole("button", { name: "Reset" })).not.toBeInTheDocument();
+ });
+
+ it("names the active filter count on the filter control, and Reset clears the filters", async () => {
+ const user = userEvent.setup();
+ mocks.projectViewState.filters = { statuses: ["in_progress"], priorities: [], leads: [] };
+ renderProjects();
+
+ expect(screen.getByRole("button", { name: "1 filter" })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Reset" }));
+ expect(mocks.projectViewState.clearFilters).toHaveBeenCalled();
+ });
+
+ it("switches between table and cards from the display settings", async () => {
+ const user = userEvent.setup();
+ renderProjects();
+
+ expect(screen.getByRole("button", { name: "Display settings" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Table", pressed: true })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Cards", pressed: false }));
+ expect(mocks.projectViewState.setViewMode).toHaveBeenCalledWith("comfortable");
+ });
+
+ it("creates a project from the header", async () => {
+ const user = userEvent.setup();
+ renderProjects();
+
+ await user.click(screen.getByRole("button", { name: "New project" }));
+ expect(mocks.openModal).toHaveBeenCalledWith("create-project");
+ });
+});
diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsx
index 5a1b6c2ff9..991f7bf77e 100644
--- a/packages/views/projects/components/projects-page.tsx
+++ b/packages/views/projects/components/projects-page.tsx
@@ -1,22 +1,15 @@
"use client";
-import { useCallback, useMemo, useState, type MouseEvent } from "react";
+import { useCallback, useMemo, useState } from "react";
import {
- ArrowDown,
- ArrowUp,
- ChevronDown,
ExternalLink,
- Filter,
FolderKanban,
LayoutGrid,
- MoreHorizontal,
Pin,
PinOff,
- Plus,
Rows3,
Search,
Trash2,
- X,
} from "@multica/ui/icons";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
@@ -41,13 +34,11 @@ import { useAuthStore } from "@multica/core/auth";
import { useActorName } from "@multica/core/workspace/hooks";
import { memberListOptions } from "@multica/core/workspace/queries";
import { useModalStore } from "@multica/core/modals";
-import { AppLink, useIntentNavigate, useRowLink } from "../../navigation";
+import { AppLink, useIntentNavigate } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import { Input } from "@multica/ui/components/ui/input";
import {
Dialog,
DialogContent,
@@ -60,39 +51,14 @@ import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
- DropdownMenuGroup,
DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- ListGrid,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
- LIST_GRID_BOTTOM_CLEARANCE,
- type ListGridSortDirection,
-} from "@multica/ui/components/ui/list-grid";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
-import { Switch } from "@multica/ui/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
-import { IconButton } from "@multica/ui/components/common/icon-button";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
+import { Toggle } from "@multica/ui/components/ui/toggle";
import type {
MemberWithUser,
Project,
@@ -101,19 +67,30 @@ import type {
UpdateProjectRequest,
} from "@multica/core/types";
import {
+ CollectionCreateButton,
+ CollectionFilterButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
} from "../../layout/collection-page";
+import {
+ CollectionBatchBar,
+ CollectionDisplayMenu,
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ CollectionRowMenu,
+ type CollectionColumn,
+ type CollectionSort,
+} from "../../layout/collection-list";
import { ProjectIcon } from "./project-icon";
import { useT } from "../../i18n";
-import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import { useFormatRelativeDate } from "./labels";
import { ProjectStatusBadge, ProjectPriorityBadge } from "./project-badge";
import { ProjectLeadPicker } from "./project-lead-picker";
-import { PAGE_GUTTER, PAGE_TOOLBAR } from "../../layout/page-header";
+import { PAGE_GUTTER } from "../../layout/page-header";
import { cn } from "@multica/ui/lib/utils";
-import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
// Sort order maps for the enum columns (header sort needs a total order).
const PRIORITY_ORDER: Record<ProjectPriority, number> = {
@@ -140,60 +117,8 @@ function leadFilterValue(p: Project): string | null {
return p.lead_type && p.lead_id ? `${p.lead_type}:${p.lead_id}` : null;
}
-// Table (compact) view — ListGrid. Name + status are the core columns;
-// priority/progress/lead/issues/created collapse below @2xl, with min-width
-// + the wrapper's overflow as the escape valve. Rows use whole-row mouse
-// navigation; inline controls stop propagation so edit/menu clicks stay local.
-
-const COLUMN_WIDTHS: Record<ProjectColumnKey, number> = {
- priority: 116,
- progress: 88,
- lead: 132,
- issues: 80,
- created: 104,
-};
-
-// Fixed tracks: edges 12+12, checkbox 16, name min 200, status 116,
-// kebab 28 = 384, plus the 10 gap-x-3 gaps between the wide template's
-// 11 tracks.
-const FIXED_TRACKS_WIDTH = 384 + 10 * 12;
-
-// Render/track order: checkbox, name, status (core, fixed 116px), priority,
-// progress, lead, issues, created, kebab. MUST be a literal string —
-// Tailwind can't see interpolated `grid-cols-[...]` arbitrary values, so an
-// interpolated width silently drops the whole template and the grid
-// collapses to one column.
-const GRID_COLS =
- "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_116px_1.75rem_0.75rem] " +
- "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_116px_var(--pjc-priority)_var(--pjc-progress)_var(--pjc-lead)_var(--pjc-issues)_var(--pjc-created)_1.75rem_0.75rem]";
-
-const stopRowNavigation = (e: MouseEvent) => e.stopPropagation();
-
-function columnTrackVars(
- isVisible: (key: ProjectColumnKey) => boolean,
-): React.CSSProperties {
- const width = (key: ProjectColumnKey) =>
- isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";
- const minWidth =
- FIXED_TRACKS_WIDTH +
- (Object.keys(COLUMN_WIDTHS) as ProjectColumnKey[]).reduce(
- (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),
- 0,
- );
- return {
- "--pjc-priority": width("priority"),
- "--pjc-progress": width("progress"),
- "--pjc-lead": width("lead"),
- "--pjc-issues": width("issues"),
- "--pjc-created": width("created"),
- "--pjc-minw": `${minWidth}px`,
- } as React.CSSProperties;
-}
-
function ProgressRing({ project }: { project: Project }) {
- if (project.issue_count === 0) {
- return <span className="text-caption text-faint-foreground">—</span>;
- }
+ if (project.issue_count === 0) return <CollectionEmptyValue />;
const pct = Math.round((project.done_count / project.issue_count) * 100);
return (
<span className="flex items-center gap-1.5">
@@ -213,15 +138,14 @@ function ProgressRing({ project }: { project: Project }) {
/>
</svg>
</span>
- <span className="text-caption tabular-nums text-muted-foreground">
+ <span className="tabular-nums">
{project.done_count}/{project.issue_count}
</span>
</span>
);
}
-// Compact rows own whole-row navigation; callers stop propagation around this
-// menu so action clicks do not bubble into the rowLink handler.
+// Shared by table rows (⋯ and right-click) and cards.
function ProjectRowActions({
project,
pinned,
@@ -247,59 +171,41 @@ function ProjectRowActions({
return (
<>
- <DropdownMenu>
- <DeferredTooltip
- content={t(($) => $.page.row_menu)}
- trigger={
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- aria-label={t(($) => $.page.row_menu)}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"
- >
- <MoreHorizontal className="size-4" />
- </button>
- }
- />
+ <CollectionRowMenu label={t(($) => $.page.row_menu)} contentClassName="w-44">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ wsPaths.projectDetail(project.id),
+ "foreground-tab",
+ project.title,
+ )
}
- />
- <DropdownMenuContent align="end" className="w-44">
- <DropdownMenuItem
- onClick={() =>
- intentNavigate(
- wsPaths.projectDetail(project.id),
- "foreground-tab",
- project.title,
- )
- }
- >
- <ExternalLink className="size-3.5" />
- {tCommon(($) => $.navigation.open_in_new_tab)}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={togglePin}>
- {pinned ? (
- <PinOff className="size-3.5" />
- ) : (
- <Pin className="size-3.5" />
- )}
- {pinned ? t(($) => $.page.unpin) : t(($) => $.page.pin)}
- </DropdownMenuItem>
- {canDelete && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleteOpen(true)}
- >
- <Trash2 className="size-3.5" />
- {t(($) => $.page.delete)}
- </DropdownMenuItem>
- </>
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={togglePin}>
+ {pinned ? (
+ <PinOff className="size-3.5" />
+ ) : (
+ <Pin className="size-3.5" />
)}
- </DropdownMenuContent>
- </DropdownMenu>
+ {pinned ? t(($) => $.page.unpin) : t(($) => $.page.pin)}
+ </DropdownMenuItem>
+ {canDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteOpen(true)}
+ >
+ <Trash2 className="size-3.5" />
+ {t(($) => $.page.delete)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </CollectionRowMenu>
<Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<DialogContent className="sm:max-w-md">
@@ -341,241 +247,19 @@ function ProjectRowActions({
);
}
-function CheckboxCell({
- checked,
- onToggle,
-}: {
- checked: boolean;
- onToggle: () => void;
-}) {
- return (
- <ListGridCell className="justify-center px-0">
- <button
- type="button"
- aria-pressed={checked}
- onClick={(e) => {
- stopRowNavigation(e);
- onToggle();
- }}
- onAuxClick={stopRowNavigation}
- className={`-m-1.5 flex items-center p-1.5 ${
- checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"
- }`}
- >
- <Checkbox checked={checked} tabIndex={-1} className="pointer-events-none" />
- </button>
- </ListGridCell>
- );
-}
-
-function ProjectTableRow({
+function ProjectInlineCell({
project,
- pinned,
- canDelete,
- isColVisible,
- selected,
- onToggleSelect,
- rowHref,
- rowLink,
+ children,
}: {
project: Project;
- pinned: boolean;
- canDelete: boolean;
- isColVisible: (key: ProjectColumnKey) => boolean;
- selected: boolean;
- onToggleSelect: () => void;
- rowHref: string;
- rowLink: ReturnType<typeof useRowLink>;
+ children: (handleUpdate: (data: UpdateProjectRequest) => void) => React.ReactNode;
}) {
- const formatRelativeDate = useFormatRelativeDate();
const updateProject = useUpdateProject();
const handleUpdate = useCallback(
(data: UpdateProjectRequest) => updateProject.mutate({ id: project.id, ...data }),
[project.id, updateProject],
);
-
- return (
- <ListGridRow
- className={`h-11 cursor-pointer ${selected ? "bg-accent/30" : ""}`}
- {...rowLink(rowHref, project.title)}
- >
- <CheckboxCell checked={selected} onToggle={onToggleSelect} />
- <ListGridCell className="gap-2">
- <ProjectIcon project={project} size="sm" />
- <span className="min-w-0 truncate text-body font-medium">
- {project.title}
- </span>
- </ListGridCell>
-
- {/* status — core column, always visible */}
- <ListGridCell onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
- <ProjectStatusBadge project={project} handleUpdate={handleUpdate} align="start" />
- </ListGridCell>
-
- {isColVisible("priority") ? (
- <ListGridCell className="hidden @2xl:flex" onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
- <ProjectPriorityBadge project={project} handleUpdate={handleUpdate} align="start" />
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
-
- {isColVisible("progress") ? (
- <ListGridCell className="hidden @2xl:flex">
- <ProgressRing project={project} />
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
-
- {isColVisible("lead") ? (
- <ListGridCell className="hidden @2xl:flex" onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
- <ProjectLeadPicker
- project={project}
- handleUpdate={handleUpdate}
- align="start"
- renderTrigger={(leadName) => (
- <button
- type="button"
- className="flex min-w-0 items-center gap-1.5 rounded-xs px-1 py-0.5 transition-colors hover:bg-accent/60"
- >
- {project.lead_type && project.lead_id ? (
- <ActorAvatar actorType={project.lead_type} actorId={project.lead_id} size="sm" enableHoverCard />
- ) : (
- <span className="inline-flex h-[18px] w-[18px] rounded-full border border-dashed border-muted-foreground/30" />
- )}
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {leadName ?? "—"}
- </span>
- </button>
- )}
- />
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
-
- {isColVisible("issues") ? (
- <ListGridCell className="hidden justify-end font-mono text-caption tabular-nums text-muted-foreground @2xl:flex">
- {project.issue_count}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
-
- {isColVisible("created") ? (
- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">
- {formatRelativeDate(project.created_at)}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
-
- <ListGridCell className="justify-end px-0">
- <span onClick={stopRowNavigation} onAuxClick={stopRowNavigation} className="flex items-center">
- <ProjectRowActions project={project} pinned={pinned} canDelete={canDelete} />
- </span>
- </ListGridCell>
- </ListGridRow>
- );
-}
-
-function ProjectTableHeader({
- sortField,
- sortDirection,
- onSort,
- isColVisible,
- allSelected,
- someSelected,
- onToggleAll,
-}: {
- sortField: ProjectSortField;
- sortDirection: ListGridSortDirection;
- onSort: (field: ProjectSortField) => void;
- isColVisible: (key: ProjectColumnKey) => boolean;
- allSelected: boolean;
- someSelected: boolean;
- onToggleAll: () => void;
-}) {
- const { t } = useT("projects");
- const sorted = (field: ProjectSortField) =>
- sortField === field ? sortDirection : false;
- const anySelected = allSelected || someSelected;
- return (
- <ListGridHeader>
- <div className="flex items-center justify-center">
- <button
- type="button"
- aria-pressed={allSelected}
- onClick={onToggleAll}
- className={`-m-1.5 flex items-center p-1.5 ${
- anySelected ? "" : "opacity-0 transition-opacity group-hover/header:opacity-100"
- }`}
- >
- <Checkbox
- checked={allSelected}
- indeterminate={someSelected && !allSelected}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
- </div>
- <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>
- {t(($) => $.table.name)}
- </ListGridHeaderCell>
- <ListGridHeaderCell sorted={sorted("status")} onSort={() => onSort("status")}>
- {t(($) => $.table.status)}
- </ListGridHeaderCell>
- {isColVisible("priority") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("priority")}
- onSort={() => onSort("priority")}
- >
- {t(($) => $.table.priority)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("progress") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("progress")}
- onSort={() => onSort("progress")}
- >
- {t(($) => $.table.progress)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("lead") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.table.lead)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("issues") ? (
- <ListGridHeaderCell className="hidden justify-end @2xl:flex" align="right">
- {t(($) => $.table.issues)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("created")}
- onSort={() => onSort("created")}
- >
- {t(($) => $.table.created)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- <span aria-hidden="true" />
- </ListGridHeader>
- );
+ return <>{children(handleUpdate)}</>;
}
// Card (comfortable) view — kept from the prior page.
@@ -674,8 +358,23 @@ function ProjectCard({
);
}
-// Toolbar — search + result count + filter + display (compact only) + view
-// toggle.
+// Header tools — scope menu, filter, display (view, sort, columns).
+
+// Scope splits the lifecycle in two: still being worked on, or closed. The
+// status filter narrows further within it.
+type ProjectScope = "all" | "active" | "closed";
+const PROJECT_SCOPES: ProjectScope[] = ["all", "active", "closed"];
+const CLOSED_STATUSES: ReadonlySet<ProjectStatus> = new Set(["completed", "cancelled"]);
+
+function inScope(project: Project, scope: ProjectScope): boolean {
+ if (scope === "all") return true;
+ return CLOSED_STATUSES.has(project.status) === (scope === "closed");
+}
+
+const VIEW_MODES: { mode: ProjectViewMode; Icon: typeof Rows3 }[] = [
+ { mode: "compact", Icon: Rows3 },
+ { mode: "comfortable", Icon: LayoutGrid },
+];
const STATUS_VALUES: ProjectStatus[] = [
"planned",
@@ -685,8 +384,6 @@ const STATUS_VALUES: ProjectStatus[] = [
"cancelled",
];
const PRIORITY_VALUES: ProjectPriority[] = ["urgent", "high", "medium", "low", "none"];
-const COLUMN_KEYS: ProjectColumnKey[] = ["priority", "progress", "lead", "issues", "created"];
-const SORT_FIELDS: ProjectSortField[] = ["name", "priority", "status", "progress", "created"];
function countActiveFilters(f: ProjectListFilters): number {
let c = 0;
@@ -714,27 +411,11 @@ function ProjectBatchToolbar({
const deleteProject = useDeleteProject();
const [confirmDelete, setConfirmDelete] = useState(false);
- if (rows.length === 0) return null;
const anyUnpinned = rows.some((p) => !pinnedIds.has(p.id));
return (
<>
- <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg max-md:above-chat-launcher">
- <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">
- <span className="text-body font-medium">
- {t(($) => $.page.selected, { count: rows.length })}
- </span>
- <TooltipHint label={t(($) => $.page.clear_selection)}>
- <button
- type="button"
- aria-label={t(($) => $.page.clear_selection)}
- onClick={onClear}
- className="rounded-xs p-0.5 transition-colors hover:bg-accent"
- >
- <X className="size-3.5 text-muted-foreground" />
- </button>
- </TooltipHint>
- </div>
+ <CollectionBatchBar count={rows.length} onClear={onClear}>
{anyUnpinned && (
<Button
variant="ghost"
@@ -763,7 +444,7 @@ function ProjectBatchToolbar({
{t(($) => $.page.delete)}
</Button>
)}
- </div>
+ </CollectionBatchBar>
<Dialog open={confirmDelete} onOpenChange={setConfirmDelete}>
<DialogContent className="sm:max-w-md">
@@ -800,7 +481,6 @@ export function ProjectsPage() {
const { t } = useT("projects");
const wsId = useWorkspaceId();
const wsPaths = useWorkspacePaths();
- const rowLink = useRowLink();
const currentUser = useAuthStore((s) => s.user);
const { getActorName } = useActorName();
@@ -817,7 +497,7 @@ export function ProjectsPage() {
const toggleFilter = useProjectViewStore((s) => s.toggleFilter);
const clearFilters = useProjectViewStore((s) => s.clearFilters);
const isCompact = viewMode === "compact";
- const isColVisible = (key: ProjectColumnKey) => !hiddenColumns.includes(key);
+ const formatRelativeDate = useFormatRelativeDate();
const { data: projects = [], isLoading } = useQuery(projectListOptions(wsId));
const { data: members = [] } = useQuery(memberListOptions(wsId));
@@ -839,15 +519,8 @@ export function ProjectsPage() {
return s;
}, [pins]);
- const [search, setSearch] = useState("");
+ const [scope, setScope] = useState<ProjectScope>("all");
const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(new Set());
- const toggleSelected = (id: string) =>
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
const activeFilterCount = countActiveFilters(filters);
const hasActiveFilters = activeFilterCount > 0;
@@ -866,12 +539,15 @@ export function ProjectsPage() {
return m;
}, [projects]);
+ const scopeCounts = useMemo<Record<ProjectScope, number>>(() => {
+ const counts = { all: projects.length, active: 0, closed: 0 };
+ for (const p of projects) counts[inScope(p, "closed") ? "closed" : "active"] += 1;
+ return counts;
+ }, [projects]);
+
const visible = useMemo(() => {
- const q = search.trim().toLowerCase();
const filtered = projects.filter((p) => {
- if (q && !p.title.toLowerCase().includes(q) && !matchesPinyin(p.title, q)) {
- return false;
- }
+ if (!inScope(p, scope)) return false;
if (filters.statuses.length && !filters.statuses.includes(p.status)) return false;
if (filters.priorities.length && !filters.priorities.includes(p.priority)) {
return false;
@@ -904,54 +580,269 @@ export function ProjectsPage() {
return (Date.parse(a.created_at) - Date.parse(b.created_at)) * dir;
});
return sorted;
- }, [projects, search, filters, sortField, sortDirection]);
+ }, [projects, scope, filters, sortField, sortDirection]);
const selectedProjects = visible.filter((p) => selectedIds.has(p.id));
- const allSelected = visible.length > 0 && selectedProjects.length === visible.length;
- const someSelected = selectedProjects.length > 0 && !allSelected;
- const handleToggleAll = () =>
- setSelectedIds(allSelected ? new Set() : new Set(visible.map((p) => p.id)));
- const sortLabel = (f: ProjectSortField) =>
- f === "name"
- ? t(($) => $.table.name)
- : f === "priority"
- ? t(($) => $.table.priority)
- : f === "status"
- ? t(($) => $.table.status)
- : f === "progress"
- ? t(($) => $.table.progress)
- : t(($) => $.table.created);
- const columnLabel = (k: ProjectColumnKey) =>
- k === "priority"
- ? t(($) => $.table.priority)
- : k === "progress"
- ? t(($) => $.table.progress)
- : k === "lead"
- ? t(($) => $.table.lead)
- : k === "issues"
- ? t(($) => $.table.issues)
- : t(($) => $.table.created);
+ const columns = useMemo<CollectionColumn<Project>[]>(
+ () => [
+ {
+ key: "name",
+ header: t(($) => $.table.name),
+ sortKey: "name",
+ cell: (project) => (
+ <CollectionNameCell
+ icon={<ProjectIcon project={project} size="sm" />}
+ title={project.title}
+ />
+ ),
+ },
+ {
+ // The project's defining lifecycle field: always visible.
+ key: "status",
+ header: t(($) => $.table.status),
+ width: 116,
+ sortKey: "status",
+ core: true,
+ interactive: true,
+ cell: (project) => (
+ <ProjectInlineCell project={project}>
+ {(handleUpdate) => (
+ <ProjectStatusBadge project={project} handleUpdate={handleUpdate} align="start" />
+ )}
+ </ProjectInlineCell>
+ ),
+ },
+ {
+ key: "priority",
+ header: t(($) => $.table.priority),
+ width: 116,
+ sortKey: "priority",
+ hideable: true,
+ interactive: true,
+ cell: (project) => (
+ <ProjectInlineCell project={project}>
+ {(handleUpdate) => (
+ <ProjectPriorityBadge project={project} handleUpdate={handleUpdate} align="start" />
+ )}
+ </ProjectInlineCell>
+ ),
+ },
+ {
+ key: "progress",
+ header: t(($) => $.table.progress),
+ width: 80,
+ sortKey: "progress",
+ hideable: true,
+ cell: (project) => <ProgressRing project={project} />,
+ },
+ {
+ key: "lead",
+ header: t(($) => $.table.lead),
+ width: 132,
+ hideable: true,
+ interactive: true,
+ cell: (project) => (
+ <ProjectInlineCell project={project}>
+ {(handleUpdate) => (
+ <ProjectLeadPicker
+ project={project}
+ handleUpdate={handleUpdate}
+ align="start"
+ renderTrigger={(leadName) => (
+ <button
+ type="button"
+ className="-mx-1 flex min-w-0 items-center gap-1.5 rounded-xs px-1 py-0.5 transition-colors hover:bg-accent/60"
+ >
+ {project.lead_type && project.lead_id ? (
+ <ActorAvatar
+ actorType={project.lead_type}
+ actorId={project.lead_id}
+ size="sm"
+ enableHoverCard
+ />
+ ) : (
+ <span className="inline-flex h-[18px] w-[18px] rounded-full border border-dashed border-muted-foreground/30" />
+ )}
+ <span className="min-w-0 truncate">{leadName ?? "—"}</span>
+ </button>
+ )}
+ />
+ )}
+ </ProjectInlineCell>
+ ),
+ },
+ {
+ key: "issues",
+ header: t(($) => $.table.issues),
+ width: 64,
+ align: "end",
+ hideable: true,
+ className: "font-mono tabular-nums",
+ cell: (project) => project.issue_count,
+ },
+ {
+ key: "created",
+ header: t(($) => $.table.created),
+ width: 104,
+ sortKey: "created",
+ hideable: true,
+ cell: (project) => (
+ <span className="tabular-nums">{formatRelativeDate(project.created_at)}</span>
+ ),
+ },
+ ],
+ [t, formatRelativeDate],
+ );
+
+ const sort: CollectionSort = {
+ field: sortField,
+ direction: sortDirection,
+ onToggle: (field) => toggleSort(field as ProjectSortField),
+ onFieldChange: (field) => setSortField(field as ProjectSortField),
+ onDirectionChange: setSortDirection,
+ };
const showEmpty = !isLoading && projects.length === 0;
const countBadge = (n: number) => (
<span className="ml-auto pl-3 text-caption text-muted-foreground">{n}</span>
);
+ const scopeLabels: Record<ProjectScope, string> = {
+ all: t(($) => $.page.scope_all),
+ active: t(($) => $.page.scope_active),
+ closed: t(($) => $.page.scope_closed),
+ };
return (
// relative: positioning anchor for the page-centered batch toolbar.
<div className="relative flex flex-1 min-h-0 flex-col">
<CollectionPageHeader
icon={FolderKanban}
- title={t(($) => $.page.title)}
- count={projects.length}
- actions={
- <CollectionPageHeaderAction
- icon={Plus}
- label={t(($) => $.page.new_project)}
- onClick={openCreateProject}
+ title={scopeLabels[scope]}
+ menu={
+ <CollectionScopeItems
+ value={scope}
+ onChange={setScope}
+ options={PROJECT_SCOPES.map((s) => ({
+ value: s,
+ label: scopeLabels[s],
+ count: scopeCounts[s],
+ }))}
/>
}
+ tools={
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger render={<CollectionFilterButton count={activeFilterCount} />} />
+ <DropdownMenuContent align="start" className="w-auto">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.toolbar.section_status)}</span>
+ {filters.statuses.length > 0 && (
+ <span className="text-caption font-medium text-primary">{filters.statuses.length}</span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {STATUS_VALUES.map((s) => (
+ <DropdownMenuCheckboxItem
+ key={s}
+ checked={filters.statuses.includes(s)}
+ onCheckedChange={() => toggleFilter("statuses", s)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.statuses.includes(s)} />
+ {t(($) => $.status[s])}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.toolbar.section_priority)}</span>
+ {filters.priorities.length > 0 && (
+ <span className="text-caption font-medium text-primary">{filters.priorities.length}</span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {PRIORITY_VALUES.map((pr) => (
+ <DropdownMenuCheckboxItem
+ key={pr}
+ checked={filters.priorities.includes(pr)}
+ onCheckedChange={() => toggleFilter("priorities", pr)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.priorities.includes(pr)} />
+ {t(($) => $.priority[pr])}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.toolbar.section_lead)}</span>
+ {filters.leads.length > 0 && (
+ <span className="text-caption font-medium text-primary">{filters.leads.length}</span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...leadOptions.entries()].map(([value, { type, id, count }]) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={filters.leads.includes(value)}
+ onCheckedChange={() => toggleFilter("leads", value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.leads.includes(value)} />
+ <ActorAvatar actorType={type} actorId={id} size="sm" />
+ <span className="min-w-0 truncate">{getActorName(type, id)}</span>
+ {countBadge(count)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {hasActiveFilters ? <CollectionResetButton onClick={clearFilters} /> : null}
+ </>
+ }
+ actions={
+ <>
+ {/* Sort applies to both views; columns only to the table. */}
+ <CollectionDisplayMenu
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ onToggleColumn={(key) => toggleColumn(key as ProjectColumnKey)}
+ sort={sort}
+ showColumns={isCompact}
+ triggerIcon={isCompact ? Rows3 : LayoutGrid}
+ extra={
+ <div
+ role="group"
+ aria-label={t(($) => $.toolbar.view)}
+ className="grid grid-cols-2 gap-0.5 rounded-lg bg-muted p-0.5"
+ >
+ {VIEW_MODES.map(({ mode, Icon }) => (
+ <Toggle
+ key={mode}
+ pressed={viewMode === mode}
+ onPressedChange={() => setViewMode(mode)}
+ className="h-auto min-w-0 flex-col gap-1 rounded-md px-0.5 py-1.5 text-caption font-normal text-muted-foreground hover:bg-transparent hover:text-foreground aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm aria-pressed:hover:bg-background"
+ >
+ <Icon className="size-4" />
+ <span className="max-w-full truncate">
+ {mode === "compact" ? t(($) => $.page.view_table) : t(($) => $.page.view_cards)}
+ </span>
+ </Toggle>
+ ))}
+ </div>
+ }
+ />
+ <CollectionCreateButton
+ label={t(($) => $.page.new_project)}
+ onClick={openCreateProject}
+ />
+ </>
+ }
/>
{showEmpty ? (
@@ -966,313 +857,37 @@ export function ProjectsPage() {
/>
) : (
<>
- {/* Toolbar */}
- <div className={PAGE_TOOLBAR}>
- <div className="flex min-w-0 items-center gap-2">
- <div className="relative hidden md:block">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- aria-label={t(($) => $.page.search_placeholder)}
- placeholder={t(($) => $.page.search_placeholder)}
- className="h-8 w-56 pl-8 text-body"
+ {isCompact ? (
+ <CollectionList
+ label={scopeLabels[scope]}
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ rows={visible}
+ loading={isLoading}
+ getRowId={(project) => project.id}
+ getRowHref={(project) => wsPaths.projectDetail(project.id)}
+ getRowTitle={(project) => project.title}
+ rowMenu={(project) => (
+ <ProjectRowActions
+ project={project}
+ pinned={pinnedProjectIds.has(project.id)}
+ canDelete={isWorkspaceAdmin}
/>
- </div>
- {(hasActiveFilters || search.trim().length > 0) && (
- <span
- title={t(($) => $.toolbar.result_count_title)}
- className="hidden shrink-0 text-caption tabular-nums text-muted-foreground md:inline"
- >
- {visible.length} / {projects.length}
- </span>
)}
- </div>
-
- <div className="flex shrink-0 items-center gap-1">
- {/* Filter */}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant={hasActiveFilters ? "default" : "outline"}
- size="sm"
- className={
- hasActiveFilters
- ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"
- : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- }
- >
- <Filter className="size-3.5" />
- {hasActiveFilters ? (
- <>
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_active_count, { count: activeFilterCount })}
- </span>
- <span className="tabular-nums md:hidden">{activeFilterCount}</span>
- </>
- ) : (
- <span className="hidden md:inline">{t(($) => $.toolbar.filter_label)}</span>
- )}
- {hasActiveFilters && (
- <span
- role="button"
- tabIndex={-1}
- aria-label={t(($) => $.toolbar.clear_filters)}
- className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- clearFilters();
- }}
- onPointerDown={(e) => e.stopPropagation()}
- >
- <X className="size-3" />
- </span>
- )}
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.toolbar.section_status)}</span>
- {filters.statuses.length > 0 && (
- <span className="text-caption font-medium text-primary">{filters.statuses.length}</span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {STATUS_VALUES.map((s) => (
- <DropdownMenuCheckboxItem
- key={s}
- checked={filters.statuses.includes(s)}
- onCheckedChange={() => toggleFilter("statuses", s)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.statuses.includes(s)} />
- {t(($) => $.status[s])}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.toolbar.section_priority)}</span>
- {filters.priorities.length > 0 && (
- <span className="text-caption font-medium text-primary">{filters.priorities.length}</span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {PRIORITY_VALUES.map((pr) => (
- <DropdownMenuCheckboxItem
- key={pr}
- checked={filters.priorities.includes(pr)}
- onCheckedChange={() => toggleFilter("priorities", pr)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.priorities.includes(pr)} />
- {t(($) => $.priority[pr])}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.toolbar.section_lead)}</span>
- {filters.leads.length > 0 && (
- <span className="text-caption font-medium text-primary">{filters.leads.length}</span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...leadOptions.entries()].map(([value, { type, id, count }]) => (
- <DropdownMenuCheckboxItem
- key={value}
- checked={filters.leads.includes(value)}
- onCheckedChange={() => toggleFilter("leads", value)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.leads.includes(value)} />
- <ActorAvatar actorType={type} actorId={id} size="sm" />
- <span className="min-w-0 truncate">{getActorName(type, id)}</span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {/* Display (sort + columns). Always present — view mode is a
- pure presentation choice and must not reshape the toolbar.
- Sort applies to both views; the columns section is shown
- only in the table view (cards have no columns). */}
- <Popover>
- <Tooltip>
- <PopoverTrigger
- render={
- <TooltipTrigger
- render={
- <Button variant="outline" size="sm" className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5">
- {sortDirection === "asc" ? <ArrowUp className="size-3.5" /> : <ArrowDown className="size-3.5" />}
- <span className="hidden md:inline">{sortLabel(sortField)}</span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">{t(($) => $.toolbar.display)}</TooltipContent>
- </Tooltip>
- <PopoverContent align="end" className="w-64 p-0">
- <div className="border-b px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">{t(($) => $.toolbar.sort_by)}</span>
- <div className="mt-2 flex items-center gap-1.5">
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button variant="outline" size="sm" className="flex-1 justify-between text-caption">
- {sortLabel(sortField)}
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={sortField}
- onValueChange={(v) => setSortField(v as ProjectSortField)}
- >
- {SORT_FIELDS.map((f) => (
- <DropdownMenuRadioItem key={f} value={f}>
- {sortLabel(f)}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <IconButton
- variant="outline"
- size="icon-sm"
- onClick={() => setSortDirection(sortDirection === "asc" ? "desc" : "asc")}
- label={sortDirection === "asc" ? t(($) => $.toolbar.direction_asc) : t(($) => $.toolbar.direction_desc)}
- >
- {sortDirection === "asc" ? <ArrowUp className="size-3.5" /> : <ArrowDown className="size-3.5" />}
- </IconButton>
- </div>
- </div>
- {isCompact && (
- <div className="px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">{t(($) => $.toolbar.section_columns)}</span>
- <div className="mt-2 space-y-2">
- {COLUMN_KEYS.map((key) => (
- <label key={key} className="flex cursor-pointer items-center justify-between">
- <span className="text-body">{columnLabel(key)}</span>
- <Switch size="sm" checked={!hiddenColumns.includes(key)} onCheckedChange={() => toggleColumn(key)} />
- </label>
- ))}
- </div>
- </div>
- )}
- </PopoverContent>
- </Popover>
-
- {/* View selector — a dropdown menu to pick the list view,
- aligned with the issue list's view menu. The trigger shows
- the active view; the menu carries every mode so new views
- can be added as menu items. Pure presentation. */}
- <DropdownMenu>
- <Tooltip>
- <DropdownMenuTrigger
- render={
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- >
- {isCompact ? (
- <Rows3 className="size-3.5" />
- ) : (
- <LayoutGrid className="size-3.5" />
- )}
- <span className="hidden md:inline">
- {isCompact ? t(($) => $.page.view_table) : t(($) => $.page.view_cards)}
- </span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">{t(($) => $.toolbar.view)}</TooltipContent>
- </Tooltip>
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuGroup>
- <DropdownMenuLabel>{t(($) => $.toolbar.view)}</DropdownMenuLabel>
- </DropdownMenuGroup>
- <DropdownMenuRadioGroup
- value={viewMode}
- onValueChange={(v) => setViewMode(v as ProjectViewMode)}
- >
- <DropdownMenuRadioItem value="compact">
- <Rows3 />
- {t(($) => $.page.view_table)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="comfortable">
- <LayoutGrid />
- {t(($) => $.page.view_cards)}
- </DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
-
- {/* Body */}
- {isLoading ? (
- <LoadingState isCompact={isCompact} />
+ sort={sort}
+ selection={{ selectedIds, onChange: setSelectedIds }}
+ empty={t(($) => $.page.no_matches)}
+ />
+ ) : isLoading ? (
+ <CardsLoading />
) : visible.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center py-24 text-muted-foreground">
<Search className="mb-3 h-10 w-10 opacity-30" />
<p className="text-body">{t(($) => $.page.no_matches)}</p>
</div>
- ) : isCompact ? (
- <div className="min-h-0 flex-1 overflow-auto @container">
- <ListGrid
- className={`${GRID_COLS} @2xl:min-w-[var(--pjc-minw)]`}
- style={{
- ...columnTrackVars(isColVisible),
- paddingBottom: LIST_GRID_BOTTOM_CLEARANCE,
- }}
- >
- <ProjectTableHeader
- sortField={sortField}
- sortDirection={sortDirection}
- onSort={toggleSort}
- isColVisible={isColVisible}
- allSelected={allSelected}
- someSelected={someSelected}
- onToggleAll={handleToggleAll}
- />
- {visible.map((project) => (
- <ProjectTableRow
- key={project.id}
- project={project}
- pinned={pinnedProjectIds.has(project.id)}
- canDelete={isWorkspaceAdmin}
- isColVisible={isColVisible}
- selected={selectedIds.has(project.id)}
- onToggleSelect={() => toggleSelected(project.id)}
- rowHref={wsPaths.projectDetail(project.id)}
- rowLink={rowLink}
- />
- ))}
- </ListGrid>
- </div>
) : (
- <div className={cn("min-h-0 flex-1 overflow-y-auto pt-4", PAGE_GUTTER)}>
- <div
- className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4"
- style={{ paddingBottom: LIST_GRID_BOTTOM_CLEARANCE }}
- >
+ <div className={cn("min-h-0 flex-1 overflow-y-auto pt-4 pb-16", PAGE_GUTTER)}>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
{visible.map((project) => (
<ProjectCard
key={project.id}
@@ -1297,18 +912,7 @@ export function ProjectsPage() {
);
}
-function LoadingState({ isCompact }: { isCompact: boolean }) {
- if (isCompact) {
- return (
- <div className={cn("min-h-0 flex-1 overflow-auto pt-4", PAGE_GUTTER)}>
- <div className="space-y-2">
- {Array.from({ length: 6 }).map((_, i) => (
- <Skeleton key={i} className="h-11 w-full rounded-md" />
- ))}
- </div>
- </div>
- );
- }
+function CardsLoading() {
return (
<div className={cn("grid grid-cols-1 gap-3 pt-4 sm:grid-cols-2 lg:grid-cols-4", PAGE_GUTTER)}>
{Array.from({ length: 8 }).map((_, i) => (
diff --git a/packages/views/runtimes/components/machine-cli-section.tsx b/packages/views/runtimes/components/machine-cli-section.tsx
index eb26e63c62..68d928d735 100644
--- a/packages/views/runtimes/components/machine-cli-section.tsx
+++ b/packages/views/runtimes/components/machine-cli-section.tsx
@@ -29,6 +29,25 @@ export function machineUpdateRuntime(
);
}
+/**
+ * Whether the machine has a CLI version or update channel to show.
+ * A viewer's ability to send an update command must not gate the
+ * machine-level version and manager information. The only local machine
+ * without anything to report is Desktop's synthesized stopped-daemon row.
+ */
+export function machineHasCliInfo(
+ machine: RuntimeMachine,
+ updateRuntime: AgentRuntime | null,
+): boolean {
+ if (machine.mode !== "local") return !!machine.cliVersion;
+ return (
+ !!updateRuntime ||
+ machine.runtimes.length > 0 ||
+ !!machine.cliVersion ||
+ !!machine.launchedBy
+ );
+}
+
export function MachineCliSection({
machine,
currentUserId,
@@ -44,22 +63,10 @@ export function MachineCliSection({
canManagePublicRuntimes,
);
- if (machine.mode !== "local") {
- return machine.cliVersion ? (
- <span className="font-mono">CLI {machine.cliVersion}</span>
- ) : null;
- }
+ if (!machineHasCliInfo(machine, updateRuntime)) return null;
- // A viewer's ability to send an update command must not gate the
- // machine-level version and manager information. The only local machine
- // without anything to report is Desktop's synthesized stopped-daemon row.
- if (
- !updateRuntime &&
- machine.runtimes.length === 0 &&
- !machine.cliVersion &&
- !machine.launchedBy
- ) {
- return null;
+ if (machine.mode !== "local") {
+ return <span className="font-mono">CLI {machine.cliVersion}</span>;
}
return (
diff --git a/packages/views/runtimes/components/qoder-detail-page.test.tsx b/packages/views/runtimes/components/qoder-detail-page.test.tsx
index 0410bc42c3..53f0eb27fa 100644
--- a/packages/views/runtimes/components/qoder-detail-page.test.tsx
+++ b/packages/views/runtimes/components/qoder-detail-page.test.tsx
@@ -10,6 +10,8 @@ import {
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import type { AgentRuntime } from "@multica/core/types";
+import enCommon from "../../locales/en/common.json";
+import enLayout from "../../locales/en/layout.json";
import enRuntimes from "../../locales/en/runtimes.json";
import { isQoderLocator, QoderDetailPage } from "./qoder-detail-page";
@@ -74,7 +76,7 @@ vi.mock("./qoder-configuration", () => ({
}));
vi.mock("./usage-section", () => ({ UsageSection: () => null }));
vi.mock("./runtime-detail", () => ({
- ServingAgentsCard: ({ agents }: { agents: { id: string; name: string }[] }) => (
+ ServingAgentList: ({ agents }: { agents: { id: string; name: string }[] }) => (
<ul aria-label="serving agents">
{agents.map((agent) => (
<li key={agent.id}>{agent.name}</li>
@@ -127,7 +129,10 @@ function mount() {
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
render(
- <I18nProvider locale="en" resources={{ en: { runtimes: enRuntimes } }}>
+ <I18nProvider
+ locale="en"
+ resources={{ en: { common: enCommon, layout: enLayout, runtimes: enRuntimes } }}
+ >
<QueryClientProvider client={client}>
<QoderDetailPage />
</QueryClientProvider>
diff --git a/packages/views/runtimes/components/qoder-detail-page.tsx b/packages/views/runtimes/components/qoder-detail-page.tsx
index 9ef83d3de9..5dcd8e238f 100644
--- a/packages/views/runtimes/components/qoder-detail-page.tsx
+++ b/packages/views/runtimes/components/qoder-detail-page.tsx
@@ -36,7 +36,13 @@ import {
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
import { cn } from "@multica/ui/lib/utils";
-import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
+import { CollectionPageState } from "../../layout/collection-page";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectSection,
+} from "../../layout/object-page";
import { AppLink, useNavigation } from "../../navigation";
import { createPathWithParams } from "../../agents/create/squad-param";
import { useT } from "../../i18n";
@@ -50,13 +56,15 @@ import {
savedQoderInput,
} from "./qoder-connection-cards";
import { QoderStatusBadge } from "./qoder-status-badge";
-import { ServingAgentsCard } from "./runtime-detail";
+import { ServingAgentList } from "./runtime-detail";
import { UsageSection } from "./usage-section";
import { parseActiveAgentsConflict } from "./delete-runtime-dialog";
/** Route locator of the workspace's Qoder Cloud Agents page. */
export const QODER_RUNTIME_LOCATOR = "qoder";
+const LAYOUT_ID = "multica_runtime_detail_layout";
+
/**
* Whether a runtimes route locator names Qoder: its own locator, the machine
* id its runtime registers under, or the id of a Qoder runtime.
@@ -92,25 +100,46 @@ export function QoderDetailPage() {
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
- if (connection.isPending || runtimesLoading) return <QoderPageSkeleton />;
+ const title = t(($) => $.qoder.cloud_title);
+ const segments = [{ href: paths.runtimes(), label: t(($) => $.page.title) }];
+ const leaf = (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <ProviderLogo provider="qoder_cloud" className="size-3.5 shrink-0" />
+ <span className="truncate">{title}</span>
+ </span>
+ );
+
+ if (connection.isPending || runtimesLoading) {
+ return (
+ <ObjectPage layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
+ <QoderBodySkeleton />
+ </ObjectPage>
+ );
+ }
const data = connection.data;
if (connection.isError || data?.available !== true) {
return (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
- <AlertCircle aria-hidden="true" className="size-8 text-destructive" />
- <p className="max-w-md text-body">
- {connection.isError
- ? connection.error.message
- : t(($) => $.qoder.unavailable)}
- </p>
- <Button
- size="sm"
- render={<AppLink href={paths.runtimes()} />}
- nativeButton={false}
- >
- {t(($) => $.detail.all_runtimes)}
- </Button>
- </div>
+ <ObjectPage layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
+ <CollectionPageState
+ icon={AlertCircle}
+ tone="destructive"
+ title={
+ connection.isError
+ ? connection.error.message
+ : t(($) => $.qoder.unavailable)
+ }
+ actions={
+ <Button
+ size="sm"
+ variant="outline"
+ render={<AppLink href={paths.runtimes()} />}
+ nativeButton={false}
+ >
+ {t(($) => $.detail.all_runtimes)}
+ </Button>
+ }
+ />
+ </ObjectPage>
);
}
@@ -134,172 +163,144 @@ export function QoderDetailPage() {
data.status === "online" &&
runtime?.status === "online";
+ const failing = data.enabled && data.status === "error" && !!data.lastError;
+
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <QoderHeader
- data={data}
- agentCount={boundAgents.length}
- action={
- ready && runtime ? (
- <Button
- size="sm"
- onClick={() =>
- navigation.push(
- createPathWithParams(paths.newAgentManual(), {
- runtime: runtime.id,
- }),
- )
- }
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={leaf}
+ actions={
+ ready && runtime ? (
+ <Button
+ size="sm"
+ onClick={() =>
+ navigation.push(
+ createPathWithParams(paths.newAgentManual(), {
+ runtime: runtime.id,
+ }),
+ )
+ }
+ >
+ <Plus aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.create_agent)}
+ </Button>
+ ) : undefined
+ }
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="space-y-3">
+ <ObjectIdentity
+ media={
+ <div className="flex size-12 items-center justify-center rounded-xl border bg-muted/50">
+ <ProviderLogo provider="qoder_cloud" className="size-6" />
+ </div>
+ }
+ title={title}
+ trailing={<QoderStatusBadge connection={data} />}
+ description={
+ data.configured ? (
+ <QoderSummary data={data} agentCount={boundAgents.length} />
+ ) : undefined
+ }
+ />
+ {failing && (
+ <p
+ role="alert"
+ className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-caption text-destructive"
>
- <Plus aria-hidden="true" className="size-3.5" />
- {t(($) => $.qoder.create_agent)}
- </Button>
- ) : null
- }
- />
- <div className="min-h-0 flex-1 overflow-y-auto bg-background">
- <div
- className={cn(
- PAGE_RAIL,
- PAGE_GUTTER,
- "grid grid-cols-1 gap-4 py-4 sm:py-6 lg:grid-cols-[minmax(0,1fr)_320px]",
+ {data.lastError}
+ </p>
)}
- >
- <div className="min-w-0 space-y-4">
- {data.configured ? (
- <>
- <QoderConnectionCard wsId={wsId} data={data} canManage={isAdmin} />
- <QoderRepositoriesCard
- wsId={wsId}
- data={data}
- canManage={isAdmin}
- />
- </>
- ) : (
- <QoderSection title={t(($) => $.qoder.page.configuration)}>
- <div className="p-4">
- {isAdmin ? (
- <QoderConfiguration />
- ) : (
- <div className="py-6 text-center">
- <p className="text-body font-medium">
- {t(($) => $.qoder.page.not_connected_title)}
- </p>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.qoder.page.not_connected_hint)}
- </p>
- </div>
- )}
- </div>
- </QoderSection>
- )}
- {runtime && isRuntimeUsableForUser(runtime, userId) && (
- <UsageSection runtime={runtime} />
- )}
- </div>
- <div className="space-y-4">
- <ServingAgentsCard
- agents={boundAgents}
- presenceMap={presenceMap}
- agentHref={(id) => paths.agentDetail(id)}
- />
- {data.configured && (
- <QoderLimitsCard wsId={wsId} data={data} canManage={isAdmin} />
- )}
- {isAdmin && data.configured && (
- <ManageCard
- wsId={wsId}
- data={data}
- boundAgents={boundAgents}
- onDisconnected={() => {
- navigation.replace(paths.runtimes());
- toast.success(t(($) => $.qoder.disconnect_confirm.done));
- }}
- />
- )}
- </div>
</div>
+
+ {data.configured ? (
+ <>
+ <QoderConnectionCard wsId={wsId} data={data} canManage={isAdmin} />
+ <QoderRepositoriesCard wsId={wsId} data={data} canManage={isAdmin} />
+ </>
+ ) : (
+ <QoderSection title={t(($) => $.qoder.page.configuration)}>
+ <div className="p-4">
+ {isAdmin ? (
+ <QoderConfiguration />
+ ) : (
+ <div className="py-6 text-center">
+ <p className="text-body font-medium">
+ {t(($) => $.qoder.page.not_connected_title)}
+ </p>
+ <p className="mt-1 text-caption text-muted-foreground">
+ {t(($) => $.qoder.page.not_connected_hint)}
+ </p>
+ </div>
+ )}
+ </div>
+ </QoderSection>
+ )}
+
+ <ObjectSection
+ title={t(($) => $.page.columns.agents)}
+ count={boundAgents.length}
+ >
+ <ServingAgentList
+ agents={boundAgents}
+ presenceMap={presenceMap}
+ agentHref={(id) => paths.agentDetail(id)}
+ />
+ </ObjectSection>
+
+ {data.configured && (
+ <QoderLimitsCard wsId={wsId} data={data} canManage={isAdmin} />
+ )}
+ {runtime && isRuntimeUsableForUser(runtime, userId) && (
+ <ObjectSection title={t(($) => $.detail.usage_title)}>
+ <UsageSection runtime={runtime} />
+ </ObjectSection>
+ )}
+ {isAdmin && data.configured && (
+ <ManageCard
+ wsId={wsId}
+ data={data}
+ boundAgents={boundAgents}
+ onDisconnected={() => {
+ navigation.replace(paths.runtimes());
+ toast.success(t(($) => $.qoder.disconnect_confirm.done));
+ }}
+ />
+ )}
</div>
- </div>
+ </ObjectPage>
);
}
-function QoderHeader({
+function QoderSummary({
data,
agentCount,
- action,
}: {
data: QoderConnection;
agentCount: number;
- action: React.ReactNode;
}) {
const { t } = useT("runtimes");
- const paths = useWorkspacePaths();
- const title = t(($) => $.qoder.cloud_title);
const region =
data.baseUrl === QODER_REGIONS.cn
? t(($) => $.qoder.region_cn)
: t(($) => $.qoder.region_global);
- const failing = data.enabled && data.status === "error" && !!data.lastError;
return (
- <header className="shrink-0 border-b bg-background pb-5 pt-3">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
- <div className="flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
- <AppLink
- href={paths.runtimes()}
- className="rounded-sm transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {t(($) => $.page.title)}
- </AppLink>
- <span aria-hidden="true">/</span>
- <span className="truncate text-foreground">{title}</span>
- </div>
- <div className="mt-4 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
- <div className="flex min-w-0 items-start gap-4">
- <div className="flex size-12 shrink-0 items-center justify-center rounded-xl border bg-card sm:size-14">
- <ProviderLogo provider="qoder_cloud" className="size-6" />
- </div>
- <div className="min-w-0 pt-0.5">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
- <h1 className="min-w-0 text-balance text-title-lg font-semibold tracking-tight sm:text-display-sm">
- {title}
- </h1>
- <QoderStatusBadge connection={data} />
- </div>
- {failing && (
- <p role="alert" className="mt-1 text-body text-destructive">
- {data.lastError}
- </p>
- )}
- {data.configured ? (
- <div className="mt-1.5 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-muted-foreground">
- <span>{region}</span>
- <span aria-hidden="true">·</span>
- <span>
- {t(($) => $.qoder.agent_count, { count: agentCount })}
- </span>
- <span aria-hidden="true">·</span>
- <span className="tabular-nums">
- {data.enabled && data.status === "online"
- ? t(($) => $.qoder.usage, {
- active: data.activeRuns,
- limit: data.maxConcurrency,
- queued: data.queuedRuns,
- })
- : t(($) => $.qoder.page.workload_idle)}
- </span>
- </div>
- ) : null}
- </div>
- </div>
- {action && (
- <div className="flex shrink-0 items-center gap-2 self-end lg:self-start">
- {action}
- </div>
- )}
- </div>
- </div>
- </header>
+ <span className="flex flex-wrap items-center gap-x-1.5">
+ <span>{region}</span>
+ <span aria-hidden="true">·</span>
+ <span>{t(($) => $.qoder.agent_count, { count: agentCount })}</span>
+ <span aria-hidden="true">·</span>
+ <span className="tabular-nums">
+ {data.enabled && data.status === "online"
+ ? t(($) => $.qoder.usage, {
+ active: data.activeRuns,
+ limit: data.maxConcurrency,
+ queued: data.queuedRuns,
+ })
+ : t(($) => $.qoder.page.workload_idle)}
+ </span>
+ </span>
);
}
@@ -556,24 +557,17 @@ export function DisconnectQoderDialog({
);
}
-function QoderPageSkeleton() {
+function QoderBodySkeleton() {
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="border-b pb-5 pt-3">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
- <Skeleton className="h-3 w-36" />
- <div className="mt-4 flex items-start gap-4">
- <Skeleton className="size-14 rounded-xl" />
- <div className="flex-1">
- <Skeleton className="h-7 w-64" />
- <Skeleton className="mt-2 h-4 w-40" />
- </div>
- </div>
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-xl" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-5 w-56" />
+ <Skeleton className="h-4 w-40" />
</div>
</div>
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-6")}>
- <Skeleton className="h-64 w-full rounded-lg" />
- </div>
+ <Skeleton className="h-64 w-full rounded-lg" />
</div>
);
}
diff --git a/packages/views/runtimes/components/runtime-detail-page.test.tsx b/packages/views/runtimes/components/runtime-detail-page.test.tsx
new file mode 100644
index 0000000000..574dd4b826
--- /dev/null
+++ b/packages/views/runtimes/components/runtime-detail-page.test.tsx
@@ -0,0 +1,202 @@
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { agentTaskSnapshotOptions } from "@multica/core/agents";
+import { runtimeProfileListOptions } from "@multica/core/runtimes";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import type { AgentRuntime } from "@multica/core/types";
+import {
+ agentListOptions,
+ memberListOptions,
+} from "@multica/core/workspace/queries";
+import enCommon from "../../locales/en/common.json";
+import enLayout from "../../locales/en/layout.json";
+import enRuntimes from "../../locales/en/runtimes.json";
+import { RuntimeDetailPage } from "./runtime-detail-page";
+
+const TEST_RESOURCES = {
+ en: { common: enCommon, layout: enLayout, runtimes: enRuntimes },
+};
+const WS = "ws-test";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (select: (state: unknown) => unknown) =>
+ select({ isLoading: false, user: { id: "user-1" } }),
+}));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ runtimes: () => "/runtimes",
+ runtimeSettings: (machineId: string, runtimeId: string) =>
+ `/runtimes/${machineId}/runtime/${runtimeId}`,
+ }),
+}));
+vi.mock("@multica/core/realtime", () => ({ useWSEvent: () => {} }));
+vi.mock("../../navigation", () => ({
+ AppLink: ({ href, children, ...props }: { href: string; children: ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("./provider-logo", () => ({ ProviderLogo: () => null }));
+vi.mock("./qoder-detail-page", () => ({
+ isQoderLocator: () => false,
+ QoderDetailPage: () => null,
+}));
+vi.mock("./runtime-list", () => ({
+ buildWorkloadIndex: () => new Map(),
+ RuntimeList: ({ runtimes }: { runtimes: AgentRuntime[] }) => (
+ <ul aria-label="machine runtimes">
+ {runtimes.map((runtime) => (
+ <li key={runtime.id}>{runtime.name}</li>
+ ))}
+ </ul>
+ ),
+}));
+vi.mock("./update-section", () => ({
+ UpdateSection: ({ currentVersion }: { currentVersion: string | null }) => (
+ <span>CLI version {currentVersion}</span>
+ ),
+}));
+vi.mock("./rename-machine-dialog", () => ({
+ RenameMachineDialog: ({ open }: { open: boolean }) =>
+ open ? <div role="dialog">Rename machine dialog</div> : null,
+}));
+vi.mock("./runtime-profiles-dialog", () => ({
+ RuntimeProfilesDialog: () => <div role="dialog">Custom runtime dialog</div>,
+}));
+
+const NOW = Date.now();
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "rt-claude",
+ workspace_id: WS,
+ daemon_id: "daemon-1",
+ name: "Claude (dev-machine.local)",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "dev-machine.local · claude 1.0.0",
+ metadata: { cli_version: "0.3.17" },
+ owner_id: "user-1",
+ visibility: "private",
+ last_seen_at: new Date(NOW - 5_000).toISOString(),
+ created_at: new Date(NOW - 60_000).toISOString(),
+ updated_at: new Date(NOW - 60_000).toISOString(),
+ ...overrides,
+ };
+}
+
+function renderPage({
+ runtimeId = "rt-claude",
+ runtimes = [makeRuntime()],
+}: {
+ runtimeId?: string;
+ /** `null` leaves the runtime list unseeded, so the page renders loading. */
+ runtimes?: AgentRuntime[] | null;
+} = {}) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ if (runtimes) qc.setQueryData(runtimeListOptions(WS).queryKey, runtimes);
+ qc.setQueryData(runtimeProfileListOptions(WS).queryKey, []);
+ qc.setQueryData(agentListOptions(WS).queryKey, []);
+ qc.setQueryData(agentTaskSnapshotOptions(WS).queryKey, []);
+ qc.setQueryData(memberListOptions(WS).queryKey, [
+ {
+ id: "member-1",
+ workspace_id: WS,
+ user_id: "user-1",
+ role: "owner",
+ created_at: new Date(NOW).toISOString(),
+ name: "Jiayuan",
+ email: "[email protected]",
+ avatar_url: null,
+ },
+ ]);
+ return render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <RuntimeDetailPage
+ runtimeId={runtimeId}
+ localDaemonId="daemon-1"
+ localMachineName="Studio Mac"
+ hasLocalMachine
+ localMachineActions={<button type="button">Start</button>}
+ />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+describe("RuntimeDetailPage", () => {
+ it("keeps the breadcrumb header in place while the machine loads", () => {
+ const { container } = renderPage({ runtimes: null });
+
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("link", { name: "Runtimes" })).toHaveAttribute(
+ "href",
+ "/runtimes",
+ );
+ expect(screen.getAllByRole("banner")).toHaveLength(1);
+ expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();
+ });
+
+ it("lays the machine out as identity, Daemon and Runtimes sections with a properties panel", () => {
+ renderPage();
+
+ const header = screen.getByRole("banner");
+ expect(screen.getAllByRole("banner")).toHaveLength(1);
+ expect(header).toHaveTextContent("Studio Mac");
+ expect(within(header).queryByRole("button", { name: "Start" })).not.toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 1, name: "Studio Mac" })).toBeInTheDocument();
+ expect(screen.getByText("This device")).toBeInTheDocument();
+
+ const daemon = screen.getByRole("heading", { level: 2, name: "Daemon" }).closest("section")!;
+ expect(within(daemon).getByRole("button", { name: "Start" })).toBeInTheDocument();
+ expect(within(daemon).getByText("CLI version 0.3.17")).toBeInTheDocument();
+
+ const runtimes = screen.getByRole("heading", { level: 2, name: "Runtimes" }).closest("section")!;
+ expect(within(runtimes).getByText("1")).toBeInTheDocument();
+ expect(within(runtimes).getByRole("list", { name: "machine runtimes" })).toHaveTextContent(
+ "Claude (dev-machine.local)",
+ );
+ expect(within(runtimes).getByRole("button", { name: /Add custom runtime/ })).toBeInTheDocument();
+
+ expect(screen.getByRole("button", { name: "Properties" })).toBeInTheDocument();
+ expect(screen.getByText("Status")).toBeInTheDocument();
+ expect(screen.getByText("Owner")).toBeInTheDocument();
+ expect(screen.getByText("Jiayuan")).toBeInTheDocument();
+ expect(screen.getByText("Daemon ID")).toBeInTheDocument();
+ });
+
+ it("moves Rename machine into the ⋯ menu", async () => {
+ renderPage();
+
+ expect(screen.queryByRole("button", { name: "Rename machine" })).not.toBeInTheDocument();
+ fireEvent.click(
+ within(screen.getByRole("banner")).getByRole("button", { name: "More actions" }),
+ );
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Rename machine" }));
+ expect(await screen.findByRole("dialog")).toHaveTextContent("Rename machine dialog");
+ });
+
+ it("shows not-found in the body under the same breadcrumb", () => {
+ renderPage({ runtimeId: "missing" });
+
+ expect(
+ within(screen.getByRole("banner")).getByRole("link", { name: "Runtimes" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Machine not found" })).toBeInTheDocument();
+ expect(screen.getByText("All runtimes").closest("a")).toHaveAttribute(
+ "href",
+ "/runtimes",
+ );
+ });
+});
diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsx
index 8b2ca29851..ea11d082a8 100644
--- a/packages/views/runtimes/components/runtime-detail-page.tsx
+++ b/packages/views/runtimes/components/runtime-detail-page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { AlertCircle, Cloud, Monitor, Pencil, Plus, Server } from "@multica/ui/icons";
+import { AlertCircle, MoreHorizontal, Pencil, Plus, Server } from "@multica/ui/icons";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -14,24 +14,57 @@ import {
agentListOptions,
memberListOptions,
} from "@multica/core/workspace/queries";
+import type { MemberWithUser } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { CollectionPageState } from "../../layout/collection-page";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIconMark,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectPanelSection,
+ ObjectProperty,
+ ObjectSection,
+ ObjectSectionAction,
+ ObjectSectionCard,
+} from "../../layout/object-page";
import { AppLink } from "../../navigation";
import { buildWorkloadIndex, RuntimeList } from "./runtime-list";
import {
buildRuntimeMachines,
sharedCustomName,
+ type RuntimeMachine,
} from "./runtime-machines";
import { RenameMachineDialog } from "./rename-machine-dialog";
import { RuntimeProfilesDialog } from "./runtime-profiles-dialog";
import { pendingRuntimesForProfiles } from "./pending-runtime";
-import { MachineCliSection } from "./machine-cli-section";
+import {
+ MachineCliSection,
+ machineHasCliInfo,
+ machineUpdateRuntime,
+} from "./machine-cli-section";
import { isQoderLocator, QoderDetailPage } from "./qoder-detail-page";
-import { HealthIcon, useHealthLabel } from "./shared";
+import {
+ HealthIcon,
+ ProviderIconStack,
+ machineIcon,
+ shortDaemonId,
+ useHealthLabel,
+} from "./shared";
import { useT, useTimeAgo } from "../../i18n";
+const LAYOUT_ID = "multica_runtime_detail_layout";
+
export interface RuntimeDetailPageProps {
/** A machine id, or a legacy runtime id that locates its machine. */
runtimeId: string;
@@ -93,7 +126,6 @@ export function RuntimeDetailPage({
const paths = useWorkspacePaths();
const qc = useQueryClient();
const healthLabel = useHealthLabel();
- const timeAgo = useTimeAgo();
const currentUserId = useAuthStore((state) => state.user?.id);
const { data: runtimes = [], isLoading } = useQuery(runtimeListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
@@ -185,175 +217,160 @@ export function RuntimeDetailPage({
) {
return <QoderDetailPage />;
}
- if (isLoading) return <MachineDetailSkeleton />;
+
+ const segments = [{ href: paths.runtimes(), label: t(($) => $.page.title) }];
+
+ if (isLoading) {
+ return (
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={<Skeleton className="h-4 w-40" />}
+ panel={<PropertiesSkeleton />}
+ >
+ <MachineBodySkeleton />
+ </ObjectPage>
+ );
+ }
if (!machine) {
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
- <AlertCircle className="h-8 w-8 text-destructive" />
- <div>
- <p className="text-body font-medium">
- {t(($) => $.machine.not_found_title)}
- </p>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.machine.not_found_hint)}
- </p>
- </div>
- <Button
- size="sm"
- render={<AppLink href={paths.runtimes()} />}
- nativeButton={false}
- >
- {t(($) => $.detail.all_runtimes)}
- </Button>
- </div>
- </div>
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.machine.not_found_title)}
+ </span>
+ }
+ >
+ <CollectionPageState
+ icon={AlertCircle}
+ tone="destructive"
+ title={t(($) => $.machine.not_found_title)}
+ description={t(($) => $.machine.not_found_hint)}
+ actions={
+ <Button
+ size="sm"
+ variant="outline"
+ render={<AppLink href={paths.runtimes()} />}
+ nativeButton={false}
+ >
+ {t(($) => $.detail.all_runtimes)}
+ </Button>
+ }
+ />
+ </ObjectPage>
);
}
- const Icon = machine.section === "cloud" ? Cloud : Monitor;
- const busyCount = machine.runningCount + machine.queuedCount;
+ const Icon = machineIcon(machine);
+ const updateRuntime = machineUpdateRuntime(machine, currentUserId, isAdmin);
+ const daemonActions = machine.isCurrent ? localMachineActions : null;
+ const hasCliInfo = machineHasCliInfo(machine, updateRuntime);
+ const summary = [
+ machine.subtitle,
+ machine.cliVersion ? `CLI ${machine.cliVersion}` : null,
+ healthLabel(machine.health),
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <header className="shrink-0 border-b bg-background pb-5 pt-3">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
- <div className="flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
- <AppLink
- href={paths.runtimes()}
- className="rounded-sm transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- {t(($) => $.page.title)}
- </AppLink>
- <span aria-hidden="true">/</span>
- <span className="truncate text-foreground">{machine.title}</span>
- </div>
+ <>
+ <ObjectPage
+ layoutId={LAYOUT_ID}
+ segments={segments}
+ leaf={
+ <span className="flex min-w-0 items-center gap-1.5">
+ <Icon aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{machine.title}</span>
+ </span>
+ }
+ actions={
+ renameTarget ? (
+ <MachineActionsMenu onRename={() => setRenameOpen(true)} />
+ ) : undefined
+ }
+ panel={<MachineProperties machine={machine} members={members} />}
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <ObjectIdentity
+ media={<ObjectIconMark icon={Icon} />}
+ title={machine.title}
+ trailing={
+ machine.isCurrent ? (
+ <span className="shrink-0 rounded-xs bg-foreground px-1.5 py-0.5 text-micro font-medium text-background">
+ {t(($) => $.machine.this_machine)}
+ </span>
+ ) : null
+ }
+ description={summary}
+ />
- <div className="mt-4 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
- <div className="flex min-w-0 items-start gap-4">
- <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border bg-card sm:h-14 sm:w-14">
- <Icon
- aria-hidden="true"
- className="h-5 w-5 text-muted-foreground sm:h-6 sm:w-6"
- />
- </div>
- <div className="min-w-0 pt-0.5">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
- <h1 className="min-w-0 text-balance text-title-lg font-semibold tracking-tight sm:text-display-sm">
- {machine.title}
- </h1>
- <span className="inline-flex items-center gap-1.5 text-caption">
- <HealthIcon health={machine.health} />
- {healthLabel(machine.health)}
- </span>
- {machine.isCurrent && (
- <span className="rounded-xs bg-foreground px-1.5 py-0.5 text-micro font-medium text-background">
- {t(($) => $.machine.this_machine)}
- </span>
- )}
- </div>
- {machine.subtitle && (
- <p className="mt-1 text-body text-muted-foreground">
- {machine.subtitle}
- </p>
- )}
- <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-caption text-muted-foreground">
- <span>
- {t(($) => $.machine.runtime_count, {
- count: machineRuntimes.length,
- })}
- </span>
- <span>
- {busyCount > 0
- ? t(($) => $.machine.metrics.workload_hint, {
- running: machine.runningCount,
- queued: machine.queuedCount,
- })
- : t(($) => $.machine.metrics.workload_idle)}
- </span>
+ {(hasCliInfo || daemonActions) && (
+ <ObjectSection
+ title={t(($) => $.machine.daemon_title)}
+ action={daemonActions}
+ >
+ {hasCliInfo && (
+ <ObjectSectionCard className="px-3 py-2.5 text-caption">
<MachineCliSection
machine={machine}
currentUserId={currentUserId}
canManagePublicRuntimes={isAdmin}
/>
- {machine.lastSeenAt && (
- <span>{timeAgo(machine.lastSeenAt)}</span>
- )}
- </div>
- </div>
- </div>
-
- <div className="flex shrink-0 items-center gap-2 self-end lg:self-start">
- {renameTarget && (
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={() => setRenameOpen(true)}
- >
- <Pencil aria-hidden="true" className="h-3.5 w-3.5" />
- {t(($) => $.machine.rename)}
- </Button>
+ </ObjectSectionCard>
)}
- {machine.isCurrent && localMachineActions}
- </div>
- </div>
- </div>
- </header>
+ </ObjectSection>
+ )}
- <div className="min-h-0 flex-1 overflow-y-auto bg-background">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-4 sm:py-6")}>
- <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
- <div className="min-w-0">
- <h2 className="text-body font-semibold">
- {t(($) => $.machine.metrics.runtimes)}
- </h2>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.machine.select_runtime)}
- </p>
- </div>
- {canAddRuntime && (
- <Button
- type="button"
- size="sm"
- onClick={() => setCreateProfileOpen(true)}
- >
- <Plus aria-hidden="true" className="h-3.5 w-3.5" />
- {t(($) => $.profiles.add_custom)}
- </Button>
+ <ObjectSection
+ title={t(($) => $.machine.metrics.runtimes)}
+ count={machineRuntimes.length}
+ action={
+ canAddRuntime ? (
+ <ObjectSectionAction
+ icon={Plus}
+ onClick={() => setCreateProfileOpen(true)}
+ >
+ {t(($) => $.profiles.add_custom)}
+ </ObjectSectionAction>
+ ) : null
+ }
+ >
+ {machineRuntimes.length > 0 ? (
+ <div className="-mx-2">
+ <RuntimeList
+ runtimes={machineRuntimes}
+ now={now}
+ machineTitle={machine.title}
+ runtimeHref={(childRuntimeId) =>
+ paths.runtimeSettings(machine.id, childRuntimeId)
+ }
+ />
+ </div>
+ ) : (
+ <div className="flex min-h-40 flex-col items-center justify-center rounded-lg border border-dashed px-6 text-center">
+ <Server
+ aria-hidden="true"
+ className="size-6 text-faint-foreground"
+ />
+ <p className="mt-3 text-body font-medium">
+ {bootstrapping
+ ? t(($) => $.page.bootstrapping.title)
+ : t(($) => $.machine.no_runtimes_title)}
+ </p>
+ <p className="mt-1 max-w-sm text-caption text-muted-foreground">
+ {bootstrapping
+ ? t(($) => $.page.bootstrapping.hint)
+ : t(($) => $.machine.no_runtimes_hint)}
+ </p>
+ </div>
)}
- </div>
- {machineRuntimes.length > 0 ? (
- <div className="overflow-hidden rounded-lg border bg-card">
- <RuntimeList
- runtimes={machineRuntimes}
- now={now}
- machineTitle={machine.title}
- runtimeHref={(childRuntimeId) =>
- paths.runtimeSettings(machine.id, childRuntimeId)
- }
- />
- </div>
- ) : (
- <div className="flex min-h-48 flex-col items-center justify-center rounded-lg border border-dashed px-6 text-center">
- <Server
- aria-hidden="true"
- className="h-7 w-7 text-faint-foreground"
- />
- <p className="mt-3 text-body font-medium">
- {bootstrapping
- ? t(($) => $.page.bootstrapping.title)
- : t(($) => $.machine.no_runtimes_title)}
- </p>
- <p className="mt-1 max-w-sm text-caption text-muted-foreground">
- {bootstrapping
- ? t(($) => $.page.bootstrapping.hint)
- : t(($) => $.machine.no_runtimes_hint)}
- </p>
- </div>
- )}
+ </ObjectSection>
</div>
- </div>
+ </ObjectPage>
{renameTarget && (
<RenameMachineDialog
@@ -372,32 +389,140 @@ export function RuntimeDetailPage({
onClose={() => setCreateProfileOpen(false)}
/>
)}
+ </>
+ );
+}
+
+function MachineActionsMenu({ onRename }: { onRename: () => void }) {
+ const { t } = useT("runtimes");
+ const { t: tCommon } = useT("common");
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={tCommon(($) => $.more_actions)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ >
+ <MoreHorizontal />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-auto">
+ <DropdownMenuItem onClick={onRename}>
+ <Pencil className="size-3.5" />
+ {t(($) => $.machine.rename)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function MachineProperties({
+ machine,
+ members,
+}: {
+ machine: RuntimeMachine;
+ members: MemberWithUser[];
+}) {
+ const { t } = useT("runtimes");
+ const { t: tLayout } = useT("layout");
+ const healthLabel = useHealthLabel();
+ const timeAgo = useTimeAgo();
+ const ownerId = machine.runtimes[0]?.owner_id ?? null;
+ const owner = ownerId
+ ? members.find((member) => member.user_id === ownerId) ?? null
+ : null;
+ const busy = machine.runningCount + machine.queuedCount > 0;
+ const daemonShort = shortDaemonId(machine.daemonId);
+
+ return (
+ <ObjectPanelSection title={tLayout(($) => $.object_page.properties)}>
+ <ObjectProperty label={t(($) => $.page.columns.status)}>
+ <HealthIcon health={machine.health} />
+ <span className="truncate">
+ {healthLabel(machine.health)}
+ {machine.lastSeenAt && machine.health !== "online"
+ ? ` · ${timeAgo(machine.lastSeenAt)}`
+ : null}
+ </span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.fact_owner)}>
+ {owner ? (
+ <>
+ <ActorAvatar
+ actorType="member"
+ actorId={owner.user_id}
+ size="xs"
+ enableHoverCard
+ />
+ <span className="truncate">{owner.name}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.fact_device)}>
+ <span className={machine.deviceSummary ? "truncate" : "text-muted-foreground"}>
+ {machine.deviceSummary ?? "—"}
+ </span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.page.columns.harness)}>
+ {machine.providerNames.length > 0 ? (
+ <ProviderIconStack providers={machine.providerNames} />
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.page.columns.workload)}>
+ <span className={busy ? "truncate tabular-nums" : "text-muted-foreground"}>
+ {busy
+ ? t(($) => $.machine.metrics.workload_hint, {
+ running: machine.runningCount,
+ queued: machine.queuedCount,
+ })
+ : t(($) => $.machine.metrics.workload_idle)}
+ </span>
+ </ObjectProperty>
+ {daemonShort && (
+ <ObjectProperty label={t(($) => $.detail.fact_daemon_id)}>
+ <span className="truncate font-mono">{daemonShort}</span>
+ </ObjectProperty>
+ )}
+ </ObjectPanelSection>
+ );
+}
+
+function PropertiesSkeleton() {
+ return (
+ <div className="space-y-3 px-2">
+ <Skeleton className="h-3 w-20" />
+ {Array.from({ length: 5 }).map((_, index) => (
+ <Skeleton key={index} className="h-4 w-full" />
+ ))}
</div>
);
}
-function MachineDetailSkeleton() {
+function MachineBodySkeleton() {
return (
- <div className="flex min-h-0 flex-1 flex-col">
- <div className="border-b pb-5 pt-3">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
- <Skeleton className="h-3 w-36" />
- <div className="mt-4 flex items-start gap-4">
- <Skeleton className="h-14 w-14 rounded-xl" />
- <div className="flex-1">
- <Skeleton className="h-7 w-64" />
- <Skeleton className="mt-2 h-4 w-40" />
- <Skeleton className="mt-3 h-3 w-72" />
- </div>
- </div>
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-xl" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-5 w-56" />
+ <Skeleton className="h-4 w-40" />
</div>
</div>
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-6")}>
+ <div className="space-y-2">
<Skeleton className="h-4 w-24" />
- <Skeleton className="mt-2 h-3 w-72" />
- <div className="mt-4 overflow-hidden rounded-lg border">
- {Array.from({ length: 4 }).map((_, index) => (
- <Skeleton key={index} className="h-14 w-full rounded-none border-b last:border-b-0" />
+ <div className="overflow-hidden rounded-lg border">
+ {Array.from({ length: 3 }).map((_, index) => (
+ <Skeleton
+ key={index}
+ className="h-14 w-full rounded-none border-b last:border-b-0"
+ />
))}
</div>
</div>
diff --git a/packages/views/runtimes/components/runtime-detail-rail.test.tsx b/packages/views/runtimes/components/runtime-detail-rail.test.tsx
deleted file mode 100644
index bca54e6bda..0000000000
--- a/packages/views/runtimes/components/runtime-detail-rail.test.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-// @vitest-environment jsdom
-
-import { describe, it, expect, vi } from "vitest";
-import { render } from "@testing-library/react";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enRuntimes from "../../locales/en/runtimes.json";
-import { RuntimeDetailPage } from "./runtime-detail-page";
-
-// MUL-7107: the loading header used to sit on a bare gutter while the header
-// that replaced it rode the rail, so on a wide window the title jumped inward
-// the moment the query resolved. The skeleton is not exported, so drive it
-// through the page's own isLoading branch rather than reaching past the seam.
-//
-// PAGE_RAIL is overridden with a sentinel because its real value is an
-// ordinary Tailwind class that a hand-written element could match by accident.
-const RAIL_SENTINEL = "rail-sentinel";
-vi.mock("../../layout/page-header", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../../layout/page-header")>()),
- PAGE_RAIL: "rail-sentinel",
-}));
-
-vi.mock("@tanstack/react-query", async () => {
- const actual =
- await vi.importActual<typeof import("@tanstack/react-query")>(
- "@tanstack/react-query",
- );
- return {
- ...actual,
- useQuery: () => ({ data: [], isLoading: true }),
- useQueryClient: () => ({ invalidateQueries: vi.fn() }),
- };
-});
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
-vi.mock("@multica/core/auth", () => ({
- useAuthStore: (sel: (s: { user: { id: string } }) => unknown) =>
- sel({ user: { id: "user-1" } }),
-}));
-vi.mock("@multica/core/paths", () => ({
- useWorkspacePaths: () => ({ runtimes: () => "/runtimes", agentDetail: () => "/agents" }),
-}));
-vi.mock("@multica/core/realtime", () => ({ useWSEvent: () => {} }));
-vi.mock("@multica/core/agents", () => ({
- agentTaskSnapshotOptions: () => ({ queryKey: ["tasks"] }),
-}));
-vi.mock("@multica/core/runtimes", () => ({
- runtimeProfileListOptions: () => ({ queryKey: ["profiles"] }),
- deriveRuntimeHealth: () => "online",
- runtimeDisplayName: () => "machine",
- isRuntimeUsableForUser: () => true,
- parseRuntimeProfileBoundConflict: () => null,
- useDeleteRuntimeProfile: () => ({ mutateAsync: vi.fn(), isPending: false }),
-}));
-vi.mock("@multica/core/runtimes/queries", () => ({
- runtimeListOptions: () => ({ queryKey: ["runtimes"] }),
- runtimeKeys: { list: () => ["runtimes"] },
-}));
-vi.mock("@multica/core/workspace/queries", () => ({
- agentListOptions: () => ({ queryKey: ["agents"] }),
- memberListOptions: () => ({ queryKey: ["members"] }),
-}));
-
-describe("RuntimeDetailPage loading state", () => {
- it("puts the loading header on the same rail as the loaded header", () => {
- const { container } = render(
- <I18nProvider
- locale="en"
- resources={{ en: { common: enCommon, runtimes: enRuntimes } }}
- >
- <RuntimeDetailPage runtimeId="rt-1" />
- </I18nProvider>,
- );
-
- const railed = container.querySelectorAll(`.${RAIL_SENTINEL}`);
- // Header band and body band; neither may be left on a bare gutter, or the
- // page shifts sideways when loading finishes.
- expect(railed.length).toBeGreaterThanOrEqual(2);
- expect(container.querySelector(".border-b")).toContainElement(
- container.querySelector(`.${RAIL_SENTINEL}`) as HTMLElement,
- );
- });
-});
diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
index 42e8d0da4e..0989552265 100644
--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx
@@ -3,15 +3,16 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { ComponentProps, ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
+import enLayout from "../../locales/en/layout.json";
import enRuntimes from "../../locales/en/runtimes.json";
import enAgents from "../../locales/en/agents.json";
const TEST_RESOURCES = {
- en: { common: enCommon, runtimes: enRuntimes, agents: enAgents },
+ en: { common: enCommon, layout: enLayout, runtimes: enRuntimes, agents: enAgents },
};
const mockUpdateRuntime = vi.hoisted(() => vi.fn());
@@ -145,14 +146,19 @@ vi.mock("./provider-logo", () => ({ ProviderLogo: () => null }));
vi.mock("./usage-section", () => ({
UsageSection: () => <div data-testid="usage-section" />,
}));
-vi.mock("./shared", () => ({ HealthBadge: () => null }));
+vi.mock("./shared", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./shared")>()),
+ HealthBadge: () => null,
+}));
vi.mock("../../agents/presence", () => ({
availabilityConfig: { offline: { dotClass: "", textClass: "" } },
workloadConfig: { idle: { icon: () => null, textClass: "" } },
}));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
vi.mock("../../navigation", () => ({
- AppLink: ({ children }: { children: ReactNode }) => <>{children}</>,
+ AppLink: ({ href, children }: { href: string; children: ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
useNavigation: () => ({ push: vi.fn(), replace: vi.fn() }),
}));
@@ -256,16 +262,35 @@ describe("RuntimeDetail visibility section", () => {
}),
);
- fireEvent.click(
- screen.getByRole("button", { name: "Technical details" }),
- );
-
+ expect(screen.getByText("Daemon CLI")).toBeInTheDocument();
expect(screen.getByText("0.3.17")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Update" }),
).not.toBeInTheDocument();
});
+ it("lays the runtime out as one header, body sections and a properties panel", () => {
+ renderDetail(
+ makeRuntime({ device_info: "host.local · 2.1.121 (Claude Code)" }),
+ { machineHref: "/runtimes/local:daemon-1", machineLabel: "Studio Mac" },
+ );
+
+ expect(screen.getAllByRole("banner")).toHaveLength(1);
+ expect(screen.getByRole("link", { name: "Runtimes" })).toHaveAttribute("href", "/runtimes");
+ expect(screen.getByRole("link", { name: "Studio Mac" })).toHaveAttribute(
+ "href",
+ "/runtimes/local:daemon-1",
+ );
+ expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 2, name: /Agents/ })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 2, name: "Usage" })).toBeInTheDocument();
+ expect(screen.getByText("No agents are bound to this runtime yet.")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Properties" })).toBeInTheDocument();
+ expect(screen.getByText("host.local")).toBeInTheDocument();
+ expect(screen.getByText("2.1.121 (Claude Code)")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Toggle right sidebar" })).toBeInTheDocument();
+ });
+
it("uses the provider name when the runtime alias is the machine name", () => {
renderDetail(
makeRuntime({
@@ -399,7 +424,7 @@ describe("RuntimeDetail visibility section", () => {
expect(screen.queryByText("Public")).not.toBeInTheDocument();
});
- it("hides usage from a workspace admin viewing another member's private runtime", () => {
+ it("hides usage from a workspace admin viewing another member's private runtime", async () => {
mockQueryData.members = [
{ user_id: "user-me", role: "admin" },
{ user_id: "someone-else", role: "member" },
@@ -410,9 +435,7 @@ describe("RuntimeDetail visibility section", () => {
);
expect(screen.queryByTestId("usage-section")).not.toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: /Delete runtime/i }),
- ).toBeInTheDocument();
+ expect(await openDeleteItem()).toBeInTheDocument();
});
it("shows usage to a workspace admin viewing another member's public runtime", () => {
@@ -441,9 +464,9 @@ describe("RuntimeDetail visibility section", () => {
// MUL-3352: an owner viewing an online local (self-healing) runtime
// used to see a disabled Delete button with only a hover tooltip
- // explaining why. The new contract: the button is always clickable
+ // explaining why. The new contract: the action is always clickable
// for owner/admin; the dialog now carries the self-heal warning.
- it("renders an enabled Delete runtime button for an owner on a self-healing local runtime", () => {
+ it("offers an enabled Delete runtime action for an owner on a self-healing local runtime", async () => {
renderDetail(
makeRuntime({
owner_id: "user-me",
@@ -451,13 +474,10 @@ describe("RuntimeDetail visibility section", () => {
status: "online",
}),
);
- const btn = screen.getByRole("button", {
- name: /Delete runtime/i,
- }) as HTMLButtonElement;
- expect(btn.disabled).toBe(false);
+ expect(await openDeleteItem()).not.toHaveAttribute("aria-disabled", "true");
});
- it("hides the Delete runtime button entirely for callers who cannot edit", () => {
+ it("hides the Delete runtime action entirely for callers who cannot edit", () => {
renderDetail(
makeRuntime({
owner_id: "someone-else",
@@ -466,8 +486,10 @@ describe("RuntimeDetail visibility section", () => {
}),
);
expect(
- screen.queryByRole("button", { name: /Delete runtime/i }),
+ within(screen.getByRole("banner")).queryByRole("button", { name: "More actions" }),
).not.toBeInTheDocument();
+ expect(screen.queryByText("Delete runtime")).not.toBeInTheDocument();
+ expect(screen.getByText("Read-only")).toBeInTheDocument();
});
it("routes custom runtime deletion through the profile delete dialog for admins", async () => {
@@ -484,9 +506,9 @@ describe("RuntimeDetail visibility section", () => {
}),
);
- fireEvent.click(screen.getByRole("button", { name: /Delete runtime/i }));
+ fireEvent.click(await openDeleteItem());
expect(
- screen.getByText("Delete custom runtime from workspace?"),
+ await screen.findByText("Delete custom runtime from workspace?"),
).toBeInTheDocument();
expect(
screen.getByRole("alertdialog", {
@@ -514,7 +536,14 @@ describe("RuntimeDetail visibility section", () => {
);
expect(
- screen.queryByRole("button", { name: /Delete runtime/i }),
+ within(screen.getByRole("banner")).queryByRole("button", { name: "More actions" }),
).not.toBeInTheDocument();
});
});
+
+async function openDeleteItem() {
+ fireEvent.click(
+ within(screen.getByRole("banner")).getByRole("button", { name: "More actions" }),
+ );
+ return screen.findByRole("menuitem", { name: /Delete runtime/i });
+}
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 914ccc6532..829d2f01ec 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -2,10 +2,10 @@
import { useEffect, useState } from "react";
import {
- Trash2,
ChevronRight,
- Cpu,
Lock,
+ MoreHorizontal,
+ Trash2,
} from "@multica/ui/icons";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
@@ -29,12 +29,27 @@ import {
useWorkspacePresenceMap,
} from "@multica/core/agents";
import { useWorkspacePaths } from "@multica/core/paths";
-import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "../../common/actor-avatar";
-import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectPanelSection,
+ ObjectProperty,
+ ObjectSection,
+ ObjectSectionCard,
+} from "../../layout/object-page";
import { AppLink, useNavigation } from "../../navigation";
import { availabilityConfig, workloadConfig } from "../../agents/presence";
-import { HealthBadge } from "./shared";
+import { HealthBadge, HealthIcon, shortDaemonId, useHealthLabel } from "./shared";
import { ProviderLogo } from "./provider-logo";
import { UsageSection } from "./usage-section";
import { DeleteRuntimeDialog } from "./delete-runtime-dialog";
@@ -55,12 +70,6 @@ function getCliVersion(metadata: Record<string, unknown>): string | null {
return null;
}
-function shortDaemonId(id: string | null): string | null {
- if (!id) return null;
- if (id.length <= 10) return id;
- return `${id.slice(0, 6)}··${id.slice(-2)}`;
-}
-
// 30s tick keeps derived runtime health honest as time-based windows
// (recently_lost → offline → long_offline) cross thresholds without any new
// query data arriving. Agent presence has no time windows anymore, so it
@@ -141,17 +150,21 @@ export function RuntimeDetail({
navigation.replace(deleteDestination);
};
- const daemonShort = shortDaemonId(runtime.daemon_id);
const lastSeen = runtime.last_seen_at
? timeAgo(runtime.last_seen_at)
: t(($) => $.detail.never_seen);
const runtimeName = machineLabel
? runtimeRowLabel(runtime, machineLabel)
: runtimeDisplayName(runtime);
+ const device = runtime.device_info ? parseDeviceInfo(runtime.device_info) : null;
+ const summary = [device?.runtime, t(($) => $.detail.last_seen, { when: lastSeen })]
+ .filter(Boolean)
+ .join(" · ");
return (
- <div className="flex h-full flex-col">
- <BreadcrumbHeader
+ <>
+ <ObjectPage
+ layoutId="multica_runtime_detail_layout"
segments={[
{ href: paths.runtimes(), label: t(($) => $.page.title) },
...(machineHref && machineLabel
@@ -159,56 +172,68 @@ export function RuntimeDetail({
: []),
]}
leaf={
- <span className="truncate font-mono text-caption text-foreground">
- {runtimeName}
+ <span className="flex min-w-0 items-center gap-1.5">
+ <ProviderLogo provider={runtime.provider} className="size-3.5 shrink-0" />
+ <span className="truncate">{runtimeName}</span>
</span>
}
actions={
- !canEditRuntime ? (
- <span className="inline-flex items-center gap-1 text-caption text-muted-foreground">
- <Lock className="h-3 w-3" />
- {t(($) => $.detail.read_only)}
- </span>
- ) : null
+ canDelete ? (
+ <RuntimeActionsMenu onDelete={() => setDeleteOpen(true)} />
+ ) : undefined
}
- />
-
- {/* Body — single scroll container that owns the Hero card AND the
- analytic blocks below. Putting Hero inside the scroll (instead of
- pinning it under the topbar) means the scroll bar starts at the
- page boundary rather than mid-content; the topbar stays sticky on
- its own because it's navigation, not data. */}
- <div className="flex-1 min-h-0 overflow-y-auto">
- <div className="grid grid-cols-1 gap-4 p-6 lg:grid-cols-[minmax(0,1fr)_320px]">
- <div className="min-w-0 space-y-5">
- <HeroCard
- runtime={runtime}
- runtimeName={runtimeName}
- health={health}
- lastSeen={lastSeen}
- ownerMember={ownerMember}
- cliVersion={cliVersion}
- daemonShort={daemonShort}
- />
- {canReadRuntime && <UsageSection runtime={runtime} />}
- </div>
+ panel={
+ <RuntimeProperties
+ runtime={runtime}
+ health={health}
+ lastSeen={lastSeen}
+ ownerMember={ownerMember}
+ device={device}
+ cliVersion={cliVersion}
+ canEditVisibility={!!isRuntimeOwner}
+ />
+ }
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <ObjectIdentity
+ media={
+ <div className="flex size-12 items-center justify-center rounded-xl border bg-muted/50">
+ <ProviderLogo provider={runtime.provider} className="size-6" />
+ </div>
+ }
+ title={runtimeName}
+ trailing={
+ <>
+ <HealthBadge health={health} />
+ {!canEditRuntime && (
+ <span className="inline-flex shrink-0 items-center gap-1 text-caption text-muted-foreground">
+ <Lock className="size-3" />
+ {t(($) => $.detail.read_only)}
+ </span>
+ )}
+ </>
+ }
+ description={summary}
+ />
- {/* Right rail: serving agents + diagnostics */}
- <div className="space-y-4">
- <ServingAgentsCard
+ <ObjectSection
+ title={t(($) => $.page.columns.agents)}
+ count={servingAgents.length}
+ >
+ <ServingAgentList
agents={servingAgents}
presenceMap={presenceMap}
agentHref={(id) => paths.agentDetail(id)}
/>
- <DiagnosticsCard
- runtime={runtime}
- canEditVisibility={!!isRuntimeOwner}
- canDelete={!!canDelete}
- onDelete={() => setDeleteOpen(true)}
- />
- </div>
+ </ObjectSection>
+
+ {canReadRuntime && (
+ <ObjectSection title={t(($) => $.detail.usage_title)}>
+ <UsageSection runtime={runtime} />
+ </ObjectSection>
+ )}
</div>
- </div>
+ </ObjectPage>
{isCustomRuntime && runtimeProfile ? (
<DeleteRuntimeProfileDialog
@@ -227,15 +252,15 @@ export function RuntimeDetail({
onDeleted={handleRuntimeDeleted}
/>
)}
- </div>
+ </>
);
}
// `device_info` arrives as a single composite string the daemon assembles
// (e.g. "host.local · 2.1.121 (Claude Code)"). Splitting on the first
// " · " gives us a hostname half + a runtime-version half so each can be
-// labelled separately in the Hero card. Older runtimes that report just a
-// hostname still work — `runtime` is undefined in that case.
+// labelled separately. Older runtimes that report just a hostname still
+// work — `runtime` is undefined in that case.
function parseDeviceInfo(raw: string): { hostname: string; runtime?: string } {
const idx = raw.indexOf(" · ");
if (idx < 0) return { hostname: raw };
@@ -245,146 +270,124 @@ function parseDeviceInfo(raw: string): { hostname: string; runtime?: string } {
};
}
-function HeroCard({
+function RuntimeActionsMenu({ onDelete }: { onDelete: () => void }) {
+ const { t } = useT("runtimes");
+ const { t: tCommon } = useT("common");
+ // Delete stays available even when the runtime is a live local daemon
+ // (self-healing, MUL-3352); the dialog explains the trade-off.
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={tCommon(($) => $.more_actions)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ >
+ <MoreHorizontal />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-auto">
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.detail.delete_button)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function RuntimeProperties({
runtime,
- runtimeName,
health,
lastSeen,
ownerMember,
+ device,
cliVersion,
- daemonShort,
+ canEditVisibility,
}: {
runtime: AgentRuntime;
- runtimeName: string;
health: ReturnType<typeof deriveRuntimeHealth>;
lastSeen: string;
ownerMember: MemberWithUser | null;
+ device: { hostname: string; runtime?: string } | null;
cliVersion: string | null;
- daemonShort: string | null;
+ /**
+ * Runtime owner only (MUL-6126). Sharing a machine with the workspace is
+ * the owner's call, so a workspace admin sees the read-only chip even
+ * though they may still rename or delete the runtime.
+ */
+ canEditVisibility: boolean;
}) {
const { t } = useT("runtimes");
- const [showDetails, setShowDetails] = useState(false);
- const device = runtime.device_info ? parseDeviceInfo(runtime.device_info) : null;
- const hasTechDetails = !!cliVersion || !!daemonShort;
+ const { t: tLayout } = useT("layout");
+ const healthLabel = useHealthLabel();
+ const daemonShort = shortDaemonId(runtime.daemon_id);
return (
- <div className="rounded-lg border bg-card">
- {/* Identity row — provider logo, name, status badge, last seen. */}
- <div className="flex items-start gap-3 border-b p-4">
- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border bg-card">
- <ProviderLogo provider={runtime.provider} className="h-5 w-5" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
- <h2 className="truncate text-title-sm font-semibold tracking-tight">
- {runtimeName}
- </h2>
- <HealthBadge health={health} />
- <span className="text-caption text-muted-foreground">
- {t(($) => $.detail.last_seen, { when: lastSeen })}
- </span>
- </div>
- </div>
- </div>
-
- {/* User-visible facts — Owner / Device / Runtime, each labelled.
- Replaces the older dense `·`-separated meta strip that mixed
- everything (including dev-only IDs) at the same visual weight. */}
- <dl className="grid grid-cols-1 divide-y sm:grid-cols-3 sm:divide-x sm:divide-y-0">
- <Fact label={t(($) => $.detail.fact_owner)}>
+ <div className="space-y-5">
+ <ObjectPanelSection title={tLayout(($) => $.object_page.properties)}>
+ <ObjectProperty label={t(($) => $.page.columns.status)}>
+ <HealthIcon health={health} />
+ <span className="truncate">
+ {health === "online" ? healthLabel(health) : `${healthLabel(health)} · ${lastSeen}`}
+ </span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.fact_owner)}>
{ownerMember ? (
- <span className="inline-flex min-w-0 items-center gap-1.5">
+ <>
<ActorAvatar
actorType="member"
actorId={ownerMember.user_id}
- size="sm"
+ size="xs"
enableHoverCard
/>
- <span className="cursor-pointer truncate text-body">{ownerMember.name}</span>
- </span>
+ <span className="truncate">{ownerMember.name}</span>
+ </>
) : (
- <span className="text-body text-muted-foreground">—</span>
+ <span className="text-muted-foreground">—</span>
)}
- </Fact>
- <Fact label={t(($) => $.detail.fact_device)}>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.fact_device)}>
{device?.hostname ? (
<TruncatedTooltip content={device.hostname}>
- <span className="block truncate font-mono text-caption">
- {device.hostname}
- </span>
+ <span className="block truncate font-mono">{device.hostname}</span>
</TruncatedTooltip>
) : (
- <span className="text-body text-muted-foreground">—</span>
+ <span className="text-muted-foreground">—</span>
)}
- </Fact>
- <Fact label={t(($) => $.detail.fact_runtime)}>
- <span className="block truncate text-body">
- {device?.runtime ?? (
- <span className="capitalize">{runtime.provider}</span>
- )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.fact_runtime)}>
+ <span className="truncate">
+ {device?.runtime ?? <span className="capitalize">{runtime.provider}</span>}
</span>
- </Fact>
- </dl>
-
- {/* Diagnostic IDs — multica CLI git hash + truncated daemon UUID.
- Only useful when filing an issue or reading logs; folded by
- default so they don't compete with the user-visible facts above. */}
- {hasTechDetails && (
- <div className="border-t">
- <button
- type="button"
- onClick={() => setShowDetails((v) => !v)}
- className="flex w-full items-center gap-1 px-4 py-2 text-caption text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
- >
- <ChevronRight
- className={`h-3 w-3 transition-transform ${
- showDetails ? "rotate-90" : ""
- }`}
- />
- {t(($) => $.detail.technical_details)}
- </button>
- {showDetails && (
- <dl className="grid grid-cols-1 gap-y-2 border-t bg-muted/30 px-4 py-3 sm:grid-cols-2">
- {cliVersion && (
- <Fact label={t(($) => $.detail.fact_daemon_cli)} mono compact>
- {cliVersion}
- </Fact>
- )}
- {daemonShort && (
- <Fact label={t(($) => $.detail.fact_daemon_id)} mono compact>
- {daemonShort}
- </Fact>
- )}
- </dl>
+ </ObjectProperty>
+ {cliVersion && (
+ <ObjectProperty label={t(($) => $.detail.fact_daemon_cli)}>
+ <span className="truncate font-mono">{cliVersion}</span>
+ </ObjectProperty>
+ )}
+ {daemonShort && (
+ <ObjectProperty label={t(($) => $.detail.fact_daemon_id)}>
+ <span className="truncate font-mono">{daemonShort}</span>
+ </ObjectProperty>
+ )}
+ </ObjectPanelSection>
+ <ObjectPanelSection title={t(($) => $.detail.diagnostics_visibility)}>
+ <div className="pr-0.5 pt-1">
+ {canEditVisibility ? (
+ <RuntimeAccessEditor runtime={runtime} />
+ ) : (
+ <RuntimeAccessReadout runtime={runtime} />
)}
</div>
- )}
+ </ObjectPanelSection>
</div>
);
}
-function Fact({
- label,
- children,
- mono,
- compact,
-}: {
- label: string;
- children: React.ReactNode;
- mono?: boolean;
- compact?: boolean;
-}) {
- return (
- <div className={`min-w-0 ${compact ? "" : "px-4 py-3"}`}>
- <dt className="text-micro uppercase tracking-wider text-muted-foreground">
- {label}
- </dt>
- <dd className={`mt-1 ${mono ? "font-mono text-caption" : ""}`}>{children}</dd>
- </div>
- );
-}
-
-export function ServingAgentsCard({
+export function ServingAgentList({
agents,
presenceMap,
agentHref,
@@ -395,129 +398,59 @@ export function ServingAgentsCard({
}) {
const { t } = useT("runtimes");
const { t: tAgents } = useT("agents");
+ if (agents.length === 0) {
+ return (
+ <p className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">
+ {t(($) => $.detail.no_agents)}
+ </p>
+ );
+ }
return (
- <div className="rounded-lg border">
- <div className="flex items-center justify-between border-b px-4 py-2.5">
- <span className="text-caption font-semibold">{t(($) => $.detail.serving_title)}</span>
- <span className="text-caption text-muted-foreground">
- {t(($) => $.detail.serving_count, { count: agents.length })}
- </span>
- </div>
- {agents.length === 0 ? (
- <div className="flex flex-col items-center px-4 py-6 text-center">
- <Cpu className="h-5 w-5 text-faint-foreground" />
- <p className="mt-2 text-caption text-muted-foreground">
- {t(($) => $.detail.no_agents)}
- </p>
- </div>
- ) : (
- <div className="divide-y">
- {agents.map((agent) => {
- const detail = presenceMap.get(agent.id);
- const av = detail
- ? availabilityConfig[detail.availability]
- : availabilityConfig.offline;
- const avLabel = tAgents(($) => $.availability[detail?.availability ?? "offline"]);
- const wl = detail ? workloadConfig[detail.workload] : null;
- const running = detail?.runningCount ?? 0;
- const queued = detail?.queuedCount ?? 0;
- return (
- <AppLink
- key={agent.id}
- href={agentHref(agent.id)}
- className="group flex items-center gap-2 px-4 py-2 transition-colors hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none"
- >
- <ActorAvatar actorType="agent" actorId={agent.id} size="sm" enableHoverCard showStatusDot />
- <div className="min-w-0 flex-1">
- <div className="truncate text-caption font-medium">
- {agent.name}
- </div>
- <div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-caption">
- <span className="inline-flex items-center gap-1.5">
- <span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} />
- <span className={av.textClass}>{avLabel}</span>
- </span>
- {wl && detail && detail.workload !== "idle" && (
- <span className={`inline-flex items-center gap-1 ${wl.textClass}`}>
- <span className="text-muted-foreground">·</span>
- <wl.icon
- className={`h-3 w-3 ${detail.workload === "working" ? "animate-spin" : ""}`}
- />
- {tAgents(($) => $.workload[detail.workload])}
- {running > 0 && (
- <span className="text-muted-foreground">{t(($) => $.detail.running_chip, { count: running })}</span>
- )}
- {queued > 0 && (
- <span className="text-muted-foreground">{t(($) => $.detail.queued_chip, { count: queued })}</span>
- )}
- </span>
- )}
- </div>
- </div>
- <ChevronRight className="h-3.5 w-3.5 shrink-0 text-faint-foreground transition-colors group-hover:text-muted-foreground" />
- </AppLink>
- );
- })}
- </div>
- )}
- </div>
- );
-}
-
-function DiagnosticsCard({
- runtime,
- canEditVisibility,
- canDelete,
- onDelete,
-}: {
- runtime: AgentRuntime;
- /**
- * Runtime owner only — narrower than the card's other affordances on
- * purpose (MUL-6126). Sharing a machine with the workspace is the owner's
- * call, so a workspace admin sees the read-only chip here even though they
- * may still rename or delete the runtime.
- */
- canEditVisibility: boolean;
- canDelete: boolean;
- onDelete: () => void;
-}) {
- const { t } = useT("runtimes");
- return (
- <div className="rounded-lg border">
- <div className="border-b px-4 py-2.5">
- <span className="text-caption font-semibold">{t(($) => $.detail.diagnostics_title)}</span>
- </div>
- <div className="space-y-3 p-4">
- <div>
- <div className="mb-1.5 text-micro uppercase tracking-wide text-muted-foreground">
- {t(($) => $.detail.diagnostics_visibility)}
- </div>
- {canEditVisibility ? (
- <RuntimeAccessEditor runtime={runtime} />
- ) : (
- <RuntimeAccessReadout runtime={runtime} />
- )}
- </div>
- {canDelete && (
- // The button stays clickable even when the runtime is a live
- // local daemon (self-healing). The owner explicitly asked for
- // it (MUL-3352) — disabling here left them looking at a button
- // they had every permission to click but couldn't. The dialog
- // raises a self-heal banner so the user sees the trade-off
- // before confirming.
- <div className="border-t pt-3">
- <Button
- variant="ghost"
- size="sm"
- className="h-8 w-full justify-start gap-2 text-destructive hover:bg-destructive/10 hover:text-destructive"
- onClick={onDelete}
- >
- <Trash2 className="h-3.5 w-3.5" />
- {t(($) => $.detail.delete_button)}
- </Button>
- </div>
- )}
- </div>
- </div>
+ <ObjectSectionCard>
+ {agents.map((agent) => {
+ const detail = presenceMap.get(agent.id);
+ const av = detail
+ ? availabilityConfig[detail.availability]
+ : availabilityConfig.offline;
+ const avLabel = tAgents(($) => $.availability[detail?.availability ?? "offline"]);
+ const wl = detail ? workloadConfig[detail.workload] : null;
+ const running = detail?.runningCount ?? 0;
+ const queued = detail?.queuedCount ?? 0;
+ return (
+ <AppLink
+ key={agent.id}
+ href={agentHref(agent.id)}
+ className="group flex items-center gap-2.5 px-3 py-2 transition-colors hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none"
+ >
+ <ActorAvatar actorType="agent" actorId={agent.id} size="sm" enableHoverCard showStatusDot />
+ <span className="min-w-0 flex-1 truncate text-body font-medium">
+ {agent.name}
+ </span>
+ <span className="flex shrink-0 items-center gap-x-1.5 text-caption">
+ <span className="inline-flex items-center gap-1.5">
+ <span className={`h-1.5 w-1.5 rounded-full ${av.dotClass}`} />
+ <span className={av.textClass}>{avLabel}</span>
+ </span>
+ {wl && detail && detail.workload !== "idle" && (
+ <span className={`inline-flex items-center gap-1 ${wl.textClass}`}>
+ <span className="text-muted-foreground">·</span>
+ <wl.icon
+ className={`h-3 w-3 ${detail.workload === "working" ? "animate-spin" : ""}`}
+ />
+ {tAgents(($) => $.workload[detail.workload])}
+ {running > 0 && (
+ <span className="text-muted-foreground">{t(($) => $.detail.running_chip, { count: running })}</span>
+ )}
+ {queued > 0 && (
+ <span className="text-muted-foreground">{t(($) => $.detail.queued_chip, { count: queued })}</span>
+ )}
+ </span>
+ )}
+ </span>
+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-faint-foreground transition-colors group-hover:text-muted-foreground" />
+ </AppLink>
+ );
+ })}
+ </ObjectSectionCard>
);
}
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index 43d647b308..c6219a941b 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -7,7 +7,6 @@ import {
Globe,
Users,
Loader2,
- MoreHorizontal,
Pencil,
Trash2,
} from "@multica/ui/icons";
@@ -36,25 +35,22 @@ import {
} from "@multica/core/runtimes";
import { useWorkspacePaths } from "@multica/core/paths";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
- DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- ListGrid,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
-} from "@multica/ui/components/ui/list-grid";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
-import { useIntentNavigate, useRowLink } from "../../navigation";
+import { useIntentNavigate } from "../../navigation";
+import {
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ CollectionRowMenu,
+ type CollectionColumn,
+} from "../../layout/collection-list";
import { ActorAvatar } from "../../common/actor-avatar";
import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { ProviderLogo } from "./provider-logo";
@@ -75,62 +71,11 @@ import {
pendingRuntimeCommandName,
} from "./pending-runtime";
import { useT, useTimeAgo } from "../../i18n";
-import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";
-// The machine detail's runtimes table on the shared ListGrid. Paradigm
-// pieces are taken À LA CARTE here: subgrid template + var-width tracks +
-// two-zone responsiveness (the detail pane gets squeezed by the machine
-// list, so the container-driven core-set collapse matters more than on the
-// full-width pages), but NO virtualization / sorting / filters / column
-// toggles / batch selection — a machine hosts 1-5 runtimes, those would all
-// be dead weight, and batch-deleting runtimes (a cascade-confirm heavy
-// operation) is deliberately not offered.
-const GRID_COLS =
- "grid-cols-[0.75rem_minmax(120px,1fr)_var(--rtc-health)_var(--rtc-kebab)_0.75rem] " +
- "@2xl:grid-cols-[0.75rem_minmax(140px,1fr)_var(--rtc-health)_var(--rtc-owner)_var(--rtc-agents)_var(--rtc-cost)_var(--rtc-cli)_var(--rtc-kebab)_0.75rem]";
-
-const COLUMN_WIDTHS = {
- // Health folds the workload in as a suffix ("Healthy · 2 running") —
- // same merge as the agents list's status cell.
- health: 176,
- owner: 96,
- agents: 92,
- cost: 96,
- cli: 112,
-} as const;
-
-// Fixed tracks (edges 12+12, name min 140) plus the 8 gap-x-3 gaps
-// between the wide template's 9 tracks (zero-width tracks still carry
-// gaps).
-const FIXED_TRACKS_WIDTH = 164 + 8 * 12;
-
-// The kebab track is conditional like the owner column: on a list where
-// no row carries a delete-permission, EVERY row's only action is hidden,
-// and an unconditionally reserved 28px action track would hang a
-// permanent dead zone off the last column.
-function columnTrackVars(
- showOwner: boolean,
- showActions: boolean,
-): React.CSSProperties {
- const minWidth =
- FIXED_TRACKS_WIDTH +
- COLUMN_WIDTHS.health +
- (showOwner ? COLUMN_WIDTHS.owner : 0) +
- COLUMN_WIDTHS.agents +
- COLUMN_WIDTHS.cost +
- COLUMN_WIDTHS.cli +
- (showActions ? 28 : 0);
- return {
- "--rtc-health": `${COLUMN_WIDTHS.health}px`,
- "--rtc-owner": showOwner ? `${COLUMN_WIDTHS.owner}px` : "0px",
- "--rtc-agents": `${COLUMN_WIDTHS.agents}px`,
- "--rtc-cost": `${COLUMN_WIDTHS.cost}px`,
- "--rtc-cli": `${COLUMN_WIDTHS.cli}px`,
- "--rtc-kebab": showActions ? "1.75rem" : "0px",
- "--rtc-minw": `${minWidth}px`,
- } as React.CSSProperties;
-}
+// The machine detail's runtimes table. A machine hosts 1-5 runtimes, so no
+// sorting, filters, column toggles or batch selection — and batch-deleting
+// runtimes (a cascade-confirm heavy operation) is deliberately not offered.
interface RuntimeWorkload {
agentIds: string[];
@@ -203,21 +148,18 @@ function RuntimeNameCell({
*/
machineTitle?: string;
}) {
- const label = runtimeRowLabel(runtime, machineTitle ?? "");
return (
- <ListGridCell className="gap-2">
- <div className="flex h-8 w-8 shrink-0 items-center justify-center">
- <ProviderLogo provider={runtime.provider} className="h-5 w-5" />
- </div>
- <div className="flex min-w-0 flex-1 items-center gap-1.5">
- <span className="block min-w-0 shrink truncate text-body font-medium">
- {label}
- </span>
- <RuntimeKindBadge runtime={runtime} />
- <PendingRuntimeBadge runtime={runtime} />
- <VisibilityBadge runtime={runtime} />
- </div>
- </ListGridCell>
+ <CollectionNameCell
+ icon={<ProviderLogo provider={runtime.provider} className="size-4 shrink-0" />}
+ title={runtimeRowLabel(runtime, machineTitle ?? "")}
+ badges={
+ <>
+ <RuntimeKindBadge runtime={runtime} />
+ <PendingRuntimeBadge runtime={runtime} />
+ <VisibilityBadge runtime={runtime} />
+ </>
+ }
+ />
);
}
@@ -305,43 +247,34 @@ function HealthCell({
const labelOf = useHealthLabel();
const timeAgo = useTimeAgo();
if (isDisabledCustomRuntime(runtime)) {
- return (
- <ListGridCell>
- <span className="text-caption text-muted-foreground">
- {t(($) => $.list.pending_health_disabled)}
- </span>
- </ListGridCell>
- );
+ return <span className="truncate">{t(($) => $.list.pending_health_disabled)}</span>;
}
const registrationFailure = customRuntimeRegistrationFailure(runtime);
if (registrationFailure) {
return (
- <ListGridCell className="gap-1.5">
- <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-destructive" />
- <span
- className="block min-w-0 truncate text-caption text-destructive"
- title={registrationFailure}
- >
+ <>
+ <AlertTriangle className="size-3.5 shrink-0 text-destructive" />
+ <span className="min-w-0 truncate text-destructive" title={registrationFailure}>
{t(($) => $.list.pending_health_error)}
</span>
- </ListGridCell>
+ </>
);
}
if (isPendingCustomRuntime(runtime)) {
const warning = isPendingCustomRuntimeWarning(runtime, now);
return (
- <ListGridCell className="gap-1.5">
+ <>
{warning ? (
- <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-warning" />
+ <AlertTriangle className="size-3.5 shrink-0 text-warning" />
) : (
- <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-info" />
+ <Loader2 className="size-3.5 shrink-0 animate-spin text-info" />
)}
- <span className="block min-w-0 truncate text-caption">
+ <span className="min-w-0 truncate text-foreground">
{warning
? t(($) => $.list.pending_health_warning)
: t(($) => $.list.pending_health)}
</span>
- </ListGridCell>
+ </>
);
}
@@ -351,21 +284,19 @@ function HealthCell({
const active = workload.runningCount + workload.queuedCount;
return (
- <ListGridCell className="gap-1.5">
+ <>
<HealthIcon health={health} />
- <span className="block min-w-0 truncate text-caption">
- {labelOf(health)}
- {health !== "online" && lastSeen && (
- <span className="text-muted-foreground"> · {lastSeen}</span>
- )}
+ <span className="min-w-0 truncate">
+ <span className="text-foreground">{labelOf(health)}</span>
+ {health !== "online" && lastSeen && <> · {lastSeen}</>}
{!offline && active > 0 && (
- <span className="text-muted-foreground">
+ <>
{" · "}
{tAgents(($) => $.row.task_count, { count: active })}
- </span>
+ </>
)}
</span>
- </ListGridCell>
+ </>
);
}
@@ -407,13 +338,7 @@ export function CostCell({
);
const delta = pctChange(cost7d, costPrev7d);
- if (usage.length === 0) {
- return (
- <div className="w-full text-right">
- <span className="text-caption text-faint-foreground">—</span>
- </div>
- );
- }
+ if (usage.length === 0) return <CollectionEmptyValue />;
const fmt = cost7d >= 100 ? `$${cost7d.toFixed(0)}` : `$${cost7d.toFixed(2)}`;
const deltaTone =
delta == null
@@ -430,19 +355,19 @@ export function CostCell({
? t(($) => $.list.cost_delta_flat)
: `${delta > 0 ? "↑" : "↓"}${Math.abs(delta)}%`;
return (
- <div className="flex w-full flex-col items-end leading-tight">
+ <span className="flex items-baseline gap-1.5">
<CurrencyNumberFlow
value={cost7d}
locales={locales}
aria-label={fmt}
- className="text-body font-medium"
+ className="text-caption font-medium text-foreground"
/>
{deltaLabel && (
<span className={`text-micro tabular-nums ${deltaTone}`}>
{deltaLabel}
</span>
)}
- </div>
+ </span>
);
}
@@ -452,49 +377,24 @@ export function CliCell({ runtime }: { runtime: AgentRuntime }) {
if (failure) {
const command = pendingRuntimeCommandName(runtime);
return (
- <div className="flex min-w-0 flex-col text-caption">
- {command && (
- <TruncatedTooltip content={command}>
- <span
- className="truncate font-mono text-muted-foreground"
- >
- {command}
- </span>
- </TruncatedTooltip>
- )}
- <TruncatedTooltip content={failure}>
- <span className="truncate text-destructive">
- {failure}
- </span>
- </TruncatedTooltip>
- </div>
+ <TruncatedTooltip content={command ? `${command}: ${failure}` : failure}>
+ <span className="truncate text-destructive">{failure}</span>
+ </TruncatedTooltip>
);
}
if (isPendingCustomRuntime(runtime)) {
const command = pendingRuntimeCommandName(runtime);
if (!command) {
- return (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.list.pending_cli_unknown)}
- </span>
- );
+ return <span className="truncate">{t(($) => $.list.pending_cli_unknown)}</span>;
}
return (
- <div className="flex min-w-0 items-center text-caption">
- <TruncatedTooltip content={command}>
- <span
- className="truncate font-mono text-muted-foreground"
- >
- {command}
- </span>
- </TruncatedTooltip>
- </div>
+ <TruncatedTooltip content={command}>
+ <span className="truncate font-mono">{command}</span>
+ </TruncatedTooltip>
);
}
- if (runtime.runtime_mode === "cloud") {
- return <span className="text-caption text-faint-foreground">—</span>;
- }
+ if (runtime.runtime_mode === "cloud") return <CollectionEmptyValue />;
const meta = runtime.metadata as Record<string, unknown> | null;
// `version` is the agent's own underlying CLI tool version — distinct per
// provider (e.g. "2.1.5 (Claude Code)", "codex-cli 0.118.0", "0.42.0").
@@ -506,26 +406,16 @@ export function CliCell({ runtime }: { runtime: AgentRuntime }) {
const version =
meta && typeof meta.version === "string" ? meta.version : null;
- if (!version) {
- return <span className="text-caption text-faint-foreground">—</span>;
- }
+ if (!version) return <CollectionEmptyValue />;
- return (
- <div className="flex min-w-0 items-center text-caption">
- <span className="truncate font-mono text-muted-foreground">
- {version}
- </span>
- </div>
- );
+ return <span className="truncate font-mono">{version}</span>;
}
// Stacks up to 3 agent avatars, then a "+N" pill if more bind to this
// runtime. Each avatar uses the wrapping ActorAvatar so hover automatically
// surfaces AgentProfileCard.
function AgentStack({ agentIds }: { agentIds: string[] }) {
- if (agentIds.length === 0) {
- return <span className="text-caption text-faint-foreground">—</span>;
- }
+ if (agentIds.length === 0) return <CollectionEmptyValue />;
const visible = agentIds.slice(0, 3);
const extra = agentIds.length - visible.length;
return (
@@ -538,13 +428,13 @@ function AgentStack({ agentIds }: { agentIds: string[] }) {
<ActorAvatar
actorType="agent"
actorId={id}
- size="md"
+ size="sm"
enableHoverCard
/>
</span>
))}
{extra > 0 && (
- <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-caption font-medium text-muted-foreground ring-2 ring-background">
+ <span className="inline-flex size-5 items-center justify-center rounded-full bg-muted text-micro font-medium text-muted-foreground ring-2 ring-background">
+{extra}
</span>
)}
@@ -583,59 +473,39 @@ export function RuntimeRowMenu({
// would undo this". The dialog now carries the self-heal warning and
// the user gets to decide.
- if (!canDelete) {
- return <span aria-hidden />;
- }
+ if (!canDelete) return null;
return (
<>
- <DropdownMenu>
- <DeferredTooltip
- content={t(($) => $.list.row_actions_aria)}
- trigger={
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- aria-label={t(($) => $.list.row_actions_aria)}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"
- >
- <MoreHorizontal className="size-4" />
- </button>
- }
- />
- }
- />
- <DropdownMenuContent align="end" className="w-40">
- {detailHref && (
- <>
- <DropdownMenuItem
- onClick={() => intentNavigate(detailHref, "foreground-tab")}
- >
- <ExternalLink aria-hidden="true" className="h-3.5 w-3.5" />
- {tCommon(($) => $.navigation.open_in_new_tab)}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- </>
- )}
- {isCustomRuntime && profile && (
- <DropdownMenuItem onClick={() => setEditOpen(true)}>
- <Pencil aria-hidden="true" className="h-3.5 w-3.5" />
- {t(($) => $.list.edit_action)}
+ <CollectionRowMenu label={t(($) => $.list.row_actions_aria)} contentClassName="w-40">
+ {detailHref && (
+ <>
+ <DropdownMenuItem
+ onClick={() => intentNavigate(detailHref, "foreground-tab")}
+ >
+ <ExternalLink aria-hidden="true" className="h-3.5 w-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
</DropdownMenuItem>
- )}
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleteOpen(true)}
- title={t(($) => $.list.delete_permission_hint)}
- >
- <Trash2 aria-hidden="true" className="h-3.5 w-3.5" />
- {isCustomRuntime
- ? t(($) => $.list.delete_profile_action)
- : t(($) => $.list.delete_action)}
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {isCustomRuntime && profile && (
+ <DropdownMenuItem onClick={() => setEditOpen(true)}>
+ <Pencil aria-hidden="true" className="h-3.5 w-3.5" />
+ {t(($) => $.list.edit_action)}
</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ )}
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteOpen(true)}
+ title={t(($) => $.list.delete_permission_hint)}
+ >
+ <Trash2 aria-hidden="true" className="h-3.5 w-3.5" />
+ {isCustomRuntime
+ ? t(($) => $.list.delete_profile_action)
+ : t(($) => $.list.delete_action)}
+ </DropdownMenuItem>
+ </CollectionRowMenu>
{isCustomRuntime && profile && editOpen && (
<RuntimeProfilesDialog
wsId={wsId}
@@ -690,7 +560,6 @@ export function RuntimeList({
const { t } = useT("runtimes");
const wsId = useWorkspaceId();
const wsPaths = useWorkspacePaths();
- const rowLink = useRowLink();
const user = useAuthStore((s) => s.user);
const { data: agents = [] } = useQuery(agentListOptions(wsId));
@@ -754,113 +623,96 @@ export function RuntimeList({
});
}, [runtimes, profileById, memberById, workloadIndex, isAdmin, user]);
- // Mirrors RuntimeRowMenu's render guard: the kebab track only earns its
- // width when at least one row will actually show the menu.
- const showActions = rows.some((row) => row.canDelete);
+ const columns: CollectionColumn<RuntimeRow>[] = [
+ {
+ key: "name",
+ header: t(($) => $.list.col_runtime),
+ cell: (row) => <RuntimeNameCell runtime={row.runtime} machineTitle={machineTitle} />,
+ },
+ {
+ // Health folds the workload in as a suffix ("Healthy · 2 tasks") —
+ // same merge as the agents list's status cell.
+ key: "health",
+ header: t(($) => $.list.col_health),
+ width: 176,
+ core: true,
+ cell: (row) => <HealthCell runtime={row.runtime} workload={row.workload} now={now} />,
+ },
+ // Owner only earns its space when the list has more than one owner.
+ ...(showOwner
+ ? [
+ {
+ key: "owner",
+ header: t(($) => $.list.col_owner),
+ width: 120,
+ cell: (row: RuntimeRow) =>
+ row.ownerMember ? (
+ <>
+ <ActorAvatar actorType="member" actorId={row.ownerMember.user_id} size="sm" />
+ <span className="min-w-0 truncate">{row.ownerMember.name}</span>
+ </>
+ ) : (
+ <CollectionEmptyValue />
+ ),
+ },
+ ]
+ : []),
+ {
+ key: "agents",
+ header: t(($) => $.list.col_agents),
+ width: 92,
+ cell: (row) => <AgentStack agentIds={row.workload.agentIds} />,
+ },
+ {
+ key: "cost",
+ header: t(($) => $.list.col_cost),
+ width: 96,
+ align: "end",
+ cell: (row) =>
+ isPendingCustomRuntime(row.runtime) ? (
+ <CollectionEmptyValue />
+ ) : (
+ <CostCell
+ runtimeId={row.runtime.id}
+ enabled={canReadRuntimeUsage(row.runtime, user?.id ?? null)}
+ />
+ ),
+ },
+ {
+ key: "cli",
+ header: t(($) => $.list.col_cli),
+ width: 112,
+ cell: (row) => <CliCell runtime={row.runtime} />,
+ },
+ ];
+
+ const detailHrefOf = (row: RuntimeRow) =>
+ isPendingCustomRuntime(row.runtime)
+ ? undefined
+ : (runtimeHref?.(row.runtime.id) ?? wsPaths.runtimeDetail(row.runtime.id));
return (
- <div className="overflow-x-auto overflow-y-hidden @container">
- <ListGrid
- className={`${GRID_COLS} @2xl:min-w-[var(--rtc-minw)]`}
- style={columnTrackVars(showOwner, showActions)}
- >
- <ListGridHeader>
- <ListGridHeaderCell>
- {t(($) => $.list.col_runtime)}
- </ListGridHeaderCell>
- <ListGridHeaderCell>{t(($) => $.list.col_health)}</ListGridHeaderCell>
- {showOwner ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.list.col_owner)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.list.col_agents)}
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex" align="right">
- {t(($) => $.list.col_cost)}
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.list.col_cli)}
- </ListGridHeaderCell>
- <span aria-hidden="true" />
- </ListGridHeader>
- {rows.map((row) => {
- const pending = isPendingCustomRuntime(row.runtime);
- const detailHref = pending
- ? undefined
- : runtimeHref?.(row.runtime.id) ??
- wsPaths.runtimeDetail(row.runtime.id);
- return (
- <ListGridRow
- key={row.runtime.id}
- className={pending ? "cursor-default" : "cursor-pointer"}
- {...(detailHref ? rowLink(detailHref) : {})}
- >
- <RuntimeNameCell runtime={row.runtime} machineTitle={machineTitle} />
- <HealthCell
+ <CollectionList
+ embedded
+ label={t(($) => $.list.col_runtime)}
+ columns={columns}
+ rows={rows}
+ getRowId={(row) => row.runtime.id}
+ getRowHref={detailHrefOf}
+ // The ⋯ slot only earns its width when some row can show the menu.
+ rowMenu={
+ rows.some((row) => row.canDelete)
+ ? (row) => (
+ <RuntimeRowMenu
runtime={row.runtime}
- workload={row.workload}
- now={now}
+ profile={row.profile}
+ wsId={wsId}
+ canDelete={row.canDelete}
+ detailHref={detailHrefOf(row)}
/>
- {showOwner ? (
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
- {row.ownerMember ? (
- <>
- <ActorAvatar
- actorType="member"
- actorId={row.ownerMember.user_id}
- size="sm"
- />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {row.ownerMember.name}
- </span>
- </>
- ) : (
- <span className="text-caption text-faint-foreground">—</span>
- )}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- <ListGridCell className="hidden @2xl:flex">
- <AgentStack agentIds={row.workload.agentIds} />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- {pending ? (
- <div className="w-full text-right">
- <span className="text-caption text-faint-foreground">—</span>
- </div>
- ) : (
- <CostCell
- runtimeId={row.runtime.id}
- enabled={canReadRuntimeUsage(row.runtime, user?.id ?? null)}
- />
- )}
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <CliCell runtime={row.runtime} />
- </ListGridCell>
- <ListGridCell className="justify-end px-0">
- <span
- onClick={(e) => e.stopPropagation()}
- className="flex items-center"
- >
- <RuntimeRowMenu
- runtime={row.runtime}
- profile={row.profile}
- wsId={wsId}
- canDelete={row.canDelete}
- detailHref={detailHref}
- />
- </span>
- </ListGridCell>
- </ListGridRow>
- );
- })}
- </ListGrid>
- </div>
+ )
+ : undefined
+ }
+ />
);
}
diff --git a/packages/views/runtimes/components/runtime-row-menu.test.tsx b/packages/views/runtimes/components/runtime-row-menu.test.tsx
index d4f7acb71c..1c35066957 100644
--- a/packages/views/runtimes/components/runtime-row-menu.test.tsx
+++ b/packages/views/runtimes/components/runtime-row-menu.test.tsx
@@ -162,8 +162,8 @@ function makeAdapter(
};
}
-// The row menu is a plain exported component on the ListGrid version of the
-// list — render it directly with the row fields it reads.
+// The row menu is a plain exported component — render it directly with the
+// row fields it reads.
function renderActionsCell(
row: RuntimeRow,
options: { detailHref?: string; adapter?: NavigationAdapter } = {},
diff --git a/packages/views/runtimes/components/runtime-settings-page.tsx b/packages/views/runtimes/components/runtime-settings-page.tsx
index 81dbde91c6..95b31f33d2 100644
--- a/packages/views/runtimes/components/runtime-settings-page.tsx
+++ b/packages/views/runtimes/components/runtime-settings-page.tsx
@@ -7,6 +7,9 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { runtimeListOptions } from "@multica/core/runtimes/queries";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { cn } from "@multica/ui/lib/utils";
+import { CollectionPageState } from "../../layout/collection-page";
+import { OBJECT_PAGE_BODY, ObjectPage } from "../../layout/object-page";
import { RuntimeDetail } from "./runtime-detail";
import { buildRuntimeMachines } from "./runtime-machines";
import { QoderDetailPage } from "./qoder-detail-page";
@@ -26,17 +29,26 @@ export function RuntimeSettingsPage({
const decodedMachineId = decodeRouteParam(machineId);
const decodedRuntimeId = decodeRouteParam(runtimeId);
+ const segments = [{ href: paths.runtimes(), label: t(($) => $.page.title) }];
+
if (isLoading) {
return (
- <div className="flex h-full flex-col p-6">
- <Skeleton className="h-12 w-1/2" />
- <div className="mt-6 grid grid-cols-3 gap-3">
- <Skeleton className="h-20 rounded-lg" />
- <Skeleton className="h-20 rounded-lg" />
- <Skeleton className="h-20 rounded-lg" />
+ <ObjectPage
+ layoutId="multica_runtime_detail_layout"
+ segments={segments}
+ leaf={<Skeleton className="h-4 w-40" />}
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-xl" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-5 w-56" />
+ <Skeleton className="h-4 w-40" />
+ </div>
+ </div>
+ <Skeleton className="h-48 w-full rounded-lg" />
</div>
- <Skeleton className="mt-4 h-48 w-full rounded-lg" />
- </div>
+ </ObjectPage>
);
}
@@ -47,16 +59,21 @@ export function RuntimeSettingsPage({
);
if (!target) {
return (
- <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
- <Server
- aria-hidden="true"
- className="h-10 w-10 text-faint-foreground"
+ <ObjectPage
+ layoutId="multica_runtime_detail_layout"
+ segments={segments}
+ leaf={
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.detail_page.not_found_title)}
+ </span>
+ }
+ >
+ <CollectionPageState
+ icon={Server}
+ title={t(($) => $.detail_page.not_found_title)}
+ description={t(($) => $.detail_page.not_found_hint)}
/>
- <p className="mt-3 text-body">{t(($) => $.detail_page.not_found_title)}</p>
- <p className="mt-1 text-caption text-muted-foreground">
- {t(($) => $.detail_page.not_found_hint)}
- </p>
- </div>
+ </ObjectPage>
);
}
const { machine, runtime } = target;
diff --git a/packages/views/runtimes/components/runtimes-page.test.tsx b/packages/views/runtimes/components/runtimes-page.test.tsx
index 8902acd230..da8456650e 100644
--- a/packages/views/runtimes/components/runtimes-page.test.tsx
+++ b/packages/views/runtimes/components/runtimes-page.test.tsx
@@ -15,10 +15,13 @@ import {
memberListOptions,
} from "@multica/core/workspace/queries";
import enCommon from "../../locales/en/common.json";
+import enLayout from "../../locales/en/layout.json";
import enRuntimes from "../../locales/en/runtimes.json";
import { RuntimesPage } from "./runtimes-page";
-const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };
+const TEST_RESOURCES = {
+ en: { common: enCommon, layout: enLayout, runtimes: enRuntimes },
+};
const WS = "ws-test";
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
@@ -45,7 +48,12 @@ vi.mock("../../navigation", () => ({
),
rowLinkInteractiveProps: {},
useNavigation: () => ({ push: vi.fn() }),
- useRowLink: () => () => ({}),
+ useIntentNavigate: () => vi.fn(),
+ useRowLink: () => () => ({
+ onClick: vi.fn(),
+ onAuxClick: vi.fn(),
+ onMouseEnter: vi.fn(),
+ }),
}));
const NOW = Date.now();
@@ -141,16 +149,71 @@ describe("RuntimesPage", () => {
expect(screen.getByText("Claude Managed Agents")).toBeInTheDocument();
});
- it("keeps the header, toolbar and column headers up while the list loads", () => {
+ it("keeps the header and column headers up while the list loads", () => {
const { container } = renderPage({ runtimes: null });
- expect(screen.getByRole("heading", { name: "Runtimes" })).toBeInTheDocument();
- expect(screen.getByRole("textbox")).toBeInTheDocument();
+ const header = screen.getByRole("banner");
+ expect(
+ within(header).getByRole("heading", { name: "All runtimes", level: 1 }),
+ ).toBeInTheDocument();
expect(screen.getAllByRole("columnheader").length).toBeGreaterThan(0);
expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();
expect(screen.queryByText("Machines")).not.toBeInTheDocument();
});
+ it("keeps the top bar to one row of icon tools with a single icon add action", () => {
+ renderPage();
+
+ const header = screen.getByRole("banner");
+ expect(screen.getAllByRole("banner")).toHaveLength(1);
+ expect(within(header).queryByText("Learn more →")).not.toBeInTheDocument();
+ expect(within(header).queryByText("2")).not.toBeInTheDocument();
+ const add = within(header).getByRole("button", { name: "Add runtime" });
+ expect(add).not.toHaveTextContent("Add runtime");
+ expect(screen.queryByRole("button", { name: /^Offline/ })).not.toBeInTheDocument();
+ });
+
+ it("lists every add option behind the + icon", async () => {
+ const user = userEvent.setup();
+ renderPage({ connection: qoder({ configured: true, enabled: true, status: "online" }) });
+
+ await user.click(screen.getByRole("button", { name: "Add runtime" }));
+ const menu = await screen.findByRole("menu");
+ expect(within(menu).getByText("Machines")).toBeInTheDocument();
+ expect(within(menu).getByText("This computer")).toBeInTheDocument();
+ expect(within(menu).getByText("Other machine or server")).toBeInTheDocument();
+ expect(within(menu).getByText("Cloud services")).toBeInTheDocument();
+ expect(within(menu).getByText("Qoder Cloud Agents")).toBeInTheDocument();
+ expect(within(menu).getByText("Cursor Cloud Agents")).toBeInTheDocument();
+ expect(within(menu).getByText("Claude Managed Agents")).toBeInTheDocument();
+ });
+
+ it("counts machines and cloud services per status in the scope menu", async () => {
+ const user = userEvent.setup();
+ renderPage({
+ runtimes: [
+ makeRuntime(),
+ makeRuntime({
+ id: "rt-codex",
+ daemon_id: "daemon-2",
+ name: "Codex (build-server)",
+ provider: "codex",
+ device_info: "build-server · codex 0.5.0",
+ status: "offline",
+ last_seen_at: new Date(NOW - 3 * 60 * 60_000).toISOString(),
+ }),
+ ],
+ connection: qoder({ configured: true, enabled: true, status: "online" }),
+ });
+
+ await user.click(screen.getByRole("button", { name: /All runtimes/ }));
+ expect(
+ await screen.findByRole("menuitemradio", { name: /All runtimes/ }),
+ ).toHaveTextContent("3");
+ expect(screen.getByRole("menuitemradio", { name: /Online/ })).toHaveTextContent("2");
+ expect(screen.getByRole("menuitemradio", { name: /Offline/ })).toHaveTextContent("1");
+ });
+
it("offers the desktop download on web when no machine is connected", () => {
renderPage({ runtimes: [] });
@@ -169,7 +232,7 @@ describe("RuntimesPage", () => {
expect(screen.getByText("This device")).toBeInTheDocument();
expect(screen.queryByText("Run on this computer")).not.toBeInTheDocument();
- await user.click(screen.getByRole("button", { name: /^Add/ }));
+ await user.click(screen.getByRole("button", { name: "Add runtime" }));
const menu = await screen.findByRole("menu");
expect(within(menu).getByText("Connected · Jiayuan's MacBook")).toBeInTheDocument();
expect(within(menu).getByText("Other machine or server")).toBeInTheDocument();
@@ -177,7 +240,7 @@ describe("RuntimesPage", () => {
expect(within(menu).getByText("By Qoder")).toBeInTheDocument();
});
- it("filters rows by search and status", async () => {
+ it("filters rows by status", async () => {
const user = userEvent.setup();
renderPage({
runtimes: [
@@ -195,19 +258,23 @@ describe("RuntimesPage", () => {
connection: qoder({ configured: true, enabled: true, status: "online" }),
});
- await user.click(screen.getByRole("button", { name: /^Offline/ }));
+ await user.click(screen.getByRole("button", { name: /All runtimes/ }));
+ await user.click(await screen.findByRole("menuitemradio", { name: /Offline/ }));
+ expect(
+ within(screen.getByRole("banner")).getByRole("heading", { name: "Offline" }),
+ ).toBeInTheDocument();
expect(screen.getByText("build-server")).toBeInTheDocument();
expect(screen.queryByText("dev-machine.local")).not.toBeInTheDocument();
expect(screen.queryByText("Qoder Cloud Agents")).not.toBeInTheDocument();
- await user.click(screen.getByRole("button", { name: /^All/ }));
- await user.type(screen.getByRole("textbox"), "zzz");
- expect(
- screen.getByText("No machines or cloud services match"),
- ).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: /Offline/ }));
+ await user.click(await screen.findByRole("menuitemradio", { name: /All runtimes/ }));
+ expect(screen.getByText("dev-machine.local")).toBeInTheDocument();
+ expect(screen.getByText("build-server")).toBeInTheDocument();
});
- it("never lists the Qoder runtime as a machine", () => {
+ it("never lists the Qoder runtime as a machine", async () => {
+ const user = userEvent.setup();
const qoderRuntime = makeRuntime({
id: "rt-qoder",
daemon_id: "qoder-managed-ws-test",
@@ -228,9 +295,10 @@ describe("RuntimesPage", () => {
expect(screen.queryAllByText("Qoder Cloud Agents")).toHaveLength(
1,
);
- expect(screen.getByRole("button", { name: /^All/ })).toHaveTextContent(
- connection.configured ? "2" : "1",
- );
+ await user.click(screen.getByRole("button", { name: /All runtimes/ }));
+ expect(
+ await screen.findByRole("menuitemradio", { name: /All runtimes/ }),
+ ).toHaveTextContent(connection.configured ? "2" : "1");
unmount();
}
});
diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsx
index b6359358f0..58a6619988 100644
--- a/packages/views/runtimes/components/runtimes-page.tsx
+++ b/packages/views/runtimes/components/runtimes-page.tsx
@@ -3,15 +3,10 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import {
Check,
- ChevronDown,
- ChevronRight,
Cloud,
Download,
Laptop,
Loader2,
- Monitor,
- Plus,
- Search,
Server,
SquareTerminal,
} from "@multica/ui/icons";
@@ -44,7 +39,6 @@ import type { AgentRuntime, MemberWithUser } from "@multica/core/types";
import type { QoderConnection } from "@multica/core/runtimes/qoder";
import { Badge } from "@multica/ui/components/ui/badge";
import { Button, buttonVariants } from "@multica/ui/components/ui/button";
-import { Input } from "@multica/ui/components/ui/input";
import {
Dialog,
DialogContent,
@@ -61,27 +55,25 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- ListGrid,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
-} from "@multica/ui/components/ui/list-grid";
import {
MikaRuntimeChoice,
type MikaRuntimeSelection,
} from "./mika-runtime-choice";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { CollectionPageHeader } from "../../layout/collection-page";
-import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
-import { cn } from "@multica/ui/lib/utils";
import {
- AppLink,
- rowLinkInteractiveProps,
- useNavigation,
- useRowLink,
-} from "../../navigation";
+ CollectionCreateButton,
+ CollectionPageHeader,
+ CollectionScopeItems,
+} from "../../layout/collection-page";
+import {
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ CollectionTag,
+ type CollectionColumn,
+ type CollectionGroup,
+} from "../../layout/collection-list";
+import { cn } from "@multica/ui/lib/utils";
+import { useNavigation } from "../../navigation";
import { getMikaOnboarding, pickContentLang } from "../../onboarding/templates";
import { qoderOptions } from "@multica/core/runtimes/qoder";
import { QODER_RUNTIME_LOCATOR } from "./qoder-detail-page";
@@ -92,9 +84,13 @@ import { ProviderLogo } from "./provider-logo";
import { RuntimeList, buildWorkloadIndex } from "./runtime-list";
import { pendingRuntimeFromProfile } from "./pending-runtime";
import { buildRuntimeMachines, type RuntimeMachine } from "./runtime-machines";
-import { HealthDot, HealthIcon, useHealthLabel } from "./shared";
+import {
+ HealthIcon,
+ ProviderIconStack,
+ machineIcon,
+ useHealthLabel,
+} from "./shared";
import { useT, useTimeAgo } from "../../i18n";
-import { daemonRuntimesDocsHref } from "./runtime-docs";
export interface RuntimesPageProps {
/** Desktop-only daemon id used to identify this device. */
@@ -117,15 +113,20 @@ const COMING_SOON_SERVICES = [
{ provider: "claude", name: "Claude Managed Agents", vendor: "Anthropic" },
];
-// Track order: edge, name, harness, agents, workload, status, actions, edge.
-// Below @2xl only name, status and actions keep a track; the other cells are
-// `hidden @2xl:flex` and drop out of subgrid placement. MUST stay a literal
-// string so Tailwind sees the arbitrary template.
-const GRID_COLS =
- "grid-cols-[0.5rem_minmax(160px,1fr)_112px_5.5rem_0.5rem] " +
- "@2xl:grid-cols-[0.5rem_minmax(120px,1fr)_128px_64px_112px_136px_5.5rem_0.5rem]";
-
-const OPTIONAL_CELL = "hidden @2xl:flex";
+type RuntimeRow =
+ | { kind: "machine"; id: string; machine: RuntimeMachine; agentCount: number }
+ | { kind: "qoder"; id: string; connection: QoderConnection; agentCount: number }
+ | { kind: "coming-soon"; id: string; provider: string; name: string; vendor: string }
+ | {
+ kind: "action";
+ id: string;
+ icon: typeof Server;
+ title: string;
+ description: string;
+ action: ReactNode;
+ };
+
+type QoderStatus = "stopped" | "online" | "error" | "offline" | "starting";
function useNowTick(intervalMs = 30_000): number {
const [now, setNow] = useState(() => Date.now());
@@ -144,6 +145,22 @@ function qoderIsOnline(connection: QoderConnection): boolean {
);
}
+function qoderStatus(connection: QoderConnection): QoderStatus {
+ if (!connection.enabled) return "stopped";
+ if (connection.status === "online") return "online";
+ if (connection.status === "error") return "error";
+ if (connection.status === "offline") return "offline";
+ return "starting";
+}
+
+const QODER_DOT: Record<QoderStatus, string> = {
+ online: "bg-success",
+ error: "bg-destructive",
+ starting: "bg-warning",
+ offline: "bg-muted-foreground/40",
+ stopped: "bg-muted-foreground/40",
+};
+
export function RuntimesPage({
localDaemonId,
localMachineName,
@@ -151,7 +168,7 @@ export function RuntimesPage({
bootstrapping,
cloudRuntimeEnabled = false,
}: RuntimesPageProps = {}) {
- const { t, i18n } = useT("runtimes");
+ const { t } = useT("runtimes");
const isAuthLoading = useAuthStore((state) => state.isLoading);
const currentUserId = useAuthStore((state) => state.user?.id);
const wsId = useWorkspaceId();
@@ -162,7 +179,6 @@ export function RuntimesPage({
const [qoderDialogOpen, setQoderDialogOpen] = useState(false);
const [showConnectDialog, setShowConnectDialog] = useState(false);
const [showCloudRuntimeDialog, setShowCloudRuntimeDialog] = useState(false);
- const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
@@ -258,30 +274,19 @@ export function RuntimesPage({
).length;
const localMachine = machineList.find((machine) => machine.isCurrent);
- const needle = query.trim().toLowerCase();
- const filtering = needle.length > 0 || statusFilter !== "all";
- const matchesQuery = (...fields: (string | null | undefined)[]) =>
- !needle || fields.some((field) => field?.toLowerCase().includes(needle));
+ const filtering = statusFilter !== "all";
const matchesStatus = (online: boolean) =>
statusFilter === "all" || (statusFilter === "online") === online;
- const visibleMachines = machineList.filter(
- (machine) =>
- matchesStatus(machine.health === "online") &&
- matchesQuery(machine.title, machine.subtitle, ...machine.providerNames),
+ const visibleMachines = machineList.filter((machine) =>
+ matchesStatus(machine.health === "online"),
);
const qoderConfigured = qoder?.configured === true;
const showQoderRow =
qoder !== null &&
- matchesQuery(t(($) => $.qoder.cloud_title), "qoder") &&
(statusFilter === "all" ||
(qoderConfigured && matchesStatus(qoderIsOnline(qoder))));
- const visibleComingSoon =
- statusFilter === "all"
- ? COMING_SOON_SERVICES.filter((service) =>
- matchesQuery(service.name, service.vendor),
- )
- : [];
+ const visibleComingSoon = statusFilter === "all" ? COMING_SOON_SERVICES : [];
const showThisComputerRow =
!filtering && !isDesktop && machineList.length === 0;
const showAddMachineRow = !filtering && machineList.length === 0;
@@ -302,19 +307,164 @@ export function RuntimesPage({
offline: totalCount - onlineCount,
};
+ const scopeLabels: Record<StatusFilter, string> = {
+ all: t(($) => $.page.filters.all),
+ online: t(($) => $.page.filters.online),
+ offline: t(($) => $.page.filters.offline),
+ };
+
const openQoder = () =>
qoderConfigured ? navigation.push(qoderHref) : setQoderDialogOpen(true);
+ const columns = useMemo<CollectionColumn<RuntimeRow>[]>(
+ () => [
+ {
+ key: "name",
+ header: t(($) => $.page.columns.name),
+ cell: (row) => (
+ <RuntimeNameCell
+ row={row}
+ currentUserId={currentUserId ?? null}
+ members={members}
+ onConnectQoder={() => setQoderDialogOpen(true)}
+ />
+ ),
+ },
+ {
+ key: "harness",
+ header: t(($) => $.page.columns.harness),
+ width: 112,
+ cell: (row) =>
+ row.kind === "machine" ? (
+ <ProviderIconStack providers={row.machine.providerNames} />
+ ) : row.kind === "qoder" ? (
+ <CollectionEmptyValue />
+ ) : null,
+ },
+ {
+ key: "agents",
+ header: t(($) => $.page.columns.agents),
+ width: 56,
+ align: "end",
+ className: "tabular-nums",
+ cell: (row) =>
+ row.kind === "machine" || (row.kind === "qoder" && row.connection.configured)
+ ? row.agentCount
+ : row.kind === "qoder"
+ ? <CollectionEmptyValue />
+ : null,
+ },
+ {
+ key: "workload",
+ header: t(($) => $.page.columns.workload),
+ width: 112,
+ cell: (row) => <RuntimeWorkloadCell row={row} />,
+ },
+ {
+ key: "status",
+ header: t(($) => $.page.columns.status),
+ width: 136,
+ core: true,
+ cell: (row) => <RuntimeStatusCell row={row} bootstrapping={bootstrapping} />,
+ },
+ ],
+ [t, currentUserId, members, bootstrapping],
+ );
+
+ const machineRows: RuntimeRow[] = visibleMachines.map((machine) => ({
+ kind: "machine",
+ id: machine.id,
+ machine,
+ agentCount: machine.runtimes.reduce(
+ (sum, runtime) => sum + (agentCountByRuntime.get(runtime.id) ?? 0),
+ 0,
+ ),
+ }));
+ if (showThisComputerRow) {
+ machineRows.push({
+ kind: "action",
+ id: "action:this-computer",
+ icon: Laptop,
+ title: t(($) => $.page.rows.this_computer_title),
+ description: t(($) => $.page.rows.this_computer_hint),
+ action: (
+ <a
+ href="/download"
+ target="_blank"
+ rel="noreferrer"
+ className={buttonVariants({ variant: "outline", size: "xs" })}
+ >
+ <Download aria-hidden="true" className="size-3.5" />
+ {t(($) => $.page.rows.download_desktop)}
+ </a>
+ ),
+ });
+ }
+ if (showAddMachineRow) {
+ machineRows.push({
+ kind: "action",
+ id: "action:add-machine",
+ icon: SquareTerminal,
+ title: t(($) => $.page.rows.add_machine_title),
+ description: t(($) => $.page.rows.add_machine_hint),
+ action: (
+ <Button variant="outline" size="xs" onClick={() => setShowConnectDialog(true)}>
+ {t(($) => $.page.rows.view_commands)}
+ </Button>
+ ),
+ });
+ }
+ const cloudRows: RuntimeRow[] = [];
+ if (showQoderRow && qoder) {
+ cloudRows.push({
+ kind: "qoder",
+ id: "qoder",
+ connection: qoder,
+ agentCount: qoderAgentCount,
+ });
+ }
+ for (const service of visibleComingSoon) {
+ cloudRows.push({ kind: "coming-soon", id: `soon:${service.provider}`, ...service });
+ }
+ const groups: CollectionGroup<RuntimeRow>[] = nothingMatches
+ ? []
+ : [
+ {
+ key: "machines",
+ label: t(($) => $.page.groups.machines.title),
+ count: machineList.length,
+ rows: machineRows,
+ },
+ {
+ key: "cloud",
+ label: t(($) => $.page.groups.cloud.title),
+ count: configuredCloudCount,
+ rows: cloudRows,
+ },
+ ];
+ const rowHref = (row: RuntimeRow) =>
+ row.kind === "machine"
+ ? paths.runtimeDetail(row.machine.id)
+ : row.kind === "qoder" && row.connection.configured
+ ? qoderHref
+ : null;
+
return (
<div className="flex min-h-0 flex-1 flex-col">
<CollectionPageHeader
icon={Server}
- title={t(($) => $.page.title)}
- count={totalCount}
- learnMore={{
- href: daemonRuntimesDocsHref(i18n.language),
- label: t(($) => $.page.learn_more),
- }}
+ title={scopeLabels[statusFilter]}
+ menu={
+ <CollectionScopeItems
+ value={statusFilter}
+ onChange={setStatusFilter}
+ options={STATUS_FILTERS.map((filter) => ({
+ value: filter,
+ label: scopeLabels[filter],
+ count: statusCounts[filter],
+ }))}
+ />
+ }
actions={
<AddRuntimeMenu
isDesktop={isDesktop}
@@ -329,116 +479,25 @@ export function RuntimesPage({
/>
<div className="min-h-0 flex-1 overflow-y-auto">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex flex-col gap-3 py-4 sm:py-6")}>
- <RuntimesToolbar
- query={query}
- onQueryChange={setQuery}
- statusFilter={statusFilter}
- onStatusFilterChange={setStatusFilter}
- counts={statusCounts}
- />
-
- <div className="@container overflow-hidden rounded-lg border bg-card">
- <ListGrid className={cn(GRID_COLS, "[&>[role=row]:last-child]:border-b-0")}>
- <ListGridHeader className="static border-b bg-card after:hidden">
- <ListGridHeaderCell>{t(($) => $.page.columns.name)}</ListGridHeaderCell>
- <ListGridHeaderCell className={OPTIONAL_CELL}>
- {t(($) => $.page.columns.harness)}
- </ListGridHeaderCell>
- <ListGridHeaderCell className={OPTIONAL_CELL}>
- {t(($) => $.page.columns.agents)}
- </ListGridHeaderCell>
- <ListGridHeaderCell className={OPTIONAL_CELL}>
- {t(($) => $.page.columns.workload)}
- </ListGridHeaderCell>
- <ListGridHeaderCell>{t(($) => $.page.columns.status)}</ListGridHeaderCell>
- <ListGridHeaderCell aria-hidden="true" />
- </ListGridHeader>
-
- {listLoading ? (
- <RuntimeRowsSkeleton />
- ) : nothingMatches ? (
- <div
- role="row"
- className="col-span-full px-4 py-10 text-center text-caption text-muted-foreground"
- >
- {t(($) => $.page.rows.no_matches)}
- </div>
- ) : (
- <>
- <GroupHeader
- title={t(($) => $.page.groups.machines.title)}
- count={machineList.length}
- />
- {visibleMachines.map((machine) => (
- <MachineRow
- key={machine.id}
- machine={machine}
- bootstrapping={bootstrapping}
- currentUserId={currentUserId ?? null}
- members={members}
- agentCount={machine.runtimes.reduce(
- (sum, runtime) =>
- sum + (agentCountByRuntime.get(runtime.id) ?? 0),
- 0,
- )}
- />
- ))}
- {showThisComputerRow && (
- <ActionRow
- icon={Laptop}
- title={t(($) => $.page.rows.this_computer_title)}
- description={t(($) => $.page.rows.this_computer_hint)}
- action={
- <a
- href="/download"
- target="_blank"
- rel="noreferrer"
- className={buttonVariants({ variant: "outline", size: "sm" })}
- >
- <Download aria-hidden="true" className="size-3.5" />
- {t(($) => $.page.rows.download_desktop)}
- </a>
- }
- />
- )}
- {showAddMachineRow && (
- <ActionRow
- icon={SquareTerminal}
- title={t(($) => $.page.rows.add_machine_title)}
- description={t(($) => $.page.rows.add_machine_hint)}
- action={
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowConnectDialog(true)}
- >
- {t(($) => $.page.rows.view_commands)}
- </Button>
- }
- />
- )}
-
- <GroupHeader
- title={t(($) => $.page.groups.cloud.title)}
- count={configuredCloudCount}
- />
- {showQoderRow && qoder && (
- <QoderRow
- connection={qoder}
- agentCount={qoderAgentCount}
- detailHref={qoderHref}
- onConnect={() => setQoderDialogOpen(true)}
- />
- )}
- {visibleComingSoon.map((service) => (
- <ComingSoonRow key={service.provider} {...service} />
- ))}
- </>
- )}
- </ListGrid>
- </div>
-
+ <CollectionList
+ embedded
+ pageShortcuts
+ label={scopeLabels[statusFilter]}
+ columns={columns}
+ groups={groups}
+ loading={listLoading}
+ getRowId={(row) => row.id}
+ getRowHref={rowHref}
+ getRowTitle={(row) =>
+ row.kind === "machine"
+ ? row.machine.title
+ : row.kind === "qoder"
+ ? t(($) => $.qoder.cloud_title)
+ : undefined
+ }
+ empty={t(($) => $.page.rows.no_matches)}
+ />
+ <div className="flex flex-col gap-6 px-6 pt-6 pb-16 empty:hidden">
{!agentsLoading &&
!chatSessionsLoading &&
memberNeedsMikaSetup(agents, chatSessions) &&
@@ -456,7 +515,6 @@ export function RuntimesPage({
<OrphanRuntimeProfiles
runtimes={orphanProfileRuntimes}
now={now}
- hasMachines={machines.length > 0}
/>
)}
</div>
@@ -496,13 +554,7 @@ function AddRuntimeMenu({
return (
<DropdownMenu>
<DropdownMenuTrigger
- render={
- <Button size="sm" className="gap-1">
- <Plus aria-hidden="true" className="size-3.5" />
- {t(($) => $.page.add)}
- <ChevronDown aria-hidden="true" className="size-3.5 opacity-70" />
- </Button>
- }
+ render={<CollectionCreateButton label={t(($) => $.page.add)} />}
/>
<DropdownMenuContent align="end" className="w-80">
<DropdownMenuGroup>
@@ -616,184 +668,96 @@ function AddMenuItem({
);
}
-function RuntimesToolbar({
- query,
- onQueryChange,
- statusFilter,
- onStatusFilterChange,
- counts,
+function RuntimeNameCell({
+ row,
+ currentUserId,
+ members,
+ onConnectQoder,
}: {
- query: string;
- onQueryChange: (query: string) => void;
- statusFilter: StatusFilter;
- onStatusFilterChange: (filter: StatusFilter) => void;
- counts: Record<StatusFilter, number>;
+ row: RuntimeRow;
+ currentUserId: string | null;
+ members: MemberWithUser[];
+ onConnectQoder: () => void;
}) {
const { t } = useT("runtimes");
- const labels: Record<StatusFilter, string> = {
- all: t(($) => $.page.filters.all),
- online: t(($) => $.page.filters.online),
- offline: t(($) => $.page.filters.offline),
- };
- return (
- <div className="flex min-w-0 items-center gap-2">
- <div className="relative min-w-0 flex-1 sm:flex-none">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- value={query}
- onChange={(e) => onQueryChange(e.target.value)}
- aria-label={t(($) => $.page.search_placeholder)}
- placeholder={t(($) => $.page.search_placeholder)}
- className="h-8 w-full pl-8 text-body sm:w-64"
+ switch (row.kind) {
+ case "machine": {
+ const { machine } = row;
+ const Icon = machineIcon(machine);
+ const ownerId = machine.runtimes[0]?.owner_id ?? null;
+ const owner =
+ ownerId && ownerId === currentUserId
+ ? t(($) => $.page.rows.owner_you)
+ : (members.find((member) => member.user_id === ownerId)?.name ?? null);
+ const description =
+ [machine.deviceSummary, owner].filter(Boolean).join(" · ") ||
+ (machine.section === "cloud"
+ ? t(($) => $.machine.metrics.cloud_worker)
+ : t(($) => $.machine.metrics.local_daemon));
+ return (
+ <CollectionNameCell
+ icon={<Icon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />}
+ title={machine.title}
+ badges={
+ machine.isCurrent ? (
+ <CollectionTag>{t(($) => $.machine.this_machine)}</CollectionTag>
+ ) : undefined
+ }
+ description={description}
/>
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {STATUS_FILTERS.map((filter) => (
- <Button
- key={filter}
- variant="outline"
- size="sm"
- aria-pressed={statusFilter === filter}
- className={
- statusFilter === filter
- ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"
- : "gap-1.5 text-muted-foreground"
- }
- onClick={() => onStatusFilterChange(filter)}
- >
- {labels[filter]}
- <span className="tabular-nums text-caption text-muted-foreground">
- {counts[filter]}
+ );
+ }
+ case "qoder": {
+ const { connection } = row;
+ const byQoder = t(($) => $.page.rows.provided_by, { vendor: "Qoder" });
+ const error =
+ connection.configured &&
+ qoderStatus(connection) === "error" &&
+ connection.lastError;
+ return (
+ <CollectionNameCell
+ icon={<ProviderLogo provider="qoder_cloud" className="size-4 shrink-0" />}
+ title={t(($) => $.qoder.cloud_title)}
+ description={error || byQoder}
+ trailing={
+ connection.configured ? undefined : (
+ <Button variant="outline" size="xs" onClick={onConnectQoder}>
+ {t(($) => $.page.rows.connect)}
+ </Button>
+ )
+ }
+ />
+ );
+ }
+ case "coming-soon":
+ return (
+ <CollectionNameCell
+ icon={
+ <span className="shrink-0 opacity-60">
+ <ProviderLogo provider={row.provider} className="size-4" />
</span>
- </Button>
- ))}
- </div>
- </div>
- );
-}
-
-function GroupHeader({ title, count }: { title: string; count: number }) {
- return (
- <div
- role="row"
- className="col-span-full flex h-9 min-w-0 items-center gap-2 border-b bg-muted/40 px-4 text-caption"
- >
- <span className="font-semibold text-foreground">{title}</span>
- <span className="font-mono tabular-nums text-muted-foreground">{count}</span>
- </div>
- );
-}
-
-function ActionRow({
- icon: Icon,
- title,
- description,
- action,
-}: {
- icon: typeof Server;
- title: string;
- description: string;
- action: ReactNode;
-}) {
- return (
- <div
- role="row"
- className="col-span-full flex min-h-14 items-center gap-3 border-b px-4 py-2.5"
- >
- <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-dashed text-muted-foreground">
- <Icon aria-hidden="true" className="size-4" />
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-body font-medium">{title}</span>
- <span className="block truncate text-caption text-muted-foreground">
- {description}
- </span>
- </span>
- <span className="shrink-0">{action}</span>
- </div>
- );
-}
-
-function RowTile({
- children,
- dot,
-}: {
- children: ReactNode;
- dot?: ReactNode;
-}) {
- return (
- <span className="relative flex size-8 shrink-0 items-center justify-center rounded-lg border bg-background">
- {children}
- {dot}
- </span>
- );
-}
-
-function NameCell({
- tile,
- title,
- href,
- badge,
- subtitle,
- muted,
-}: {
- tile: ReactNode;
- title: string;
- href?: string;
- badge?: ReactNode;
- subtitle: string;
- muted?: boolean;
-}) {
- return (
- <ListGridCell className="gap-3 py-2.5">
- {tile}
- <span className="min-w-0 flex-1">
- <span className="flex min-w-0 items-center gap-2">
- {href ? (
- <AppLink
- href={href}
- className="truncate text-body font-medium focus-visible:outline-none focus-visible:underline"
- {...rowLinkInteractiveProps}
- >
- {title}
- </AppLink>
- ) : (
- <span
- className={cn(
- "truncate text-body font-medium",
- muted && "text-muted-foreground",
- )}
- >
- {title}
+ }
+ title={row.name}
+ description={t(($) => $.page.rows.provided_by, { vendor: row.vendor })}
+ muted
+ />
+ );
+ case "action": {
+ const Icon = row.icon;
+ return (
+ <CollectionNameCell
+ icon={
+ <span className="flex size-5 shrink-0 items-center justify-center rounded-sm border border-dashed text-muted-foreground">
+ <Icon aria-hidden="true" className="size-3" />
</span>
- )}
- {badge}
- </span>
- <span className="block truncate text-caption text-muted-foreground">
- {subtitle}
- </span>
- </span>
- </ListGridCell>
- );
-}
-
-function EmptyCell({ optional = true }: { optional?: boolean }) {
- return (
- <ListGridCell className={cn(optional && OPTIONAL_CELL, "text-caption text-faint-foreground")}>
- —
- </ListGridCell>
- );
-}
-
-function RowChevron() {
- return (
- <ListGridCell className="justify-end">
- <ChevronRight
- aria-hidden="true"
- className="size-4 text-faint-foreground transition-transform group-hover/row:translate-x-0.5 group-hover/row:text-muted-foreground"
- />
- </ListGridCell>
- );
+ }
+ title={row.title}
+ description={row.description}
+ trailing={<span className="shrink-0">{row.action}</span>}
+ />
+ );
+ }
+ }
}
function WorkloadText({
@@ -804,286 +768,93 @@ function WorkloadText({
queued: number;
}) {
const { t } = useT("runtimes");
- if (running + queued === 0) {
- return (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.machine.metrics.workload_idle)}
- </span>
- );
- }
+ if (running + queued === 0) return <>{t(($) => $.machine.metrics.workload_idle)}</>;
return (
- <span className="truncate text-caption tabular-nums">
+ <span className="truncate tabular-nums text-foreground">
{t(($) => $.machine.metrics.workload_hint, { running, queued })}
</span>
);
}
-function MachineRow({
- machine,
+function RuntimeWorkloadCell({ row }: { row: RuntimeRow }) {
+ if (row.kind === "machine") {
+ return row.machine.health === "online" ? (
+ <WorkloadText running={row.machine.runningCount} queued={row.machine.queuedCount} />
+ ) : (
+ <CollectionEmptyValue />
+ );
+ }
+ if (row.kind === "qoder") {
+ return row.connection.configured && qoderStatus(row.connection) === "online" ? (
+ <WorkloadText running={row.connection.activeRuns} queued={row.connection.queuedRuns} />
+ ) : (
+ <CollectionEmptyValue />
+ );
+ }
+ return null;
+}
+
+function RuntimeStatusCell({
+ row,
bootstrapping,
- currentUserId,
- members,
- agentCount,
}: {
- machine: RuntimeMachine;
+ row: RuntimeRow;
bootstrapping?: boolean;
- currentUserId: string | null;
- members: MemberWithUser[];
- agentCount: number;
}) {
const { t } = useT("runtimes");
const healthLabel = useHealthLabel();
const timeAgo = useTimeAgo();
- const paths = useWorkspacePaths();
- const rowLink = useRowLink();
- const href = paths.runtimeDetail(machine.id);
- const Icon = machine.isCurrent
- ? Laptop
- : machine.section === "cloud"
- ? Cloud
- : Monitor;
- const ownerId = machine.runtimes[0]?.owner_id ?? null;
- const owner =
- ownerId && ownerId === currentUserId
- ? t(($) => $.page.rows.owner_you)
- : (members.find((member) => member.user_id === ownerId)?.name ?? null);
- const subtitle =
- [machine.deviceSummary, owner].filter(Boolean).join(" · ") ||
- (machine.section === "cloud"
- ? t(($) => $.machine.metrics.cloud_worker)
- : t(($) => $.machine.metrics.local_daemon));
- const starting =
- machine.isCurrent && bootstrapping && machine.runtimes.length === 0;
- const online = machine.health === "online";
-
- return (
- <ListGridRow
- className="h-auto min-h-14 cursor-pointer border-b"
- {...rowLink(href, machine.title)}
- >
- <NameCell
- tile={
- <RowTile
- dot={
- <HealthDot
- health={machine.health}
- className="absolute -bottom-0.5 -right-0.5 ring-2 ring-card"
- />
- }
- >
- <Icon aria-hidden="true" className="size-4 text-muted-foreground" />
- </RowTile>
- }
- title={machine.title}
- href={href}
- badge={
- machine.isCurrent ? (
- <Badge variant="secondary" className="shrink-0">
- {t(($) => $.machine.this_machine)}
- </Badge>
- ) : undefined
- }
- subtitle={subtitle}
- />
- <ListGridCell className={OPTIONAL_CELL}>
- <ProviderIconStack providers={machine.providerNames} />
- </ListGridCell>
- <ListGridCell className={cn(OPTIONAL_CELL, "text-body tabular-nums")}>
- {agentCount}
- </ListGridCell>
- {online ? (
- <ListGridCell className={OPTIONAL_CELL}>
- <WorkloadText
- running={machine.runningCount}
- queued={machine.queuedCount}
- />
- </ListGridCell>
- ) : (
- <EmptyCell />
- )}
- <ListGridCell className="gap-1.5 text-caption">
- {starting ? (
+ switch (row.kind) {
+ case "machine": {
+ const { machine } = row;
+ if (machine.isCurrent && bootstrapping && machine.runtimes.length === 0) {
+ return (
<>
- <Loader2 aria-hidden="true" className="size-3 animate-spin text-muted-foreground" />
- <span className="truncate text-muted-foreground">
- {t(($) => $.page.bootstrapping.title)}
- </span>
+ <Loader2 aria-hidden="true" className="size-3 shrink-0 animate-spin" />
+ <span className="truncate">{t(($) => $.page.bootstrapping.title)}</span>
</>
- ) : (
- <>
- <HealthIcon health={machine.health} />
- <span className={cn("truncate", !online && "text-muted-foreground")}>
- {healthLabel(machine.health)}
- {!online && machine.lastSeenAt
- ? ` · ${timeAgo(machine.lastSeenAt)}`
- : ""}
- </span>
- </>
- )}
- </ListGridCell>
- <RowChevron />
- </ListGridRow>
- );
-}
-
-function QoderRow({
- connection,
- agentCount,
- detailHref,
- onConnect,
-}: {
- connection: QoderConnection;
- agentCount: number;
- detailHref: string;
- onConnect: () => void;
-}) {
- const { t } = useT("runtimes");
- const rowLink = useRowLink();
- const title = t(($) => $.qoder.cloud_title);
- const logo = <ProviderLogo provider="qoder_cloud" className="size-4" />;
- const byQoder = t(($) => $.page.rows.provided_by, { vendor: "Qoder" });
-
- if (!connection.configured) {
- return (
- <ListGridRow className="h-auto min-h-14 border-b">
- <NameCell
- tile={
- <RowTile
- dot={
- <span className="absolute -bottom-0.5 -right-0.5 size-2 rounded-full bg-warning ring-2 ring-card" />
- }
- >
- {logo}
- </RowTile>
- }
- title={title}
- subtitle={byQoder}
- />
- <EmptyCell />
- <EmptyCell />
- <EmptyCell />
- <ListGridCell>
+ );
+ }
+ const online = machine.health === "online";
+ return (
+ <>
+ <HealthIcon health={machine.health} />
+ <span className={cn("truncate", online && "text-foreground")}>
+ {healthLabel(machine.health)}
+ {!online && machine.lastSeenAt ? ` · ${timeAgo(machine.lastSeenAt)}` : ""}
+ </span>
+ </>
+ );
+ }
+ case "qoder": {
+ if (!row.connection.configured) {
+ return (
<Badge variant="secondary" className="bg-warning/10 text-warning">
{t(($) => $.page.rows.not_connected)}
</Badge>
- </ListGridCell>
- <ListGridCell className="justify-end">
- <Button variant="outline" size="sm" onClick={onConnect}>
- {t(($) => $.page.rows.connect)}
- </Button>
- </ListGridCell>
- </ListGridRow>
- );
- }
-
- const status = !connection.enabled
- ? "stopped"
- : connection.status === "online"
- ? "online"
- : connection.status === "error"
- ? "error"
- : connection.status === "offline"
- ? "offline"
- : "starting";
- const dotTone =
- status === "online"
- ? "bg-success"
- : status === "error"
- ? "bg-destructive"
- : status === "starting"
- ? "bg-warning"
- : "bg-muted-foreground/40";
- const subtitle =
- status === "error" && connection.lastError ? connection.lastError : byQoder;
-
- return (
- <ListGridRow
- className="h-auto min-h-14 cursor-pointer border-b"
- {...rowLink(detailHref, title)}
- >
- <NameCell
- tile={
- <RowTile
- dot={
- <span
- className={cn(
- "absolute -bottom-0.5 -right-0.5 size-2 rounded-full ring-2 ring-card",
- dotTone,
- )}
- />
- }
+ );
+ }
+ const status = qoderStatus(row.connection);
+ return (
+ <>
+ <span aria-hidden="true" className={cn("size-1.5 shrink-0 rounded-full", QODER_DOT[status])} />
+ <span
+ className={cn(
+ "truncate",
+ status === "online" && "text-foreground",
+ status === "error" && "text-destructive",
+ )}
>
- {logo}
- </RowTile>
- }
- title={title}
- href={detailHref}
- subtitle={subtitle}
- />
- <EmptyCell />
- <ListGridCell className={cn(OPTIONAL_CELL, "text-body tabular-nums")}>
- {agentCount}
- </ListGridCell>
- {status === "online" ? (
- <ListGridCell className={OPTIONAL_CELL}>
- <WorkloadText
- running={connection.activeRuns}
- queued={connection.queuedRuns}
- />
- </ListGridCell>
- ) : (
- <EmptyCell />
- )}
- <ListGridCell className="gap-1.5 text-caption">
- <span aria-hidden="true" className={cn("size-1.5 rounded-full", dotTone)} />
- <span
- className={cn(
- "truncate",
- status === "error" && "text-destructive",
- status !== "online" && status !== "error" && "text-muted-foreground",
- )}
- >
- {t(($) => $.qoder[status])}
- </span>
- </ListGridCell>
- <RowChevron />
- </ListGridRow>
- );
-}
-
-function ComingSoonRow({
- provider,
- name,
- vendor,
-}: {
- provider: string;
- name: string;
- vendor: string;
-}) {
- const { t } = useT("runtimes");
- return (
- <ListGridRow className="h-auto min-h-14 border-b hover:bg-transparent">
- <NameCell
- tile={
- <RowTile>
- <span className="opacity-60">
- <ProviderLogo provider={provider} className="size-4" />
- </span>
- </RowTile>
- }
- title={name}
- subtitle={t(($) => $.page.rows.provided_by, { vendor })}
- muted
- />
- <EmptyCell />
- <EmptyCell />
- <EmptyCell />
- <ListGridCell>
- <Badge variant="secondary">{t(($) => $.page.groups.cloud.coming_soon)}</Badge>
- </ListGridCell>
- <ListGridCell aria-hidden="true" />
- </ListGridRow>
- );
+ {t(($) => $.qoder[status])}
+ </span>
+ </>
+ );
+ }
+ case "coming-soon":
+ return <Badge variant="secondary">{t(($) => $.page.groups.cloud.coming_soon)}</Badge>;
+ case "action":
+ return null;
+ }
}
/**
@@ -1214,15 +985,13 @@ function MikaSetupCard({
function OrphanRuntimeProfiles({
runtimes,
now,
- hasMachines,
}: {
runtimes: ReturnType<typeof pendingRuntimeFromProfile>[];
now: number;
- hasMachines: boolean;
}) {
const { t } = useT("runtimes");
return (
- <section className={hasMachines ? "mt-6" : undefined}>
+ <section>
<div className="mb-3">
<h2 className="text-body font-semibold">
{t(($) => $.profiles.unassigned_title)}
@@ -1231,71 +1000,9 @@ function OrphanRuntimeProfiles({
{t(($) => $.profiles.unassigned_description)}
</p>
</div>
- <div className="overflow-hidden rounded-lg border bg-card">
- <RuntimeList runtimes={runtimes} now={now} />
- </div>
+ <RuntimeList runtimes={runtimes} now={now} />
</section>
);
}
-function ProviderIconStack({ providers }: { providers: string[] }) {
- const visible = providers.slice(0, 4);
- const extra = providers.length - visible.length;
- if (visible.length === 0) return null;
- return (
- <span className="flex min-w-0 items-center -space-x-1">
- {visible.map((provider) => (
- <span
- key={provider}
- className="inline-flex h-5 w-5 items-center justify-center rounded-xs bg-background ring-1 ring-border"
- >
- <ProviderLogo provider={provider} className="h-3.5 w-3.5" />
- </span>
- ))}
- {extra > 0 && (
- <span className="inline-flex h-5 min-w-5 items-center justify-center rounded-xs bg-muted px-1 text-micro font-medium text-muted-foreground ring-1 ring-border">
- +{extra}
- </span>
- )}
- </span>
- );
-}
-
-function RuntimeRowsSkeleton() {
- return (
- <>
- <div
- role="row"
- className="col-span-full flex h-9 items-center border-b bg-muted/40 px-4"
- >
- <Skeleton className="h-3 w-20" />
- </div>
- {Array.from({ length: 3 }).map((_, index) => (
- <ListGridRow key={index} className="h-auto min-h-14 border-b hover:bg-transparent">
- <ListGridCell className="gap-3">
- <Skeleton className="size-8 shrink-0 rounded-lg" />
- <div className="min-w-0 flex-1">
- <Skeleton className="h-3.5 w-36 max-w-full" />
- <Skeleton className="mt-1.5 h-3 w-24 max-w-full" />
- </div>
- </ListGridCell>
- <ListGridCell className={OPTIONAL_CELL}>
- <Skeleton className="size-4 rounded-sm" />
- </ListGridCell>
- <ListGridCell className={OPTIONAL_CELL}>
- <Skeleton className="h-3 w-6" />
- </ListGridCell>
- <ListGridCell className={OPTIONAL_CELL}>
- <Skeleton className="h-3 w-10" />
- </ListGridCell>
- <ListGridCell>
- <Skeleton className="h-3 w-16" />
- </ListGridCell>
- <ListGridCell aria-hidden="true" />
- </ListGridRow>
- ))}
- </>
- );
-}
-
export default RuntimesPage;
diff --git a/packages/views/runtimes/components/shared.tsx b/packages/views/runtimes/components/shared.tsx
index 31c426a27e..571adc4fbc 100644
--- a/packages/views/runtimes/components/shared.tsx
+++ b/packages/views/runtimes/components/shared.tsx
@@ -1,7 +1,16 @@
-import { Cloud, Monitor, Wifi, WifiHigh, WifiOff } from "@multica/ui/icons";
+import {
+ Cloud,
+ Laptop,
+ Monitor,
+ Wifi,
+ WifiHigh,
+ WifiOff,
+ type IconComponent,
+} from "@multica/ui/icons";
import { Badge } from "@multica/ui/components/ui/badge";
import type { RuntimeHealth } from "@multica/core/runtimes";
import { ProviderLogo } from "./provider-logo";
+import type { RuntimeMachine } from "./runtime-machines";
import { useT } from "../../i18n";
export function RuntimeModeIcon({ mode }: { mode: string }) {
@@ -12,6 +21,42 @@ export function RuntimeModeIcon({ mode }: { mode: string }) {
);
}
+export function machineIcon(
+ machine: Pick<RuntimeMachine, "isCurrent" | "section">,
+): IconComponent {
+ if (machine.isCurrent) return Laptop;
+ return machine.section === "cloud" ? Cloud : Monitor;
+}
+
+export function shortDaemonId(id: string | null): string | null {
+ if (!id) return null;
+ if (id.length <= 10) return id;
+ return `${id.slice(0, 6)}··${id.slice(-2)}`;
+}
+
+export function ProviderIconStack({ providers }: { providers: string[] }) {
+ const visible = providers.slice(0, 4);
+ const extra = providers.length - visible.length;
+ if (visible.length === 0) return null;
+ return (
+ <span className="flex min-w-0 items-center -space-x-1">
+ {visible.map((provider) => (
+ <span
+ key={provider}
+ className="inline-flex h-5 w-5 items-center justify-center rounded-xs bg-background ring-1 ring-border"
+ >
+ <ProviderLogo provider={provider} className="h-3.5 w-3.5" />
+ </span>
+ ))}
+ {extra > 0 && (
+ <span className="inline-flex h-5 min-w-5 items-center justify-center rounded-xs bg-muted px-1 text-micro font-medium text-muted-foreground ring-1 ring-border">
+ +{extra}
+ </span>
+ )}
+ </span>
+ );
+}
+
// Compact provider tag: small logo square + provider name. Used in dense
// list rows to identify which CLI / model provider a runtime is wired to.
export function ProviderChip({ provider }: { provider: string }) {
diff --git a/packages/views/search/index.ts b/packages/views/search/index.ts
index 5f25bb0a88..29bb634e49 100644
--- a/packages/views/search/index.ts
+++ b/packages/views/search/index.ts
@@ -1,3 +1,2 @@
export { SearchCommand } from "./search-command";
-export { SearchTrigger } from "./search-trigger";
export { useSearchStore } from "./search-store";
diff --git a/packages/views/search/search-trigger.tsx b/packages/views/search/search-trigger.tsx
deleted file mode 100644
index 87fe87018a..0000000000
--- a/packages/views/search/search-trigger.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client";
-
-import { Search } from "@multica/ui/icons";
-import { SidebarMenuButton } from "@multica/ui/components/ui/sidebar";
-import {
- useShortcut,
-} from "@multica/core/shortcuts";
-import { useSearchStore } from "./search-store";
-import { useT } from "../i18n";
-import { ShortcutKeycaps } from "../common/shortcut-keycaps";
-
-export function SearchTrigger() {
- const { t } = useT("search");
- const shortcut = useShortcut("openSearch");
- return (
- <SidebarMenuButton
- className="text-muted-foreground"
- onClick={() => useSearchStore.getState().setOpen(true)}
- >
- <Search />
- <span>{t(($) => $.trigger.label)}</span>
- {shortcut ? (
- <ShortcutKeycaps shortcut={shortcut} decorative className="pointer-events-none ml-auto" />
- ) : null}
- </SidebarMenuButton>
- );
-}
diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.ts
index dd7434bfd7..e1c74b03b5 100644
--- a/packages/views/search/use-root-model.ts
+++ b/packages/views/search/use-root-model.ts
@@ -37,6 +37,7 @@ const PAGE_KEYWORDS: Record<WorkspacePageKey, string[]> = {
chat: ["chat", "messages", "conversation", "聊天", "消息", "对话"],
myIssues: ["my", "issues", "assigned", "mine", "我的", "任务"],
issues: ["issues", "tasks", "bugs", "任务"],
+ views: ["views", "saved", "filters", "视图", "筛选"],
projects: ["projects", "kanban", "项目"],
autopilots: ["autopilot", "autopilots", "automation", "schedule", "cron", "webhook", "自动化", "定时"],
agents: ["agents", "bots", "ai", "智能体"],
diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsx
index c833f37fa3..6e646eaa9b 100644
--- a/packages/views/settings/components/members-tab.tsx
+++ b/packages/views/settings/components/members-tab.tsx
@@ -477,6 +477,18 @@ export function MembersTab() {
const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
const canManageWorkspace = currentMember?.role === "owner" || currentMember?.role === "admin";
+
+ // The Team panel's invite button links here with `?invite=1`; it waits for
+ // the member list so only managers get the dialog.
+ const inviteRequested = navigation?.searchParams.has("invite") ?? false;
+ useEffect(() => {
+ if (!inviteRequested || !navigation || !currentMember) return;
+ if (canManageWorkspace) setInviteOpen(true);
+ const params = new URLSearchParams(navigation.searchParams);
+ params.delete("invite");
+ navigation.replace(`${navigation.pathname}?${params}`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- consume the intent once the role is known
+ }, [inviteRequested, currentMember?.role]);
const isOwner = currentMember?.role === "owner";
const ownerCount = members.filter((m) => m.role === "owner").length;
// Only owners/admins may list share links; skip the request for plain
diff --git a/packages/views/settings/components/preferences-tab.tsx b/packages/views/settings/components/preferences-tab.tsx
index 186fe8371b..d40b0705de 100644
--- a/packages/views/settings/components/preferences-tab.tsx
+++ b/packages/views/settings/components/preferences-tab.tsx
@@ -25,12 +25,7 @@ import {
CommandList,
} from "@multica/ui/components/ui/command";
import { useTheme } from "@multica/ui/components/common/theme-provider";
-import {
- DEFAULT_LOCALE,
- SUPPORTED_LOCALES,
- type SupportedLocale,
-} from "@multica/core/i18n";
-import { useLocaleAdapter } from "@multica/core/i18n/react";
+import type { SupportedLocale } from "@multica/core/i18n";
import { useAuthStore } from "@multica/core/auth";
import { useChatStore } from "@multica/core/chat";
import {
@@ -50,6 +45,7 @@ import {
} from "@multica/core/issues/stores/issue-create-settings-store";
import { api } from "@multica/core/api";
import { browserTimezone, timezoneOptions } from "../../common/timezone-select";
+import { useLanguageSwitch } from "../../common/use-language-switch";
import { SegmentedToggle } from "../../common/segmented-toggle";
import { useT } from "../../i18n";
import {
@@ -148,58 +144,12 @@ function ThemeRow() {
}
function LanguageRow() {
- const { t, i18n } = useT("settings");
- const localeAdapter = useLocaleAdapter();
- const user = useAuthStore((s) => s.user);
-
- // i18next.language can be a region-tagged BCP-47 string (e.g. "en-US",
- // "zh-Hans-CN") returned by intl-localematcher. Normalize to a supported
- // locale before comparing — otherwise the select shows neither option.
- const currentLocale: SupportedLocale = SUPPORTED_LOCALES.includes(
- i18n.language as SupportedLocale,
- )
- ? (i18n.language as SupportedLocale)
- : DEFAULT_LOCALE;
-
- const languageOptions: { value: SupportedLocale; label: string }[] = [
- { value: "en", label: t(($) => $.preferences.language.english) },
- { value: "zh-Hans", label: t(($) => $.preferences.language.chinese) },
- { value: "zh-Hant", label: t(($) => $.preferences.language.chinese_traditional) },
- { value: "ko", label: t(($) => $.preferences.language.korean) },
- { value: "ja", label: t(($) => $.preferences.language.japanese) },
- { value: "fr", label: t(($) => $.preferences.language.french) },
- ];
-
- // Persist locally → sync to user.language → reload. Reload (vs in-place
- // changeLanguage) avoids hydration mismatch and is the i18next-recommended
- // pattern for App Router. The reload itself is the confirmation.
- //
- // If the cross-device sync (PATCH /api/me) fails, the local cookie is
- // already written so the new locale will take effect after reload — but
- // the user's other devices won't see the change. Surface that explicitly
- // via a toast and delay the reload long enough for the toast to be read,
- // otherwise the failure would be invisible.
- const handleLanguageChange = async (next: SupportedLocale) => {
- if (next === currentLocale) return;
- localeAdapter.persist(next);
-
- let syncFailed = false;
- if (user) {
- try {
- await api.updateMe({ language: next });
- } catch {
- syncFailed = true;
- }
- }
-
- if (syncFailed) {
- toast.warning(t(($) => $.preferences.language.sync_failed));
- // Give the toast 2.5s of visible time before navigating away.
- setTimeout(() => window.location.reload(), 2500);
- return;
- }
- window.location.reload();
- };
+ const { t } = useT("settings");
+ const {
+ options: languageOptions,
+ currentLocale,
+ changeLanguage: handleLanguageChange,
+ } = useLanguageSwitch();
return (
<SettingsRow
diff --git a/packages/views/settings/components/settings-layout.tsx b/packages/views/settings/components/settings-layout.tsx
index e8a1161c1c..8a45c056d8 100644
--- a/packages/views/settings/components/settings-layout.tsx
+++ b/packages/views/settings/components/settings-layout.tsx
@@ -1,10 +1,18 @@
"use client";
-import { useId, type ReactNode } from "react";
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useId,
+ type ReactNode,
+} from "react";
+import { createPortal } from "react-dom";
import {
AlertCircle,
Building2,
Check,
+ ChevronRight,
Eye,
Laptop,
Loader2,
@@ -93,6 +101,22 @@ function WorkspaceScopeBadge({
);
}
+/**
+ * The settings page's one header, as a set of slots the open tab fills. The
+ * page names the section itself, so it stays put while a tab loads; the tab
+ * contributes what only it knows — where its setting takes effect, its
+ * page-level actions, and the name of a detail page opened inside it.
+ */
+export interface SettingsHeaderSlots {
+ trail: HTMLElement | null;
+ meta: HTMLElement | null;
+ actions: HTMLElement | null;
+ /** Tells the page a detail is open, so the section name links back. */
+ onDetailChange: (open: boolean) => void;
+}
+
+export const SettingsHeaderContext = createContext<SettingsHeaderSlots | null>(null);
+
export function SettingsTab({
title,
description,
@@ -104,12 +128,52 @@ export function SettingsTab({
title: ReactNode;
description?: ReactNode;
scope?: SettingsScope;
- /** Primary page-level action, aligned with the title. */
+ /** Page-level actions, at the right of the page header. */
actions?: ReactNode;
- /** Parent location for detail pages; rendered above the title. */
+ /**
+ * Parent location for detail pages. Inside the settings page the header
+ * shows the trail itself; standalone, this renders above the title.
+ */
breadcrumb?: ReactNode;
children: ReactNode;
}) {
+ const header = useContext(SettingsHeaderContext);
+ const detail = breadcrumb != null && breadcrumb !== false;
+ const onDetailChange = header?.onDetailChange;
+ useEffect(() => {
+ if (!onDetailChange || !detail) return;
+ onDetailChange(true);
+ return () => onDetailChange(false);
+ }, [onDetailChange, detail]);
+
+ if (header) {
+ return (
+ <div className="space-y-8">
+ {header.trail && detail
+ ? createPortal(
+ <>
+ <ChevronRight aria-hidden="true" className="size-3 shrink-0 text-faint-foreground" />
+ <span aria-current="page" className="min-w-0 truncate">
+ {title}
+ </span>
+ </>,
+ header.trail,
+ )
+ : null}
+ {header.meta && scope
+ ? createPortal(<SettingsScopeBadge scope={scope} />, header.meta)
+ : null}
+ {header.actions && actions ? createPortal(actions, header.actions) : null}
+ {description ? (
+ <p className="max-w-2xl text-body leading-6 text-muted-foreground">
+ {description}
+ </p>
+ ) : null}
+ {children}
+ </div>
+ );
+ }
+
return (
<div className="space-y-8">
<header>
diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsx
index 8dd5280b98..7f7875637b 100644
--- a/packages/views/settings/components/settings-page.test.tsx
+++ b/packages/views/settings/components/settings-page.test.tsx
@@ -10,17 +10,47 @@ import {
import { renderWithI18n } from "../../test/i18n";
// This file tests the settings SHELL — the chrome around the tabs — so every
-// tab panel is stubbed out. Their contents have their own test files.
+// tab panel is stubbed out. Their contents have their own test files. Profile
+// and Messaging keep the real SettingsTab, which is what feeds the page header.
const stub = vi.hoisted(() => (name: string) => () => ({
[name]: () => <div>{name}</div>,
}));
-vi.mock("./account-tab", stub("AccountTab"));
+const tabs = vi.hoisted(() => ({ channelDetail: false }));
+vi.mock("./account-tab", async () => {
+ const { SettingsTab } = await import("./settings-layout");
+ return {
+ AccountTab: () => (
+ <SettingsTab
+ title="Profile"
+ description="How you appear to your team."
+ scope="account"
+ actions={<button type="button">Sign out</button>}
+ >
+ <div>AccountTab</div>
+ </SettingsTab>
+ ),
+ };
+});
+vi.mock("./channels-tab", async () => {
+ const { SettingsTab } = await import("./settings-layout");
+ return {
+ ChannelsTab: () =>
+ tabs.channelDetail ? (
+ <SettingsTab title="Slack" scope="workspace" breadcrumb={<nav>Messaging</nav>}>
+ <div>SlackDetail</div>
+ </SettingsTab>
+ ) : (
+ <SettingsTab title="Messaging" scope="workspace">
+ <div>ChannelsTab</div>
+ </SettingsTab>
+ ),
+ };
+});
vi.mock("./preferences-tab", stub("PreferencesTab"));
vi.mock("./tokens-tab", stub("TokensTab"));
vi.mock("./workspace-tab", stub("WorkspaceTab"));
vi.mock("./members-tab", stub("MembersTab"));
vi.mock("./code-tab", stub("CodeTab"));
-vi.mock("./channels-tab", stub("ChannelsTab"));
vi.mock("./notifications-tab", stub("NotificationsTab"));
vi.mock("./labels-tab", stub("LabelsTab"));
vi.mock("../../workflows/workflows-tab", stub("WorkflowsTab"));
@@ -101,6 +131,7 @@ beforeEach(() => {
navigationState.search = "";
shell.appsAvailable = false;
shell.role = "owner";
+ tabs.channelDetail = false;
configStore.getState().setFeatureFlags({});
replace.mockClear();
push.mockClear();
@@ -108,9 +139,9 @@ beforeEach(() => {
describe("SettingsPage nav trigger", () => {
it("opens the nav from settings at compact widths", () => {
- // Settings builds its own chrome instead of a PageHeader, so without this
- // control a touch user who lands here has no way back to the nav at all —
- // the keyboard shortcut is not an answer on a tablet.
+ // At compact widths the nav is a sheet, so without this control a touch
+ // user who lands here has no way back to it at all — the keyboard
+ // shortcut is not an answer on a tablet.
renderWithI18n(
<SidebarProvider>
<NavStateProbe />
@@ -126,7 +157,7 @@ describe("SettingsPage nav trigger", () => {
});
it("hides the trigger only where the nav is a permanent column", () => {
- // The nav is in-flow from `xl` up, so the control is CSS-gated rather than
+ // The nav is in-flow from `lg` up, so the control is CSS-gated rather than
// unmounted — jsdom applies no stylesheet, hence the class assertion.
renderWithI18n(
<SidebarProvider>
@@ -134,7 +165,7 @@ describe("SettingsPage nav trigger", () => {
</SidebarProvider>,
);
- expect(trigger().className).toContain("xl:hidden");
+ expect(trigger().className).toContain("lg:hidden");
});
it("still renders standalone, without a sidebar around it", () => {
@@ -149,6 +180,52 @@ describe("SettingsPage nav trigger", () => {
});
});
+describe("SettingsPage header", () => {
+ function pageHeader() {
+ return within(screen.getByRole("banner"));
+ }
+
+ it.each([
+ { search: "", label: "Profile" },
+ { search: "tab=preferences", label: "Preferences" },
+ { search: "tab=shortcuts", label: "Shortcuts" },
+ { search: "tab=members", label: "Members" },
+ { search: "tab=channels", label: "Messaging" },
+ { search: "tab=mcp", label: "MCP servers" },
+ ])("names the $label section in the page header", ({ search, label }) => {
+ navigationState.search = search;
+ renderWithI18n(<SettingsPage />);
+
+ expect(pageHeader().getByRole("heading", { level: 2 })).toHaveTextContent(label);
+ });
+
+ it("moves the section's scope and actions into the header and drops the body title", () => {
+ renderWithI18n(<SettingsPage />);
+
+ const header = pageHeader();
+ expect(header.getByText("Account · synced")).toBeInTheDocument();
+ expect(header.getByRole("button", { name: "Sign out" })).toBeInTheDocument();
+ expect(screen.getAllByRole("heading", { name: "Profile" })).toHaveLength(1);
+ expect(screen.getByText("How you appear to your team.")).toBeInTheDocument();
+ expect(header.queryByText("How you appear to your team.")).toBeNull();
+ });
+
+ it("shows a detail page as a trail back to its section", () => {
+ navigationState.search = "tab=channels&integration=slack";
+ tabs.channelDetail = true;
+ renderWithI18n(<SettingsPage />);
+
+ const header = pageHeader();
+ const title = within(header.getByRole("heading", { level: 2 }));
+ expect(title.getByText("Slack")).toHaveAttribute("aria-current", "page");
+ const back = title.getByRole("link", { name: "Messaging" });
+ expect(back.getAttribute("href")).toContain("tab=channels");
+ expect(back.getAttribute("href")).not.toContain("integration");
+ expect(header.getByText("Acme workspace")).toBeInTheDocument();
+ expect(screen.queryByText("Messaging", { selector: "nav" })).toBeNull();
+ });
+});
+
describe("SettingsPage Plugin feature flag", () => {
it("hides Plugins and falls back from a direct tab URL when disabled", () => {
navigationState.search = "tab=plugins";
@@ -223,21 +300,24 @@ describe("SettingsPage workspace subscription feature flag", () => {
});
describe("SettingsPage information architecture", () => {
- it("groups pages by who they affect, then by topic", () => {
+ it("lists pages in flat sections under a single level of headings", () => {
renderWithI18n(<SettingsPage />);
- const personal = within(nav()).getByRole("region", { name: /Personal/ });
+ const sections = within(nav()).getAllByRole("region");
+ expect(sections.map((section) => within(section).getByRole("heading").textContent)).toEqual([
+ "Personal",
+ "Workspace",
+ "Issues & workflow",
+ "Connections & extensions",
+ ]);
+ const personal = within(nav()).getByRole("region", { name: "Personal" });
expect(within(personal).getByRole("link", { name: "Preferences" })).toBeInTheDocument();
expect(within(personal).getByRole("link", { name: "API Tokens" })).toBeInTheDocument();
- // The workspace group is named after the workspace it configures.
- const workspace = within(nav()).getByRole("region", { name: /Acme/ });
- const issues = within(workspace).getByRole("group", { name: "Issues & workflow" });
- expect(
- within(issues).getByRole("link", { name: "Workflows" }),
- ).toBeInTheDocument();
- const connections = within(workspace).getByRole("group", {
- name: "Connections & extensions",
- });
+ const workspace = within(nav()).getByRole("region", { name: "Workspace" });
+ expect(within(workspace).getByRole("link", { name: "Members" })).toBeInTheDocument();
+ const issues = within(nav()).getByRole("region", { name: "Issues & workflow" });
+ expect(within(issues).getByRole("link", { name: "Workflows" })).toBeInTheDocument();
+ const connections = within(nav()).getByRole("region", { name: "Connections & extensions" });
for (const name of ["Code", "Messaging", "MCP servers"]) {
expect(within(connections).getByRole("link", { name })).toBeInTheDocument();
}
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 808b2b7ea2..e80bf23145 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -9,7 +9,6 @@ import {
FolderGit2,
Keyboard,
KeyRound,
- Laptop,
ListPlus,
Lock,
MessagesSquare,
@@ -25,7 +24,6 @@ import {
Workflow,
Zap,
} from "@multica/ui/icons";
-import { useAuthStore } from "@multica/core/auth";
import { useCurrentWorkspace } from "@multica/core/paths";
import { useFeatureEnabled } from "@multica/core/config";
import { useCurrentMember } from "@multica/core/permissions";
@@ -33,13 +31,10 @@ import {
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
PLUGINS_V1_FLAG,
} from "@multica/core/feature-flags";
-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { cn } from "@multica/ui/lib/utils";
import { resolveSettingsLocation, settingsHref } from "./settings-navigation";
import { AppLink, useNavigation } from "../../navigation";
-import { WorkspaceAvatar } from "../../workspace/workspace-avatar";
import { AccountTab } from "./account-tab";
import { PreferencesTab } from "./preferences-tab";
import { TokensTab } from "./tokens-tab";
@@ -57,12 +52,19 @@ import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";
import { PluginsTab } from "./plugins-tab";
import { McpTab } from "./mcp-tab";
import { BillingTab } from "./billing-tab";
-import { SETTINGS_ANCHOR_ATTR } from "./settings-layout";
+import {
+ SETTINGS_ANCHOR_ATTR,
+ SettingsHeaderContext,
+ type SettingsHeaderSlots,
+} from "./settings-layout";
import { searchSettings } from "./settings-search";
import { HighlightText } from "../../search/highlight-text";
import { useSettingsSearchIndex } from "./use-settings-search-index";
import { WakeupsTab } from "./wakeups-tab";
-import { CollapsedNavTrigger } from "../../layout/page-header";
+import { CollapsedNavTrigger, PageHeader } from "../../layout/page-header";
+import { PanelHeader } from "../../layout/panel-nav";
+import { useListColumnCollapsed } from "../../layout/app-shell-context";
+import { ListColumn } from "../../layout/list-column";
import { useT } from "../../i18n";
export interface ExtraSettingsTab {
@@ -92,10 +94,8 @@ interface SettingsSubgroup {
interface SettingsScopeGroup {
key: "personal" | "workspace" | "device";
label: string;
- /** Leading mark: whose settings these are. */
- mark: React.ReactNode;
- /** Trailing detail (the user's name, "Workspace"). */
- tag?: string;
+ /** Nav heading of the unlabeled first subgroup, when it differs from `label`. */
+ navLabel?: string;
subgroups: SettingsSubgroup[];
}
@@ -106,10 +106,10 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
const { t } = useT("settings");
const workspace = useCurrentWorkspace();
const workspaceName = workspace?.name ?? t(($) => $.page.workspace_fallback);
- const user = useAuthStore((s) => s.user);
const { role } = useCurrentMember(workspace?.id ?? "");
const isMember = role === "member";
const navigation = useNavigation();
+ const listCollapsed = useListColumnCollapsed();
const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);
const billingEnabled = useFeatureEnabled(
BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
@@ -128,15 +128,6 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
{
key: "personal",
label: t(($) => $.page.groups.personal),
- mark: (
- <ActorAvatar
- name={user?.name ?? ""}
- initials={(user?.name ?? "U").charAt(0).toUpperCase()}
- avatarUrl={resolvePublicFileUrl(user?.avatar_url)}
- size="xs"
- />
- ),
- tag: user?.name,
subgroups: [
{
key: "personal",
@@ -171,15 +162,7 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
{
key: "workspace",
label: workspaceName,
- mark: (
- <WorkspaceAvatar
- name={workspaceName}
- avatarUrl={workspace?.avatar_url}
- size="sm"
- className="size-4 rounded-xs"
- />
- ),
- tag: t(($) => $.page.groups.workspace),
+ navLabel: t(($) => $.page.groups.workspace),
subgroups: [
{
key: "workspace",
@@ -264,7 +247,6 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
{
key: "device" as const,
label: t(($) => $.page.groups.device),
- mark: <Laptop aria-hidden="true" className="size-4 text-muted-foreground" />,
subgroups: [{ key: "device", entries: extraDeviceTabs as SettingsEntry[] }],
},
]
@@ -288,6 +270,22 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
),
);
+ // --- header ---------------------------------------------------------------
+ const [headerTrail, setHeaderTrail] = useState<HTMLElement | null>(null);
+ const [headerMeta, setHeaderMeta] = useState<HTMLElement | null>(null);
+ const [headerActions, setHeaderActions] = useState<HTMLElement | null>(null);
+ const [detailOpen, setDetailOpen] = useState(false);
+ const headerSlots = useMemo<SettingsHeaderSlots>(
+ () => ({
+ trail: headerTrail,
+ meta: headerMeta,
+ actions: headerActions,
+ onDetailChange: setDetailOpen,
+ }),
+ [headerTrail, headerMeta, headerActions],
+ );
+ const ActiveIcon = active.icon;
+
// --- search ---------------------------------------------------------------
const [query, setQuery] = useState("");
const [activeResult, setActiveResult] = useState(0);
@@ -358,7 +356,7 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
className={cn(
"flex min-h-8 items-center gap-2.5 rounded-lg px-3 py-1.5 text-body transition-colors focus-visible:outline-2 focus-visible:outline-ring",
active.value === item.value
- ? "bg-surface-selected font-medium text-surface-selected-foreground hover:bg-surface-selected"
+ ? "bg-surface-selected text-surface-selected-foreground hover:bg-surface-selected"
: "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
)}
>
@@ -424,13 +422,13 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background md:flex-row">
- <aside className="shrink-0 border-b border-surface-border md:flex md:w-60 md:flex-col md:border-b-0 md:border-r">
- <div className="flex h-16 shrink-0 items-center gap-1 px-4 md:px-5">
- <CollapsedNavTrigger />
- <h1 className="text-title font-semibold tracking-tight">
- {t(($) => $.page.title)}
- </h1>
- </div>
+ <ListColumn
+ collapsed={listCollapsed}
+ // Below md the navigation stacks above the content as a select.
+ className="max-md:h-auto max-md:w-full"
+ innerClassName="border-surface-border max-md:h-auto max-md:w-full max-md:border-r-0 max-md:border-b"
+ >
+ <PanelHeader as="h1" title={t(($) => $.page.title)} leading={<CollapsedNavTrigger />} />
<div className="px-4 pb-4 md:hidden">
<label className="sr-only" htmlFor="settings-navigation">
{t(($) => $.page.navigate)}
@@ -512,65 +510,66 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {
{query ? (
searchResults
) : (
- <div className="divide-y divide-surface-border">
- {groups.map((group) => (
- <section
- key={group.key}
- aria-labelledby={`settings-group-${group.key}`}
- className="py-2.5 first:pt-0"
- >
- <h2
- id={`settings-group-${group.key}`}
- className="flex h-8 min-w-0 items-center gap-2.5 px-3 text-label font-semibold text-foreground"
- >
- <span className="flex size-4 shrink-0 items-center justify-center">
- {group.mark}
- </span>
- <span className="truncate">{group.label}</span>
- {group.tag ? (
- <span className="ml-auto shrink-0 truncate text-micro font-medium text-muted-foreground">
- {group.tag}
- </span>
- ) : null}
- </h2>
- {group.subgroups.map((subgroup) => (
- <div
- key={subgroup.key}
- role={subgroup.label ? "group" : undefined}
- aria-labelledby={
- subgroup.label ? `settings-subgroup-${subgroup.key}` : undefined
- }
+ // One level of headings: each page names its own scope in a badge,
+ // so the nav only groups. Same section rhythm as the space panels.
+ groups.flatMap((group) =>
+ group.subgroups.map((subgroup) => {
+ const id = `settings-group-${group.key}-${subgroup.key}`;
+ return (
+ <section key={id} aria-labelledby={id} className="mt-5 first:mt-0">
+ <h2
+ id={id}
+ className="flex h-7 min-w-0 items-center px-3 text-caption font-medium text-muted-foreground"
>
- {subgroup.label ? (
- <h3
- id={`settings-subgroup-${subgroup.key}`}
- className="px-3 pb-1 pt-3 text-caption font-medium text-muted-foreground"
- >
- {subgroup.label}
- </h3>
- ) : null}
- <ul className="space-y-px">{subgroup.entries.map(navItem)}</ul>
- </div>
- ))}
- </section>
- ))}
- </div>
+ <span className="truncate">
+ {subgroup.label ?? group.navLabel ?? group.label}
+ </span>
+ </h2>
+ <ul className="space-y-px">{subgroup.entries.map(navItem)}</ul>
+ </section>
+ );
+ }),
+ )
)}
</nav>
- </aside>
- <div
- ref={contentRef}
- key={`${active.value}:${location.integration ?? ""}`}
- className="min-w-0 flex-1 overflow-y-auto overscroll-contain"
- >
- <div
- className={cn(
- "mx-auto w-full px-4 py-6 sm:px-6 md:px-10 md:py-8",
- active.wide ? "max-w-5xl" : "max-w-4xl",
- )}
- >
- {active.content}
- </div>
+ </ListColumn>
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <PageHeader leading={listCollapsed ? <CollapsedNavTrigger /> : false}>
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <h2 className="flex min-w-0 items-center gap-2 px-2 text-body font-medium">
+ <ActiveIcon className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ {detailOpen ? (
+ <AppLink
+ href={href(active.value)}
+ className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {active.label}
+ </AppLink>
+ ) : (
+ <span className="truncate">{active.label}</span>
+ )}
+ <span ref={setHeaderTrail} className="contents" />
+ </h2>
+ <span ref={setHeaderMeta} className="contents" />
+ </div>
+ <div ref={setHeaderActions} className="flex shrink-0 items-center gap-2 empty:hidden" />
+ </PageHeader>
+ <SettingsHeaderContext.Provider value={headerSlots}>
+ <div
+ ref={contentRef}
+ key={`${active.value}:${location.integration ?? ""}`}
+ className="min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain"
+ >
+ <div
+ className={cn(
+ "mx-auto w-full px-4 py-6 sm:px-6 md:px-10 md:py-8",
+ active.wide ? "max-w-5xl" : "max-w-4xl",
+ )}
+ >
+ {active.content}
+ </div>
+ </div>
+ </SettingsHeaderContext.Provider>
</div>
</div>
);
diff --git a/packages/views/skills/components/create-skill-dialog.test.tsx b/packages/views/skills/components/create-skill-dialog.test.tsx
index acf4f7fc89..46e82d46c2 100644
--- a/packages/views/skills/components/create-skill-dialog.test.tsx
+++ b/packages/views/skills/components/create-skill-dialog.test.tsx
@@ -39,7 +39,7 @@ vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));
-import { CreateSkillDialog } from "./create-skill-dialog";
+import { CreateSkillDialog, type CreateSkillMethod } from "./create-skill-dialog";
const ARCHIVE_FILE = new File(["pk"], "review-helper.skill", {
type: "application/zip",
@@ -87,7 +87,11 @@ function installLiveFileList(input: HTMLInputElement, files: File[]) {
});
}
-function renderDialog(onCreated = vi.fn(), onClose = vi.fn()) {
+function renderDialog(
+ onCreated = vi.fn(),
+ onClose = vi.fn(),
+ initialMethod?: CreateSkillMethod,
+) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
@@ -97,7 +101,11 @@ function renderDialog(onCreated = vi.fn(), onClose = vi.fn()) {
...render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
<QueryClientProvider client={queryClient}>
- <CreateSkillDialog onClose={onClose} onCreated={onCreated} />
+ <CreateSkillDialog
+ onClose={onClose}
+ onCreated={onCreated}
+ initialMethod={initialMethod}
+ />
</QueryClientProvider>
</I18nProvider>,
),
@@ -323,3 +331,23 @@ describe("CreateSkillDialog local import", () => {
).not.toBeInTheDocument();
});
});
+
+describe("CreateSkillDialog opened on a method", () => {
+ it("skips the chooser, and Cancel leaves the dialog", () => {
+ const { onClose } = renderDialog(vi.fn(), vi.fn(), "manual");
+ expect(screen.getByText(enSkills.create.manual.name_label)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /Import from URL/i })).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: enSkills.create.manual.cancel }));
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it("still steps back to the chooser when the user came through it", () => {
+ const { onClose } = renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: /Create manually/i }));
+ fireEvent.click(screen.getByRole("button", { name: enSkills.create.manual.cancel }));
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByRole("button", { name: /Import from URL/i })).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/skills/components/create-skill-dialog.tsx b/packages/views/skills/components/create-skill-dialog.tsx
index 2866905b53..9631735b1a 100644
--- a/packages/views/skills/components/create-skill-dialog.tsx
+++ b/packages/views/skills/components/create-skill-dialog.tsx
@@ -52,6 +52,8 @@ import { isNameConflictError } from "../lib/utils";
type Method = "chooser" | "manual" | "local" | "url" | "runtime";
+export type CreateSkillMethod = Exclude<Method, "chooser">;
+
function seedAfterCreate(
qc: ReturnType<typeof useQueryClient>,
wsId: string,
@@ -67,7 +69,7 @@ function seedAfterCreate(
function MethodChooser({ onChoose }: { onChoose: (m: Method) => void }) {
const { t } = useT("skills");
const methods: {
- key: Exclude<Method, "chooser">;
+ key: CreateSkillMethod;
icon: typeof Plus;
}[] = [
{ key: "manual", icon: Plus },
@@ -599,14 +601,17 @@ function LocalForm({
// Root dialog
export function CreateSkillDialog({
+ initialMethod,
onClose,
onCreated,
}: {
+ /** Opens straight on one method; without it the dialog starts on the chooser. */
+ initialMethod?: CreateSkillMethod;
onClose: () => void;
onCreated?: (skill: Skill) => void;
}) {
const { t } = useT("skills");
- const [method, setMethod] = useState<Method>("chooser");
+ const [method, setMethod] = useState<Method>(initialMethod ?? "chooser");
const [localPrepared, setLocalPrepared] = useState<PreparedSkillArchive | null>(
null,
);
@@ -695,6 +700,13 @@ export function CreateSkillDialog({
setLocalPrepared(wrapExistingSkillArchive(file));
};
+ // Opened on a method, Cancel leaves the dialog: the chooser it would fall
+ // back to is a step the user never took.
+ const cancelForm = () => {
+ if (initialMethod) onClose();
+ else setMethod("chooser");
+ };
+
const wide = method === "runtime";
return (
@@ -782,10 +794,7 @@ export function CreateSkillDialog({
{/* Method body — each form owns its scroll middle + footer */}
{method === "chooser" && <MethodChooser onChoose={handleChoose} />}
{method === "manual" && (
- <ManualForm
- onCreated={handleCreated}
- onCancel={() => setMethod("chooser")}
- />
+ <ManualForm onCreated={handleCreated} onCancel={cancelForm} />
)}
{method === "local" && (
<LocalForm
@@ -795,17 +804,14 @@ export function CreateSkillDialog({
onCreated={handleCreated}
onCancel={() => {
resetLocal();
- setMethod("chooser");
+ cancelForm();
}}
onChooseFolder={openFolderPicker}
onChooseArchive={openArchivePicker}
/>
)}
{method === "url" && (
- <UrlForm
- onCreated={handleCreated}
- onCancel={() => setMethod("chooser")}
- />
+ <UrlForm onCreated={handleCreated} onCancel={cancelForm} />
)}
{method === "runtime" && (
<RuntimeLocalSkillImportPanel
diff --git a/packages/views/skills/components/file-tree.tsx b/packages/views/skills/components/file-tree.tsx
index 1e29bd2edd..9a24463e91 100644
--- a/packages/views/skills/components/file-tree.tsx
+++ b/packages/views/skills/components/file-tree.tsx
@@ -208,7 +208,7 @@ function TreeNodeItem({
className={cn(
"flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md pr-2.5 text-left text-caption transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
isSelected
- ? "font-medium text-surface-selected-foreground"
+ ? "text-surface-selected-foreground"
: "text-muted-foreground group-hover/row:text-foreground",
)}
style={{ paddingLeft: `${depth * 12 + 10}px` }}
diff --git a/packages/views/skills/components/file-viewer.tsx b/packages/views/skills/components/file-viewer.tsx
index 92d0e468ff..aba8d5e852 100644
--- a/packages/views/skills/components/file-viewer.tsx
+++ b/packages/views/skills/components/file-viewer.tsx
@@ -22,8 +22,8 @@ export function isMarkdownPath(path: string) {
* Body of a single skill file.
*
* Frontmatter is stripped from the preview because `name` / `description` are
- * surfaced as first-class properties on the Overview tab — rendering them
- * again here was the third copy of the same two fields.
+ * surfaced as first-class properties of the skill — rendering them again here
+ * was the third copy of the same two fields.
*/
export function FileViewer({
path,
diff --git a/packages/views/skills/components/skill-detail-page.test.tsx b/packages/views/skills/components/skill-detail-page.test.tsx
index 83bb12cda7..945091232f 100644
--- a/packages/views/skills/components/skill-detail-page.test.tsx
+++ b/packages/views/skills/components/skill-detail-page.test.tsx
@@ -1,34 +1,19 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { fireEvent, render, screen } from "@testing-library/react";
+import { fireEvent, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Skill } from "@multica/core/types";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enSkills from "../../locales/en/skills.json";
+import { toast } from "sonner";
+import { renderWithI18n } from "../../test/i18n";
import { NavigationProvider, type NavigationAdapter } from "../../navigation";
-const TEST_RESOURCES = { en: { common: enCommon, skills: enSkills } };
-
-// MUL-7107: every band of a detail page reads the shared rail. The read-only
-// capability banner was the one left behind, so a viewer without edit rights
-// saw a near-full-width card above centred content on a wide window. The
-// constants are overridden with sentinels because their real values are
-// ordinary Tailwind classes a hand-written element could match by accident.
-const RAIL_SENTINEL = "rail-sentinel";
-const GUTTER_SENTINEL = "gutter-sentinel";
-vi.mock("../../layout/page-header", async (importOriginal) => ({
- ...(await importOriginal<typeof import("../../layout/page-header")>()),
- PAGE_RAIL: "rail-sentinel",
- PAGE_GUTTER: "gutter-sentinel",
-}));
-
const skillRef = vi.hoisted(() => ({ current: null as unknown }));
const agentsRef = vi.hoisted(() => ({ current: [] as unknown[] }));
const membersRef = vi.hoisted(() => ({ current: [] as unknown[] }));
const canEditRef = vi.hoisted(() => ({ current: true }));
+const copyTextMock = vi.hoisted(() => vi.fn(() => Promise.resolve(true)));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
vi.mock("@multica/core/workspace/queries", () => ({
@@ -71,7 +56,10 @@ vi.mock("@multica/core/auth", () => {
// SkillIcon, so the real module has to stay reachable.
vi.mock("@multica/core/paths", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/paths")>()),
- useWorkspacePaths: () => ({ skills: () => "/acme/skills" }),
+ useWorkspacePaths: () => ({
+ skills: () => "/acme/skills",
+ skillDetail: (id: string) => `/acme/skills/${id}`,
+ }),
}));
vi.mock("@multica/core/permissions", () => ({
useSkillPermissions: () => ({ canEdit: { allowed: true, reason: null } }),
@@ -82,11 +70,26 @@ vi.mock("@multica/core/workspace/avatar-url", () => ({
vi.mock("@multica/core/api", () => ({
api: { updateSkill: vi.fn(), deleteSkill: vi.fn() },
}));
+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: copyTextMock }));
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock("../hooks/use-can-edit-skill", () => ({
useCanEditSkill: () => canEditRef.current,
}));
+// jsdom gives every element a zero-size rect, so a live resize handle claims
+// every pointerdown on the page and no menu could open.
+vi.mock("react-resizable-panels", () => ({
+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
+ usePanelRef: () => ({
+ current: { isCollapsed: () => false, expand: vi.fn(), collapse: vi.fn() },
+ }),
+}));
+vi.mock("@multica/ui/components/ui/resizable", () => ({
+ ResizablePanelGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ ResizablePanel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ ResizableHandle: () => null,
+}));
+
// Heavy leaves that carry no behaviour under test.
vi.mock("../../rich-content", () => ({
RichContent: ({ content }: { content: string }) => (
@@ -96,7 +99,10 @@ vi.mock("../../rich-content", () => ({
vi.mock("../../labels/resource-label-picker", () => ({
ResourceLabelPicker: () => <div data-testid="labels" />,
}));
-vi.mock("./skill-list-actions", () => ({ AddToAgentDialog: () => null }));
+vi.mock("./skill-list-actions", () => ({
+ AddToAgentDialog: ({ open }: { open: boolean }) =>
+ open ? <div data-testid="add-to-agent-dialog" /> : null,
+}));
vi.mock("@multica/ui/components/common/capability-banner", () => ({
CapabilityBanner: () => <div data-testid="capability-banner" />,
}));
@@ -110,6 +116,8 @@ const LONG_DESCRIPTION =
"Animation for product interfaces — when to animate and when not to. " +
"Triggers on: animation, easing, cubic-bezier, spring, keyframes.";
+const SOURCE_URL = "https://github.com/anthropics/skills/tree/main/animations";
+
const baseSkill: Skill = {
id: "skill-1",
workspace_id: "ws-1",
@@ -129,26 +137,24 @@ function renderPage(searchParams = new URLSearchParams()) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
- const replace = vi.fn();
+ const push = vi.fn();
const navigation: NavigationAdapter = {
- push: vi.fn(),
- replace,
+ push,
+ replace: vi.fn(),
back: vi.fn(),
pathname: "/acme/skills/skill-1",
searchParams,
hash: "",
- getShareableUrl: (path) => path,
+ getShareableUrl: (path) => `https://app.test${path}`,
};
- render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <NavigationProvider value={navigation}>
- <QueryClientProvider client={queryClient}>
- <SkillDetailPage skillId="skill-1" />
- </QueryClientProvider>
- </NavigationProvider>
- </I18nProvider>,
+ renderWithI18n(
+ <NavigationProvider value={navigation}>
+ <QueryClientProvider client={queryClient}>
+ <SkillDetailPage skillId="skill-1" />
+ </QueryClientProvider>
+ </NavigationProvider>,
);
- return { replace, queryClient };
+ return { push, queryClient };
}
/** Publishes a new server version of the skill, as a `skill:updated` event would. */
@@ -162,41 +168,179 @@ async function remoteUpdate(queryClient: QueryClient, next: Partial<Skill>) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
+function section(name: string) {
+ return screen.getByRole("heading", { name, level: 2 }).closest("section")!;
+}
+
+/** The description lives behind its panel row; opening it yields the field. */
+async function openDescription(current = LONG_DESCRIPTION) {
+ await userEvent.click(await screen.findByRole("button", { name: current }));
+ return (await screen.findByLabelText("Description")) as HTMLTextAreaElement;
+}
+
+async function openMoreActions() {
+ await userEvent.click(await screen.findByRole("button", { name: "More actions" }));
+ return screen.findByRole("menu");
+}
+
beforeEach(() => {
vi.clearAllMocks();
skillRef.current = baseSkill;
agentsRef.current = [];
- membersRef.current = [{ user_id: "user-1", role: "member" }];
+ membersRef.current = [
+ { user_id: "user-1", role: "member", name: "Ada Lovelace", avatar_url: null },
+ ];
canEditRef.current = true;
});
-describe("SkillDetailPage tabs", () => {
- it("opens on Overview and exposes exactly two tabs", async () => {
+describe("SkillDetailPage header", () => {
+ it("puts the skill under Skills in the breadcrumb, with Add to agent as the one solid action", async () => {
+ renderPage();
+ await screen.findByRole("heading", { name: "aiforui-animations", level: 1 });
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("link", { name: "Skills" })).toHaveAttribute(
+ "href",
+ "/acme/skills",
+ );
+ expect(within(header).getByText("aiforui-animations")).toBeInTheDocument();
+
+ await userEvent.click(within(header).getByRole("button", { name: "Add to agent" }));
+ expect(screen.getByTestId("add-to-agent-dialog")).toBeInTheDocument();
+ });
+
+ it("keeps copy link, update from source and delete in the ⋯ menu", async () => {
+ skillRef.current = {
+ ...baseSkill,
+ config: { origin: { type: "github", source_url: SOURCE_URL } },
+ };
+ renderPage();
+ const menu = await openMoreActions();
+ expect(
+ within(menu).getAllByRole("menuitem").map((item) => item.textContent),
+ ).toEqual(["Copy link", "Update from source", "Delete skill"]);
+ });
+
+ it("copies the skill's shareable link", async () => {
+ renderPage();
+ const menu = await openMoreActions();
+ await userEvent.click(within(menu).getByRole("menuitem", { name: "Copy link" }));
+ expect(copyTextMock).toHaveBeenCalledWith("https://app.test/acme/skills/skill-1");
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Link copied"));
+ });
+
+ it("confirms before deleting", async () => {
+ renderPage();
+ const menu = await openMoreActions();
+ await userEvent.click(within(menu).getByRole("menuitem", { name: "Delete skill" }));
+ expect(await screen.findByRole("dialog")).toHaveTextContent("Delete skill");
+ });
+
+ it("offers read-only viewers only what they can do", async () => {
+ canEditRef.current = false;
+ renderPage();
+ const menu = await openMoreActions();
+ expect(
+ within(menu).getAllByRole("menuitem").map((item) => item.textContent),
+ ).toEqual(["Copy link"]);
+ });
+});
+
+describe("SkillDetailPage body", () => {
+ it("reads as identity, then Content, Files and Used by — with no tabs", async () => {
+ renderPage();
+ expect(
+ await screen.findByRole("heading", { name: "aiforui-animations", level: 1 }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getAllByRole("heading", { level: 2 }).map((h) => h.textContent),
+ ).toEqual(["Content", "Files", "Used by"]);
+ expect(screen.queryAllByRole("tab")).toHaveLength(0);
+ });
+
+ it("previews SKILL.md without its frontmatter", async () => {
+ renderPage();
+ const preview = await screen.findByTestId("skill-content-preview");
+ expect(preview.textContent).toContain("# Interface Animations");
+ expect(preview.textContent).not.toContain("name: aiforui-animations");
+ });
+
+ it("lists supporting files with their count", async () => {
+ renderPage();
+ await screen.findByRole("heading", { name: "Files", level: 2 });
+ const files = section("Files");
+ expect(within(files).getByText("1")).toBeInTheDocument();
+ expect(within(files).getByRole("button", { name: "patterns.md" })).toBeInTheDocument();
+ });
+
+ it("opens Add to agent from the Used by section too", async () => {
+ renderPage();
+ await screen.findByRole("heading", { name: "Used by", level: 2 });
+ await userEvent.click(
+ within(section("Used by")).getByRole("button", { name: "Add to agent" }),
+ );
+ expect(screen.getByTestId("add-to-agent-dialog")).toBeInTheDocument();
+ });
+
+ it("gives read-only viewers Open instead of Edit, and no Add", async () => {
+ canEditRef.current = false;
+ renderPage();
+ await screen.findByRole("heading", { name: "Content", level: 2 });
+ expect(within(section("Content")).getByRole("button", { name: "Open" })).toBeInTheDocument();
+ expect(within(section("Content")).queryByRole("button", { name: "Edit" })).toBeNull();
+ expect(within(section("Files")).queryByRole("button", { name: "Add" })).toBeNull();
+ expect(screen.getByText("Read-only")).toBeInTheDocument();
+ });
+});
+
+describe("SkillDetailPage files view", () => {
+ it("Content › Edit opens SKILL.md in a focused editor", async () => {
+ const { push } = renderPage();
+ await screen.findByRole("heading", { name: "Content", level: 2 });
+ await userEvent.click(within(section("Content")).getByRole("button", { name: "Edit" }));
+
+ expect(push).toHaveBeenCalledWith("/acme/skills/skill-1?view=files");
+ expect(document.activeElement).toBe(
+ screen.getByRole("textbox", { name: /SKILL\.md/ }),
+ );
+ // The breadcrumb walks back to the skill, then names the open file.
+ const header = screen.getByRole("banner");
+ expect(
+ within(header).getByRole("link", { name: "aiforui-animations" }),
+ ).toHaveAttribute("href", "/acme/skills/skill-1");
+ expect(within(header).getByText("SKILL.md")).toBeInTheDocument();
+ });
+
+ it("opens a supporting file from the Files section", async () => {
renderPage();
- const tabs = await screen.findAllByRole("tab", { name: /Overview|Files/ });
- expect(tabs.map((t) => t.textContent)).toEqual(["Overview", "Files 2"]);
- // A Settings tab would only hold a delete button and a read-only
- // sentence — the skill update payload has no settings-shaped fields.
- expect(screen.queryByRole("tab", { name: "Settings" })).toBeNull();
+ await screen.findByRole("heading", { name: "Files", level: 2 });
+ await userEvent.click(
+ within(section("Files")).getByRole("button", { name: "patterns.md" }),
+ );
expect(
- screen.getByRole("tab", { name: "Overview" }).getAttribute("aria-selected"),
+ screen.getByRole("tab", { name: "patterns.md" }).getAttribute("aria-selected"),
).toBe("true");
});
- it("mirrors the active tab into ?view= so the pane survives a reload", async () => {
- const { replace } = renderPage();
- fireEvent.click(await screen.findByRole("tab", { name: "Files 2" }));
- expect(replace).toHaveBeenCalledWith("/acme/skills/skill-1?view=files");
+ it("Files › Add opens the editor on the new-file field", async () => {
+ renderPage();
+ await screen.findByRole("heading", { name: "Files", level: 2 });
+ await userEvent.click(within(section("Files")).getByRole("button", { name: "Add" }));
+ expect(await screen.findByPlaceholderText("templates/review.md")).toBeInTheDocument();
});
- it("restores the Files tab from ?view=files", async () => {
+ it("restores the files from ?view=files, the link the retired Files tab wrote", async () => {
renderPage(new URLSearchParams("view=files"));
expect(
- (await screen.findByRole("tab", { name: "Files 2" })).getAttribute(
- "aria-selected",
- ),
+ (await screen.findByRole("tab", { name: "SKILL.md" })).getAttribute("aria-selected"),
).toBe("true");
});
+
+ it("lands on the overview for an old ?tab= link", async () => {
+ renderPage(new URLSearchParams("tab=settings"));
+ expect(
+ await screen.findByRole("heading", { name: "Content", level: 2 }),
+ ).toBeInTheDocument();
+ });
});
describe("SkillDetailPage file mode", () => {
@@ -284,15 +428,71 @@ describe("SkillDetailPage edit action (MUL-5654)", () => {
});
});
+describe("SkillDetailPage properties panel", () => {
+ it("edits the name in place", async () => {
+ renderPage();
+ const field = (await screen.findByLabelText("Name")) as HTMLInputElement;
+ expect(field.value).toBe("aiforui-animations");
+ });
+
+ it("opens the whole description in a field sized for it", async () => {
+ renderPage();
+ const field = await openDescription();
+ expect(field.value).toBe(LONG_DESCRIPTION);
+ expect(Number(field.rows)).toBeGreaterThanOrEqual(4);
+ expect(
+ screen.getByText(`${LONG_DESCRIPTION.length} characters`, { exact: false }),
+ ).toBeTruthy();
+ });
+
+ it("links an imported origin to its source", async () => {
+ skillRef.current = {
+ ...baseSkill,
+ config: { origin: { type: "github", source_url: SOURCE_URL } },
+ };
+ renderPage();
+ const link = (await screen.findByRole("link", {
+ name: "Imported · GitHub",
+ })) as HTMLAnchorElement;
+ expect(link.getAttribute("href")).toBe(SOURCE_URL);
+ expect(link.getAttribute("target")).toBe("_blank");
+ expect(link.getAttribute("rel")).toContain("noopener");
+ });
+
+ it("keeps manual origins as plain text", async () => {
+ renderPage();
+ expect(await screen.findByText("Created manually")).toBeTruthy();
+ expect(
+ screen.queryByRole("link", { name: "Created manually" }),
+ ).toBeNull();
+ });
+
+ // Which source_urls are linkable is originSourceUrl's contract; its full
+ // matrix lives in ../lib/origin.test.ts. What belongs here is the row's
+ // behaviour when the helper refuses: it degrades to plain text, still
+ // naming the origin, rather than dropping the label along with the href.
+ it("degrades a refused source_url to plain text, keeping the label", async () => {
+ skillRef.current = {
+ ...baseSkill,
+ config: {
+ origin: { type: "github", source_url: "https://evil.example/skills" },
+ },
+ };
+ renderPage();
+ expect(await screen.findByText("Imported · GitHub")).toBeTruthy();
+ expect(
+ screen.queryByRole("link", { name: "Imported · GitHub" }),
+ ).toBeNull();
+ });
+});
+
describe("SkillDetailPage save pill", () => {
it("is absent while clean and floats in with a change summary once dirty", async () => {
renderPage();
- await screen.findByRole("tab", { name: "Overview" });
+ const field = await openDescription();
expect(screen.queryByRole("button", { name: /Save changes/ })).toBeNull();
- fireEvent.change(screen.getByLabelText("Description"), {
- target: { value: "changed" },
- });
+ fireEvent.change(field, { target: { value: "changed" } });
expect(screen.getByText("Changed: Description")).toBeTruthy();
expect(
screen.getByRole("button", { name: /Save changes/ }).hasAttribute("disabled"),
@@ -304,7 +504,7 @@ describe("SkillDetailPage save pill", () => {
fireEvent.change(await screen.findByLabelText("Name"), {
target: { value: "renamed-skill" },
});
- fireEvent.change(screen.getByLabelText("Description"), {
+ fireEvent.change(await openDescription(), {
target: { value: "changed" },
});
expect(screen.getByText("Changed: Name · Description")).toBeTruthy();
@@ -328,18 +528,6 @@ describe("SkillDetailPage save pill", () => {
});
});
-describe("SkillDetailPage properties", () => {
- it("renders the whole description in an editable field sized for it", async () => {
- renderPage();
- const field = (await screen.findByLabelText("Description")) as HTMLTextAreaElement;
- expect(field.value).toBe(LONG_DESCRIPTION);
- expect(Number(field.rows)).toBeGreaterThanOrEqual(4);
- expect(
- screen.getByText(`${LONG_DESCRIPTION.length} characters`, { exact: false }),
- ).toBeTruthy();
- });
-});
-
/**
* MUL-5645. Dirty state is measured against the seeded baseline, not against
* the latest server skill. The two failures that rule prevents:
@@ -358,37 +546,36 @@ describe("SkillDetailPage draft baseline (MUL-5645)", () => {
it("opens clean when the description carries a trailing newline", async () => {
skillRef.current = { ...baseSkill, description: `${LONG_DESCRIPTION}\n` };
renderPage();
- await screen.findAllByRole("tab", { name: /Overview|Files/ });
+ await screen.findByRole("heading", { name: "Content", level: 2 });
expect(screen.queryByText(/^Changed:/)).toBeNull();
});
it("stays clean after Discard on a trailing-newline description", async () => {
skillRef.current = { ...baseSkill, description: `${LONG_DESCRIPTION}\n` };
renderPage();
- const field = (await screen.findByLabelText(
- "Description",
- )) as HTMLTextAreaElement;
- fireEvent.change(field, { target: { value: "edited" } });
+ fireEvent.change(await openDescription(), { target: { value: "edited" } });
fireEvent.click(await screen.findByRole("button", { name: "Discard" }));
expect(screen.queryByText(/^Changed:/)).toBeNull();
});
it("pulls a remote edit in silently while the draft is untouched", async () => {
const { queryClient } = renderPage();
- await screen.findAllByRole("tab", { name: /Overview|Files/ });
+ await screen.findByRole("heading", { name: "Content", level: 2 });
await remoteUpdate(queryClient, { description: "Rewritten by the agent" });
// The new text reaching the field IS the fix: the old code left the editor
// frozen on the pre-update value behind a conflict banner.
- expect(await screen.findByDisplayValue("Rewritten by the agent")).toBeTruthy();
+ expect(await openDescription("Rewritten by the agent")).toHaveValue(
+ "Rewritten by the agent",
+ );
expect(screen.queryByText(CONFLICT_BANNER)).toBeNull();
expect(screen.queryByText(/^Changed:/)).toBeNull();
});
it("pulls a remote SKILL.md edit in silently too", async () => {
const { queryClient } = renderPage(new URLSearchParams("view=files"));
- await screen.findAllByRole("tab", { name: /Overview|Files/ });
+ await screen.findByRole("tab", { name: "SKILL.md" });
await remoteUpdate(queryClient, {
content: `${baseSkill.content}\n## Added remotely\n`,
@@ -402,9 +589,7 @@ describe("SkillDetailPage draft baseline (MUL-5645)", () => {
it("releases the conflict once the user reverts their own edits", async () => {
const { queryClient } = renderPage();
- const field = (await screen.findByLabelText(
- "Description",
- )) as HTMLTextAreaElement;
+ const field = await openDescription();
fireEvent.change(field, { target: { value: "my unsaved edit" } });
await remoteUpdate(queryClient, { description: "Rewritten by the agent" });
@@ -421,85 +606,12 @@ describe("SkillDetailPage draft baseline (MUL-5645)", () => {
it("keeps the draft and warns when a remote edit lands on real local edits", async () => {
const { queryClient } = renderPage();
- const field = (await screen.findByLabelText(
- "Description",
- )) as HTMLTextAreaElement;
+ const field = await openDescription();
fireEvent.change(field, { target: { value: "my unsaved edit" } });
await remoteUpdate(queryClient, { description: "Rewritten by the agent" });
expect(await screen.findByText(CONFLICT_BANNER)).toBeTruthy();
- expect(
- (screen.getByLabelText("Description") as HTMLTextAreaElement).value,
- ).toBe("my unsaved edit");
- });
-});
-
-describe("SkillDetailPage origin link", () => {
- const SOURCE_URL = "https://github.com/anthropics/skills/tree/main/animations";
-
- it("links the imported-origin chip to its source", async () => {
- skillRef.current = {
- ...baseSkill,
- config: { origin: { type: "github", source_url: SOURCE_URL } },
- };
- renderPage();
- const link = (await screen.findByRole("link", {
- name: "Imported · GitHub",
- })) as HTMLAnchorElement;
- expect(link.getAttribute("href")).toBe(SOURCE_URL);
- expect(link.getAttribute("target")).toBe("_blank");
- expect(link.getAttribute("rel")).toContain("noopener");
- });
-
- it("keeps manual origins as plain text", async () => {
- renderPage();
- expect(await screen.findByText("Created manually")).toBeTruthy();
- expect(
- screen.queryByRole("link", { name: "Created manually" }),
- ).toBeNull();
- });
-
- // Which source_urls are linkable is originSourceUrl's contract; its full
- // matrix lives in ../lib/origin.test.ts. What belongs here is the chip's
- // behaviour when the helper refuses: it degrades to plain text, still
- // naming the origin, rather than dropping the label along with the href.
- it("degrades a refused source_url to plain text, keeping the chip", async () => {
- skillRef.current = {
- ...baseSkill,
- config: {
- origin: { type: "github", source_url: "https://evil.example/skills" },
- },
- };
- renderPage();
- expect(await screen.findByText("Imported · GitHub")).toBeTruthy();
- expect(
- screen.queryByRole("link", { name: "Imported · GitHub" }),
- ).toBeNull();
- });
-});
-
-
-describe("SkillDetailPage rail", () => {
- it("keeps the read-only capability banner on the shared rail", async () => {
- canEditRef.current = false;
- renderPage();
- await screen.findAllByRole("tab", { name: /Overview|Files/ });
-
- const banner = document.body.querySelector(
- `.${RAIL_SENTINEL}.${GUTTER_SENTINEL}.pt-3`,
- );
- expect(banner).toBeTruthy();
- });
-
- it("puts the identity strip and the tab row on that same rail", async () => {
- renderPage();
- await screen.findAllByRole("tab", { name: /Overview|Files/ });
-
- const railed = document.body.querySelectorAll(
- `.${RAIL_SENTINEL}.${GUTTER_SENTINEL}`,
- );
- // Identity strip, tab row and the Overview panel at minimum.
- expect(railed.length).toBeGreaterThanOrEqual(3);
+ expect(field.value).toBe("my unsaved edit");
});
});
diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsx
index 87f75f3477..3d5b1f9473 100644
--- a/packages/views/skills/components/skill-detail-page.tsx
+++ b/packages/views/skills/components/skill-detail-page.tsx
@@ -1,22 +1,28 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import {
AlertCircle,
AlertTriangle,
- Clock3,
- Download,
+ ChevronRight,
+ File,
FileText,
- HardDrive,
+ Link2,
Loader2,
Lock,
+ MoreHorizontal,
Pencil,
Plus,
RotateCw,
Save,
Trash2,
- UserPlus,
- Users,
} from "@multica/ui/icons";
import { SkillIcon } from "../lib/skill-icon";
import type {
@@ -31,7 +37,6 @@ import { toast } from "sonner";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
-import { useTimeAgo } from "../../i18n";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import {
@@ -42,11 +47,10 @@ import {
workspaceKeys,
} from "@multica/core/workspace/queries";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import {
- runtimeDisplayLabel,
- runtimeListOptions,
-} from "@multica/core/runtimes";
+import { runtimeListOptions } from "@multica/core/runtimes";
+import { parseFrontmatter } from "@multica/core/skills/frontmatter";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
+import { IconButton } from "@multica/ui/components/common/icon-button";
import { Button, buttonVariants } from "@multica/ui/components/ui/button";
import {
Dialog,
@@ -56,39 +60,42 @@ import {
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
-import { Input } from "@multica/ui/components/ui/input";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { Textarea } from "@multica/ui/components/ui/textarea";
import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { copyText } from "@multica/ui/lib/clipboard";
import { cn } from "@multica/ui/lib/utils";
import { AppLink, useNavigation } from "../../navigation";
-import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
+import { CollectionPageState } from "../../layout/collection-page";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIconMark,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectSection,
+ ObjectSectionAction,
+ ObjectSectionCard,
+} from "../../layout/object-page";
+import { RichContent } from "../../rich-content";
import { useCanEditSkill } from "../hooks/use-can-edit-skill";
import { useSkillPermissions } from "@multica/core/permissions";
import { CapabilityBanner } from "@multica/ui/components/common/capability-banner";
-import {
- isRefreshableOrigin,
- originSourceUrl,
- readOrigin,
- totalFileCount,
- type OriginInfo,
-} from "../lib/origin";
-import { FileTree } from "./file-tree";
-import { FileViewer, isMarkdownPath, type FileMode } from "./file-viewer";
+import { isRefreshableOrigin, readOrigin } from "../lib/origin";
+import { isMarkdownPath, type FileMode } from "./file-viewer";
+import { SKILL_MD, SkillFilesEditor } from "./skill-files-editor";
+import { SkillPropertiesPanel } from "./skill-properties-panel";
import {
AddToAgentDialog,
type SkillActionsContext,
} from "./skill-list-actions";
import { RefreshSkillDialog } from "./refresh-skill-dialog";
import { useT } from "../../i18n";
-import { ResourceLabelPicker } from "../../labels/resource-label-picker";
-
-const SKILL_MD = "SKILL.md";
type DraftFile = { id?: string; path: string; content: string };
@@ -159,249 +166,147 @@ function hasLocalEdits(draft: SkillDraft, baseline: SkillDraft | null): boolean
}
/**
- * Two tabs, not three. A skill has no settings axis to speak of:
- * `UpdateSkillRequest` carries only name / description / content / config /
- * files, and edit rights are derived (creator or workspace admin) with no
- * writable counterpart — so a Settings tab would hold a delete button and a
- * read-only sentence. Delete lives in the header instead, matching the agent
- * detail page where Archive sits in the header.
+ * The page body: the skill's sections, or its files beside an editor. The
+ * files need more width than the reading column, so they take the body over
+ * instead of being a section of it. `?view=files` is also what the retired
+ * Files tab wrote, so its links still land on the files.
*/
type DetailView = "overview" | "files";
-function isDetailView(value: string | null): value is DetailView {
- return value === "overview" || value === "files";
+function readView(value: string | null): DetailView {
+ return value === "files" ? "files" : "overview";
}
-// File path validation + inline add
-
-export function useValidateNewFilePath() {
- const { t } = useT("skills");
- return (path: string, existing: string[]): string => {
- const p = path.trim();
- if (!p) return t(($) => $.detail.add_file.errors.empty);
- if (p.startsWith("/")) return t(($) => $.detail.add_file.errors.absolute);
- if (p.split("/").includes("..")) return t(($) => $.detail.add_file.errors.double_dot);
- if (p === SKILL_MD) return t(($) => $.detail.add_file.errors.reserved);
- if (existing.includes(p)) return t(($) => $.detail.add_file.errors.exists);
- // Directories are inferred from paths, not stored, so a file named after
- // one merges into that folder's node when the tree is built — it drops off
- // the rail while still sitting in the draft. Rejected in both directions:
- // a file cannot take a folder's name, and cannot take a name that an
- // existing file is already nested under.
- if (existing.some((other) => other.startsWith(`${p}/`))) {
- return t(($) => $.detail.add_file.errors.is_directory);
- }
- if (existing.some((other) => p.startsWith(`${other}/`))) {
- return t(($) => $.detail.add_file.errors.under_file);
- }
- return "";
- };
-}
+const SKILL_DETAIL_LAYOUT_ID = "multica_skill_detail_layout";
-function AddFileInline({
- existingPaths,
- onAdd,
- onCancel,
+function Notice({
+ title,
+ children,
}: {
- existingPaths: string[];
- onAdd: (path: string) => void;
- onCancel: () => void;
+ title?: React.ReactNode;
+ children: React.ReactNode;
}) {
- const { t } = useT("skills");
- const validate = useValidateNewFilePath();
- const [path, setPath] = useState("");
- const [error, setError] = useState("");
-
- const submit = () => {
- const err = validate(path, existingPaths);
- if (err) {
- setError(err);
- return;
- }
- onAdd(path.trim());
- };
-
return (
- <div className="mt-1.5">
- <Input
- autoFocus
- value={path}
- onChange={(e) => {
- setPath(e.target.value);
- setError("");
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") submit();
- if (e.key === "Escape") onCancel();
- }}
- placeholder={t(($) => $.detail.add_file.placeholder)}
- className="h-7 font-mono text-caption"
- />
- {error && (
- <p role="alert" className="mt-1 text-caption text-destructive">
- {error}
- </p>
- )}
- <div className="mt-1.5 flex items-center gap-1.5">
- <Button type="button" size="xs" onClick={submit}>
- {t(($) => $.detail.add_file.add)}
- </Button>
- <Button type="button" size="xs" variant="ghost" onClick={onCancel}>
- {t(($) => $.detail.add_file.cancel)}
- </Button>
+ <div
+ role="status"
+ aria-live="polite"
+ className="flex items-start gap-2 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-caption"
+ >
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" />
+ <div className="min-w-0 flex-1">
+ {title && <div className="font-medium text-foreground">{title}</div>}
+ <div className={cn("text-muted-foreground", title && "mt-0.5")}>
+ {children}
+ </div>
</div>
</div>
);
}
-// Header
-
-function useOriginLabel(origin: OriginInfo | null, runtime: AgentRuntime | null) {
- const { t } = useT("skills");
- if (!origin) return null;
- if (origin.type === "runtime_local") {
- return runtime
- ? t(($) => $.detail.subline.origin_runtime_named, {
- name: runtimeDisplayLabel(runtime),
- })
- : origin.provider
- ? t(($) => $.detail.subline.origin_runtime_provider, { provider: origin.provider })
- : t(($) => $.detail.subline.origin_runtime_unknown);
- }
- if (origin.type === "clawhub") return t(($) => $.detail.subline.origin_clawhub);
- if (origin.type === "skills_sh") return t(($) => $.detail.subline.origin_skills_sh);
- if (origin.type === "github") return t(($) => $.detail.subline.origin_github);
- return t(($) => $.detail.subline.origin_workspace);
-}
-
/**
- * Identity strip under the breadcrumb: mark, name, and the counts that say
- * what this skill is made of. One line, because everything a reader would
- * scroll past it for is a field on the Overview tab.
- *
- * The description is not repeated here. It used to be, above an editable copy
- * of itself two tabs' worth of chrome below — every visit to a page whose only
- * verbs are edit, add and delete paid for a read-only restatement of a field
- * the next screenful lets you change. The list this page is reached from
- * already carries the description for anyone deciding whether to open it.
- *
- * The agent detail header still has the taller form. Bringing it across is a
- * separate change to a page this branch does not otherwise touch.
+ * SKILL.md as it reads, frontmatter stripped since name and description are
+ * properties of their own. Clamped, with a toggle only when something is
+ * clamped: a long skill would otherwise push every section below it out of
+ * sight.
*/
-function SkillIdentity({
- skill,
- origin,
- originRuntime,
- agentCount,
- creator,
-}: {
- skill: Skill;
- origin: OriginInfo | null;
- originRuntime: AgentRuntime | null;
- agentCount: number;
- creator: MemberWithUser | null;
-}) {
+function SkillContentPreview({ content }: { content: string }) {
const { t } = useT("skills");
- const timeAgo = useTimeAgo();
- const originLabel = useOriginLabel(origin, originRuntime);
- const isRuntimeOrigin = origin?.type === "runtime_local";
- const sourceUrl = originSourceUrl(origin);
+ const { t: tCommon } = useT("common");
+ const body = useMemo(() => parseFrontmatter(content).body, [content]);
+ const [expanded, setExpanded] = useState(false);
+ const [clamped, setClamped] = useState(false);
+ const frameRef = useRef<HTMLDivElement | null>(null);
+ const innerRef = useRef<HTMLDivElement | null>(null);
+
+ const measure = useCallback(() => {
+ const frame = frameRef.current;
+ const inner = innerRef.current;
+ if (!frame || !inner || expanded) return;
+ setClamped(inner.scrollHeight > frame.clientHeight + 1);
+ }, [expanded]);
+
+ useLayoutEffect(() => {
+ measure();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ if (frameRef.current) observer.observe(frameRef.current);
+ if (innerRef.current) observer.observe(innerRef.current);
+ return () => observer.disconnect();
+ }, [measure, body]);
return (
- <div className="shrink-0 border-b py-3">
+ <ObjectSectionCard>
<div
- className={cn(
- PAGE_RAIL,
- PAGE_GUTTER,
- "flex flex-wrap items-center gap-x-4 gap-y-1.5",
- )}
+ ref={frameRef}
+ className={cn("relative px-4 py-3", !expanded && "max-h-80 overflow-hidden")}
>
- <div className="flex min-w-0 items-center gap-2.5">
- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border bg-muted text-muted-foreground">
- <SkillIcon className="h-4 w-4" aria-hidden="true" />
- </div>
- <h1 className="min-w-0 truncate font-mono text-title font-semibold tracking-tight">
-
- {skill.name}
- </h1>
- </div>
- <div className="flex min-w-0 flex-wrap items-center gap-x-4 gap-y-1 text-caption text-muted-foreground sm:ml-auto">
- {originLabel && (
- <span className="inline-flex min-w-0 items-center gap-1.5">
- {/* Same three-way split as the list's Source column: runtime,
- created here, imported. */}
- {isRuntimeOrigin ? (
- <HardDrive className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- ) : origin?.type === "manual" ? (
- <Pencil className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- ) : (
- <Download className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- )}
- {sourceUrl ? (
- <Tooltip>
- <TooltipTrigger
- render={
- <a
- href={sourceUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="truncate hover:underline"
- >
- {originLabel}
- </a>
- }
- />
- <TooltipContent side="top">{sourceUrl}</TooltipContent>
- </Tooltip>
- ) : (
- <span className="truncate">{originLabel}</span>
- )}
- </span>
- )}
- <span className="inline-flex items-center gap-1.5">
- <FileText className="h-3.5 w-3.5" aria-hidden="true" />
- {t(($) => $.detail.header.files, { count: totalFileCount(skill) })}
- </span>
- <span className="inline-flex items-center gap-1.5">
- <Users className="h-3.5 w-3.5" aria-hidden="true" />
- {t(($) => $.detail.header.used_by, { count: agentCount })}
- </span>
- <span className="inline-flex items-center gap-1.5">
- <Clock3 className="h-3.5 w-3.5" aria-hidden="true" />
- {creator
- ? t(($) => $.detail.header.updated_by, {
- when: timeAgo(skill.updated_at),
- name: creator.name,
- })
- : t(($) => $.detail.header.updated, { when: timeAgo(skill.updated_at) })}
- </span>
+ <div ref={innerRef} data-testid="skill-content-preview">
+ <RichContent
+ content={body || t(($) => $.file_viewer.no_content)}
+ density="document"
+ phase="settled"
+ />
</div>
+ {clamped && !expanded && (
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-gradient-to-t from-card to-transparent"
+ />
+ )}
</div>
- </div>
+ {(clamped || expanded) && (
+ <button
+ type="button"
+ onClick={() => setExpanded((value) => !value)}
+ className="flex h-9 w-full items-center px-4 text-caption text-muted-foreground transition-colors hover:text-foreground focus-visible:text-foreground focus-visible:outline-none"
+ >
+ {expanded
+ ? tCommon(($) => $.expandable_description.collapse)
+ : tCommon(($) => $.expandable_description.expand)}
+ </button>
+ )}
+ </ObjectSectionCard>
);
}
-// Overview tab
-
-function PropertyRow({
- label,
- htmlFor,
- children,
+function SupportingFileList({
+ paths,
+ onOpen,
}: {
- label: string;
- htmlFor?: string;
- children: React.ReactNode;
+ paths: string[];
+ onOpen: (path: string) => void;
}) {
+ const { t } = useT("skills");
+ if (paths.length === 0) {
+ return (
+ <div className="rounded-lg border border-dashed px-3 py-6 text-center text-caption text-muted-foreground">
+ {t(($) => $.detail.files.supporting_empty)}
+ </div>
+ );
+ }
return (
- <div className="grid gap-1.5 py-2.5 sm:grid-cols-[128px_minmax(0,1fr)] sm:gap-4">
- <label
- htmlFor={htmlFor}
- className="pt-1.5 text-caption text-muted-foreground sm:text-body"
- >
- {label}
- </label>
- <div className="min-w-0">{children}</div>
- </div>
+ <ObjectSectionCard>
+ {[...paths].sort().map((path) => {
+ const Icon = isMarkdownPath(path) ? FileText : File;
+ return (
+ <button
+ key={path}
+ type="button"
+ onClick={() => onOpen(path)}
+ className="group/file flex h-10 w-full items-center gap-2.5 px-3 text-left text-body transition-colors hover:bg-accent/50 focus-visible:bg-accent/50 focus-visible:outline-none"
+ >
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate font-mono text-caption">
+ {path}
+ </span>
+ <ChevronRight
+ className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/file:opacity-100"
+ aria-hidden="true"
+ />
+ </button>
+ );
+ })}
+ </ObjectSectionCard>
);
}
@@ -415,9 +320,9 @@ function UsedByList({ agents }: { agents: Agent[] }) {
);
}
return (
- <ul className="divide-y overflow-hidden rounded-lg border bg-card">
+ <ObjectSectionCard>
{agents.map((a) => (
- <li key={a.id} className="flex items-center gap-2.5 px-3 py-2.5">
+ <div key={a.id} className="flex min-h-11 items-center gap-2.5 px-3 py-2">
<ActorAvatar
name={a.name}
initials={a.name.slice(0, 2).toUpperCase()}
@@ -433,318 +338,9 @@ function UsedByList({ agents }: { agents: Agent[] }) {
</div>
)}
</div>
- </li>
- ))}
- </ul>
- );
-}
-
-function OverviewTab({
- skill,
- name,
- description,
- canEdit,
- creatorName,
- skillAgents,
- onNameChange,
- onDescriptionChange,
- onAddToAgents,
-}: {
- skill: Skill;
- name: string;
- description: string;
- canEdit: boolean;
- creatorName: string | null;
- skillAgents: Agent[];
- onNameChange: (value: string) => void;
- onDescriptionChange: (value: string) => void;
- onAddToAgents: () => void;
-}) {
- const { t } = useT("skills");
-
- return (
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-4 sm:py-6 md:py-8")}>
- <div className="w-full max-w-3xl">
- <section>
- <h2 className="text-title-sm font-medium">{t(($) => $.detail.overview.properties)}</h2>
- <details className="mt-1 text-caption text-muted-foreground">
- <summary className="cursor-pointer rounded-sm py-2 focus-visible:outline-2 focus-visible:outline-ring">
- {t(($) => $.detail.overview.properties_help)}
- </summary>
- <p className="mt-1">{t(($) => $.detail.overview.properties_hint)}</p>
- </details>
- <div className="mt-4 divide-y">
- <PropertyRow label={t(($) => $.detail.overview.name)} htmlFor="skill-name">
- <Input
- id="skill-name"
- value={name}
- readOnly={!canEdit}
- onChange={(e) => onNameChange(e.target.value)}
- placeholder={t(($) => $.detail.name_placeholder)}
- className="font-mono text-body read-only:cursor-default"
- />
- </PropertyRow>
-
- <PropertyRow
- label={t(($) => $.detail.overview.description)}
- htmlFor="skill-description"
- >
- {/* Real descriptions run 500–900 characters (they carry the
- trigger vocabulary an agent matches on), so this field is
- sized for the data rather than the two rows it had before. */}
- <Textarea
- id="skill-description"
- value={description}
- readOnly={!canEdit}
- onChange={(e) => onDescriptionChange(e.target.value)}
- placeholder={t(($) => $.detail.description_placeholder)}
- rows={6}
- className="text-body leading-relaxed read-only:cursor-default"
- />
- <div className="mt-1.5 flex flex-wrap justify-between gap-x-4 gap-y-1 text-caption text-muted-foreground">
- <p>{t(($) => $.detail.overview.description_hint)}</p>
- <span className="tabular-nums">
- {t(($) => $.detail.overview.character_count, { count: description.length })}
- </span>
- </div>
- </PropertyRow>
-
- <PropertyRow label={t(($) => $.detail.overview.labels)}>
- <ResourceLabelPicker
- resourceType="skill"
- resourceId={skill.id}
- canEdit={canEdit}
- />
- </PropertyRow>
- </div>
- </section>
-
- <section className="mt-10">
- <div className="flex items-center justify-between gap-3">
- <h2 className="min-w-0 text-title-sm font-medium">
- {t(($) => $.detail.overview.used_by, { count: skillAgents.length })}
- </h2>
- <Button
- variant="outline"
- size="xs"
- className="shrink-0 gap-1"
- onClick={onAddToAgents}
- >
- <UserPlus className="h-3 w-3" />
- {t(($) => $.actions.add_to_agent)}
- </Button>
- </div>
- <div className="mt-3">
- <UsedByList agents={skillAgents} />
- </div>
- </section>
-
- <p className="mt-10 rounded-lg bg-muted px-3 py-2.5 text-caption leading-relaxed text-muted-foreground">
- {canEdit
- ? t(($) => $.detail.overview.permissions_owner)
- : creatorName
- ? t(($) => $.detail.overview.permissions_locked_creator, { name: creatorName })
- : t(($) => $.detail.overview.permissions_locked)}
- </p>
- </div>
- </div>
- );
-}
-
-// Files tab
-
-function FilesTab({
- filePaths,
- selectedPath,
- selectedContent,
- mode,
- canEdit,
- addingFile,
- focusEditor,
- onSelectPath,
- onModeChange,
- onStartAddFile,
- onAddFile,
- onCancelAddFile,
- onDeleteFile,
- onRenameFile,
- onEditFile,
- onContentChange,
- onFocusHandled,
-}: {
- filePaths: string[];
- selectedPath: string;
- selectedContent: string;
- mode: FileMode;
- canEdit: boolean;
- addingFile: boolean;
- focusEditor: boolean;
- onSelectPath: (path: string) => void;
- onModeChange: (mode: FileMode) => void;
- onStartAddFile: () => void;
- onAddFile: (path: string) => void;
- onCancelAddFile: () => void;
- onDeleteFile: (path?: string) => void;
- onRenameFile: (from: string, to: string) => void;
- onEditFile: (path: string) => void;
- onContentChange: (content: string) => void;
- onFocusHandled: () => void;
-}) {
- const { t } = useT("skills");
- const validatePath = useValidateNewFilePath();
- const supportingPaths = filePaths.filter((p) => p !== SKILL_MD);
- const isMd = isMarkdownPath(selectedPath);
- // Absent for read-only viewers so the tree never offers an action it would
- // then refuse. Both rails get the same object: SKILL.md keeps Edit and loses
- // rename/delete, which the tree derives from reservedPath.
- const treeActions = canEdit
- ? {
- onEdit: onEditFile,
- validatePath,
- onRename: onRenameFile,
- onDelete: onDeleteFile,
- reservedPath: SKILL_MD,
- }
- : undefined;
-
- return (
- <div className={cn(PAGE_RAIL, "flex min-h-full flex-col md:h-full md:flex-row")}>
- {/* The file list IS the second-level navigation, so it uses the same
- rail treatment as the agent detail page's capability/settings nav
- instead of inventing a third sidebar style. */}
- <aside
- role="tablist"
- aria-orientation="vertical"
- aria-label={t(($) => $.detail.files.list_aria)}
- className={cn(
- "shrink-0 border-b border-surface-border py-3 md:w-52 md:overflow-y-auto md:border-b-0 md:border-r md:py-4",
- PAGE_GUTTER,
- )}
- >
- <p className="px-2.5 pb-1 text-micro font-semibold uppercase tracking-wider text-muted-foreground">
- {t(($) => $.detail.files.main)}
- </p>
- <FileTree
- actions={treeActions}
- filePaths={[SKILL_MD]}
- selectedPath={selectedPath}
- onSelect={onSelectPath}
- />
-
- <p className="px-2.5 pb-1 pt-3 text-micro font-semibold uppercase tracking-wider text-muted-foreground">
- {t(($) => $.detail.files.supporting, { count: supportingPaths.length })}
- </p>
- {supportingPaths.length > 0 ? (
- <FileTree
- actions={treeActions}
- filePaths={supportingPaths}
- selectedPath={selectedPath}
- onSelect={onSelectPath}
- />
- ) : (
- !addingFile && (
- <p className="px-2.5 py-1 text-caption text-muted-foreground">
- {t(($) => $.detail.files.supporting_empty)}
- </p>
- )
- )}
-
- {canEdit &&
- (addingFile ? (
- <AddFileInline
- existingPaths={filePaths}
- onAdd={onAddFile}
- onCancel={onCancelAddFile}
- />
- ) : (
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={onStartAddFile}
- className="mt-2 h-8 w-full justify-start px-2.5 text-muted-foreground"
- >
- <Plus className="h-3.5 w-3.5" />
- {t(($) => $.detail.files.add_file)}
- </Button>
- ))}
- </aside>
-
- <section className="flex min-h-[32rem] min-w-0 flex-1 flex-col md:min-h-0">
- <div className="flex h-10 shrink-0 items-center gap-3 border-b px-3 sm:px-4">
- <span className="truncate font-mono text-caption text-muted-foreground">
- {selectedPath}
- </span>
- <div className="ml-auto flex shrink-0 items-center gap-1">
- {isMd && (
- // The second segment is named for what it does for THIS viewer:
- // "Edit" when the pane it opens accepts typing, "Plain text"
- // when the same pane is read-only. Same mode either way — only
- // the promise differs, and offering an edit the page would
- // refuse is the thing this rail is careful not to do.
- <div
- role="group"
- aria-label={t(($) => $.detail.files.mode_aria)}
- className="flex items-center gap-0.5 rounded-md bg-muted p-0.5"
- >
- {(["preview", "raw"] as const).map((value) => (
- <button
- key={value}
- type="button"
- aria-pressed={mode === value}
- onClick={() => onModeChange(value)}
- className={cn(
- "h-6 rounded-xs px-2 text-caption font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- mode === value
- ? "bg-surface text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground",
- )}
- >
- {value === "preview"
- ? t(($) => $.detail.files.mode_preview)
- : canEdit
- ? t(($) => $.detail.files.mode_edit)
- : t(($) => $.detail.files.mode_raw)}
- </button>
- ))}
- </div>
- )}
- {selectedPath !== SKILL_MD && canEdit && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- onClick={() => onDeleteFile()}
- className="text-muted-foreground hover:text-destructive"
- aria-label={t(($) => $.detail.delete_file)}
- >
- <Trash2 className="h-3.5 w-3.5" />
- </Button>
- }
- />
- <TooltipContent>{t(($) => $.detail.delete_file)}</TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
-
- <div className="min-h-0 flex-1">
- <FileViewer
- key={selectedPath}
- path={selectedPath}
- content={selectedContent}
- mode={mode}
- readOnly={!canEdit}
- autoFocus={focusEditor}
- onChange={onContentChange}
- onFocusHandled={onFocusHandled}
- />
</div>
- </section>
- </div>
+ ))}
+ </ObjectSectionCard>
);
}
@@ -752,6 +348,7 @@ function FilesTab({
export function SkillDetailPage({ skillId }: { skillId: string }) {
const { t } = useT("skills");
+ const { t: tCommon } = useT("common");
const wsId = useWorkspaceId();
const qc = useQueryClient();
const paths = useWorkspacePaths();
@@ -815,28 +412,16 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
const urlView = navigation.searchParams.get("view");
const [activeView, setActiveView] = useState<DetailView>(() =>
- isDetailView(urlView) ? urlView : "overview",
+ readView(urlView),
);
const lastUrlViewRef = useRef(urlView);
useEffect(() => {
if (urlView === lastUrlViewRef.current) return;
lastUrlViewRef.current = urlView;
- setActiveView(isDetailView(urlView) ? urlView : "overview");
+ setActiveView(readView(urlView));
}, [urlView]);
- const selectView = useCallback(
- (next: DetailView) => {
- setActiveView(next);
- const params = new URLSearchParams(navigation.searchParams);
- if (next === "overview") params.delete("view");
- else params.set("view", next);
- const query = params.toString();
- navigation.replace(`${navigation.pathname}${query ? `?${query}` : ""}`);
- },
- [navigation],
- );
-
const draftRef = useRef({ name, description, content, files });
draftRef.current = { name, description, content, files };
@@ -977,6 +562,33 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
dirtySummary.descChanged ||
dirtySummary.changedFileCount > 0;
+ const viewHref = (view: DetailView) => {
+ const params = new URLSearchParams(navigation.searchParams);
+ if (view === "overview") params.delete("view");
+ else params.set("view", view);
+ const query = params.toString();
+ return `${navigation.pathname}${query ? `?${query}` : ""}`;
+ };
+
+ /**
+ * Opens the files on `path`. "Edit" owes three things in one gesture: the
+ * file is open, the pane is the editor rather than the preview, and the
+ * caret is in it — fewer would leave the user a click away from typing.
+ */
+ const openFiles = (
+ path: string,
+ { edit = false, add = false }: { edit?: boolean; add?: boolean } = {},
+ ) => {
+ setSelectedPath(path);
+ if (edit && canEdit) {
+ setFileMode("raw");
+ setFocusPath(path);
+ }
+ if (add && canEdit) setAddingFile(true);
+ setActiveView("files");
+ navigation.push(viewHref("files"));
+ };
+
const handleSave = async () => {
if (!skill || !canEdit) return;
const trimmedName = name.trim();
@@ -1031,6 +643,14 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
}
};
+ const handleCopyLink = () => {
+ void copyText(navigation.getShareableUrl(paths.skillDetail(skillId))).then(
+ (ok) => {
+ if (ok) toast.success(t(($) => $.detail.menu.link_copied));
+ },
+ );
+ };
+
const handleAddFile = (path: string) => {
setFiles((prev) => [...prev, { path, content: "" }]);
setSelectedPath(path);
@@ -1045,10 +665,6 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
if (path === selectedPath) setSelectedPath(SKILL_MD);
};
- // "Edit" from a row menu is one gesture that owes three things: the file is
- // open, the pane is the editor rather than the preview, and the caret is in
- // it. Doing fewer would leave the user another click away from typing, which
- // is the whole reason the entry exists.
const handleEditFile = useCallback(
(path: string) => {
if (!canEdit) return;
@@ -1085,56 +701,66 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
};
const supportingQueryDown = !!agentsError || !!membersError || !!runtimesError;
+ const listSegment = { href: paths.skills(), label: t(($) => $.page.title) };
if (isLoading) {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-3 w-3 rounded-xs" />
- <Skeleton className="h-4 w-40" />
- </div>
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "space-y-3 py-6")}>
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-5/6" />
- <Skeleton className="h-4 w-3/4" />
+ <ObjectPage
+ layoutId={SKILL_DETAIL_LAYOUT_ID}
+ segments={[listSegment]}
+ leaf={<Skeleton className="h-4 w-40" />}
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-xl" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-5 w-48" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
+ </div>
+ <div className="space-y-3">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-5/6" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
</div>
- </div>
+ </ObjectPage>
);
}
if (error || !skill) {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-3">
- <Button
- variant="ghost"
- size="xs"
- render={<AppLink href={paths.skills()} />}
- nativeButton={false}
- >
- {t(($) => $.detail.all_skills)}
- </Button>
- </div>
- <div className="flex flex-1 flex-col items-center justify-center gap-2 text-center">
- <AlertCircle className="h-8 w-8 text-faint-foreground" />
- <p className="text-body font-medium">{t(($) => $.detail.not_found.title)}</p>
- <p className="max-w-xs text-caption text-muted-foreground">
- {error instanceof Error ? error.message : t(($) => $.detail.not_found.fallback)}
- </p>
- <AppLink
- href={paths.skills()}
- className={`${buttonVariants({ variant: "outline", size: "xs" })} mt-2`}
- >
- {t(($) => $.detail.not_found.back)}
- </AppLink>
- </div>
- </div>
+ <ObjectPage
+ layoutId={SKILL_DETAIL_LAYOUT_ID}
+ segments={[listSegment]}
+ leaf={
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.detail.not_found.title)}
+ </span>
+ }
+ >
+ <CollectionPageState
+ role="alert"
+ icon={AlertCircle}
+ title={t(($) => $.detail.not_found.title)}
+ description={
+ error instanceof Error ? error.message : t(($) => $.detail.not_found.fallback)
+ }
+ actions={
+ <AppLink
+ href={paths.skills()}
+ className={buttonVariants({ variant: "outline", size: "xs" })}
+ >
+ {t(($) => $.detail.not_found.back)}
+ </AppLink>
+ }
+ />
+ </ObjectPage>
);
}
- // Segments reuse the overview field labels so the pill and the fields it
- // points at never use different words for the same thing.
+ // Segments reuse the property labels so the pill and the fields it points
+ // at never use different words for the same thing.
const changedParts = [
dirtySummary.nameChanged ? t(($) => $.detail.overview.name) : null,
dirtySummary.descChanged ? t(($) => $.detail.overview.description) : null,
@@ -1145,204 +771,236 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
: null,
].filter((part): part is string => part !== null);
- const TABS: { id: DetailView; label: string }[] = [
- { id: "overview", label: t(($) => $.detail.tabs.overview) },
- {
- id: "files",
- label: t(($) => $.detail.tabs.files, { count: totalFileCount(skill) }),
- },
- ];
+ const canRefresh = canEdit && !!origin && isRefreshableOrigin(origin);
+ const displayName = name.trim() || skill.name;
+ const supportingPaths = filePaths.filter((p) => p !== SKILL_MD);
- return (
- // relative: positioning anchor for the floating save pill (page-centered,
- // same rule as the skills list batch toolbar).
- <div className="relative flex flex-1 min-h-0 flex-col">
- <BreadcrumbHeader
- segments={[{ href: paths.skills(), label: t(($) => $.page.title) }]}
- leaf={
- <span className="truncate font-mono text-caption text-foreground">
- {skill.name}
- </span>
- }
- actions={
- <>
- {!canEdit && (
- <span className="inline-flex items-center gap-1 text-caption text-muted-foreground">
- <Lock className="h-3 w-3" />
- {t(($) => $.detail.read_only)}
- </span>
- )}
- {canEdit && origin && isRefreshableOrigin(origin) && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="xs"
- className="gap-1"
- onClick={() => setConfirmRefresh(true)}
- >
- <RotateCw className="h-3 w-3" />
- {t(($) => $.detail.refresh.button)}
- </Button>
- }
- />
- <TooltipContent>
- {t(($) => $.detail.refresh.tooltip)}
- </TooltipContent>
- </Tooltip>
- )}
- <Button
- variant="outline"
- size="xs"
- className="gap-1"
- onClick={() => setShowAddToAgents(true)}
- >
- <UserPlus className="h-3 w-3" />
- {t(($) => $.actions.add_to_agent)}
- </Button>
- {canEdit && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setConfirmDelete(true)}
- className="text-muted-foreground hover:text-destructive"
- aria-label={t(($) => $.detail.delete_aria)}
- >
- <Trash2 className="h-3.5 w-3.5" />
- </Button>
- }
- />
- <TooltipContent>{t(($) => $.detail.delete_tooltip)}</TooltipContent>
- </Tooltip>
- )}
- </>
- }
+ const notices = [
+ !canEdit && (
+ <CapabilityBanner
+ key="capability"
+ reason={skillPermissions.canEdit.reason}
+ resource="skill"
+ ownerName={creator?.name}
/>
+ ),
+ supportingQueryDown && (
+ <Notice key="supporting">{t(($) => $.detail.supporting_data_warning)}</Notice>
+ ),
+ conflictPending && canEdit && (
+ <Notice key="conflict" title={t(($) => $.detail.conflict_banner.title)}>
+ {t(($) => $.detail.conflict_banner.body)}
+ </Notice>
+ ),
+ ].filter(Boolean);
+
+ const headerActions = (
+ <>
+ <Button size="sm" onClick={() => setShowAddToAgents(true)}>
+ <Plus />
+ {t(($) => $.actions.add_to_agent)}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={tCommon(($) => $.more_actions)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ >
+ <MoreHorizontal />
+ </IconButton>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-auto min-w-48">
+ <DropdownMenuItem onClick={handleCopyLink}>
+ <Link2 />
+ {t(($) => $.detail.menu.copy_link)}
+ </DropdownMenuItem>
+ {canRefresh && (
+ <DropdownMenuItem onClick={() => setConfirmRefresh(true)}>
+ <RotateCw />
+ {t(($) => $.actions.refresh)}
+ </DropdownMenuItem>
+ )}
+ {canEdit && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setConfirmDelete(true)}
+ >
+ <Trash2 />
+ {t(($) => $.detail.menu.delete)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </>
+ );
- {!canEdit && (
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "pt-3")}>
- <CapabilityBanner
- reason={skillPermissions.canEdit.reason}
- resource="skill"
- ownerName={creator?.name}
- />
- </div>
- )}
+ const panel = origin && (
+ <SkillPropertiesPanel
+ skill={skill}
+ name={name}
+ description={description}
+ canEdit={canEdit}
+ origin={origin}
+ originRuntime={originRuntime}
+ creator={creator}
+ onNameChange={setName}
+ onDescriptionChange={setDescription}
+ />
+ );
- {supportingQueryDown && (
- <div
- role="status"
- className="shrink-0 border-b bg-warning/10 py-2 text-caption text-muted-foreground"
- >
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex items-start gap-2")}>
- <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" />
- <span>{t(($) => $.detail.supporting_data_warning)}</span>
- </div>
- </div>
- )}
+ const skillLeaf = (
+ <span className="flex min-w-0 items-center gap-1.5 text-foreground">
+ <SkillIcon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <span className="truncate">{displayName}</span>
+ </span>
+ );
- <SkillIdentity
- skill={skill}
- origin={origin}
- originRuntime={originRuntime}
- agentCount={skillAgents.length}
- creator={creator}
- />
+ const overview = (
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8 pb-24")}>
+ <div className="space-y-4">
+ <ObjectIdentity
+ media={<ObjectIconMark icon={SkillIcon} />}
+ title={displayName}
+ description={description.trim() || undefined}
+ trailing={
+ !canEdit && (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-caption text-muted-foreground">
+ <Lock className="size-3" aria-hidden="true" />
+ {t(($) => $.detail.read_only)}
+ </span>
+ )
+ }
+ />
+ {notices.length > 0 && <div className="space-y-2">{notices}</div>}
+ </div>
- <div
- className="shrink-0 overflow-x-auto border-b"
- role="tablist"
- aria-label={t(($) => $.detail.tabs.aria)}
+ <ObjectSection
+ title={t(($) => $.detail.sections.content)}
+ count={<span className="font-mono">{SKILL_MD}</span>}
+ action={
+ canEdit ? (
+ <ObjectSectionAction
+ icon={Pencil}
+ onClick={() => openFiles(SKILL_MD, { edit: true })}
+ >
+ {t(($) => $.detail.sections.edit)}
+ </ObjectSectionAction>
+ ) : (
+ <ObjectSectionAction
+ icon={FileText}
+ onClick={() => openFiles(SKILL_MD)}
+ >
+ {t(($) => $.detail.sections.open)}
+ </ObjectSectionAction>
+ )
+ }
>
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex items-center gap-6")}>
- {TABS.map((tab) => (
- <button
- key={tab.id}
- type="button"
- role="tab"
- aria-selected={activeView === tab.id}
- onClick={() => selectView(tab.id)}
- className={cn(
- "relative shrink-0 py-3 text-body font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
- activeView === tab.id
- ? "text-foreground after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 after:bg-foreground"
- : "text-muted-foreground hover:text-foreground",
- )}
+ <SkillContentPreview content={content} />
+ </ObjectSection>
+
+ <ObjectSection
+ title={t(($) => $.detail.sections.files)}
+ count={supportingPaths.length}
+ action={
+ canEdit && (
+ <ObjectSectionAction
+ icon={Plus}
+ onClick={() => openFiles(selectedPath, { add: true })}
>
- {tab.label}
- </button>
- ))}
- </div>
- </div>
+ {t(($) => $.detail.sections.add)}
+ </ObjectSectionAction>
+ )
+ }
+ >
+ <SupportingFileList paths={supportingPaths} onOpen={openFiles} />
+ </ObjectSection>
+
+ <ObjectSection
+ title={t(($) => $.table.used_by)}
+ count={skillAgents.length}
+ action={
+ <ObjectSectionAction icon={Plus} onClick={() => setShowAddToAgents(true)}>
+ {t(($) => $.actions.add_to_agent)}
+ </ObjectSectionAction>
+ }
+ >
+ <UsedByList agents={skillAgents} />
+ </ObjectSection>
+ </div>
+ );
- {conflictPending && canEdit && (
- <div
- role="status"
- aria-live="polite"
- className="shrink-0 border-b border-warning/30 bg-warning/10 py-2 text-caption"
- >
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex items-start gap-2")}>
- <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" />
- <div className="flex-1">
- <div className="font-medium text-foreground">
- {t(($) => $.detail.conflict_banner.title)}
- </div>
- <div className="mt-0.5 text-muted-foreground">
- {t(($) => $.detail.conflict_banner.body)}
- </div>
- </div>
- </div>
+ const filesView = (
+ <div className="flex min-h-full flex-col md:h-full">
+ {notices.length > 0 && (
+ <div className={cn(PAGE_RAIL, PAGE_GUTTER, "space-y-2 pt-3")}>
+ {notices}
</div>
)}
+ <div className="flex min-h-0 flex-1 flex-col">
+ <SkillFilesEditor
+ filePaths={filePaths}
+ selectedPath={selectedPath}
+ selectedContent={selectedContent}
+ mode={fileMode}
+ canEdit={canEdit}
+ addingFile={addingFile}
+ focusEditor={focusPath === selectedPath}
+ onSelectPath={setSelectedPath}
+ onModeChange={setFileMode}
+ onStartAddFile={() => setAddingFile(true)}
+ onAddFile={handleAddFile}
+ onCancelAddFile={() => setAddingFile(false)}
+ onDeleteFile={handleDeleteFile}
+ onRenameFile={handleRenameFile}
+ onEditFile={handleEditFile}
+ onContentChange={handleFileContentChange}
+ onFocusHandled={handleFocusHandled}
+ />
+ </div>
+ </div>
+ );
- <div
- className={cn(
- "min-h-0 flex-1 overflow-y-auto",
- activeView === "files" && "md:overflow-hidden",
- )}
+ return (
+ // relative: positioning anchor for the floating save pill (page-centered,
+ // same rule as the skills list batch toolbar).
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ <ObjectPage
+ layoutId={SKILL_DETAIL_LAYOUT_ID}
+ segments={
+ activeView === "files"
+ ? [
+ listSegment,
+ {
+ href: paths.skillDetail(skill.id),
+ label: displayName,
+ className: "min-w-0 max-w-72 truncate",
+ },
+ ]
+ : [listSegment]
+ }
+ leaf={
+ activeView === "files" ? (
+ <span className="truncate font-mono text-caption text-foreground">
+ {selectedPath}
+ </span>
+ ) : (
+ skillLeaf
+ )
+ }
+ actions={headerActions}
+ panel={panel}
>
- {activeView === "overview" ? (
- <OverviewTab
- skill={skill}
- name={name}
- description={description}
- canEdit={canEdit}
- creatorName={creator?.name ?? null}
- skillAgents={skillAgents}
- onNameChange={setName}
- onDescriptionChange={setDescription}
- onAddToAgents={() => setShowAddToAgents(true)}
- />
- ) : (
- <FilesTab
- filePaths={filePaths}
- selectedPath={selectedPath}
- selectedContent={selectedContent}
- mode={fileMode}
- canEdit={canEdit}
- addingFile={addingFile}
- focusEditor={focusPath === selectedPath}
- onSelectPath={setSelectedPath}
- onModeChange={setFileMode}
- onStartAddFile={() => setAddingFile(true)}
- onAddFile={handleAddFile}
- onCancelAddFile={() => setAddingFile(false)}
- onDeleteFile={handleDeleteFile}
- onRenameFile={handleRenameFile}
- onEditFile={handleEditFile}
- onContentChange={handleFileContentChange}
- onFocusHandled={handleFocusHandled}
- />
- )}
- </div>
+ {activeView === "files" ? filesView : overview}
+ </ObjectPage>
- {/* Page-level so it covers edits made on either tab. Dirty-only and
- floating, matching the skills list batch toolbar; anchored to the
- page root (relative), NOT the viewport. */}
+ {/* Dirty-only and floating, matching the skills list batch toolbar;
+ anchored to the page root (relative), NOT the viewport. */}
{canEdit && isDirty && (
<div
role="status"
diff --git a/packages/views/skills/components/skill-file-path.test.tsx b/packages/views/skills/components/skill-file-path.test.tsx
index c5338868c8..b36059dace 100644
--- a/packages/views/skills/components/skill-file-path.test.tsx
+++ b/packages/views/skills/components/skill-file-path.test.tsx
@@ -4,7 +4,7 @@
import { afterEach, describe, expect, it } from "vitest";
import { cleanup } from "@testing-library/react";
import { renderWithI18n } from "../../test/i18n";
-import { useValidateNewFilePath } from "./skill-detail-page";
+import { useValidateNewFilePath } from "./skill-files-editor";
afterEach(cleanup);
diff --git a/packages/views/skills/components/skill-files-editor.tsx b/packages/views/skills/components/skill-files-editor.tsx
new file mode 100644
index 0000000000..031d88f0f5
--- /dev/null
+++ b/packages/views/skills/components/skill-files-editor.tsx
@@ -0,0 +1,297 @@
+"use client";
+
+import { useState } from "react";
+import { Plus, Trash2 } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
+import { useT } from "../../i18n";
+import { FileTree } from "./file-tree";
+import { FileViewer, isMarkdownPath, type FileMode } from "./file-viewer";
+
+export const SKILL_MD = "SKILL.md";
+
+// File path validation + inline add
+
+export function useValidateNewFilePath() {
+ const { t } = useT("skills");
+ return (path: string, existing: string[]): string => {
+ const p = path.trim();
+ if (!p) return t(($) => $.detail.add_file.errors.empty);
+ if (p.startsWith("/")) return t(($) => $.detail.add_file.errors.absolute);
+ if (p.split("/").includes("..")) return t(($) => $.detail.add_file.errors.double_dot);
+ if (p === SKILL_MD) return t(($) => $.detail.add_file.errors.reserved);
+ if (existing.includes(p)) return t(($) => $.detail.add_file.errors.exists);
+ // Directories are inferred from paths, not stored, so a file named after
+ // one merges into that folder's node when the tree is built — it drops off
+ // the rail while still sitting in the draft. Rejected in both directions:
+ // a file cannot take a folder's name, and cannot take a name that an
+ // existing file is already nested under.
+ if (existing.some((other) => other.startsWith(`${p}/`))) {
+ return t(($) => $.detail.add_file.errors.is_directory);
+ }
+ if (existing.some((other) => p.startsWith(`${other}/`))) {
+ return t(($) => $.detail.add_file.errors.under_file);
+ }
+ return "";
+ };
+}
+
+function AddFileInline({
+ existingPaths,
+ onAdd,
+ onCancel,
+}: {
+ existingPaths: string[];
+ onAdd: (path: string) => void;
+ onCancel: () => void;
+}) {
+ const { t } = useT("skills");
+ const validate = useValidateNewFilePath();
+ const [path, setPath] = useState("");
+ const [error, setError] = useState("");
+
+ const submit = () => {
+ const err = validate(path, existingPaths);
+ if (err) {
+ setError(err);
+ return;
+ }
+ onAdd(path.trim());
+ };
+
+ return (
+ <div className="mt-1.5">
+ <Input
+ autoFocus
+ value={path}
+ onChange={(e) => {
+ setPath(e.target.value);
+ setError("");
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") submit();
+ if (e.key === "Escape") onCancel();
+ }}
+ placeholder={t(($) => $.detail.add_file.placeholder)}
+ className="h-7 font-mono text-caption"
+ />
+ {error && (
+ <p role="alert" className="mt-1 text-caption text-destructive">
+ {error}
+ </p>
+ )}
+ <div className="mt-1.5 flex items-center gap-1.5">
+ <Button type="button" size="xs" onClick={submit}>
+ {t(($) => $.detail.add_file.add)}
+ </Button>
+ <Button type="button" size="xs" variant="ghost" onClick={onCancel}>
+ {t(($) => $.detail.add_file.cancel)}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The skill's files as a tree beside the open file. Wider than an object
+ * page's reading column, so it fills the page body on its own rather than
+ * sitting in a section.
+ */
+export function SkillFilesEditor({
+ filePaths,
+ selectedPath,
+ selectedContent,
+ mode,
+ canEdit,
+ addingFile,
+ focusEditor,
+ onSelectPath,
+ onModeChange,
+ onStartAddFile,
+ onAddFile,
+ onCancelAddFile,
+ onDeleteFile,
+ onRenameFile,
+ onEditFile,
+ onContentChange,
+ onFocusHandled,
+}: {
+ filePaths: string[];
+ selectedPath: string;
+ selectedContent: string;
+ mode: FileMode;
+ canEdit: boolean;
+ addingFile: boolean;
+ focusEditor: boolean;
+ onSelectPath: (path: string) => void;
+ onModeChange: (mode: FileMode) => void;
+ onStartAddFile: () => void;
+ onAddFile: (path: string) => void;
+ onCancelAddFile: () => void;
+ onDeleteFile: (path?: string) => void;
+ onRenameFile: (from: string, to: string) => void;
+ onEditFile: (path: string) => void;
+ onContentChange: (content: string) => void;
+ onFocusHandled: () => void;
+}) {
+ const { t } = useT("skills");
+ const validatePath = useValidateNewFilePath();
+ const supportingPaths = filePaths.filter((p) => p !== SKILL_MD);
+ const isMd = isMarkdownPath(selectedPath);
+ // Absent for read-only viewers so the tree never offers an action it would
+ // then refuse. Both rails get the same object: SKILL.md keeps Edit and loses
+ // rename/delete, which the tree derives from reservedPath.
+ const treeActions = canEdit
+ ? {
+ onEdit: onEditFile,
+ validatePath,
+ onRename: onRenameFile,
+ onDelete: onDeleteFile,
+ reservedPath: SKILL_MD,
+ }
+ : undefined;
+
+ return (
+ <div className={cn(PAGE_RAIL, "flex min-h-full flex-col md:h-full md:flex-row")}>
+ <aside
+ role="tablist"
+ aria-orientation="vertical"
+ aria-label={t(($) => $.detail.files.list_aria)}
+ className={cn(
+ "shrink-0 border-b border-surface-border py-3 md:w-52 md:overflow-y-auto md:border-b-0 md:border-r md:py-4",
+ PAGE_GUTTER,
+ )}
+ >
+ <p className="px-2.5 pb-1 text-micro font-semibold uppercase tracking-wider text-muted-foreground">
+ {t(($) => $.detail.files.main)}
+ </p>
+ <FileTree
+ actions={treeActions}
+ filePaths={[SKILL_MD]}
+ selectedPath={selectedPath}
+ onSelect={onSelectPath}
+ />
+
+ <p className="px-2.5 pb-1 pt-3 text-micro font-semibold uppercase tracking-wider text-muted-foreground">
+ {t(($) => $.detail.files.supporting, { count: supportingPaths.length })}
+ </p>
+ {supportingPaths.length > 0 ? (
+ <FileTree
+ actions={treeActions}
+ filePaths={supportingPaths}
+ selectedPath={selectedPath}
+ onSelect={onSelectPath}
+ />
+ ) : (
+ !addingFile && (
+ <p className="px-2.5 py-1 text-caption text-muted-foreground">
+ {t(($) => $.detail.files.supporting_empty)}
+ </p>
+ )
+ )}
+
+ {canEdit &&
+ (addingFile ? (
+ <AddFileInline
+ existingPaths={filePaths}
+ onAdd={onAddFile}
+ onCancel={onCancelAddFile}
+ />
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={onStartAddFile}
+ className="mt-2 h-8 w-full justify-start px-2.5 text-muted-foreground"
+ >
+ <Plus className="h-3.5 w-3.5" />
+ {t(($) => $.detail.files.add_file)}
+ </Button>
+ ))}
+ </aside>
+
+ <section className="flex min-h-[32rem] min-w-0 flex-1 flex-col md:min-h-0">
+ <div className="flex h-10 shrink-0 items-center gap-3 border-b px-3 sm:px-4">
+ <span className="truncate font-mono text-caption text-muted-foreground">
+ {selectedPath}
+ </span>
+ <div className="ml-auto flex shrink-0 items-center gap-1">
+ {isMd && (
+ // The second segment is named for what it does for THIS viewer:
+ // "Edit" when the pane it opens accepts typing, "Plain text"
+ // when the same pane is read-only. Same mode either way — only
+ // the promise differs, and offering an edit the page would
+ // refuse is the thing this rail is careful not to do.
+ <div
+ role="group"
+ aria-label={t(($) => $.detail.files.mode_aria)}
+ className="flex items-center gap-0.5 rounded-md bg-muted p-0.5"
+ >
+ {(["preview", "raw"] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ aria-pressed={mode === value}
+ onClick={() => onModeChange(value)}
+ className={cn(
+ "h-6 rounded-xs px-2 text-caption font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ mode === value
+ ? "bg-surface text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {value === "preview"
+ ? t(($) => $.detail.files.mode_preview)
+ : canEdit
+ ? t(($) => $.detail.files.mode_edit)
+ : t(($) => $.detail.files.mode_raw)}
+ </button>
+ ))}
+ </div>
+ )}
+ {selectedPath !== SKILL_MD && canEdit && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => onDeleteFile()}
+ className="text-muted-foreground hover:text-destructive"
+ aria-label={t(($) => $.detail.delete_file)}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ }
+ />
+ <TooltipContent>{t(($) => $.detail.delete_file)}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1">
+ <FileViewer
+ key={selectedPath}
+ path={selectedPath}
+ content={selectedContent}
+ mode={mode}
+ readOnly={!canEdit}
+ autoFocus={focusEditor}
+ onChange={onContentChange}
+ onFocusHandled={onFocusHandled}
+ />
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/packages/views/skills/components/skill-list-actions.tsx b/packages/views/skills/components/skill-list-actions.tsx
index cad592eb72..bf38e90f7e 100644
--- a/packages/views/skills/components/skill-list-actions.tsx
+++ b/packages/views/skills/components/skill-list-actions.tsx
@@ -6,12 +6,10 @@ import {
ChevronRight,
ExternalLink,
Loader2,
- MoreHorizontal,
Plus,
RotateCw,
Search,
Trash2,
- X,
} from "@multica/ui/icons";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
@@ -37,11 +35,8 @@ import {
DialogTitle,
} from "@multica/ui/components/ui/dialog";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
- DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import {
Tooltip,
@@ -49,14 +44,16 @@ import {
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
-import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
import { useIntentNavigate } from "../../navigation";
+import {
+ CollectionBatchBar,
+ CollectionRowMenu,
+} from "../../layout/collection-list";
import { isRefreshableOrigin, readOrigin } from "../lib/origin";
import { RefreshSkillDialog } from "./refresh-skill-dialog";
import type { SkillRow } from "./skill-list-filter";
-import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
// Shared context the row kebab and the batch toolbar both need. Assembled
// once at the page level.
@@ -640,10 +637,6 @@ export function UpdateSkillsDialog({
// Row kebab
-// The row is a plain `<div>` whose whole-row navigation is a mouse `onClick`
-// (see `useRowLink`), not an ancestor `<a>`. The wrapper span stops click
-// propagation so opening this menu never navigates the row — just
-// stopPropagation, no preventDefault (there is no native anchor to cancel).
export function SkillRowActions({
row,
ctx,
@@ -663,65 +656,44 @@ export function SkillRowActions({
const canRefresh = row.canEdit && isRefreshableOrigin(origin);
return (
- <span
- onClick={(e) => e.stopPropagation()}
- className="flex items-center"
- >
- <DropdownMenu>
- <DeferredTooltip
- content={t(($) => $.actions.row_menu)}
- trigger={
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- aria-label={t(($) => $.actions.row_menu)}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"
- >
- <MoreHorizontal className="size-4" />
- </button>
- }
- />
+ <>
+ <CollectionRowMenu label={t(($) => $.actions.row_menu)} contentClassName="w-52">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ paths.skillDetail(row.skill.id),
+ "foreground-tab",
+ row.skill.name,
+ )
}
- />
- <DropdownMenuContent align="end" className="w-52">
- <DropdownMenuItem
- onClick={() =>
- intentNavigate(
- paths.skillDetail(row.skill.id),
- "foreground-tab",
- row.skill.name,
- )
- }
- >
- <ExternalLink className="size-3.5" />
- {tCommon(($) => $.navigation.open_in_new_tab)}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => setAddOpen(true)}>
- <Plus className="size-3.5" />
- {t(($) => $.actions.add_to_agent)}
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => setAddOpen(true)}>
+ <Plus className="size-3.5" />
+ {t(($) => $.actions.add_to_agent)}
+ </DropdownMenuItem>
+ {canRefresh && (
+ <DropdownMenuItem onClick={() => setRefreshOpen(true)}>
+ <RotateCw className="size-3.5" />
+ {t(($) => $.actions.refresh)}
</DropdownMenuItem>
- {canRefresh && (
- <DropdownMenuItem onClick={() => setRefreshOpen(true)}>
- <RotateCw className="size-3.5" />
- {t(($) => $.actions.refresh)}
+ )}
+ {row.canEdit && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteOpen(true)}
+ >
+ <Trash2 className="size-3.5" />
+ {t(($) => $.actions.delete)}
</DropdownMenuItem>
- )}
- {row.canEdit && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleteOpen(true)}
- >
- <Trash2 className="size-3.5" />
- {t(($) => $.actions.delete)}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ </>
+ )}
+ </CollectionRowMenu>
<AddToAgentDialog
skills={[row.skill]}
ctx={ctx}
@@ -743,7 +715,7 @@ export function SkillRowActions({
open={deleteOpen}
onOpenChange={setDeleteOpen}
/>
- </span>
+ </>
);
}
@@ -763,8 +735,6 @@ export function SkillBatchToolbar({
const [updateOpen, setUpdateOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
- if (rows.length === 0) return null;
-
const allDeletable = rows.every((r) => r.canEdit);
const updatable = rows.filter(
(r) => r.canEdit && isRefreshableOrigin(readOrigin(r.skill)),
@@ -801,27 +771,7 @@ export function SkillBatchToolbar({
return (
<>
- {/* Anchored to the page root (relative), NOT the viewport: with a
- sidebar/split pane open, viewport-centering sits visibly off the
- list's own center. Same rule for every future list page's batch
- toolbar. */}
- <div className="absolute bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-1 rounded-lg border bg-background px-2 py-1.5 shadow-lg max-md:above-chat-launcher">
- <div className="mr-1 flex items-center gap-1.5 border-r pl-1 pr-2">
- <span className="text-body font-medium">
- {t(($) => $.actions.selected, { count: rows.length })}
- </span>
- <TooltipHint label={t(($) => $.actions.clear_selection)}>
- <button
- type="button"
- aria-label={t(($) => $.actions.clear_selection)}
- onClick={onClear}
- className="rounded-xs p-0.5 transition-colors hover:bg-accent"
- >
- <X className="size-3.5 text-muted-foreground" />
- </button>
- </TooltipHint>
- </div>
-
+ <CollectionBatchBar count={rows.length} onClear={onClear}>
<Button variant="ghost" size="sm" onClick={() => setAddOpen(true)}>
<Plus className="mr-1 size-3.5" />
{t(($) => $.actions.add_to_agent)}
@@ -852,7 +802,7 @@ export function SkillBatchToolbar({
</TooltipContent>
</Tooltip>
)}
- </div>
+ </CollectionBatchBar>
<AddToAgentDialog
skills={rows.map((r) => r.skill)}
diff --git a/packages/views/skills/components/skill-list-controls.tsx b/packages/views/skills/components/skill-list-controls.tsx
new file mode 100644
index 0000000000..d5879da507
--- /dev/null
+++ b/packages/views/skills/components/skill-list-controls.tsx
@@ -0,0 +1,366 @@
+"use client";
+
+import { useState } from "react";
+import {
+ Download,
+ FolderOpen,
+ HardDrive,
+ Pencil,
+ Plus,
+ Tags,
+} from "@multica/ui/icons";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { labelListOptions } from "@multica/core/labels/queries";
+import type { Agent, Label, MemberWithUser } from "@multica/core/types";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
+import {
+ type SkillListFilters,
+ type SkillOriginType,
+} from "@multica/core/skills/stores";
+import { LabelChip } from "../../labels/label-chip";
+import { LabelManager } from "../../labels/label-manager";
+import {
+ CollectionCreateButton,
+ CollectionFilterButton,
+} from "../../layout/collection-page";
+import { useT } from "../../i18n";
+import type { CreateSkillMethod } from "./create-skill-dialog";
+import type { SkillRow } from "./skill-list-filter";
+
+export function countActiveFilterDimensions(
+ filters: SkillListFilters,
+): number {
+ let count = 0;
+ if (filters.usage.length > 0) count++;
+ if (filters.origins.length > 0) count++;
+ if (filters.agents.length > 0) count++;
+ if (filters.creators.length > 0) count++;
+ if (filters.labels.length > 0) count++;
+ return count;
+}
+
+const ORIGIN_TYPES: SkillOriginType[] = [
+ "manual",
+ "runtime_local",
+ "clawhub",
+ "skills_sh",
+ "github",
+];
+
+function originIcon(type: SkillOriginType) {
+ if (type === "manual") return <Pencil className="size-3.5" />;
+ if (type === "runtime_local") return <HardDrive className="size-3.5" />;
+ return <Download className="size-3.5" />;
+}
+
+function CountBadge({ n }: { n: number }) {
+ return (
+ <span className="ml-auto pl-3 text-caption text-muted-foreground">{n}</span>
+ );
+}
+
+/** The header's filter icon and its menu: one submenu per dimension. */
+export function SkillFilterMenu({
+ filters,
+ onToggleFilter,
+ rows,
+}: {
+ filters: SkillListFilters;
+ onToggleFilter: (key: keyof SkillListFilters, value: string) => void;
+ /** Rows of the current scope, unfiltered: options and counts derive from them. */
+ rows: SkillRow[];
+}) {
+ const { t } = useT("skills");
+ const [labelSearch, setLabelSearch] = useState("");
+ const [manageLabelsOpen, setManageLabelsOpen] = useState(false);
+ const wsId = useWorkspaceId();
+ const { data: catalogLabels = [] } = useQuery(labelListOptions(wsId, "skill"));
+
+ // Counted over the unfiltered rows so toggling one dimension doesn't make
+ // the others' options vanish.
+ const usedCount = rows.filter((r) => r.agents.length > 0).length;
+ const unusedCount = rows.length - usedCount;
+
+ const originCounts = new Map<SkillOriginType, number>();
+ const agentOptions = new Map<string, { agent: Agent; count: number }>();
+ const creatorOptions = new Map<
+ string,
+ { member: MemberWithUser; count: number }
+ >();
+ const labelCounts = new Map<string, number>();
+ for (const row of rows) {
+ originCounts.set(row.originType, (originCounts.get(row.originType) ?? 0) + 1);
+ for (const agent of row.agents) {
+ const entry = agentOptions.get(agent.id);
+ if (entry) entry.count += 1;
+ else agentOptions.set(agent.id, { agent, count: 1 });
+ }
+ if (row.creator) {
+ const entry = creatorOptions.get(row.creator.user_id);
+ if (entry) entry.count += 1;
+ else creatorOptions.set(row.creator.user_id, { member: row.creator, count: 1 });
+ }
+ for (const label of row.skill.labels ?? []) {
+ labelCounts.set(label.id, (labelCounts.get(label.id) ?? 0) + 1);
+ }
+ }
+
+ const labelQuery = labelSearch.trim().toLowerCase();
+ const filteredLabels = catalogLabels.filter((label: Label) =>
+ label.name.toLowerCase().includes(labelQuery),
+ );
+
+ const ORIGIN_LABELS: Record<SkillOriginType, string> = {
+ manual: t(($) => $.table.source_manual),
+ runtime_local: t(($) => $.table.source_runtime_unknown),
+ clawhub: t(($) => $.table.source_clawhub),
+ skills_sh: t(($) => $.table.source_skills_sh),
+ github: t(($) => $.table.source_github),
+ };
+
+ const dimensionCount = (n: number) =>
+ n > 0 ? (
+ <span className="text-caption font-medium text-primary">{n}</span>
+ ) : null;
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <CollectionFilterButton
+ count={countActiveFilterDimensions(filters)}
+ />
+ }
+ />
+ <DropdownMenuContent align="start" className="w-auto">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_usage)}
+ </span>
+ {dimensionCount(filters.usage.length)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44">
+ {(["used", "unused"] as const).map((value) => (
+ <DropdownMenuCheckboxItem
+ key={value}
+ checked={filters.usage.includes(value)}
+ onCheckedChange={() => onToggleFilter("usage", value)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.usage.includes(value)} />
+ {value === "used"
+ ? t(($) => $.page.scopes.used.label)
+ : t(($) => $.page.scopes.unused.label)}
+ <CountBadge n={value === "used" ? usedCount : unusedCount} />
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.table.source)}</span>
+ {dimensionCount(filters.origins.length)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-48">
+ {ORIGIN_TYPES.filter((type) => originCounts.has(type)).map(
+ (type) => (
+ <DropdownMenuCheckboxItem
+ key={type}
+ checked={filters.origins.includes(type)}
+ onCheckedChange={() => onToggleFilter("origins", type)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.origins.includes(type)} />
+ {originIcon(type)}
+ {ORIGIN_LABELS[type]}
+ <CountBadge n={originCounts.get(type) ?? 0} />
+ </DropdownMenuCheckboxItem>
+ ),
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.table.used_by)}</span>
+ {dimensionCount(filters.agents.length)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...agentOptions.values()].map(({ agent, count }) => (
+ <DropdownMenuCheckboxItem
+ key={agent.id}
+ checked={filters.agents.includes(agent.id)}
+ onCheckedChange={() => onToggleFilter("agents", agent.id)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={filters.agents.includes(agent.id)} />
+ <ActorAvatar
+ name={agent.name}
+ initials={agent.name.slice(0, 2).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(agent.avatar_url)}
+ isAgent
+ size="sm"
+ />
+ <span className="min-w-0 truncate">{agent.name}</span>
+ <CountBadge n={count} />
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.table.created_by)}</span>
+ {dimensionCount(filters.creators.length)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {[...creatorOptions.values()].map(({ member, count }) => (
+ <DropdownMenuCheckboxItem
+ key={member.user_id}
+ checked={filters.creators.includes(member.user_id)}
+ onCheckedChange={() =>
+ onToggleFilter("creators", member.user_id)
+ }
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck
+ checked={filters.creators.includes(member.user_id)}
+ />
+ <ActorAvatar
+ name={member.name}
+ initials={member.name.slice(0, 2).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(member.avatar_url)}
+ size="sm"
+ />
+ <span className="min-w-0 truncate">{member.name}</span>
+ <CountBadge n={count} />
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ {/* Labels — Skill-scoped catalog, OR-within-labels like Issues. */}
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">
+ {t(($) => $.toolbar.section_labels)}
+ </span>
+ {dimensionCount(filters.labels.length)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-52 p-0">
+ <div className="border-b border-foreground/5 px-2 py-1.5">
+ <input
+ type="text"
+ value={labelSearch}
+ onChange={(e) => setLabelSearch(e.target.value)}
+ placeholder={t(($) => $.toolbar.filter_search_placeholder)}
+ className="w-full bg-transparent text-body outline-none placeholder:text-muted-foreground"
+ autoFocus
+ />
+ </div>
+ <div className="max-h-64 overflow-y-auto p-1">
+ {filteredLabels.map((label) => {
+ const checked = filters.labels.includes(label.id);
+ const count = labelCounts.get(label.id) ?? 0;
+ return (
+ <DropdownMenuCheckboxItem
+ key={label.id}
+ checked={checked}
+ onCheckedChange={() =>
+ onToggleFilter("labels", label.id)
+ }
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ <LabelChip label={label} />
+ {count > 0 && <CountBadge n={count} />}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ {filteredLabels.length === 0 && (
+ <div className="px-2 py-3 text-center text-body text-muted-foreground">
+ {labelSearch
+ ? t(($) => $.toolbar.no_results)
+ : t(($) => $.toolbar.no_labels)}
+ </div>
+ )}
+ </div>
+ {/* A shortcut to the skill label catalog, next to the
+ skills it tags; Settings → Labels manages the same list. */}
+ <DropdownMenuSeparator className="my-0" />
+ <div className="p-1">
+ <DropdownMenuItem onClick={() => setManageLabelsOpen(true)}>
+ <Tags />
+ {t(($) => $.toolbar.manage_labels)}
+ </DropdownMenuItem>
+ </div>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <Dialog open={manageLabelsOpen} onOpenChange={setManageLabelsOpen}>
+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-3xl">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.toolbar.manage_labels_title)}</DialogTitle>
+ </DialogHeader>
+ <LabelManager scope="skill" />
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
+const CREATE_METHODS: { key: CreateSkillMethod; icon: typeof Plus }[] = [
+ { key: "manual", icon: Plus },
+ { key: "local", icon: FolderOpen },
+ { key: "url", icon: Download },
+ { key: "runtime", icon: HardDrive },
+];
+
+/** The "+" icon, opening the ways a skill can be added. */
+export function SkillCreateMenu({
+ onCreate,
+}: {
+ onCreate: (method: CreateSkillMethod) => void;
+}) {
+ const { t } = useT("skills");
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<CollectionCreateButton label={t(($) => $.page.new_skill)} />}
+ />
+ <DropdownMenuContent align="end" className="w-auto min-w-48">
+ {CREATE_METHODS.map(({ key, icon: Icon }) => (
+ <DropdownMenuItem key={key} onClick={() => onCreate(key)}>
+ <Icon />
+ {t(($) => $.create.method[key].title)}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/skills/components/skill-list-filter.ts b/packages/views/skills/components/skill-list-filter.ts
index a36cebae40..5baab96a26 100644
--- a/packages/views/skills/components/skill-list-filter.ts
+++ b/packages/views/skills/components/skill-list-filter.ts
@@ -13,16 +13,13 @@ export interface SkillRow {
/**
* Pure row-filter predicate: returns true if the row matches all active
- * filter dimensions plus name search. Empty arrays are inactive. Label
- * matching is OR-within-labels, matching Issue list semantics.
+ * filter dimensions. Empty arrays are inactive. Label matching is
+ * OR-within-labels, matching Issue list semantics.
*/
export function rowMatchesFilters(
row: SkillRow,
filters: SkillListFilters,
- query: string,
): boolean {
- const q = query.trim().toLowerCase();
- if (q && !row.skill.name.toLowerCase().includes(q)) return false;
if (filters.usage.length > 0) {
const usage = row.agents.length > 0 ? "used" : "unused";
if (!filters.usage.includes(usage)) return false;
diff --git a/packages/views/skills/components/skill-list-toolbar.tsx b/packages/views/skills/components/skill-list-toolbar.tsx
deleted file mode 100644
index 12540fd725..0000000000
--- a/packages/views/skills/components/skill-list-toolbar.tsx
+++ /dev/null
@@ -1,602 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import {
- ArrowDown,
- ArrowUp,
- ChevronDown,
- Download,
- Filter,
- HardDrive,
- Pencil,
- Search,
- Tags,
- X,
-} from "@multica/ui/icons";
-import { useQuery } from "@tanstack/react-query";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { labelListOptions } from "@multica/core/labels/queries";
-import type { Agent, Label, MemberWithUser } from "@multica/core/types";
-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import { Button } from "@multica/ui/components/ui/button";
-import { IconButton } from "@multica/ui/components/common/icon-button";
-import {
- DropdownMenu,
- DropdownMenuCheckboxItem,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
- DropdownMenuTrigger,
-} from "@multica/ui/components/ui/dropdown-menu";
-import { Input } from "@multica/ui/components/ui/input";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
-import { Switch } from "@multica/ui/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
-import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
-import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
-import {
- type SkillColumnKey,
- type SkillListFilters,
- type SkillOriginType,
- type SkillSortDirection,
- type SkillSortField,
-} from "@multica/core/skills/stores";
-import { LabelChip } from "../../labels/label-chip";
-import { LabelManager } from "../../labels/label-manager";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@multica/ui/components/ui/dialog";
-import { useT } from "../../i18n";
-import type { SkillRow } from "./skill-list-filter";
-import { PAGE_TOOLBAR } from "../../layout/page-header";
-
-export type OriginType = SkillOriginType;
-
-const COLUMN_KEYS: SkillColumnKey[] = [
- "usedBy",
- "source",
- "creator",
- "updated",
- "created",
-];
-
-const SORT_FIELDS: SkillSortField[] = ["name", "usedBy", "updated", "created"];
-
-export function countActiveFilterDimensions(
- filters: SkillListFilters,
-): number {
- let count = 0;
- if (filters.usage.length > 0) count++;
- if (filters.origins.length > 0) count++;
- if (filters.agents.length > 0) count++;
- if (filters.creators.length > 0) count++;
- if (filters.labels.length > 0) count++;
- return count;
-}
-
-const ORIGIN_TYPES: OriginType[] = [
- "manual",
- "runtime_local",
- "clawhub",
- "skills_sh",
- "github",
-];
-
-function originIcon(type: OriginType) {
- if (type === "manual") return <Pencil className="size-3.5" />;
- if (type === "runtime_local") return <HardDrive className="size-3.5" />;
- return <Download className="size-3.5" />;
-}
-
-export function SkillListToolbar({
- search,
- onSearchChange,
- filters,
- onToggleFilter,
- onClearFilters,
- sortField,
- sortDirection,
- onSortFieldChange,
- onSortDirectionChange,
- hiddenColumns,
- onToggleColumn,
- allRows,
- visibleCount,
-}: {
- search: string;
- onSearchChange: (v: string) => void;
- filters: SkillListFilters;
- onToggleFilter: (key: keyof SkillListFilters, value: string) => void;
- onClearFilters: () => void;
- sortField: SkillSortField;
- sortDirection: SkillSortDirection;
- onSortFieldChange: (field: SkillSortField) => void;
- onSortDirectionChange: (direction: SkillSortDirection) => void;
- hiddenColumns: SkillColumnKey[];
- onToggleColumn: (key: SkillColumnKey) => void;
- /** Unfiltered rows — option lists and counts derive from the full set. */
- allRows: SkillRow[];
- /** Rows surviving search + filters — shown as "n / total" when narrowed. */
- visibleCount: number;
-}) {
- const { t } = useT("skills");
- const [labelSearch, setLabelSearch] = useState("");
- const [manageLabelsOpen, setManageLabelsOpen] = useState(false);
- const wsId = useWorkspaceId();
- const { data: catalogLabels = [] } = useQuery(labelListOptions(wsId, "skill"));
-
- const activeCount = countActiveFilterDimensions(filters);
- const hasActiveFilters = activeCount > 0;
-
- // Option lists with counts, derived from the unfiltered rows so toggling
- // one dimension doesn't make the others' options vanish.
- const usedCount = allRows.filter((r) => r.agents.length > 0).length;
- const unusedCount = allRows.length - usedCount;
-
- const originCounts = new Map<OriginType, number>();
- const agentOptions = new Map<string, { agent: Agent; count: number }>();
- const creatorOptions = new Map<
- string,
- { member: MemberWithUser; count: number }
- >();
- const labelCounts = new Map<string, number>();
- for (const row of allRows) {
- originCounts.set(row.originType, (originCounts.get(row.originType) ?? 0) + 1);
- for (const agent of row.agents) {
- const entry = agentOptions.get(agent.id);
- if (entry) entry.count += 1;
- else agentOptions.set(agent.id, { agent, count: 1 });
- }
- if (row.creator) {
- const entry = creatorOptions.get(row.creator.user_id);
- if (entry) entry.count += 1;
- else creatorOptions.set(row.creator.user_id, { member: row.creator, count: 1 });
- }
- for (const label of row.skill.labels ?? []) {
- labelCounts.set(label.id, (labelCounts.get(label.id) ?? 0) + 1);
- }
- }
-
- const labelQuery = labelSearch.trim().toLowerCase();
- const filteredLabels = catalogLabels.filter((label: Label) =>
- label.name.toLowerCase().includes(labelQuery),
- );
-
- const ORIGIN_LABELS: Record<OriginType, string> = {
- manual: t(($) => $.table.source_manual),
- runtime_local: t(($) => $.table.source_runtime_unknown),
- clawhub: t(($) => $.table.source_clawhub),
- skills_sh: t(($) => $.table.source_skills_sh),
- github: t(($) => $.table.source_github),
- };
-
- const COLUMN_LABELS: Record<SkillColumnKey, string> = {
- usedBy: t(($) => $.table.used_by),
- source: t(($) => $.table.source),
- creator: t(($) => $.table.created_by),
- updated: t(($) => $.table.updated),
- created: t(($) => $.table.created),
- };
-
- const SORT_LABELS: Record<SkillSortField, string> = {
- name: t(($) => $.table.name),
- usedBy: t(($) => $.table.used_by),
- updated: t(($) => $.table.updated),
- created: t(($) => $.table.created),
- };
- const sortLabel = SORT_LABELS[sortField];
-
- const countBadge = (n: number) => (
- <span className="ml-auto pl-3 text-caption text-muted-foreground">{n}</span>
- );
-
- return (
- <div className={PAGE_TOOLBAR}>
- {/* Left: name search + result count. The count only appears while
- search/filters narrow the list — in the idle state it would just
- duplicate the total already shown in the page header. Below md the
- search (and its count) disappear entirely, following the issues
- header's small-screen treatment. */}
- <div className="flex min-w-0 items-center gap-2">
- <div className="relative hidden md:block">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
- <Input
- value={search}
- onChange={(e) => onSearchChange(e.target.value)}
- aria-label={t(($) => $.page.search_placeholder)}
- placeholder={t(($) => $.page.search_placeholder)}
- className="h-8 w-64 pl-8 text-body"
- />
- </div>
- {(hasActiveFilters || search.trim().length > 0) && (
- <span
- title={t(($) => $.toolbar.result_count_title)}
- className="hidden shrink-0 text-caption tabular-nums text-muted-foreground md:inline"
- >
- {visibleCount} / {allRows.length}
- </span>
- )}
- </div>
-
- <div className="flex shrink-0 items-center gap-1">
- {/* Filter */}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant={hasActiveFilters ? "default" : "outline"}
- size="sm"
- className={
- hasActiveFilters
- ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"
- : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- }
- >
- <Filter className="size-3.5" />
- {hasActiveFilters ? (
- <>
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_active_count, {
- count: activeCount,
- })}
- </span>
- <span className="tabular-nums md:hidden">
- {activeCount}
- </span>
- </>
- ) : (
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_label)}
- </span>
- )}
- {hasActiveFilters && (
- <span
- role="button"
- tabIndex={-1}
- aria-label={t(($) => $.toolbar.clear_filters)}
- className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onClearFilters();
- }}
- onPointerDown={(e) => e.stopPropagation()}
- >
- <X className="size-3" />
- </span>
- )}
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-auto">
- {/* Usage */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_usage)}
- </span>
- {filters.usage.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.usage.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {(["used", "unused"] as const).map((value) => (
- <DropdownMenuCheckboxItem
- key={value}
- checked={filters.usage.includes(value)}
- onCheckedChange={() => onToggleFilter("usage", value)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.usage.includes(value)} />
- {value === "used"
- ? t(($) => $.page.scopes.used.label)
- : t(($) => $.page.scopes.unused.label)}
- {countBadge(value === "used" ? usedCount : unusedCount)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Source */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.table.source)}</span>
- {filters.origins.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.origins.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-48">
- {ORIGIN_TYPES.filter((type) => originCounts.has(type)).map(
- (type) => (
- <DropdownMenuCheckboxItem
- key={type}
- checked={filters.origins.includes(type)}
- onCheckedChange={() => onToggleFilter("origins", type)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.origins.includes(type)} />
- {originIcon(type)}
- {ORIGIN_LABELS[type]}
- {countBadge(originCounts.get(type) ?? 0)}
- </DropdownMenuCheckboxItem>
- ),
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Used by */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.table.used_by)}</span>
- {filters.agents.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.agents.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...agentOptions.values()].map(({ agent, count }) => (
- <DropdownMenuCheckboxItem
- key={agent.id}
- checked={filters.agents.includes(agent.id)}
- onCheckedChange={() => onToggleFilter("agents", agent.id)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.agents.includes(agent.id)} />
- <ActorAvatar
- name={agent.name}
- initials={agent.name.slice(0, 2).toUpperCase()}
- avatarUrl={resolvePublicFileUrl(agent.avatar_url)}
- isAgent
- size="sm"
- />
- <span className="min-w-0 truncate">{agent.name}</span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Creator */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.table.created_by)}</span>
- {filters.creators.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.creators.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {[...creatorOptions.values()].map(({ member, count }) => (
- <DropdownMenuCheckboxItem
- key={member.user_id}
- checked={filters.creators.includes(member.user_id)}
- onCheckedChange={() =>
- onToggleFilter("creators", member.user_id)
- }
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck
- checked={filters.creators.includes(member.user_id)}
- />
- <ActorAvatar
- name={member.name}
- initials={member.name.slice(0, 2).toUpperCase()}
- avatarUrl={resolvePublicFileUrl(member.avatar_url)}
- size="sm"
- />
- <span className="min-w-0 truncate">{member.name}</span>
- {countBadge(count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {/* Labels — Skill-scoped catalog, OR-within-labels like Issues. */}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">
- {t(($) => $.toolbar.section_labels)}
- </span>
- {filters.labels.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {filters.labels.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-52 p-0">
- <div className="border-b border-foreground/5 px-2 py-1.5">
- <input
- type="text"
- value={labelSearch}
- onChange={(e) => setLabelSearch(e.target.value)}
- placeholder={t(($) => $.toolbar.filter_search_placeholder)}
- className="w-full bg-transparent text-body outline-none placeholder:text-muted-foreground"
- autoFocus
- />
- </div>
- <div className="max-h-64 overflow-y-auto p-1">
- {filteredLabels.map((label) => {
- const checked = filters.labels.includes(label.id);
- const count = labelCounts.get(label.id) ?? 0;
- return (
- <DropdownMenuCheckboxItem
- key={label.id}
- checked={checked}
- onCheckedChange={() =>
- onToggleFilter("labels", label.id)
- }
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={checked} />
- <LabelChip label={label} />
- {count > 0 && countBadge(count)}
- </DropdownMenuCheckboxItem>
- );
- })}
- {filteredLabels.length === 0 && (
- <div className="px-2 py-3 text-center text-body text-muted-foreground">
- {labelSearch
- ? t(($) => $.toolbar.no_results)
- : t(($) => $.toolbar.no_labels)}
- </div>
- )}
- </div>
- {/* A shortcut to the skill label catalog, next to the
- skills it tags; Settings → Labels manages the same list. */}
- <DropdownMenuSeparator className="my-0" />
- <div className="p-1">
- <DropdownMenuItem onClick={() => setManageLabelsOpen(true)}>
- <Tags />
- {t(($) => $.toolbar.manage_labels)}
- </DropdownMenuItem>
- </div>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {/* Display settings — same paradigm as the issues header: Popover
- with bordered sections, trigger shows the active sort (direction
- arrow + field label), sort row is a nested select + a direction
- toggle button, columns are label+Switch rows. Mutates the same
- sort state pair the list header buttons use. */}
- <Popover>
- <Tooltip>
- <PopoverTrigger
- render={
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- >
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- <span className="hidden md:inline">{sortLabel}</span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">
- {t(($) => $.toolbar.display)}
- </TooltipContent>
- </Tooltip>
- <PopoverContent align="end" className="w-64 p-0">
- <div className="border-b px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.sort_by)}
- </span>
- <div className="mt-2 flex items-center gap-1.5">
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="flex-1 justify-between text-caption"
- >
- {sortLabel}
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={sortField}
- onValueChange={(v) =>
- onSortFieldChange(v as SkillSortField)
- }
- >
- {SORT_FIELDS.map((field) => (
- <DropdownMenuRadioItem key={field} value={field}>
- {SORT_LABELS[field]}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <IconButton
- variant="outline"
- size="icon-sm"
- onClick={() =>
- onSortDirectionChange(
- sortDirection === "asc" ? "desc" : "asc",
- )
- }
- label={
- sortDirection === "asc"
- ? t(($) => $.toolbar.direction_asc)
- : t(($) => $.toolbar.direction_desc)
- }
- >
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- </IconButton>
- </div>
- </div>
-
- <div className="px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.section_columns)}
- </span>
- <div className="mt-2 space-y-2">
- {COLUMN_KEYS.map((key) => (
- <label
- key={key}
- className="flex cursor-pointer items-center justify-between"
- >
- <span className="text-body">{COLUMN_LABELS[key]}</span>
- <Switch
- size="sm"
- checked={!hiddenColumns.includes(key)}
- onCheckedChange={() => onToggleColumn(key)}
- />
- </label>
- ))}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- </div>
-
- <Dialog open={manageLabelsOpen} onOpenChange={setManageLabelsOpen}>
- <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-3xl">
- <DialogHeader>
- <DialogTitle>{t(($) => $.toolbar.manage_labels_title)}</DialogTitle>
- </DialogHeader>
- <LabelManager scope="skill" />
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/packages/views/skills/components/skill-properties-panel.tsx b/packages/views/skills/components/skill-properties-panel.tsx
new file mode 100644
index 0000000000..dc1e618a9f
--- /dev/null
+++ b/packages/views/skills/components/skill-properties-panel.tsx
@@ -0,0 +1,239 @@
+"use client";
+
+import { Download, HardDrive, Pencil } from "@multica/ui/icons";
+import type { AgentRuntime, MemberWithUser, Skill } from "@multica/core/types";
+import { runtimeDisplayLabel } from "@multica/core/runtimes";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@multica/ui/components/ui/popover";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import { ObjectPanelSection, ObjectProperty } from "../../layout/object-page";
+import { ResourceLabelPicker } from "../../labels/resource-label-picker";
+import { useT, useTimeAgo } from "../../i18n";
+import { originSourceUrl, totalFileCount, type OriginInfo } from "../lib/origin";
+
+function useOriginLabel(origin: OriginInfo, runtime: AgentRuntime | null) {
+ const { t } = useT("skills");
+ if (origin.type === "runtime_local") {
+ return runtime
+ ? t(($) => $.detail.subline.origin_runtime_named, {
+ name: runtimeDisplayLabel(runtime),
+ })
+ : origin.provider
+ ? t(($) => $.detail.subline.origin_runtime_provider, { provider: origin.provider })
+ : t(($) => $.detail.subline.origin_runtime_unknown);
+ }
+ if (origin.type === "clawhub") return t(($) => $.detail.subline.origin_clawhub);
+ if (origin.type === "skills_sh") return t(($) => $.detail.subline.origin_skills_sh);
+ if (origin.type === "github") return t(($) => $.detail.subline.origin_github);
+ return t(($) => $.detail.subline.origin_workspace);
+}
+
+function SourceValue({
+ origin,
+ runtime,
+}: {
+ origin: OriginInfo;
+ runtime: AgentRuntime | null;
+}) {
+ const label = useOriginLabel(origin, runtime);
+ const sourceUrl = originSourceUrl(origin);
+ // Same three-way split as the list's Source column: runtime, created here,
+ // imported.
+ const Icon =
+ origin.type === "runtime_local"
+ ? HardDrive
+ : origin.type === "manual"
+ ? Pencil
+ : Download;
+ return (
+ <>
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
+ {sourceUrl ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <a
+ href={sourceUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="truncate hover:underline"
+ >
+ {label}
+ </a>
+ }
+ />
+ <TooltipContent side="top">{sourceUrl}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="truncate">{label}</span>
+ )}
+ </>
+ );
+}
+
+/**
+ * Description opens into a field sized for it: real descriptions run 500–900
+ * characters (they carry the trigger vocabulary an agent matches on), far
+ * more than a panel row can show.
+ */
+function DescriptionValue({
+ description,
+ canEdit,
+ onChange,
+}: {
+ description: string;
+ canEdit: boolean;
+ onChange: (value: string) => void;
+}) {
+ const { t } = useT("skills");
+ return (
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ className={cn(
+ "min-w-0 flex-1 truncate text-left transition-colors hover:text-foreground",
+ !description && "text-muted-foreground",
+ )}
+ >
+ {description ||
+ (canEdit ? t(($) => $.detail.panel.add_description) : "—")}
+ </button>
+ }
+ />
+ <PopoverContent side="left" align="start" className="w-96 p-3">
+ <Textarea
+ id="skill-description"
+ aria-label={t(($) => $.detail.overview.description)}
+ value={description}
+ readOnly={!canEdit}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={t(($) => $.detail.description_placeholder)}
+ rows={8}
+ className="text-body leading-relaxed read-only:cursor-default"
+ />
+ <div className="mt-1.5 flex flex-wrap justify-between gap-x-4 gap-y-1 text-caption text-muted-foreground">
+ <p>{t(($) => $.detail.overview.description_hint)}</p>
+ <span className="tabular-nums">
+ {t(($) => $.detail.overview.character_count, {
+ count: description.length,
+ })}
+ </span>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/**
+ * The skill's properties. Name and description edit the page's draft, so
+ * they save with the files through the same Save pill; labels save on pick.
+ */
+export function SkillPropertiesPanel({
+ skill,
+ name,
+ description,
+ canEdit,
+ origin,
+ originRuntime,
+ creator,
+ onNameChange,
+ onDescriptionChange,
+}: {
+ skill: Skill;
+ name: string;
+ description: string;
+ canEdit: boolean;
+ origin: OriginInfo;
+ originRuntime: AgentRuntime | null;
+ creator: MemberWithUser | null;
+ onNameChange: (value: string) => void;
+ onDescriptionChange: (value: string) => void;
+}) {
+ const { t } = useT("skills");
+ const timeAgo = useTimeAgo();
+
+ return (
+ <div className="space-y-5">
+ <ObjectPanelSection title={t(($) => $.detail.overview.properties)}>
+ <ObjectProperty label={t(($) => $.detail.overview.name)}>
+ {canEdit ? (
+ <input
+ id="skill-name"
+ aria-label={t(($) => $.detail.overview.name)}
+ value={name}
+ onChange={(e) => onNameChange(e.target.value)}
+ placeholder={t(($) => $.detail.name_placeholder)}
+ className="h-7 min-w-0 flex-1 rounded-sm bg-transparent font-mono text-caption outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring"
+ />
+ ) : (
+ <span className="truncate font-mono">{name}</span>
+ )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.overview.description)}>
+ <DescriptionValue
+ description={description}
+ canEdit={canEdit}
+ onChange={onDescriptionChange}
+ />
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.overview.labels)}>
+ <ResourceLabelPicker
+ resourceType="skill"
+ resourceId={skill.id}
+ canEdit={canEdit}
+ />
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.table.source)}>
+ <SourceValue origin={origin} runtime={originRuntime} />
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.table.created_by)}>
+ {creator ? (
+ <>
+ <ActorAvatar
+ name={creator.name}
+ initials={creator.name.slice(0, 2).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(creator.avatar_url)}
+ size="sm"
+ />
+ <span className="truncate">{creator.name}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.table.updated)}>
+ {timeAgo(skill.updated_at)}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.table.created)}>
+ {timeAgo(skill.created_at)}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.detail.sections.files)}>
+ {t(($) => $.detail.header.files, { count: totalFileCount(skill) })}
+ </ObjectProperty>
+ </ObjectPanelSection>
+
+ <p className="px-2 text-caption leading-relaxed text-muted-foreground">
+ {canEdit
+ ? t(($) => $.detail.overview.permissions_owner)
+ : creator
+ ? t(($) => $.detail.overview.permissions_locked_creator, {
+ name: creator.name,
+ })
+ : t(($) => $.detail.overview.permissions_locked)}
+ </p>
+ </div>
+ );
+}
diff --git a/packages/views/skills/components/skills-page-filter-predicate.test.ts b/packages/views/skills/components/skills-page-filter-predicate.test.ts
index f7743cfbf7..315d13bd71 100644
--- a/packages/views/skills/components/skills-page-filter-predicate.test.ts
+++ b/packages/views/skills/components/skills-page-filter-predicate.test.ts
@@ -64,21 +64,21 @@ describe("rowMatchesFilters — labels dimension", () => {
const unlabeled = makeRow();
const labeled = makeRow({ labels: [makeLabel("lab-1")] });
const empty = makeRow({ labels: [] });
- expect(rowMatchesFilters(unlabeled, noFilters, "")).toBe(true);
- expect(rowMatchesFilters(labeled, noFilters, "")).toBe(true);
- expect(rowMatchesFilters(empty, noFilters, "")).toBe(true);
+ expect(rowMatchesFilters(unlabeled, noFilters)).toBe(true);
+ expect(rowMatchesFilters(labeled, noFilters)).toBe(true);
+ expect(rowMatchesFilters(empty, noFilters)).toBe(true);
});
it("missing labels fail when a labels filter is on", () => {
const unlabeled = makeRow();
- expect(rowMatchesFilters(unlabeled, withLabels(noFilters, "lab-1"), "")).toBe(
+ expect(rowMatchesFilters(unlabeled, withLabels(noFilters, "lab-1"))).toBe(
false,
);
});
it("empty labels fail when a labels filter is on", () => {
const empty = makeRow({ labels: [] });
- expect(rowMatchesFilters(empty, withLabels(noFilters, "lab-1"), "")).toBe(
+ expect(rowMatchesFilters(empty, withLabels(noFilters, "lab-1"))).toBe(
false,
);
});
@@ -88,9 +88,9 @@ describe("rowMatchesFilters — labels dimension", () => {
const b = makeRow({ labels: [makeLabel("lab-b")] });
const neither = makeRow({ labels: [makeLabel("lab-c")] });
const filters = withLabels(noFilters, "lab-a", "lab-b");
- expect(rowMatchesFilters(a, filters, "")).toBe(true);
- expect(rowMatchesFilters(b, filters, "")).toBe(true);
- expect(rowMatchesFilters(neither, filters, "")).toBe(false);
+ expect(rowMatchesFilters(a, filters)).toBe(true);
+ expect(rowMatchesFilters(b, filters)).toBe(true);
+ expect(rowMatchesFilters(neither, filters)).toBe(false);
});
it("labels + usage filter: both must pass (AND)", () => {
@@ -104,21 +104,7 @@ describe("rowMatchesFilters — labels dimension", () => {
labels: ["lab-1"],
usage: ["used"],
};
- expect(rowMatchesFilters(used, filters, "")).toBe(true);
- expect(rowMatchesFilters(unused, filters, "")).toBe(false);
- });
-
- it("labels + name search: both must pass (AND)", () => {
- const match = makeRow({
- name: "review-helper",
- labels: [makeLabel("lab-1")],
- });
- const miss = makeRow({
- name: "deploy-notes",
- labels: [makeLabel("lab-1")],
- });
- const filters = withLabels(noFilters, "lab-1");
- expect(rowMatchesFilters(match, filters, "review")).toBe(true);
- expect(rowMatchesFilters(miss, filters, "review")).toBe(false);
+ expect(rowMatchesFilters(used, filters)).toBe(true);
+ expect(rowMatchesFilters(unused, filters)).toBe(false);
});
});
diff --git a/packages/views/skills/components/skills-page.header.test.tsx b/packages/views/skills/components/skills-page.header.test.tsx
new file mode 100644
index 0000000000..9dc727f892
--- /dev/null
+++ b/packages/views/skills/components/skills-page.header.test.tsx
@@ -0,0 +1,208 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { SkillSummary } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+
+const mocks = vi.hoisted(() => ({
+ skills: [] as SkillSummary[],
+ viewState: {
+ sortField: "name",
+ sortDirection: "asc" as string,
+ hiddenColumns: [] as string[],
+ filters: {
+ usage: [] as string[],
+ origins: [] as string[],
+ agents: [] as string[],
+ creators: [] as string[],
+ labels: [] as string[],
+ },
+ toggleSort: vi.fn(),
+ setSortField: vi.fn(),
+ setSortDirection: vi.fn(),
+ toggleColumn: vi.fn(),
+ toggleFilter: vi.fn(),
+ clearFilters: vi.fn(),
+ },
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: (options: { queryKey?: readonly unknown[] }) => ({
+ data: options.queryKey?.[0] === "skills" ? mocks.skills : [],
+ isLoading: false,
+ error: null,
+ refetch: vi.fn(),
+ }),
+}));
+
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: ({ count }: { count: number }) => ({
+ getVirtualItems: () =>
+ Array.from({ length: count }, (_, index) => ({
+ index,
+ key: index,
+ start: index * 48,
+ end: (index + 1) * 48,
+ size: 48,
+ })),
+ getTotalSize: () => count * 48,
+ }),
+}));
+
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (selector: (state: unknown) => unknown) =>
+ selector({ user: { id: "user-1" } }),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+// Partial mock: SkillIcon resolves its icon from the real WORKSPACE_PAGES.
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useWorkspacePaths: () => ({
+ skillDetail: (id: string) => `/acme/skills/${id}`,
+ }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ skillListOptions: () => ({ queryKey: ["skills"] }),
+ agentListOptions: () => ({ queryKey: ["agents"] }),
+ memberListOptions: () => ({ queryKey: ["members"] }),
+ selectSkillAssignments: () => new Map(),
+}));
+vi.mock("@multica/core/labels/queries", () => ({
+ labelListOptions: () => ({ queryKey: ["labels"] }),
+}));
+vi.mock("@multica/core/runtimes", () => ({
+ runtimeListOptions: () => ({ queryKey: ["runtimes"] }),
+ runtimeDisplayLabel: () => "runtime",
+}));
+vi.mock("@multica/core/workspace/avatar-url", () => ({
+ resolvePublicFileUrl: (u: string | null) => u,
+}));
+vi.mock("@multica/core/skills/stores", () => ({
+ useSkillsViewStore: (selector: (state: unknown) => unknown) =>
+ selector(mocks.viewState),
+ DEFAULT_HIDDEN_COLUMNS: [],
+}));
+
+vi.mock("@multica/ui/components/common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+vi.mock("../../labels/label-manager", () => ({ LabelManager: () => null }));
+vi.mock("./create-skill-dialog", () => ({
+ CreateSkillDialog: ({ initialMethod }: { initialMethod?: string }) => (
+ <div data-testid="create-dialog">{initialMethod}</div>
+ ),
+}));
+vi.mock("./skill-list-actions", () => ({
+ SkillBatchToolbar: () => null,
+ SkillRowActions: () => null,
+}));
+
+import SkillsPage from "./skills-page";
+
+function skill(id: string, name: string, createdBy: string): SkillSummary {
+ return {
+ id,
+ workspace_id: "ws-1",
+ name,
+ description: "",
+ config: {},
+ created_by: createdBy,
+ created_at: "2026-07-28T18:11:37Z",
+ updated_at: "2026-07-28T18:14:40Z",
+ };
+}
+
+function renderPage() {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/skills",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (p) => p,
+ };
+ renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <SkillsPage />
+ </NavigationProvider>,
+ );
+ return screen.getByRole("banner");
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.skills = [
+ skill("skill-1", "mine-skill", "user-1"),
+ skill("skill-2", "team-skill", "user-2"),
+ ];
+});
+
+describe("SkillsPage header", () => {
+ it("titles the page with its scope and keeps every control in one row", () => {
+ const header = renderPage();
+ expect(
+ within(header).getByRole("heading", { name: "All skills", level: 1 }),
+ ).toBeInTheDocument();
+ for (const name of ["Filter", "Display settings", "New skill"]) {
+ expect(within(header).getByRole("button", { name })).toBeInTheDocument();
+ }
+ expect(screen.queryByRole("link", { name: /Learn more/ })).toBeNull();
+ expect(screen.queryByText("New skill")).toBeNull();
+ });
+
+ it("switches scope from the title menu, which counts each scope", async () => {
+ const user = userEvent.setup();
+ const header = renderPage();
+
+ await user.click(within(header).getByRole("button", { name: /All skills/ }));
+ expect(
+ await screen.findByRole("menuitemradio", { name: /All skills/ }),
+ ).toHaveTextContent("2");
+ const mine = screen.getByRole("menuitemradio", { name: /My skills/ });
+ expect(mine).toHaveTextContent("1");
+
+ await user.click(mine);
+ expect(
+ within(header).getByRole("heading", { name: "My skills", level: 1 }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("mine-skill")).toBeInTheDocument();
+ expect(screen.queryByText("team-skill")).toBeNull();
+ });
+
+ it("has no search, and offers Reset only while a filter narrows the list", () => {
+ const header = renderPage();
+ expect(within(header).queryByRole("textbox")).toBeNull();
+ expect(within(header).queryByRole("button", { name: /search/i })).toBeNull();
+ expect(within(header).queryByRole("button", { name: "Reset" })).toBeNull();
+ });
+
+ it("resets the filters", async () => {
+ const user = userEvent.setup();
+ mocks.viewState.filters.usage = ["used"];
+ try {
+ const header = renderPage();
+ await user.click(within(header).getByRole("button", { name: "Reset" }));
+ expect(mocks.viewState.clearFilters).toHaveBeenCalled();
+ } finally {
+ mocks.viewState.filters.usage = [];
+ }
+ });
+
+ it("offers every way to add a skill from the + menu and opens the dialog on it", async () => {
+ const user = userEvent.setup();
+ const header = renderPage();
+
+ await user.click(within(header).getByRole("button", { name: "New skill" }));
+ const menu = await screen.findByRole("menu");
+ expect(
+ within(menu).getAllByRole("menuitem").map((item) => item.textContent),
+ ).toEqual(["Create manually", "Import from local", "Import from URL", "Copy from runtime"]);
+
+ await user.click(within(menu).getByRole("menuitem", { name: "Import from URL" }));
+ expect(screen.getByTestId("create-dialog")).toHaveTextContent("url");
+ });
+});
diff --git a/packages/views/skills/components/skills-page.source-link.test.tsx b/packages/views/skills/components/skills-page.source-link.test.tsx
index c649050777..842bcc667a 100644
--- a/packages/views/skills/components/skills-page.source-link.test.tsx
+++ b/packages/views/skills/components/skills-page.source-link.test.tsx
@@ -115,7 +115,12 @@ vi.mock("@multica/ui/components/ui/tooltip", () => ({
TooltipContent: () => null,
}));
vi.mock("./create-skill-dialog", () => ({ CreateSkillDialog: () => null }));
-vi.mock("./skill-list-toolbar", () => ({ SkillListToolbar: () => null }));
+vi.mock("./skill-list-controls", () => ({
+ countActiveFilterDimensions: () => 0,
+ SkillFilterMenu: () => null,
+ SkillDisplayMenu: () => null,
+ SkillCreateMenu: () => null,
+}));
vi.mock("./skill-list-actions", () => ({
SkillBatchToolbar: () => null,
SkillRowActions: () => null,
@@ -220,13 +225,3 @@ describe("SkillsPage source link vs row navigation", () => {
);
});
});
-
-describe("SkillsPage docs link", () => {
- it("points Learn more at the viewer's docs locale", () => {
- renderPage(makeAdapter(), "fr");
-
- expect(
- screen.getByRole("link", { name: "En savoir plus →" }),
- ).toHaveAttribute("href", "https://multica.ai/docs/fr/skills");
- });
-});
diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsx
index 91d2f239bb..c8d6873279 100644
--- a/packages/views/skills/components/skills-page.tsx
+++ b/packages/views/skills/components/skills-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, useRef, useState } from "react";
+import { useMemo, useState } from "react";
import {
AlertCircle,
AlertTriangle,
@@ -8,7 +8,6 @@ import {
HardDrive,
Lock,
Pencil,
- Plus,
} from "@multica/ui/icons";
import { SkillIcon } from "../lib/skill-icon";
import type {
@@ -19,7 +18,6 @@ import type {
SkillSummary,
} from "@multica/core/types";
import { useQuery } from "@tanstack/react-query";
-import { useVirtualizer } from "@tanstack/react-virtual";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
@@ -32,123 +30,49 @@ import {
import { runtimeDisplayLabel, runtimeListOptions } from "@multica/core/runtimes";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { Button } from "@multica/ui/components/ui/button";
-import { Checkbox } from "@multica/ui/components/ui/checkbox";
-import {
- LIST_GRID_BOTTOM_CLEARANCE,
- ListGrid,
- ListGridBody,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
- type ListGridSortDirection,
-} from "@multica/ui/components/ui/list-grid";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
-import {
- rowLinkInteractiveProps,
- useNavigation,
- useRowLink,
-} from "../../navigation";
+import { rowLinkInteractiveProps, useNavigation } from "../../navigation";
import {
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
} from "../../layout/collection-page";
+import {
+ CollectionDisplayMenu,
+ CollectionList,
+ CollectionNameCell,
+ type CollectionColumn,
+ type CollectionSort,
+} from "../../layout/collection-list";
import { canEditSkill } from "../hooks/use-can-edit-skill";
import { originSourceUrl, readOrigin } from "../lib/origin";
import { rowMatchesFilters, type SkillRow } from "./skill-list-filter";
-import { CreateSkillDialog } from "./create-skill-dialog";
+import {
+ CreateSkillDialog,
+ type CreateSkillMethod,
+} from "./create-skill-dialog";
import {
useSkillsViewStore,
- DEFAULT_HIDDEN_COLUMNS,
type SkillColumnKey,
type SkillSortField,
} from "@multica/core/skills/stores";
-import { SkillListToolbar } from "./skill-list-toolbar";
+import {
+ SkillCreateMenu,
+ SkillFilterMenu,
+ countActiveFilterDimensions,
+} from "./skill-list-controls";
import {
SkillBatchToolbar,
SkillRowActions,
type SkillActionsContext,
} from "./skill-list-actions";
import { useT, useTimeAgo } from "../../i18n";
-import { docsLocalePrefix } from "../../common/docs-locale";
-
-// Column template — single source of truth for header, rows, and skeletons.
-// Tracks: [edge 0.75rem] [checkbox 1rem] [name, only fr track]
-// [usedBy] [source] [creator] [updated] [created] [kebab 1.75rem]
-// [edge 0.75rem].
-// Content cells carry a default px-2 from list-grid.tsx
-// (structural columns opt out with px-0), so the narrow edge tracks plus
-// cell padding land content 20px from the container edge. Non-core cells
-// carry `hidden @2xl:flex`. The breakpoint queries the CONTAINER (the page
-// wrapper is the `@container`), not the viewport, so sidebars and split
-// panes are accounted for.
-// Hideable tracks are DETERMINISTIC widths via CSS vars (no max-content):
-// rows are virtualized, so with only the visible slice mounted a
-// content-driven track would resize as different rows scrolled into view.
-// Truncation moved from per-cell max-w caps to the tracks themselves.
-// A user-hidden column zeroes its var (columnTrackVars), collapsing the
-// track exactly like the old max-content placeholder did; the empty
-// placeholder cell stays rendered to keep subgrid auto-placement intact.
-//
-// TWO-ZONE RESPONSIVENESS (replaces the retired per-tier breakpoints):
-// - Container ≥ @2xl (672px): WYSIWYG — every user-enabled column renders.
-// The grid carries min-width = Σ(enabled tracks + gaps) so when the
-// enabled set outgrows the container the wrapper scrolls horizontally.
-// The scrollbar is the escape valve for an over-provisioned column set,
-// never the default experience; an enabled column must NEVER silently
-// vanish (that "dead toggle" bug shipped twice).
-// - Container < @2xl (phones, slim split panes): static core set
-// (name + usedBy), no horizontal scroll, column toggles don't apply.
-const GRID_COLS =
- "grid-cols-[0.75rem_1rem_minmax(120px,1fr)_var(--lgc-usedby)_1.75rem_0.75rem] " +
- "@2xl:grid-cols-[0.75rem_1rem_minmax(200px,1fr)_var(--lgc-usedby)_var(--lgc-source)_var(--lgc-creator)_var(--lgc-updated)_var(--lgc-created)_1.75rem_0.75rem]";
-
-// h-12 rows. The virtualizer's fixed-size contract: every row renders at
-// exactly this height, which is what lets it skip per-row measurement.
-const ROW_HEIGHT = 48;
-
-// Single source for hideable column widths: track vars and the grid's
-// min-width derive from the same numbers.
-const COLUMN_WIDTHS: Record<SkillColumnKey, number> = {
- usedBy: 144,
- source: 152,
- creator: 144,
- updated: 104,
- created: 104,
-};
-
-// Fixed tracks (edges 12+12, checkbox 16, name min 200, kebab 28) plus the
-// 9 gap-x-3 gaps between the wide template's 10 tracks (zero-width tracks
-// still carry gaps).
-const FIXED_TRACKS_WIDTH = 268 + 9 * 12;
-
-function columnTrackVars(
- isVisible: (key: SkillColumnKey) => boolean,
-): React.CSSProperties {
- const width = (key: SkillColumnKey) =>
- isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";
- const minWidth =
- FIXED_TRACKS_WIDTH +
- (Object.keys(COLUMN_WIDTHS) as SkillColumnKey[]).reduce(
- (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),
- 0,
- );
- return {
- "--lgc-usedby": width("usedBy"),
- "--lgc-source": width("source"),
- "--lgc-creator": width("creator"),
- "--lgc-updated": width("updated"),
- "--lgc-created": width("created"),
- "--lgc-minw": `${minWidth}px`,
- } as React.CSSProperties;
-}
// Sort/filter/column types and defaults live in the core view store
// (@multica/core/skills/stores/view-store) so the persisted state and the
@@ -156,131 +80,55 @@ function columnTrackVars(
export type SortField = SkillSortField;
export { rowMatchesFilters, type SkillRow } from "./skill-list-filter";
-// Page header bar — uses shared PageHeader so the mobile sidebar trigger and
-// h-12 chrome stay consistent with every other dashboard list page.
-
-function PageHeaderBar({
- totalCount,
- onCreate,
-}: {
- totalCount: number;
- onCreate: () => void;
-}) {
- const { t, i18n } = useT("skills");
- return (
- <CollectionPageHeader
- icon={SkillIcon}
- title={t(($) => $.page.title)}
- count={totalCount}
- learnMore={{
- href: `https://multica.ai/docs${docsLocalePrefix(i18n.language)}/skills`,
- label: t(($) => $.page.learn_more),
- }}
- actions={
- <CollectionPageHeaderAction
- icon={Plus}
- label={t(($) => $.page.new_skill)}
- onClick={onCreate}
- />
- }
- />
- );
-}
+type SkillScope = "all" | "mine";
// Cells
-// Hover-revealed multi-select checkbox. Same pattern as SkillPickerList:
-// the shadcn Checkbox is presentational only (`pointer-events-none`, so the
-// Base UI button can never swallow the click) and the wrapping <button> owns
-// the toggle. It stops click propagation so toggling never triggers the
-// row's whole-row navigation (see `useRowLink`) — no preventDefault needed,
-// the row is a plain <div>, not an <a>.
-function CheckboxCell({
- checked,
- onToggle,
-}: {
- checked: boolean;
- onToggle: () => void;
-}) {
- return (
- <ListGridCell className="justify-center px-0">
- <button
- type="button"
- aria-pressed={checked}
- onClick={(e) => {
- e.stopPropagation();
- onToggle();
- }}
- className={`-m-1.5 flex items-center p-1.5 ${
- checked ? "" : "opacity-0 transition-opacity group-hover/row:opacity-100"
- }`}
- >
- <Checkbox
- checked={checked}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
- </ListGridCell>
- );
-}
-
function NameCell({ row }: { row: SkillRow }) {
const { t } = useT("skills");
const { skill, canEdit } = row;
return (
- <ListGridCell className="gap-1.5">
- <span className="min-w-0 truncate text-body font-medium">
- {skill.name}
- </span>
- {!canEdit && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Lock className="h-3 w-3 shrink-0 text-faint-foreground" />
- }
- />
- <TooltipContent>{t(($) => $.table.lock_tooltip)}</TooltipContent>
- </Tooltip>
- )}
- </ListGridCell>
+ <CollectionNameCell
+ icon={<SkillIcon className="size-4 shrink-0 text-muted-foreground" />}
+ title={skill.name}
+ badges={
+ !canEdit && (
+ <Tooltip>
+ <TooltipTrigger
+ render={<Lock className="h-3 w-3 shrink-0 text-faint-foreground" />}
+ />
+ <TooltipContent>{t(($) => $.table.lock_tooltip)}</TooltipContent>
+ </Tooltip>
+ )
+ }
+ description={skill.description || undefined}
+ />
);
}
function UsedByCell({ agents }: { agents: Agent[] }) {
const { t } = useT("skills");
- if (agents.length === 0) {
- return (
- <ListGridCell>
- <span className="text-caption text-muted-foreground">
- {t(($) => $.table.unused)}
- </span>
- </ListGridCell>
- );
- }
+ if (agents.length === 0) return <span>{t(($) => $.table.unused)}</span>;
const soleAgent = agents.length === 1 ? agents[0] : undefined;
if (soleAgent) {
const agent = soleAgent;
return (
- <ListGridCell className="gap-1.5">
+ <>
<ActorAvatar
name={agent.name}
initials={agent.name.slice(0, 2).toUpperCase()}
avatarUrl={resolvePublicFileUrl(agent.avatar_url)}
isAgent
- size="md"
+ size="sm"
/>
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {agent.name}
- </span>
- </ListGridCell>
+ <span className="min-w-0 truncate">{agent.name}</span>
+ </>
);
}
const visible = agents.slice(0, 3);
const extra = agents.length - visible.length;
return (
- <ListGridCell>
- <div className="flex items-center -space-x-1.5">
+ <div className="flex items-center -space-x-1.5">
{visible.map((a) => (
<Tooltip key={a.id}>
<TooltipTrigger
@@ -291,7 +139,7 @@ function UsedByCell({ agents }: { agents: Agent[] }) {
initials={a.name.slice(0, 2).toUpperCase()}
avatarUrl={resolvePublicFileUrl(a.avatar_url)}
isAgent
- size="md"
+ size="sm"
/>
</span>
}
@@ -300,12 +148,11 @@ function UsedByCell({ agents }: { agents: Agent[] }) {
</Tooltip>
))}
{extra > 0 && (
- <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-caption font-medium text-muted-foreground ring-2 ring-background">
+ <span className="inline-flex size-5 items-center justify-center rounded-full bg-muted text-micro font-medium text-muted-foreground ring-2 ring-background">
+{extra}
</span>
)}
- </div>
- </ListGridCell>
+ </div>
);
}
@@ -346,7 +193,7 @@ function SourceCell({
const sourceUrl = originSourceUrl(origin);
return (
- <ListGridCell className="hidden gap-1.5 text-caption text-muted-foreground @2xl:flex">
+ <>
{icon}
{sourceUrl ? (
<Tooltip>
@@ -368,202 +215,38 @@ function SourceCell({
) : (
<span className="min-w-0 truncate">{label}</span>
)}
- </ListGridCell>
+ </>
);
}
function CreatorCell({ creator }: { creator: MemberWithUser | null }) {
+ if (!creator) return null;
return (
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
- {creator && (
- <>
- <ActorAvatar
- name={creator.name}
- initials={creator.name.slice(0, 2).toUpperCase()}
- avatarUrl={resolvePublicFileUrl(creator.avatar_url)}
- size="md"
- />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {creator.name}
- </span>
- </>
- )}
- </ListGridCell>
+ <>
+ <ActorAvatar
+ name={creator.name}
+ initials={creator.name.slice(0, 2).toUpperCase()}
+ avatarUrl={resolvePublicFileUrl(creator.avatar_url)}
+ size="sm"
+ />
+ <span className="min-w-0 truncate">{creator.name}</span>
+ </>
);
}
// Empty state
-function EmptyState({ onCreate }: { onCreate: () => void }) {
+function EmptyState() {
const { t } = useT("skills");
return (
<CollectionPageState
icon={SkillIcon}
title={t(($) => $.page.empty.title)}
description={t(($) => $.page.empty.description)}
- actions={
- <Button type="button" onClick={onCreate} size="sm">
- <Plus aria-hidden="true" className="size-3" />
- {t(($) => $.page.new_skill)}
- </Button>
- }
/>
);
}
-// List
-
-function SkillListHeader({
- sortField,
- sortDirection,
- onSort,
- allSelected,
- someSelected,
- onToggleAll,
- isColVisible,
-}: {
- sortField: SortField;
- sortDirection: ListGridSortDirection;
- onSort: (field: SortField) => void;
- allSelected: boolean;
- someSelected: boolean;
- onToggleAll: () => void;
- isColVisible: (key: SkillColumnKey) => boolean;
-}) {
- const { t } = useT("skills");
- const sorted = (field: SortField) =>
- sortField === field ? sortDirection : false;
- const anySelected = allSelected || someSelected;
- return (
- <ListGridHeader>
- {/* Tri-state select-all in the checkbox track. Same presentational
- Checkbox + interactive wrapper pattern as the row cells; revealed
- on header hover or whenever a selection exists. */}
- <div className="flex items-center justify-center">
- <button
- type="button"
- aria-pressed={allSelected}
- onClick={onToggleAll}
- className={`-m-1.5 flex items-center p-1.5 ${
- anySelected
- ? ""
- : "opacity-0 transition-opacity group-hover/header:opacity-100"
- }`}
- >
- <Checkbox
- checked={allSelected}
- indeterminate={someSelected && !allSelected}
- tabIndex={-1}
- className="pointer-events-none"
- />
- </button>
- </div>
- <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>
- {t(($) => $.table.name)}
- </ListGridHeaderCell>
- {isColVisible("usedBy") ? (
- <ListGridHeaderCell
- sorted={sorted("usedBy")}
- onSort={() => onSort("usedBy")}
- >
- {t(($) => $.table.used_by)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="px-0" />
- )}
- {isColVisible("source") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.table.source)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("creator") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.table.created_by)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("updated") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("updated")}
- onSort={() => onSort("updated")}
- >
- {t(($) => $.table.updated)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("created")}
- onSort={() => onSort("created")}
- >
- {t(($) => $.table.created)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- <span aria-hidden="true" />
- </ListGridHeader>
- );
-}
-
-function LoadingSkeleton() {
- return (
- <ListGrid
- className={GRID_COLS}
- style={columnTrackVars((key) => !DEFAULT_HIDDEN_COLUMNS.includes(key))}
- >
- <ListGridHeader>
- <span aria-hidden="true" />
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-14" />
- </ListGridHeaderCell>
- {/* Source and created are hidden by default — keep their tracks
- mapped with empty placeholders so the skeleton matches the
- default layout. */}
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-10" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridHeader>
- {Array.from({ length: 5 }).map((_, i) => (
- <ListGridRow key={i} className="hover:bg-transparent">
- <span aria-hidden="true" />
- <ListGridCell>
- <Skeleton className="h-3.5 w-40 max-w-full" />
- </ListGridCell>
- <ListGridCell>
- <Skeleton className="h-5 w-14" />
- </ListGridCell>
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
- <Skeleton className="size-5 rounded-full" />
- <Skeleton className="h-3 w-12" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-10" />
- </ListGridCell>
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridRow>
- ))}
- </ListGrid>
- );
-}
-
// Page
export default function SkillsPage() {
@@ -571,7 +254,6 @@ export default function SkillsPage() {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
- const rowLink = useRowLink();
const timeAgo = useTimeAgo();
const currentUserId = useAuthStore((s) => s.user?.id ?? null);
@@ -591,16 +273,17 @@ export default function SkillsPage() {
runtimeListOptions(wsId),
);
- const [createOpen, setCreateOpen] = useState(false);
+ const [createMethod, setCreateMethod] = useState<CreateSkillMethod | null>(
+ null,
+ );
const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(
new Set(),
);
- const [search, setSearch] = useState("");
+ const [scope, setScope] = useState<SkillScope>("all");
// Persisted view preferences (per workspace, per user/device). Header sort
- // buttons and the toolbar's display panel mutate the SAME store, so both
- // surfaces always agree. Search and selection stay session-local on
- // purpose.
+ // buttons and the header's display panel mutate the SAME store, so both
+ // surfaces always agree. Selection stays session-local on purpose.
const sortField = useSkillsViewStore((s) => s.sortField);
const sortDirection = useSkillsViewStore((s) => s.sortDirection);
const hiddenColumns = useSkillsViewStore((s) => s.hiddenColumns);
@@ -612,17 +295,6 @@ export default function SkillsPage() {
const toggleFilter = useSkillsViewStore((s) => s.toggleFilter);
const clearFilters = useSkillsViewStore((s) => s.clearFilters);
- const isColVisible = (key: SkillColumnKey) => !hiddenColumns.includes(key);
-
- const toggleSelected = (id: string) => {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- };
-
const assignments = useMemo(() => selectSkillAssignments(agents), [agents]);
const membersById = useMemo(() => {
@@ -649,7 +321,6 @@ export default function SkillsPage() {
isAdmin,
};
- // Full assembled set — toolbar option lists and counts derive from this.
const allRows = useMemo<SkillRow[]>(() => {
return skills.map((skill) => {
const origin = readOrigin(skill);
@@ -670,11 +341,20 @@ export default function SkillsPage() {
});
}, [skills, assignments, membersById, runtimesById, currentUserId, myRole]);
- // Visible rows: name search + filters, then sort.
+ const mineRows = useMemo(
+ () =>
+ currentUserId
+ ? allRows.filter((row) => row.skill.created_by === currentUserId)
+ : [],
+ [allRows, currentUserId],
+ );
+ // The current scope, unfiltered — filter option lists and counts derive
+ // from this.
+ const scopeRows = scope === "mine" ? mineRows : allRows;
+
+ // Visible rows: filters, then sort.
const rows = useMemo<SkillRow[]>(() => {
- const filtered = allRows.filter((row) =>
- rowMatchesFilters(row, filters, search),
- );
+ const filtered = scopeRows.filter((row) => rowMatchesFilters(row, filters));
const dir = sortDirection === "asc" ? 1 : -1;
filtered.sort((a, b) => {
@@ -698,41 +378,130 @@ export default function SkillsPage() {
);
});
return filtered;
- }, [allRows, search, filters, sortField, sortDirection]);
-
- // Row virtualization — Linear-style: the virtualizer only does the math
- // (visible index range + offsets); the DOM stays ours. Offsets become
- // padding on the rows wrapper, so the mounted rows remain direct subgrid
- // children and column alignment is untouched. Fixed ROW_HEIGHT rows mean
- // no per-row measurement. The scroll element is the SINGLE outer
- // scroller (both axes) — see ListGridBody's comment for why the split
- // scroll structure was retired.
- const listScrollRef = useRef<HTMLDivElement | null>(null);
- const rowVirtualizer = useVirtualizer({
- count: rows.length,
- getScrollElement: () => listScrollRef.current,
- estimateSize: () => ROW_HEIGHT,
- overscan: 10,
- });
+ }, [scopeRows, filters, sortField, sortDirection]);
const handleCreated = (skill: Skill) => {
navigation.push(paths.skillDetail(skill.id));
};
const selectedRows = rows.filter((row) => selectedIds.has(row.skill.id));
- const allSelected = rows.length > 0 && selectedRows.length === rows.length;
- const someSelected = selectedRows.length > 0 && !allSelected;
- const handleToggleAll = () => {
- setSelectedIds(
- allSelected ? new Set() : new Set(rows.map((r) => r.skill.id)),
- );
+
+ const columns = useMemo<CollectionColumn<SkillRow>[]>(
+ () => [
+ {
+ key: "name",
+ header: t(($) => $.table.name),
+ sortKey: "name",
+ cell: (row) => <NameCell row={row} />,
+ },
+ {
+ key: "usedBy",
+ header: t(($) => $.table.used_by),
+ width: 144,
+ sortKey: "usedBy",
+ core: true,
+ hideable: true,
+ cell: (row) => <UsedByCell agents={row.agents} />,
+ },
+ {
+ key: "source",
+ header: t(($) => $.table.source),
+ width: 152,
+ hideable: true,
+ cell: (row) => <SourceCell skill={row.skill} runtime={row.runtime} />,
+ },
+ {
+ key: "creator",
+ header: t(($) => $.table.created_by),
+ width: 144,
+ hideable: true,
+ cell: (row) => <CreatorCell creator={row.creator} />,
+ },
+ {
+ key: "updated",
+ header: t(($) => $.table.updated),
+ width: 104,
+ sortKey: "updated",
+ hideable: true,
+ cell: (row) => <span className="tabular-nums">{timeAgo(row.skill.updated_at)}</span>,
+ },
+ {
+ key: "created",
+ header: t(($) => $.table.created),
+ width: 104,
+ sortKey: "created",
+ hideable: true,
+ cell: (row) => <span className="tabular-nums">{timeAgo(row.skill.created_at)}</span>,
+ },
+ ],
+ [t, timeAgo],
+ );
+
+ const sort: CollectionSort = {
+ field: sortField,
+ direction: sortDirection,
+ onToggle: (field) => handleSort(field as SkillSortField),
+ onFieldChange: (field) => handleSortFieldSelect(field as SkillSortField),
+ onDirectionChange: setSortDirection,
+ };
+
+ const narrowed = countActiveFilterDimensions(filters) > 0;
+ const scopeLabels: Record<SkillScope, string> = {
+ all: t(($) => $.page.scopes.all.label),
+ mine: t(($) => $.page.scopes.mine.label),
};
+ const header = (
+ <CollectionPageHeader
+ icon={SkillIcon}
+ title={scopeLabels[scope]}
+ menu={
+ <CollectionScopeItems
+ value={scope}
+ onChange={setScope}
+ options={[
+ { value: "all", label: scopeLabels.all, count: allRows.length },
+ { value: "mine", label: scopeLabels.mine, count: mineRows.length },
+ ]}
+ />
+ }
+ tools={
+ <>
+ <SkillFilterMenu
+ filters={filters}
+ onToggleFilter={toggleFilter}
+ rows={scopeRows}
+ />
+ {narrowed && <CollectionResetButton onClick={clearFilters} />}
+ </>
+ }
+ actions={
+ <>
+ <CollectionDisplayMenu
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ onToggleColumn={(key) => toggleColumn(key as SkillColumnKey)}
+ sort={sort}
+ />
+ <SkillCreateMenu onCreate={setCreateMethod} />
+ </>
+ }
+ />
+ );
+
+ const createDialog = createMethod && (
+ <CreateSkillDialog
+ initialMethod={createMethod}
+ onClose={() => setCreateMethod(null)}
+ onCreated={handleCreated}
+ />
+ );
+
// --- List request error ---
if (listError) {
return (
<div className="flex flex-1 min-h-0 flex-col">
- <PageHeaderBar totalCount={0} onCreate={() => setCreateOpen(true)} />
+ {header}
<CollectionPageState
role="alert"
tone="destructive"
@@ -754,35 +523,20 @@ export default function SkillsPage() {
</Button>
}
/>
+ {createDialog}
</div>
);
}
- const totalCount = skills.length;
- const showEmpty = !isLoading && totalCount === 0;
+ const showEmpty = !isLoading && skills.length === 0;
const supportingQueryDown =
!!agentsError || !!membersError || !!runtimesError;
- // Unmounted rows above/below the visible slice become padding on the
- // scrolling body, exactly like Linear's --x-paddingTop/Bottom offsets.
- const virtualItems = rowVirtualizer.getVirtualItems();
- const firstVirtual = virtualItems[0];
- const lastVirtual = virtualItems[virtualItems.length - 1];
- const virtualPadding = {
- top: firstVirtual ? firstVirtual.start : 0,
- bottom: lastVirtual
- ? rowVirtualizer.getTotalSize() - lastVirtual.end
- : 0,
- };
-
return (
// relative: positioning anchor for the batch toolbar (page-centered,
// not viewport-centered).
<div className="relative flex flex-1 min-h-0 flex-col">
- <PageHeaderBar
- totalCount={totalCount}
- onCreate={() => setCreateOpen(true)}
- />
+ {header}
{supportingQueryDown && (
<div
@@ -796,117 +550,23 @@ export default function SkillsPage() {
{showEmpty ? (
<div className="flex flex-1 items-center justify-center">
- <EmptyState onCreate={() => setCreateOpen(true)} />
+ <EmptyState />
</div>
) : (
- <>
- {/* Mounted through loading so the rows don't drop by a toolbar's
- height when the list lands. */}
- <SkillListToolbar
- search={search}
- onSearchChange={setSearch}
- filters={filters}
- onToggleFilter={toggleFilter}
- onClearFilters={clearFilters}
- sortField={sortField}
- sortDirection={sortDirection}
- onSortFieldChange={handleSortFieldSelect}
- onSortDirectionChange={setSortDirection}
- hiddenColumns={hiddenColumns}
- onToggleColumn={toggleColumn}
- allRows={allRows}
- visibleCount={rows.length}
- />
- {isLoading ? (
- <div className="flex-1 overflow-y-auto @container">
- <LoadingSkeleton />
- </div>
- ) : (
- <div
- ref={listScrollRef}
- className="min-h-0 flex-1 overflow-auto @container"
- >
- <ListGrid
- className={`${GRID_COLS} @2xl:min-w-[var(--lgc-minw)]`}
- style={columnTrackVars(isColVisible)}
- >
- <SkillListHeader
- sortField={sortField}
- sortDirection={sortDirection}
- onSort={handleSort}
- allSelected={allSelected}
- someSelected={someSelected}
- onToggleAll={handleToggleAll}
- isColVisible={isColVisible}
- />
- <ListGridBody
- style={{
- paddingTop: virtualPadding.top,
- paddingBottom:
- virtualPadding.bottom + LIST_GRID_BOTTOM_CLEARANCE,
- }}
- >
- {rows.length === 0 && (
- <div className="col-span-full py-16 text-center text-body text-muted-foreground">
- {t(($) => $.page.no_matches.title)}
- </div>
- )}
- {virtualItems.map((vi) => {
- const row = rows[vi.index];
- if (!row) return null;
- return (
- <ListGridRow
- key={row.skill.id}
- className={`cursor-pointer ${
- selectedIds.has(row.skill.id) ? "bg-accent/30" : ""
- }`}
- {...rowLink(paths.skillDetail(row.skill.id), row.skill.name)}
- >
- <CheckboxCell
- checked={selectedIds.has(row.skill.id)}
- onToggle={() => toggleSelected(row.skill.id)}
- />
- <NameCell row={row} />
- {isColVisible("usedBy") ? (
- <UsedByCell agents={row.agents} />
- ) : (
- <ListGridCell className="px-0" />
- )}
- {isColVisible("source") ? (
- <SourceCell skill={row.skill} runtime={row.runtime} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("creator") ? (
- <CreatorCell creator={row.creator} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("updated") ? (
- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">
- {timeAgo(row.skill.updated_at)}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">
- {timeAgo(row.skill.created_at)}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- <ListGridCell className="justify-end px-0">
- <SkillRowActions row={row} ctx={actionsCtx} />
- </ListGridCell>
- </ListGridRow>
- );
- })}
- </ListGridBody>
- </ListGrid>
- </div>
- )}
- </>
+ <CollectionList
+ label={scopeLabels[scope]}
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ rows={rows}
+ loading={isLoading}
+ getRowId={(row) => row.skill.id}
+ getRowHref={(row) => paths.skillDetail(row.skill.id)}
+ getRowTitle={(row) => row.skill.name}
+ rowMenu={(row) => <SkillRowActions row={row} ctx={actionsCtx} />}
+ sort={sort}
+ selection={{ selectedIds, onChange: setSelectedIds }}
+ empty={t(($) => $.page.no_matches.title)}
+ />
)}
<SkillBatchToolbar
@@ -915,12 +575,7 @@ export default function SkillsPage() {
onClear={() => setSelectedIds(new Set())}
/>
- {createOpen && (
- <CreateSkillDialog
- onClose={() => setCreateOpen(false)}
- onCreated={handleCreated}
- />
- )}
+ {createDialog}
</div>
);
}
diff --git a/packages/views/squads/components/squad-detail-page.test.tsx b/packages/views/squads/components/squad-detail-page.test.tsx
new file mode 100644
index 0000000000..894ca19975
--- /dev/null
+++ b/packages/views/squads/components/squad-detail-page.test.tsx
@@ -0,0 +1,334 @@
+import type React from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { Issue, Squad, SquadMember, SquadMemberStatus } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import { SquadDetailPage } from "./squad-detail-page";
+
+type QueryResult = { data?: unknown; isError?: boolean; isPending?: boolean };
+
+const mocks = vi.hoisted(() => ({
+ queries: {} as Record<string, QueryResult>,
+ userId: "creator",
+ openModal: vi.fn(),
+ copyText: vi.fn(),
+ api: {
+ updateSquad: vi.fn(),
+ deleteSquad: vi.fn(),
+ removeSquadMember: vi.fn(),
+ },
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: (options: { queryKey?: readonly unknown[] }) => ({
+ isError: false,
+ isPending: false,
+ refetch: vi.fn(),
+ ...mocks.queries[(options.queryKey ?? []).join("/")],
+ }),
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
+ useMutation: ({ mutationFn }: { mutationFn: (input?: unknown) => Promise<unknown> }) => ({
+ mutate: (input?: unknown) => void mutationFn(input),
+ mutateAsync: (input?: unknown) => mutationFn(input),
+ isPending: false,
+ }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: () => ({ queryKey: ["agents"] }),
+ memberListOptions: () => ({ queryKey: ["members"] }),
+ squadMemberStatusOptions: () => ({ queryKey: ["member-status"] }),
+ workspaceKeys: { squads: () => ["squads"] },
+}));
+vi.mock("@multica/core/api", () => ({ api: mocks.api }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (select: (s: { user: { id: string } }) => unknown) => select({ user: { id: mocks.userId } }),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-1", slug: "acme" }),
+ useWorkspacePaths: () => ({
+ squads: () => "/acme/squads",
+ newAgent: () => "/acme/agents/new",
+ agentDetail: (id: string) => `/acme/agents/${id}`,
+ issueDetail: (id: string) => `/acme/issues/${id}`,
+ }),
+}));
+vi.mock("@multica/core/modals", () => ({
+ useModalStore: { getState: () => ({ open: mocks.openModal }) },
+}));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => ({ categoryOf: () => "started", colorOf: () => undefined, iconOf: () => undefined }),
+}));
+vi.mock("../../issues/utils/status-label", () => ({
+ useStatusLabel: () => (status: string) => (status === "in_progress" ? "In Progress" : status),
+}));
+vi.mock("../../issues/components/status-icon", () => ({ StatusIcon: () => null }));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("../../common/avatar-upload-control", () => ({
+ AvatarUploadControl: () => <span data-testid="avatar-upload" />,
+}));
+vi.mock("../../editor/readonly-content", () => ({
+ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+vi.mock("../../editor/content-editor", () => ({
+ ContentEditor: ({ value, onUpdate }: { value: string; onUpdate: (v: string) => void }) => (
+ <textarea
+ aria-label="Instructions editor"
+ value={value}
+ onChange={(event: React.ChangeEvent<HTMLTextAreaElement>) => onUpdate(event.target.value)}
+ />
+ ),
+}));
+vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: mocks.copyText }));
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+// jsdom gives every element a zero-size rect, so a live resize handle claims
+// every pointerdown on the page and no menu could open.
+vi.mock("react-resizable-panels", () => ({
+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
+ usePanelRef: () => ({
+ current: { isCollapsed: () => false, expand: vi.fn(), collapse: vi.fn() },
+ }),
+}));
+vi.mock("@multica/ui/components/ui/resizable", () => ({
+ ResizablePanelGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ ResizablePanel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ ResizableHandle: () => null,
+}));
+
+const SQUAD: Squad = {
+ id: "sq-1",
+ workspace_id: "ws-1",
+ name: "Strike Team",
+ description: "Ships the risky stuff",
+ instructions: "Start with a failing test.",
+ avatar_url: null,
+ leader_id: "agent-lead",
+ creator_id: "creator",
+ created_at: "2026-10-01T00:00:00Z",
+ updated_at: "2026-10-02T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+};
+
+function member(id: string, type: "agent" | "member", role = ""): SquadMember {
+ return { id: `m-${id}`, squad_id: "sq-1", member_type: type, member_id: id, role, created_at: SQUAD.created_at };
+}
+
+const MEMBERS = [member("agent-lead", "agent", "Coordinator"), member("agent-2", "agent"), member("creator", "member")];
+
+const STATUSES: SquadMemberStatus[] = [
+ {
+ member_type: "agent",
+ member_id: "agent-2",
+ status: "working",
+ active_issues: [
+ { issue_id: "i-1", identifier: "ARIE-2", title: "Fix login", issue_status: "in_progress" },
+ ],
+ last_active_at: null,
+ } as SquadMemberStatus,
+];
+
+const ISSUE = {
+ id: "i-1",
+ identifier: "ARIE-2",
+ title: "Fix login",
+ status: "in_progress",
+ updated_at: "2026-10-02T00:00:00Z",
+} as Issue;
+
+function seed(squad: Squad | undefined = SQUAD, extra: Record<string, QueryResult> = {}) {
+ mocks.queries = {
+ "squads/sq-1": { data: squad },
+ "squads/sq-1/members": { data: MEMBERS },
+ "member-status": { data: { members: STATUSES } },
+ "squads/sq-1/recent-issues": { data: { issues: [ISSUE], total: 1 } },
+ agents: {
+ data: [
+ { id: "agent-lead", name: "Lambda", archived_at: null },
+ { id: "agent-2", name: "Kappa", archived_at: null },
+ ],
+ },
+ members: {
+ data: [
+ { user_id: "creator", name: "Jiayuan", role: "member" },
+ { user_id: "viewer", name: "Viewer", role: "member" },
+ ],
+ },
+ ...extra,
+ };
+}
+
+function renderPage(search = "") {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/squads/sq-1",
+ searchParams: new URLSearchParams(search),
+ hash: "",
+ getShareableUrl: (path) => `https://multica.test${path}`,
+ };
+ renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <SquadDetailPage />
+ </NavigationProvider>,
+ );
+ return adapter;
+}
+
+function section(name: string) {
+ return screen.getByRole("heading", { level: 2, name }).closest("section") as HTMLElement;
+}
+
+beforeEach(() => {
+ seed();
+ mocks.userId = "creator";
+ mocks.openModal.mockReset();
+ mocks.copyText.mockReset().mockResolvedValue(true);
+ mocks.api.updateSquad.mockReset().mockResolvedValue(SQUAD);
+ mocks.api.deleteSquad.mockReset().mockResolvedValue(undefined);
+ mocks.api.removeSquadMember.mockReset().mockResolvedValue(undefined);
+});
+
+describe("SquadDetailPage", () => {
+ it("puts the squads list in the breadcrumb and the squad in the leaf", () => {
+ renderPage();
+ const header = screen.getByRole("banner");
+ expect(within(header).getByRole("link", { name: "Squads" })).toHaveAttribute("href", "/acme/squads");
+ expect(within(header).getByText("Strike Team")).toBeInTheDocument();
+ expect(within(header).queryByRole("tab")).toBeNull();
+ });
+
+ it("assigns work to the squad from the header's one solid action", async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(screen.getByRole("button", { name: "Assign work" }));
+ expect(mocks.openModal).toHaveBeenCalledWith("create-issue", {
+ assignee_type: "squad",
+ assignee_id: "sq-1",
+ });
+ });
+
+ it("keeps the other page actions in the more menu", async () => {
+ const user = userEvent.setup();
+ const { push } = renderPage();
+
+ await user.click(screen.getByRole("button", { name: "More actions" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Copy link" }));
+ expect(mocks.copyText).toHaveBeenCalledWith("https://multica.test/acme/squads/sq-1");
+
+ await user.click(screen.getByRole("button", { name: "More actions" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Create Agent" }));
+ expect(push).toHaveBeenCalledWith("/acme/agents/new?squad=sq-1");
+
+ await user.click(screen.getByRole("button", { name: "More actions" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Archive" }));
+ await user.click(await screen.findByRole("button", { name: "Archive" }));
+ expect(mocks.api.deleteSquad).toHaveBeenCalledWith("sq-1");
+ });
+
+ it("shows identity, members, instructions and recent work as sections", () => {
+ renderPage();
+
+ expect(screen.getByRole("heading", { level: 1, name: "Strike Team" })).toBeInTheDocument();
+ expect(screen.getByText("Ships the risky stuff")).toBeInTheDocument();
+
+ const members = section("Members");
+ expect(within(members).getByText("3")).toBeInTheDocument();
+ expect(within(members).getByRole("button", { name: "Add member" })).toBeInTheDocument();
+ expect(within(members).getByText("Lambda")).toBeInTheDocument();
+ expect(within(members).getByText("Leader")).toBeInTheDocument();
+ expect(within(members).getByText("Working on")).toBeInTheDocument();
+ expect(within(members).getByRole("link", { name: "ARIE-2" })).toHaveAttribute("href", "/acme/issues/i-1");
+
+ expect(within(section("Instructions")).getByText("Start with a failing test.")).toBeInTheDocument();
+ expect(within(section("Instructions")).getByRole("button", { name: "Edit" })).toBeInTheDocument();
+
+ const recent = section("Recent work");
+ expect(within(recent).getByRole("link", { name: /Fix login/ })).toHaveAttribute("href", "/acme/issues/i-1");
+ });
+
+ it("keeps per-member actions in the row menu", async () => {
+ const user = userEvent.setup();
+ const { push } = renderPage();
+
+ await user.click(screen.getByRole("button", { name: "Actions for Kappa" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Make squad leader" }));
+ expect(mocks.api.updateSquad).toHaveBeenCalledWith("sq-1", { leader_id: "agent-2" });
+
+ await user.click(screen.getByRole("button", { name: "Actions for Kappa" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Open agent detail" }));
+ expect(push).toHaveBeenCalledWith("/acme/agents/agent-2");
+
+ await user.click(screen.getByRole("button", { name: "Actions for Jiayuan" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Remove from squad" }));
+ expect(mocks.api.removeSquadMember).toHaveBeenCalledWith("sq-1", {
+ member_type: "member",
+ member_id: "creator",
+ });
+ });
+
+ it("edits instructions in place", async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.click(within(section("Instructions")).getByRole("button", { name: "Edit" }));
+ const editor = screen.getByRole("textbox", { name: "Instructions editor" });
+ await user.clear(editor);
+ await user.type(editor, "Ship small.");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ expect(mocks.api.updateSquad).toHaveBeenCalledWith("sq-1", { instructions: "Ship small." });
+ });
+
+ it("lists the squad's properties in the panel", () => {
+ renderPage();
+
+ expect(screen.getByRole("button", { name: "Toggle right sidebar" })).toBeInTheDocument();
+ expect(screen.getByText("Properties")).toBeInTheDocument();
+ expect(screen.getByText("Visibility")).toBeInTheDocument();
+ expect(screen.getByText("Workspace")).toBeInTheDocument();
+ expect(screen.getByText("3 members")).toBeInTheDocument();
+ expect(screen.getByText("Created by")).toBeInTheDocument();
+ });
+
+ it("gives viewers who cannot manage the squad a read-only page", async () => {
+ const user = userEvent.setup();
+ mocks.userId = "viewer";
+ renderPage();
+
+ expect(screen.getByRole("button", { name: "Assign work" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Add member" })).toBeNull();
+ expect(within(section("Instructions")).queryByRole("button", { name: "Edit" })).toBeNull();
+ expect(screen.queryByTestId("avatar-upload")).toBeNull();
+
+ await user.click(screen.getByRole("button", { name: "More actions" }));
+ expect(await screen.findByRole("menuitem", { name: "Copy link" })).toBeInTheDocument();
+ expect(screen.queryByRole("menuitem", { name: "Archive" })).toBeNull();
+ });
+
+ it("drops assigning and editing on an archived squad", () => {
+ seed({ ...SQUAD, archived_at: "2026-10-03T00:00:00Z" });
+ renderPage();
+
+ expect(screen.queryByRole("button", { name: "Assign work" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Add member" })).toBeNull();
+ expect(screen.getAllByText("Archived").length).toBeGreaterThan(0);
+ });
+
+ it("ignores a legacy ?tab= link", () => {
+ renderPage("tab=instructions");
+ expect(screen.getByRole("heading", { level: 1, name: "Strike Team" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 2, name: "Members" })).toBeInTheDocument();
+ });
+
+ it("shows not found in the body when the squad fails to load", () => {
+ seed(undefined, { "squads/sq-1": { data: undefined, isError: true } });
+ renderPage();
+ expect(screen.getByRole("link", { name: "Squads" })).toBeInTheDocument();
+ expect(screen.getByText("Squad not found")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsx
index 790cfae862..2ab1f15e58 100644
--- a/packages/views/squads/components/squad-detail-page.tsx
+++ b/packages/views/squads/components/squad-detail-page.tsx
@@ -6,30 +6,59 @@ import { api } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useModalStore } from "@multica/core/modals";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { isImeComposing } from "@multica/core/utils";
import { getShortcut, shortcutMatchesEvent } from "@multica/core/shortcuts";
-import { useTimeAgo } from "../../i18n";
+import { useLocale, useT, useTimeAgo } from "../../i18n";
import { agentListOptions, memberListOptions, squadMemberStatusOptions, workspaceKeys } from "@multica/core/workspace/queries";
-import { useNavigation } from "../../navigation";
-import { AppLink } from "../../navigation";
-import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
-import { PageHeader } from "../../layout/page-header";
-import { Users, Plus, Trash2, ArrowUpRight, Crown, Loader2, Pencil, FileText, Save } from "@multica/ui/icons";
+import { AppLink, currentPath, useNavigation } from "../../navigation";
+import {
+ OBJECT_PAGE_BODY,
+ ObjectIdentity,
+ ObjectPage,
+ ObjectPanelSection,
+ ObjectProperty,
+ ObjectSection,
+ ObjectSectionAction,
+ ObjectSectionCard,
+} from "../../layout/object-page";
+import { CollectionPageState } from "../../layout/collection-page";
+import {
+ Bot,
+ ChevronDown,
+ Crown,
+ Globe,
+ Link2,
+ Loader2,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+ Save,
+ Trash2,
+ UserPlus,
+ Users,
+} from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
+import { IconButton } from "@multica/ui/components/common/icon-button";
import { Input } from "@multica/ui/components/ui/input";
import { Label } from "@multica/ui/components/ui/label";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@multica/ui/components/ui/popover";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
import {
Dialog,
DialogContent,
@@ -49,30 +78,38 @@ import {
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "../../common/actor-avatar";
import { AvatarUploadControl } from "../../common/avatar-upload-control";
import { ContentEditor } from "../../editor/content-editor";
+import { ReadonlyContent } from "../../editor/readonly-content";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { useStatusLabel } from "../../issues/utils/status-label";
import {
PickerItem,
PickerSection,
PickerEmpty,
} from "../../issues/components/pickers/property-picker";
-import { ChevronDown, UserPlus } from "@multica/ui/icons";
import { toast } from "sonner";
-import type { Squad, SquadMember, SquadMemberStatus, SquadMemberStatusValue, Agent, MemberWithUser } from "@multica/core/types";
-import { useT } from "../../i18n";
+import type { Issue, Squad, SquadMember, SquadMemberStatus, Agent, MemberWithUser } from "@multica/core/types";
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
+const RECENT_WORK_LIMIT = 5;
+
export function SquadDetailPage() {
const { t } = useT("squads");
+ const { t: tLayout } = useT("layout");
+ const { t: tCommon } = useT("common");
const workspace = useCurrentWorkspace();
const wsId = useWorkspaceId();
const p = useWorkspacePaths();
- const { pathname, push } = useNavigation();
+ const router = useNavigation();
+ const { pathname, push } = router;
const queryClient = useQueryClient();
const squadId = pathname.split("/").pop() ?? "";
- const { data: squad, refetch: refetchSquad } = useQuery<Squad>({
+ const { data: squad, isError: squadError, refetch: refetchSquad } = useQuery<Squad>({
queryKey: [...workspaceKeys.squads(wsId), squadId],
queryFn: () => api.getSquad(squadId),
enabled: !!workspace?.id && !!squadId,
@@ -86,8 +123,8 @@ export function SquadDetailPage() {
// Per-squad working/idle/offline + active-issue snapshot. WS task / agent /
// daemon events invalidate this via use-realtime-sync; the staleTime is a
- // tab-focus safety net. Indexed by member_id so SquadMembersTab can look up
- // its row in O(1).
+ // tab-focus safety net. Indexed by member_id so each member row can look up
+ // its status in O(1).
const { data: memberStatusResp } = useQuery({
...squadMemberStatusOptions(wsId, squadId),
enabled: !!workspace?.id && !!squadId,
@@ -98,6 +135,18 @@ export function SquadDetailPage() {
return map;
}, [memberStatusResp]);
+ const { data: recentWork, isPending: recentWorkPending } = useQuery({
+ queryKey: [...workspaceKeys.squads(wsId), squadId, "recent-issues"],
+ queryFn: () =>
+ api.listIssues({
+ assignee_filters: [{ type: "squad", id: squadId }],
+ sort_by: "updated_at",
+ sort_direction: "desc",
+ limit: RECENT_WORK_LIMIT,
+ }),
+ enabled: !!workspace?.id && !!squadId,
+ });
+
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const { data: wsMembers = [] } = useQuery(memberListOptions(wsId));
@@ -182,8 +231,27 @@ export function SquadDetailPage() {
return wsMembers.find((m) => m.user_id === id)?.name ?? id.slice(0, 8);
};
+ const segments = [{ href: p.squads(), label: t(($) => $.page.title) }];
+ const layoutId = "multica_squad_detail_layout";
+
if (!squad) {
- return <SquadDetailSkeleton />;
+ if (squadError) {
+ return (
+ <ObjectPage layoutId={layoutId} segments={segments} leaf={null}>
+ <CollectionPageState icon={Users} title={t(($) => $.detail.not_found)} />
+ </ObjectPage>
+ );
+ }
+ return (
+ <ObjectPage
+ layoutId={layoutId}
+ segments={segments}
+ leaf={<Skeleton className="h-4 w-32" />}
+ panel={<SquadPanelSkeleton />}
+ >
+ <SquadBodySkeleton />
+ </ObjectPage>
+ );
}
const availableAgents = agents.filter((a: Agent) => !a.archived_at && !members.some((m) => m.member_type === "agent" && m.member_id === a.id));
@@ -191,65 +259,155 @@ export function SquadDetailPage() {
const isLeader = (m: SquadMember) => m.member_type === "agent" && squad.leader_id === m.member_id;
const isArchived = (m: SquadMember) =>
m.member_type === "agent" && !!agents.find((a: Agent) => a.id === m.member_id)?.archived_at;
-
- const initials = squad.name
- .split(" ")
- .map((w) => w[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
+ const archived = !!squad.archived_at;
+ const createAgentHref = `${p.newAgent()}?squad=${encodeURIComponent(squadId)}`;
+
+ const assignWork = () =>
+ useModalStore.getState().open("create-issue", {
+ assignee_type: "squad",
+ assignee_id: squad.id,
+ });
+
+ const copyLink = () => {
+ void copyText(router.getShareableUrl(currentPath(router))).then((ok) => {
+ if (ok) toast.success(t(($) => $.detail.link_copied));
+ });
+ };
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <BreadcrumbHeader
- segments={[{ href: p.squads(), label: t(($) => $.page.title) }]}
- leaf={
- <>
- <SquadHeaderAvatar squad={squad} initials={initials} />
- <h1 className="truncate text-body font-medium text-foreground">{squad.name}</h1>
- </>
- }
- actions={
- canManage ? (
- <Button size="sm" variant="ghost" className="text-destructive hover:text-destructive" onClick={() => setConfirmArchive(true)}>
- <Trash2 className="size-3.5 mr-1" />
- {t(($) => $.inspector.archive_button)}
+ <ObjectPage
+ layoutId={layoutId}
+ segments={segments}
+ leaf={
+ <span className="flex min-w-0 items-center gap-1.5">
+ <SquadAvatar squad={squad} size="xs" />
+ <span className="truncate font-medium text-foreground">{squad.name}</span>
+ </span>
+ }
+ actions={
+ <>
+ {!archived && (
+ <Button size="sm" onClick={assignWork}>
+ <Plus className="size-3.5" />
+ {t(($) => $.detail.assign_work)}
</Button>
- ) : null
- }
- />
-
- {/* Two-column grid mirrors agent-detail-page: left inspector (identity +
- properties + leader), right pane with tabs (Members | Instructions).
- Mobile collapses to stacked single column. */}
- <div className="flex flex-1 min-h-0 flex-col gap-3 overflow-y-auto p-3 md:grid md:grid-cols-[280px_minmax(0,1fr)] md:gap-4 md:overflow-hidden md:p-6 lg:grid-cols-[320px_minmax(0,1fr)]">
- <SquadDetailInspector
- squad={squad}
- memberCount={members.length}
- leaderName={getEntityName("agent", squad.leader_id)}
- creatorName={getEntityName("member", squad.creator_id)}
- canManage={canManage}
- onUploadAvatar={(url) => updateSquadMut.mutateAsync({ avatar_url: url })}
- onRename={async (next) => { await updateSquadMut.mutateAsync({ name: next.trim() }); }}
- onUpdateDescription={async (next) => { await updateSquadMut.mutateAsync({ description: next }); }}
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={tCommon(($) => $.more_actions)}
+ tooltipSide="bottom"
+ className="text-muted-foreground"
+ />
+ }
+ >
+ <MoreHorizontal />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto min-w-44">
+ <DropdownMenuItem onClick={copyLink}>
+ <Link2 className="size-3.5" />
+ {t(($) => $.detail.copy_link)}
+ </DropdownMenuItem>
+ {canManage && !archived && (
+ <>
+ <DropdownMenuItem onClick={() => push(createAgentHref)}>
+ <Bot className="size-3.5" />
+ {t(($) => $.members_tab.create_agent_button)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={() => setConfirmArchive(true)}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.page.archive_action)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </>
+ }
+ panel={
+ <ObjectPanelSection title={tLayout(($) => $.object_page.properties)}>
+ <SquadProperties
+ squad={squad}
+ members={members}
+ canManage={canManage && !archived}
+ isArchived={isArchived}
+ getEntityName={getEntityName}
+ onSetLeader={(id) => setLeaderMut.mutate(id)}
+ setLeaderPending={setLeaderMut.isPending}
+ />
+ </ObjectPanelSection>
+ }
+ >
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <ObjectIdentity
+ media={
+ canManage ? (
+ <AvatarUploadControl
+ variant="squad"
+ value={squad.avatar_url ?? null}
+ name={squad.name}
+ size={48}
+ onUploaded={(url) => updateSquadMut.mutateAsync({ avatar_url: url })}
+ />
+ ) : (
+ <SquadAvatar squad={squad} size="identity" />
+ )
+ }
+ title={
+ canManage ? (
+ <SquadNameEditor
+ value={squad.name}
+ onSave={async (next) => { await updateSquadMut.mutateAsync({ name: next.trim() }); }}
+ />
+ ) : (
+ squad.name
+ )
+ }
+ description={
+ canManage ? (
+ <SquadDescriptionEditor
+ value={squad.description ?? ""}
+ onSave={async (next) => { await updateSquadMut.mutateAsync({ description: next }); }}
+ />
+ ) : (
+ squad.description || undefined
+ )
+ }
+ trailing={
+ archived ? (
+ <span className="shrink-0 rounded-sm bg-muted px-1.5 py-0.5 text-caption text-muted-foreground">
+ {t(($) => $.profile_card.archived)}
+ </span>
+ ) : undefined
+ }
/>
- <SquadOverviewPane
- squad={squad}
+ <SquadMembersSection
members={members}
memberStatusById={memberStatusById}
- canManage={canManage}
+ canManage={canManage && !archived}
isLeader={isLeader}
isArchived={isArchived}
getEntityName={getEntityName}
onAddMemberClick={() => setShowAddMember(true)}
- createAgentHref={canManage ? `${p.newAgent()}?squad=${encodeURIComponent(squadId)}` : undefined}
onSetLeader={(id) => setLeaderMut.mutate(id)}
onRemoveMember={(m) => removeMemberMut.mutate(m)}
onUpdateRole={async (m, role) => { await updateRoleMut.mutateAsync({ member: m, role }); }}
- onSaveInstructions={async (next) => { await updateSquadMut.mutateAsync({ instructions: next }); toast.success(t(($) => $.toasts.instructions_saved)); }}
setLeaderPending={setLeaderMut.isPending}
/>
+
+ <SquadInstructionsSection
+ squad={squad}
+ canManage={canManage && !archived}
+ onSave={async (next) => { await updateSquadMut.mutateAsync({ instructions: next }); toast.success(t(($) => $.toasts.instructions_saved)); }}
+ />
+
+ <SquadRecentWorkSection
+ issues={recentWork?.issues}
+ loading={recentWorkPending}
+ />
</div>
{showAddMember && (
@@ -290,81 +448,494 @@ export function SquadDetailPage() {
</AlertDialogContent>
</AlertDialog>
)}
- </div>
+ </ObjectPage>
);
}
-// Initial-load skeleton — mirrors the two-column layout of the loaded page
-// (left inspector + right tabs panel) so the swap to real content doesn't
-// shift layout. Column widths match the md:/lg: breakpoints used below.
-function SquadDetailSkeleton() {
+function SquadBodySkeleton() {
return (
- <div className="flex flex-1 min-h-0 flex-col">
- <PageHeader>
- <Skeleton className="h-5 w-48" />
- </PageHeader>
- <div className="flex flex-1 min-h-0 flex-col gap-3 overflow-y-auto p-3 md:grid md:grid-cols-[280px_minmax(0,1fr)] md:gap-4 md:overflow-hidden md:p-6 lg:grid-cols-[320px_minmax(0,1fr)]">
- <div className="flex flex-col gap-4 rounded-lg border p-5">
- <Skeleton className="h-16 w-16 rounded-full" />
+ <div className={cn(OBJECT_PAGE_BODY, "space-y-8")}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-12 rounded-full" />
+ <div className="space-y-2">
<Skeleton className="h-5 w-40" />
- <Skeleton className="h-3 w-full" />
- <div className="space-y-2">
- <Skeleton className="h-3 w-3/4" />
- <Skeleton className="h-3 w-2/3" />
- <Skeleton className="h-3 w-1/2" />
- </div>
- </div>
- <div className="flex flex-col gap-4 rounded-lg border p-6">
- <div className="flex items-center gap-4">
- <Skeleton className="h-4 w-20" />
- <Skeleton className="h-4 w-24" />
- </div>
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-5/6" />
- <Skeleton className="h-4 w-4/6" />
+ <Skeleton className="h-3 w-64" />
</div>
</div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-36 w-full rounded-lg" />
+ </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-16 w-full rounded-lg" />
+ </div>
</div>
);
}
-// Compact 16px avatar shown next to the name in the page header. Falls back
-// to the Users icon when no custom avatar is set so the squad still has a
-// recognisable glyph in the breadcrumb strip.
-function SquadHeaderAvatar({ squad, initials }: { squad: Squad; initials: string }) {
- if (!squad.avatar_url) {
- return <Users className="h-4 w-4 text-muted-foreground" />;
- }
+function SquadPanelSkeleton() {
return (
- <ActorAvatarBase
- name={squad.name}
- initials={initials}
- avatarUrl={resolvePublicFileUrl(squad.avatar_url)}
- size="sm"
- className="shrink-0"
- />
+ <div className="space-y-3 px-2 pt-1">
+ <Skeleton className="h-3 w-20" />
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-4 w-full" />
+ ))}
+ </div>
);
}
-// Read-only 64px avatar for viewers who can't manage the squad — same visual
-// as the editable control's resting state but without the click/upload
-// affordance.
-function SquadStaticAvatar({ squad, initials }: { squad: Squad; initials: string }) {
+// The squad's avatar, or the squad glyph when none is set. "identity" is the
+// 48px mark at the top of the body.
+function SquadAvatar({ squad, size }: { squad: Squad; size: "xs" | "identity" }) {
+ const initials = squad.name
+ .split(" ")
+ .map((w) => w[0])
+ .join("")
+ .toUpperCase()
+ .slice(0, 2);
return (
- <div className="h-16 w-16 shrink-0 overflow-hidden rounded-full bg-muted">
- {squad.avatar_url ? (
- <ActorAvatarBase
- name={squad.name}
- initials={initials}
- avatarUrl={resolvePublicFileUrl(squad.avatar_url)}
- size="2xl"
- />
- ) : (
- <div className="flex h-full w-full items-center justify-center text-muted-foreground">
- <Users className="h-7 w-7" />
+ <span className={cn("inline-flex shrink-0", size === "identity" && "[--avatar-slot-size:3rem]")}>
+ <ActorAvatarBase
+ name={squad.name}
+ initials={initials}
+ avatarUrl={squad.avatar_url ? resolvePublicFileUrl(squad.avatar_url) : null}
+ isSquad
+ size={size === "identity" ? "2xl" : "xs"}
+ />
+ </span>
+ );
+}
+
+const SQUAD_STATUS_LABEL_KEYS = {
+ working: "status_working",
+ idle: "status_idle",
+ offline: "status_offline",
+ unstable: "status_unstable",
+ archived: "status_archived",
+} as const;
+
+function SquadMembersSection({
+ members,
+ memberStatusById,
+ canManage,
+ isLeader,
+ isArchived,
+ getEntityName,
+ onAddMemberClick,
+ onSetLeader,
+ onRemoveMember,
+ onUpdateRole,
+ setLeaderPending,
+}: {
+ members: SquadMember[];
+ memberStatusById: Map<string, SquadMemberStatus>;
+ // When false, add/leader/remove controls and role editing are hidden; the
+ // roster stays visible and read-only. See canManageSquad in
+ // server/internal/handler/squad.go.
+ canManage: boolean;
+ isLeader: (m: SquadMember) => boolean;
+ isArchived: (m: SquadMember) => boolean;
+ getEntityName: (type: string, id: string) => string;
+ onAddMemberClick: () => void;
+ onSetLeader: (agentId: string) => void;
+ onRemoveMember: (m: SquadMember) => void;
+ onUpdateRole: (m: SquadMember, role: string) => Promise<void>;
+ setLeaderPending: boolean;
+}) {
+ const { t } = useT("squads");
+ const timeAgo = useTimeAgo();
+ const p = useWorkspacePaths();
+ const { push } = useNavigation();
+
+ return (
+ <ObjectSection
+ title={t(($) => $.members_tab.section_title)}
+ count={members.length}
+ action={
+ canManage ? (
+ <ObjectSectionAction icon={UserPlus} onClick={onAddMemberClick}>
+ {t(($) => $.members_tab.add_member_button)}
+ </ObjectSectionAction>
+ ) : null
+ }
+ >
+ {members.length > 0 ? (
+ <ObjectSectionCard>
+ {members.map((m) => {
+ const name = getEntityName(m.member_type, m.member_id);
+ const leader = isLeader(m);
+ const status = memberStatusById.get(m.member_id);
+ const statusValue = status?.status ?? null;
+ const statusLabel =
+ statusValue && statusValue in SQUAD_STATUS_LABEL_KEYS
+ ? t(($) => $.members_tab[SQUAD_STATUS_LABEL_KEYS[statusValue as keyof typeof SQUAD_STATUS_LABEL_KEYS]])
+ : null;
+ const activeIssues = status?.active_issues ?? [];
+ const primaryIssue = activeIssues[0];
+ const extraIssueCount = Math.max(0, activeIssues.length - 1);
+ const canMakeLeader = canManage && m.member_type === "agent" && !leader && !isArchived(m);
+ const canRemove = canManage && !leader;
+ const hasMenu = m.member_type === "agent" || canMakeLeader || canRemove;
+ return (
+ <div key={m.id} className="group/member flex min-h-11 items-center gap-3 px-3 py-1.5 text-body">
+ <ActorAvatar
+ actorType={m.member_type}
+ actorId={m.member_id}
+ size="md"
+ showStatusDot
+ enableHoverCard={m.member_type === "agent"}
+ hoverCardVariant="live"
+ />
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <span className="truncate font-medium">{name}</span>
+ {leader && (
+ <span className="inline-flex shrink-0 items-center gap-0.5 rounded-sm border px-1 text-caption text-muted-foreground">
+ <Crown className="size-3" />
+ {t(($) => $.members_tab.leader_chip)}
+ </span>
+ )}
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.member_type[m.member_type])}
+ </span>
+ {canManage ? (
+ <RoleEditor
+ value={m.role ?? ""}
+ onSave={async (next) => { await onUpdateRole(m, next); }}
+ />
+ ) : m.role ? (
+ <span className="min-w-0 truncate text-caption text-muted-foreground">· {m.role}</span>
+ ) : null}
+ </div>
+ {m.member_type === "agent" && (
+ <div className="flex min-w-0 max-w-[45%] shrink-0 items-center gap-1 text-caption text-muted-foreground">
+ {statusValue === "working" && primaryIssue ? (
+ <>
+ <span className="shrink-0">{t(($) => $.detail.working_on)}</span>
+ <AppLink
+ href={p.issueDetail(primaryIssue.issue_id)}
+ title={primaryIssue.title}
+ className="shrink-0 font-mono uppercase transition-colors hover:text-foreground"
+ >
+ {primaryIssue.identifier}
+ </AppLink>
+ {primaryIssue.issue_status === "blocked" && (
+ <span className="shrink-0 text-micro uppercase tracking-wide text-warning">
+ {t(($) => $.members_tab.issue_status_blocked)}
+ </span>
+ )}
+ {extraIssueCount > 0 && (
+ <span className="truncate">
+ · {t(($) => $.members_tab.active_issue_more, { count: extraIssueCount })}
+ </span>
+ )}
+ </>
+ ) : statusLabel ? (
+ <span className="truncate">
+ {statusLabel}
+ {statusValue !== "working" && status?.last_active_at
+ ? ` · ${timeAgo(status.last_active_at)}`
+ : null}
+ </span>
+ ) : null}
+ </div>
+ )}
+ {hasMenu ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <IconButton
+ label={t(($) => $.detail.member_menu, { name })}
+ size="icon-xs"
+ className="text-muted-foreground opacity-0 group-hover/member:opacity-100 focus-visible:opacity-100 data-[popup-open]:opacity-100 [@media(pointer:coarse)]:opacity-100"
+ />
+ }
+ >
+ <MoreHorizontal />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-auto min-w-44">
+ {m.member_type === "agent" && (
+ <DropdownMenuItem onClick={() => push(p.agentDetail(m.member_id))}>
+ <Bot className="size-3.5" />
+ {t(($) => $.members_tab.view_agent_tooltip)}
+ </DropdownMenuItem>
+ )}
+ {canMakeLeader && (
+ <DropdownMenuItem disabled={setLeaderPending} onClick={() => onSetLeader(m.member_id)}>
+ <Crown className="size-3.5" />
+ {t(($) => $.members_tab.make_leader_tooltip)}
+ </DropdownMenuItem>
+ )}
+ {canRemove && (
+ <>
+ {m.member_type === "agent" && <DropdownMenuSeparator />}
+ <DropdownMenuItem variant="destructive" onClick={() => onRemoveMember(m)}>
+ <Trash2 className="size-3.5" />
+ {t(($) => $.members_tab.remove_member_tooltip)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <span aria-hidden="true" className="size-6 shrink-0" />
+ )}
+ </div>
+ );
+ })}
+ </ObjectSectionCard>
+ ) : null}
+ </ObjectSection>
+ );
+}
+
+// The squad leader's prompt picks these up at task claim time
+// (server/internal/handler/daemon.go).
+function SquadInstructionsSection({
+ squad,
+ canManage,
+ onSave,
+}: {
+ squad: Squad;
+ canManage: boolean;
+ onSave: (instructions: string) => Promise<void>;
+}) {
+ const { t } = useT("squads");
+ const saved = squad.instructions ?? "";
+ const [editing, setEditing] = useState(false);
+ const [value, setValue] = useState(saved);
+ const [saving, setSaving] = useState(false);
+ const isDirty = value !== saved;
+
+ useEffect(() => {
+ if (!editing) setValue(saved);
+ }, [saved, editing]);
+
+ const handleSave = async () => {
+ setSaving(true);
+ try {
+ await onSave(value);
+ setEditing(false);
+ } catch {
+ // toast handled by parent
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <ObjectSection
+ title={t(($) => $.detail.instructions)}
+ action={
+ canManage && !editing ? (
+ <ObjectSectionAction icon={Pencil} onClick={() => setEditing(true)}>
+ {t(($) => $.detail.edit)}
+ </ObjectSectionAction>
+ ) : null
+ }
+ >
+ {editing ? (
+ <div className="space-y-2">
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.instructions_tab.description)}
+ </p>
+ <div className="rounded-lg border bg-card px-3 py-2.5 transition-colors focus-within:border-input">
+ <ContentEditor
+ key={squad.id}
+ value={value}
+ onUpdate={setValue}
+ placeholder={t(($) => $.instructions_tab.placeholder)}
+ debounceMs={150}
+ disableMentions
+ className="min-h-24"
+ />
+ </div>
+ <div className="flex items-center justify-end gap-2">
+ {isDirty && (
+ <span className="text-caption text-muted-foreground">{t(($) => $.instructions_tab.unsaved_changes)}</span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={saving}
+ onClick={() => {
+ setValue(saved);
+ setEditing(false);
+ }}
+ >
+ {t(($) => $.detail.cancel)}
+ </Button>
+ <Button size="sm" onClick={() => void handleSave()} disabled={!isDirty || saving}>
+ {saving ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <Save className="size-3.5" />
+ )}
+ {t(($) => $.instructions_tab.save_button)}
+ </Button>
+ </div>
</div>
+ ) : saved ? (
+ <ObjectSectionCard className="px-3 py-2.5 text-body">
+ <ReadonlyContent content={saved} />
+ </ObjectSectionCard>
+ ) : (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.instructions_tab.description)}
+ </p>
)}
- </div>
+ </ObjectSection>
+ );
+}
+
+function SquadRecentWorkSection({
+ issues,
+ loading,
+}: {
+ issues: Issue[] | undefined;
+ loading: boolean;
+}) {
+ const { t } = useT("squads");
+ const timeAgo = useTimeAgo();
+ const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
+ const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
+ const statusLabel = useStatusLabel(wsId);
+
+ return (
+ <ObjectSection title={t(($) => $.detail.recent_work)}>
+ {loading ? (
+ <Skeleton className="h-20 w-full rounded-lg" />
+ ) : issues && issues.length > 0 ? (
+ <ObjectSectionCard>
+ {issues.map((issue) => (
+ <AppLink
+ key={issue.id}
+ href={p.issueDetail(issue.id)}
+ className="flex h-10 items-center gap-3 px-3 text-body transition-colors hover:bg-accent/50"
+ >
+ <StatusIcon
+ status={issue.status}
+ category={categoryOf(issue.status)}
+ color={colorOf(issue.status)}
+ icon={iconOf(issue.status)}
+ className="size-3.5"
+ />
+ <span className="shrink-0 font-mono text-caption text-muted-foreground">{issue.identifier}</span>
+ <span className="min-w-0 flex-1 truncate">{issue.title}</span>
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {statusLabel(issue.status)} · {timeAgo(issue.updated_at)}
+ </span>
+ </AppLink>
+ ))}
+ </ObjectSectionCard>
+ ) : (
+ <p className="text-caption text-muted-foreground">{t(($) => $.detail.recent_work_empty)}</p>
+ )}
+ </ObjectSection>
+ );
+}
+
+function SquadProperties({
+ squad,
+ members,
+ canManage,
+ isArchived,
+ getEntityName,
+ onSetLeader,
+ setLeaderPending,
+}: {
+ squad: Squad;
+ members: SquadMember[];
+ canManage: boolean;
+ isArchived: (m: SquadMember) => boolean;
+ getEntityName: (type: string, id: string) => string;
+ onSetLeader: (agentId: string) => void;
+ setLeaderPending: boolean;
+}) {
+ const { t } = useT("squads");
+ const locale = useLocale();
+ const timeAgo = useTimeAgo();
+ const leaderName = getEntityName("agent", squad.leader_id);
+ const leaderCandidates = members.filter((m) => m.member_type === "agent" && !isArchived(m));
+ const leaderValue = (
+ <>
+ <ActorAvatar actorType="agent" actorId={squad.leader_id} size="xs" />
+ <span className="truncate">{leaderName}</span>
+ </>
+ );
+
+ return (
+ <>
+ <ObjectProperty label={t(($) => $.details.leader)}>
+ {canManage ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ disabled={setLeaderPending}
+ render={
+ <button
+ type="button"
+ className="inline-flex min-w-0 items-center gap-1.5 text-caption transition-colors hover:text-foreground"
+ />
+ }
+ >
+ {leaderValue}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-auto min-w-48">
+ <DropdownMenuRadioGroup
+ value={squad.leader_id}
+ onValueChange={(id) => {
+ if (id !== squad.leader_id) onSetLeader(id as string);
+ }}
+ >
+ {leaderCandidates.map((m) => (
+ <DropdownMenuRadioItem key={m.member_id} value={m.member_id}>
+ <ActorAvatar actorType="agent" actorId={m.member_id} size="xs" />
+ <span className="truncate">{getEntityName("agent", m.member_id)}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ leaderValue
+ )}
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.details.members)}>
+ {members.length > 0 && (
+ <span className="flex shrink-0 items-center -space-x-1">
+ {members.slice(0, 4).map((m) => (
+ <span key={m.id} className="inline-flex rounded-full ring-2 ring-background">
+ <ActorAvatar actorType={m.member_type} actorId={m.member_id} size="xs" />
+ </span>
+ ))}
+ </span>
+ )}
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.profile_card.member_count, { count: members.length })}
+ </span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.details.visibility)}>
+ <Globe className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{t(($) => $.details.visibility_workspace)}</span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.details.created_by)}>
+ <ActorAvatar actorType="member" actorId={squad.creator_id} size="xs" />
+ <span className="truncate">{getEntityName("member", squad.creator_id)}</span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.details.created)}>
+ <span className="text-muted-foreground">
+ {new Date(squad.created_at).toLocaleDateString(locale, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ })}
+ </span>
+ </ObjectProperty>
+ <ObjectProperty label={t(($) => $.details.updated)}>
+ <span className="text-muted-foreground">{timeAgo(squad.updated_at)}</span>
+ </ObjectProperty>
+ </>
);
}
@@ -692,139 +1263,29 @@ function RoleEditor({ value, onSave }: { value: string; onSave: (next: string) =
}}
disabled={saving}
placeholder={t(($) => $.role_editor.placeholder)}
- className="h-6 mt-0.5 text-caption px-1.5"
+ className="h-6 w-40 min-w-0 px-1.5 text-caption"
/>
);
}
+ // An empty role only offers "Add role…" while the row is hovered, so a
+ // roster of role-less members doesn't repeat the prompt on every line.
return (
<button
type="button"
onClick={() => setEditing(true)}
- className="text-caption text-muted-foreground mt-0.5 text-left hover:text-foreground transition-colors"
+ className={cn(
+ "min-w-0 truncate text-left text-caption text-muted-foreground transition-colors hover:text-foreground",
+ !value &&
+ "opacity-0 focus-visible:opacity-100 group-hover/member:opacity-100 [@media(pointer:coarse)]:opacity-100",
+ )}
>
- {value || <span className="italic opacity-60">{t(($) => $.role_editor.empty)}</span>}
+ {value ? `· ${value}` : <span className="italic">{t(($) => $.role_editor.empty)}</span>}
</button>
);
}
-// SquadDetailInspector — left 320px column, mirrors AgentDetailInspector.
-// Holds identity (avatar / name / description) + leader / member count /
-// timestamps. All inline-editable.
-function SquadDetailInspector({
- squad,
- memberCount,
- leaderName,
- creatorName,
- canManage,
- onUploadAvatar,
- onRename,
- onUpdateDescription,
-}: {
- squad: Squad;
- memberCount: number;
- leaderName: string;
- creatorName: string;
- // When false the identity block renders as static text (no avatar upload,
- // no rename/description popovers) — the viewer can read the squad but not
- // edit it. Mirrors the agent inspector's `canEdit` read-only treatment.
- canManage: boolean;
- onUploadAvatar: (url: string) => Promise<unknown>;
- onRename: (next: string) => Promise<void>;
- onUpdateDescription: (next: string) => Promise<void>;
-}) {
- const { t } = useT("squads");
- const timeAgo = useTimeAgo();
- const initials = squad.name
- .split(" ")
- .map((w) => w[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
-
- return (
- <aside className="flex w-full flex-col rounded-lg border bg-background md:h-full md:min-h-0 md:overflow-y-auto">
- {/* Identity */}
- <div className="flex flex-col gap-3 border-b px-5 pb-5 pt-5">
- {canManage ? (
- <>
- <AvatarUploadControl
- variant="squad"
- value={squad.avatar_url ?? null}
- name={squad.name}
- size={64}
- onUploaded={onUploadAvatar}
- />
- <div className="flex flex-col gap-1">
- <SquadNameEditor value={squad.name} onSave={onRename} />
- <SquadDescriptionEditor
- value={squad.description ?? ""}
- onSave={onUpdateDescription}
- />
- </div>
- </>
- ) : (
- <>
- <SquadStaticAvatar squad={squad} initials={initials} />
- <div className="flex flex-col gap-1">
- <span className="text-title font-semibold leading-tight">{squad.name}</span>
- {squad.description ? (
- <span className="text-caption leading-relaxed text-muted-foreground">
- {squad.description}
- </span>
- ) : (
- <span className="text-caption italic leading-relaxed text-muted-foreground">
- {t(($) => $.description_dialog.placeholder_empty)}
- </span>
- )}
- </div>
- </>
- )}
- </div>
-
- {/* Details — read-only */}
- <div className="border-b px-5 py-4">
- <div className="mb-1 -mx-2 px-2 text-micro font-medium uppercase tracking-wider text-muted-foreground">
- {t(($) => $.inspector.details_section)}
- </div>
- <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5">
- <InspectorRow label={t(($) => $.details.leader)}>
- <span className="flex min-w-0 items-center gap-1.5">
- <ActorAvatar actorType="agent" actorId={squad.leader_id} size="xs" />
- <span className="truncate">{leaderName}</span>
- </span>
- </InspectorRow>
- <InspectorRow label={t(($) => $.details.members)}>
- <span className="text-muted-foreground tabular-nums">{memberCount}</span>
- </InspectorRow>
- <InspectorRow label={t(($) => $.details.created_by)}>
- <span className="flex min-w-0 items-center gap-1.5">
- <ActorAvatar actorType="member" actorId={squad.creator_id} size="xs" />
- <span className="truncate">{creatorName}</span>
- </span>
- </InspectorRow>
- <InspectorRow label={t(($) => $.details.created)}>
- <span className="text-muted-foreground">{timeAgo(squad.created_at)}</span>
- </InspectorRow>
- <InspectorRow label={t(($) => $.details.updated)}>
- <span className="text-muted-foreground">{timeAgo(squad.updated_at)}</span>
- </InspectorRow>
- </div>
- </div>
- </aside>
- );
-}
-
-function InspectorRow({ label, children }: { label: string; children: ReactNode }) {
- return (
- <>
- <div className="px-2 py-1 text-caption text-muted-foreground">{label}</div>
- <div className="min-w-0 px-2 py-1 text-caption">{children}</div>
- </>
- );
-}
-
-// Click-to-edit description editor for the inspector. Mirrors
+// Click-to-edit description editor for the identity block. Mirrors
// agent-detail-inspector's DescriptionEditor: opens a modal with a textarea
// (enough room for multi-paragraph descriptions); the inline trigger shows
// the current value (or a placeholder) with a hover-revealed Pencil.
@@ -842,14 +1303,14 @@ function SquadDescriptionEditor({
<button
type="button"
onClick={() => setOpen(true)}
- className="group -mx-1 inline-flex items-start gap-1.5 self-start rounded-xs px-1 text-left text-caption leading-relaxed transition-colors hover:bg-accent/50"
+ className="group -mx-1 inline-flex max-w-full items-start gap-1.5 rounded-sm px-1 text-left transition-colors hover:bg-accent/50"
>
{value ? (
- <span className="text-muted-foreground">{value}</span>
+ <span className="line-clamp-2 text-muted-foreground">{value}</span>
) : (
<span className="italic text-muted-foreground">{t(($) => $.description_dialog.placeholder_empty)}</span>
)}
- <Pencil className="mt-0.5 h-3 w-3 shrink-0 text-transparent transition-colors group-hover:text-muted-foreground" />
+ <Pencil className="mt-1 h-3 w-3 shrink-0 text-transparent transition-colors group-hover:text-muted-foreground" />
</button>
<Dialog open={open} onOpenChange={setOpen}>
@@ -928,467 +1389,3 @@ function SquadDescriptionEditorBody({
</>
);
}
-
-// SquadOverviewPane — right column with two tabs (Members | Instructions).
-// Mirrors AgentOverviewPane: dirty-guard via AlertDialog when switching tabs
-// with unsaved Instructions.
-type SquadDetailTab = "members" | "instructions";
-
-const squadDetailTabs: { id: SquadDetailTab; icon: typeof FileText }[] = [
- { id: "members", icon: Users },
- { id: "instructions", icon: FileText },
-];
-
-function SquadOverviewPane({
- squad,
- members,
- memberStatusById,
- canManage,
- isLeader,
- isArchived,
- getEntityName,
- onAddMemberClick,
- createAgentHref,
- onSetLeader,
- onRemoveMember,
- onUpdateRole,
- onSaveInstructions,
- setLeaderPending,
-}: {
- squad: Squad;
- members: SquadMember[];
- memberStatusById: Map<string, SquadMemberStatus>;
- // Gates every mutating control in the Members and Instructions tabs. When
- // false the tabs render read-only (no add/remove/leader/role edits, no
- // Save). See canManageSquad in server/internal/handler/squad.go.
- canManage: boolean;
- isLeader: (m: SquadMember) => boolean;
- isArchived: (m: SquadMember) => boolean;
- getEntityName: (type: string, id: string) => string;
- onAddMemberClick: () => void;
- // Optional — only passed when the current user can manage the squad
- // (workspace owner/admin or the creator). Hidden otherwise so viewers
- // don't see a button they can't action.
- createAgentHref?: string;
- onSetLeader: (agentId: string) => void;
- onRemoveMember: (m: SquadMember) => void;
- onUpdateRole: (m: SquadMember, role: string) => Promise<void>;
- onSaveInstructions: (next: string) => Promise<void>;
- setLeaderPending: boolean;
-}) {
- const { t } = useT("squads");
- const [activeTab, setActiveTab] = useState<SquadDetailTab>("members");
- const [activeDirty, setActiveDirty] = useState(false);
- const [pendingTab, setPendingTab] = useState<SquadDetailTab | null>(null);
-
- const requestTabChange = (next: SquadDetailTab) => {
- if (next === activeTab) return;
- if (activeDirty) { setPendingTab(next); return; }
- setActiveTab(next);
- };
-
- const commitTabChange = () => {
- if (pendingTab) {
- setActiveTab(pendingTab);
- setActiveDirty(false);
- setPendingTab(null);
- }
- };
-
- return (
- <div className="flex min-h-[60vh] flex-col overflow-hidden rounded-lg border bg-background md:h-full md:min-h-0">
- <div className="flex shrink-0 items-center gap-0 overflow-x-auto border-b px-2 md:px-4">
- {squadDetailTabs.map((tab) => (
- <button
- key={tab.id}
- type="button"
- onClick={() => requestTabChange(tab.id)}
- className={`flex shrink-0 items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-2.5 text-caption font-medium transition-colors ${
- activeTab === tab.id
- ? "border-foreground text-foreground"
- : "border-transparent text-muted-foreground hover:text-foreground"
- }`}
- >
- <tab.icon className="h-3.5 w-3.5" />
- {t(($) => $.detail_tabs[tab.id])}
- </button>
- ))}
- </div>
-
- <div className="flex-1 min-h-0 overflow-y-auto">
- {activeTab === "members" && (
- <div className="flex h-full flex-col p-4 md:p-6">
- <SquadMembersTab
- members={members}
- memberStatusById={memberStatusById}
- canManage={canManage}
- isLeader={isLeader}
- isArchived={isArchived}
- getEntityName={getEntityName}
- onAddMemberClick={onAddMemberClick}
- createAgentHref={createAgentHref}
- onSetLeader={onSetLeader}
- onRemoveMember={onRemoveMember}
- onUpdateRole={onUpdateRole}
- setLeaderPending={setLeaderPending}
- />
- </div>
- )}
- {activeTab === "instructions" && (
- <div className="flex h-full flex-col p-4 md:p-6">
- <SquadInstructionsTab
- squad={squad}
- canManage={canManage}
- onSave={onSaveInstructions}
- onDirtyChange={setActiveDirty}
- />
- </div>
- )}
- </div>
-
- {pendingTab !== null && (
- <AlertDialog open onOpenChange={(v) => { if (!v) setPendingTab(null); }}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{t(($) => $.discard_changes_dialog.title)}</AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.discard_changes_dialog.description)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t(($) => $.discard_changes_dialog.keep_editing)}</AlertDialogCancel>
- <AlertDialogAction variant="destructive" onClick={commitTabChange}>
- {t(($) => $.discard_changes_dialog.discard_button)}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )}
- </div>
- );
-}
-
-// Visual config for the five squad member status buckets. Mirrors
-// availabilityConfig + workloadConfig in packages/views/agents/presence.ts —
-// same semantic tokens so a status dot here matches the agent page's dot.
-// Unknown / null statuses (human members, server-side enum drift) render as
-// a neutral muted pill; this is the "downgrade, don't crash" defense from
-// CLAUDE.md > API Response Compatibility.
-const SQUAD_STATUS_DOT_CLASS: Record<SquadMemberStatusValue, string> = {
- working: "bg-success",
- idle: "bg-muted-foreground/40",
- offline: "bg-muted-foreground/40",
- unstable: "bg-warning",
- archived: "bg-muted-foreground/40",
-};
-
-// Members tab body — re-uses the existing list/role editing patterns.
-function SquadMembersTab({
- members,
- memberStatusById,
- canManage,
- isLeader,
- isArchived,
- getEntityName,
- onAddMemberClick,
- createAgentHref,
- onSetLeader,
- onRemoveMember,
- onUpdateRole,
- setLeaderPending,
-}: {
- members: SquadMember[];
- memberStatusById: Map<string, SquadMemberStatus>;
- // When false, add/create/leader/remove controls and role editing are hidden;
- // the roster stays visible and read-only.
- canManage: boolean;
- isLeader: (m: SquadMember) => boolean;
- isArchived: (m: SquadMember) => boolean;
- getEntityName: (type: string, id: string) => string;
- onAddMemberClick: () => void;
- // Hidden for viewers who can't manage — see SquadOverviewPane.
- createAgentHref?: string;
- onSetLeader: (agentId: string) => void;
- onRemoveMember: (m: SquadMember) => void;
- onUpdateRole: (m: SquadMember, role: string) => Promise<void>;
- setLeaderPending: boolean;
-}) {
- const { t } = useT("squads");
- const timeAgo = useTimeAgo();
- const p = useWorkspacePaths();
- return (
- <div className="flex flex-col gap-4">
- <div className="flex items-center justify-between">
- <div>
- <h3 className="text-body font-medium">{t(($) => $.members_tab.section_title)}</h3>
- <p className="text-caption text-muted-foreground mt-0.5">
- {t(($) => $.members_tab.section_count, { count: members.length })}
- </p>
- </div>
- {canManage && (
- <div className="flex items-center gap-2">
- {createAgentHref && (
- <Button
- size="sm"
- variant="outline"
- render={<AppLink href={createAgentHref} />}
- nativeButton={false}
- >
- <Plus className="size-3.5 mr-1.5" />
- {t(($) => $.members_tab.create_agent_button)}
- </Button>
- )}
- <Button size="sm" variant="outline" onClick={onAddMemberClick}>
- <Plus className="size-3.5 mr-1.5" />
- {t(($) => $.members_tab.add_member_button)}
- </Button>
- </div>
- )}
- </div>
-
- <div className="space-y-2">
- {members.map((m) => {
- const status = memberStatusById.get(m.member_id);
- const statusValue = status?.status ?? null;
- const dotClass =
- statusValue && statusValue in SQUAD_STATUS_DOT_CLASS
- ? SQUAD_STATUS_DOT_CLASS[statusValue as keyof typeof SQUAD_STATUS_DOT_CLASS]
- : null;
- const statusLabel =
- statusValue === "working" ? t(($) => $.members_tab.status_working)
- : statusValue === "idle" ? t(($) => $.members_tab.status_idle)
- : statusValue === "offline" ? t(($) => $.members_tab.status_offline)
- : statusValue === "unstable" ? t(($) => $.members_tab.status_unstable)
- : statusValue === "archived" ? t(($) => $.members_tab.status_archived)
- : null;
- const activeIssues = status?.active_issues ?? [];
- const primaryIssue = activeIssues[0];
- const extraIssueCount = Math.max(0, activeIssues.length - 1);
- // Show last_active only when the agent isn't currently working —
- // a "working" pill already implies the agent is live, and a
- // "last active 2s ago" line next to it is just noise.
- const showLastActive =
- m.member_type === "agent" && statusValue && statusValue !== "working" && status?.last_active_at;
- return (
- <div key={m.id} className="group flex items-start gap-3 rounded-lg border p-3">
- <ActorAvatar
- actorType={m.member_type}
- actorId={m.member_id}
- size="lg"
- showStatusDot
- enableHoverCard={m.member_type === "agent"}
- hoverCardVariant="live"
- />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-body font-medium">{getEntityName(m.member_type, m.member_id)}</span>
- <span className="text-caption text-muted-foreground">
- {t(($) => $.member_type[m.member_type])}
- </span>
- {isLeader(m) && (
- <span className="inline-flex items-center gap-0.5 text-caption bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-1.5 py-0.5 rounded-xs">
- <Crown className="size-3" />
- {t(($) => $.members_tab.leader_chip)}
- </span>
- )}
- {m.member_type === "agent" && statusLabel && (
- <span className="inline-flex items-center gap-1 text-caption text-muted-foreground">
- <span className={`h-1.5 w-1.5 rounded-full ${dotClass ?? "bg-muted-foreground/40"}`} />
- {statusLabel}
- </span>
- )}
- </div>
- {canManage ? (
- <RoleEditor
- value={m.role ?? ""}
- onSave={async (next) => { await onUpdateRole(m, next); }}
- />
- ) : m.role ? (
- <div className="mt-0.5 text-caption text-muted-foreground">{m.role}</div>
- ) : null}
- {primaryIssue && (
- <div className="mt-1 flex items-center gap-1 text-caption text-muted-foreground min-w-0">
- <AppLink
- href={p.issueDetail(primaryIssue.issue_id)}
- className="inline-flex items-center gap-1 min-w-0 hover:text-foreground transition-colors"
- >
- <span className="font-mono text-micro uppercase shrink-0">{primaryIssue.identifier}</span>
- <span className="truncate">{primaryIssue.title}</span>
- {primaryIssue.issue_status === "blocked" && (
- <span className="shrink-0 inline-flex items-center text-micro uppercase tracking-wide text-warning">
- {t(($) => $.members_tab.issue_status_blocked)}
- </span>
- )}
- </AppLink>
- {extraIssueCount > 0 && (
- <span className="shrink-0">
- · {t(($) => $.members_tab.active_issue_more, { count: extraIssueCount })}
- </span>
- )}
- </div>
- )}
- {showLastActive && (
- <div className="mt-0.5 text-caption text-muted-foreground">
- {t(($) => $.members_tab.last_active_label, {
- time: timeAgo(status!.last_active_at!),
- })}
- </div>
- )}
- </div>
- <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">
- {m.member_type === "agent" && (
- <Tooltip>
- <TooltipTrigger
- render={
- <AppLink
- href={p.agentDetail(m.member_id)}
- className="inline-flex items-center justify-center h-8 w-8 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
- aria-label={t(($) => $.members_tab.view_agent_tooltip)}
- >
- <ArrowUpRight className="size-3.5" />
- </AppLink>
- }
- />
- <TooltipContent>
- {t(($) => $.members_tab.view_agent_tooltip)}
- </TooltipContent>
- </Tooltip>
- )}
- {canManage && m.member_type === "agent" && !isLeader(m) && !isArchived(m) && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="sm"
- variant="ghost"
- className="text-muted-foreground hover:text-amber-600 h-8 w-8 p-0"
- onClick={() => onSetLeader(m.member_id)}
- disabled={setLeaderPending}
- aria-label={t(($) => $.members_tab.make_leader_tooltip)}
- >
- <Crown className="size-3.5" />
- </Button>
- }
- />
- <TooltipContent>
- {t(($) => $.members_tab.make_leader_tooltip)}
- </TooltipContent>
- </Tooltip>
- )}
- {canManage && !isLeader(m) && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="sm"
- variant="ghost"
- className="text-muted-foreground hover:text-destructive h-8 w-8 p-0"
- onClick={() => onRemoveMember(m)}
- aria-label={t(($) => $.members_tab.remove_member_tooltip)}
- >
- <Trash2 className="size-3.5" />
- </Button>
- }
- />
- <TooltipContent>
- {t(($) => $.members_tab.remove_member_tooltip)}
- </TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
- );
- })}
- </div>
- </div>
- );
-}
-
-// Instructions tab body — mirrors agent's InstructionsTab. ContentEditor +
-// Save button. The squad leader's prompt picks these up at task claim time
-// (server/internal/handler/daemon.go).
-function SquadInstructionsTab({
- squad,
- canManage,
- onSave,
- onDirtyChange,
-}: {
- squad: Squad;
- canManage: boolean;
- onSave: (instructions: string) => Promise<void>;
- onDirtyChange?: (dirty: boolean) => void;
-}) {
- const { t } = useT("squads");
- const [value, setValue] = useState(squad.instructions ?? "");
- const [saving, setSaving] = useState(false);
- const isDirty = value !== (squad.instructions ?? "");
-
- useEffect(() => {
- setValue(squad.instructions ?? "");
- }, [squad.id, squad.instructions]);
-
- useEffect(() => {
- // A read-only viewer never has unsaved changes to guard on tab-switch.
- onDirtyChange?.(canManage && isDirty);
- }, [canManage, isDirty, onDirtyChange]);
-
- const handleSave = async () => {
- setSaving(true);
- try {
- await onSave(value);
- } catch {
- // toast handled by parent
- } finally {
- setSaving(false);
- }
- };
-
- return (
- <div className="flex h-full flex-col gap-4">
- <p className="text-caption text-muted-foreground">
- {t(($) => $.instructions_tab.description)}
- </p>
-
- {/* When the viewer can't manage the squad, the editor is wrapped in a
- pointer-events-none / aria-disabled shell — ContentEditor reads
- `editable` at mount and can't be toggled, so this is the documented
- way to present it read-only (see editor/content-editor.tsx). */}
- <div
- aria-disabled={!canManage}
- className={`flex-1 min-h-0 overflow-y-auto rounded-md border bg-background px-4 py-3 transition-colors ${
- canManage ? "focus-within:border-input" : "pointer-events-none"
- }`}
- >
- <ContentEditor
- key={squad.id}
- value={value}
- onUpdate={canManage ? setValue : () => {}}
- placeholder={
- canManage
- ? t(($) => $.instructions_tab.placeholder)
- : ""
- }
- debounceMs={150}
- disableMentions
- className="min-h-full"
- />
- </div>
-
- {canManage && (
- <div className="flex items-center justify-end gap-3">
- {isDirty && (
- <span className="text-caption text-muted-foreground">{t(($) => $.instructions_tab.unsaved_changes)}</span>
- )}
- <Button size="sm" onClick={handleSave} disabled={!isDirty || saving}>
- {saving ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Save className="h-3.5 w-3.5" />
- )}
- {t(($) => $.instructions_tab.save_button)}
- </Button>
- </div>
- )}
- </div>
- );
-}
diff --git a/packages/views/squads/components/squads-page.test.tsx b/packages/views/squads/components/squads-page.test.tsx
new file mode 100644
index 0000000000..f5d931c79b
--- /dev/null
+++ b/packages/views/squads/components/squads-page.test.tsx
@@ -0,0 +1,165 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { Squad } from "@multica/core/types";
+import type { SquadsScope } from "@multica/core/squads/stores";
+import { renderWithI18n } from "../../test/i18n";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+import { SquadsPage } from "./squads-page";
+
+const mocks = vi.hoisted(() => ({
+ squads: [] as Squad[],
+ openModal: vi.fn(),
+ viewState: {
+ scope: "all" as SquadsScope,
+ sortField: "name",
+ sortDirection: "asc",
+ hiddenColumns: [] as string[],
+ filters: { leaders: [] as string[], creators: [] as string[] },
+ setScope: vi.fn(),
+ toggleSort: vi.fn(),
+ setSortField: vi.fn(),
+ setSortDirection: vi.fn(),
+ toggleColumn: vi.fn(),
+ toggleFilter: vi.fn(),
+ clearFilters: vi.fn(),
+ },
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: (options: { queryKey?: readonly unknown[] }) => ({
+ data: options.queryKey?.[0] === "squads" ? mocks.squads : [],
+ isLoading: false,
+ }),
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
+ useMutation: () => ({ mutate: vi.fn(), isPending: false }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: () => ({ queryKey: ["agents"] }),
+ memberListOptions: () => ({ queryKey: ["members"] }),
+ squadListOptions: () => ({ queryKey: ["squads"] }),
+ workspaceKeys: { squads: () => ["squads"] },
+}));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-1", slug: "acme" }),
+ useWorkspacePaths: () => ({
+ squadDetail: (id: string) => `/acme/squads/${id}`,
+ agentDetail: (id: string) => `/acme/agents/${id}`,
+ }),
+}));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (select: (s: { user: { id: string } }) => unknown) => select({ user: { id: "me" } }),
+}));
+vi.mock("@multica/core/api", () => ({ api: {} }));
+vi.mock("@multica/core/modals", () => ({
+ useModalStore: { getState: () => ({ open: mocks.openModal }) },
+}));
+vi.mock("@multica/core/squads/stores", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/squads/stores")>()),
+ useSquadsViewStore: (select: (s: typeof mocks.viewState) => unknown) => select(mocks.viewState),
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+
+function squad(id: string, name: string, creatorId: string): Squad {
+ return {
+ id,
+ workspace_id: "ws-1",
+ name,
+ description: "",
+ instructions: "",
+ avatar_url: null,
+ leader_id: `agent-${id}`,
+ creator_id: creatorId,
+ created_at: "2026-10-01T00:00:00Z",
+ updated_at: "2026-10-01T00:00:00Z",
+ archived_at: null,
+ archived_by: null,
+ };
+}
+
+function renderPage() {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/squads",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => path,
+ };
+ renderWithI18n(
+ <NavigationProvider value={adapter}>
+ <SquadsPage />
+ </NavigationProvider>,
+ );
+}
+
+beforeEach(() => {
+ mocks.squads = [squad("s1", "Strike Team", "me"), squad("s2", "Design Crew", "someone")];
+ mocks.viewState.scope = "all";
+ mocks.viewState.filters = { leaders: [], creators: [] };
+ mocks.viewState.setScope.mockReset();
+ mocks.viewState.clearFilters.mockReset();
+ mocks.openModal.mockReset();
+});
+
+describe("SquadsPage header", () => {
+ it("titles the page with the scope and picks another scope from the title menu", async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ expect(screen.getByRole("heading", { level: 1, name: "All squads" })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "All squads" }));
+ const mine = await screen.findByRole("menuitemradio", { name: /^My squads/ });
+ expect(mine).toHaveTextContent("1");
+ expect(screen.getByRole("menuitemradio", { name: /^All squads/ })).toHaveTextContent("2");
+ await user.click(mine);
+ expect(mocks.viewState.setScope).toHaveBeenCalledWith("mine");
+ });
+
+ it("lists only the squads in the current scope", () => {
+ mocks.viewState.scope = "mine";
+ renderPage();
+
+ expect(screen.getByRole("heading", { level: 1, name: "My squads" })).toBeInTheDocument();
+ expect(screen.getByText("Strike Team")).toBeInTheDocument();
+ expect(screen.queryByText("Design Crew")).not.toBeInTheDocument();
+ });
+
+ it("has no search, and offers Reset only while a filter narrows the list", () => {
+ renderPage();
+
+ expect(screen.queryByRole("button", { name: /search/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Reset" })).not.toBeInTheDocument();
+ });
+
+ it("names the active filter count on the filter control, and Reset clears the filters", async () => {
+ const user = userEvent.setup();
+ mocks.viewState.filters = { leaders: ["agent-s1"], creators: ["me"] };
+ renderPage();
+
+ expect(screen.getByRole("button", { name: "2 filters" })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Reset" }));
+ expect(mocks.viewState.clearFilters).toHaveBeenCalled();
+ });
+
+ it("keeps display settings and create as icon controls on the right", async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ expect(screen.getByRole("button", { name: "Display settings" })).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "New squad" }));
+ expect(mocks.openModal).toHaveBeenCalledWith("create-squad");
+ });
+
+ it("offers to create the first squad from the empty state", async () => {
+ const user = userEvent.setup();
+ mocks.squads = [];
+ renderPage();
+
+ expect(screen.getByText("No squads yet.")).toBeInTheDocument();
+ const buttons = screen.getAllByRole("button", { name: "New squad" });
+ await user.click(buttons[buttons.length - 1]!);
+ expect(mocks.openModal).toHaveBeenCalledWith("create-squad");
+ });
+});
diff --git a/packages/views/squads/components/squads-page.tsx b/packages/views/squads/components/squads-page.tsx
index b03215bdd8..e1dbf35877 100644
--- a/packages/views/squads/components/squads-page.tsx
+++ b/packages/views/squads/components/squads-page.tsx
@@ -2,17 +2,11 @@
import { useMemo, useState } from "react";
import {
- ArrowDown,
- ArrowUp,
- ChevronDown,
ExternalLink,
- Filter,
Loader2,
- MoreHorizontal,
Plus,
Trash2,
Users,
- X,
} from "@multica/ui/icons";
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
@@ -30,7 +24,6 @@ import { useModalStore } from "@multica/core/modals";
import {
useSquadsViewStore,
SQUAD_SCOPES,
- SQUAD_DEFAULT_HIDDEN_COLUMNS,
type SquadColumnKey,
type SquadListFilters,
type SquadsScope,
@@ -38,7 +31,6 @@ import {
} from "@multica/core/squads/stores";
import type { Agent, MemberWithUser, Squad } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
-import { IconButton } from "@multica/ui/components/common/icon-button";
import {
Dialog,
DialogContent,
@@ -52,93 +44,34 @@ import {
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- ListGrid,
- ListGridCell,
- ListGridHeader,
- ListGridHeaderCell,
- ListGridRow,
- LIST_GRID_BOTTOM_CLEARANCE,
- type ListGridSortDirection,
-} from "@multica/ui/components/ui/list-grid";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
-import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { Switch } from "@multica/ui/components/ui/switch";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@multica/ui/components/ui/tooltip";
import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
import { ActorAvatar } from "../../common/actor-avatar";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
-import { useIntentNavigate, useRowLink } from "../../navigation";
+import { useIntentNavigate } from "../../navigation";
import {
+ CollectionCreateButton,
+ CollectionFilterButton,
CollectionPageHeader,
- CollectionPageHeaderAction,
CollectionPageState,
+ CollectionResetButton,
+ CollectionScopeItems,
} from "../../layout/collection-page";
+import {
+ CollectionDisplayMenu,
+ CollectionEmptyValue,
+ CollectionList,
+ CollectionNameCell,
+ CollectionRowMenu,
+ type CollectionColumn,
+ type CollectionSort,
+} from "../../layout/collection-list";
import { useLocale, useT } from "../../i18n";
-import { PAGE_TOOLBAR } from "../../layout/page-header";
-import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
-
-// Column template — the simplest member of the ListGrid family (squads are
-// the fewest entity, 1-5 rows): subgrid template + var tracks + two-zone
-// responsiveness + single scroll container, but NO virtualization, checkbox,
-// or batch. Identity two-line rows (avatar + name + description, 64px) like
-// the agents list. Name + leader are the core set (<@2xl); members / creator
-// / created are @2xl. The kebab track collapses when the viewer can't manage
-// any squad (workspace admin only).
-const GRID_COLS =
- "grid-cols-[0.75rem_minmax(120px,1fr)_var(--sqc-leader)_var(--sqc-kebab)_0.75rem] " +
- "@2xl:grid-cols-[0.75rem_minmax(200px,1fr)_var(--sqc-leader)_var(--sqc-members)_var(--sqc-creator)_var(--sqc-created)_var(--sqc-kebab)_0.75rem]";
-
-const LEADER_WIDTH = 160;
-const COLUMN_WIDTHS: Record<SquadColumnKey, number> = {
- members: 120,
- creator: 144,
- created: 104,
-};
-
-// Fixed tracks (edges 12+12, name min 200, leader 160) plus the 7 gap-x-3
-// gaps between the wide template's 8 tracks (zero-width tracks still carry
-// gaps).
-const FIXED_TRACKS_WIDTH = 224 + LEADER_WIDTH + 7 * 12;
-
-function columnTrackVars(
- isVisible: (key: SquadColumnKey) => boolean,
- showActions: boolean,
-): React.CSSProperties {
- const width = (key: SquadColumnKey) =>
- isVisible(key) ? `${COLUMN_WIDTHS[key]}px` : "0px";
- const minWidth =
- FIXED_TRACKS_WIDTH +
- (Object.keys(COLUMN_WIDTHS) as SquadColumnKey[]).reduce(
- (sum, key) => sum + (isVisible(key) ? COLUMN_WIDTHS[key] : 0),
- 0,
- ) +
- (showActions ? 28 : 0);
- return {
- "--sqc-leader": `${LEADER_WIDTH}px`,
- "--sqc-members": width("members"),
- "--sqc-creator": width("creator"),
- "--sqc-created": width("created"),
- "--sqc-kebab": showActions ? "1.75rem" : "0px",
- "--sqc-minw": `${minWidth}px`,
- } as React.CSSProperties;
-}
// Cells
@@ -155,7 +88,7 @@ function SquadAvatar({ squad }: { squad: Squad }) {
name={squad.name}
initials={initials}
avatarUrl={resolvePublicFileUrl(squad.avatar_url)}
- size="lg"
+ size="sm"
className="shrink-0"
/>
);
@@ -165,31 +98,12 @@ function SquadAvatar({ squad }: { squad: Squad }) {
name={squad.name}
initials={initials}
isSquad
- size="lg"
+ size="sm"
className="shrink-0"
/>
);
}
-// Two-line identity cell — same form as the agents list.
-function NameCell({ squad }: { squad: Squad }) {
- return (
- <ListGridCell className="gap-3">
- <SquadAvatar squad={squad} />
- <div className="min-w-0 flex-1">
- <span className="block min-w-0 truncate text-body font-medium">
- {squad.name}
- </span>
- {squad.description ? (
- <span className="block min-w-0 truncate text-caption text-muted-foreground">
- {squad.description}
- </span>
- ) : null}
- </div>
- </ListGridCell>
- );
-}
-
function LeaderCell({
leaderId,
leader,
@@ -198,12 +112,10 @@ function LeaderCell({
leader: Agent | undefined;
}) {
return (
- <ListGridCell className="gap-1.5">
+ <>
<ActorAvatar actorType="agent" actorId={leaderId} size="sm" />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {leader?.name ?? leaderId.slice(0, 8)}
- </span>
- </ListGridCell>
+ <span className="min-w-0 truncate">{leader?.name ?? leaderId.slice(0, 8)}</span>
+ </>
);
}
@@ -213,18 +125,11 @@ function LeaderCell({
function MembersCell({ squad }: { squad: Squad }) {
const preview = squad.member_preview ?? [];
const count = squad.member_count ?? preview.length;
- if (count === 0) {
- return (
- <ListGridCell className="hidden @2xl:flex">
- <span className="text-caption text-faint-foreground">—</span>
- </ListGridCell>
- );
- }
+ if (count === 0) return <CollectionEmptyValue />;
const visible = preview.slice(0, 3);
const overflow = count - visible.length;
return (
- <ListGridCell className="hidden @2xl:flex">
- <div className="flex items-center -space-x-1.5">
+ <div className="flex items-center -space-x-1.5">
{visible.map((m) => (
<span
key={`${m.member_type}-${m.member_id}`}
@@ -233,18 +138,17 @@ function MembersCell({ squad }: { squad: Squad }) {
<ActorAvatar
actorType={m.member_type}
actorId={m.member_id}
- size="md"
+ size="sm"
enableHoverCard={m.member_type === "agent"}
/>
</span>
))}
{overflow > 0 && (
- <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-muted text-caption font-medium text-muted-foreground ring-2 ring-background">
+ <span className="inline-flex size-5 items-center justify-center rounded-full bg-muted text-micro font-medium text-muted-foreground ring-2 ring-background">
+{overflow}
</span>
)}
- </div>
- </ListGridCell>
+ </div>
);
}
@@ -322,118 +226,39 @@ function SquadRowActions({ squad }: { squad: Squad }) {
const intentNavigate = useIntentNavigate();
const [archiveOpen, setArchiveOpen] = useState(false);
return (
- <span
- onClick={(e) => e.stopPropagation()}
- className="flex items-center"
- >
- <DropdownMenu>
- <DeferredTooltip
- content={t(($) => $.page.row_menu)}
- trigger={
- <DropdownMenuTrigger
- render={
- <button
- type="button"
- aria-label={t(($) => $.page.row_menu)}
- className="flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-accent-foreground group-hover/row:opacity-100 data-popup-open:bg-accent data-popup-open:opacity-100 data-popup-open:text-accent-foreground"
- >
- <MoreHorizontal className="size-4" />
- </button>
- }
- />
+ <>
+ <CollectionRowMenu label={t(($) => $.page.row_menu)} contentClassName="w-40">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ p.squadDetail(squad.id),
+ "foreground-tab",
+ squad.name,
+ )
}
- />
- <DropdownMenuContent align="end" className="w-40">
- <DropdownMenuItem
- onClick={() =>
- intentNavigate(
- p.squadDetail(squad.id),
- "foreground-tab",
- squad.name,
- )
- }
- >
- <ExternalLink className="size-3.5" />
- {tCommon(($) => $.navigation.open_in_new_tab)}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setArchiveOpen(true)}
- >
- <Trash2 className="size-3.5" />
- {t(($) => $.page.archive_action)}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setArchiveOpen(true)}
+ >
+ <Trash2 className="size-3.5" />
+ {t(($) => $.page.archive_action)}
+ </DropdownMenuItem>
+ </CollectionRowMenu>
<ArchiveSquadDialog
squad={squad}
open={archiveOpen}
onOpenChange={setArchiveOpen}
/>
- </span>
+ </>
);
}
-// Header + toolbar
-
-function SquadListHeader({
- sortField,
- sortDirection,
- onSort,
- isColVisible,
-}: {
- sortField: SquadSortField;
- sortDirection: ListGridSortDirection;
- onSort: (field: SquadSortField) => void;
- isColVisible: (key: SquadColumnKey) => boolean;
-}) {
- const { t } = useT("squads");
- const sorted = (field: SquadSortField) =>
- sortField === field ? sortDirection : false;
- return (
- <ListGridHeader>
- <ListGridHeaderCell sorted={sorted("name")} onSort={() => onSort("name")}>
- {t(($) => $.page.table.name)}
- </ListGridHeaderCell>
- <ListGridHeaderCell>{t(($) => $.page.table.leader)}</ListGridHeaderCell>
- {isColVisible("members") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("members")}
- onSort={() => onSort("members")}
- >
- {t(($) => $.page.table.members)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("creator") ? (
- <ListGridHeaderCell className="hidden @2xl:flex">
- {t(($) => $.page.table.creator)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridHeaderCell
- className="hidden @2xl:flex"
- sorted={sorted("created")}
- onSort={() => onSort("created")}
- >
- {t(($) => $.page.table.created)}
- </ListGridHeaderCell>
- ) : (
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- )}
- {/* kebab track placeholder (track width collapses when no actions) */}
- <span aria-hidden="true" />
- </ListGridHeader>
- );
-}
-
-const COLUMN_KEYS: SquadColumnKey[] = ["members", "creator", "created"];
-const SORT_FIELDS: SquadSortField[] = ["name", "members", "created"];
+// Toolbar
interface ActorOption {
id: string;
@@ -441,329 +266,83 @@ interface ActorOption {
count: number;
}
-function SquadListToolbar({
- scope,
- onScopeChange,
- scopeCounts,
+function countActiveFilters(filters: SquadListFilters): number {
+ return (
+ (filters.leaders.length > 0 ? 1 : 0) +
+ (filters.creators.length > 0 ? 1 : 0)
+ );
+}
+
+function SquadFilterMenu({
filters,
onToggleFilter,
- onClearFilters,
leaderOptions,
creatorOptions,
- visibleCount,
- totalCount,
- sortField,
- sortDirection,
- onSortFieldChange,
- onSortDirectionChange,
- hiddenColumns,
- onToggleColumn,
}: {
- scope: SquadsScope;
- onScopeChange: (scope: SquadsScope) => void;
- scopeCounts: Record<SquadsScope, number>;
filters: SquadListFilters;
onToggleFilter: (key: keyof SquadListFilters, value: string) => void;
- onClearFilters: () => void;
leaderOptions: ActorOption[];
creatorOptions: ActorOption[];
- visibleCount: number;
- totalCount: number;
- sortField: SquadSortField;
- sortDirection: ListGridSortDirection;
- onSortFieldChange: (field: SquadSortField) => void;
- onSortDirectionChange: (direction: ListGridSortDirection) => void;
- hiddenColumns: SquadColumnKey[];
- onToggleColumn: (key: SquadColumnKey) => void;
}) {
const { t } = useT("squads");
- const activeFilterCount =
- (filters.leaders.length > 0 ? 1 : 0) +
- (filters.creators.length > 0 ? 1 : 0);
- const hasActiveFilters = activeFilterCount > 0;
const countBadge = (n: number) => (
<span className="ml-auto pl-3 text-caption text-muted-foreground">{n}</span>
);
- const SCOPE_LABELS: Record<SquadsScope, string> = {
- mine: t(($) => $.scope.mine),
- all: t(($) => $.scope.all),
- };
- const SORT_LABELS: Record<SquadSortField, string> = {
- name: t(($) => $.page.table.name),
- members: t(($) => $.page.table.members),
- created: t(($) => $.page.table.created),
- };
- const COLUMN_LABELS: Record<SquadColumnKey, string> = {
- members: t(($) => $.page.table.members),
- creator: t(($) => $.page.table.creator),
- created: t(($) => $.page.table.created),
- };
- const sortLabel = SORT_LABELS[sortField];
return (
- <div className={PAGE_TOOLBAR}>
- <div className="flex min-w-0 items-center gap-2">
- <div className="hidden shrink-0 items-center gap-1 md:flex">
- {SQUAD_SCOPES.map((s) => (
- <Button
- key={s}
- variant="outline"
- size="sm"
- className={
- scope === s
- ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"
- : "gap-1.5 text-muted-foreground"
- }
- onClick={() => onScopeChange(s)}
- >
- {SCOPE_LABELS[s]}
- <span className="tabular-nums text-caption text-muted-foreground">
- {scopeCounts[s]}
- </span>
- </Button>
- ))}
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="shrink-0 gap-1 text-muted-foreground md:hidden"
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<CollectionFilterButton count={countActiveFilters(filters)} />}
+ />
+ <DropdownMenuContent align="start" className="w-auto">
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.page.table.leader)}</span>
+ {filters.leaders.length > 0 && (
+ <span className="text-caption font-medium text-primary">{filters.leaders.length}</span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {leaderOptions.map((o) => (
+ <DropdownMenuCheckboxItem
+ key={o.id}
+ checked={filters.leaders.includes(o.id)}
+ onCheckedChange={() => onToggleFilter("leaders", o.id)}
+ className={FILTER_ITEM_CLASS}
>
- <span className="truncate">{SCOPE_LABELS[scope]}</span>
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={scope}
- onValueChange={(value) => onScopeChange(value as SquadsScope)}
- >
- {SQUAD_SCOPES.map((s) => (
- <DropdownMenuRadioItem key={s} value={s}>
- {SCOPE_LABELS[s]}
- <span className="ml-2 tabular-nums text-caption text-muted-foreground">
- {scopeCounts[s]}
- </span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {hasActiveFilters && (
- <span
- title={t(($) => $.toolbar.result_count_title)}
- className="hidden shrink-0 text-caption tabular-nums text-muted-foreground md:inline"
- >
- {visibleCount} / {totalCount}
- </span>
- )}
- </div>
-
- <div className="flex shrink-0 items-center gap-1">
- {/* Filter */}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant={hasActiveFilters ? "default" : "outline"}
- size="sm"
- className={
- hasActiveFilters
- ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:w-auto md:px-2.5"
- : "h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- }
- >
- <Filter className="size-3.5" />
- {hasActiveFilters ? (
- <>
- <span className="hidden md:inline">
- {t(($) => $.toolbar.filter_active_count, { count: activeFilterCount })}
- </span>
- <span className="tabular-nums md:hidden">{activeFilterCount}</span>
- </>
- ) : (
- <span className="hidden md:inline">{t(($) => $.toolbar.filter_label)}</span>
- )}
- {hasActiveFilters && (
- <span
- role="button"
- tabIndex={-1}
- aria-label={t(($) => $.toolbar.clear_filters)}
- className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onClearFilters();
- }}
- onPointerDown={(e) => e.stopPropagation()}
- >
- <X className="size-3" />
- </span>
- )}
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-auto">
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.page.table.leader)}</span>
- {filters.leaders.length > 0 && (
- <span className="text-caption font-medium text-primary">{filters.leaders.length}</span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {leaderOptions.map((o) => (
- <DropdownMenuCheckboxItem
- key={o.id}
- checked={filters.leaders.includes(o.id)}
- onCheckedChange={() => onToggleFilter("leaders", o.id)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.leaders.includes(o.id)} />
- <ActorAvatar actorType="agent" actorId={o.id} size="sm" />
- <span className="min-w-0 truncate">{o.name}</span>
- {countBadge(o.count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <span className="flex-1">{t(($) => $.page.table.creator)}</span>
- {filters.creators.length > 0 && (
- <span className="text-caption font-medium text-primary">{filters.creators.length}</span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
- {creatorOptions.map((o) => (
- <DropdownMenuCheckboxItem
- key={o.id}
- checked={filters.creators.includes(o.id)}
- onCheckedChange={() => onToggleFilter("creators", o.id)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={filters.creators.includes(o.id)} />
- <ActorAvatar actorType="member" actorId={o.id} size="sm" />
- <span className="min-w-0 truncate">{o.name}</span>
- {countBadge(o.count)}
- </DropdownMenuCheckboxItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
-
- {/* Display settings */}
- <Popover>
- <Tooltip>
- <PopoverTrigger
- render={
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="h-8 w-8 gap-1 px-0 text-muted-foreground md:w-auto md:px-2.5"
- >
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- <span className="hidden md:inline">{sortLabel}</span>
- </Button>
- }
- />
- }
- />
- <TooltipContent side="bottom">
- {t(($) => $.toolbar.display)}
- </TooltipContent>
- </Tooltip>
- <PopoverContent align="end" className="w-64 p-0">
- <div className="border-b px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.sort_by)}
- </span>
- <div className="mt-2 flex items-center gap-1.5">
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="flex-1 justify-between text-caption"
- >
- {sortLabel}
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto">
- <DropdownMenuRadioGroup
- value={sortField}
- onValueChange={(v) =>
- onSortFieldChange(v as SquadSortField)
- }
- >
- {SORT_FIELDS.map((field) => (
- <DropdownMenuRadioItem key={field} value={field}>
- {SORT_LABELS[field]}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- <IconButton
- variant="outline"
- size="icon-sm"
- onClick={() =>
- onSortDirectionChange(
- sortDirection === "asc" ? "desc" : "asc",
- )
- }
- label={
- sortDirection === "asc"
- ? t(($) => $.toolbar.direction_asc)
- : t(($) => $.toolbar.direction_desc)
- }
+ <HoverCheck checked={filters.leaders.includes(o.id)} />
+ <ActorAvatar actorType="agent" actorId={o.id} size="sm" />
+ <span className="min-w-0 truncate">{o.name}</span>
+ {countBadge(o.count)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span className="flex-1">{t(($) => $.page.table.creator)}</span>
+ {filters.creators.length > 0 && (
+ <span className="text-caption font-medium text-primary">{filters.creators.length}</span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="max-h-72 w-auto min-w-48 overflow-y-auto">
+ {creatorOptions.map((o) => (
+ <DropdownMenuCheckboxItem
+ key={o.id}
+ checked={filters.creators.includes(o.id)}
+ onCheckedChange={() => onToggleFilter("creators", o.id)}
+ className={FILTER_ITEM_CLASS}
>
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- </IconButton>
- </div>
- </div>
- <div className="px-3 py-2.5">
- <span className="text-caption font-medium text-muted-foreground">
- {t(($) => $.toolbar.section_columns)}
- </span>
- <div className="mt-2 space-y-2">
- {COLUMN_KEYS.map((key) => (
- <label
- key={key}
- className="flex cursor-pointer items-center justify-between"
- >
- <span className="text-body">{COLUMN_LABELS[key]}</span>
- <Switch
- size="sm"
- checked={!hiddenColumns.includes(key)}
- onCheckedChange={() => onToggleColumn(key)}
- />
- </label>
- ))}
- </div>
- </div>
- </PopoverContent>
- </Popover>
- </div>
- </div>
+ <HoverCheck checked={filters.creators.includes(o.id)} />
+ <ActorAvatar actorType="member" actorId={o.id} size="sm" />
+ <span className="min-w-0 truncate">{o.name}</span>
+ {countBadge(o.count)}
+ </DropdownMenuCheckboxItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>
);
}
@@ -775,7 +354,6 @@ export function SquadsPage() {
const workspace = useCurrentWorkspace();
const wsId = workspace?.id ?? "";
const p = useWorkspacePaths();
- const rowLink = useRowLink();
const currentUser = useAuthStore((s) => s.user);
const { data: squads = [], isLoading } = useQuery({
@@ -816,7 +394,13 @@ export function SquadsPage() {
const toggleFilter = useSquadsViewStore((s) => s.toggleFilter);
const clearFilters = useSquadsViewStore((s) => s.clearFilters);
- const isColVisible = (key: SquadColumnKey) => !hiddenColumns.includes(key);
+ const hasActiveFilters = countActiveFilters(filters) > 0;
+ const openCreateSquad = () => useModalStore.getState().open("create-squad");
+
+ const scopeLabels: Record<SquadsScope, string> = {
+ mine: t(($) => $.scope.mine),
+ all: t(($) => $.scope.all),
+ };
const scopeCounts = useMemo<Record<SquadsScope, number>>(() => {
let mine = 0;
@@ -826,8 +410,8 @@ export function SquadsPage() {
return { mine, all: squads.length };
}, [squads, currentUser]);
- // Rows within the current scope, unfiltered — filter option lists + the
- // "n / total" denominator derive from this.
+ // Rows within the current scope, unfiltered — the filter option lists
+ // derive from this.
const scopeRows = useMemo<Squad[]>(() => {
return squads.filter((s) => {
if (scope === "mine") {
@@ -908,19 +492,119 @@ export function SquadsPage() {
[isWorkspaceAdmin, rows, currentUser],
);
+ const canManage = (squad: Squad) =>
+ isWorkspaceAdmin || (!!currentUser && squad.creator_id === currentUser.id);
+
+ const columns = useMemo<CollectionColumn<Squad>[]>(
+ () => [
+ {
+ key: "name",
+ header: t(($) => $.page.table.name),
+ sortKey: "name",
+ cell: (squad) => (
+ <CollectionNameCell
+ icon={<SquadAvatar squad={squad} />}
+ title={squad.name}
+ description={squad.description}
+ />
+ ),
+ },
+ {
+ key: "leader",
+ header: t(($) => $.page.table.leader),
+ width: 160,
+ core: true,
+ cell: (squad) => (
+ <LeaderCell leaderId={squad.leader_id} leader={agentsById.get(squad.leader_id)} />
+ ),
+ },
+ {
+ key: "members",
+ header: t(($) => $.page.table.members),
+ width: 120,
+ sortKey: "members",
+ hideable: true,
+ cell: (squad) => <MembersCell squad={squad} />,
+ },
+ {
+ key: "creator",
+ header: t(($) => $.page.table.creator),
+ width: 144,
+ hideable: true,
+ cell: (squad) => (
+ <>
+ <ActorAvatar actorType="member" actorId={squad.creator_id} size="sm" />
+ <span className="min-w-0 truncate">
+ {membersById.get(squad.creator_id)?.name ?? squad.creator_id.slice(0, 8)}
+ </span>
+ </>
+ ),
+ },
+ {
+ key: "created",
+ header: t(($) => $.page.table.created),
+ width: 104,
+ sortKey: "created",
+ hideable: true,
+ cell: (squad) => (
+ <span className="tabular-nums">
+ {new Date(squad.created_at).toLocaleDateString(locale)}
+ </span>
+ ),
+ },
+ ],
+ [t, locale, agentsById, membersById],
+ );
+
+ const sort: CollectionSort = {
+ field: sortField,
+ direction: sortDirection,
+ onToggle: (field) => handleSort(field as SquadSortField),
+ onFieldChange: (field) => handleSortFieldSelect(field as SquadSortField),
+ onDirectionChange: setSortDirection,
+ };
+
return (
<div className="flex flex-1 min-h-0 flex-col">
<CollectionPageHeader
icon={Users}
- title={t(($) => $.page.title)}
- count={squads.length}
- actions={
- <CollectionPageHeaderAction
- icon={Plus}
- label={t(($) => $.page.new_button)}
- onClick={() => useModalStore.getState().open("create-squad")}
+ title={scopeLabels[scope]}
+ menu={
+ <CollectionScopeItems
+ value={scope}
+ onChange={setScope}
+ options={SQUAD_SCOPES.map((s) => ({
+ value: s,
+ label: scopeLabels[s],
+ count: scopeCounts[s],
+ }))}
/>
}
+ tools={
+ <>
+ <SquadFilterMenu
+ filters={filters}
+ onToggleFilter={toggleFilter}
+ leaderOptions={leaderOptions}
+ creatorOptions={creatorOptions}
+ />
+ {hasActiveFilters ? <CollectionResetButton onClick={clearFilters} /> : null}
+ </>
+ }
+ actions={
+ <>
+ <CollectionDisplayMenu
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ onToggleColumn={(key) => toggleColumn(key as SquadColumnKey)}
+ sort={sort}
+ />
+ <CollectionCreateButton
+ label={t(($) => $.page.new_button)}
+ onClick={openCreateSquad}
+ />
+ </>
+ }
/>
{!isLoading && squads.length === 0 ? (
@@ -928,161 +612,31 @@ export function SquadsPage() {
icon={Users}
title={t(($) => $.page.empty_no_squads)}
actions={
- <Button
- size="sm"
- onClick={() => useModalStore.getState().open("create-squad")}
- >
+ <Button size="sm" variant="outline" onClick={openCreateSquad}>
<Plus aria-hidden="true" className="size-3.5" />
{t(($) => $.page.new_button)}
</Button>
}
/>
) : (
- <>
- {/* Mounted through loading so the rows don't drop by a toolbar's
- height when the list lands. */}
- <SquadListToolbar
- scope={scope}
- onScopeChange={setScope}
- scopeCounts={scopeCounts}
- filters={filters}
- onToggleFilter={toggleFilter}
- onClearFilters={clearFilters}
- leaderOptions={leaderOptions}
- creatorOptions={creatorOptions}
- visibleCount={rows.length}
- totalCount={scopeRows.length}
- sortField={sortField}
- sortDirection={sortDirection}
- onSortFieldChange={handleSortFieldSelect}
- onSortDirectionChange={setSortDirection}
- hiddenColumns={hiddenColumns}
- onToggleColumn={toggleColumn}
- />
- {isLoading ? (
- <LoadingSkeleton />
- ) : (
- <div className="min-h-0 flex-1 overflow-auto @container">
- <ListGrid
- className={`${GRID_COLS} @2xl:min-w-[var(--sqc-minw)]`}
- style={{
- ...columnTrackVars(isColVisible, canManageAnyRow),
- paddingBottom: LIST_GRID_BOTTOM_CLEARANCE,
- }}
- >
- <SquadListHeader
- sortField={sortField}
- sortDirection={sortDirection}
- onSort={handleSort}
- isColVisible={isColVisible}
- />
- {rows.length === 0 ? (
- <div className="col-span-full py-16 text-center text-body text-muted-foreground">
- {t(($) => $.page.no_matches)}
- </div>
- ) : (
- rows.map((squad) => (
- <ListGridRow
- key={squad.id}
- className="cursor-pointer"
- {...rowLink(p.squadDetail(squad.id), squad.name)}
- >
- <NameCell squad={squad} />
- <LeaderCell
- leaderId={squad.leader_id}
- leader={agentsById.get(squad.leader_id)}
- />
- {isColVisible("members") ? (
- <MembersCell squad={squad} />
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("creator") ? (
- <ListGridCell className="hidden gap-1.5 @2xl:flex">
- <ActorAvatar
- actorType="member"
- actorId={squad.creator_id}
- size="sm"
- />
- <span className="min-w-0 truncate text-caption text-muted-foreground">
- {membersById.get(squad.creator_id)?.name ??
- squad.creator_id.slice(0, 8)}
- </span>
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- {isColVisible("created") ? (
- <ListGridCell className="hidden whitespace-nowrap text-caption tabular-nums text-muted-foreground @2xl:flex">
- {new Date(squad.created_at).toLocaleDateString(locale)}
- </ListGridCell>
- ) : (
- <ListGridCell className="hidden px-0 @2xl:flex" />
- )}
- <ListGridCell className="justify-end px-0">
- {isWorkspaceAdmin ||
- (!!currentUser && squad.creator_id === currentUser.id) ? (
- <SquadRowActions squad={squad} />
- ) : null}
- </ListGridCell>
- </ListGridRow>
- ))
- )}
- </ListGrid>
- </div>
- )}
- </>
+ <CollectionList
+ label={scopeLabels[scope]}
+ columns={columns}
+ hiddenColumns={hiddenColumns}
+ rows={rows}
+ loading={isLoading}
+ getRowId={(squad) => squad.id}
+ getRowHref={(squad) => p.squadDetail(squad.id)}
+ getRowTitle={(squad) => squad.name}
+ rowMenu={
+ canManageAnyRow
+ ? (squad) => (canManage(squad) ? <SquadRowActions squad={squad} /> : null)
+ : undefined
+ }
+ sort={sort}
+ empty={t(($) => $.page.no_matches)}
+ />
)}
</div>
);
}
-
-function LoadingSkeleton() {
- return (
- <div className="min-h-0 flex-1 overflow-auto @container">
- <ListGrid
- className={GRID_COLS}
- style={columnTrackVars(
- (key) => !SQUAD_DEFAULT_HIDDEN_COLUMNS.includes(key),
- true,
- )}
- >
- <ListGridHeader>
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell>
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden @2xl:flex">
- <Skeleton className="h-3 w-12" />
- </ListGridHeaderCell>
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <ListGridHeaderCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridHeader>
- {Array.from({ length: 4 }).map((_, i) => (
- <ListGridRow key={i} className="h-16 hover:bg-transparent">
- <ListGridCell className="gap-3">
- <Skeleton className="size-8 rounded-full" />
- <div className="min-w-0 flex-1 space-y-1.5">
- <Skeleton className="h-3.5 w-32 max-w-full" />
- <Skeleton className="h-3 w-48 max-w-full" />
- </div>
- </ListGridCell>
- <ListGridCell className="gap-1.5">
- <Skeleton className="size-5 rounded-full" />
- <Skeleton className="h-3 w-16" />
- </ListGridCell>
- <ListGridCell className="hidden @2xl:flex">
- <Skeleton className="h-5 w-16" />
- </ListGridCell>
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <ListGridCell className="hidden px-0 @2xl:flex" />
- <span aria-hidden="true" />
- </ListGridRow>
- ))}
- </ListGrid>
- </div>
- );
-}
diff --git a/packages/views/workflows/project-workflow-menu.tsx b/packages/views/workflows/project-workflow-menu.tsx
index cae0fb282b..1207c61253 100644
--- a/packages/views/workflows/project-workflow-menu.tsx
+++ b/packages/views/workflows/project-workflow-menu.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useState } from "react";
+import { useState, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
-import { ChevronDown, ChevronRight, ListTree, Settings, Workflow } from "@multica/ui/icons";
+import { ChevronRight, ListTree, Settings, Workflow } from "@multica/ui/icons";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import {
@@ -13,10 +13,7 @@ import {
import { useWorkspacePaths } from "@multica/core/paths";
import { projectListOptions } from "@multica/core/projects/queries";
import type { IssueWorkflow, Project } from "@multica/core/types";
-import { Button } from "@multica/ui/components/ui/button";
import {
- DropdownMenu,
- DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
@@ -24,7 +21,6 @@ import {
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
- DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@multica/ui/components/ui/sheet";
import { cn } from "@multica/ui/lib/utils";
@@ -39,10 +35,20 @@ import { useProjectWorkflowSwitch, WorkflowChoiceItems } from "./project-workflo
import { stepHandlerActor, useStepHandlerLabel } from "./step-handler";
/**
- * The project board's "Workflow" menu (MUL-7420): open the full flow or switch
- * workflows; workflows themselves are made in settings.
+ * The project's "Workflow" submenu (MUL-7420), shown in the project title's
+ * menu: open the full flow or switch workflows; workflows themselves are made
+ * in settings.
+ *
+ * The flow sheet and the switch dialog must outlive the menu that opens them,
+ * so this host owns both and hands the submenu to `children` to place.
*/
-export function ProjectWorkflowMenu({ project }: { project: Project }) {
+export function ProjectWorkflowMenuHost({
+ project,
+ children,
+}: {
+ project: Project;
+ children: (submenu: ReactNode) => ReactNode;
+}) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
const navigation = useNavigation();
@@ -53,53 +59,54 @@ export function ProjectWorkflowMenu({ project }: { project: Project }) {
const [flowOpen, setFlowOpen] = useState(false);
const workflow = resolveProjectWorkflow(workflows, project);
- if (!workflow) return null;
+ const submenu = workflow ? (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger disabled={busy}>
+ <Workflow className="size-3.5" />
+ <span className="flex-1">{t(($) => $.workflows.project.label)}</span>
+ <span className="ml-3 max-w-32 truncate text-caption font-medium text-muted-foreground">
+ {workflow.name}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-64">
+ <DropdownMenuItem onClick={() => setFlowOpen(true)}>
+ <ListTree className="size-3.5" />
+ {t(($) => $.workflows.menu.view_flow)}
+ </DropdownMenuItem>
+ {canManageProject && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Workflow className="size-3.5" />
+ {t(($) => $.workflows.menu.switch)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-80">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.workflows.project.picker_title)}</DropdownMenuLabel>
+ <WorkflowChoiceItems project={project} onChoose={(w) => void choose(w)} />
+ </DropdownMenuGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )}
+ {canCreateWorkflow && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => navigation.push(`${paths.settings()}?tab=workflows`)}>
+ <Settings className="size-3.5" />
+ {t(($) => $.workflows.project.manage)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ ) : null;
return (
<>
- <DropdownMenu>
- <DropdownMenuTrigger
- disabled={busy}
- render={
- <Button variant="ghost" size="sm" className="gap-1.5 text-muted-foreground">
- <Workflow className="size-3.5" />
- <span className="max-w-40 truncate">{workflow.name}</span>
- <ChevronDown className="size-3" />
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="w-64">
- <DropdownMenuItem onClick={() => setFlowOpen(true)}>
- <ListTree className="size-3.5" />
- {t(($) => $.workflows.menu.view_flow)}
- </DropdownMenuItem>
- {canManageProject && (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <Workflow className="size-3.5" />
- {t(($) => $.workflows.menu.switch)}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-80">
- <DropdownMenuGroup>
- <DropdownMenuLabel>{t(($) => $.workflows.project.picker_title)}</DropdownMenuLabel>
- <WorkflowChoiceItems project={project} onChoose={(w) => void choose(w)} />
- </DropdownMenuGroup>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- )}
- {canCreateWorkflow && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => navigation.push(`${paths.settings()}?tab=workflows`)}>
- <Settings className="size-3.5" />
- {t(($) => $.workflows.project.manage)}
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ {children(submenu)}
{dialog}
- <WorkflowFlowSheet open={flowOpen} onOpenChange={setFlowOpen} project={project} workflow={workflow} />
+ {workflow && (
+ <WorkflowFlowSheet open={flowOpen} onOpenChange={setFlowOpen} project={project} workflow={workflow} />
+ )}
</>
);
}
diff --git a/server/internal/handler/issue_table_advanced.go b/server/internal/handler/issue_table_advanced.go
new file mode 100644
index 0000000000..f94bc3a097
--- /dev/null
+++ b/server/internal/handler/issue_table_advanced.go
@@ -0,0 +1,328 @@
+package handler
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// issueTableDueDates are the relative due-date buckets `filters.due_dates`
+// and advanced `due_dates` conditions accept. They resolve against
+// `filters.today`, the viewer's calendar day, so a saved view never pins a
+// date and "today" means the viewer's today rather than the server's.
+var issueTableDueDates = []string{"overdue", "today", "this_week", "next_7_days", "none"}
+
+// issueTableFilterFields are the dimensions an advanced condition can test,
+// named like their flat `filters` counterparts. A condition can also test a
+// custom property as `property:<definitionId>`.
+var issueTableFilterFields = []string{
+ "statuses", "priorities", "assignees", "creators",
+ "project_ids", "project_statuses", "label_ids", "relations", "due_dates",
+}
+
+const issueTableFilterPropertyPrefix = "property:"
+
+const (
+ issueTableFilterMaxConditions = 50
+ issueTableFilterMaxValues = 500
+ issueTableFilterNoneValue = "none"
+)
+
+// issueTableFilterNode is one node of `filters.advanced`: a group when it has
+// `children`, otherwise a condition. The root is a group; a group directly
+// under the root may hold conditions only, so the tree is at most two levels
+// of parentheses deep. Values are strings, except that a property condition
+// takes the members `filters.properties` does, operator objects included.
+type issueTableFilterNode struct {
+ Match string `json:"match,omitempty"`
+ Children []issueTableFilterNode `json:"children,omitempty"`
+ Field string `json:"field,omitempty"`
+ Negate bool `json:"negate,omitempty"`
+ Values []json.RawMessage `json:"values,omitempty"`
+}
+
+func (n issueTableFilterNode) isGroup() bool {
+ return n.Field == ""
+}
+
+// canonicalIssueTableFilterNode copies the tree with condition values sorted
+// and deduplicated, so equivalent trees share a fingerprint.
+func canonicalIssueTableFilterNode(node *issueTableFilterNode) *issueTableFilterNode {
+ if node == nil {
+ return nil
+ }
+ out := issueTableFilterNode{
+ Match: node.Match,
+ Field: node.Field,
+ Negate: node.Negate,
+ Values: sortedUniqueRawJSON(node.Values),
+ }
+ if len(node.Children) > 0 {
+ out.Children = make([]issueTableFilterNode, len(node.Children))
+ for i := range node.Children {
+ out.Children[i] = *canonicalIssueTableFilterNode(&node.Children[i])
+ }
+ }
+ return &out
+}
+
+func parseIssueTableToday(raw string) (time.Time, bool) {
+ today, err := time.Parse(time.DateOnly, raw)
+ return today, err == nil
+}
+
+// issueTableDueDatePredicate matches one relative due-date bucket. Weeks run
+// Monday to Sunday.
+func issueTableDueDatePredicate(bucket string, today time.Time, addArg func(any) string) string {
+ switch bucket {
+ case "overdue":
+ return fmt.Sprintf("i.due_date < %s::date", addArg(today))
+ case "today":
+ return fmt.Sprintf("i.due_date = %s::date", addArg(today))
+ case "this_week":
+ offset := (int(today.Weekday()) + 6) % 7
+ monday := today.AddDate(0, 0, -offset)
+ return fmt.Sprintf("(i.due_date >= %s::date AND i.due_date < %s::date)", addArg(monday), addArg(monday.AddDate(0, 0, 7)))
+ case "next_7_days":
+ return fmt.Sprintf("(i.due_date >= %s::date AND i.due_date < %s::date)", addArg(today), addArg(today.AddDate(0, 0, 7)))
+ default: // none
+ return "i.due_date IS NULL"
+ }
+}
+
+// issueTableFilterCompiler turns `filters.advanced` into one SQL predicate.
+// The user and the viewer's day are resolved only when a condition needs
+// them, so a tree without relations or due dates does not require them.
+type issueTableFilterCompiler struct {
+ addArg func(any) string
+ userRef func() (string, error)
+ today func() (time.Time, error)
+ conditions int
+}
+
+type issueTableFilterError struct {
+ status int
+ message string
+}
+
+func (e issueTableFilterError) Error() string { return e.message }
+
+func invalidIssueTableFilter(format string, args ...any) error {
+ return issueTableFilterError{status: http.StatusBadRequest, message: fmt.Sprintf(format, args...)}
+}
+
+// compile returns "" for a tree that constrains nothing.
+func (c *issueTableFilterCompiler) compile(root issueTableFilterNode) (string, error) {
+ if !root.isGroup() {
+ return "", invalidIssueTableFilter("invalid filters.advanced: root must be a group")
+ }
+ return c.group(root, 0)
+}
+
+func (c *issueTableFilterCompiler) group(node issueTableFilterNode, depth int) (string, error) {
+ joiner := " AND "
+ switch node.Match {
+ case "", "all":
+ case "any":
+ joiner = " OR "
+ default:
+ return "", invalidIssueTableFilter("invalid filters.advanced.match")
+ }
+ parts := make([]string, 0, len(node.Children))
+ for _, child := range node.Children {
+ var (
+ predicate string
+ err error
+ )
+ if child.isGroup() {
+ if depth > 0 {
+ return "", invalidIssueTableFilter("invalid filters.advanced: groups nest one level deep")
+ }
+ predicate, err = c.group(child, depth+1)
+ } else {
+ predicate, err = c.condition(child)
+ }
+ if err != nil {
+ return "", err
+ }
+ // Empty conditions and groups drop out rather than reading as TRUE,
+ // which would make an "any" group match everything.
+ if predicate != "" {
+ parts = append(parts, predicate)
+ }
+ }
+ switch len(parts) {
+ case 0:
+ return "", nil
+ case 1:
+ return parts[0], nil
+ default:
+ return "(" + strings.Join(parts, joiner) + ")", nil
+ }
+}
+
+func (c *issueTableFilterCompiler) condition(node issueTableFilterNode) (string, error) {
+ propertyID, isProperty := strings.CutPrefix(node.Field, issueTableFilterPropertyPrefix)
+ if !isProperty && !issueTableContainsString(issueTableFilterFields, node.Field) {
+ return "", invalidIssueTableFilter("invalid filters.advanced.field")
+ }
+ if len(node.Children) > 0 || node.Match != "" {
+ return "", invalidIssueTableFilter("invalid filters.advanced: a condition has no children")
+ }
+ if len(node.Values) == 0 {
+ return "", nil
+ }
+ if len(node.Values) > issueTableFilterMaxValues {
+ return "", invalidIssueTableFilter("invalid filters.advanced: too many values")
+ }
+ c.conditions++
+ if c.conditions > issueTableFilterMaxConditions {
+ return "", invalidIssueTableFilter("invalid filters.advanced: too many conditions")
+ }
+ var (
+ predicate string
+ err error
+ )
+ if isProperty {
+ predicate, err = c.propertyPredicate(propertyID, node.Values)
+ } else {
+ values := make([]string, 0, len(node.Values))
+ for _, raw := range node.Values {
+ var value string
+ if json.Unmarshal(raw, &value) != nil {
+ return "", invalidIssueTableFilter("invalid filters.advanced values for %s", node.Field)
+ }
+ values = append(values, value)
+ }
+ predicate, err = c.fieldPredicate(node.Field, sortedUniqueStrings(values))
+ }
+ if err != nil {
+ return "", err
+ }
+ if node.Negate {
+ return "(" + predicate + ") IS NOT TRUE", nil
+ }
+ return predicate, nil
+}
+
+// propertyPredicate compiles a property condition exactly like the same
+// members under `filters.properties`.
+func (c *issueTableFilterCompiler) propertyPredicate(propertyID string, values []json.RawMessage) (string, error) {
+ groups, err := compilePropertiesFilter(map[string][]json.RawMessage{propertyID: values})
+ if err != nil {
+ return "", invalidIssueTableFilter("invalid filters.advanced: %s", err.Error())
+ }
+ if len(groups) == 0 {
+ return "", nil
+ }
+ return propertiesFilterPredicate(groups, c.addArg), nil
+}
+
+func (c *issueTableFilterCompiler) fieldPredicate(field string, values []string) (string, error) {
+ invalid := invalidIssueTableFilter("invalid filters.advanced values for %s", field)
+ ors := make([]string, 0, len(values))
+ switch field {
+ case "statuses":
+ for _, status := range values {
+ if len(status) > 64 {
+ return "", invalid
+ }
+ }
+ return fmt.Sprintf("i.status = ANY(%s::text[])", c.addArg(values)), nil
+ case "priorities":
+ for _, priority := range values {
+ if !issueTableContainsString(validIssuePriorities, priority) {
+ return "", invalid
+ }
+ }
+ return fmt.Sprintf("i.priority = ANY(%s::text[])", c.addArg(values)), nil
+ case "assignees", "creators":
+ column := "assignee"
+ if field == "creators" {
+ column = "creator"
+ }
+ for _, value := range values {
+ if value == issueTableFilterNoneValue && field == "assignees" {
+ ors = append(ors, "(i.assignee_type IS NULL AND i.assignee_id IS NULL)")
+ continue
+ }
+ actorType, rawID, ok := strings.Cut(value, ":")
+ if !ok || !isIssueActorType(actorType) {
+ return "", invalid
+ }
+ id, err := util.ParseUUID(rawID)
+ if err != nil {
+ return "", invalid
+ }
+ ors = append(ors, fmt.Sprintf("(i.%[1]s_type = %[2]s::text AND i.%[1]s_id = %[3]s::uuid)", column, c.addArg(actorType), c.addArg(id)))
+ }
+ case "project_ids":
+ ids := make([]pgtype.UUID, 0, len(values))
+ for _, value := range values {
+ if value == issueTableFilterNoneValue {
+ ors = append(ors, "i.project_id IS NULL")
+ continue
+ }
+ id, err := util.ParseUUID(value)
+ if err != nil {
+ return "", invalid
+ }
+ ids = append(ids, id)
+ }
+ if len(ids) > 0 {
+ ors = append(ors, fmt.Sprintf("i.project_id = ANY(%s::uuid[])", c.addArg(ids)))
+ }
+ case "project_statuses":
+ for _, status := range values {
+ if !issueTableContainsString(validProjectStatuses, status) {
+ return "", invalid
+ }
+ }
+ return fmt.Sprintf(
+ "EXISTS (SELECT 1 FROM project p WHERE p.id = i.project_id AND p.workspace_id = i.workspace_id AND p.status = ANY(%s::text[]))",
+ c.addArg(values),
+ ), nil
+ case "label_ids":
+ ids := make([]pgtype.UUID, 0, len(values))
+ for _, value := range values {
+ id, err := util.ParseUUID(value)
+ if err != nil {
+ return "", invalid
+ }
+ ids = append(ids, id)
+ }
+ return fmt.Sprintf("EXISTS (SELECT 1 FROM issue_to_label itl WHERE itl.issue_id = i.id AND itl.label_id = ANY(%s::uuid[]))", c.addArg(ids)), nil
+ case "relations":
+ for _, relation := range values {
+ if !issueTableContainsString(issueTableRelations, relation) {
+ return "", invalid
+ }
+ }
+ userRef, err := c.userRef()
+ if err != nil {
+ return "", err
+ }
+ for _, relation := range values {
+ ors = append(ors, issueTableRelationPredicate(relation, userRef))
+ }
+ case "due_dates":
+ for _, bucket := range values {
+ if !issueTableContainsString(issueTableDueDates, bucket) {
+ return "", invalid
+ }
+ }
+ today, err := c.today()
+ if err != nil {
+ return "", err
+ }
+ for _, bucket := range values {
+ ors = append(ors, issueTableDueDatePredicate(bucket, today, c.addArg))
+ }
+ }
+ return "(" + strings.Join(ors, " OR ") + ")", nil
+}
diff --git a/server/internal/handler/issue_table_advanced_test.go b/server/internal/handler/issue_table_advanced_test.go
new file mode 100644
index 0000000000..ba35220f21
--- /dev/null
+++ b/server/internal/handler/issue_table_advanced_test.go
@@ -0,0 +1,274 @@
+package handler
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// rawValues encodes condition values the way a client sends them.
+func rawValues(values ...any) []json.RawMessage {
+ out := make([]json.RawMessage, 0, len(values))
+ for _, value := range values {
+ buf, err := json.Marshal(value)
+ if err != nil {
+ panic(err)
+ }
+ out = append(out, buf)
+ }
+ return out
+}
+
+// issueTableFixtureRows lists, sorted, the ids from `fixture` that a workspace
+// table query with these filters returns.
+func issueTableFixtureRows(t *testing.T, fixture map[string]struct{}, filters issueTableFiltersRequest) []string {
+ t.Helper()
+ var response issueTableRowsResponse
+ testutil.Call(t, testHandler.ListIssueTableRows,
+ newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Filters: filters,
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "none"},
+ Page: issueTablePageRequest{Limit: 100},
+ }),
+ ).Want(http.StatusOK).JSON(&response)
+ ids := make([]string, 0, len(response.Rows))
+ for _, row := range response.Rows {
+ if _, ok := fixture[row.Issue.ID]; ok {
+ ids = append(ids, row.Issue.ID)
+ }
+ }
+ sort.Strings(ids)
+ return ids
+}
+
+// Buckets resolve against the viewer's day: 2026-03-11 is a Wednesday, so
+// "this week" is Mar 9–15 and "next 7 days" is Mar 11–17.
+func TestIssueTableRowsDueDateBuckets(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ issue := func(title string, due any) string {
+ return dbfx.Issue(t, fmt.Sprintf("due %s %d", title, suffix), testutil.Cols{"due_date": due})
+ }
+ yesterday := issue("yesterday", "2026-03-10")
+ today := issue("today", "2026-03-11")
+ sunday := issue("sunday", "2026-03-15")
+ nextMonday := issue("next monday", "2026-03-16")
+ later := issue("later", "2026-03-30")
+ undated := issue("undated", nil)
+ fixture := map[string]struct{}{
+ yesterday: {}, today: {}, sunday: {}, nextMonday: {}, later: {}, undated: {},
+ }
+ assertRows := func(name string, filters issueTableFiltersRequest, want ...string) {
+ t.Helper()
+ filters.Today = "2026-03-11"
+ got := issueTableFixtureRows(t, fixture, filters)
+ sort.Strings(want)
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("%s: ids = %v, want %v", name, got, want)
+ }
+ }
+
+ assertRows("overdue", issueTableFiltersRequest{DueDates: []string{"overdue"}}, yesterday)
+ assertRows("today", issueTableFiltersRequest{DueDates: []string{"today"}}, today)
+ assertRows("this week runs Monday to Sunday",
+ issueTableFiltersRequest{DueDates: []string{"this_week"}}, yesterday, today, sunday)
+ assertRows("next 7 days starts today",
+ issueTableFiltersRequest{DueDates: []string{"next_7_days"}}, today, sunday, nextMonday)
+ assertRows("no due date", issueTableFiltersRequest{DueDates: []string{"none"}}, undated)
+ assertRows("buckets OR together",
+ issueTableFiltersRequest{DueDates: []string{"overdue", "none"}}, yesterday, undated)
+ assertRows("is not overdue keeps undated rows",
+ issueTableFiltersRequest{DueDates: []string{"overdue"}, Negate: []string{"due_dates"}},
+ today, sunday, nextMonday, later, undated)
+}
+
+// The tree ORs across dimensions, which no combination of flat filters can.
+func TestIssueTableRowsAdvancedFilter(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ project := dbfx.Project(t, fmt.Sprintf("advanced project %d", suffix))
+ label := dbfx.Insert(t, "issue_label", testutil.Cols{
+ "workspace_id": testWorkspaceID, "name": fmt.Sprintf("bug %d", suffix), "color": "#ff0000",
+ })
+ issue := func(title string, cols testutil.Cols) string {
+ return dbfx.Issue(t, fmt.Sprintf("advanced %s %d", title, suffix), cols)
+ }
+ estimate := uuid.NewString()
+ estimateOf := func(n int) any { return testutil.Raw(fmt.Sprintf(`'{"%s": %d}'::jsonb`, estimate, n)) }
+ urgentInProject := issue("urgent in project", testutil.Cols{"priority": "urgent", "project_id": project, "properties": estimateOf(5)})
+ bugInProject := issue("bug in project", testutil.Cols{"priority": "low", "project_id": project, "due_date": "2026-03-10", "properties": estimateOf(2)})
+ quietInProject := issue("quiet in project", testutil.Cols{"priority": "low", "project_id": project, "status": "done"})
+ urgentElsewhere := issue("urgent elsewhere", testutil.Cols{"priority": "urgent", "assignee_type": "member", "assignee_id": testUserID})
+ dbfx.InsertNoID(t, "issue_to_label", testutil.Cols{"issue_id": bugInProject, "label_id": label},
+ "issue_id = $1", bugInProject)
+ fixture := map[string]struct{}{
+ urgentInProject: {}, bugInProject: {}, quietInProject: {}, urgentElsewhere: {},
+ }
+ cond := func(field string, negate bool, values ...any) issueTableFilterNode {
+ return issueTableFilterNode{Field: field, Negate: negate, Values: rawValues(values...)}
+ }
+ atLeast3 := map[string]string{"op": "gte", "value": "3"}
+ assertTree := func(name string, root issueTableFilterNode, want ...string) {
+ t.Helper()
+ got := issueTableFixtureRows(t, fixture, issueTableFiltersRequest{Advanced: &root, Today: "2026-03-11"})
+ sort.Strings(want)
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("%s: ids = %v, want %v", name, got, want)
+ }
+ }
+
+ assertTree("project AND (urgent OR bug)",
+ issueTableFilterNode{Match: "all", Children: []issueTableFilterNode{
+ cond("project_ids", false, project),
+ {Match: "any", Children: []issueTableFilterNode{
+ cond("priorities", false, "urgent"),
+ cond("label_ids", false, label),
+ }},
+ }},
+ urgentInProject, bugInProject)
+ assertTree("any at the root ORs across dimensions",
+ issueTableFilterNode{Match: "any", Children: []issueTableFilterNode{
+ cond("label_ids", false, label),
+ cond("relations", false, "assigned"),
+ }},
+ bugInProject, urgentElsewhere)
+ assertTree("negated condition keeps rows without a value",
+ issueTableFilterNode{Children: []issueTableFilterNode{
+ cond("project_ids", true, project),
+ }},
+ urgentElsewhere)
+ assertTree("assignee none and due buckets",
+ issueTableFilterNode{Children: []issueTableFilterNode{
+ cond("assignees", false, "none"),
+ cond("due_dates", true, "overdue"),
+ cond("statuses", true, "done"),
+ }},
+ urgentInProject)
+ // An empty condition or group must not read as TRUE inside "any".
+ assertTree("empty members drop out",
+ issueTableFilterNode{Match: "any", Children: []issueTableFilterNode{
+ cond("priorities", false),
+ {Match: "all"},
+ cond("label_ids", false, label),
+ }},
+ bugInProject)
+ assertTree("an empty tree constrains nothing",
+ issueTableFilterNode{Match: "any"},
+ urgentInProject, bugInProject, quietInProject, urgentElsewhere)
+ assertTree("a one-condition group is that condition",
+ issueTableFilterNode{Match: "any", Children: []issueTableFilterNode{
+ cond("priorities", false, "urgent"),
+ }},
+ urgentInProject, urgentElsewhere)
+ assertTree("a property condition ORs with a dimension",
+ issueTableFilterNode{Match: "any", Children: []issueTableFilterNode{
+ cond("property:"+estimate, false, atLeast3),
+ cond("label_ids", false, label),
+ }},
+ urgentInProject, bugInProject)
+ assertTree("a negated property condition keeps rows without a value",
+ issueTableFilterNode{Children: []issueTableFilterNode{
+ cond("property:"+estimate, true, atLeast3),
+ }},
+ bugInProject, quietInProject, urgentElsewhere)
+ assertTree("a property condition takes no value",
+ issueTableFilterNode{Children: []issueTableFilterNode{
+ cond("property:"+estimate, false, noPropertyValue),
+ cond("priorities", false, "urgent"),
+ }},
+ urgentElsewhere)
+ got := issueTableFixtureRows(t, fixture, issueTableFiltersRequest{
+ ProjectIDs: []string{project},
+ Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{
+ cond("priorities", false, "urgent"),
+ }},
+ })
+ if fmt.Sprint(got) != fmt.Sprint([]string{urgentInProject}) {
+ t.Fatalf("flat AND tree: ids = %v, want [%s]", got, urgentInProject)
+ }
+}
+
+func TestIssueTableRowsRejectsInvalidAdvancedAndDueDates(t *testing.T) {
+ nested := issueTableFilterNode{Children: []issueTableFilterNode{
+ {Match: "any", Children: []issueTableFilterNode{
+ {Match: "all", Children: []issueTableFilterNode{{Field: "priorities", Values: rawValues("high")}}},
+ }},
+ }}
+ tooMany := issueTableFilterNode{}
+ for i := 0; i <= issueTableFilterMaxConditions; i++ {
+ tooMany.Children = append(tooMany.Children, issueTableFilterNode{Field: "priorities", Values: rawValues("high")})
+ }
+ for name, filters := range map[string]issueTableFiltersRequest{
+ "unknown bucket": {DueDates: []string{"tomorrow"}, Today: "2026-03-11"},
+ "bucket without today": {DueDates: []string{"today"}},
+ "malformed today": {DueDates: []string{"today"}, Today: "11/03/2026"},
+ "tree nested too deep": {Advanced: &nested},
+ "unknown field": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{{Field: "title", Values: rawValues("x")}}}},
+ "bad actor value": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{{Field: "assignees", Values: rawValues("robot:1")}}}},
+ "creator cannot be none": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{{Field: "creators", Values: rawValues("none")}}}},
+ "unknown match": {Advanced: &issueTableFilterNode{Match: "xor"}},
+ "root is a condition": {Advanced: &issueTableFilterNode{Field: "priorities", Values: rawValues("high")}},
+ "tree due without today": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{{Field: "due_dates", Values: rawValues("overdue")}}}},
+ "too many conditions": {Advanced: &tooMany},
+ "property id not a uuid": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{{Field: "property:estimate", Values: rawValues("3")}}}},
+ "bad property operator": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{
+ {Field: "property:" + uuid.NewString(), Values: rawValues(map[string]string{"op": "gte", "value": "many"})},
+ }}},
+ "non-string dimension value": {Advanced: &issueTableFilterNode{Children: []issueTableFilterNode{{Field: "priorities", Values: rawValues(1)}}}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ testutil.Call(t, testHandler.ListIssueTableRows,
+ newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Filters: filters,
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "none"},
+ Page: issueTablePageRequest{Limit: 50},
+ }),
+ ).Want(http.StatusBadRequest)
+ })
+ }
+}
+
+func TestIssueTableFingerprintCanonicalizesAdvancedValues(t *testing.T) {
+ spec := func(values ...any) issueTableQuerySpec {
+ return issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Filters: issueTableFiltersRequest{Advanced: &issueTableFilterNode{
+ Match: "any",
+ Children: []issueTableFilterNode{{Field: "priorities", Values: rawValues(values...)}},
+ }},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ }
+ }
+ original := spec("urgent", "high", "urgent")
+ a, err := canonicalIssueTableFingerprint(testWorkspaceID, original)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := canonicalIssueTableFingerprint(testWorkspaceID, spec("high", "urgent"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if a != b {
+ t.Fatalf("value order changed the fingerprint: %s != %s", a, b)
+ }
+ values := make([]string, 0, 3)
+ for _, raw := range original.Filters.Advanced.Children[0].Values {
+ values = append(values, string(raw))
+ }
+ if fmt.Sprint(values) != `["urgent" "high" "urgent"]` {
+ t.Fatalf("fingerprint mutated the request: %v", values)
+ }
+}
diff --git a/server/internal/handler/issue_table_facets.go b/server/internal/handler/issue_table_facets.go
index 0b0481dc31..f289676c4a 100644
--- a/server/internal/handler/issue_table_facets.go
+++ b/server/internal/handler/issue_table_facets.go
@@ -50,21 +50,40 @@ func issueTableQueryWithoutFacet(input issueTableQuerySpec, facet issueTableFace
}
}
+ withoutNegate := func(field string) {
+ kept := make([]string, 0, len(input.Filters.Negate))
+ for _, negated := range input.Filters.Negate {
+ if negated != field {
+ kept = append(kept, negated)
+ }
+ }
+ if len(kept) == 0 {
+ kept = nil
+ }
+ output.Filters.Negate = kept
+ }
+
switch facet.Kind {
case "status":
output.Filters.Statuses = nil
+ withoutNegate("statuses")
case "priority":
output.Filters.Priorities = nil
+ withoutNegate("priorities")
case "assignee":
output.Filters.Assignees = nil
output.Filters.IncludeNoAssignee = false
+ withoutNegate("assignees")
case "creator":
output.Filters.Creators = nil
+ withoutNegate("creators")
case "project":
output.Filters.ProjectIDs = nil
output.Filters.IncludeNoProject = false
+ withoutNegate("project_ids")
case "label":
output.Filters.LabelIDs = nil
+ withoutNegate("label_ids")
case "property":
delete(output.Filters.Properties, facet.PropertyID)
case "working_agents":
diff --git a/server/internal/handler/issue_table_negation_test.go b/server/internal/handler/issue_table_negation_test.go
new file mode 100644
index 0000000000..1d2e363f16
--- /dev/null
+++ b/server/internal/handler/issue_table_negation_test.go
@@ -0,0 +1,184 @@
+package handler
+
+import (
+ "fmt"
+ "net/http"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// "Is not" keeps exactly the rows "is" drops — including rows where the
+// dimension has no value at all — and relations OR together the ways the
+// requesting user relates to an issue.
+func TestIssueTableRowsNegationAndRelations(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ otherUser := dbfx.User(t, fmt.Sprintf("negate other %d", suffix), fmt.Sprintf("negate-%[email protected]", suffix))
+ myAgent := dbfx.Agent(t, fmt.Sprintf("negate mine %d", suffix), "")
+ otherAgent := dbfx.Agent(t, fmt.Sprintf("negate theirs %d", suffix), "", testutil.Cols{"owner_id": otherUser})
+ project := dbfx.Project(t, fmt.Sprintf("negate project %d", suffix))
+
+ issue := func(title string, cols testutil.Cols) string {
+ return dbfx.Issue(t, fmt.Sprintf("negate %s %d", title, suffix), cols)
+ }
+ // Created by the test user unless stated otherwise.
+ assignedToMe := issue("assigned to me", testutil.Cols{
+ "status": "done", "assignee_type": "member", "assignee_id": testUserID, "project_id": project,
+ })
+ mineByAgent := issue("my agent", testutil.Cols{
+ "assignee_type": "agent", "assignee_id": myAgent, "creator_id": otherUser,
+ })
+ theirAgent := issue("their agent", testutil.Cols{
+ "assignee_type": "agent", "assignee_id": otherAgent, "creator_id": otherUser, "project_id": project,
+ })
+ unassignedByOther := issue("unassigned", testutil.Cols{
+ "status": "in_progress", "creator_id": otherUser,
+ })
+
+ fixture := map[string]struct{}{
+ assignedToMe: {}, mineByAgent: {}, theirAgent: {}, unassignedByOther: {},
+ }
+ rows := func(filters issueTableFiltersRequest) []string {
+ t.Helper()
+ var response issueTableRowsResponse
+ testutil.Call(t, testHandler.ListIssueTableRows,
+ newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Filters: filters,
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "none"},
+ Page: issueTablePageRequest{Limit: 100},
+ }),
+ ).Want(http.StatusOK).JSON(&response)
+ ids := make([]string, 0, len(response.Rows))
+ for _, row := range response.Rows {
+ if _, ok := fixture[row.Issue.ID]; ok {
+ ids = append(ids, row.Issue.ID)
+ }
+ }
+ sort.Strings(ids)
+ return ids
+ }
+ assertRows := func(name string, filters issueTableFiltersRequest, want ...string) {
+ t.Helper()
+ got := rows(filters)
+ sort.Strings(want)
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Fatalf("%s: ids = %v, want %v", name, got, want)
+ }
+ }
+
+ assertRows("status is not done",
+ issueTableFiltersRequest{Statuses: []string{"done"}, Negate: []string{"statuses"}},
+ mineByAgent, theirAgent, unassignedByOther)
+ // The unassigned row has no assignee to compare: "is not" keeps it.
+ assertRows("assignee is not me keeps unassigned rows",
+ issueTableFiltersRequest{
+ Assignees: []issueTableActorRef{{Type: "member", ID: testUserID}},
+ Negate: []string{"assignees"},
+ },
+ mineByAgent, theirAgent, unassignedByOther)
+ assertRows("assignee is not 'no assignee'",
+ issueTableFiltersRequest{IncludeNoAssignee: true, Negate: []string{"assignees"}},
+ assignedToMe, mineByAgent, theirAgent)
+ assertRows("project is not P keeps projectless rows",
+ issueTableFiltersRequest{ProjectIDs: []string{project}, Negate: []string{"project_ids"}},
+ mineByAgent, unassignedByOther)
+ assertRows("negating a dimension without values changes nothing",
+ issueTableFiltersRequest{Negate: []string{"label_ids", "priorities"}},
+ assignedToMe, mineByAgent, theirAgent, unassignedByOther)
+
+ assertRows("relation assigned",
+ issueTableFiltersRequest{Relations: []string{"assigned"}},
+ assignedToMe)
+ assertRows("relation my agents excludes other people's agents",
+ issueTableFiltersRequest{Relations: []string{"my_agents"}},
+ mineByAgent)
+ assertRows("relations OR within the dimension",
+ issueTableFiltersRequest{Relations: []string{"assigned", "my_agents"}},
+ assignedToMe, mineByAgent)
+ assertRows("relation is not created by me",
+ issueTableFiltersRequest{Relations: []string{"created"}, Negate: []string{"relations"}},
+ mineByAgent, theirAgent, unassignedByOther)
+ assertRows("negation is per dimension and ANDs with the rest",
+ issueTableFiltersRequest{
+ Relations: []string{"assigned"},
+ Statuses: []string{"done"},
+ Negate: []string{"relations"},
+ },
+ )
+}
+
+func TestIssueTableRowsRejectsUnknownNegateAndRelation(t *testing.T) {
+ for name, filters := range map[string]issueTableFiltersRequest{
+ "negate": {Negate: []string{"date"}},
+ "relation": {Relations: []string{"involved"}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ testutil.Call(t, testHandler.ListIssueTableRows,
+ newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Filters: filters,
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "none"},
+ Page: issueTablePageRequest{Limit: 50},
+ }),
+ ).Want(http.StatusBadRequest)
+ })
+ }
+}
+
+func TestIssueTableFingerprintCanonicalizesNegateAndRelations(t *testing.T) {
+ spec := func(negate, relations []string) issueTableQuerySpec {
+ return issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Filters: issueTableFiltersRequest{
+ Statuses: []string{"done"},
+ Relations: relations,
+ Negate: negate,
+ },
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ }
+ }
+ a, err := canonicalIssueTableFingerprint(testWorkspaceID, spec(
+ []string{"statuses", "relations"}, []string{"created", "assigned"}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := canonicalIssueTableFingerprint(testWorkspaceID, spec(
+ []string{"relations", "statuses", "statuses"}, []string{"assigned", "created"}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if a != b {
+ t.Fatalf("order and duplicates changed the fingerprint: %s != %s", a, b)
+ }
+ plain, err := canonicalIssueTableFingerprint(testWorkspaceID, spec(nil, []string{"assigned", "created"}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if plain == a {
+ t.Fatal("negation did not change the fingerprint")
+ }
+}
+
+func TestIssueTableQueryWithoutFacetDropsItsNegation(t *testing.T) {
+ query := issueTableQuerySpec{Filters: issueTableFiltersRequest{
+ Statuses: []string{"done"},
+ LabelIDs: []string{"00000000-0000-0000-0000-000000000001"},
+ Negate: []string{"statuses", "label_ids"},
+ }}
+ got := issueTableQueryWithoutFacet(query, issueTableFacetSpec{Kind: "status"})
+ if got.Filters.Statuses != nil || fmt.Sprint(got.Filters.Negate) != "[label_ids]" {
+ t.Fatalf("status facet query = %+v", got.Filters)
+ }
+ if fmt.Sprint(query.Filters.Negate) != "[statuses label_ids]" {
+ t.Fatalf("input negate mutated: %v", query.Filters.Negate)
+ }
+}
diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.go
index 25abc4acd5..3b667ea59e 100644
--- a/server/internal/handler/issue_table_query.go
+++ b/server/internal/handler/issue_table_query.go
@@ -92,6 +92,21 @@ type issueTableFiltersRequest struct {
// (`validProjectStatuses`), independently of ProjectIDs.
ProjectStatuses []string `json:"project_statuses,omitempty"`
LabelIDs []string `json:"label_ids,omitempty"`
+ // Relations narrows by how the requesting user relates to the issue
+ // (`issueTableRelations`), OR within the list.
+ Relations []string `json:"relations,omitempty"`
+ // DueDates narrows by relative due-date bucket (`issueTableDueDates`),
+ // OR within the list, resolved against Today.
+ DueDates []string `json:"due_dates,omitempty"`
+ // Today is the viewer's calendar day (YYYY-MM-DD). Required whenever a
+ // due-date bucket is filtered on, here or in Advanced.
+ Today string `json:"today,omitempty"`
+ // Negate names the dimensions above (by JSON field) whose predicate is
+ // inverted. A listed dimension with no values of its own changes nothing.
+ Negate []string `json:"negate,omitempty"`
+ // Advanced is a condition tree ANDed with every flat filter: the one
+ // place an "or" can span dimensions.
+ Advanced *issueTableFilterNode `json:"advanced,omitempty"`
// Members are raw JSON so operator objects ({op, value}) and plain
// strings both survive the round-trip into parsePropertiesFilterParam.
Properties map[string][]json.RawMessage `json:"properties,omitempty"`
@@ -263,6 +278,10 @@ func canonicalIssueTableFingerprint(workspaceID string, spec issueTableQuerySpec
normalized.Filters.ProjectIDs = sortedUniqueStrings(normalized.Filters.ProjectIDs)
normalized.Filters.ProjectStatuses = sortedUniqueStrings(normalized.Filters.ProjectStatuses)
normalized.Filters.LabelIDs = sortedUniqueStrings(normalized.Filters.LabelIDs)
+ normalized.Filters.Relations = sortedUniqueStrings(normalized.Filters.Relations)
+ normalized.Filters.Negate = sortedUniqueStrings(normalized.Filters.Negate)
+ normalized.Filters.DueDates = sortedUniqueStrings(normalized.Filters.DueDates)
+ normalized.Filters.Advanced = canonicalIssueTableFilterNode(normalized.Filters.Advanced)
normalized.Filters.Assignees = sortedUniqueActors(normalized.Filters.Assignees)
normalized.Filters.WorkingIssueIDs = sortedUniqueStrings(normalized.Filters.WorkingIssueIDs)
normalized.Filters.Creators = sortedUniqueActors(normalized.Filters.Creators)
@@ -393,6 +412,31 @@ func parseIssueTableActor(w http.ResponseWriter, actor issueTableActorRef, field
return issueActorFilter{actorType: actor.Type, actorID: id}, true
}
+// issueTableRelations are the viewer relations `filters.relations` accepts.
+var issueTableRelations = []string{"assigned", "created", "my_agents"}
+
+// issueTableNegatableFilters are the `filters` fields `filters.negate` may name.
+var issueTableNegatableFilters = []string{
+ "statuses", "priorities", "assignees", "creators",
+ "project_ids", "project_statuses", "label_ids", "relations", "due_dates",
+}
+
+// issueTableRelationPredicate matches issues related to the user one way.
+func issueTableRelationPredicate(relation string, userRef string) string {
+ switch relation {
+ case "assigned":
+ return fmt.Sprintf("(i.assignee_type = 'member' AND i.assignee_id = %s::uuid)", userRef)
+ case "created":
+ return fmt.Sprintf("(i.creator_type = 'member' AND i.creator_id = %s::uuid)", userRef)
+ default: // my_agents
+ return fmt.Sprintf(`(i.assignee_type = 'agent' AND i.assignee_id IN (
+ SELECT a.id FROM agent a
+ WHERE a.workspace_id = $1
+ AND a.owner_id = %s::uuid
+ ))`, userRef)
+ }
+}
+
func appendIssueTableInvolvedPredicate(where []string, addArg func(any) string, userID pgtype.UUID) []string {
ref := addArg(userID)
return append(where, fmt.Sprintf(`(
@@ -447,6 +491,25 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
return "$" + strconv.Itoa(len(args))
}
+ negated := make(map[string]bool, len(spec.Filters.Negate))
+ for _, field := range spec.Filters.Negate {
+ if !issueTableContainsString(issueTableNegatableFilters, field) {
+ writeError(w, http.StatusBadRequest, "invalid filters.negate")
+ return issueTableSQL{}, false
+ }
+ negated[field] = true
+ }
+ // "Is not" keeps every row the positive predicate does not accept,
+ // including rows where it is NULL (no assignee, no project): `IS NOT TRUE`
+ // rather than `NOT`, which would drop those too.
+ appendFilter := func(field, predicate string) {
+ if negated[field] {
+ where = append(where, "("+predicate+") IS NOT TRUE")
+ return
+ }
+ where = append(where, predicate)
+ }
+
// Any non-empty status KEY, not just the 7 built-ins. A status filter names
// the exact statuses the user picked, and since MUL-6243 those can be custom
// — rejecting them here 400'd the entire request, so filtering a board by a
@@ -460,7 +523,7 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
}
}
if len(spec.Filters.Statuses) > 0 {
- where = append(where, fmt.Sprintf("i.status = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Statuses))))
+ appendFilter("statuses", fmt.Sprintf("i.status = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Statuses))))
}
for _, priority := range spec.Filters.Priorities {
if !issueTableContainsString(validIssuePriorities, priority) {
@@ -469,7 +532,7 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
}
}
if len(spec.Filters.Priorities) > 0 {
- where = append(where, fmt.Sprintf("i.priority = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Priorities))))
+ appendFilter("priorities", fmt.Sprintf("i.priority = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Priorities))))
}
// Workspace and project scopes share the optional assignee-type
@@ -572,9 +635,9 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
// Omitted assignees means "no assignee filter"; an explicitly
// empty list means "match none", so API callers can preserve an
// intentionally active empty predicate.
- where = append(where, "FALSE")
+ appendFilter("assignees", "FALSE")
} else {
- where = append(where, "("+strings.Join(ors, " OR ")+")")
+ appendFilter("assignees", "("+strings.Join(ors, " OR ")+")")
}
}
@@ -587,7 +650,31 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
}
ors = append(ors, fmt.Sprintf("(i.creator_type = %s::text AND i.creator_id = %s::uuid)", addArg(actor.actorType), addArg(actor.actorID)))
}
- where = append(where, "("+strings.Join(ors, " OR ")+")")
+ appendFilter("creators", "("+strings.Join(ors, " OR ")+")")
+ }
+
+ for _, relation := range spec.Filters.Relations {
+ if !issueTableContainsString(issueTableRelations, relation) {
+ writeError(w, http.StatusBadRequest, "invalid filters.relations")
+ return issueTableSQL{}, false
+ }
+ }
+ if relations := sortedUniqueStrings(spec.Filters.Relations); len(relations) > 0 {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ userUUID, err := util.ParseUUID(userID)
+ if err != nil {
+ writeError(w, http.StatusUnauthorized, "user not authenticated")
+ return issueTableSQL{}, false
+ }
+ userRef := addArg(userUUID)
+ ors := make([]string, 0, len(relations))
+ for _, relation := range relations {
+ ors = append(ors, issueTableRelationPredicate(relation, userRef))
+ }
+ appendFilter("relations", "("+strings.Join(ors, " OR ")+")")
}
projectIDs, ok := parseIssueTableUUIDList(w, spec.Filters.ProjectIDs, "filters.project_ids")
@@ -602,7 +689,7 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
if spec.Filters.IncludeNoProject {
ors = append(ors, "i.project_id IS NULL")
}
- where = append(where, "("+strings.Join(ors, " OR ")+")")
+ appendFilter("project_ids", "("+strings.Join(ors, " OR ")+")")
}
if len(spec.Filters.ProjectStatuses) > 0 {
@@ -617,7 +704,7 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
// foreign keys by design, so a stale or corrupt `issue.project_id` can
// name a project in another workspace. Without the bound, that
// tenant's project status would decide this row's membership.
- where = append(where, fmt.Sprintf(
+ appendFilter("project_statuses", fmt.Sprintf(
"EXISTS (SELECT 1 FROM project p WHERE p.id = i.project_id AND p.workspace_id = i.workspace_id AND p.status = ANY(%s::text[]))",
addArg(spec.Filters.ProjectStatuses),
))
@@ -628,7 +715,71 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
return issueTableSQL{}, false
}
if len(labelIDs) > 0 {
- where = append(where, fmt.Sprintf("EXISTS (SELECT 1 FROM issue_to_label itl WHERE itl.issue_id = i.id AND itl.label_id = ANY(%s::uuid[]))", addArg(labelIDs)))
+ appendFilter("label_ids", fmt.Sprintf("EXISTS (SELECT 1 FROM issue_to_label itl WHERE itl.issue_id = i.id AND itl.label_id = ANY(%s::uuid[]))", addArg(labelIDs)))
+ }
+
+ var (
+ today time.Time
+ todayResolved bool
+ )
+ resolveToday := func() (time.Time, error) {
+ if !todayResolved {
+ parsed, ok := parseIssueTableToday(spec.Filters.Today)
+ if !ok {
+ return time.Time{}, invalidIssueTableFilter("filters.today is required for due-date filters")
+ }
+ today, todayResolved = parsed, true
+ }
+ return today, nil
+ }
+ writeFilterError := func(err error) {
+ var filterErr issueTableFilterError
+ if errors.As(err, &filterErr) {
+ writeError(w, filterErr.status, filterErr.message)
+ return
+ }
+ writeError(w, http.StatusBadRequest, err.Error())
+ }
+
+ for _, bucket := range spec.Filters.DueDates {
+ if !issueTableContainsString(issueTableDueDates, bucket) {
+ writeError(w, http.StatusBadRequest, "invalid filters.due_dates")
+ return issueTableSQL{}, false
+ }
+ }
+ if buckets := sortedUniqueStrings(spec.Filters.DueDates); len(buckets) > 0 {
+ day, err := resolveToday()
+ if err != nil {
+ writeFilterError(err)
+ return issueTableSQL{}, false
+ }
+ ors := make([]string, 0, len(buckets))
+ for _, bucket := range buckets {
+ ors = append(ors, issueTableDueDatePredicate(bucket, day, addArg))
+ }
+ appendFilter("due_dates", "("+strings.Join(ors, " OR ")+")")
+ }
+
+ if spec.Filters.Advanced != nil {
+ compiler := issueTableFilterCompiler{
+ addArg: addArg,
+ today: resolveToday,
+ userRef: func() (string, error) {
+ userUUID, err := util.ParseUUID(requestUserID(r))
+ if err != nil {
+ return "", issueTableFilterError{status: http.StatusUnauthorized, message: "user not authenticated"}
+ }
+ return addArg(userUUID), nil
+ },
+ }
+ predicate, err := compiler.compile(*spec.Filters.Advanced)
+ if err != nil {
+ writeFilterError(err)
+ return issueTableSQL{}, false
+ }
+ if predicate != "" {
+ where = append(where, predicate)
+ }
}
if len(spec.Filters.Properties) > 0 {
diff --git a/server/internal/handler/issue_view.go b/server/internal/handler/issue_view.go
index d6b79fdd5f..6fd00d869b 100644
--- a/server/internal/handler/issue_view.go
+++ b/server/internal/handler/issue_view.go
@@ -238,6 +238,22 @@ func (h *Handler) ListIssueViews(w http.ResponseWriter, r *http.Request) {
}
scopeType := r.URL.Query().Get("scope_type")
+ if scopeType == "all" {
+ views, err := h.Queries.ListAllIssueViewsForUser(r.Context(), db.ListAllIssueViewsForUserParams{
+ WorkspaceID: wsUUID,
+ OwnerID: parseUUID(userID),
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list views")
+ return
+ }
+ resp := make([]IssueViewResponse, len(views))
+ for i, v := range views {
+ resp[i] = issueViewToResponse(v)
+ }
+ writeJSON(w, http.StatusOK, resp)
+ return
+ }
if !contains(validIssueViewScopeTypes, scopeType) {
writeError(w, http.StatusBadRequest, "invalid scope_type")
return
diff --git a/server/internal/handler/issue_view_preference.go b/server/internal/handler/issue_view_preference.go
index be99cd00b0..65348a6bb6 100644
--- a/server/internal/handler/issue_view_preference.go
+++ b/server/internal/handler/issue_view_preference.go
@@ -17,7 +17,8 @@ import (
// resolvePreferenceScope validates scope params and backfills scope_id so
// the composite key never carries NULL: workspace scope uses the workspace
-// id, my scope the user id, project scope the project id (validated).
+// id, my and sidebar scopes the user id, project scope the project id
+// (validated).
func (h *Handler) resolvePreferenceScope(
w http.ResponseWriter, r *http.Request,
wsUUID pgtype.UUID, userID string, scopeType, rawScopeID string,
@@ -25,7 +26,7 @@ func (h *Handler) resolvePreferenceScope(
switch scopeType {
case "workspace":
return wsUUID, true
- case "my":
+ case "my", "sidebar":
return parseUUID(userID), true
case "project":
if rawScopeID == "" {
diff --git a/server/internal/handler/issue_view_preference_test.go b/server/internal/handler/issue_view_preference_test.go
index 51a3d58d20..e9e6d07f6b 100644
--- a/server/internal/handler/issue_view_preference_test.go
+++ b/server/internal/handler/issue_view_preference_test.go
@@ -96,3 +96,41 @@ func TestIssueViewPreferenceIsPerUser(t *testing.T) {
t.Fatalf("another member must not inherit my prefs, got %s", got.Prefs)
}
}
+
+func TestSidebarIssueViewPreferenceIsSeparateFromWorkspace(t *testing.T) {
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM issue_view_preference WHERE workspace_id = $1`, testWorkspaceID)
+ })
+
+ put := func(scopeType string, prefs map[string]any) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.PutIssueViewPreference(w, newRequest("PUT", "/api/issue-view-preferences", map[string]any{
+ "scope_type": scopeType,
+ "prefs": prefs,
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("put %s: expected 200, got %d: %s", scopeType, w.Code, w.Body.String())
+ }
+ }
+ put("sidebar", map[string]any{"order": []string{"builtin:my_issues", "view:abc"}})
+ // An older client writing the workspace doc wholesale must not touch it.
+ put("workspace", map[string]any{"hidden": []string{}})
+
+ w := httptest.NewRecorder()
+ testHandler.GetIssueViewPreference(w, newRequest("GET", "/api/issue-view-preferences?scope_type=sidebar", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("get sidebar: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var got IssueViewPreferenceResponse
+ json.NewDecoder(w.Body).Decode(&got)
+ var round map[string]any
+ json.Unmarshal(got.Prefs, &round)
+ if order, _ := round["order"].([]any); len(order) != 2 || order[1] != "view:abc" {
+ t.Fatalf("sidebar order lost: %s", got.Prefs)
+ }
+ if got.ScopeID == nil || *got.ScopeID != testUserID {
+ t.Fatalf("sidebar scope must be keyed by the user, got %v", got.ScopeID)
+ }
+}
diff --git a/server/internal/handler/issue_view_test.go b/server/internal/handler/issue_view_test.go
index 62aeac376a..57c4646af3 100644
--- a/server/internal/handler/issue_view_test.go
+++ b/server/internal/handler/issue_view_test.go
@@ -119,6 +119,59 @@ func TestIssueViewPrivateInvisibleToOthers(t *testing.T) {
}
}
+func TestListAllIssueViewsAcrossScopes(t *testing.T) {
+ shared, code, body := createIssueViewForTest(t, map[string]any{
+ "name": "Shared board",
+ "scope_type": "workspace",
+ "visibility": "workspace",
+ "query": map[string]any{},
+ })
+ if code != http.StatusCreated {
+ t.Fatalf("create shared: %d %s", code, body)
+ }
+ mine, code, body := createIssueViewForTest(t, map[string]any{
+ "name": "Created by me",
+ "scope_type": "my",
+ "scope_variant": "created",
+ "query": map[string]any{},
+ })
+ if code != http.StatusCreated {
+ t.Fatalf("create my: %d %s", code, body)
+ }
+
+ listAll := func(userID string) map[string]bool {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("GET", "/api/issue-views?scope_type=all", nil)
+ if userID != "" {
+ req.Header.Set("X-User-ID", userID)
+ }
+ testHandler.ListIssueViews(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("list all: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var views []IssueViewResponse
+ json.NewDecoder(w.Body).Decode(&views)
+ ids := map[string]bool{}
+ for _, v := range views {
+ ids[v.ID] = true
+ }
+ return ids
+ }
+
+ own := listAll("")
+ if !own[shared.ID] || !own[mine.ID] {
+ t.Fatalf("owner's all-list must include every scope, got %v", own)
+ }
+ other := listAll(createSecondWorkspaceMember(t))
+ if !other[shared.ID] {
+ t.Fatalf("shared view missing from another member's all-list")
+ }
+ if other[mine.ID] {
+ t.Fatalf("private view leaked into another member's all-list")
+ }
+}
+
func TestUpdateIssueViewRevisionConflict(t *testing.T) {
view, code, body := createIssueViewForTest(t, map[string]any{
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
index 3b89204d8e..6f3a563a42 100644
--- a/server/internal/handler/property.go
+++ b/server/internal/handler/property.go
@@ -991,33 +991,41 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
writeError(w, http.StatusBadRequest, "properties filter must be a JSON object of {definitionId: [values]}")
return nil, false
}
- if len(parsed) > maxPropertiesFilterDefinitions {
- writeError(w, http.StatusBadRequest, fmt.Sprintf("properties filter cannot cover more than %d definitions", maxPropertiesFilterDefinitions))
+ groups, err := compilePropertiesFilter(parsed)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
return nil, false
}
+ return groups, true
+}
+
+// compilePropertiesFilter is parsePropertiesFilterParam after decoding; the
+// error is the 400 message. Returns nil when nothing constrains.
+func compilePropertiesFilter(parsed map[string][]json.RawMessage) ([][]json.RawMessage, error) {
+ errInvalid := errors.New("properties filter is invalid")
+ if len(parsed) > maxPropertiesFilterDefinitions {
+ return nil, fmt.Errorf("properties filter cannot cover more than %d definitions", maxPropertiesFilterDefinitions)
+ }
groups := make([][]json.RawMessage, 0, len(parsed))
totalAlternatives := 0
for definitionID, values := range parsed {
if _, err := uuid.Parse(definitionID); err != nil {
- writeError(w, http.StatusBadRequest, fmt.Sprintf("properties filter key %q is not a definition id", definitionID))
- return nil, false
+ return nil, fmt.Errorf("properties filter key %q is not a definition id", definitionID)
}
if len(values) == 0 {
continue
}
if len(values) > maxPropertiesFilterValues {
- writeError(w, http.StatusBadRequest, fmt.Sprintf("properties filter for %s cannot list more than %d values", definitionID, maxPropertiesFilterValues))
- return nil, false
+ return nil, fmt.Errorf("properties filter for %s cannot list more than %d values", definitionID, maxPropertiesFilterValues)
}
alternatives := make([]json.RawMessage, 0, len(values)*3)
- appendAlt := func(v any) bool {
+ appendAlt := func(v any) error {
buf, err := json.Marshal(map[string]any{definitionID: v})
if err != nil {
- writeError(w, http.StatusBadRequest, "properties filter is invalid")
- return false
+ return errInvalid
}
alternatives = append(alternatives, buf)
- return true
+ return nil
}
hasNoValue := false
for _, rawValue := range values {
@@ -1026,8 +1034,7 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
if err := json.Unmarshal(rawValue, &stringValue); err == nil {
value := stringValue
if value == "" {
- writeError(w, http.StatusBadRequest, "properties filter values cannot be empty")
- return nil, false
+ return nil, errors.New("properties filter values cannot be empty")
}
if value == noPropertyValue {
if hasNoValue {
@@ -1035,19 +1042,22 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
}
marker, err := json.Marshal(map[string]string{noPropertyValue: definitionID})
if err != nil {
- writeError(w, http.StatusBadRequest, "properties filter is invalid")
- return nil, false
+ return nil, errInvalid
}
alternatives = append(alternatives, marker)
hasNoValue = true
continue
}
- if !appendAlt(value) || !appendAlt([]string{value}) { // select string / multi_select element
- return nil, false
+ // select string / multi_select element
+ if err := appendAlt(value); err != nil {
+ return nil, err
+ }
+ if err := appendAlt([]string{value}); err != nil {
+ return nil, err
}
if value == "true" || value == "false" {
- if !appendAlt(value == "true") { // checkbox boolean
- return nil, false
+ if err := appendAlt(value == "true"); err != nil { // checkbox boolean
+ return nil, err
}
}
if num, err := strconv.ParseFloat(value, 64); err == nil &&
@@ -1056,8 +1066,8 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
// stored jsonb number, not the string form appended above. NaN /
// Infinity are skipped: they are not representable as JSON, so
// marshaling them would 400 the whole filter.
- if !appendAlt(num) {
- return nil, false
+ if err := appendAlt(num); err != nil {
+ return nil, err
}
}
continue
@@ -1065,18 +1075,15 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
// An object member is a scalar operator.
var op propertyFilterOperator
if err := json.Unmarshal(rawValue, &op); err != nil || op.Op == "" {
- writeError(w, http.StatusBadRequest, "properties filter values must be strings or {op, value} objects")
- return nil, false
+ return nil, errors.New("properties filter values must be strings or {op, value} objects")
}
pattern, err := validatePropertyFilterOperator(definitionID, op)
if err != nil {
- writeError(w, http.StatusBadRequest, err.Error())
- return nil, false
+ return nil, err
}
- buf, marshalErr := json.Marshal(pattern)
- if marshalErr != nil {
- writeError(w, http.StatusBadRequest, "properties filter is invalid")
- return nil, false
+ buf, err := json.Marshal(pattern)
+ if err != nil {
+ return nil, errInvalid
}
alternatives = append(alternatives, buf)
}
@@ -1084,15 +1091,14 @@ func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.Raw
groups = append(groups, alternatives)
}
if len(groups) == 0 {
- return nil, true
+ return nil, nil
}
// Bound the OR fan-out: each alternative becomes one bind parameter in
// the SQL below, and a runaway filter would bloat the statement.
if totalAlternatives > 256 {
- writeError(w, http.StatusBadRequest, "properties filter is too large")
- return nil, false
+ return nil, errors.New("properties filter is too large")
}
- return groups, true
+ return groups, nil
}
// parseNoPropertyValuePattern reports whether an alternative is the synthesized
diff --git a/server/internal/handler/reserved_slugs.json b/server/internal/handler/reserved_slugs.json
index ef00466ac8..2f44f97f86 100644
--- a/server/internal/handler/reserved_slugs.json
+++ b/server/internal/handler/reserved_slugs.json
@@ -76,6 +76,7 @@
"squads",
"inbox",
"my-issues",
+ "views",
"usage",
"runtimes",
"skills",
diff --git a/server/migrations/595_issue_view_preference_sidebar.down.sql b/server/migrations/595_issue_view_preference_sidebar.down.sql
new file mode 100644
index 0000000000..6db410e09c
--- /dev/null
+++ b/server/migrations/595_issue_view_preference_sidebar.down.sql
@@ -0,0 +1,4 @@
+DELETE FROM issue_view_preference WHERE scope_type = 'sidebar';
+ALTER TABLE issue_view_preference DROP CONSTRAINT issue_view_preference_scope_type_check;
+ALTER TABLE issue_view_preference ADD CONSTRAINT issue_view_preference_scope_type_check
+ CHECK (scope_type IN ('workspace', 'my', 'project'));
diff --git a/server/migrations/595_issue_view_preference_sidebar.up.sql b/server/migrations/595_issue_view_preference_sidebar.up.sql
new file mode 100644
index 0000000000..8515d69405
--- /dev/null
+++ b/server/migrations/595_issue_view_preference_sidebar.up.sql
@@ -0,0 +1,8 @@
+-- The sidebar's starred views become one more per-user preference
+-- container: `prefs.order` lists the starred items ("builtin:<key>" /
+-- "view:<uuid>") in sidebar order. scope_id is backfilled with the user id,
+-- like the my scope. A separate scope keeps older clients, which write the
+-- workspace doc wholesale, from ever clobbering it.
+ALTER TABLE issue_view_preference DROP CONSTRAINT issue_view_preference_scope_type_check;
+ALTER TABLE issue_view_preference ADD CONSTRAINT issue_view_preference_scope_type_check
+ CHECK (scope_type IN ('workspace', 'my', 'project', 'sidebar'));
diff --git a/server/pkg/db/generated/issue_view.sql.go b/server/pkg/db/generated/issue_view.sql.go
index 88679cd124..ed8060a92b 100644
--- a/server/pkg/db/generated/issue_view.sql.go
+++ b/server/pkg/db/generated/issue_view.sql.go
@@ -213,6 +213,56 @@ func (q *Queries) GetIssueView(ctx context.Context, arg GetIssueViewParams) (Iss
return i, err
}
+const listAllIssueViewsForUser = `-- name: ListAllIssueViewsForUser :many
+SELECT id, workspace_id, owner_id, name, scope_type, scope_id, scope_variant, visibility, definition_version, query, display, revision, created_at, updated_at FROM issue_view
+WHERE workspace_id = $1
+ AND (owner_id = $2 OR visibility = 'workspace')
+ORDER BY created_at ASC
+LIMIT 500
+`
+
+type ListAllIssueViewsForUserParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+}
+
+// Every view the caller can open, across all scopes: the All views
+// directory and the sidebar's starred list resolve against this.
+func (q *Queries) ListAllIssueViewsForUser(ctx context.Context, arg ListAllIssueViewsForUserParams) ([]IssueView, error) {
+ rows, err := q.db.Query(ctx, listAllIssueViewsForUser, arg.WorkspaceID, arg.OwnerID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueView{}
+ for rows.Next() {
+ var i IssueView
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.OwnerID,
+ &i.Name,
+ &i.ScopeType,
+ &i.ScopeID,
+ &i.ScopeVariant,
+ &i.Visibility,
+ &i.DefinitionVersion,
+ &i.Query,
+ &i.Display,
+ &i.Revision,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listIssueViewsForUser = `-- name: ListIssueViewsForUser :many
SELECT id, workspace_id, owner_id, name, scope_type, scope_id, scope_variant, visibility, definition_version, query, display, revision, created_at, updated_at FROM issue_view
WHERE workspace_id = $1
diff --git a/server/pkg/db/queries/issue_view.sql b/server/pkg/db/queries/issue_view.sql
index 7ca2b41f17..b0717aee34 100644
--- a/server/pkg/db/queries/issue_view.sql
+++ b/server/pkg/db/queries/issue_view.sql
@@ -21,6 +21,15 @@ ORDER BY created_at ASC
-- data far below it; the LIMIT is the abuse backstop.
LIMIT 200;
+-- name: ListAllIssueViewsForUser :many
+-- Every view the caller can open, across all scopes: the All views
+-- directory and the sidebar's starred list resolve against this.
+SELECT * FROM issue_view
+WHERE workspace_id = $1
+ AND (owner_id = $2 OR visibility = 'workspace')
+ORDER BY created_at ASC
+LIMIT 500;
+
-- name: CountIssueViewsByOwner :one
SELECT COUNT(*) FROM issue_view
WHERE workspace_id = $1 AND owner_id = $2;