Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(ui): add global command menu (#7877)
Andrew Huang2965244f09c2
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.tsindex 77c89dbca5..69bd6117bb 100644--- a/backend/src/server/routes/v1/project-router.ts+++ b/backend/src/server/routes/v1/project-router.ts@@ -78,6 +78,31 @@ const projectWithEnv = SanitizedProjectSchema.merge();export const registerProjectRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/accessible-with-sub-orgs",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: true,+ operationId: "listAccessibleProjectsWithSubOrgs",+ response: {+ 200: z.object({+ projects: SanitizedProjectSchema.pick({ id: true, orgId: true, name: true, slug: true, type: true }).array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const projects = await server.services.project.getAccessibleProjectsWithSubOrgs({+ actorId: req.permission.id,+ actorOrgId: req.permission.orgId+ });+ return { projects };+ }+ });+server.route({method: "GET",url: "/me/project-access-requests",diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.tsindex afa66fb53d..ce614ae995 100644--- a/backend/src/services/project/project-dal.ts+++ b/backend/src/services/project/project-dal.ts@@ -308,7 +308,7 @@ export const projectDALFactory = (db: TDbClient) => {}};- const findUserProjects = async (userId: string, orgId: string, projectType?: ProjectType) => {+ const findUserProjects = async (userId: string, orgId: string | string[], projectType?: ProjectType) => {try {const userGroupSubquery = db.replicaNode()(TableName.Groups)@@ -320,7 +320,7 @@ export const projectDALFactory = (db: TDbClient) => {.replicaNode()(TableName.Membership).where(`${TableName.Membership}.scope`, AccessScope.Project).join(TableName.Project, `${TableName.Membership}.scopeProjectId`, `${TableName.Project}.id`)- .where(`${TableName.Project}.orgId`, orgId)+ .whereIn(`${TableName.Project}.orgId`, Array.isArray(orgId) ? orgId : [orgId]).whereNull(`${TableName.Project}.deleteAfter`).andWhere((qb) => {void qbdiff --git a/backend/src/services/project/project-service.test.ts b/backend/src/services/project/project-service.test.tsnew file mode 100644index 0000000000..eeaea0b454--- /dev/null+++ b/backend/src/services/project/project-service.test.ts@@ -0,0 +1,132 @@+import { describe, expect, test, vi } from "vitest";++import { OrgMembershipStatus } from "@app/db/schemas";+import { ActorType } from "@app/services/auth/auth-type";++import { projectServiceFactory } from "./project-service";++const setup = () => {+ const memberships = new Map<+ string,+ { isActive: boolean; status: OrgMembershipStatus | null; actorGroupId: string | null }+ >([["accessible-sub-org", { isActive: true, status: OrgMembershipStatus.Accepted, actorGroupId: null }]]);+ const orgDAL = {+ listOrganizationsWithSubOrgs: vi.fn().mockResolvedValue([+ { id: "root", subOrganizations: [{ id: "accessible-sub-org" }] },+ { id: "other-root", subOrganizations: [{ id: "other-sub-org" }] }+ ]),+ findEffectiveOrgMembership: vi.fn(async ({ orgId, status }: { orgId: string; status: OrgMembershipStatus }) => {+ const membership = memberships.get(orgId);+ return membership && (membership.status === status || membership.status === null) ? membership : null;+ })+ };+ const projectDAL = { findUserProjects: vi.fn().mockResolvedValue([]) };+ const service = projectServiceFactory({+ orgDAL,+ projectDAL+ } as unknown as Parameters<typeof projectServiceFactory>[0]);++ return { service, orgDAL, projectDAL, memberships };+};++describe("project navigation across sub-organizations", () => {+ test("limits project membership lookup to the current root and its accessible sub-organizations", async () => {+ const { service, orgDAL, projectDAL } = setup();++ await service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" });++ expect(orgDAL.listOrganizationsWithSubOrgs).toHaveBeenCalledWith({ actorId: "user" });+ expect(orgDAL.findEffectiveOrgMembership).toHaveBeenCalledExactlyOnceWith({+ actorType: ActorType.USER,+ actorId: "user",+ orgId: "accessible-sub-org",+ status: OrgMembershipStatus.Accepted+ });+ expect(projectDAL.findUserProjects).toHaveBeenCalledExactlyOnceWith("user", ["root", "accessible-sub-org"]);+ });++ test.each([+ { label: "inactive direct", isActive: false, status: OrgMembershipStatus.Accepted, actorGroupId: null },+ { label: "inactive group", isActive: false, status: OrgMembershipStatus.Accepted, actorGroupId: "group" },+ { label: "invited", isActive: true, status: OrgMembershipStatus.Invited, actorGroupId: null }+ ])("excludes projects with $label sub-organization membership", async ({ isActive, status, actorGroupId }) => {+ const { service, projectDAL, memberships } = setup();+ memberships.set("accessible-sub-org", { isActive, status, actorGroupId });+ const retainedProject = {+ id: "project",+ orgId: "accessible-sub-org",+ name: "Platform",+ slug: "platform",+ type: "secret-manager"+ };+ projectDAL.findUserProjects.mockImplementation(async (_userId: string, orgIds: string[]) =>+ orgIds.includes(retainedProject.orgId) ? [retainedProject] : []+ );++ await expect(service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" })).resolves.toEqual(+ []+ );+ expect(projectDAL.findUserProjects).toHaveBeenCalledExactlyOnceWith("user", ["root"]);+ });++ test("excludes a sub-organization whose effective membership no longer exists", async () => {+ const { service, projectDAL, memberships } = setup();+ memberships.delete("accessible-sub-org");++ await service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" });++ expect(projectDAL.findUserProjects).toHaveBeenCalledExactlyOnceWith("user", ["root"]);+ });++ test.each([OrgMembershipStatus.Accepted, null])("retains active group membership with status %s", async (status) => {+ const { service, projectDAL, memberships } = setup();+ memberships.set("accessible-sub-org", { isActive: true, status, actorGroupId: "group" });++ await service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" });++ expect(projectDAL.findUserProjects).toHaveBeenCalledExactlyOnceWith("user", ["root", "accessible-sub-org"]);+ });++ test("does not query projects when membership validation fails", async () => {+ const { service, orgDAL, projectDAL } = setup();+ orgDAL.findEffectiveOrgMembership.mockRejectedValue(new Error("Membership lookup failed"));++ await expect(service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" })).rejects.toThrow(+ "Membership lookup failed"+ );+ expect(projectDAL.findUserProjects).not.toHaveBeenCalled();+ });++ test("does not expand a sub-organization session into its parent or siblings", async () => {+ const { service, projectDAL } = setup();++ await service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "accessible-sub-org" });++ expect(projectDAL.findUserProjects).toHaveBeenCalledExactlyOnceWith("user", ["accessible-sub-org"]);+ });++ test("keeps the existing organization scope when no accessible root matches", async () => {+ const { service, orgDAL, projectDAL } = setup();+ orgDAL.listOrganizationsWithSubOrgs.mockResolvedValue([]);++ await service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" });++ expect(projectDAL.findUserProjects).toHaveBeenCalledExactlyOnceWith("user", ["root"]);+ });++ test("returns only project navigation metadata", async () => {+ const { service, projectDAL } = setup();+ const project = {+ id: "project",+ orgId: "accessible-sub-org",+ name: "Platform",+ slug: "platform",+ type: "secret-manager"+ };+ projectDAL.findUserProjects.mockResolvedValue([{ ...project, environments: [{ name: "Production" }], roles: [] }]);++ await expect(service.getAccessibleProjectsWithSubOrgs({ actorId: "user", actorOrgId: "root" })).resolves.toEqual([+ project+ ]);+ });+});diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.tsindex b982b52167..3350df746c 100644--- a/backend/src/services/project/project-service.ts+++ b/backend/src/services/project/project-service.ts@@ -7,6 +7,7 @@ import {ActionProjectType,OrganizationActionScope,OrgMembershipRole,+ OrgMembershipStatus,ProjectMembershipRole,ProjectType,ProjectVersion,@@ -176,7 +177,7 @@ type TProjectServiceFactoryDep = {permissionService: TPermissionServiceFactory;licenseService: Pick<TLicenseServiceFactory, "getPlan" | "invalidateGetPlan">;smtpService: Pick<TSmtpService, "sendMail">;- orgDAL: Pick<TOrgDALFactory, "findOne" | "findEffectiveOrgMembership">;+ orgDAL: Pick<TOrgDALFactory, "findOne" | "findEffectiveOrgMembership" | "listOrganizationsWithSubOrgs">;keyStore: Pick<TKeyStoreFactory, "deleteItem" | "acquireLock" | "getItem" | "setItemWithExpiry" | "ttl">;roleDAL: Pick<TRoleDALFactory, "find" | "insertMany" | "delete">;kmsService: Pick<@@ -902,6 +903,28 @@ export const projectServiceFactory = ({return workspaces;};+ const getAccessibleProjectsWithSubOrgs = async ({+ actorId,+ actorOrgId+ }: Pick<TListProjectsDTO, "actorId" | "actorOrgId">) => {+ const organizations = await orgDAL.listOrganizationsWithSubOrgs({ actorId });+ const currentOrganization = organizations.find((organization) => organization.id === actorOrgId);+ const organizationIds = [actorOrgId];+ for (const organization of currentOrganization?.subOrganizations ?? []) {+ // eslint-disable-next-line no-await-in-loop -- Keep membership reads bounded to one database connection.+ const membership = await orgDAL.findEffectiveOrgMembership({+ actorType: ActorType.USER,+ actorId,+ orgId: organization.id,+ status: OrgMembershipStatus.Accepted+ });+ if (membership?.isActive) organizationIds.push(organization.id);+ }++ const projects = await projectDAL.findUserProjects(actorId, organizationIds);+ return projects.map(({ id, orgId, name, slug, type }) => ({ id, orgId, name, slug, type }));+ };+const getAProject = async ({ actorId, actorOrgId, actorAuthMethod, filter, actor }: TGetProjectDTO) => {const project = await projectDAL.findProjectByFilter(filter);@@ -2361,6 +2384,7 @@ export const projectServiceFactory = ({createProject,deleteProject,getProjects,+ getAccessibleProjectsWithSubOrgs,updateProject,getProjectUpgradeStatus,getAProject,diff --git a/frontend/src/components/v3/generic/AlertDialog/AlertDialog.tsx b/frontend/src/components/v3/generic/AlertDialog/AlertDialog.tsxindex 5981132736..27638741bb 100644--- a/frontend/src/components/v3/generic/AlertDialog/AlertDialog.tsx+++ b/frontend/src/components/v3/generic/AlertDialog/AlertDialog.tsx@@ -76,7 +76,7 @@ function AlertDialogOverlay({<AlertDialogPrimitive.Overlaydata-slot="alert-dialog-overlay"className={cn(- "fixed inset-0 z-50 bg-black/10 duration-100 data-closed:animate-out data-closed:fade-out-0 data-open:animate-in data-open:fade-in-0 supports-backdrop-filter:backdrop-blur-xs",+ "fixed inset-0 z-50 bg-black/10 data-closed:animate-out data-closed:duration-100 data-closed:ease-in data-closed:fade-out-0 data-open:animate-in data-open:duration-150 data-open:ease-in data-open:fade-in-0 supports-backdrop-filter:backdrop-blur-xs",className)}{...props}@@ -98,7 +98,7 @@ function AlertDialogContent({data-slot="alert-dialog-content"data-size={size}className={cn(- "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg bg-popover p-4 text-foreground ring-1 ring-foreground/10 duration-100 outline-none data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-[size=sm]:max-w-sm",+ "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg bg-popover p-4 text-foreground ring-1 ring-foreground/10 outline-none data-closed:animate-out data-closed:duration-100 data-closed:ease-in data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:duration-150 data-open:ease-in data-open:fade-in-0 data-open:zoom-in-95 data-[size=sm]:max-w-sm",DIALOG_CONTENT_WIDTH_CLASSNAME,className)}diff --git a/frontend/src/components/v3/generic/Command/Command.stories.tsx b/frontend/src/components/v3/generic/Command/Command.stories.tsxindex e2ef156741..0f4ea305ee 100644--- a/frontend/src/components/v3/generic/Command/Command.stories.tsx+++ b/frontend/src/components/v3/generic/Command/Command.stories.tsx@@ -1,6 +1,7 @@-import { useState } from "react";+import { useEffect, useState } from "react";import type { Meta, StoryObj } from "@storybook/react-vite";import {+ BoxesIcon,BuildingIcon,CalendarIcon,CheckIcon,@@ -11,7 +12,9 @@ import {UserIcon} from "lucide-react";+import { Badge } from "../Badge";import { Button } from "../Button";+import { Input } from "../Input";import { Popover, PopoverContent, PopoverTrigger } from "../Popover";import {Command,@@ -24,6 +27,11 @@ import {CommandSeparator,CommandShortcut} from "./Command";+import {+ GlobalCommandMenu,+ type GlobalCommandMenuGroup,+ type GlobalCommandMenuSearchStatus+} from "./GlobalCommandMenu";/*** Command renders a searchable command palette — an input paired with a scrollable@@ -221,6 +229,209 @@ export const AsDialog: Story = {render: () => <AsDialogStory />};+const GlobalNavigationStory = () => {+ const [open, setOpen] = useState(false);+ const [destination, setDestination] = useState("No destination selected");+ const groups: GlobalCommandMenuGroup[] = [+ {+ heading: "Navigation",+ items: [+ {+ id: "navigation-calendar",+ label: "Calendar",+ breadcrumb: "Acme / Operations",+ icon: CalendarIcon,+ keywords: ["schedule", "events"],+ onSelect: () => setDestination("Calendar selected")+ },+ {+ id: "navigation-files",+ label: "Files",+ breadcrumb: "Acme / Documents",+ icon: FileIcon,+ keywords: ["documents"],+ onSelect: () => setDestination("Files selected")+ },+ {+ id: "navigation-sub-org-files",+ label: "Files",+ breadcrumb: "Acme / Engineering / Documents",+ icon: FileIcon,+ badge: (+ <Badge variant="sub-org">+ <BoxesIcon aria-hidden="true" />+ Sub-organization+ </Badge>+ ),+ keywords: ["documents", "engineering"],+ onSelect: () => setDestination("Engineering files selected")+ }+ ]+ },+ {+ heading: "Account",+ items: [+ {+ id: "account-settings",+ label: "Personal Settings",+ breadcrumb: "Account / General",+ icon: SettingsIcon,+ keywords: ["profile", "preferences"],+ onSelect: () => setDestination("Personal Settings selected")+ }+ ]+ }+ ];++ return (+ <div className="flex w-full max-w-96 flex-col gap-3">+ <div className="flex flex-col gap-1.5 text-sm">+ <span>Example field</span>+ <Input+ id="global-command-example-field"+ aria-label="Example field"+ placeholder="The shortcut works while typing here"+ />+ </div>+ <Button variant="outline" onClick={() => setOpen(true)}>+ Search Navigation+ <CommandShortcut>⌘/Ctrl K</CommandShortcut>+ </Button>+ <p role="status" className="text-sm text-accent">+ {destination}+ </p>+ <GlobalCommandMenu+ groups={[+ ...groups,+ {+ heading: "Explore",+ items: [+ {+ id: "search-files",+ label: "Search Files…",+ breadcrumb: "Global / Files",+ icon: FolderIcon,+ children: [{ heading: "Files", items: groups[0].items.slice(1) }],+ drilldownPlaceholder: "Search files..."+ }+ ]+ }+ ]}+ searchGroups={groups}+ open={open}+ onOpenChange={setOpen}+ />+ </div>+ );+};++export const GlobalNavigation: Story = {+ name: "Example: Global Navigation",+ parameters: {+ docs: {+ description: {+ story:+ 'Use `GlobalCommandMenu` for a root-mounted, context-aware navigation palette. Every result has a primary label and contextual breadcrumb. Empty input shows small browse groups, typing searches `searchGroups`, and items with `children` open a drill-down view. It opens with Command+K on Apple devices and Control+K elsewhere, including from ordinary inputs. Rich editors can retain the shortcut with `data-command-menu-shortcut="ignore"`.'+ }+ }+ },+ render: () => <GlobalNavigationStory />+};++const AsyncGlobalNavigationStory = () => {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const [resolvedQuery, setResolvedQuery] = useState("");+ const [searchStatus, setSearchStatus] = useState<GlobalCommandMenuSearchStatus>({+ state: "idle"+ });++ useEffect(() => {+ const normalizedQuery = query.trim().toLowerCase();+ setResolvedQuery("");++ if (normalizedQuery.length < 2) {+ setSearchStatus({ state: "idle" });+ return undefined;+ }++ setSearchStatus({ state: "loading", message: "Searching project resources…" });+ const timeout = window.setTimeout(() => {+ if (normalizedQuery === "error") {+ setSearchStatus({ state: "error", message: "Could not search project resources." });+ return;+ }++ setResolvedQuery(normalizedQuery);+ setSearchStatus({ state: "idle" });+ }, 700);++ return () => window.clearTimeout(timeout);+ }, [query]);++ const resourceGroups: GlobalCommandMenuGroup[] = resolvedQuery+ ? [+ {+ heading: "Project resources",+ items: [+ {+ id: "resource-api-key",+ label: "API_KEY",+ breadcrumb: "Production / apps / api / Secret",+ icon: FileIcon,+ keywords: ["secret", "production", "api"],+ onSelect: () => setOpen(false)+ },+ {+ id: "resource-api-folder",+ label: "api",+ breadcrumb: "Production / apps / Folder",+ icon: FolderIcon,+ keywords: ["folder", "production"],+ onSelect: () => setOpen(false)+ }+ ]+ }+ ]+ : [];++ return (+ <div className="flex w-full max-w-96 flex-col gap-3">+ <Button variant="outline" onClick={() => setOpen(true)}>+ Search Project Resources+ <CommandShortcut>⌘/Ctrl K</CommandShortcut>+ </Button>+ <p className="text-sm text-accent">+ Type at least two characters. Type “missing” to compare searching and empty states, or+ “error” to preview the failure state.+ </p>+ <GlobalCommandMenu+ groups={[]}+ searchGroups={resourceGroups}+ searchStatus={searchStatus}+ onSearchChange={setQuery}+ open={open}+ onOpenChange={setOpen}+ placeholder="Search project resources..."+ emptyMessage="No project resources found."+ />+ </div>+ );+};++export const GlobalAsyncSearch: Story = {+ name: "Example: Async Search",+ parameters: {+ docs: {+ description: {+ story:+ "Pass `onSearchChange` and `searchStatus` when a consumer adds debounced server-backed results. Loading and failure remain distinct from an empty result set, and the generic component stays independent of resource APIs."+ }+ }+ },+ render: () => <AsyncGlobalNavigationStory />+};+const ORGANIZATIONS = [{ id: "1", name: "Infisical Infrastructure" },{ id: "2", name: "Acme Corp" },diff --git a/frontend/src/components/v3/generic/Command/Command.tsx b/frontend/src/components/v3/generic/Command/Command.tsxindex 4ac038d6be..543db7853f 100644--- a/frontend/src/components/v3/generic/Command/Command.tsx+++ b/frontend/src/components/v3/generic/Command/Command.tsx@@ -33,25 +33,37 @@ function CommandDialog({description = "Search for a command to run...",children,className,+ contentProps,+ loop = false,+ shouldFilter,showCloseButton = true,...props}: React.ComponentProps<typeof Dialog> & {title?: string;description?: string;className?: string;+ contentProps?: Omit<React.ComponentProps<typeof DialogContent>, "children" | "className">;+ loop?: boolean;+ shouldFilter?: boolean;showCloseButton?: boolean;}) {return (<Dialog {...props}>- <DialogHeader className="sr-only">- <DialogTitle>{title}</DialogTitle>- <DialogDescription>{description}</DialogDescription>- </DialogHeader><DialogContent+ {...contentProps}className={cn("overflow-hidden p-0", className)}showCloseButton={showCloseButton}>- <Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">+ <DialogHeader className="sr-only">+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>+ <Command+ label={title}+ loop={loop}+ shouldFilter={shouldFilter}+ className="**:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12"+ >{children}</Command></DialogContent>@@ -61,14 +73,19 @@ function CommandDialog({function CommandInput({className,+ startAdornment,+ endAdornment,...props-}: React.ComponentProps<typeof CommandPrimitive.Input>) {+}: React.ComponentProps<typeof CommandPrimitive.Input> & {+ startAdornment?: React.ReactNode;+ endAdornment?: React.ReactNode;+}) {return (<divdata-slot="command-input-wrapper"className="flex h-9 items-center gap-2 border-b border-border px-3">- <SearchIcon className="size-4 shrink-0 opacity-50" />+ {startAdornment ?? <SearchIcon aria-hidden="true" className="size-4 shrink-0 opacity-50" />}<CommandPrimitive.Inputdata-slot="command-input"className={cn(@@ -77,6 +94,7 @@ function CommandInput({)}{...props}/>+ {endAdornment}</div>);}@@ -98,7 +116,7 @@ function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitivereturn (<CommandPrimitive.Emptydata-slot="command-empty"- className="py-2.5 text-center text-sm text-accent"+ className="flex h-14 flex-col justify-center py-2.5 text-center text-sm text-accent"{...props}/>);diff --git a/frontend/src/components/v3/generic/Command/GlobalCommandMenu.tsx b/frontend/src/components/v3/generic/Command/GlobalCommandMenu.tsxnew file mode 100644index 0000000000..84ef0f024a--- /dev/null+++ b/frontend/src/components/v3/generic/Command/GlobalCommandMenu.tsx@@ -0,0 +1,384 @@+import * as React from "react";+import type { LucideIcon } from "lucide-react";+import {+ ArrowLeftIcon,+ ChevronLeftIcon,+ ChevronRightIcon,+ CircleAlertIcon,+ CornerDownLeftIcon,+ LoaderCircleIcon+} from "lucide-react";++import { cn } from "../../utils";+import { Kbd } from "../Kbd";+import {+ CommandDialog,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandShortcut+} from "./Command";++const APPLE_PLATFORM_PATTERN = /Mac|iPhone|iPad|iPod/i;+const SHORTCUT_EXCLUSION_SELECTOR =+ '[data-command-menu-shortcut="ignore"], [contenteditable]:not([contenteditable="false"]), .cm-editor, .monaco-editor, .xterm';++export type GlobalCommandMenuItem = {+ id: string;+ label: string;+ breadcrumb: string;+ icon?: LucideIcon;+ iconClassName?: string;+ badge?: React.ReactNode;+ keywords?: string[];+ shortcut?: React.ReactNode;+ priority?: number;+ isDisabled?: boolean;+ onSelect?: () => void;+ children?: GlobalCommandMenuGroup[];+ drilldownPlaceholder?: string;+};++export type GlobalCommandMenuGroup = {+ heading?: string;+ items: GlobalCommandMenuItem[];+};++export type GlobalCommandMenuSearchStatus =+ | { state: "idle" }+ | { state: "loading"; message?: string }+ | { state: "error"; message: string };++export type GlobalCommandMenuProps = {+ groups: GlobalCommandMenuGroup[];+ searchGroups?: GlobalCommandMenuGroup[];+ searchStatus?: GlobalCommandMenuSearchStatus;+ onSearchChange?: (search: string) => void;+ isEnabled?: boolean;+ open?: boolean;+ defaultOpen?: boolean;+ onOpenChange?: (open: boolean) => void;+ title?: string;+ description?: string;+ placeholder?: string;+ emptyMessage?: string;+ showFooter?: boolean;+ className?: string;+};++const usesAppleCommandKey = () => {+ if (typeof navigator === "undefined") return false;+ return APPLE_PLATFORM_PATTERN.test(`${navigator.platform} ${navigator.userAgent}`);+};++const isGlobalCommandShortcut = (event: KeyboardEvent) => {+ if (+ event.defaultPrevented ||+ event.isComposing ||+ event.repeat ||+ event.key.toLowerCase() !== "k" ||+ event.altKey ||+ event.shiftKey+ ) {+ return false;+ }++ return usesAppleCommandKey() ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;+};++const getSearchScore = (item: GlobalCommandMenuItem, search: string) => {+ const query = search.trim().toLowerCase();+ if (!query) return item.priority ?? 0;++ const label = item.label.toLowerCase();+ const breadcrumb = item.breadcrumb.toLowerCase();+ const keywords = item.keywords?.map((keyword) => keyword.toLowerCase()) ?? [];+ let relevance = -1;++ if (label === query) relevance = 100;+ else if (label.startsWith(query)) relevance = 80;+ else if (label.includes(query)) relevance = 60;+ else if (keywords.some((keyword) => keyword.startsWith(query))) relevance = 50;+ else if (keywords.some((keyword) => keyword.includes(query))) relevance = 40;+ else if (breadcrumb.includes(query)) relevance = 30;++ return relevance < 0 ? relevance : relevance + (item.priority ?? 0);+};++const filterGroups = (groups: GlobalCommandMenuGroup[], search: string) =>+ groups+ .map((group) => ({+ ...group,+ items: group.items+ .map((item) => ({ item, score: getSearchScore(item, search) }))+ .filter(({ score }) => score >= 0)+ .sort((a, b) => b.score - a.score)+ .map(({ item }) => item)+ }))+ .filter(({ items }) => items.length > 0);++const flattenSearchGroups = (+ groups: GlobalCommandMenuGroup[],+ search: string+): GlobalCommandMenuGroup[] => [+ {+ items: [+ ...new Map(groups.flatMap((group) => group.items).map((item) => [item.id, item])).values()+ ]+ .map((item) => ({ item, score: getSearchScore(item, search) }))+ .filter(({ score }) => score >= 0)+ .sort((a, b) => b.score - a.score)+ .map(({ item }) => item)+ }+];++const CommandResult = ({ item }: { item: GlobalCommandMenuItem }) => {+ const Icon = item.icon;++ return (+ <>+ {Icon && (+ <div className="flex aspect-square size-8 shrink-0 items-center justify-center">+ <Icon aria-hidden="true" className={cn("size-4", item.iconClassName)} />+ </div>+ )}+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate font-medium text-foreground">{item.label}</span>+ {item.badge}+ </span>+ <span className="block truncate text-xs text-muted">{item.breadcrumb}</span>+ </span>+ {item.shortcut && <CommandShortcut>{item.shortcut}</CommandShortcut>}+ {item.children && <ChevronRightIcon aria-hidden="true" className="ml-auto size-4" />}+ </>+ );+};++export const GlobalCommandMenu = ({+ groups,+ searchGroups = groups,+ searchStatus = { state: "idle" },+ onSearchChange,+ isEnabled = true,+ open: controlledOpen,+ defaultOpen = false,+ onOpenChange,+ title = "Command Menu",+ description = "Search available commands.",+ placeholder = "Search commands...",+ emptyMessage = "No commands found.",+ showFooter = true,+ className+}: GlobalCommandMenuProps) => {+ const [uncontrolledOpen, setUncontrolledOpen] = React.useState(defaultOpen);+ const [search, setSearch] = React.useState("");+ const [drilldown, setDrilldown] = React.useState<GlobalCommandMenuItem[]>([]);+ const open = controlledOpen ?? uncontrolledOpen;+ const openRef = React.useRef(open);+ const invokerRef = React.useRef<HTMLElement | null>(null);+ const activeDrilldown = drilldown.at(-1);+ let mode = "browse";+ if (search.trim()) mode = "search";+ if (activeDrilldown) mode = "drill-down";++ React.useEffect(() => {+ openRef.current = open;+ }, [open]);++ const updateSearch = React.useCallback(+ (nextSearch: string) => {+ setSearch(nextSearch);+ if (!activeDrilldown) onSearchChange?.(nextSearch);+ },+ [activeDrilldown, onSearchChange]+ );++ const resetMenu = React.useCallback(() => {+ setSearch("");+ onSearchChange?.("");+ setDrilldown([]);+ }, [onSearchChange]);++ const setOpen = React.useCallback(+ (nextOpen: boolean) => {+ openRef.current = nextOpen;+ if (controlledOpen === undefined) setUncontrolledOpen(nextOpen);+ if (!nextOpen) resetMenu();+ onOpenChange?.(nextOpen);+ },+ [controlledOpen, onOpenChange, resetMenu]+ );++ React.useEffect(() => {+ if (!isEnabled) return undefined;++ const handleKeyDown = (event: KeyboardEvent) => {+ if (!isGlobalCommandShortcut(event)) return;++ const { target } = event;+ if (target instanceof Element && target.closest(SHORTCUT_EXCLUSION_SELECTOR)) return;++ event.preventDefault();+ event.stopPropagation();+ setOpen(!openRef.current);+ };++ window.addEventListener("keydown", handleKeyDown, true);+ return () => window.removeEventListener("keydown", handleKeyDown, true);+ }, [isEnabled, setOpen]);++ const goBack = () => {+ updateSearch("");+ setDrilldown((current) => current.slice(0, -1));+ };++ const visibleGroups = React.useMemo(() => {+ if (activeDrilldown?.children) return filterGroups(activeDrilldown.children, search);+ if (mode === "search") return flattenSearchGroups([...groups, ...searchGroups], search);+ return groups.filter(({ items }) => items.length > 0);+ }, [activeDrilldown, groups, mode, search, searchGroups]);++ const visibleItems = visibleGroups.flatMap((group) => group.items);+ const resultCount = visibleItems.length;+ const inputPlaceholder = activeDrilldown?.drilldownPlaceholder ?? placeholder;+ const isAsyncRootSearch = mode === "search" && !activeDrilldown;+ const isSearching = isAsyncRootSearch && searchStatus.state === "loading";+ const searchError =+ isAsyncRootSearch && searchStatus.state === "error" ? searchStatus.message : undefined;+ const liveStatus = (() => {+ if (isSearching) return searchStatus.message ?? "Searching resources.";+ if (searchError) return searchError;+ if (resultCount === 0) return emptyMessage;+ return `${resultCount} ${resultCount === 1 ? "result" : "results"}`;+ })();++ return (+ <CommandDialog+ modal+ open={open}+ onOpenChange={setOpen}+ title={title}+ description={description}+ className={cn("top-[12%] max-w-2xl origin-top translate-y-0 shadow-2xl", className)}+ loop+ shouldFilter={false}+ showCloseButton={false}+ contentProps={{+ overlayClassName: "bg-black/20",+ onOpenAutoFocus: () => {+ invokerRef.current =+ document.activeElement instanceof HTMLElement ? document.activeElement : null;+ },+ onCloseAutoFocus: (event) => {+ event.preventDefault();++ const invoker = invokerRef.current;+ invokerRef.current = null;+ if (invoker?.isConnected) invoker.focus();+ },+ onKeyDownCapture: (event) => {+ if (event.key === "ArrowLeft" && !search && activeDrilldown) {+ event.preventDefault();+ event.stopPropagation();+ goBack();+ }+ }+ }}+ >+ <CommandInput+ aria-label={activeDrilldown ? `${activeDrilldown.label}: ${inputPlaceholder}` : title}+ placeholder={inputPlaceholder}+ value={search}+ onValueChange={updateSearch}+ startAdornment={+ activeDrilldown ? (+ <button+ type="button"+ aria-label="Back to previous commands"+ className="-ml-1 flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted outline-none hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ onClick={goBack}+ >+ <ChevronLeftIcon aria-hidden="true" className="size-4" />+ </button>+ ) : undefined+ }+ />+ <CommandList+ key={`${activeDrilldown?.id ?? "root"}-${mode}`}+ className="max-h-[calc(100dvh-8rem)] sm:max-h-[26rem]"+ >+ <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">+ {liveStatus}+ </div>+ {resultCount === 0 && !isSearching && !searchError && (+ <CommandEmpty>{emptyMessage}</CommandEmpty>+ )}+ {resultCount > 0 &&+ visibleGroups.map((group) => (+ <CommandGroup key={group.heading ?? "commands"} heading={group.heading}>+ {group.items.map((item) => (+ <CommandItem+ key={item.id}+ value={item.id}+ keywords={[item.label, item.breadcrumb, ...(item.keywords ?? [])]}+ disabled={item.isDisabled}+ onSelect={() => {+ if (item.children) {+ updateSearch("");+ setDrilldown((current) => [...current, item]);+ return;+ }++ setOpen(false);+ item.onSelect?.();+ }}+ >+ <CommandResult item={item} />+ </CommandItem>+ ))}+ </CommandGroup>+ ))}+ {isSearching && (+ <div className="flex h-14 items-center justify-center gap-2 py-2.5 text-sm text-muted">+ <LoaderCircleIcon aria-hidden="true" className="size-4 animate-spin" />+ <span>{searchStatus.message ?? "Searching resources…"}</span>+ </div>+ )}+ {searchError && (+ <div+ role="alert"+ className="flex h-14 items-center justify-center gap-2 py-2.5 text-sm text-danger"+ >+ <CircleAlertIcon aria-hidden="true" className="size-4" />+ <span>{searchError}</span>+ </div>+ )}+ </CommandList>+ {showFooter && (+ <div className="flex items-center justify-end gap-4 border-t border-border px-3 py-2 text-xs text-muted">+ {activeDrilldown && (+ <div className="flex items-center gap-1.5">+ <Kbd>+ <ArrowLeftIcon aria-hidden="true" className="size-3" />+ </Kbd>+ <span>Back</span>+ </div>+ )}+ <div className="flex items-center gap-1.5">+ <Kbd>+ <CornerDownLeftIcon aria-hidden="true" className="size-3" />+ </Kbd>+ <span>Select</span>+ </div>+ <div className="flex items-center gap-1.5">+ <Kbd>Esc</Kbd>+ <span>Close</span>+ </div>+ </div>+ )}+ </CommandDialog>+ );+};diff --git a/frontend/src/components/v3/generic/Command/index.ts b/frontend/src/components/v3/generic/Command/index.tsindex 4de6159a1c..864d2ff79d 100644--- a/frontend/src/components/v3/generic/Command/index.ts+++ b/frontend/src/components/v3/generic/Command/index.ts@@ -1 +1,2 @@export * from "./Command";+export * from "./GlobalCommandMenu";diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsxindex 6d0c59a397..6ac5472641 100644--- a/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsx+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-keyboard-shortcuts.tsx@@ -11,10 +11,9 @@ import {DialogTitle} from "@app/components/v3/generic/Dialog";import { Input } from "@app/components/v3/generic/Input";+import { Kbd, KbdGroup } from "@app/components/v3/generic/Kbd";import { Separator } from "@app/components/v3/generic/Separator";-import { Kbd, KbdGroup } from "./ui/kbd";-const SHORTCUT_KEY = "/";interface ShortcutGroup {diff --git a/frontend/src/components/v3/generic/DataGrid/ui/kbd.tsx b/frontend/src/components/v3/generic/DataGrid/ui/kbd.tsxdeleted file mode 100644index 5edfa14214..0000000000--- a/frontend/src/components/v3/generic/DataGrid/ui/kbd.tsx+++ /dev/null@@ -1,20 +0,0 @@-// Minimal Kbd component for Dice UI DataGrid keyboard shortcuts dialog-import * as React from "react";--import { cn } from "@app/components/v3/utils";--export function Kbd({ className, ...props }: React.HTMLAttributes<HTMLElement>) {- return (- <kbd- className={cn(- "pointer-events-none inline-flex h-5 items-center gap-1 rounded border border-border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted select-none",- className- )}- {...props}- />- );-}--export function KbdGroup({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {- return <div className={cn("flex items-center gap-0.5", className)} {...props} />;-}diff --git a/frontend/src/components/v3/generic/Dialog/Dialog.tsx b/frontend/src/components/v3/generic/Dialog/Dialog.tsxindex 94fe5ca8da..183276c00d 100644--- a/frontend/src/components/v3/generic/Dialog/Dialog.tsx+++ b/frontend/src/components/v3/generic/Dialog/Dialog.tsx@@ -37,7 +37,7 @@ function DialogOverlay({<DialogPrimitive.Overlaydata-slot="dialog-overlay"className={cn(- "fixed inset-0 z-50 bg-black/50 data-[state=open]:animate-in data-[state=open]:fade-in-0",+ "fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:duration-100 data-[state=closed]:ease-in data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:duration-150 data-[state=open]:ease-in data-[state=open]:fade-in-0",className)}{...props}@@ -63,7 +63,7 @@ function DialogContent({<DialogPrimitive.Contentdata-slot="dialog-content"className={cn(- "fixed top-[50%] left-[50%] z-50 flex max-h-[calc(100dvh-2rem)] thin-scrollbar translate-x-[-50%] translate-y-[-50%] flex-col gap-6 overflow-y-auto overscroll-none rounded-lg border border-border bg-popover p-6 text-foreground shadow-lg duration-200 outline-none has-data-[slot=dialog-footer]:pb-0 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",+ "fixed top-[50%] left-[50%] z-50 flex max-h-[calc(100dvh-2rem)] thin-scrollbar translate-x-[-50%] translate-y-[-50%] flex-col gap-6 overflow-y-auto overscroll-none rounded-lg border border-border bg-popover p-6 text-foreground shadow-lg outline-none has-data-[slot=dialog-footer]:pb-0 data-[state=closed]:animate-out data-[state=closed]:duration-100 data-[state=closed]:ease-in data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:duration-150 data-[state=open]:ease-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",DIALOG_CONTENT_WIDTH_CLASSNAME,className)}diff --git a/frontend/src/components/v3/generic/Kbd/Kbd.stories.tsx b/frontend/src/components/v3/generic/Kbd/Kbd.stories.tsxnew file mode 100644index 0000000000..0dfeb2eec1--- /dev/null+++ b/frontend/src/components/v3/generic/Kbd/Kbd.stories.tsx@@ -0,0 +1,70 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ArrowLeftIcon, CornerDownLeftIcon } from "lucide-react";++import { Kbd, KbdGroup } from "./Kbd";++/**+ * `Kbd` displays a keyboard key or shortcut as non-interactive instructional content.+ * Use `KbdGroup` to keep multiple keycaps together.+ */+const meta = {+ title: "Generic/Kbd",+ component: Kbd,+ parameters: {+ layout: "centered"+ },+ tags: ["autodocs"],+ argTypes: {+ className: {+ table: { disable: true }+ },+ children: {+ table: { disable: true }+ }+ },+ args: {+ children: "Esc"+ }+} satisfies Meta<typeof Kbd>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {};++export const Shortcut: Story = {+ name: "Example: Shortcut",+ render: () => (+ <KbdGroup>+ <Kbd>⌘</Kbd>+ <span aria-hidden="true" className="px-0.5 text-xs text-muted">+ ++ </span>+ <Kbd>K</Kbd>+ </KbdGroup>+ )+};++export const IconKeys: Story = {+ name: "Example: Icon Keys",+ render: () => (+ <KbdGroup>+ <Kbd aria-label="Left Arrow">+ <ArrowLeftIcon aria-hidden="true" className="size-3" />+ </Kbd>+ <Kbd aria-label="Enter">+ <CornerDownLeftIcon aria-hidden="true" className="size-3" />+ </Kbd>+ </KbdGroup>+ )+};++export const InInstruction: Story = {+ name: "Example: Instruction",+ render: () => (+ <div className="flex items-center gap-1.5 text-xs text-muted">+ <Kbd>Esc</Kbd>+ <span>Close</span>+ </div>+ )+};diff --git a/frontend/src/components/v3/generic/Kbd/Kbd.tsx b/frontend/src/components/v3/generic/Kbd/Kbd.tsxnew file mode 100644index 0000000000..7bcdd1b52e--- /dev/null+++ b/frontend/src/components/v3/generic/Kbd/Kbd.tsx@@ -0,0 +1,24 @@+import * as React from "react";++import { cn } from "../../utils";++function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {+ return (+ <kbd+ data-slot="kbd"+ className={cn(+ "pointer-events-none inline-flex h-5 min-w-5 items-center justify-center gap-1 rounded border border-border bg-container px-1.5 font-mono text-[10px] leading-none font-medium text-foreground select-none",+ className+ )}+ {...props}+ />+ );+}++function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div data-slot="kbd-group" className={cn("flex items-center gap-0.5", className)} {...props} />+ );+}++export { Kbd, KbdGroup };diff --git a/frontend/src/components/v3/generic/Kbd/index.ts b/frontend/src/components/v3/generic/Kbd/index.tsnew file mode 100644index 0000000000..14bc264de0--- /dev/null+++ b/frontend/src/components/v3/generic/Kbd/index.ts@@ -0,0 +1 @@+export * from "./Kbd";diff --git a/frontend/src/components/v3/generic/Sheet/Sheet.tsx b/frontend/src/components/v3/generic/Sheet/Sheet.tsxindex be22788532..c897522067 100644--- a/frontend/src/components/v3/generic/Sheet/Sheet.tsx+++ b/frontend/src/components/v3/generic/Sheet/Sheet.tsx@@ -37,7 +37,7 @@ function SheetOverlay({<SheetPrimitive.Overlaydata-slot="sheet-overlay"className={cn(- "fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",+ "fixed inset-0 z-50 bg-black/50 ease-out data-[state=closed]:animate-out data-[state=closed]:duration-250 data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:duration-200 data-[state=open]:fade-in-0",className)}{...props}@@ -75,15 +75,15 @@ function SheetContent({onInteractOutside?.(e);}}className={cn(- "fixed z-50 flex thin-scrollbar flex-col border-border bg-popover text-foreground shadow-lg outline-0 transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",+ "fixed z-50 flex thin-scrollbar flex-col border-border bg-popover text-foreground shadow-lg outline-0 transition ease-out data-[state=closed]:animate-out data-[state=closed]:duration-250 data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:duration-200 data-[state=open]:fade-in-0",side === "right" &&- "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-md",+ "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right-8 data-[state=open]:slide-in-from-right-2 sm:max-w-md",side === "left" &&- "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-md",+ "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left-8 data-[state=open]:slide-in-from-left-2 sm:max-w-md",side === "top" &&- "inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",+ "inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top-8 data-[state=open]:slide-in-from-top-2",side === "bottom" &&- "inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",+ "inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom-8 data-[state=open]:slide-in-from-bottom-2",className)}{...props}diff --git a/frontend/src/components/v3/generic/Tabs/Tabs.stories.tsx b/frontend/src/components/v3/generic/Tabs/Tabs.stories.tsxindex a79c905f04..5bad385781 100644--- a/frontend/src/components/v3/generic/Tabs/Tabs.stories.tsx+++ b/frontend/src/components/v3/generic/Tabs/Tabs.stories.tsx@@ -1,6 +1,6 @@import { useState } from "react";import type { Meta, StoryObj } from "@storybook/react-vite";-import { expect, userEvent, within } from "storybook/test";+import { expect, userEvent, waitFor, within } from "storybook/test";import { Button } from "../Button";import { Card, CardContent } from "../Card";@@ -115,11 +115,13 @@ export const HorizontalOverflow: Story = {await userEvent.click(firstTab);await userEvent.keyboard("{End}");- await expect(finalTab).toHaveFocus();- await expect(finalTab).toHaveAttribute("data-state", "active");- await expect(finalTab.getBoundingClientRect().right).toBeLessThanOrEqual(- list.getBoundingClientRect().right + 1- );+ await waitFor(async () => {+ await expect(finalTab).toHaveFocus();+ await expect(finalTab).toHaveAttribute("data-state", "active");+ await expect(finalTab.getBoundingClientRect().right).toBeLessThanOrEqual(+ list.getBoundingClientRect().right + 1+ );+ });}};@@ -165,10 +167,12 @@ export const Controlled: Story = {await userEvent.click(canvas.getByRole("button", { name: "Select final tab" }));- await expect(finalTab).toHaveAttribute("data-state", "active");- await expect(finalTab.getBoundingClientRect().right).toBeLessThanOrEqual(- list.getBoundingClientRect().right + 1- );+ await waitFor(async () => {+ await expect(finalTab).toHaveAttribute("data-state", "active");+ await expect(finalTab.getBoundingClientRect().right).toBeLessThanOrEqual(+ list.getBoundingClientRect().right + 1+ );+ });}};@@ -201,12 +205,16 @@ export const ManualActivation: Story = {await userEvent.click(overviewTab);await userEvent.keyboard("{ArrowRight}");- await expect(activityTab).toHaveFocus();- await expect(overviewTab).toHaveAttribute("aria-selected", "true");- await expect(activityTab).toHaveAttribute("aria-selected", "false");+ await waitFor(async () => {+ await expect(activityTab).toHaveFocus();+ await expect(overviewTab).toHaveAttribute("aria-selected", "true");+ await expect(activityTab).toHaveAttribute("aria-selected", "false");+ });await userEvent.keyboard("{Enter}");- await expect(activityTab).toHaveAttribute("aria-selected", "true");+ await waitFor(async () => {+ await expect(activityTab).toHaveAttribute("aria-selected", "true");+ });}};@@ -240,8 +248,10 @@ export const Disabled: Story = {await userEvent.click(overviewTab);await userEvent.keyboard("{ArrowRight}");- await expect(settingsTab).toHaveFocus();- await expect(settingsTab).toHaveAttribute("aria-selected", "true");+ await waitFor(async () => {+ await expect(settingsTab).toHaveFocus();+ await expect(settingsTab).toHaveAttribute("aria-selected", "true");+ });}};diff --git a/frontend/src/components/v3/generic/index.ts b/frontend/src/components/v3/generic/index.tsindex 6cafe4c56b..d75a28185d 100644--- a/frontend/src/components/v3/generic/index.ts+++ b/frontend/src/components/v3/generic/index.ts@@ -28,6 +28,7 @@ export * from "./IconButton";export * from "./Input";export * from "./InputGroup";export * from "./Item";+export * from "./Kbd";export * from "./Label";export * from "./Loader";export * from "./Pagination";diff --git a/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsx b/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsxnew file mode 100644index 0000000000..5b0de4f966--- /dev/null+++ b/frontend/src/components/v3/platform/RootCommandMenu/RootCommandMenu.tsx@@ -0,0 +1,1073 @@+import { useLocation, useNavigate, useParams, useRouteContext } from "@tanstack/react-router";+import {+ BlocksIcon,+ BuildingIcon,+ CogIcon,+ CreditCardIcon,+ DatabaseIcon,+ FileTextIcon,+ FolderOpenIcon,+ InboxIcon,+ KeyIcon,+ KeyRoundIcon,+ LayoutDashboardIcon,+ SearchIcon,+ ServerCogIcon,+ SettingsIcon,+ ShieldCheckIcon,+ ShieldIcon,+ UserIcon,+ UsersIcon+} from "lucide-react";++import {+ GlobalCommandMenu,+ type GlobalCommandMenuGroup,+ type GlobalCommandMenuItem,+ type GlobalCommandMenuSearchStatus+} from "@app/components/v3/generic/Command";+import { OrgIcon, ProjectIcon, SubOrgIcon } from "@app/components/v3/platform/ScopeIcons";+import {+ OrgPermissionActions,+ OrgPermissionAuditLogsActions,+ OrgPermissionBillingActions,+ OrgPermissionGroupActions,+ OrgPermissionIdentityActions,+ OrgPermissionMemberActions,+ OrgPermissionSubjects,+ ProjectPermissionActions,+ ProjectPermissionAuditLogsActions,+ ProjectPermissionCertificateActions,+ ProjectPermissionIdentityActions,+ ProjectPermissionKmipActions,+ ProjectPermissionMemberActions,+ ProjectPermissionPkiDiscoveryActions,+ ProjectPermissionSub,+ type TProjectPermission,+ useOrganization,+ useOrgPermission,+ useProject,+ useProjectPermission+} from "@app/context";+import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";+import {+ ProjectPermissionAppConnectionActions,+ ProjectPermissionSecretScanningFindingActions,+ ProjectPermissionSecretSyncActions+} from "@app/context/ProjectPermissionContext/types";+import { getProjectLucideIcon, getProjectTitle } from "@app/helpers/project";+import { useGetOrganizationGroups, useGetOrganizationsWithSubOrgs } from "@app/hooks/api";+import { useGetAccessibleProjectsWithSubOrgs } from "@app/hooks/api/projects/queries";+import type { Project, TProjectNavigation } from "@app/hooks/api/projects/types";+import { ProjectType } from "@app/hooks/api/projects/types";+import { useGetUserOrgPermissions } from "@app/hooks/api/roles";+import { IntegrationsListPageTabs } from "@app/types/integrations";+import { OrgAccessControlTabSections } from "@app/types/org";++import { useSecretManagerCommandSearch } from "./useSecretManagerCommandSearch";++export type RootCommandMenuShell = "organization" | "admin" | "personal-settings";++type CommandContent = {+ browseGroups: GlobalCommandMenuGroup[];+ searchGroups: GlobalCommandMenuGroup[];+ searchStatus?: GlobalCommandMenuSearchStatus;+};++type AsyncCommandSearch = {+ groups: GlobalCommandMenuGroup[];+ searchStatus: GlobalCommandMenuSearchStatus;+ onSearchChange: (search: string) => void;+};++const projectIconClassNames: Record<ProjectType, string> = {+ [ProjectType.SecretManager]: "text-product-sm",+ [ProjectType.CertificateManager]: "text-product-pki",+ [ProjectType.KMS]: "text-product-kms",+ [ProjectType.SecretScanning]: "text-product-ss",+ [ProjectType.PAM]: "text-product-pam"+};++const NavigationCommandMenu = ({+ browseGroups,+ searchGroups,+ searchStatus,+ asyncSearch+}: CommandContent & {+ asyncSearch?: AsyncCommandSearch;+}) => (+ <GlobalCommandMenu+ groups={browseGroups}+ searchGroups={[...searchGroups, ...(asyncSearch?.groups ?? [])]}+ searchStatus={+ [searchStatus, asyncSearch?.searchStatus].find((status) => status?.state === "loading") ??+ [searchStatus, asyncSearch?.searchStatus].find((status) => status?.state === "error")+ }+ onSearchChange={asyncSearch?.onSearchChange}+ title="Search Infisical"+ description="Search pages, projects, organizations, teams, and commands."+ placeholder="Find..."+ emptyMessage="No matching pages or commands."+ showFooter={false}+ />+);++const navigateToProject = (+ navigate: ReturnType<typeof useNavigate>,+ project: TProjectNavigation+) => {+ switch (project.type) {+ case ProjectType.SecretManager:+ return navigate({+ to: "/organizations/$orgId/projects/secret-management/$projectId/overview",+ params: { orgId: project.orgId, projectId: project.id }+ });+ case ProjectType.CertificateManager:+ return navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/overview",+ params: { orgId: project.orgId, projectId: project.id }+ });+ case ProjectType.SecretScanning:+ return navigate({+ to: "/organizations/$orgId/projects/secret-scanning/$projectId/data-sources",+ params: { orgId: project.orgId, projectId: project.id }+ });+ case ProjectType.PAM:+ return navigate({+ to: "/organizations/$orgId/pam/accounts",+ params: { orgId: project.orgId }+ });+ case ProjectType.KMS:+ default:+ return navigate({+ to: "/organizations/$orgId/projects/kms/$projectId/overview",+ params: { orgId: project.orgId, projectId: project.id }+ });+ }+};++const useEntityCommandGroups = ({+ currentOrganizationId,+ currentOrganizationName+}: {+ currentOrganizationId?: string;+ currentOrganizationName?: string;+}) => {+ const navigate = useNavigate();+ const projectsQuery = useGetAccessibleProjectsWithSubOrgs(currentOrganizationId ?? "");+ const organizationsQuery = useGetOrganizationsWithSubOrgs();+ const { data: projects = [] } = projectsQuery;+ const { data: rootOrganizations = [] } = organizationsQuery;+ const { data: orgPermissionData } = useGetUserOrgPermissions({+ orgId: currentOrganizationId ?? ""+ });+ const canReadTeams = Boolean(+ orgPermissionData?.permission.can(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups)+ );+ const { data: teams = [] } = useGetOrganizationGroups(+ canReadTeams ? (currentOrganizationId ?? "") : ""+ );+ const organizations = rootOrganizations.flatMap((organization) => [+ { ...organization, rootOrganizationName: undefined, isSubOrganization: false },+ ...organization.subOrganizations.map((subOrganization) => ({+ ...subOrganization,+ rootOrganizationName: organization.name,+ isSubOrganization: true+ }))+ ]);+ const organizationsById = new Map(+ organizations.map((organization) => [organization.id, organization])+ );++ const projectItems: GlobalCommandMenuItem[] = projects.map((project) => {+ const organization = organizationsById.get(project.orgId);+ const organizationPath = [+ organization?.rootOrganizationName,+ organization?.name ?? "Organization"+ ]+ .filter(Boolean)+ .join(" / ");++ return {+ id: `entity-project-${project.id}`,+ label: project.name,+ breadcrumb: `${organizationPath} / ${getProjectTitle(project.type)}`,+ icon: getProjectLucideIcon(project.type),+ iconClassName: projectIconClassNames[project.type],+ keywords: [project.slug, project.type, getProjectTitle(project.type), "project"],+ priority: project.orgId === currentOrganizationId ? 20 : 0,+ onSelect: () => navigateToProject(navigate, project)+ };+ });++ const organizationItems: GlobalCommandMenuItem[] = organizations.map((organization) => ({+ id: `entity-organization-${organization.id}`,+ label: organization.name,+ breadcrumb: organization.isSubOrganization+ ? `${organization.rootOrganizationName} / Sub-Organization`+ : "Organization",+ icon: organization.isSubOrganization ? SubOrgIcon : OrgIcon,+ iconClassName: organization.isSubOrganization ? "text-sub-org" : "text-org",+ keywords: [+ organization.slug,+ "organization",+ "workspace",+ ...(organization.isSubOrganization ? ["sub", "sub-org", "sub-organization"] : [])+ ],+ priority: organization.id === currentOrganizationId ? 20 : 0,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/projects",+ params: { orgId: organization.id }+ })+ }));++ const teamItems: GlobalCommandMenuItem[] = teams.map((team) => ({+ id: `entity-team-${team.id}`,+ label: team.name,+ breadcrumb: `${currentOrganizationName ?? "Organization"} / Team`,+ icon: UsersIcon,+ iconClassName: "text-org",+ keywords: [team.slug, "team", "group"],+ priority: 15,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/groups/$groupId",+ params: { orgId: currentOrganizationId!, groupId: team.id }+ })+ }));++ let searchStatus: GlobalCommandMenuSearchStatus = { state: "idle" };+ if (projectsQuery.isLoading || organizationsQuery.isLoading) {+ searchStatus = { state: "loading", message: "Loading projects and organizations…" };+ } else if (projectsQuery.isError || organizationsQuery.isError) {+ searchStatus = { state: "error", message: "Could not load projects or organizations." };+ }++ return {+ projectItems,+ organizationItems,+ teamItems,+ searchStatus,+ searchGroups: [+ { heading: "Projects", items: projectItems },+ { heading: "Organizations", items: organizationItems },+ { heading: "Teams", items: teamItems }+ ]+ };+};++const getNestedCommandGroup = ({+ projectItems,+ organizationItems,+ teamItems+}: {+ projectItems: GlobalCommandMenuItem[];+ organizationItems: GlobalCommandMenuItem[];+ teamItems: GlobalCommandMenuItem[];+}): GlobalCommandMenuGroup => ({+ heading: "Explore",+ items: [+ {+ id: "command-search-projects",+ label: "Search Projects…",+ breadcrumb: "Global / Projects",+ icon: SearchIcon,+ keywords: ["find", "switch", "project"],+ children: [{ heading: "Projects", items: projectItems }],+ drilldownPlaceholder: "Search projects..."+ },+ {+ id: "command-switch-organization",+ label: "Switch Organization…",+ breadcrumb: "Global / Organizations",+ icon: BuildingIcon,+ keywords: ["team", "workspace", "organization"],+ children: [{ heading: "Organizations", items: organizationItems }],+ drilldownPlaceholder: "Search organizations..."+ },+ ...(teamItems.length+ ? [+ {+ id: "command-search-teams",+ label: "Search Teams…",+ breadcrumb: "Current Organization / Teams",+ icon: UsersIcon,+ keywords: ["group", "members"],+ children: [{ heading: "Teams", items: teamItems }],+ drilldownPlaceholder: "Search teams..."+ }+ ]+ : [])+ ]+});++const getAccountItems = (navigate: ReturnType<typeof useNavigate>): GlobalCommandMenuItem[] => [+ {+ id: "account-personal-settings",+ label: "Personal Settings",+ breadcrumb: "Account / General",+ icon: UserIcon,+ keywords: ["profile", "name", "email", "account"],+ priority: 5,+ onSelect: () => navigate({ to: "/personal-settings", search: { selectedTab: "general" } })+ },+ {+ id: "account-authentication",+ label: "Authentication",+ breadcrumb: "Account / Personal Settings",+ icon: ShieldCheckIcon,+ keywords: ["password", "mfa", "passkeys", "sessions"],+ priority: 5,+ onSelect: () =>+ navigate({ to: "/personal-settings", search: { selectedTab: "authentication" } })+ },+ {+ id: "account-api-keys",+ label: "API Keys",+ breadcrumb: "Account / Personal Settings",+ icon: KeyRoundIcon,+ keywords: ["tokens"],+ priority: 5,+ onSelect: () => navigate({ to: "/personal-settings", search: { selectedTab: "api-keys" } })+ }+];++const PersonalSettingsCommandMenu = () => {+ const organizationId = useRouteContext({+ from: "/_authenticate",+ select: (context) => context.organizationId+ });+ const navigate = useNavigate();+ const accountItems = getAccountItems(navigate).map((item) => ({ ...item, priority: 30 }));+ const entityGroups = useEntityCommandGroups({ currentOrganizationId: organizationId });+ const nestedGroup = getNestedCommandGroup(entityGroups);++ return (+ <NavigationCommandMenu+ searchStatus={entityGroups.searchStatus}+ browseGroups={[{ heading: "Account", items: accountItems }, nestedGroup]}+ searchGroups={[+ { heading: "Pages & Settings", items: accountItems },+ ...entityGroups.searchGroups+ ]}+ />+ );+};++const AdminCommandMenu = () => {+ const { currentOrg } = useOrganization();+ const navigate = useNavigate();+ const accountItems = getAccountItems(navigate);+ const entityGroups = useEntityCommandGroups({+ currentOrganizationId: currentOrg.id,+ currentOrganizationName: currentOrg.name+ });+ const adminItems: GlobalCommandMenuItem[] = [+ {+ id: "admin-general",+ label: "General",+ breadcrumb: "Server Console / Settings",+ icon: CogIcon,+ keywords: ["server", "configuration"],+ priority: 30,+ onSelect: () => navigate({ to: "/admin" })+ },+ {+ id: "admin-resource-overview",+ label: "Resource Overview",+ breadcrumb: "Server Console / Resources",+ icon: BuildingIcon,+ keywords: ["organizations", "users", "machine identities", "email domains"],+ priority: 30,+ onSelect: () =>+ navigate({+ to: "/admin/resources/overview",+ search: { selectedTab: "organizations" }+ })+ },+ {+ id: "admin-access-control",+ label: "Access Control",+ breadcrumb: "Server Console / Administration",+ icon: ShieldIcon,+ keywords: ["permissions", "admins"],+ priority: 30,+ onSelect: () => navigate({ to: "/admin/access-management" })+ }+ ];++ return (+ <NavigationCommandMenu+ searchStatus={entityGroups.searchStatus}+ browseGroups={[+ { heading: "Server Console", items: adminItems },+ { heading: "Global", items: accountItems.slice(0, 1) },+ getNestedCommandGroup(entityGroups)+ ]}+ searchGroups={[+ { heading: "Pages & Settings", items: [...adminItems, ...accountItems] },+ ...entityGroups.searchGroups+ ]}+ />+ );+};++const getOrganizationItems = ({+ navigate,+ organizationId,+ organizationName,+ isRootOrganization,+ canReadAccessControl,+ canReadMachineIdentities,+ canReadRoles,+ canReadAuditLogs,+ canReadBilling,+ canReadAppConnections,+ canReadIntegrations,+ canReadSettings+}: {+ navigate: ReturnType<typeof useNavigate>;+ organizationId: string;+ organizationName: string;+ isRootOrganization: boolean;+ canReadAccessControl: boolean;+ canReadMachineIdentities: boolean;+ canReadRoles: boolean;+ canReadAuditLogs: boolean;+ canReadBilling: boolean;+ canReadAppConnections: boolean;+ canReadIntegrations: boolean;+ canReadSettings: boolean;+}): GlobalCommandMenuItem[] => [+ {+ id: `organization-${organizationId}-home`,+ label: "Organization Home",+ breadcrumb: organizationName,+ icon: isRootOrganization ? OrgIcon : SubOrgIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["projects", "home"],+ priority: 25,+ onSelect: () =>+ navigate({ to: "/organizations/$orgId/projects", params: { orgId: organizationId } })+ },+ ...(canReadIntegrations+ ? [+ {+ id: `organization-${organizationId}-integrations`,+ label: "Integrations",+ breadcrumb: `${organizationName} / Organization`,+ icon: BlocksIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["connections"],+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/integrations",+ params: { orgId: organizationId }+ })+ },+ ...(canReadAppConnections+ ? [+ {+ id: `organization-${organizationId}-app-connections`,+ label: "App Connections",+ breadcrumb: `${organizationName} / Integrations`,+ icon: BlocksIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["integrations", "connections"],+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/integrations",+ params: { orgId: organizationId },+ search: { selectedTab: IntegrationsListPageTabs.AppConnections }+ })+ }+ ]+ : [])+ ]+ : []),+ ...(canReadAccessControl+ ? [+ {+ id: `organization-${organizationId}-access-control`,+ label: "Access Control",+ breadcrumb: `${organizationName} / Organization`,+ icon: ShieldIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["users", "groups", "teams", "roles", "machine identities"],+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/access-management",+ params: { orgId: organizationId }+ })+ }+ ]+ : []),+ ...(canReadMachineIdentities+ ? [+ {+ id: `organization-${organizationId}-machine-identities`,+ label: "Machine Identities",+ breadcrumb: `${organizationName} / Access Control`,+ icon: UserIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["identities", "identity", "access control"],+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/access-management",+ params: { orgId: organizationId },+ search: { selectedTab: OrgAccessControlTabSections.Identities }+ })+ }+ ]+ : []),+ ...(canReadRoles+ ? [+ {+ id: `organization-${organizationId}-roles`,+ label: "Roles",+ breadcrumb: `${organizationName} / Access Control`,+ icon: ShieldCheckIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["organization roles", "permissions", "access control"],+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/access-management",+ params: { orgId: organizationId },+ search: { selectedTab: OrgAccessControlTabSections.Roles }+ })+ }+ ]+ : []),+ ...(isRootOrganization && canReadBilling+ ? [+ {+ id: `organization-${organizationId}-billing`,+ label: "Usage & Billing",+ breadcrumb: `${organizationName} / Organization Settings`,+ icon: CreditCardIcon,+ iconClassName: "text-org",+ keywords: ["subscription", "plan"],+ priority: 25,+ onSelect: () =>+ navigate({ to: "/organizations/$orgId/billing", params: { orgId: organizationId } })+ }+ ]+ : []),+ ...(canReadAuditLogs+ ? [+ {+ id: `organization-${organizationId}-audit-logs`,+ label: "Audit Logs",+ breadcrumb: `${organizationName} / Organization`,+ icon: FileTextIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/audit-logs",+ params: { orgId: organizationId }+ })+ }+ ]+ : []),+ ...(canReadSettings+ ? [+ {+ id: `organization-${organizationId}-settings`,+ label: "Settings",+ breadcrumb: `${organizationName} / Organization`,+ icon: SettingsIcon,+ iconClassName: isRootOrganization ? "text-org" : "text-sub-org",+ keywords: ["general", "organization settings"],+ priority: 25,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/settings",+ params: { orgId: organizationId },+ search: { selectedTab: "tab-org-general" }+ })+ }+ ]+ : [])+];++const getProjectLandingItem = ({+ navigate,+ project,+ organizationName,+ isCertificateManagerAdmin+}: {+ navigate: ReturnType<typeof useNavigate>;+ project: Project;+ organizationName: string;+ isCertificateManagerAdmin?: boolean;+}): GlobalCommandMenuItem => {+ const breadcrumb = `${organizationName} / ${project.name}`;++ if (project.type === ProjectType.CertificateManager && !isCertificateManagerAdmin) {+ return {+ id: `project-${project.id}-approval-requests`,+ label: "Approval Requests",+ breadcrumb,+ icon: InboxIcon,+ iconClassName: projectIconClassNames[project.type],+ keywords: [project.name, "certificate manager", "requests"],+ priority: 40,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/requests",+ params: { orgId: project.orgId, projectId: project.id }+ })+ };+ }++ const presentation: Record<ProjectType, { label: string; icon: GlobalCommandMenuItem["icon"] }> =+ {+ [ProjectType.SecretManager]: { label: "Secrets", icon: ProjectIcon },+ [ProjectType.CertificateManager]: { label: "Dashboard", icon: LayoutDashboardIcon },+ [ProjectType.KMS]: { label: "Overview", icon: KeyIcon },+ [ProjectType.SecretScanning]: { label: "Data Sources", icon: DatabaseIcon },+ [ProjectType.PAM]: { label: "Accounts", icon: FolderOpenIcon }+ };++ return {+ id: `project-${project.id}-home`,+ label: presentation[project.type].label,+ breadcrumb,+ icon: presentation[project.type].icon,+ iconClassName: projectIconClassNames[project.type],+ keywords: [project.name, project.type, getProjectTitle(project.type)],+ priority: 40,+ onSelect: () => navigateToProject(navigate, project)+ };+};++const getProjectPageItems = ({+ navigate,+ project,+ organizationName,+ pathname,+ isCertificateManagerAdmin+}: {+ navigate: ReturnType<typeof useNavigate>;+ project: Project;+ organizationName: string;+ pathname: string;+ isCertificateManagerAdmin?: boolean;+}): GlobalCommandMenuItem[] => {+ const breadcrumb = `${organizationName} / ${project.name}`;+ const item = (+ id: string,+ label: string,+ icon: GlobalCommandMenuItem["icon"],+ pathSuffix: string,+ onSelect: () => void,+ keywords?: string[]+ ): GlobalCommandMenuItem => ({+ id: `project-${project.id}-${id}`,+ label,+ breadcrumb,+ icon,+ iconClassName: projectIconClassNames[project.type],+ keywords: [project.name, getProjectTitle(project.type), ...(keywords ?? [])],+ priority: pathname.includes(`/${pathSuffix}`) ? 50 : 35,+ onSelect+ });+ const sortByContext = (items: GlobalCommandMenuItem[]) =>+ items.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));++ switch (project.type) {+ case ProjectType.SecretManager:+ return sortByContext([+ getProjectLandingItem({ navigate, project, organizationName }),+ item("integrations", "Integrations", BlocksIcon, "integrations", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-management/$projectId/integrations",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("access-control", "Access Control", ShieldIcon, "access-management", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-management/$projectId/access-management",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("audit-logs", "Audit Logs", FileTextIcon, "audit-logs", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-management/$projectId/audit-logs",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("settings", "Settings", SettingsIcon, "settings", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-management/$projectId/settings",+ params: { orgId: project.orgId, projectId: project.id },+ search: { selectedTab: "tab-project-general" }+ })+ )+ ]);+ case ProjectType.KMS:+ return sortByContext([+ getProjectLandingItem({ navigate, project, organizationName }),+ item("kmip", "KMIP", KeyIcon, "kmip", () =>+ navigate({+ to: "/organizations/$orgId/projects/kms/$projectId/kmip",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("access-control", "Access Control", ShieldIcon, "access-management", () =>+ navigate({+ to: "/organizations/$orgId/projects/kms/$projectId/access-management",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("audit-logs", "Audit Logs", FileTextIcon, "audit-logs", () =>+ navigate({+ to: "/organizations/$orgId/projects/kms/$projectId/audit-logs",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("settings", "Settings", SettingsIcon, "settings", () =>+ navigate({+ to: "/organizations/$orgId/projects/kms/$projectId/settings",+ params: { orgId: project.orgId, projectId: project.id }+ })+ )+ ]);+ case ProjectType.SecretScanning:+ return sortByContext([+ getProjectLandingItem({ navigate, project, organizationName }),+ item("findings", "Findings", SearchIcon, "findings", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-scanning/$projectId/findings",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("app-connections", "App Connections", BlocksIcon, "app-connections", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-scanning/$projectId/app-connections",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("access-control", "Access Control", ShieldIcon, "access-management", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-scanning/$projectId/access-management",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("audit-logs", "Audit Logs", FileTextIcon, "audit-logs", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-scanning/$projectId/audit-logs",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("settings", "Settings", SettingsIcon, "settings", () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-scanning/$projectId/settings",+ params: { orgId: project.orgId, projectId: project.id },+ search: { selectedTab: "general" }+ })+ )+ ]);+ case ProjectType.CertificateManager: {+ const landing = getProjectLandingItem({+ navigate,+ project,+ organizationName,+ isCertificateManagerAdmin+ });+ if (!isCertificateManagerAdmin) return [landing];+ return sortByContext([+ landing,+ item("inventory", "Inventory", DatabaseIcon, "inventory", () =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/inventory",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("discovery", "Discovery", SearchIcon, "discovery", () =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/discovery",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("access-control", "Access Control", ShieldIcon, "access-management", () =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/access-management",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("audit-logs", "Audit Logs", FileTextIcon, "audit-logs", () =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/audit-logs",+ params: { orgId: project.orgId, projectId: project.id }+ })+ ),+ item("settings", "Settings", SettingsIcon, "settings", () =>+ navigate({+ to: "/organizations/$orgId/projects/cert-manager/$projectId/settings",+ params: { orgId: project.orgId, projectId: project.id }+ })+ )+ ]);+ }+ case ProjectType.PAM:+ default:+ return [getProjectLandingItem({ navigate, project, organizationName })];+ }+};++const filterProjectPageItems = (items: GlobalCommandMenuItem[], permission: TProjectPermission) => {+ const canReadAccessControl =+ permission.can(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member) ||+ permission.can(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Groups) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Role) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.ServiceTokens);+ const canReadIntegrations =+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Integrations) ||+ permission.can(ProjectPermissionSecretSyncActions.Read, ProjectPermissionSub.SecretSyncs) ||+ permission.can(ProjectPermissionAppConnectionActions.Read, ProjectPermissionSub.AppConnections);+ const canReadSettings =+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Settings) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Environments) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Webhooks) ||+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.IpAllowList);++ return items.filter(({ id }) => {+ if (id.endsWith("-access-control")) return canReadAccessControl;+ if (id.endsWith("-integrations")) return canReadIntegrations;+ if (id.endsWith("-audit-logs")) {+ return permission.can(ProjectPermissionAuditLogsActions.Read, ProjectPermissionSub.AuditLogs);+ }+ if (id.endsWith("-settings")) return canReadSettings;+ if (id.endsWith("-kmip")) {+ return permission.can(ProjectPermissionKmipActions.ReadClients, ProjectPermissionSub.Kmip);+ }+ if (id.endsWith("-inventory")) {+ return permission.can(+ ProjectPermissionCertificateActions.Read,+ ProjectPermissionSub.Certificates+ );+ }+ if (id.endsWith("-discovery")) {+ return permission.can(+ ProjectPermissionPkiDiscoveryActions.Read,+ ProjectPermissionSub.PkiDiscovery+ );+ }+ if (id.endsWith("-findings")) {+ return permission.can(+ ProjectPermissionSecretScanningFindingActions.Read,+ ProjectPermissionSub.SecretScanningFindings+ );+ }+ if (id.endsWith("-app-connections")) {+ return permission.can(+ ProjectPermissionAppConnectionActions.Read,+ ProjectPermissionSub.AppConnections+ );+ }+ return true;+ });+};++const CertificateProjectCommandMenu = ({+ content,+ hasProjectRole,+ permission+}: {+ content: CommandContent;+ hasProjectRole: (role: string) => boolean;+ permission: TProjectPermission;+}) => {+ const { currentOrg } = useOrganization();+ const { currentProject } = useProject();+ const navigate = useNavigate();+ const { pathname } = useLocation();+ const projectItems = filterProjectPageItems(+ getProjectPageItems({+ navigate,+ project: currentProject,+ organizationName: currentOrg.name,+ pathname,+ isCertificateManagerAdmin: hasProjectRole("admin")+ }),+ permission+ );++ return (+ <NavigationCommandMenu+ searchStatus={content.searchStatus}+ browseGroups={[+ { heading: currentProject.name, items: projectItems.slice(0, 2) },+ ...content.browseGroups+ ]}+ searchGroups={[{ heading: "Current Project", items: projectItems }, ...content.searchGroups]}+ />+ );+};++const SecretManagerProjectCommandMenu = ({+ content,+ projectItems+}: {+ content: CommandContent;+ projectItems: GlobalCommandMenuItem[];+}) => {+ const { currentProject } = useProject();+ const asyncSearch = useSecretManagerCommandSearch(currentProject);++ return (+ <NavigationCommandMenu+ searchStatus={content.searchStatus}+ browseGroups={[+ { heading: currentProject.name, items: projectItems.slice(0, 2) },+ ...content.browseGroups+ ]}+ searchGroups={[{ heading: "Current Project", items: projectItems }, ...content.searchGroups]}+ asyncSearch={asyncSearch}+ />+ );+};++const CurrentProjectCommandMenu = ({ content }: { content: CommandContent }) => {+ const { currentOrg } = useOrganization();+ const { currentProject } = useProject();+ const navigate = useNavigate();+ const { pathname } = useLocation();+ const { hasProjectRole, permission } = useProjectPermission();++ if (currentProject.type === ProjectType.CertificateManager) {+ return (+ <CertificateProjectCommandMenu+ content={content}+ hasProjectRole={hasProjectRole}+ permission={permission}+ />+ );+ }++ const projectItems = filterProjectPageItems(+ getProjectPageItems({+ navigate,+ project: currentProject,+ organizationName: currentOrg.name,+ pathname+ }),+ permission+ );++ if (currentProject.type === ProjectType.SecretManager) {+ return <SecretManagerProjectCommandMenu content={content} projectItems={projectItems} />;+ }++ return (+ <NavigationCommandMenu+ searchStatus={content.searchStatus}+ browseGroups={[+ { heading: currentProject.name, items: projectItems.slice(0, 2) },+ ...content.browseGroups+ ]}+ searchGroups={[{ heading: "Current Project", items: projectItems }, ...content.searchGroups]}+ />+ );+};++const OrganizationCommandMenu = () => {+ const { pathname } = useLocation();+ const { projectId } = useParams({ strict: false }) as { projectId?: string };+ const { currentOrg, isRootOrganization } = useOrganization();+ const user = useRouteContext({ from: "/_authenticate", select: (context) => context.user });+ const { permission } = useOrgPermission();+ const navigate = useNavigate();+ const entityGroups = useEntityCommandGroups({+ currentOrganizationId: currentOrg.id,+ currentOrganizationName: currentOrg.name+ });+ const organizationItems = getOrganizationItems({+ navigate,+ organizationId: currentOrg.id,+ organizationName: currentOrg.name,+ isRootOrganization,+ canReadAccessControl:+ permission.can(OrgPermissionMemberActions.Read, OrgPermissionSubjects.Member) ||+ permission.can(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity) ||+ permission.can(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups) ||+ permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.Role),+ canReadMachineIdentities: permission.can(+ OrgPermissionIdentityActions.Read,+ OrgPermissionSubjects.Identity+ ),+ canReadRoles: permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.Role),+ canReadAuditLogs: permission.can(+ OrgPermissionAuditLogsActions.Read,+ OrgPermissionSubjects.AuditLogs+ ),+ canReadBilling: permission.can(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing),+ canReadAppConnections: permission.can(+ OrgPermissionAppConnectionActions.Read,+ OrgPermissionSubjects.AppConnections+ ),+ canReadIntegrations:+ permission.can(+ OrgPermissionAppConnectionActions.Read,+ OrgPermissionSubjects.AppConnections+ ) || permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.Settings),+ canReadSettings: permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.Settings)+ });+ const accountItems = getAccountItems(navigate);+ const globalItems = [+ ...accountItems,+ ...(user.superAdmin+ ? [+ {+ id: "account-server-console",+ label: "Server Console",+ breadcrumb: "Global / Administration",+ icon: ServerCogIcon,+ keywords: ["admin", "server"],+ priority: 5,+ onSelect: () => navigate({ to: "/admin" })+ }+ ]+ : [])+ ];+ const content: CommandContent = {+ searchStatus: entityGroups.searchStatus,+ browseGroups: [+ { heading: currentOrg.name, items: organizationItems.slice(0, 3) },+ { heading: "Global", items: globalItems.slice(0, user.superAdmin ? 2 : 1) },+ getNestedCommandGroup(entityGroups)+ ],+ searchGroups: [+ { heading: "Pages & Settings", items: [...organizationItems, ...globalItems] },+ ...entityGroups.searchGroups+ ]+ };+ const isProjectRoute = Boolean(projectId);+ const isPamRoute = pathname.startsWith(`/organizations/${currentOrg.id}/pam`);++ if (isProjectRoute || isPamRoute) return <CurrentProjectCommandMenu content={content} />;+ return <NavigationCommandMenu {...content} />;+};++export const RootCommandMenu = ({ shell }: { shell: RootCommandMenuShell }) => {+ switch (shell) {+ case "organization":+ return <OrganizationCommandMenu />;+ case "admin":+ return <AdminCommandMenu />;+ case "personal-settings":+ return <PersonalSettingsCommandMenu />;+ default:+ return null;+ }+};diff --git a/frontend/src/components/v3/platform/RootCommandMenu/index.ts b/frontend/src/components/v3/platform/RootCommandMenu/index.tsnew file mode 100644index 0000000000..ba3c89e94d--- /dev/null+++ b/frontend/src/components/v3/platform/RootCommandMenu/index.ts@@ -0,0 +1 @@+export * from "./RootCommandMenu";diff --git a/frontend/src/components/v3/platform/RootCommandMenu/secretManagerCommandSearch.test.ts b/frontend/src/components/v3/platform/RootCommandMenu/secretManagerCommandSearch.test.tsnew file mode 100644index 0000000000..acaae4655a--- /dev/null+++ b/frontend/src/components/v3/platform/RootCommandMenu/secretManagerCommandSearch.test.ts@@ -0,0 +1,79 @@+import assert from "node:assert/strict";+import { describe, it } from "node:test";++import type { TDashboardProjectSecretsQuickSearch } from "@app/hooks/api/dashboard/types";+import type { ProjectEnv } from "@app/hooks/api/projects/types";++import { buildSecretManagerCommandMatches } from "./secretManagerCommandSearch";++const environments = [+ { id: "env-prod", name: "Production", slug: "prod" },+ { id: "env-dev", name: "Development", slug: "dev" }+] as ProjectEnv[];++const data = {+ folders: {+ "/apps": [{ id: "folder-api", name: "api", envId: "env-prod", path: "/apps/api" }]+ },+ secrets: {+ "/apps/api/API_KEY": [{ id: "secret-api", key: "API_KEY", env: "prod", path: "/apps/api" }]+ },+ dynamicSecrets: {+ "/database": [+ {+ id: "dynamic-db",+ name: "database-credentials",+ environment: "dev",+ path: "/database"+ }+ ]+ },+ secretRotations: {+ "/apps/api/API_KEY": [+ {+ id: "rotation-api",+ name: "API key rotation",+ environment: { name: "Production", slug: "prod" },+ folder: { path: "/apps/api" }+ }+ ]+ }+} as unknown as Pick<+ TDashboardProjectSecretsQuickSearch,+ "folders" | "secrets" | "dynamicSecrets" | "secretRotations"+>;++describe("Secret Manager command search", () => {+ it("ranks exact resource names and keeps navigation scope without secret values", () => {+ const matches = buildSecretManagerCommandMatches({+ data,+ environments,+ projectName: "Platform",+ query: "API_KEY"+ });++ assert.equal(matches[0].label, "API_KEY");+ assert.equal(matches[0].resourceType, "secret");+ assert.equal(matches[0].environmentSlug, "prod");+ assert.equal(matches[0].path, "/apps/api");+ assert.equal(matches[0].search, "API_KEY");+ assert.equal(matches[0].breadcrumb, "Platform / Production / apps / api / Secret");+ assert.equal("value" in matches[0], false);+ });++ it("maps every supported resource type and caps the result set", () => {+ const matches = buildSecretManagerCommandMatches({+ data,+ environments,+ projectName: "Platform",+ query: "api",+ limit: 3+ });++ assert.equal(matches.length, 3);+ assert.deepEqual(+ new Set(matches.map((match) => match.resourceType)),+ new Set(["folder", "rotation", "secret"])+ );+ });+});diff --git a/frontend/src/components/v3/platform/RootCommandMenu/secretManagerCommandSearch.ts b/frontend/src/components/v3/platform/RootCommandMenu/secretManagerCommandSearch.tsnew file mode 100644index 0000000000..5a5945572a--- /dev/null+++ b/frontend/src/components/v3/platform/RootCommandMenu/secretManagerCommandSearch.ts@@ -0,0 +1,171 @@+import type { TDashboardProjectSecretsQuickSearch } from "@app/hooks/api/dashboard/types";+import type { ProjectEnv } from "@app/hooks/api/projects/types";++import type { SecretManagerResourceSlug } from "../SecretManagerResources/SecretManagerResources";++type SearchableSecretManagerResourceSlug = Extract<+ SecretManagerResourceSlug,+ "folder" | "dynamic" | "rotation" | "secret"+>;++export type SecretManagerCommandMatch = {+ id: string;+ label: string;+ breadcrumb: string;+ keywords: string[];+ environmentSlug: string;+ path: string;+ filterBy?: SearchableSecretManagerResourceSlug;+ search?: string;+ resourceType: SearchableSecretManagerResourceSlug;+};++type QuickSearchResults = Pick<+ TDashboardProjectSecretsQuickSearch,+ "folders" | "secrets" | "dynamicSecrets" | "secretRotations"+>;++const formatBreadcrumb = ({+ projectName,+ environmentName,+ path,+ resourceName+}: {+ projectName: string;+ environmentName: string;+ path: string;+ resourceName: string;+}) =>+ [projectName, environmentName, ...path.split("/").filter(Boolean), resourceName]+ .filter(Boolean)+ .join(" / ");++const getMatchScore = (match: SecretManagerCommandMatch, query: string) => {+ const normalizedQuery = query.trim().toLowerCase();+ const label = match.label.toLowerCase();++ if (label === normalizedQuery) return 100;+ if (label.startsWith(normalizedQuery)) return 80;+ if (label.includes(normalizedQuery)) return 60;+ if (match.breadcrumb.toLowerCase().includes(normalizedQuery)) return 30;+ return 0;+};++export const buildSecretManagerCommandMatches = ({+ data,+ environments,+ projectName,+ query,+ limit = 12+}: {+ data?: QuickSearchResults;+ environments: ProjectEnv[];+ projectName: string;+ query: string;+ limit?: number;+}) => {+ if (!data) return [];++ const environmentById = new Map(environments.map((environment) => [environment.id, environment]));+ const environmentBySlug = new Map(+ environments.map((environment) => [environment.slug, environment])+ );+ const matches: SecretManagerCommandMatch[] = [];++ Object.values(data.folders)+ .flat()+ .forEach((folder) => {+ const environment = environmentById.get(folder.envId);+ const environmentSlug = environment?.slug ?? folder.envId;+ matches.push({+ id: `project-resource-folder-${environmentSlug}-${folder.id}`,+ label: folder.name,+ breadcrumb: formatBreadcrumb({+ projectName,+ environmentName: environment?.name ?? environmentSlug,+ path: folder.path,+ resourceName: "Folder"+ }),+ keywords: ["folder", environmentSlug, folder.path],+ environmentSlug,+ path: folder.path,+ resourceType: "folder"+ });+ });++ Object.values(data.dynamicSecrets)+ .flat()+ .forEach((dynamicSecret) => {+ const environment = environmentBySlug.get(dynamicSecret.environment);+ matches.push({+ id: `project-resource-dynamic-${dynamicSecret.environment}-${dynamicSecret.id}`,+ label: dynamicSecret.name,+ breadcrumb: formatBreadcrumb({+ projectName,+ environmentName: environment?.name ?? dynamicSecret.environment,+ path: dynamicSecret.path,+ resourceName: "Dynamic Secret"+ }),+ keywords: ["dynamic secret", dynamicSecret.environment, dynamicSecret.path],+ environmentSlug: dynamicSecret.environment,+ path: dynamicSecret.path,+ filterBy: "dynamic",+ search: dynamicSecret.name,+ resourceType: "dynamic"+ });+ });++ Object.values(data.secretRotations)+ .flat()+ .forEach((rotation) => {+ const environmentSlug = rotation.environment.slug;+ const environment = environmentBySlug.get(environmentSlug);+ matches.push({+ id: `project-resource-rotation-${environmentSlug}-${rotation.id}`,+ label: rotation.name,+ breadcrumb: formatBreadcrumb({+ projectName,+ environmentName: environment?.name ?? rotation.environment.name,+ path: rotation.folder.path,+ resourceName: "Secret Rotation"+ }),+ keywords: ["secret rotation", environmentSlug, rotation.folder.path],+ environmentSlug,+ path: rotation.folder.path,+ filterBy: "rotation",+ search: rotation.name,+ resourceType: "rotation"+ });+ });++ Object.values(data.secrets)+ .flat()+ .forEach((secret) => {+ const environment = environmentBySlug.get(secret.env);+ const path = secret.path ?? "/";+ matches.push({+ id: `project-resource-secret-${secret.env}-${secret.id}`,+ label: secret.key,+ breadcrumb: formatBreadcrumb({+ projectName,+ environmentName: environment?.name ?? secret.env,+ path,+ resourceName: "Secret"+ }),+ keywords: ["secret", secret.env, path],+ environmentSlug: secret.env,+ path,+ filterBy: "secret",+ search: secret.key,+ resourceType: "secret"+ });+ });++ return matches+ .sort((a, b) => {+ const scoreDifference = getMatchScore(b, query) - getMatchScore(a, query);+ if (scoreDifference) return scoreDifference;+ return a.label.localeCompare(b.label);+ })+ .slice(0, limit);+};diff --git a/frontend/src/components/v3/platform/RootCommandMenu/useSecretManagerCommandSearch.tsx b/frontend/src/components/v3/platform/RootCommandMenu/useSecretManagerCommandSearch.tsxnew file mode 100644index 0000000000..9ab03d0c7a--- /dev/null+++ b/frontend/src/components/v3/platform/RootCommandMenu/useSecretManagerCommandSearch.tsx@@ -0,0 +1,104 @@+import { useMemo, useState } from "react";+import { useNavigate } from "@tanstack/react-router";++import type {+ GlobalCommandMenuGroup,+ GlobalCommandMenuSearchStatus+} from "@app/components/v3/generic/Command";+import { useDebounce } from "@app/hooks";+import { useGetProjectSecretsQuickSearch } from "@app/hooks/api/dashboard";+import type { Project } from "@app/hooks/api/projects/types";++import { SECRET_MANAGER_RESOURCES } from "../SecretManagerResources/SecretManagerResources";+import { buildSecretManagerCommandMatches } from "./secretManagerCommandSearch";++const MINIMUM_SEARCH_LENGTH = 2;+const SEARCH_DEBOUNCE_DELAY = 300;+const SEARCH_RESULT_LIMIT = 12;+const SEARCH_RESULT_LIMIT_PER_RESOURCE = 6;++export const useSecretManagerCommandSearch = (project: Project) => {+ const navigate = useNavigate();+ const [search, setSearch] = useState("");+ const normalizedSearch = search.trim();+ const [debouncedSearch] = useDebounce(normalizedSearch, SEARCH_DEBOUNCE_DELAY);+ const isRawSearchEnabled = normalizedSearch.length >= MINIMUM_SEARCH_LENGTH;+ const isSearchEnabled = debouncedSearch.length >= MINIMUM_SEARCH_LENGTH;++ const query = useGetProjectSecretsQuickSearch(+ {+ projectId: project.id,+ secretPath: "/",+ search: debouncedSearch,+ environments: project.environments.map((environment) => environment.slug),+ tags: {},+ limit: SEARCH_RESULT_LIMIT_PER_RESOURCE,+ offset: 0+ },+ { enabled: isSearchEnabled }+ );++ const isWaitingForDebounce = isRawSearchEnabled && normalizedSearch !== debouncedSearch;+ const isLoading =+ isRawSearchEnabled && (isWaitingForDebounce || query.isFetching || query.isPlaceholderData);+ const matches = useMemo(+ () =>+ isRawSearchEnabled && isSearchEnabled && !isWaitingForDebounce && !query.isPlaceholderData+ ? buildSecretManagerCommandMatches({+ data: query.data,+ environments: project.environments,+ projectName: project.name,+ query: normalizedSearch,+ limit: SEARCH_RESULT_LIMIT+ })+ : [],+ [+ isSearchEnabled,+ isRawSearchEnabled,+ isWaitingForDebounce,+ normalizedSearch,+ project.environments,+ project.name,+ query.data,+ query.isPlaceholderData+ ]+ );++ const groups = useMemo<GlobalCommandMenuGroup[]>(+ () => [+ {+ heading: "Project resources",+ items: matches.map((match) => ({+ id: match.id,+ label: match.label,+ breadcrumb: match.breadcrumb,+ keywords: match.keywords,+ icon: SECRET_MANAGER_RESOURCES[match.resourceType].Icon,+ priority: 60,+ onSelect: () =>+ navigate({+ to: "/organizations/$orgId/projects/secret-management/$projectId/overview",+ params: { orgId: project.orgId, projectId: project.id },+ search: {+ search: match.search,+ clearSearch: match.resourceType === "folder" ? true : undefined,+ secretPath: match.path,+ environments: [match.environmentSlug],+ filterBy: match.filterBy+ }+ })+ }))+ }+ ],+ [matches, navigate, project.id, project.orgId]+ );++ let searchStatus: GlobalCommandMenuSearchStatus = { state: "idle" };+ if (isLoading) {+ searchStatus = { state: "loading", message: "Searching project resources…" };+ } else if (isRawSearchEnabled && isSearchEnabled && query.isError) {+ searchStatus = { state: "error", message: "Could not search project resources." };+ }++ return { groups, searchStatus, onSearchChange: setSearch };+};diff --git a/frontend/src/components/v3/platform/index.ts b/frontend/src/components/v3/platform/index.tsindex ee37858af0..f0d800d1be 100644--- a/frontend/src/components/v3/platform/index.ts+++ b/frontend/src/components/v3/platform/index.ts@@ -11,6 +11,7 @@ export * from "./PageLoader";export * from "./PasswordGenerator";export * from "./PermissionActionSelect";export * from "./ProjectPermissionSubjects/ProjectPermissionSubjects";+export * from "./RootCommandMenu";export * from "./ScopeIcons";export * from "./SecretInput";export * from "./SecretManagerResources/SecretManagerResources";diff --git a/frontend/src/hooks/api/projects/queries.tsx b/frontend/src/hooks/api/projects/queries.tsxindex c5c7968f8f..7e9447673c 100644--- a/frontend/src/hooks/api/projects/queries.tsx+++ b/frontend/src/hooks/api/projects/queries.tsx@@ -33,6 +33,7 @@ import {TGetMembershipPermissionAuditResponse,TGetUpgradeProjectStatusDTO,TMyPendingProjectAccessRequestsResponse,+ TProjectNavigation,TSearchProjectsDTO,TUpdateWorkspaceUserRoleDTO,UpdateAuditLogsRetentionDTO,@@ -142,6 +143,19 @@ export const useGetUserProjectsByType = (type: ProjectType) =>select: (projects) => projects.slice(0, 100)});+export const useGetAccessibleProjectsWithSubOrgs = (orgId: string) =>+ useQuery({+ queryKey: projectKeys.getAccessibleProjectsWithSubOrgs(orgId),+ queryFn: async ({ signal }) => {+ const { data } = await apiRequest.get<{ projects: TProjectNavigation[] }>(+ "/api/v1/projects/accessible-with-sub-orgs",+ { signal }+ );+ return data.projects;+ },+ enabled: Boolean(orgId)+ });+export const useSearchProjects = ({ options, ...dto }: TSearchProjectsDTO) =>useQuery({queryKey: projectKeys.searchProject(dto),diff --git a/frontend/src/hooks/api/projects/query-keys.tsx b/frontend/src/hooks/api/projects/query-keys.tsxindex 50ab413225..d72f0058b3 100644--- a/frontend/src/hooks/api/projects/query-keys.tsx+++ b/frontend/src/hooks/api/projects/query-keys.tsx@@ -13,6 +13,8 @@ export const projectKeys = {getProjectAuthorization: (projectId: string) => [{ projectId }, "project-authorizations"],getProjectIntegrations: (projectId: string) => [{ projectId }, "project-integrations"],getAllUserProjects: () => [...projectKeys.allProjectQueries()] as const,+ getAccessibleProjectsWithSubOrgs: (orgId: string) =>+ [...projectKeys.getAllUserProjects(), "with-sub-orgs", { orgId }] as const,getMyPendingProjectAccessRequests: () =>[...projectKeys.allProjectQueries(), "my-pending-access-requests"] as const,getProjectAuditLogs: (projectId: string) => [{ projectId }, "project-audit-logs"] as const,diff --git a/frontend/src/hooks/api/projects/types.ts b/frontend/src/hooks/api/projects/types.tsindex d252ce4ee4..3ab59728a1 100644--- a/frontend/src/hooks/api/projects/types.ts+++ b/frontend/src/hooks/api/projects/types.ts@@ -46,6 +46,8 @@ export type Project = {isLegacyAdditionalPrivilegesEnabled: boolean;};+export type TProjectNavigation = Pick<Project, "id" | "orgId" | "name" | "slug" | "type">;+export type ProjectEnv = {id: string;name: string;diff --git a/frontend/src/hooks/api/subOrganizations/mutations.tsx b/frontend/src/hooks/api/subOrganizations/mutations.tsxindex a969147fb1..7c73acde87 100644--- a/frontend/src/hooks/api/subOrganizations/mutations.tsx+++ b/frontend/src/hooks/api/subOrganizations/mutations.tsx@@ -1,6 +1,8 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";+import { organizationKeys } from "@app/hooks/api/organization/queries";+import { projectKeys } from "@app/hooks/api/projects/query-keys";import { subOrganizationsQuery } from "./queries";import {@@ -23,6 +25,9 @@ export const useCreateSubOrganization = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: subOrganizationsQuery.allKey() });+ queryClient.invalidateQueries({+ queryKey: organizationKeys.getUserOrganizationsWithSubOrgs+ });}});};@@ -39,6 +44,9 @@ export const useUpdateSubOrganization = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: subOrganizationsQuery.allKey() });+ queryClient.invalidateQueries({+ queryKey: organizationKeys.getUserOrganizationsWithSubOrgs+ });}});};@@ -53,7 +61,11 @@ export const useDeleteSubOrganization = () => {return data;},onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: projectKeys.getAllUserProjects() });queryClient.invalidateQueries({ queryKey: subOrganizationsQuery.allKey() });+ queryClient.invalidateQueries({+ queryKey: organizationKeys.getUserOrganizationsWithSubOrgs+ });}});};@@ -68,7 +80,11 @@ export const useJoinSubOrganization = () => {return data;},onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: projectKeys.getAllUserProjects() });queryClient.invalidateQueries({ queryKey: subOrganizationsQuery.allKey() });+ queryClient.invalidateQueries({+ queryKey: organizationKeys.getUserOrganizationsWithSubOrgs+ });}});};diff --git a/frontend/src/pages/root.tsx b/frontend/src/pages/root.tsxindex 169c9ac610..e9c3b6c415 100644--- a/frontend/src/pages/root.tsx+++ b/frontend/src/pages/root.tsx@@ -1,8 +1,12 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { createRootRouteWithContext, Outlet } from "@tanstack/react-router";+import { createRootRouteWithContext, Outlet, useRouterState } from "@tanstack/react-router";import { NotificationContainer } from "@app/components/notifications";import { TooltipProvider } from "@app/components/v2";+import {+ RootCommandMenu,+ type RootCommandMenuShell+} from "@app/components/v3/platform/RootCommandMenu";import { adminQueryKeys, fetchServerConfig } from "@app/hooks/api/admin/queries";import { TServerConfig } from "@app/hooks/api/admin/types";import { authKeys } from "@app/hooks/api/auth/queries";@@ -14,11 +18,35 @@ type TRouterContext = {queryClient: QueryClient;};+const RootCommandMenuMount = () => {+ const shell = useRouterState({+ select: (state): RootCommandMenuShell | null => {+ const routeIds = new Set(state.matches.map((match) => match.routeId));++ if (routeIds.has("/_authenticate/_inject-org-details/admin/_admin-layout")) {+ return "admin";+ }+ if (routeIds.has("/_authenticate/_inject-org-details/_org-layout")) {+ return "organization";+ }+ if (routeIds.has("/_authenticate/personal-settings/_layout")) {+ return "personal-settings";+ }+ return null;+ }+ });++ if (!shell) return null;++ return <RootCommandMenu shell={shell} />;+};+const RootPage = () => {return (<QueryClientProvider client={queryClient}><TooltipProvider><Outlet />+ <RootCommandMenuMount /><NotificationContainer /></TooltipProvider></QueryClientProvider>diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsxindex dd0f38630f..f3887fa679 100644--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx@@ -253,13 +253,14 @@ import {SecretTableRow} from "./components";import {+ hasOneShotOverviewSearchState,hasOverviewScopeChanged,- hasSensitiveOverviewSearchState,normalizeOverviewEnvironments,parseOverviewTags,resolveOverviewEnvironmentSlugs,+ resolveOverviewSearchFilter,serializeOverviewResourceFilter,- stripSensitiveOverviewSearchState,+ stripOneShotOverviewSearchState,updateOverviewSecretPath} from "./overviewSearchState";@@ -312,6 +313,7 @@ const OverviewPageContent = () => {select: (el) => ({secretPath: el.secretPath,search: el.search,+ clearSearch: el.clearSearch,environments: el.environments,dynamicSecretId: el.dynamicSecretId,honeyTokenId: el.honeyTokenId,@@ -457,9 +459,9 @@ const OverviewPageContent = () => {);useEffect(() => {- if (routerSearch.search) setSearchFilter(routerSearch.search);+ setSearchFilter((currentSearch) => resolveOverviewSearchFilter(currentSearch, routerSearch));if (routerSearch.tags !== undefined) setTagFilter(parseOverviewTags(routerSearch.tags));- }, [routerSearch.search, routerSearch.tags]);+ }, [routerSearch.clearSearch, routerSearch.search, routerSearch.tags]);useEffect(() => {const requestedSlugs = normalizeOverviewEnvironments(@@ -470,18 +472,16 @@ const OverviewPageContent = () => {requestedSlugs.length === routerSearch.environments.length &&requestedSlugs.join(",") === selectedEnvironmentSlugs.join(",");const shouldNormalizeEnvironments = userAvailableEnvs.length > 0 && !isCanonical;- const shouldStripSensitiveState = hasSensitiveOverviewSearchState(routerSearch);+ const shouldStripOneShotState = hasOneShotOverviewSearchState(routerSearch);const normalizedEnvironments = selectedEnvironmentSlugs.length? selectedEnvironmentSlugs: undefined;- if (!shouldNormalizeEnvironments && !shouldStripSensitiveState) return;+ if (!shouldNormalizeEnvironments && !shouldStripOneShotState) return;navigate({search: (prev) => {- const nextSearch = shouldStripSensitiveState- ? stripSensitiveOverviewSearchState(prev)- : prev;+ const nextSearch = shouldStripOneShotState ? stripOneShotOverviewSearchState(prev) : prev;return {...nextSearch,diff --git a/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.test.ts b/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.test.tsindex fb33e3df9d..6b0eac2f95 100644--- a/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.test.ts+++ b/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.test.ts@@ -2,12 +2,15 @@ import assert from "node:assert/strict";import { describe, it } from "node:test";import {+ hasOneShotOverviewSearchState,hasOverviewScopeChanged,hasSensitiveOverviewSearchState,normalizeOverviewEnvironments,parseOverviewTags,resolveOverviewEnvironmentSlugs,+ resolveOverviewSearchFilter,serializeOverviewResourceFilter,+ stripOneShotOverviewSearchState,stripSensitiveOverviewSearchState,updateOverviewSecretPath} from "./overviewSearchState";@@ -55,6 +58,27 @@ describe("Secrets overview query state", () => {);});+ it("consumes explicit search clearing without erasing a previously consumed search", () => {+ assert.equal(resolveOverviewSearchFilter("DATABASE_URL", { clearSearch: true }), "");+ assert.equal(resolveOverviewSearchFilter("DATABASE_URL", { search: "API_KEY" }), "API_KEY");+ assert.equal(resolveOverviewSearchFilter("API_KEY", { search: "" }), "API_KEY");++ const current = {+ secretPath: "/apps",+ environments: ["prod"],+ clearSearch: true,+ unrelated: "preserved"+ };++ assert.equal(hasOneShotOverviewSearchState(current), true);+ assert.deepEqual(stripOneShotOverviewSearchState(current), {+ ...current,+ clearSearch: undefined,+ search: undefined,+ tags: undefined+ });+ });+it("normalizes direct environment links to accessible project slugs", () => {assert.deepEqual(normalizeOverviewEnvironments(["removed", "prod", "prod"], ["dev", "prod"]), ["prod"diff --git a/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.ts b/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.tsindex 8f3f26b80f..0149169ae5 100644--- a/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.ts+++ b/frontend/src/pages/secret-manager/OverviewPage/overviewSearchState.ts@@ -2,6 +2,7 @@ export type OverviewSearchState = {secretPath?: string;environments?: string[];search?: string;+ clearSearch?: boolean;tags?: string;filterBy?: string;};@@ -22,6 +23,22 @@ export const stripSensitiveOverviewSearchState = <T extends OverviewSearchState>tags: undefined});+export const hasOneShotOverviewSearchState = (search: OverviewSearchState) =>+ hasSensitiveOverviewSearchState(search) || Boolean(search.clearSearch);++export const stripOneShotOverviewSearchState = <T extends OverviewSearchState>(search: T): T => ({+ ...stripSensitiveOverviewSearchState(search),+ clearSearch: undefined+});++export const resolveOverviewSearchFilter = (+ currentSearch: string,+ search: Pick<OverviewSearchState, "search" | "clearSearch">+) => {+ if (search.clearSearch) return "";+ return search.search || currentSearch;+};+export const serializeOverviewResourceFilter = (filter: Record<string, boolean>,resourceTypes: string[]diff --git a/frontend/src/pages/secret-manager/OverviewPage/route.tsx b/frontend/src/pages/secret-manager/OverviewPage/route.tsxindex e21184e07a..9e0d4d413a 100644--- a/frontend/src/pages/secret-manager/OverviewPage/route.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/route.tsx@@ -6,6 +6,7 @@ import { OverviewPage } from "./OverviewPage";const SecretOverviewPageQuerySchema = z.object({search: z.string().catch(""),+ clearSearch: z.boolean().optional(),secretPath: z.string().catch("/"),connectionId: z.string().optional(),connectionName: z.string().optional(),@@ -26,6 +27,7 @@ export const Route = createFileRoute(stripSearchParams({secretPath: "/",search: "",+ clearSearch: undefined,environments: [],tags: undefined,filterBy: undefined